// form validation function //

// Messages:
	msg1 = '<strong>Oops</strong><br />This is required.';
	msg2 = '<strong>Error</strong><br />Please enter the security code as shown below.';

//

function validate(formName, notRequired, OrderedFields) {

    // take care of optional notRequired parameter
    notRequired = notRequired || new Array ();
    
    if (!testIsValidObject(notRequired) || notRequired=='') {
        notRequired=''
    }

    OrderedFields = OrderedFields || new Array ();
    
    // Get all the Elements of the Form
    var formFields = new Array();
    var form1 = document.getElementById(formName);   
    var thisEl;
    var item;
    var radioButtonFlag;
    
    if (formName == 'frmTAF') { //taf form
       
        var bFriendNameRequired = true; //true for false
        return validateTAF(form1, bFriendNameRequired); 
    
    }
    
    else {  //all other forms
   
        //force form field validation in specific order if OrderedFields is not empty
        if (testIsValidObject(OrderedFields) && OrderedFields != '')
        {
           var OrderedFields_array = OrderedFields.split(",");
           
           for (item=0; item < OrderedFields_array.length; item++)
           { 
	            if (ValidFormFields(form1, notRequired, ltrim(rtrim(OrderedFields_array[item])))==false)
	            {
	                return false;		       
	            }
           }
        }     
        else {
            OrderedFields = '';
        }
             
        for (i=0; i<form1.elements.length; i++) {
            thisEl = form1.elements[i];
            if (OrderedFields.indexOf(thisEl.name) == -1)
            { 
                if (ValidFormFields(form1, notRequired, thisEl.name)==false)
	            {
	                return false;   
	            }  
            }            
        } 
        
   }
   
   return true;
   
}


