/*
 @Name: $RCSfile: registrationBuyer.js,v $
 @Version: $Revision: 1.2 $
 @Date: $Date: 2009/12/16 17:37:02 $
 
 Copyright (C) 2007 Copart, Inc. All rights reserved.
 */
var line1 = "";
var line2 = "";
var country = "";
var state = "";
var city = "";
var zip1 = "";
var zip2 = "";
var blank = "";
emailValid = false;
email1Valid = false;
email2Valid = false;

/**
 Populate the State dropdown given (by id) with the
 state list for the country selected.
 
 This will also hide/show/change various other related fields.
 
 **/
//	Validation Options
//  Additional validation rules for the Buyer Registration form.
var validationOptions = {
    validGroups: 0,
    additionalValidationRules: [['validate-length-3', '', function(v){
        return (v.length != 3 && v != "") ? false : true;
    }
], ['validate-length-4', '', function(v){
        return (v.length != 4 && v != "") ? false : true;
    }
], ['validate-length-10', '', function(v){
        return (v.length != 10 && v != "") ? false : true;
    }
], ['validate-length-16', '', function(v){
        return (v.length != 16 && v != "") ? false : true;
    }
], ['validate-dealerLicense', '', function(v, elm){
        return validateLicenseGroup("dealerLicense", elm);
    }
], ['validate-businessLicense', '', function(v, elm){
        return validateLicenseGroup("businessLicense", elm);
    }
], ['validate-salesTaxLicense', '', function(v, elm){
        return validateLicenseGroup("salesTaxLicense", elm);
    }
], ['physical-zip-required-if-usa', '', function(v){
        return validateZipIfUSA(true, v);
    }
    
], ['mailing-zip-required-if-usa', '', function(v){
        return validateZipIfUSA(false, v);
    }
], ['physical-zip2-required-if-usa', '', function(v){
        return validateZip2IfUSA(true, v);
    }
], ['mailing-zip2-required-if-usa', '', function(v){
        return validateZip2IfUSA(false, v);
    }
]]
};

// Additional funciton run for each validation rule.
function runOnElementValidate(){
	if($("information-text") != null && $("information-text") !== undefined)
	{
		if ($("information-text").visible()) {
			$("information-text").hide();
		}
	}
}


function validateLicenseGroup(group, elm, standAlone){

    var standAlone = standAlone || false;
    var validateGroup = false;
    var isValid = true;
    
    // If any of the fields are set, then validate the group.
    if ($F(group + ".number") != "" ||
    $F(group + ".country") != "" ||
    $F(group + ".state") != "") {
        validateGroup = true;
    }
    
    if (validateGroup &&
    $F(group + ".number") == "" &&
    Validation.getElmID(elm) == group + ".number") {
        isValid = false;
    }
    else 
        if (validateGroup &&
        $F(group + ".country") == "" &&
        Validation.getElmID(elm) == group + ".country") {
            isValid = false;
        }
        else 
            if (validateGroup &&
            $F(group + ".state") == "" &&
            Validation.getElmID(elm).indexOf(group + ".state") != -1) {
                isValid = false;
            }
    
    if (validateGroup && isValid && !standAlone) {
        validationOptions.validGroups++;
    }
    
    return isValid
}

