﻿var ErrorContainer_Suffix = '_err';
var Container_Suffix = '_ctr';
var ErrMsg_Required = 'Value 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_Required_ZIP = 'Please enter a 5 number zip code.';
var ErrMsg_Required_EML = 'Please enter a valid email address like, john_doe@email.com.';
var ErrMsg_Required_EML2 = 'Please re-enter the same email address as in the first email field.';

var ErrMsg_Required_Login_EML = 'Please enter a valid e-mail address.';
var ErrMsg_Required_Login_PWD = 'Please enter a password for your myCORNER account.';

var ErrMsg_Required_DOB = 'Please provide your date of birth.';
var ErrMsg_Required_PWD = 'Please enter a password for your myCorner 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_UT = 'Please choose a category that best describes you.';
var ErrMsg_Required_CS = 'Please select which stage your cancer was/is in.';
var ErrMsg_Required_FTX = 'Please select when you expect to finish treatment.'; //Not required.
var ErrMsg_Required_WASNOW = 'Please provide an answer about which hormonal breast cancer treatments you have used.';
var ErrMsg_Required_MONTHS = 'Please enter the "months taken" for the treatment you are now on.';

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 = 'Format is MM-DD-YYYY';
var ErrMsg_Match_EML = 'The E-mail addresses you entered do 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 email 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 "Sign up" again.';
var ErrMsg_MonthsExceedsMax = 'Please do not enter more than 60 months.';

//////////////////////////////////////////////////////////////////////
// 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;
}

function clearAllErrors() {
	clearMainErrorMessage();
	clearErrors();
	errExceedHMaxFlag = false;
}

//clears the main error message
function clearMainErrorMessage() {
	var errorsummary = document.getElementById('errorsummary');
	errorsummary.innerHTML = '';
	errorsummary.className = 'reg_main_err_msg_off'; 
	
}

//displays the main error message
function setMainErrorMessage(message)
{
     var errDiv = document.getElementById("errorsummary");     
     if (errDiv) 
     {
         errDiv.innerHTML = message;
         if (message=="")
             errDiv.className = "reg_main_err_msg_off"; 
         else
             errDiv.className = "reg_main_err_msg"; 
     }
}

//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','reg_user_LastName_err');
	arrErrorDivs.push('reg_user_Address1_err','reg_user_Address2_err','reg_user_City_err');
	arrErrorDivs.push('reg_user_State_err','reg_user_Zip_err','reg_user_EmailAddress_err');
	arrErrorDivs.push('reg_user_ConfirmEmail_err','reg_user_Password_err','reg_user_ConfirmPassword_err');
	arrErrorDivs.push('reg_user_Phone1_err','reg_user_Specialty_err','reg_user_DOBMain_err');
	//Surveys
	arrErrorDivs.push('reg_survey_1_err');
	arrErrorDivs.push('reg_survey_6_err');
	arrErrorDivs.push('reg_survey_15_err');
	/////////////////////////////////////////////
	var arrContainerDivs = []; //Container error div id
	//User fields
	arrContainerDivs.push('reg_user_FirstName_ctr','reg_user_LastName_ctr');
	arrContainerDivs.push('reg_user_Address1_ctr','reg_user_Address2_ctr','reg_user_City_ctr');
	arrContainerDivs.push('reg_user_State_ctr','reg_user_Zip_ctr','reg_user_EmailAddress_ctr');
	arrContainerDivs.push('reg_user_ConfirmEmail_ctr','reg_user_Password_ctr','reg_user_ConfirmPassword_ctr');
	arrContainerDivs.push('reg_user_Phone1_ctr','reg_user_Specialty_ctr','reg_user_DOBMain_ctr');
	//Surveys
	arrContainerDivs.push('reg_survey_1_ctr');
	arrContainerDivs.push('reg_survey_6_ctr');
	arrContainerDivs.push('reg_survey_15_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 = 'reg_err_msg_off';
		}
	}
}

//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 == 'reg_err_msg')
                conDiv.className = 'reg_err_msg_off';   
        }
        else
        {
            if (conDiv.className == 'reg_err_msg_off')
                conDiv.className = 'reg_err_msg'; 
        }
    }
}

/////////////////////////////////////////////////////////////

//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 "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 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;

