$(document).ready(function() {
	// Fix for pop-out e-forms
	if($("iframe .bc-formpopout").length) {
		$("body").css("background", "none");
		$("body").css("background-color", "#FFF");
	}
	// Ensure pop-out eforms never use cache on older IE browsers
	$("a.popoutEform").each(function() {
		var href = $(this).attr("href");
		var prefix = href.indexOf("?") != -1 ? "&" : "?";
		$(this).attr("href", $(this).attr("href") + prefix + "timestamp="+new Date().getTime()+"&ignoreAnalytics=true");
	});
	// Set up the fancybox plugins for standard links
	$("a.popoutEform, .galleryLink, .popoutInline").fancybox();
	// Set up the fancybox plugin for YouTube/Vimeo links
	$(".videoLink").click(function(e) {
		if($(this).attr("href").toLowerCase().indexOf("youtube") > -1) {
			$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: $(this).attr("title"),
				'width'		: 680,
				'height'		: 495,
				'href'			: $(this).attr("href").replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
					 'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});
		}
		if($(this).attr("href").toLowerCase().indexOf("vimeo") > -1) {
			$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: $(this).attr("title"),
				'width'		: 680,
				'height'		: 385,
				'href'			: $(this).attr("href").replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
				'type'			: 'swf',
				'swf'			: {
					 'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});
		}
		e.preventDefault();
		return false;
	});
	
	// Show the booking title on a pop-out e-form
	if($("#bc-description").length) {
		var propertyTitle = getQueryStringByName("title", $(".bookViewing").attr("href"));
		if(propertyTitle != "") {
			$("#bc-description p").text(propertyTitle);
			$(".eform_input_requested_property input").val(propertyTitle);
		}
	}
	
	// Switch tab on the property map
	$(".listTab").click(function(e) {
		SwitchTab($(this).attr("rel"));
		e.preventDefault();
		return false;
	});
	
	// Bind to the search input tabs,
	// ensure selected tab is saved to cookies
	$("#bc-searchtab-sale a").click(function() {
		SearchSale(true);
	});
	$("#bc-searchtab-let a").click(function() {
		SearchLet(true);
	});
	
	if(window.location.href.match(/\/Lettings-7489.html$/)) {
		SearchLet(true);
	}
	else if(window.location.href.match(/\/Sales-7488.html$/)) {
		SearchSale(true);
	}
	else if($.cookie('SearchType') == 'Let') {
		SearchLet(true);
	}
	else {
		SearchSale(true);
	}
	
	// Property gallery hover-overs
	$(".galleryLink img").hover(function() {
		$(".mediumGalleryImage img").attr("src", $(this).attr("rel"));
	});
	// Ensure that when the medium gallery image is clicked, the fancybox
	// opens at the correct image
	$(".mediumGalleryImage img").click(function(e) {
		$(".hoverableGallery[rel='"+$(this).attr("src")+"']").trigger("click");
		e.preventDefault();
		return false;
	});
});

function SwitchTab(newId) {	
	$("#bc-mappopoutcanvas-property, #bc-mappopoutcanvas-list, #bc-mappopoutcanvas-sale, #bc-mappopoutcanvas-let").stop(true, true);
	$(".listTab").removeClass("bc-maptabactive").addClass("bc-maptaboff");
	$(".listTab[rel='"+newId+"']").removeClass("bc-maptaboff").addClass("bc-maptabactive");
	$(".mapCanvas").css("display", "none");
	if($("#"+newId).css("position") == "absolute") {
		$("#"+newId).css("position", "relative");
		$("#"+newId).css("left", "0");
	}
	$("#"+newId).fadeIn("fast");
}

function SearchSale(setCookie) {
	if(setCookie) {
	$.cookie('SearchType', 'Sale');
	}
	$("#bc-searchtab-let a").removeClass("bc-searchtabactive").addClass("bc-searchtaboff");
		$("#bc-searchtab-sale a").removeClass("bc-searchtaboff").addClass("bc-searchtabactive");
		$("#bc-searcharea-let").stop(true, true);
		$("#bc-searcharea-sale").stop(true, true);
		$("#bc-searcharea-let").fadeOut("fast", function() {
			$("#bc-searcharea-sale").fadeIn("fast");
		});
}

function SearchLet(setCookie) {
	if(setCookie) {
		$.cookie('SearchType', 'Let');
	}
	$("#bc-searchtab-sale a").removeClass("bc-searchtabactive").addClass("bc-searchtaboff");
		$("#bc-searchtab-let a").removeClass("bc-searchtaboff").addClass("bc-searchtabactive");
		$("#bc-searcharea-let").stop(true, true);
		$("#bc-searcharea-sale").stop(true, true);
		$("#bc-searcharea-sale").fadeOut("fast", function() {
			$("#bc-searcharea-let").fadeIn("fast");
		});
}

var globalLat;
var globalLng;
var globalId;

var listingMap;
var propertyMap;

function InitPropertyMaps()
{
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=gmapInitDone";
	window.gmapInitDone = function() {
		listingMap = InitMap(54.597269,-5.930109,"bc-mappopoutcanvas-list");
		if($("#bc-mappopoutcanvas-property").length) {
			propertyMap = InitMap(54.597269,-5.930109,"bc-mappopoutcanvas-property");
		}
		gMapsLoaded();
	};
	document.body.appendChild(script);	
}

function InitMap(lat,lng,id) {
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    return new google.maps.Map(document.getElementById(id),
        myOptions);
}

function AddPropertyMarker(map, prop)
{
var toLetImage = new google.maps.MarkerImage('/Branches/Bladon/BladonAndCo/Files/Images/map-tolet.png',
      new google.maps.Size(30, 30),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 30));
	var forSaleImage = new google.maps.MarkerImage('/Branches/Bladon/BladonAndCo/Files/Images/map-forsale.png',
      new google.maps.Size(30, 30),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 30));
	  
	var latlng = new google.maps.LatLng(prop.lat, prop.lng);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		icon: prop.forSale == true ? forSaleImage : toLetImage,
		title: prop.title,
		zIndex: 0
	});
	var propInfoWindow = new google.maps.InfoWindow({
		content: "<div class=\"infoWindow\"><img src=\"/Branches/Bladon/BladonAndCo/Files/Images/map-logo.jpg\" style=\"padding-right:5px;\" class=\"infoWindowLogo\"><div class=\"infoWindowText\"><div class=\"infoWindowTitle\">"+prop.title+"</div><div class=\"infoWindowMoreInfoLink\"><a href=\""+prop.moreInfoLink+"\">Click here for more info &raquo;</a></div><div class=\"infoWindowStreetViewLink\"><a href=\""+prop.streetViewLink+"\" target=\"_blank\">See on streetview &raquo;</a></div><div class=\"infoWindowPhone\">"+prop.phone+"</div></div><div style=\"clear:both;\"></div></div>"
	});
		
	google.maps.event.addListener(marker, 'click', function() {
	  propInfoWindow.open(map,marker);
	});
	
	google.maps.event.addListener(map, 'idle', function() {
		propInfoWindow.open(map,marker);
	});
}

