/**
 * @author meilyrgwilym
 */
//http://maps.google.com/?ie=UTF8&ll=52.207607,-3.856201&spn=1.511406,5.141602&z=8&om=0http://maps.google.com/?ie=UTF8&ll=52.898962,-3.872681&spn=1.487781,5.141602&z=8&om=0
var centerLatitude = 52.2076072;
var centerLongitude = -3.878174;
var startZoom = 7;
var geocoder;
var errorFlag = false;
var map;

//adds a marker to the map
function addMarker(latitude, longitude, description) {
	
	var marker = new GMarker(new GLatLng(latitude, longitude));
	GEvent.addListener(marker, 'click',
		function() {
			marker.openInfoWindowHtml(description);
		}
	);
	
	map.addOverlay(marker);
}

//removes all markers from the map (when user has initialised new search)
function removeMarker(){
	
}

// for showing and hiding the loading graphic
function loading(){
	var loading = "<div id=\"loading\"><img src=\"img/loading.gif\" height=\"16\" width=\"16\"> Llwytho</div>";
	$("body").append(loading);
}
function loaded(){
	$("#loading").remove();
}

// makes the AJAX request and displays the results
function pingServer(val){
	
	// get rid of the error message, if any
	if(errorFlag){
		hideError();
	}
	// ajax call to the server with the request,
	// then process
	
	$.getJSON("process.php", 
		  {location:val},
		  function(json){
			loaded();
			// check for 200 code
			if(json.response.listings){
				newCenter(val);
				var props = json.response.listings;
				$.each(props, function(i, item){
					var desc = "<div id=\"infowindow\"><img src=\""+item.thumb_url+"\" style=\"float:left;\"><p>"+item.title+"</p>"+"<p>&pound;"+item.price_formatted+", <a href=\""+item.lister_url+"\">Mwy o wybodaeth</a><div>";
					addMarker(item.latitude, item.longitude, desc);
				});
			}else{
				var location = json.request.location;
				showError('Sori, ond nid ydw i wedi deall. Ceisia eto ogydd.');
			}					
   	}); // $.getJSON
   		  
}

// shows an error message
function showError(msg){
	errorFlag = true;
	$("#control").append('<p class="error">'+msg+'</p>');
}
// hides the error message
function hideError(){
	errorFlag = false;
	$("#control>p.error").remove();
}

// finds the lat & long of the search term, and moves the map accordingly
function newCenter(placename){
	geocoder = new GClientGeocoder();

    // Retrieve location information, pass it to addToMap()
    geocoder.getLocations(placename, addToMap);
}
// used with above function
function addToMap(response){
      // Retrieve the object
      place = response.Placemark[0];

      // Retrieve the latitude and longitude
      point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);

      // Center the map on this point
      map.setCenter(point, 11);
}


function createForm(){
	var html = '<form method="" action="">';
	html += '<label for="postcode">Enw tref neu bentref neu g&ocirc;d post...</label>';
	html += '<input type="text" name="postcode" id="postcode" value="">';
	html += '<input type="submit" name="submit" value="anfon" id="submit">';
	html += '</form>';
	
	$("#control").append(html);
}

// called when document is loaded
function init(){
	$("#noscript").hide(); // hide the JS warning
	
	if (GBrowserIsCompatible()) {		
		
		// get viewport dimensions to set the map's size
		intHeight = window.innerHeight-100; // -100px
		intWidth = window.innerWidth;
		if (!intHeight) {
			// for IE
			intHeight = document.body.offsetHeight-100;
			intWidth = document.body.offsetWidth;
		}
				
		// get the #map div, set the width & height
		objMap = document.getElementById("map");
		objMap.style.height = intHeight + "px";
		objMap.style.width= intWidth + "px";
		
		//create!
		map = new GMap2(objMap);				
		// fries with that?
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
		
		// check for form clicks
		check4Submit();
		
	}
}

// ronseal door varnish
function check4Submit(){
	$("#submit").click(function(){

			loading();
			var input = $("#postcode").val();
			pingServer(input);

			return false;
		});
}

// let's rock and roll...
 $(document).ready(function(){
 	createForm();
	init();
});