/* Based on: Travis Beckham ::
http://www.squidfingers.com | http://www.podlob.com
Based on: Manzi Olivier :: http://www.imanzi.com/
Based on: jgw (jgwang@csua.berkeley.edu )/ */

/*

Functions	
	validateField(obj, newClass, alerttype)
		obj 		- 	sending object
		newClass 	- 	the css class to be applied to the object when validation fails, defaults to red 
							background
		alerttype 	- 	the style of notification that will be given on failed validation
	
	
	
Attributes				options
	fieldToValidate		indicates the field that is to be validated.  This attribute is not required, if not 
							provided default is the object calling the validateField() method
	displayName			this is the name of the field that will be displayed when an error message is displayed
	validationType		required (field is required to be 

The following elements are not validated...

	button   type="button"
	checkbox type="checkbox"
	radio    type="radio"
	reset    type="reset"
	submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

	isEmail = true;          // valid email address
	isAlpha = true;          // A-Z a-z characters only
	isNumeric = true;        // 0-9 characters only
	isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
	isLength = number;       // must be exact length
	isLengthBetween = string; // "lowNumber-highNumber" must be between lowNumber and highNumber. eg: "4-255"
	isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
	isDate = true;           // valid date. See "isDate()" comments for the formatting rules
	isMatch = string or number;   //value must match
	optional = true;         // element will not be validated

	alerttype = 0            // no error msg
	alerttype = 1            // error msg in div
	alerttype = 2            // error msg in alert
	alerttype = 3            // error msg in div and alert
*/

var DEFAULT_ALERT_TYPE = 1;
var DEFAULT_CLASSNAME = ""; //this is used to preserve any preexisting class on a field
var FAILED_CLASSNAME = "validatorRequired";
var PASSED_CLASSNAME = "validatorPassed";
var _PASSED_CLASSNAME = "validatorPassed";
//check for submit entry 
var ERROR_GLOBAL = "false";
var TAB_MESSAGE = "false";
//for timer function
var timerID = 0;
var tStart  = null;

//this will be utilized to diplay the group of errors shown across
var erroContent='';


function checkCapsLock(e) 
{
	var myKeyCode = 0;
	var myShiftKey = false;

	// Internet Explorer 4+
	if ( document.all ) 
	{
		myKeyCode = e.keyCode;
		myShiftKey = e.shiftKey;

	// Netscape 4
	} 
	else if ( document.layers ) 
	{
		myKeyCode = e.which;
		myShiftKey = ( myKeyCode == 16 ) ? true : false;

	// Netscape 6
	} 
	else if ( document.getElementById ) 
	{
		myKeyCode = e.which;
		myShiftKey = ( myKeyCode == 16 ) ? true : false;

	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) 
	{
		alert( errormsg[100] );

	// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	} 
	else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) 
	{
		alert( errormsg[100] );
	}
}

function CalcKeyCode(aChar) 
{
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function checkNumber(val) 
{

  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var cCode = CalcKeyCode(lchar);


  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

  if (cCode < 48 || cCode > 57 ) 
  {
    var myNumber = val.value.substring(0, (strLength) - 1);
    val.value = myNumber;
  }
  
  return false;
}

function isEmpty(str)
{

     str = stripWhitespace(str);
	 return (str == null) || (str.length == 0) ||(str.value == ' ');
}

// returns true if the string is a valid email
function isEmail(str)
{
  if(isEmpty(str)) return false;
  var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
  return re.test(str);
}
//HS016425
//return true if the string is like a url
function isUrl(s)
{
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return regexp.test(s);
}
//hs016425:end of code


// returns true if the string only contains characters A-Z or a-z
function isAlpha(str)
{
  var re = /[^a-zA-Z]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string only contains characters 0-9
function isNumeric (sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
 
  if (sText.length == 0){return false;}
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
         IsNumber = false;
      }
    }
   
   return IsNumber;
}

function isValidDecimalNumber(value, min, max ){
	var valid = false;
	var ValidChars = "0123456789.";
	var indxOfDecimal = null;

	var minimum = (typeof(min) != 'undefined') ? min : 0.01;
	var maximum = (typeof(max) != 'undefined') ? max : 999.99;

	if ((value >= minimum && value <= maximum) || value == "") {
		valid = true;
	}
	for ( var i = 0; i <= value.length -1; i++) {
		var ch = value.charAt(i);
		if (ValidChars.indexOf(ch) == -1) {
			valid = false;
		}else if(ch == '.'){
			
			if (indxOfDecimal == null) {
				indxOfDecimal = i;
			}else{
				valid = false;
			}	
		}
	}

	if(indxOfDecimal != null){
		if(value.length - indxOfDecimal > 3){
			valid = false;
		}
	}
	return valid;
}


// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str)
{
  var re = /[^a-zA-Z0-9\s]/g;
  //if (re.test(str) return false;
  //return true;
  return !(re.test(str));
}
//HS016425: added for validating for limited special characters on the string
function isAlphaNumericWithSplCharacter(str)
{
	var  s = replaceAll(str,"'","&apos;");
	//alert(s);
	
  var re = /[^a-zA-Z0-9\s\-\_\:\;\&]/g;
	
  return !(re.test(s));
}
//HS016425: convert special character back from the encoded string
	function replaceAll(oldStr,findStr,repStr) {
	//alert(oldStr);
	  var srchNdx = 0;  // srchNdx will keep track of where in the whole line
	                    // of oldStr are we searching.
	  var newStr = "";  // newStr will hold the altered version of oldStr.
	  while (oldStr.indexOf(findStr,srchNdx) != -1)  
	                    // As long as there are strings to replace, this loop
	                    // will run. 
	  {
	    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
	                    // Put it all the unaltered text from one findStr to
	                    // the next findStr into newStr.
	    newStr += repStr;
	                    // Instead of putting the old string, put in the
	                    // new string instead. 
	    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
	                    // Now jump to the next chunk of text till the next findStr.           
	  }
	  newStr += oldStr.substring(srchNdx,oldStr.length);
	                    // Put whatever's left into newStr.             
	  return newStr;
}
// returns true if the string's length equals "len"
function isLength(str, len)
{
  return str.length == len;
}

// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max)
{
  return (str.length >= min) && (str.length <= max);
}

function isNumberBetween(str,min,max){
	return ((str >= min) && (str <= max));
}

//This method ensures that only digits, commas, and decimals are used in fee field.
function isValidFeeValue(value){
	var validChars = "0123456789.,";
	var char;
	for (i = 0; i < value.length; i++) 
	{ 
		  char = value.charAt(i); 
	      if (validChars.indexOf(char) == -1) 
	      {
	         return false;
	      }
	 }
	 return true;
}
// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str)
{
  var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
  return re.test(str);
}

// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str)
{
  var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;

  if (!re.test(str)) return false;

  var result = str.match(re);
  
  var y = parseInt(result[3],10);
  var m = parseInt(result[1],10);
  var d = parseInt(result[2],10);
  if(m < 1 || m > 12 || y < 1900 || y > 2100) return false;
  
  var days;  
  if(m == 2)
  {
  	days = ((y % 4) == 0) ? 29 : 28;
  }
  else if(m == 4 || m == 6 || m == 9 || m == 11)
  {
    days = 30;
  }
  else
  {
  	days = 31;
  }
  return (d >= 1 && d <= days);
}

// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2)
{
  return str1 == str2;
}

// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str) // NOT USED IN FORM VALIDATION
{    
	var re = /[\S]/g;
	if (re.test(str)) return false;
	return true;
}

function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
Ext.MessageBox.alert('Invalid Entry!', 'Time is not in a valid format.', function(){} );
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null; }

if (hour < 0  || hour > 23) {
Ext.MessageBox.alert('Invalid Entry!', 'Hour must be between 1 and 12. (or 0 and 23 for military time)', function(){} );
return false;
}
if (hour <= 12 && ampm == null) {
if ( Ext.MessageBox.confirm('Invalid Entry!', 'Is this standard time format?  Yes = Standard Time, No = Military Time.', function(){} ) == 'ok' ) {
Ext.MessageBox.alert('Invalid Entry!', 'You must specify AM or PM.', function(){} );
return false;
   }
}
if  (hour > 12 && ampm != null) {
Ext.MessageBox.alert('Invalid Entry!', 'You can not specify AM or PM for military time.', function(){} );
return false;
}
if (minute<0 || minute > 59) {
Ext.MessageBox.alert('Invalid Entry!', 'Minute must be between 0 and 59.', function(){} );
return false;
}
if (second != null && (second < 0 || second > 59)) {
Ext.MessageBox.alert('Invalid Entry!', 'Second must be between 0 and 59.', function(){} );
return false;
}
return true;
}

// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(inputString)// NOT USED IN FORM VALIDATION
{
	// Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   
   return retValue; // Return the trimmed string back to the user
  
}

// validate the form

