﻿// Initialise the autocomplete
jQuery(document).ready(function(){
	searchBox.Init();
});

// Initialise function and other autocomplete functions
var searchBox = {


	Init:function(){

		// objects
		searchBox.AutoCompleteTextBox = jQuery('#searchIntellLocation')[0];
		searchBox.AutoCompleteTypeBox = jQuery('#searchIntellType')[0];
		searchBox.SubmitButton = jQuery('.advancedsearchsubmit')[0];
		searchBox.MessageBox = jQuery('#searchMessageBox')[0];
		searchBox.isLondonLocation = false;
		
		// prepare Controls
		this.EnableMinControls();
		
		// Watermark Controls
        jQuery(searchBox.AutoCompleteTextBox).Watermark("Region?");
		jQuery(searchBox.AutoCompleteTypeBox).Watermark("Property Type?");
			
		// events
		jQuery(this.SubmitButton).click(function(e){searchBox.onSubmit(e);});
		
		// auto complete
		jQuery(this.AutoCompleteTextBox).autocomplete('/services/GetLocation.aspx', {

		    delay: 400,
		    width: 400,
		    scroll: false,
		    formatItem: formatItem,
		    formatResult: formatResult,
			selectFirst: true,
			cacheLength: 1,
			max:15,
		    extraParams: {
                // Olly - since this is fixed when initialised we use a function to get the current country
				country: function() { 
                    // currentCountry should be initalised to "" on the page itself
                    if (currentCountry == -1)  { 
                        return "";
                    } else {
                        return currentCountry;
                    } 
                },
		        countryID: "0",
				GetLocationsByPrefix:"a"
		    }
	    });
		
		// auto complete for types
		jQuery(this.AutoCompleteTypeBox).autocomplete('/services/GetTypes.aspx', {
		    delay: 100,
		    width: 400,
		    scroll: false,
		    formatItem: formatItem,
		    formatResult: formatResult,
			selectFirst: true,
		    extraParams: {
				country: "",
		        countryID: "0",
				GetTypesByPrefix:"a"
		    }
	    });
		
		jQuery(this.AutoCompleteTypeBox).result(function(event,data,formatted){

			var url = data[3];
			var name = data[1];
			var id = data[2];
			searchBox.SelectedTypeID = id;
			searchBox.SelectedTypeURL = url;
		});
		
		jQuery(this.AutoCompleteTextBox).result(function(event,data,formatted){

			var level = data[4];
			var IDs;
			var regionID;
            IDs = data[3].split('_');
			if(level==1){ regionID = data[2]; }
			else{ regionID = IDs[0]; }
			
			// set location id
			searchBox.SelectedLocationID = data[2];
			searchBox.SelectedLocationURL = data[1];
			
			// now check if the selected location is in Greater London?
			if (IDs[0]==50503) {
				searchBox.isLondonLocation = true;
			}
		});
	},

	onSubmit:function(e){

		e.preventDefault();
		
		// construct URL here

		// var _targetDomain = 'http://'+ document.domain;
        //var _targetDomain = "http://localhost:61558"
        var _targetDomain = 'http://properties.aplaceinthesun.com';
		var _targetURL = _targetDomain;
        var _defaultURL = '/notfound.aspx'
		
        // Do we have any type selected? If so append to targeturl
		if(searchBox.SelectedTypeURL!='')
        {	
			_targetURL += '/' + searchBox.SelectedTypeURL;	
        }
        // Do we have a location selected?
		if(searchBox.SelectedLocationURL != '') 
        {
			_targetURL += '/' + searchBox.SelectedLocationURL;
		}
        else 
        {
            // No country selected 
            if (jQuery('.countryvalue').val() == -1) {
                // If they've filled 'something' in...
                if (jQuery('#searchIntellLocation').val() != "Region?")
                {
                    _targetURL = _targetDomain + '/search_results/' + jQuery('#searchIntellLocation').val();
                }
            } else {
                // At least show results for the country they've selected
                _targetURL += '/' + jQuery('.countryvalue').val() + '/';
            }
		}
        

		if (isInteger(jQuery('#searchIntellType').val())) 
        {
        	//if property id then redirect to property detail page		
			_targetURL = '/details/' + (jQuery('#searchIntellType').val()) + '/';
        }
			
		_targetURL = _targetURL.toLowerCase().replace(/ /gi, "_");

        // On server form is aspnetForm
        jQuery('#aspnetForm').attr("action", _targetURL);
		jQuery('#aspnetForm').attr("method", "post");
		jQuery('#aspnetForm').submit();

        //alert(_targetURL);
        //return false;
        // For testing form is form1
        //jQuery('#form1').attr("action", _targetURL);
		//jQuery('#form1').attr("method", "post");
		//jQuery('#form1').submit();
	},

	FillDropDown:function(data,obj){
		jQuery(obj).removeOption(/./);
		
		jQuery(data).each(function(index){

			var cols = data[index].split('|');
			var optn = document.createElement("option");
			optn.text = cols[0];
			optn.value = cols[1];	
			if (cols[1]!=undefined){
				jQuery(obj)[0].options.add(optn);}
		});
	},
	AutoCompleteTextBox:null,
	AutoCompleteTypeBox:null,
	SubmitButton:null,
	MessageBox:null,
	SelectedLocationID:0,
	SelectedLocationURL:'',
	SelectedTypeID:0,
	SelectedTypeURL:'',
	SelectedCountryLocationID:function(){
		return this.SelectedCountryLocationIDByName(siteRootLocation);
	},
	SelectedCountryLocationIDByName:function(name){
		var i = null;
		var countries = this.getCountries();
		jQuery(countries).each(function(index){
			var cols = countries[index].split('|');
			if(cols[0]==name)
			{
				i = cols[1];
				index = 1000;
			}
		});
		return i;
	},
	CacheRegions:true,
	UseFreshCountryData:false,
	isLondonLocation:false,
	SubmitURL:"property/search",
	SubmitMethod:"POST",
	UpdateSubmitButton:function(){
        // Olly - removed this redundant code
	},
	remoteURL:"/tmc.system/tmc.services.locations.asp?IncludePromoted=true&IsDeep=true&GetLMSChildLocations=",
	remoteCountryDataURL:"/tmc.system/tmc.services.locations.asp?Country=ActiveLMS",
	EnableMinControls:function(){	
        // Countryvalue is the class attached to the country drop down (I hate jquery + .net selectors)
        if (jQuery('.countryvalue').val() == -1) {
            this.AutoCompleteTextBox.disabled = true;
        }
        else
        {
            this.AutoCompleteTextBox.disabled = false;
        }
		this.AutoCompleteTypeBox.disabled = false;
	},
	getCountries:function(){
		if (this.UseFreshCountryData){
			var dummy = 'Please Select Country|0';
			jQuery.ajax({
				type: "GET",
				url:this.remoteCountryDataURL,
				async:false,
				beforeSend: function(xhr) {
				},
				success:function(s){
					var ary = s.split('\n').join(':');
					dummy = dummy + ':' + ary;
				}
			});
			return dummy.split(":");
		} 
        else 
        {
			return countries;
		}
	},
	getCurrencies:function(){return defaultCurrencies;},
	getPriceRanges:function(){return ("@label|-1:@value|0:@valuek|25:@valuek|50:@valuek|75:@valuek|100:@valuek|150:@valuek|200:@valuek|300:@valuek|500:@valuek|1000").split(":");},
	getBedRanges:function(){return ("@label|@label:Studio|0:1|1:2|2:3|3:4|4:5|5:6|6:7|7:8|8:9|9:10|10").split(":");}
}

function Init(){
	searchBox.Init();
}

function formatItem(row) {
    return row[1].replace(/[/]/gi," &#187 ").replace(/[_]/gi," ");
}

function formatResult(row) {
	return row[0];
}

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}
