
function getObj(name)
{
	if (document.getElementById)
	{
		this.obj = document.getElementById(name);
	}
	else if (document.all)
	{
		this.obj = document.all[name];
	}
	else if (document.layers)
	{
		this.obj = document.layers[name];
	}
}//function getObj(name)


////////////////////////////////////////////////////////////////////////////////////////////////
//// Trimming functions

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
////////////////////////////////////////////////////////////////////////////////////////////////

//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
function isNull(val){return(val==null);}

////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks if the field is empty. Takes a string with the name of the field to check.
////////////////////////////////////////////////////////////////////////////////////////////////
function isEmpty(txtFieldId){
	var field = new getObj(txtFieldId);
	if (trim(field.obj.value) == "")
		return true;
	else
		return false;

}


////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks that a certain VALUE is selected in a Selected box
////
//// @Param  objSelId  		Name of the Select object
//// @Param  value  		Value looked for<option value="value">
////
//// @Return boolean
//////////////////////////////////////////////////////////////////////////////////////////////// 

function isSelected(objSelId, value) {
	var oSel = new getObj(objSelId);
	if(oSel.obj.options[oSel.obj.selectedIndex].value==value){		
		return true;
	} else {		
		return false;
	}
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// This function received a SELECT object and returns an array with the index or indexes
//// of the selections made for the list. 
////
//// @Param  SELECT_OBJECT
////
//// @Return Array
////////////////////////////////////////////////////////////////////////////////////////////////

function getSelectedIndexes(selObj){
	if (selObj.type == 'select-one'){
	    return new Array(selObj.selectedIndex);
	} 
	else{
	    var indexes = new Array();
	    for (var i = 0; i < selObj.options.length; i++){
		    if (selObj.options[i].selected){
			    indexes.push(i);
		    }
	    }
	    return indexes;
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////
//// Uses the isSelected function to validate that the default values is NOT selected. If this is true then 
//// uses the div sent as a second parameter to display the message provided as a third parameter.
////////////////////////////////////////////////////////////////////////////////////////////////
function validateSelected(cmbFieldId, divId, defvalue, msg){
	var divCon = new getObj(divId);
	
	if (isSelected(cmbFieldId, defvalue) == true){
		divCon.obj.innerHTML = msg;
		return false;
	}
	else{
		divCon.obj.innerHTML = "";
		return true;
	}	
}







////////////////////////////////////////////////////////////////////////////////////////////////
//// Sets the txtField to a default text if no text is present
////////////////////////////////////////////////////////////////////////////////////////////////
function setDefaultText(txtField, strDefault){
	if(trim(txtField.value)=='')
		txtField.value = strDefault;
}

////////////////////////////////////////////////////////////////////////////////////////////////
//// Sets the txtField to no text if the default text is present
////////////////////////////////////////////////////////////////////////////////////////////////
function setNoText(txtField, strDefault){
	if(trim(txtField.value)==strDefault)
		txtField.value = ''; 
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks for a valid US Zip code
////////////////////////////////////////////////////////////////////////////////////////////////
function validateUSZipCode(str){
	var objRegExp = /(^\d{5}$)/;	
  	return objRegExp.test(str);
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks for a valid City name
////////////////////////////////////////////////////////////////////////////////////////////////
function validateCity(str){
	if(isAlphaNumeric(str))	
		return true;
	else
		return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks for a valid State name
////////////////////////////////////////////////////////////////////////////////////////////////
function validateState(str){
	var objRegExpState = /^(AA|AE|AE|AE|AE|AK|AL|AP|AR|AS|AZ|CA|CO|CT|DC|DE|FL|FM|GA|GU|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MH|MI|MN|MO|MP|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|PR|PW|RI|SC|SD|TN|TX|UT|VA|VI|VT|WA|WI|WV|WY){1}$/;
	return objRegExpState.test(str.toUpperCase());
}



////////////////////////////////////////////////////////////////////////////////////////////////
//// Checks for a valid City/State combination
////////////////////////////////////////////////////////////////////////////////////////////////
function validateCityState(str){	
	if (str.indexOf(',')!=-1){
		var strTmp = str.split(',');
		if(strTmp.length == 2){
			if(validateCity(trim(strTmp[0])) && validateState(trim(strTmp[1])))
				return true; 
			else
				return false; 
		}		
		else
			return false;
	}
	else 
		return false;
	
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string only contains characters A-Z, a-z,0-9 or White spaces
////////////////////////////////////////////////////////////////////////////////////////////////
function isAlphaNumeric(str){	
    str = stripInternationalCharacters(str); 
	var re = /[^\w\s]/g
	
	if (re.test(str)) 
		return false;
	return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string only contains characters A-Z, a-z,0-9
////////////////////////////////////////////////////////////////////////////////////////////////
function isAlphaNumericNoSpace(str){
    str = stripInternationalCharacters(str); 
    
	var re = /[^\w]/g
	
	if (re.test(str)) 
		return false;
	return true;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string is a username
////////////////////////////////////////////////////////////////////////////////////////////////
function isUserName(str){
    if (str.length >= 3){
	    var re = /[^\w]/g;
    	
	    if (re.test(str)) 
		    return false;
        else
	        return true;
	}
	else
	    return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string only contains characters A-Z, a-z,0-9 or White spaces or '.',',','!','?','-'
////////////////////////////////////////////////////////////////////////////////////////////////
function isAlphaNumericWithPunctuation(str){	
	str = str.replace(/[\!\.\,\?\+\-\&\#\:\;\*\@\$\%\(\)\`\'\"\[\]\{\}\^\~\/]/g, "");

	var re = /[^\w\s]/g;
	
	if (re.test(str)) 
		return false;
	return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string only contains characters A-Z, a-z or White spaces
////////////////////////////////////////////////////////////////////////////////////////////////
function isAlpha(str){	
    str = stripInternationalCharacters(str); 
	var re = /[^a-zA-Z\s]/g;
	if (re.test(str)) 
		return false;
	return true;
}



////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string only contains characters 0-9
//// @Param  str  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////
function isNumeric(str){
	var re = /[^0-9\s]/g
	if (re.test(str)) 
		return false;
	return true;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the phone number is valid
//// @Param  phone  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////
function isPhone(phone)
{	
	var fmtphone = trim(phone).replace(/ /g,"");	
	fmtphone = fmtphone.replace(/-/g,"");
	fmtphone = fmtphone.replace("(","");
	fmtphone = fmtphone.replace(")","");
	
	if(!isNumeric(fmtphone))
		return false;

	// 9999999
	if(fmtphone.length == 7)
	{
		if(phone.indexOf("-") != -1)
		{
			if(trim(phone).charAt(3) != '-')
				return false;
			else if(!isNumeric(trim(phone).replace("-","")))
				return false;
		}	
	}
	// 1112223333
	else if(fmtphone.length == 10)
	{
		if(phone.indexOf("(") != -1)
		{
			if(trim(phone).charAt(0) != '(' && trim(phone).charAt(4) != ')')
				return false;
			if(trim(phone).charAt(trim(phone).length-5) != '-')
				return false;		
		}
		else if(phone.indexOf("-") != -1)
		{
			// (111) 222-3333 or 111-222-3333 or 111 222-3333
			if(!(trim(phone).charAt(3) == '-' || trim(phone).charAt(3) == ' ') ||
			 trim(phone).charAt(trim(phone).length-5) != '-')
				return false;	
		}
	}
	// 18001112222 
	else if(fmtphone.length == 11)
	{
		var nospace = phone.replace(/ /g,"");
		
		if(phone.indexOf("(") != -1)
		{
			if(nospace.charAt(1) != '(' && nospace.charAt(4) != ')')
				return false;
			else if(nospace.charAt(nospace.length-5) != '-')
				return false;		
		}
		else if(phone.indexOf("-") != -1)
		{		
			if(!(trim(phone).charAt(1) == '-' || trim(phone).charAt(1) == ' ') || 
		 	!(trim(phone).charAt(5) == '-' || trim(phone).charAt(5) == ' ') ||
			nospace.charAt(nospace.length-5) != '-')
				return false;
		}
	}
	else
		return false;

	return true;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string has a correct email format
//// @Param  txtEmail  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////

function isEmail(txtEmail) {
	var objRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  //check for valid email
	if (objRegExp.test(txtEmail))
		return true;
	return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string has a correct Url format
//// @Param  txtUrl  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////

function isUrl(txtUrl) {
	//var objRegExp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
	var objRegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/; 
	  //check for valid url
	if (objRegExp.test(txtUrl))
		return true;
	return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// returns true if the string has a correct money format. Removes all $ and ',' + verifies the 
//// the amout of decimals used. 
//// @Param  txtMoney  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////


function isMoney(txtMoney){
	var bMoney = true;
	//var re = /^\$/g;
	
	// remove "$"
	var tmpMoney = txtMoney;
	//if there's no decimal point
	var tmpMoneyArr = tmpMoney.split(".");
	//No decimal point
	if (tmpMoneyArr.length == 1 ){ 		
		if(isNumeric(tmpMoneyArr[0]))
			bMoney = true;
		else
			bMoney = false
	}
	//1 decimal point
	else if(tmpMoneyArr.length == 2)
	{
		
		if(isNumeric(tmpMoneyArr[0]) && isNumeric(tmpMoneyArr[1]) && tmpMoneyArr[1] < 100 && tmpMoneyArr[1].length < 3)
			bMoney = true;
		else
			bMoney = false;
		
	}
	//more than 2 decimal points
	else
		bMoney = false;
	return bMoney;
	
}



////////////////////////////////////////////////////////////////////////////////////////////////
//// This function accepts a string variable and verifies if it is a
//// proper date or not. It validates format matching either
//// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
//// has the proper number of days, based on which month it is.
////
//// @Param  dateStr  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////

function isDate(dateStr) {

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {		
		return false;
	}

	month = matchArray[1]; // p@rse date into variables
	day = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12) { // check month range
		return false;
	}

	if (day < 1 || day > 31) {
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap))
		return false;
	}
	return true; // date is valid
}



////////////////////////////////////////////////////////////////////////////////////////////////
//// This function removes all the vowel accents and returns the string without them. 
//// 
////
//// @Param  str the text to validate
////
//// @Return str without vowel accents
////////////////////////////////////////////////////////////////////////////////////////////////
function stripInternationalCharacters(str)
{
	//À,Á,Â,Ã,Ä,Å,Æ
	str=str.replace(/[\xC0-\xC6]/g, "A");
	//à,á,â,ã,ä,å,æ
	str=str.replace(/[\xE0-\xE6]/g, "a");
	//È,É,Ê,Ë	
	str=str.replace(/[\xC8-\xCB]/g, "E");
	//è,é,ê,ë
	str=str.replace(/[\xE8-\xEB]/g, "e");
	//Ì,Í,Î,Ï
	str=str.replace(/[\xCC-\xCF]/g, "I");
	//ì,í,î,ï
	str=str.replace(/[\xEC-\xEF]/g, "i");
	//Ò,Ó,Ô,Õ,Ö,Ø
	str=str.replace(/[\xD2-\xD8]/g, "O");
	//ò,ó,ô,õ,ö,ø
	str=str.replace(/[\xF2-\xF8]/g, "o");
	//Ù,Ú,Û,Ü
	str=str.replace(/[\xD9-\xDC]/g, "U");
	//ù,ú,û,ü
	str=str.replace(/[\xF9-\xFC]/g, "u");	
	return str;	
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// @Param  txtFieldId  		Id (string) of the textfield object 
//// @Param  divId  			Id (string) of the div to show the msg if the validation shows true
//// @Param  datatype	  		Name of the datatype (string). Options include: "alphanum", "number", "phone", "ccard", "money", "date"
//// @Param  msg			Message to display in the DIV.
//// @Param  brequired			Boolean that toggles if the textfield is required or not. 
////
//// @Return boolean			false is validation happened. true is field is OK. 
////////////////////////////////////////////////////////////////////////////////////////////////

function validateTextfield(txtFieldId, divId, datatype, msg, brequired){	
	var divCon = new getObj(divId);
	var txtField = new getObj(txtFieldId);
	var bReturn = true; 
	
	//if it's empty
	if(isEmpty(txtFieldId)){
		//if the field is required and it's empty
		if(brequired){
			divCon.obj.innerHTML = "Required";
			bReturn = false;
		}
		//if the field is NOT required and it's empty there's no big deal.
		else{
			divCon.obj.innerHTML = "";
			return bReturn;
		}
	}
	//if it's NOT empty
	else{
		divCon.obj.innerHTML = "";
		bReturn = true;
	}		

	
	//if the field is not required or data is present
	if (bReturn){
		switch(datatype){		
			case "alpha":
				if(isAlpha(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
			case "alphanum":
				if(isAlphaNumericWithPunctuation(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
		    case "alphanumnospace":
		        if(isAlphaNumericNoSpace(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}		        
		        break;
			case "number": 
				if(isNumeric(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
			case "money": 
				if(isMoney(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
			case "date": 
				if(isDate(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}				
				break;				
			case "phone": 
				if(isPhone(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}				
				break;
			case "ccard": 
				if(isCCard(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}				
				break;	
			case "email":
				if(isEmail(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
			case "url":
				if(isUrl(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
			case "username":
				if(isUserName(txtField.obj.value)){
					divCon.obj.innerHTML = "";
					bReturn = true;	
				}
				else{
					divCon.obj.innerHTML = msg;
					bReturn = false;
				}
				break;
				
			default:
				divCon.obj.innerHTML = "The data type is not supported";
				bReturn = false;
				break; 
		}		
	}
	return bReturn;
}



////////////////////////////////////////////////////////////////////////////////////////////////
//// This function takes A BUTTON element and toggles the disabled status + changes the text (value)
//// to whatever defined. 
////
//// @Param  dateStr  		the text to validate
////
//// @Return boolean
////////////////////////////////////////////////////////////////////////////////////////////////

function toggleDisabled(elem,txt){
	if ((elem != null) && (elem.disabled != 'undefined')){
		elem.disabled = !(elem.disabled);
		if (txt != '')
			elem.value = txt;
	}
}


////////////////////////////////////////////////////////////////////////////////////////////////
//// This function takes A textbox element and toggles the presence of the sDefaultText specified
//// Should be used on the onFocus and onBlur events
////
//// @Param  sTextbox  		the textbox to use
//// @Param  sDefaultText  	the text to default
////
////////////////////////////////////////////////////////////////////////////////////////////////

function toggleSampleTextinTextbox(sTextbox, sDefaultText){
	var txtBox=new getObj(sTextbox).obj;
	if (trim(txtBox.value) == "")
		txtBox.value = sDefaultText;	
	else if (trim(txtBox.value) == sDefaultText)
		txtBox.value = "";
}


//Function that takes a container and shows/hides it
function toggleShowHide(divname){
    var div = new getObj(divname).obj;   

    if (div.style.display == 'none')
        div.style.display = 'block';
    else
        div.style.display = 'none';
}


// catches the keydown event and sends enters to the button submit specified.
function keyDown(e,btn)
{
	if (checkKeyPress(e) == 13 || checkKeyPress(e) == 10)
	{
		e.returnValue=false;
		e.cancel = true;
		if (new getObj(btn).obj) new getObj(btn).obj.click();
	}
}


//For Mozilla / Firefox you need to send the event
function checkKeyPress(e) {
	if(!e) var e = window.event;

	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	//code contains the pressed key in all browsers

	return code; 
}

//Once an Enter is hit over the control a click is sent to the button sent.
function checkEnter(evt, btnSendId){
    if (checkKeyPress(evt) == 13){	
		var btnSend = new getObj(btnSendId).obj;	
		if (btnSend.dispatchEvent) 
        {
            evt.preventDefault();
            evt.cancelBubble = true;           
            
            var e = document.createEvent("MouseEvents"); 
            e.initEvent("click", true, true);
            btnSend.dispatchEvent(e); 
        }
        else
        {
            evt.returnValue=false;
            evt.cancelBubble = true;
            
            btnSend.click(); 
        }
    		
	}
}

// Prevents multi-line text boxes from typing over the max character limit
function maxLenKeypress(e,control,maxLength)
{
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          e.returnValue = false;
          maxLength = parseInt(maxLength);
     }
}

// Added function to get this to work in Firefox
function maxLenUpdate(e,control,maxLength)
{
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          control.value = control.value.substring(0, maxLength);
          e.returnValue = false;
     }
}

// Prevents pasting if over the max length
function maxLenBeforePaste(e,control,maxLength)
{
     if(maxLength)
     {
          e.returnValue = false;
     }
}

// Truncates a paste so it doesn't go over max length
function maxLenPaste(e,control,maxLength)
{
    value = control.value;
     if(maxLength){
          e.returnValue = false;
          maxLength = parseInt(maxLength);
          var oTR = control.document.selection.createRange();
          var iInsertLength = maxLength - value.length + oTR.text.length;
          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
          oTR.text = sData;
     }
}


// Specifies the next focused element once a textfield is full with the MaxLength items.
// Add to onkeyup event on textfields
function tabOver(tf, nf, len)
{
	var thisform = new getObj(tf).obj;
	
	if(trim(thisform.value).length == len)
		setTimeout("new getObj('"+nf+"').obj.focus();",250);
		
}

// Only allow number input
// Returns true if the input type is valid or false if it's not. 
// Add to onkeydown event on textfields
function numbersOnly(evt)
{
	var keynum = checkKeyPress(evt);
	
	if((keynum <= 57 && keynum != 32) || (keynum >= 96 && keynum <= 105))
		return true;
	else
		return false;
}




//Cancels a form submition. 
//Prevents the default action to be triggered when an event fires. 
function preventDefaultAction(e) { 
   if (e) { 
      if (typeof e.preventDefault!= 'undefined') { 
         e.preventDefault(); // W3C 
      } else { 
         e.returnValue = false; // IE 
      } 
   } 
   // safey for handling DOM Level 0 
   return false; 
} 

//Functions to Attach an event on a page
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

//Functions to Remove an event on a page
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

