/*
    Filename:   register.js
    Author:     Steve Smith stephen.smith@akqa.com
    Description:    Functions specific to the registration form
                    Has dependancies on MooTools library and common.js
                    Please ensure any updates maintain document's validity
                    Test validity at http://jslint.com/lint.html
*/

//Persistent object for the building of dealer locator queries
var dealerQuery = {         
    "dealerRegion": null,
    "dealerCountry": null,
    "dealerCity": null
};

//Set the country row label to city label if selected area was Italy
//This changes the meaning from the uers's point of view, without changing the functional behaviour
function setCountryRowLabel(dealerAreaValue) {
	var countryRowLabel = $E("#DealerCountryRow label");
	if (countryRowLabel) {
		if (dealerAreaValue == 4 && !countryRowLabel.getProperty("prev")) {
			//record previous value then replace with text from city row
			countryRowLabel.setProperty("prev", countryRowLabel.innerHTML);
			countryRowLabel.innerHTML = $E("#DealerCityRow label").innerHTML;
		} else if (countryRowLabel.getProperty("prev")) {
			//restore value
			countryRowLabel.innerHTML = countryRowLabel.getAttribute("prev");
			countryRowLabel.removeProperty("prev");
		}
	}
	
}

//Show the city row if region isn't Italy, otherwise hide it
function showDealerCityRow() {
	if (dealerQuery.dealerRegion == 4) {
		//hide the city row as it is redundant
		hideElementById("DealerCityRow");
	} else {
		//show the row
		showElementById("DealerCityRow");
	}
}

//Simulate user selecting the city if region is Italy ( field is hidden, so user can't select it manually)
function simulateDealerCityClick() {
	if (dealerQuery.dealerRegion == 4) {
		//get element that user would have clicked on
		var customSelectElement = $E("#DealerCityRow li a");
		//set its value to match the country value (Which is actually a city)
		dealerQuery.dealerCity = dealerQuery.dealerCountry;
		//set hidden input field
		$("HiddenPrefDealerCity").value = customSelectElement.rel.split("|")[1].trim();
		//simulate click on city element in order to load dealer data
		onDealerCityCustomDropDownChange(customSelectElement);
	}
}

//Focus cursor on specified element
function focusOnFirstInputElementInForm() {
    var formElement = $E("#FormContainer .firstTabPosition"); //get first element with 'firstTabPosition' class
    if(formElement) {
        formElement.focus();
    }
}

//Loops through and hides all exploded drop downs
function hideAllExplodedSelectContainers() {
    var collectionOfExplodedSelectContainers = $$(".explodedSelectContainer"); 
    for(var i = 0; i < collectionOfExplodedSelectContainers.length; i++) {
        collectionOfExplodedSelectContainers[i].getFirst().setStyle('display', 'none');
    }
}

//Tries to use displayElementWithTransition()
//from common.js, to display and element
//if it cant find displayElementWithTransition then
//just change display type with no transition
function attemptToDisplayElementWithTransition(elementId) {
    if(typeof(getElementStyle) != "function") {
        return false;
    }
    var elementStyle;
    elementStyle = getElementStyle(elementId, "display"); 
    if($(elementId) && elementStyle != "block") {
        if(typeof(displayElementWithTransition) == "function") {
            displayElementWithTransition(elementId, 'display', 'none', 250);
        }
        else {
            $(elementId).setStyle("display", "block");
        }
    }
}

//Passes items in an array to attemptToDisplayElementWithTransition()
function attemptToDisplayElementsWithTransition(elementIdCollection) {
    for(var i = 0; i < elementIdCollection.length; i++) {
        attemptToDisplayElementWithTransition(elementIdCollection[i]);
    }
}

//Iterates through a collection of element ids
//and adds a 'display:none' style to each
function hideEachElementInCollection(elementIdCollection) {
    for(var i = 0; i < elementIdCollection.length; i++) {
        if($(elementIdCollection[i])) {
            $(elementIdCollection[i]).setStyle("display", "none");
        }
    }
}

