﻿var ErrorContainer_Suffix = '_err';
var Container_Suffix = '_ctr';
var ErrMsg_Required = 'Value is required.';
var ERROR_OFF = 'reg_err_msg_off';
var ERROR_ON = 'reg_err_msg_on';

var ErrMsg_Required = 'This field is required.';
var ErrMsg_Required_FN = 'Please provide your first name.';
var ErrMsg_Required_LN = 'Please provide your last name.';
var ErrMsg_Required_ADDR = 'Please provide your address.';
var ErrMsg_Required_CITY = 'Please provide your city.';
var ErrMsg_Required_ST = 'Please select a state.';
var ErrMsg_Invalid_ZIP = 'Zip code must be 5 digits.';
var ErrMsg_Invalid_EML = 'Invalid e-mail address &mdash; format is name@domain.com.';
var ErrMsg_Required_Login_EML = 'Please enter a valid e-mail address.';
var ErrMsg_Required_Login_PWD = 'Please enter a password for your account.';
var ErrMsg_Required_DOB = 'Please provide your date of birth.';
var ErrMsg_Required_PWD = 'Please enter a password for your account.';
var ErrMsg_Required_PWD2 = 'Please re-enter the same password as in the first password field.';
var ErrMsg_Required_SEL = 'Please make a selection';
var ErrMsg_Required_SPEC = 'Please select your area of professional expertise.';
var ErrMsg_Required_ONE_ANS = 'Please choose at least 1 answer from the list above.';
var ErrMsg_InvalidMin_PWD = 'Your password, which is case sensitive, must be between 5 and 10 characters. It can contain both numbers and letters.  Do not use special characters such as * or #.';
var ErrMsg_InvalidMax_PWD = 'Your password, which is case sensitive, must be between 5 and 10 characters. It can contain both numbers and letters.  Do not use special characters such as * or #.';
var ErrMsg_InvalidChars_PWD = 'Your password, which is case sensitive, must be between 5 and 10 characters. It can contain both numbers and letters.  Do not use special characters such as * or #.';
var ErrMsg_Invalid_DOB = 'Invalid birthdate &mdash; please use format MM/DD/YYYY.';
var ErrMsg_Invalid_PHONE = 'Phone number format is 123 456 7890.';
var ErrMsg_Match_EML = 'E-mail confirmation does not match.';
var ErrMsg_Match_PWD = 'The passwords you entered do not match.';
var ErrMsg_OptionalMissing = 'Value is optional but missing.';
var ErrMsg_ValidType = 'Please specify valid value.';
var ErrMsg_ValidDate = 'Please specify a valid date with the format DD MM YYYY.';
var ErrMsg_ValidMinLength = 'The value has less than the minimum number of allowable characters.';
var ErrMsg_ValidMaxLength = 'The value exceeded the maximum number of allowable characters.';
var ErrMsg_ValidMinValueLength = 'The selection has less than the minimum number of values.';
var ErrMsg_ValidMaxValueLength = 'The selection exceeded the maximum number of values.';
var ErrMsg_EmailVerify = 'Please verify your e-mail address correctly.';
var ErrMsg_PasswordInvalid = 'Your password must contain 5-10 alphanumeric characters, with no special characters.';
var ErrMsg_PasswordVerify = 'Please verify your password correctly.';
var DefaultErrorMessage = 'Some required information is missing from your form. Please complete the required fields and click "Submit" again.';
var ErrMsg_MonthsExceedsMax = 'Please do not enter more than 60 months.';

var RETYPE_ABS_PATH = '/bipolar-disorder-support-survey.aspx';

//////////////////////////////////////////////////////////////////////
// Flag that helps us test server side validation by disabling client side validation. 
// This should be set to 'true' for release. Affects both login and registration forms.
//////////////////////////////////////////////////////////////////////
var DO_CLIENT_VALIDATION = true;
//////////////////////////////////////////////////////////////////////

function Validation(name, value, type, required, maxlen, minlen, regex, errmsg, customfunc) 
{
    this.Type = type;
    this.Name = name;
    this.Value = value;
    this.Required = required;
    this.MaximumLength = maxlen;
    this.MinimumLength = minlen;
    this.RegularExpression = regex;
    this.ErrorMessage = errmsg;
    this.CustomFunction = customfunc;
}

//retrieve question form id
Validation.prototype.GetFormQuestionId = function ()
{
    return this.Name;
}

// get element in the page by name
function getElement(name)
{
    if (!name)
        return null;
    return document.getElementsByName(name);
}