function ValidFormFields(form1, notRequired, fieldName)
{
    var phoneFlag;
    var FullPhoneNumber ;
    
    thisEl = form1.elements[fieldName];
    
    //to make inlinemsg work.  If no id in this field, give them the id = field name
    if (thisEl.id == '') {
       thisEl.id = thisEl.name 
    }
      
    //window.alert (fieldName);
    
    switch (fieldName)
    {
        case "firstName": 
           if (notRequired.indexOf(fieldName) == -1)
                { if (!validateName(thisEl))  return false; }                           
           break;
        case "lastName":                    
            if (notRequired.indexOf(fieldName) == -1)
            { if (!validateName(thisEl)) return false; }                  
            break;
        case "email":  
            if (notRequired.indexOf(fieldName) == -1)
            { if (!validateEmail(thisEl)) return false; }       
            break;
        case "email2":
        case "emailVerify":
        case "emailConfirm":  
            if (notRequired.indexOf(fieldName) == -1)
            {if (!validateMatch(thisEl, 'email')) return false;}   
            break;
        case "address1":  
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false;} 
            }
            if (!validateAddress(thisEl)) { return false; } 
            break;
        case "address2": 
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false;} 
            }
            if (!validateAddress(thisEl)) { return false; } 
            break;
        case "city":  
            if (notRequired.indexOf(fieldName) == -1)
            { if (!validateRequired(thisEl)) return false; }
            break;
        case "state":  
            if (notRequired.indexOf(fieldName) == -1)
            { if (!validateRequired(thisEl)) return false; }
            break;
        case "zip":  
        case "zipCode":
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false;} 
            }
            if (!validateZip(thisEl, form1)) return false; 
            break;
        case "password": 
            if (notRequired.indexOf(fieldName) == -1)
            { if (!validatePassword(thisEl)) return false; } 
            break;
        case "passwordVerify":                   
            if (notRequired.indexOf(fieldName) == -1)
            {if (!validateMatch(thisEl, 'password')) return false; } 
            break;
        //case "gender":
            
            //if (notRequired.indexOf(fieldName) == -1)
            //{ if (!validateRequired(thisEl)) return false; }
            //window.alert(validateRadios(fieldName));
            //break;
        case "phone":                   
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false;} 
            }
            if (!validatePhone(thisEl,thisEl.value)) {return false;}
            break;
            
        // if phone number has 3 fields
		case "phone1":
		    if (notRequired.indexOf(fieldName) == -1) {	      
                if (!validateRequired(thisEl)) { return false;}   
            }
            if (thisEl.value != '' && thisEl.value.length !=3) {
                inlineMsg(thisEl.name,'<strong>Error</strong><br />Please complete your phone number.',2);
                return false;
            }
            break;
        case "phone2":
		    if (notRequired.indexOf(fieldName) == -1) {	      
                if (!validateRequired(thisEl)) { return false; }   
            }
            if (thisEl.value != '' && thisEl.value.length !=3) {
                inlineMsg(thisEl.name,'<strong>Error</strong><br />Please complete your phone number.',2);
                return false;
            }
            break;
        case "phone3":
		    if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false; }                
            }
            if (thisEl.value != '' && thisEl.value.length !=4) {
                inlineMsg(thisEl.name,'<strong>Error</strong><br />Please complete your phone number.',2);
                return false;
            }
            else {
                if (form1.elements['phone1'].value!='' || form1.elements['phone2'].value!='' || form1.elements['phone3'].value!='') {
                    if (form1.elements['phone1'].value=='' || form1.elements['phone2'].value=='' || form1.elements['phone3'].value=='') 
                    {
                        inlineMsg(thisEl.name,'<strong>Error</strong><br />Please complete your phone number.',2);
                        return false;
                    }
                }
                FullPhoneNumber = form1.elements['phone1'].value + '-' + form1.elements['phone2'].value + '-' + thisEl.value;
                if (FullPhoneNumber!="")
                { if (!validatePhone(thisEl,FullPhoneNumber)) {return false;}}  
            }
            break;
            
        case "birthDate":
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {return false;} 
            }
            if (!validateDOB(thisEl)) return false; 
            break;  
        //if birthDate has 3 fields 
        case "birthMonth":  
            if (notRequired.indexOf(fieldName) == -1)
                { if(!validateBirthMonth(thisEl,true)) {return false;} }
            else
                { if(!validateBirthMonth(thisEl,false)) {return false;} }
            break;
        case "birthDay":
            if (notRequired.indexOf(fieldName) == -1)
                { if(!validateBirthDay(thisEl,true)) {return false;} }
            else
                { if(!validateBirthDay(thisEl,false)) {return false;} }
            break;
       case "birthYear":
            if (notRequired.indexOf(fieldName) == -1)
                { if(!validateBirthYear(thisEl,true)) {return false;} }
            else
                { if(!validateBirthYear(thisEl,false)) {return false;} }
            
            
            if (!validateDOB_3fields(form1.elements['birthMonth'].value, form1.elements['birthDay'].value, thisEl.value)) 
            { return false }
            
            break;

        case "securityCode":  //for old captcha use    
             if (!validateRequired(thisEl)) return false;
             break;
             
        case "CaptchaControl1":  //for new captcha use    
             if (!validateRequired(thisEl)) return false;
             break;           
             
        case "photoEssay":
            var pessay = rtrim(ltrim(form1.photoEssay.value));
            //if (pessay  == "")
            //{
            //    inlineMsg('photoEssay','<strong>Error</strong><br />You must enter an essay.',2);    
           //     return false;
            //}
            //else
            if (pessay  != "")
            {
                if(pessay.split(' ').length > 150 )
                {
                    inlineMsg('photoEssay','<strong>Error</strong><br />The description must be 150 words or less.',2);    
                    return false;
                }
            }
            break;
            
        case "file1":
            if (trim(form1.file1.value) == "")
		    {
			    inlineMsg('file1','<strong>Error</strong><br />Please upload your photo.',2);    
                return false;
		    }		
		    else
		    {	
			        fileTemp = form1.file1.value.toLowerCase();
				    if (fileTemp.indexOf('.jpg')== -1 && fileTemp.indexOf('.gif')== -1 && fileTemp.indexOf('.jpeg')== -1)
				    {
					    inlineMsg('file1','<strong>Error</strong><br />Please upload a jpg or gif file.\n',2);    
                        return false;
				    }
		    }
            break;
            
        default:
            if (thisEl.type != 'hidden') {
                if (notRequired.indexOf(fieldName) == -1) {
                    if (!testIsValidObject(thisEl.type))
                    { 
                        //radio button
                        //if (!validateRadioButton(thisEl, fieldName)) {return false;} 
                        if (!validateRadios(fieldName)) { return false;}  
                    }
                    else
                    {
                        if (!validateRequired(thisEl))  {
                            return false; 
                        }  
                    }  
                }
            }
            break;
    }
    
    return true;
    
}


