var CABINET_LINK_LOCATION = "/about/learn_more";
var TIME_COEFFICIENT = 1;

var PRELOAD_IMAGE_URLS = ["/about/media/img/personas_1+2.jpg",
                          "/about/media/img/animation/slide_background.gif",
                          "/about/media/img/personas_3+4.jpg" ];

var image_preloading_completed = false;
var canvasOut_waiting_for_preload = false;

$(document).ready( function() {

        var remaining_images_to_load = PRELOAD_IMAGE_URLS.length;
        var load_func = function() {
            
            remaining_images_to_load--;

            if(remaining_images_to_load == 0) {
                image_preloading_completed = true;

                if(canvasOut_waiting_for_preload) {
                    canvasOut_waiting_for_preload = true;
                    imageAnimation.canvasOut_proceed();
                }
                //setTimeout('runAnimation()', 0);
            }
        };

        for(var i = 0; i < PRELOAD_IMAGE_URLS.length; i++) {
            var imgurl = PRELOAD_IMAGE_URLS[i];
            var img = new Image();
            $(img).load(load_func).error(load_func).attr("src", imgurl);
        }

        setTimeout('runAnimation()', 0);
    });

runAnimation = function() {
        if (typeof(DD_belatedPNG) === 'object') DD_belatedPNG.fix('.earSequence');

        var isMac = (navigator.platform.indexOf('Mac') > -1);

        for (var i=1; i < 5; i++) {
            $('#earSequenceSource'+i).prependTo('#persona'+i+' .ears');
        }
        $('.ears .earSequence').css('zIndex',80);
        if (isMac && false) {
            if (navigator.userAgent.indexOf('irefox/3.0.') < 0 ) {
                $(' .ears .earSequence').css('top', '-1px');
            }
            else {
                $(' .ears .earSequence').css('top', '0px');
            }
        }

        // Compose the cabinetbox div
        $('#cabinet1').css('display','block').css('opacity',1);
        $('#cabinetdisplay').css('display','block').css('opacity',0).animate({opacity:1}, 2000, 'easeInSine');
        imageAnimation.start();
        //$('#persona1').css('opacity','1');

        $(".slider span, .fadein img").click(function() {
                document.location = CABINET_LINK_LOCATION;
            });
    };

globalTimeValue = 1000*TIME_COEFFICIENT;


