/* GOOGLE MAPS */

var google_maps = new Object();
google_maps.controls = true;
google_maps.maps = new Array();

google_maps.mapViews = new Array();
google_maps.streetView_loaded = new Array()

// google_maps.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBQY-Bcq95I3vOFl3kSSbPnZZREduhR8DS5MFv2klQYV0RPTSzmggSjXug'; // 2113.proof.acms.artavia.co.uk
// google_maps.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBQ121kA1_oxg_SB0CnmhMbXG2awDRSsYTqczxz9zHLvwrT4_Oj074ChHg'; // 2113.acms.server8.artavia.co.uk
google_maps.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBSXg49vfc-c0NLZCEJ1FZw7YTPi_xTz5f_9BBpiqfMrvUvM7e-EgqtR7w' // www.webbers.co.uk
google_maps.apiReady = false;

google_maps.create = function(wrapperId, ready_callback){
	google_maps.wrapperId = wrapperId;
	google_maps.ready_callback = ready_callback;
	
	if(google_maps.apiReady){
		google_maps.api_ready();
	}
	else{
		var script = document.createElement("script");
		script.src = "http://www.google.com/jsapi?key=" + google_maps.apiKey + "&callback=google_maps.api_ready";
		script.type = "text/javascript";
		document.getElementsByTagName("head")[0].appendChild(script);
	}
}

google_maps.api_ready = function(){
	google_maps.apiReady = true;
	google.load("maps", "2", {"callback" : google_maps.maps_ready});
}

google_maps.displayStreetView = function(id, position){
	if ( position == null ) {
		// The geocoder didn't find anything...
		$('#streetView_wrapper_' + id).html('Sorry, no street view is available for this address');
	} else {
		// Use Streetview Client object to find nearest camera.
		var gStreetView = new GStreetviewClient();
		gStreetView.getNearestPanoramaLatLng(
			position,
			function ( camera ) {
				if ( camera == null ) {
					// No near-by camera found.
					$('#streetView_wrapper_' + id).html('Sorry, no street view is available for this address');
				} else {
					
					// We have to know which direction to point the camera, so we calculate the
					// bearing between the address position and the camera position.
					var bearing = LatLon.bearing( camera.lat(), camera.lng(), position.lat(), position.lng() );
					
					// To point the camera in that direct, we have to pass a "Point of View" object.
					var pov = { yaw: bearing };

					// Now we put the street view on the page.
					$('#streetView_wrapper_' + id).html('');
					google_maps.streetView = new GStreetviewPanorama(document.getElementById('streetView_wrapper_' + id));
					google_maps.streetView.setLocationAndPOV( camera, pov );
				}
			}
		)
	}
}

google_maps.switchStreetView = function(id){
	if(google_maps.mapViews[id] == 'map'){
		
		if(!google_maps.streetView_loaded[id]){
			
			$('#streetView_wrapper_' + id).html('Loading street view...');
			
			// Flag as loaded
			google_maps.streetView_loaded[id] = true;
			
			if(typeof(google_maps.streetViewCoords) == 'object'){
				var position = new GLatLng(google_maps.streetViewCoords[0], google_maps.streetViewCoords[1]);
				google_maps.displayStreetView(id, position)
			}
			else{
				// Create Geocoder Object.
				var gGeocoder = new GClientGeocoder();
				
				// Attempt to get Lat/Lng for address
				gGeocoder.getLatLng(
					google_maps.streetViewAddress,
					function( position ) {
						google_maps.displayStreetView(id, position)
					}
				);
			}
			
			//var coords = new GLatLng(google_maps.streetView_lat, google_maps.streetView_lng);
			//var panoramaOptions = { latlng:coords };
			//google_maps.streetView = new GStreetviewPanorama(document.getElementById("streetView_wrapper_" + id), panoramaOptions);
			//google_maps.streetView_loaded[id] = true;
		}
		
		$('#streetView_wrapper_' + id).css('display', 'block');
		$('#gmap_wrapper_' + id).css('display', 'none');
		
		$('#google_maps_streetView_link_' + google_maps.currMap).html('Switch to map view');
		
		google_maps.mapViews[id] = 'street';
	}
	else{
		$('#google_maps_streetView_link_' + google_maps.currMap).html('Switch to street view');
		
		$('#streetView_wrapper_' + id).css('display', 'none');
		$('#gmap_wrapper_' + id).css('display', 'block');
		
		google_maps.mapViews[id] = 'map';
	}
}