// Get values of a particular field.
function GetValues(id, type)
{
    var values = "";
    type = type.toLowerCase();
    //iterate through the selections if type is checkbox, radio or checkboxlist
    if ( type == "radio" || type == "checkbox" || type == "checkboxlist")
    {
        var valuelist = document.getElementsByName(id);      
        if (valuelist) 
        {    
            for (var i=0; i<valuelist.length; i++){
            
                // Added valuelist[i].name == id check to fix an ie6 bug where
                // calls to document.getElementsByName() returns elements with the name
                // OR the id equal to the provided value. 
                if (valuelist[i].name == id && (valuelist[i].checked || valuelist[i].selected)) 
                {
                    if (values == "")
                        values = valuelist[i].value;
                    else
                        values = values + "," + valuelist[i].value;
                }
         
            }

        }
    }
    //iterate through the list of items if the type is multiselect
    else if (type == "multiselect")
    {
        var list = document.getElementById(id); 
        if (list)
        {
            for (var i=0; i<list.options.length; i++)
                if (list.options[i].selected) 
                {
                    if (values == "")
                        values = list.options[i].value;
                    else
                        values = values + "," + list.options[i].value;
                }
        }
    }
    //otherwise jsut retrieve the data
    else
    {
        var formQuestion = document.getElementById(id);   
        if (formQuestion)
            return formQuestion.value;
    }
        
    return values;
}

//displays the main error message
function setMainErrorMessage(message)
{
        var errDiv = document.getElementById("errorsummary");     
        if (errDiv) 
        {
            errDiv.innerHTML = message;
            if (message=="")
					errDiv.className = ERROR_OFF;
                //errDiv.className = "reg_main_err_msg_off"; 
            else
					errDiv.className = ERROR_ON; 
                //errDiv.className = "reg_main_err_msg_on"; 
        }
}
//sets the error message of a particular field
function setErrorMessage(containerId, message)
{
    var errorDivId = containerId + ErrorContainer_Suffix;
    var errDiv = document.getElementById(errorDivId);     

    if (errDiv)
        errDiv.innerHTML = message;
    
    var conDivId = containerId + Container_Suffix;
    var conDiv = document.getElementById(conDivId);     
    
    if (conDiv) 
    {
        if (message == "")
        {
            if (conDiv.className == ERROR_ON)
                conDiv.className = ERROR_OFF;   
        }
        else
        {
				//7/24/09: updated for ie8, since it assigns additional classes 
				//to elements (such as "ie7_class75")
            if (conDiv.className == ERROR_OFF || (conDiv.className.indexOf(ERROR_OFF) > -1)) 
                conDiv.className = ERROR_ON; 
        }
    }
}

//Main validation function.
function ValidateRegistration()
{
    setMainErrorMessage("");
    var bSuccess = true;
    if(validations)
    {


        for(var i=0;i<validations.length;i++)
        {
            var questionId = validations[i].GetFormQuestionId();
            setErrorMessage(questionId, "");

				//alert('1: ' + questionId);
			
            validations[i].Value = GetValues(questionId, validations[i].Type);

            if (!validations[i].HasRequiredValue()) 
            {
					 //alert('failed: ' + questionId + ': ' + 'HasRequiredValue');
                setErrorMessage(questionId, ErrMsg_Required);
                bSuccess = false;
                continue; 
            }

            if (!validations[i].HasValidType())    
            {
					 //alert('failed: ' + questionId + ': ' + 'HasValidType');
                setErrorMessage(questionId, ErrMsg_ValidType);
                bSuccess = false;
                continue;
            }
            
            if (!validations[i].ExecuteExpression())
            {
					 //alert('failed: ' + questionId + ': ' + 'ExecuteExpression');
                setErrorMessage(questionId, validations[i].ErrorMessage);
                bSuccess = false;
                continue;
            }
           
            if (!validations[i].HasValidMinLength())
            {
                if (validations[i].Type.toLowerCase() == "checkboxlist" ||
                    validations[i].Type.toLowerCase() == "multiselect") {
						//alert('failed: ' + questionId + ': ' + 'HasValidMinLength: checkboxlist or multiselect');
						setErrorMessage(questionId, ErrMsg_ValidMinValueLength);
					 }
                else {
						//alert('failed: ' + questionId + ': ' + 'HasValidMinLength: standard');
                  setErrorMessage(questionId, ErrMsg_ValidMinLength);
						bSuccess = false;
						continue;
                }
            }

            if (!validations[i].HasValidMaxLength())
            {
                if (validations[i].Type.toLowerCase() == "checkboxlist" ||
                    validations[i].Type.toLowerCase() == "multiselect") 
                    setErrorMessage(questionId, ErrMsg_ValidMaxValueLength);
                else
                    setErrorMessage(questionId, ErrMsg_ValidMaxLength);
                bSuccess = false;
                continue;
            }
            
            
            var message = validations[i].ExecuteCustomFunction();
            if (message != "") 
            {
					 //alert('failed: ' + questionId + ': ' + 'ExecuteCustomFunction');
                setErrorMessage(questionId, message);
                bSuccess = false;
                continue;
            }
        }
    }
    
    if (!bSuccess)
    {
        setMainErrorMessage(DefaultErrorMessage);
        window.location.href = "#top";
    }
    
    //set the js flag so the form can finish validating on the server.
    toggleJsFlag(true);
    
    //alert('form was valid ?' + bSuccess);
    return bSuccess;
}

