//********************************************************************
//*-------------------------------------------------------------------
//* 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
//////////////////////////////////////////////////////////
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_old(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;
}
function isValidEmail(strEmail){
	var errorEmail = '';
	if (strEmail == null || strEmail == '') {
  		errorEmail = '11000';
		return errorEmail;
	}
		
	var str = strEmail;
  	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(^\#)|(^\*)|(^\@)|(^\&)|(^\^)|(%)/; //not valid 
  	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{1,3}|[0-9]{1,3})(\]?)$/; // valid
	var reg3 = /^www/;//not valid
	//var reg4 = /[^0-9](aol|yahoo|msn|hotmail)/;
	var reg4 = /^[0-9][a-zA-Z0-9\-\.]+\@(aol|yahoo|msn|hotmail)/;//not valid
	//As people generally know about some basic admin email addresses, they are not allowed.
	var reg5 = /^webmaster@|^administrator@|^support@|^admin@/; //not valid
	//Regular domain level checks & Country level domain checks
	var reg6 = /(\.aero|\.biz|\.cat|\.com|\.coop|\.edu|\.gov|\.info|\.int|\.jobs|\.mil|\.mobi|\.museum|\.name|\.net|\.org|\.pro|\.tel|\.travel|\.ac|\.ad|\.ae|\.af|\.ag|\.ai|\.al|\.am|\.an|\.ao|\.aq|\.ar|\.as|\.at|\.au|\.aw|\.ax|\.az|\.ba|\.bb|\.bd|\.be|\.bf|\.bg|\.bh|\.bi|\.bj|\.bm|\.bn|\.bo|\.br|\.bs|\.bt|\.bv|\.bw|\.by|\.bz|\.ca|\.cc|\.cd|\.cf|\.cg|\.ch|\.ci|\.ck|\.cl|\.cm|\.cn|\.co|\.cr|\.cu|\.cv|\.cx|\.cy|\.cz|\.de|\.dj|\.dk|\.dm|\.do|\.dz|\.ec|\.ee|\.eg|\.er|\.es|\.et|\.eu|\.fi|\.fj|\.fk|\.fm|\.fo|\.fr|\.ga|\.gb|\.gd|\.ge|\.gf|\.gg|\.gh|\.gi|\.gl|\.gm|\.gn|\.gp|\.gq|\.gr|\.gs|\.gt|\.gu|\.gw|\.gy|\.hk|\.hm|\.hn|\.hr|\.ht|\.hu|\.id|\.ie|\.il|\.im|\.in|\.io|\.iq|\.ir|\.is|\.it|\.je|\.jm|\.jo|\.jp|\.ke|\.kg|\.kh|\.ki|\.km|\.kn|\.kr|\.kw|\.ky|\.kz|\.la|\.lb|\.lc|\.li|\.lk|\.lr|\.ls|\.lt|\.lu|\.lv|\.ly|\.ma|\.mc|\.md|\.mg|\.mh|\.mk|\.ml|\.mm|\.mn|\.mo|\.mp|\.mq|\.mr|\.ms|\.mt|\.mu|\.mv|\.mw|\.mx|\.my|\.mz|\.na|\.nc|\.ne|\.nf|\.ng|\.ni|\.nl|\.no|\.np|\.nr|\.nu|\.nz|\.om|\.pa|\.pe|\.pf|\.pg|\.ph|\.pk|\.pl|\.pm|\.pn|\.pr|\.ps|\.pt|\.pw|\.py|\.qa|\.re|\.ro|\.ru|\.rw|\.sa|\.sb|\.sc|\.sd|\.se|\.sg|\.sh|\.si|\.sj|\.sk|\.sl|\.sm|\.sn|\.so|\.sr|\.st|\.su|\.sv|\.sy|\.sz|\.tc|\.td|\.tf|\.tg|\.th|\.tj|\.tk|\.tl|\.tm|\.tn|\.to|\.tp|\.tr|\.tt|\.tv|\.tw|\.tz|\.ua|\.ug|\.uk|\.um|\.us|\.uy|\.uz|\.va|\.vc|\.ve|\.vg|\.vi|\.vn|\.vu|\.wf|\.ws|\.ye|\.yt|\.yu|\.za|\.zm|\.zw)$/; //valid

  if (!reg1.test(str) && reg2.test(str) &&  !reg3.test(str) && !reg4.test(str.toLowerCase()) && !reg5.test(str.toLowerCase()) && reg6.test(str.toLowerCase())) { 
  		errorEmail = 'true';
    	return errorEmail;
 	} else {
 		errorEmail = '11000';
 		if (reg5.test(str.toLowerCase()))
 			errorEmail = '11010';
 		else if (!reg6.test(str.toLowerCase()))
 			errorEmail = '11011';
		return errorEmail;
	}
}