google_maps.maps_ready = function(){
	
	google_maps.currMap = google_maps.maps.length;
	
	$('#' + google_maps.wrapperId).css('position','relative');
	if(google_maps.streetViewAddress){
		$('#' + google_maps.wrapperId).append('<a id="google_maps_streetView_link_' + google_maps.currMap + '" class="google_maps_streetView_link" href="javascript:google_maps.switchStreetView(\'' + google_maps.currMap + '\');">Switch to street view</a>');
	}
	
	var width = $('#' + google_maps.wrapperId).width();
	var height = $('#' + google_maps.wrapperId).height();
	
	$('#' + google_maps.wrapperId).append('<div id="gmap_wrapper_' + google_maps.currMap + '"></div>');
	$('#gmap_wrapper_' + google_maps.currMap).css({
		width: width + 'px',
		height: height + 'px'
	});
	
	$('#' + google_maps.wrapperId).append('<div id="streetView_wrapper_' + google_maps.currMap + '"></div>');
	$('#streetView_wrapper_' + google_maps.currMap).css({
		width: width + 'px',
		height: height + 'px',
		display: 'none'
	});
	
	google_maps.wrapperId = 'gmap_wrapper_' + google_maps.currMap;
	google_maps.maps[google_maps.currMap] = new google.maps.Map2(document.getElementById(google_maps.wrapperId));
	
	GEvent.addListener(google_maps.maps[google_maps.currMap], "movestart", google_maps.hidePropertyPopup);
	
	google_maps.mapViews[google_maps.currMap] = 'map';
	
	if(google_maps.controls == true){
		google_maps.maps[google_maps.currMap].addControl(new GLargeMapControl3D());
		google_maps.maps[google_maps.currMap].addControl(new GMenuMapTypeControl());
	}
	else if(google_maps.controlsSmall == true){
		google_maps.maps[google_maps.currMap].addControl(new GLargeMapControl());
	}
	else{
		google_maps.maps[google_maps.currMap].disableDragging();
	}
	
	if(typeof(google_maps.ready_callback) == 'function'){
		google_maps.ready_callback();
	}
}

google_maps.importanceOrder = function(marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

google_maps.addCharMarker = function(lat, lng, char, hoverCallback){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	google_maps.streetView_lat = lat;
	google_maps.streetView_lng = lng;
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.iconSize = new GSize(26, 26);
	baseIcon.shadow = '';
	baseIcon.iconAnchor = new GPoint(11, 9);

	var letteredIcon = new GIcon(baseIcon);
	
	if(char == ''){
		letteredIcon.image = "/modules/properties/gmapIcon/images/propertyBlank.png";
	}
	else{
		letteredIcon.image = "/modules/properties/gmapIcon/index.php?char=" + char;
	}
	
	// zIndexProcess - force these markers to have a higher z-index than the office markers
	if($.browser.msie && parseInt($.browser.version) == 8){
		markerOptions = { icon:letteredIcon };
	}
	else{
		markerOptions = { icon:letteredIcon, zIndexProcess:google_maps.importanceOrder };
	}
	
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, markerOptions);
	
	if(typeof(hoverCallback) == 'function'){
		GEvent.addListener(marker, "mouseover", hoverCallback);
	}
	
	google_maps.maps[google_maps.currMap].addOverlay(marker);
	
}

google_maps.addOfficeMarker = function(lat, lng, name, hoverCallback){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	google_maps.streetView_lat = lat;
	google_maps.streetView_lng = lng;
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.iconSize = new GSize(26, 26);
	baseIcon.shadow = '';
	baseIcon.iconAnchor = new GPoint(11, 9);

	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "/modules/properties/gmapIcon/images/webbers.png";
	markerOptions = { icon:letteredIcon };
	
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, markerOptions);
	
	if(typeof(hoverCallback) == 'function'){
		GEvent.addListener(marker, "mouseover", hoverCallback);
	}
	
	google_maps.maps[google_maps.currMap].addOverlay(marker);
	
}

google_maps.latLngToPixels = function(lat, lng){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	var point = new GLatLng(lat, lng);
	
	var zoom = google_maps.maps[google_maps.currMap].getZoom();	
	var projection = G_NORMAL_MAP.getProjection();
	
	var bounds = google_maps.maps[google_maps.currMap].getBounds();
	var ne = bounds.getNorthEast();
	var sw = bounds.getSouthWest();
	var upperLeft_lat = ne.lat();
	var upperLeft_lng = sw.lng();
	var upperLeftPoint = new GLatLng(upperLeft_lat, upperLeft_lng);
	
	var upperLeftPixel = projection.fromLatLngToPixel(upperLeftPoint, zoom);
	var markerPixel = projection.fromLatLngToPixel(point, zoom);

	var x = markerPixel.x - upperLeftPixel.x;
	var y = markerPixel.y - upperLeftPixel.y;
	
	return [x,y];
}

google_maps.hidePropertyPopup = function(){
	$('#map_popup').hide();
}

google_maps.officePopup = function(lat, lng, name){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	var xy = google_maps.latLngToPixels(lat, lng);
	
	var gmap_width = $('#gmap').width();
	var gmap_height = $('#gmap').height();
	
	$('#map_popup').removeClass('tr').removeClass('tl').removeClass('bl').removeClass('br');
	$('#map_popup').removeClass('office_tr').removeClass('office_tl').removeClass('office_bl').removeClass('office_br');
	$('#map_popup').removeClass('property_tr').removeClass('property_tl').removeClass('property_bl').removeClass('property_br');
	
	if(xy[0] > (gmap_width / 2)){
		if(xy[1] > (gmap_height / 2)){
			// Bottom Right
			$('#map_popup').addClass('br').addClass('office_br');
			xy[0] -= 214;
			xy[1] -= 88;
		}
		else{
			// Top Right
			$('#map_popup').addClass('tr').addClass('office_tr');
			xy[0] -= 214;
			xy[1] -= 18;
		}
	}
	else{
		if(xy[1] > (gmap_height / 2)){
			// Bottom Left
			$('#map_popup').addClass('bl').addClass('office_bl');
			xy[0] -= 0;
			xy[1] -= 88;
		}
		else{
			// Top Left
			$('#map_popup').addClass('tl').addClass('office_tl');
			xy[0] -= 0;
			xy[1] -= 18;
		}
	}
	
	$('#map_popup').show().css({
		left: xy[0] + 'px',
		top: xy[1] + 'px'
	});
	
	google_maps.officePopup_view(name);
}