var markersLoaded = 0;
var markersTotal = 0;
var saleMap = null;
var letMap = null;

var allMarker = null;
var saleMarker = null;
var letMarker = null;

function InitAllMarkers(map, markerJson)
{

	saleMap = InitMap(54.597269,-5.930109, "bc-mappopoutcanvas-sale");
	letMap = InitMap(54.597269,-5.930109, "bc-mappopoutcanvas-let");
	
	markersTotal = markerJson.properties.length - 1;
	var toLetImage = new google.maps.MarkerImage('/Branches/Bladon/BladonAndCo/Files/Images/map-tolet.png',
      new google.maps.Size(30, 30),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 30));
	var forSaleImage = new google.maps.MarkerImage('/Branches/Bladon/BladonAndCo/Files/Images/map-forsale.png',
      new google.maps.Size(30, 30),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 30));
	 
	 var markerArray = new Array();
	 var saleArray = new Array();
	 var letArray = new Array();
	 var propInfos = new Array();
	 var propInfosSale = new Array();
	 var propInfosLet = new Array();
	 
	for(var i =0; i<markerJson.properties.length; i++)
	{
		var prop = markerJson.properties[i];
		var lat = prop.latlng.split(',')[0];
		var lng = prop.latlng.split(',')[1];
		var latlng = new google.maps.LatLng(lat, lng);
		markerArray[i] = new google.maps.Marker({
			position: latlng,
			map: map,
			icon: prop.forSale == true ? forSaleImage : toLetImage,
			title: prop.title,
			zIndex: i
		});
		if(prop.forSale) {
			saleArray[i] = new google.maps.Marker({
				position: latlng,
				map: saleMap,
				icon: forSaleImage,
				title: prop.title,
				zIndex: i
			});
		}
		else {
			letArray[i] = new google.maps.Marker({
				position: latlng,
				map: letMap,
				icon: toLetImage,
				title: prop.title,
				zIndex: i
			});
		}
		
		var phone = prop.branch == "Belfast" ? "028 9002 7000" : "028 3844 2000";
		var streetViewLink = "http://maps.google.com/?cbll="+prop.latlng+"&cbp=12,20.09,,0,5&layer=c";
		
		propInfos[i] = new google.maps.InfoWindow({
			content: "<div class=\"infoWindow\"><img src=\"/Branches/Bladon/BladonAndCo/Files/Images/map-logo.jpg\" style=\"padding-right:5px;\" class=\"infoWindowLogo\"><div class=\"infoWindowText\"><div class=\"infoWindowTitle\">"+prop.title+"</div><div class=\"infoWindowMoreInfoLink\"><a href=\""+prop.moreInfoLink+"\">Click here for more info &raquo;</a></div><div class=\"infoWindowStreetViewLink\"><a href=\""+streetViewLink+"\" target=\"_blank\">See on streetview &raquo;</a></div><div class=\"infoWindowPhone\">"+phone+"</div></div><div style=\"clear:both;\"></div></div>"
		});
		propInfosSale[i] = new google.maps.InfoWindow({
			content: "<div class=\"infoWindow\"><img src=\"/Branches/Bladon/BladonAndCo/Files/Images/map-logo.jpg\" style=\"padding-right:5px;\" class=\"infoWindowLogo\"><div class=\"infoWindowText\"><div class=\"infoWindowTitle\">"+prop.title+"</div><div class=\"infoWindowMoreInfoLink\"><a href=\""+prop.moreInfoLink+"\">Click here for more info &raquo;</a></div><div class=\"infoWindowStreetViewLink\"><a href=\""+streetViewLink+"\" target=\"_blank\">See on streetview &raquo;</a></div><div class=\"infoWindowPhone\">"+phone+"</div></div><div style=\"clear:both;\"></div></div>"
		});
		propInfosLet[i] = new google.maps.InfoWindow({
			content: "<div class=\"infoWindow\"><img src=\"/Branches/Bladon/BladonAndCo/Files/Images/map-logo.jpg\" style=\"padding-right:5px;\" class=\"infoWindowLogo\"><div class=\"infoWindowText\"><div class=\"infoWindowTitle\">"+prop.title+"</div><div class=\"infoWindowMoreInfoLink\"><a href=\""+prop.moreInfoLink+"\">Click here for more info &raquo;</a></div><div class=\"infoWindowStreetViewLink\"><a href=\""+streetViewLink+"\" target=\"_blank\">See on streetview &raquo;</a></div><div class=\"infoWindowPhone\">"+phone+"</div></div><div style=\"clear:both;\"></div></div>"
		});
			
		google.maps.event.addListener(markerArray[i], 'click', function(e) {
		  propInfos[this.zIndex].open(map,markerArray[this.zIndex]);
		  if(allMarker != null	) {
			allMarker.close();
		  }
		  allMarker = propInfos[this.zIndex];
		});
		if(prop.forSale) {
		google.maps.event.addListener(saleArray[i], 'click', function(e) {
		  propInfosSale[this.zIndex].open(saleMap,saleArray[this.zIndex]);
		  if(saleMarker != null) {
			saleMarker.close();
		  }
		  saleMarker = propInfosSale[this.zIndex];
		});
		}
		else {
		google.maps.event.addListener(letArray[i], 'click', function(e) {
		  propInfosLet[this.zIndex].open(letMap,letArray[this.zIndex]);
		  if(letMarker != null) {
			letMarker.close();
		  }
		  letMarker = propInfosLet[this.zIndex];
		});
		}
	}
	google.maps.event.addListenerOnce(map, 'idle', function(){
		$(".bc-propertyloading").fadeOut("slow");
	});
}

function getQueryStringByName(name, scope)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(scope);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
