var CS_PASSWORD                 = CS_ALPHANUMERIC + "_-.~`!@#$%^&*()_+";

var emailTaken = '';
var emailInvalid = false;
var passwordFailed = false;
var passwordFailureMessage = "Please enter a more secure password that is between 6 and 16 characters long, does not begin or end with a space, and is dissimilar from your email address.";
var emailInvalidMessage = "Please enter an email address in the format address@domain.com.";
var emailTakenMessage = "Please enter an email address not already taken.  If this account is registered to you, please log into it.";

//***********************************
//  submitRegistration()
//  - Performs client-side validations against 
//    unauth registration 
//***********************************
function submitRegistration(form)
{
    
    //Check that required first name was entered
    if(!checkName(document.getElementById("firstname").value,1))
    {
        document.getElementById("firstname").focus();
        document.getElementById("firstname").select();
        return false;
    }
    
    //Check that required last name was entered
    if(!checkName(document.getElementById("lastname").value,2))
    {
        document.getElementById("lastname").focus();
        document.getElementById("lastname").select();
        return false;
    }
    
    if (!isZip(document.getElementById("zipcode").value) ) 
    {
		alert("Please enter a valid zipcode.");
		document.getElementById("zipcode").focus();
		document.getElementById("zipcode").select();
		return false;
	}

    
	//If birthMonth is in the form and the first value is selected
	if (document.getElementById("birthMonth") != null)
	{
	    if(document.getElementById("birthMonth").selectedIndex == 0)
	    {
	        alert("Please select a birth month.");
	        document.getElementById("birthMonth").focus();
	        return false;
	    }
	}

	//If birthday is in the form and the first value is selected
	if (document.getElementById("birthDay") != null)
	{
	    if(document.getElementById("birthDay").selectedIndex == 0)
	    {
	        alert("Please select a birth day.");
	        document.getElementById("birthDay").focus();
	        return false;
	    }
	}

	//If birthYear is in the form and it is NULL...
	if (document.getElementById("birthYear") != null)
	{
	    var birthYearObj = document.getElementById("birthYear");
	    if (birthYearObj.value.length != 4 ||
            !string_charset_check(birthYearObj.value,CS_NUMERIC, ""))
        {
            alert("Please enter a 4-digit birth year.");
            birthYearObj.focus();
            birthYearObj.select();
            return false;
        }
	}

    //Call this, again, to have a chance to reset emailInvalid if the first email field was changed.
	validateConfirmEmail();
	
	if(emailInvalid || !check_email_addr(document.getElementById("emailAdd").value))
    {
        alert(emailInvalidMessage);
        document.getElementById("emailAdd").focus();
        document.getElementById("emailAdd").select();
        return false;
    }
    
    //If email is already taken and active, give them the chance to log in, or return to the form to select another email
	if (emailTaken == 'not_available') {
	    document.getElementById('emailTakenPopUp').style.display='block';
	    return false;
	}
    //If email is already taken and requires confirmation, give them the chance to confirm or receive antoher confirmation email
	else if (emailTaken == 'requires_confirmation') {
	    document.getElementById('emailRequiresConfirmationPopUp').style.display='block';
	    return false;
	}
	
	// Password is empty or doesn't match retypePassword...
    if(!checkName(document.getElementById("password").value,4))
    {
        document.getElementById("password").focus();
        document.getElementById("password").select();
        return false;
    }
    if (document.getElementById("password").value != document.getElementById("retypePassword").value) 
    {
    	alert("Password and Retype Password do not match.");
    	document.getElementById("retypePassword").focus();
        document.getElementById("retypePassword").select();
    	return false;
    }
    
    // Check result of business logic performed on password
    if (passwordFailed)
    {
    	alert(passwordFailureMessage);
    	document.getElementById("password").focus();
        document.getElementById("password").select();
        return false;
    } 
    
    //Check Security Q&A 
    if((document.getElementById("securityQuestion").value.length < 1) || 
       (document.getElementById("securityQuestion").value == "Type your security question here"))
    {
        alert("Please be sure to enter a Security Question which may be used in case you forget your password.");
    	document.getElementById("securityQuestion").focus();
        document.getElementById("securityQuestion").select();
        return false;        
    }
    if(document.getElementById("securityAnswer").value.length < 1)
    {
        alert("Please be sure to enter a Security Answer which may be used in case you forget your password.");
    	document.getElementById("securityAnswer").focus();
        document.getElementById("securityAnswer").select();
        return false;        
    }
    
	//If captcha is empty...
    if(!checkName(document.getElementById("captcha").value,6))
    {
        document.getElementById("captcha").focus();
        document.getElementById("captcha").select();
        return false;
    }
    
    return true;
}


/*
function submitRegisterForm()
{
    
    document.registration.action="register/later";
    document.registration.submit();
}

function submitRegisterNow()
{
	var isMyInfoClear = checkMyInfoFields();
	if (!isMyInfoClear) {
		return false;
	}	
   
    document.registration.action="/myprofile/register/now";
    return true;

}
*/