//taf form validation
function validateTAF(form1, bFriendNameRequired) {

    var error1 = "Friend's name is required.\n";
	var error2 = "A valid email address is required.\n (ex. username@isp.com)"
	var error3 = "Please don't refer the same email address more than once."	
	var error4 = "Please provide an email address in addition to your friend's name.\n"	
	var error5 = "Please refer at least one person."
		
	var inputs = document.getElementsByTagName('input');

	var prevEmails = new Array(inputs.length);
	var j = 0
	
	/*if (trim(form1.yourName.value)=='') {
	    inlineMsg('yourName','Please enter your name.',2);
        form1.yourName.focus();        
        return false;
    }
    if (trim(form1.yourEmail.value)=='') {
	    inlineMsg('yourEmail','Please enter your email.',2);
        form1.yourEmail.focus();   
        return false;
    }
    else {
        if (!validateEmail(form1.yourEmail)) {
            inlineMsg('yourEmail','Please enter an valid email.',2);
            form1.yourEmail.focus(); 
        return false;
        }
    }*/
	
	for(var k=0;k<inputs.length;k++)
	{
		var input = inputs[k];
		//to make inlinemsg work.  If no id in this field, give them the id = field name
        if (input.id == '') {
           input.id = input.name 
        }
		
		// Case 1:  We are looking at a non-empty friendEmail field
		if (trim(input.value)!='' && input.name.substring(0,11)=='friendEmail'){	
			if (bFriendNameRequired) {
			    if (trim(form1.elements["friendName"+trim(input.name.substring(11,13))].value)=="") {
					inlineMsg(document.getElementById(form1.elements["friendName"+trim(input.name.substring(11,13))].name).id,error1,2);
                    input.focus();
                    return false;
				}
			}
			if (!validateFriendEmail(input))
			{
				inlineMsg(input.id,error2,2);
				input.focus();
				return false;
			}
			else
			{
				var i=0;
				for (i=0;i<j;i++) {
					if (trim(input.value) == prevEmails[i])	{
						inlineMsg(input.id,error3,2);
						input.focus();
						return false;
					}
				}
				prevEmails[j++] = trim(input.value)
			}
		}
		
		// Case 2:  We are looking at a non-empty friendName field and the name is required (bFriendNameRequired is true)
		if (bFriendNameRequired && trim(input.value)!='' && input.name.substring(0,10)=="friendName")	{	
			if (trim(form1.elements["friendEmail"+trim(input.name.substring(10,12))].value)=="") {
				inlineMsg(document.getElementById(form1.elements["friendEmail"+trim(input.name.substring(10,12))].name).id,error4,2);
				input.focus();
				return false
			}
		}		
	}
	
	if (j==0)
	{
		inlineMsg(document.getElementById('friendEmail1').id,error5,2);	
		form1.friendEmail1.focus();
		return false
	}	
	return true
}

function testIsValidObject(objToTest) {
    if (objToTest == null || objToTest == undefined) {
    return false;
    }
    return true;
}

// Only to be used on text, checkboxes and single selects.
function validateRequired(element) {
	
	var reqEl = '';
	
	//window.alert (element);
	
	if (element.type=='checkbox') {
    	if (element.checked) {reqEl='1';}
    } else if (element.type=='select-one') {
    	reqEl=element.options[element.selectedIndex].value;   
    } else {
        //window.alert(validateRadios('gender'));
    	var reqEl = element.value;
    }
    reqEl = ltrim(rtrim(reqEl));
    if(reqEl == '') {
      // If you need custom messsages, put in a switch statement here
      switch (element.id)
      {
        case "CaptchaControl1":
            inlineMsg(element.id,msg2,2);
            break;
        case "optin1":
            inlineMsg(element.id,"Please agree to the Terms and Conditions.",2);
            break;
        default:
            inlineMsg(element.id,msg1,2);
      }
      return false;
    }

    return true;
}

