if (typeof(Array.prototype.strInArray) == "undefined") {
	Array.prototype.strInArray = function (value) {
		// Returns true if the passed string is found in the
		// array. Returns false if it is not.
		var i;
		var tl = this.length;
		for (i=0; i < tl; i++) {
			if (this[i]==value) {
				return true;
			}
		}
		return false;
	};
}
if (typeof(Array.prototype.inArray) == "undefined")
	Array.prototype.inArray = Array.prototype.strInArray;

var object_search_cb = function (data) {
};

if (typeof jQuery != 'undefined' && typeof jQuery.fn.delayedObserver != "undefined") jQuery(document).ready(function($) {
	var page = 1;
	var form = $("form#object-search").submit(function() {
		var form = $(this);

		$.post(form.attr("action"), form.serialize() + "&action=object-search&page="+String(page), function(data) {
			data = $(data);
			object_search_cb(data);
			$("#object-search-results").html(data);
			$("#object-search-results .pagination a[rev]").each(function() {
				$(this).click(function() {
					page = $(this).attr("rev");
					form.submit();
					return false;
				});
			});
		});
		return false;
	}).trigger("submit");

	form.find("input[type~=text]").delayedObserver(function() {
		object_search_page = 1;
		form.submit();
	});
	form.find("select").change(function() {
		page = 1;
		form.submit();
	}).click(function() {
		page = 1;
		form.submit()
	});
});

if (typeof jQuery != 'undefined') (function($) {
	if ($.fn.livequery) {
        $("input.label-is-value").livequery(function() {
            var el = $(this);
            var defaultValue = this.defaultValue;
            el.focus(function() {
                if (el.val() == defaultValue)
                    el.val('');
            });
            el.blur(function() {
                if (el.val() == '')
                    el.val(defaultValue);
            });
            el.closest("form").submit(function() {
				if (el.val() == defaultValue) {
					el.val('');
					window.setTimeout(function() { el.val(defaultValue); }, 250);
				}
            });
        });

        $("input[type=text].label-is-value-password").livequery(function() {
            var $el = $(this);
            var defaultValue = this.defaultValue;
            
            var $real_el = $('<input type="password">').
                attr('name', $el.attr('name')).
                attr('class', $el.attr('class')).
                hide();
            if ($el.val() != defaultValue)
                $real_el.val($el.val());
            $el.after($real_el);

            $el.focus(function() {
                $el.hide();
                $real_el.show().focus();
            });
        });

        $("input.ajax-complete-simple").livequery(function() {
            if (typeof $.fn.autocomplete == 'undefined')
                return alert('You must use {!$jquery_ui_include} after {!$javascript_include} to use the AJAX autocomplete');
            var $el = $(this);
            if ($el.data('ajax_search_applied'))
                return;
            $el.data('ajax_search_applied', true)
            /*
            var $div = $('<div>').addClass('ajax-search-results').css('z-index', '100');
            /* XXX this was at the top. changed to bottom for prestonbarker.co.uk/buy.html */
            /*
            $(document.body).append($('<div>').css('position', 'relative').append($div));
            */
            var parameters = "field="+escape($el.attr("rel") ? $el.attr('rel') : '')
                +"&show_type="+Number(Boolean($el.hasClass("ac-show-type")))
                +"&only_predefined="+Number(Boolean($el.hasClass("ac-only-predefined")))
                +"&output=json";
            if ($el.attr("rev"))
                parameters += "&parameters="+$el.attr("rev");
            $el.autocomplete({
                minLength: 1,
                delay: 200,
                source: function(request, response) {
                    $.post('/ajax/viewport-search', parameters + '&value=' + escape(request.term), function(data) {
                        response(data);
                    }, "json");
                }

            });
        });
    }
})(jQuery);

