var extraCheckboxes = [];

//these are hidden elements of the form
var standardElements = ['keyword','minimumSize','maximumSize','minimumPrice','maximumPrice','bedrooms','propertyType','centerType','residential','new_build','commercial','fineandcountry','land','new_instruction'];

var search_timeout = undefined;

var minimumPricesBuy = {0:{'title':'£0','value':'0'},1:{'title':'£175k','value':'175000'},2:{'title':'£250k','value':'250000'},3:{'title':'£350k','value':'350000'},4:{'title':'£500k','value':'500000'},5:{'title':'£750k','value':'750000'},6:{'title':'£1M','value':'1000000'}};
var minimumPricesRent = {0:{'title':'£0 pw','value':'0'},1:{'title':'£100 pw','value':'100'},2:{'title':'£200 pw','value':'200'},3:{'title':'£300 pw','value':'300'},4:{'title':'£400 pw','value':'400'},5:{'title':'£500 pw','value':'500'},6:{'title':'£600 pw','value':'600'},7:{'title':'£750 pw','value':'750'},8:{'title':'£1,000 pw','value':'1000'},9:{'title':'£2,000 pw','value':'2000'},10:{'title':'£3,000 pw','value':'3000'},11:{'title':'£4,000 pw','value':'4000'},12:{'title':'£5,000 pw','value':'5000'}};
var maximumPricesBuy = {0:{'title':'£175k','value':'175000'},1:{'title':'£250k','value':'250000'},2:{'title':'£350k','value':'350000'},3:{'title':'£500k','value':'500000'},4:{'title':'£750k','value':'750000'},5:{'title':'£1M','value':'1000000'},6:{'title':'£2M','value':'2000000'}};
var maximumPricesRent = {0:{'title':'£100 pw','value':'100'},1:{'title':'£200 pw','value':'200'},2:{'title':'£300 pw','value':'300'},3:{'title':'£400 pw','value':'400'},4:{'title':'£500 pw','value':'500'},5:{'title':'£600 pw','value':'600'},6:{'title':'£750 pw','value':'750'},7:{'title':'£1,000 pw','value':'1000'},8:{'title':'£2,000 pw','value':'2000'},9:{'title':'£3,000 pw','value':'3000'},10:{'title':'£4,000 pw','value':'4000'},11:{'title':'£5,000 pw','value':'5000'},12:{'title':'£10,000+ pw','value':'100000'}};
var minimumSizesMetric = {0:{'title':'X','value':'X'},1:{'title':'X','value':'X'}};
var minimumSizesImperial = {0:{'title':'X','value':'X'},1:{'title':'X','value':'X'}};
var maximumSizesMetric = {0:{'title':'X','value':'X'},1:{'title':'X','value':'X'}};
var maximumSizesImperial = {0:{'title':'X','value':'X'},1:{'title':'X','value':'X'}};
var suggestionThickbox = [450,600]

var thickboxInlineId = 'suggestionsContainer'; // suggestions container id
var searchEngineType = "searchajax";

var canChangeCriteria;

function HomeSearch(formId) {
    this.form = '#' + formId + ' fieldset';
    this.canSubmitRightAway = false;
    this.init();
}

HomeSearch.prototype.adjustPrices = function(toKeep) {
    if (toKeep == 'minimumPrice') {
        if (parseInt($('#maximumPrice').val(),10) <= parseInt($('#minimumPrice').val(),10)) {
            var found = false;
            $('#maximumPrice option:selected').removeAttr('selected');
            $('#maximumPrice option').each(function() {
                if (found !== true) {
                    if (parseInt($('#minimumPrice').val(),10) < parseInt($(this).val(),10)) {
                        $(this).attr('selected','selected');
                        found = true;
                    }
                }
            });
        }
    } else {
        if (parseInt($('#maximumPrice').val(),10) <= parseInt($('#minimumPrice').val(),10)) {
            $('#minimumPrice option').each(function(i) {
                if (parseInt($(this).val(),10) < parseInt($('#maximumPrice').val(),10)) {
                    $('#minimumPrice option:selected').removeAttr('selected');
                    $(this).attr('selected','selected');
                }
            });
        }
    }
};

