function _preload_images() {
    // Preload the app headers
    $.ImagePreload("images/ss_layout_top.png");
    $.ImagePreload("images/cf_layout_top.png");
    $.ImagePreload("images/pv_layout_top.png"); 
}

$(document).ready(function() {    
    // Preload important images
    _preload_images();
    
    var $isShowingDetail = false;
    var $isFlashAvailable = true;
    var $detailInfoElemShown;
    
    _show_flash_upgrade_msg = function() {
        $('.colorTrailer').stop().css({opacity: 1.0}).fadeTo(500, 0.2);
        if(!$isShowingDetail) 
            $("#flashtrailer").append('<div id="upgradeflash"><h3>upgrade flash to view trailer</h3></div>');
        else {
            $("#flashdetailtrailer").append('<div id="flashdetailupgrade"><h3>upgrade flash to view trailer</h3></div>');
        }
        $isFlashAvailable = false;
    }
    
    _check_flash_available = function() {
        if(!$isFlashAvailable)
            _show_flash_upgrade_msg();
        
        // If we don't have flash, replace the trailer tag
        if(!swfobject.hasFlashPlayerVersion("1")) {
            _show_flash_upgrade_msg();
        } else {
            $isFlashAvailable = true;
        }   
    }
            
    // ?partnerId=30&siteID=JCZBUf*/kEg
    var $pvoid = $('<div id="detailtop"><img id="pv_layout_top" src="images/pv_layout_top.png"></div><div id="detailaction"><div id="detailactiontitle"><img src="images/pv_layout_bottom.png"></div><div id="detailactioniphone"><a href="http://itunes.apple.com/us/app/project-void/id347231324?partnerId=30&siteID=JCZBUf*/kEg" target="_blank" border=0 onClick="_gaq.push([\'_trackEvent\', \'Link\', \'Visit\', \'iTunes Project Void\']);"><img id="iphone_badge" src="images/iphone_store_norm.png" onmouseover=this.src="images/iphone_store_hover.png" onmouseout=this.src="images/iphone_store_norm.png"></a></div><div id="detailactioninfo"><img id="voidinfo" src="images/detail_norm.png" onmouseover=this.src="images/detail_hover.png" onmouseout=this.src="images/detail_norm.png"></div></div>');
    var $spin = $('<div id="detailtop"><img id="ss_layout_top" src="images/ss_layout_top.png"></div><div id="detailaction"><div id="detailactiontitle"><img src="images/ss_layout_bottom.png"></div><div id="detailactioniphone"><a href="http://itunes.apple.com/bw/app/spin-shoot/id323573091?partnerId=30&siteID=JCZBUf*/kEg" target="_blank" border=0 onClick="_gaq.push([\'_trackEvent\', \'Link\', \'Visit\', \'iTunes Spin & Shoot\']);"><img id="iphone_badge" src="images/iphone_store_norm.png" onmouseover=this.src="images/iphone_store_hover.png" onmouseout=this.src="images/iphone_store_norm.png"></a></div><div id="detailactioninfo"><img id="spininfo" src="images/detail_norm.png" onmouseover=this.src="images/detail_hover.png" onmouseout=this.src="images/detail_norm.png"></div></div>');
    var $color = $('<div id="detailtop"><img id="cf_layout_top" src="images/cf_layout_top.png"></div><div id="detailaction"><div id="detailactiontitle"><img src="images/cf_layout_bottom.png"></div><div id="detailactionipad"><a href="http://itunes.apple.com/us/app/colorflys/id392814699?partnerId=30&siteID=JCZBUf*/kEg" target="_blank" border=0 onClick="_gaq.push([\'_trackEvent\', \'Link\', \'Visit\', \'iTunes Colorflys\']);"><img id="ipad_badge" src="images/ipad_store_norm.png" onmouseover=this.src="images/ipad_store_hover.png" onmouseout=this.src="images/ipad_store_norm.png"></a></div><div id="detailactioninfo"><img id="colorinfo" src="images/detail_norm.png" onmouseover=this.src="images/detail_hover.png" onmouseout=this.src="images/detail_norm.png"></div><div id="flashtrailer"><div id="flashdetailtrailer"><a class="colorTrailer" href="http://www.youtube.com/watch?v=zD1tyw-iIik&hd=1" target="_blank" onClick="_gaq.push([\'_trackEvent\', \'Videos\', \'Play\', \'Colorflys\']);"><img src="images/colorflys_trailer_norm.png" onmouseover="this.src=\'images/colorflys_trailer_hover.png\'" onmouseout="this.src=\'images/colorflys_trailer_norm.png\'"></a></div></div></div>');

    var $transition_timer;
    
    _hide_header_and_show_detail = function(headhtml) {
        // Make sure the transition timer isn't running
        clearTimeout($transition_timer);
        
        // Reset info header if it has been toggled
        _clear_header_detail($detailInfoElemShown);
                    
        // If the detail is already shown, don't try and hide the main header
        if(!$isShowingDetail) {
            $("#topheader").stop().animate({opacity: "hide"}, "fast");
            $("#topheaderaction").stop().animate({opacity: "hide"}, "fast");
        } else {
            // Let's still do a cool transition
            $("#topheaderapp").stop().animate({opacity: "hide"}, "fast");
        }
    
        $transition_timer = setTimeout(function() {_load_content(headhtml)}, 700);
        $isHeaderHidden = false;
    }
        
    _hide_detail_and_show_orig = function() {
        if(!isShowingDetail)
            return;
        
        $("#topheaderapp").animate({opacity: "hide"}, "fast");
          
        $("#topheader").delay(500).animate({opacity: "show"}, "fast");
        $("#topheaderaction").delay(500).animate({opacity: "show"}, "fast");
        _clear_content();
    }
    
    _show_origional_header = function() {
        clearTimeout($transition_timer);
        $isHeaderHidden = false;
        $("#topheader").stop().css({opacity: 1.0}).animate({opacity: "show"}, "fast");
        $("#topheaderaction").stop().css({opacity: 1.0}).animate({opacity: "show"}, "fast");
    }
    
    _reset_animation = function() {
        $("#topheaderapp").stop().css({opacity: 1.0})
        $("#topheaderapp").animate({opacity: "show"}, "fast");
        clearTimeout($transition_timer);
        
        // user moved mouse too quick before showing an app detail, reset the header to original
        if(!$isShowingDetail)
            _show_origional_header();
    }
    
    _clear_content = function() {
        document.getElementById('topheaderapp').innerHTML = "";
    }
    
    _load_content = function(headhtml) {
        $('#topheaderapp').html(headhtml);
        $isShowingDetail = true;
        
        // Still want a fade to happen if the user crosses multiple icons too fast, need to make sure the opacity is full
        $("#topheaderapp").stop().css({opacity: 1.0}).animate({opacity: "show"}, "fast");
        
        // Check flash
        _check_flash_available();
    }
    
    _swap_info_bar_bg = function(name) {
        document.getElementById('infobar').style.backgroundImage = "url('" + name + "')";
    }
    
    // Watch for the user to hover over a specific app icon div
    $("#spin_app_detail").hover(function() {
	    _gaq.push(['_trackEvent', 'AppIcon', 'Hover', 'Spin & Shoot']);
            _hide_header_and_show_detail($spin);
	}, function() {
            _reset_animation();
    });
    
    $("#color_app_detail").hover(function() {
	    _gaq.push(['_trackEvent', 'AppIcon', 'Hover', 'Colorflys']);
            _hide_header_and_show_detail($color);
	}, function() {
            _reset_animation();
    });
    
    $("#void_app_detail").hover(function() {
	    _gaq.push(['_trackEvent', 'AppIcon', 'Hover', 'Project Void']);
            _hide_header_and_show_detail($pvoid);
	}, function() {
            _reset_animation();
    });
    
    $("#midwelcomebarright").hover(function() {
	    _gaq.push(['_trackEvent', 'AppIcon', 'Hover', 'YieldKeeper']);
            $("#next_popup").ImageSwitch({Type:"FadeIn", Speed: 500, NewImage:"images/visit_project_popup.png"});
	}, function() {
            $("#next_popup").ImageSwitch({Type:"FadeIn", Speed: 500, NewImage:"images/next_project_popup.png"});
    });
    
    var $pvdetail = $('<div class="appdetail"><div id="detaildescription">Remember those awesome Tetris pieces? Try and use them to fill up to 4 voids shown at a time. Easy, right?</div><div id="detailfeature"><img id="detailquoteleft" src="images/quote_open.png"><img id="detailquoteright" src="images/quote_close.png"><div id="detailfeaturesingle"><h3>Play Through 50 Stages</h3></div><div id="detailfeaturesingle"><h3>Two modes: Casual & Time Attack</h3></div><div id="detailfeaturedouble"><h3>Stages Are Built Randomly, So Never Play It The Same Twice!</h3></div><div id="detailfeaturesingle"><h3>Original Music</h3></div><div id="detailfeaturesingle"><h3>Leaderboards</h3></div></div><div id="detailquotes"><h3>"Tired of Tetris and other traditional block puzzlers? This simple twist might make you smile." - 1up.com</h3><h3>"In many ways it is the anti-Tetris and compliments the gameplay of it perfectly." - TheAPPera.com</h3><h3>"Project Void is seriously addicting." - appSafari.com</h3></div></div>');
    var $ssdetail = $('<div class="appdetail"><div id="detaildescription">Spin. Shoot. Chase. Repeat.</div><div id="detailfeature"><img id="detailquoteleft" src="images/quote_open.png"><img id="detailquoteright" src="images/quote_close.png"><div id="detailfeaturesingle"><h3>Database Loaded With Drinks</h3></div><div id="detailfeaturesingle"><h3>Play With 4 Friends</h3></div><div id="detailfeaturedouble"><h3>Customize The App And Insert Your Own Drinks</h3></div><div id="detailfeaturedouble"><h3>Discover The Lightweights Among You</h3></div></div><div id="detailquotes"><h3></h3><h3>"Avoid being THAT ONE. Please Drink Responsibly!" - The Developer</h3><h3></h3></div></div>');
    var $cfdetail = $('<div class="appdetail"><div id="detaildescription">Everybody loves Butterflies! Come capture some by looping your finger around them!</div><div id="detailfeature"><img id="detailquoteleft" src="images/quote_open.png"><img id="detailquoteright" src="images/quote_close.png"><div id="detailfeaturesingle"><h3>60 Levels Through 3 Environments</h3></div><div id="detailfeaturesingle"><h3>Kids Mode For Our Younger Players</h3></div><div id="detailfeaturedouble"><h3>Challenges Introduced Which Will Twist The Way You Capture Butterflies</h3></div><div id="detailfeaturesingle"><h3>Game Center Support</h3></div><div id="detailfeaturesingle"><h3>Unique Art Style</h3></div></div><div id="detailquotes"><h3>"Great for kids. Intelligent, wonderful design." - App Store</h3><h3>"I thought this game worked, looked and sounded great. It\'s colorful, easy to play, hard to master." - App Store</h3><h3>"My four year old daughter and myself cannot stop playing it. The graphics are beautiful as well as the music." - App Store</h3></div></div>');
    
    var $isHeaderHidden = false;
    var $origHeader;
    
    _load_header = function(html) {
        $("#detailtop").append(html);
    };
    
    _toggle_header_img = function(el, headerdetail) {        
        if(!$isHeaderHidden) {
            $(el).animate({opacity: 0.05}, "fast");
            $isHeaderHidden = true;
            
            // Save orig and load details into the header
            $origHeader = $("#detailtop").html();
            setTimeout(function() {_load_header(headerdetail)}, 500);
        } else {
            $(".appdetail").remove();
            $(el).css({opacity: 1}).fadeTo("fast", 1);
            $isHeaderHidden = false;
        }
    };
    
    _clear_header_detail = function(el) {
        if(!el) return;
        
        $(".appdetail").remove();
        $(el).fadeTo(1000, 1.0);
        $isHeaderHidden = false;
    }
    
    // Live keeps this beast around
    $("#voidinfo").live('click', function() {
        $detailInfoElemShown = "#pv_layout_top";
        _toggle_header_img($detailInfoElemShown, $pvdetail);
	_gaq.push(['_trackEvent', 'AppIcon', 'Info', 'Project Void']);
    });
    $("#spininfo").live('click', function() {
        $detailInfoElemShown = "#ss_layout_top";
        _toggle_header_img($detailInfoElemShown, $ssdetail);
	_gaq.push(['_trackEvent', 'AppIcon', 'Info', 'Spin & Shoot']);
    });
    $("#colorinfo").live('click', function() {
        $detailInfoElemShown = "#cf_layout_top";
        _toggle_header_img($detailInfoElemShown, $cfdetail);
	_gaq.push(['_trackEvent', 'AppIcon', 'Info', 'Colorflys']);
    });
    
    // check URL for app tag
    check_app_start_URL = function() {
        var $appstart = window.location.href.split('#')[1];
        if(!$appstart)
            return false;
        
        if($appstart == "spin")
            _hide_header_and_show_detail($spin);
        else if($appstart == "void")
            _hide_header_and_show_detail($pvoid);
        else if($appstart == "color") {
            _hide_header_and_show_detail($color);
        }
        
        return true;
    }
    
    // Check flash
    _check_flash_available();
    
    // Check for special condition in the URL
    check_app_start_URL();
    
    // Handler for flash video button
    $("a.colorTrailer").live('click', function() {
        if(!$isFlashAvailable)
            return false;
        
        $.fancybox({
            'padding'             : 0,
            'autoScale'           : false,
            'transitionIn'        : 'elastic',
            'transitionOut'       : 'elastic',
            'width'               : 560,
            'height'              : 345,
            'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'                : 'swf',
            'swf'                 : {'allowfullscreen':'true', 'vmode': 'transparent'}
        });
        return false;
    });
});
