$(function() {
	// Hides warning boxes
	$("#noInfo").hide();
	$("#noLatLong").hide();
	$("#noResult").hide();

	// Form Submission
	$("#searchForm").submit(function() {
		showAddress();
		return false;
	});

	// This populates the dropdown box
	// var availableTags = "jsonRequest-searchbox.php";
	// $("#search").autocomplete({
	// source: availableTags,
	//		
	// select: function( event, ui ) {
	// //$("#search").val();
	// var longstring=$(this).val();
	// var brokenstring=longstring.split(",");
	//
	//			
	// $('#uid').attr('value',brokenstring.pop());
	//			
	//			
	// var localSearch = new GlocalSearch();
	// localSearch.setSearchCompleteCallback(null, function(){
	// if(localSearch.results[0]){
	// $('#latitude').attr('value',localSearch.results[0].lat);
	// $('#longitude').attr('value',localSearch.results[0].lng);
	// return true;
	// }else {
	// $('#latitude').attr('value','');
	// $('#longitude').attr('value','');
	// return false;
	// }
	// });
	//		
	// localSearch.execute(jQuery.trim($(this).val()) + ", UK");
	//
	// }
	//		
	// });

	// This returns the lat and longtitude of a searched address
	$('#search').keyup(function() {
		$(".alertbox").fadeOut('500');
		getLatLon(this, $(".country_select:checked").attr('id'));
	});
	
	$('#search').focusout(function() {
		$(".alertbox").fadeOut('500');
		getLatLon(this, $(".country_select:checked").attr('id'));
	});
	
	$('#postcode').keyup(function() {
		getLatLon(this, '');
	});
	
	$('#postcode').focusout(function() {
		getLatLon(this, '');
	});
	
	// On change of country we update the lat & lon
	$(".country_select").change(function() {
		$(".alertbox").fadeOut('500');
		$('#search').val('');
		getLatLon(this);
	});
	
	function getLatLon(search, country)
	{
		$("#noLatLong").hide();
		$('#uid').attr('value', '');
		var localSearch = new GlocalSearch();
		localSearch.setSearchCompleteCallback(null, function() {
			if (localSearch.results[0]) {
				$('#latitude').attr('value', localSearch.results[0].lat);
				$('#longitude').attr('value', localSearch.results[0].lng);
				return true;
			} else {
				$('#latitude').attr('value', '');
				$('#longitude').attr('value', '');
				return false;
			}
		});
		localSearch.execute(jQuery.trim(jQuery.trim($(search).val()) + " " + country));
	}

	// Hides alerts
	$('#search').click(function() {
		$(".alertbox").fadeOut('500');
	});

	// Ui Slider

	$("#slider-range-min").slider( {
		range : "min",
		value : 10,
		min : 1,
		max : 50,
		slide : function(event, ui) {
			$("#amount").val(ui.value);
		}
	});
	$("#amount").val($("#slider-range-min").slider("value"));

	// Map Configuration
	var map = new GMap2($("#map_canvas").get(0));
	var burnsvilleMN = new GLatLng(54.016479, -1.073864);
	map.setCenter(burnsvilleMN, 5);
	map.setUIToDefault();
	var Icon = new GIcon(G_DEFAULT_ICON);
	Icon.image = "pin.png";
	markerOptions = {
		icon : Icon
	};
	var bounds = null;
	var geo = new GClientGeocoder();
	
	
	
	
	var map = new GMap2(document.getElementById("map_canvas"));
	map.setUIToDefault();
//	map.addControl(new GSmallMapControl());
//	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(54.016479, -1.073864), 5);

	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
	
	
	

	// This is the search retailers box
	function showAddress() {
		var searchbox = $("input[name='search']").val();
		var longitude = $("input[name='longitude']").val();
		var latitude = $("input[name='latitude']").val();
		var id = $('#uid').val();
		var range = $('#amount').val();
		var count = 0;
		
		// For debugging the response.
//		$(document).ajaxError(function(e, xhr, settings, exception) {
//			alert('error in: ' + settings.url + ' \n'+'error:\n' + xhr.responseText );
//		}); 

		//alert("Lat=" + latitude + " and Lon="+longitude);
		
		if (searchbox) {
			if (longitude && latitude || id) {
				$.ajax( {
					type : "GET",

					url : "jsonRequest-map.php",
					dataType : "json",
					data : "longitude=" + longitude + "&latitude=" + latitude
							+ "&range=" + range + "&id=" + id,
					success : function(response) {

						// THIS IS WHERE THE PAGE POPULATION GOES
					$('.list li').remove();
					map.clearOverlays();
					bounds = new GLatLngBounds();
					for (x in response) 
					{
						var letter = String.fromCharCode("A".charCodeAt(0) + count);
						// Adding the content below the map
						telephone = "<p>Tel No - " + response[x][4] + "</p>";
						email = "<p>Email - <a href=\"mailto:" + response[x][6]
								+ "\">" + response[x][6] + "</a></p>";
						website = "<p>Website - <a href=\"http://"
								+ response[x][5] + "\" title=\""
								+ response[x][5] + "\">" + response[x][5]
								+ "</a></p>";
						contentList = "<li><p><strong>" + letter + " - " + response[x][0]
								+ "</strong>, " + response[x][1] + ", "
								+ response[x][2] + ", " + response[x][9] + ", "
								+ response[x][3] + "</p>";
						if (response[x][4])
							contentList += telephone;
						if (response[x][6])
							contentList += email;
						if (response[x][5])
							contentList += website;

						contentList += "</li>";
						$('.list').append(contentList);

						// Populating the map
						addLocation(response[x], count);
						count++;
					}// End of for loop
					
					zoomToBounds();
					$('.list li').hide();
					$('.list li').slideDown('1500');
					return true;
				},

				error : function() {
					$("#noResult").slideDown();
				}

				});

			} else {
				$("#noLatLong").slideDown();
				return false;
			}

		} else {
			$("#noInfo").slideDown();
			return false;
		}

	}

	// Adds a point and info to the pointers
	function addLocation(location, count) {
		// Creates a marker whose info window displays the letter corresponding
		// to the given index.
		function createMarker(point, index) {
			// Create a lettered icon for this point using our icon class
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.com/mapfiles/marker"
					+ letter + ".png";

			// Set up our GMarkerOptions object
			markerOptions = {
				icon : letteredIcon
			};
			var marker = new GMarker(point, markerOptions);

			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");

				var bubbleContent = "<div class=\"bubble\"><p><strong>"
						+ location[0] + "</strong><br />" + location[1] + ", "
						+ location[2] + ", " + location[3] + ", " + location[4]
						+ "</p>";

				telephone = "<p>Tel No - " + location[4] + "</p>";
				email = "<p>Email - <a href=\"mailto:" + location[6] + "\">"
						+ location[6] + "</a></p>";
				website = "<p>Website - <a href=\"http://" + location[5]
						+ "\" title=\"" + location[5] + "\">" + location[5]
						+ "</a></p>";

				if (location[4])
					bubbleContent += telephone;
				if (location[6])
					bubbleContent += email;
				if (location[5])
					bubbleContent += website;
				bubbleContent += "<div>";

				marker.openInfoWindowHtml(bubbleContent);
			});
			return marker;
		}

		var point = new GLatLng(location[7], location[8]);
		bounds.extend(point);
		map.addOverlay(createMarker(point, count));
	}
	// Zooms map to correct place
	function zoomToBounds() {
		map.setCenter(bounds.getCenter());
		// map.setZoom(map.getBoundsZoomLevel(bounds)-1);
		map.setZoom(map.getBoundsZoomLevel(bounds));
	}

});