function validateMatch(element, matches) {
	
    var reqEl = element.value;
    var matchesEl = document.getElementById(matches).value;
    
    if(reqEl != matchesEl) {
      inlineMsg(element.id,'<strong>Oops</strong><br />Does not match ' + matches +'.',2);
      return false;
    }

    return true;
}

function validateName(element) {
	
    var name = element.value;
    var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;

    if(name == "") {
        inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid name.',2);
        return false;
      }
    if(!name.match(nameRegex)) {
      inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid name.',2);
      return false;
    }
    return true;
}

function validateEmail(element) {
   
    var email = element.value;
    var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;

    if(email == "") {
      inlineMsg(element.id,'<strong>Oops</strong><br />Please enter your email address.',2);
      return false;
    }
    if(!email.match(emailRegex)) {
      inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid email address.',2);
      return false;
    }
    return true;
}

function validateFriendEmail(element) {
   
    var email = element.value;
    var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;

    if (email!='' && email!=null) {
        if(!email.match(emailRegex)) {
          inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid email address.',2);
          return false;
        }
    }
    return true;
}

function validatePassword(element) {
	
    var password = element.value;
    
    var passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
    //var passwordRegex = /^(?=.*[A-Za-z])(?=.*[0-9])(?!.*[^A-Za-z0-9])(?!.*\s).{5,12}$/;
    if(password == "") {
      inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a password.',2);
      return false;
    }
    if(!password.match(passwordRegex)) {
      inlineMsg(element.id,'<strong>Oops</strong><br />Password must be at least six characters and contain one number, one lower case character and one upper case character',2);
      return false;
    }
    return true;
}

function validateAddress(element) {
    
    var address = element.value;
    
    var valstreet_address = new RegExp("[pP]{1}[.]*[oO]{1}[.]*[ ]*[bB]{1}[oO]{1}[xX]{1}");
    
    if (address!='' && address!=null) {
        if (address.match(valstreet_address)!=null) {
            inlineMsg(element.id,'<strong>Error</strong><br />No P.O. Box Allowed in Address.',2);
            return false;
        }
    }
    return true;
}

function validateZip(element, form1) {
	
    var zip = element.value;
    var zipcodeRegex = /^\d{5}([\-]\d{4})?$/;
     
    var stateElement = form1.state; 
    var sStateProv;
    
    if (testIsValidObject(stateElement)) {  //incase no state field  
        if (stateElement.type=='checkbox') {
    	    if (stateElement.checked) {sStateProv='1';}
        } else if (stateElement.type=='select-one') {
    	    sStateProv=stateElement.options[stateElement.selectedIndex].value;   
        } else {
    	    var sStateProv = stateElement.value;
        }
        sStateProv = ltrim(rtrim(sStateProv));
    }
    else {
        sStateProv = '';
    }
    
    if (zip!='' && zip!=null) {    
        //check if the state is Canada province
        if ( sStateProv == "AB" || sStateProv == "BC" || sStateProv == "MB" || sStateProv == "NB" || sStateProv == "NL" || sStateProv == "NT" || sStateProv == "NS" || sStateProv == "NU" || sStateProv == "ON" || sStateProv == "PE" || sStateProv == "QC" || sStateProv == "SK" || sStateProv == "YT" ){
		    if (!isCanadaZipCode(zip)) 	{
			    inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid Canadian postal code.',2);
			    return false;
		    }
	    }
        else {
            if(!zip.match(zipcodeRegex)) {
              inlineMsg(element.id,'<strong>Oops</strong><br />Please enter a valid zip code.',2);
              return false;
            }
        }
    }

    return true;
}

