/* ********************************************************
globals.js

Only place common scripts used in most or all pages in this file.
******************************************************** */

/*
 *  Set all glodal vars before anything else.
 */
 
	var focused = new Array();
	var fm = self.document.forms;
	var CurrentObj = null;
	var CurrentForm = null;


/* *************************
   Rollover Scripts
************************** */
		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 for setting visibility attribute in layers */
	function showHideLayers() {
	  var i,p,v,obj,args=showHideLayers.arguments;if(document.getElementById){
	   for (i=0; i<(args.length-2); i+=3){ obj=ns6_findObj(args[i]);v=args[i+2];
	   v=(v=='show')?'visible':(v='hide')?'hidden':v;
	   if(obj)obj.style.visibility=v;}} else{
	  for (i=0; i<(args.length-2); i+=3) if ((obj=findObj(args[i]))!=null) { v=args[i+2];
	    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
	    obj.visibility=v; }}
	}
	
	
		
	/* Closes popup window - invoked when an Action button as closepopup=true
	 * Delay the close for browsers like Netscape to allow for page submission
	 */
	function closePopupWindow( w )
	{ 
		w.setTimeout("close()",100); 
	}
		
		
	/* Used to create a pop-up window */
	function popUpWindow( filename , title , windowHeight , windowWidth , scroll, options) {
	  var ScrollBar = 0;
	  if (scroll == "yes" || scroll == "Yes")
	    ScrollBar = 1;
	  var features = "top=20,left=20,alwaysRaised=1,resizable=yes,scrollbars=" + ScrollBar;
	  if( windowWidth && windowWidth > 0 ) { features += ",width=" + windowWidth; }
	  else { features += ",width=550"; }
	  if( windowHeight && windowHeight > 0 ) { features += ",height=" + windowHeight; }
	  else { features += ",height=585"; }
	  var strOptions = "";
	  if ( options && options != " " ){
	    var strChopList = options.split( ",");
	    strOptions = "?";
	    for (count = 0 ; count < strChopList.length; count++ ){
	      strOptions = strOptions + "&" + strChopList[ count ];
	    }
	  }
	  if( !title ) { title = "popupWindow"; }
	  if( top.window.popupWindow && ! top.window.popupWindow.closed )
	    top.window.popupWindow.close();
	  top.window.popupWindow=window.open(filename + strOptions, title, features);
	}
	
	/* Sets the checked property of all gadgets of the same type
	 * as the passed gadget to the value of the passed gadget
	 */
	function checkAll(gadget, aForm)
	{
	  for (var i=0;i<aForm.elements.length;i++)
	  {
	    var e = aForm.elements[i];
	    if (e.tagName == gadget.tagName) 
	    {
	      if (e.type == gadget.type) 
	      { 
	      	e.checked = gadget.checked; 
	      }
	    }
	  }
	}
	
	/**
	 * Will uncheck a checked parent gadget if a child control is unchecked.
	 * The parent gadget would be the gadget that when checked, checks all
	 * of the child gadgets.
	 */
	function checkAllChildHandler(child, parent, aForm) 
	{
		if (parent && parent.checked && !child.checked) {
			parent.checked = false;
		}
	}
			

		function confirmation(loc)
		{
			var x = confirm(self.logOffText);
			if (x)			
			{ 
				// Output when OK is clicked
				location=loc;
				//alert ("??? You have logged off. ???"); 
			}	
			else
			{
					void(0);
				//alert ("??? You are still logged in ???"); 
			}
		}

		
		
	/* Global function to show mesages in the browser's status bar */
	function displayStatusMsg(msgStr) 
	{ 
		window.status=msgStr; return true; 
	}


	/*  Set the value of a selection box to the given value.  Return false if value
	 *  not found in set of options.
	 */
	function setSelect(e,value){
	  for( var i=0; i < e.length; ++i ){
	    var sText = e.options[i].text;
	    if( sText==value){
	      e.selectedIndex=i;
	      return true;
	    }
	  }
	  return false;
	}


	function setCookie(label,data,expires){
	  if( expires ) 
	  { 
	  	document.cookie = label+"="+escape(data)+";expires="+expires; 
	  }
	  else 
	  { 
	  	document.cookie = label+"="+escape(data); 
	  }
	}

	function removeCookie(label)
	{ 
		document.cookie = label+"=.;expires=Thu, 01-Jan-70 00:00:01 GMT" 
	}
	
	
	/* Encode attributes by escaping quotes using their hex value srrounded by %% chars.
	 * Note that the better solution would have been to use true XML encoding
	 * &#x27; rather than %%x27%% -.
	 */
	function encodeXMLAttribute( str ){
	  str = str.replace(/\'/g,"%%#x27%%");
	  str = str.replace(/\"/g,"%%#x22%%");
	  str = str.replace(/&/g,"%%#x38%%");
	  return str;
	}

	function decodeXMLAttribute( str ){
	  str = str.replace(/%%#x27%%/g,"'");
	  str = str.replace(/%%#x22%%/g,'"');
	  str = str.replace(/%%#x38%%/g,"&");
	  str = str.replace(/&#x27;/g,"'");
	  str = str.replace(/&#x22;/g,'"');
	  return str;
	}

	/* Establish focus on first field in form */
	function setInitFocus() {
		for(var i = 0; i < fm.length; i++) {
			var f = fm[i];
			if (!f.name ||
			   	(f.name &&
			   	 f.name != "LanguageForm" &&
			   	 f.name != "utilForm" &&
			   	 f.name != "HeaderCatalogSearchForm")
			   ) {
			   
				CurrentForm = f;
				for(var i = 0; i < f.elements.length; i++) {
					var elt = f.elements[i];
					
					if(elt.type != "hidden" &&
					   !elt.disabled &&
					   elt.id != "resultsPerPage") {
					   
						f.elements[i].focus();
						return;					
					}
				}
			}
		}
	}
	
	/* This function will submit the current form when the <enter> key is pressed. */
	function elementOnKeyPress(e) {
		if (e.keyCode == 13) {
			if (CurrentForm != null) {
				CurrentForm.submit();
			}
		}
	}
	
	function addLoadEvent(func) 
	{
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      oldonload();
	      func();
	    }
	  }
	}

	function setFormElementEvents()
	{			
		// iterate over forms
		for(var i = 0; i < fm.length; i++) {
			// iterate over the elements
			var elements = fm[i];
			var elementsLength = elements.length;
			for( var j = 0; j < elementsLength; j++ )
			{
				var elm = elements[j];
				if( elm.type !="hidden" && elm.disabled != true )
				{
					addAnEvent(elm, "blur", clearCurrentForm);
					addAnEvent(elm, "focus", setCurrentForm);
					// keypress events should not be captured by textarea elements
					if (elm.type != "textarea") {
						addAnEvent(elm, "keypress", elementOnKeyPress);
					}
				}
			}
		}
	}
	
	function addAnEvent(el, evname, func) 
	{	
     if (el.attachEvent) 
     {
        el.attachEvent("on" + evname, func);
     } 
     else if (el.addEventListener) 
     {
        el.addEventListener(evname, func, true);         
     } 
     else 
     {
        el["on" + evname] = func;
     }
	}
		
	function clearCurrentForm()
	{
		CurrentForm = null;
	}
	
	function setCurrentForm()
	{
		if (this && this.form) {
			CurrentForm = this.form;
		} else {
			CurrentForm = event.srcElement.form;
		}
	}
	
	/*
	 * Uses the utility form to set the new language ID and refresh the current page
	 * by doing a post.
	 */
	 function switchLanguage(langId) {
	 
	 	if (langId) {
		 	updateUtilFormParam("langId", langId);
		} else {
			// no langId parameter was included when the function was called
		 	var currentLangId = getUtilFormParam("langId");
		 	if (currentLangId && currentLangId != "") {
		 		if (currentLangId == "-1") {
		 			switchLanguage("-11")
		 		} else if (currentLangId == "-11") {
			 		switchLanguage("-1");
		 		} else if (currentLangId == "-12") {
			 		switchLanguage("-13")
		 		} else if (currentLangId == "-13") {
		 			switchLanguage("-12")
		 		}
		 	}
		}
		
	 	// do not set a view, not setting a view will submit to the current view
		submitUtilForm();
	 }
	
	/*
	 *  Takes a list of selected produts, and builds the request parameters from them and some
	 *  hidden fields and sends a request to the OrderItemAdd URL.
	 */
	function addSelectedToCart(form) {
		
		form.action = "AddSelectedToCart";
		form.submit();
	}
	
	/*
	 *  Takes a list of selected produts, and builds the request parameters from them and some
	 *  hidden fields and sends a request to the SavedListChoicePage URL.
	 */
	function addSelectedToList(form) {
	
		form.action = "SavedListChoicePage";
		form.submit();
	}
	
	/*
	 *  Adds/update the value of the Results per Page dropdown to the
	 *  current page's query string.
	 */
	function updateResultsPerPage(cboResultsPerPage, viewName, pageParam) {
		
		updateUtilFormParam(cboResultsPerPage.id, cboResultsPerPage.value);
		
		
		if (pageParam) {
			updateUtilFormParam(pageParam, "1");
		}
		
		
		submitUtilForm(viewName);
	}
	
	/*
	 * Changes the sort order if the same sub column was clicked again.  Otherwise,
	 * the sort column, subcolumn, and direction parameters are updated.
	 */
	function sortMultiHeaderCol(viewName,
								tableUid,
								currentSortColumn,
								newSortColumn,
								currentSortSubcolumn,
								newSortSubcolumn,
								currentSortDirection) {
		
		var href = location.href;
		var sortDirectionName = "d-" + tableUid + "-o";
		
		// determine if the same sort column is being clicked again
		if (currentSortColumn == newSortColumn && currentSortSubcolumn == newSortSubcolumn) {
			// just update the sort direction
			var newSortDirection = 1;
			if (newSortDirection == currentSortDirection) {
				newSortDirection = 2;
			}
			updateUtilFormParam(sortDirectionName, newSortDirection);
			
		} else {
			
			if (newSortColumn != currentSortColumn) {
				var sortColumnName = "d-" + tableUid + "-s";
				// replace the sort column value
				updateUtilFormParam(sortColumnName, newSortColumn);
			}
			
			if (newSortSubcolumn != currentSortSubcolumn) {
				// replace the sub column value
				updateUtilFormParam("ssub", newSortSubcolumn);
			}
			
			if (currentSortDirection != 2) {
				// first sort ascending
				updateUtilFormParam(sortDirectionName, 2);
			}
		}
		
		submitUtilForm(viewName);
	} // end sortMultiHeaderCol()
	
	/*
	 * Obtains a value given a name from the UtilForm
	 */
	function getUtilFormParam(paramName) {
		var paramValue = "";
		var utilForm = document.utilForm;
		if (utilForm[paramName]) {
			paramValue = utilForm[paramName].value;
		}
		return paramValue;
	}
	
	/*
	 * If the name of the parameter is already a hidden field on the utility form,
	 * then the value is just updated.  Otherwise, a temp hidden field is changed
	 * to reflect both the name and value of the passed arguments.
	 */
	function updateUtilFormParam(paramName, paramValue) {
		var utilForm = document.utilForm;
		if (utilForm[paramName]) {
			// the param value was in the request, so it already is a hidden field
			utilForm[paramName].value = paramValue;
		} else {
			// one of the 
			var index = 1;
			var tempParamName = "temp" + index;
			var tempParam = utilForm[tempParamName];
			var found = false;
			
			while (tempParam && !found) {
				if (tempParam.name == '') {
					// a temp hidden field was found that can be used
					tempParam.name = paramName;
					// don't change the value of the ID attribute
					tempParam.value = paramValue;
					// exit the loop
					found = true;
				} else {
					// update the conditional variables
					index++;
					tempParamName = "temp" + index;
					tempParam = utilForm[tempParamName];
				}
			} // ~while
		}
	} // ~ updateUtilFormParam()
	
	/*
	 * Sets the utility form's action and submits it.
	 */
	function submitUtilForm(viewName) {
		var utilForm = document.utilForm;
		if (viewName) {
			utilForm.action = viewName;
		}
		utilForm.submit();
	}
	
	function clearForm(form) {
		var elements = form.elements;
		for (var i = 0; i < elements.length; i++) {
			var element = elements[i];
			if (element.type == 'text') {
				element.value = '';
			} else if (element.type == 'select-one') {
				element.selectedIndex = 0;
			}
			// additional types can be added later
		}
	}
	
	/*
	 * Function removes leading and trailing whitespaces from a String.
	 */
	function trim(str) {
	
		while (str.substring(0, 1) == ' ') {
			str = str.substring(1, str.length);
		}
		
		while (str.substring(str.length-1, str.length) == ' ') {
			str = str.substring(0, str.length - 1);
		}
		
		return str;
	}
	
	/*
	 * Function replaces placeholders in the message with the given parameters.
	 * Placeholders in the message must follow the pattern {0}, {1}, {2} ... {n}
	 * Placeholders must also start at 0 and be numbered consecutively to
	 * ensure their replacement.
	 * If the message contains more placeholder then parameters that were provided,
	 * the placeholders will be replaced by the empty string.
	 */
	 function replaceMsgParams(msg, params) {
	 
	 	var hasMoreParams = true;
	 	// the replacement of params will be placeholder driven, not parameter (var params) driven
	 	for (var i = 0; hasMoreParams; i++) {
	 		// replace the parameter with the current index
	 		var replaceValue = "";
	 		if (i < params.length) {
	 			replaceValue = params[i];
	 		}
		 	msg = msg.replace("[" + i + "]", replaceValue);
		 	
	 		// see if the message has another parameter
	 		hasMoreParams = ((msg.indexOf("[" + (i + 1) + "]")) >= 0);
	 	}
	 	
	 	return msg;
	 }
	/*
	 * Function used to disable any buttons  on the form so that
	 * it cannot be clicked twice
	 *
	 */
	 function disableIt(obj)
		{
						
			var z = (obj.disabled) ? 'disabled' : 'enabled';
			// alert(obj.type + ' now ' + z);
			 obj.style.background="#C0C0C0";
			 obj.style.backgroundimage="";
			 obj.disabled = true;
			 
			 
		}
	addLoadEvent(setInitFocus);
	addLoadEvent(setFormElementEvents);
	
	/*
	 * Function used to link to other pages with a input button
	 *
	 */
	
	function MM_goToURL() { //v3.0
		  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
		  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
		}
	
	
	/*
	 *  Formats the Canadian Postal Code XXX XXX
	 */
	 function formatPostalCode(form){
	 	if(form.storeId.value == '10052'){
	 		var zip = form.zipCode.value;
	 		if(zip.length == 6){
	 			form.zipCode.value = zip.substring(0,3)+" "+zip.substring(3,6);
	 		}
	 		if(zip.length == 7 && zip.substring(3,4) == '-') {
	 			form.zipCode.value = zip.substring(0,3)+" "+zip.substring(4,7);
	 		}
	 		form.zipCode.value = form.zipCode.value.toUpperCase();
	 	}
	 }
	
	/*
	 *  Formats the Canadian Postal Code XXX XXX
	 */
	 function formatOrgPostalCode(form){
	 	if(form.storeId.value == '10052'){
	 		var zip = form.zipCode.value;
	 		var billZip = form.BillTo_zipCode.value;
	 		if(zip.length == 6){
	 			form.zipCode.value = zip.substring(0,3)+" "+zip.substring(3,6);
	 		}
	 		if(zip.length == 7 && zip.substring(3,4) == '-'){
	 			form.zipCode.value = zip.substring(0,3)+" "+zip.substring(4,7);
	 		}
	 		if(billZip.length == 6) {
		 		form.BillTo_zipCode.value = billZip.substring(0,3)+" "+billZip.substring(3,6);
	 		}
	 		if(billZip.length == 7 && billZip.substring(3,4) == '-'){
	 			form.BillTo_zipCode.value = billZip.substring(0,3)+" "+billZip.substring(4,7);
	 		}
	 		
	 	}
	 }
	 
	 /*
	 * Updates WCParam.poNumber field if changes were made during the Final Review page (function is called from OrderSubmitForm.jsp)
	 */
	 function changePONumber(poNumberVal)
	 {
	 	document.utilForm.poNumber.value = poNumberVal;
	 	document.utilForm.submit();
	 }
	 

	/*
	* This javascript function is to be used to prevent the event caused by the enter key. For example, when a form has 
	* only one input of type text and the enter key is hit, the form is submitted. To prevent this behaviour, use this function in
	* the onKeyPress event for the field in question.
	*/
	function disableEnterKey(newEvent)
	{
		var key = (window.event) ? newEvent.keyCode : (event.which) ? newEvent.which : newEvent.charCode;

		if (key == 13)
		{
			if (window.event)
			{
				window.event.keyCode = 0;
			}
			
	 		return false;			
		}
		else
		{
			return true;
		}

	}
	
	
	/*
	* Formats the list of Promo Codes
	*/
	function formatPromoCode(form)
	{
		if (form.promoCode != null)
		{
			form.promoCode.value = form.promoCode.value.toUpperCase();  		
		}
	}
	
	/*
	*
	*/
	function lengthCheck(field, maxlength)
	{
		if (field.value.length > maxlength)
			field.value = field.value.substring(0, maxlength);
	}
	

