//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") == -1) 
	{
		window.location.replace("/Help/~h9120/CookiesDisabled/");
	}
}
catch(e){}

function RunLoadEvents()
{  
	for(var i = 0;i < onloadFunctions.length;i++) 
	{   
	    try
	    {
		    eval(onloadFunctions[i]);
		}
	    catch(e){}    
	}
}
		
function AttachLoadEvent(func)
{  
	onloadFunctions[onloadFunctions.length] = func;
}

var Url = {
	encode : function (string) {
		var output = '';
		var x = 0;
		string = string.toString();
		var regex = /(^[a-zA-Z0-9_.]*)/;
		while (x < string.length) {
			var match = regex.exec(string.substr(x));
			if (match != null && match.length > 1 && match[1] != '') {
				output += match[1];
				x += match[1].length;
			} else {
				if (string[x] == ' ')
					output += '+';
				else {
					var charCode = string.charCodeAt(x);
					var hexVal = charCode.toString(16);
					output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
				}
				x++;
			}
		}
		return output;
	}
}

var onloadFunctions = new Array();

function showhideArticles(anchor) {
	var link = $(anchor);
	link.up('div.content').select('div.articles').each(function(e, index) {
		if (e.match('.expanded')) {
			e.setStyle({'height':'200px'});
			e.removeClassName('expanded');
			link.update('Read more');
			return false;
		}
		else if (!e.match('.expanded')) {
			e.setStyle({'height':'auto'});
			e.addClassName('expanded');
			link.update('Collapse');
			return false;
		}
	});
};

document.observe("dom:loaded", function() {

	InitCarousel();
	searchAsYouType.initialize(document.getElementById('search'), false); 
	
	$$('.ajax__tab_tab').each(function(e, i) {
		e.observe('click', function(event) {
			new Truncate($$('.product_grid_list span.title'), { 
				lines: 4, 
				lineHeight: 13
			});		
		});
	});
	
	new Truncate($$('.mycarousels h3 a'), { lines: 3, lineHeight: 15 });
	new Truncate($$('.mycarousels_double h3 a'), { lines: 3, lineHeight: 15, display: 'block' });
	new Truncate($$('.product_grid_list span.title'), { lines: 4, lineHeight: 13 });
	new Truncate($$('.featured-products h3 a, .vertical-list h3 a'), { lines: 2, lineHeight: 14, display: 'block' });
	
	if($('promo') != null) {
		var el = $('promo');
		new GAME.UI.Rotator( 'promo', { 
			sDelay : 5, 
			sElement : 'li', 
			sShowClass : 'show', 
			sHideClass : 'hide', 
			sFadeClass : 'fade', 
			sOrder : 'asc', 
			bLoop : 'true', 
			sControlElement : 'ol'
		});	
	}
	
	var SubmitSearch = function() {
		var search = $('search');
		if(search.value.length > 0) {
			var action = search.up('form').readAttribute('action');		
			var querystring = action.split('?');
			location.href = (querystring.length > 1) ? action + '&s=' + Url.encode(search.value) : action + '?s=' + Url.encode(search.value);
		}
	}
	
	if($('SearchGo') != null) {
		$('SearchGo').observe('click', function(event) {
			new SubmitSearch;
			event.stop();
		});
	}
	
	if($('search') != null) {
		$('search').observe('keydown', function(event) {
			if(event.keyCode == Event.KEY_RETURN) {
				new SubmitSearch;
				event.stop();
			}
		});
	}
	
	if($('dym-search') != null) {
		$('dym-search').observe('click', function(event) {
			var search = $('sadv').value;
			this.writeAttribute('href', this.readAttribute('href') + '?s=' + search);
		});
	}
	
	if($('sadv') != null) {
		$('sadv').observe('keydown', function(event) {
			var submit = $('dym-search');
			if(event.keyCode == 13) {
				window.location = submit.readAttribute('href') + '?s=' + this.value;
				event.stop();
			}
		});
	}
	
	$$('.dimension', '.static-nav').each(function(e, i) {
		var el = $(e);
		el.select('li').each(function(e, i) {
			var li = e;
			li.onmouseover = function() {
				if(li.match('.view-all')) {
					li.addClassName('view-all-hover');
				} else {
					li.addClassName('list-hover');
				}
				/* - removed, bug #38210.
				li.onclick = function() {
					window.location = li.down().readAttribute('href');
				} */
				
				li.insert('<span class="bottom"></span><span class="bottom-inner"></span>');
			};
			li.onmouseout = function() {
				if(li.match('.view-all')) {
					li.removeClassName('view-all-hover');
				} else {
					li.removeClassName('list-hover');
				}
				li.select('.bottom', '.bottom-inner').each(function(e, index) {
					e.remove();
				})
			};
		});
	});
	
	 InitExpand()
	
}); 



//This function gets called after asynchronous postback as we need to 
//re-initialise the carousel
function InitCarousel()
{
	var previous = '<a href="javascript:void(0)" class="previous_button"></a>';
	var next = '<a href="javascript:void(0)" class="next_button"></a>';
	
	// 4 item carousel
	$$('.mycarousels .wrapper').each(function(e, index) {
		e.insert({ top: previous });
		e.insert({ bottom: next });
		new UI.Carousel(e, { scrollInc: 4, circular: true });
	});
	
	// screenshots/video carousels
	$$(".mycarousels_screenshots").each(function(e, index) {
		e.insert({ top: previous });
		e.insert({ bottom: next });		
		new UI.Carousel(e, { elementSize: 102, scrollInc: 5, circular: true });
	});
	
	// double carousel
	$$(".mycarousels_double .wrapper").each(function(e, index) {
		e.insert({ top: previous });
		e.insert({ bottom: next });		
		new UI.Carousel(e, { scrollInc: 2, circular: false });
	});
}

//This function gets called after asynchronous postback as we need to 
//re-initialise the expandable element events
function InitExpand()
{
	$$('.expandable').each(function(e, index) {
		$(e).setStyle({ 'height': 'auto' });
	});

	var aExpandAjax = 
	$$('.box_bottom_link_ajax').each(function(e, index) {
		e.select('a').each(function(e, index) {
			var el = $(e);
			el.observe('click', function(event) {
				var htmlTxt = el.innerHtml;
				if(el.match('.expanded')){
					el.up('.box_bottom_link_ajax').siblings().each(function(e, index) {
						if($(e).match('.expandable')) {
							$(e).setStyle({'height':'60px'});
						}
					});
					el.update('Read More');
					el.removeClassName('expanded');
				}
				if(!el.match('.expanded')){
					el.up('.box_bottom_link_ajax').siblings().each(function(e, index) {
						if($(e).match('.expandable')) {
							$(e).setStyle({'height':'auto'});
						}
					});
					el.update('Collapse');
					el.addClassName('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) {
}

// 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 '';
}; 


//Dynamically change the style of any class 
function changeCSSProperty(theClass,element,value) 
{
	return;
}

function triggerHideOutOfStock(e) {
	var uri = '';
	var check = e.checked ? 1 : 0
	var hasQS = (location.search.substring(1) != '');
	if(hasQS)
		uri = (location.search.substring(1).search('hideflag') < 0) ? location.search.substring(1) + '&hideflag=' + check : location.search.substring(1).replace('hideflag=' + ((check == 0) ? 1 : 0), '') + 'hideflag=' + check;
	else
		uri = 'hideflag=' + (e.checked ? 1 : 0)
	location.replace('?' + uri);
}