//***********************************
// Tests zipcode for an associated region
// We only want to display the region error once to the user
//***********************************
var regionErrorDisplayed = false;
function validateZipcodeForRegion() {
	var zipcode = $('zipcode');
    if ( !isZip(zipcode.value) ) 
    {
		alert("Please enter a valid zipcode.");
		zipcode.focus();
		zipcode.select();
		return false;
	}
	else if(!regionErrorDisplayed) {
		var url = "/myprofile/register/validateZipcodeForRegion";
		myAjax = new Ajax.Request(url, 
			{method: 'post', 
			parameters: {zipcode: zipcode.value}, 
			asynchronous: true, 
			onComplete: zipcodeValidationResponse}
			);
	}

}

function zipcodeValidationResponse(request) {
	var response = request.responseText;
	if (response != "null") {
		regionErrorDisplayed = true;
		alert(response);
	}
}

//***********************************
// Tests email address for valid format and uniqueness
//***********************************
var emailDomain;
function validateEmail() {
	var emailAddr = $('emailAdd');
    
    //Verify email format
    if(!check_email_addr(emailAddr.value))
    {
        alert("Please enter an email address in the format address@domain.com.");
        emailAddr.focus();
        emailAddr.select();
        return false;
    }

    //Make AJAX call to determine if email address is available
	var url = "/myprofile/register/checkemail";
	var myAjax = new Ajax.Request(url, 
		{method: 'post', 
		parameters: {emailAdd: emailAddr.value}, 
		asynchronous: true, 
		onComplete: emailValidationResponse}
		);
}

function emailValidationResponse2(request) 
{
	var result = request.responseText;
	if (result == 'email_invalid') {
		emailInvalid = true;
		alert(emailInvalidMessage);
	}
	if (result == 'email_not_available') {
	    emailTaken = true;
	    alert(emailTakenMessage);
	}
	else 
	{   
		emailInvalid = false;
	    emailTaken = false;
	}
}

function emailValidationResponse(request) 
{
	var result = request.responseText;
	if (result == 'not_available') {
		emailTaken = 'not_available';
	    document.getElementById('emailTakenPopUp').style.display='block';
	}
	//else if (result == 'requires_confirmation') {
	//	emailTaken = 'requires_confirmation';
	//    document.getElementById('emailRequiresConfirmationPopUp').style.display='block';
	//}
	else if (result == 'email_invalid') 
	{
		emailInvalid = true;
		alert(emailInvalidMessage);
	}
	else 
	{
	    var resultString = new String(result);
		if (resultString.indexOf("typo_in_domain") != -1)
		{
		    var topLevelDomain = resultString.substring(resultString.indexOf(":") + 1);
		    var confirmTopLevel = confirm("We do not recognize the domain you entered in your email address: \"" + topLevelDomain+ "\".  Is this the correct domain?  (If yes, click OK)");    
		    if (!confirmTopLevel)
		    {
                var emailAddr = $('emailAdd');
                emailAddr.focus();
                emailAddr.select();
                return;
            }
		}
		emailInvalid = false;
	    emailTaken = '';
	}
}

function validateConfirmEmail() 
{
	var emailAddr = $('emailAdd');
	var confirmEmailAddr = $('emailAddConfirm');
    
    //Verify email format
    if(emailAddr.value != confirmEmailAddr.value)
    {
        emailInvalidMessage = "Please be sure your email address is correct in both email fields.";
        emailInvalid = true;
        alert(emailInvalidMessage);
        confirmEmailAddr.focus();
        confirmEmailAddr.select(); 
        return false;
    }
    else
    {
        emailInvalid = false;
    }
}

//***********************************
// Tests password 
// Ensure that password is provided and that it follows the password requirements
//***********************************
function validatePassword() {
	var password = $('password');
	var emailAddr = $('emailAdd');

    //Verify email format so it can be compared with password
    if(!check_email_addr(emailAddr.value))
    {
        alert("Please enter an email address in the format address@domain.com before entering a password.");
        emailAddr.focus();
        emailAddr.select();
        return false;
    }

	// Password is empty or doesn't match retypePassword...
    if(!checkName(password.value,4))
    {
        password.focus();
        password.select();
        passwordFailed = true;
        return false;
    }
    
	var url = "/myprofile/register/validatePassword";
	var myAjax = new Ajax.Request(url, 
		{method: 'post', 
		parameters: {password: password.value, emailAdd: emailAddr.value}, 
		asynchronous: true, 
		onComplete: passwordValidationResponse}
		);
    
}

function passwordValidationResponse(request) 
{
	var result = request.responseText;
	if (result == 'failed') 
	{
        passwordFailed = true;
	    alert(passwordFailureMessage);
	}
	else
	{
        passwordFailed = false;
	}
}
//***********************************
// Tests password and retype password for a match
//***********************************
function validateRetypePassword() {
	var password = $('password');
	var retypePass = $('retypePassword');
    if (password.value != retypePass.value) 
    {
    	alert("Password and Retype Password do not match.");
    	retypePass.focus();
        retypePass.select();
    	return false;
    }

}

