// Test is the given string is made of all whitespace (includes empty string)
function isWhitespace(string)
{
	var ch;
	var isWhitespace = true;
	
	// Beware of undefined input.
	if ( !string ) { return true; }

	for (i = 0; i < string.length; i++) {
		ch = string.charAt(i);
		if ( ch != ' ' ) {
			isWhitespace = false;
			break;
		}
	}
	
	return isWhitespace;
}

// Trim off whitespace from the left side of the given string
function leftTrim(string)
{
	var ch;
	
	// Beware of empty string
	if ( isWhitespace(string) ) { return ''; }
	
	// Start scanning from the left end of the string
	for (i = 0; i < string.length; i++) {
		ch = string.charAt(i);
		if ( ch == ' ' ) {
			// We have encountered nothing but whitespace.  Keep going.
			continue;
		} else {
			// We encountered the first non-whitespace character.
			// Return the rest of the string.
			return string.substring(i);
		}
	}
	
}

// Trim off whitespace from the right side of the given string
function rightTrim(string)
{
	var ch;

	// Beware of empty string
	if ( isWhitespace(string) ) { return ''; }
	
	// Javascript's for...loop can only increment.
	// However we need to scan the string backwards.
	var index = string.length - 1;
	for (i = 0; i < string.length; i++) {
		ch = string.charAt(index);
		if ( ch == ' ' ) {
			// We have encountered nothing but whitespace.  Keep going.
			index--;
			continue;
		} else {
			// We encountered the first non-whitespace character.
			// Return the rest of the string.
			return string.substring(0, index+1);
		}
	}
}

// Trim off whitespace from both sides of the given string
function trim(string)
{
	return rightTrim(leftTrim(string));
}


function existEmbeddedWhitespace(string)
{
	var trimmedString = trim(string);
	
	if ( trimmedString.indexOf(' ') == -1 ) {
		return false;
	} else {
		return true;
	}
}


function isNumber(string)
{
	// Beware of empty string
	if ( isWhitespace(string) ) { return false; }

	if ( isNaN(trim(string)) ) {
		return false;
	}
	
	return true;
}


function isInteger(string)
{
	if ( isNaN(string) ) { return false; }
	
	var intString = parseInt(string);
	
	if ( intString == string ) {
		return true;
	}
	else {
		return false;;
	}
}


// Determine if all characters in 'string1' is found within 'string2'
function isAllCharsInStringValid(string1, string2)
{
	// Watch out for undefined or empty inputs
	if ( !string1 || string1 == '' ) { return false; }
	if ( !string2 || string2 == '' ) { return false; }
	
	var ch;
	
	// Loop through 'string1' and inspect each character
	for (i = 0; i < string1.length; i++) {
		ch = string1.charAt(i);
		// If a character is not found in 'string2'.  Return false.
		// Else continue to work on the next character.
		if ( string2.indexOf(ch) == -1 ) {
			return false;
		}
	}
	
	// Scanned through 'string1' and all characters are OK.
	return true;
}


// Determine the number of times 'ch' appears in 'string'
function countCharInString(ch, string)
{
	var count = 0;		// Initialize the count variable

	// Watch out for undefined or empty inputs
	if ( !ch || ch == '' ) { return count; }
	if ( !string || string == '' ) { return count; }
	
	for (i = 0; i < string.length; i++) {
		if ( ch == string.charAt(i) ) { 
			// Increment the count every time there is a match
			count++; 
		}
	}
	
	return count;
}


function isEmail(string)
{
	var validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWKYZ.-_!1234567890';
	var trimmedString;
	
	// Reject empty string or string with all whitespace
	if ( isWhitespace(string) ) { 
		// alert('All whitespace');  
		return false; 
	}
	
	// Trim the input string.  The trimmed input string is the copy we can start working with.
	trimmedString = trim(string);
	
	// There must be exactly one '@' character in the string.  No more and no less.
	if ( countCharInString('@', trimmedString) != 1 ) { 
		// alert('No @ or too many @ in email');  
		return false; 
	}
	
	// The '@' sign may not be at either end of the string
	var position = trimmedString.indexOf('@');
	if ( position == 0 || position == trimmedString.length - 1 ) { 
		// alert('@ at either end of usename');  
		return false; 
	}

	// Break the email into its username and domain components
	var tempArray;
	tempArray = trimmedString.split('@');
	var username = tempArray[0];  // alert('Username - (' + username + ')');
	var domain = tempArray[1];  // alert('Domain - (' + domain + ')');

	// Check that the username part of the email address is made up of valid characters
	if ( !isAllCharsInStringValid(username, validChars) ) { 
		// alert('Invalid character in username');  
		return false; 
	}

	// Check that the domain part of the email address is made up of valid characters
	if ( !isAllCharsInStringValid(domain, validChars) ) { 
		// alert('Invalid character in domain');  
		return false; 
	}

	// There must be at least one '.' in the domain
	if ( countCharInString('.', domain) < 1 ) { 
		// alert('No . in domain');  
		return false; 
	}
	
	// No '.' may be at the left or right end of domain
	position = domain.indexOf('.');
	if ( position == 0 || position == domain.length - 1 ) { 
		// alert('. at either end of domain');  
		return false; 
	}
	
	// Everything checked out.  Return true.
	return true;	
}


