/*************************************************************************************

Javascript by Robby Ticknor for Swimbo inc.  2007-2008

Validation


How to use:

    The script requires 3 things.
        1) the object to validate
        2) a box with an astris that we will update
        3) a box to display our message in

    the script will apply a style to the astris box upon failure or sucess.  these styles are required in the css
        Required_met
        Required_again
        Required_failed


    <script>
            var oCurrentElement = document.getElementById("first_name");
            var iCurrentArrayIndex = aValidationObject.length;        
            aValidationObject[iCurrentArrayIndex] = new ValidationObject(oCurrentElement, iCurrentArrayIndex);
            
            aValidationObject[iCurrentArrayIndex].ObjectToDisplayResultsIn( document.getElementById("first_name_message"));
            aValidationObject[iCurrentArrayIndex].RequiredFieldIndicator( document.getElementById("first_name_required"));
            
            //This is the line that sets up the validation.  just add types of validation you want seperated by a camma (no spaces)
            aValidationObject[iCurrentArrayIndex].SetTypeOfValidationToRun("alpha,required");
            
                    
        oCurrentElement.onblur = new Function(aValidationObject[iCurrentArrayIndex].Return_onBlur_Validation_To_Execute());
    </script>
    
    
    Validation types:
    
            password
            email
            maxLength  (must set this.minLength)
            minLength  (Must set this.mixLength)
            alpha
            num
            required
            required_select
            onchange_executeCustomCode    (must set this.onchangeCodeToExecute... will be executed onblur)

    Special Usage:
        
        Passwords:
        
            If you have a password field that needs to crosscheck another field that must be the same, then update these properties
            
                this.oPasswordIDToCrossreference = null;    // Object that we are going to crosscheck
                this.oOtherNameToDisplayResults = null;     // If we need to output any message to end user, here is where it happens
                this.oOtherRequiredFieldIndicator = null;   // If we want to update an astric upon failure.


        Updateing Messages:
        
             If you want to change the message that is displayed to the end user, update these properties.   
                this.PasswordMessage	= "Passwords do not match.<br>";
                this.RequiredField = "This field is Required.<br>";
                this.EmailMessage = "Email addres is invalid.<br>";
                this.MustBeAlphaMessage = "String must only contain Letters. <br>";
                this.MustBeLessMessage = "Must be less then **-TOKEN-**. <br>";
                this.MustBeMoreMessage = "Must be more then **-TOKEN-**. <br>";



*************************************************************************************/

if ((typeof aValidationObject == "undefined"))
	var aValidationObject=new Array();


function ValidationObject(oThisFormElementInput,   iArrayNumber){
    
    this.oFormElementBase = oThisFormElementInput;
    if (this.oFormElementBase == null)
    {
        alert("Validation Config error.  Object number "+ (iArrayNumber + 1) +" to validate not found");
        return false;
    }
    
    this.iThisArrayNumber = iArrayNumber;
    this.sResultsMessage = "";
    this.sObjNameToDisplayResults = null;
    this.sObjRequiredFieldIndicator = null;
    this.bAlertResults = true;
    this.sSuccess = true;
    this.minLength = null;
    this.mixLength = null;
    this.exactLength = null;
    this.maxNum = null;
    this.minNum = null;
    
    this.aValuesNotAloud = null;
    this.bIncludeThisElementInFormValidation = true;
    
    this.onchangeCodeToExecute = null;
    this.selectDefaultValue = null;
    this.oPasswordIDToCrossreference = null;
    this.oOtherNameToDisplayResults = null;
    this.oOtherRequiredFieldIndicator = null;
    this.sThisElementDefaultText = "";
    this.Touched = false;
    this.DefaultValueLoaded = false;
    if (BrowserDetect.browser == "Explorer")
        this.bBrowserIsIE = true;
    this.DefaultBaseInputObjectType = this.oFormElementBase.type;
    
    this.DefaultTextClass = "FormInput_default";
    this.DefaultTextClass_Removed = "FormInput";
    this.DefaultTextClass_Failed = "FormInput";
    
    // Declaring required variables
	this.PhoneValidationdigits = "0123456789";
	// non-digit characters which are allowed in phone numbers
	this.PhoneValidationphoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
	this.PhoneValidationvalidWorldPhoneChars = this.PhoneValidationphoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	this.PhoneValidationminDigitsInIPhoneNumber = 10;
    
    
    this.SaChecksToRun = "";
    
    this.bHideElementOnSuccessValidation = false;
    this.oHideElementOnSuccessValidation = null;
    
    
    this.SuccessValidationMessage = "";
    this.PasswordMessage	= "Passwords do not match";
    this.RequiredField = "Required";
    this.EmailMessage = "Invalid e-mail";
    this.MustBeAlphaMessage = "Letters only (no numbers or special characters)";
    this.MustBeNumMessage = "Numbers only";
    this.MustBeLessMessage = "Must be less then or equal to **-TOKEN-** characters";
    this.MustBeMoreMessage = "At least **-TOKEN-** characters";
    this.PhoneNumberInvlaid = "Invalid Phone Number";
    this.NumberMustBeLessThan = "Must be less then **-TOKEN-**";
    this.NumberExactLengthMessage = "Length must be **-TOKEN-**";
    
    this.ValuesAlredySavedMessage = "'**-TOKEN-**' already used";
    
    this.GetURLMessage = "URL is not valid";
    this.GetDateMessage = "Date is not valid";
    this.GetDateElapsedMessage = "This Date has already elapsed.  Please enter a future date";
    
    
    
    this.ValidationFormMessageClass = "FormMessage";
    this.ValidationFormMessageClass_Success = "FormMessage_Off";
    
    
    
    return this;
    
}

