//********************************************************************
//*-------------------------------------------------------------------
//* Licensed Materials - Property of IBM
//*
//* 5724-A18
//*
//* (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 function to validate an email address
// It does not allow double byte characters
// Source from www.breakingpar.com
//
// strEmail = the email address string to be validated
// Return true if the email address is valid; false otherwise
//////////////////////////////////////////////////////////
function isValidEmail(emailAddress) 
{
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(emailAddress);
}

//////////////////////////////////////////////////////////
// A function to validate ISBN length
// Valid ISBN length is either 10 or 13 
//////////////////////////////////////////////////////////
 function isValidateISBNLength(isbn) 
  {
  	if (isbn == null){
  		return false;
  	}
  	
  	isbn = Trim(isbn);
  	if(!(isbn.length == 10 || isbn.length == 13)) {
  		return false;
  	} else {
  		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;
}

function doubleClkCheck() 
{
	var buttonStatus = event.srcElement.clicked;
    if (buttonStatus == 'true')
    {
    	return false;
    }
    else 
    {
        event.srcElement.clicked = "true";
        return true;
    }
}

function doubleClkCheckXBrowser(obj)
{
	var buttonStatus = obj.clicked;
    if (obj.clicked)
    {
    	return false;
    }
    else 
    {
        obj.clicked = true;
        return true;
    }
}

/* 
*  Function multElementDoubleClkCheck is used to prevent 
*  multiple clicks spanning elements on a single page
*  that might start multiple commands or the same 
*  command multiple times.
*/   

var anElementAlreadyClicked = false;
function multElementDoubleClkCheck() {
	//alert("multElementDoubleClkCheck()=" + anElementAlreadyClicked);
	if (!anElementAlreadyClicked ) {
		anElementAlreadyClicked  = true;
		return true;
	}
	return false;
}
function multElementDoubleClkCheckReset() {
	anElementAlreadyClicked  = false;
}

/* 
*  Function RTrim gets rid of the trailing spaces 
*  for a string.
*  
*  return a trimmed string
*/   

function RTrim(oString)
{
    if(oString == null || oString.length == 0) return;

    var len = oString.length;
    var whitespace = " \t\n\r";
          
    //get right most non blank char position
    for(j=len; j>=0; j--)
    {
        c = oString.charAt(j);
        if (whitespace.indexOf(c) == -1)
        {
            break;
        }
    }
    // get right trimmed string
    return (oString.substring(0,j+1));
}    

/* 
*  Function LTrim gets rid of the leading spaces 
*  for a string.
*  
*  return a trimmed string
*/   

function LTrim(oString)
{
    if(oString == null || oString.length == 0) return;
    
    var len = oString.length;
    var whitespace = " \t\n\r";
          
    //get leftmost non blank char position
    for(i=0; i<len; i++)
    {
        c = oString.charAt(i);
        if (whitespace.indexOf(c) == -1)
        {
            break;
        }
    }
    // get right trimmed string
    return (oString.substring(i));
}    

/* 
*  Function Trim gets rid of the leading and trailing spaces 
*  for a string.
*  
*  return a trimmed string
*/   
function Trim(str)
{
   return RTrim(LTrim(str));
}

function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

function removeDashes(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split("-");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

function selectFirst(id) {
	if(document.getElementById(id) != null) {
		document.getElementById(id).options[0].selected = true
	}
}

function hideLayer(id) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.display = 'none';
  	document.getElementById(id).style.visibility = 'hidden';
  }
}
function showLayer(id) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.display = 'block';
  	document.getElementById(id).style.visibility = 'visible';
  }
}

function showLayerADA(id, leftLocation) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.display = 'block';
  	document.getElementById(id).style.left = leftLocation;
  }
}

function hideLayerADA(id) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.display = 'none';
  	document.getElementById(id).style.left = '-10000px';
  }
}

