//using JQuery with Prototype
jQuery.noConflict();

//Variable which allows pages to control the blur and focus events on form fields
var createFocusAndBlurEvents = true;

//Check Browser has cookies enabled
try
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof(navigator.cookieEnabled) == "undefined" && !cookieEnabled)
	{ 
		document.cookie = "testcookie";
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}

	if (!cookieEnabled && window.location.toString().indexOf("CookiesDisabled.aspx") == -1) 
	{
		window.location.replace("/Help/CookiesDisabled.aspx");
	}
}
catch(e){}

function RunLoadEvents()
{  
	for(var i = 0;i < onloadFunctions.length;i++) 
	{   
		eval(onloadFunctions[i]);
	}
}
		
function AttachLoadEvent(func)
{  
	onloadFunctions[onloadFunctions.length] = func;
}

var onloadFunctions = new Array();


/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function itemFirstInHandler(carousel, li, idx, state) {
	var numbers_container = jQuery(li).parent().parent().parent().parent();
	jQuery(numbers_container).find('div.item_number').children('.item_total').html(carousel.size());
	jQuery(numbers_container).find('div.item_number').children('.current_item').html(idx);
}

function showhideArticles(anchor) {
    var link = jQuery( anchor );
    var panel = link.parent().parent().children( 'div.articles' );
    if ( panel.is( '.expanded' ) ) {
        panel.css( 'height', '200px' );
        panel.removeClass( 'expanded' );
        link.html( 'Read more' );
        return false;
    }
    else if ( panel.not( '.expanded' ) ) {
        panel.css( 'height', 'auto' );
        panel.addClass( 'expanded' );
        link.html( 'Collapse' );
        return false;
    };
};

function showhideProductInfo(anchor) {
    var link = jQuery( anchor );
    var panel = link.parent().parent().children( 'div.content' );
    if ( panel.is( '.expanded' ) ) {
        panel.css( 'height', '200px' );
        panel.removeClass( 'expanded' );
        link.html( 'Read more' );
        return false;
    }
    else if ( panel.not( '.expanded' ) ) {
        panel.css( 'height', 'auto' );
        panel.addClass( 'expanded' );
        link.html( 'Collapse' );
        return false;
    };
};

