$(document).ready(function() {

	// Set up API keys
	var flickr_api_key = '0a8ffb437fafe951579a14a512c215f7';
	var digitalnz_api_key = 'a44c43c464377032d1c2f916b2276d3e';
	
	var locName;

	var lat = -40.45;
	var lng = 174.7;
	var zoom = 5;
	var perPage = 10;
	var currentDisplay = 0;
	var lastDisplay = perPage;
	var recordID = 0;
	var thumbnailSize = 50;
     
	// Create new map object
	var gmap = new google.maps.Map2($('#map_canvas').get(0));
      
	gmap.setCenter(new google.maps.LatLng(lat,lng), zoom);
     
	gmap.setUIToDefault(); 


	
	GEvent.addListener(gmap, 'movestart', function() {
		searchTerm = '';
		$("#loader").empty();
		$("#summary").empty();
		$("#results").empty();
		$("#more").css("display","none");
		gmap.clearOverlays();
	});
      
	GEvent.addListener(gmap, 'zoomend', function() {
		
	});
	
	GEvent.addListener(gmap, 'moveend', function() {
		$('#startFrom').val('0');
		findCenter();
		gmap.clearOverlays();
		var bounds = new google.maps.LatLngBounds();
		getPlaceName(center.lat(),center.lng(),accuracy);
	});
  
	
	GEvent.addDomListener($('#crosshair').get(0), 'dblclick', function() {
		gmap.zoomIn();
	});  

	
	// Find the centre of the map
	function findCenter() {
		center = gmap.getCenter();
		accuracy = gmap.getZoom();
	}
	
	
	// Detect if the browser is location aware
	if(navigator.geolocation) {
		$('<button id="location"></button>').html('Go to my location').appendTo('#locBtn');
		
		$("#location").click(function(event) {
			event.preventDefault();
			navigator.geolocation.getCurrentPosition(locationSuccess,locationError,{maximumAge:300000});
		});
	}


	
	function locationSuccess(position) {
		var lat = position.coords.latitude;
		var lng = position.coords.longitude;
		
		gmap.setCenter(new google.maps.LatLng(lat,lng), 14);
		getPlaceName(lat,lng,14);
	}
	
	function locationError(error) {
		switch(error.code) {
			case 2:
				alert("Sorry, we are unable to determine your location"); 
				break;
			default:
				alert("error:"+ error.code);
		}
	}
	
	
	
	
	// Update the results if a user clicks on the search type radio buttons
	$("input[name='accuracy']").click(function() {
		findCenter();
		$("#startFrom").val('0');
		getPlaceName(center.lat(),center.lng(),accuracy);
    });


	// When a user clicks on the "more" button add in more search results
	$("#more").click(function(event) {
		event.preventDefault();
		var startFrom = $("#startFrom").val();
		getSearchResults(searchTerm,startFrom);
	});
	
	
	// When a user clicks on a result, display the full record
	$("#results li a").livequery('click',function(event) {
		event.preventDefault();
		
		// IE7 is taking the whole link rather than just the href (eg: www.paulhagon.com etc).
		// Add a bit of a hack to pull the reference from a title tag (ugly hack)
		if($.browser.msie) {	
			var recordID = $(this).attr('title');
		} else {
			var recordID = $(this).attr('href');
		}
		
		getDetailedRecord(recordID);
	});
	
	
	// When a user clicks on the "close" button, remove the full record
	$(".close").click(function(event) {
		event.preventDefault();
		$("#record").empty();
		//$('#overlay').css("display","none");
		$('#overlay').hide("slow");
	});




	// Query the Flickr API with the latitude & longitude to get the place name
	function getPlaceName(lat,lng,accuracy) {
		$.getJSON('http://api.flickr.com/services/rest/?method=flickr.places.findByLatLon&api_key='+ flickr_api_key +'&lat='+ lat +'&lon='+ lng +'&accuracy='+ accuracy +'&format=json&jsoncallback=?', function(data) {
			if(data.places.total == 1) {
				searchTerm = data.places.place[0].name.split(",")[0];
				woeid = data.places.place[0].woeid;
				
				
				// Create a 'content loading' image to display until the AJAX call is returned
				$("#loader").empty();
				$("#summary").empty();
				$("#results").empty();
				
				$("#loader").html('Loading results<br /><img src="images/pleasewait.gif" />');
				
				var startFrom = $("#startFrom").val();
				
				displayPolygon(woeid);
				getSearchResults(searchTerm,startFrom);
				
			}																																																																																																			 		});
	}


	// Query Digital NZ for the search term
	function getSearchResults(searchTerm,startFrom) {
		
		//console.log("searchTerm=", searchTerm);
		
		
		var searchType = $("input[name='accuracy']:checked").val();
		if(searchType == 'location') {
			var finalSearchTerm = 'placename%3A'+searchTerm;
		} else {
			var finalSearchTerm = searchTerm;
		}
		
		
		// Make an AJAX XML request to DigitalNZ
		$.ajax({ 
			type: 'get', 
			url: 'http://www.paulhagon.com/playground/digitalnz/proxy.php', 
			data: 'url=http%3A%2F%2Fapi.digitalnz.org%2Frecords%2Fv1.xml%3Fapi_key='+ digitalnz_api_key +'%26num_results='+ perPage +'%26start='+ startFrom +'%26search_text='+ finalSearchTerm +'', 
			dataType: 'xml', 
			success: function(xml){
				
				$("#loader").empty();
				
				var maxNum = $(xml).find('result-count').text();
				var numResults = $(xml).find('result').length;
				var startFrom = parseInt($(xml).find('start').text())+numResults;
				
				$("#startFrom").val(parseInt($(xml).find('start').text())+numResults);

				//console.log("startFrom=",startFrom);
				//console.log("numResults=",numResults);
								
				
				if(maxNum == 0) {
					$("#summary").html('There are no results for <strong>'+ searchTerm +'</strong>');					
				} else if(maxNum == 1) {
					$("#summary").html('Found <strong>'+ maxNum +'</strong> result for <strong>'+ searchTerm +'</strong>');
				} else {
					$("#summary").html('Found <strong>'+ maxNum +'</strong> results for <strong>'+ searchTerm +'</strong>. Displaying <strong>1</strong> to <strong id="maxDisplay">'+ startFrom +'</strong>');
				}
				
				
				$(xml).find('result').each(function() {
					var category = $(this).find('category').text();
					var title = $(this).find('title').text();
					var contentPartner = $(this).find('content-provider').text();
					var thumbnail = $(this).find('thumbnail-url').text();					
					var id = $(this).find('id').text();
					
					if(thumbnail) {
						$('<li></li>').html('<a href="'+ id +'" rel="overlay" title="'+ id +'"><span class="thumbnail"><img src="'+ thumbnail +'" /></span> '+ title +'</a><br />'+ category +' from '+ contentPartner).appendTo('#results');	
						
						// Once the image is loaded run a function to resize it
						$('.thumbnail').load(function(){
							alert("Image loaded");
						}).attr('src',thumbnail);
						/*
						$('.thumbnail').load(function(){
							alert("Image loaded");
						}).attr('src','myImage.jpg');
						*/
					} else {
						$('<li></li>').html('<a href="'+ id +'" rel="overlay" title="'+ id +'">'+ title +'</a><br />'+ category +' from '+ contentPartner).appendTo('#results');	
					}
					
					
					
				});
				
				
				$('.thumbnail img').load(function() {
					var width=$(this).width();
					var height=$(this).height();
					
					if(width>=height) {
						$(this).attr("width",thumbnailSize);
					} else {
						$(this).attr("height",thumbnailSize);
					}
					
				});
				
				if(maxNum <= startFrom) {
					$('#more').css("display","none");					
				} else {
					$('#more').css("display","block");
				}
				
			}
		});		
				
	}

	

	// Query Digital NZ for the detailed record 
	function getDetailedRecord(recordID) {
		
		//console.log("recordID=", recordID);
		
		// Make an AJAX XML request to DigitalNZ
		$.ajax({ 
			type: 'get', 
			url: 'http://www.paulhagon.com/playground/digitalnz/proxy.php', 
			data: 'url=http%3A%2F%2Fapi.digitalnz.org%2Frecords%2Fv1%2F'+ recordID +'.xml%2F?api_key='+ digitalnz_api_key +'',
			dataType: 'xml', 
			success: function(xml){
				
				
				// Create a bunch of variables from the XML
				// Need to do come code forking for XML namespaces - ugly
				if($.browser.mozilla || $.browser.msie){
					var title = $(xml).find('dc\\:title').text();
					var description = $(xml).find('dc\\:description').text();
					var date = $(xml).find('dc\\:date').text();
					var publisher = $(xml).find('dc\\:publisher').text();
					var relation = $(xml).find('dc\\:relation').text();
					var rights = $(xml).find('dc\\:rights').text();
					var type = $(xml).find('dc\\:type').text();
					var category = $(xml).find('dnz\\:category').text();
					var thumbnail = $(xml).find('dnz\\:thumbnail_url').text();
					var contentPartner = $(xml).find('dnz\\:content_partner').text();
					var landingURL = $(xml).find('dnz\\:landing_url').text();
				} else {
					var title = $(xml).find('title').text();
					var description = $(xml).find('description').text();
					var date = $(xml).find('date').text();
					var publisher = $(xml).find('publisher').text();
					var relation = $(xml).find('relation').text();
					var rights = $(xml).find('rights').text();
					var type = $(xml).find('type').text();
					var category = $(xml).find('category').text();
					var thumbnail = $(xml).find('thumbnail_url').text();
					var contentPartner = $(xml).find('content_partner').text();
					var landingURL = $(xml).find('landing_url').text();

				}				
				
				$("<h2></h2>").html(title).appendTo('#record');
				if(thumbnail) {
					$("<p></p>").html('<img src="'+ thumbnail +'" alt="'+ title +'" />').appendTo('#record');	
				}
				$("<p></p>").html(description).appendTo('#record');
				if(date) {
					$("<p></p>").html('<strong>Date:</strong> '+ date).appendTo('#record');
				}
				if(publisher) {
					$("<p></p>").html('<strong>Published by:</strong> '+ publisher).appendTo('#record');
				}
				if(relation) {
					$("<p></p>").html('<strong>Relation:</strong> '+ relation).appendTo('#record');
				}
				
				$("<p></p>").html('<a href="'+ landingURL +'" class="view">View '+ category +' details</a> at '+ contentPartner).appendTo('#record');
				
				$("#overlay").show("slow");
							
			}
		});
	}
	

	// Display the shapefile as an overlay
	function displayPolygon(woeid) {
		$.getJSON('http://api.flickr.com/services/rest/?method=flickr.places.getInfo&api_key='+ flickr_api_key +'&woe_id='+ woeid +'&format=json&jsoncallback=?', function(data) {
			if(data.place.has_shapedata == 1) {
				$.each(data.place.shapedata.polylines.polyline, function(index,polyline) {
					thepoints = [];
					$.each(polyline._content.split(/ /), function(pindex, point) {
						lat = parseFloat(point.split(/,/)[0]);
						lng = parseFloat(point.split(/,/)[1]);
						thepoints[pindex] = new google.maps.LatLng(lat, lng);
					});
 
					var polyOptions = {geodesic:true};          
					
					var polygon = new google.maps.Polygon(thepoints, '#CC6600', 2, 1, '#CC6600', 0.2, polyOptions);
					gmap.addOverlay(polygon);
				});
			}
		});
	}
	

});