// JavaScript Document
function include_dom(script_filename) {
	var html_doc = document.getElementsByTagName('head').item(0);
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', script_filename);
	html_doc.appendChild(js);
	return false;
}

include_dom('/includes/javascript/b2b/ajax_standard.js');
include_dom('/includes/javascript/global/popup.js');

function getElementsByClassName(classname, node)  {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
	return a;
}

function getXMLHttp() {
	var xmlHttp;
	
	try
	{
		//Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		//Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	
	return xmlHttp;
}

function buyNowCapture(pcode,type,linktype,domain,deal_pos) {
	var ajax = new Ajax();
	ajax.async = false; // Synchronous mode, ie. wait to finish before continuing.
	ajax.doGet('/tools/buy-now-capture.php?pcode=' + pcode + '&type=' + type + '&page=' + window.location.href + '&linktype=' + linktype + '&domain=' + domain + '&dealpos=' + deal_pos);
}

function identifyBrowser() {
	var agent = navigator.userAgent.toLowerCase();

	if(typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" && typeof window.sidebar != "undefined") {
		return "kde";
	}else if(typeof window.opera != "undefined") {
		var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));
		if(version >= 7) {
			return "opera7";
		}else if (version >= 5) {
			return "opera 5";
		}
		return false;
	}else if (typeof document.all != "undefined") {
		if(typeof document.getElementById != "undefined") {
			var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");
			if(typeof document.uniqueID != "undefined") {
				if(browser.indexOf("5.5") != -1) {
					return browser.replace(/(.*5\.5).*/, "$1");
				}else {
					return browser.replace(/(.*)\..*/, "$1");
				}
			}else {
				return "ie5mac";
			}
		}
		return false;
	}else if(typeof document.getElementById != "undefined") {
		if(navigator.vendor.indexOf("Apple Computer, Inc.") != -1) {
			if(typeof window.XMLHttpRequest != "undefined") {
				return "safari1.2";
			}
			return "safari1";
		}else if(agent.indexOf("gecko") != -1) {
			return "mozilla";
		}
	}
	return false;
}

function getScrollPosition() {
	var position = [0, 0];

	if(typeof window.pageYOffset != 'undefined') {
		position = [
		window.pageXOffset,
		window.pageYOffset,
		];
	}else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) {
		position = [
		document.documentElement.scrollLeft,
		document.documentElement.scrollTop,
		];
	}else if(typeof document.body.scrollTop != 'undefined') {
		position = [
		document.body.scrollLeft,
		document.body.scrollTop,
		];
	}
	return position;
}

function getBrowserSize() {
	var size = [0, 0];

	if(typeof window.innerWidth != 'undefined') {
		size = [
		window.innerWidth,
		window.innerHeight
		];
	}else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
		size = [
		document.documentElement.clientWidth,
		document.documentElement.clientHeight
		];
	}else {
		size = [
		document.getElementsByTagName('body')[0].clientWidth,
		document.getElementsByTagName('body')[0].clientHeight,
		];
	}
	return size;
}

// Cookie Functions
function trim(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}

	return sString;
}

function setCookie(cookieName, cookieValue, nDays, secure) {
	var theCookie = cookieName + "=" + cookieValue;

	// Cookie expiry date
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*nDays);
	theCookie += ";expires=" + expire.toGMTString();

	// Cookie domain
	//theCookie += ";domain=dev.mobileshop.com";

	// Cookie path
	theCookie += ";path=/";

	// Secure cookie (https)
	if(secure) {
		theCookie += ";secure";
	}

	document.cookie = theCookie;
}

function writeSessionCookie (cookieName, cookieValue) {

	document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
}

//function getCookie(searchName) {
//	var cookies = document.cookie.split(";");
//
//	for(var i = 0; i < cookies.length; i++) {
//		var cookieCrumbs = cookies[i].split("=");
//		var cookieName = cookieCrumbs[0];
//		var cookieValue = cookieCrumbs[1];
//
//		if(trim(cookieName) == trim(searchName)) {
//			return cookieValue;
//		}
//	}
//	return false;
//}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return false;
	}
}

// Gives us the ability to assign any number of load event handlers
function getEventTarget(event)
{
	var targetElement = null;
	
	if (typeof event.target != "undefined")
	{
		targetElement = event.target;
	}
	else
	{
		targetElement = event.srcElement;
	}

	while (targetElement.nodeType == 3 &&
	targetElement.parentNode != null)
	{
		targetElement = targetElement.parentNode;
	}

	return targetElement;
}

function addLoadListener(fn)
{
	if(typeof window.addEventListener != 'undefined')
	{
		window.addEventListener('load', fn, false);
	}
	else if(typeof document.addEventListener != 'undefined')
	{
		document.addEventListener('load', fn, false);
	}
	else if(typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		var oldfn = window.onload;
		if(typeof window.onload != 'function')
		{
			window.onload.fn;
		}
		else
		{
			window.onload = function()
			{
				oldfn();
				fn();
			};
		}
	}
}