google_maps.officePopup_view = function(name){
	
	$('#map_popup .padding').html('Loading...');
	
	clearTimeout(google_maps.propertyPopup_viewTimeout);
	google_maps.propertyPopup_viewTimeout = setTimeout(function(){
	
		var ajaxUrl = '/modules/properties/ajax.php';
		var ts = new Date().getTime();
		$.ajax({
			type: "GET",
			url: ajaxUrl,
			data: 'officeMap_details=' + name + '&_' + ts,
			success: function(html){
				$('#map_popup .padding').html(html);
			}
		});
	
	}, 500);
}

google_maps.propertyPopup = function(lat, lng, idSet){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	delete google_maps.propertyIdSet;
	google_maps.propertyIdSet = idSet.split(',');
	
	var xy = google_maps.latLngToPixels(lat, lng);
	
	var gmap_width = $('#gmap').width();
	var gmap_height = $('#gmap').height();
	
	$('#map_popup').removeClass('tr').removeClass('tl').removeClass('bl').removeClass('br');
	$('#map_popup').removeClass('office_tr').removeClass('office_tl').removeClass('office_bl').removeClass('office_br');
	$('#map_popup').removeClass('property_tr').removeClass('property_tl').removeClass('property_bl').removeClass('property_br');
	
	if(xy[0] > (gmap_width / 2)){
		if(xy[1] > (gmap_height / 2)){
			// Bottom Right
			$('#map_popup').addClass('br').addClass('property_br');
			xy[0] -= 214;
			xy[1] -= 227;
		}
		else{
			// Top Right
			$('#map_popup').addClass('tr').addClass('property_tr');
			xy[0] -= 214;
			xy[1] -= 18;
		}
	}
	else{
		if(xy[1] > (gmap_height / 2)){
			// Bottom Left
			$('#map_popup').addClass('bl').addClass('property_bl');
			xy[0] -= 0;
			xy[1] -= 227;
		}
		else{
			// Top Left
			$('#map_popup').addClass('tl').addClass('property_tl');
			xy[0] -= 0;
			xy[1] -= 18;
		}
	}
	
	$('#map_popup').show().css({
		left: xy[0] + 'px',
		top: xy[1] + 'px'
	});
	
	google_maps.propertyPopup_view(google_maps.propertyIdSet[0]);
}

google_maps.propertyPopup_view = function(propId){
	
	$('#map_popup .padding').html('Loading...');
	
	clearTimeout(google_maps.propertyPopup_viewTimeout);
	google_maps.propertyPopup_viewTimeout = setTimeout(function(){
	
		var total = google_maps.propertyIdSet.length;
		for(var i in google_maps.propertyIdSet){
			if(google_maps.propertyIdSet[i] == propId){
				var currentIndex = i;
			}
		}
		
		var ajaxUrl = '/modules/properties/ajax.php';
		var ts = new Date().getTime();
		$.ajax({
			type: "GET",
			url: ajaxUrl,
			data: 'search_googleMaps_propertyPopup&propId=' + propId + '&idSet=' + google_maps.propertyIdSet.join(',') + '&currentIndex=' + currentIndex + '&_' + ts,
			success: function(html){
				$('#map_popup .padding').html(html);
			}
		});
	
	}, 500);
}

google_maps.addDefaultMarker = function(lat, lng){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	var point = new GLatLng(lat, lng);
	google_maps.maps[google_maps.currMap].addOverlay(new GMarker(point));
}

google_maps.center = function(lat, lng, zoom){
	
	lat = parseFloat(lat);
	lng = parseFloat(lng);
	
	google_maps.maps[google_maps.currMap].setCenter(new google.maps.LatLng(lat, lng), zoom);
}

/* SEARCH MAP */

var search_map = new Object();
	
search_map.init = function(){
	search_map.xml = '';
	search_map.offices = new Array();
}

search_map.addOfficeMarkers = function(){
	$('#search_map_wrapper .office').remove();
	
	if(typeof(search_map.xml) == 'object'){
		search_map.parseXML(search_map.xml);
	}
	else{
		var xmlUrl = '/modules/properties/ajax.php?offices';
		$.ajax({
			type: "GET",
			url: xmlUrl,
			success: function(xml){
				search_map.xml = xml;
				search_map.parseXML(search_map.xml);
			}
		});
	}
}

search_map.parseXML = function(xml){
	
	$(xml).find('office').each(function(){
		var name = $(this).attr('name');
		var ocode = $(this).attr('ocode');
		var x = parseInt($(this).attr('markerX'));
		var y = parseInt($(this).attr('markerY'));
		search_map.addOfficeMarker(name, ocode, x, y);
	});
}

search_map.addOfficeMarker = function(name, ocode, x, y){
	var key = ocode;
	
	search_map.offices[key] = new Object();
	
	search_map.offices[key].name = name;
	search_map.offices[key].ocode = ocode;
	search_map.offices[key].x = x;
	search_map.offices[key].y = y;
	
	var marker = '<a href="javascript:;" onClick="search_map.selectOffice(\'' + ocode + '\')" class="office" id="office_' + key + '">' + name + '</a>';
	$('#search_map_wrapper .inner').append(marker);
	
	$('#office_'+key).css({
		left: x + 'px',
		top: y + 'px'
	});
}