//Used by the dealer locator, this function
//clears the values from a specified drop down
//and its corresponding hidden input item
function clearValueFromNextDropDown(nextCollapsedSelectId, nextHiddenInputId, defaultValue) {
    if($(nextCollapsedSelectId)) {
        //set collapsed select as default
        $(nextCollapsedSelectId).setText(defaultValue);
    }
    if($(nextHiddenInputId)) {
        $(nextHiddenInputId).value = "";
    }
}

function hideElementById(elementId) {
    if($(elementId)) {
        $(elementId).addClass("hiddenQuestion");
    }
}

function showElementById(elementId) {
    if($(elementId)) {
        $(elementId).removeClass("hiddenQuestion");
    }
}

//Populates a dropdowns sibling (passed in within the rel attribute)
//with the content of a pipe and comma delimeted data set
function populateCustomResultDropDown(text, customSelectElement, targetExplodedElementId, targetCollapsedElementId, targetHiddenElementId) {
	var resultRow = text.split("#");
    var resultDropDown;
    var resultDropDownContent = "";
    var resultItems;
    var resultElementIdentifier;
    var customSelectElementRelItems = customSelectElement.rel.split("|");
    if(customSelectElementRelItems.length >= 8) {
        if($(customSelectElementRelItems[5].trim()) != typeof("undefined")) {
            resultDropDown = $(customSelectElementRelItems[5].trim());
            resultDropDown.empty();
            for(var i = 0; i < resultRow.length; i++) {
                //check that row contains correct data
                resultItems = resultRow[i].split("|");
                if(resultItems.length === 2) {
                    resultDropDownContent += "<li><a rel='" + customSelectElementRelItems[7].trim() + " | " + resultItems[0] + " | " + resultItems[1] + " | " + customSelectElementRelItems[6].trim() + " | " + customSelectElementRelItems[5].trim() + " | " + targetExplodedElementId + " | " + targetCollapsedElementId + " | " + targetHiddenElementId + " | ' href='#' title='" + resultItems[1] + "'>" + resultItems[1] + "</a></li>";
                }
            }
            resultDropDown.setHTML(resultDropDownContent);
            setUpCustomSelectorItems(customSelectElementRelItems[5].trim());
            hideAllExplodedSelectContainers();
        }
    }
    addEventsToNewElements(customSelectElementRelItems);
}

//Calls the getCountries service with region code
//passes result to populateResultDropDown()
//NB: depends on MooTools Ajax class
function onDealerRegionCustomDropDownChange(customSelectElement) {
	dealerQuery.dealerRegion = customSelectElement.rel.split("|")[1].trim();
    if(dealerQuery.dealerRegion) {
		var request = new Ajax('dealerLocator?method=getCountriesMap&areaCode=' + dealerQuery.dealerRegion, {
			method: 'get',
			onComplete: function(text) {
				populateCustomResultDropDown(text, customSelectElement, "ExplodedPrefDealerCity", "CollapsedPrefDealerCity", "HiddenPrefDealerCity");
				setCountryRowLabel(dealerQuery.dealerRegion);
				showElementById("DealerCountryRow");
			}
		}).request();
		if($("DefaultDropDownValue")) {
			clearValueFromNextDropDown("CollapsedPrefDealerCountry", "HiddenPrefDealerCountry", $("DefaultDropDownValue").value);
			hideElementById("DealerCountryRow");
			clearValueFromNextDropDown("CollapsedPrefDealerCity", "HiddenPrefDealerCity", $("DefaultDropDownValue").value);
			hideElementById("DealerCityRow");
			clearValueFromNextDropDown("CollapsedPrefDealerId", "HiddenPrefDealerId", $("DefaultDropDownValue").value);
			hideElementById("DealerIdRow");
		}
    }
}

