var AccommodationFormPage = Class.create();
Object.extend(AccommodationFormPage.prototype, {
    form: null,
    initialize: function() {
        this.form = arguments.length == 0 ? $('searchfrm') : $(arguments[0]);
        this.revive();
        this.populated = false;
        this.observer = {
            provinceChangeHandlerPrototype: function(event) {
                var select = Event.element(event);
                var provinceId = select.options[select.selectedIndex].value;
                if (parseInt(provinceId) == 0) {
                    $("city-list").disabled = true;
                } else {
                    this.fetchCityListByProvince(provinceId);
                }
            },
            countryChangeHandlerPrototype: function(event) {
                var select = Event.element(event);
                var countryId = select.options[select.selectedIndex].value;
                if (parseInt(countryId) == 0) {
                    ["province", "city"].each(function(item) {
                        var element = $(item + "-list");
                        element.length = 0;
                        if (element.getAttribute('message')) {
                            element.options[element.length] = new Option(element.getAttribute("message"));
                        }
                        element.disabled = true;
                    });
                } else {
                    this.fetchProvinceList(countryId);
                }
            }
        }
        if (!$("custom-city-radio") || ! $("custom-city-radio").checked) this.bindSubmit();
        this.observer.provinceChangeHandler = this.observer.provinceChangeHandlerPrototype.bindAsEventListener(this);
        this.observer.countryChangeHandler  = this.observer.countryChangeHandlerPrototype.bindAsEventListener(this);
    },
    populate: function() {
        this.populated = true;
        this.process();
    },
    process: function() {
        this.fetchData();
    },
    fetchData: function() {
        this.fetchCountryList();
    },
    fetchCountryList: function() {
        var options = {
            method: "get",
            parameters: {type: "location", action: "countries"},
            onSuccess: function(transport) {
                var json = eval(transport.responseText);
                this.countries = [];
                for (var i  = 0; i < json.length; i++) {
                    var country = Object.clone(new Object.extend(Country.prototype, json[i]));
                    this.countries.push(country);
                }
                if (this.countries.length == 1 ||
                    ($("country-list") && ! $("country-list").getAttribute("default"))) {
                    this.fetchProvinceList(this.countries[0].getId());
                } else if ($("country-list") && $("country-list").getAttribute("default")) {
                    this.fetchProvinceList($("country-list").getAttribute("default"));
                }

                this.build();
                this.bindSubmit();
            }.bind(this),
            onFailure: function(){
                this.bindSubmit();
            }
        };
        
        this.disableSelect($("country-list"));
        this.disableSelect($("province-list"));
        this.disableSelect($("city-list"));
        new Ajax.Request("/accommodation/", options);
    },
    fetchProvinceList: function(countryId) {
        if (parseInt(countryId) == 0) {
            return;
        }
        if (! countryId && this.countries.length > 1) {
            this.build();
            return;
        }
        this.disableSelect($("province-list"));
        this.disableSelect($("city-list"));
        new Ajax.Request("/accommodation/", {
            method: "get",
            parameters: {type: "location", action: "provinces", countryId: countryId},
            onSuccess: function(transport) {
                this.provinceListContainer = $("province-list");
                var json = eval(transport.responseText); 
                var defaultValue = this.provinceListContainer.getAttribute("default");

                if (json.length == 0) {
                    this.provinceListContainer.hide();
                    this.fetchCityListByCountry($("country-list").options[$("country-list").selectedIndex].value);
                } else {
                    this.provinceListContainer.show();
                    $("city-list").length = 0;
                    if ($("city-list").getAttribute('message')) {
                        $("city-list").options[$("city-list").length] = new Option($("city-list").getAttribute("message"), 0);
                    }
                    $("city-list").disabled = true;
                }

                this.provinces = [];
                for (var i  = 0; i < json.length; i++) {
                    var province = Object.clone(new Object.extend(Province.prototype, json[i]));
                    this.provinces.push(province);
                }

                this.provinceListContainer.removeAttribute("disabled");
                this.provinceListContainer.length = 0;
                if (this.provinceListContainer.getAttribute("message")) {
                    this.provinceListContainer.options[this.provinceListContainer.length] = new Option(this.provinceListContainer.getAttribute("message"), 0);
                }
                for (var i = 0; i < this.provinces.length; i++) {
                    var option = new Option(this.provinces[i].getName(), this.provinces[i].getId());
                    this.provinceListContainer.options[this.provinceListContainer.length] = option;
                    if (defaultValue && parseInt(defaultValue) == parseInt(option.value)) {
                        option.selected = true;
                    }
                }

                if (defaultValue) {
                    this.fetchCityListByProvince(parseInt(defaultValue));
                    this.provinceListContainer.removeAttribute("default");
                } else if ($("city-list").options.length == 0 ) {
                    this.fetchCityListByProvince(this.provinces[0].getId());
                }
                Event.stopObserving(this.provinceListContainer, "change", this.observer.provinceChangeHandler);
                Event.observe(this.provinceListContainer, "change", this.observer.provinceChangeHandler);
            }.bind(this)
        });
    },
    fetchCityListByProvince: function(id) {
        if (! id || parseInt(id) == 0) {
            return;
        }
        var id = parseInt(id);
        var options = {
            type: "location",
            action: "cities",
            provinceId: id
        };
        this.fetchCityList(options);
    },
    fetchCityListByCountry: function(id) {
        if (! id || parseInt(id) == 0) {
            return;
        }
        var id = parseInt(id);
        var options = {
            type: "location",
            action: "cities",
            countryId: id
        };
        this.fetchCityList(options);
    },
    disableSelect: function(element) {
        if (element) {
            element.length = 0;
            element.setAttribute("disabled", "disabled");
            element.options[element.length] = new Option("Please wait");
        }
    },
    fetchCityList: function(options) {
        this.disableSelect($("city-list"));
        new Ajax.Request("/accommodation/", {
            method: "get",
            parameters: options,
            onSuccess: function(transport) {
                var json = eval(transport.responseText);
                this.cityListContainer = $("city-list");
                var defaultValue = this.cityListContainer.getAttribute("default");
                this.cities = [];
                for (var i  = 0; i < json.length; i++) {
                    var city = Object.clone(new Object.extend(City.prototype, json[i]));
                    this.cities.push(city);
                }

                this.cityListContainer.removeAttribute("disabled");
                this.cityListContainer.length = 0;
                if (this.cityListContainer.getAttribute("message")) {
                    this.cityListContainer.options[this.cityListContainer.length] = new Option(this.cityListContainer.getAttribute("message"), 0);
                }
                for (var i = 0; i < this.cities.length; i++) {
                    var option = new Option(this.cities[i].getName(), this.cities[i].getId());
                    this.cityListContainer.options[this.cityListContainer.length] = option;
                    if (defaultValue && parseInt(defaultValue) == parseInt(option.value)) {
                        option.selected = true;
                    }
                }

                if (defaultValue) {
                    this.cityListContainer.removeAttribute("default");
                }

            }.bind(this)
        });
    },
    build: function() {
        if (! (this.countryListContainer = $("country-list"))) return; 

        var defaultValue = this.countryListContainer.getAttribute("default");
        if (defaultValue) {
            this.countryListContainer.removeAttribute("default");
        }

        this.countryListContainer.removeAttribute("disabled");
        this.countryListContainer.length = 0;
        if (this.countryListContainer.getAttribute("message")) {
            this.countryListContainer.options[this.countryListContainer.length] = new Option(this.countryListContainer.getAttribute("message"), 0);
        }

        for (var i = 0; i < this.countries.length; i++) {
            var option = new Option(this.countries[i].getName(), this.countries[i].getId());
            this.countryListContainer.options[this.countryListContainer.length] = option;
            if (defaultValue && (parseInt(option.value) == parseInt(defaultValue))) {
                option.selected = true;
            }
        }

        if (this.countries.length == 1) {
            this.countryListContainer.options[this.countryListContainer.options.length - 1].selected = true;
            this.countryListContainer.hide();
        } else {
            this.countryListContainer.show();
        }

        Event.stopObserving(this.countryListContainer, "change",this.observer.countryChangeHandler);
        Event.observe(this.countryListContainer, "change", this.observer.countryChangeHandler);
    },
    revive: function() {
        if ($("custom-city-radio")) {
            Event.observe("custom-city-radio", "click", function(event) {
                $("location-container").getElementsBySelector("select").each(function(select) {
                    if (select.options.length > 1) {
                        select.removeAttribute("disabled");
                    }
                });
                if ($("popular-city-box")) {
                    $("popular-city-box").getElementsBySelector("select").each(function(select) {
                        select.setAttribute("disabled", "disabled");
                    });
                }
                if (this.populated != true) {
                    this.populate();
                }
            }.bindAsEventListener(this));
        }

        if ($("popular-city-box")) {
            $("popular-city-box").getElementsBySelector('input[type="radio"]').each(function(item) {
                Event.observe(item, "click", function(event) {
                    if ($("location-container")) {
                        $("location-container").getElementsBySelector("select").each(function(select) {
                            select.setAttribute("disabled", "disabled");
                        });
                    }
                    if ($("popular-city-box")) {
                        $("popular-city-box").getElementsBySelector("select").each(function(select) {
                            select.removeAttribute("disabled");
                        });
                    }
                }.bindAsEventListener(this));
            }.bind(this));
        }
        if ($("custom-city-radio") && $("custom-city-radio").checked) {
            this.populate();
        }

        this.form.getElementsBySelector('select[name="typeId"]').each(function(selectElement) {
            Event.observe(selectElement, "change", function(event) {
                var select = Event.element(event);
                var option = select.options[select.selectedIndex];
                var radioElements = this.form.getElementsBySelector('input[name="rating"]');
                if (parseInt(option.getAttribute("norating")) == 1) {
                    $("rating-0").checked = true;
                    radioElements.each(function(radio) {
                        radio.setAttribute("disabled", "disabled");
                    });
                } else {
                    radioElements.each(function(radio) {
                        radio.removeAttribute("disabled");
                    });
                }
            });
        });

        Event.observe(this.form, 'submit', function(event) {
            if (! this.validate()) {
                Event.stop(event);
            }
        }.bindAsEventListener(this));

        if ($('searchphrasefrm')) {
	        Event.observe("searchphrasefrm", "submit", function(event) {
	            if ($F("searchtext").length == 0) {
	                $("searchtext").focus();
	                alert('Please type search phrase');
	                Event.stop(event);
	            }
	        }.bindAsEventListener(this));
	    }
    },
    bindSubmit: function() {
        if (! this.bindedSubmit) {
            $('perform-search').observe('click', function(event){
                if (this.validate()) {
                    this.form.submit()
                }
            }.bindAsEventListener(this));
            $('perform-search').removeClassName('transparent');
            this.bindedSubmit = true;
        }
    },
    validate: function() {
        if ((globalVars['clientName'] == 'melbourne.com'
                && $("custom-city-radio")
                && $("custom-city-radio").checked
                && $F('popular-city-list') == '')
            || (globalVars['clientName'] != 'melbourne.com'
                && $("custom-city-radio") 
                && $("custom-city-radio").checked 
                && ! parseInt($F("city-list")))) {
            alert("Select a city");
            return false;
        }
        return true;
    }
});