function number_format(a, b, c, d) {
	// number_format(number, decimals, comma, formatSeparator)
	//
	if (!b) b = 0;
	if (!c) c = ".";
	if (!d) d = ",";

	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a.toString()
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function html_entity_decode(str) {
	var ta = document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
	toReturn = ta.value;
	ta = null;
	return toReturn
}
if (!salePrices)
	var salePrices = [75000, 100000, 125000, 150000, 175000, 200000, 225000, 250000, 275000, 300000, 325000, 350000, 375000, 400000, 425000, 450000, 475000, 500000, 750000, 1000000];
if (!letPrices)
	var letPrices = [350, 450, 500, 550, 600, 650, 700, 800, 1000, 1500, 2000];

function selectInstructionType(el_it, el_minprice, el_maxprice, cb) {
	var $ = jQuery;
	el_it = $("#"+el_it);
	el_minprice = $("#"+el_minprice);
	el_maxprice = $("#"+el_maxprice);

	if (!el_it.length)
		return;
	var value = el_it.val();

	if (selectInstructionType.custom) {
		var data = selectInstructionType.custom[value];
		if (el_minprice.length) populatePrices(el_minprice, data.prices, "min", data.format);
		if (el_maxprice.length) populatePrices(el_maxprice, data.prices, "max", data.format);
	} else switch (value) {
		case "Letting":
			if (el_minprice.length) populatePrices(el_minprice, letPrices, "min", selectInstructionType.format.let);
			if (el_maxprice.length) populatePrices(el_maxprice, letPrices, "max", selectInstructionType.format.let);
			break;
		default:
			if (el_minprice.length) populatePrices(el_minprice, salePrices, "min", selectInstructionType.format.sale);
			if (el_maxprice.length) populatePrices(el_maxprice, salePrices, "max", selectInstructionType.format.sale);
			break;
	}
	if (typeof(cb) == "function")
		cb(value.toLowerCase());
	return value;
}

selectInstructionType.format = {};
selectInstructionType.format.sale = selectInstructionType.format.let = "&pound;{!$price}";
selectInstructionType.custom = false;

function selectInstructionTypeRadio(el_it, el_minprice, el_maxprice, cb) {
	var $ = jQuery;
	el_minprice = $("#"+el_minprice);
	el_maxprice = el_maxprice ? $("#"+el_maxprice) : false;

	var inputs = $("input[name="+el_it+"]:checked");
	var v = "";

	inputs.each(function() {
			var el = $(this);
			if (el.attr("type") != "radio") return;
			var opts = {}
			if (el.attr("rev"))
				opts = eval('('+el.attr("rev")+')');
			var prices = format = null;
			switch (el.val()) {
				case "Sale":
					prices = typeof(opts.prices) != "undefined" ? opts.prices : salePrices;
					format = typeof(opts.format) != "undefined" ? opts.format : selectInstructionType.format.sale;
					break;
				case "Letting":
					prices = typeof(opts.prices) != "undefined" ? opts.prices : letPrices;
					format = typeof(opts.format) != "undefined" ? opts.format : selectInstructionType.format.let;
					break;
			}
			if (prices && format) {
				if (el_minprice.length) populatePrices(el_minprice, prices, "min", format);
				if (el_maxprice.length) populatePrices(el_maxprice, prices, "max", format);
			}
			v = el.value;
			if (typeof(cb) == "function")
				cb(el.value.toLowerCase(), el_minprice, el_maxprice);
	});
	return v;
}

function populatePrices(el, prices, type, format) {
	var $ = jQuery;
	var value = el.val()
	var prices = prices.slice();

	while (el.attr("options").length > 0)
		el.get(0).remove(0);
	
	if (typeof(prices[0]) == "string") {
		var mintext = html_entity_decode(prices[0]);
		prices.shift();
	} else var mintext = "No Minimum";

	if (typeof(prices[prices.length-1]) == "string") {
		var maxtext = html_entity_decode(prices[prices.length-1]);
		prices.pop();
	} else var maxtext = "No Maximum";

	if (populatePrices.initialOption)
		addSelectOption(el, "", populatePrices.initialOption);

	if (type == "min")
		addSelectOption(el, "", mintext);

	format = html_entity_decode(format);

	$.each(prices, function(n, price) {
			var text = format.replace("%%price%%", number_format(price)).replace("{!$price}", number_format(price));
			addSelectOption(el, price, text);
			if (price == value)
				el.attr("selectedIndex", el.attr("options").length-1);
	});
	if (type == "max") {
		addSelectOption(el, "", maxtext);
		el.attr("selectedIndex", (populatePrices.selectedIndex && typeof(populatePrices.selectedIndex.max) == "number") ? populatePrices.selectedIndex.max : el.attr("options").length-1);
	}
}

function addSelectOption(el, value, text) {
	var $ = jQuery;
	el.append($("<option></option>").attr("value", value).text(text));
}

var ListSearch = function(el) {
	$(el).parents("form").attr("action", "/search/");
};
var MapSearch = function(el) {
	$(el).parents("form").attr("action", "/search2/");
};
var setFormAction = function(el, action) {
	$(el).parents("form").attr("action", action);
}

var touchHandler = function(event) {
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
    
    switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }
        
    //initMouseEvent(type, canBubble, cancelable, view, clickCount,
    //           screenX, screenY, clientX, clientY, ctrlKey,
    //           altKey, shiftKey, metaKey, button, relatedTarget);
    
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                              first.screenX, first.screenY,
                              first.clientX, first.clientY, false,
                              false, false, false, 0/*left*/, null);
                                                                            
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