//Calls the getCitiesMap service with country and region code
//passes result to populateResultDropDown()
//NB: depends on MooTools Ajax class
function onDealerCountryCustomDropDownChange(customSelectElement) {
	dealerQuery.dealerCountry = customSelectElement.rel.split("|")[1].trim();
    if(dealerQuery.dealerCountry) {
        var request = new Ajax('dealerLocator?method=getCitiesMap&areaCode=' + dealerQuery.dealerRegion + '&countryCode=' + dealerQuery.dealerCountry, {
            method: 'get',
            onComplete: function(text) {
                populateCustomResultDropDown(text, customSelectElement, "ExplodedPrefDealerId", "CollapsedPrefDealerId", "HiddenPrefDealerId");
                showDealerCityRow();
				simulateDealerCityClick.delay(100);
            }
        }).request();
        if($("DefaultDropDownValue")) {
            clearValueFromNextDropDown("CollapsedPrefDealerCity", "HiddenPrefDealerCity", $("DefaultDropDownValue").value);
            hideElementById("DealerCityRow");
            clearValueFromNextDropDown("CollapsedPrefDealerId", "HiddenPrefDealerId", $("DefaultDropDownValue").value);
            hideElementById("DealerIdRow");
        }            
    }
}

//Calls the getDealersMap service with city, country and region code
//passes result to populateResultDropDown()
//NB: depends on MooTools Ajax class
function onDealerCityCustomDropDownChange(customSelectElement) {
	dealerQuery.dealerCity = customSelectElement.rel.split("|")[1].trim();
    if(dealerQuery.dealerCity) {
		//explicity remeove city value if region is 4 (italy)
		//preventing exclusion of italian dealers
		if(dealerQuery.dealerRegion == "4") {
			dealerQuery.dealerCity = "";
		}
        var request = new Ajax('dealerLocator?method=getDealersMap&areaCode=' + dealerQuery.dealerRegion + '&countryCode=' + dealerQuery.dealerCountry + '&cityCode=' +  dealerQuery.dealerCity, {
            method: 'get',
            onComplete: function(text) {
                populateCustomResultDropDown(text, customSelectElement, "", "", "");
                showElementById("DealerIdRow");
            }
        }).request();
        if($("DefaultDropDownValue")) {
            clearValueFromNextDropDown("CollapsedPrefDealerId", "HiddenPrefDealerId", $("DefaultDropDownValue").value);
            hideElementById("DealerIdRow");
        }            
    }
}

//Checks occurence of values of elements in given collection of fields <fields>
//for matches to values in given collection of values <pivotalValues>
function hasPivotalValueBeenSelected(pivotalValues, fields) {
    for(var i = 0; i < fields.length; i++) {
        if($(fields[i])) {
            if(pivotalValues.contains($(fields[i]).getValue())) {
                return true;
            }
        }
    }
    return false;
    
}

//Returns true if any of the given fields
//have a value
function areFieldValuesEmpty(fields) {
    var returnValue = true;
    for(var i = 0; i < fields.length; i++) {
        if($(fields[i])) {
            if($(fields[i]).getValue() !== "") {
                returnValue =  false;
            }
        }
    }
    return returnValue;
}

//Handles the dynamic showing of relevant
//questions on the choice of manufacturer
function configureFieldsOnManufacturerCustomDropValue() {
    var pivotalManufacturers = ["75"]; //manufacturer code that, when chosen, cause dependant questions to be shown
    var questionsToBeShownOnPivotalManufacturer = ["WouldYouConsiderCalifornia"]; //ids of question containers that are dependant on pivotalManufacturers being chosen
    var questionsToBeShownOnOtherManufacturer = ["HaveYouOwnedAFerrari", "PossibleFerrariOwner"]; //ids of question containers shown if any manufacturer other than pivotalManufacturers is chosen
    var carManufacturerHiddenFields = ["HiddenUserCarManufacturer0", "HiddenUserCarManufacturer1", "HiddenUserCarManufacturer2"];
    if(hasPivotalValueBeenSelected(pivotalManufacturers, carManufacturerHiddenFields)) {
        //pivotal manufacturer chosen (in any visible drop down) so,
        //display questions identified in questionsToBeShownOnPivotalManufacturer
        //and hide questions identified in questionsToBeShownOnOtherManufacturer
        attemptToDisplayElementsWithTransition(questionsToBeShownOnPivotalManufacturer);
        hideEachElementInCollection(questionsToBeShownOnOtherManufacturer);
    }
    else if(!areFieldValuesEmpty(carManufacturerHiddenFields)){
        //other manufacturer chosen so,
        //display questions identified in questionsToBeShownOnOtherManufacturer
        //and hide questions identified in questionsToBeShownOnPivotalManufacturer
        attemptToDisplayElementsWithTransition(questionsToBeShownOnOtherManufacturer);
        hideEachElementInCollection(questionsToBeShownOnPivotalManufacturer);
    }
}

