var current = "about";
var next;
var previous;
var screenshots_group = "wii";
var subpage;
var newsdetail_id;
var ie6 = ($.browser.msie && $.browser.version.substr(0,1)<7);
var language = "en";
var init = 1;
var deepLink = "customize";
var cufon_init = 0;
var original_pageName;

/** Each menu button is given a position.
 *  In addition to this, each separator is given a position as well
 */
var mbmap = {
    'about': 1,
    'news': 3,
    'screenshots': 5,
    'coolStuff': 7
};

var thumb_groups = {};
var medium_groups = {};
var full_groups = {};

/*
 * Hides the content for the current page
 */
function hide_content(){
    //hide the content, then call show_content afterwards
    $("#center").animate({
        marginLeft: "-550px"
    }, 250, null, show_content);
}

/*
 * Shows the content for the next page
 */
function show_content(){
    //shows the "next" content
    if(previous)
        $("#"+previous).hide();

    $("#"+current).show();
    if(current == "news"){
        if(subpage == "newsdetail"){
            $("#newslisting").hide();
            
            if(newsdetail_id != null){
                $("#newsdetails div.newsdetail").each(function(){
                    $(this).hide();
                });
                $("#newsdetail_"+newsdetail_id).show();
            }
            
            $("#newsdetails").show();
        }
        else{
            $("#newslisting").show();
            $("#newsdetails").hide();
        }
    }
    else if(current == "screenshots"){
        initialize_image_browser("screenshots_container", screenshots_group);
        //Set up the screenshots page
        $("#" + screenshots_group).addClass("system_on");
    }
    else if(current == "coolStuff"){
        //If the browser has four or fewer images, don't show the navigation arrows
        check_image_browser_arrows("buddies_container");
    }

    $("#center").animate({
        marginLeft: "0px"
    }, 250);
}

/*
 * Activates a button
 * @param   id: DOM identifier for the page the button is associated with 
 */
function activate_button(id){
    $("#"+id+"_button").addClass("menubutton_on");

    var sep_before = $("#separator_" + (mbmap[id] - 1));
    var sep_after = $("#separator_" + (mbmap[id] + 1));

    var sep_before_class = sep_before.attr("class");
    if(sep_before_class.indexOf("null_off") != -1)
        sep_before.removeClass("null_off").addClass("null_on");
    if(sep_before_class.indexOf("off_off") != -1)
        sep_before.removeClass("off_off").addClass("off_on");
    if(sep_before_class.indexOf("on_off") != -1)
        sep_before.removeClass("on_off").addClass("on_on");

    var sep_after_class = sep_after.attr("class");
    if(sep_after_class.indexOf("off_null") != -1)
        sep_after.removeClass("off_null").addClass("on_null");
    if(sep_after_class.indexOf("off_off") != -1)
        sep_after.removeClass("off_off").addClass("on_off");
    if(sep_after_class.indexOf("off_on") != -1)
        sep_after.removeClass("off_on").addClass("on_on");
        
    // Refreshes the cufon font after the hover effect
    Cufon.replace($("#"+id+"_button").children(".label"));
    Cufon.now();
}

/*
 * Deactivates a button
 * @param   id: DOM identifier for the page the button is associated with 
 */
function deactivate_button(id){
    if($("#"+id+"_button").hasClass("menubutton_on"))
        $("#"+id+"_button").removeClass("menubutton_on");

    var sep_before = $("#separator_" + (mbmap[id] - 1));
    var sep_after = $("#separator_" + (mbmap[id] + 1));

    var sep_before_class = sep_before.attr("class");
    if(sep_before_class.indexOf("null_on") != -1)
        sep_before.removeClass("null_on").addClass("null_off");
    if(sep_before_class.indexOf("off_on") != -1)
        sep_before.removeClass("off_on").addClass("off_off");
    if(sep_before_class.indexOf("on_on") != -1)
        sep_before.removeClass("on_on").addClass("on_off");

    var sep_after_class = sep_after.attr("class");
    if(sep_after_class.indexOf("on_null") != -1)
        sep_after.removeClass("on_null").addClass("off_null");
    if(sep_after_class.indexOf("on_off") != -1)
        sep_after.removeClass("on_off").addClass("off_off");
    if(sep_after_class.indexOf("on_on") != -1)
        sep_after.removeClass("on_on").addClass("off_on");

    // Refreshes the cufon font after the hover effect
    Cufon.replace($("#"+id+"_button").children(".label"));
    Cufon.now();
}


/*
 * Move the images in the image browser left or right
 * @param   container_id: the DOM id of the entire container of the browser
 * @param   direction: the direction to move in (left or right)
 * @param   margin: the amount to move left or right (i.e. "99px")
 */