//validates value give the maximum length
Validation.prototype.HasValidMaxLength = function ()
{
    if(!this.MaximumLength || this.MaximumLength < 0)
        return true;
    
    if (this.Type.toLowerCase() == "checkboxlist" ||
        this.Type.toLowerCase() == "multiselect") 
    {
        var len = 0;
        if (this.Value && this.Value != "")
        {
            var arrvalue = this.Value.split(",");   
            len = arrvalue.length;
        } 
        return (len <= this.MaximumLength);
    }
    else
        return (this.Value.length <= this.MaximumLength);
}

//validates value give the minimum length
Validation.prototype.HasValidMinLength = function ()
{
    if(!this.MinimumLength || this.MinimumLength < 0)
        return true;
        
    if (this.Type.toLowerCase() == "checkboxlist" ||
        this.Type.toLowerCase() == "multiselect") 
    {
        var len = 0;
        if (this.Value && this.Value != "")
        {
            var arrvalue = this.Value.split(",");   
            len = arrvalue.length;
        }
        
        return ( len >= this.MinimumLength);
    }
    else
        return (this.Value.length >= this.MinimumLength);
}


//execute regular expression to validate a particular field
Validation.prototype.ExecuteExpression = function ()
{
    if(!this.Value || this.Value == "" || !this.RegularExpression || this.RegularExpression == "" )
        return true;

    return IsValidRegularExpression(this.Value, this.RegularExpression);
}

// validates the required field
Validation.prototype.HasRequiredValue = function ()
{
    if(!this.Required || this.Required == "")
        return true;
    if (this.Required.toLowerCase() == "y" && (!this.Value || this.Value == "") )
        return false;
    return true;
}

//validate the value according to Type
Validation.prototype.HasValidType = function ()
{
    if(!this.Value || this.Value == "" || !this.Type || this.Type == "" )
        return true;

    switch(this.Type.toLowerCase())
    {
        case "alpha":
            return IsValidRegularExpression(this.Value, "^[A-Za-z ]+$");
        case "numeric":
            return IsValidRegularExpression(this.Value,"^[0-9]+$");
        case "alphanumeric":
            return IsValidRegularExpression(this.Value,"^[A-Za-z0-9 ]+$");
        case "phone":
            return IsValidRegularExpression(this.Value, "^([0-9]+[() .]?)+[xX]?[ ]?[0-9]+$");
        case "zip":
             return IsValidRegularExpression(this.Value, "^[0-9]{5}(-[0-9]{4})?$");
        case "email":
            return IsValidEmailAddress(this.Value);
        case "date":
            return isDate(this.Value);
        case "url":
            return IsValidRegularExpression(this.Value, "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$");
        case "radio", "checkbox", "checkboxlist, multiselect":
            return true;
        default: 
            return true;
    }        

}

// execute custom function if there is any
Validation.prototype.ExecuteCustomFunction = function ()
{
    if(!this.CustomFunction || this.CustomFunction == "")
        return "";
        
    try
    {
        var b = eval(this.CustomFunction + "()");
        return b;
    }
    catch(e) {
        return ErrMsg_ValidType;
    }

}

//if the value is a valid email address
function IsValidEmailAddress(value)
{
    if (value == "")
        return true;
    var regExpr = "^[a-zA-Z0-9\-\._]+\@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9]{2,4})$";
    return IsValidRegularExpression(value, regExpr)
}

//if the value matched the regular expression
function IsValidRegularExpression(value, regExpr)
{
    var rexp = new RegExp(regExpr);
    return rexp.test(value);
}

// following code shows the date validation
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(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;
}

function stripCharsInBag(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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false;
	}
    return true;
}


//////////////////////////// SER XR C Validation Functions ////////////////////

/**
validation error handling functions
**/

function clearAllErrors() {

	var bIsRetypePage = isOnPage(RETYPE_ABS_PATH);
	if (bIsRetypePage) {
		clearMainErrorMessage();
		clearRetypeErrors();
	}
	else {
		clearMainErrorMessage();
		clearErrors();
	}
	//errExceedHMaxFlag = false;
}

function isOnPage(strAbsPath) {
	var bIsOnPage = false;
	var strPath = document.location.pathname.toLowerCase();
	if (strPath == strAbsPath) { bIsOnPage = true; }
	return bIsOnPage;
}

//clears the main error message
function clearMainErrorMessage() {
	var errorsummary = document.getElementById('errorsummary');
	errorsummary.innerHTML = '';       
	errorsummary.className = ERROR_OFF; 
	//errorsummary.className = 'reg_main_err_msg_off'; 
	
}

//Scroll the top of the page on error
function scrollToErrorSummary() {
	var top = document.getElementById('errorsummary');
	Common.scrollToElement(top);
}