// Check if the given string constitutes a valid date
function isDate(string) 
{
	// Reject empty string or string with all whitespace
	if ( isWhitespace(string) ) { return false; }
	
	var millisec = Date.parse(trim(string));
	
	// alert(millisec + ' msec');
	
	if ( isNaN(millisec) ) {
		return false;
	}
	else {
		return true;
	}
}
function quotemeta (str) { 
// *     example 1: quotemeta(". + * ? ^ ( $ )"); 
// *     returns 1: '\. \+ \* \? \^ \( \$ \)' 
return (str+'').replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1'); 
}

//New added by Eddy 4/15/2011
//Phone number field
function formatTelNo (telNo)
{
    // If it's blank, save yourself some trouble by doing nothing.
    if (telNo.value == "") return;

    var phone = new String (telNo.value);
    
    phone = phone.substring(0,14);

    /*
    "." means any character. If you try to use "(" and ")", the regular expression becomes 
    complicated sice both are reserve characters and escaping them sometimes fails. So just 
    use "." for any character and replace it later.
    */
    if (phone.match (".[0-9]{3}.[0-9]{3}-[0-9]{4}") == null)
    {
        /*
        Following "if" is for user making any changes to the formatted tel. no. If you don't put this 
        "if" condition, the user can not correct a digit by first deleting it and then entering a 
        correct one, since this will fire two "onkeyup" events : first one on deleting a 
        character and second one on entering the correct one. The first "onkeyup" event will fire this 
        function which will reformatt the tel no before the user gets a chace to correct the digit. This 
        will surely confuse the user. The "if" condition below eliminates that.
        */
        if (phone.match (".[0-9]{2}.[0-9]{3}-[0-9]{4}|" + ".[0-9].[0-9]{3}-[0-9]{4}|" +
            ".[0-9]{3}.[0-9]{2}-[0-9]{4}|" + ".[0-9]{3}.[0-9]-[0-9]{4}") == null)
        {
            /*
            You will reach here only if the user is still typing the number or if he/she has 
            messed up already formatted number. 
            */
            var phoneNumeric = phoneChar = "", i;
            // Loop thru what user has entered.
            for (i=0;i<phone.length;i++)
            {
                // Go thru what user has entered one character at a time.
                phoneChar = phone.substr (i,1);
    
                // If that character is not a number or is a White space, ignore it. Only if it is a digit, 
                // concatinate it with a number string.
                if (!isNaN (phoneChar) && (phoneChar != " ")) phoneNumeric = phoneNumeric + phoneChar;
            }
    
            phone = "";
            // At this point, you have picked up only digits from what user has entered. Loop thru it.
            for (i=0;i<phoneNumeric.length;i++)
            {
                // If it's the first digit, throw in "(" before that.
                if (i == 0) phone = phone + "(";
                // If you are on the 4th digit, put ") " before that.
                if (i == 3) phone = phone + ") ";
                // If you are on the 7th digit, insert "-" before that.
                if (i == 6) phone = phone + "-";
                // Add the digit to the phone charatcer string you are building.
                phone = phone + phoneNumeric.substr (i,1)
            }
        }
    }
    else
    { 
        // This means the tel no is in proper format. Make sure by replacing the 0th, 4th and 8th character.
        phone = "(" + phone.substring (1,4) + ") " + phone.substring (5,8) + "-" + phone.substring(9,13); 
    }
    // So far you are working internally. Refresh the screen with the re-formatted value.
    if (phone != telNo.value) telNo.value = phone;
}
//New added by Eddy 4/15/2011
function checkTelNo (telNo)
{
    if (telNo.value == "") return;
    if (telNo.value.match (".[0-9]{3}.[0-9]{3}-[0-9]{4}") == null)
    {
        if (telNo.value.match ("[0-9]{10}") != null)
            formatTelNo (telNo)              
    }
}

//New added by Eddy 4/15/2011
//XMLHttpRequest class function
function datosServidor() {
};
datosServidor.prototype.iniciar = function() {
	try {
		// Mozilla / Safari
		this._xh = new XMLHttpRequest();
	} catch (e) {
		// Explorer
		var _ieModelos = new Array(
		'MSXML2.XMLHTTP.5.0',
		'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
		);
		var success = false;
		for (var i=0;i < _ieModelos.length && !success; i++) {
			try {
				this._xh = new ActiveXObject(_ieModelos[i]);
				success = true;
			} catch (e) {
			}
		}
		if ( !success ) {
			return false;
		}
		return true;
	}
}

