﻿$jq.namespace('MatchCore');

MatchCore.RegistrationLocation = function() {
    var container;

    var loadingOption = { value: '', text: 'Loading...' };
    var countriesWithPostalCodes = [1, 2, 224];
    var service = new MatchCore.ServiceProxy(MatchCore.Application.resolveUrl('~/rest/MainService.ashx'));

    var ddlCountry;
    var ddlState;
    var ddlCity;
    var txtPostal;
    var ddlCityForPostal;

    var divPostalPane;
    var divCountryPane;
    var divStatePane;
    var divCityPane;
    var divCityForPostalPane;

    var SelectedCountryCode = -1;
    var SelectedStateCode = -1;
    var SelectedCityCode = -1;
    var SelectedCityCodeForPostal = -1;
    var SelectedPostalCode = '';
    var showErrors = true;

    var countriesJSON;
    var statesJSON;
    var citiesJSON;
    var citiesForPostalJSON;

    var includeNoAnswer = {
        forCountry: false,
        forCity: false,
        forState: false,
        forCityInPostal: false,
        CountryNoAnswer: "",
        StateNoAnswer: "",
        CityNoAnswer: "",
        CityInPostalNoAnswer: ""
    };





    //Functions to get values from dropdownlists
    var get_SelectedCountryCode = function() {
        var selectedCountry = $jq("option:selected", ddlCountry).val();

        if (selectedCountry == null) {
            selectedCountry = $jq("option", ddlCountry).val();
        }

        return selectedCountry;
    };

    var get_SelectedStateCode = function() {
        var selectedState = $jq("option:selected", ddlState).val();

        if (selectedState == null) {
            selectedState = $jq("option", ddlState).val();
        }

        return selectedState;
    };

    var get_SelectedCityCode = function() {
    };

    var get_SelectedCityCodeForPostal = function() {
    };

    var deactivateStatePane = function() {
        SelectedStateCode = -1;
        $jq(divStatePane).hide();
        $jq(ddlState).clearOptions();
    };

    var deactivateCityPane = function() {
        SelectedCityCode = -1;
        $jq(divCityPane).hide();
        $jq(ddlCity).clearOptions();
    };

    var deactivateCityForPostalPane = function() {
        SelectedCityCodeForPostal = -1;
        $jq(divCityForPostalPane).hide();
        $jq(ddlCity).clearOptions();
    };

    var deactivatePostalPane = function() {
        SelectedPostalCode = '';
        $jq(divPostalPane).hide();
        $jq(txtPostal).val('');
        deactivateCityForPostalPane();
    };

    var ToggleVisibility = function() {
        if (txtPostal) {
            if (CountryIsPostal()) {
                $jq(divPostalPane).show();
                $jq(divStatePane).hide();
                $jq(divCityPane).hide();
            }
            else {
                $jq(divPostalPane).hide();
                $jq(divStatePane).hide();
                $jq(divCityPane).hide();
            }
        }
    };

    var CountryIsPostal = function() {
        var countryCode = get_SelectedCountryCode();
        var showPostal = false;

        for (i = 0; i < countriesWithPostalCodes.length; i++) {
            if (countriesWithPostalCodes[i].toString() == countryCode.toString()) {
                showPostal = true;
                break;
            }
        }

        return showPostal;
    };

    //Gets for JSON objects
    var findCountry = function(code) {
        var SelectedCountry;
        $jq("option", ddlCountry).each(function() {
            if (code == $jq(this).val()) {
                SelectedCountry = { value: $jq(this).val(), HasStates: eval($jq(this).attr('hasStates')), HasCities: eval($jq(this).attr('hasCities')), text: $jq(this).attr('text') };
            }
        });

        return SelectedCountry;
    };

    var findState = function(code) {
        for (var i = 0; i < statesJSON.length; i++) {
            if (statesJSON[i].Code == code)
                return statesJSON[i];
        }

        return null;
    };


    //Country Calls and handler
    var ajax_FillCountryList = function() {
        if (ddlCountry)
            service.invoke({
                method: 'GetAllCountries',
                success: handle_FillCountryList
            });
    };

    var handle_FillCountryList = function(response) {
        $jq(ddlCountry).clearOptions();

        //Fill Country list
        //Based on selected country, toggle postal field visibility
        //Based on Selected Country, fill state list

        if (response[0]) {
            countriesJSON = response;

            if (includeNoAnswer.forCountry) {
                ddlCountry.addOption(
					{ value: -1, text: includeNoAnswer.CountryNoAnswer, selected: (SelectedCountryCode == -1) }
				);
            }

            for (var i = 0; i < response.length; i++) {
                $jq(ddlCountry).addOption(
					{ value: response[i].Code, text: response[i].Name, selected: (response[i].Code.toString() == SelectedCountryCode.toString()) }
				);
            }

            //Fix for IE6
            $jq(ddlCountry).val(SelectedCountryCode);

            ToggleVisibility();

            ajax_FillStateList();


        }
    };

    //State Calls and handler
    var ajax_FillStateList = function() {
        if (ddlState) {
            $jq(ddlState).clearOptions();
            $jq(ddlState).addOption(loadingOption);

            $jq(ddlCity).clearOptions();
            $jq(ddlCity).addOption(loadingOption);

            var countryCode = get_SelectedCountryCode();

            var currentCountry = findCountry(countryCode);

            if (currentCountry != null) {
                if (!CountryIsPostal()) {
                    if (currentCountry.HasStates) {
                        $jq(ddlState).parents('.statePane').show();

                        service.invoke({
                            method: 'GetStatesByCountryCode',
                            data: {
                                'countryCode': countryCode
                            },
                            success: handler_FillStateList,
                            failure: handler_FillStateListFailure
                        });
                    }
                    else {
                        $jq('.statePane', container).hide();

                        ajax_FillCityListByCountry();
                    }
                }
                else {
                    ToggleVisibility();
                    $jq(txtPostal).val(SelectedPostalCode);
                    postalCode_changed();
                }
            }
            else {
                deactivateCityForPostalPane();
                deactivateCityPane();
                deactivatePostalPane();
                deactivateStatePane();
            }
        }
    };

    var handler_FillStateListFailure = function() {
        deactivateStatePane();
        deactivateCityPane();
        deactivateCityForPostalPane();
        deactivatePostalPane();
        if (showErrors)
            alert("Unable to load states.  Please try again later.");
    }

    var handler_FillStateList = function(response) {
        $jq(ddlState).clearOptions();

        if (response[0].Code) {
            statesJSON = response;

            if (includeNoAnswer.forState) {
                $jq(ddlState).addOption(
					    { value: -1, text: includeNoAnswer.StateNoAnswer, selected: (SelectedStateCode == -1) }
				    );
            }

            for (var i = 0; i < response.length; i++) {
                $jq(ddlState).addOption(
					    { value: response[i].Code, text: response[i].Name, selected: (response[i].Code.toString() == SelectedStateCode.toString()) }
				    );
            }

            //Fix for IE6
            $jq(ddlState).val(SelectedStateCode);

            ajax_FillCityListByState();
        }
        else {
            if (showErrors)
                alert('Error loading states');
        }
    };

    //City call and handler
    var ajax_FillCityListByCountry = function() {
        if (ddlCity) {
            var countryCode = $jq('option:selected', ddlCountry).val();

            var countryCode = get_SelectedCountryCode();
            var currentCountry = findCountry(countryCode);

            if (currentCountry != null) {
                $jq(divCityPane).show();

                service.invoke({
                    method: 'GetCitiesByCountryCode',
                    data: {
                        'countryCode': countryCode
                    },
                    success: handle_FillCityList,
                    failure: handle_FillCityListByCountryFailure
                });
            }
            else {
                deactivateCityPane();
            }
        }
    };

    var handle_FillCityListByCountryFailure = function() {
        deactivateCityForPostalPane();
        deactivateCityPane();
        deactivateStatePane();
        deactivatePostalPane();
        if (showErrors)
            alert('Unable to load cities.  Please try again later.')
    };

    var ajax_FillCityListByState = function() {
        if (ddlCity) {
            $jq(ddlCity).clearOptions();
            $jq(ddlCity).addOption(loadingOption);

            var countryCode = get_SelectedCountryCode();
            var selectedCountry = findCountry(countryCode);

            var stateCode = get_SelectedStateCode();
            var selectedState = findState(stateCode);

            if (selectedCountry != null && selectedState != null) {
                $jq(divCityPane).show();

                service.invoke({
                    method: 'GetCitiesByStateCodeAndCountryCode',
                    data: {
                        'stateCode': stateCode,
                        'countryCode': countryCode
                    },
                    success: handle_FillCityList,
                    failure: handle_FillCityListByStateFailure
                });
            }
            else {
                deactivateCityPane();
            }
        }
    };

    var handle_FillCityListByStateFailure = function() {
        deactivateCityForPostalPane();
        deactivateCityPane();
        deactivatePostalPane();
        if (showErrors)
            alert('Unable to load cities.  Please try again later.');
    };

    var handle_FillCityList = function(response) {
        $jq(ddlCity).clearOptions();

        if (includeNoAnswer.forCity) {
            $jq(ddlCity).addOption(
				{ value: -1, text: includeNoAnswer.CityNoAnswer, selected: (SelectedCityCode == -1) }
			);
        }

        for (var i = 0; i < response.length; i++) {
            $jq(ddlCity).addOption(
				{ value: response[i].Code, text: response[i].Name, selected: (SelectedCityCode == response[i].Code) }
			);
        }

        //Fix for IE6
        $jq(ddlCity).val(SelectedCityCode);
    };

    //Cities for postal call and handler
    var handler_FillCityForPostalList = function(response) {
        if (response[0]) {
            if (response.length > 1) {

                $jq(ddlCityForPostal).clearOptions();


                if (includeNoAnswer.forCityInPostal) {
                    $jq(ddlCityForPostal).addOption(
				        { value: -1, text: includeNoAnswer.CityInPostalNoAnswer, selected: (SelectedCityCodeForPostal == -1) }
			        );
                }

                for (var i = 0; i < response.length; i++) {
                    $jq(ddlCityForPostal).addOption(
				        { value: response[i].Code, text: response[i].Name, selected: (SelectedCityCodeForPostal == response[i].Code) }
			        );
                }

                //Fix for IE6
                $jq(ddlCityForPostal).val(SelectedCityCodeForPostal);

                $jq(divCityForPostalPane).show();
            }
            else {
                $jq(divCityForPostalPane).hide();
            }
        }
        else {
            $jq(divCityForPostalPane).hide();
        }
    };







    //Selection changed handlers for dropdowns
    var country_changed = function() {
        deactivateStatePane();
        deactivateCityPane();
        deactivatePostalPane();

        ToggleVisibility();

        ajax_FillStateList();

    };

    var state_changed = function() {
        deactivateCityPane();
        deactivatePostalPane();

        ToggleVisibility();
        $jq(divStatePane).show();

        ajax_FillCityListByState();
    };

    var postalCode_changed = function() {
        if (get_SelectedCountryCode() == 1) {
            selectedPostalCode = $jq(txtPostal).val();
            if (selectedPostalCode.length == 5) {
                service.invoke({
                    method: 'GetCitiesForPostalCode',
                    data: {
                        postalCode: selectedPostalCode
                    },
                    success: handler_FillCityForPostalList
                });
            }
            else {
                $jq(divCityForPostalPane).hide();
                $jq(ddlCityForPostal).clearOptions;
            }
        }
    };











    var self = {
        init: function(opts) {
            var config = opts.meta;
            container = opts.container;

            ddlCountry = (config.countryList != undefined) ? $jq(config.countryList) : $jq('.ddlCountries', container).get(0);
            ddlState = (config.stateList != undefined) ? $jq(config.stateList) : $jq('.ddlStates', container).get(0);
            ddlCity = (config.cityList != undefined) ? $jq(config.cityList) : $jq('.ddlCity', container).get(0);
            ddlCityForPostal = (config.cityForPostalList != undefined) ? $jq(config.cityForPostalList) : $jq('.ddlCitiesForPostal', container);
            txtPostal = (config.postalField != undefined) ? $jq(config.postalField) : $jq('.txtPostal', container);

            divCityForPostalPane = $jq('.cityForPostalPane', container);
            divCityPane = $jq('.cityPane', container);
            divCountryPane = $jq('.countryPane', container);
            divPostalPane = $jq('.postalPane', container);
            divStatePane = $jq('.statePane', container);




            if (config.selectedCountryCode)
                SelectedCountryCode = config.selectedCountryCode;

            if (config.selectedCityCode)
                SelectedCityCode = config.selectedCityCode;

            if (config.selectedStateCode)
                SelectedStateCode = config.selectedStateCode;

            if (config.selectedCityCodeForPostal)
                SelectedCityCodeForPostal = config.selectedCityCodeForPostal;

            if (config.selectedPostalCode)
                SelectedPostalCode = config.selectedPostalCode

            if (config.includeNoAnswer)
                includeNoAnswer = config.includeNoAnswer;

            if (config.showErrors != undefined)
                showErrors = config.showErrors;

            //wireup event handlers
            $jq(ddlCountry).change(country_changed);
            $jq(ddlState).change(state_changed);
            $jq(txtPostal).keyup(postalCode_changed);

            $jq(document).ready(function() {
                $jq(ddlCountry).val(SelectedCountryCode);
                ToggleVisibility();

                ajax_FillStateList();
            });
        }
    };





    return self;
};