$(document).ready(function(){

	$("#content").show();

	$("#store-search-field").hint();
	
	var map;
	var geocoder;
	var markerOptions;
	var nearestStores;
	
	function initialize() {
		
		geocoder = new google.maps.ClientGeocoder();
		
		map = new google.maps.Map2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(-26, 134), 4);
		map.setMapType(G_HYBRID_MAP);
		map.enableDoubleClickZoom();
		
		var justIcon = new google.maps.Icon();
		justIcon.image = "/storelocator/marker.png";
		justIcon.iconSize = new google.maps.Size(28, 28);
		justIcon.iconAnchor = new google.maps.Point(12, 14);
		justIcon.infoWindowAnchor = new google.maps.Point(12, 14);
		markerOptions = { icon:justIcon };
	
		if(google.loader.ClientLocation) {
			findStores( google.loader.ClientLocation.address.city+" "+google.loader.ClientLocation.address.country );
		} else {
			$("#myLocation").html("Enter a location to find your nearest stores.");
		}
	}	
	
	function findStores(location) {
		geocoder.getLocations(location, displayStores);
	}
	
	$("#store-search-btn").click(function () {
		findStores( $("#store-search-field").val() + " " + $('input:radio[name=country]:checked').val() );
    });
	$("#store-search").keyup(function(event) {
		if (event.keyCode == '13') {
			$("#store-search-btn").click();
		}
	});
	
	var initialRun = true;
	function displayStores(response) {
	  if (!response || response.Status.code != 200) {
		alert("Sorry, please enter a location");
		
	  } else {
		
		var place = response.Placemark[0];
		var point = new google.maps.LatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		
		nearestStores = [];
		map.clearOverlays();
		
		var marker = new google.maps.Marker(point);
		var html = "<b>Your location:</b><br/>"+place.address;
		google.maps.Event.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
		});
		map.addOverlay(marker);
		
		//alert( place.address );
		var storesToFind = Number( $("#store-search-number").val() );
		
		if( initialRun ) {
			$("#myLocation").html("The "+storesToFind+" nearest stores to <em>"+place.address+"</em> are:");
			initialRun = false;
		} else {
			$("#myLocation").html("The "+storesToFind+" stores nearest to <em>"+place.address+"</em> are:");
		}
		
		
		google.maps.DownloadUrl("/storelocator/stores.xml", function(data) {

			var xml = google.maps.Xml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("store");
			for (var i=0 ; i<markers.length ; i++ ) {
				  
				var latlng = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")) );
				
				
				if( storesToFind > 0 ) {
					var name = markers[i].getAttribute("name");
					var address = markers[i].getAttribute("streetaddress");
					var suburb = markers[i].getAttribute("suburb");
					var state = markers[i].getAttribute("state");
					var postcode = markers[i].getAttribute("postcode");
					var phone = markers[i].getAttribute("phone");
					var stock = markers[i].getAttribute("stock");
					var dist = Math.round(point.distanceFrom(latlng));
					var store = {latlng:latlng, name:name, address:address, suburb:suburb, state:state, postcode:postcode, phone:phone, stock:stock, dist:dist};
					var added = false;
					
					if( $("#kids").is(":checked") && stock == "" ) {} else {
					
						if( nearestStores.length > 0 ) {
							for(var j=0 ; j<nearestStores.length ; j++ ) {

								if( dist <= nearestStores[j].dist ) {
									nearestStores.splice(j,0,store);
									added = true;
									break;
								}
							}
							if( !added ) {
								nearestStores.push(store);
							}
						} else {
							nearestStores.push(store);
						}
						storesToFind--;
						
					}
				} else {

					var dist = Math.round(point.distanceFrom(latlng));
					for(var j=0 ; j<nearestStores.length ; j++ ) {

						if( dist <= nearestStores[j].dist ) {
							
							var name = markers[i].getAttribute("name");
							var address = markers[i].getAttribute("streetaddress");
							var suburb = markers[i].getAttribute("suburb");
							var state = markers[i].getAttribute("state");
							var postcode = markers[i].getAttribute("postcode");
							var phone = markers[i].getAttribute("phone");
							var stock = markers[i].getAttribute("stock");
							var store = {latlng:latlng, name:name, address:address, suburb:suburb, state:state, postcode:postcode, phone:phone, stock:stock, dist:dist};
							
							if( $("#kids").is(":checked") && stock == "" ) {} else {
								nearestStores.splice(j,0,store);
								nearestStores.pop();
								break;
							}
						}
					}
				}
				
			}
			
			$("#nearest-stores tbody").empty();
			var bounds  = new google.maps.LatLngBounds();
			mapMarkers = [];
			
			for (var i = 0; i < nearestStores.length; i++) {
				bounds.extend(nearestStores[i].latlng);
				// add store line to table
				var kmDist = ((nearestStores[i].dist/1000).toFixed(2));
				var specialStock = "";
				if( nearestStores[i].stock != "" ) specialStock = nearestStores[i].stock;
				
				$("#nearest-stores tbody").append( "<tr id='"+i+"'><td>"+nearestStores[i].name+"</td><td>"+nearestStores[i].address+", "+nearestStores[i].suburb+", "+nearestStores[i].state+" "+nearestStores[i].postcode+"</td><td>"+nearestStores[i].phone+"</td><td style='text-align:right'>"+kmDist+" km</td><td>"+specialStock+"</td></tr>" );
				
				var marker = nearestStores[i].marker = new google.maps.Marker(nearestStores[i].latlng, markerOptions);
				marker.bindInfoWindowHtml( "<b>" + nearestStores[i].name + "</b> <br/>" + nearestStores[i].address + "<br/>" + nearestStores[i].suburb + ", " + nearestStores[i].state + " " + nearestStores[i].postcode + "<br/><em>" + specialStock + "</em>" );
				
				google.maps.Event.addListener(marker,'mouseover',function(){
					this.setImage("/storelocator/marker_over.png");
				});
				google.maps.Event.addListener(marker,'mouseout',function(){
					this.setImage("/storelocator/marker.png");
				});	
				$("#nearest-stores tbody tr#"+i).click(function() {
					google.maps.Event.trigger(nearestStores[$(this).attr("id")].marker,"click");
				});
				$("#nearest-stores tbody tr#"+i).mouseover(function() {
					nearestStores[$(this).attr("id")].marker.setImage("/storelocator/marker_over.png");
				}).mouseout(function() {
					nearestStores[$(this).attr("id")].marker.setImage("/storelocator/marker.png");
				});
				
				map.addOverlay(nearestStores[i].marker);
			}
			
			$("#nearest-stores tbody tr:odd td").addClass("odd");
			map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
		  });
	  }
	}
	
	
	initialize();
	
});




