var animation;

$(document).ready(function() {

    animation = [1,
    {
        pics: [],
        loaded: 0, //keeps track of how many pics left to load
        loading: 0,
        scratch: $('#scratch1'),
        container: $('#img1'),
        status: $('#currentStatus1'),
        preview: $('#preview1'),
        sound: $('#jquery_jplayer1'),
        startingW: 400,
        startingH: 300,
        x: 0,
        y: 0,
        w: 400,
        h: 300,
        maxX: 400,
        maxY: 300,
        maxTimeout: 300,
        timeout: 100,
        count: 0,
        dir: 1,
        play: 1,
        to: null
    },
    {
        pics: [],
        loaded: 0, //keeps track of how many pics left to load
        loading: 0,
        scratch: $('#scratch2'),
        container: $('#img2'),
        status: $('#currentStatus2'),
        preview: $('#preview2'),
        sound: $('#jquery_jplayer2'),
        startingW: 400,
        startingH: 300,
        x: 0,
        y: 0,
        w: 400,
        h: 300,
        maxX: 400,
        maxY: 300,
        maxTimeout: 300,
        timeout: 100,
        count: 0,
        dir: 1,
        play: 1,
        to: null
    }]
    
    $('.sliderhandle').mousedown(
        function(e){
            var slider = $(this);
            var sliderStartPos = slider.position().left;
            var startPos = e.clientX;
            var sliderPos = $(this).parents().position().left;
            var rel = $(this).parents().attr("rel").split("#");
            
            document.onselectstart = function(){ return false; }
            document.onmousedown = function(){ return false; }
           
            $(document).mousemove(
                function(e){
                    var newPos = constrain(sliderStartPos + e.clientX - startPos,2,85);
                    slider.css('left',newPos);
                    if (rel[1] == 'x') changeWidth(Math.floor(animation[rel[0]].startingW * (newPos / 84)), rel[0],1);
                    else if (rel[1] == 'y') changeHeight(Math.floor(animation[rel[0]].startingH * (newPos / 84)),rel[0],1);
                    else if (rel[1] == 's') changeTimeout(Math.floor(animation[rel[0]].maxTimeout * (newPos / 84)),rel[0],1);
                }
            );
        }
    );
    
    $('.scratch').mousedown(
        function(e){
            var startPos = [e.clientX,e.clientY];
            var scratchPos = [$(this).position().left,$(this).position().top];
            var scratch = $(this);
            var rel = $(this).attr("rel").split("#");
            
            document.onselectstart = function(){ return false; }
            document.onmousedown = function(){ return false; }
            
            $(document).mousemove(
                function(e){
                    var newX = scratchPos[0] - (startPos[0] - e.clientX);
                    var newY = scratchPos[1] - (startPos[1] - e.clientY);
                    if (newX > 0 && newX + scratch.width() < 160){
                        if (newX < 5) newX = 0;
                        else if (newX + scratch.width() > 155) newX = 160 - scratch.width();
                        scratch.css('left',newX);
                        animation[rel[0]].x = Math.floor((newX * 5) / 2);
                        animation[rel[0]].container.css('left',animation[rel[0]].x);
                    }
                    if (newY > 0 && newY + scratch.height() < 120){
                        if (newY < 5)   newY = 0;
                        else if (newY + scratch.height() > 115) newY = 120 - scratch.height();
                        scratch.css('top',newY);
                        animation[rel[0]].y = Math.floor((newY * 5) / 2);
                        animation[rel[0]].container.css('top',animation[rel[0]].y);
                    }
                }
            );
        }
    );
    
    $('#opacityslider,#musicslider,#lockslider').mousedown(
        function(e){
            var slider = $(this).find('div:first');
            var sliderPos = $(this).position().left;
            document.onselectstart = function(){ return false; }
            document.onmousedown = function(){ return false; }
            var sliderType = this.id;
            if (sliderType == 'lockslider') slider = $('#opacityslider,#musicslider').find('div:first');
            
            $(document).mousemove(
                function(e){
                    var newPos = constrain(e.clientX - sliderPos - (slider.width() / 2), 2, 334);
                    var newOp = Math.floor(100 * (newPos / 334)) / 100;
                    if (sliderType == 'lockslider') $('#sliderlock').css('left', newPos + 25);
                    
                    slider.css('left', newPos);
                    
                    if (sliderType != 'musicslider'){
                        animation[1].container.css('opacity',1-newOp);
                        animation[2].container.css('opacity',newOp);
                    }
                    if (sliderType != 'opacityslider'){
                        animation[1].sound.volume((1-newOp) * 100);
                        animation[2].sound.volume(newOp * 100);
                    }
                }
            );
        }
    );
    
    $(document).mouseup(
        function(e){
            $(document).unbind('mousemove');
            document.onselectstart = null;
            document.onmousedown = null;
        }
    );
    
    $('.currentStatus').click(
        function (e){
            var onTop = 1;
            var onBot = 2;
            if ($(this).attr('rel') == '2'){
                onTop = 2;
                onBot = 1;
            }
            animation[0] = onTop;
            animation[onTop].container.css('z-index','100');
            animation[onBot].container.css('z-index','10');
            animation[onTop].status[0].parentNode.style.background = '#391113';
            animation[onBot].status[0].parentNode.style.background = '#000000';
            animation[onTop].status.css('background','url(images/controls/selected.gif) no-repeat 24px top');
            animation[onBot].status.css('background','url(images/controls/deck'+onBot+'.gif) no-repeat 24px top');
            animation[onTop].scratch.css('z-index','100');
            animation[onBot].scratch.css('z-index','10');
            animation[onTop].scratch.css('backgroundColor','#ccc');
            animation[onBot].scratch.css('backgroundColor','#aaa');
        }
    );
    
    $('#tabsArea h4').click(
        function(){
            $('#tabsArea h4').css({'font-weight':'normal','color':'#999'});
            $(this).css({'font-weight':'bold','color':'#ddd'});
            if (this.id == 'helpTab'){
                $('#audioArea,#visualsArea').hide();
                $('#helpArea').show('fast');
            }
            else if (this.id == 'visualsTab'){
                $('#audioArea,#helpArea').hide();
                $('#visualsArea').show('fast');
            }
            else if (this.id == 'audioTab'){
                $('#helpArea,#visualsArea').hide();
                $('#audioArea').show('fast');
            }
        }
    );
    
    $('.musicLink').hover(
        function(){ $(this).css('backgroundImage','url(\'images/controls/headphones.gif\')'); },
        function(){ $(this).css('backgroundImage',''); }
    ).click(
        function(e){
            animation[animation[0]].sound.setFile('mp3/'+$(this).html()+'.mp3').play();
            $('#song_title'+animation[0]).html($(this).html());
        }
    );
    
    animation[2].container.css('opacity',0);
    loadLibrary();
    loadAni(1,1);
    loadAni(2,2);
    
    loadMusic(1);
    loadMusic(2);
});


    function changeHeight(changeH,whichone,set){
        var newH = (set == 1) ? changeH : animation[whichone].h + changeH;
        newH = constrain(newH,0,400);
        
        animation[whichone].h = newH;
        $('#img'+whichone).height(newH);
        for (var a in animation[whichone].pics) animation[whichone].pics[a].style.height = newH + 'px';
        animation[whichone].scratch.height(Math.floor((newH / 5) * 2));

        var imgH = animation[whichone].y;
        
        if (newH + animation[whichone].y > animation[whichone].maxY){
            var newTop = animation[whichone].y - (newH + animation[whichone].x - animation[whichone].maxY);
            animation[whichone].container.css('top',newTop);
            animation[whichone].scratch.css('top',Math.floor((newTop / 5) * 2));
        }
    }
    
    function changeWidth(changeW,whichone,set){
        var newW = (set == 1) ? changeW : animation[whichone].w + changeW;
        newW = constrain(newW,0,400);
        
        animation[whichone].w = newW
        $('#img'+whichone).width(newW);
        for (var a in animation[whichone].pics) animation[whichone].pics[a].style.width = newW + 'px';
        animation[whichone].scratch.width(Math.floor((newW / 5) * 2));

        if (newW + animation[whichone].x > animation[whichone].maxX){
            var newLeft = imgW - (newW + animation[whichone].x - animation[whichone].maxX);
            animation[whichone].container.css('left',newLeft);
            animation[whichone].scratch.css('left',Math.floor((newLeft / 5) * 2));
        }
    }

    function playpause(whichone){
        animation[whichone].play = (animation[whichone].play == 1) ? 0 : 1;
        if (animation[whichone].play == 1) animate();
    }

    function switchDir(whichone){ animation[whichone].dir = (animation[whichone].dir == 1) ? -1 : 1; }
    
    function changeTimeout(changeto,whichone,set){
        animation[whichone].timeout = (set == 1) ? changeto : animation[whichone].timeout + changeto;
        if (animation[whichone].timeout < 0) animation[whichone].timeout = 0;
    }
    
    function animate(whichone){
        if (animation[whichone].pics.length > 2){
            try {
                clearTimeout(animation[whichone].to);
                animation[whichone].container[0].removeChild(animation[whichone].pics[animation[whichone].count]);
            }
            catch(e){}
            
            if (animation[whichone].dir > 0) animation[whichone].count = (animation[whichone].count < animation[whichone].pics.length - 1) ? animation[whichone].count + 1 : 0;
            else animation[whichone].count = (animation[whichone].count > 0) ? animation[whichone].count - 1 : animation[whichone].pics.length - 1;
            animation[whichone].container[0].appendChild(animation[whichone].pics[animation[whichone].count]);
        }
        if (animation[whichone].loaded == 0){
            if (animation[whichone].loading == animation[whichone].pics.length){
                animation[whichone].loaded = 1;
                showAnimation(whichone);
            }
            $('#loadcount'+whichone).html(animation[whichone].loading+"\\"+animation[whichone].pics.length);
            animation[whichone].to = setTimeout(function(){animate(whichone);},animation[whichone].timeout);
            return;
        }
        if (animation[whichone].play == 1) animation[whichone].to = setTimeout(function(){animate(whichone);},animation[whichone].timeout);
    }

    function showAnimation(whichone){
        if (animation[1].loaded == 1 && animation[2].loaded == 1) $('#loading').fadeOut("slow");
        for (var p in animation[whichone].pics) animation[whichone].pics[p].style.display = 'block';
        $('loadcount'+whichone).html("Loaded");
    }
    
    function loadAni(newanis,whichone){
        $('#loading').css('display','block');
        var newani;
        /////////////////////
        // Settings for flexibility and media library
        /////////////////////
        if (newanis > -1) newani = newSrc[newanis];
        else newani = newSrc[parseInt(newanis.getAttribute('rel'))];
        if (!whichone) whichone = animation[0];
        /////////////////////
        
        $('loadcount'+whichone).html('');
        try {
            animation[whichone].container[0].removeChild(animation[whichone].pics[animation[whichone].count]);
            clearTimeout(animation[whichone].to);
        }
        catch(e){}
        animation[whichone].pics.length = 0;
        animation[whichone].play = 0;
        animation[whichone].loading = 0;
        animation[whichone].loaded = 0;
        for (var a in newani){
            animation[whichone].pics[a] = new Image();
            animation[whichone].pics[a].src = newani[a];
            animation[whichone].pics[a].style.display = 'none';
            animation[whichone].pics[a].onload = function(){ animation[whichone].loading++; }
        }
        animation[whichone].play = 1;
        animate(whichone);
        animation[whichone].preview.attr('src',newani[0]);
        changeHeight(0,whichone);
        changeWidth(0,whichone);
        animation[whichone].to = setTimeout(function(){animate(whichone);},animation[whichone].timeout);
    }
    //////////////////////////////////
    // Load Visual Library
    //////////////////////////////////
    function loadLibrary(){
        var ml = $('#medialibrary');
        var newDiv = new Array();
        
        for (var a in newSrc){
            newDiv[a] = document.createElement('div');
            var newImg = document.createElement('img');
            newImg.src = newSrc[a][0];
            newImg.setAttribute('rel',a);
            newDiv[a].className = 'mlitem';
            $(newImg).click(
                function(){
                    loadAni(this);
                }
            );
            newDiv[a].appendChild(newImg);
            $(newDiv[a]).appendTo(ml);
        }
        $('<div style="clear:both"></div>').appendTo(ml);
    }