HomeSearch.prototype.adjustSizes = function(toKeep) {
    if (toKeep == 'minimumSize') {
        if (parseInt($('#maximumSize').val(),10) <= parseInt($('#minimumSize').val(),10)) {
            var found = false;
            $('#maximumSize option:selected').removeAttr('selected');
            $('#maximumSize option').each(function() {
                if (found !== true) {
                    if (parseInt($('#minimumSize').val(),10) < parseInt($(this).val(),10)) {
                        $(this).attr('selected','selected');
                        found = true;
                    }
                }
            });
        }
    } else {
        if (parseInt($('#maximumSize').val(),10) <= parseInt($('#minimumSize').val(),10)) {
            $('#minimumSize option').each(function(i) {
                if (parseInt($(this).val(),10) < parseInt($('#maximumSize').val(),10)) {
                    $('#minimumSize option:selected').removeAttr('selected');
                    $(this).attr('selected','selected');
                }
            });
        }
    }
};

HomeSearch.prototype.setPredictedPropertiesNumberText = function(msg) {
    $('#predictedPropertiesNumber').text(msg);
    if (msg === 1) {
        $('#predictedPropertiesNumberLabel').text('property');
    } else {
        $('#predictedPropertiesNumberLabel').text('properties');
    }
    if (msg === 0) {
        $('#predictedPropertiesText').addClass('zeroProperties');
    } else {
        $('#predictedPropertiesText').removeClass('zeroProperties');
    }
};


/**
 *  Called if any of the search criteria has changed
 */
HomeSearch.prototype.criteriaChanged = function() {
    if ($('#geoLocationType').val() === 'unknown' && $('#centerType').val() === 'geoName') {
        return;
    }
    url = this.getSearchEngineUrl('count');
    if (search_timeout !== undefined) {
        clearTimeout(search_timeout);
    }
    search_timeout = setTimeout(function() {
        search_timeout = undefined;
        $('#predictedPropertiesBusy').show();
        $.ajax({
            url: url,
            success: function(msg){
                searchForm.setPredictedPropertiesNumberText(msg);
            },
            complete: function (XMLHttpRequest, textStatus) {
                $('#predictedPropertiesBusy').hide();
            }
        });
    }, 1000);
};

HomeSearch.prototype.getSearchEngineUrlPartCenterType = function() {
    var centerTypeUrl = '';
    if ($('#centerType').val() == 'office') {
        var selectedOffices = this.getOffices();
        var officesIdList = '';
        for (var i in selectedOffices) {
            if (selectedOffices[i] !== undefined) {
                officesIdList = officesIdList+selectedOffices[i].id+',';
            }
        }
        centerTypeUrl = 'offices/'+officesIdList.replace(/,+$/,"")+'/';
    } else {
        var geoLocationType = $('#geoLocationType').val();
        var geoLocationId = $('#geoLocationId').val();
        var location = $('#location').val();
        if (location !== '') {
            centerTypeUrl = 'location/'+location+'/geoLocationId/'+geoLocationId+'/geoLocationType/'+geoLocationType+'/';
        }
    }
    return centerTypeUrl;
};


HomeSearch.prototype.getSearchEngineUrlPartPrecision = function() {
    var precisionUrl = '';
    if ($('#precision').attr('checked') !== true) {
        precisionUrl = 'precision/nearby/';
    } else {
        precisionUrl = 'precision/exact/';
    }
    if ($('#minLat').val() !== '' && $('#minLat').val() !== undefined) {
        precisionUrl = precisionUrl + 'minLat/'+$('#minLat').val()+'/minLng/'+$('#minLng').val()+'/maxLat/'+$('#maxLat').val()+'/maxLng/'+$('#maxLng').val()+'/';
    }
    return precisionUrl;
};

HomeSearch.prototype.getSearchEngineUrlPartGeneralBits = function () {
    var generalBitsUrl = '';
    if ($('#new_built').val() === 'yes') {
        generalBitsUrl += 'new_built/yes/';
    }
    return generalBitsUrl;
};

HomeSearch.prototype.getSearchType = function() {
    if ($('#searchType-buy').attr('checked') === true) {
        return 'buy';
    } else if ($('#searchType-rent').attr('checked') === true) {
        return 'rent';
    } else {
        return 'unknown';
    }
};