ValidationObject.prototype.ReturnResults = function()
    {
        return this.sResultsMessage ;
    }
    
ValidationObject.prototype.SetTypeOfValidationToRun = function(sArrayListOfChecksToRun)
    {
        this.SaChecksToRun = sArrayListOfChecksToRun;
    }
    
ValidationObject.prototype.ReturnValidationObj = function()
    {
        
        return this.oFormElementBase;
        
    } 
    
ValidationObject.prototype._Failed = function()
    {
        
        if (this.sSuccess == true)
            this.sSuccess = false;
        
    }    
    
    
ValidationObject.prototype._Success = function()
    {
        if (this.sSuccess == false)
            this.sSuccess = false;
            else
            this.sSuccess = true;
    }  
    
ValidationObject.prototype._GetLessThenMessage = function()
    {
       return this.MustBeLessMessage.replace("**-TOKEN-**",this.maxLength);
    }     

ValidationObject.prototype._GetMoreThenMessage = function()
    {
       return this.MustBeMoreMessage.replace("**-TOKEN-**",this.minLength);
    }      
   
ValidationObject.prototype._NumberMustBeLessThan = function()
    {
       return this.NumberMustBeLessThan.replace("**-TOKEN-**",this.maxNum);
    } 
    
ValidationObject.prototype._GetExactLengthMessage = function()
    {
       return this.NumberExactLengthMessage.replace("**-TOKEN-**",this.exactLength);
    } 
 
 
 ValidationObject.prototype._GetValuesAlredySavedMessage = function(sFoundText)
    {
       return this.ValuesAlredySavedMessage.replace("**-TOKEN-**",sFoundText);
    }

        

ValidationObject.prototype.ObjectToDisplayResultsIn = function(sID){

    this.sObjNameToDisplayResults =sID;
}


ValidationObject.prototype.Init_Events = function() // doe snot work yet
{

    //oCurrentElement.onblur = new Function(aValidationObject[iCurrentArrayIndex].Return_onBlur_Validation_To_Execute());
    eval ('var fonBlur = function (event) { aValidationObject["'+this.iThisArrayNumber+'"].Return_onBlur_Validation_To_Execute();}');
    
    AddEvent(this.oFormElementBase, 'onblur', fonBlur);
         

}



ValidationObject.prototype.RequiredFieldIndicator = function(sID){

    this.sObjRequiredFieldIndicator =sID;
}