/////////////////////////////////
// Load Music Library
/////////////////////////////////
function loadMusic(whichone){
    var vol = (whichone == 2) ? 1 : 100;
	animation[whichone].sound.jPlayer({
		ready: function () { $(this).volume(vol); },
		oggSupport: true
	})
	.jPlayerId("play", "player_play"+whichone)
	.jPlayerId("pause", "player_pause"+whichone)
	.jPlayerId("stop", "player_stop"+whichone)
	.jPlayerId("loadBar", "player_progress_load_bar"+whichone)
	.jPlayerId("playBar", "player_progress_play_bar"+whichone)
	.jPlayerId("volumeMin", "player_volume_min"+whichone)
	.jPlayerId("volumeMax", "player_volume_max"+whichone)
	.jPlayerId("volumeBar", "player_volume_bar"+whichone)
	.jPlayerId("volumeBarValue", "player_volume_bar_value"+whichone)
	.onProgressChange( function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		var myPlayedTime = new Date(playedTime);
		var ptMin = (myPlayedTime.getUTCMinutes() < 10) ? "0" + myPlayedTime.getUTCMinutes() : myPlayedTime.getUTCMinutes();
		var ptSec = (myPlayedTime.getUTCSeconds() < 10) ? "0" + myPlayedTime.getUTCSeconds() : myPlayedTime.getUTCSeconds();
		$("#play_time"+whichone).text(ptMin+":"+ptSec);

		var myTotalTime = new Date(totalTime);
		var ttMin = (myTotalTime.getUTCMinutes() < 10) ? "0" + myTotalTime.getUTCMinutes() : myTotalTime.getUTCMinutes();
		var ttSec = (myTotalTime.getUTCSeconds() < 10) ? "0" + myTotalTime.getUTCSeconds() : myTotalTime.getUTCSeconds();
		$("#total_time"+whichone).text(ttMin+":"+ttSec);
	})
    .onSoundComplete( function() {
        $(this).play();
    });
}