HomeSearch.prototype.getSearchEngineUrlRadius = function() {
    var radiusUrl = '';
    if ($('#radius').val() > 0 ) { // some radius is selected
        radiusUrl = 'radius/'+$('#radius').val() + '/';
    }
    return radiusUrl;
};
HomeSearch.prototype.getUnitSize = function() {
    if ($('#sizeUnit-imperial').attr('checked') === true) {
        return 'imperial';
    } else if ($('#sizeUnit-metric').attr('checked') === true) {
        return 'metric';
    } else {
        return 'unknown';
    }
};

/**
 * @return string url to call in ajax
 * @param string resultType is one of possible result types: map|count|list
 */
HomeSearch.prototype.getSearchEngineUrl = function(resultType, controller) {
    var searchType = '';
    if (searchForm.getSearchType() === 'buy') {
        searchType = 'buy/';
    }
    if (searchForm.getSearchType() === 'rent') {
        searchType = 'rent/';
    }
    if (searchForm.getSearchType() === 'all') {
        searchType = 'all/';
    }
    var sizeUnit = '';
    if (searchForm.getUnitSize() === 'metric') {
        sizeUnit = 'metric/';
    }
    
    if (searchForm.getUnitSize() === 'imperial') {
        sizeUnit = 'imperial/';
    }

    var centerTypeUrl = this.getSearchEngineUrlPartCenterType();
    var precisionUrl = this.getSearchEngineUrlPartPrecision();
    var generalBits = this.getSearchEngineUrlPartGeneralBits();
    var radiusUrl = this.getSearchEngineUrlRadius();

    var url = '';
    if (resultType == 'count' || resultType == 'mapxml' || resultType == 'getboundary') {
        url = '/' + searchEngineType +'/'+resultType+'/';
    } else {
        if (controller == 'undefined') {
            controller = 'search';
        }
        url = '/' + controller + '/'+resultType+'/';
    }

    $(standardElements).each(function(i, standardElement){
        if ($('#'+standardElement).val() !== '' && $('#'+standardElement).val() !== undefined) {
            url = url + standardElement + '/' +$('#'+standardElement).val() + '/';
        }
    });

    $(extraCheckboxes).each(function(i, extraCheckbox){
        if ($('#'+extraCheckbox).attr('checked') === true && $('#'+extraCheckbox).attr('disabled') !== true) {
            url = url + extraCheckbox + '/yes/';
        }
    });

    url = url + 'searchType/'+searchType + centerTypeUrl + precisionUrl + generalBits + radiusUrl;

    if (resultType == "additionaldatasets") {
        url = "/" + searchEngineType + "/additionaldatasetsxml/searchType/"+searchType+precisionUrl+generalBits+radiusUrl;
    }
    
    if (sizeUnit !='') {
    	url = url + 'sizeUnit/' + sizeUnit;
    }
    
    return url;
};


HomeSearch.prototype.addOffice = function(officeId, officeName, dontReload) {
    this.removeOffice(officeId, true);
    $(this.form).prepend('<input name="offices['+officeId+']" type="hidden" value="'+$.trim(officeName)+'" />');
    if (dontReload !== true) {
        this.criteriaChanged();
    }
};

HomeSearch.prototype.removeOffice = function(officeId, dontReload) {
    $(this.form + ' input[name="offices['+officeId+']"]').remove();
    if (dontReload !== true) {
        this.criteriaChanged();
    }
};

HomeSearch.prototype.getOffices = function() {
    var ret = [];
    $i=0;
    $(this.form+' input[name^="offices["]').each(function(i,element) {
        var key = $(element).attr('name').match(/\d+/g);
        var office = {'id':key,'name':$(element).val()};
        ret[i] = office;
        $i++;
    });
    return ret;
};

HomeSearch.prototype.switchCenterTypeToOffice = function() {
    $('#centerType').val('office');
    $('#location').attr('readonly','readonly');
    this.criteriaChanged();
};

HomeSearch.prototype.switchCenterTypeToGeoName = function() {
    $('#centerType').val('geoName');
    $('#location').removeAttr("readonly");
    this.criteriaChanged();
};

HomeSearch.prototype.switchCenterTypeToBoundary = function(clearLocation) {
    if (clearLocation === true) {
        $('#location').val('');
        $('#geoLocationType').val('');
        $('#geoLocationId').val('');
    }
    $('#centerType').val('boundary');
    $('#location').removeAttr("readonly");
};

HomeSearch.prototype.getCenterType = function() {
    return $('#centerType').val();
};

