var protocol = null;

// ==========================================
// General DOM Functions
//
function getElementObject (element)
{
	if (document.getElementById)
		return document.getElementById (element);
	else 
	if (document.all)
		return document.all[element];
	else 
		return null;
}

function removeElementChildren (element)
{
	if (document.getElementById && document.removeChild)
	{
		var el = document.getElementById (element);
		while (el.hasChildNodes ())
			el.removeChild (el.lastChild);		
		return true;
	} 
	else 
	if (document.getElementById && document.innerHTML) 
	{
		document.getElementById( element ).innerHTML = '';				
		return true;
	}
	
	return false;
}

if (Array.prototype.push == null)
	Array.prototype.push = function (item) { this[this.length] = item; return this.length; }

function closeElement (element)
{
	if (document.getElementById)
		document.getElementById (element).style.display = 'none';
	else 
	if (document.all)
		document.all[element].style.display = 'none';
	else 
	if (document.layers)
		document.layers[element].style.display = 'none';
}

function showElement (element)
{
	if (document.getElementById)
		document.getElementById (element).style.display = 'block';
	else 
	if (document.all)
		document.all[element].style.display = 'block';
	else 
	if (document.layers)
		document.layers[element].style.display = 'block';
}

function setElementVisibility (element, show) 
{       		
	try
	{
		if (document.getElementById)
			document.getElementById (element).style.display = (show) ? '' : 'none';
		else 
		if (document.all)
			document.all[element].style.display = (show) ? '' : 'none';
		else 
		if (document.layers)
			document.layers[element].style.display = (show) ? '' : 'none';
	}
	catch (e)
	{
		//alert (e.message);
	}
}