/**
*	Function called for Field Validation (not submitted)
*	@obj = the element object
*	@newClass = the css class to be applied to the object when validation fails, defaults to red background
*	@alerttype = the style of notification that will be given on failed validation
*/
function validateField(obj, newClass, alerttype)
{
 	var errors = '';
  	var errorsa = '';
  	var f = obj; //sending element is the element to be formatted
	
	//added a default failed classname type so we dont have to pass it all the time
    if(newClass == null || newClass == "undefined")
    {
  		newClass = FAILED_CLASSNAME;
  	}
  	//end
  	
  	 //added a default alert type so we dont have to pass it all the time
	 if(alerttype == null || alerttype == "undefined")
	 {
	  	alerttype = DEFAULT_ALERT_TYPE;
	 }
	 //end	

	//check to see if a different field is to be validated
	var ftv = obj.fieldToValidate;
	
	if((ftv != null)) // check on || (ftv != undefined)
    {
       	//get other field to validate
    	var f = document.getElementById(ftv);
  	}
 
	var t = f.type;
	var v = f.value;
	var n;
	
	//get displayName for alert
	if(!obj.displayName == "")
	{
		n = obj.displayName;
	}
	else
	{
		n = obj.name;
	}


  	//Get Validation Type(s), add to array
	var valStr = f.validationType;
	var mySplit = [];
	
	if(valStr.indexOf(",") > 0)
	{
		mySplit = valStr.split(",");
	}
	else
	{
		mySplit[0] = valStr;
	}
	
	var pos = valStr.indexOf("required");
  	//validation for text inputs
	if(t == 'text' || t == 'password' || t == 'textarea' || t=='hidden' || t=='select-one')
	{
	  	for(z = 0; z < mySplit.length; z++)
		{	
			var vType = (mySplit[z]);
			switch (vType)
			{
				case "isMatch":
					if (isMatch(v, document.getElementById(f.comparewith).value))
					{
						obj.className = PASSED_CLASSNAME;
					}
					else
					{
						errors += n +' ' + errormsg[11] + '<br>';
				        errorsa += n +' ' + errormsg[11]+'\n';
				        obj.className = FAILED_CLASSNAME;
						continue;
					}
					break;
				case "isPwd": // HS016425 for validating password
					//2. password and confirm password has to match
					if (!isMatch(v, document.getElementById(f.comparewith).value))
					{
						errors += n +' ' + errormsg[11] + '<br>';
				        errorsa += n +' ' + errormsg[11]+'\n';
				        obj.className = FAILED_CLASSNAME;
				        document.getElementById(f.comparewith).className = FAILED_CLASSNAME;
				        continue;
					}
					//checking for number of character
					//Not sure why this is set to a length of six?  --MS014408							
					if (!isLength(v,6))
					{
						errors += n +' ' + errormsg[17] + '<br>';
				        errorsa += n +' ' + errormsg[17]+'\n';
				        obj.className = FAILED_CLASSNAME;
						continue;
					}
					break; // HS016425: end of code
				case "required": //required field
					if(isEmpty(v))
					{
						errors += n +' ' + errormsg[1] + '<br>';
				        errorsa += n +' ' + errormsg[1]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				    }
					break;
				case "phone" ://for valid US Phone Numbers
				     if(!isPhoneNumber(v))
				     {
				        errors += n +' ' + errormsg[14] + '<br>';
				        errorsa += n +' ' + errormsg[14]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				     }//end if
				     break;
				case "email" : //HS016425 : to validate email
				     if(!isEmail(v))
				     {
				        errors += n +' ' + errormsg[15] + '<br>';
				        errorsa += n +' ' + errormsg[15]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				     }//end if
				     break;
				case "url" :
				     if(!isUrl(v))
				     {
				        errors += n +' ' + errormsg[16] + '<br>';
				        errorsa += n +' ' + errormsg[16]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				     }//end if
				     break;
				case "password" :
				     if(!isPassword(v))
				     {
				        errors += n +' ' + errormsg[17] + '<br>';
				        errorsa += n +' ' + errormsg[17]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				     }//end if
				     break;
				case "alphanumeric" :
				     if(!isAlphaNumeric(v))
				     {
				        errors += n +' ' + errormsg[5] + '<br>';
				        errorsa += n +' ' + errormsg[5]+'\n';
				        obj.className=FAILED_CLASSNAME;
				        continue;
				     }//end if
				     break;
				 case "requiredaplhanumericwithsplcharacter" :
						if(isEmpty(v))
						{
							errors += n +' ' + errormsg[1] + '<br>';
					        errorsa += n +' ' + errormsg[1]+'\n';
					        obj.className=FAILED_CLASSNAME;
				      	}				 
					 	else if (!isAlphaNumericWithSplCharacter(v))
				 		{
					        errors += n.bold() +':' + errormsg[19] + '<br>';
					        errorsa += n.bold() +':' + errormsg[19]+'\n';
					        obj.className=FAILED_CLASSNAME;
					        continue;
				 		}
				 		break;
				case "requiredalphanumeric" :
					if(isEmpty(v))
					{
						errors += n +' ' + errormsg[1] + '<br>';
				        errorsa += n +' ' + errormsg[1]+'\n';
				        obj.className=FAILED_CLASSNAME;
			      	}
				    else if(!isAlphaNumeric(v))
				    {
				       errors += n +' ' + errormsg[5] + '<br>';
				       errorsa += n +' ' + errormsg[5]+'\n';
				       obj.className=FAILED_CLASSNAME;
				       continue;
				    }//end if
				    break;
				case "numeric": //numeric only
					if(!isNumeric(v))
				    {
				        errors += n+errormsg[4]+ '<br>';
					    errorsa += n+errormsg[4]+'\n';
						obj.className = FAILED_CLASSNAME;
						continue;
			        }
					break;
				
				case "requiredNumeric"://required and numeric
					if(isEmpty(v))
					{
						errors += n +' ' + errormsg[1] + '<br>';
				        errorsa += n +' ' + errormsg[1]+'\n';
				        obj.className=FAILED_CLASSNAME;
				    }
					else if(!isNumeric(v))
				    {
				        errors += n+errormsg[4]+ '<br>';
					    errorsa += n+errormsg[4]+'\n';
						obj.className = FAILED_CLASSNAME;
						continue;
			        }
					break;
								
			    case "date": //date field
			       	if(!isEmpty(v))
			    	{
			    	    if(!isDate(v))
			    	    {
						    errors += v+errormsg[10]+ '<br>';
					        errorsa += n+errormsg[10]+'\n';
					        obj.className=newClass;
					        continue;
					    }
					}
			    	if (pos == 0 && isEmpty(v)) //field is required AND Empty, keep failed validation class
			    	{			    		
			    		obj.className=FAILED_CLASSNAME;
				        continue;
			    	}
					break;
			    	
			    case "lengthBetween":
			    	if(!isEmpty(v))
			    	{
				    	//get range values
				    	var r = f.range;
				    				    
			    		if(r != null)		    		
			    		{
					      	locOfDash = r.indexOf("-");
					      	var min = r.substring(0,locOfDash);
					        var max = r.substring(locOfDash+1);
					
					    	if(!isLengthBetween(v,min,max))
					    	{
					    				    			
						        errors += n+errormsg[8] + min + '-' + max + '<br>';
						        errorsa += n+errormsg[8] + min + '-' + max + '\n';
						        obj.className=newClass;
						        continue;
						    }
						}
					}
					if (pos == 0 && isEmpty(v)) //field is required AND Empty, keep failed validation class
			    	{			    		
			    	//alert("meets");
			    		obj.className=FAILED_CLASSNAME;
				        continue;
			    	}
					break;
				
				case 'numberBetween':
				    if(!isEmpty(v))
			    	{
				    	//get range values
				    	var r = f.range;
				    	//alert(r);
			    		if(r != null)		    		
			    		{
					      	//locOfDash = r.indexOf("-");
					      	//var min = r.substring(0,locOfDash);
					        //var max = r.substring(locOfDash+1);
							//alert(min+'::'+max);
							var min = parseInt(r.split('-')[0]);
							var max = parseInt(r.split('-')[1]);							
					    	if(!isNumberBetween(v,min,max))
					    	{
					    				    			
						        errors += n+errormsg[18] + min + '-' + max + '<br>';
						        errorsa += n+errormsg[18] + min + '-' + max + '\n';
						        obj.className=newClass;
						        continue;
						    }
						}
					}
					if (pos == 0 && isEmpty(v)) //field is required AND Empty, keep failed validation class
			    	{			    		
			    	//alert("meets");
			    		obj.className=FAILED_CLASSNAME;
				        continue;
			    	}
					break;	
				case "decimal":
			    	//get range values
			    	var r = f.range;
			    	//alert(r);
		    		if(r != null)		    		
		    		{
				      	//locOfDash = r.indexOf("-");
				      	//var min = r.substring(0,locOfDash);
				        //var max = r.substring(locOfDash+1);
						var min = parseFloat(r.split('-')[0]);
						var max = parseFloat(r.split('-')[1]);							
						//alert(min+'::'+max);						
				    	if(!isValidDecimalNumber(v,min,max))
				    	{
				    				    			
					        errors += n+errormsg[18] + min + '-' + max + '<br>';
					        errorsa += n+errormsg[18] + min + '-' + max + '\n';
					        obj.className=newClass;
					        continue;
					    }
					}
					break;				
		       	case "length": //validate for exact length
		    		if(!isEmpty(v)) //non-empty string
		    		{
		    			if(!isLength(v,f.validationLength))//length does not meet requirements
			    		{
					        errors += n+errormsg[7]+ f.validationLength + ' characters long' + '<br>';
					        errorsa += n+errormsg[7]+ f.validationLength + ' characters long' + '\n';
					        obj.className=newClass;
					        continue;
				      	}
			    	}
			    	if (pos == 0 && isEmpty(v)) //field is required AND Empty, keep failed validation class
			    	{			    		
			    		obj.className=FAILED_CLASSNAME;
				        continue;
			    	}
					break;
				case "fee": //validate for fee value/
					if(!isValidFeeValue(v))
					{
						errors += errormsg[101] + '<br>';
					    errorsa += errormsg[101] + '\n';
					    obj.className=newClass;
					    continue;						
					}
					break;	    
				default:
					break;
			}
		}
	  
		//display errors	  
	 	if(errors != '') 
	 	{
			if(alerttype == '2' || alerttype == '3') {
				//alert("if block1: " + errorsa);
				erroContent = ''+ erroContent + '<tr><td>'+errorsa+'</td></tr>';
				//alert("2 " + erroContent);
	    	}
			if(alerttype == '1' || alerttype == '3') {
	 			 ////alert("if block1: " + errorsa);
				 erroContent = ''+erroContent+ '<tr><td>'+errorsa+'</td></tr>';
				 //alert("1 " + erroContent);
				 return false;
				//return ErrorHandler(errors);
	    	}
	    	
	  	}		
	}	
}