datosServidor.prototype.ocupado = function() {
	estadoActual = this._xh.readyState;
	return (estadoActual && (estadoActual < 4));
}

datosServidor.prototype.procesa = function() {
	if (this._xh.readyState == 4 && this._xh.status == 200) {
		this.procesado = true;
	}
}

datosServidor.prototype.enviar = function(urlget,datos) {
	if (!this._xh) {
		this.iniciar();
	}
	if (!this.ocupado()) {
		this._xh.open("GET",urlget,false);
		this._xh.send(datos);
		if (this._xh.readyState == 4 && this._xh.status == 200) {
			return this._xh.responseText;
		}
		
	}
	return false;
}

//New added by Eddy 4/15/2011
function addValueToFields(theForm){
	
	var remotos;
	var nt;
	// Go through all form feilds to see if we can find values for them
	var theform, elements, i, elm; 
	theform = document.getElementById ? document.getElementById(theForm) : document.forms[theForm]; 
	if (document.getElementsByTagName)
	{
		//Only 3 types of form elements will be checked.
		// input type where type="text"
		// all select fields
		// and textarea fields
		elements = document.getElementsByTagName("input");
		elements2 = document.getElementsByTagName("select");
		elements3 = document.getElementsByTagName("textarea");
		for( i=0, elm; elm=elements.item(i++); )
		{ 
			
			if (elm.getAttribute('type').toLowerCase()  == "text")	{
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					elm.value = nt;
					}
				}
			if (elm.getAttribute('type').toLowerCase()  == "checkbox")	{
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					for (x=0; x < elm.length;x++)
						{
						if (elm.options[x].value==nt)elm.options[x].checked=true;
						}
					}
				}
			if (elm.getAttribute('type').toLowerCase()  == "radio")	{
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					for (x=0; x < elm.length;x++)
						{
						if (elm.options[x].value==nt)elm.options[x].checked=true;
						}
					}
				}
		}
		for( i=0, elm; elm=elements2.item(i++); )
		{ 
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					for (x=0; x < elm.length;x++)
						{
						if (elm.options[x].value==nt)elm.options[x].selected=true;
						}
					}
		}
		for( i=0, elm; elm=elements3.item(i++); )
		{ 
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					elm.value = nt;
					}
		}
		
	}
	else
	{
		elements = theform.elements;
		for( i=0, elm; elm=elements[i++]; )
		{
			if (elm.type.toLowerCase() == "text")
			{
				remotos = new datosServidor;
				nt = remotos.enviar("/js/lookup.asp?fieldname=i&content="+elm.name,"");
				if (nt != "") {
					elm.value = nt;
					}
			}
		}
	}

}
var navigatorName = navigator.appName;
var isIE;
var isNetscape;
var appVersion = parseInt(navigator.appVersion);

if (navigatorName == 'Microsoft Internet Explorer')
{
	isIE = true;
	isNetscape = false;
}
else
{
	isIE = false;
	isNetscape = true;
}
var platform = navigator.platform;

function GetKeyCode(eventParams)
{
	if (isIE == true)
	{
		return eventParams.keyCode;
	}
	else
	{
		return eventParams.which;
	}
	
}

function GetDocumentObjectReference(elementID)
{
	return eval("document." + elementID);
}
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
  var keyCode = (isNN) ? e.which : e.keyCode; 
  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
  
  if(input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
    input.form[(getIndex(input)+1) % input.form.length].focus();
  }

  function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
    else
    index++;
    return found;
  }

  function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
  }
  return true;
}
function NumOnlyKeyPress(inputValue, exceptions, delimiter)
{
	/***************************************************************************/
	/* NumOnlyKeyPress
	/*
	/* Determines if the specified input data value is 'allowable' based on 
	/* whether it is either numeric OR matches an entry in the exception array.
	/*
	/* WARNING:  Exceptions MUST be defined using their ASCII character code.
	/***************************************************************************/

	// Define variables
	var counter = 0;
	var found = false;
//	var exceptionList;

	// Tack all numeric codes(48-57)and the Backspace(8) to the exceptions
	exceptions += delimiter + "8" + delimiter + "48" + delimiter;
	exceptions += "49" + delimiter + "50" + delimiter + "51" + delimiter;
	exceptions += "52" + delimiter + "53" + delimiter + "54" + delimiter;
	exceptions += "55" + delimiter + "56" + delimiter + "57";
	var exceptionList = exceptions.split(delimiter);

	// Loop through the exceptions list and test for an occurrence.  If the value
	// matches one in the exception list, the function returns true, else false.
	for (counter = 0; counter <= exceptionList.length; counter++)
	{
		if (inputValue == Number(exceptionList[counter]))
		{
			found = true;
			break;
		}
	}
	return found;
}