search_map.selectOffice = function(ocode){
	
	var office = search_map.offices[ocode];
	if( $('#office_search_row_' + ocode).length == 0 ){
		$('#office_search_fields ul').append('<li id="office_search_row_' + ocode + '">' + office.name + '<input type="hidden" name="offices[' + ocode + ']" value="' + ocode + '" /></li>');
		$('#office_' + ocode).addClass('selected').blur();
	}
	else{
		$('#office_search_row_' + ocode).remove();
		$('#office_' + ocode).removeClass('selected').blur();
	}
	
	search_form.numResults();
	
}

search_map.selectAll = function(){
	$('#search_map_wrapper .office').each(function(){
		var clickAction = $(this).attr('onClick');
		
		if($.browser.msie){ clickAction(); }
		else{ eval(clickAction); }
	});
}

search_map.deselectAll = function(){
	$('#office_search_fields ul').html('');
	$('#search_map_wrapper .office').each(function(){
		$(this).removeClass('selected');
	});
	search_form.numResults();
}

search_map.show = function(){
	
	search_form.clearRefPoint();
	$('#location').val('');
	
	if($('#search_map_wrapper .inner').length == 0){
		
		var mapInsert = '<div id="search_map_wrapper"><div class="inner">';
		mapInsert += '<a class="inner_back_link" href="javascript:search_map.hide();">&lt; Back to location property search</a>';
		
		// Select/De-select
		mapInsert += '<div id="search_map_select">';
		mapInsert += '<p>Click on location name to select office</p>';
		mapInsert += '<p>To deselect, click office name again</p>';
		mapInsert += '<a href="javascript:search_map.selectAll();">Select All</a>';
		mapInsert += '<a href="javascript:search_map.deselectAll();">Deselect All</a>';
		mapInsert += '</div>';
		
		mapInsert += '</div></div>';
				
		if( $('#search_home').length == 1 ){
			
			if($('#search_map_replace_contents').length == 0){
				var html = $('#search_home').html();
				$('#search_home').html('<div id="search_map_replace_contents">' + html + '</div>');
			}
			
			$('#search_map_replace_contents').hide();
			$('#search_home').prepend(mapInsert);
		}
		else{
			
			if($('#search_map_replace_contents').length == 0){
				var html = $('.main_content .right_column').html();
				$('.main_content .right_column').html('<div id="search_map_replace_contents">' + html + '</div>');
			}
			
			$('#search_map_replace_contents').hide();
			$('.main_content .right_column').prepend(mapInsert);

		}

		search_map.addOfficeMarkers();
	}

	$('#search_map_wrapper').css('display','block');
	$('#office_search').css('display','block');
	$('#location_search').css('display','none');
	
	$("#mainSearch").css({'borderRight':'none','height' : '387px'});
	$(".mainSearch").css({'background' : 'none'});
};

search_map.hide = function(){
	search_map.deselectAll();
	
	$('#search_map_wrapper').remove();
	$('#office_search').css('display','none');	
	$('#location_search').css('display','block');
	
	$('#search_map_replace_contents').show();
	
	$(".mainSearch fieldset").css({'borderRight':'1px solid #F22542','height' : 'auto'})
	$(".three_column_layout_sig .mainSearch fieldset").css({'borderRight':'1px solid #C3DFEC','height' : 'auto'})
	$(".three_column_layout_fine .site_wrapper .content_holder_ls .left_col #search_results_form_wrapper #placeholderSearch .search #search_form #mainSearch").css({'borderRight':'1px solid #867D54'});
	$(".mainSearch").css({'background' : '#E6E6E6'});

};

$(document).ready(search_map.init);

/* SEARCH RESULTS */

var search_results = new Object();

search_results.init = function(){
	$('#search_results_sort').change(search_results.changeOrder);
	$('#search_results_per_page').change(search_results.changePerPage);
	$('#propertyBookmarks_sort').change(search_results.propertyBookmarks_changeOrder);
}

search_results.changeOrder = function(){
	var url = $('#search_results_sort').val();
	window.location.href = url;
}

search_results.propertyBookmarks_changeOrder = function(){
	var url = $('#propertyBookmarks_sort').val();
	window.location.href = url;
}

search_results.changePerPage = function(){
	var url = $('#search_results_per_page').val();
	window.location.href = url;
}

$(document).ready(search_results.init);

/* PROPERTY BOOKMARKING */

var property_bookmarks = new Object();

property_bookmarks.add = function(id){
	
	if($('.propertyBookmark_saveLink_' + id + ' img').length == 0){
		$('.propertyBookmark_saveLink_' + id).append('<img src="/images/ajax-loader.gif">');
	}
	$('.propertyBookmark_saveLink_' + id).blur();
	
	var ajaxUrl = '/modules/properties/ajax.php';
	var ts = new Date().getTime();
	$.ajax({
		type: "GET",
		url: ajaxUrl,
		data: 'propertyBookmarks_add=' + id + '&_' + ts,
		success: function(){
			property_bookmarks.updateStatus();
		}
	});
}