function isCanadaZipCode (zipStr)
{
    var bCanada = (zipStr.length == 7 || zipStr.length == 6) ? true : false;
    //var bUS = (zipStr.length == 5 || zipStr.length == 10) ? true : false;
    //var bValid = (bCanada || bUS) ? true : false;
    var bValid = (bCanada) ? true : false;
    var sSlash = "-";
    var sSpace = " ";
    var usPattern =  /^(\d{5}((-)\d{4})?)$/;
    var canPattern = /^([A-Za-z]\d[A-Za-z]( |-)?\d[A-Za-z]\d)$/;
    
    if (!bValid) {
        sPostal = "Please enter a valid US Zip or Canadian Postal Code.";
        return false;
    }
    
    if (bCanada) {
        if (zipStr.length == 7) {
            if (zipStr.indexOf(sSlash) == -1 && zipStr.indexOf(sSpace) == -1) {
                sPostal = "Canadian postal codes must be formatted as [XXX XXX] or [XXX-XXX].";
                return false;
            } else {
                if (zipStr.search(canPattern) == -1) {
                    sPostal = "The postal code entered is invalid.";
                    return false;
                }
                return true;
            }
        }
        if (zipStr.length == 6) {
            if (zipStr.search(canPattern) == -1) {
                sPostal = "The postal code entered is invalid.";
                return false;
            }
        }
    }
	return true;
}

function validateDOB(element) {
    var birthDate = element.value;
    if (birthDate!='' && birthDate!=null) {
        if(!IsDate(birthDate)){
             inlineMsg(thisEl.id,'<strong>Error</strong><br />You have entered an invalid birthdate.',2);
             return false;
        }
    }
    return true;
}

function validateDOB_3fields(birthMonthValue, birthDayValue, birthYearValue) {

    var birthMonth = birthMonthValue.toUpperCase();
    var birthDay = birthDayValue.toUpperCase();
    var birthYear = birthYearValue.toUpperCase();
    
    if (birthMonth=='' || birthMonth==null || birthMonth=='MM' || birthMonth=='MONTH' )
    {   birthMonth = '' }
    
    if (birthDay=='' || birthDay==null || birthDay=='DD' || birthDay=='DAY' )
    {   birthDay = '' }
    
    if (birthYear=='' || birthYear==null || birthYear=='YYYY' || birthYear=='YEAR' )
    {   birthYear = '' }
    
    var birthDate = birthMonthValue + '/' + birthDayValue + '/' + birthYearValue ;

    if (birthMonth!='' || birthDay!='' || birthYear!='') {
        if (!IsDate(birthDate)){
            inlineMsg(thisEl.id,'<strong>Error</strong><br />Please check all 3 fields and make sure you have entered an invalid birthdate.',2);
            return false;  
        }         
    }

    return true;
}

function validateBirthMonth(element, bBirthMonthRequired) {
    var birthMonth = element.value;
    if (birthMonth=='' || birthMonth==null || birthMonth=='MM' || birthMonth=='MONTH' )
    {   birthMonth = '' }
    
    if (bBirthMonthRequired) {
        if (birthMonth=='') {
            inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth month.',2);
            return false;
        }
    }
    else {   
        if (birthMonth!='') {
            var intMonth = parseInt(birthMonth,10);
            if (!(intMonth >=1 && intMonth <=12)) {
                 inlineMsg(thisEl.id,'<strong>Error</strong><br />You have entered an invalid birth month.',2);
                 return false;
            }
        }
    }
    return true;
}

function validateBirthDay(element, bBirthDayRequired) {
    var birthDay = element.value;
    if (birthDay=='' || birthDay==null || birthDay=='DD' || birthDay=='DAY' )
    {   birthDay = '' }
    
    if (bBirthDayRequired) {
        if (birthDay=='') {
            inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth day.',2);
            return false;
        }
    }
    else { 
        if (birthDay!='') {
            var intDay = parseInt(birthDay,10);
            if (!(intDay >=1 && intDay <=31)) {
                 inlineMsg(thisEl.id,'<strong>Error</strong><br />You have entered an invalid birth day.',2);
                 return false;
            }
        }
    }
    return true;
}