jQuery(document).ready(function() {


    jQuery('.mycarousels').css('marginLeft', '5px');
	//4 item carousel
	jQuery(".mycarousels").jcarousel({
	    wrap:"circular",
		itemVisible: 4,
		itemScroll: 4,
		scrollAnimation:"1000"
	});

	jQuery('.mycarousels li').css({height:'auto'});
	jQuery('.mycarousels li img').css('marginLeft', '0');
	//jQuery('.mycarousels li').css('overflow-y', 'none' );
  
  /** 1 item carousels **/
	jQuery(".mycarousels_small").jcarousel({
	    wrap:"circular",	
		itemVisible: 1,
		itemScroll: 1,
		scrollAnimation:"1000",
		itemFirstInHandler: itemFirstInHandler
	});
	
	 /** 2 item carousels **/
	jQuery(".mycarousels_double").jcarousel({
	    wrap:"circular",	
		itemVisible: 2,
		itemScroll: 2,
		scrollAnimation:"1000"
	});
	
	 /** screenshots/video carousels **/
	jQuery(".mycarousels_screenshots").jcarousel({
	    wrap:"circular",	
		itemVisible: 5,
		itemScroll: 5,
		scrollAnimation:"1000"
	});
	
	
	//disables height when js enabled
	jQuery('.mycarousels_small li').css({height:'auto'});
	//jQuery('.mycarousels_small li').css('overflow-y', 'none');

	//disables carousels button default action
	jQuery("a.carousel_btn").click(function() {
		return false;
	});

	

	/***top promo image swapping***/
	jQuery(".top_promo_links:first-child").find("a:first").addClass("on");
	jQuery(".top_promo").find("li").hide();
	jQuery(".top_promo").find("li:first").show();


	jQuery(".top_promo_links li a").click(function() {
		
		if(jQuery(this).is(".on")){
			return false;
		} else{
			jQuery(this).parent().parent().find("a").removeClass("on");
			jQuery(this).addClass("on");

			var cur_li = jQuery(this).parent()[0];				
			var aindex = jQuery(this).parent().parent().find("li").index(cur_li);
			
		    var tp_promo = jQuery(this).parent().parent().parent().find(".top_promo").find("li");
							
			tp_promo.hide();
			tp_promo.eq(aindex).show();
		}		
		return false;
	});
	
	
	/***input fields focuses and tab sequence tweaks***/
	jQuery("input.email").focus(function() {
			jQuery(this).attr("value", "");
	}).blur(function() {
		jQuery(this).attr("value", "Email address");
	});
	jQuery("#keyword").focus().next().blur(function() {
		jQuery('.left_nav li:first a').focus();
	});
	jQuery('#nav_popup').find('ul:last li:last a').blur(function() {
		jQuery('.box_news').find('h2 a').focus();
	});



	var tn_list = jQuery('#a_nav_popup');
	var tn_all_link = tn_list.children('a');
	var popup = jQuery('#nav_popup');	
	
	var select_box = jQuery('.search_bar .select_container .select_box');
	
	var select_contents = jQuery(select_box).html();
	var select_box_image = '<img src="/css/gameUK/img/search_select_replacement.gif" />';
	
	jQuery(tn_list).hoverIntent(function() {
	    
	    jQuery(select_box).html(select_box_image);
	    
		jQuery(popup).fadeIn('fast', function(){
          jQuery(select_box).html(select_box_image);
        });
		jQuery(tn_all_link).addClass("laston");
	},
	 function() {
		jQuery(popup).fadeOut('fast',function(){
          jQuery(select_box).html(select_contents);
        });
		jQuery(tn_all_link).removeClass("laston");
	});
	
		jQuery(tn_all_link).focus(function() {
			jQuery(popup).fadeIn('fast');
			jQuery(tn_all_link).addClass("laston");
		});
		
		popup.find('a.last').blur(function() {
			jQuery(popup).fadeOut('fast');
			jQuery(tn_all_link).removeClass("laston");
		});

	


	/*** product page expanding/colapsing boxes ***/
	var aExpand = jQuery('.box_bottom_link').find('a');
	
	//collapse all divs on load
	jQuery('.expandable').css('height','auto');

	jQuery(aExpand).click(function(){
		var htmlTxt = jQuery(this).html();
		
		var gameSummaryDiv;
		var gameSummaryEmbedArray;
		
		if(jQuery(this).is('.expanded')){
			jQuery(this).parent('.box_bottom_link').siblings('.expandable').css('height','47px');
			jQuery(this).html("Read More");
			jQuery(this).removeClass();

            /* Do we need to hide any embedded content*/			
			gameSummaryDiv = document.getElementById('game_summary');
			if ( gameSummaryDiv )
			{
			    gameSummaryEmbedArray = gameSummaryDiv.getElementsByTagName('embed');

                /* Cycle over the embedded content */			    
			    for (index=0;index<gameSummaryEmbedArray.length;index++)
			    {
			        gameSummaryEmbedArray[index].style.display = 'none';
			    }
			}
			
			return false;
		}
		if(jQuery(this).not('.expanded')){
			jQuery(this).parent('.box_bottom_link').siblings('.expandable').css('height','auto');
			jQuery(this).html("Collapse");
			jQuery(this).addClass('expanded');
			
			/* Do we need to show any embedded content*/			
			gameSummaryDiv = document.getElementById('game_summary');
			if ( gameSummaryDiv )
			{
			    gameSummaryEmbedArray = gameSummaryDiv.getElementsByTagName('embed');

                /* Cycle over the embedded content */			    
			    for (index=0;index<gameSummaryEmbedArray.length;index++)
			    {
			        gameSummaryEmbedArray[index].style.display = '';
			    }
			}
		}
		return false;
	});
	
	/*** product page expanding/colapsing boxes ***/
	var aExpandAjax = jQuery('.box_bottom_link_ajax').find('a');
	
	//collapse all divs on load
	jQuery('.expandable').css('height','auto');

	jQuery(aExpandAjax).click(function(){
		var htmlTxt = jQuery(this).html();
		
		if(jQuery(this).is('.expanded')){
			jQuery(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','47px');
			jQuery(this).html("Read More");
			jQuery(this).removeClass();
			
			return false;
		}
		if(jQuery(this).not('.expanded')){
			jQuery(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','auto');
			jQuery(this).html("Collapse");
			jQuery(this).addClass('expanded');
		}
		return false;
	});
		
	var recommCarousel = jQuery('.recommendationsWindow');
	var close_link = jQuery(recommCarousel).find('a.close_link');
	
	jQuery(close_link).click(function(){
		jQuery(recommCarousel).find('.expandableDiv').toggle();
		
		if(jQuery(this).is('.expanded')){
			jQuery(this).html("Close recommendations window");
			jQuery(this).removeClass('expanded');
			return false;
		}
		if(jQuery(this).not('.expanded')){
			jQuery(this).html("Open recommendations window");
			jQuery(this).addClass('expanded');
		}
		return false;
	});
});



//This function gets called after asynchronous postback as we need to 
//re-initialise the carousel
function InitCarousel()
{
	jQuery(document).ready(
	function() 
	{
		jQuery('.mycarousels').css('marginLeft', '5px');
		//4 item carousel
		jQuery(".mycarousels").jcarousel({
	        wrap:"circular",		
			itemVisible: 4,
			itemScroll: 4,
			scrollAnimation:"1000"
		});

		jQuery('.mycarousels li').css({height:'auto'});
		jQuery('.mycarousels li img').css('marginLeft', '0');
		//jQuery('.mycarousels li').css('overflow-y', 'none' );
	  
	  /** 1 item carousels **/
		jQuery(".mycarousels_small").jcarousel({
	        wrap:"circular",		
			itemVisible: 1,
			itemScroll: 1,
			scrollAnimation:"1000",
			itemFirstInHandler: itemFirstInHandler
		});
		
		 /** 2 item carousels **/
		jQuery(".mycarousels_double").jcarousel({
	        wrap:"circular",		
			itemVisible: 2,
			itemScroll: 2,
			scrollAnimation:"1000"
		});
		
		 /** screenshots/video carousels **/
		jQuery(".mycarousels_screenshots").jcarousel({
	        wrap:"circular",		
			itemVisible: 5,
			itemScroll: 5,
			scrollAnimation:"1000"
		});
		
		
		//disables height when js enabled
		jQuery('.mycarousels_small li').css({height:'auto'});
		//jQuery('.mycarousels_small li').css('overflow-y', 'none');

		//disables carousels button default action
		jQuery("a.carousel_btn").click(function() {
			return false;
		});
	});
}

//This function gets called after asynchronous postback as we need to 
//re-initialise the expandable element events
function InitExpand()
{
	/*** product page expanding/colapsing boxes ***/
	var aExpandAjax = jQuery('.box_bottom_link_ajax').find('a');
	
	//collapse all divs on load
	jQuery('.expandable').css('height','auto');

	jQuery(aExpandAjax).click(function(){
		var htmlTxt = jQuery(this).html();
		
		if(jQuery(this).is('.expanded')){
			jQuery(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','60px');
			jQuery(this).html("Read More");
			jQuery(this).removeClass();
			
			return false;
		}
		if(jQuery(this).not('.expanded')){
			jQuery(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','auto');
			jQuery(this).html("Collapse");
			jQuery(this).addClass('expanded');
		}
		return false;
	});
}

function LoadImage(imageCtrl, imageSrc, altText, screenshotContainer, VideoInfoContainer)
{
	var image = document.getElementById(imageCtrl);
	var screenshotImageHolder = document.getElementById(screenshotContainer);
	var VideoPlayerContainer = document.getElementById(VideoInfoContainer);
	if(image && screenshotImageHolder && VideoPlayerContainer)
	{
        image.src = imageSrc;
		image.alt = altText;
		
		screenshotImageHolder.style.display = 'block';
		VideoPlayerContainer.style.display = 'none';
		//stops video.
		setplayerURL ("");
		screenshotImageHolder.removeClassName("progress");
	}
}

//function is used to attach the click event to a button
//which firefox does not recognise, this enabled the enter key 
//to fire events using the DefaultButton
function attachClickEvent(btn)
{
	if (btn && typeof(btn.click) == 'undefined') 
	{
		btn.click = function() 
		{  
			var result = true;
			if (btn.onclick) result = btn.onclick();
			if (typeof(result) == 'undefined' || result) 
			{
				eval(btn.href);
			}
		}
	}
}

// added to support links to external sites in /gadgets
function popitup(url) {
	newwindow=window.open(url,'name','height=500,width=750,resizable=yes,status=yes,menubar=yes,toolbar=yes,location=yes,scrollbars=yes,copyhistory=yes' );
	if (window.focus) 
	{
		newwindow.focus();
	}
	return false;
}

// ** added IE specific function to emulate the :focus pseudo-class which is supported in all other browsers.
// ** input pseudo-class:focus hack 
// ** fyi - implemented this technique http://www.htmldog.com/articles/suckerfish/focus/ 

function doFocus(type, tag, parentId) 
{
	if(createFocusAndBlurEvents)
	{
		var sfEls = (parentId==null)?document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
		type(sfEls);
	}
}

sfFocus = function(sfEls) 
{
	if(createFocusAndBlurEvents)
	{
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onfocus=function() {
				this.className+=" sffocus";
			}
			sfEls[i].onblur=function() {
				this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
			}
		}
	}
}

function bookmarkPage(pageTitle,url)
{
    if (window.sidebar) // Firefox
	    window.sidebar.addPanel(pageTitle, url, "");
    else if(window.opera && window.print)
    { // Opera
	    var element = document.createElement('a');
	    element.setAttribute('href',url);
	    element.setAttribute('title',pageTitle);
	    element.setAttribute('rel','sidebar');
	    element.click();
    } 
    else if(document.all)// Internet Explorer
	    window.external.AddFavorite(url, pageTitle);
}

// attach event to specific HTML elements
AttachLoadEvent('doFocus(sfFocus, "INPUT")');
AttachLoadEvent('doFocus(sfFocus, "TEXTAREA")');
AttachLoadEvent('doFocus(sfFocus, "SELECT")');

//THIS MUST BE THE ONLY PLACE IN THE SITE WHICH ASSIGNS A FUNCTION TO THE ONLOAD EVENT
//OTHERWISE COREMETRICS WILL NOT LOAD CORRECTLY, IF YOU WANT TO ADD ONLOAD FUNCTION CALLS
//CALL THE AttachLoadEvent() FUNCTION PASSING IN THE FUNCTION REFERENCE
//I.E. AttachLoadEvent("attachClickEvent(document.getElementById('ControlId'));")
window.onload = RunLoadEvents;

//the below empty function is required for the ajax tab control for function. Please do not remove this function
function ActiveTabChanged(sender, e) {
}

function hideIESelectElements() {
    if (jQuery.browser.msie ) {
        jQuery( 'select' ).hide();
    };
};

function showIESelectElements() {
    if (jQuery.browser.msie ) {
        jQuery( 'select' ).show();
    };
};

// tracking and cookie

function setTrackingCookie() {
    setCookie( 'tracking', true, 1 );
};
function getTrackingCookie() {
    return getCookie( 'tracking' );
};
function deleteTrackingCookie() {
    setCookie( 'tracking', '', 0 );
};
function insertTrackingImg( src, id ) {
    var img = new Image();
    img.src = src;
    img.width = 1;
    img.height = 1;
    $( id ).insert ( img );
};

function setCookie( name, value, days ) {
    var date = new Date();
    date.setDate( date.getDate() + days );
    document.cookie = name + '=' + escape( value ) + ( ( days == null ) ? '' : ';expires=' + date.toGMTString() );
};

function getCookie( name ) {
    if ( document.cookie.length > 0 ) {
        var start = document.cookie.indexOf( name + '=' );
        if ( start != -1 ) {
            start = start + name.length + 1;
            var end = document.cookie.indexOf( ';', start );
            if ( end == -1 ) {
                end=document.cookie.length;
            };
            return unescape( document.cookie.substring( start, end ) );
        }
    }
    return '';
};