property_bookmarks.remove = function(id){
	
	$('#property_' + id).prepend('<img class="property_activity" src="/images/ajax-loader.gif">');
	
	var ajaxUrl = '/modules/properties/ajax.php';
	var ts = new Date().getTime();
	$.ajax({
		type: "GET",
		url: ajaxUrl,
		data: 'propertyBookmarks_remove=' + id + '&_' + ts,
		success: function(){
			$('#property_' + id).remove();
			property_bookmarks.updateStatus();
		}
	});
}

property_bookmarks.updateStatus = function(){
	var ajaxUrl = '/modules/properties/ajax.php';
	var ts = new Date().getTime();
	$.ajax({
		type: "GET",
		url: ajaxUrl,
		data: 'propertyBookmarks_status' + '&_' + ts,
		success: function(xml){
			
			var total = $(xml).find('total').text();
			$('.propertyBookmarks_totalSaved').html(total);
			
			$(xml).find('idSet id').each(function(){
				var id = $(this).text();
				$('.propertyBookmark_saveLink_' + id + ' img').remove();
				$('.propertyBookmark_saveLink_' + id).html('SAVED').addClass('saved');
			});
			
		}
	});	
	
}

/* PROPERTY DETAILS */

var property_details = new Object();

property_details_clickToFocusThumbs = false;

property_details.updateImgInfo = function(){
	//$('#property_details_gallery_controls .controls .current').html((property_details.img_current + 1) + ' of ' + property_details.img_count);
	$('#property_details_gallery_controls .controls .current').html(property_details.currSet + ' of ' + property_details.setCount);
	$('#property_details_gallery_controls .info').html('Picture ' + (property_details.img_current + 1));
}

property_details.nextSet = function(){
	property_details.currSet++;
	if(property_details.currSet > property_details.setCount){
		property_details.currSet = 1;
	}
	property_details.refreshSet();
	property_details.updateImgInfo();
}

property_details.prevSet = function(){
	property_details.currSet--;
	if(property_details.currSet < 1){
		property_details.currSet = property_details.setCount;
	}
	property_details.refreshSet();
	property_details.updateImgInfo();
}

property_details.refreshSet = function(){
	$('.property_details_gallery .thumbs .thumbSet').css('display','none');
	$('#thumbSet_' + property_details.currSet).css('display','block');
}

property_details.nextImg = function(){
	property_details.img_current++;
	if(property_details.img_current >= property_details.img_count){
		property_details.img_current = 0;
	}
	
	property_details.showFullSizeImage(property_details.img_current);
	property_details.updateImgInfo();
}

property_details.prevImg = function(){
	property_details.img_current--;
	if(property_details.img_current < 0){
		property_details.img_current = property_details.img_count - 1;
	}
	
	property_details.showFullSizeImage(property_details.img_current);
	property_details.updateImgInfo();
}

property_details.init = function(){
	
	$('a[rel="prettyPhoto[pp_gal]"]').click(function(){
		property_details_clickToFocusThumbs = false;
	});
	
	property_details.currSet = 1;
	property_details.setCount = $('.property_details_gallery .thumbs .thumbSet').length;
	
	var width = 415;
	var height = 315;
	
	property_details.images = new Array();
	
	var key = 0;
	
	property_details.imgCache = new Array();
	
	$('.property_details_gallery .thumbs a[rel^="prettyPhoto"] img').each(function(){
		
		property_details.images[key] = new Object();
		
		var thumb = $(this).attr('src');
		var tmpKey = key;
		
		// Larger Image
			var full = $(this).attr('src');
			full = full.replace(/width=[0-9]+/, 'width=' + width);
			full = full.replace(/height=[0-9]+/, 'height=' + height);
			
			// Preload
			var cacheImage_medium = document.createElement('img');
			cacheImage_medium.src = full;
			property_details.imgCache.push(cacheImage_medium);
		
		// prettyPhoto Image
			var prettyPhoto = $(this).attr('src');
			prettyPhoto = prettyPhoto.replace(/width=[0-9]+/, 'width=' + 800);
			prettyPhoto = prettyPhoto.replace(/height=[0-9]+/, 'height=' + 600);
			
			// Preload
			var cacheImage_large = document.createElement('img');
			cacheImage_large.src = prettyPhoto;
			property_details.imgCache.push(cacheImage_large);
		
		property_details.images[key].thumb = thumb;
		property_details.images[key].full = full;
		property_details.images[key].prettyPhoto = prettyPhoto;
		
		
		$(this).parent().hover(function(){
			if(!property_details_clickToFocusThumbs){
				property_details.img_current = tmpKey;
				property_details.showFullSizeImage(property_details.img_current);
				property_details.updateImgInfo();
			}
		});
		
		key++;
	});
	
	property_details.img_count = $('.property_details_gallery .thumbs img').length;
	property_details.img_current = 0
	
	property_details.updateImgInfo();
}

property_details.playVideoette = function(url){
	property_details_clickToFocusThumbs = true;
	
	$('.property_details_gallery .large_view img').css('display','none');
	$('.property_details_gallery .large_view').append('<div id="videoette"></div>');
	
	$('#videoette').flash({
		'src' : url,
		'width' : '415',
		'height' : '315'
	});
}