//New DOB max values to prevent future date of birth values.
var dtDateNow = new Date();

var intDobCurrentYear = dtDateNow.getFullYear();
var intDobCurrentMonth = dtDateNow.getMonth()+1;
var intDobCurrentDay = dtDateNow.getDate();
var maxDOBMonth=intDobCurrentMonth;
var maxDOBDay=intDobCurrentDay-1;
var maxDOBYear=intDobCurrentYear;

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;
	}
	//Check for future dates of birth...
	var bBDayValid = isBirthdayValid(month, day, year);
	if (!bBDayValid) { 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;
}

//Weeds out future dates only.
function isBirthdayValid(m,d,y) {
	var bValid = true;
	if (y > intDobCurrentYear) { 
		bValid = bValid && false; 
	}
	else {
		if (y == intDobCurrentYear) {
			if (m > intDobCurrentMonth) {
				bValid = bValid && false; 
			}
			else {
				if (m == intDobCurrentMonth) {
					if (d > maxDOBDay) {
						bValid = bValid && false;
					}
				}
			}
		}
	}
	return bValid;
}

/////////////////////////////////////////////////////////////


/** 
validation list init functions 
**/

function initReqTextboxes() {

	var arrReqTextIDs = [];
	var arrReqTextBoxes = [];
	arrReqTextIDs.push('reg_user_FirstName','reg_user_LastName','reg_user_Address1');
	arrReqTextIDs.push('reg_user_City','reg_user_Zip');

	// 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_FN);
					break;
				case 'reg_user_LastName':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required_LN);
					break;
				case 'reg_user_Address1':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required_ADDR);
					break;
				case 'reg_user_City':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required_CITY);
					break;
				case 'reg_user_Zip':
					setErrorMessage(arrReqTexts[i].id, ErrMsg_Required_ZIP);
					break;
			}
			//setErrorMessage(arrReqTexts[i].id, ErrMsg_Required);
			setMainErrorMessage(DefaultErrorMessage);
			bValid = false;
		}
	}
	
	//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 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_ValidType);
		bValid = false;
	}
	
	//Validate email and password: Required, Regex and Match.
	var bValidEmail = ValidateEmail();
	var bValidConfirmEmail = ValidateConfirmEmail();
	var bValidPass = ValidatePassword();
	var bValidConfirmPass = ValidateConfirmPassword();
	
	if (!bValidEmail || !bValidConfirmEmail || !bValidPass || !bValidConfirmPass) {
		bValid = false;
	}

	//Validate DOB: Required, Regex.
	var bValidDOB = ValidateBirthDate();
	if (!bValidDOB) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_DOBMain', ErrMsg_Invalid_DOB);
		bValid = false;
	}
	
	//Validate phone (optional), Regex.
	var ph = document.getElementById('reg_user_Phone1');
	if (ph.value.length > 0) {
		var bValidPhone = isValidPhoneNumber(ph.value);
		if (!bValidPhone) {
			//Set error
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_user_Phone1', ErrMsg_ValidType);
			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; }
	//4/22/09: Updated to include all top-level domains, such as
	//.travel, .museum, .xn--hgbk6aj7f53bba, .xn--11b5bs3a9aj6gs, .xn--hlcj6aya9esc7a
	//NEW:
	re = /^[a-zA-Z0-9\-\._]+\@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2,18})$/; 
	//OLD:
	//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 = 'reg_err_msg';
		err.innerHTML = ErrMsg_Required_ST;
		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_EML);
		return false;
	}
	if (!isValidEmailAddress(emailID.value)) {
		//Set error
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_user_EmailAddress', ErrMsg_ValidType);
		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_EML2);
		return false;
	}
	
	if (confirmID && emailID) {
		if (emailID.value != '' || confirmID.value != '') {
			if (!isValidEmailAddress(confirmID.value)) {
				//Set error
				setMainErrorMessage(DefaultErrorMessage);
				setErrorMessage('reg_user_ConfirmEmail', ErrMsg_ValidType);
				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 mon = document.getElementById('reg_user_DOBMonth');
	var day = document.getElementById('reg_user_DOBDay');
	var year = document.getElementById('reg_user_DOBYear');
	var m = mon.value;
	var d = day.value;
	var y = year.value;
	
	//Since DOB is not required, if all fields are blank, return true.
	if (m.length == 0 && d.length == 0 && y.length == 0) { return true; }
	
	//Otherwise, if any one of the fields are blank, return false.
	if (m.length == 0 || d.length == 0 || y.length == 0) { return false; }
	
	//check if we have numeric values we can work with...
	if (!IsNumeric(m) || !(m.length == 2)) { setInvalidDOB_Month(); bNumeric = false; }
	if (!IsNumeric(d) || !(d.length == 2)) { setInvalidDOB_Day(); bNumeric = false; }
	if (!IsNumeric(y) || !(y.length == 4)) { setInvalidDOB_Year(); bNumeric = false; }
	if (!bNumeric) { return false; }
	
	//We have numeric values...continue validation...
	var dt = mon.value + '/' + day.value + '/' + year.value;
	if (!isDate(dt)) {
		//Set error
		bValid = false;
	}
	
	return bValid;
}

function setInvalidDOB_Month() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOBMain', ErrMsg_Invalid_DOB);
}
function setInvalidDOB_Day() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOBMain', ErrMsg_Invalid_DOB);
}
function setInvalidDOB_Year() {
	//Set error
	setMainErrorMessage(DefaultErrorMessage);
	setErrorMessage('reg_user_DOBMain', 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;
}	

//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) {
	
		//Validate user...
		var bValidUser = ValidateUser();
		
		//alert('user data valid: ' + bValidUser);
	
		//Validate surveys...
		var bValidSurveys = ValidateSurveyData();
		if (bValidSurveys && bValidUser) { 
			bValid = true; 
		}
	}
	else {
		bValid = true;
	}
	
	return bValid;
}