// This sets what values are passed to the function attachEventListener().
function attachEventListener(target, eventType, functionRef, capture) {
	if(typeof target.addEventListener != "undefined") { // If target.addEventListener can be defined in browser.

		target.addEventListener(eventType, functionRef, capture); // Use these values in target.addEventListener.

	}else if(typeof target.attachEvent != "undefined") { // If IE browser - target.attachEvent can be defined.

		target.attachEvent("on" + eventType, functionRef); // Add 'on' to the begining of the event type e.g. 'onclick'.

	}else {

		// This is for really old browsers.
		eventType = "on" + eventType;

		if(typeof target[eventType] == "function") {

			var oldListener = target[eventType];

			target[eventType] = function() {

				oldListener();

				return functionRef;

			};

		}else {

			target[eventType] = functionRef;

		}

	}

}

function trackPage(pagename) {
	// Added 04/09/2008 by CS
	// This function enables a tag to be recorded in Google Analytics when a page is loaded
	addLoadListener(function() {
		urchinTracker(pagename);
	});
}

function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
	}

	arrayPageSizeWithScroll = yWithScroll;
	//arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}

/********** Debugging Functions **********/
function dumpAlert(arr,level)
{
	var dumped_text = "";
	
	if(!level)
	{
		level = 0;
	}
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	
	for(var j = 0; j < level + 1; j++)
	{
		level_padding += "    ";
	}
	
	if(typeof(arr) == 'object') //Array/Hashes/Objects 
	{ 
		for(var item in arr)
		{
			var value = arr[item];
			
			if(typeof(value) == 'object') //If it is an array,
			{
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			}
			else
			{
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	}
	else //Stings/Chars/Numbers etc.
	{ 
		dumped_text = arr+": (" + typeof(arr) + ")";
	}
	
	alert(dumped_text);
}
/********** Debugging Functions End **********/

document.onclick = function(e)
{
	var thisBrowser = identifyBrowser();

	var target = e ? e.target : window.event.srcElement;

	while (target && !/^(a|body)$/i.test(target.nodeName))
	{
		target = target.parentNode;
	}

	if (target && target.getAttribute('rel'))
	{
		// If no width or height is specified.
		if(target.rel == 'globalPopup')
		{
			if(thisBrowser == 'ie6')
			{
				var target = e ? e.target : window.event.srcElement;
				window.open(target.href,'globalIE6Popup','width=500,height=600');
				return false;
			}
			else
			{
				globalPopup(target.href);
				return false;
			}
		}
		else
		{
			// If a width and height is given.
			var targetRel = target.rel.split("-");
			
			if(thisBrowser == 'ie6' && targetRel[0] == 'globalPopup')
			{
				var target = e ? e.target : window.event.srcElement;
				
				// Set the default link.
				var targetPopupLink = target.href;
				
				// If the default link has an image ext.
				if(targetPopupLink.match(/\.jpg|\.gif|.png/))
				{
					// Set the link to the parent's href.
					targetPopupLink = window.event.srcElement.parentNode.href; 
				}
				
				window.open(targetPopupLink,'globalIE6Popup','width=570,height=600,status=1,scrollbars=1');				
				return false;
			}
			else
			{
				if(targetRel[0] == 'globalPopup')
				{
					var width    = parseInt(targetRel[1]);
					var height   = parseInt(targetRel[2]);
					var linkHref = target.href;

					if(targetRel[3])
					{
						if(targetRel[3] == 'div')
						{
							var linkHrefRaw = target.href.split('/');
							linkHref = linkHrefRaw[linkHrefRaw.length-1];
						}
					}

					globalPopup(linkHref,width,height);
					return false;
				}
			}
		}
	}
}

/********** Top Tens Click Handlers Start *********/
$(document).ready(function()
{
	if($('#toptenheader').length)
	{	
		var tabArray = $('#toptenheader h2');
		var contentArray = $('#handsetscontainer div');
		
		//the top ten tabs onClick handler
		$('#toptenheader h2').click(function()
		{	
			//fade out and remove tabon classes and content
			$('#toptenheader h2').removeClass("tabOn");				
			
			//set last tab id back to last tab
			if($('#lastTabOn').length)
			{
				$('#lastTabOn').attr("id", "lastTab");
			}		
			
			if($(this).attr("id") == "lastTab")
			{
				$('#lastTab').attr("id", "lastTabOn");
				//on last tab change id to last tab on
			}
			else
			{		
				//add class tabon to (this) element
				$(this).addClass("tabOn");
			}
			
			var tabKey = getArrayKey(tabArray, $(this).text());		
			
			if(tabKey != -1)
			{
				if ($(contentArray[tabKey]).length)
				{
					$('#handsetscontainer div').fadeOut("slow");
					$('#handsetscontainer div').removeClass("curTopTen");
					$(contentArray[tabKey]).addClass("curTopTen");
					$(contentArray[tabKey]).fadeIn("slow");
				}
			}
			
		});
	}
});

function getArrayKey(array, value)
{
	var result = -1;
	var arrayLen = array.length;
	
	if(arrayLen > 0)
	{
		for(var a = 0; a < arrayLen; a++)
		{			
			if ($(array[a]).text() == value)
			{				
				result = a;				
				break;
			}
		}
	}
	
	return result;
}

/*********** Top Tens Click Handlers End **********/