var tagTool = {
    
    // Segments: {in (ms), out (ms), tag, user}
    segments: Array(),
    currentTags: Array(),

    tagContainer: "",
    player: false,
    showTagInPage: true,
    showTagInPlayer: true,
    stopOnSegment: false,

    playSegment: function(seg, pause) {

        if (pause == "on")
            this.stopOnSegment = this.segments[seg].sout;

        this.player.seek(this.segments[seg].sin / 1000);
    },

    displayTags: function() {
                
        if (this.showTagInPage) {
            taglist=$('<ul></ul>');
            for (tag in this.currentTags)
                $('<li>' + this.currentTags[tag] + '</li>').appendTo(taglist);
            $(this.tagContainer).html(taglist);
        }

        if (this.showTagInPlayer) {
            if (this.currentTags.length == 0)
                this.player.getPlugin('content').fadeOut();
            else {
                line = '<p>' + this.currentTags.join('<br>') + '</p>';
                this.player.getPlugin('content').animate({height: 15*(this.currentTags.length + 1) + 'px'});
                this.player.getPlugin('content').setHtml(line).fadeIn();
            }
        }
    },

    addTag: function(tag) {
        this.currentTags.push(tag);
        this.displayTags();
    },

    removeTag: function(tag) {
        this.currentTags.splice(this.currentTags.indexOf(tag), 1);
        this.displayTags();
    },

    rebuildCurrentTags: function(position) {
        this.currentTags = new Array();
        for (seg in this.segments) {
            if (this.segments[seg].sin < position && this.segments[seg].sout > position) {
                this.currentTags.push(this.segments[seg].tag);
            }
        }
        this.displayTags();
    },

    setupHandlers: function(player) {

        cuepoints = new Array();
        for (seg in this.segments) {
            cuepoint = {time: this.segments[seg].sin, tag: this.segments[seg].tag};
            cuepoints.push(cuepoint);
            cuepoint = {time: this.segments[seg].sout, tag: this.segments[seg].tag, out: 'true'};
            cuepoints.push(cuepoint);
        }
        player.onCuepoint(cuepoints, function(clip, cuepoint) {
            if (cuepoint.out) {
                tagTool.removeTag(cuepoint.tag);
                if (tagTool.stopOnSegment == cuepoint.time) {
                    this.pause();
                    tagTool.stopOnSegment = false;
                }
            } else {
                tagTool.addTag(cuepoint.tag);
            }
        });

    }
}