function setElementText (element, text) 
{       		
	try
	{
		text = text.replace (/\n/g, "<BR>");
		text = text.replace (/\'/g, "\\\'");	

		if (document.getElementById)
			document.getElementById (element).innerHTML = text;
		else 
		if (document.all)
			document.all[element].innerHTML = text;
		else 
		if (document.layers)
			document.layers[element].innerHTML = text;
	}
	catch (e)
	{
		//alert (e.message);
	}
}

function setAttributeClass (objElement, strValue, bAdd)
{	
	var strClass = objElement.className;
	if (strClass != null && strClass.length > 0)
	{
		if (bAdd)
		{
			objElement.className += " " + strValue;
			return;
		}
	} 
	
	objElement.className = strValue;
}

function removeFromClassAttribute (objElement, strValue)
{
	if (objElement.className.indexOf (strValue) < 0)
		return;
	
	if (objElement.className.indexOf (strValue) > 0)
		strValue = ' ' + strValue;
		
	objElement.className = objElement.className.replace (strValue, '');
}


// End DOM Functions
//==========================================

// Page Utilities

function setUsabilityButtons(){
	var obj = getElementObject( "txt-norm" );
	var objContent = getElementObject( "content" ) ? getElementObject( "content" ) : getElementObject( "content-only" );
	if( obj ){
		obj.onclick = function(){objContent.style.fontSize = "100%";return false;};
		obj.title = "Normal Text"
	}
	
	obj = getElementObject( "txt-larg" );
	if( obj ){
		obj.onclick = function(){objContent.style.fontSize = "115%";return false;};
		obj.title = "Large Text";
	}
	
	obj = getElementObject( "txt-xlp" );
	if( obj ) {
		obj.onclick = function(){objContent.style.fontSize = "130%";return false;};
		obj.title = "Larger Text";
	}

	obj = getElementObject( "btn-print" );
	if( obj ){
		obj.onclick = function(){if(window.print){window.print();return false;}};
	}
}

if (window.addEventListener) { // DOM 
	window.addEventListener('load', setUsabilityButtons, false);
} else if (window.attachEvent) { // IE
	window.attachEvent('onload', setUsabilityButtons);
}


// ==========================================


function GetProtocol()
{
	if (!protocol) {
		try {
			protocol = window.location.protocol;
		} catch (e) {
		}
	}
	return protocol;
}

function GetContentRequestAuthority()
{
	if (GetProtocol() == "https:")
		return "https://origin-image.alienware.com";
	else
		return "http://image.alienware.com";
}

function getCookie(name) {
	var result = null;
	var myCookie = " " + document.cookie + ";";
	var searchName = " " + name + "=";
	var startOfCookie = myCookie.indexOf(searchName);
	var endOfCookie;
	if( startOfCookie != -1 ) {
		startOfCookie += searchName.length; // skip past cookie name
		endOfCookie = myCookie.indexOf(";", startOfCookie);
		result = unescape(myCookie.substring(startOfCookie, endOfCookie));
	}
	return result;
}

//////////////////////////////////////////////////////////////////////////////////////
//  Browser detector class
function BrowserDetector( ua /* ua = User Agent */ ) 
{
	// Default values
	this.browser = "Unknown";
	this.platform = "Unknown";
	this.version = "";
	this.majorver = "";
	this.minorver = "";

	uaLen = ua.length;

	// Split into stuff before parens and stuff in parens
	var preparens = "";
	var parenthesized = "";
	var operaFix = ua.indexOf( "Opera" ) > 0;

	i = ua.indexOf( "(" );
	if( i >= 0 )
	{
		preparens = Trim( ua.substring( 0,i ) );
		parenthesized = ua.substring( i + 1, uaLen );
		j = parenthesized.indexOf( ")" );

		if( j >= 0 ) 
			parenthesized = parenthesized.substring(0, j);
	}
	else 
		preparens = ua;
  
	// First assume browser and version are in preparens
	// override later if we find them in the parenthesized stuff
	var browVer = preparens;
	var tokens = parenthesized.split( ";" );
	var token = "";

	// Now go through parenthesized tokens
	for( var i = 0; i < tokens.length; i++ ) 
	{
		token = Trim( tokens[i] );
        // compatible - might want to reset from Netscape
        if( token == "compatible" ) 
        {
			// One might want to reset browVer to a null string
			// here, but instead, we'll assume that if we don't
			// find out otherwise, then it really is Mozilla
			// (or whatever showed up before the parens).
			// browser - try for Opera or IE
		}
        else if( token.indexOf( "MSIE" ) >= 0 ) 
        	browVer = token;
		else if( token.indexOf( "Opera" ) >= 0 ) 
			browVer = token;
		//platform - try for X11, SunOS, Win, Mac, PPC
		else if( ( token.indexOf( "X11" ) >= 0 ) || 
				 ( token.indexOf( "SunOS" ) >= 0 ) ||
				 ( token.indexOf( "Linux" ) >= 0 ) ) 
			this.platform = "Unix";
        else if( token.indexOf( "Win" ) >= 0 ) 
        	this.platform = token;
        else if( ( token.indexOf( "Mac" ) >= 0 ) || ( token.indexOf( "PPC" ) >= 0 ) ) 
        	this.platform = token;        
	}

	var msieIndex = browVer.indexOf( "MSIE" );
	if( msieIndex >= 0 )
		browVer = browVer.substring( msieIndex, browVer.length );
	
	var leftover = "";
  
	if( !operaFix && browVer.substring( 0, "Mozilla".length ) == "Mozilla" ) 
	{
		this.browser = "Netscape";
        leftover = browVer.substring( "Mozilla".length + 1, browVer.length );
	}
	else if( !operaFix && browVer.substring( 0, "Lynx".length ) == "Lynx" ) 
	{
		this.browser = "Lynx";
        leftover = browVer.substring( "Lynx".length + 1, browVer.length );
	}
	else if( !operaFix && browVer.substring( 0, "MSIE".length ) == "MSIE" ) 
	{
		this.browser = "IE";
		leftover = browVer.substring( "MSIE".length + 1, browVer.length );
	}
	else if( !operaFix && 
		browVer.substring( 0, "Microsoft Internet Explorer".length ) ==	"Microsoft Internet Explorer" ) 
	{
		this.browser = "IE"
        leftover = browVer.substring( "Microsoft Internet Explorer".length + 1, browVer.length );
	}
	else if( operaFix || browVer.substring( 0, "Opera".length ) == "Opera" )
	{
		this.browser = "Opera";
		if( operaFix )
			leftover = browVer.substring( "MSIE".length + 1, browVer.length );
		else
			leftover = browVer.substring( "Opera".length + 1, browVer.length );
	}

	leftover = Trim(leftover);

	// Try to get version info out of leftover stuff
	i = leftover.indexOf( " " );
	if( i >= 0 ) 
		this.version = leftover.substring( 0, i );
	else
		this.version = leftover;
	
	j = this.version.indexOf( "." );
	if( j >= 0 ) 
	{
		this.majorver = this.version.substring( 0,j );
		this.minorver = this.version.substring( j + 1, this.version.length );
	}
	else 
		this.majorver = this.version;	
}

/*********************************************************************************/
/* OPEN WINDOW FUNCTIONS */
/*********************************************************************************/

function PromotionPopup() {
	OpenWindow('/promotion_pages/current_promotions.aspx', 'promotion', '586', '244', 'no');
	return true;
}

function PerSessionPopup(url, name, width, height, props) {
	OpenWindow(url, name, width, height, props);
	return true;
}

function OpenDetailsWindow (sUrl) {	
	OpenWindow(sUrl, 'Details', 635, 490, 'yes');
}

function OpenPerformanceAnalyzerWindow (sUrl, bSubmit) 
{
	if (!bSubmit)
		alert (sUrl);

	OpenWindow (sUrl, 'MadOnionWindow', 594, 505, 'yes');
	if (bSubmit) 
	{
		var SystemSelectionObj = GetObjRef(document.PageControlForm, ":SystemSelection");				
		SystemSelectionObj.value = GetSystemSelection();		 		
		document.forms[0].submit ();
	}	
}

function OpenPreliminaryShippingWindow (sUrl, bSubmit) {
	OpenWindow (sUrl, 'PreliminaryShipping', 594, 505, 'yes');
	if (bSubmit) {
		var SystemSelectionObj = GetObjRef (document.PageControlForm, ":SystemSelection");				
		SystemSelectionObj.value = GetSystemSelection();		 
		document.forms[0].submit ();
	}	
}

function OpenWindow(sUrl, sWinName, dWidth, dHeight, bShowScroll, winResize)
{   	   
   var winl = (screen.width - dWidth) / 2;
   var wint = (screen.height - dHeight) / 2;
   var winprops = 'height=' + dHeight + ',width=' + dWidth + ',top=' + wint + ',left=' + winl + ',scrollbars=' + bShowScroll + ', resizable=' + winResize;
   var win = window.open(sUrl, sWinName, winprops);   
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}


function OpenImageWindow( strImage, nWidth, nHeight )
{
	var winl = (screen.width - nWidth) / 2;
	var wint = (screen.height - nHeight) / 2;
	
	var winprops = "width=" + nWidth + ",height=" + nHeight + ",top=" + wint + ",left=" + winl + ",scrollbars=1, resizable=1";
	
	win = window.open( "", "", winprops); 
	
	win.document.write( "<html>\n<head>\n\t<title>Alienware: Enlarge Image</title>\n" );
	win.document.write( "\t<style type=\"text/css\">\n\tbody{margin:0;padding:0;overflow:hidden;}\n\t</style>\n</head>\n<body>\n" );
	win.document.write( "\t<div align=\"center\">\n\t\t" );
	win.document.write( "<img src=\"" + strImage +  "\" id=\"image\" />\n" );
	win.document.write( "\t</div>\n</body>\n</html> ");
}

function Round (dPrice, nDecimal)
{	
	var dPowerOfTen = Math.pow(10, nDecimal);

	var dTempPrice = dPrice * dPowerOfTen;
	var dRoundedPrice = Math.floor (dTempPrice);
	var dFloorRemainder = dTempPrice - dRoundedPrice;

	if (dFloorRemainder > 0.5 || (dFloorRemainder == 0.5 && dRoundedPrice % 2 != 0))
		dRoundedPrice += 1;
	
	return dRoundedPrice / dPowerOfTen;
}

function RoundPrice (dPrice, nDecimal)
{		
	dPrice = Round (dPrice, nDecimal);
	var sDig = "000000000";
	var sTempValue = dPrice.toString();	
	if (nDecimal > 0) {
		var nPos = sTempValue.indexOf(".");
		if (nPos == -1) {
			sTempValue += ".";
			nPos = sTempValue.length - 1;
		}		
		var nDec = sTempValue.length - nPos - 1;	
		sTempValue += sDig.substr(0, nDecimal - nDec);
	}					
	return sTempValue;	
}

function FormatCurrency (nValue, sCurrencyFormat)
{	
	var sTempValue = RoundPrice (Math.abs (nValue), 2);	
	var sRemainder = "";
	if (sTempValue.match (/\./) != null) {
		sRemainder = sTempValue.replace (/^.*\./, '');
		sTempValue = sTempValue.replace (/\..*$/, '');
	}		

	var sThousands = "";	
	if (sTempValue.length > 3)
		sThousands = sTempValue.replace (/^(\d+)(\d\d\d)$/, '$1');		
	var sHundreds = sTempValue.substr (sThousands.length, sTempValue.length);		
	if (!sThousands.length)
		sCurrencyFormat = sCurrencyFormat.replace (/XXX.*YYY/, "YYY");
				
	sCurrencyFormat = sCurrencyFormat.replace (/XXX/, sThousands);			
	sCurrencyFormat = sCurrencyFormat.replace (/YYY/, sHundreds);			
	sCurrencyFormat = sCurrencyFormat.replace (/ZZ/,  sRemainder);
	
	if (nValue < 0)
		sCurrencyFormat = "-" + sCurrencyFormat;		
	return sCurrencyFormat;			
}

function GetObjRef(form, objname) 
{
	var objref = null;	
	for (i=0; i < form.elements.length; i++) {
		if (form.elements[i].name.indexOf(objname) != -1) {
			objref = form.elements[i];
			break;
		}		
	}
	return objref;
}

function GetDocumentObject (sId) 
{       
	var obj = null;
        
    if (document.getElementById)
    	obj = document.getElementById (sId);	     
	else if (document.all)
		obj = document.all[sId];
	
	return obj;	
}

function CalculateFinancePrice (dPrice, dAPR, nMonths, dFinancingMinimumMonthlyPayment) 
{
	return Math.max (Math.ceil (dPrice * 3 / 100), dFinancingMinimumMonthlyPayment).toString ();

    //var nMonthlyAmount = Math.round (dPrice * ((dAPR / 1200) / (1 - (1 / (Math.pow (1 + (dAPR / 1200), nMonths))))));                          	        
    //nMonthlyAmount = Math.max (nMonthlyAmount, nMinValue);
    //return nMonthlyAmount.toString();    
}

function SetLayerText (sLayerId, sText) 
{       		
	sText = sText.replace (/\n/g, "<BR>");
	sText = sText.replace (/\'/g, "\\\'");
			
    var sStatement;
    if (document.all) 
	  sStatement = "document.all['" + sLayerId + "'].innerHTML = '" + sText + "';";	     
    else if (document.getElementById)           
	  sStatement = "document.getElementById('" + sLayerId + "').innerHTML = '" + sText + "';";              
                        
	try {	    
	    eval (sStatement); 	    	   
	    //alert ("Success [" + sLayerId + ", " + sText + "]"); 
	} catch (e) {
	    //alert ("Error [" + sLayerId + ", " + sText + "]" + e.message);		
	}
}

/*********************************************************************************/
/* NETSCAPE FIX RESIZE BUG NS4 */
/*********************************************************************************/
function WM_netscapeCssFix() {
  if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
        document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
     document.location = document.location;
    }
}

function WM_netscapeCssFixCheckIn() {
  if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion) == 4)) {
    if (typeof document.WM == 'undefined'){
       document.WM = new Object;
       }
    if (typeof document.WM.WM_scaleFont == 'undefined') {
       document.WM.WM_netscapeCssFix = new Object;
       document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
       document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
       }
    window.onresize = WM_netscapeCssFix;
  }
}

