//********************************************************************
//*-------------------------------------------------------------------
//* 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(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;
}

// Retrieves the value of the 'keyName' stored in 'cookieName'. If value is null then display "0".
function getIntegerValue(cookieName, keyName)
{
	var str = getUserCookieValue(cookieName, keyName);
	if(str == null)
		str = "0";
	return str;
}

// This script is used to display Items for cookie CVMINICART & balancePoints for CVREWRDPOINTS cookies
function displayIntegerValue(cookieName, keyName)
{
	//alert("IN displayCartItems method");
	document.write(getIntegerValue(cookieName, keyName));
}

// Retrieves 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.
function getAmountValue(cookieName, keyName)
{
	var str = getUserCookieValue(cookieName, keyName);
	if (str != null && str.length > 0)
	{
		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 str;
}

// This script is used to display Items amount total for cookie CVMINICART & balanceAmount for CVREWRDPOINTS cookies
function displayAmountValue(cookieName, keyName)
{
	//alert("IN displayCartItems method");
	document.write(getAmountValue(cookieName, keyName));
}

 var pairDelimiter = "~~~" ;
 var nameDelimiter = "@" ;
 
 function getUserCookieValue(cookieName, keyName)
{
 //alert("in getUserCookieValue");
 var cookieValue = getCookie(cookieName);
 //alert("cookieValue="+cookieValue);
  if ( cookieValue == null )
 	return null;
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;
}

function changeCookieValue(cookieName, keyName, newValue) {
	var curValue = getUserCookieValue(cookieName, keyName)
	var cookie = getCookie(cookieName);
	if (curValue == null || cookie == null)
		return null;
	document.cookie = cookieName + "=" + cookie.replace(curValue, newValue) + "; path=/";
}

function createMiniCartCookie(storeId, qty, total) {
	document.cookie = storeId + "_CVMINICART=items" + pairDelimiter + qty + nameDelimiter + "amount" + pairDelimiter + total + nameDelimiter + "; path=/";
}

function showInvalidateLink(url) {
	$("#invalidateLink").show();
	$("#invalidateLink a").attr("href", url);
}

//------------------------------------------------------------

/** @return true if the field's value is a valid quantity.  Alerts a message otherwise. */
function checkQuantity(field) {
	var s = field.value;
	if (s > 0 && s < 100) { // coercion to number will fail if input contains non-digits
		return true;
	}
	alert("Please enter a valid quantity value between 1 and 99.");
	return false;
}

var qoeSubmitted = false;

/** Submits the add-to-cart form with the indicated sku and (optional) quantity. */
function addToCart(sku, quantity) {
	if (qoeSubmitted) {
		return;
	}
	_resetAddToCartForm();
	_addToAddToCartForm(sku, quantity, 1);
	document.QuickOrderEntryForm.submit();
	qoeSubmitted = true;
}

/** 
 * Submits the add-to-cart form for all input elements classed "qoeQuantity" with a non-blank value.
 * Expects each element to also have a sku sttribute.
 */
function addAllToCart() {
	if (qoeSubmitted) {
		return;
	}
	
	_resetAddToCartForm();

	var i = 0;
	$(".qoeQuantity").each(function(index, e) {
		i++;
		trimMe(e);
		if (e.value.length > 0) {
			_addToAddToCartForm(e.getAttribute('sku'), e.value, i);
			qoeSubmitted = true;
		}
	});
	
	if (qoeSubmitted) {
		document.QuickOrderEntryForm.submit();
	} else {
		alert("Please enter a quantity for at least one item.");
	}
}

function _resetAddToCartForm() {
	$("#QuickOrderEntryForm :input[name^=sku_]").remove();
	$("#QuickOrderEntryForm :input[name^=quantity_]").remove();
}

function _addToAddToCartForm(sku, quantity, index) {
	var skuField = document.createElement("input");
	skuField.setAttribute("name", "sku_" + index);
	skuField.setAttribute("type", "hidden");
	skuField.setAttribute("value", sku);
	document.QuickOrderEntryForm.appendChild(skuField);
	
	var quantityField = document.createElement("input");
	quantityField.setAttribute("name","quantity_" + index);
	quantityField.setAttribute("type", "hidden");
	quantityField.setAttribute("value", quantity ? quantity : 1);
	document.QuickOrderEntryForm.appendChild(quantityField);
}

//------------------------------------------------------------
function submitEmailSignUpForm(e) {
	var key = e ? e.keyCode || e.which : 13;
	if (key == 13) {
		var email = document.getElementById('recipient').value;			
		if (email == '' || !isValidEmail(email)) {
			document.getElementById("emailSignUpError").innerHTML = '<font color="red">Please enter a valid email address.<\/font><br /><br />';
		} else {
			document.emailSignUpForm.submit();
		}
	}
	return false;
}

//------------------------------------------------------------
/** 
 * Populates the options for state dropdown, on receiving the country name as input
 * It also calls showOrHideState to show/hide the state dropdown from user
 */
function populateStates(country)
{
				

	$('#addrErrors').hide();

	
	var selectedCountryId=country.options[country.selectedIndex].value;
	
	populateStatesOptions(selectedCountryId, country.form, 'state');
	
	showOrHideState(selectedCountryId);
	var formname = country.form.name;
	
	if((selectedCountryId=='USA')||(selectedCountryId=='CAN'))
	{
		
	  $('.moreStreets').hide();
	  document.getElementById("streetaddr2").value = "";
	  document.getElementById("streetaddr3").value = "";
	  document.getElementById("streetaddr4").value = "";	  			
	}else{
		$('.moreStreets').show();

	}
}

/** 
 * Populates the options for state dropdown, on receiving the country name as input
 **/	
function populateStatesOptions(selectedCountryId,form,stateid)
{

	var ajaxOptions = {
		type: "POST",
		url: "CVProcessAddress",
		dataType: "json",
		data: "countryCode="+selectedCountryId,
		async: false,
		success: function(json)
		{
			var response = json.JSON;
			var stateToBePopulated = $('form[name='+form.name+'] :input[name="' + stateid +'"]');
		
			if( response[0] != null)
			{
				
				var tab = "11"
				stateToBePopulated.replaceWith('<select tabindex="' + tab +'" id="' + stateid + '"  name="' + stateid +'" value="" ></select>');
				
				var stateElement = document.getElementById(stateid);
			
				for(var i=0; response[i] != null; i++)
				{
					var stateProvince = response[i];
					stateElement.options[i] = new Option(stateProvince[1], stateProvince[0]);
				}
			}
		}
	}	
	
	$.ajax(ajaxOptions);
}
/** 
 * It shows/hides the state dropdown from user
 **/	
function showOrHideState(country) {
				if (country == "USA" || country == "CAN") {
					$("#zipRequired").show();
					$("#state_tr").show();
					$("#state").focus();
					$("#state").select();
				} else {
					$("#zipRequired").hide();
					$("#state_tr").hide();
					$("#zipCode").focus();
					$("#zipCode").select();
				}
}

