﻿jQuery.fn.dynamicStateControl = function(stateData, options, usAldValue, ukAldValue, stateRequiredCountries, provinceTranslation, stateTranslation, countyTranslation, isRequired) {
    var settings = jQuery.extend({
        countryControlId: null,
        selectOneText: "-- select one --",
        usAldValue: "US",
        ukAldValue: "UK",
        stateRequiredCountries: null,
        provinceTranslation: "Province",
        stateTranslation: "State",
        countyTranslation: "County",
        isRequired: "0"
    }, options);

    var textbox = jQuery(this);
    var doNotClear = false;

    // Hide the freeform text box
    textbox.hide();

    return this.each(function(index) {
        if (settings.countryControlId.length > 0) {
            var countryDropDown = $("#" + settings.countryControlId + " select");
        }

        var stateList = $("<select id='state" + index + "'><option>" + settings.selectCountry + "</option></select>");
        if (countryDropDown != null) {
            if (countryDropDown.length == 0) {
                populateState(stateList, settings.usAldValue);
            }
        }

        stateList.change(function() {
            textbox.val($(this).val());
        });
        textbox.after(stateList);

        if (countryDropDown != null) {
            countryDropDown.change(function() {
                var selected = $(this).val();
                var state = textbox.next("select");

                if (selected == settings.usAldValue || selected == "") {
                    $($(textbox).parent().find("label")[0]).html(settings.stateTranslation + "<span class='alert'>*</span>");
                }
                else if (selected == settings.ukAldValue) {
                    $($(textbox).parent().find("label")[0]).html(settings.countyTranslation + "<span class='alert'>*</span>");
                }
                else {
                    $($(textbox).parent().find("label")[0]).html(settings.provinceTranslation + "<span class='alert'>*</span>");
                }

                populateState(state, selected);

                // By default-- entering the state is not required.
                isRequired = false;
                // If there is no configuration key (or the configuration key is empty)
                // regarding which countries require state/province information, set
                // isRequired to true.
                if (settings.stateRequiredCountries.length < 1) {
                    isRequired = true;
                }
                else {
                    // Ensure that the country we have change to does not
                    // require State/Province information.  If it does,
                    // set the isRequired flag to TRUE.
                    n = 0
                    nTop = settings.stateRequiredCountries.length;
                    states = settings.stateRequiredCountries;
                    while (n < nTop) {
                        if (states[n] == selected) {
                            isRequired = true;
                        }
                        n = n + 1;
                    }
                }

                // We will always update the UI to show that the control
                // is not required unless it is at all a possibility that
                // the control be required.
                if (settings.isRequired == "1") {
                    // The control is set to be required, but unless the country is among the
                    // list of countries requiring state/country validation or the list of
                    // countries requiring validation is empty, we will not set the UI to indicate
                    // that the field is required.
                    //
                    // Actual validation is handled elsewhere using the same logic.
                    if (isRequired) {
                        setIsRequired(Labels, true);
                    }
                    else {
                        setIsRequired(Labels, false);
                    }
                }
                else {
                    setIsRequired(Labels, false);
                }
            });

            // Fire the OnChange event in case this field was prepopulated
            doNotClear = true;
            countryDropDown.change();
            doNotClear = false;
        } else {

            var state = textbox.next("select");
            populateState(state, settings.usAldValue); // Default to US states

        }

        // Set the value of the statelist drop down to match what the
        // actual control's value is.
        stateList.val(textbox.val());

        // Populate the state dropdown menu.
        function populateState(stateControl, selectedCountry) {
            // As long as not specified otherwise, reset textbox
            if (!doNotClear) {
                textbox.val("");
            }

            stateControl.empty().hide();
            if (selectedCountry != "") {
                var currentStateList = $.grep(stateData, function(s) {
                    return s.CountryValue == selectedCountry;
                });
            }
            else {
                var currentStateList = new Array();
            }

            stateControl.append("<option value=''>" + settings.selectOneText + "</option>").hide();
            // Find the various controls we will soon need.

            var stateControlParent = stateControl.parent();
            var DynamicSelect = stateControlParent.find("select")[0];
            var PrimaryInput = stateControlParent.find("input")[0];
            Labels = stateControlParent.find("label");  // Must be global (do _not_ add 'var' to the beginning of this statement)

            // Reset the value of the field
            modifyDisplay(DynamicSelect, false);
            modifyDisplay(PrimaryInput, true);
            modifyDisplay(Labels, true);

            if (currentStateList.length > 0) {
                for (var i = 0; i < currentStateList.length; i++) {
                    stateControl.append("<option value='" + currentStateList[i].AldValue + "'>" + currentStateList[i].DisplayName + "</option>");
                }
                modifyDisplay(DynamicSelect, true);
                modifyDisplay(PrimaryInput, false);
                modifyDisplay(Labels, true);
            }
        }

        function setIsRequired(Labels, yes) {
            if (yes) {
                $(Labels).find("span").show();
            }
            else {
                $(Labels).find("span").hide();
            }
        }

        function modifyDisplay(control, yes) {
            if (yes) {
                $(control).show();
            }
            else {
                $(control).show(); // IE is a streetwalker.
                $(control).hide();
            }
        }
    });
}
