﻿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_ONEVAL = 'Please enter at least 1 value.';
var ErrMsg_Required_FN = 'Please provide your first name.';
var ErrMsg_Required_LN = 'Please provide your last name.';
var ErrMsg_Required_PRACTICE = 'Please provide your hospital or practice.';
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_Required_Login_EML = 'Please enter a valid email 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_Invalid_WHOLE = 'Please use whole numbers only.'
var ErrMsg_Invalid_EML = 'Invalid e-mail address - format is name@domain.com.';
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 = 'Date of birth is 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 ErrMsg_Required_Numeric = 'Please enter a numeric value.';
var ErrMsg_Required_Numeric_Percent = 'Please enter a numeric value less than or equal to 100 for each field.';
var ErrMsg_PercentsMustEqual100 = 'Totals must equal 100%.';

//////////////////////////////////////////////////////////////////////
// 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++)
                if (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
        {
            if (conDiv.className == ERROR_OFF)
                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, "");

            validations[i].Value = GetValues(questionId, validations[i].Type);

            if (!validations[i].HasRequiredValue()) 
            {
                setErrorMessage(questionId, ErrMsg_Required);
                bSuccess = false;
                continue; 
            }

            if (!validations[i].HasValidType())    
            {
                setErrorMessage(questionId, ErrMsg_ValidType);
                bSuccess = false;
                continue;
            }
            
            if (!validations[i].ExecuteExpression())
            {
                setErrorMessage(questionId, validations[i].ErrorMessage);
                bSuccess = false;
                continue;
            }
           
            if (!validations[i].HasValidMinLength())
            {
                if (validations[i].Type.toLowerCase() == "checkboxlist" ||
                    validations[i].Type.toLowerCase() == "multiselect") 
                    setErrorMessage(questionId, ErrMsg_ValidMinValueLength);
                else
                    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 != "") 
            {
                setErrorMessage(questionId, message);
                bSuccess = false;
                continue;
            }
        }
    }
    
    if (!bSuccess)
    {
        setMainErrorMessage(DefaultErrorMessage);
        window.location.href = "#top";
    }
    
    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 P Validation Functions ////////////////////

/**
validation error handling functions
**/

function clearAllErrors() {

	clearMainErrorMessage();	
	clearErrors();	
	errExceedHMaxFlag = false;
}

//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_PracticeName_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_Specialty_err');
	
	//Surveys
	arrErrorDivs.push('reg_survey_2_err');
	arrErrorDivs.push('reg_survey_3_err');
	arrErrorDivs.push('reg_survey_4_err');
	arrErrorDivs.push('reg_survey_5_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_PracticeName_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_Specialty_ctr');
	
	//Surveys
	arrContainerDivs.push('reg_survey_2_ctr');
	arrContainerDivs.push('reg_survey_3_ctr');
	arrContainerDivs.push('reg_survey_4_ctr');
	arrContainerDivs.push('reg_survey_5_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.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_PracticeName');
	arrReqTextIDs.push('reg_user_Address1');
	arrReqTextIDs.push('reg_user_City');
	arrReqTextIDs.push('reg_user_Zip');

	// Note: Email, ConfirmEmail 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_PracticeName':
					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;
			}
			//setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
			
			setMainErrorMessage(DefaultErrorMessage);
			
			bValid = false;
			
		}
	}
	
	/////////////////////////////////////////////
	// Uncomment for forms with Specialty field.
	/////////////////////////////////////////////
	
	//Validate Specialty: Required (HCP).
	var bValidSpecialty = ValidateSpecialty();
	if (!bValidSpecialty) {
		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 practice name: Regex.
	var strLast = document.getElementById('reg_user_PracticeName').value;
	var bValidLast = isValidName(strLast);
	if (!bValidLast) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_PracticeName', 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);
		bValid = false;
	}
	
	//Validate email and password: Required, Regex and Match.
	
	var bValidEmail = ValidateEmail();
	
	var bValidConfirmEmail = ValidateConfirmEmail();
    
	if (!bValidEmail || !bValidConfirmEmail) {
		bValid = 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;
}