ValidationObject.prototype.bVerifyResultsAndSetMessage = function(){


        //alert(this.oFormElementBase.id + " before: " + this.sSuccess);  
        this.sSuccess = true;  
        this.RemoveDefaultText();
        this.ReValidateOnSubmitNow();
        //alert(this.oFormElementBase.id + " after: " + this.sSuccess);    

        this.DisplaySuccess(this.sSuccess);
    
        if (!this.sSuccess){
        
               if (this.bHideElementOnSuccessValidation)
            	   if (this.oHideElementOnSuccessValidation != null)
            		   this.oHideElementOnSuccessValidation.style.display = "";
                                
                //this.oFormElementBase.focus();
                if (this.sObjNameToDisplayResults != null)
                    {
                        this.sObjNameToDisplayResults["className"] = this.ValidationFormMessageClass;
                        this.sObjNameToDisplayResults.innerHTML = this.sResultsMessage;
                        if (this.oPasswordIDToCrossreference != null) // if we are validation a password, need to add message to other password box
                            {
                                if (this.oPasswordToCrossreferenceNameToDisplayResults != null)
                                    this.oPasswordToCrossreferenceNameToDisplayResults.innerHTML = this.sResultsMessage;
                            
                            }
                        
                        
                        this.sResultsMessage = "";
                    }
                    else
                    alert(this.sResultsMessage);
                
                
                return false;
                
            }
            else
            {
            	if (this.bHideElementOnSuccessValidation)
             	   if (this.oHideElementOnSuccessValidation != null)
             		   this.oHideElementOnSuccessValidation.style.display = "none";
            	
                this.sResultsMessage = "";
                if (this.sObjNameToDisplayResults != null)
                    {
                        this.sObjNameToDisplayResults["className"] = this.ValidationFormMessageClass_Success;
                        this.sObjNameToDisplayResults.innerHTML = this.SuccessValidationMessage;
                    }
                this.sSuccess = true;
                return true;
            }
    
}


ValidationObject.prototype.DisplaySuccess = function(bYesNo){

    var oRequiredField =  this.sObjRequiredFieldIndicator;

    if (oRequiredField != null)
    {
        if (bYesNo)
            {
                oRequiredField["className"] = "Required_met";
            
            }
            else
            {
                oRequiredField["className"] = "Required_again";
                this.oFormElementBase["className"]= this.DefaultTextClass_Failed;
                
                if (this.oPasswordIDToCrossreference != null)
                {
                    if (this.oOtherRequiredFieldIndicator != null)
                        this.oOtherRequiredFieldIndicator["className"] = "Required_again";
                
                }
                
                
            }
    }
    
}



ValidationObject.prototype.VerifyResults = function(){

    this.DisplaySuccess(this.sSuccess);
    
   if (!this.sSuccess){
            
	   if (this.bHideElementOnSuccessValidation)
    	   if (this.oHideElementOnSuccessValidation != null)
    		   this.oHideElementOnSuccessValidation.style.display = "";
                                
                //this.oFormElementBase.focus();
                if (this.sObjNameToDisplayResults != null)
                    {
                        this.sObjNameToDisplayResults["className"] = this.ValidationFormMessageClass;
                        this.sObjNameToDisplayResults.innerHTML = this.sResultsMessage;
                        
                        if (this.oPasswordIDToCrossreference != null) // if we are validation a password, need to add message to other password box
                            {
                                if (this.oOtherNameToDisplayResults != null)
                                    this.oOtherNameToDisplayResults.innerHTML = this.sResultsMessage;
                            
                            }
                        this.sResultsMessage = "";
                    }
                    else
                    alert(this.sResultsMessage);
                
            }
            else
            {
            	if (this.bHideElementOnSuccessValidation)
             	   if (this.oHideElementOnSuccessValidation != null)
             		   this.oHideElementOnSuccessValidation.style.display = "none";
            	
                this.sResultsMessage = "";
                 if (this.sObjNameToDisplayResults != null)
                    {
                        this.sObjNameToDisplayResults["className"] = this.ValidationFormMessageClass_Success;
                        this.sObjNameToDisplayResults.innerHTML = this.SuccessValidationMessage;
                    }
            }
            
   
    this.sSuccess = true;
    return this;
    
}



