formId = '';
var extraCheckboxes = ['parking','garden','leasehold','freehold','furnished','unfurnished'];
var lastLocation = '';
var lastGeoLocationType = null;
var lastGeoLocationId = null;

var maxZoomLevel = 8;
var minZoomLevel = 18;
var autoEnableAutosuggest = true; // when the location input box is actually a dropdown this needs to be false

/**
 * This is called when there is an exact match on location
 */
function locationSelected(item) {
    $('#geoLocationType').val($.evalJSON(item).geoLocationType);
    $('#geoLocationId').val($.evalJSON(item).geoLocationId);
    $('#location').val($.evalJSON(item).location);
    $.ajax({
        url: searchForm.getSearchEngineUrl('getboundary'),
        success: function(msg) {
            if ($.trim(msg) == 'false') {
                alert('There are no properties in selected location which fit search criteria');
                $('#location').val(lastLocation);
                $('#geoLocationType').val(lastGeoLocationType);
                $('#geoLocationId').val(lastGeoLocationId);
                //updateMarkers();
            } else {
                searchForm.updateBoundary($.evalJSON(msg).minLat,$.evalJSON(msg).maxLat,$.evalJSON(msg).minLng,$.evalJSON(msg).maxLng);
                reCentreMap();
                //updateMarkers();
                lastLocation = $('#location').val();
                lastGeoLocationType = $('#geoLocationType').val();
                lastGeoLocationId = $('#geoLocationId').val();
            }
            $('#location').focus();
            if (autoEnableAutosuggest === true) {
                searchForm.enableAutosuggest();
            }
        }
    });
}


/**
 * This is called by clicking on a link in the suggested locations in a thickbox popup
 */
function locationSelectedFromParams(geoLocationId, geoLocationType, location) {
    var item = '{"geoLocationId":'+geoLocationId+',"location":"'+location+'","geoLocationType":"'+geoLocationType+'","parentLocation":""}';
    tb_remove();
    $('#location').focus();
    return locationSelected(item);
}


function MapSearch(formId) {
    formId = formId;
    this.defaultAction = '';
    this.form = '#'+ formId + ' fieldset';
    this.init();
    this.initExtend();
    this.setDefaultAction('update');
}

MapSearch.prototype.initExtend = function() {
	//this is called after init, just so I can extend init
	return false;
}

// inherit from HomeSearch
MapSearch.prototype = new HomeSearch(formId);

MapSearch.prototype.setDefaultAction = function(defaultAction) {
    this.defaultAction = defaultAction;
    if (defaultAction == 'submit') {
        this.criteriaChanged();
    }
};

/**
 *  Called if any of the search criteria has changed
 */
MapSearch.prototype.criteriaChanged = function() {
    if (this.defaultAction == 'submit') {
        HomeSearch.prototype.criteriaChanged.apply(this);
    } else {
        updateMarkers();
    }
};

MapSearch.prototype.updateBoundary = function(minLat, maxLat, minLng, maxLng) {
    $('#minLat').val(minLat);
    $('#maxLat').val(maxLat);
    $('#minLng').val(minLng);
    $('#maxLng').val(maxLng);
    this.setDefaultAction('update');
};

MapSearch.prototype.init = function(resultType) {
    var params = [resultType];
    HomeSearch.prototype.init.apply(this,params);

    $('.advancedSearchOptions :checkbox').click(function() {
        searchForm.criteriaChanged();
    });
    
	$('#radius').unbind('change');
    $('#radius').change(function() {
        $.ajax({
            url: '/locationsearch/locationmatch/q/'+$('#location').val(),
            success: function(msg){
                if ($.trim(msg) == 'false') {
                    alert('There are no properties in selected location which fit search criteria');
                } else {
                    locationSelected(msg);
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                $('#predictedPropertiesBusy').hide();
            }
         });
        return false;
    });

    $(this.form).parent().unbind('submit');
    $(this.form).parent().submit(function(event) {
        searchForm.disableAutosuggest();
        $.ajax({
            url: '/locationsearch/locationmatch/q/'+$('#location').val(),
            success: function(msg){
                if ($.trim(msg) === '') {
                    alert('Please type in the location name');
                } else if ( $.trim(msg) === 'no_match' ) {
                    alert('There are no locations matching the location searched');
                } else { // we have either exact or close matches
                    msgobject = $.evalJSON(msg);
                    if (msgobject.result === 'exact_match') {
                        $('#geoLocationType').val(msgobject.locations.geoLocationType);
                        $('#geoLocationId').val(msgobject.locations.geoLocationId);
                        if (msgobject.locations.location  !== '') {
                            $('#location').val(msgobject.locations.location );
                        }
                        var item = '{"geoLocationId":'+msgobject.locations.geoLocationId+',"location":"'+msgobject.locations.location+'","geoLocationType":"'+msgobject.locations.geoLocationType+'","parentLocation":""}';
                        locationSelected(item);
                    } else {
                        $('#suggestionsContainer ul').empty();
                        for (var i in msgobject.locations) {
                            if (msgobject.locations[i] !== undefined) {
                                var itemTitle = msgobject.locations[i].location;
                                if (msgobject.locations[i].parentLocation !== '' && msgobject.locations[i].parentLocation !== null) {
                                    itemTitle = msgobject.locations[i].location+', '+msgobject.locations[i].parentLocation;
                                }
                                $('#suggestionsContainer ul').append('<li><a href="javascript:{}" onclick=\'locationSelectedFromParams('+msgobject.locations[i].geoLocationId+',"'+msgobject.locations[i].geoLocationType+'","'+msgobject.locations[i].location+'")\'>'+itemTitle+'</a></li>');
                            }
                        }
                        tb_show('caption', '#TB_inline?height='+suggestionThickbox[1]+'&width='+suggestionThickbox[0]+'&inlineId=suggestionsContainer', false);
                    }
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                $('#predictedPropertiesBusy').hide();
            }
        });
        return false;
    });

    lastLocation = $('#location').val();
    $("#location").result(function(handle, item) {
        locationSelected(item);
    });

    $('#mapPopup').mouseover(setUpMapTimeouts);
    $('#officePopup').mouseover(setUpMapTimeouts);
    
};