function onCountryChange(countryDropdownId, stateDropdownId, state){

    var selectedCountry = $F(countryDropdownId);
    var setState = state ? state : "";
    
    var requestURL = "stateCountry.ajax";
    var requestParameters = $H({
        country: selectedCountry
    });
    
    var stateDropdownContainerId = stateDropdownId + "-container";
    var stateNameContainerId = stateDropdownId + "-name-container";
    
    var addressPrefixes = ['physicalAddress.', 'mailingAddress.'];
    
    var prefix = countryDropdownId.substring(0, countryDropdownId.indexOf("country"));
    
    var contactPhoneId = "contactPhone";
    
    var stateCodeDisplay = "";
    
    var xmlDoc;
    var nodeCounter = 0;
    
    if (selectedCountry != "") {
    
        // Perform an AJAX request to fill the States for the given Country.
        new Ajax.Request(requestURL, {
            method: "get",
            parameters: requestParameters,
            onComplete: function(transport){
                xmlDoc = returnXMLDocument(transport.responseText);
                nodeCounter = xmlDoc.getElementsByTagName("state").length;
                
                if (nodeCounter > 0) {
                    $(stateDropdownId + "-dropdown").options.length = 0;
                    $(stateDropdownId + "-dropdown").options[0] = new Option(message.selectAState, '');
                    for (var i = 0; i < nodeCounter; i++) {
                        var desc = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("description").value;
                        var code = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("code").value;
                        var stateCodeDisplay = "";
                        
                        if (selectedCountry != "USA") {
                            stateCodeDisplay = " (" + code + ")";
                        }
                        
                        var newOption = new Option(desc + stateCodeDisplay, code);
                        $(stateDropdownId + "-dropdown").options[i + 1] = newOption;
                        
                        if (($(stateDropdownId + "-dropdown").options[i + 1].value == setState) && setState != "") {
                            $(stateDropdownId + "-dropdown").options.selectedIndex = i + 1;
                        }
                        
                    }
                }
                
            },
            onFailure: function(){
            }
        });
        
        if (addressPrefixes.include(prefix)) {
            if (selectedCountry == "USA") {
                if (prefix == "physicalAddress.") {
                    $("contactPhone-USA-container").show();
                    $("contactPhone-container").hide();
                    $("altPhone-USA-container").show();
                    $("altPhone-container").hide();
                }
                $(prefix + "zip.zip2").show();
                $(prefix + "zip.zip1").setAttribute('size', 5);
                $(prefix + "zip.zip1").setAttribute('maxlength', 5);
                $(prefix + "zip.zip2").setAttribute('size', 4);
                $(prefix + "zip.zip2").setAttribute('maxlength', 4);
            }
            else 
                if (selectedCountry == "CAN") {
                    $(prefix + "zip.zip2").show();
                    $(prefix + "zip.zip1").setAttribute('size', 3);
                    $(prefix + "zip.zip1").setAttribute('maxlength', 3);
                    $(prefix + "zip.zip2").setAttribute('size', 3);
                    $(prefix + "zip.zip2").setAttribute('maxlength', 3);
                    
                    if (setState == "") {
                        $(prefix + "zip.zip1").value = "";
                        $(prefix + "zip.zip2").value = "";
                    }
                    if (prefix == "physicalAddress.") {
                        $("contactPhone-USA-container").hide();
                        $("contactPhone-container").show();
                        $("altPhone-USA-container").hide();
                        $("altPhone-container").show();
                    }
                }
                else {
                    if (prefix == "physicalAddress.") {
                        $("contactPhone-USA-container").hide();
                        $("contactPhone-container").show();
                        $("altPhone-USA-container").hide();
                        $("altPhone-container").show();
                    }
                    
                    $(prefix + "zip.zip2").hide();
                    $(prefix + "zip.zip1").setAttribute('size', 5);
                    $(prefix + "zip.zip1").setAttribute('maxlength', 5);
                    $(prefix + "zip.zip2").setAttribute('size', 4);
                    $(prefix + "zip.zip2").setAttribute('maxlength', 4);
                }
        }
    }
    else {
        $(stateDropdownId + "-dropdown").options.length = 0;
        var newOption = new Option(message.selectAState, "");
        $(stateDropdownId + "-dropdown").options[0] = newOption;
    }
}

/**
 Submit the buyer registraiton form.
 **/