imageAnimation = function() {

    var initialBackground = 0x6fb536;

    var currentBackground = 0x6fb536;
    var currentBorder     = 0.0;
    var intervalObject    = null;
    var currentCanvas     = 1;
    var earCount          = 0;
    var showDepressions   = true;
    var stopAnimation     = false;
    var startFadeSize     = 0.9;
    var numAnimations     = 0;

    // Values for important animation times and sizes
    var fullDisplayTime   = 4000*TIME_COEFFICIENT;


    return {

        start: function() {

            imageAnimation.initialize();
            // Fade in the current canvas/persona
            var pers = $('#persona' + currentCanvas);
            if(numAnimations == 0) {
                pers.css({opacity:1});
                imageAnimation.showNoteDepressions();
            } else {
                pers.animate({opacity:1},900, function(){imageAnimation.showNoteDepressions()});
            }


            //$('#persona' + currentCanvas).css('opacity',1);
            //imageAnimation.showNoteDepressions();

        },

        initialize: function() {

            // Initialize the slide in backgrounds and all other stuff so that IE plays along
            $('#persona'+currentCanvas+' .slider').css('opacity',0); //.css('background-position','-10px -10px');
            $('#persona'+currentCanvas+' .fadein').css('opacity',0).css('display','block');
            $('#persona'+currentCanvas).css('opacity',0).css('display','block');

            // Set the background image of the "ears" to not show anything.
            $('#persona' + currentCanvas + ' .ears .earSequence').css('backgroundPosition', '18px');
            
            // Move the sliding images into the correct location
            $('#persona' + currentCanvas + ' .slider span').each(function(l) {
                    width = parseInt($(this).css('width'));
                    if (width > 0) $(this).css('right', width+'px').css('opacity',1).css('display','block');
                });

            // Hide the previous layer's cabinet.
            if (currentCanvas-1 < 1) {
                $('#cabinet4').css('opacity',0).css('display','none');
                $('#cabinet1').css('opacity',1).css('display','block');
                $('#cabinet5').css('opacity',0).css('display','none');
            }
            else {
                $('#cabinet'+(currentCanvas-1)).css('opacity',0).css('display','none');
            }
        },

        controller: function() {
            setTimeout("imageAnimation.fadeIn()", numAnimations==0?0:30);
            setTimeout("imageAnimation.slide()", numAnimations==0?0:250);
            setTimeout('imageAnimation.makeEars()', numAnimations==0?0:1500); // Let the images appear, then create the ears
        },
            
        makeEars: function() {
            if (intervalObject !== null) clearInterval(intervalObject);

            // Populate all the shadow divs with the correct shadows. Get the contained image
            // size and select the proper shadow to attach.
            $('#persona'+currentCanvas+' .ears').each(function() {
                    imgRef = $(this).find('img').eq(0);
                    spanRef = $(this).find('span').eq(0);

                    h      = parseInt($(imgRef).attr('height'));
                    w      = parseInt($(imgRef).attr('width'));
                    hCss = parseInt($(spanRef).css('height'));
                    wCss = parseInt($(spanRef).css('width'));

                    wIndex = parseInt(((w-100)/120)+1.4);
                    hIndex = parseInt(((h-100)/120)+1.4);

                    var newW = (w+6);
                    var newH = (h+6);

                    if ($(this).attr('class').indexOf('fadein') > -1) {
                        $(imgRef).css('width',w+'px').css('height',h+'px');

                        $(this).css('background','url(/about/media/img/animation/shadow_'+wIndex+'x'+hIndex+'.png) no-repeat')
                            .css('width', w)
                            .css('height', h)
                            .css('marginBottom', parseInt(-1*h));
                        var to = {width: newW, height: newH};
                        if(numAnimations == 0) {
                            $(this).css(to);
                        } else {
                            $(this).animate(to, 1000);
                        }
                    }
                    else {
                        wIndex = parseInt(((wCss-100)/120)+1.4);
                        hIndex = parseInt(((hCss-100)/120)+1.4);
                        $(this).css('background','url(/about/media/img/animation/shadow_'+wIndex+'x'+hIndex+'.png) no-repeat 0px -1px')
                            .css('marginBottom', parseInt(-1*hCss))
                            .css('width', wCss)
                            .css('height', hCss);
                        var to = {width: wCss+6, height: hCss+6};

                        if(numAnimations == 0) {
                            $(this).css(to);
                        } else {
                            $(this).animate(to, 1000);
                        }
                    }
                        
                });

            if(numAnimations == 0) { // jump to 5th frame of ear animation.
                earCount = 5;
                imageAnimation.nextEar();
            } else { // render ears one by one.
                // Start the animation of the ears coming in.
                intervalObject = setInterval('imageAnimation.nextEar()', 80);
            }
        },

        nextEar: function() {
            $('#persona'+currentCanvas+' .ears .earSequence').css('backgroundPosition', (earCount*-20)+'px 1px');
            earCount ++;
            if (earCount > 5) {                
                earCount = 0;
                try { clearInterval(intervalObject); } catch(e) {}
                intervalObject = null;
                setTimeout('imageAnimation.canvasOut()', fullDisplayTime);
            }

        },

        showNoteDepressions: function() {
            //setTimeout('imageAnimation.controller()', 400);
            var sliders = $('#persona'+currentCanvas+' .slider').css('opacity',0).css('display','block');
            var to = {opacity:1, backgroundPosition: '0 0'};
            if(numAnimations == 0) {
                sliders.css(to);
            } else {
                sliders.animate(to, 1000);
            }
            imageAnimation.controller();
        },

        slide: function() {

            $('#persona'+currentCanvas+' .slider span').each(function(k) {
                    $(this).css('opacity',1);
                    var to = {right:"0px"};
                    if(numAnimations == 0) {
                        $(this).css(to);
                    } else {
                        $(this).animate(to, globalTimeValue, 'easeOutQuart');
                    }
                    
                })
        },

        fadeIn: function() {

            $('#persona'+currentCanvas+' .fadein').each(function(e) {
                    width  = parseInt($(this).css('width'));
                    height = parseInt($(this).css('height'));
                    left   = parseInt($(this).css('left'));
                    topOff = parseInt($(this).css('top'));

                    if (isNaN(left))   left = 0;
                    if (isNaN(topOff)) top  = 0;

                    initialSizeIndex = parseInt((width+height)/100);
                    initSize = startFadeSize;
                    switch (initialSizeIndex) {
                    case 3:
                        initSize = 0.96;
                        break;

                    case 4:
                        initSize = 0.98;
                        break;

                    }

                    imgRef = $(this).find('img').eq(0);

                    $(this).css('display','none')
                        .css('width', parseInt(initSize*width))
                        .css('height',parseInt(initSize*height))
                        .css('left',  left+(parseInt(((1-initSize)*width)/2)))
                        .css('top',   topOff+(parseInt(((1-initSize)*height)/2))+'px');

                    var to = {opacity:'1', width: width+'px', height: height+'px', left: left+'px',top:topOff+'px'};
                    if(numAnimations == 0) {
                        $(this).css(to).show();
                    } else {
                        $(this).animate(to,globalTimeValue,'easeInCubic');
                    }
                })
        },

        canvasOut: function() {
            if(stopAnimation) return;

            if(image_preloading_completed) {
                imageAnimation.canvasOut_proceed();
            } else {
                canvasOut_waiting_for_preload = true;
            }
            ////if (!stopAnimation) $('#persona' + currentCanvas).fadeOut(1000, function() {imageAnimation.resetCanvas();});
        },

        canvasOut_proceed: function() {
            $('#persona' + currentCanvas).fadeOut(1000, function() {imageAnimation.resetCanvas();});
        },

        resetCanvas: function() {
            // After being faded out, hide the enclosing <div>
            $('#persona'+currentCanvas+' .fadein').css('display','none').css('opacity',0);

            // Also reset the size and background for the slide containers
            $('#persona'+currentCanvas+' .ears').each(function() {
                    var width  = parseInt($(this).css('width'));
                    var height = parseInt($(this).css('height'));

                    $(this).css('width', (width-6)+'px')
                        .css('height', (height-6)+'px');

                    if ($(this).attr('class').indexOf('slider') > -1) {
                        $(this).css('background','url(/about/media/img/animation/slide_background.gif) no-repeat');
                    }


                });

            $('#persona'+currentCanvas+' .fadein').each(function() {
                    imgRef = $(this).find('img').eq(0).css('width','100%').css('height','100%');
                });

            currentCanvas++;
            if (currentCanvas > 4) currentCanvas = 1;
            
            numAnimations++;
            
            this.fadeCabinet();
        },

        fadeCabinet: function() {

            var fadeCabinet = (currentCanvas === 1) ? 5 : currentCanvas;

            $('#cabinet'+fadeCabinet)
                .css('opacity',0)
                .css('display','block')
                .animate({opacity:1}, 800, 'easeInSine', function() {imageAnimation.start()});

        }
    }
}();