function validateBirthYear(element, bBirthYearRequired) {
    var birthYear = element.value;
    if (birthYear=='' || birthYear==null || birthYear=='YYYY' || birthYear=='YEAR' )
    {   birthYear = '' }
    
    if (bBirthYearRequired) {
        if (birthYear=='') {
            inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth year.',2);
            return false;
        }
    }
    else {   
        if (birthYear=='') {
            var intYear = parseInt(birthYear,10);
            if (intYear < 0 && year.length != 4) {
                 inlineMsg(thisEl.id,'<strong>Error</strong><br />You have entered an invalid birth year.',2);
                 return false;
            }
        }
    }
    return true;
}

function validatePhone(element, phoneNumber) {
	 
    var phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/;

    if (phoneNumber!='' && phoneNumber!=null) {
        if(!phoneNumber.match(phoneRegex)) {
          inlineMsg(element.id,'<strong>Error</strong><br />You have entered an invalid phone number.',2);
          return false;
        }
    }
    return true;
}

function validateRadioButton (element, fieldName) {
    var radioButtonFlag;
    for (var u=0; u<element.length; u++) {   
        if (element[u].checked) {
            radioButtonFlag = true;
            break;
        }
        else {
            radioButtonFlag = false;
        }                        
    }
    if (radioButtonFlag == false) {
        inlineMsg(fieldName,'<strong>Error</strong><br />Please enter the ' + fieldName + '.',2);
        return false;
    } 
    return true;   
}

function validateRadios(fieldName) {
	// Is my radio checked ?
	var opts = document.getElementsByName(fieldName);
	for (var i = 0; i < opts.length; i++) {
	    //window.alert (opts.item(i).id);
	    if (i==0) {var errFieldID = opts.item(i).id;}
		if (opts.item(i).checked) {
			return true;
		}
	}
	inlineMsg(errFieldID,'<strong>Error</strong><br />Please enter the ' + fieldName + '.',2);
    return false;
}


function IsDate (s)
{
	var daysInMonth;
	var year;
	var month;
	var day;
	var delimiter;
	var stemp;
	
	// check for illegal characters
	if (s.search(/[^0-9-\/_]/) != -1)
		return false;
		
	// parse string to get year, month and day
	if (s.search(/\/{1}/) != -1)
		delimiter = "/";
	else
	{
		if (s.search(/-{1}/) != -1)
			delimiter = "-";
		else
			return false;
	}
	stemp = s;
	DelimAt = stemp.indexOf(delimiter);
	month = stemp.substring(0,DelimAt);
	stemp = stemp.substring(DelimAt + 1, stemp.length);
	DelimAt = stemp.indexOf(delimiter);
	day = stemp.substring(0,DelimAt);
	year = stemp.substring(DelimAt + 1, stemp.length);
		
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year,10);
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);
    
	// catch invalid years (not 4-digit)
	if (intYear < 0) return false;
    if (year.length != 4) return false;

	// catch invalid months
	if (!(intMonth >=1 && intMonth <=12)) return false;
	
    // catch invalid days, except for February
    if (!(intDay >=1 && intDay <=31)) return false;
    switch (intMonth)
    {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			daysInMonth = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			daysInMonth = 30;
			break;
		case 2:
			daysInMonth = ((intYear % 4 == 0) && ( (!(intYear % 100 == 0)) || (intYear % 400 == 0) ) ) ? 29 : 28;
			break;
	}
	    
    if (intDay > daysInMonth) return false; 

    return true;
}

// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "../images/msg_arrow.gif"; 
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
function isPhone (s)
{
	var k;
	var valid;
	var stemp;
	var re;
	
	if (s == null)
		return false;
	if (s.length != 12)
       	return false;
    if (s.length == 12 && s.search(/-/) == -1)
		return false;
   	valid = true;
   	re = /-/gi;
   	stemp = s.replace(re, "");
   	for (k=0;k<9;k++)
   	{
       	if (stemp.charAt(k) < "0" || stemp.charAt(k) > "9")
       	{
         	valid = false;
          	break;
       	}
       	
   	}
   	return (valid);
}