function checkName(name, nameType) 
{
    var value = trim(name);
    
    if ( !check_len(value,0) )
    {
    	if ( nameType == 1 ) {
    		alert("Please enter a value for first name.");
    	}
    	else if ( nameType == 2 ) {
    		alert("Please enter a value for last name.");
    	}
    	else if ( nameType == 4 ) {
    		alert("Please enter a value for password.");
    	}
    	else if ( nameType == 6 ) {
    		alert("Please enter a value for security image verification.");
    	}
    	else {
    		alert("Please enter a value for street address.");
    	}
    	
    	return false;
    }
    	
    //Make sure values have been changed from "First Name" and "Last Name"
    if(nameType == 1 && name == "First Name")
    {
        alert("Please enter a value for first name.");
        return false;
    }
    if(nameType == 2 && name == "Last Name")
    {
        alert("Please enter a value for last name.");
        return false;
    }
    	
    //check there are no invalid characters
    if (!string_charset_check(value,CS_NAME, ""))
    {
        if ( nameType == 1 ) {
            alert("First name includes invalid character(s)");
            return false;
        }
        else if ( nameType == 2 ) {
            alert("Last name includes invalid character(s)");
            return false;
        }
        else if (nameType == 3 ) {
            if (!string_charset_check(value,CS_ADDRESS, ""))
            {
                alert("Street address includes invalid character(s).");
                return false;
            }
        }
        else if (nameType == 4 ) {
            if (!string_charset_check(value,CS_PASSWORD, ""))
            {
                alert("Password includes invalid character(s).");
                return false;
            }
        }
    }
    
    return true;
}		

function isZip(s)
{
	//check the length is greater than zero
	if (!check_len(s,0))
	{
		return false;
	}
	
	//check if length is more than 5 (db constrict)
	if (check_len(s,5))
	{
		return false;
	}

	//check for exact length
	if (!check_exact_len(s,5))
	{
		return false;
	}
	
	//check zipcode between valid range
	if (!min_zipcode(s))
	{
		return false;
	}
    return true;
}

//////////////////////////////////////////////////
// min_zipcode()
//
//	- Rather "loose" check to see if zipcode is valid
//	  (i.e. between 00600 and 99999)
//
//	Input: string of zipcode
//	Output: True/False
/////////////////////////////////////////////////
function min_zipcode(zipcode)
{
    n_zipcode = parseInt(zipcode,10); 
	return (n_zipcode >= 600 && n_zipcode <= 99999);
}

// NOTE: We have to add 1 for the empty space on the drop-down, so all
//       numbers look off by 1
function setMaxDays(selectBox)
{
    var daysObj = document.getElementById("birthDay"); 
    var oldLength = daysObj.length;
    
    // if Apr, June, Sept, Nov
    if (selectBox.selectedIndex == 4 || selectBox.selectedIndex == 6 ||
        selectBox.selectedIndex == 9 || selectBox.selectedIndex == 11)
    {     
        //If old length was less than 30, add the option value for the 30th day
        if (oldLength == 30)
        {
            var optionObj = document.createElement("OPTION");
            optionObj.text = "30";
            optionObj.value = "30";
            daysObj.options.add(optionObj);
        }
        //Else, simply limit the size of the selectBox to 30
        else
            daysObj.length = 31; //Including space at top 
    }
    // if Feb
    else if (selectBox.selectedIndex == 2)
    {
        //Simply limit the size to 29 days
        daysObj.length = 30; //Including space at top and leap year
    }
    else
    {
        //If old length was less than 30, add the option value for the 30th day
        if (oldLength == 30)
        {
            var optionObj = document.createElement("OPTION");
            optionObj.text = "30";
            optionObj.value = "30";
            daysObj.options.add(optionObj);
            
            //and another
            var optionObj2 = document.createElement("OPTION");
            optionObj2.text = "31";
            optionObj2.value = "31";
            daysObj.options.add(optionObj2);
        }
        //If old length was less than 31, add the option value for the 31st day
        else if (oldLength == 31)
        {
            var optionObj = document.createElement("OPTION");
            optionObj.text = "31";
            optionObj.value = "31";
            daysObj.options.add(optionObj);
        }
    }
}

function passwordCheck(passwordText)
{
    var proposedPassword = new String(passwordText);
    if (passwordText.length < 6 || passwordText.length > 16)
        return false;
            
     //if space is at the beginning or the end
     if ((proposedPassword.indexOf(" ") == 0) || (proposedPassword.lastIndexOf(" ") == (proposedPassword.length -1)))
        return false;
           
     // the word "password" not allowed 
     if (proposedPassword.toLowerCase() == "password")
        return false;
            
     var pswPrefix   = proposedPassword.substr(0,4);
     var emailPrefix = document.getElementById("emailAdd").value.substr(0,4);
     if (pswPrefix == emailPrefix)
        return false;
    
      //If past all these, return true
      return true;
}

function clearField(textbox,initialValue)
{
    var value = textbox.value;
    if (value == initialValue)
    {
        textbox.value = "";
    }
}