HomeSearch.prototype.switchSearchTypeToBuy = function() {
    this.switchSearchType(minimumPricesBuy, maximumPricesBuy);
    $('#advancedCheckboxesForRent').hide();
    $('#advancedCheckboxesForRent :checkbox').attr('disabled','disabled');
    $('#advancedCheckboxesForBuy :checkbox').removeAttr('disabled');
    $('#advancedCheckboxesForBuy').show();
};

HomeSearch.prototype.switchSearchTypeToRent = function() {
    this.switchSearchType(minimumPricesRent, maximumPricesRent);
    $('#advancedCheckboxesForRent').show();
    $('#advancedCheckboxesForRent :checkbox').removeAttr('disabled');
    $('#advancedCheckboxesForBuy :checkbox').attr('disabled','disabled');
    $('#advancedCheckboxesForBuy').hide();
};

HomeSearch.prototype.switchSearchType = function(minimumPrices, maximumPrices) {
    $('#minimumPrice').empty();
    $('#maximumPrice').empty();
    for (var i in minimumPrices) {
        if (minimumPrices[i].value !== 'undefined' ) {
            $('#minimumPrice').append('<option value="'+minimumPrices[i].value+'">'+minimumPrices[i].title+'</option>');
        }
    }
    for (i in maximumPrices) {
        if (maximumPrices[i].value !== 'undefined' ) {
            $('#maximumPrice').append('<option value="'+maximumPrices[i].value+'">'+maximumPrices[i].title+'</option>');
        }
    }
    $('#maximumPrice option:last').attr('selected','selected');
};

HomeSearch.prototype.getMinLat = function() {
    return parseFloat($('#minLat').val());
};

HomeSearch.prototype.getMinLng = function() {
    return parseFloat($('#minLng').val());
};

HomeSearch.prototype.getMaxLat = function() {
    return parseFloat($('#maxLat').val());
};

HomeSearch.prototype.getMaxLng = function() {
    return parseFloat($('#maxLng').val());
};

HomeSearch.prototype.clearBoundary = function() {
    $('#minLat').val('');
    $('#maxLat').val('');
    $('#minLng').val('');
    $('#maxLng').val('');
};

HomeSearch.prototype.disableAutosuggest = function() {
    $('#location').setOptions({
        minChars: 9999999
    });
};

HomeSearch.prototype.enableAutosuggest = function() {
    $('#location').setOptions({
        minChars: 2
    });
};

HomeSearch.prototype.submitLocationSearch = function(geoLocationId, geoLocationType, location ) {
    $('#geoLocationType').val(geoLocationType);
    $('#geoLocationId').val(geoLocationId);
    if (location !== '') {
        $('#location').val(location);
    }
    this.canSubmitRightAway = true;
    return $(this.form).parent().submit();
};

HomeSearch.prototype.switchUnitSize = function(minimumSizes, maximumSizes) {
    $('#minimumSize').empty();
    $('#maximumSize').empty();
    for (var i in minimumSizes) {
        if (minimumSizes[i].value !== 'undefined' ) {
            $('#minimumSize').append('<option value="'+minimumSizes[i].value+'">'+minimumSizes[i].title+'</option>');
        }
    }
    for (i in maximumSizes) {
        if (maximumSizes[i].value !== 'undefined' ) {
            $('#maximumSize').append('<option value="'+maximumSizes[i].value+'">'+maximumSizes[i].title+'</option>');
        }
    }
    $('#maximumSize option:last').attr('selected','selected');
};

HomeSearch.prototype.keywordChanged = function() {
	if (canChangeCriteria === true) {
		keyword = $('#keyword').val();
        if (keyword != '') {
        	searchForm.criteriaChanged();
        }
	}
};

