/*
*  The Validator
*   The class that handles all validation related issues
*    
*   pass the name of the form while constructing.
*   methods:
*    addValidation(input_item_name,validation_descriptor,error_string)
*       call this method for each input item. Single input item can have 
*       many validations
*      
*    setAddnlValidationFunction(function_name)
*             call this function to set a custom validate function, which will
*						 be called after other validations are over.
*			       The function should return 'true' or 'false' 


* Global variable explanations -
* These two variables are used by the function vdesc_validate() to 
* highlight the error character to the user if there is one
* str - Holds the entered data
* ch - Holds the substring, which is the illegal character

* gFrmObj - global form object
* submitcount - Attempt to circumvent double submitting
*/
var str,ch,gFrmObj,submitcount=0;

function Validator(frmname){gFrmObj=document.forms[frmname];this.formobj=gFrmObj;if(!this.formobj){alert("BUG: could not get Form object "+frmname);return;}if(this.formobj.onsubmit){this.formobj.old_onsubmit = this.formobj.onsubmit;this.formobj.onsubmit=null;}else{this.formobj.old_onsubmit = null;}this.formobj.onsubmit=form_submit_handler;this.addValidation = add_validation;this.setAddnlValidationFunction=set_addnl_vfunction;this.clearAllValidations = clear_all_validations;}
function set_addnl_vfunction(functionname){this.formobj.addnlvalidation = functionname;}
function clear_all_validations(){for(var itr=0;itr < this.formobj.elements.length;itr++){this.formobj.elements[itr].validationset = null;}}
function add_validation(itemname,descriptor,errstr){if(!this.formobj){alert("BUG: the form object is not set properly");return;}var itemobj = this.formobj[itemname];if(!itemobj){alert("BUG: Could not get the input object named: "+itemname);return;}if(!itemobj.validationset){itemobj.validationset = new ValidationSet(itemobj);}itemobj.validationset.add(descriptor,errstr);}
function ValidationDesc(inputitem,desc,error){this.desc=desc;this.error=error;this.itemobj=inputitem;this.validate=vdesc_validate;}
function ValidationSet(inputitem){this.vSet=new Array();this.add= add_validationdesc;this.validate= vset_validate;this.itemobj=inputitem;}
function add_validationdesc(desc,error){this.vSet[this.vSet.length]=new ValidationDesc(this.itemobj,desc,error);}
function vset_validate(){for(var itr=0;itr<this.vSet.length;itr++){if(!this.vSet[itr].validate()){return false;}}return true;}
function form_submit_handler(){
	var ret,itr;
	for(itr=0;itr < this.elements.length;itr++){if(this.elements[itr].validationset && !this.elements[itr].validationset.validate()){return false;}}
	if(this.addnlvalidation){str=";ret = "+this.addnlvalidation+"()";eval(str);if(!ret){return ret;}}
	if(submitcount === 0){submitcount++;}else{alert("This form has already been submitted. If you have had no response then please Refresh/Reload and try again.");return false;}
	return true;
}
function vdesc_validate(){
	if(!V2validateData(this.desc,this.itemobj,this.error)){
		// Only attempt to select the invalid char if the obj is a text box or text area
		if(this.itemobj.type==='text' || this.itemobj.type==='textarea') {
			// Return and select the error character if the browser supports createTextRange
			if(this.itemobj.createTextRange){
				var rng = this.itemobj.createTextRange();
				if (rng.findText(ch)) {
			 		rng.select();
				}else{
			 		this.itemobj.select();
			 		if(this.itemobj.focus===true){this.itemobj.focus();}
				}//if
			}else{
				this.itemobj.select();
				if(this.itemobj.focus===true){this.itemobj.focus();}
			}//if
		}else{	
			if(this.itemobj.focus===true){this.itemobj.focus();}
		}//if
		return false;
	}
	return true;
}

//---------------------------------EMail Check ------------------------------------ 

/*  checks the validity of an email address entered 
*   returns true or false 
*   
*/ 