/**
  Just to ensure there is some tab validation that occured
*/

function IsFormValidated(value) {
   if(value == "submit") {   
      return TAB_MESSAGE;
   }
   else {
   	TAB_MESSAGE = "true";
   }
}

function validateForm(submitButton, preCheck, newClass, alerttype,typecall)
{
  var errors = '';
  var errorsa = '';
  var u = undefined;
  var p; //used as field that should be formatted --- for validating hidden fields
  
  //get the form object
  var f = submitButton;
  
  if(preCheck != null)
  {
	ERROR_GLOBAL="false";
	erroContent += preCheck;
  }
  var i,e,t,n,v;
  
  //added a default failed classname type so we dont have to pass it all the time
  if(newClass == null || newClass == "undefined")
  {
  	newClass = FAILED_CLASSNAME;
  }
  //end
  
  //added a default alert type so we dont have to pass it all the time
  if(alerttype == null || alerttype == "undefined")
  {
  	alerttype = DEFAULT_ALERT_TYPE;
  }
  else {
      //pick the alert make it as an error and pass it to the dialog .
      //appicable for all single alerts frm the module
	  ERROR_GLOBAL="false";   
	  erroContent="<tr><td>"+alerttype+"</td></tr>";   
      errorMsgDisplay.showDialog();           
      return false;
  }
   var myErrors = [];
  //end
  //ensure form is present at scope
  if(f != null) {
  	var elementSize = f.elements.length;

  for(i=0; i < elementSize ; i++)
  {
    e = f.elements[i];

    //if(e.optional) continue;
   
    t = e.type;
    n = e.displayName;
    v = e.value;
   // alert(t+n+v);
    //check to see if element has validation
    if (e.validationType != u)
	{
		var str = e.validationType;
		//alert ("field = " + n + '\n' + "validationType = " + str + '\n' );
		
		//if there is an existing className store it and use that
		// 		 instead of PASSED_CLASSNAME
		if ((e.className != '') && (e.className != 'validatorRequired') && (e.className != 'validatorPassed'))
		{
			//alert("existing class (" + f.className+ ") found on " +f.id);
			DEFAULT_CLASSNAME = e.className;
			PASSED_CLASSNAME = DEFAULT_CLASSNAME;
			e.setAttribute("defaultClassName", DEFAULT_CLASSNAME);
		}
		else if (e.getAttribute("defaultClassName"))
		{
			PASSED_CLASSNAME = e.getAttribute("defaultClassName");
		}
		else
		{
			PASSED_CLASSNAME = _PASSED_CLASSNAME;
		}
		
		//check if field is a "Required" field or need Validation
		var pos = str.indexOf("required");
		if (pos != -1 || v != "")
		{
			var retValue = validateField(e);
			if (retValue == false)
			{
				myErrors[i] = 1;
			}
			else
			{
				e.className = PASSED_CLASSNAME;
			}
		}
 		else
		{
			e.className = PASSED_CLASSNAME;
		}
 	}
   }
 }
  if(myErrors.length != 0) 
  {
    //  alert("here isn changeing false");
      ERROR_GLOBAL="false";      
      errorMsgDisplay.showDialog();           
      return false;
  }
  else
  {
	//no errors, submit the form
	//submitForm(submitButton);

	   if(submitButton !="" && submitButton!=null) {
	   	//  alert("here isn changeing true");
	  		ERROR_GLOBAL="true";
	  }
	  return true;
  }
  
}