function image_browser_animate(container_id, direction){
    var posDiv = $("#" + container_id + " span.position");
    var pos = parseInt(posDiv.text());

    if(direction == "right"){
        if(pos < get_image_browser_count(container_id)-4){
            var nodes = $("#" + container_id + " div.nodes_inner");
            var marginLeft = parseInt(nodes.css("margin-left").replace("px", ""));
            nodes.animate({
                marginLeft: "-=" + get_image_browser_movement_amount(container_id) + "px"
            });
            posDiv.html(pos+1);
        }
    }
    else if(direction == "left"){
        if(pos > 0){
            var nodes = $("#" + container_id + " div.nodes_inner");
            var marginLeft = parseInt(nodes.css("margin-left").replace("px", ""));
            nodes.animate({
                marginLeft: "+=" + get_image_browser_movement_amount(container_id) + "px"
            });
            posDiv.html(pos-1);
        }
    }
    check_image_browser_arrows(container_id);
}

/*
 * Calculate the number of pixels to move each image by.  Amount is width of node + margin_left + margin_right
 * @param   container_id: the DOM id of the entire container of the browser
 * @returns integer pixel amount (i.e. 99)
 */
function get_image_browser_movement_amount(container_id){
    var node = $("#" + container_id + " .node");
    var width = parseInt(node.css("width"));
    var margin = parseInt(node.css("marginRight")) * 2;
    return (width + margin);
}

/*
 * Calculate the number of image nodes in the given container
 * @param   container_id: the DOM id of the entire container of the browser
 * @returns integer number of nodes
 */
function get_image_browser_count(container_id){
    return parseInt($("#" + container_id + " .node").size());
}

/*
 * Show the medium-sized image in the image browser screenshot area
 * @param   container_id: the DOM id of the entire container of the browser
 * @param   group: the group of images set
 * @param   index: the index of the group array to show
 */
function set_image_browser_highlighted(container_id, group, index){
    var highlighted = medium_groups[group];
    if(!index)
        index = 0;
        
    if(highlighted.length > 0){
        $("#screenshot_highlighted").attr("src", highlighted[index]);
        updateie6(document.getElementById("screenshot_highlighted"));
    }
}

/*
 * Initialize an image browser
 * @param   container_id: the DOM id of the entire container of the browser
 * @param   group: the group of images set
 */
function initialize_image_browser(container_id, group){
    var container = $("#" + container_id + " div.nodes_inner");
    var thumbs = thumb_groups[group];
    var full = full_groups[group];

    //Reset position so we don't retain another image browser's position
    $("#" + container_id + " span.position").text("0");
    
    var margin_left = "0px";
    if(ie6 && container_id == "buddies_container")
        margin_left = "-8px";
    
    container.css("marginLeft", margin_left);
    container.html("");
    
    var border_src;
    for(var i=0; i<thumbs.length; i++){
        container.append("<div class=\"node\" id=\"screenshots_container_node_" + i + "\" style=\"cursor:default;background:url(" + thumbs[i] + ") no-repeat top left;\"><img src=\"images/ssbrowser_border.png\" /></a>");
    }

    //If the browser has four or fewer images, don't show the navigation arrows
    check_image_browser_arrows(container_id);

    if(medium_groups[group] != null)
        set_image_browser_highlighted(container_id, group, 0);

	if(ie6)
		supersleight.run();
}

/*
 * Wraps around the hide_content() function to show news detail
 * @param   id: DOM identifier for the news blurb in question
 */
function show_news_detail(id){
    subpage = "newsdetail";
    newsdetail_id = id;
    hide_content();
}

/*
 * Wraps around the hide_content() function to show the news listing
 */
function show_news_listing(){
    subpage = null;
    newsdetail_id = null;
    hide_content();
}

/*
 * Updates a div/image in IE6 to force it to see the updated element
 */
function updateie6(div){
	if(ie6){
		div.style.border = "0";
		supersleight.runFor(div);
	}
}

/*
 * Wrapper around the required omniture call
 */
function omniCall(element, omniTag) {
/*
    // Some special links need to have the current pagename appended
    var modifiedTag = omniTag;
    switch(omniTag.substring(0,7)){
        case 'preorde':
        case 'newslet':
            modifiedTag = getPageName() + ":" + omniTag;
            break;
    }
*/
	setOmniValues(element,'o',omniTag,'','','',0,'','');
}

/*
 * Some links need to call omniture with a psuedo-http request
 */