////////////////////////////////////////////////////////////////////////
// survey validation functions 
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
// Main function for validating survey info.
////////////////////////////////////////////////////////////////////////
function ValidateSurveyData() {

	var bValid = true;
	var bSeg = ValidateSegmentation();		//We're validating group 1 here.
	var bCS = ValidateCancerStage();			//We're validating group 3 here.
	var bVHT = ValidateHormonalTherapy();	//We're validating group 7 here.
	
	//alert('bVHT: ' + bSeg);
	//alert('bCS: ' + bCS);
	//alert('bVHT: ' + bVHT);
	
	if (!bSeg || !bCS || !bVHT) { 
		bValid = false;
		scrollToErrorSummary();
	}
	
	////////////////////////////////////
	//alert('surveys valid: ' + bValid);
	////////////////////////////////////
	return bValid;
}

/**
survey validation helper functions 
**/

//Validates the user type: patient, caregiver, hcp, other.
function ValidateSegmentation() {
	var bValid = true;
	
	var q1 = document.getElementById('reg_survey_1');
	var q2 = document.getElementById('reg_survey_2');
	var q3 = document.getElementById('reg_survey_3');
	var q4 = document.getElementById('reg_survey_4');
	
	if (!q1.checked && !q2.checked && !q3.checked && !q4.checked) {
		bValid = false;
	}
	
	//If anything is not valid in survey group 1, flag.
	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_1', ErrMsg_Required_UT);
	}
	return bValid;
}

function ValidateCancerStage() {
	var bValid = true;
	var bPatient = isUserPatient();
	
	//alert('is user patient?' + bPatient);
	
	if (bPatient) {
		
		var q6 = document.getElementById('reg_survey_6');
		var q7 = document.getElementById('reg_survey_7');
		var q8 = document.getElementById('reg_survey_8');
		
		if (!q6.checked && !q7.checked && !q8.checked) {
			bValid = false;
		}

		//If anything is not valid in survey group 3, flag.
		if (!bValid) {
			setMainErrorMessage(DefaultErrorMessage);
			setErrorMessage('reg_survey_6', ErrMsg_Required_CS);
		}
	}
	
	//alert('ValidateCancerStage valid: ' + bValid);
	
	return bValid;
}

