$(document).ready(function () {

/////////////////////////////////////////////////////
// Keyword + Clip closures

function cKeyword (id) {
    var that = {};
    that.id = id;
    that.clips = [];
    that.elt = $("#"+that.id);
    that.selected = false;
    that.hasSelectedClip = true;
    
    that.update = function () {
        if (that.selected) {
            that.elt.addClass("selected");
        } else {
            that.elt.removeClass("selected");
        }

        that.hasSelectedClip = false;
        for (var i=0; i<that.clips.length; i++) {
            if (that.clips[i].selected) {
                that.hasSelectedClip = true;
                break;
            }
        }
        if (that.hasSelectedClip) {
            that.elt.removeClass("out");
        } else {
            that.elt.addClass("out");
        }
    }
    that.setSelected = function (val) {
        that.selected = val;
    }
    
    // Events
    that.elt.mouseover(function () {
        that.elt.addClass("highlight");
        for (var i=0; i<that.clips.length; i++) {
            that.clips[i].elt.addClass("highlight");
        }
    }).mouseout(function () {
        that.elt.removeClass("highlight");
        for (var i=0; i<that.clips.length; i++) {
            that.clips[i].elt.removeClass("highlight");
        }
    }).click(function () {
        if (selectedKey === that) {
            // this key is selected already: toggle selection (deselect)
            setSelectedKey(null);
        } else if (selectedKey !== null) {
            // another key is selected...
            if (lastKeyClicked === that) {
                // second click: set as selection
                setSelectedKey(that);
            } else if (that.hasSelectedClip) {
                // check if key is already in context...
                // in which case nothing needs to be done
                // (or immediately setSelectedKey)
                if (that.elt.hasClass("playing")) {
                    setSelectedKey(that);
                } else {
                    // ... and this clip is related to the selection: play a related clip
                    var relatedclips = [];
                    for (var i=0; i<that.clips.length; i++) {
                        if (that.clips[i].selected) {
                            relatedclips.push(that.clips[i]);
                        }
                    }
                    if (relatedclips.length > 0) {
                        $.random_choice(relatedclips).play();
                    }
                }
            } else {
                // ... and this clip is not related: select this key
                setSelectedKey(that);
            }
        } else {
            // no key is selected: select this key
            setSelectedKey(that);
        }
        lastKeyClicked = that;
    });    
    return that;
}

function cClip (elt) {
    var that = {};
    that.elt = $(elt);
    that.keys = [];
    that.url = $(elt).attr("href");
    that.start_tc = $(elt).attr("data-start");
    that.start = $.timecode_tosecs(that.start_tc);
    that.end_tc = $(elt).attr("data-end");
    that.end = $.timecode_tosecs(that.end_tc);
    that.duration = that.end - that.start;
    
    that.selected = true; // all clips are initially selected

    function init() {
        var keyids = $(elt).attr("data-keys").split(/,/);
        for (var i=0; i<keyids.length; i++) {
            var keyid = keyids[i];
            if (!keysByID[keyid]) {
                var key = cKeyword(keyid)
                keysByID[keyid] = key;
                allkeys.push(key);
            }
            that.keys.push(keysByID[keyid]);
            keysByID[keyid].clips.push(that);
        }
    }
    init();
    
    function keysAddClass (cname) {
        for (var i=0; i<that.keys.length; i++) {
            that.keys[i].elt.addClass(cname);
        }
    }
    function keysRemoveClass (cname) {
        for (var i=0; i<that.keys.length; i++) {
            that.keys[i].elt.removeClass(cname);
        }
    }
    that.setPlaying = function (val) {
        if (val) {
            that.elt.addClass("playing");
            keysAddClass("playing");
        } else {
            that.elt.removeClass("playing");
            keysRemoveClass("playing");
        }
    }
    that.setSelected = function (val) {
        that.selected = val;
    }
    that.update = function () {
        if (that.selected) {
            that.elt.removeClass("out");
            // Animate out
            $(that.elt).removeAttr('style').hide().fadeIn();
            // $(that.elt).hide().fadeIn();
        } else {
            that.elt.addClass("out");
            // Animate in
            $(that.elt).hide('slow', function() {// Animation complete. 
            });
        }
    }
    // Events
    $(elt).mouseover(function () {
        that.elt.addClass("highlight");
        keysAddClass("highlight");
    }).mouseout(function () {
        that.elt.removeClass("highlight");
        keysRemoveClass("highlight");
    }).click(function () {
        that.play();
        return false;
    });

    that.play = function () {
        setPlayingClip(that);
        flowplayer(0).play({
            url: that.url,
            provider: "lighttpd",
            start: that.start,
            duration: that.duration
        });
    }

    return that;
}

/////////////////////////////////////////

var clips = [];
var allkeys = [];
var keysByID = {};
var playingClip = null;
var selectedKey = null;
var lastKeyClicked = null;


function update () {
	var amount=0;
    var i;
    for (i=0; i<clips.length; i++) {
        clips[i].update()
    }
    for (i=0; i<allkeys.length; i++) {
        allkeys[i].update()
    }
    //
    for (i=0; i<clips.length; i++) {
        if (clips[i].selected) {
        	amount+=1;
    	}
    }
    
	var SizePerClipX;
	var SizePerClipY;
	SizePerClipX =  1200 / amount ;
	SizePerClipY =  675 /  amount ;
	 
	if (SizePerClipX < 27){SizePerClipX = 27;}
	else if (SizePerClipX > 100){SizePerClipX = 104;}
	else{SizePerClipX = 41;}
	
	if (SizePerClipY < 15){SizePerClipY = 15;}
	else if (SizePerClipY > 80){SizePerClipY = 59;}
	else{SizePerClipY = 23;}
	
	for (i=0; i<clips.length; i++) {
        clips[i].elt.css({ width: SizePerClipX });
        clips[i].elt.css({ height: SizePerClipY });

    }
    //
    
}

function setPlayingClip (c) {
    if (playingClip) { playingClip.setPlaying(false); }
    playingClip = c;
    if (playingClip) { playingClip.setPlaying(true); }
}

function setSelectedKey (k) {
    // cleanup old selectedKey
    if (selectedKey === null) {
        for (var i=0; i<clips.length; i++) {
            clips[i].setSelected(false);
        }
    } else {
        selectedKey.setSelected(false);
        for (var i=0; i<selectedKey.clips.length; i++) {
            selectedKey.clips[i].setSelected(false);
        }
    }
    // set newly selected key
    selectedKey = k;
    if (selectedKey === null) {
        for (var i=0; i<clips.length; i++) {
            clips[i].setSelected(true); // all clips implicitly selected
        }
    } else {
        selectedKey.setSelected(true);
        for (var i=0; i<selectedKey.clips.length; i++) {
            selectedKey.clips[i].setSelected(true);
        }
    }
    update();
}

function autoPlayCountdown () {
    // console.log("doAutoPlay...");
    var q = $(".autoplay");
    var flashcount = 0;
    function flash () {
        // console.log("flash");
        flashcount += 1;
        if (flashcount % 2 === 1) {
            q.addClass("flash");
        } else {
            q.removeClass("flash");
            if (flashcount > 6) {
                autoPlay();
                return;
            }
        }
        window.setTimeout(flash, 500);
    }
    flash();
}

function autoPlay () {
    // console.log("AUTOPLAY");
    $.random_choice(clips).play();
}

function doClipDone () {
    /*
    var ap = ($("input.autoplay:checked").length === 1);
    // console.log("ap", ap);
    if (ap) {
        autoPlayCountdown();
    }
    */
}

////////////////////
// INIT

$(".clip").each(function () {
    var clip = cClip(this);
    $(this).data("obj", clip);
    clips.push(clip);
});

flowplayer("player", FP_SWF, {
    clip: {
        onFinish: function (clip) {
            // console.log("clip: onFinish", clip);
            doClipDone();
        },
        // onStop: function (clip) {},
        scaling: "orig"
    },
    plugins: {
        lighttpd: { url: FP_PSEUDO_SWF }
    }
});

update();

}); // end document ready