/*
*This method checks for errors and then gives go ahead for the user
*/
function approveSubmit() {
  
  //alert(ERROR_GLOBAL);
    if(ERROR_GLOBAL=="true"){   
     // alert("true");      
      return true;
    }
    else {
      //alert("false");
      return false;
    }
}



// create the HelloWorld application (single instance)
var errorMsgDisplay = function(){
    
    // define some private variables
    var dialog, showBtn;
    
    // return a public interface
    return {
        showDialog : function(){ 
        document.getElementById('validationerror').innerHTML ="<div></div>";        
        document.getElementById('validationerror').innerHTML = '<div><table style="width:100%;">'+erroContent+'</table></div>'; 
        //to clear the message for next content to be displayed                     
        erroContent='';
          if(!dialog){ // lazy initialize the dialog and only create it once
                dialog = new Ext.BasicDialog("alert-error-dlg", { 
                        modal: true,
                        //shim: true,
                        width: 350,
                        height: 300,
                        shadow: true,
                        minWidth: 300,
                        minHeight: 120
                });
                dialog.addKeyListener(27, dialog.hide, dialog);
                dialog.addButton('Close', dialog.hide, dialog);     
           }
            dialog.show();                   
        },
        hideDisplay : function(){               
       		  dialog.hide();	 
        }
    };
}();