//If an id is entered here, its error will be cleared. when the form is resubmitted.
//To add: Add the ids for both the error array and the container array.
function clearErrors() {

	/////////////////////////////////////////////
	var arrErrorDivs = []; //Error div id
	//User fields
	arrErrorDivs.push('reg_user_FirstName_err');
	arrErrorDivs.push('reg_user_LastName_err');
	arrErrorDivs.push('reg_user_Address1_err');
	arrErrorDivs.push('reg_user_Address2_err');
	arrErrorDivs.push('reg_user_City_err');
	arrErrorDivs.push('reg_user_State_err');
	arrErrorDivs.push('reg_user_Zip_err');
	arrErrorDivs.push('reg_user_EmailAddress_err');
	arrErrorDivs.push('reg_user_ConfirmEmail_err');
	arrErrorDivs.push('reg_user_DOB_err');
	//Survey fields
	arrErrorDivs.push('reg_survey_1_err');
	arrErrorDivs.push('reg_survey_2_err');
	arrErrorDivs.push('reg_survey_3_err');
	arrErrorDivs.push('reg_survey_4_err');
	/////////////////////////////////////////////
	var arrContainerDivs = []; //Container error div id
	//User fields
	arrContainerDivs.push('reg_user_FirstName_ctr');
	arrContainerDivs.push('reg_user_LastName_ctr');
	arrContainerDivs.push('reg_user_Address1_ctr');
	arrContainerDivs.push('reg_user_Address2_ctr');
	arrContainerDivs.push('reg_user_City_ctr');
	arrContainerDivs.push('reg_user_State_ctr');
	arrContainerDivs.push('reg_user_Zip_ctr');
	arrContainerDivs.push('reg_user_EmailAddress_ctr');
	arrContainerDivs.push('reg_user_ConfirmEmail_ctr');
	arrContainerDivs.push('reg_user_DOB_ctr');
	//Survey fields
	arrContainerDivs.push('reg_survey_1_ctr');
	arrContainerDivs.push('reg_survey_2_ctr');
	arrContainerDivs.push('reg_survey_3_ctr');
	arrContainerDivs.push('reg_survey_4_ctr');
	/////////////////////////////////////////////
	for (var i in arrErrorDivs) {
		var divE = document.getElementById(arrErrorDivs[i]);
		if (divE) {
			//clear the error div innerHTML
			if (divE.id.length > 0) {
				if (divE.id.indexOf(ErrorContainer_Suffix) != -1) { 
					divE.innerHTML = '';
				}
			}
		}
	}
	/////////////////////////////////////////////
	for (var i in arrContainerDivs) {
		var divC = document.getElementById(arrContainerDivs[i]);
		//reset the classname on the container divs
		if (divC != null && divC.id.indexOf(Container_Suffix) != -1) { //'_ctr'
			divC.className = ERROR_OFF;
		}
	}
}

/** 
validation list init functions 
**/


function initReqTextboxes() {

	var arrReqTextIDs = []; //Standard textbox fields frequently on forms.
	var arrReqTextBoxes = [];
	arrReqTextIDs.push('reg_user_FirstName');
	arrReqTextIDs.push('reg_user_LastName');
	arrReqTextIDs.push('reg_user_Address1');
	arrReqTextIDs.push('reg_user_City');
	arrReqTextIDs.push('reg_user_Zip');
	arrReqTextIDs.push('reg_user_DOB');

	// Note: Email, ConfirmEmail, Password and ConfirmPassword are excluded 
	// from the above list and are validated later.
	
	//add the textboxes to the array.
	for (var i in arrReqTextIDs) {
		arrReqTextBoxes.push(document.getElementById(arrReqTextIDs[i]));
	}
	//return the array of textboxes.
	return arrReqTextBoxes;
}

////////////////////////////////////////////////////////////////////////
// user validation functions 
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
// Main function for validating user info.
// Returns boolean indicating whether to enable submit button.
////////////////////////////////////////////////////////////////////////
function ValidateUser() {

	var bValidUser = false;

	//Check client validation flag (should be 'true' for release)...
	if (DO_CLIENT_VALIDATION) {

		//first, clear errors before revalidating.
		clearAllErrors();
		
		var bValid = ValidateUserData();

		if (bValid) { 
			bValidUser = true; 
		}
		else { 
			bValidUser = false; 
			scrollToErrorSummary();
		}
	}
	return bValidUser;
}