ValidationObject.prototype.Return_onBlur_Validation_To_Execute = function()
    {

    
    var sReturnStringToExecute = "";
    var aValidationList = this.SaChecksToRun.split(",");
    
    sReturnStringToExecute += "aValidationObject["+ this.iThisArrayNumber +"]";


        for (var i = 0; i < aValidationList.length; i++){
            switch (aValidationList[i]){
                                
                    case 'password':{
                        sReturnStringToExecute += ".Validate_Password(this)";
                    break;
                    }
                    
                    case 'email':{
                        sReturnStringToExecute += ".isValidEmail(this)";
                    break;
                    }
                    
                    case 'maxLength':{
                        if (this.maxLength != null)
                            sReturnStringToExecute += ".Validate_maxLength(this)";
                    
                    break;
                    }
                    
                    case 'minLength':{
                    
                        if (this.minLength != null)
                            sReturnStringToExecute += ".Validate_minLength(this)";
                    break;
                    }
                    
                    case 'phone':{
                        sReturnStringToExecute += ".Validate_PhoneNumber(this)";
                    break;
                    }
                    
                    case 'alpha':{
                        sReturnStringToExecute += ".Validate_Alpha(this)";
                    break;
                    }
                    
                    case 'lname':{
                        sReturnStringToExecute += ".Validate_Last_Name(this)";
                    break;
                    }
                    
                    case 'num':{
                        sReturnStringToExecute += ".Validate_Num(this)";
                    break;
                    }
                    
                    case 'exactlength':{
                        sReturnStringToExecute += ".Validate_exactLength(this)";
                    break;
                    }
                    
                    case 'int':{
                        sReturnStringToExecute += ".Validate_INT_Num(this)";
                    break;
                    }
                    
                    case 'url':{
                        sReturnStringToExecute += ".Validate_URL(this)";
                    break;
                    }
                    
                    
                    case 'validate_values_does_not_exist':{
                        sReturnStringToExecute += ".Validate_Values_Does_Not_Exist(this)";
                    break;
                    }
                    
                    case 'date':{
                        sReturnStringToExecute += ".Validate_Date(this)";
                    break;
                    }
                    
                    case 'date_not_elspsed':{
                        sReturnStringToExecute += ".Validate_DateElapsed(this)";
                    break;
                    }
                    
                    case 'required_tinyMCE':{
                        sReturnStringToExecute += ".Required_tinyMCE_Check(this)";
                    break;
                    }
                    
                    case 'required':{
                        sReturnStringToExecute += ".Required_Field_Check(this)";
                    break;
                    }
                    
                    
                    case 'required_select':{
                        sReturnStringToExecute += ".Required_Select_Check(this)";
                    break;
                    }
                    
                    case 'max_num':{
                        sReturnStringToExecute += ".Max_Num(this)";
                    break;
                    }
                    case 'min_num':{
                        sReturnStringToExecute += ".Min_Num(this)";
                    break;
                    }
                    
                    case 'onchange_executeCustomCode':{
                        sReturnStringToExecute += ".On_Change_ExecuteCustomCode(this)";
                    break;
                    }
                    
                    case 'onSave_executeCustomCode':{
                        sReturnStringToExecute += ".On_Change_ExecuteCustomCode(this)";
                    break;
                    }
                    
             }

        }
        
        
        sReturnStringToExecute += ".VerifyResults().ReCheckDefaultText(); "; 

        return sReturnStringToExecute;


}



///
// Function takes the current object (the second password box), and the name of the first pass
// word box.  
ValidationObject.prototype.Validate_Password = function(oThis)
{

    var oFirstPassword = this.oPasswordIDToCrossreference;
    
    
    if (oFirstPassword.value != "")
        if (this.oFormElementBase.value == oFirstPassword.value){// good to go, save data
                //oAjax.ajax_Save_This_Form_Element_Information(oThis);
                //Required_Field_Check(oThis, oThis.id + "_required");
                this._Success();
                return this;
            }else
            {
                oFirstPassword.value = "";
                this.oFormElementBase.value = "";
               // Required_Field_Check(oThis, oThis.id + "_required");
                //Required_Field_Check(oFirstPassword, oFirstPassword.id + "_required");
                this.sResultsMessage = this.PasswordMessage;
                
                this._Failed();
                return this;
            
            }
    else
        return this;
    
    
}



ValidationObject.prototype.Required_Field_Check = function(oThis)
{

    
    var oRequiredField =  this.sObjRequiredFieldIndicator;

    if (oRequiredField != null)
    {
        if (this.oFormElementBase.value.length > 0)
            {
                this._Success();
            }
            else{
                this.sResultsMessage = this.RequiredField;
                this._Failed();
            }
            
                
        }
        else
        {
            alert("Error: Must set Required field ID");
        }
        return this;

}


