//********************************************************************
//*-------------------------------------------------------------------
//* 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);
	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('BordersForgotUserNameCmd') == 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 openWindow(url)
{
	op = window.open(url,"window","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resize=0,width=516,height=550");
}

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;
}

//Function used to clear init display message.
//Used as of on sharePage.jsp 
function clearInitText (obj,initMsg){

	if (obj.value == initMsg)
	{
		obj.value="";
	}
}

function check_length(maxchars,element){
	var msgText = document.getElementById(element);
	var len = msgText.value.length;
		if (len > maxchars) {
	    	msgText.value = msgText.value.substr(0,maxchars);
	        len = maxchars;
		}
	   // document.getElementById('wordcount').innerHTML = len;
	   // document.getElementById('remaining').innerHTML = maxchars - len;
}

	
//////////////////////////////////////////////////////////
// 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" || ccType == "VISA") && (cvvCount == 3)) ) {
		return true;
	} else {
		return false;
	}
}

function changeToLowerCase(element)
{
	return element.toLowerCase();
}

//**Start of Ajax calls to get user info**//
//setup the ajax call to retrieve user info
var cookie_email = "borders_email";
var cookie_firstName = "borders_fName";
var cookie_encodedUserId = "borders_encodedUserId";
var cookie_loggedIn = "borders_loggedIn";
var cookie_miniCart = "miniCartInfo";
var cookie_userId = "borders_userId";
var cookie_eCookies = "borders_eCookies";
var wc_userId = getUserIdFromWCCookie();
eraseUserCookies();
var ajx_userEmail = readCookie(cookie_email);
var ajx_userFirstName = readCookie(cookie_firstName);
var ajx_loggedIn = readCookie(cookie_loggedIn);
var ajx_userId = readCookie(cookie_userId);
var ajx_encodedUserId = readCookie(cookie_encodedUserId);
function setUserEmail(emailId){
	//alert("inside setUserEmail(" + emailId + ")");
	//alert("ajx_userEmail: " + ajx_userEmail);
	if( !isUserGeneric() ){
		if( ajx_userEmail && ajx_userEmail != "" ){
			$(emailId).value = ajx_userEmail;
			
		}
		else  {
			var url = "ajax/userInfo.jsp";
			var myAjax = new Ajax.Request(url, 
				{	 
					onSuccess: getUserInfoFromResponse, 
					onComplete: function(){$(emailId).value = ajx_userEmail;}}
				);
		}
	}
}

//sets the user name on a page. Takes in an array of Ids. to call: setUserFirstName(["id1","id2"]);
function setUserFirstName(firstNameIdArray){
	//alert("inside setUserFirstName(" + firstNameId + ")");
	//alert("ajx_userFirstName: " + ajx_userFirstName);
	if( !isUserGeneric() ){
		if( ajx_userFirstName && ajx_userFirstName != "" ){
			updateUserName(ajx_userFirstName,firstNameIdArray);
		}
		else {
			var url = "ajax/userInfo.jsp";
			var myAjax = new Ajax.Request(url, 
				{	 
					onSuccess: getUserInfoFromResponse, 
					onComplete: function(){updateUserName(ajx_userFirstName,firstNameIdArray);}
				});
		}
	}
}

//update user names
function updateUserName(srcUserName, destIdArray){
	for( var i=0; i<destIdArray.length; i++ ){
		$(destIdArray[i]).innerHTML = srcUserName;
		//alert("firstname : " + ajx_userFirstName);
	}
}