function ValidateUserData() {
	var bValid = true;

	//Get control collections
	var arrReqTexts = initReqTextboxes();
	//var arrDOBs = initDobIDs();
	
	//Check required textboxes: Check if we have text because fields are required.
	for (var i in arrReqTexts) {
		if (arrReqTexts[i].value.length <= 0) {
		
			//Set required field error.	
			switch (arrReqTexts[i].id) {
				case 'reg_user_FirstName': 
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
				case 'reg_user_LastName':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
				case 'reg_user_Address1':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
				case 'reg_user_City':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
				case 'reg_user_Zip':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
				case 'reg_user_DOB':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
					break;
			}
			//setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
			setMainErrorMessage(DefaultErrorMessage);
			bValid = false;
		}
	}
	
	//Validate State: Required.
	var bValidState = ValidateState();
	if (!bValidState) {
		bValid = false;
	}
	
	//Validate first name: Regex.
	var strFirst = document.getElementById('reg_user_FirstName').value;
	var bValidFirst = isValidName(strFirst);
	if (!bValidFirst) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_FirstName', ErrMsg_ValidType);
		bValid = false;
	}
	
	//Validate last name: Regex.
	var strLast = document.getElementById('reg_user_LastName').value;
	var bValidLast = isValidName(strLast);
	if (!bValidLast) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_LastName', ErrMsg_ValidType);
		bValid = false;
	}

	//Validate address1: Regex.
	var strAddr1 = document.getElementById('reg_user_Address1').value;
	var bValidAddr1 = isValidAddress(strAddr1);
	if (!bValidAddr1) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_Address1', ErrMsg_ValidType);
		bValid = false;
	}

	//Validate address2: Regex.
	var strAddr2 = document.getElementById('reg_user_Address2').value;
	if (strAddr2.length > 0) {
		var bValidAddr2 = isValidAddress(strAddr2);
		if (!bValidAddr2) {
			//Set error
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_user_Address2', ErrMsg_ValidType);
			bValid = false;
		}
	}

	//Validate city: Regex.
	var strCity = document.getElementById('reg_user_City').value;
	var bValidCity = isValidCity(strCity);
	if (!bValidCity) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_City', ErrMsg_ValidType);
		bValid = false;
	}
	
	//Validate zip: Regex.
	var strZip = document.getElementById('reg_user_Zip').value;
	var bValidZip = isValidZipCode(strZip);
	if (!bValidZip) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		//setErrorMessage('reg_user_Zip', ErrMsg_Invalid_ZIP);
		setErrorMessage('reg_user_Zip', ErrMsg_Invalid_ZIP);
		bValid = false;
	}
	
	//Validate email and password: Required, Regex and Match.
	var bValidEmail = ValidateEmail();
	var bValidConfirmEmail = ValidateConfirmEmail();

	if (!bValidEmail || !bValidConfirmEmail) {
		bValid = false;
	}

	//Validate DOB: Regex.
	var bValidDOB = ValidateBirthDate();
	if (!bValidDOB) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_DOB', ErrMsg_Invalid_DOB);
		bValid = false;
	}
	else {
		
		//Don't redirect if we have no value. 
		//The required field validation will take care of this case.
		if (!document.getElementById('reg_user_DOB').value.length > 0) {
			return; 
		}
	
		//Date is valid.
		//Check if the user is eligible (18 years old).
		//If not, redirect user to ineligible page.
		var strIneligibleUrl = '/thinking-forward-ineligible.aspx?msg=1';
		var dob = document.getElementById('reg_user_DOB').value;
		var bEligible = isUserEligible(dob);
		
		if (!bEligible) { 
			Common.goTo(strIneligibleUrl); 
			return false;
		}
	}
	
	//If we wanted to validate maxlengths we could do so here.
	//However, we are limiting maxlength form elements and validating
	//on the server.
	
	return bValid;
}

// Age helper function
function checkleapyear(datea) {
	if(datea.getYear()%4 == 0) {
		if (datea.getYear()% 10 != 0) { return true; }
		else {
			if(datea.getYear()% 400 == 0) return true;
			else return false;
		}
	}
return false;
}
// Age helper function
function DaysInMonth(Y, M) {
	with (new Date(Y, M, 1, 12)) {
	  setDate(0);
	  return getDate();
	}
}
// Age helper function
function datediff(date1, date2) {
	var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
	y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();
	if (d1 < d2) {
		m1--;
		d1 += DaysInMonth(y2, m2);
	}
	if (m1 < m2) {
		y1--;
		m1 += 12;
	}
	return [y1 - y2, m1 - m2, d1 - d2];
}
// Age helper function
function getAge(m, d, y) {
	var dt = new Date();
	var curday = dt.getDate();
	var curmon = dt.getMonth()+1;
	var curyear = dt.getFullYear();
	var curd = new Date(curyear,curmon-1,curday);
	var cald = new Date(y,m-1,d);
	var diff =  Date.UTC(curyear,curmon,curday,0,0,0) - Date.UTC(y,m,d,0,0,0);
	var dife = datediff(curd,cald);
	var bd_yrs = parseInt(dife[0]);
	return bd_yrs;
}
// Age eligibility function
function isUserEligible(dob) {
	var bEligible = false;
	var m = dob.split('/')[0];
	var d = dob.split('/')[1];
	var y = dob.split('/')[2];
	var a = getAge(m, d, y);
	if (a >= 18) { bEligible = true; }
	return bEligible;
}

/**
user validation helper functions 
**/

//password regex: 6-10 alphanumeric chars, no special chars.
function isValidPassword(value) {
	if (value.length == 0) { return true; }
	re = /^\w{5,10}$/;
   return re.test(value);
}

function isValidEmailAddress(value) {
	if (value.length == 0) { return true; }
	re = /^[a-zA-Z0-9\-\._]+\@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9]{2,4})$/;
	return re.test(value);
}

function isValidZipCode(value) {
	if (value.length == 0) { return true; }
	re = /^\d{5}([\-]\d{4})?$/;
	return re.test(value);
}

function isAlpha(value) {
	if (value.length == 0) { return true; }
   re = /^[A-Za-z]+$/;
   return re.test(value);
}

