/*********************************************************
Global JS file for GEAppliances.com (as of 08/09 redesign)
*********************************************************/


// fixes IE6 background image flicker bug
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

// global vars
var popupWin;
var scrnwidth=screen.width;
var scrnheight=screen.height;


// define Base_Href variable for testing purposes
var exceptions = new Array();
	var i = 0;
	exceptions[i++] = "postsaleservice";
	exceptions[i++] = "consumerspot";
	exceptions[i++] = "aftermind";
	exceptions[i++] = "geapplianceparts";
	exceptions[i++] = "genet2";
	exceptions[i++] = "genet";
	exceptions[i++] = "millstone";
	exceptions[i++] = "products";
	exceptions[i++] = "monogram";
	exceptions[i++] = "ap1lnx";
	exceptions[i++] = "answers";
	exceptions[i++] = "prodcontent";

var Base_Href = window.location.protocol +"//www.geappliances.com";
var UnSecure_Base_Href = "http://www.geappliances.com";
if (window.location.host.indexOf('team') != -1)
{
	var Base_Href = window.location.protocol +"//"+ window.location.host;
	var UnSecure_Base_Href = "http://"+ window.location.host;
	for (count = 0; count < exceptions.length; count++)
	{
		if (window.location.host.indexOf(exceptions[count]) != -1)
		{
			var Base_Href = window.location.protocol +"//www.geappliances.com";
			var UnSecure_Base_Href = "http://www.geappliances.com";
		}//Close if
	}//Close for
}//Close if




// "only 1 open at a time" popup function.
//-----------------------------------------------------------------------------
// The fifth argument, windowname, is optional.  If specified, it is passed as
// the second argument to window.open().  This is required in order to leave
// the popup opener page (without closing the popup), come back to it, and NOT
// have a duplicate popup window.
//-----------------------------------------------------------------------------
function openPop (url, width, height, addloptions, windowname) {
	if (windowname == null) {
		windowname = "";
	}
	var xspot = Math.round((scrnwidth/2)-(width/2));
	var yspot = Math.round((scrnheight/2)-(height/2)-30);
	features = "height="+height+",width="+width+",top="+yspot+",screenY="+yspot+",left="+xspot+",screenX="+xspot;
	if (addloptions && addloptions!="") { features += ","+addloptions; }
	if (!popupWin || popupWin.closed) {
		popupWin = window.open(url, windowname, features);
	}
	else {
		window.popupWin.close();
		popupWin = window.open(url, windowname, features);
	}
}


/*
Function to encode special characters, as well as anything that's not
printable ASCII, as HTML entities for safe inclusion in generated HTML.
	
Usage example:

	document.write('<a href="' + encodeEntities(url) + '">moo</a>\n');
*/
function encodeEntities (s) {
	s = s.replace(/&/g, "&amp;");
	s = s.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	s = s.replace(/\x22/g, "&quot;"); /* double quotation mark */
	s = s.replace(/\x27/g, "&#39;"); /* ASCII apostrophe -
		&apos; is not universal yet */
	s = s.replace(/[^\x20-\x7e]/g,
		function (ch) {
			return "&#" + ch.charCodeAt(0) + ";";
		}
	); /* escape anything other than ASCII printable */
	return s;
}

