﻿(function($) {
    $.fn.GetCountryDropdown = function() {
        var CountryInput = $(this);
        var NewCountryInput;
        $.getJSON("/AJAX/GetCountryList", { countryCode: CountryInput.val() }, function(data) {
            if (data != '') {
                NewCountryInput = $("<select>");
                $.each(data, function(i, optionData) {
                    if (optionData.Selected)
                        NewCountryInput.append($("<option selected value='" + optionData.Value + "'>" + optionData.Text + "</option>"));
                    else
                        NewCountryInput.append($("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>"));
                });
            } else {
                NewCountryInput = $("<input type='text'>").val(CountryInput.val());
            }
            CountryInput.replaceWith(NewCountryInput.attr("name", CountryInput.attr("name")).attr("id", CountryInput.attr("id")).attr("tabindex", CountryInput.attr("tabindex")));
        });
        return CountryInput;
    };

    $.fn.GetRegionDropdown = function(CountryCode) {
        var RegionInput = $(this);
        var NewRegionInput;
        $.getJSON("/AJAX/GetRegionList", { countryCode: CountryCode, regionCode: RegionInput.val() }, function(data) {
            if (data != '') {
                NewRegionInput = $("<select>");
                $.each(data, function(i, optionData) {
                    if (optionData.Selected)
                        NewRegionInput.append($("<option selected value='" + optionData.Value + "'>" + optionData.Text + "</option>"));
                    else
                        NewRegionInput.append($("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>"));
                });
            } else {
                NewRegionInput = $("<input type='text'>").val(RegionInput.val());
            }
            RegionInput.replaceWith(NewRegionInput.attr("name", RegionInput.attr("name")).attr("id", RegionInput.attr("id")).attr("tabindex", RegionInput.attr("tabindex")));
        });
        return RegionInput;
    };
})(jQuery);