//Calls the getCars service with manufacturer code
//passes result to populateCustomResultDropDown()
//NB: depends on MooTools Ajax class and trim()
function onCarManufacturerCustomDropDownChange(customSelectElement) {
    var elementRelCollection = customSelectElement.rel.split("|");
    var elementValue = elementRelCollection[1].trim();
    
    if(elementValue) {
        //populate model drop down
        var request = new Ajax('getCars.htm?manufacturerCode=' + elementValue, {
            method: 'get',
            onComplete: function(text) {
                populateCustomResultDropDown(text, customSelectElement, "");
            }
        }).request();
        
        configureFieldsOnManufacturerCustomDropValue();
    }
}

//On postback, if a manufacturer is chosen
//then proceed to populate 2nd drop down
function handlePreSelectManufacturer(anchor) {
    var manufacturerAnchors;
    var chosenManufacturerAnchor;
    var elementRelCollection;
    if($(anchor.rel.split("|")[0].trim())) {
        if($(anchor.rel.split("|")[0].trim()).getValue() !== "") {
            //need to get the anchor of the value of the hidden input field
            manufacturerAnchors = $$("ul#" + anchor.rel.split("|")[4].trim() + " a");
            //need to get the anchor that corresponds to the chosen manufacturer
            for(var i = 0; i < manufacturerAnchors.length; i++) {
                if(manufacturerAnchors[i].rel.split("|")[1].trim() == $(anchor.rel.split("|")[0].trim()).getValue()) {
                    chosenManufacturerAnchor = manufacturerAnchors[i];
                }
            }
            if(chosenManufacturerAnchor) {
                onCustomSelectItemSelected(chosenManufacturerAnchor.rel);
                onCarManufacturerCustomDropDownChange(chosenManufacturerAnchor);
                        
                if($(chosenManufacturerAnchor.rel.split("|")[4].trim())) {
                    $(chosenManufacturerAnchor.rel.split("|")[4].trim()).setStyle("display", "none");
                }
            }
        }
    }
}

