// 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 testIsValidObject(objToTest) {
    if (objToTest == null || objToTest == undefined) {
    return false;
    }
    return true;
}


function validate(formName, notRequired, OrderedFields) {

    // take care of optional notRequired parameter
    notRequired = notRequired || new Array ();
    
    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;
   
    //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;		       
	        }
       }
    }     
    
    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;   
	        }  
        }
    }    
   
}


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 as field name
    if (thisEl.id == '') {
       thisEl.id = thisEl.name 
    }
      
    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 "emailVerify":  
            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 (thisEl.value != '' && !validateAddress(thisEl)) {
                    return false;
            }
            break;
        case "address2": 
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {
                    return false; 
                } 
            }
            if (thisEl.value != '' && !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":  
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {
                    return false; 
                } 
            }
            if (thisEl.value != '' && !validateZip(thisEl)) {
                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 "phone":                   
            if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {
                    return false; 
                } 
            }
            if (thisEl.value != '' && !validatePhone(thisEl,thisEl.value)) {
                return false;
            }
            break;
            
        // if phone number is 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;
                //window.alert(FullPhoneNumber); 
                if (FullPhoneNumber!="")
                {
                    if (!validatePhone(thisEl,FullPhoneNumber))
                    {
                        return false;
                    }
                }
                
            }
            
            break;
        case "birthDate":
           if (notRequired.indexOf(fieldName) == -1) {
                if (!validateRequired(thisEl)) {
                    return false; 
                } 
                else {
                    if (!validateDOB(thisEl)){
                        return false; 
                    }                    
                }
            }
            else {
                if(thisEl.value != "" && !validateDOB(thisEl)){
                    return false;
                }
            }
            break;   
        case "birthMonth":  
            if (notRequired.indexOf(fieldName) == -1)
            {
                if(thisEl.value == "" || thisEl.value == 'MM') {
                    inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth month.',2);
                    return false;
                }                    
            }
            break;
        case "birthDay":
            if (notRequired.indexOf(fieldName) == -1)
            {
                if(thisEl.value == "" || thisEl.value == 'DD') {
                    inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth day.',2);
                    return false;
                }   
            }
            break;
       case "birthYear":
            if (notRequired.indexOf(fieldName) == -1)
            {
                if(thisEl.value == "" || thisEl.value == 'YYYY') {
                    inlineMsg(thisEl.id,'<strong>Error</strong><br />You must enter your birth year.',2);
                    return false;
                }   
            }
            break;
       
        
        case "CaptchaControl1":        
             if (!validateRequired(thisEl)) 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;}   
                    }
                    else
                    {
                        //if (notRequired.indexOf(fieldName) == -1) { 
                            if (!validateRequired(thisEl))  {
                                return false; 
                            }
                        //} 
                    }
                    
                }
            }
    }
       
    return true;
    
}

// Only to be used on text, checkboxes and single selects.
function validateRequired(element) {
	
	var reqEl = '';
    
    if (element.type=='checkbox') {
        //if (element.checked) {reqQel='1';}
    	if (element.checked) {reqEl='1';}
    } else if (element.type=='select-one') {
    	reqEl=element.options[element.selectedIndex].value;   
    } else {
    	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;
        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 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 validateDOB(element) {
    if(!IsDate(element.value)){
         inlineMsg(thisEl.id,'<strong>Error</strong><br />You have entered an invalid birthdate.',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 validateZip(element) {
	
    var zip = element.value;
    var zipcodeRegex = /^\d{5}([\-]\d{4})?$/;
    var sStateProv = trim(document.frmRegister.state.options[document.frmRegister.state.selectedIndex].value);
    
    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 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.match(valstreet_address)!=null) {
        inlineMsg(element.id,'<strong>Error</strong><br />No P.O. Box Allowed in Address.',2);
        return false;
    }
    return true;
}

function validatePhone(element, phoneNumber) {
	
    //var phone = element.value;
    
    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(phone == "") {
    //  inlineMsg(element.id,'<strong>Error</strong><br />You must enter your phone number.',2);
    //  return false;
    //}
    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 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);
}