property_details.showFullSizeImage = function(key){
	var src = property_details.images[key].full;
	var prettyPhoto_href = property_details.images[key].prettyPhoto;
	
	$('#videoette').remove();
	
	$('.property_details_gallery .large_view img').hide();
	$('.property_details_gallery .large_view').append('<div class="loading">Loading...</div>');
	
	$('<img />').attr('src',src).ready(function(){
		$('.property_details_gallery .large_view img').attr('src', src).show();
		$('.property_details_gallery .large_view a').attr('href', prettyPhoto_href);
		$('.property_details_gallery .large_view .loading').remove();
	});
}

$(document).ready(property_details.init);

/* SEARCH FORM */

var search_form = new Object();

search_form.searchByOffice = function(){
	search_form.clearRefPoint();
	
	$('#office_search').css('display','block');
	$('#location_search').css('display','none');
	
	$('#location').val('');
	search_form.numResults();
}

search_form.searchByLocation = function(){
	search_form.clearRefPoint();
	
	$('#office_search').css('display','none');
	$('#location_search').css('display','block');
	
	$('#office_search_fields li input[type="checkbox"]').attr('checked','');
	search_form.numResults();
}

search_form.setAnyCounty = function(){
	if( $('#county_choices').length == 1 ){
		$('#county_choices input').attr('checked','');
		$('#county_choices input:last').attr('checked','checked');
	}
}

search_form.init = function(){
	search_form.lastData = '';
	search_form.lastChangeInternal = false;
	
	$('#search_form input, #search_form select').change(search_form.numResults).keyup(search_form.numResults); // Get number of results any time a change is made to the form	
	$('#location').keyup(search_form.getSuggestions); // Search suggestions
	
	$('#location').keyup(search_form.setAnyCounty).change(search_form.setAnyCounty); // Set county to "All" when typing in #location field
	
	//$('#location').blur(function(){
		//setTimeout(search_form.removeSuggestions, 100); // Slight delay to ensure suggestion click is captured
	//});
}

search_form.searchQS = function(){
	var dataObj = new Object();
	$('#search_form input[type="hidden"], #search_form input[type="text"], #search_form input[type="checkbox"]:checked, #search_form input[type="radio"]:checked, #search_form select').each(function(){
		var key = $(this).attr('name');
		var val = $(this).val();
		dataObj[key] = val;
	});
	var data = new Array();
	for(var i in dataObj){
		data[data.length] = i + '=' + dataObj[i];
	}
	data = data.join('&');
	return data;
}

search_form.getSuggestions = function(){
	
	if(search_form.lastChangeInternal){
		search_form.lastChangeInternal = false;
		return;
	}
	
	$('#location').addClass('searching');
	
	search_form.clearRefPoint();
	
	clearTimeout(search_form.getSuggestions_timeout);
	search_form.getSuggestions_timeout = setTimeout(function(){
		var ajaxUrl = '/modules/properties/ajax.php';
		var string = escape($('#location').val());
		var data = 'search_suggestion=' + string
		
		$.ajax({
			type: "GET",
			url: ajaxUrl,
			data: data,
			success: function(xml){
				
				$('#location').removeClass('searching');
				$('#search_suggestions').remove();
				$('#location').after('<div id="search_suggestions"><ul></ul></div>');
				
				$(xml).find('suggestion').each(function(){
					var label = $(this).attr('label');
					var matchStr = $(this).attr('match');
					
					var lat = $(this).attr('lat');
					var lng = $(this).attr('lng');
					
					$('#search_suggestions ul').append('<li><a href="javascript:search_form.setLocation(\'' + matchStr + '\', ' + lat + ',' + lng + ');">' + label + '</a></li>');
				});
			}
		});
	}, 1000);
}

search_form.setRefPoint = function(lat, lng){
	$('#propRange_lat').val(lat);
	$('#propRange_lng').val(lng);
	
	if(lat != 0 && lng != 0){
		$('#propRange_choices').css('display','block');
	}
}

search_form.clearRefPoint = function(){
	$('#propRange_choices').css('display','none');
	$('#propRange_lat').val('0');
	$('#propRange_lng').val('0');
}

search_form.setLocation = function(matchStr, lat, lng){
	search_form.lastChangeInternal = true;
	search_form.setRefPoint(lat, lng);
	search_form.removeSuggestions();
	$('#location').val(matchStr);
}

search_form.removeSuggestions = function(){
	$('#search_suggestions').remove();
}

search_form.advancedSearch_selectAll = function(){
	$('#advancedSearch input').attr('checked','checked');
}

search_form.numResults = function(){
	clearTimeout(search_form.numResults_timeout);
	search_form.numResults_timeout = setTimeout(function(){
		
		$('#props_found img').show();
		
		data = search_form.searchQS();
		data += '&search_numResults=true';
		
		if(search_form.lastData == data){
			$('#props_found img').hide();
			return;
		}
		search_form.lastData == data;
		
		$.ajax({
			type: "GET",
			url: "/modules/properties/ajax.php",
			data: data,
			success: function(total){
				$('#props_found img').hide();
				$('#props_found span').html(total);
			}
		});
				
	}, 750);
}

$(document).ready(search_form.init);

/* ----------------------------------------------------------------------- */

