    /* Motels search */
    Motels = {

//        updateHotDealsDelay: 3000,

        reqObj: null,    
        isLoading: false,
        data: null,
        lgeocoder: null,


        keywordsSearch: function(skipHomeDataSaving) {
            if(this.isLoading || !window["gm"]) return false;

            if(!skipHomeDataSaving) {
                var str = $("inp_keywords").value;
                HomeData.setValue("find_motel", str);
                HomeData.setValue("find_target", str == "" ? "" : "m");
                HomeData.save();
            }

            this.isLoading = true;

            $("search_results").innerHTML = "<div style='width: auto; text-align: center;'>Loading...<br><img src='/static/images/loading_bar.gif' class='loading_animation_bar'/></div>";
            $("inp_keywords").disabled = true;

            var request_params = {
                dialog: 'controller',
                action: 'motels_search',
                keywords: $("inp_keywords").value
            }

            var o = this;
            var cb = function(data) {
                o.onKeywordsSearchResponce(data);
            }

            this.reqObj = new AJAX_Request({url: "", params: request_params, callback: cb});
        },


        onKeywordsSearchResponce: function(data) {
            $("inp_keywords").disabled = false;
            this.isLoading = false;
            this.data = data;

            if(data && data.length > 0) {
                var html = "";
                for(var i=0; i<data.length; i++) {
                    var addr = (data[i]["state"].toUpperCase() + " " + data[i]["country"]).toUpperCase();
                    html += "<div class='item'>" + 
                            "<div class='title'>" + data[i]["member"] + " (" + addr + ")</div><div>" +
                            "<a href='javascript:Motels.showItemOnMap(\"" + i + "\")'>Show on map</a> | "+ 
                            "<a href='" + data[i].url + "'>Go to website</a>"+
                            "</div></div>";
                }
            } else {

                var html = "<div class='message_error' style='margin-left: 5px; margin-right: 10px;'>Sorry!<br>nothing found...</div>";
            }
            $("search_results").innerHTML = html;
            this.reqObj = null;
        },



        // Location search
        locationSearch: function(skipHomeDataSaving) {
            if(this.isLoading || !window["gm"]) return false;

            if(!skipHomeDataSaving) {
                var str = $("inp_location").value;
                HomeData.setValue("find_location", str);
                HomeData.setValue("find_target", str == "" ? "" : "l");
                HomeData.save();
            }

            this.isLoading = true;

            $("search_results").innerHTML = "<div style='width: auto; text-align: center;'>Loading...<br><img src='/static/images/loading_bar.gif' class='loading_animation_bar'/></div>";

            var self = this;
            var cb = function(data) {
                if (data['custom_location']) {
                    self.isLoading = false;        
                    $("search_results").innerHTML = "";
                    var custom_location = data['custom_location'];
                    gm.setMapCenter(new GLatLng(custom_location['lat'], custom_location['lng']), custom_location['zoom']); 
                }
                else {
                    if(!this.lgeocoder) {
                        this.lgeocoder = new GClientGeocoder();
                    }
                    var addr = $("inp_location").value;

                    var onAddrResult = function(point) {
                        self.isLoading = false;
                        if(!point) {
                            $("search_results").innerHTML = "<div class='message_error'>Sorry, address<br/><b>" + addr + "</b><br/>not found.</div>";
                        } else {
                            $("search_results").innerHTML = "";
                            var map = gm.getMapObject();
                            map.setCenter(point, 13);
//                            var marker = new GMarker(point);
//                            map.addOverlay(marker);
//                            marker.openInfoWindowHtml(addr);
                       }
                    }

                    this.lgeocoder.getLatLng(addr, onAddrResult);
                }
            };

            var request_params = {
                dialog: 'controller',
                action: 'cloc_from_find',
                loc: $("inp_location").value
            };
            new AJAX_Request({url: '', params: request_params, callback: cb});
        },





        showItemOnMap: function(idx) {
            if(!window["gm"] || !this.data) return;

            var m = this.data[idx];

            if(m.lon == null || m.lat == null) {
                gm.findAddress(m.city + ", " + (m.country + ", " + m.state).toUpperCase());
            } else {
            var a = new GLatLng(m.lat, m.lon);
                gm.navigateToCoordinate(new GLatLng(m.lat, m.lon), 9);
            }
        },



        // User interface 
        ui_values_loaded: false,

        init: function(name) {
            if(this.ui_values_loaded) return;
            this.ui_values_loaded = true;

            if (direct_data){
                if (direct_data.motel_name){
                    HomeData.setValue("find_motel", direct_data.motel_name);
                    HomeData.setValue("find_target", "m");
                    HomeData.setValue("map_target", "a");
                    HomeData.save();
                    gm.navigateToCoordinate(new GLatLng(direct_data.lat, direct_data.lon), 9);
                }
            }
            $("inp_keywords").value = HomeData.getValue("find_motel");
            $("inp_location").value = HomeData.getValue("find_location");


            $('country_select').value = HomeData.getValue("country");
            $('state_select').value = HomeData.getValue("state");
            $('city_select')._homeCity = HomeData.getValue("city");

            var fl = true;

            if(!this.mapNavigated) {
                if(HomeData.getValue("map_target")) {
                    gm.navigateToCoordinate(new GLatLng(HomeData.getValue("map_lat"), HomeData.getValue("map_lng")), HomeData.getValue("map_zoom"));
                } else {
                    gm.navigateToAU();
                    fl = false;
                }

                if(HomeData.getValue("state") != "") {
                    this.onAddressUpdate("state", fl);
//                        HotDeals.refresh();
                }
            }



            var t = HomeData.getValue("find_target");
            if(t == "m") {
                this.keywordsSearch(true);
            } else if(t == "l") {
                this.locationSearch(true);
            }
        },

/*
        showTab: function(name) {
            if(!window.isGmapReady) return;
            if(name == "search") {
                $hide("gmap_tools_directions");
                $show("gmap_tools_search");
                $("gmap_tab_directions").className = "tab";
                $("gmap_tab_search").className = "tab_selected";
            } else if(name == "directions") {
                $show("gmap_tools_directions");
                $hide("gmap_tools_search");
                $("gmap_tab_directions").className = "tab_selected";
                $("gmap_tab_search").className = "tab";
            }
            this.initTabData(name);
            HomeData.setValue("tab", name);
            HomeData.save();
        },


        showDirections: function(skipHomeDataSaving) {
            if(!window["gm"]) return false;
            var start = $("gmap_dir_start").value;
            var end = $("gmap_dir_end").value;

            if(!skipHomeDataSaving) {
                HomeData.setValue("trip_start", start);
                HomeData.setValue("trip_end", end);
                HomeData.save();
            }

            gm.setDirections(start, end, "en");
            $("directions").innerHTML = "<div style='width: auto; text-align: center;'>Loading...<br><img src='/static/images/loading_bar.gif' class='loading_animation_bar'/></div>";
            return false;
        },
        */

        addressTimeout: null,
/*
        updateHotDeals: function() {
            if(this.addressTimeout) {
                clearTimeout(this.addressTimeout);
            }
            var updateHD = function() {
                HotDeals.applyAddress();
            }
            this.addressTimeout = setTimeout(updateHD, this.updateHotDealsDelay);
        },
*/


        activeCountry: null,
        activeState: null,
        searchCache: {"au": {}, "nz": {}},


        onAddressUpdate: function(level, skipHomeDataSaving) {
//            this.updateHotDeals();
            if(!window["gm"]) return false;

            var country = $('country_select').value;
            var state = $('state_select').value;
            var cty = $('city_select').value;

            if(country == 'nz') {
                $('state_select').value = '';
                $('state_select').disabled = true;
                var st = '';
            } else {
                $('state_select').disabled = false;
                var st = $('state_select').value;
            }
            if( st && country == '') {
                $('country_select').value = 'au';
                country = 'au';
            }

            var endFl = false;

            switch( level ) {
                case 'state':
                    if(this.activeState == state) endFl = true;
                    this.activeState = state;
                    $('city_select').value = '';
                    break;
                case 'country':
                    if(this.activeCountry == country) endFl = true;
                    this.activeCountry = country;
                    $('state_select').value = '';
                    $('city_select').value = '';
                    break;
            }

            if(!skipHomeDataSaving) {
                HomeData.setValue("country", country);
                if(country == "au") {
                    HomeData.setValue("state", state);
                } else {
                    HomeData.setValue("state", "");
                }
                HomeData.setValue("city", cty);
                HomeData.setValue("find_target", "");
                HomeData.setValue("map_target", "a");
                HomeData.save();
            }


            if(endFl || (level == "country" && country == "")) return;

            var request_params = { dialog: 'controller', action: 'searchgetcities', c: country };
            if( st ) request_params.s = st;
            var zoom = gm.calcZoom(country, st ? st : null, cty ? cty : null);
            gm.navigateTo(gm.makeAddress(country, st ? st : null, cty ? cty : null), zoom);

            var sc_country = request_params["c"];
            var sc_state = request_params["s"] || 0;
            var cache = this.searchCache[sc_country][sc_state];

            if ('city' == level) {
                if( cty ) request_params.cty = cty;
                var o = this;
                var cb = function(data) {
                    if (data['custom_location']) {
                        var custom_location = data['custom_location'];
                        gm.setMapCenter(new GLatLng(custom_location['lat'], custom_location['lng']), custom_location['zoom']); 
                    } else {
                        if(!skipHomeDataSaving) {
                            gm.navigateTo(gm.makeAddress(country, st ? st : null, cty ? cty : null), zoom);
                        }
                    }
                }
                new AJAX_Request({url: '', params: request_params, callback: cb});
                return;
            }

            if(cache) {
                this.addMainCities();
                this.onCitiesListResponce(cache);
                if (cache['custom_location']) {
                    var custom_location = cache['custom_location'];
                    gm.setMapCenter(new GLatLng(custom_location['lat'], custom_location['lng']), custom_location['zoom']); 
                }
                else {
                    if(!skipHomeDataSaving) {
                        gm.navigateTo(gm.makeAddress(country, st ? st : null, cty ? cty : null), zoom);
                    }
                }
            } else if(!cty) {
                var o = this;
                var cb = function(data) {
                    o.searchCache[sc_country][sc_state] = data;
                    o.onCitiesListResponce(data);
                    if (data['custom_location']) {
                        var custom_location = data['custom_location'];
                        gm.setMapCenter(new GLatLng(custom_location['lat'], custom_location['lng']), custom_location['zoom']); 
                    }
                    else {
                        if(!skipHomeDataSaving) {
//                            gm.navigateTo(gm.makeAddress(country, st ? st : null, cty ? cty : null), zoom);
                        }
                    }
                }
                this.addMainCities();
                new AJAX_Request({url: '', params: request_params, callback: cb});
            }
        },


        onCitiesListResponce: function(data) {
            var s = $('city_select');
            if(!data) { 
                s._homeCity = false;
                return;
            }
            for(var i=0; i<data['cities'].length; i++) {
                s.options.add(new Option(data['cities'][i]['City'], data['cities'][i]['City']));
            }
            if(s._homeCity) {
                s.value = s._homeCity;
                s._homeCity = false;
            }
        },


        addMainCities: function() {
            var s = $('city_select');
            var v = s.value;
            s.options.length = 1;
            var state = $('state_select').value;
            if($('country_select').value == "nz" || state == "") return;

            var cl = this.citiesOrder[state].split("|");
            for(var i=0; i<cl.length; i++) {
                s.options.add(new Option(cl[i], cl[i]));
                s.options[s.options.length-1].style.fontWeight = "bold";
            }
            setTimeout(function() { s.value = v; }, 1);
        },


        citiesOrder: {
            "qld": "Brisbane|Capricorn Coast|Darling Downs|Far North Queensland|Fraser Coast|Great Barrier Reef|Gold Coast|North Coast|Sunshine Coast|Whitsunday Coast",
            "nsw": "Sydney|Blue Mountains|Central Coast|Central West|Far North Coast|Islands|Lower North Coast|Mid North Coast|New England|North West|South Coast|South West|Snowy Mountains",
            "nt": "Darwin",
            "act": "Canberra",
            "sa": "Adelaide|Adelaide Hills|Barossa Valley|Eyre Peninsula|Fleurieu Peninsula|Flinders Ranges|Kangaroo Island|Mid North|Yorke Peninsula",
            "tas": "Hobart",
            "vic": "Melbourne|Great Dividing Range|Great Ocean Road",
            "wa": "Perth|Coral Coast|Kimberley|Pilbara"
        }


    }