function validateBuyerRegistration(formName, valid, pg){

    // clear out error mesages
    $("errorDiv").innerHTML = "";
    Validation.removeErrorMessage('CCExpirationDate');
    Validation.removeErrorMessage('emailNotMatch');
    Validation.removeErrorMessage('email1NotValid');
    Validation.removeErrorMessage('email2NotValid');
    
    if (pg == 0) {
		if($F("email") != $F("emailConfirm"))
        {
            emailValid = false;
            Validation.addErrorMessage('emailNotMatch', $('advice-common-before'), message.errorMatchEmails, {
                    focusTo: "",
                    linkTo: ""
            });
        }
        else
        {
            var email1IsValid = checkEmail($("email"), message.errorInvalidEmail, null);
            var email2IsValid = checkEmail($("emailConfirm"), message.errorInvalidEmail2, null);
            
            if(!email1IsValid)
            {
                Validation.addErrorMessage('email1NotValid', $('advice-common-before'), message.errorInvalidEmail, {
                    focusTo: "",
                    linkTo: ""
                });
            }
            
            if(!email2IsValid)
            {
                Validation.addErrorMessage('email2NotValid', $('advice-common-before'), message.errorInvalidEmail2, {
                    focusTo: "",
                    linkTo: ""
                });
            }
            
            if(email1IsValid && email2IsValid)
            {
                emailValid = true;
            }
            else
            {
                emailValid = false;
            }
        }
        if ($F("physicalAddress.country") != "USA") {
            var contactPhoneText = $F("contactPhoneText");
            $("contactPhone.areaCode").value = contactPhoneText.substring(0, 3);
            $("contactPhone.prefix").value = contactPhoneText.substring(3, 6);
            $("contactPhone.line").value = contactPhoneText.substring(6, 10);
            
            var altPhoneText = $F("altPhoneText");
            $("altPhone.areaCode").value = altPhoneText.substring(0, 3);
            $("altPhone.prefix").value = altPhoneText.substring(3, 6);
            $("altPhone.line").value = altPhoneText.substring(6, 10);
            $("contactPhone.extension").value = "";
        }
        $("_eventId").value = "validateRegistrationInformation";
        
        Validation.removeErrorMessage('licenseGroups');
        Validation.removeErrorMessage('CCExpirationDate');
        
        valid.reset();
        validationOptions.validGroups = 0;
        
        var isValid = valid.validate();
        if (!emailValid) {
            isValid = false;
        }
    }
    else 
	{
        valid.reset();
        var isValid = valid.validate();
        if (!$("creditCard.number").disabled) {
            if ($F("creditCard.expirationYear") == "" || $F("creditCard.expirationMonth") == "") {
                Validation.addErrorMessage('CCExpirationDate', $('advice-common-before'), message.errorCreditCardDate, {
                    focusTo: "",
                    linkTo: ""
                });
                isValid = false;
            }
        }
    }
    if (isValid) {
        $(formName).submit();
    }
}

function editReg(formName){
    $("_eventId").value = "editBuyerRegistration";
    $(formName).submit();
}


// Toggle mailing address fields based on "Same As Physical" checkbox.
function toggleMailingAddress(){

    var disabled = false;
    
    if ($("mailingAddressSameAsPhysicalCheckbox").checked) {
        disabled = true;
    }
    else {
        disabled = false;
    }
    $("mailingAddressSameAsPhysical").value = disabled;
    $("mailingAddress.line1").disabled = disabled;
    $("mailingAddress.line2").disabled = disabled;
    $("mailingAddress.country").disabled = disabled;
    $("mailingAddress.state-field-dropdown").disabled = disabled;
    $("mailingAddress.city").disabled = disabled;
    $("mailingAddress.zip.zip1").disabled = disabled;
    $("mailingAddress.zip.zip2").disabled = disabled;
}

/**
 * This function is used when the user toggles Same As Physical.
 */