(function($){
	$.fn.extend({
		mab_repayment: function(price){
			
			price = parseInt(price);
			var url = '/modules/properties/mab_xml_proxy.php';
			var data = 'ID=488&term=25&propertyprice=' + price;
			
			var elems = this;
			
			$.ajax({
				url: url,
				data: data,
				dataType: 'xml',
				success: function(xml){
					var monthlycostrepayment = parseFloat($(xml).find('monthlycostrepayment').text());
					
					elems.each(function(){
						$(this).html('&pound;' + monthlycostrepayment);
					});
				}
			});
			
		},
	
		tfs_repayment: function(price){
			
			var PP = price;
			var DP = 25;
			var DA = 0;
			var A = 0;
			var T = 25;
			var R = 0;
			
			var lowestdepositamount = 5;
		
			A = Math.round(PP-DA)
		
			if (DP < 10) {
				R = 4.99
			}
			else if (DP < 15) {
				R = 4.29
			}
			else if (DP < 20) {
				R = 3.19
			}
			else if (DP < 25) {
				R = 2.49
			}
			else if (DP < 40) {
				R = 1.99
			}
			else {
				R = 2.19
			}
		
			DA = PP/100 * DP
			A = PP-DA
		
			R = R / 100;
			var P = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T))));
			P = Math.round(P * 100) / 100; // 2 decimal places
			
			return this.each(function(){
				$(this).html('&pound;' + P);
			});
		}
	});
})(jQuery);  

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*  Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2009            */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

/*
 * Use Haversine formula to calculate distance (in km) between two points specified by
 * latitude/longitude (in numeric degrees)
 *
 * from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine",
 *       Sky and Telescope, vol 68, no 2, 1984
 *       http://www.census.gov/cgi-bin/geo/gisfaq?Q5.1
 *
 * example usage from form:
 *   result.value = LatLon.distHaversine(lat1.value.parseDeg(), long1.value.parseDeg(),
 *                                       lat2.value.parseDeg(), long2.value.parseDeg());
 * where lat1, long1, lat2, long2, and result are form fields
 */
LatLon.distHaversine = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad();
  lat1 = lat1.toRad(), lat2 = lat2.toRad();

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1) * Math.cos(lat2) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}


/*
 * Use Law of Cosines to calculate distance (in km) between two points specified by latitude/longitude
 * (in numeric degrees).
 */
LatLon.distCosineLaw = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var d = Math.acos(Math.sin(lat1.toRad())*Math.sin(lat2.toRad()) +
                    Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*Math.cos((lon2-lon1).toRad())) * R;
  return d;
}


/*
 * calculate (initial) bearing between two points
 *   see http://williams.best.vwh.net/avform.htm#Crs
 */
LatLon.bearing = function(lat1, lon1, lat2, lon2) {
  lat1 = lat1.toRad(); lat2 = lat2.toRad();
  var dLon = (lon2-lon1).toRad();

  var y = Math.sin(dLon) * Math.cos(lat2);
  var x = Math.cos(lat1)*Math.sin(lat2) -
          Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
  return Math.atan2(y, x).toBrng();
}


/*
 * calculate midpoint of great circle line between p1 & p2.
 *   see http://mathforum.org/library/drmath/view/51822.html for derivation
 */
LatLon.midPoint = function(lat1, lon1, lat2, lon2) {
  lat1 = lat1.toRad();
  lat2 = lat2.toRad();
  var dLon = (lon2-lon1).toRad();

  var Bx = Math.cos(lat2) * Math.cos(dLon);
  var By = Math.cos(lat2) * Math.sin(dLon);

  lat3 = Math.atan2(Math.sin(lat1)+Math.sin(lat2),
                    Math.sqrt((Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By ) );
  lon3 = lon1.toRad() + Math.atan2(By, Math.cos(lat1) + Bx);

  if (isNaN(lat3) || isNaN(lon3)) return null;
  return new LatLon(lat3.toDeg(), lon3.toDeg());
}


/*
 * calculate destination point given start point, initial bearing (deg) and distance (km)
 *   see http://williams.best.vwh.net/avform.htm#LL
 */
LatLon.prototype.destPoint = function(brng, d) {
  var R = 6371; // earth's mean radius in km
  var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
  brng = brng.toRad();

  var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) +
                        Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );
  var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
                               Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
  lon2 = (lon2+Math.PI)%(2*Math.PI) - Math.PI;  // normalise to -180...+180

  if (isNaN(lat2) || isNaN(lon2)) return null;
  return new LatLon(lat2.toDeg(), lon2.toDeg());
}


/*
 * calculate final bearing arriving at destination point given start point, initial bearing and distance
 */
LatLon.prototype.finalBrng = function(brng, d) {
  var p1 = this, p2 = p1.destPoint(brng, d);
  // get reverse bearing point 2 to point 1
  var rev = LatLon.bearing(p2.lat, p2.lon, p1.lat, p1.lon);
  // & reverse it by adding 180°
  var brng = (rev + 180) % 360;
  return brng;
}


/*
 * calculate distance, bearing, destination point on rhumb line
 *   see http://williams.best.vwh.net/avform.htm#Rhumb
 */
LatLon.distRhumb = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var dLat = (lat2-lat1).toRad(), dLon = Math.abs(lon2-lon1).toRad();
  var dPhi = Math.log(Math.tan(lat2.toRad()/2+Math.PI/4)/Math.tan(lat1.toRad()/2+Math.PI/4));
  var q = (Math.abs(dLat) > 1e-10) ? dLat/dPhi : Math.cos(lat1.toRad());
  // if dLon over 180° take shorter rhumb across 180° meridian:
  if (dLon > Math.PI) dLon = 2*Math.PI - dLon;
  var d = Math.sqrt(dLat*dLat + q*q*dLon*dLon);
  return d * R;
}