WM_netscapeCssFixCheckIn();


/*********************************************************************************/
/* COOKIE CODE */
/*********************************************************************************/
function setCookie(szName, szValue, szExpires, szPath, szDomain, bSecure)
{
 	var szCookieText = 	   escape(szName) + '=' + escape(szValue);
	szCookieText +=	 	   (szExpires ? '; EXPIRES=' + szExpires.toGMTString() : '');
	szCookieText += 	   (szPath ? '; PATH=' + szPath : '');
	szCookieText += 	   (szDomain ? '; DOMAIN=' + szDomain : '');
	if (bSecure || GetProtocol() == "https:")
	    szCookieText += '; SECURE';
	
	document.cookie = szCookieText;
}



function getCookie(szName)
{
 	var szValue =	  null;
	if(document.cookie)	   //only if exists
	{
       	var arr = 		  document.cookie.split((escape(szName) + '=')); 
       	if(2 <= arr.length)
       	{
           	var arr2 = 	   arr[1].split(';');
       		szValue  = 	   unescape(arr2[0]);
       	}
	}
	return szValue;
}

function deleteCookie(szName)
{
 	var tmp = 	  			 	 getCookie(szName);
	if(tmp) 
	{ setCookie(szName,tmp,(new Date(1))); }
}

function stopError() {return true;}
window.onerror=stopError;
/*********************************************************************************/


