jQuery(document).ready(function($) {
	$("#header form.search .submit-button").hide();
	
	$(".development-search select").keypress(function(event) {
		if (event.which == '13') {
			$(".development-search").submit();
			return false;
		}
	});

	$("label.infield").inFieldLabels();
	
	$("#header form.search #query").autocomplete(Parameters.rootPath + "public/lookup/list").result(function(event, item) {
			//$("#header form.search").submit();
			//return false;
		});	

	$(".development-search input[type=reset]").click(function() {
		$(".development-search select").each(function() {
			$(this).find("option:first").attr("selected", "selected");
		});
		
		$(this).parent("form").submit();
		return false;
	});

	$("#site-selector").change(function() {
		if ($(this).val() != "") { 	
			$("#header form.search").submit();
			return false;
		}
	});

	$(".collapsible h5").click(function() {
		var container = $(this).parent();

		if (container.hasClass("collapsed")) {
			container.find("div").slideDown();
			container.removeClass("collapsed");
		}
		else {
			container.find("div").slideUp();
			container.addClass("collapsed");
		}
	});
	
	/* External links markers */
  $('a:not(:has(img))').filter(function() {
    return !$(this).hasClass("ignore-external") && this.hostname && this.hostname !== location.hostname;
  }).addClass("external");
	
	/**
	 * Image Rotator
	 */
	$(".image-rotator").each(function() {
		$(this).find("li").eq(0).show();

		$(this).find("li img").each(function() {
			var caption = $(this).attr("alt");
			
			if (caption != null && caption != "") {
				$(this).after("<h5 class='photo-caption'>" + caption + "</h5>");
			}
		});
		
		$(this).cycle('fade');
	});
	
	if ($(".content-header .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>";
			$(".content-header .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);
	});
	
	$("a.confirm").click(function() {
		return confirm($(this).attr("title"));
	});
		
	/* General Enquiries inputs */
	$("#general-enquiry input.text-field").click(
		function() {
			$(this).select();
		}
	);
	
	/* Photo Gallery*/
	$(".photo-list h5").click(function() {
		$(this).parent().find("a").click();
	});
	
	$(".photo-list a").each(function() {
		var caption = $(this).parent().find(".photo-caption").text();
		
		if (caption) {
			$(this).attr("title", caption);		
		}
	});

	$("a[rel=popup]").each(function() {
		$(this).attr("title", $(this).find("img").attr("alt"));
	});

	$("a[rel=popup]").lightBox({
		imageBtnPrev: Parameters.rootPath + "images/common/lightbox-btn-prev.gif", 
		imageBtnNext: Parameters.rootPath + "images/common/lightbox-btn-next.gif",
		imageLoading: Parameters.rootPath + "images/common/lightbox-ico-loading.gif",
		imageBtnClose: Parameters.rootPath + "images/common/lightbox-btn-close.gif",
		imageBlank: Parameters.rootPath + "images/common/lightbox-blank.gif",
		fixedNavigation:true
		});
	
	/* Deals */
	$("a.deal-link").each(function() {
		var show = new AdvertManager.show("Homebuyer's offer", $(this).attr("title"), false);
		
		$(this).click(function() {
			show = new AdvertManager.show("Homebuyer's offer", $(this).attr("title"), true);
		});
	});
	
	/* Add twitter feed */
	$("#footer").each(function() {
		$("#footer").prepend("<div class='twitter'><a href='http://www.twitter.com/bannerhomesplc' target='_blank'><img src='" + Parameters.rootPath + 'images/common/twitter.gif' + "' alt='Twitter'/></a><ul></ul></div>");
		
		var listOfTweets = $(".twitter ul");
		
		$.getJSON("https://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 + '" target="_blank">' + 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});
		});
	});

	/* Replace links to YouTube videos with embed code */
	if ($("#admin-header").length == 0) {
		$("a[href^='http://www.youtube.com']").each(function() {
			var container = $(this).parentsUntil("div").parent(); 
			container.addClass("with-video");
			
			$(this).text('If you cannot see this video, click here');
			
			// Embed video under link
			var videoLink = $(this).attr('href');
			
			container.prepend('<div class="video"/>');
			var wrapper = container.find("div.video");
			wrapper.append($(this));

			var width = wrapper.width() ? wrapper.width() : '640';
			var height = wrapper.height() ? wrapper.height() : '385';
			
			var re = /v=(.[^&]*)/;			
			if (re.test(videoLink)) {
				var videoId = re.exec(videoLink)[1];
				
				var embedHtml = '<object id="the-video" width="'+ width +'" height="'+ height +'"><param name="movie" value="http://www.youtube.com/v/' + videoId + '&amp;hl=en_GB&amp;fs=1&amp;enablejsapi=1&amp;version=3"></param>'+
				'<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>'+
				'<embed src="http://www.youtube.com/v/' + videoId + '&amp;hl=en_GB&amp;fs=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true"'+ 
				'width="'+ width +'" height="'+ height +'"></embed></object>';		
				
				wrapper.prepend(embedHtml);
			}
		});
	}

	$(".content-header .menu li a").each(function() {
		var link = encodeURI($(this).attr("href"));
		var location = window.location.href;

		if (location.match(link + "$") || location.match(link + "/view$")) {
			$(this).addClass("active");
		}
	});
	
	/* Development search form */
	$("select#county").change(function() {
		if ($(this).val() != '-1') {
			$("select#town").val("");
		}
	});

	$("select#town").change(function() {
		if ($(this).val() != '-1') {
			$("select#county").val("");
		}
	});
	
	addNHBClogosToCertainDevelopments();
});

function addNHBClogosToCertainDevelopments() {
	/*
	 * Ferndale Gate, Blackwell
	 * Partridge Corner, Birdlip
	 * Lambourne Gate, Burnham
	 * Church View, Southam
	 */
	var developmentIDs = ["75750", "71609", '21009', '68783'];
	
	var currentDevelopmentID = jQuery("body").attr("id");
	
	var index;
	for (index = 0; index < developmentIDs.length; index++) {
		var developmentID = developmentIDs[index];
		
		if (currentDevelopmentID.indexOf(developmentID) !== -1) {
			var img = '<img src="' + Parameters.rootPath + 'images/badges/nhbc-new.jpg" alt="NHBC Pride in the Job 30 years" class="badge-nhbc" />';
			
			jQuery(".content-header").append(img);
		} 
	}
}

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");
			});
		}
	}
};

