// common.js
// This fill will contain the common functions for javscript
//
// local variable
var isIE = (document.all) ? true : false;

//count of form submissions
var submittedformcount = 0;
//the static path
var staticpath = "";

singleClickLink = getNavClickHandler();
singleClickForm = getFormSubmitHandler();

// the image path 
var imgpath = "";

//current lang id 
var currentLang = "";	


	////////////////////////////////////////////////////// 
	// isInteger 
	// 
	// Returns true if all characters in string s are numbers.
	// EXAMPLE FUNCTION CALL:     RESULT:
	// isInteger ("5")            true 
	// isInteger ("")             defaultEmptyOK
	// isInteger ("-5")           false
	// isInteger ("", true)       true
	// isInteger ("", false)      false
	// isInteger ("5", false)     true
	////////////////////////////////////////////////////////
	function isInteger (s) {   
		var i;
	
	    if (isEmpty(s)) 
	       if (isInteger.arguments.length == 1) return defaultEmptyOK;
	       else return (isInteger.arguments[1] == true);
	    // Search through string's characters one by one
	    // until we find a non-numeric character.
	    // When we do, return false; if we don't, return true.
	    for (i = 0; i < s.length; i++)
	    {   
	        // Check that current character is number.
	        var c = s.charAt(i);
	        if (!isDigit(c)) return false;
	    }
	    // All characters are numbers.
	    return true;
	}
	
	/**
	* Check whether string s is empty.
	**/
	function isEmpty(s) {   
		return ((s == null) || (s.length == 0))
	}
	
	/**
	*  Returns true if character c is a digit (0 .. 9).
	**/
	function isDigit (c){   
		return ((c >= "0") && (c <= "9"))
	}
	
	
	/**
	* replace the string with new one 
	*/
	function replaceString(valueStr, replaceStr){		
			while (valueStr.indexOf(replaceStr) != -1){
				valueStr = valueStr.replace(replaceStr," ");
			}
			return valueStr;
		}

	
	//////////////////////////////////////
	//  Build commerce URL from static pages
	//////////////////////////////////////
	function buildWcsUrl( viewName , storeId ){
		var urlStr = "/webapp/wcs/stores/servlet/" + viewName + "?" + "storeId=" + storeId ;
		//first try to read it from cookie 
		var cookieVal = getCookieValue('WebLang');
		//alert("cookieVal " + cookieVal);
		if ( null != cookieVal) {
			urlStr = urlStr +  "&langId=" + cookieVal;
		}
		return urlStr;
	}
	
	
	      
	/////////////////////////////////////////////////////////////// 
	// Bulids url for html pages or the content pages
	// Since the path of displaying HTML is different
	// in production and local
	/////////////////////////////////////////////////////////////
	function buildContentURL(htmlName, storeId){
			
		var TempHost=location.host;
		
		var urlParam1 = "https://";
		var urlParam2 = "/webapp/wcs/stores/";
		var urlParam3 = "?" + "storeId=" + storeId;
		
		if ( TempHost != 'localhost'){
			urlParam2='/wcsstore/';
		}
		
		var url = urlParam1 + TempHost + urlParam2 + htmlName + urlParam3;
		return url ;
		
	}
	
	/////////////////////////////////////////////////////////////// 
	// Bulids url for html pages or the WCS depenidng on the isHTML param
	// passed.
	// Since the path of displaying HTML is different
	// in production and local
	/////////////////////////////////////////////////////////////
      function buildURL(viewName, isHTML , storeId,anchorObj){
            if ( isHTML ){
                  //build the HTML link

	//event.srcElement.href=buildContentURL(viewName,storeId);
                  anchorObj.href = buildContentURL(viewName,storeId);
            }
            else{
                  // build WCS link
                  //event.srcElement.href=buildWcsUrl(viewName,storeId);
                  anchorObj.href = buildWcsUrl(viewName,storeId);
            }
      }
	
	/////////////////////////////////////////////////////////////////////// 
	// Sets the global image path dynamically 
	// in production and local
	/////////////////////////////////////////////////////////////
	function setGlobalImagePath(storeName){
		var TempHost=location.host;
		var urlParam2="";
		
		if ( TempHost != 'localhost'){
			//production
			urlParam2='/wcsstore/';
			imgpath=urlParam2+ storeName + "/content/images/";
		}else{
			//localhost
			imgpath=storeName + "/content/images/";
		}
		
	}
	
	
	/////////////////////////////////////////////////////////////////// 
	// Sets the image path dynamically for images with the tag Id 
	// 
	/////////////////////////////////////////////////////////////
	function setImagesPath(storeName, imgId ){
		//get the document lists 
		var ilist = document.images;
		for ( var i=0 ; i < ilist.length ; i++ ){
		
			var tempImgId= ilist[i].id;
		 	if (  tempImgId.indexOf(imgId) != -1 ){
				var imgName= ilist[i];
				ilist[i].src=imgpath+imgName;
			}
		}
	}
	
	/////////////////////////////////////////////////////////////////// 
	// 
	//	This function returns a function that handles form submission. Such handler will submit a 
	// form only once even if the a double-click is issued by a user. Each handler can be used 
	// for multiple forms.
	// Usage: 
	//		1. Create a global handler within an activation context: var formHandler = getSubmitHandler();
	//		2. Call the handler for an "onclick" event: onclick="formHandler(form); return false;"
	/////////////////////////////////////////////////////////////////// 
	function getFormSubmitHandler(){
			// Variable to prevent people from double clicking on a link
			var busy = false;
			function handler(form){
				if(!busy){
					busy = true;
					form.submit();
				}
				return false;
			}
			
			return handler;
		}
		
	
	
	/////////////////////////////////////////////////////////////////// 
	// This function is similar to the function getFormSubmitHandler(), except that the returned 
	// handler will submit a given URL instead of a form.
	/////////////////////////////////////////////////////////////////// 
	function getNavClickHandler(){
		// variable to prevent people from double clicking on a link
		var busy = false;
			function handler(url){
				if(!busy){
					busy = true;
					location.href = url;
				}
				return false;
			}
			return handler;
		}	
		
	/////////////////////////////////////////////////////////////////// 
	// submit with action (action deprecated) + only allows one submit per form 
	// w/ hourglass cursor to fix IE6 progress bar bug and status message
	/////////////////////////////////////////////////////////////////// 
	function formSubmit(fName,fAction) {
		if (submittedformcount == 0) {
			submittedformcount++;
			if (fAction > "") eval("document." + fName + ".action = '" + fAction + "';");
				eval("document." + fName + ".submit();");
				document.body.style.cursor='wait'; 
				status='Loading...';
		}
	}
	
	
	
	/////////////////////////////////////////////////////////////////// 
	// Deriving the static path. Since the localhost and production static path 
	// vary. 
	// 
	/////////////////////////////////////////////////////////////////// 
	function buildStaticPath(){
			var TempHost=location.host;
			if ( TempHost != 'localhost'){
				staticpath='/wcsstore/'
			}
	}
	
	/////////////////////////////////////////////////////////////////// 
	//	Get the query variable 
	//	from the query string
	/////////////////////////////////////////////////////////////////// 
	function getQueryVariable(variable) { 
		var query = window.location.search.substring(1); 
		var vars = query.split("&"); 
		for (var i=0;i<vars.length;i++) { 
			var pair = vars[i].split("="); 
			if (pair[0] == variable) { 
				return pair[1]; 
			} 
		} 
	} 
	
	/////////////////////////////////////////////////////////////////// 
	// Replace the value of the param in the query string 
	/////////////////////////////////////////////////////////////////// 
	function replaceParamValue(paramName , newVal) { 
		var query = window.location.search.substring(1); 
		var newQuery = "?"
		var vars = query.split("&"); 
		for (var i=0;i<vars.length;i++) { 
			if ( i > 0 ) newQuery+="&";
			var pair = vars[i].split("="); 
			if (pair[0] == paramName) { 
				newQuery += pair[0]+"=" + newVal;
			} else{
				newQuery += pair[0]+"=" + pair[1];
			}
		} 
		return newQuery;
		 
	} 
	
	
	//////////////////////////////////////////////////////////////////
	// Open an UTF-8 modal dialog
	///////////////////////////////////////////////////////////
	function openModalDialog(url, width, height, scrolling, args) {
		var features = "";
		var dialogName = (new Date()).getMilliseconds().toString();
		var dialogWidth = width;
		var dialogHeight = height;
		var dialogArgs = new Object();
		var returnValue = null;
	
		for (i in args) {
			dialogArgs[i] = args[i];
		}
	
		dialogArgs.timeout = false;
		if (isIE) {
			features = "dialogWidth: " + dialogWidth + "px; dialogHeight: " + dialogHeight + "px; center; status: no; help: no;";
			features += (scrolling)?(" scroll: yes;"):(" scroll: no;");
			returnValue = window.showModalDialog(url, dialogArgs, features);
			if (dialogArgs.timeout == true) {
				top.close();
			}
			return returnValue;
		}
		else {
			dialogWidth = (dialogWidth - 20 <= 0)?(dialogWidth):(dialogWidth - 20);
			dialogHeight = (dialogHeight - 20 <= 0)?(dialogHeight):(dialogHeight - 20);
			var posX = window.screenX + ((window.outerWidth - parseInt(dialogWidth)) / 2);
			var posY = window.screenY + ((window.outerHeight - parseInt(dialogHeight)) / 2);
			window.dialogArguments = dialogArgs;
			features = "screenX=" + posX + ", screenY=" + posY + ", width=" + dialogWidth + "px, height=" + dialogHeight + "px, modal=yes, sidebars=no, menubars=no";
			features += (scrolling)?(", scrollbars=yes"):(", scrollbars=no");
			window.returnValue = null;
			window.open(url, dialogName, features);
	
			if (window.returnValue != null)
				return window.returnValue;
		}
	}
	
	
	///////////////////////////////////////////////////////////////
	// Adjusts the size of the modal dialog to fit the content.
	///////////////////////////////////////////////////////////
	function autoResizeModalDialog() {
		var hiddenWidth = getPageWidth() - getClientWidth();
		var hiddenHeight = getPageHeight() - getClientHeight();
	
		if (isIE) {
			window.dialogWidth = parseInt(window.dialogWidth) + hiddenWidth + 18 + "px";
			window.dialogHeight = parseInt(window.dialogHeight) + hiddenHeight + 18 + "px";
		}
		else if (isNS) {
			window.sizeToContent();
		}
	}
	
		 
	 
	 //change the web site language
	 // on change function called 
	 function changeWebsiteLang(){
	 	
	 	var x = document.getElementById('selectLang');
	 	var sel = x.options[x.selectedIndex].value;
	 	if ( sel != currentLang) {
	 	
		 	var host=location.host;
		 	var path=location.pathname;
		 	var qurStr = replaceParamValue("langId" , sel);
			//create the new action string
		 	var actionStr = null;
		 	
		 	//put the action
		 	actionStr = "https:" + "//" + host + path + qurStr;
		 	//alert(actionStr );
		 	//submit the form
		 	var selLangform = document.getElementById('langSelectForm');
		 	//set the new action
			selLangform.action=actionStr;
			selLangform.submit();
		}
	 }
	 
	 
	 //set the lang 
	 //in the global variable
	 function setCurrentLang(){
	 	currentLang=getQueryVariable('langId');
	 }
	 
	 //set the current lang
	 //setCurrentLang();	


	///////////////////////////////////////////////////////////////////// 
	// Get the cookie value
	/////////////////////////////////////////////////////////////
	function getCookieValue( cookieName ) {
		if(cookieName == "WebLang" || cookieName == "AnonymousClientId" ||cookieName == "UserID" 
					||cookieName == "CountryCode"){
			var found = false;		
			var sialSiteDefIndex = document.cookie.indexOf("SialSiteDef=");
			if(sialSiteDefIndex != -1){
				sialSiteDefIndex = sialSiteDefIndex + 12;
				var sialSiteDefEndIndex = document.cookie.indexOf(";",sialSiteDefIndex);
				if(sialSiteDefEndIndex == -1){
					sialSiteDefEndIndex = document.cookie.length;
				}
				var sialSiteDefValue = document.cookie.substring(sialSiteDefIndex, sialSiteDefEndIndex);
				
				var arr = sialSiteDefValue.split("|");
				for(var i=0 ; i< arr.length ; i++){
					var tempV = arr[i];
					if(tempV.indexOf(cookieName) > -1){
						var acltIDarr = tempV.split("~");
						found = true ;
						return unescape(acltIDarr[1]);
					}
				}
				if(!found){
					return null;
				}
			}
		}
		else{
			//first try to read it from cookie 
			var cookieIndex = document.cookie.indexOf( cookieName +"=");
			if ( cookieIndex != -1 ) {
				var startcount = cookieIndex + cookieName.length + 1;
				var endcount = document.cookie.indexOf(";", startcount);
				if (endcount == -1) endcount = document.cookie.length;
					var langIdVar = document.cookie.substring(startcount, endcount); //Extract value
					return unescape(langIdVar);
			}
			else{
				return null;
			}
		}//end of else
	}//end of function
	
	//////////////////////////////////////////////////////////////////// 
	/////// Special Sigma function(s)
	/////////////////////////////////////////////////////////////

	function OpenWin(URL, windowattributes) {
		help=window.open(URL,"Help",windowattributes);
		help.focus();
	}

	function OpenWindow(URL, windowattributes) {
    	help=window.open(URL,"Help",windowattributes);
    	help.focus();
	}

	function changeParentURL(url){
		window.opener.location = url;
	}

	function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
	}     

	// **added for CoreMetrics**
	
	function getMemberId() {
		var hasWCUserActivityCookie  = document.cookie.indexOf("WC_USERACTIVITY_");
		if (hasWCUserActivityCookie != -1 ){ 
			var startcount2 = hasWCUserActivityCookie + 16;// Start cookie value 
			var endcount2 = document.cookie.indexOf("=", startcount2); // End cookie value 
			if (endcount2 == -1) endcount = document.cookie.length; 
				var MemberID = document.cookie.substring(startcount2, endcount2); //Extract value 
		} 
		else 
		{ 
			MemberID = "Unknown"; 
		}

		if(MemberID == "-1002"){MemberID = "Unknown";}
		return MemberID;
	}

	function getClientId() {
		var ClientID = "Unknown";
		var userCookie = document.cookie;
 		var hasAnonymousClientIdCookie = userCookie.indexOf("AnonymousClientId="); 
		if (hasAnonymousClientIdCookie != -1 )
			{userCookie = userCookie.substring(hasAnonymousClientIdCookie + 21, userCookie.length);} 
 		var hasClientIdCookie = userCookie.indexOf("ClientId=");
		if (hasClientIdCookie != -1 ){
			var startcount = hasClientIdCookie + 9;
			var endcount = userCookie.indexOf(";", startcount);
				if (endcount == -1) endcount = userCookie.length; 
				{ClientID = userCookie.substring(startcount, endcount);}
		}
		return ClientID;
	}