/*
based on openLarger() from http://www.gelighting.com/na/scripts/global.js

Usage example --- onclick event (also applies for href="javascript:..."):

	<a target="_blank" href="images/foo.jpg"
		onclick="openNakedImagePopup('images/foo.jpg', 640, 480, 'GE Profile(TM) Washers and Dryers'); return false;">
			view larger photo
	</a>

	Got &, <, >, ', ", or other special characters?

	<a target="_blank" href="images/foo.jpg?foo=1&amp;bar=2"
		onclick="openNakedImagePopup('images/foo.jpg?foo=1&amp;bar=2', 640, 480, 'GE Profile&trade; Washers &amp; Dryers'); return false;">
			view larger photo
	</a>

	REMEMBER:
	While this function runs encodeEntities on the imageURL and altText,
	you still need to escape <, >, &, ', and " characters in onclick events
	or any other HTML attribute value (the browser unescapes them, then
	openNakedImagePopup re-escapes them).
	While most browsers are lenient, XHTML validation tools will issue
	warnings or error messages if you do not do this.

Usage example --- <script> element (also applies for .js files):

	<script type="text/javascript">
		function openPopup () {
			openNakedImagePopup('images/foo.jpg', 640, 480, 'GE Profile(TM) Washers and Dryers');
			// Got special characters?
			openNakedImagePopup('images/foo.jpg?foo=1&bar=2', 640, 480, 'GE Profile\u2122 Washers & Dryers'); // [1] one way
			openNakedImagePopup('images/foo.jpg?foo=1&bar=2', 640, 480, 'GE Profile&trade; Washers &amp; Dryers', true); // [2] another way
			// notice lack of entity escaping here --^ in the URLs.
			// you don't need to entity-escape the URLs in <script>
			// elements or .js files.
		}
	</script>
	<a target="_blank" href="images/foo.jpg" onclick="openPopup(); return false;">
		view larger photo
	</a>

	Got &, <, >, ', ", or other special characters?

	REMEMBER:
	Since browsers do NOT unescape entities in <script> elements like they
	do in HTML attribute values, you do NOT need to do HTML entity escaping
	here.  \ escaping still applies.  See [1] above.

	If you don't like looking up Unicode hex values, you can use HTML
	entity escaping instead.  However, within <script> elements and .js
	files, you MUST pass an optional fifth argument of true.  In other
	contexts, such as onclick attributes and javascript: hrefs, you
	MUST NOT pass the optional fifth argument.  (The browser unescapes
	entities in onclick/href attributes, but not in script elements or
	.js files; the optional fifth argument tells openNakedImagePopup
	to *not* perform entity-escaping on the alt text.)
	
*/

var nakedImagePopupWindow;
function openNakedImagePopup(imageURL, width, height, altText, isEscaped) {
	var screenX = Math.round((screen.width - width) / 2);
	var screenY = Math.round((screen.height - height - 60) / 2); /* assume 60px for titlebar, toolbars, other vertical real-estate */
	var features = ( /* parenthesis for multiline expression */
		"width=" + width
		+ ",height=" + height
		+ ",screenX=" + screenX + ",screenY=" + screenY /* Netscape */
		+ ",left=" + screenX + ",top=" + screenY /* IE */
	);
	if (nakedImagePopupWindow && !(nakedImagePopupWindow.closed)) {
		nakedImagePopupWindow.close();
	}
	nakedImagePopupWindow = window.open(null, null, features);
	if (altText != null && !isEscaped) {
		altText = encodeEntities(altText);
	}
	var html = ( /* parenthesis for multiline expression */
		'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n'
		+ '<html>\n'
		+ '<head>\n'
		+ '<title>'
		+ ((altText != null) ? altText : 'Photo')
		+ '</title>\n'
		+ '<style type="text/css">\n'
		+ 'html, body { margin: 0; padding: 0; background-color: white; color: black; }\n'
		+ '</style>\n'
		+ '</head>\n'
		+ '<body>\n'
		+ '<img src="' + encodeEntities(imageURL) + '"\n'
		+ ' width="' + width + '"'
		+ ' height="' + height + '"'
		+ ((altText != null) ? (' alt="' + altText + '"') : "")
		+ ' border="0"'
		+ ' />\n'
		+ '</body>\n'
		+ '</html>\n'
	);
	nakedImagePopupWindow.document.open();
	nakedImagePopupWindow.document.write(html);
	nakedImagePopupWindow.document.close();
}


function closepopups(){
	if (popupWin && popupWin.open){
		window.popupWin.close();
	}
}

// Function to open FAQ popups
// Uses the 'openPop' function
function callOpenPop(faqFileName){
	urlFaq="/search/fast/infobase/"+faqFileName;
	openPop(urlFaq,'575','480','scrollbars,resizable,toolbar');
}