// error msg depends on the language
var errormsg = [];
errormsg[0] = frmwrk_rm.get("Validation_error_select_checkbox");
errormsg[1] = frmwrk_rm.get("Validation_error_cannot_be_empty");
errormsg[2] = frmwrk_rm.get("Validation_error_cannot_use_default_value");
errormsg[3] = frmwrk_rm.get("Validation_error_alpha_only");
errormsg[4] = frmwrk_rm.get("Validation_error_numeric_only");
errormsg[5] = frmwrk_rm.get("Validation_error_alphanumberic_only");
errormsg[6] = frmwrk_rm.get("Validation_error_invalid_email");
errormsg[7] = frmwrk_rm.get("Validation_error_num_characters_exact");
errormsg[8] = frmwrk_rm.get("Validation_error_num_characters_range");
errormsg[9] = frmwrk_rm.get("Validation_error_invalid_phone_us");
errormsg[10] = frmwrk_rm.get("Validation_error_invalid_date");
errormsg[11] = frmwrk_rm.get("Validation_error_does_not_match");
errormsg[12] = frmwrk_rm.get("Validation_error_needs_option_selected");
errormsg[13] = frmwrk_rm.get("Validation_error_needs_file_to_upload");
errormsg[14] = frmwrk_rm.get("Validation_error_invalid_phone"); 
errormsg[15] = frmwrk_rm.get("Validation_error_invalid_email_id");
errormsg[16] = frmwrk_rm.get("Validation_error_invalid_url");
errormsg[17] = frmwrk_rm.get("Validation_error_pwd_length");
errormsg[18] = ' should be between ';
errormsg[19] = 'The only special characters allowed in this field are underscores ( _ ), hyphens ( - ),apostrophes ( \' ) and colons ( : )'; // HS016425
errormsg[99] = frmwrk_rm.get("Validation_warning_erasing_form_info");
errormsg[100] = frmwrk_rm.get("Validation_warning_caps_lock");
errormsg[101] = "Only numbers, commas, and decimal points can be entered in the fee field. Review your entries and then click Save.";