ValidationObject.prototype.Required_tinyMCE_Check = function(oThis)
{


//setTimeout ("alert(tinyMCE.get(document.getElementById('answerFaq').id).getContent());", 1000);
    
    var oRequiredField =  this.sObjRequiredFieldIndicator;

    if (oRequiredField != null)
    {
    
        var oText = tinyMCE.get(this.oFormElementBase.id).getContent();
    
         
        if (oText.length > 0)
            {
                this._Success();
            }
            else{
                this.sResultsMessage = this.RequiredField;
                this._Failed();
            }
            
                
        }
        
        
        return this;

}



ValidationObject.prototype.Required_Select_Check = function(oThis)
{

    var oRequiredField = this.oFormElementBase;
    
    if (oRequiredField.selectedIndex != -1)
    {
        var sSelectedValue = this.oFormElementBase.options[oRequiredField.selectedIndex].value;
            
        if (sSelectedValue != this.selectDefaultValue)
            {
                this._Success();
            }
            else{
                this.sResultsMessage = this.RequiredField;
                this._Failed();
            }
            
            
    }else{
            this.sResultsMessage = this.RequiredField;
            this._Failed();
        }
    
    
        return this;



}


ValidationObject.prototype.isValidEmail = function(oThis)
{



    var val = this.oFormElementBase.value;
       
    if (val != ""){
        val = val.toLowerCase( );
        if (val.indexOf("@") > 1) {
            var addr = val.substring(0, val.indexOf("@"));
            var domain = val.substring(val.indexOf("@") + 1, val.length);
            // at least one top level domain required
            if (domain.indexOf(".") == -1) {
                this.sResultsMessage = this.EmailMessage;
                
                this._Failed();
                return this;
            }
            // parse address portion first, character by character
            for (var i = 0; i < addr.length; i++) {
                oneChar = addr.charAt(i).charCodeAt(0);
                // dot or hyphen not allowed in first position; dot in last
                if ((i == 0 && (oneChar == 45 || oneChar == 46))  || 
                    (i == addr.length - 1 && oneChar == 46)) {
                    this.sResultsMessage = this.EmailMessage;
                    this._Failed();
                    return this;
                }
                // acceptable characters (- . _ 0-9 a-z)
                if (oneChar == 45 || oneChar == 46 || oneChar == 95 || 
                    (oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123))
    {
                    continue;
                } else {
                    this.sResultsMessage = this.EmailMessage;
                    this._Failed();
                    return this;
                }
            }
            for (i = 0; i < domain.length; i++) {
                oneChar = domain.charAt(i).charCodeAt(0);
                if ((i == 0 && (oneChar == 45 || oneChar == 46)) || 
                    ((i == domain.length - 1  || i == domain.length - 2) && oneChar == 46))
    {   
                    this.sResultsMessage = this.EmailMessage;
                    this._Failed();
                    return this;
                }
                if (oneChar == 45 || oneChar == 46 || oneChar == 95 || 
                    (oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123))
    {
                    continue;
                } else {
                    this.sResultsMessage = this.EmailMessage;
                    this._Failed();
                    return this;
                }
            }
            this._Success();
            return this;
        }
            this._Failed();
           this.sResultsMessage = this.EmailMessage;
    }
    else
        this._Success();
        
    return this;
}





ValidationObject.prototype.Validate_maxLength = function(oThis)
{

    
    if (this.oFormElementBase.value.length >  this.maxLength){
            this.sResultsMessage = this._GetLessThenMessage();
            this._Failed();
            return this;
        }
        else
        {
            this._Success();
            return this;
        
        }

}


ValidationObject.prototype.Validate_exactLength = function(oThis)
{
	

     if (this.oFormElementBase.value.length == this.exactLength || this.oFormElementBase.value == ''){
            this._Success();
            return this;
            }
        else
        {
            this.sResultsMessage = this._GetExactLengthMessage();
            this._Failed();
            return this;
        }
}


ValidationObject.prototype.Validate_minLength = function(oThis)
{
	if (this.oFormElementBase.value.length > 0)
     if (this.oFormElementBase.value.length >= this.minLength){
        this._Success();
        return this;
        }
        else
        {
        this.sResultsMessage = this._GetMoreThenMessage();
        this._Failed();
        return this;
        }
	
	return this;
}

ValidationObject.prototype.On_Change_ExecuteCustomCode = function(oThis)
{

        if (this.onchangeCodeToExecute != null)
        {
            eval( this.onchangeCodeToExecute);
        }
        
        return this;

}