function toggleMailingAddressUser(){
    var disabled = $("mailingAddressSameAsPhysicalCheckbox").checked;
    if (disabled) {
        line1 = $F("mailingAddress.line1");
        line2 = $F("mailingAddress.line2");
        country = $F("mailingAddress.country");
        state = $F("mailingAddress.state-field-dropdown");
        city = $F("mailingAddress.city");
        zip1 = $F("mailingAddress.zip.zip1");
        zip2 = $F("mailingAddress.zip.zip2");
        
        $("mailingAddress.country").value = "";
        presetCountry("mailingAddress.country", "mailingAddress.state-field", "");
        $("mailingAddress.country").options[0].selected = true;
        $("mailingAddress.state-field-dropdown").options.length = 1;
        
        $("mailingAddress.line1").value = "";
        $("mailingAddress.line2").value = "";
        $("mailingAddress.city").value = "";
        $("mailingAddress.zip.zip1").value = "";
        $("mailingAddress.zip.zip2").value = "";
    }
    else {
        $("mailingAddress.country").value = country;
        onCountryChange("mailingAddress.country", "mailingAddress.state-field", state);
        $("mailingAddress.line1").value = line1;
        $("mailingAddress.line2").value = line2;
        $("mailingAddress.city").value = city;
        $("mailingAddress.zip.zip1").value = zip1;
        $("mailingAddress.zip.zip2").value = zip2;
        // $("mailingAddress.state-field-dropdown").value = state;
    }
    
    
    $("mailingAddressSameAsPhysical").value = disabled;
    $("mailingAddress.line1").disabled = disabled;
    $("mailingAddress.line2").disabled = disabled;
    $("mailingAddress.country").disabled = disabled;
    $("mailingAddress.state-field-dropdown").disabled = disabled;
    $("mailingAddress.city").disabled = disabled;
    $("mailingAddress.zip.zip1").disabled = disabled;
    $("mailingAddress.zip.zip2").disabled = disabled;
}


function setPaymentType(objClicked){
    if (objClicked == 1) {
        objClicked = $('payViaCreditCardRadio');
        $('payViaCreditCardRadio').checked = true;
    }
    else 
        if (objClicked == 0) {
            objClicked = $('payLaterRadio');
            $('payLaterRadio').checked = true;
        }
    
    var rad_val;
    var radioBtns = $("payViaCreditCardRadio", "payLaterRadio");
    for (var i = 0; i < radioBtns.length; i++) {
        if (radioBtns[i] != objClicked) {
            radioBtns[i].checked = false;
        }
        if (radioBtns[i].checked) {
            rad_val = radioBtns[i].value;
            
            if (rad_val == "payViaCreditCard") {
                $("payViaCreditCard").value = 1;
                $("creditCard.number").disabled = false;
                $("creditCard.expirationMonth").disabled = false;
                $("creditCard.expirationYear").disabled = false;
            }
            else {
                $("payViaCreditCard").value = 0;
                $("creditCard.number").disabled = true;
                $("creditCard.expirationMonth").disabled = true;
                $("creditCard.expirationYear").disabled = true;
            }
        }
        
    }
}

function updateRegistrationFee(){
    var newDate = new Date();
    if ($F('physicalAddress.country') != "") {
        if ($F('physicalAddress.country') == "CAN" && $F('physicalAddress.zip.zip2') != "") {
            regFeeAJAX();
        }
        if ($F('physicalAddress.country') != "CAN") {
            regFeeAJAX();
        }
    }
}

function regFeeAJAX(){

}

function updateStateValue(obj){
    var hiddenStateField = "";
    if (obj.name.indexOf("-dropdown") > -1) {
        hiddenStateField = obj.name.replace("-field-dropdown", "");
    }
    else {
        hiddenStateField = obj.name.replace("-field", "");
    }
    $(hiddenStateField).value = $F(obj);
}

function setOnFailureRegFee(){

}


function updatePhoneNumbersText(){
    if ($F("physicalAddress.country") != "USA") {
        $("contactPhoneText").value = $F("contactPhone.areaCode") + $F("contactPhone.prefix") + $F("contactPhone.line");
        $("altPhoneText").value = $F("altPhone.areaCode") + $F("altPhone.prefix") + $F("altPhone.line");
    }
}

/**
 * This function is called on load to preset the country and state dropdowns.
 * @param {Object} countryDropDown - the country dropdown to update
 * @param {Object} stateDropDown - state dropdown that has to be updated via ajax
 * @param {Object} initialValue - is the value of country when the page loads,
 *                 if initialValue is "" or null then we preset country and state
 *                 to the default value.
 */
function presetCountry(countryDropDown, stateDropDown, initialValue){
    if (initialValue == "" || initialValue == null) {
        $(countryDropDown).value = "USA";
        onCountryChange(countryDropDown, stateDropDown, '');
    }
}