//parse response for user info ajax request, currently only email address is being parsed.
function getUserInfoFromResponse(Response){
	//alert("getUserInfoFromResponse");
	var user = Response.responseXML.getElementsByTagName("user");
	ajx_userId = user[0].getElementsByTagName("userId")[0].firstChild.nodeValue;
	if( ajx_userId == "-1002" ){
		//alert("bad user id");
		eraseUserCookies();
	}
	else{
		//alert("good user id");
		ajx_loggedIn = user[0].getElementsByTagName("loggedIn")[0].firstChild.nodeValue;
		ajx_loggedIn = user[0].getElementsByTagName("loggedIn")[0].firstChild.nodeValue;
		if( ajx_userEmail = user[0].getElementsByTagName("email")[0].firstChild ){
			ajx_userEmail = user[0].getElementsByTagName("email")[0].firstChild.nodeValue;	
		}
		ajx_userFirstName = user[0].getElementsByTagName("firstName")[0].firstChild.nodeValue;
		ajx_encodedUserId = user[0].getElementsByTagName("encodedUserId")[0].firstChild.nodeValue;
		
		createCookie(cookie_email, ajx_userEmail);
		createCookie(cookie_firstName, ajx_userFirstName);
		createCookie(cookie_loggedIn, ajx_loggedIn);
		createCookie(cookie_encodedUserId, ajx_encodedUserId);
		createCookie(cookie_userId, ajx_userId);
		createCookie(cookie_eCookies, 'false');
		//alert("user first name set: " + ajx_userFirstName);
	}
}

//reset user cookies info if the user is generic
function eraseUserCookies(){
	if( isUserGeneric() || (readCookie(cookie_eCookies)!=null && readCookie(cookie_eCookies)=='true')){
		//delete user cookies
		eraseCookie(cookie_email);
		eraseCookie(cookie_firstName);
		eraseCookie(cookie_userId);
		eraseCookie(cookie_encodedUserId);
		eraseCookie(cookie_loggedIn);
		if(isUserGeneric())
		{	eraseCookie(cookie_miniCart);}
		eraseCookie(cookie_eCookies);
	}
}
function isUserGeneric(){
	var isUserGeneric = (wc_userId != null && wc_userId == "-1002");
	return isUserGeneric?true:(getUserIdFromWCCookie()=="-1002");
}

//returns true if user is registered, false if not
function isRegUserId(aString){
	var numaric = aString;
	for(var j=0; j<numaric.length; j++){
		var aChar = numaric.charAt(j);
		var ascii = aChar.charCodeAt(0);
		if(!(ascii > 47 && ascii < 58)){
			return false;
		}
	}
 	return true;
}

//get user Id from cookie
function getUserIdFromWCCookie() {
	var WCCookieMask = "WC_USERACTIVITY_";
	var genericUserId = "-1002";
	var returnUserId = null;
	var WCCookieMaskLength = WCCookieMask.length;
	var cookieArray = document.cookie.split(';');

	for(var i=0; i < cookieArray.length; i++) {
		var cookie = cookieArray[i];
		while (cookie.charAt(0)==' ') cookie = cookie.substring(1,cookie.length);
		if (cookie.substring(0,WCCookieMaskLength) == WCCookieMask ) {
			var c_nameEndIndex = cookie.indexOf("=");
			var cookieName = cookie.substring(0,c_nameEndIndex);
			var userId = cookieName.substring(WCCookieMaskLength,c_nameEndIndex);
			if (isRegUserId(userId)){
				returnUserId = userId;
			}
			else{
				returnUserId = genericUserId;
			}
		}
	}
	if(returnUserId==null)
	returnUserId = readCookie("borders_userId");
	
	//alert("userId="+returnUserId);
	return returnUserId;
}


    function decode(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
    
    
  function bzBvpage(bvpage){
  
  		var decodedbvPage= decode(bvpage);
  		var idx = -1;
	    var encodedUserId = readCookie('borders_encodedUserId');
	    var rtnBVPage = null;
	    
      	if(decodedbvPage != null && decodedbvPage.length > 0)
				{
					 idx = decodedbvPage.indexOf("user=");
					 if (idx > -1)
					 {
					 	var userStr = decodedbvPage.substring(idx+5);
						
					 	if(userStr != null && userStr.length > 0)
					 	{
					 		var idx1 = userStr.indexOf("&"); //do we need to verify the decoded form here.
					 		
					 		if(idx1 > -1)
					 		{
					 			var regexStr = userStr.substring(0,idx1);
					 			if (regexStr != null && regexStr.length > 0)
					 			{
					 				rtnBVPage=bvpage.replace(regexStr,encodedUserId);
						 						
					 			}
					 		}
					 	}	
					}
					 	
				}
			return 	rtnBVPage;
  }  