ValidationObject.prototype.Max_Num = function(oThis)
{

    if (this.oFormElementBase.value.length > 0)
        if (!isNaN(this.oFormElementBase.value))
         if (this.oFormElementBase.value <= this.maxNum){
            this._Success();
            return this;
            }
            else
            {
            this.sResultsMessage = this._NumberMustBeLessThan();
            this._Failed();
            return this;
            }
        else
        {
            this.sResultsMessage = this._NumberMustBeLessThan();
            this._Failed();
            return this;
        }
    return this;
}


ValidationObject.prototype.Min_Num = function(oThis)
{

if (this.oFormElementBase.value.length > 0)
    if (!isNaN(this.oFormElementBase.value))
     if (this.oFormElementBase.value >= this.minNum){
        this._Success();
        return this;
        }
        else
        {
        this.sResultsMessage = this._NumberMustBeLessThan();
        this._Failed();
        return this;
        }
    else
    {
        this.sResultsMessage = this._NumberMustBeLessThan();
        this._Failed();
        return this;
    }

return this;
    
}



ValidationObject.prototype.Validate_Values_Does_Not_Exist = function(oThis)
{

    var bValueFound = false;
    var sFoundValue = "";

    if (this.oFormElementBase.value != "")
        {
            if ( (this.aValuesNotAloud != null) && (this.aValuesNotAloud.length > 0))
            {
            
                for (ExcludeString in this.aValuesNotAloud)
                {
                
                 if (this.aValuesNotAloud[ExcludeString].toLowerCase()  == this.oFormElementBase.value.toLowerCase())
                    { 
                    bValueFound = true;
                    sFoundValue = this.aValuesNotAloud[ExcludeString];
                    }
                
                
                }
            }
        
        
        
     if (!bValueFound){
        this._Success();
        return this;
        }
        else
        {
        this.sResultsMessage = this._GetValuesAlredySavedMessage(sFoundValue);
        this._Failed();
        return this;
        }
        
        
      }

    return this;

}


ValidationObject.prototype.Validate_URL = function(oThis)
{

    
    var sURL = this.oFormElementBase.value;
    
    var RegExp = /^(([\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})*)?$/;
    if (sURL != "")
        {
            if(!RegExp.test(sURL))
            {
                this.sResultsMessage = this.GetURLMessage;
                this._Failed();
                return this;
            }else{
            this._Success();
            return this;
            }
        }
        else
            return this;
}


ValidationObject.prototype.Validate_Date = function(oThis)
{
   var sDate = this.oFormElementBase.value;
    
   var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    //var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay mm/dd/yyyy.';
    
    if (sDate != "")
    {
        
        if (!RegExPattern.test(sDate) ) {
            this.sResultsMessage = this.GetDateMessage;
                this._Failed();
                return this;
            
        }else    
         {
            this._Success();
            return this;
            }   
     }else    
         {
            this._Success();
            return this;
            }   
     
}


ValidationObject.prototype.Validate_DateElapsed = function(oThis)
{
   var sDate = this.oFormElementBase.value;
    
    
    if ((sDate != "") || (sDate != "Never")) // if sDate is blank, do nothing
    {
         var dDateToValidate = new Date(sDate); // convert string to date object
   
        var dCurrentTime = new Date();
        
            if (dDateToValidate.getTime() <  dCurrentTime.getTime() ) {
                this.sResultsMessage = this.GetDateElapsedMessage;
                    this._Failed();
                    return this;
                
            }else    
             {
                this._Success();
                return this;
                }   
     }else    
         {
            this._Success();
            return this;
            }   
     
}





	ValidationObject.prototype.Validate_PhoneNumber = function(oThis)
	{
	
	    var Phone = this.oFormElementBase;
	    		
		if ((Phone.value==null)||(Phone.value=="")){
				// since we are not checking required here, we just want to exit if it's blank
			    return this;
		}
		if (this.checkInternationalPhone(Phone.value)==false){
				this._Failed();
			    this.sResultsMessage = this.PhoneNumberInvlaid;
			    return this;
		}
	
	
	
	 return this;
	
	}



	//Part of phone validation
	ValidationObject.prototype.checkInternationalPhone = function(strPhone)
		{
			s= this.stripCharsInBag(strPhone,this.PhoneValidationvalidWorldPhoneChars);
			return (this.isInteger(s) && s.length >= this.PhoneValidationminDigitsInIPhoneNumber);
		}
		
		
	ValidationObject.prototype.isInteger = function(s)
		{   var i;
		    for (i = 0; i < s.length; i++)
		    {   
		        // Check that current character is number.
		        var c = s.charAt(i);
		        if (((c < "0") || (c > "9"))) return false;
		    }
		    // All characters are numbers.
		    return true;
		}
		
	ValidationObject.prototype.stripCharsInBag = function(s, bag)
		{   var i;
		    var returnString = "";
		    // Search through string's characters one by one.
		    // If character is not in bag, append to returnString.
		    for (i = 0; i < s.length; i++)
		    {   
		        // Check that current character isn't whitespace.
		        var c = s.charAt(i);
		        if (bag.indexOf(c) == -1) returnString += c;
		    }
		    return returnString;
		}
	// END Part of phone validation




