// All results
$(document).ready(function() {
	$.ajaxSetup({
		cache: false
	});
	$('#site_search_input').addClass("idle_field");
	$('#site_search_input').focus(function() {
		$(this).removeClass("idle_field").addClass("focus_field");
		if (this.value == this.defaultValue){
			this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	$('#site_search_input').blur(function() {
		$(this).removeClass("focus_field").addClass("idle_field");
		if ($.trim(this.value) == '') {
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
	function results() {}
	if ($('#mls_results').length) {
		results();
	}
	$('#action_compare_go').live('click', function(e) {
		if ($('#compareListingsWrap > ul > li:visible').length <= 1) {
				alert('You must select at least two properties to compare.');
				return false;
			} else {
				location.href = $(this).attr('href');
		}
	});
	$('#action_compare_clear').live('click', function() {
		if ($('#compareListingsWrap > ul > li:visible').length) {
			$.ajax({
				type: 'GET',
				url: '/inc/functions.php?action=compare-clear',
				dataType: 'html',
				success: function(response) {
					$('#compareListingsWrap > ul').empty();
					$('input.compare').attr('checked', false);
					$('#compareListingsWrap > ul').append('<li></li>');
				},
				error: function() {
					alert('There was a problem clearing the compare list. Please refresh the page and try again.');
				}
			});
		}
	});
	$('#compareListingsWrap li:first-child').hide();
	$('.compare').live('click', function() {
		var mlsIDSplitter = this.id.split('_');
		var mlsID = mlsIDSplitter[1];
		if (this.checked) {
				if ($('#compareListingsWrap > ul > li:visible').length > 4) {
					alert('You already have the maximum of five properties selected.');
					return false;
				}
				$.ajax({
					type: 'GET',
					url: '/inc/functions.php?action=compare-add&id=' + mlsID,
					dataType: 'html',
					success: function(response) {
						$('#compareListingsWrap li:first-child').before('<li id="compare_' + mlsID + '"><a href="javascript:void(0);" onclick="return false;" id="remove_' + mlsID + '" class="remove"><img src="/images/action_delete.png" height="12" width="14" border="0" alt="Remove" align="absmiddle"></a> <strong>' + ($('#cb_' + mlsID).attr('title').length > 17 ? $('#cb_' + mlsID).attr('title').substring(0, 17) + '...' : $('#cb_' + mlsID).attr('title')) + '</strong></li>');
						$('#compareListingsWrap li:first-child').hide();
						$('#compareListingsWrap li:first-child').show('fast');
					},
					error: function() {
						alert('There was a problem adding this property. Please refresh the page and try again.');
					}
				});
			} else {
				$.ajax({
					type: 'GET',
					url: '/inc/functions.php?action=compare-remove&id=' + mlsID,
					dataType: 'html',
					success: function(response) {
						$('#compare_' + mlsID).hide();
					},
					error: function() {
						alert('There was a removing this property from the compare list. Please refresh the page and try again.');
					}
				});
		}
	});
	$('.remove').live('click', function() {
		var mlsIDSplitter = this.id.split('_');
		var mlsID = mlsIDSplitter[1];
		$.ajax({
			type: 'GET',
			url: '/inc/functions.php?action=compare-remove&id=' + mlsID,
			dataType: 'html',
			success: function(response) {
				$('#compare_' + mlsID).hide();
				$('#cb_' + mlsID).attr('checked', false);
			},
			error: function() {
				alert('There was a removing this property from the compare list. Please refresh the page and try again.');
			}
		});
	});

	// Gallery

	// Map
	var map = null;
	//var pointArray = new Array();
	var map_point = '';
	var directionsPanel, directions;
	var zoomAdjustment = 0;

	//function display_map() {
		pointArray = new Array();
		// Removed below with removal of JavaScript dependence
		// Only show map if #map is found
		// $('#map').show();
		if ($('.latlong').length && $('#map').length) {
			// We have map points and a map container; set up map and add controls
			map = new GMap2(document.getElementById("map"));
			// Center it in the QC
			map.setCenter(new GLatLng(41.523432, -90.575836), 9);
			//map.addControl(new GSmallZoomControl3D());
			$('.latlong').each(function() {
				// For each map point, generate a marker on the map
				// Each map_point span should be a list separated by a pipe
				var latlong = $(this).html().split('|');
				latlong[0] = latlong[0].replace(/<\/?[^>]+(>|$)/g, '');
        latlong[1] = latlong[1].replace(/<\/?[^>]+(>|$)/g, '');
				map_point = new GLatLng(latlong[0], latlong[1]);
				var marker = new GMarker(map_point);
				map.addOverlay(marker);
				pointArray.push(map_point);
				GEvent.addListener(marker, 'click', function() {
					marker.openInfoWindowHtml('<table width="250" cellpadding="2" cellspacing="1"><tr><td valign="top" align="left" width="124">' + latlong[7] + '</td><td valign="top" align="left"><strong>' + latlong[2] + '</strong><br />' + latlong[3] + '<br />' + latlong[4] + '<br />' + latlong[5] + '<br />' + latlong[6] + '</td></tr></table>');
				});
			});
			map.setUIToDefault();
			reCenterMap();
		}
	//}

	if ($('#map_small').length) {
		pointArray = new Array();
		if ($('.latlong').length && $('#map_small').length) {
			$('#map_small').toggle();
			// We have map points and a map container; set up map and add controls
			map = new GMap2(document.getElementById('map_small'));
			// Center it in the QC
			map.setCenter(new GLatLng(41.523432, -90.575836), 9);
			//map.addControl(new GSmallZoomControl3D());
			$('.latlong').each(function() {
				// For each map point, generate a marker on the map
				// Each map_point span should be a list separated by a comma
				var latlong = $(this).html().split('|');
				map_point = new GLatLng(latlong[0], latlong[1]);
				var marker = new GMarker(map_point);
				map.addOverlay(marker);
				pointArray.push(map_point);
			});
			if ($('#directions_from').length && $('#directions_from').val().length) {
				function error_trap() {
					if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
							alert('No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: ' + directions.getStatus().code);
						} else if (directions.getStatus().code == G_GEO_SERVER_ERROR) {
							alert('A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: ' + directions.getStatus().code);
						} else if (directions.getStatus().code == G_GEO_MISSING_QUERY) {
							alert('The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: ' + directions.getStatus().code);
						} else if (directions.getStatus().code == G_GEO_BAD_KEY) {
							alert('The given key is either invalid or does not match the domain for which it was given. \n Error code: ' + directions.getStatus().code);
						} else if (directions.getStatus().code == G_GEO_BAD_REQUEST) {
							alert('A directions request could not be successfully parsed.\n Error code: ' + directions.getStatus().code);
						} else {
							alert('An unknown error occurred.');
					}
				}
				directionsPanel = document.getElementById('driving_directions');
				directions = new GDirections(map, directionsPanel);
				GEvent.addListener(directions, 'error', error_trap);
				//alert($('#directions_from').val() + '|' + $.trim($('#listing_address').html()));
				directions.load('from: ' + $('#directions_from').val() + ' to: ' + $.trim($('#listing_address').html()), {'getPolyline': false, 'preserveViewport': true});
			}
			map.setUIToDefault();
			zoomAdjustment = -5;
			reCenterMap();
		}
	}

	function reCenterMap() {
		var bounds = new GLatLngBounds();
		if (pointArray && pointArray.length) {
			for (var i = 0; i < pointArray.length; i++) {
				var pt = pointArray[i];
				if (pt) {
					bounds.extend(pt);
				}
			}
			// TODO make sure this works over dateline
			var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
			var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
			var zoom = map.getBoundsZoomLevel(bounds) + (typeof zoomAdjustment == 'number' ? zoomAdjustment : -1);
			map.setCenter(new GLatLng(center_lat, center_lng), zoom);
		}
	}

	// Listing Page: Request Information dialogue
	$('#listing_requestinformation').colorbox({
		height: '435px',
		width: '400px',
		iframe: true,
		opacity: .5
	});

	// Listing Page: Email Listing dialogue
	$('#listing_emaillisting').colorbox({
		height: '455px',
		width: '400px',
		iframe: true,
		opacity: .5
	});

	// Listing Page: Schedule Showing dialogue
	$('#listing_scheduleshowing').colorbox({
		height: '435px',
		width: '400px',
		iframe: true,
		opacity: .5
	});

	// Calculator: Annual Cost
	$('#calc-annualcosts').colorbox({
		height: '450px',
		width: '610px',
		iframe: true,
		opacity: .5
	});

	// Calculator: Qualify
	$('#calc-qualify').colorbox({
		height: '470px',
		width: '610px',
		iframe: true,
		opacity: .5
	});

	// Calculator: Mortgage
	$('#calc-mortgage').colorbox({
		height: '450px',
		width: '610px',
		iframe: true,
		opacity: .5
	});

	// Calculator: Annual Cost
	$('#calc-owning').colorbox({
		height: '450px',
		width: '610px',
		iframe: true,
		opacity: .5
	});

	// New Construction / Builder gallery
	$('a[rel=mini_gallery]').colorbox({
		height: '450px',
		width: '610px'
	});

	// Clean up Google maps
	if (map != null) {
		$(window).unload(function() {
			GUnload();
		});
	}

	// Vendor list
	$('.vendor').live('click', function() {
		id_split = this.id.split('_');
		if ($('#vendors' + id_split[1]).is(':visible')) {
				$('#vendors' + id_split[1]).toggle();
			} else {
				$.ajax({
					type: 'GET',
					url: '/inc/functions.php?action=get_vendors&vendor_id=' + id_split[1],
					dataType: 'html',
					success: function(response) {
						$('#vendors_' + id_split[1]).html(response);
						$('#vendors_' + id_split[1]).toggle();
					},
					error: function() {
						$('#vendors_' + id_split[1]).html('<br />Error retrieving vendors.');
					}
				});
		}
	});
});

// Mouseover
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// Quick Search
function tab_show(_id) {
	$('#menunav > ul > li > a').each(function() {
		if (this.id == 'tab_' + _id) {
				$(this).addClass('current');
			} else {
				$(this).removeClass('current');
		}
		$('#tabcontainer_' + this.id.substring(4)).not('.hidden').addClass('hidden');
	});
	$('#tabcontainer_' + _id).removeClass('hidden');
	document.getElementById('location_' + _id).focus();
}