var RecentLocations = {

	initialised: false,
	init: function() {
		if (!this.initialised) {
			this.$div = $('<div/>').attr("id", "recent-locations").hide().appendTo(document.body);
			var $form = $("form");
			this.el_longitude = $('<input/>').attr("type", "hidden").attr("name", "longitude").appendTo($form);
			this.el_latitude = $('<input/>').attr("type", "hidden").attr("name", "latitude").appendTo($form);
			$('<input/>').attr("type", "hidden").attr("name", "latitude").insertAfter(this);
			this.el_address_keyword = $("form input[name=address_keyword]");
			if (!this.el_address_keyword.length)
				alert("Your form must contain an a field for address_keyword");
			this.initialised = true;
		}
	},

	getCurrentLocation: function() {
		this.init();

		if (navigator.geolocation) {
			var el_latitude = this.el_latitude;
			var el_longitude = this.el_longitude;
			var el_address_keyword = this.el_address_keyword;
			navigator.geolocation.getCurrentPosition(function(position) {
				var geocoder = new google.maps.Geocoder();
				geocoder.geocode({ latLng: new google.maps.LatLng(position.coords.latitude, position.coords.longitude) }, function(results, status) {
					var address = results[0].formatted_address;
					el_address_keyword.val(address).attr("name", "");
					el_latitude.val(position.coords.latitude);
					el_longitude.val(position.coords.longitude);

					$.post("/recent_locations.html", {
						action: 'add',
						address: address,
						latitude: position.coords.latitude,
						longitude: position.coords.longitude
					});
				})
			});
		}
	},

	setManualLocation: function() {
		this.el_address_keyword.attr("name", "address_keyword");
		this.el_latitude.val('');
		this.el_longitude.val('');
	},

	showRecentLocations: function() {
		this.init();
		this.$div.show().load("/recent_locations.html");
		document.body.appendChild(this.$div.get(0));
	},

	closeRecentLocations: function() {
		this.init();
		this.$div.hide();
		return false;
	},

	setCurrentLocation: function(latitude, longitude, address) {
		this.init();
		this.el_address_keyword.val(address);
		if (latitude || longitude) {
			this.el_latitude.val(latitude);
			this.el_longitude.val(longitude);
			this.el_address_keyword.attr("name", "");
		} else {
			this.el_latitude.val('');
			this.el_longitude.val('');
			this.el_address_keyword.attr("name", "address_keyword");
		}
		closeRecentLocations();
	}
}

var getCurrentLocation = function() { RecentLocations.getCurrentLocation() };
var setCurrentLocation = function() { RecentLocations.setCurrentLocation.apply(RecentLocations, arguments) };
var setManualLocation = function() { RecentLocations.setManualLocation() };
var showRecentLocations = function() { RecentLocations.showRecentLocations() };
var closeRecentLocations = function() { RecentLocations.closeRecentLocations() };

function addToShortlist(id, skipreclass) {
	$.post("/ajax/add_to_shortlist", { id: id }, updateShortlistCallback, "json");
	if (!skipreclass) $(".shortlist-property-"+id).addClass("remove-from-shortlist");
}

function deleteFromShortlist(id, skipreclass) {
	$.post("/ajax/delete_from_shortlist", { id: id }, updateShortlistCallback, "json");
	if (!skipreclass) $(".shortlist-property-"+id).removeClass("remove-from-shortlist");
}

function toggleInShortlist(id) {
	var actioned = false;
	$(".shortlist-property-"+id).each(function() {
		$this = $(this);
		if ($this.hasClass("remove-from-shortlist")) {
			if (!actioned) {
				deleteFromShortlist(id, true);
				actioned = true;
			}
			$this.removeClass("remove-from-shortlist");
			$this.addClass("add-to-shortlist");
		} else {
			if (!actioned) {
				addToShortlist(id, true);
				actioned = true;
			}
			$this.removeClass("add-to-shortlist");
			$this.addClass("remove-from-shortlist");
		}
	});
}

function updateShortlistCallback(data) {
	$("#shortlist").html(data);
}

function mapLayerCheckboxes() {
	$("input.maplayercheckbox").each(function() {
			var $this = $(this);
			switchLayer($(this).attr("id"), Boolean($(this).attr("checked")));
	});
}