function isNumeric(value) {
	if (value.length == 0) { return true; }
   re = /^[0-9]+$/;
   return re.test(value);
}

function isAlphaNumeric(value) {
	if (value.length == 0) { return true; }
   re = /^[A-Za-z0-9]+$/;
   return re.test(value);
}

function isValidName(value) {
	if (value.length == 0) { return true; }
	re = /^([A-Za-z\-\.\'\s]*)$/;
	return re.test(value);
}

function isValidAddress(value) {
	if (value.length == 0) { return true; }
	re = /^([A-Za-z0-9\&\-\.\'\#\,\s]*)$/;
	return re.test(value);	
}

function isValidCity(value) {
	if (value.length == 0) { return true; }
	re = /^([A-Za-z\&\-\.\'\s]*)$/;
	return re.test(value);	
}

function isValidPhoneNumber(value) {
	if (value.length == 0) { return true; }
   re = /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
   
   //OLD:
   //re = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/; 
   
   return re.test(value);
}

function ValidateState() {
	var bValid = true;
	var c = document.getElementById('reg_user_State_ctr');
	var err = document.getElementById('reg_user_State_err');
	var st = document.getElementById('reg_user_State');

	if (st.selectedIndex == 0) {
		//Set error.
		setMainErrorMessage(DefaultErrorMessage);
		c.className = ERROR_ON;
		err.innerHTML = ErrMsg_Required;
		bValid = false;
	}
	return bValid;
}

function ValidateEmail() {
	var emailID = document.getElementById('reg_user_EmailAddress');
	if (emailID.value.length == 0) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_EmailAddress', ErrMsg_Required);
		return false;
	}
	if (!isValidEmailAddress(emailID.value)) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_EmailAddress', ErrMsg_Invalid_EML);
		return false;
	}
	return true;
}

function ValidateConfirmEmail() {
	var emailID = document.getElementById('reg_user_EmailAddress');
	var confirmID = document.getElementById('reg_user_ConfirmEmail');
	
	if (confirmID.value.length == 0) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_ConfirmEmail', ErrMsg_Required);
		return false;
	}
	
	if (confirmID && emailID) {
		if (emailID.value != '' || confirmID.value != '') {
			if (!isValidEmailAddress(confirmID.value)) {
				//Set error
				setMainErrorMessage(DefaultErrorMessage);
				setErrorMessage('reg_user_ConfirmEmail', ErrMsg_Invalid_EML);
				return false;
			}
			else if (emailID.value != confirmID.value) {
				//Set error
				setMainErrorMessage(DefaultErrorMessage);
				setErrorMessage('reg_user_EmailAddress', ErrMsg_Match_EML);
				setErrorMessage('reg_user_ConfirmEmail', ErrMsg_Match_EML);
				return false;
			}
		}
	}
	return true;
}

function ValidateBirthDate() {

//alert('validating dob');

	var bValid = true;
	var bNumeric = true;
	var elemDate = document.getElementById('reg_user_DOB');
	
	if (elemDate.value == '') {
		return true; //We're not validating required, only regex.
	}
	if (elemDate.value.length < 10) {
		return false;
	}
	if (elemDate.value.length > 10) {
		return false;
	}
	
	var arrDate = elemDate.value.split('/');
	var m = arrDate[0];
	var d = arrDate[1];
	var y = arrDate[2];
	
	
	//check if we have numeric values we can work with...
	if (!Common.isNumeric(m) || !(m.length == 2)) { setInvalidDOB_Month(); bNumeric = false; }
	if (!Common.isNumeric(d) || !(d.length == 2)) { setInvalidDOB_Day(); bNumeric = false; }
	if (!Common.isNumeric(y) || !(y.length == 4)) { setInvalidDOB_Year(); bNumeric = false; }
	if (!bNumeric) { return false; }
	
	//We have numeric values...continue validation...
	var dt = m + '/' + d + '/' + y;
	if (!isDate(dt)) {
		//Set error
		bValid = false;
	}
	
	return bValid;
}

function setInvalidDOB_Month() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOB', ErrMsg_Invalid_DOB);
}
function setInvalidDOB_Day() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOB', ErrMsg_Invalid_DOB);
}
function setInvalidDOB_Year() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOB', ErrMsg_Invalid_DOB);
}

function ValidateSpecialty() {
	var bValidSpecialty = true;
	var bHCP = isHCP();
	if (bHCP) {
		if (document.getElementById('reg_user_Specialty').selectedIndex == 0) {
		
			//Set error
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_user_Specialty', ErrMsg_Required_SPEC);
			bValidSpecialty = false;
		}
	}
	return bValidSpecialty;
}