/**
 * This function is used to validate the zip code if the selected country matches
 * the ones copart has denoted as being required for. At this time, the countries
 * that require a zip code are USA, CAN and MEX.
 * @param {Object} isPhysical
 * @param {Object} v
 */
function validateZipIfUSA(isPhysical, v){
    var countryDropDownName = isPhysical ? "physicalAddress.country" : "mailingAddress.country";
    switch ($F(countryDropDownName)) {
        case "USA":
            return /^\d{5}$/.test(v);
            break;
        case "CAN":
            return /^[a-z]\d[a-z]$/i.test(v);
            break;
        default:
            return true;
    }
}

/**
 * This function is used to validate the zip code if the selected country matches
 * the ones copart has denoted as being required for. At this time, the countries
 * that require a zip code are USA, CAN and MEX.
 * @param {Object} isPhysical
 * @param {Object} v
 */
function validateZip2IfUSA(isPhysical, v){
    var countryDropDownName = isPhysical ? "physicalAddress.country" : "mailingAddress.country";
    
    if (Validation.get('IsEmpty').test(v)) {
        return true;
    }
    switch ($F(countryDropDownName)) {
        case "USA":
            return /^\d{4}$/.test(v);
            break;
        case "CAN":
            return /^\d[a-z]\d$/i.test(v);
            break;
        default:
            return true;
    }
}

function getKeyCode(eventObj){
    if (window.event) // IE
    {
        return eventObj.keyCode;
    }
    else 
        if (eventObj.which) // Netscape/Firefox/Opera
        {
            return eventObj.which;
        }
}

function checkSize(fieldValue, refCountry, eventObj, isPlus4){
    var maxSize = 5;
    if (isPlus4) {
        if ($F(refCountry + ".country") == "CAN") {
            maxSize = 3;
        }
        else {
            maxSize = 4;
        }
        
    }
    else {
        if ($F(refCountry + ".country") == "CAN") {
            maxSize = 3;
        }
        else {
            maxSize = 5;
        }
    }
    var charIn = String.fromCharCode(getKeyCode(eventObj));
    if (String.fromCharCode(getKeyCode(eventObj)) >= " ") {
        if (fieldValue.length > (maxSize - 1)) {
            return false;
        }
    }
    return true;
}

/**
 *	All the functions below are for Promo Lead
 */
function submitPromoLead(formName){
    if (validateForm()) {
        $(formName).action = "registrationPromoLead.html";
        $(formName).submit();
    }
    return false;
    
}

function validateForm(){
    var errorMsg = "";
    //if only one of email, fname or lname are entered then check if other 2 are entered. 
    if (trimWS($("email").value) != "" || trimWS($("lastName").value) != "" || trimWS($("firstName").value) != "") {
        if (trimWS($("email").value) == "") {
            errorMsg += message.error_email_required + "<br>";
        }
        if (trimWS($("firstName").value) == "") {
            errorMsg += message.error_firstName_required + "<br>";
        }
        if (trimWS($("lastName").value) == "") {
            errorMsg += message.error_lastName_required + "<br>";
        }
    }
    //do all validations only if the 3 mandatory fields are entered, i.e fname,lastname,email
    if (trimWS($("email").value) != "" && trimWS($("lastName").value) != "" && trimWS($("firstName").value) != "") {
    
        if (trimWS($("company").value) != "" && !validateCompanyName(trimWS($("company").value))) {
            errorMsg += message.error_companyName_required + "<br>";
        }
        if (trimWS($("promoLeadPhone").value) != "" && isNaN($("promoLeadPhone").value)) {
            errorMsg += message.error_phone_required + "<br>";
        }
        if (trimWS($("physicalAddress.city").value) != "" && !validateName(trimWS($("physicalAddress.city").value))) {
            errorMsg += message.error_city_required + "<br>";
        }
        
        if (trimWS($("physicalAddress.state").value) != "" && !validateName(trimWS($("physicalAddress.state").value))) {
            errorMsg += message.error_state_required + "<br>";
        }
        if (trimWS($("physicalAddress.zip.zip1").value) != "" && $("physicalAddress.zip.zip1").value.length != 5) {
            errorMsg += message.error_zip_required + "<br>";
        }
        if (trimWS($("physicalAddress.country").value) != "" && !validateName(trimWS($("physicalAddress.country").value))) {
            errorMsg += message.error_country_required + "<br>";
        }
    }
    //validate the mandatory fields always.
    if (trimWS($("email").value) != "" && !validateSendEmail(trimWS($("email").value))) {
        errorMsg += message.error_email_required + "<br>";
    }
    if (trimWS($("firstName").value) != "" && !validateName(trimWS($("firstName").value))) {
        errorMsg += message.error_firstName_required + "<br>";
    }
    if (trimWS($("lastName")).value != "" && !validateName(trimWS($("lastName").value))) {
        errorMsg += message.error_lastName_required + "<br>";
    }
    
    if (errorMsg == "") {
        return true;
    }
    $("errorContent").innerHTML = errorMsg;
    return false;
}


