//---------------------------------------------------------
//
// Property Searching
//
//---------------------------------------------------------

if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

// global arrays to hold copies of the markers and html used by the sidebar
var gmarkers = [];
var htmls = [];
var proprefs = [];
var gpoints = [];

// global "map" variable
var map;
var markerCluster = null;
var zoom = 11;
var mapSearch = false;
//var styles = [[ { url: '/images/heart30.png', height: 26, width: 30, opt_anchor: [4, 0], opt_textColor: '#FF00FF' }, { url: '/images/heart40.png', height: 35, width: 40, opt_anchor: [8, 0], opt_textColor: '#FF0000' }, { url: '/images/heart50.png', height: 44, width: 50, opt_anchor: [12, 0] }]];
var styles = [[ { url: '/images/home_blue.png', height: 37, width: 32, opt_anchor: [8, 0], opt_textColor: '#FFFFFF' }, { url: '/images/home_blue.png', height: 37, width: 32, opt_anchor: [8, 0], opt_textColor: '#FFFFFF'  }, { url: '/images/home_blue.png', height: 37, width: 32, opt_anchor: [8, 0], opt_textColor: '#FFFFFF'  }]];

function initMap(start, amount, where, order, dir, data, lat, lon, mapOveride) {
	// Set lat/long if there isnt one set
	if(!lat) {
		lat = 1;
	}
	if(!lon) {
		lon = 1;
	}

	map = new GMap(document.getElementById("searchmapbox"));
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(lat,lon), zoom);
	mapSearch = true;
	showData(start, amount, where, order, dir, data, mapOveride);
}

function createMarker(point, html) {
	// Create a lettered icon for this point using our icon class
	var gicon = new GIcon();
	gicon.image = "/images/house.png";
	gicon.iconSize = new GSize(32, 37);
	gicon.iconAnchor = new GPoint(17, 37);
	gicon.infoWindowAnchor = new GPoint(6, 1);
	// Set up our GMarkerOptions object
	markerOptions = { icon:gicon };
	var marker = new GMarker(point, markerOptions);
	//var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		map.panTo(new GLatLng(this.B.y, this.B.x));
	});
	return marker;
}

function showData(start, amount, where, order, dir, data, mapOveride) {
	
	if(mapOveride != "true") {
		$.ajax({
					url: "/includes/propsearch/getData.php", 
					cache: true,
					data: {start: start, amount: amount, where: where, order: order, dir: dir, data: data}, 
					success: function(searchData) {
						var temp = searchData.split("$$$");
						$("#tabledata").html(temp[0]);
						$("#tableinfo").html(temp[1]);
						$("#sortmenu").html(temp[2]);
						$("#pagelinks").html(temp[3]);
						$("#pagelinks2").html(temp[3]);
						$(".links").html(temp[3]);
						// Gets the customer data as a JSON object
						if(temp.length == 6) {
							var json = temp[5];
							if(json.length > 0) {
								// Eval json into array
								json = eval( '(' + json + ')' );
								// Loop through values array
								$.each( json, function( key, val ) {
									// Show the value
									jQuery(".value"+key.toLowerCase()).text(val.toString());
									// enable or diable depending on the value
									if(val == "0") {
										jQuery(".enable"+key.toLowerCase()).attr('disabled','disabled');
									}
									else {
										jQuery(".enable"+key.toLowerCase()).removeAttr('disabled');
									}
								});
							}
						}
					}
				});
	}
	
	if(mapSearch) {
		map.clearOverlays();
		if (markerCluster != null) {
			markerCluster.clearMarkers();
		}
		
		$.get("/includes/propsearch/getMapData.php", {start: start, amount: amount, where: where, order: order, dir: dir, data: data}, function(searchData) {
			var json = eval( '(' + searchData + ')' );
			//var json = eval(searchData);
			var bounds = new GLatLngBounds();
			var markers = [];
			$.each( json, function( key, val ) {
				if(json[key].LAT != "" && json[key].LAT != "0") {
					var point = new GLatLng(json[key].LAT, json[key].LONG);
					var marker = createMarker(point, '<div class="mapinfobox"><h2><a href="/cottage-details/' + json[key].PROPREF + '">' + json[key].PROPNAME + '</a></h2>' + json[key].ADDR1 + '<br />' + json[key].AREANAME + '<br />Sleeps: ' + json[key].ACCOM + '<br /><a href="/cottage-details/' + json[key].PROPREF + '">View Property</a>');
					bounds.extend(point);
					markers.push(marker);
					//map.addOverlay(marker);
				}
			});
			markerCluster = new MarkerClusterer(map, markers, {styles: styles[0]});
			
			if(document.location.pathname == "/regions/ceredigion.html") {
				map.setZoom(map.getBoundsZoomLevel(bounds)-1);
			}
			else {
				map.setZoom(map.getBoundsZoomLevel(bounds));
			}
			map.panTo(bounds.getCenter());
		});
	}
}

$.fn.combineData = function (options) {
	// Default settings
	var defaults = { 	start: 0,
						amount: 10,
						order: '', 
						dir: '',
						data: '' };
							
	var options = $.extend(defaults, options);
	
	$(this).submit(function() {
		
		$.ajax({
			type: $(this).attr("method"),
			url: "/includes/custom/property-search-ajax.php",
			data: $(this).serialize(),
			success: function(html) {
				showData(options.start, options.amount, html, options.order, options.dir, options.data);
			}
		});
		
		return false;
	});
}

$.fn.combineDataElement = function (options) {
	// Default settings
	var defaults = { 	start: 0,
						amount: 10,
						order: '', 
						dir: '',
						data: '' };
							
	var options = $.extend(defaults, options);
	var target = $(this);
	
	try {
		if(target.attr("type").indexOf("select") > -1) {
			target.change(function() {	
				$.ajax({
					type: target.closest("form").attr("method"),
					url: "/includes/custom/property-search-ajax.php",
					data: target.closest("form").serialize(),
					success: function(html) {
						showData(options.start, options.amount, html, options.order, options.dir, options.data);
					}
				});
			});
		}
		else if(target.attr("type") == "text") {
			target.blur(function() {	
				$.ajax({
					type: target.closest("form").attr("method"),
					url: "/includes/custom/property-search-ajax.php",
					data: target.closest("form").serialize(),
					success: function(html) {
						showData(options.start, options.amount, html, options.order, options.dir, options.data);
					}
				});
			});
		}
		else {
			target.click(function() {	
				$.ajax({
					type: target.closest("form").attr("method"),
					url: "/includes/custom/property-search-ajax.php",
					data: target.closest("form").serialize(),
					success: function(html) {
						showData(options.start, options.amount, html, options.order, options.dir, options.data);
					}
				});
			});
		}
	}
	catch(e) {}
}
	
$(document).ready(function(){

	var searchdata = "property";
	if($("#searchlist")) {
		searchdata = $("#searchlist").val();
	}

	$(".searchform").combineData({data: searchdata});	
	$(".searchelement").combineDataElement({data: searchdata});
});


//------------------------------------------------------
//
// Add to short list
//
//------------------------------------------------------

function addToShortlist(propref) {
	$.get("/includes/addtoshortlist.php", {prop: propref}, function() {
		alert("Added to shortlist");
	});
}

function removeFromShortlist(propref) {
	$.get("/includes/removefromshortlist.php", {prop: propref}, function() {
		alert("Removed from shortlist");
	});
}