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 = parseInt(this.segments[seg]['out']);
        }
        
        this.player.seek(parseInt(this.segments[seg]['in']) / 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 (parseInt(this.segments[seg]['in']) < position && parseInt(this.segments[seg]['out']) > position) {
                this.currentTags.push(this.segments[seg]['tags'].join(', '));
            }
        }
        this.displayTags();
    },

    setupHandlers: function(player) {

        cuepoints = new Array();
        
        for (seg in this.segments) {
            cuepoint = {time: parseInt(this.segments[seg]['in']), tag: this.segments[seg]['tags'].join(', ')};
            cuepoints.push(cuepoint);
            cuepoint = {time: parseInt(this.segments[seg]['out']), tag: this.segments[seg]['tags'].join(', '), out: 'true'};
            cuepoints.push(cuepoint);
        }
        
        if (cuepoints.length > 0) {
	        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);
	            }
	        });
        }
    }
}