/* Store Locations Script */
$(document).ready(function(){
						   
	if( screen.width > 480 ) {
	
		$("#locatorSearch").show();
	
		$("#store-search-field").hint();
		
		var map;
		var geocoder;
		var markerOptions;
		var nearestStores;
		
		var clientLocationFound;
		function initialize() {
			
			geocoder = new google.maps.ClientGeocoder();
			
			map = new google.maps.Map2(document.getElementById("map"));
			map.addControl(new GMapTypeControl(1));
			map.addControl(new GLargeMapControl());
			//map.addControl(new GScaleControl(256));
			//map.enableScrollWheelZoom();
			map.enableDoubleClickZoom();
			
			//Create Just Jeans marker icon
			var justIcon = new google.maps.Icon();
			justIcon.image = "/images/global/storelocaton_marker.gif";
			justIcon.iconSize = new google.maps.Size(24, 27);
			justIcon.iconAnchor = new google.maps.Point(12, 14);
			justIcon.infoWindowAnchor = new google.maps.Point(12, 14);
			markerOptions = { icon:justIcon };
			
			// get user actual location
			if(google.loader.ClientLocation) {
				//visitor_lat = google.loader.ClientLocation.latitude;
				//visitor_lon = google.loader.ClientLocation.longitude;
				//visitor_city = google.loader.ClientLocation.address.city;
				//visitor_region = google.loader.ClientLocation.address.region;
				//visitor_country = google.loader.ClientLocation.address.country;
				//visitor_countrycode = google.loader.ClientLocation.address.country_code;
				//document.getElementById("myLocation").innerHTML = "We detected that you are located in <em>"+visitor_city+" "+visitor_country+"</em>.";
				//map.addOverlay( createMarker(new google.maps.LatLng(visitor_lat,visitor_lon), null) );
				//alert( "city: " + google.loader.ClientLocation.address.city + " country: " + google.loader.ClientLocation.address.country );
				clientLocationFound = true;
				findStores( google.loader.ClientLocation.address.city+" "+google.loader.ClientLocation.address.country );
			} else {
				clientLocationFound = false;
				findStores( "Australia" )
			}
		}
		
		
		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, we were unable to find an address for that 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 ) {
				if( clientLocationFound ) {
					$("#myLocation").html("We have detected that you are located near <em>"+place.address+"</em>. The "+storesToFind+" nearest stores are:");
					initialRun = false;
				} else {
					$("#myLocation").html("We are unable to find your location on the map, please enter an address to search on");	
					clientLocationFound = true;
					initialRun = false;
				}
	
			} else {
				$("#myLocation").html("The "+storesToFind+" stores nearest to <em>"+place.address+"</em> are:");
			}
			
			
			google.maps.DownloadUrl("/xml/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 ) {
						//add first x stores
						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++ ) {
									//alert( dist + " <= " + nearestStores[j].dist + " = " + (dist <= nearestStores[j].dist) );
									if( dist <= nearestStores[j].dist ) {
										nearestStores.splice(j,0,store);
										added = true;
										//alert( "insert: " + dist + ", result: " + printDist() );
										break;
									}
								}
								if( !added ) {
									nearestStores.push(store);
									//alert( "added to end: " + printDist() );
								}
							} else {
								nearestStores.push(store);
								//alert( "added first: " + printDist() );
							}
							storesToFind--;
							
						}
					} else {
						//look though entire list to find any closer stores
						var dist = Math.round(point.distanceFrom(latlng));
						for(var j=0 ; j<nearestStores.length ; j++ ) {
							//alert( dist + " <= " + nearestStores[j].dist + " = " + (dist <= nearestStores[j].dist) );
							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+" stock available";
					
					$("#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>" );
					
					// add marker to map
					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("/images/global/storelocaton_marker_over.gif");
					});
					google.maps.Event.addListener(marker,'mouseout',function(){
						this.setImage("/images/global/storelocaton_marker.gif");
					});	
					
					// display info window when table row is clicked
					$("#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("/images/global/storelocaton_marker_over.gif");
					}).mouseout(function() {
						nearestStores[$(this).attr("id")].marker.setImage("/images/global/storelocaton_marker.gif");
					});
					
					map.addOverlay(nearestStores[i].marker);
				}
				
				$("#nearest-stores tbody tr:odd td").addClass("odd");
				map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
			  });
		  }
		}
		
		
		initialize();
	}
	
});



