var theForm;

function fieldValidate(fieldType,fieldValue) {
    if (fieldType == "name") {
        var reNames = /^([A-Za-z][A-Za-z\-\s\'.]+)$/;
        if(!reNames.test(fieldValue)) {
          return false;
        }
    }
    else if (fieldType == "email") {
       var reEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
       if(!reEmail.test(fieldValue)) {
          return false;
       }
    }
    else
        alert("ERROR - Invalid type");
    return(true);
}


function checkAge(birthMonth,birthDay,birthYear,minAge) {
    var iMonth = parseInt(birthMonth) - 1;
    var iDay = parseInt(birthDay);
    var iYear = parseInt(birthYear);
    var iMinAge = parseInt(minAge);

	var theirDate = new Date((iYear + iMinAge), iMonth, iDay);
	var today = new Date;
    today.getTime();     
           // use this if getting the date client-side
    //today.setFullYear(2008,11,18);      //use this if using server date (replace the 3 numbers; need to subtract 1 from month, js starts with 0)
	if ((today - theirDate.getTime()) < 0) {
		optin.errorMsgText = "You must be a minimum of " + iMinAge + " years old to sign up.";
		return false;
	}

	if ((birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11) && birthDay == 31){
		optin.errorMsgText = "Invalid date. (only 30 days in that month)";
		return false;
	}
	
	if (birthMonth == 2 && birthDay > 29){
		optin.errorMsgText = "Invalid date. (only 28 or 29 days in Feb)";
		return false;
	}
	
	if (birthMonth == 2 && birthDay == 29 && !(birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0))){
		optin.errorMsgText = "Invalid date. (not a leap year)";
		return false;
	}
	
	else {
		return true;
	}
}

function formValidate(theForm) {
    var firstName = trimField(theForm.fname.value);
    var lastName = trimField(theForm.lname.value);
    var email = trimField(theForm.email.value);
    var country = "USA";

    if (firstName != "" && !fieldValidate("name",firstName)) {
        optin.errorMsgText = "Please re-enter your first name - only letters, spaces, and apostrophes are allowed.";
        theForm.fname.value = "";
        theForm.fname.focus();
        clearErrorClass();
        document.getElementById("fnameLbl").className = "error";
        return(false);   
    }

    if (lastName != "" && !fieldValidate("name",lastName)) {
        optin.errorMsgText = "Please re-enter your last name - only letters, spaces, and apostrophes are allowed.";
        theForm.lname.value = "";
        theForm.lname.focus();
        clearErrorClass();
        document.getElementById("lnameLbl").className = "error";
        return(false);    
    }


    if (email == "") {
        optin.errorMsgText = "Please enter your email address.";
        theForm.email.value = "";
        theForm.email.focus();
        clearErrorClass();
        document.getElementById("emailLbl").className = "error";
        return(false);
    }
    else {
        if (!fieldValidate("email",email)) {
            optin.errorMsgText = "Please enter a valid email address.";
            theForm.email.value = "";
            theForm.email.focus();
            clearErrorClass();
            document.getElementById("emailLbl").className = "error";
            return(false);    
        }
    }
    
    var country = theForm.CountryID.options[theForm.CountryID.selectedIndex].value; 
    if(country=="") {
        optin.errorMsgText = "Please select your country";
        theForm.CountryID.focus();
        clearErrorClass();
        document.getElementById("countryLbl").className = "error";
        return(false);
     }
     
    var birthYear = theForm.bdayY.options[theForm.bdayY.selectedIndex].value; 
    var birthMonth = theForm.bdayM.options[theForm.bdayM.selectedIndex].value;
    var birthDay = theForm.bdayD.options[theForm.bdayD.selectedIndex].value;
    var minAge = 13;
    
    if(birthYear=="" || birthMonth=="" || birthDay=="") {
        optin.errorMsgText = "Please select your birthdate."
        theForm.bdayY.focus();
        clearErrorClass();
        document.getElementById("bdayLbl").className = "error";
        return(false);
    }
    else {
        if (!checkAge(birthMonth,birthDay,birthYear,minAge)) {  
            theForm.bdayY.focus();
            clearErrorClass();      
            document.getElementById("bdayLbl").className = "error";
            return(false);
        }
    }

    return(true);
}

function formStep2Validate() {    
    if(optin.theCount == 1) {
        var missingQ = -1;
        var mktgTraits = document.getElementById("two").getElementsByTagName("select");
        var traitLabels = document.getElementById("two").getElementsByTagName("label");
        for (var i=0, allTraits = mktgTraits.length; i<allTraits; i++) {
            if(mktgTraits[i].options[mktgTraits[i].selectedIndex].value == "" && missingQ == -1) {
                missingQ = i;    
            }        
        }
        if(missingQ > -1) {
            optin.errorMsgText = "Please select answers for all questions.";
            mktgTraits[missingQ].focus();
            clearErrorClass();
            traitLabels[missingQ].className = "error";
            return (false);
        }
        else {return true;} 
    }
       
}

function formStep3Validate() {  
    if(optin.theCount == 2) {
        var optinChkBox = document.getElementById("optinChkBx");
        clearErrorClass();
        if (!optinChkBox.checked) {            
            optin.errorMsgText = "If you want to become a Bior&eacute;<sup>&reg;</sup> Brand Member, please check Yes!<br/>";
            optinChkBox.focus();
            document.getElementById("mainYes").className = "error";
            return (false);
        }
        else {return true;} 
    }
}

function checkForm() {
    if (formValidate(document.form1)) {
        submitOptinForm();
    }
}

function trimField(fld) {
    // removes leading and trailing blanks from fld
    var res = "";
    var c = 0;
    for (i=0; i < fld.length; i++) {
      if (fld.charAt(i) != " " || c > 0) {
        res += fld.charAt(i);
        if (fld.charAt(i) != " ") c = res.length;
      }
    }
    return res.substr(0,c);
}

function submitOptinForm(e) {   
	var valid3 = formStep3Validate(theForm);
	if(valid3 && !optin.submitted){
		var jfoptin = 0;
		if(theForm.jfoptin.checked){jfoptin =1};
		var jergensoptin = 0;
		if(theForm.jergensoptin.checked){jergensoptin =1};
		var cureloptin = 0;
		if(theForm.cureloptin.checked){cureloptin =1};
		var banoptin = 0;
		if(theForm.banoptin.checked){banoptin =1};

		//var url = "/webservices/banContact.asmx/banLightboxOptin";
		var params = "fname=" + theForm.fname.value;
		params += "&lname=" + theForm.lname.value;
		params += "&email=" + theForm.email.value;
		params += "&site_CountryID=" + theForm.CountryID.options[theForm.CountryID.selectedIndex].value;
		params += "&gender=" + theForm.gender.options[theForm.gender.selectedIndex].value;
		params += "&DOB=" +  theForm.bdayM.options[theForm.bdayM.selectedIndex].value + "/" +  theForm.bdayD.options[theForm.bdayD.selectedIndex].value + "/" +  theForm.bdayY.options[theForm.bdayY.selectedIndex].value;
		params += "&traitVal_mktg1=" + theForm.mktg1.options[theForm.mktg1.selectedIndex].value;
		params += "&traitVal_mktg2=" + theForm.mktg2.options[theForm.mktg2.selectedIndex].value;
		params += "&traitVal_mktg3=" + theForm.mktg3.options[theForm.mktg3.selectedIndex].value;
		params += "&traitVal_mktg4=" + theForm.mktg4.options[theForm.mktg4.selectedIndex].value;
		params += "&jfoptin=" + jfoptin;
		params += "&jergensoptin=" + jergensoptin;
		params += "&cureloptin=" + cureloptin;
		params += "&banoptin=" + banoptin;    
    
		$.ajax({
			type: "POST",
			data: params,
			url: "/usa/webservices/bioreContact.asmx/bioreLightboxOptin",
			success:showOptinSuccess,
			failure:showOptinFail
		});
		optin.submitted = true;
	}
		optin.stopDefault(e);
}

function clearErrorClass() {
    if(optin.getElementsByClass("error",document.getElementById("theForm"),"label")[0]) {
       optin.getElementsByClass("error",document.getElementById("theForm"),"label")[0].className = "";
    }
}

function showOptinSuccess() {
	optin.theDivs[optin.theCount].style.display = "none";
	optin.theStepsLis[optin.theCount].className = "";
    optin.theCount++;
    optin.theStepsLis[0].className = "";
    optin.theStepsLis[1].className = "";
	optin.theStepsLis[2].className = "";
	optin.displayButtons();
	if (typeof(window["dcsMultiTrack"])=="function") dcsMultiTrack('DCS.dcsqry','success=true');
}

function showOptinFail() {
    optin.goForward();
}