jQuery(document).ready(function($) {
	$("#development-search #query").autocomplete(Parameters.rootPath + "public/lookup/list");	
	$("#site-selector").change(function() {
		if ($(this).val() != "") { 	
			$("form#development-search").submit();
		}
	});
	
	/* External links markers */
  $('a:not(:has(img))').filter(function() {
    return this.hostname && this.hostname !== location.hostname;
  }).addClass("external");
	
	/**
	 * Set up the sliders 
	 */
	$("#bedroomSelector").hide();
	$("#bedroomSelector").after("<span class='caption'>Number of bedrooms</span><div id='bedroomSelectorCaption'><div id='bedroomSelectorSlider' class='slider'><div class='ui-slider-handle'></div></div></div>");
	$("#priceSelector").hide();
	$("#priceSelector").after("<span class='caption'>Price</span><div id='priceSelectorSlider' class='slider'><div class='ui-slider-handle'></div><div class='ui-slider-handle' style='left: 167px;'></div></div><span id='priceDisplay' class='caption'/>");

	$("#priceDisplay").html(Formatter.formatRange(50000, 2000000)); // TODO min-to-max

	$("#bedroomSelectorSlider").slider(
		{
			steps: 6, 
			startValue: $("#rooms").val(), 
			min: 0, 
			max: 6, 
			change: function(e,ui) {	
				$("#rooms").val(ui.value);
			}
		});
		
	$("#priceSelectorSlider").slider(
		{
			steps: 100, 
			min: 15, 
			max: 100,
			range: true, 
			change: function(e,ui) { 		
				var minValue = Calculator.calculate($("#priceSelectorSlider").slider('value', 0));
				var maxValue = Calculator.calculate($("#priceSelectorSlider").slider('value', 1));
				
				$("#minPrice").val(minValue);
				$("#maxPrice").val(maxValue);
			 	
			 	$("#priceDisplay").html(Formatter.formatRange(minValue, maxValue));
			 }
		});
		
		new SliderControl($("#priceSelectorSlider")).move(Calculator.toSliderValue($("#minPrice").val()), Calculator.toSliderValue($("#maxPrice").val()));
		
	/**
	 * Image Rotator
	 */
	if ($(".image-rotator").length > 0) {
		$(".image-rotator").cycle('fade');
	}
	
	/* Send to mobile */
	$("a.mobile").click(
		function() {
			window.open(this.href, 'banner-mobile', 'width=260,height=305,resizable=no,scrollbars=no,location=no,directories=no,menubar=no');
			return false;
		}
	);
	
	if ($("#main-menu ul").length > 0) {
		var back = jQuery.url.param("back-to-development");
		
		if (back) {
			var html = "<li><a href='" + Parameters.rootPath + back + "'>Back to Development</a></li>";
			$("#main-menu ul").append(html);
		}	
	}
	
	/* Captioning */
	$("div.property-image div.photo-caption").each(function() {
		var img = $(this).prev("img");
		$(this).width($(img).width() - 8);
	});

	$("div.has-captions div.photo-caption").each(function() {
		var img = $(this).prev("img");
		$(this).width($(img).width() - 6);
	});

	$("div.photo-caption").each(function() {
		var imageLink = $(this).prev("a");
		
		if (imageLink != null && imageLink.hasClass("thickbox")) {
			imageLink.attr("title", $(this).text());
		}	
	});
	
	$("a.confirm").click(function() {
		return confirm($(this).attr("title"));
	});
		
	/* General Enquiries inputs */
	$("#general-enquiry input.text-field").click(
		function() {
			$(this).select();
		}
	);
	
	/* Deals */
	$("a.deal-link").each(function() {
		new AdvertManager.show("Homebuyer's offer", $(this).attr("title"), false);
		
		$(this).click(function() {
			new AdvertManager.show("Homebuyer's offer", $(this).attr("title"), true);
		});
	});
	
	/* Add twitter feed */
	$("body#page-index").each(function() {
		$("#content").append("<div class='twitter'><h5><a href='http://www.twitter.com/bannerhomesplc'>Latest from Twitter:</a></h5><ul></ul></div>");
		
		var listOfTweets = $(".twitter ul");
		
		$.getJSON("http://search.twitter.com/search.json?q=from:bannerhomesplc&callback=?", function(data) {
			$.each(data.results, function(i, item) {
				var re = new RegExp("(http://bit\.ly/.[a-zA-Z0-9]*)");
				var tweet = item.text;
				var tweetWithLink = tweet;

				if (re.test(tweet)) {
					var bitlyURL = re.exec(tweet)[0];
					var url = '<a href="' + bitlyURL + '">' + bitlyURL + '</a>';
					tweetWithLink = tweet.replace(re, url);
				}

				listOfTweets.append("<li title='" + tweet + "'>" + tweetWithLink + "</li>");
			});

			listOfTweets.cycle({fx:'fade', pause:1, speed: 2500, speedIn: -1, speedOut: -1, cleartype:true});
		});
	});
	
});

var Formatter = {
	formatRange : function(min, max) {
		return Formatter.formatPrice(min) + " to " + Formatter.formatPrice(max);
	},

	formatPrice : function(price) {
		if (price < 1000000) {
			return "&pound;" + Math.round(price/1000) + "k";
		}
		
		return "&pound;" + (Math.round(price/100000))/10 + "m";
	}
};

var Calculator = {
	calculate : function (value) {
		return Calculator.round(Math.pow(value, 2)*200, 5000);	
	},
	toSliderValue : function(value) {
		var result = Calculator.round(Math.sqrt(value/200), 1);
		
		return result;
	},
	round : function(value, nearest) {
		return Math.round(value/nearest) * nearest;
	}
};

var SliderControl = function(sliderControl) {
	this.sliderControl = sliderControl;
}
SliderControl.prototype = {
	"move" : function(start, end) {
		this.sliderControl.slider("moveTo", end, 1);
		this.sliderControl.slider("moveTo", start, 0);
	}
};

var AdvertManager = {
	show : function(title, text, override) {
		var developmentId = jQuery("#development-link").attr("rel");
		var hidden = jQuery.cookie('banner-development-advert-' + developmentId) == "true";
		var home = window.location.href.match(/\/d\//) || window.location.href.match(/\/development\/view\//);
		
		if (override || (home && !hidden)) {
			if (jQuery("#advert").length == 0) {		
				jQuery("body").append("<div id='advert' style='display:none'><h2>" + title + "</h2><p>" + text.replace(/\[n\]/g, '</p><p>') + "</p><div><a id='advert-close' href='#'>Close</a><a id='advert-hide' href='#'>Don't show me this again</a></div></div>");
			}
			jQuery("#advert").show("slow");
			jQuery("#advert-close").click(function() {
				jQuery("#advert").hide("slow");
			});
			jQuery("#advert-hide").click(function() {
				jQuery.cookie('banner-development-advert-' + developmentId, 'true', {expires: 30}); 
				jQuery("#advert").hide("slow");
			});
		}
	}
}

