//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 = $(li).parent().parent().parent().parent();
	$(numbers_container).find('div.item_number').children('.item_total').html(carousel.size());
	$(numbers_container).find('div.item_number').children('.current_item').html(idx);
}


jQuery(document).ready(function() {
	
	ActivateCarousel();
	autoComplete();
	
	$('.vertical-list h3 a, .narrow-chart h3 a').truncate({ lines: 2 });
	$('.gridListContainer h3 a').truncate({ lines: 3, display: 'inline' });
	$('.mycarousels h3 a').truncate({ lines: 3, offset: -5 });
	
	// Add the search box event handlers....
	$('#dym-search').click(function() {
	    var search = $('#sadv').val();
	    this.href += '?s=' + search;
	});

	$('#sadv').bind('keydown', function(event) {
	    var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
	    if (keycode == 13) {
	        var input = $(this).val();
	        window.location = $('#dym-search').attr('href') + '?s=' + input;
	        return false;
	    } else {
	        return true;
	    }
	}); 
	
    var searchText = $('#s').val();
    $('#s').focus(function() {
        if ($(this).val() == searchText) {
            $(this).val('');
        }
    }).blur(function() {
        if ($(this).val() == "") {
            $(this).val(searchText);
        }
    });

    $('#SearchForm').submit(function(e) {
        if ($('#s').val() == "" || $('#s').val() == searchText) {
            return false;
        }
    });
	
	/*** product page expanding/colapsing boxes ***/
	var aExpand = $('.box_bottom_link').find('a');
	
	//collapse all divs on load
	$('.expandable').css('height','auto');

	$(aExpand).click(function(){
		var htmlTxt = $(this).html();
		
		var gameSummaryDiv;
		var gameSummaryEmbedArray;
		
		if($(this).is('.expanded')){
			$(this).parent('.box_bottom_link').siblings('.expandable').css('height','55px');
			$(this).html(systemResources.ReadMore);
			$(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($(this).not('.expanded')){
			$(this).parent('.box_bottom_link').siblings('.expandable').css('height','auto');
			$(this).html(systemResources.Collapse);
			$(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 = $('.box_bottom_link_ajax').find('a');
	
	//collapse all divs on load
	$('.expandable').css('height','auto');

	$(aExpandAjax).click(function(){
		var htmlTxt = $(this).html();
		
		if($(this).is('.expanded')){
			$(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','55px');
			$(this).html(systemResources.ReadMore);
			$(this).removeClass();
			
			return false;
		}
		if($(this).not('.expanded')){
			$(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','auto');
			$(this).html(systemResources.Collapse);
			$(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() 
	{
		ActivateCarousel();	
	});
}

function ActivateCarousel() {

	$('.mycarousels').css('marginLeft', '5px');
		//4 item carousel
		jQuery(".mycarousels").jcarousel({
	        wrap:"circular",		
			itemVisible: 4,
			itemScroll: 4,
			scrollAnimation:"1000"
		});

		$('.mycarousels li').css({height:'auto'});
		$('.mycarousels li img').css('marginLeft', '0');
		//$('.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
		$('.mycarousels_small li').css({height:'auto'});
		//$('.mycarousels_small li').css('overflow-y', 'none');

		//disables carousels button default action
		$("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 = $('.box_bottom_link_ajax').find('a');
	
	//collapse all divs on load
	$('.expandable').css('height','auto');

	$(aExpandAjax).click(function(){
		var htmlTxt = $(this).html();
		
		if($(this).is('.expanded')){
			$(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','60px');
			$(this).html(systemResources.ReadMore);
			$(this).removeClass();
			
			return false;
		}
		if($(this).not('.expanded')){
			$(this).parent('.box_bottom_link_ajax').siblings('.expandable').css('height','auto');
			$(this).html(systemResources.Collapse);
			$(this).addClass('expanded');
		}
		return false;
	});
}

function LoadImage(imageCtrl, imageSrc, altText)
{
	var image = document.getElementById(imageCtrl);
	if(image)
	{
		image.src = imageSrc;
		image.alt = altText;
	}
}

//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")');


/*****************************************************************
Add to basket prompting
/*****************************************************************/
AttachLoadEvent('checkBasket()');

function HintFactory()
{
    return new basketHinter();
}

//Prototype to encapsulate properties
function basketHinter()
{
    this.theCount  = document.getElementById("ctl00_ctlShoppingBasket_lblItemsCount");
    this.theLooker = document.getElementById ("ohLook");
    this.theLink   = document.getElementById ("ctl00_QuickLinks1_ListItemRepeater_ctl02_QuickLinksMenu");
    
    this.closeHint = function() 
    {
        this.theLooker.style.display = "none";
        this.theLink.style.color = 'red';
        window.setTimeout("HintFactory().theLink.style.color='black';", 1000);    
    }
    
    this.openHint = function()
    {
        nowCount = this.theCount.innerHTML;
        wasCount = getCookie("numb");
        
        if (nowCount > 0)
        {
            this.theLink.style.fontWeight = "bold";    
        }

        if (nowCount > wasCount && wasCount != null) //Has basket count increased... 
        {
            this.theLooker.style.display  = "block";
            this.theLink.style.color      = "red";
         }
            
        //Store value for comparison
        setCookie("numb",nowCount,"","/");
    }
}

// Check if anything is added to basket and render some UI hints
function checkBasket()
{
    HintFactory().openHint();
}

//Dismiss the UI hints
function closeBubbler()
{
    HintFactory().closeHint();
}

/**
Cookie Helpers - http://www.java2s.com/Code/JavaScript/Development/Cookieutilityfunction.htm
**/

// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/*****************************************************************/



//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;


// Script from Bryan Roberts to support lowdown

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
 
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
 
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
 
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function triggerHideOutOfStock(e) {
	var uri = '';
	var check = e.checked ? 1 : 0
	var hasQS = (location.search.substring(1) != '');
	if (hasQS) {
	    // There is currently a query string, first we will remove any existing "hidelag" value (note the RegEx "i" param makes it case insensitive)
	    uri = location.search.replace(new RegExp("[\&\?]hideflag=[^&]+", "i"), "")
	    // Next remove any leading "&" if it exists and replace with a "?"
	    uri = uri.replace(new RegExp("^&"), "?")

	    if (check) {
	        // The user wants to hide out of stocks so we need to either add "hideflag=1" to the existing query string
	        if (uri == "") {
	            uri = "?hideflag=1"
	        }
	        else {
	            uri = uri + "&hideflag=1"
	        }
	    }
	    else {
	        if (uri == "") {
	            uri = "?hideflag=0"
	        }
	    } 
	    location.replace(uri);
	}
	else {
	    // There is currently no query string and the user wants to hide out of stocks so add ?hideflag=1
	    if (check) {
	        location.replace('?hideflag=1');
	    }
	    // Note if there is currently no query string and the user wants to see out of stocks we don't need to do anything to the url
	}
}