//Listens for and attachs functions to the click event
//on specified custom select items
//NB: reliant on onCustomSelectItemSelected in customSelectElement
function configureIndexChangeEventsForCustomDropDowns() {
    var collectionOfEventfulCustomDropDowns = $$("ul.populatesNextSibling");
    var collectionOfCustomDropDownAnchors;
    var stopEvent;
    if(typeof(onCustomSelectItemSelected) != "function") {
        return false;
    }
    for(var i = 0; i < collectionOfEventfulCustomDropDowns.length; i++) {
        //car manufacturer drop down
        if(collectionOfEventfulCustomDropDowns[i].hasClass("carManufacturers")) {
            collectionOfCustomDropDownAnchors = collectionOfEventfulCustomDropDowns[i].getElementsBySelector("a");
            for(var n = 0; n < collectionOfCustomDropDownAnchors.length; n++) {
                //add click listener
                collectionOfCustomDropDownAnchors[n].addEvent("click", function(evt){
                    stopEvent = new Event(evt).stop();
                    onCustomSelectItemSelected(this.rel);
                    onCarManufacturerCustomDropDownChange(this);
                    //clear drop down item and hidden item
                    elementRelCollection = this.rel.split("|");    
                    clearValueFromNextDropDown(elementRelCollection[6].trim(), elementRelCollection[7].trim(), $("CarModelDropDownValue").getValue());

                    if($(this.rel.split("|")[4].trim())) {
                        $(this.rel.split("|")[4].trim()).setStyle("display", "none");
                    }
                });
                //if value is true then populate next field (only for 1st car)
                if(n === 0) {
                    handlePreSelectManufacturer(collectionOfCustomDropDownAnchors[n]);
                }
            }
        }
        
        //dealer region drop down only - other dealer locator dropdowns are
        //given events after AJAX call
        if(collectionOfEventfulCustomDropDowns[i].hasClass("prefDealerArea")) {
            collectionOfCustomDropDownAnchors = collectionOfEventfulCustomDropDowns[i].getElementsBySelector("a");
            for(var m = 0; m < collectionOfCustomDropDownAnchors.length; m++) {
                collectionOfCustomDropDownAnchors[m].addEvent("click", function(){
					onDealerRegionCustomDropDownChange(this);
                    if($(this.rel.split("|")[4].trim())) {
                        $(this.rel.split("|")[4].trim()).setStyle("display", "none");
                    }
                });            
            }
        }
    }
}

//Attach events to new anchors
//created on response to AJAX call
function addEventsToNewElements(relItemCollection) {
    var anchorContainer = $(relItemCollection[5].trim());
    var anchors = anchorContainer.getElementsBySelector("a");
    for(var n = 0; n < anchors.length; n++) {
        if(relItemCollection[5].trim() == "ExplodedPrefDealerCountry") {
            anchors[n].addEvent("click", function(){
                onDealerCountryCustomDropDownChange(this);
                if($(relItemCollection[4].trim())) {
                    $(relItemCollection[4].trim()).setStyle("display", "none");
                }
            });            
        }
        else if(relItemCollection[5].trim() == "ExplodedPrefDealerCity") {
            anchors[n].addEvent("click", function(){
                onDealerCityCustomDropDownChange(this);
                if($(relItemCollection[4].trim())) {
                    $(relItemCollection[4].trim()).setStyle("display", "none");
                }
            });            
        }
    }

}

//Attach click events to questions that cause dependant questions to be
//shown or hidden depending on answer chosen
function configureInputsWithDependantElements() {
    var inputsWithDependantElementsCollection = $$("input.inputWithDependantElements");
    for(var i = 0; i < inputsWithDependantElementsCollection.length; i++) {
        if(inputsWithDependantElementsCollection[i].hasClass("haveYouOwnedAFerrari")) {
            //add click event
            inputsWithDependantElementsCollection[i].addEvent("click", function(){
                if(this.value == "true") {
                    attemptToDisplayElementsWithTransition(["PreviouslyOwnedFerrariModel", "PreviouslyOwnedFerrariYear"]);
                }
                else {
                    hideEachElementInCollection(["PreviouslyOwnedFerrariModel", "PreviouslyOwnedFerrariYear"]);
                }
            });   
            //if value is true then show appropriate question
            if(inputsWithDependantElementsCollection[i].getValue() === "true") {
                attemptToDisplayElementsWithTransition(["PreviouslyOwnedFerrariModel", "PreviouslyOwnedFerrariYear"]);
            }
        }
        if(inputsWithDependantElementsCollection[i].hasClass("dealerSpecified")) {
            inputsWithDependantElementsCollection[i].addEvent("click", function(){
                if(this.value == "true") {
					attemptToDisplayElementWithTransition("DealerLocatorContainer");
                }
                else {
                    hideEachElementInCollection(["DealerLocatorContainer"]);
                }
            });    

        }
    }
}