/**
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() {

	var bValid = true;
	var bNumeric = true;
	var elemDate = document.getElementById('reg_user_DOB');
	
	if (elemDate.value == '') {
		return false;
	}
	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;
	
	if (document.getElementById('reg_user_Specialty').selectedIndex == 0) {
	
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_Specialty', ErrMsg_Required);
		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;
}	

//Determines if we have data entered in M, D or Y fields, because this field is optional.
function isMDYDataPresent(arrDOB) {
	var bDataPresent = false;
	for (var i in arrDOB) {
		if (arrDOB[i].value.length > 0) { bDataPresent = true; }
	}
	return bDataPresent;
}

////////////////////////////////////////////////////////////////////////
// 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;
	
	//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();
		
		if (bValidSurveys && bValidUser) { 
		    
			bValid = true; 
		}
	}
	else {
		bValid = true;
	}
	
	//Hide and show footer for IE6
	resetFooter();
	
	return bValid;
}

//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';
	}
}

function resetFooter() {
	//Hide and show footer for IE6
	document.getElementById('footer').style.display = 'none';
	document.getElementById('footer').style.display = 'block';
}

////////////////////////////////////////////////////////////////////////
// survey validation functions 
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
// Main function for validating survey info.
////////////////////////////////////////////////////////////////////////

function ValidateSurveyData() {

	//Main survey validation flag
	var bValid = true;
	
	//Survey validation flags
	var bQ1 = true;
	var bQ2 = true;
	var bQ3 = true;
	var bQ4 = true;
	var bTotal100 = true;
	
    bQ1 = ValidateGroup('reg_survey_2_ctr', 'input', ErrMsg_Required_Numeric_Percent, true);
    bQ2 = ValidateGroup('reg_survey_3_ctr', 'input', ErrMsg_Required_Numeric, false);
    bQ3 = ValidateGroup('reg_survey_4_ctr', 'input', ErrMsg_Required_Numeric, false);
    
	//Validate Q4 if needed
    var selectedItem = document.getElementById("reg_user_Specialty").value;
    if((selectedItem == 2) || (selectedItem == 3) || (selectedItem == 7)) {

        bQ4 = ValidateGroup('reg_survey_5_ctr', 'input', ErrMsg_Required_Numeric_Percent, true);
        if (bQ4) {
		    var total1, total2;
		    var arr = new Array(4);
		    arr[0] = 'reg_survey_26';
		    arr[1] = 'reg_survey_28';
		    arr[2] = 'reg_survey_30';
		    arr[3] = 'reg_survey_32';
		    total1 = getTotal(arr);
    		
		    arr[0] = 'reg_survey_27';
		    arr[1] = 'reg_survey_29';
		    arr[2] = 'reg_survey_31';
		    arr[3] = 'reg_survey_33';
		    total2 = getTotal(arr);

		    if ((total1 != 100) || (total2 != 100)){
			    setMainErrorMessage(DefaultErrorMessage);
			    setErrorMessage('reg_survey_5', ErrMsg_PercentsMustEqual100);
			    bTotal100 = false;
		    }
		}
	}
   
    //Check each survey flag for validity. Then set main survey flag.
    //(Prevents form from posting and validating items on server).
	if (!bQ1 || !bQ2 || !bQ3 || !bQ4 || !bTotal100) { 
		bValid = false; 
	}
	
	return bValid;
}


/**
survey validation helper functions 
**/

function trim(str) 
{
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

//Make sure all elements in container have numeric values
//containerid: container ID
//elemtype: element type
//errmsg: error message
//isPercent: should the values be valid percents <=100? 
function ValidateGroup(containerid, elemtype, errmsg, isPercent) {
    var bValidGroup = true;
	var c = document.getElementById(containerid);
	var elems = c.getElementsByTagName(elemtype);
	for (var i = 0; i < elems.length; i++) {
        var val = elems[i].value;
        if (!validateNumeric(elems[i].id)) bValidGroup = false;
        //If isPercent, make sure value is a valid % <= 100
        if (isPercent && !validatePercent(elems[i].id)) bValidGroup = false;
	}
	if (!bValidGroup) {
		//Flag error
        setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage(containerid.replace('_ctr',''), errmsg);
		bValidGroup = false;
	}
	return bValidGroup;
}

//Numeric helper
function validateNumeric(id) {
	var val = document.getElementById(id).value;
	if (trim(val) == '') {
	    //Make sure it has a value
	    return false;
    } else if (!isNumeric(val)) {
        //Check for numeric value
        return false;
    }
	return true;
}

//Percents helper
function validatePercent(id) {
	var val = document.getElementById(id).value;
    if (parseInt(val)>100) {
        //Not valid if more than 100%
        return false;
    }
	return true;
}

//Percents helper
function getTotal(arr) {
	var t = 0;
	for (var i in arr) {
		var num = parseInt(document.getElementById(arr[i]).value);
		if (isNaN(num)) { 
			num = 0; 
		}
		t += num;
	}
	return t;
}

//Determines if user is patient.
function isUserPatient() {
	var elem = document.getElementById(id);
	if (elem.checked) { 
		return true; 
	}
	else { 
		return false; 
	}
}

////Can use to validate checkbox group or radio group.
//function ValidateRadioGroup(containerid, elemtype, selectionsRequired, errmsg) {
//	var bValidGroup = true;
//	var selections = 0;
//	var c = document.getElementById(containerid);
//	var elems = c.getElementsByTagName(elemtype);
//	for (var i = 0; i < elems.length; i++) {
//		if (elems[i].checked) {
//			selections++;
//		}
//	}
//	//Did we get enough selections?
//	if (selections < selectionsRequired) {
//		//Flag error
//        setMainErrorMessage(DefaultErrorMessage);
//		setErrorMessage(containerid.replace('_ctr',''), errmsg);
//		bValidGroup = false;
//	}
//	return bValidGroup;
//}

//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;
	}
}

