//********************************************************************
//*-------------------------------------------------------------------
//* 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
// VC: Updated as code I got from net is validating more conditions
// Return true if the email address is valid; false otherwise
//////////////////////////////////////////////////////////
function isValidEmail(email){
	var at = email.lastIndexOf("@");

	// Make sure the at (@) sybmol exists and  
	// it is not the first or last character
	if (at < 1 || (at + 1) === email.length)
		return false;

	// Make sure there aren't multiple periods together
	if (/(\.{2,})/.test(email))
		return false;

	// Break up the local and domain portions
	var local = email.substring(0, at);
	var domain = email.substring(at + 1);

	// Check lengths
	if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
		return false;

	// Make sure local and domain don't start with or end with a period
	if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
		return false;

	// Check for quoted-string addresses
	// Since almost anything is allowed in a quoted-string address,
	// we're just going to let them go through
	if (!/^"(.+)"$/.test(local)) {
		// It's a dot-string address...check for valid characters
		if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
			return false;
	}

	// Make sure domain contains only valid characters and at least one period
	if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
		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;
}


// 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 = "0";
	str = getUserCookieValue(cookieName, keyName);
	if(str == null)
		str = "0";
	document.write(str);
}

function displayCheckOutButton(cookieName, keyName)
{
	//alert("IN displayCartItems method");
	var str = "0";
	str = getUserCookieValue(cookieName, keyName);
	if(str == null)
		str = "0";
	if ((str != "0") && (str != "0.00"))
	{
		$('#checkout_button').css('display','block');
	}
}

function getIntegerValue(cookieName, keyName) {
	var str = "0";
	str = getUserCookieValue(cookieName, keyName);
	
	if(str == null) {
		str = "0";
	}
	str=str+" ";
	return 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 = "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";
	}
	
	document.write(str);
}

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 str;
}

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;
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" + value +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
// this deletes the cookie when called
function EraseVehicle_Cookie( ) {
	if ( Get_Cookie( "AAP_VEHICLE_DESC" ) ) document.cookie = "AAP_VEHICLE_DESC=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
	
	if ( Get_Cookie( "AAP_VEHICLE_ID" ) ) document.cookie = "AAP_VEHICLE_ID=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
	
	if ( Get_Cookie( "AAP_VEHICLE_CODE" ) ) document.cookie = "AAP_VEHICLE_CODE=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
	
	if ( Get_Cookie( "AAP_VEHICLE_META" ) ) document.cookie = "AAP_VEHICLE_META=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// this deletes the cookie when called
function SetVehicle_Cookie( vehicle_ID, vehicle_Desc,vehicle_Code, vehicle_meta) {
	Set_Cookie( "AAP_VEHICLE_ID", vehicle_ID, 365*35, "", "", "");
	Set_Cookie( "AAP_VEHICLE_DESC", vehicle_Desc, 365*35, "", "", "");
	Set_Cookie( "AAP_VEHICLE_CODE", vehicle_Code, 365*35, "", "", "");
	Set_Cookie( "AAP_VEHICLE_META", vehicle_meta, 365*35, "", "", "");
}


// VC: Function to validate numeric text

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
	 {
	 IsNumber = false;
	 }
      }
   return IsNumber;
}


function getURLParameter( key )
{
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+key+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function validateZIP(zipCode) 
{
	var valid = "0123456789";
	var hyphencount = 0;

	if ( zipCode.length != 5 ) {
		return false;
	}
	for ( var i=0; i < zipCode.length; i++ )
	{
		if ( valid.indexOf(zipCode.charAt(i)) == "-1" ) {
			return false;
		}
	}
	return true;
}

function Only_Num(id)
{	
	if(isNaN(id.value)) {	  
		id.value='';
		id.focus();	  
	}
	return;
}