function addClickEventToRemoveButton(button) {
    var buttonRelCollection;
    var hiddenInputFieldIds;
    var hiddenInputFieldIdCollection = [];
    var collapsedSelectIds;
    var collapsedSelectIdCollection;
    var defaultTextCollection;
    button.addEvent("click", function(){ 
        buttonRelCollection = this.rel.split("|")
        hiddenInputFieldIds = buttonRelCollection[1];
        hiddenInputFieldIdCollection = hiddenInputFieldIds.split(",");
        collapsedSelectIds = buttonRelCollection[3];
        collapsedSelectIdCollection = collapsedSelectIds.split(",");
        for(var n = 0; n < hiddenInputFieldIdCollection.length; n++) {
            if($(hiddenInputFieldIdCollection[n].trim())) {
                //reset value for each hidden field
                $(hiddenInputFieldIdCollection[n].trim()).value = "";
            }
        }           
        for(var m = 0; m < collapsedSelectIdCollection.length; m++) {
            clearValueFromNextDropDown(collapsedSelectIdCollection[m].trim(), "", buttonRelCollection[4].split(",")[m]);
        }
		configureFieldsOnManufacturerCustomDropValue();

    });
}

//When user clicks 'remove' under the car
//choice, we need to clear the corresponding
//hidden input field and reset the drop down
function configureRemoveElementAnchors() {
    var hideElementAnchors = $$("a.hideElement");
    for(var i = 0; i < hideElementAnchors.length; i++) {
        hiddenInputFieldIds = hideElementAnchors[i].rel.split("|")[1];
        //check that 'remove button' has pipe delimeted data in its rel attribute
        if(hiddenInputFieldIds) {
            //split second item in pipe delimited list by commas - 
            //e.g. rel="question0 | HiddenUserCarManufacturer0, HiddenUserCar0, HiddenUserCarYear0"
            //becomes ["HiddenUserCarManufacturer0", "HiddenUserCar0", "HiddenUserCarYear0"] 
            hiddenInputFieldIdCollection = hiddenInputFieldIds.split(",");
            if(hiddenInputFieldIdCollection.length > 0) {
                addClickEventToRemoveButton(hideElementAnchors[i]);
            }                       
        }
    }
}

//On page load, after a postback (e.g. failed validation)
//we need to add events to dealer drop down items
//e.g. if user has selected a country, then we need to add
//events to the city items
function configureDealerLocatorDropDowns() {
    var dealerAreaValue;
    var dealerCountryValue;
    var dealerCityValue;
    var dealerIdValue;
    //check that hidden dealer elements exist
    //these elements contain the value that the 
    //user chose
    if($("HiddenPrefDealerArea") && 
        $("HiddenPrefDealerCountry") && 
        $("HiddenPrefDealerCity") && 
        $("HiddenPrefDealerId")) {
        dealerAreaValue = $("HiddenPrefDealerArea").getValue();
        dealerCountryValue = $("HiddenPrefDealerCountry").getValue();
        dealerCityValue = $("HiddenPrefDealerCity").getValue();
        dealerIdValue = $("HiddenPrefDealerId").getValue();
        if(dealerAreaValue != "") {
            //attach events to country
            //and show country drop down
            dealerQuery.dealerRegion = dealerAreaValue;
            addEventsToNewElements(["HiddenPrefDealerArea", dealerAreaValue, "", "CollapsedPrefDealerArea", "ExplodedPrefDealerArea", "ExplodedPrefDealerCountry", "CollapsedPrefDealerCountry", "HiddenPrefDealerCountry", ""]);
            setCountryRowLabel(dealerAreaValue);
			showElementById("DealerCountryRow");
        }
        if(dealerCountryValue != "") {
            //attach events to city
            //and show city drop down
            dealerQuery.dealerRegion = dealerAreaValue;
            dealerQuery.dealerCountry = dealerCountryValue;
            addEventsToNewElements(["HiddenPrefDealerCountry", dealerCountryValue, "", "CollapsedPrefDealerCountry", "ExplodedPrefDealerCountry", "ExplodedPrefDealerCity", "CollapsedPrefDealerCity", "HiddenPrefDealerCity", ""]);
            showDealerCityRow();
        }
        if(dealerCityValue != "") {
            //display dealer drop down
            showElementById("DealerIdRow");
        }
    }
}