function ValidateHormonalTherapy() {
	//First determine if the user is a patient.
	//If not, the group 8 surveys are not required, so return true.
	var bPat = isUserPatient();
	if (bPat) {
		
		//First determine if the user has never used hormonal treatment
		//If this is selected, this is the only item that is required.
		var bNotHormonalTreatmentUser = isNotHormonalTreatmentUser();
		if (bNotHormonalTreatmentUser) {
			//Clear the rest of the hormonal survey data, just in case it's populated...
			clearHormonalSurveyItems();
			//This is the only required radio item for the survey. Return valid.
			return true;
		}
		else {
			//Validate the hormonal form elements (user has used hormonal treatment).
			var bHFV = isHormonalFormValid();
			if (bHFV) { return true; }
			else { return false; }
		}
	}
	//User is not a patient, and therefore the hormonal survey items do not need to be validated.
	return true;
}

//This function will flag hormonal survey errors.
function isHormonalFormValid() {
	var bValid = true;
	var intErrorID = 0;
	
	//Arimidex
	var o1_1 = document.getElementById('reg_survey_15');
	var o1_2 = document.getElementById('reg_survey_16');
	var o1_3 = document.getElementById('reg_survey_17');
	//Aromasin
	var o2_1 = document.getElementById('reg_survey_18');
	var o2_2 = document.getElementById('reg_survey_19');
	var o2_3 = document.getElementById('reg_survey_20');
	//Femara
	var o3_1 = document.getElementById('reg_survey_21');
	var o3_2 = document.getElementById('reg_survey_22');
	var o3_3 = document.getElementById('reg_survey_23');
	//tamoxifen
	var o4_1 = document.getElementById('reg_survey_24');
	var o4_2 = document.getElementById('reg_survey_25');
	var o4_3 = document.getElementById('reg_survey_26');
	//Others
	var o5_1 = document.getElementById('reg_survey_27');
	var o5_2 = document.getElementById('reg_survey_28');
	var o5_3 = document.getElementById('reg_survey_29');
	//faslodex (added 9/2/09)
	var o6_1 = document.getElementById('reg_survey_32');
	var o6_2 = document.getElementById('reg_survey_33');
	var o6_3 = document.getElementById('reg_survey_34');

	//Add the items to an array to do some checks...
	var arrSurveyItems = [];
	arrSurveyItems.push(o1_1, o1_2, o1_3);
	arrSurveyItems.push(o2_1, o2_2, o2_3);
	arrSurveyItems.push(o3_1, o3_2, o3_3);
	arrSurveyItems.push(o4_1, o4_2, o4_3);
	arrSurveyItems.push(o5_1, o5_2, o5_3);
	arrSurveyItems.push(o6_1, o6_2, o6_3);
		
	//See if at least one is checked.
	var bOneChecked = isOneSurveyItemChecked(arrSurveyItems);
	if (bOneChecked) {
		//Check if "Now on" was checked in a row. 
		//If so, "Months taken" needs to be specified and numeric.
		var bHRow1Valid = isHormonalSurveyRowValid(o1_1, o1_2, o1_3);
		var bHRow2Valid = isHormonalSurveyRowValid(o2_1, o2_2, o2_3);
		var bHRow3Valid = isHormonalSurveyRowValid(o3_1, o3_2, o3_3);
		var bHRow4Valid = isHormonalSurveyRowValid(o4_1, o4_2, o4_3);
		var bHRow5Valid = isHormonalSurveyRowValid(o5_1, o5_2, o5_3);
		var bHRow6Valid = isHormonalSurveyRowValid(o6_1, o6_2, o6_3);
		if (!bHRow1Valid || !bHRow2Valid 
				|| !bHRow3Valid || !bHRow4Valid 
				|| !bHRow5Valid || !bHRow6Valid) {
			intErrorID = 2;
			bValid = false;
		}
	}
	else {
		intErrorID = 1; //WAS/NOW error.
		bValid = false;
	}
		
	//If anything is not valid in survey group 8, flag.
	if (!bValid) {
		setMainErrorMessage(DefaultErrorMessage);
		//Get the type of hormonal error, so we can report an accurate msg.
		if (intErrorID == 0) {
			//General error - this should not be displayed.
			setErrorMessage('reg_survey_15', ErrMsg_Required_SEL);
		}
		if (intErrorID == 1) {
			//WAS/NOW error
			setErrorMessage('reg_survey_15', ErrMsg_Required_WASNOW);
		}
		if (intErrorID == 2) {
			//NOW/MOT error
			setErrorMessage('reg_survey_15', ErrMsg_Required_MONTHS);
		}
	}
	//Check if the user exceeded 60 months for any row.
	if (errExceedHMaxFlag) {
		setMainErrorMessage(DefaultErrorMessage);
		setErrorMessage('reg_survey_15', ErrMsg_MonthsExceedsMax);
		bValid = false;
	}
	return bValid;
}