//////////////////////////////////////////////////////////
// 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;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function createRegisterRefererCookie() {
	createRegisterRefererCookie(window.location); 
}

function createRegisterRefererCookie(value) {
	value = value + '';
	if (value != null && value.match('OrderItemDisplay') != null) {
		var indexValue = value.indexOf('?');
		value = value.substring(0, indexValue);
		//value = "https://localhost/online/store/OrderItemDisplay";
	}
	if (value != null 
		&& value.match('LogonForm') == null 
		&& value.match('UserRegistrationForm') == null 
		&& value.match('BRForgotUserNameView') == null 
		&& value.match('BRForgotPasswordView') == null
		&& value.match('StoreForgotUserNameCmd') == null 
		&& value.match('ResetPassword') == null){
		createCookie('borders.registerReferer', value, 1);
	}
}

function readRegisterRefererCookie() {
	return readCookie('borders.registerReferer');
}

//dreamweaver's never fail find object snippet
function findObj(theObj, theDoc){
	var p, i, foundObj;
	
	if(!theDoc) theDoc = document;
	if( (p = theObj.indexOf("?")) > 0 && parent.frames.length){
		theDoc = parent.frames[theObj.substring(p+1)].document;
		theObj = theObj.substring(0,p);
	}

	if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];

	for (i=0; !foundObj && i < theDoc.forms.length; i++) 
		foundObj = theDoc.forms[i][theObj];

	for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
		foundObj = findObj(theObj,theDoc.layers[i].document);

	if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

	return foundObj;
}

function openWindowSized(url, width, height)
{
	
	op = window.open(url,"window","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resize=0,width="+width+",height="+height);
}

function isInt(event)
{
  var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if(Key==8  || Key==0 || (Key >= 48 && Key <=57)) return true;
  else return false;
}

function isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	return true;
}

	//Function used in borders rewards to trim the blanks in the begining and the end of strings
	function Trim(str)
	{ 
	    while(str.charAt(0) == (" ") )
		  {  str = str.substring(1);
		  }
		while(str.charAt(str.length-1) == " " )
		  {  str = str.substring(0,str.length-1);
		  }
		return str;
	}

	
//Function used to clear children of an object
function clearChildren(obj){
	while(obj.hasChildNodes()){obj.removeChild(obj.lastChild);}
	return obj;
}


//Function used to check max length and display message.
//Used as of 10/2/07 on sharePage.jsp and shareWishlist.jsp
function checkMaxLength(obj, maxLength, errorDivName, message){
	var errorsDiv = findObj(errorDivName);

	if(obj.value.length > maxLength){
		//remove previous children if any
		errorsDiv = clearChildren(errorsDiv);

		var ulTag = document.createElement("ul");
		var liTag = document.createElement("li");
		liTag.innerHTML = message;
		ulTag.appendChild(liTag);
		errorsDiv.appendChild(ulTag);
		return false;
	}
	errorsDiv.innerHTML = '';
	return true;
}




	
//////////////////////////////////////////////////////////
// Error Handling functions in JSP
//////////////////////////////////////////////////////////
	
function showError(errorText, errorTextId)
{
	var element = getErrorElement(errorTextId);
	if (element)
	{
		element.innerHTML = errorText;
	}
	showHideErrorText("visible", errorTextId);
}

function clearError(errorText, errorTextId)
{
	showHideErrorText("hidden", errorTextId);
}

