﻿var LocationAutoComplete = Class.create({

    initialize: function (zipinput, countryselect, regionselect, cityinput, coordinatesinput) {
        this.zipinput = $(zipinput);
        this.countryselect = $(countryselect);
      
        this.regionselect = $(regionselect);
        this.cityinput = $(cityinput);
        this.coordinatesinput = $(coordinatesinput);
        this.processing = false;
        this.available = false;

        this.initEventHandler();

    },

    initEventHandler: function () {
        var _self = this;
        Event.observe(this.zipinput, "keydown", function () {
            _self.available = (_self.zipinput.value.length == 3) || (_self.zipinput.value.length == 4);
        });

        Event.observe(this.zipinput, "keyup", function () {
            if ((_self.zipinput.value.length == 4 || _self.zipinput.value.length == 5) && !_self.processing && _self.available) {
                new Ajax.Request('/Ajax/Region.aspx',
                {
                    method: 'post',
                    parameters: { zip: _self.zipinput.value, test: Math.random() },
                    onLoading: function () { _self.processing = true; },
                    onFailure: function () { _self.processing = false; },
                    onSuccess: function (response, json) { _self.onDataReceive(response, json); _self.processing = false; }
                });
            }
        });
    },

    onDataReceive: function (response, json) {

        if (json) {
            if (json.landID > 0) {
                this.selectDropDownListValue(this.countryselect, json.landID);

                if (json.regionID > 0) {
                    this.selectDropDownListValue(this.regionselect, json.regionID);
                }

                this.cityinput.value = unescape(json.city);
                this.coordinatesinput.value = unescape(json.coordinates);
                
            }
        }
    },

    selectDropDownListValue: function (dropdownlist, value) {
        for (var i = 0; i < dropdownlist.options.length; i++) {
            dropdownlist.options[i].selected = (dropdownlist.options[i].value == value);
        }
    }

});