function omniPageView(){
    var page = getPageName();
    var actual_pageName = original_pageName + ":" + page.toUpperCase();
    s_ea.prop10 = page;
    
    var props = "userId="+s_ea.prop1+",,brand="+s_ea.prop3+",franchise="+s_ea.prop4+",game="+s_ea.prop5+",,,,gameSpecificTrafficValue="+s_ea.prop9+",contentTitle="+s_ea.prop10+",territory="+s_ea.prop11+",language="+s_ea.prop12+",contentMediaType="+s_ea.prop13+",contentCategory="+s_ea.prop14+",contentBucket="+s_ea.prop15+",,country="+s_ea.prop17;
    var eVars = "userId="+s_ea.eVar1+",,game="+s_ea.eVar3+",,,,,,,,,,,,,,country="+s_ea.eVar17+",region="+s_ea.eVar18+",,,,,,,,,,,paymentMethod="+s_ea.eVar29+",eVar30="+s_ea.eVar30+",,,,eVar34="+s_ea.eVar34;

    setOmniValues('','','',props,eVars,'',1,'','',actual_pageName);
}

function getPageName(){
    return current.substr(0, 1).toUpperCase() + current.substr(1).toUpperCase();
}

function jsLink(element, omniTag, href){
    omniCall(element, omniTag);
    location.href = href;
}

/*
 * If the given group of images has four or fewer images, don't show the arrows
 */
function check_image_browser_arrows(container_id){
    var nodes = $("#" + container_id + " .node").size();
    var position = parseInt($("#" + container_id + " span.position").text());
    
    if(position == 0 || nodes <= 4)
        $("#" + container_id + " .arrow_left").css("visibility", "hidden");
    else
        $("#" + container_id + " .arrow_left").css("visibility", "visible");
 
    if(position+4 == nodes || nodes <= 4)
        $("#" + container_id + " .arrow_right").css("visibility", "hidden");
    else
        $("#" + container_id + " .arrow_right").css("visibility", "visible");
}

// check if cookies are enabled or disabled
function are_cookies_enabled(){
    $.cookie("cookiesenabled", null);
    $.cookie("cookiesenabled", "enabled");
    if($.cookie("cookiesenabled")){
        return true;
    }
    else{
        return false;
        $.cookie("cookiesenabled", null);
    }
}

/****************************************
 ** Do javascript initialization stuff and add events bindings
 ****************************************/

// Screenshots image should have a rounded border.  Doesn't quite work in IE
if(!$.browser.msie)
    DD_roundies.addRule('#screenshot_highlighted', "4px", true);


if($.cookie("lang")){
	language = $.cookie("lang");
}
else{
    if(are_cookies_enabled())
        location.href = "landing.jsp";
    else
        language = "en_US";
}