// Function to open video gallery
// Uses the 'openPop' function
function openVideoGalleryPopup(url) {
	openPop(url, 780, 620, 'scrollbars,resizable');
}

// Function to open Email-A-Friend -- ClickQuared version 
// Uses the 'openPop' function
function openEmailafriendPopup(url) {
	encurl= encodeURIComponent(url);
	openPop("http://forms.geconsumerandindustrial.com/asbs/servlet/SS?F=3123803&C=21036959&product="+encurl, 600, 630, 'scrollbars,resizable');
}


/* clears default value of text input on focus */
function textInputFocusClear(obj) {
	if(obj.value == obj.defaultValue) {
		obj.value = "";
	}
}
/* resets default value on blur if no text is entered */
function textInputBlurReset(obj) {
	if(obj.value == "") {
		obj.value = obj.defaultValue;
	}
}



//get url parameter value by name
function getParamFromURL(paramName)
{
  var regexS = "[\\?&'&amp;']"+ paramName +"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}
// Function to get a value from URL
function getValueFromURL(paramName)
{
  var regexS = "[\\?&'&amp;']"+ paramName +"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}




/***********************************************************
The "topNavSelector" function sets a selected item in the
top nav for the current page (based on the page URL and the
left nav link's HREF).

For pages that exist outside the major categories defined in
the top nav, the default behavior will be to set the home
button as selected. To force an item in the top nav to be 
set as selected, the corresponding A tag must be assigned a unique
ID in the top nav include file. Then you must pass that ID 
into the "topNavSelector" function.

This function should be run in the page immediately 
following the top nav include call.
***********************************************************/
function topNavSelector(optionalID) {
try {
	pageURL = document.location.href;
	// test for Teamsite URL
	workareaCheck = pageURL.indexOf("WORKAREA/");

	// determine URL path (testing for Teamsite, as well)
	if(workareaCheck != -1) {
		pagePath = pageURL.split("WORKAREA/")[1];
		pagePath = pagePath.substr(pagePath.indexOf("/"));
	} else {
		pagePath = location.pathname;
	}
	
	if(!optionalID || !document.getElementById(optionalID)) {
	
		var navArray = document.getElementById("topNav").getElementsByTagName("a");
		// cycle through nav items looking for one with HREF that matches the beginnging of the page URL
		for(i=1;i<navArray.length;i++) {
			
			var testHref = navArray[i].pathname;
			if(testHref.indexOf("/") != 0) { testHref = "/" + testHref; } // IE doesn't include beginning slash
			
			
			if(pagePath.indexOf(testHref) == 0 && navArray[i].parentNode.tagName != "LI") {
				navArray[i].className += " selected";
				break;
			}// if
		} // for
		
	} else {
		
		document.getElementById(optionalID).className += " selected";
		
	} // else
	
} catch(err) {} // try-catch
} // function





/* This function alternates the background color of table rows between 
	white and gray by placing a class of "odd" on every other row. 
	This function applies to tables that contain a class of 'graybarTable'.*/
function alternateOddRowsInGraybarTables () {
	/* sanity check */
	if (!document.getElementsByTagName) {
		return;
	}

	var tables = document.getElementsByTagName("table");
	for (var i = 0; i < tables.length; ++i) {
		var table = tables[i];
		if (!table.className || !/\bgraybarTable\b/.test(table.className)) {
			continue;
		}

		var els = table.getElementsByTagName("tbody");
		if (!els || !els.length) continue;
		var tbody = els[0];

		var rows = tbody.getElementsByTagName("tr");
		if (!rows || !rows.length) continue;
		for (var j = 0; j < rows.length; j += 2) {
		rows[j].className = rows[j].className + " odd";
		}
	}
}





// Function for search.
function fnMastheadSearch(fm) {
	fld = fm.SEARCHTEXT;
	val = fld.value;
	//extra validation if wanting use & care manuals
	if (fm.selSearchCategory.selectedIndex==3) {
		if (val=="") { alert("Please enter model number."); fld.focus(); return false; }
		if (val.length<3) { alert("Please enter at least 3 characters."); fld.select(); return false; }
	}
	//begin "regular" validation...
	if (val=="") { alert("Please enter search term(s)"); fld.focus(); return false; }
	//default to products search if no option selected
	if (fm.selSearchCategory.selectedIndex==0) {
		fm.selSearchCategory.selectedIndex=1;
	}
	//handle the 3 possibilities
	if (fm.selSearchCategory.selectedIndex==1) {  //products
		fm.action = "http://genet.geappliances.com/geasearch/Dispatcher?REQUEST=GETSEARCHRESULT";
		fm.SITEID.value="GEAPPLIANCES";
	}
	if (fm.selSearchCategory.selectedIndex==2) {  //service and support
		fm.action = "http://genet.geappliances.com/geasearch/Dispatcher?REQUEST=GETSEARCHRESULT";
		fm.SITEID.value="GEACAPPL";
	}
	if (fm.selSearchCategory.selectedIndex==3) {  //use & care manuals
		fm.action = "http://genet.geappliances.com/DocSearch/Dispatcher?REQUEST=SEARCHWITHURLCONNECTION";
		fm.SITEID.value="GEA";
		fm.SKU.value=val;
	}
	return true; //submits the form
}


// Function for language link.
function switchLanguage() {
	oh=new Array();tsd=new Array();
	tsh='espanol.geappliances.com';
	oh[0]='shop.homeappliances.com';tsd[0]='/enes/sdshop/dhomeappliances/';
	oh[1]='products.geappliances.com';tsd[1]='/enes/sdproducts/'; 
	oh[2]='customernet.geappliances.com';tsd[2]='/enes/sdcustomernet/';
	oh[3]='genet.geappliances.com';tsd[3]='/enes/sdgenet/';
	oh[4]='www.geappliances.com';tsd[4]='/enes/';
	idx=window.top.location.href.indexOf(tsh);
	if(idx==-1){
		for (i=0;i<oh.length;i++){ 
			idx=window.top.location.href.indexOf(oh[i]);
			if(idx>-1) break;
		}
		idx=idx+oh[i].length;hname=tsh+tsd[i];
	}else{
		for (i=0;i<tsd.length;i++){ 
			idx=window.top.location.href.indexOf(tsd[i]);
			if(idx>-1) break;
		}
		idx=idx+tsd[i].length;hname=oh[i];
	}
	path=window.top.location.href.substring(idx);
	hend=hname.charAt(hname.length-1);pstart=path.charAt(0);
	if(hend=='/' && pstart=='/')path=path.substring(path.indexOf('/')+1);
	if(hend!='/' && pstart!='/')path='/'+path;
	window.top.location.href = window.top.location.protocol+'//'+hname+path;
	return false;
}


// Knowledge Base search 
function validGEACSearch(fm) {
	if(fm.SEARCHTEXT.value=="") {
		alert("Please enter a search term or model number."); fm.SEARCHTEXT.focus(); return false;
	}
	return true;
}




/*************************** COMPARE PAGE FUNCTIONS ***************************/
// init var that means that the "only show differences" option is currently off
var differencesToggled = false;

/* This function expands and contracts the "product details" sections on COMPARE pages */
function compareProductDetailsToggle(obj) {
	
	var thisRow = obj;
	while(thisRow.tagName != "TR")	{
		thisRow = thisRow.parentNode;
	}// while
	
	var rowGroupArray = new Array();
	for(i=thisRow.rowIndex+1; i<document.getElementById("compareTable").rows.length; i++ ) {
		if( document.getElementById("compareTable").rows[i].className != "subHeadingRow" && document.getElementById("compareTable").rows[i].className != "productInfoRow" ) {
			if(document.getElementById("compareTable").rows[i].className == "differenceRow" || differencesToggled != true) {
				rowGroupArray.push(document.getElementById("compareTable").rows[i]);
			}
		} else {
			break;
		}
	}
	
	var linkSpansArray = thisRow.getElementsByTagName("span");
		
	if(rowGroupArray[0].style.display != "none") {
		
		for(i=0; i<rowGroupArray.length; i++) {
			rowGroupArray[i].style.display = "none";
		}
		for( i=0; i< linkSpansArray.length; i++ ) {
			if( linkSpansArray[i].className == "showHide" ) { linkSpansArray[i].innerHTML = "show"; }
			if( linkSpansArray[i].className == "plusMinus" ) { linkSpansArray[i].innerHTML = "+"; }
		}
		thisRow.cells[0].style.borderBottomWidth = "0";
		
	} else {
		
		for(i=0; i<rowGroupArray.length; i++) {
			rowGroupArray[i].style.display = "";
		}
		
		for( i=0; i< linkSpansArray.length; i++ ) {
			if( linkSpansArray[i].className == "showHide" ) { linkSpansArray[i].innerHTML = "hide"; }
			if( linkSpansArray[i].className == "plusMinus" ) { linkSpansArray[i].innerHTML = "-"; }
		}
		thisRow.cells[0].style.borderBottomWidth = "1px";
		
	}
}


/* This function toggles between showing all points of comparison or just the ones with differences on COMPARE pages */
function compareDifferencesToggle(obj) {
	var rowsArray = document.getElementById("compareTable").getElementsByTagName("tbody")[0].rows;
	var showHeading = false; /* init value */
	var differencesBox = document.getElementById("differencesBox");
	
	if(differencesToggled != true) {
	
		for(i=rowsArray.length-1; i>=0; i--) {
			rowsArray[i].style.display = "none";
			if( rowsArray[i].className == "differenceRow" ) {
				rowsArray[i].style.display = "";
				showHeading = true;
			}
			if( rowsArray[i].className == "subHeadingRow" && showHeading == true ) {
				var linkSpansArray = rowsArray[i].getElementsByTagName("span");
				for( j=0; j< linkSpansArray.length; j++ ) {
					if( linkSpansArray[j].className == "showHide" ) { linkSpansArray[j].innerHTML = "hide"; }
					if( linkSpansArray[j].className == "plusMinus" ) { linkSpansArray[j].innerHTML = "-"; }
				}
				
				rowsArray[i].style.display = "";
				showHeading = false;
			}
		}
		
		differencesBox.getElementsByTagName("span")[0].innerHTML = "Show All Features";
		differencesBox.getElementsByTagName("a")[0].innerHTML = "Show all features for these products.";
		
		differencesToggled = true;
	
	} else {
		
		for(i=0; i<rowsArray.length; i++) {
			rowsArray[i].style.display = "";
		
			var linkSpansArray = rowsArray[i].getElementsByTagName("span");
			for( j=0; j< linkSpansArray.length; j++ ) {
				if( linkSpansArray[j].className == "showHide" ) { linkSpansArray[j].innerHTML = "hide"; }
				if( linkSpansArray[j].className == "plusMinus" ) { linkSpansArray[j].innerHTML = "-"; }
			}
		}
		
		differencesBox.getElementsByTagName("span")[0].innerHTML = "Show Me the Differences";
		differencesBox.getElementsByTagName("a")[0].innerHTML = "Only show features that are different between models.";
		
		differencesToggled = false;
	}
}

/*************************** END COMPARE PAGE FUNCTIONS ***************************/




/*************************** SPEC PAGE FUNCTIONS ***************************/

/* This function expands and contracts the "product details" sections on SPEC pages */
function specProductDetailsToggle(obj) {
	var productDetailsTableWrapper = obj.parentNode.parentNode.getElementsByTagName("table")[0].parentNode;
	
	var linkSpansArray = obj.parentNode.getElementsByTagName("span");
		
	if(productDetailsTableWrapper.style.display != "none") {
		
		productDetailsTableWrapper.style.display = "none";
		
		for( i=0; i< linkSpansArray.length; i++ ) {
			if( linkSpansArray[i].className == "showHide" ) { linkSpansArray[i].innerHTML = "show"; }
			if( linkSpansArray[i].className == "plusMinus" ) { linkSpansArray[i].innerHTML = "+"; }
		}
		
	} else {
		
		productDetailsTableWrapper.style.display = "block";
		
		for( i=0; i< linkSpansArray.length; i++ ) {
			if( linkSpansArray[i].className == "showHide" ) { linkSpansArray[i].innerHTML = "hide"; }
			if( linkSpansArray[i].className == "plusMinus" ) { linkSpansArray[i].innerHTML = "-"; }
		}
		
	}
}




// number of current product image on spec pages (defaulted to first image)
var currentSpecImage = 0;

/* this functions sets the selected thumbnail and populates the larger image  */
function setMainImage(num) {
	
	// check the limits
	if( num < 0 ) { num = productImagesArray.length -1 }
	if( num >= productImagesArray.length ) { num = 0; }
	
	// set selected thumbnail
	document.getElementById("productThumbnail"+currentSpecImage ).childNodes[0].className = "";
	document.getElementById("productThumbnail"+num ).childNodes[0].className = "doubleBorder";
	
	// write main image
	mainImageSrc = productImagesArray[num][1];
	if(!productImagesArray[num][2]) {
		anchorContents = "";
		document.getElementById("magnifyInstructions").style.visibility = "hidden";
	}else {
		anchorContents = " class=\"MagicMagnify\" rel=\"zoom-color: #cccccc; size: 180px; type: square\" href=\"" + productImagesArray[num][2] + "\"";
		document.getElementById("magnifyInstructions").style.visibility = "visible";
	}
	document.getElementById("imageCell").innerHTML = "<a" + anchorContents + "><img id=\"mainImage\" src=\"" + mainImageSrc + "\" width=\"480\" height=\"500\" alt=\"\" title=\"\" /></a>";
	
	currentSpecImage = num;
}


/* this function populates the thumbnails and larger image on spec pages */
function populateProductImages() {
	// hide arrows and thumbs if only one image is available
	if(productImagesArray.length == 1) {
		document.getElementById("thumbnailsViewer").style.display = "none";
		leftRightButtonLinks = document.getElementById("mainImageViewer").getElementsByTagName("a");
		leftRightButtonLinks[0].style.visibility = "hidden";
		leftRightButtonLinks[1].style.visibility = "hidden";
	}
	
	// populate the thumbnails
	for(i=0; i<productImagesArray.length; i++) {
		document.getElementById("thumbnailsViewer").innerHTML += "<a id=\"productThumbnail" + i + "\" href=\"javascript:setMainImage(" + i + "); MagicMagnify_findMagnifiers();\"><img src=\"" + productImagesArray[i][0] + "\" width=\"60\" height=\"63\" alt=\"View larger\" title=\"View larger\" /></a> ";
	}
	
	// set the first thumbnail as selected and populate the larger images
	setMainImage(currentSpecImage);
}
/*************************** END SPEC PAGE FUNCTIONS ***************************/




/******************* FOOTER FUNCTIONS *******************/

function validateNewsletterSubscriptionForm (form) {
	if (!form.Email) {
		return true;
	}
	if(!(/^\w+((-\w+)|(\.\w+)|(\+\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9][A-Za-z0-9]+$/.test(form.Email.value))) {
		alert("This does not appear to be a valid e-mail address.  Please try again.");
		form.Email.select();
		return false;
	}
	return true;
}

function openPrivacyPolicyPopup (url) {
	return openPop(url, 640, 500, "scrollbars,resizable",
		       "GEAPrivacyPolicy");
}

function openTermsPopup (url) {
	return openPop(url, 640, 500, "scrollbars,resizable",
		       "GEATerms");
}

/***************** END FOOTER FUNCTIONS *****************/