/*********************************************************************************/
/* RETAILER UTILS */
/*********************************************************************************/
var CONST_COOKIE_RETAILER = "29EA853E-2460-4AB8-B778-9F6364848082";

/*try
{
	if (getCookie(CONST_COOKIE_RETAILER))
		window.attachEvent("onload", disableNavigation);
}
catch(e)
{}*/

function disableOnClick()
{
	alert("External links aren't available at this time");
	window.event.returnValue = false;
}

function disableContextMenu()
{
	window.event.returnValue = false;
}

function disableNavigation()
{
	for(i = 0; i < document.links.length; i++)
	{
		var link = document.links[i];
		if( link.href.indexOf("alienware.com") == -1 && 
			link.href.indexOf("javascript:") == -1)
		{
			link.onclick = disableOnClick;
			link.oncontextmenu = disableContextMenu;
		}
	}
}

/*********************************************************************************/
	
/*********************************************************************************/
/* SURVEY UTILS */
/*********************************************************************************/
var CONST_MIN_AVAIL_X = -10004;
var CONST_MIN_AVAIL_Y = -10097;
var CONST_MAX_XRES = 3200;
var CONST_MAX_YRES = 1536;
var CONST_URL_ROUT = "/Routing/Surveys.aspx";
var CONST_COOKIE_WSTACK = "FA7A10BC-601F-450B-8959-C7FE62BD08F7";
var CONST_COOKIE_SURVEY = "EBF8B46B-6E82-4F85-A34F-D29C8E6CCF9B";