//On postback we need to persist the view
//i.e. if the user has chosen 'home phone' from
//the drop down and then posted the form, the 
//home phone field needs to be shown on postback
function displayContactPreferenceField() {
    var hiddenPrefContactNumberInput = $("HiddenPrefContactNumber");
    if(hiddenPrefContactNumberInput) {
        if(hiddenPrefContactNumberInput.value == "home") {
            attemptToDisplayElementWithTransition("HomePhoneNumber");
        }
        else if(hiddenPrefContactNumberInput.value == "mobile") {
            attemptToDisplayElementWithTransition("MobilePhoneNumber");
        }
        else if(hiddenPrefContactNumberInput.value == "work") {
            attemptToDisplayElementWithTransition("WorkPhoneNumber");
        }
    }
}

//On click or enter key press, display
//the corresponding field
function onContactPreferenceSelect(event) {
	var theEvent = new Event(event);
	var prefContactNumberAnchorRelItems = this.rel.split("|");
    var collectionOfDependantQuestions = ["HomePhoneNumber", "MobilePhoneNumber", "WorkPhoneNumber"];
	
	if(theEvent.type == "click" || theEvent.key == "enter") {
		if(prefContactNumberAnchorRelItems[1].trim() == "home") {
		    hideEachElementInCollection(collectionOfDependantQuestions);
		    attemptToDisplayElementWithTransition(collectionOfDependantQuestions[0]);
		}
		else if(prefContactNumberAnchorRelItems[1].trim() == "mobile") {
		    hideEachElementInCollection(collectionOfDependantQuestions);
		    attemptToDisplayElementWithTransition(collectionOfDependantQuestions[1]);
		}
		else if(prefContactNumberAnchorRelItems[1].trim() == "work") {
		    hideEachElementInCollection(collectionOfDependantQuestions);
		    attemptToDisplayElementWithTransition(collectionOfDependantQuestions[2]);
		}
	}
}

//Add event to contact preferences drop down on step2
//the chosen contact type defines the field shown below
function configureContactPreferenceDropDowns() {
    var prefContactNumberAnchors = $$("#PrefContactNumberExplodedSelect a"); //get all of the anchors in the pref contact drop down
    var prefContactNumberAnchorRelItems;
    displayContactPreferenceField();
    if(prefContactNumberAnchors.length > 0) {
        for(var i = 0; i < prefContactNumberAnchors.length; i++) {
            prefContactNumberAnchors[i].addEvents({
				'click': function(event) {
					onContactPreferenceSelect.call(this, event);
				},
				'keydown': function(event) {
					onContactPreferenceSelect.call(this, event);
				}					
			});
        }       
    }
}

//Used to set up dynamic fields that correspond to the users choice on postback 
//(either either after failed validation, or when navigating back and forth through the steps)
//E.g. if the user selects Ferrari from the manufacturer drop down on step 3 then
//on page load we need to show the correct questions
//or when navigating back and forth through the steps)
function configureDynamicFields() {
    //execute on step 2 of the form
    if($$("form").filterByAttribute("name", "=", "step2").length > 0) {
        configureContactPreferenceDropDowns();
    }
    //execute on step 3 of the form
    if($$("form").filterByAttribute("name", "=", "step3").length > 0) {
        configureFieldsOnManufacturerCustomDropValue();
        configureDealerLocatorDropDowns();
    }
}


//Attaches functions onpageload
//NB: Used in place of DomReady due to SwfObject
//causing DOM irregularity
window.addEvent('load', function() {
    configureDynamicFields();
    configureInputsWithDependantElements();
    configureIndexChangeEventsForCustomDropDowns();
    configureRemoveElementAnchors();
    focusOnFirstInputElementInForm();
});