$(document).ready(function(){   
    $(".center_content_container").hide();
    original_pageName = s_ea.pageName;

    $.preloadCssImages();
    
    if(ie6)
    	supersleight.init();

    if(language){
	    //The language selector needs to select the current language
        $("#language_options li a").each(function(){
            if($(this).attr("href").indexOf("lang="+language) != -1)
                $("#language_options_active").text($(this).text());
        }); 
    }

	if($.cookie("tab"))
		current = $.cookie("tab");
		
	if($.cookie("ftab"))
		deepLink = $.cookie("ftab");

    var flashvars = {
        xmlString: "flash.php",
        deepLink: deepLink
    }; 
    var params = {
        wmode: "opaque"
    };
    swfobject.embedSWF("Main.swf", "flash_swf", "994", "540", "9.0.0.0", "", flashvars, params);
    $("#altcontent").addClass("altcontent_on").css("overflow", "auto");
    
    // Each group has an extra comma at the end, so pop the last element off the array
    var groups = $("#screenshot_groups").text().split(",");
    groups.pop();
    $.each(groups, function(){
        thumb_groups[this] = $("#" + this + "_thumbs").text().split(",");        
        thumb_groups[this].pop();
        medium_groups[this] = $("#" + this + "_medium").text().split(",");        
        medium_groups[this].pop();
        full_groups[this] = $("#" + this + "_full").text().split(",");        
        full_groups[this].pop();
    });

    //Show the current content and activate the correct button
    show_content();
    activate_button(current);
    
    //When a menu button is clicked, 
    //hide the current content and show the new content
    $(".menubutton, .menubutton_on").click(function(){
        next = $(this).attr("id").split("_")[0];
        
        if(next != current){
            subpage = null;
            hide_content();
            previous = current;
            current = next;

            activate_button(current);
            deactivate_button(previous);
            omniPageView();
        }
    });
    
    /* Tabs only come forward on click, not mouseover.
    //Activate a button on mouseover
    //A shim is used so that it covers the visual button and not the actual button.
    $(".menubutton .shim, .menubutton_on .shim").mouseover(function(){
        var tmp = $(this).attr("id").split("_")[0];
        activate_button(tmp);
    });

    //Deactivate a button on mouseout, but only if it isn't the current button
    $(".menubutton .shim, .menubutton_on .shim").mouseout(function(){
        var tmp = $(this).attr("id").split("_")[0];

        if(tmp != current)
            deactivate_button(tmp);
    });
    */
    
    //Bind to the mouseover/mouseout events for the buy/signup buttons
    $(".buy").mouseover(function(){
        $(this).addClass("buy_on");
    });
    $(".buy").mouseout(function(){
        $(this).removeClass("buy_on");
    });
    $(".signupbutton").mouseover(function(){
        $(this).addClass("signupbutton_on");
    });
    $(".signupbutton").mouseout(function(){
        $(this).removeClass("signupbutton_on");
    });
    
    
    
    //////////// Cool Stuff & Buddies ///////////////////
    
    //wallpaper rollovers
    $("#coolStuff .wplink").mouseover(function(){
        var wallpaper_parent = $(this).parent().prev().children("img");
        wallpaper_parent.attr("src", "images/wallpaper_border_on.png"); // the css() at the end is to trick IE6 into reloading the image
		updateie6(this);
    });
    $("#coolStuff .wplink").mouseout(function(){
        var wallpaper_parent = $(this).parent().prev().children("img");
        wallpaper_parent.attr("src", "images/wallpaper_border.png");
		updateie6(this);
    });
    
    // Buddies Left/Right arrow buttons
    $("#buddies_container .arrow_left").click(function(){
        image_browser_animate("buddies_container", "left");
    });
    $("#buddies_container .arrow_right").click(function(){
        image_browser_animate("buddies_container", "right");
    });
    
    /////////////// Image Browser and Buttons ////////////////
    //this attaches events to all image browser buttons (buddies + screenshots)
    $("div.image_browser .arrow_left").mouseover(function(){
        $(this).children("img").attr("src", "images/arrow_left_on.png");
        updateie6(this);
    });
    $("div.image_browser .arrow_left").mouseout(function(){
        $(this).children("img").attr("src", "images/arrow_left.png");
        updateie6(this);
    });
    $("div.image_browser .arrow_right").mouseover(function(){
        $(this).children("img").attr("src", "images/arrow_right_on.png");
        updateie6(this);
    });
    $("div.image_browser .arrow_right").mouseout(function(){
        $(this).children("img").attr("src", "images/arrow_right.png");
        updateie6(this);
    });
    $("#buddies_container .node").live('mouseover', function(){
        $(this).find(".shot img").attr("src", "images/buddy_border_on.png");
        updateie6(this);
    });
    $("#buddies_container .node").live('mouseout', function(){
        $(this).find(".shot img").attr("src", "images/buddy_border.png");
        updateie6(this);
    });

    $("#screenshots_container .node").live('mouseover', function(){
        $(this).children("img").attr("src", "images/ssbrowser_border_on.png");

        var node_id = $(this).attr("id");
        var index = node_id.split("_")[3];
        set_image_browser_highlighted("screenshots_container", screenshots_group, index);

        updateie6(this);
    });
    $("#screenshots_container .node").live('mouseout', function(){
        $(this).children("img").attr("src", "images/ssbrowser_border.png");
        updateie6(this);
    });
    
    /////////////// Screenshots, Systems /////////////////
    // mouseover/mouseout the system buttons
    $("div.system").live("mouseover", function(){
        $(this).addClass("system_on");
    });
    $("div.system").live("mouseout", function(){
        if($(this).attr("id") != screenshots_group)
            $(this).removeClass("system_on");
    });
    $("div.system").live("click", function(){
        screenshots_group = $(this).attr("id");
        initialize_image_browser("screenshots_container", screenshots_group);
        $("div.system").each(function(){
            $(this).removeClass("system_on");
        });
        $(this).addClass("system_on");
    });
    
    //Screenshots left/right arrow buttons
    $("#screenshots_container .arrow_left").click(function(){
        image_browser_animate("screenshots_container", "left");
    });
    $("#screenshots_container .arrow_right").click(function(){
        image_browser_animate("screenshots_container", "right");
    });
        
    /////////////// Game and Language Selectors /////////////////
    
    //Timeouts used to close the selector popups so they'll always close
    var myTimeout;
    var myTimeout2;
    
    //Toggle the Game Selector Menu
    $("#game_selector").click(function(){
        $("#game_options").toggle();
    });

    //Toggle the Language selector menu
    $("#language_selector").click(function(){
        $("#language_options").toggle();
    });

    $("#language_options li a").click(function(){
        var href = $(this).attr("href").substring(17);
        
        var locale = null;
        switch(href){
            case 'pt_BR':
                locale = "br";
                break;
                
            case 'cs_CZ':
                locale = "cz";
                break;
                
            case 'hu_HU':
                locale = "hu";
                break;
                
            case 'pl_PL':
                locale = "pl";
                break;
                
            case 'pt_PT':
                locale = "pt";
                break;
                
            case 'ru_RU':
                locale = "ru";
                break;
        }
        if(locale){
            location.href = "/legacy/index.html?lang=" + locale;
            return false;
        }
        
        return true;
    });

});