function ValidatePassword(){

	var pwd = document.getElementById('reg_user_Password');
	var bAdvanced = isCancerStageAdvanced();
	var bValidPass = true;
	
	//If cancer stage is not advanced, the pwd is required.
	if (!bAdvanced) {
		if (pwd.value.length == 0) {
			//Set error
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_user_Password', ErrMsg_Required_PWD);
			bValidPass = false;
		}
	}
	//If a password exists, validate it against a regex.
	if (!bAdvanced) {
		if (pwd.value.length > 0) {
			var bVerify = isValidPassword(pwd.value);
			if (!bVerify) {
				//Set appropriate invalid pass error
				if (pwd.value.length < 5) { setErrorMessage('reg_user_Password', ErrMsg_InvalidMin_PWD); }
				else if (pwd.value.length > 10) { setErrorMessage('reg_user_Password', ErrMsg_InvalidMax_PWD); }
				else { setErrorMessage('reg_user_Password', ErrMsg_InvalidChars_PWD); }
			
				setMainErrorMessage(DefaultErrorMessage);
				bValidPass = false;
			}
		}
	}
	return bValidPass;
}

function ValidateConfirmPassword() {

	var passwordID = document.getElementById('reg_user_Password');
	var confirmID = document.getElementById('reg_user_ConfirmPassword');
	var bAdvanced = isCancerStageAdvanced();
	
	if (!bAdvanced) {
	
		if (confirmID.value.length == 0) {
			//Set error
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_user_ConfirmPassword', ErrMsg_Required_PWD2);
			return false;
		}
		
		if (confirmID && passwordID) {
			if (passwordID.value != '' || confirmID.value != '') {
			
				var bVerify = isValidPassword(confirmID.value);
				if (!bVerify) {
					//Set appropriate invalid pass error
					if (confirmID.value.length < 5) { setErrorMessage('reg_user_ConfirmPassword', ErrMsg_InvalidMin_PWD); }
					else if (confirmID.value.length > 10) { setErrorMessage('reg_user_ConfirmPassword', ErrMsg_InvalidMax_PWD); }
					else { setErrorMessage('reg_user_ConfirmPassword', ErrMsg_InvalidChars_PWD); }
				}
			
				if (passwordID.value != confirmID.value) {
					//Set match error
					setMainErrorMessage(DefaultErrorMessage);
					setErrorMessage('reg_user_Password', ErrMsg_Match_PWD);
					setErrorMessage('reg_user_ConfirmPassword', ErrMsg_Match_PWD);
					return false;
				}
			}
		}
	}
	return true;
}	


////////////////////////////////////////////////////////////////////////
// This function is called before the form is submitted.
// It checks if the user information has been validated.
// Then it validates the survey data and returns true and
// submits if all is valid.
////////////////////////////////////////////////////////////////////////
function checkAllFormData() {

	//alert('checking form data...');

	var bValid = false;
	
	alert('checkAllFormData(): start');
	
	//DO_CLIENT_VALIDATION should be 'true' for release...
	if (DO_CLIENT_VALIDATION) {
	
		//Switch js flag on (allows form to finish validating on server).
		toggleJsFlag(true);
	
		//Validate user...
		var bValidUser = ValidateUser();
		
		//alert('user data valid: ' + bValidUser);
	
		//Validate surveys...
		var bValidSurveys = ValidateSurveyData();
		
		//alert('survey data valid: ' + bValidSurveys);
		
		//alert('bValidSurveys && bValidUser: ' + bValidSurveys && bValidUser);
		
		if (bValidSurveys && bValidUser) { 
			bValid = true; 
		}
	}
	else {
		bValid = true;
	}
	
	//alert('bValid is: ' + bValid);
	
	return bValid;
}

////////////////////////////////////////////////////////////////////////
// survey validation functions 
////////////////////////////////////////////////////////////////////////

//Switch js flag on (allows form to finish validating on server).
function toggleJsFlag(bOn) {
	if (bOn) {
		document.getElementById('hidJsOn').value = '1';
	}
	else {
		document.getElementById('hidJsOn').value = '0';
	}
}

////////////////////////////////////////////////////////////////////////
// Main function for validating survey info.
////////////////////////////////////////////////////////////////////////
function ValidateSurveyData() {

alert('ValidateSurveyData(): start');

	var bValid = true;
	var bDiagnosed = ValidateDiagnosed();		//Have you been diagnosed with BPD
	var bCaregiver = ValidateCaregiver();		//Are you a caregiver
	var bTypingTool = ValidateTypingTool();
	
	if (!bDiagnosed || !bCaregiver || !bTypingTool) { 
		bValid = false;
		scrollToErrorSummary();
	}
	
	alert('ValidateSurveyData(): bValid' + bValid);
	
	return bValid;
}

/**
survey validation helper functions 
**/

function ValidateTypingTool() {

	//alert('validating typing tool...');

	var bValid = true;
	var bDiagnosed = isDiagnosed();
	var bIsNotTakingMed = isNotTakingMed();
	
	//alert('ValidateTypingTool: bDiagnosed: ' + bDiagnosed);
	
	if (bDiagnosed) {
		var bValid1 = ValidateMedication1();			//Are you currently taking...
		if(!bIsNotTakingMed){
		    var bValid2 = ValidateMedication2();			//Which of the following prescription...
		    var bValid3 = ValidateMedication3();			//How long have you been taking...	
		    if (!bValid1 || !bValid2 || !bValid3) {
			    bValid = false;
		    }
		}
	}
	else {
		bValid = true;
	}

	return bValid;
}