/////////////////////////////////
var errExceedHMaxFlag = false;
/////////////////////////////////
//If radio2 (Now on) is checked, see if the "Months taken" is specified and numeric.
function startsWithNonZero(s){
   if (s.length > 0) {
		var c = s.charAt(0);
		if (c == "0") { return false; }
		else { return true; }
	}
	else { 
		return true;
	}
}
function isHormonalSurveyRowValid(radio1, radio2, txt) {
	var bNumeric;
	if (txt.value.length > 0) {
		bNumeric = isInteger(txt.value); //Decimals break profile view.
		bNumeric = bNumeric && startsWithNonZero(txt.value); //Remove leading zeros.
		if (!bNumeric) { 
			return false; 
		}
	}
	//If "now on" was checked, validate txt.
	if (radio2.checked) {
		if (txt.length == 0 || txt.value == '') { 
			return false; 
		}
	}
	//See if txt is > 60
	var n = parseInt(txt.value);
	if (n > 60) {
		//Flag error
		errExceedHMaxFlag = true;
	}
	return true;
}

//Determines if at least 1 group 8 survey radio item is checked (excluding "never used").
function isOneSurveyItemChecked(arr) {
	var bChecked = false;
	for (var i in arr) {
		if (arr[i].checked) {
			bChecked = true;
		}
	}
	return bChecked;
}


function isNotHormonalTreatmentUser() {
	var elem = document.getElementById('reg_survey_30');
	if (elem.checked) {
		return true;
	}
	else {
		return false;
	}
}

//Determines if user is an advanced breast cancer patient.
//(If so, membership does not apply).
function isCancerStageAdvanced() {
	var elem = document.getElementById('reg_survey_7');
	if (elem.checked) {
		return true;
	}
	else {
		return false;
	}
}

function isHCP() {
	var elem = document.getElementById('reg_survey_4');
	if (elem.checked) { 
		return true; 
	}
	else { 
		return false; 
	}
}

//Determines if user is patient.
function isUserPatient() {
	var elem = document.getElementById('reg_survey_1');
	if (elem.checked) { 
		return true; 
	}
	else { 
		return false; 
	}
}

//Scroll the top of the page on error
function scrollToErrorSummary() {
	var top = document.getElementById('errorsummary');
	ScrollToElement(top);
}

/////////////////////////////////////////////////////////
// login.aspx client side validation functions
/////////////////////////////////////////////////////////