ValidationObject.prototype.Validate_Alpha = function(oThis)
{

    var numaric = this.oFormElementBase.value;
        
	for(var i=0; i< numaric.length ; i++)
		{
		  var alphaa = numaric.charAt(i);
		  var hh = alphaa.charCodeAt(0);
		  if( (hh > 64 && hh<91) || (hh > 96 && hh<123))
		  {
		    this._Success();
		  }
		else	{
		    
		    this._Failed();
		    this.sResultsMessage = this.MustBeAlphaMessage;
		    return this;
		  }
		}
 return this;

}
	
ValidationObject.prototype.Validate_Last_Name = function(oThis)
{

    var numaric = this.oFormElementBase.value;
        
	for(var i=0; i< numaric.length ; i++)
		{
		  var alphaa = numaric.charAt(i);
		  var hh = alphaa.charCodeAt(0);
		  if( (hh > 64 && hh<91) || (hh > 96 && hh<123) || (alphaa == " ") || (alphaa == "-"))
		  {
		    this._Success();
		  }
		else	{
		    
		    this._Failed();
		    this.sResultsMessage = this.MustBeAlphaMessage;
		    return this;
		  }
		}
 return this;

}

ValidationObject.prototype.Validate_Num = function(oThis)
{
    var numaric = this.oFormElementBase.value;
        
	if (this.oFormElementBase.value.length > 0)
		 if(!isNaN(numaric))
		  {
		    this._Success();
		  }
		else	
		    {
		    this._Failed();
		    this.sResultsMessage = this.MustBeNumMessage;
			return this;
		  
		}
 return this;
}



ValidationObject.prototype.Validate_INT_Num = function(oThis)
{
    var numaric = this.oFormElementBase.value;
        
	for(var i=0; i< numaric.length ; i++)
		{
		  var alphaa = numaric.charAt(i);
		  var hh = alphaa.charCodeAt(0);
		 if((hh > 47 && hh<59) )
		  {
		    this._Success();
		  }
		else	{
		    this._Failed();
		    this.sResultsMessage = this.MustBeNumMessage;
			 return this;
		  }
		}
 return this;
}