//	.onSoundComplete( function() {
//		$("#jquery_jplayer2").playHead(0); // Crossover the players here
//	});

/////////////////////////////
// Controls
//////////////////////////////
    function controls(e){
        var keynum;
        var keychar;
        
        if (window.event)   keynum = event.keyCode;
        else if (e.which)   keynum = e.which;
        
        keychar = String.fromCharCode(keynum)

        if (keychar == 'c' || keychar == 'C')       switchDir(selected);
        else if(keychar == 'x' || keychar == 'X')   ontop(selected);
        else if(keychar == 'p' || keychar == 'P')   playpause(selected);
        /*
        else if (keychar == 'f' || keychar == 'F'){
            changeTimeout(-10,selected);
        }
        else if (keychar == 's' || keychar == 'S'){
            changeTimeout(10,selected);
        }
        else if(keychar == 'i' || keychar == 'I'){
            changeOpacity(10,selected);
        }
        else if(keychar == 'o' || keychar == 'O'){
            changeOpacity(-10,selected);
        }
        */
    }

/////////////////////////////
// other functions
/////////////////////////////
    function constrain(val, min, max){
        if (val > max) return max;
        else if (val < min) return min;
        return val;
    }
    
    $.fn.makeAbsolute = function(rebase) {
        return this.each(function() {
            var el = $(this);
            var pos = el.position();
            el.css({ position: "absolute",
                marginLeft: 0, marginTop: 0,
                top: pos.top, left: pos.left });
            if (rebase) el.remove().appendTo("body");
        });

    }