function checkLoginForm() {

	if (!DO_CLIENT_VALIDATION) {
		return true;
	}

	//return false;

	var bLoginValid = true;					//Main valid flag
	var bValidLoginEmailLength = true;	//Required check: Email	
	var bValidLoginEmail = true;			//Invalid check: Email
	var bValidLoginPassLength = true;	//Required check: PWD
	var bValidLoginPass = true;			//Invalid check: PWD

	//Server side validation - validates email and password against users table
	var parInvalidCredentials = document.getElementById('parInvalidCredentials');

	//Validation summary text
	var strValSummary = '';
	strValSummary += '* We\'re sorry but there are problems with your log in. ';
	strValSummary += 'Please enter the required information to log in.';
	strValSummary += '<ul>';
	var strValSummaryFooter = '</ul>';
	
	//Retrieve email and password values
	var eml = document.getElementById('ctl00_Column4Main_objLogin_txtEmail').value;
	var pwd = document.getElementById('ctl00_Column4Main_objLogin_txtPassword').value;
	
	//Retrieve labels: we'll switch to elem.style.color = '#ff0000;';
	var lblLoginEmail = document.getElementById('txtEmailLabel');
	var lblLoginPass = document.getElementById('txtPasswordLabel');
	
	//Asterisks: We'll set visibility to visible, display to block.
	var asteriskLoginEmail = document.getElementById('ctl00_Column4Main_objLogin_UserNameRequired');
	var asteriskLoginPass = document.getElementById('ctl00_Column4Main_objLogin_PasswordRequired');
	
	//Login Validation Summary container:
	var divLoginVS = document.getElementById('ctl00_Column4Main_objLogin_ValidationSummary1');
	
	//Validate email: required
	bValidLoginEmailLength = isValidLoginLength(eml);
	
	//Validate email: invalid
	if (bValidLoginEmailLength) { 
		bValidLoginEmail = isValidEmailAddress(eml); 
	}
	else {
		bLoginValid = false;
	}
	
	//Validate password: required
	bValidLoginPassLength = isValidLoginLength(pwd);
	
	//Validate password: invalid
	if (bValidLoginPassLength) { 
		bValidLoginPass = isValidPassword(pwd); 
	}
	else {
		bLoginValid = false;
	}

	//0.First clear any old errors.
	clearLoginErrors(divLoginVS, lblLoginEmail, lblLoginPass, asteriskLoginEmail, asteriskLoginPass, parInvalidCredentials);

	//1.1 Validate Login Email: Required
	if (!bValidLoginEmailLength) {
		bLoginValid = false;
		strValSummary += '<li>' + ErrMsg_Required_Login_EML  + '</li>';
		setLoginError(lblLoginEmail, asteriskLoginEmail);
	}
	//1.2 Validate Login Email: Invalid
	if (!bValidLoginEmail) {
		bLoginValid = false;
		strValSummary += '<li>' + ErrMsg_Required_Login_EML  + '</li>';
		setLoginError(lblLoginEmail, asteriskLoginEmail);
	}
	//2.1 Validate Login Password: Required
	if (!bValidLoginPassLength) {
		bLoginValid = false;
		strValSummary += '<li>' +ErrMsg_Required_Login_PWD  + '</li>';
		setLoginError(lblLoginPass, asteriskLoginPass);
	}
	//2.2 Validate Login Password: Invalid
	if (!bValidLoginPass) {
		bLoginValid = false;
		strValSummary += '<li>' + ErrMsg_InvalidChars_PWD  + '</li>';
		setLoginError(lblLoginPass, asteriskLoginPass);
	}
	//3.0 If anything is invalid, populate validation summary
	if (!bLoginValid) {
		divLoginVS.innerHTML = strValSummary + strValSummaryFooter;
		divLoginVS.style.display = 'block';
	}
	
	//Return status
	return bLoginValid;
}

function isValidLoginLength(value) {
	if (value.length <= 0) {
		return false;
	}
	else {
		return true;
	}
}

function setLoginError(elemLabel, elemAsterisk) {
	elemLabel.style.color = '#ff0000';
	elemAsterisk.style.visibility = 'visible';
}

function clearLoginErrors(divLoginVS, lbl1, lbl2, ast1, ast2, parInvalidCredentials) {
	divLoginVS.innerHTML = ''; //may want to set to invisible too
	divLoginVS.style.display = 'none';
	lbl1.style.color = '#000000';
	lbl2.style.color = '#000000';
	ast1.style.visibility = 'hidden';
	ast2.style.visibility = 'hidden';
	parInvalidCredentials.innerHTML = '';
}


/////////////////////////////////////////////////////////
// create-mycorner-account.aspx (CMA) client side validation functions
/////////////////////////////////////////////////////////