function isNotTakingMed() {
	var opt1 = document.getElementById('reg_survey_6');
	if (opt1.checked) { return true; }
	else { return false; }
}

function isTakingMed() {
	var opt1 = document.getElementById('reg_survey_5'); 
	if (opt1.checked) { return true; }
	else { return false; }
}

function isDiagnosed() {
	var opt1 = document.getElementById('reg_survey_1');
	if (opt1.checked) { return true; }
	else { return false; }
}

function isNotDiagnosed() {
	var opt2 = document.getElementById('reg_survey_2');
	if (opt2.checked) { return true; }
	else { return false; }
}
/**/
//Q1
function ValidateDiagnosed() {
	var bValid = isDiagnosedAnswered();
	
	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_1', ErrMsg_Required);
	}
	return bValid;
}
//Q1
function isDiagnosedAnswered() {
	var opt1 = document.getElementById('reg_survey_1');
	var opt2 = document.getElementById('reg_survey_2');
	
	if (!opt1.checked && !opt2.checked) {
		return false;
	}
	return true;
}
//Q2
function ValidateCaregiver() {
	var bValid = true;
	var bIsNotDiagnosed = isNotDiagnosed();
	if (bIsNotDiagnosed) {
		bValid = isCaregiverAnswered();
		if (!bValid) {
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_survey_2', ErrMsg_Required);
		}
	}
	return bValid;
}
//Q2
//Removed code that takes a user to the ineligible page with msg=2 here.
//This case is no longer valid. Instead we're saving the user's data first
//and then taking him to thinking-forward-thank-you.aspx.
function isCaregiverAnswered() {
	var opt1 = document.getElementById('reg_survey_3');
	var opt2 = document.getElementById('reg_survey_4');
	if (!opt1.checked && !opt2.checked) {
		return false;
	}
	return true;
}
//Q3
function ValidateMedication1() {

	var bValid = isMedication1Answered();
	
	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_3', ErrMsg_Required);
	}
	return bValid;
}
//Q3
function isMedication1Answered() {
	var opt1 = document.getElementById('reg_survey_5');
	var opt2 = document.getElementById('reg_survey_6');
	
	if (!opt1.checked && !opt2.checked) {
		return false;
	}
	return true;
}
//Q4
function ValidateMedication2() {

	var bValid = true;
	var bDiagnosed = isDiagnosed();
	var bIsTakingMed = isTakingMed();
	var bIsMedication2Answered = isMedication2Answered();
	var bIsMedication1Answered = isMedication1Answered();

	//See if user is taking medication first. 
	//Otherwise, question is not required.
	if (bIsTakingMed) {
		bValid = bIsMedication2Answered;
	}
	
	if (bIsTakingMed && !bIsMedication1Answered && !bIsMedication2Answered) {
		bValid = false;
	}
	
	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_4', ErrMsg_Required_ONE_ANS);
	}
	return bValid;
}
//Q4
function isMedication2Answered() {
	var opt7 = document.getElementById('reg_survey_7');
	var opt8 = document.getElementById('reg_survey_8');
	var opt9 = document.getElementById('reg_survey_9');
	var opt10 = document.getElementById('reg_survey_10');
	var opt11 = document.getElementById('reg_survey_11');
	var opt12 = document.getElementById('reg_survey_12');
	var opt13 = document.getElementById('reg_survey_13');
	var opt14 = document.getElementById('reg_survey_14');
	var opt15 = document.getElementById('reg_survey_15');
	var optNOTA = document.getElementById('reg_survey_NOTA');
	
	if (!opt7.checked && !opt8.checked && !opt9.checked 
	    && !opt10.checked && !opt11.checked && !opt12.checked 
	    && !opt13.checked && !opt14.checked && !opt15.checked 
	    && !optNOTA.checked) {
		return false;
	}
	return true;
}
//Q5 - note question was removed 2/9/09
function ValidateMedication3() {

	var bValid = true;
	var bIsTakingMed = isTakingMed();
	var bDiagnosed = isDiagnosed();
	var bIsMedication1Answered = isMedication1Answered();
	
	//See if user is taking medication first. 
	//Otherwise, question is not required.
	if (bIsTakingMed) {
		bValid = true;
	}
	
	if (bIsTakingMed && !bIsMedication1Answered) {
		bValid = false;
	}

	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_5', ErrMsg_Required);
	}
	return bValid;
}

//Lets the server repopulate values of items that are 
//frequently lost after postback and form reload.
//To use: 
//- Form element must have a "name" attribute.
//- Add form items to OptionRepopulate.config file.
//- Ensure you are including and referencing the jQuery library.
//- In RegistrationControl.ascx.vb set _reloadOptionalValuesOnError to True.
//- Configure this function to populate whatever items you need it to.
function repopulateItem(name, val, type, elemtype) {
	//Argument example: 'reg_user_DEA','AB-1231231','user','text'
	switch (elemtype) {
		case 'text':
			document.getElementsByName(name)[0].value = val;
			break;
	}
}
