//********************************************************************
//*-------------------------------------------------------------------
//* Licensed Materials - Property of IBM
//*
//* WebSphere Commerce
//*
//* (c) Copyright International Business Machines Corporation. 2003
//*     All rights reserved.
//*
//* US Government Users Restricted Rights - Use, duplication or
//* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//*
//*-------------------------------------------------------------------
//*

//////////////////////////////////////////////////////////
// Checks whether a string contains a double byte character
// target = the string to be checked
//
// Return true if target contains a double byte char; false otherwise
//////////////////////////////////////////////////////////

/*WK-2142- moved the functions from OrderItemDisplay.jsp*/
function UpdateTotal(form)
	{
		/** To stop the user from updating the cart in case quantity entered for any item is invalid**/
		if(busy)
		{
			return;
		}
		//wkpbo-1169, changing items quantity that's passed to server
		modifyQuants();
		busy = true;
		form.URL.value = 'OrderCalculate?updatePrices=1&calculationUsageId=-1&orderItemId*=&quantity*=&URL=OrderItemDisplay';
		form.submit();
	}
/**
 * function modifies hidden quantity fields that are actually passed to server.
 */
function modifyQuants(){
	var orderItems = $('#items li');
	$.each(orderItems, function(i,item){
		var selectDropDown = $(item).find('select');
		var isItemJournalOrNewsl = (selectDropDown.length != 0) ? true : false;
		var visibleQuant = $(item).find(':input.visibleQuant');
		var hiddenQuant = $(item).find(':input[name^=quantity_]');
		if(isItemJournalOrNewsl){
			hiddenQuant.val(parseInt($(item).find('.visibleQuant').val()) * parseInt(selectDropDown.val()));
		}else{
			hiddenQuant.val(parseInt($(item).find('.visibleQuant').val()));
		}
	});
}
//not required
/*
	function quickCheckout(form)
	{
		SubmitCart(form);
	}
	*/
	function SubmitCart(form)
	{
		/** To stop the user from going through checkout process in case quantity entered for any item is invalid**/
		if(busy)
		{
			return;
		}
		modifyQuants();
		busy = true;
		form.submit();
	}


	/** WK-2435 **/

	function setStandingOrder(hiddenFieldId, checkBox)
	{
		var hiddenField = document.getElementById(hiddenFieldId);
		if(hiddenField)
		{
			var checkedBoxValue = 'N';
			if(checkBox.checked) checkedBoxValue = 'Y';
			hiddenField.value = checkedBoxValue;
		}

	}

/**WK-2142 ends***/

function containsDoubleByte (target) {
     var str = new String(target);
     var oneByteMax = 0x007F;

     for (var i=0; i < str.length; i++){
        chr = str.charCodeAt(i);
        if (chr > oneByteMax) {return true;}
     }
     return false;
}

//////////////////////////////////////////////////////////
// A simple function to validate an email address
// It does not allow double byte characters
// strEmail = the email address string to be validated
//
// Return true if the email address is valid; false otherwise
// ////////////////////////////////////////////////////////
function isValidEmail(strEmail){
	// check if email contains dbcs chars
	if (containsDoubleByte(strEmail)){
		return false;
	}

	if(strEmail.length == 0) {
		return true;
	} else if (strEmail.length < 5) {
             return false;
       	}else{
           	if (strEmail.indexOf(" ") > 0){
                      	return false;
               	}else{
                  	if (strEmail.indexOf("@") < 1) {
                            	return false;
                     	}else{
                           	if (strEmail.lastIndexOf(".") < (strEmail.indexOf("@") + 2)){
                                     	return false;
                                }else{
                                        if (strEmail.lastIndexOf(".") >= strEmail.length-2){
                                        	return false;
                                        }
                              	}
                       	}
              	}
       	}
      	return true;
}