function checkCreateAccountForm() {

	if (!DO_CLIENT_VALIDATION) {
		return true;
	}

	////////////////////////
	//1. Retrieve Values
	////////////////////////

	var bCMAValid = true;					//Main valid flag
	var bValidCMAPass1Length = true;		//Required check: PWD 1
	var bValidCMAPass1 = true;				//Invalid check: PWD 1
	var bValidCMAPass2Length = true;		//Required check: PWD 2
	var bValidCMAPass2 = true;				//Invalid check: PWD 2
	var idPassword = 'ctl00_Column4Main_txtPassword';
	var idPasswordConfirm = 'ctl00_Column4Main_txtPasswordConfirm';
	var idPasswordLabel = 'lblPass1';
	var idPasswordConfirmLabel = 'lblPass2';
	var idAsteriskPassword = 'ctl00_Column4Main_vrfPassword';
	var idAsteriskPasswordConfirm = 'ctl00_Column4Main_vrfPasswordConfirm';
	var idValidationSummary = 'ctl00_Column4Main_ValidationSummary1';

	//Server side validation - validates email and password against users table
	//var parInvalidCredentials = document.getElementById('parInvalidCredentials');

	//Validation summary text
	var strValSummary = '';
	strValSummary += '* Some required information is missing from your form. ';
	strValSummary += 'Please complete the required fields and click SUBMIT again.';
	strValSummary += '<ul>';
	var strValSummaryFooter = '</ul>';

	//Retrieve password and confirm password values
	var pwd1 = document.getElementById(idPassword).value;
	var pwd2 = document.getElementById(idPasswordConfirm).value;

	//Retrieve labels: we'll switch to elem.style.color = '#ff0000;';
	var lblPwd1 = document.getElementById(idPasswordLabel);
	var lblPwd2 = document.getElementById(idPasswordConfirmLabel);

	//Retrieve asterisk spans: We'll set visibility to visible, display to block.
	var asteriskPwd1 = document.getElementById(idAsteriskPassword);
	var asteriskPwd2 = document.getElementById(idAsteriskPasswordConfirm);

	//Retrieve Validation Summary container:
	var divCMAVS = document.getElementById(idValidationSummary);

	////////////////////////
	//2. Validate
	////////////////////////

	//Validate password 1: required
	bValidCMAPassLength1 = isValidCMALength(pwd1);
	
	//Validate password 1: invalid
	if (bValidCMAPass1Length) { 
		bValidCMAPass1 = isValidPassword(pwd1); 
	}
	else {
		bCMAValid = false;
	}

	//Validate password 2: required
	bValidCMAPassLength2 = isValidCMALength(pwd2);
	
	//Validate password 2: invalid
	if (bValidCMAPass2Length) { 
		bValidCMAPass2 = isValidPassword(pwd2); 
	}
	else {
		bCMAValid = false;
	}

	////////////////////////
	//3. First clear any old errors.
	////////////////////////
	clearCMAErrors(divCMAVS, lblPwd1, lblPwd2, asteriskPwd1, asteriskPwd2, null);
	
	////////////////////////
	//4. Check values and return status.
	////////////////////////
	
	//Validate Password 1: Required
	if (!bValidCMAPassLength1) {
		bCMAValid = false;
		strValSummary += '<li>' + ErrMsg_Required_PWD  + '</li>';
		setCMAError(lblPwd1, asteriskPwd1);
	}
	//Validate Password 1: Invalid
	if (!bValidCMAPass1) {
		bCMAValid = false;
		strValSummary += '<li>' + ErrMsg_InvalidChars_PWD  + '</li>';
		setCMAError(lblPwd1, asteriskPwd1);
	}
	//Validate Password 2: Required
	if (!bValidCMAPassLength2) {
		bCMAValid = false;
		strValSummary += '<li>' + ErrMsg_Required_PWD  + '</li>';
		setCMAError(lblPwd2, asteriskPwd2);
	}
	//Validate Password 2: Invalid
	if (!bValidCMAPass2) {
		bCMAValid = false;
		strValSummary += '<li>' + ErrMsg_InvalidChars_PWD  + '</li>';
		setCMAError(lblPwd2, asteriskPwd2);
	}
	//If anything is invalid, populate validation summary
	if (!bCMAValid) {
		divCMAVS.innerHTML = strValSummary + strValSummaryFooter;
		divCMAVS.style.display = 'block';
	}
	
	//Return status
	return bCMAValid;
	
}

function clearCMAErrors(VS_DIV, lbl1, lbl2, ast1, ast2, parInvalidCredentials) {
	VS_DIV.innerHTML = ''; //may want to set to invisible too
	VS_DIV.style.display = 'none';
	lbl1.style.color = '#000000';
	lbl2.style.color = '#000000';
	ast1.style.visibility = 'hidden';
	ast2.style.visibility = 'hidden';
	//parInvalidCredentials.innerHTML = '';
}

function isValidCMALength(value) {
	if (value.length <= 0) {
		return false;
	}
	else {
		return true;
	}
}

function setCMAError(elemLabel, elemAsterisk) {
	elemLabel.style.color = '#ff0000';
	elemAsterisk.style.visibility = 'visible';
}