LatLon.brngRhumb = function(lat1, lon1, lat2, lon2) {
  var dLon = (lon2-lon1).toRad();
  var dPhi = Math.log(Math.tan(lat2.toRad()/2+Math.PI/4)/Math.tan(lat1.toRad()/2+Math.PI/4));
  if (Math.abs(dLon) > Math.PI) dLon = dLon>0 ? -(2*Math.PI-dLon) : (2*Math.PI+dLon);
  return Math.atan2(dLon, dPhi).toBrng();
}


LatLon.prototype.destPointRhumb = function(brng, dist) {
  var R = 6371; // earth's mean radius in km
  var d = parseFloat(dist)/R;  // d = angular distance covered on earths surface
  var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
  brng = brng.toRad();

  var lat2 = lat1 + d*Math.cos(brng);
  var dLat = lat2-lat1;
  var dPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4));
  var q = (Math.abs(dLat) > 1e-10) ? dLat/dPhi : Math.cos(lat1);
  var dLon = d*Math.sin(brng)/q;
  // check for some daft bugger going past the pole
  if (Math.abs(lat2) > Math.PI/2) lat2 = lat2>0 ? Math.PI-lat2 : -(Math.PI-lat2);
  lon2 = (lon1+dLon+Math.PI)%(2*Math.PI) - Math.PI;

  if (isNaN(lat2) || isNaN(lon2)) return null;
  return new LatLon(lat2.toDeg(), lon2.toDeg());
}


/*
 * construct a LatLon object: arguments in numeric degrees
 *
 * note all LatLong methods expect & return numeric degrees (for lat/long & for bearings)
 */
function LatLon(lat, lon) {
  this.lat = lat;
  this.lon = lon;
}


/*
 * represent point {lat, lon} in standard representation
 */
LatLon.prototype.toString = function() {
  return this.lat.toLat() + ', ' + this.lon.toLon();
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

// extend String object with method for parsing degrees or lat/long values to numeric degrees
//
// this is very flexible on formats, allowing signed decimal degrees, or deg-min-sec suffixed by
// compass direction (NSEW). A variety of separators are accepted (eg 3º 37' 09"W) or fixed-width
// format without separators (eg 0033709W). Seconds and minutes may be omitted. (Minimal validation
// is done).

String.prototype.parseDeg = function() {
  if (!isNaN(this)) return Number(this);                 // signed decimal degrees without NSEW

  var degLL = this.replace(/^-/,'').replace(/[NSEW]/i,'');  // strip off any sign or compass dir'n
  var dms = degLL.split(/[^0-9.]+/);                     // split out separate d/m/s
  for (var i in dms) if (dms[i]=='') dms.splice(i,1);    // remove empty elements (see note below)
  switch (dms.length) {                                  // convert to decimal degrees...
    case 3:                                              // interpret 3-part result as d/m/s
      var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break;
    case 2:                                              // interpret 2-part result as d/m
      var deg = dms[0]/1 + dms[1]/60; break;
    case 1:                                              // decimal or non-separated dddmmss
      if (/[NS]/i.test(this)) degLL = '0' + degLL;       // - normalise N/S to 3-digit degrees
      var deg = dms[0].slice(0,3)/1 + dms[0].slice(3,5)/60 + dms[0].slice(5)/3600; break;
    default: return NaN;
  }
  if (/^-/.test(this) || /[WS]/i.test(this)) deg = -deg; // take '-', west and south as -ve
  return deg;
}
// note: whitespace at start/end will split() into empty elements (except in IE)


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

// extend Number object with methods for converting degrees/radians

Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
  return this * 180 / Math.PI;
}

Number.prototype.toBrng = function() {  // convert radians to degrees (as bearing: 0...360)
  return (this.toDeg()+360) % 360;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

// extend Number object with methods for presenting bearings & lat/longs

Number.prototype.toDMS = function() {  // convert numeric degrees to deg/min/sec
  var d = Math.abs(this);  // (unsigned result ready for appending compass dir'n)
  d += 1/7200;  // add ½ second for rounding
  var deg = Math.floor(d);
  var min = Math.floor((d-deg)*60);
  var sec = Math.floor((d-deg-min/60)*3600);
  // add leading zeros if required
  if (deg<100) deg = '0' + deg; if (deg<10) deg = '0' + deg;
  if (min<10) min = '0' + min;
  if (sec<10) sec = '0' + sec;
  return deg + '\u00B0' + min + '\u2032' + sec + '\u2033';
}

Number.prototype.toLat = function() {  // convert numeric degrees to deg/min/sec latitude
  return this.toDMS().slice(1) + (this<0 ? 'S' : 'N');  // knock off initial '0' for lat!
}

Number.prototype.toLon = function() {  // convert numeric degrees to deg/min/sec longitude
  return this.toDMS() + (this>0 ? 'E' : 'W');
}

Number.prototype.toPrecision = function(fig) {  // override toPrecision method with one which displays
  if (this == 0) return 0;                      // trailing zeros in place of exponential notation
  var scale = Math.ceil(Math.log(this)*Math.LOG10E);
  var mult = Math.pow(10, fig-scale);
  return Math.round(this*mult)/mult;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */


