﻿var CountryBuilder = function (geoInfoModel, ddlCountry, ddlState) {
    this.$ddlState = ddlState,
    this.$ddlCountry = ddlCountry,
    this.geoInfo = geoInfoModel;

    this.bindCountry = function ($hdnCountry, $hdnState) {

        var $ddlState = this.$ddlState;
        var $ddlCountry = this.$ddlCountry;
        var geoInfo = this.geoInfo;
        if ($hdnCountry == undefined) {
            $hdnCountry = $('<input type="hidden" />');
        }
        if ($hdnState == undefined) {
            $hdnState = $('<input type="hidden" />');
        }

        $ddlCountry.children().remove();

        for (var j = 0; j < geoInfo.length; j++) {
            $ddlCountry.append('<option value="' + geoInfo[j].Id + '">' + geoInfo[j].Name + '</option>');
        }

        setDropDownValue($hdnCountry, $ddlCountry);

        $ddlState.parents('.row').hide();

        $ddlCountry.change(function () {
            var selectedCountryId = $(this).val();
            if ($hdnCountry != undefined) {
                $hdnCountry.val(selectedCountryId);
            }

            $ddlState.children().remove();

            var haveStates = false;
            for (var i = 0; i < geoInfo.length; i++) {

                if (geoInfo[i].Id != selectedCountryId) {
                    continue;
                }

                for (var k = 0; k < geoInfo[i].States.length; k++) {
                    haveStates = true;
                    $ddlState.append('<option value="' + geoInfo[i].States[k].Id + '">' + geoInfo[i].States[k].Name + '</option>');
                }
                break;
            }

            if (haveStates) {
                $ddlState.parents('.row').show();
                setDropDownValue($hdnState, $ddlState);
            }
            else {
                $ddlState.parents('.row').hide();
                $hdnState.val('');
            }
        });

        $ddlState.change(function () {
            var selectedStateId = $(this).val();
            $hdnState.val(selectedStateId);
        });

        $ddlCountry.change();
    };

    function setDropDownValue($hiddenField, $dropDown) {
        var id;
        var hiddenId = $hiddenField.val();
        if (hiddenId == "" || hiddenId == "-1" || hiddenId == "0") {
            id = $dropDown.first().val();
        }
        else {
            id = hiddenId;
        }
        $dropDown.val(id);
    }
};