HomeSearch.prototype.init = function() {
    $('#searchType-buy').click(function() {
        searchForm.switchSearchTypeToBuy();
        searchForm.criteriaChanged();
    });

    $('#searchType-rent').click(function() {
        searchForm.switchSearchTypeToRent();
        searchForm.criteriaChanged();
    });

    $('#minimumPrice').change(function() {
        searchForm.adjustPrices('minimumPrice');
        searchForm.criteriaChanged();
    });

    $('#maximumPrice').change(function() {
        searchForm.adjustPrices('maximumPrice');
        searchForm.criteriaChanged();
    });

    $('#bedrooms').change(function() {
        searchForm.criteriaChanged();
    });

    $('#propertyType').change(function() {
        searchForm.criteriaChanged();
    });

    $('#precision').click(function() {
        searchForm.criteriaChanged();
    });

    $('#sizeUnit-metric').click(function() {
        searchForm.switchUnitSize(minimumSizesMetric,maximumSizesMetric);
        searchForm.criteriaChanged();
    });
    
    $('#sizeUnit-imperial').click(function() {
    	searchForm.switchUnitSize(minimumSizesImperial,maximumSizesImperial);
        searchForm.criteriaChanged();
    });
    
    $('#minimumSize').change(function() {
        searchForm.adjustSizes('minimumSize');
        searchForm.criteriaChanged();
    });
    
    $('#maximumSize').change(function() {
        searchForm.adjustSizes('maximumSize');
        searchForm.criteriaChanged();
    });

    $("#location").focus(function () {
        if(typeof(searchForm) === 'object') {
            searchForm.enableAutosuggest();
        }
    });

    $('#keyword').focus(function() {
        keyword = $('#keyword').val();
        if (keyword == '') {
        	$('#keyword').val('');
        }
    });
    
    $('#keyword').keyup(function() {
    	canChangeCriteria = true;
    	setTimeout("searchForm.keywordChanged()",500);
    });
    
    $('#keyword').keydown(function() {
    	var d = new Date();
    	canChangeCriteria = false;
    });
    
    $('#keyword').blur(function() {
        keyword = $('#keyword').val();
        if (keyword == '') {
        	$('#keyword').val('');
        }
        searchForm.criteriaChanged();
    });

    $('#radius').change(function() {
        searchForm.clearBoundary();
        searchForm.criteriaChanged();
    });

    $("#location").autocomplete('/locationsearch/predictive/', {
        minChars: 2,
        //width: 310,
        matchContains: false,
        autoFill: false,
        //mustMatch: true,
        delay: 700,
        cacheLength: 0,
        formatItem: function(row, i, max) {
            row = $.evalJSON(row);
            res = row.location;
            if (row.parentLocation !== null && row.parentLocation !== "") {
                res = res + ', ' + row.parentLocation;
            }
            return res;
        },
        formatResult: function(row, i, max) {
            return $.evalJSON(row).location;
        }
    });

    $("#location").result(function(handle, item) {
        $('#geoLocationType').val($.evalJSON(item).geoLocationType);
        $('#geoLocationId').val($.evalJSON(item).geoLocationId);
        searchForm.switchCenterTypeToGeoName();
        searchForm.canSubmitRightAway = true;
    });

    /*
     * now lets see if the location was brought in by the request and if so then the canSubmtitRightAway
     * should be allowed
     */
    if ($('#geoLocationType').val() != 'unknown' && $('#geoLocationId').val() != 0) {
        // still not working correctly!!
        //this.canSubmitRightAway = true;
    }

    $(this.form).parent().submit(function(event) {
        if (searchForm.getCenterType() === 'geoName') {
            searchForm.disableAutosuggest();
            if (searchForm.canSubmitRightAway === true) {
                $('#predictedPropertiesBusy').hide();
                searchForm.canSubmitRightAway = false;
                return true;
            } else {
                $('#predictedPropertiesBusy').show();
                $.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') {
                                searchForm.submitLocationSearch(msgobject.locations.geoLocationId, msgobject.locations.geoLocationType, msgobject.locations.location  );
                            } else {
                                $('#'+thickboxInlineId+' ul').empty();
                                $(msgobject.locations).each(function(i, element) {
                                    if (element !== 'undefined' && element.location !== 'undefined') {
                                        var itemTitle = element.location;
                                        if (element.parentLocation !== '' && element.parentLocation !== null) {
                                            itemTitle = element.location+', '+element.parentLocation;
                                        }
                                        $('#'+thickboxInlineId+' ul').append('<li><a href="#" onclick="searchForm.submitLocationSearch(\''+element.geoLocationId+'\', \''+element.geoLocationType+'\', \''+element.location+'\' )">'+itemTitle+'</a></li>');
                                    }
                                });
                                tb_show('suggestions', '#TB_inline?height='+suggestionThickbox[1]+'&width='+suggestionThickbox[0]+'&inlineId='+thickboxInlineId, false);
                            }
                        }
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                      $('#predictedPropertiesBusy').hide();
                    }
                 });
            return false;
        }
        }
        return true;
    });

    $('#location').focus();
};