function validateSendEmail(email){
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email);
}

function validateName(name){
    var reg = /^[a-zA-Z0-9 \.\'\-]+$/;
    return reg.test(name);
}


function validateCompanyName(name){
    var reg = /^[a-zA-Z0-9 \.\'\-#\!\$\?%:&@\,\*]+$/;
    return reg.test(name);
}

function submitNascar(){
    var email = $("email");
    var fname = $("firstName");
    var lname = $("lastName");
    var errorSpan = $("errorSpan");
    errorSpan.innerHTML = "";
    
    // We only require email, first name, or last name if 1 has text
    if (email.value != "" || fname.value != "" || lname.value != "") {
        checkEmail(email, message.error_email_required, "errorSpan");
        checkAlphaNumeric()
        
        if (trimWS($("firstName").value).length == 0) {
            if (errorSpan.innerHTML.length > 0) {
                errorSpan.innerHTML += "<br />"
            }
            errorSpan.innerHTML += message.error_firstName_required
        }
        
        if (trimWS($("lastName").value).length == 0) {
            if (errorSpan.innerHTML.length > 0) {
                errorSpan.innerHTML += "<br />"
            }
            errorSpan.innerHTML += message.error_lastName_required
        }
    }
    
    return (errorSpan.innerHTML.length == 0);
}

/* EMAIL Validation */

/**
 * This function will validate the user's email addresses. It will make an AJAX call
 * to verify that the entered email address is unique to Copart.
 *
 * @param emailField - user's email address
 * @param email2Field - confirmation email that must match emailField
 * @return N/A
 */
function isDuplicateEmail(emailField, email2Field){
    var email = $F(emailField);
    var email2 = $F(email2Field);
    var xmlDoc;
    var responseNode;
    var responseValue;
    if (email != "" && email2 != "") {
        Validation.removeErrorMessage('dupEmail');
        var isValid = checkEmail($(emailField), message.errorInvalidEmail, null);
        if ((email == email2) && isValid) {
            new Ajax.Request("emailChecker.ajax", {
                method: "get",
                parameters: "email=" + $F(emailField) + "&duplicateCheck=Y",
                onSuccess: function(transport){
                    xmlDoc = returnXMLDocument(transport.responseText);
                    if (navigator.appName.indexOf("Explorer") >= 0) {
                        responseNode = xmlDoc.childNodes[1].firstChild;
                    }
                    else {
                        responseNode = xmlDoc.firstChild.firstChild;
                    }
                    responseValue = responseNode.nodeValue;
                    setEmailValid(emailField, responseValue);
                },
                onFailure: function(transport){
                    emailValid = false;
                    Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorInvalidEmail, {
                        focusTo: emailField,
                        linkTo: ""
                    });
                }
            });
        }
        else {
            if (!isValid) {
                emailValid = false;
                Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorInvalidEmail, {
                    focusTo: emailField,
                    linkTo: ""
                });
            }
            else {
                emailValid = false;
                Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorMatchEmails, {
                    focusTo: emailField,
                    linkTo: ""
                });
            }
        }
    }
    else {
        emailValid = false;
        Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorMessageRequiredEmails, {
            focusTo: emailField,
            linkTo: ""
        });
    }
}