function hideLayerNoBlock(id) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.visibility = 'hidden';
  }
}
function showLayerNoBlock(id) {
  if(document.getElementById(id) != null) {
  	document.getElementById(id).style.visibility = 'visible';
  }
}
function updateStateProvInput(addrType)
	{
		var countryId = addrType+'country';
		var countryCode = document.getElementById(countryId).value; 
		var OTHER = addrType+'state_OTHER';
		var US = addrType+'state_US';
		var CA = addrType+'state_CA';
		var otherLabel = addrType+'state_OTHER_label';		
		var caLabel = addrType+'state_CA_label';
		var usLabel = addrType+'state_US_label';
		var zipReq = addrType+"zipReq";
		var usStateReq = addrType+"stateReq_US";
		var caStateReq = addrType+"stateReq_CA";
		var otherStateReq = addrType+"stateReq_OTHER";
		if(countryCode == "US") {
			hideLayer(OTHER);
			hideLayer(CA);
			showLayer(US);
			hideLayer(otherLabel);
			hideLayer(caLabel);
			showLayer(usLabel);
			showLayerNoBlock(zipReq);
			showLayerNoBlock(usStateReq);
			hideLayerNoBlock(caStateReq);			
			hideLayerNoBlock(otherStateReq);
		} else if (countryCode == "CA") {
			hideLayer(OTHER);
			showLayer(CA);
			hideLayer(US);
			hideLayer(otherLabel);
			showLayer(caLabel);
			hideLayer(usLabel);			
			showLayerNoBlock(zipReq);
			hideLayerNoBlock(usStateReq);
			showLayerNoBlock(caStateReq);
			hideLayerNoBlock(otherStateReq);
		} else {
			showLayer(OTHER);
			hideLayer(CA);
			hideLayer(US);
			showLayer(otherLabel);
			hideLayer(caLabel);
			hideLayer(usLabel);			
			hideLayerNoBlock(zipReq);
			hideLayerNoBlock(usStateReq);
			hideLayerNoBlock(caStateReq);
			hideLayerNoBlock(otherStateReq);
		}
	}
	
function correctStateProvSubmission(addrType) {
	var OTHER = addrType+'state_OTHER';
	var US = addrType+'state_US';
	var CA = addrType+'state_CA';
	var countryId = addrType+'country';
	var stateField;
	if(addrType == '') {
		stateField = 'state';
	} else {
		stateField = addrType+'State';
	}
		
	var countryCode = document.getElementById(countryId).value; 
	
	if(countryCode == "US") {
		document.getElementById(stateField).value = document.getElementById(US).value;
	} else if (countryCode == "CA") {
		document.getElementById(stateField).value = document.getElementById(CA).value;
	} else {
		document.getElementById(stateField).value = document.getElementById(OTHER).value;
	}
}

//////////////////////////////////////////////////////////
//
// Corrects Canadian zipcodes if the user doesn't put
// a space in the field
//
//////////////////////////////////////////////////////////
function correctZipCode(addrType, zipCodeId)
{
	var countryId = addrType+'country';

	var countryCode = document.getElementById(countryId).value; 
	
	if (countryCode == "CA") {
		if (document.getElementById(zipCodeId) != null) {
			var zipField = Trim(document.getElementById(zipCodeId).value);
			if (zipField != null && zipField.length == 6) {
				document.getElementById(zipCodeId).value = 
					zipField.substring(0,3) + ' ' + zipField.substring(3,6);
			}
		}
	}
}

//////////////////////////////////////////////////////////

// A function to validate that a postal code is a valid MPO

// postal code

//

// postalCode = the postal code string to be validated

// Return true if the postal code is valid; false otherwise

//////////////////////////////////////////////////////////

function isValidMPOPostalCode(postalCode) 

{

    var re = /^09\d{3}|340\d{2}|96\d{3}([\-]\d{4})?$/

    return re.test(postalCode);

}

 

//////////////////////////////////////////////////////////

// A function to validate that a city is a valid MPO city

//

// city = the city string to be validated

// Return true if the city is valid; false otherwise

//////////////////////////////////////////////////////////

function isValidMPOCity(city) 

{

    var re = /^(APO|FPO)$/

    return re.test(city);

}

 

//////////////////////////////////////////////////////////

// A function to validate that a state is a valid MPO state

//

// state = the state string to be validated

// Return true if the state is valid; false otherwise

//////////////////////////////////////////////////////////

function isValidMPOState(state) 

{

    var re = /^(AA|AE|AP)$/

    return re.test(state);

}

 

//////////////////////////////////////////////////////////

// A function to validate that an address is a valid MPO 