//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string
// arg2 = the maximum number of bytes allowed in your input field
// Return false is this input string is larger then arg2
// Otherwise return true...
// ////////////////////////////////////////////////////////
function isValidUTF8length(UTF16String, maxlength) {
    if (utf8StringByteLength(UTF16String) > maxlength) return false;
    else return true;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string you want a byte count of...
// Return the integer number of bytes represented in a UTF-8 string
// ////////////////////////////////////////////////////////
function utf8StringByteLength(UTF16String) {
  if (UTF16String === null) return 0;
  var str = String(UTF16String);
  var oneByteMax = 0x007F;
  var twoByteMax = 0x07FF;
  var byteSize = str.length;

  for (i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    if (chr > oneByteMax) byteSize = byteSize + 1;
    if (chr > twoByteMax) byteSize = byteSize + 1;
  }
  return byteSize;
}

// clear field value function: removes the default value onfocus, and adds back if nothing entered
function fieldClear(obj) {
	if(obj.Val) {
		if (obj.value == '') {
			obj.value = obj.Val;
			obj.Val = null;
			obj.first = null;
		}
		else {
			obj.Val = null;
		}
	} else if (!obj.first) {
		obj.Val = obj.value;
		obj.value = '';
		obj.first = 'true';
	}
}

function trimMe(field) {
	var value = field.value ;
	value = value.replace(/^\s+|\s+$/g,"");
	field.value = value;
}

// function to convert the field to lower case
function convertToLowerCase(field){
	var value = field.value;
	value = value.toLowerCase();
	field.value = value;
}

var busy = false;
function Add2ShopCart(form)

{      //alert("catentryId="+form.catEntryId.value);

  		if (!busy) {
              busy = true;
              form.action="OrderItemAdd";
              // form.catEntryId.value = catEntryId;
              // form.quantity.value = catEntryQuantity;


              if(form.quantity.value != null)
            	  form.quantity.value = form.quantity.value.replace(/^\s+|\s+$/g,"");
              if ( form.quantity.value == null || form.quantity.value.length == 0
            		   || form.quantity.value == '0' || isNaN(form.quantity.value)||Number(form.quantity.value) == 0  )
            	  {
            	  form.quantity.value='1';
            	  }

              form.URL.value='OrderCalculate?updatePrices=1&calculationUsageId=-1&dummaryparam=1&URL=OrderItemDisplay';
              form.submit();
       }
}
// This javascript function is used by the 'Add to Wish List' button to set appropriate values before the form is submitted
function Add2WishList(form)
{
       if (!busy) {
              busy = true;
              form.action="InterestItemAdd";
             // form.catEntryId.value = catEntryId;
              if ( form.quantity.value == null || form.quantity.value.length == 0)
            	  form.quantity.value='1';
              form.URL.value='InterestItemDisplay';
              form.submit();
       }
}

// This javascript display the value of the 'keyName' stored in 'cookieName'. If value is null then display "0".
// This script is used to display Items for cookie CVMINICART & balancePoints
// for CVREWRDPOINTS cookies
function displayIntegerValue(cookieName, keyName)
{
	//alert("IN displayCartItems method");
	var str = getIntegerValue(cookieName, keyName);
	document.write(str);
}

// This javascript display the value of the 'keyName' stored in 'cookieName'. If value is null then display "0.00".
// If value is integer then it appends the .00 after the integer value.
// This script is used to display Items amount total for cookie CVMINICART &
// balanceAmount for CVREWRDPOINTS cookies
function displayAmountValue(cookieName, keyName)
{
	//alert("IN displayCartItems method");
	var str = getAmountValue(cookieName, keyName);
	document.write(str);
}
/**
 * Get the cookie value
 * @param cookieName the name of the cookie
 * @param keyName the name of the key
 * @return cookie value
 */
function getUserCookieValue(cookieName, keyName)
{
 //alert("in getUserCookieValue");
 var cookieValue = getCookie(cookieName);
 // alert("cookieValue="+cookieValue);
  if ( cookieValue == null )
 	return null;
 var  nameDelimiter = "@" ;
 var pairDelimiter = "~~~" ;
 var matchPattern = keyName + pairDelimiter + '(.*?)(' + nameDelimiter +')';
 // alert("match partern = "+matchPattern);
 var results = cookieValue.match ( matchPattern);
 // alert("resutls="+results);
  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

function getCookie ( cookieName )
{
  var results = document.cookie.match ( cookieName + '=(.*?)(;|$)' );
  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

/* ************************************
 * Get the amount value
 */
function getAmountValue(cookieName, keyName){
	var str = "0.00";
	str = getUserCookieValue(cookieName, keyName);
	if (str != null)
	{
		var iDotIndex = str.indexOf(".");
		if (str.length - iDotIndex > 3)
			str = str.substring(0, iDotIndex + 3);
		else if (iDotIndex != -1 && str.length - iDotIndex == 2)
			str = str + "0";
		else if (iDotIndex == -1)
			str = str + ".00";
	}
	else
	{
		str = "0.00";
	}
	return formatCurrency(str);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + num + '.' + cents);
}

/* *************************************
* Get the integer  value
*/
function getIntegerValue(cookieName, keyName){
	var str = "0";
	str = getUserCookieValue(cookieName, keyName);
	if(str == null)
		str = "0";
	return str;
}

function isUSAddress(countryCode) {
	return (countryCode == 'US' || countryCode == 'CA' || countryCode == 'MX');
}

/* ************************************
 * Trim and format the US phone
 */
function trimUSPhone(field) {
	var value = field.value ;
	//alert(value);
	if ( value != null && value.length > 4){
		value =  value.replace(/^\s+|\s+$/g,"");
		var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
		if (regexObj.test(value)) {
			var formattedPhoneNumber =
	    	value.replace(regexObj, "($1) $2-$3");
			field.value=formattedPhoneNumber;
		} else {
			// Invalid phone number
		}
   }
}

// Trim non-US phone
function trimPhone(field) {
	var value = field.value;
	if (value != null) {
		field.value = value.replace(/^\s+|\s+$/g, '');
	}
}

/* **********************************
 * Strip non numeric characters
 */
 function stripAlphaChars(pstrSource)
 {
	 var m_strOut = new String(pstrSource);
     m_strOut = m_strOut.replace(/[^0-9]/g, '');
     //alert(m_strOut);
     return m_strOut;
 }

/* ***********************************
 * Add to cart from Shop cart page
 */
 function Add2CartFormats(productId, storeId , catalogId, langId)
 {      //alert("catentryId="+form.catEntryId.value);

   		if (!busy) {
               busy = true;

               var add2CartURL ="OrderItemAdd?catEntryId_1="+productId +"&quantity_1=1" + "&storeId="
        	                             + storeId + "&catalogId=" + catalogId + "&langId=" + langId +
        	                             "&errorViewName=OrderItemDisplayView";
        	                             //+ "&orderId=.&errorViewName=OrderItemDisplayView&outOrderName=orderId";
        	   window.location= add2CartURL;
        }
 }
 
 /**
  * Get URL vars as name value pairs 
  * @return
  */ 
  function getUrlVars() {     
 	 var vars = [], hash;     
 	 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');     
 	 for(var i = 0; i < hashes.length; i++)     {         
 		 hash = hashes[i].split('=');         
 		 vars.push(hash[0]);         
 		 vars[hash[0]] = hash[1];     
 	 }     
 	 return vars; 
  }
 
 
/* ***************************************
 * Select the option by value
 */
function selectOption (id, val){
		//alert(packageId);
		//select the correct option from the format drop down
		var elementobj = document.getElementById(id).options;
		var optionValue='';
		for ( var j =0 ; j < elementobj.length ; j++ ) {
			 // get the option value
		     optionValue= elementobj[j].value;
		    if ( val == optionValue){
		        //alert("calling selected");
		        elementobj[j].selected=true;
		     }else{
		       //alert("calling unselected");
		        elementobj[j].selected=false;
		     }
		}
}


/* ***********************************
 * Catalog Search Form Submit page
 */
 function CatalogSearchFormSubmit(searchText)
 {
	//WKPBO-1090 When the user does not enter anything and presses the search button all the products are returned
	// Since the search text box has a default value of Search LWW when the user clicked on the search button without
	// entering any value the search term which was being passed to solr was 'Search LWW'. In order to get over this
	// we set the value of the text box to an empty string before we submit the form.
	var searchTermValue = document.getElementById("search-input").value;
	if(searchTermValue == searchText){
		document.getElementById("search-input").value = '';
		document.CatalogSearchForm.submit();
	}
	else{
		if (searchTermValue.search(/((^\s)|[A-Za-z,0-9]{2,})/ ) != -1){
			if (searchTermValue.indexOf("\'") != -1){
				document.getElementById("search-input").value = escape(searchTermValue);
			}
			document.CatalogSearchForm.submit();

		}else{
			$("#p-results").html('The data entered in the form is not valid. You must enter <strong>at least two characters.</strong>' );


		}
	}

	/*var searchTermValue = document.getElementById("search-input").value;
	if (searchTermValue.search(/((^\s)|[A-Za-z,0-9]{2,})/ ) != -1){
		if (searchTermValue.indexOf("\'") != -1){
			document.getElementById("search-input").value = escape(searchTermValue);
		}
		document.CatalogSearchForm.submit();

	}else{
		$("#p-results").html('The data entered in the form is not valid. You must enter <strong>at least two characters.</strong>' );


	}*/

 }
 
 
//Setting a cookie
 function setCookie(c_name,value,exdays)	{
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;
	}
	// Getting a cookie
 function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
		  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		  x=x.replace(/^\s+|\s+$/g,"");
		  if (x==c_name) {
		    return unescape(y);
		  }
		}
 }
 