function setEmailValid(emailField, statusResponse){
    if (statusResponse == "duplicate") // Is duplicate email
    {
        emailValid = false;
        Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorDuplicateEmail, {
            focusTo: emailField,
            linkTo: ""
        });
    }
    else 
        if (statusResponse == "invalid") {
            emailValid = false;
            Validation.addErrorMessage('dupEmail', $('advice-common-before'), message.errorInvalidEmail, {
                focusTo: emailField,
                linkTo: ""
            });
        }
        else {
            Validation.removeErrorMessage('dupEmail');
            emailValid = true;
        }
}










function onCountryChange_HowToBuy(countryDropdownId, stateDropdownId, state){
    var selectedCountry = $F(countryDropdownId);
    var setState = state ? state : "";
    
    var requestURL = "stateCountry.ajax";
    var requestParameters = $H({
        country: selectedCountry
    });
    
    var stateCodeDisplay = "";
    
    var xmlDoc;
    var nodeCounter = 0;
    
    if (selectedCountry != "") {
    
        // Perform an AJAX request to fill the States for the given Country.
        new Ajax.Request(requestURL, {
            method: "get",
            parameters: requestParameters,
            onComplete: function(transport){
                xmlDoc = returnXMLDocument(transport.responseText);
                nodeCounter = xmlDoc.getElementsByTagName("state").length;
                
                if (nodeCounter > 0) {
                    $(stateDropdownId).options.length = 0;
					$(stateDropdownId).options[0] = new Option('Select a State/Province', '');
                    for (var i = 0; i < nodeCounter; i++) {
                        var desc = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("description").value;
                        var code = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("code").value;
                        var stateCodeDisplay = "";
                        
                        if (selectedCountry != "USA") {
                            stateCodeDisplay = " (" + code + ")";
                        }
                        var newOption = new Option(desc + stateCodeDisplay, code);
                        $(stateDropdownId).options[i + 1] = newOption;
                        
                        if (($(stateDropdownId).options[i + 1].value == setState) && setState != "") {
                            $(stateDropdownId).options.selectedIndex = i + 1;
                        }
                    }
                }
            },
            onFailure: function(){
            }
        });
    }
    else {
        $(stateDropdownId).options.length = 0;
        var newOption = new Option('Select a State/Province', '');
        $(stateDropdownId).options[0] = newOption;
    }
	
    if (selectedCountry == "USA" || selectedCountry == "CAN") {
		if ($('contactPhone-USA-container') != null && $('contactPhone-USA-container') !== undefined) {
			document.getElementById("contactPhone-USA-container").style.display = 'block';
		}
		if ($('contactPhone-container') != null && $('contactPhone-container') !== undefined) {
			document.getElementById("contactPhone-container").style.display = 'none';
		}
		// alt phone
		if ($('altPhone-USA-container') != null && $('altPhone-USA-container') !== undefined) {
			document.getElementById("altPhone-USA-container").style.display = 'block';
		}
		if ($('altPhone-container') != null && $('altPhone-container') !== undefined) {
			document.getElementById("altPhone-container").style.display = 'none';
		}
		
		//alert(document.getElementById("contactPhone-USA-container"));
		//alert(document.buyerRegForm.contactPhone-USA-container);
		
       // $("contactPhone-USA-container").show();
        //$("contactPhone-container").hide();
       // $("altPhone-USA-container").show();
       // $("altPhone-container").hide();
    } else {
		if ($('contactPhone-USA-container') != null && $('contactPhone-USA-container') !== undefined) {
			document.getElementById("contactPhone-USA-container").style.display = 'none';
		}
		if ($('contactPhone-container') != null && $('contactPhone-container') !== undefined) {
			document.getElementById("contactPhone-container").style.display = 'block';
		}
		//alt phone
		if ($('altPhone-USA-container') != null && $('altPhone-USA-container') !== undefined) {
			document.getElementById("altPhone-USA-container").style.display = 'none';
		}
		if ($('altPhone-container') != null && $('altPhone-container') !== undefined) {
			document.getElementById("altPhone-container").style.display = 'block';
		}
	}
}