// address

//

// state = the state string to be validated

// city = the city string to be validated

// postalCode = the postal code string to be validated

// Return true if the address is valid; false otherwise

//////////////////////////////////////////////////////////

 

function isValidMPOAddress(state, city, postalCode)

{
      return isValidMPOState(state) && isValidMPOCity(city) && isValidMPOPostalCode(postalCode);

}


function isValidZipCode(country, zipCode) {
	zipCode = zipCode.toUpperCase();
	if(country == "US") {
		var re = /(^\d{5}$)|(^\d{5}-\d{4}$)/
		return re.test(zipCode);
	} else if(country == "CA") {
		var re = /^[ABCEGHJKLMNPRSTVXY][0-9][A-Z] ?[0-9][A-Z][0-9]$/
		return re.test(zipCode);
	}
	return true;
	 
	
}

function isValidAddress(city, state, zip, country, addressType) {
	
	if (isValidMPOState(state) && !isValidMPOAddress(state, city, zip)) {
			alert('Invalid MPO '+addressType+' address');
			return false;
		}
		if(!isValidZipCode(country, zip)) {
			alert('Invalid '+addressType+' zip code'+zip);
			return false;
		}
	return true;
}

/////////////////////////////////////////////////////////////
//
// AJAX in-house framework utility methods used on DDCS drill-down and Store Finder
//	 These methods below are an attempt to establishing a kind of home-grown 
//   AJAX framework for use on efollett.com. Below is common, shared functionality 
//   for DDCS drill-down and Store Finder
//
/////////////////////////////////////////////////////////////

/**
  Utility method which invokes ajax request with the supplied HTTP url parameters
  The AJAX-enabled page should have an iframe with id 'otherdata'. Also, an error 
  javascript method will be invoked upon errors
*/
function getData(params) {
  if(Ajax.getTransport()) {
  		new Ajax.Request(uri, {method: 'get', parameters: params, onFailure: error, onComplete: doneLoaded});
  }
}

/**
   This method is invoked after the ajax response is received.  The AJAX response is a JSON formated 
   text string with 2 parts - 'meta', and 'data'.  Note that the final step in the method will 
   invoke a javascript method called onXXX, where 'XXX' is a string specified in the 'request' 
   parameter, which is found in the meta section.  This method will be invoked with both the 
   meta and data values.
*/
function doneLoaded(data) {
  
  // 'Guard block' used to protect against interleaving AJAX requests and race conditions that result 
  clearAJAXTimer();
  if(AJAXLastSelection != null) {
    // Get the data for the last selected combo-box
    AJAXSelectTimerID = setTimeout(AJAXLastSelection, 200);
    AJAXLastSelection = null;
  }
  	
  // incoming data is JSON formatted text 
  if(data.responseText) {
     str = data.responseText.substring(data.responseText.indexOf('{'), data.responseText.lastIndexOf('}')+1);
  } 
  
  // replace/excape certain characters that confuse the Javascript JSON parser
  str = str.replace(/\n/g, "");
  str = str.replace(/\\/g, "\\\\");
  str = str.replace(/&amp;/g, "&");
  str = str.replace(/&quot;/g, '\\"');

  // Invoke the Javscript build-in JSON parser
  var contentArrayObj = eval('(' + str + ')');

  var data = contentArrayObj.data[0];
  var meta = contentArrayObj.meta[0];
  
  // Call the appropriate handler method based upon the request name
  eval('load' + meta.request + '(data,meta)');
}

/** 
  The below variables and functions are a piece of the AJAX 'guard' code which protects against 
    cases where combo-box selections are made very quickly - which can cause interleaving AJAX
    requests and race conditions.  See the 'doneLoaded()' method for the other half.
**/
var AJAXSelectTimerID = null; // javascript timer
var AJAXLastSelection = null; // holds the last selected item
function doAJAXSelect(selectedItem) {
  if(AJAXSelectTimerID == null) {
    AJAXSelectTimerID = setTimeout(selectedItem, 100);
  } else {
    AJAXLastSelection = selectedItem; // make sure we save the very last selection the user made
  }
}
function clearAJAXTimer() {
  clearTimeout(AJAXSelectTimerID);
  AJAXSelectTimerID = null;
}