/* Store Locations Script for Peter Alexander */

$(function(){
	//initialize();
	//findLocation('Carlton','271 Lygon Street Carlton Melbourne VIC 3053 Australia');
	
	$(".storelocations .store .storedetails").append("<a class='showmap' href='javascript:void(0)'>Show Map</a>");
	$("#map").css("border","solid 2px red");
	
	$('.showmap').toggle(function() {
		$("#shown").click();
		$(this).html("Hide Map");
		$(this).parent().parent().append("<div id='map'></div>");
		$(this).attr("id","shown");
		
		var storeName = $(this).siblings("h3").html()
		var storeCountry = "Australia"; if( $("body").hasClass("stores_nz_nth") || $("body").hasClass("stores_nz_sth") ) storeCountry = "New Zealand";
		var storeAddress = $(this).siblings(".streetaddress").html() +" "+ $(this).siblings(".suburb").html() +" "+ $(this).siblings(".state").html() +" "+ $(this).siblings(".postcode").html() +" "+ storeCountry;
		findLocation(storeName,storeAddress);
		
	}, function() {
		$(this).attr("id","");
		$(this).html("Show Map");
		$("#map").remove();
	});
	
});



/*************************************************************/
// GOOGLE MAPS API
/*************************************************************/

var map;
var geocoder;
var storeName;

function findLocation(name,address) {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl(1));
	map.enableDoubleClickZoom();
	geocoder = new GClientGeocoder();
  
  	// Create PA marker icon
	var peterIcon = new GIcon();
	peterIcon.image = "/images/pages/stores/storelocaton_marker.png";
	peterIcon.iconSize = new GSize(42, 42);
	peterIcon.iconAnchor = new GPoint(21, 21);
	peterIcon.infoWindowAnchor = new GPoint(25, 17);
	markerOptions = { icon:peterIcon };
	
	storeName = name;
  	geocoder.getLocations(address, addAddressToMap);
}


// addAddressToMap() is called when the geocoder returns an answer. 
// It adds a marker to the map with an open info window
function addAddressToMap(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
	alert("Sorry, we were unable to find address for that location.");
  } else {
	place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
	var windowHTML = "<div class='infowindow'><div class='title'>Peter Alexander " + storeName + " store</div><div class='body'>" + place.address + "</div><br/></div>";
	marker.bindInfoWindowHtml( windowHTML );
	marker.openInfoWindowHtml( windowHTML );
	map.setCenter(new GLatLng(place.Point.coordinates[1]+0.001, place.Point.coordinates[0]), 16);
  }
}