ValidationObject.prototype.ReValidateOnSubmitNow = function()
    {

    
    var sReturnStringToExecute = "";
    var aValidationList = this.SaChecksToRun.split(",");
    


        for (var i = 0; i < aValidationList.length; i++){
            //alert(aValidationList[i]);
        
            switch (aValidationList[i]){
                                
                    case 'password':{
                        this.Validate_Password(this,'Password1');
                    break;
                    }
                    
                    case 'email':{
                        this.isValidEmail(this);
                    break;
                    }
                    
                    case 'maxLength':{
                        if (this.maxLength != null)
                            this.Validate_maxLength(this);
                    
                    break;
                    }
                    
                    case 'minLength':{
                    
                        if (this.minLength != null)
                            this.Validate_minLength(this);
                    break;
                    }
                    
                    case 'phone':{
                        this.Validate_PhoneNumber(this);
                    break;
                    }
                    
                    case 'alpha':{
                        this.Validate_Alpha(this);
                    break;
                    }
                    
                    case 'lname':{
                        this.Validate_Last_Name(this);
                    break;
                    }
                    
                    case 'num':{
                        this.Validate_Num(this);
                    break;
                    }
                    case 'int':{
                        this.Validate_INT_Num(this);
                    break;
                    }
                    
                    case 'exactlength':{
                        this.Validate_exactLength(this);
                    break;
                    }
                    
                    case 'validate_values_does_not_exist':{
                        this.Validate_Values_Does_Not_Exist(this);
                    break;
                    }
                    
                    
                    case 'url':{
                        this.Validate_URL(this);
                    break;
                    }
                    
                    case 'date':{
                        this.Validate_Date(this);
                    break;
                    }
                    
                    case 'date_not_elspsed':{
                        this.Validate_DateElapsed(this);
                    break;
                    }
                    
                    case 'max_num':{
                        this.Max_Num(this);
                    break;
                    }
                    
                    case 'min_num':{
                        this.Min_Num(this);
                    break;
                    }
                    
                    case 'required':{
                        this.Required_Field_Check(this);
                    break;
                    }
                    
                     case 'required_tinyMCE':{
                        this.Required_tinyMCE_Check(this);
                    break;
                    }
                    
                     case 'required_select':{
                        this.Required_Select_Check(this);
                        
                    break;
                    }
                     
                     case 'onSave_executeCustomCode':{
                         this.On_Change_ExecuteCustomCode(this);
                         
                     break;
                     }
                    
                   
                    
                    
             }

        }
        
        
}
	


    //This function sets up the default text that displays in the form input boxes
    ValidationObject.prototype.SetDefaultText = function(sDefaultText)
    {
        if (this.oFormElementBase.value == "")
        {
            this.sThisElementDefaultText = sDefaultText;
            this.oFormElementBase["className"] = this.DefaultTextClass;
            this.oFormElementBase.value = this.sThisElementDefaultText;
            this.oFormElementBase.onfocus = new Function("aValidationObject[" + this.iThisArrayNumber + "].RemoveDefaultText();");
            
            
            if ((this.DefaultBaseInputObjectType == "password") && (!this.bBrowserIsIE))
                this.oFormElementBase.type = "text";
              
            if ((this.DefaultBaseInputObjectType == "password") && (this.bBrowserIsIE))
            {
                this.sThisElementDefaultText = ""; // IS is retarded, this compensates for it's lack of support
                this.oFormElementBase.value = "";  // it gets confusing if we set a default value and we can't change the type from password to text 
                
             }
        }
       
    }
    
    
    
    ValidationObject.prototype.RemoveDefaultText = function()
    {
        if (this.oFormElementBase.value == this.sThisElementDefaultText) 
        {
            this.oFormElementBase.value = "";
            this.oFormElementBase["className"] = this.DefaultTextClass_Removed;
            
            if ((this.DefaultBaseInputObjectType == "password")&& (!this.bBrowserIsIE))
                this.oFormElementBase.type = "password";
        }
        
    }

    ValidationObject.prototype.ReCheckDefaultText = function()
    {
     
        if (this.oFormElementBase.value == "")
            {
            
                this.SetDefaultText(this.sThisElementDefaultText);
            
                if ((this.DefaultBaseInputObjectType == "password") && (!this.bBrowserIsIE))
                    this.oFormElementBase.type = "text";
                  
                if ((this.DefaultBaseInputObjectType == "password") && (this.bBrowserIsIE))
                {
                    this.sThisElementDefaultText = ""; // IS is retarded, this compensates for it's lack of support
                    this.oFormElementBase.value = "";  // it gets confusing if we set a default value and we can't change the type from password to text 
                    
                 }
            }
            else
            {
                this.RemoveDefaultText();
            }
           
            
            return this;
    }
    
    //When we have a country drop down, we need to reset the texe when the country changes
    ValidationObject.prototype.ZipCodeResetDefaultText = function(sNewDefaultText, iISOCountryCode)
    {
     
        if (iISOCountryCode == "231")  // set max length if we choose USA
                    this.maxLength = 5;
                    else
                    this.maxLength = 10;
               
               
        // if they change the country, we will clear anything they have already typed            
        this.oFormElementBase.value = "";
        this.SetDefaultText(sNewDefaultText);
   
            
            
            return this;
    }



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function FindValidationObjectByValidatorName(sObjectID){

    var iCurrentArrayIndex = aValidationObject.length;  
                        
        for (i = 0; i < iCurrentArrayIndex; i++){
        
            //alert(i +" -> "+ aValidationObject[i].SaChecksToRun);
            
            if (aValidationObject[i].ReturnValidationObj().id == sObjectID)
                {
                    
                    return aValidationObject[i];
                
                }
                
        
        
        }


}