var wstackExp;

try
{
	if (getCookie(CONST_COOKIE_SURVEY))
	{
		window.attachEvent("onload", __OnLoad_Survey);
		window.attachEvent("onunload", __OnUnload_Survey);

		wstackExp = new Date();
		wstackExp.setHours(wstackExp.getHours() + 1);
	}
}
catch(e)
{}

function __OnLoad_Survey()
{
	var cv = getCookie(CONST_COOKIE_WSTACK);
	setCookie(CONST_COOKIE_WSTACK, (cv ? parseInt(cv) + 1 : 1), wstackExp, "/", null, false);
}

function __OnUnload_Survey()
{
	var cv = parseInt(getCookie(CONST_COOKIE_WSTACK)) - 1;
	setCookie(CONST_COOKIE_WSTACK, cv, wstackExp, "/", null, false);

	if (cv == 0)
		if ((event.clientX < (CONST_MIN_AVAIL_X + CONST_MAX_XRES)) && (event.clientY < (CONST_MIN_AVAIL_Y + CONST_MAX_YRES)))
			if (!getCookie(CONST_COOKIE_SURVEY + getCookie(CONST_COOKIE_SURVEY)))
			{
				deleteCookie(CONST_COOKIE_WSTACK);
				if (getCookie(CONST_COOKIE_SURVEY) != "ChannelOTHR")
				{
					InvokeSurveyRouter();
				}
			}
}

function InvokeSurveyRouter()
{
	var wn = null;
	var wf = "status=yes,scrollbars=yes,location=no,menubar=no,toolbar=no,resizable=yes";
	window.open(CONST_URL_ROUT, wn, wf, false);
}
/*********************************************************************************/

//////////////////////////////////////////////////////////////////////////////////////
//  Utility function to trim spaces from both ends of a string
function Trim(inString) 
{
	var retVal = "";
	var start = 0;
	
	while( (start < inString.length) && (inString.charAt(start) == ' ') ) 
		++start;
	
	var end = inString.length;
	
	while( (end > 0) && (inString.charAt(end - 1) == ' ') ) 
		--end;
	
	retVal = inString.substring( start, end );
	return retVal;
}

commonIncluded = true;

/*********************************************************************************/
function getCookie(name) {
	var result = null;
	var myCookie = " " + document.cookie + ";";
	var searchName = " " + name + "=";
	var startOfCookie = myCookie.indexOf(searchName);
	var endOfCookie;
	if( startOfCookie != -1 ) {
		startOfCookie += searchName.length; // skip past cookie name
		endOfCookie = myCookie.indexOf(";", startOfCookie);
		result = unescape(myCookie.substring(startOfCookie, endOfCookie));
	}
	return result;
}


/*********************************************************************************/
function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*********************************************************************************/
function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*********************************************************************************/
function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

function validVal(event, keyRE) {
    if ( String.fromCharCode(((navigator.appVersion.indexOf('MSIE') != (-1)) ? event.keyCode : event.charCode)).search(keyRE) != (-1)
        || ( navigator.appVersion.indexOf('MSIE') == (-1)
	        && ( event.keyCode.toString().search(/^(8|9|13|45|46|35|36|37|39)$/) != (-1)
		        || event.ctrlKey || event.metaKey ) ) ) {
        return true;
    } else {
        return false;
    }
}

function SetLanguageCookieAndRedirect (cookieName, cookieValue, cookieDomain, target)
{
    var date = new Date ();
    date = new Date (date.getFullYear () + 1, date.getMonth (), date.getDate ());

    setCookie (cookieName, cookieValue, date, '/', cookieDomain, false);
    window.location = target;
}