function validateEmailv2(email){
  // very simple email validation checking. 
  // you can add more complex email checking if it helps 
  email=trim(email);
   if(email){
   	var bRet,sPat,regex;
   	bRet=false
   	// The pattern below has not been used yet allows \/@!=" in the local part of the address (note I've not checked the dbl quote escape)
	//sPat="^[A-Za-z0-9'\\/!@\._%+-=!\"]+@(?:[A-Za-z0-9_'-]+\.)+[A-Za-z]{2,4}$" 
	sPat="^[\\w'._%+-]+@(?:[\\w'-]+\\.)+[A-Za-z]{2,4}$";
	regex = new RegExp(sPat);
        bRet=regex.test(email);
        //if(bRet===false){alert(bRet+"\nPatern="+sPat+"\nEmail="+email);}
        return bRet;
   }else{
   	return true;
   }// if
}

/* function V2validateData 
*  Checks each field in a form 
*
*/ 
function V2validateData(strValidateStr,objValue,strError){ 
    var epos,command,cmdvalue,bPopulated,charpos,iLength,bVal; 
    epos=strValidateStr.search("=");
    command="";
    cmdvalue=""; 
    if(epos >= 0){ 
		command  = strValidateStr.substring(0,epos); 
		cmdvalue = strValidateStr.substr(epos+1); 
    }else{ 
		command=strValidateStr; 
    } 
    objValue.value=trim(objValue.value);

    switch(command) 
    { 
        case "req": 
        case "required": 
         { 
		   bVal=false;
		   if(objValue.type.toLowerCase()==="checkbox"){
			  bVal=objValue.checked;
		   }else if(objValue.type.toLowerCase()==="radio"){
			  alert("Radio button lists are not currently being handled by the reqired validation.");
		   }else if(objValue.type.toLowerCase()==="select"){
			  alert("Select lists are not currently being handled by the reqired validation. Use 'dontselect'");
		   }else if(trim(objValue.value)){
			  bVal=true;
		   }
		   if(bVal===false){/*eval(objValue.value.length) === 0){ */
			   if(!strError || strError.length===0){strError=objValue.name + " : Required Field";}//if 
			   alert(strError); 
			   return false;
           }//if			
           break;             
         }//case required 
        
        case "reqif": 
        case "requiredif": //required if the specified control is not empty reqif=controlid
         { 
		   bPopulated=false;
		   bVal=false;
		   if(gFrmObj[cmdvalue].type.toLowerCase()==="checkbox"){
			  if(gFrmObj[cmdvalue].checked === true){bPopulated=true;}
		   }else if(gFrmObj[cmdvalue].type.toLowerCase()==="radio"){
			  alert("Radio button lists are not currently being handled by the reqiredIf validation");
		   }else if(gFrmObj[cmdvalue].type.toLowerCase()==="select"){
			  alert("Select lists are not currently being handled by the reqiredIf validation");
		   }else if(trim(gFrmObj[cmdvalue].value)){
			  bPopulated=true;
		   }		   
		   if(objValue.type.toLowerCase()==="radio" || objValue.type.toLowerCase()==="checkbox"){
			  bVal=objValue.checked;
		   }else if(objValue.type.toLowerCase()==="radio"){
			  alert("Radio button lists are not currently being handled by the reqiredIf validation");
		   }else if(objValue.type.toLowerCase()==="select"){
			  alert("Select lists are not currently being handled by the reqiredIf validation");
		   }else if(trim(objValue.value)){
			  bVal=true;
		   }
		   if(bPopulated===true && bVal===false){/*eval(objValue.value.length)=== 0){ */
			   if(!strError || strError.length===0){strError=objValue.name + " : Required Field";}//if 
			   alert(strError); 
			   return false;
           }//if
           break;             
         }//case required if
        case "maxlength": 
        case "maxlen": 
          { 
             if(eval(objValue.value.length) > eval(cmdvalue)){ 
               if(!strError || strError.length===0){strError = objValue.name + " : "+cmdvalue+" characters maximum ";}//if 
               alert(strError + "\n[Current length = " + objValue.value.length + " ]\nValue:"+objValue.value); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlength": //implies required
        case "minlen": 
           { 
             if(eval(objValue.value.length) < eval(cmdvalue)){ 
               if(!strError || strError.length===0){strError = objValue.name + " : " + cmdvalue + " characters minimum ";}//if               
               alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlen  

        case "maxlengthwrdcnt": 
        case "maxlenwrdcnt": 
          {
			iLength=CountWords(objValue);
             if(iLength > eval(cmdvalue)){ 
               if(!strError || strError.length===0){strError = objValue.name + " : "+cmdvalue+" words maximum ";}//if 
               alert(strError + "\n[Current length = " + iLength + " ]"); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlengthwrdcnt": //implies required
        case "minlenwrdcnt": 
           { 
            iLength=CountWords(objValue);
             if(iLength < eval(cmdvalue)){ 
               if(!strError || strError.length===0){strError = objValue.name + " : " + cmdvalue + " words minimum ";}//if               
               alert(strError + "\n[Current length = " + iLength + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlenwrdcnt  			

        case "optionalminlengthwrdcnt": //implies required
        case "optminlenwrdcnt": 
           { 
			if(trim(objValue.value)){
	            iLength=CountWords(objValue);
	             if(iLength < eval(cmdvalue)){ 
	               if(!strError || strError.length===0){strError = objValue.name + " : " + cmdvalue + " words minimum ";}//if               
	               alert(strError + "\n[Current length = " + iLength + " ]"); 
	               return false;                 
	             }//if 
			}//if 
             break; 
            }//case minlenwrdcnt 			
			
        case "optionalfieldminlen": //Not a required field, but if populated must be at least x long
        case "optminlen": 
           { 
				if(trim(objValue.value)){	           
					if(eval(objValue.value.length) < eval(cmdvalue)){ 
						if(!strError || strError.length===0){strError = objValue.name + " : " + cmdvalue + " characters minimum ";}//if               
						alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
						return false;                 
					}//if 
				}//if
				break; 
            }//case optionalfieldminlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              charpos = objValue.value.search(/[^\w :;\/\\\{\}\?!&@\$\£\€%\*=\(\)<>_\+,\.\-'#~]/); 
              if(objValue.value.length > 0 && charpos >= 0){ 
               if(!strError || strError.length===0){strError = objValue.name+": Only alpha-numeric characters allowed ";}//if 
                alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": 
           { 
			  str = objValue.value //create the str in order to retrieve the character at charpos
              charpos = objValue.value.search(/[^0-9]/); 
              if(objValue.value.length > 0 && charpos >= 0){ 
				ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos
                if(!strError || strError.length===0){strError = objValue.name+": Only digits allowed ";}//if               
                alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
           }//numeric 	
		case "currency": 
		   { 
              charpos = objValue.value.search(/[^0-9,.-]/); 
              if(objValue.value.length > 0 && charpos >= 0){ 
                if(!strError || strError.length===0){strError = objValue.name+": Only digits allowed ";}//if               
                alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
        }//currency 
        case "alphabetic": 
        case "alpha": 
           { 
              str = objValue.value //create the str in order to retrieve the character at charpos
			  charpos = objValue.value.search(/[^A-Za-z :;\/\\\{\}\?!&@\$\£\€#%\*=\(\)<>_\+,\.\-'[\]]/); 
			  if(objValue.value.length > 0 && charpos >= 0){ 
				ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos			
                if(!strError || strError.length===0){strError = objValue.name+": Only alphabetic characters allowed ";}//if                             
                alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//alpha 
	case "alnumhyphen":
			{
              str = objValue.value //create the str in order to retrieve the character at charpos
			  charpos = objValue.value.search(/[^\w\-_]/); 
              if(objValue.value.length > 0 && charpos >= 0){ 
			    ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos
                if(!strError || strError.length===0){strError = objValue.name+": characters allowed are A-Z,a-z,0-9,- and _";}//if                             
                alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 			
			break;
			}
	case "alNumBulkTxt": // Allows the use of " & ' vbCRLF etc. For use in bulk text fields ie/eg (Text Areas)
		{ 
			str = objValue.value //create the str in order to retrieve the character at charpos
			charpos = objValue.value.search(/[^\w :;\/\\"'\{\}\?!&@\$\£\€#%\*=\(\)<>_\+,\.\-\s[\]]/);
			if(objValue.value.length > 0 && charpos >= 0){ 
			  ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos
			  if(!strError || strError.length===0){strError = objValue.name+": Only alpha-numeric characters allowed ";}//if 
			  alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
			  return false; 
			}//if 
			break; 
		}//case alNumBulkTxt
	case "alphaGenus": //Allows the use of '(Single Quotes), -(Hyphen),  (space). For use in Name fields ie/eg O'Hara
		{ 
			str = objValue.value //create the str in order to retrieve the character at charpos
			charpos = objValue.value.search(/[^A-Za-z '-\.]/);
			if(objValue.value.length > 0 && charpos >= 0){ 
				ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos
				if(!strError || strError.length===0){strError = objValue.name+": Only alpha characters allowed ";}//if 
				alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
				return false; 
			}//if 
			break; 
		}//case alphaGenus 
        case "email": 
          { 
               if(!validateEmailv2(objValue.value)){ 
                 if(!strError || strError.length===0){strError = objValue.name+": Enter a valid Email address ";}//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNumeric(objValue.value)===false){alert(objValue.name+": Should be a number ");return false;}//if 
            if(eval(objValue.value) >= eval(cmdvalue)){ 
              if(!strError || strError.length===0){strError = objValue.name + " : value should be less than "+ cmdvalue;}//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan": 
         { 
            if(isNumeric(objValue.value)===false){alert(objValue.name+": Should be a number ");return false;}//if 
             if(eval(objValue.value) <= eval(cmdvalue)){ 
               if(!strError || strError.length===0){strError = objValue.name + " : value should be greater than "+ cmdvalue;}//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan 
        case "phone": 
         { 
			str = objValue.value //create the str in order to retrieve the character at charpos
			charpos = objValue.value.search(/[^0-9\-\(\)\ \.\+]/);
			if(objValue.value.length > 0 && charpos >= 0){ 
				ch = str.substring(charpos, charpos+1) //retrieve illegal character at charpos
				if(!strError || strError.length===0){strError = objValue.name+": Invalid Character found";}//if 
				alert(strError + "\n[Error character position " + eval(charpos+1)+"]"); 
				return false; 
			}//if 
            break; 
         }//case phone 
        case "regexp": 
         { 
			if(objValue.value.length > 0 && !objValue.value.match(cmdvalue)){ 
				if(!strError || strError.length===0){strError = objValue.name+": Invalid characters found ";}//if                                                               
				alert(strError); 
				return false;                   
			}//if 
			break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex === null){ 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex === eval(cmdvalue)){ 
             if(!strError || strError.length===0){strError = objValue.name+": Please Select one option ";}//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect 
         
        case "verifypwd": 
         { 
            if(objValue.value.length > 0 && objValue.value !== gFrmObj[cmdvalue].value) { 
             if(!strError || strError.length===0){strError = objValue.name+": passwords must match ";}//if
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case verifypwd 
		case "date":
		 {
	 	// This function uses Matt Kruse's Date.js 
	 	// Source: http://www.mattkruse.com/javascript/date/source.html
	 	// I changed this to allow me to alter the date format, the old method
	 	// only allowed dd/mm/yyyy
	 	
	 	// ------------------------------------------------------------------
		// These functions use the same 'format' strings as the 
		// java.text.SimpleDateFormat class, with minor exceptions.
		// The format string consists of the following abbreviations:
		// 
		// Field        | Full Form          | Short Form
		// -------------+--------------------+-----------------------
		// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
		// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
		//              | NNN (abbr.)        |
		// Day of Month | dd (2 digits)      | d (1 or 2 digits)
		// Day of Week  | EE (name)          | E (abbr)
		// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
		// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
		// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
		// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
		// Minute       | mm (2 digits)      | m (1 or 2 digits)
		// Second       | ss (2 digits)      | s (1 or 2 digits)
		// AM/PM        | a                  |
		//
		// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
		// Examples:
		//  "MMM d, y" matches: January 01, 2000
		//                      Dec 1, 1900
		//                      Nov 20, 00
		//  "M/d/yy"   matches: 01/20/00
		//                      9/2/00
		//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
		// ------------------------------------------------------------------
		
		str = trim(objValue.value) //create the str in order to retrieve the character at charpos
		if(str.length > 0) {
	 	  if(isDate(str,cmdvalue) === false) {
		     if(!strError || strError.length ===0) { 
			strError = objValue.name + " : value is not a valid date."
		     }//if               
		     alert(strError+"\n\nPlease use the format - " + cmdvalue.toLowerCase()); 
		     return false;
	 	  }//if
	 	}//if
	 	break;         
	}//case date
    }//switch 
    return true; 
}

/***************************************************************
*	Currency validation called onKeyPress by the specified field
****************************************************************/

function currencyFormat(fld, milSep, decSep, e) {
	var key='',i=0,j=0,len=0,len2=0,strCheck='0123456789',aux='',aux2='',whichCode;
	//whichCode = (window.Event) ? e.which : e.keyCode;
	if(e.keyCode){
		whichCode=e.keyCode;
	}else if(e.which){
		whichCode=e.which;
	}else if(event.keyCode){
		whichCode=event.keyCode;
	}else{
		alert("Unhandled event type please contact support");
	}
	
	if(whichCode === 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if(strCheck.indexOf(key) === -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if((fld.value.charAt(i) !== '0') && (fld.value.charAt(i) !== decSep)) break;
	aux = '';
	for(; i < len; i++)
	if(strCheck.indexOf(fld.value.charAt(i))!==-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if(len === 0) fld.value = '';
	if(len === 1) fld.value = '0'+ decSep + '0' + aux;
	if(len === 2) fld.value = '0'+ decSep + aux;
	if(len > 2) {
	aux2 = '';
	for(j = 0, i=len - 3; i >= 0; i--){
		if(j === 3){
			aux2 += milSep;
			j=0;
		}
		aux2 += aux.charAt(i);
		j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

/**********************************************************************************************
*	Currency validation called onKeyDown resets the control if key pressed is backspace or delete
***********************************************************************************************/

function checkKey(myCtl, e) {
	var whichCode;
	if(e.keyCode){
		whichCode=e.keyCode;
	}else if(e.which){
		whichCode=e.which;
	}else if(event.keyCode){
		whichCode=event.keyCode;
	}else{
		alert("Unhandled event type please contact support");
	}
	// If the user presses b'space or del reset the control
	if ((whichCode === 8) || (whichCode === 46)) { // backspace or delete
		myCtl.value = ""
	}
}

/**********************************************************************************************
*	Extender Functions
*   More can be found here - http://www.4guysfromrolla.com/webtech/vb2java.shtml
***********************************************************************************************/

function left(str,n){if(n <= 0){return "";}else if(n > String(str).length){return str;}else{return String(str).substring(0,n);}}
function right(str,n){var iLen;if(n <= 0){return "";}else if(n > String(str).length){return str;}else{iLen=String(str).length;return String(str).substring(iLen, iLen - n);}}
function trim(str){str = str.replace(/^\s+|\s+$/g, "");return str;} 

// Keep in mind that strings in JavaScript are zero-based, so if you ask
// for Mid("Hello",1,1), you will get "e", not "H".  To get "H", you would
// simply type in Mid("Hello",0,1)

// You can alter the above function so that the string is one-based.  Just
// check to make sure start is not <= 0, alter the iEnd = start + len to
// iEnd = (start - 1) + len, and in your final return statement, just
// return ...substring(start-1,iEnd)

function len(str){return String(str).length;}

function mid(str, start, len) {
	/***
	IN: str - the string we are LEFTing
		start - our string's starting position (0 based!!)
		len - how many characters from start we want to get
	RETVAL: The substring from start to start+len
	***/
	// Make sure start and len are within proper bounds
	if(start < 0 || len < 0) return "";
	var iEnd, iLen=String(str).length;
	if(start+len > iLen){iEnd=iLen;}else{iEnd=start+len;}
	return String(str).substring(start,iEnd);
}

function charInStr(strSearch, charSearchFor) {
	/*
	charInStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
	was found in the string str.  (If the character is NOT found, -1 is returned.)
	Requires use of: Mid function & Len function
	*/
	alert("Search String: " + strSearch + "\nSearch For: " + charSearchFor);
	for(var i=0;i < len(strSearch);i++){
		if(charSearchFor===mid(strSearch,i,1)){
			return i;
		}
	}
	return -1;
}

function inStr(sString, sSearchFor) {
//returns -1 if not found & 0 for beginning of string i.e. char 1
return sString.indexOf(sSearchFor);
}

function listFind(list,value,delimiter,ignoreCase){
	/*** 
	* Description: 	Determines the index of the first element in which a specified value occurs.
	* Return Value: 	Index of first element that contains sValue, with matching case.  if not found returns zero.
	* NOTE: 	The Search is Case Sensitive by default i.e. If you pass in a blank for compare.
	* Compare Options	vbBinaryCompare=0 ' Case Sensitive and the default
	*					vbTextCompare=1 'Case Insensitive
	* Copy of a ColdFusion Function by the same name, albeit modified somewhat.
	***/
	var i=0,returnValue=0,_tempArray=new Array();
	if(ignoreCase===1||ignoreCase===-1||ignoreCase===true){
		list=list.toLowerCase();
		value=value.toLowerCase();
	}
	if(trim(delimiter)===""){delimiter=",";}
	_tempArray=list.split(delimiter);
	for(i=0;i < _tempArray.length;i++){
		if(_tempArray[i]===value){
			returnValue=i+1;
			break;
		}
	}
	return returnValue;
}

	
function getSelectedRbl(frmName,rblName){
	/*** 
	* This function easily allows you to use different rblists and forms
	* with each call you pass in the form name and rbl name
	* Usage: 
	* 	1. alert(getSelectedRbl('frmTest','rblOrder');
	* 	2. var opt=getSelectedRbl('frmTest','rblOrder');
	***/
	var frm=document.forms[frmName],opt="",i;
	if(frm[rblName].length>0){
		/* 
		 Loop from zero to the one minus the number of radio button options. 
		 Length property is NOT zero based
		*/
		for(i=0; i < frm[rblName].length;i++){
			if(frm[rblName][i].checked===true){
				opt=frm[rblName][i].value;
				break;
			}
		}
	}else if(frm[rblName].checked===true){
		/* 
		 If the rbl only has one option in it the length check returns "undefined" e.g. 
		 if(String(frm[rblName].length)==='undefined'){alert("rbl length is undefined");} 
		*/
		opt=frm[rblName].value;
	}
	return opt;
}

function getSelectedChk(frmName,chkName){
	/*** 
	* This function easily allows you to use different rblists and forms
	* with each call you pass in the form name and rbl name
	* Usage: 
	* 	1. alert(getSelectedChk('frmTest','chkPrefs');
	* 	2. var opt=getSelectedChk('frmTest','chkPrefs');
	***/
	var frm=document.forms[frmName],opt="",i;
	if(frm[chkName].length>0){
		/* 
		 Loop from zero to the one minus the number of checkboxes. 
		 Length property is NOT zero based
		*/
		for(i=0; i < frm[chkName].length;i++){
			if(frm[chkName][i].checked===true){
				opt+=frm[chkName][i].value+",";
			}
		}
		if(opt){opt=opt.substring(0,opt.length-1)}
	}else if(frm[chkName].checked===true){
		/* 
		 If the chk only has one option in it the length check returns "undefined" e.g. 
		 if(String(frm[chkName].length)==='undefined'){alert("chk length is undefined");} 
		*/
		opt=frm[chkName].value;
	}
	return opt;
}

function getDDLSelections(frmName,ddlName,bVals){
	// get the selected items requested from the multiselectBox
	// returns a comma delimited list of selected items
	// bVals specifies whether to return selected values or the option text, returns values by default
	var i,
		ob=document.forms[frmName][ddlName],
		selected="";
	if(bVals!==true && bVals!==false){bVals=true;} // Return selected values by default
	for (i=0; i<ob.options.length; i++){
		//if (ob.options[i].selected===true && (ob.options[i].value!=="0" && ob.options[i].value!=="")){
		if (ob.options[i].selected===true){
			if(bVals===true){
				selected += (ob.options[i].value)+",";
			}else{
				selected += (ob.options[i].text)+",";
			}
		}
	}
	if(selected){selected=selected.substring(0,selected.length-1)}
	return selected;
}

function isNumeric(sText){
	/*** 
	* This function easily allows you check is a passed in value is numeric
	* with each call you pass in the value to be evaluated
	* allows decimals, no commas
	* Returns true|false
	* WARNING: Returns true if an empty string is passed in
	* Usage: 
	* 	1. alert(isNumeric('10'));
	* 	2. alert(isNumeric('hello'));
	***/
	
	var ValidChars = "0123456789.",bRet=true,Char,i;
	for (i=0; i < sText.length && bRet===true; i++){
		Char=sText.charAt(i);
		if(i===0 && Char==="-"){continue;}
		if(ValidChars.indexOf(Char)===-1){
			bRet=false;
			break;
		}
	}return bRet;
}

function CountWords(this_field){
	var word_count = this_field.value.split(/\b[\s,\.-:;]*/);
	word_count=word_count.length;
	return word_count;
}

//var xmlHttp;
//function GetXmlHttpObject(){var xmlHttp=null;try{ /* Firefox, Opera 8.0+, Safari*/ xmlHttp=new XMLHttpRequest();}catch(e){ /* Internet Explorer*/ try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;}