function showHideErrorText(visibility, errorTextId)
{

	var element = getErrorElement(errorTextId);
	if (element) {
		element.style.visibility = visibility; //'visible';

	}
}

function getErrorElement(errorTextId)
{
	var element;
	var elementId;
	if(typeof(errorTextId)=='undefined') {
		elementId = 'error_display_text';
	} else {
		elementId = errorTextId;
	}
	if (document.getElementById) {
	// IE 5.5+, NS6+, Opera 6+
		element = document.getElementById(elementId);
	} else if (document.layers) {
	// NS4
		element = document.layers[elementId];
	} else if (document.all) {
	// IE < 5.5, Opera 5(?)
		element = document.all(elementId);
	}
	return element;
}

//////////////////////////////////////////////////////////
// This function is used to check if the CC number is valid
// according to the rules for each type.
//////////////////////////////////////////////////////////
function isValidCreditCard(type, ccnum) {
   if (type == "AMEX") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "DISCOVER") {
      // Discover: length 16, prefix 6011.
      var re = /^6011\d{12}$/;
   } else if (type == "MASTER") {
      // Mastercard: length 16, prefix 51-55.
      var re = /^5[1-5]\d{14}$/;
   } else if (type == "VISA") {
      // Visa: length 13 or 16, prefix 4.
      var re = /^4(\d{12}|\d{15})$/;
   } else {
      return true;
   }
 
   if (re.test(ccnum)){
    return true;
   } else {
    return false;}
 
}

///////////////////////////////////////////////////////////////////////////////
// This function is used to check if the CVV count is valid for a given CC type 
// e.g. "AMEX" is 4, "DISCOVER" is 3, "MASTER" is 3 and "VISA" is 3
///////////////////////////////////////////////////////////////////////////////
function isValidCVVCode(ccType, cvvCount) {
	if ((ccType == "AMEX" && cvvCount == 4) || ((ccType == "DISCOVER" || ccType == "Master Card" || ccType == "VISA") && (cvvCount == 3)) ) {
		return true;
	} else {
		return false;
	}
}


         
//
//***
//* This javascript function is used by the address 'Submit' button.
//* It is used to ensure that the entered value does not exceed the maximum number of bytes allowed.
//* This function makes use of isValidUTF8length function.  Details about that function can be found in Util.js.
//***  
 	
   
	function submitForm(form)
	{
		 
		// submit the shipping address entered by the user
		if (!isValidUTF8length(form.address1.value, 50) 
		|| !isValidUTF8length(form.address2.value, 50))
		{
			/*
			<c:set var="warningMessage">
				<fmt:message key="ERROR_AddressTooLong" bundle="${storeText}" />
			</c:set>
			*/
			//alert("<c:out value="${warningMessage}" />");
		}
		else  
		{
		//alert("Before the form Submit--> To be removed in Util.js later.");   
			
			form.submit();
		}
	}   

	     
 // This function allows the user to enter the complete phone number without hitting tab. 
function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
} 
   

//This function checks for the char limit in a text box  
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	} // otherwise, update 'characters left' counter
	else {
		countfield.value = maxlimit - field.value.length;
	}
}

// this function will print the window
function printPage( myWindow) {
	myWindow.print();  
}

function openWindow(windowName, url) 
{
	 var width = 800;
	 var height = 600;
	 var left   = (screen.width  - width)/2;
	 var top    = (screen.height - height)/2;
	 var params = 'width='+width+', height='+height;
	 params += ', top='+top+', left='+left;
	 params += ', directories=no';
	 params += ', location=no';
	 params += ', menubar=yes';
	 params += ', resizable=yes';
	 params += ', scrollbars=yes';
	 params += ', status=no';
	 params += ', toolbar=no';
	 newwin = window.open(url, windowName, params);
	 if (window.focus) {newwin.focus()}
	 return false;
}

function formatCurrency(num, currencyChar) {
	if (currencyChar == null) {
		currencyChar = '$';
	}
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var 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)?'':'-') + currencyChar + num + '.' + cents);
}