// ==================== GOOGLE MAPS API MANAGER =========================	
var map;
var geo;
var bounds;
var reasons=[];
var markerManager;
var markers = new Array();
var icons = new Array();
var gdir;

function resetMap(){
	if(markers.length > 0){
		while(markers.length > 0){
			var marker = markers.pop();
			marker.hide();
		}
		markers = new Array();
		markerManager.clearMarkers();
		bounds = new GLatLngBounds();
	}
}

if(window.addEventListener) {
 window.addEventListener('load', initializeMap, false);
} else if (window.attachEvent){
 window.attachEvent('onload', initializeMap);
} 

//ICON
function newIcon(pName, pImageURL, pIntSizeH, pIntSizeL, pIntAnchorX, pIntAnchorY, pIntInfoWindowX, pIntInfoWindowY, pTransparentIconURL){
	var storeIcon = new GIcon();
	storeIcon.image = pImageURL;
	storeIcon.iconSize = new GSize(pIntSizeH, pIntSizeL);
	storeIcon.iconAnchor = new GPoint(pIntAnchorX, pIntAnchorY);
	storeIcon.infoWindowAnchor = new GPoint(pIntInfoWindowX, pIntInfoWindowY);
	storeIcon.transparent = pTransparentIconURL;
	icons[pName] = storeIcon;

}

function scriptLoaded(){
	var postcodes = new Array();
	for(var i=0;i<jSonInfo.postalCodes.length; i++){
		postcodes.push(jSonInfo.postalCodes[i].postalCode);
	}
	manager.obtainStores(postcodes);
}

function initializeMap() {
	map = new GMap2(document.getElementById("map-screen"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(37.0625,-95.677068),4);
	markerManager = new MarkerManager(map, {borderPadding:1});
	
	// ====== Empty Bounds Object ===========
	bounds = new GLatLngBounds();
	// ====== Create a Client Geocoder ======
	geo = new GClientGeocoder(); 
	
	// ====== Array for decoding the failure codes ======
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	
	var tooltip = document.createElement("div");
	tooltip.id = "tooltip_div";
	document.getElementById("map-screen").appendChild(tooltip);
	tooltip.style.visibility="hidden";
	
	gdir = new GDirections(map, document.getElementById("driving-directions"));	
	
	// === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() {
	var code = gdir.getStatus().code;
	var reason="Code "+code;
	if (reasons[code]) {
	  reason = reasons[code]
	} 
	console.log("Failed to obtain directions, "+reason);
	});
	
	
	
}

// ====== Plot a marker after positive reponse to "did you mean" ======
function place(lat,lng, pBalloonHTML) {
	var point = new GLatLng(lat,lng);
	map.setCenter(point,14);
	
	marker = createMarker(point,pBalloonHTML);
	autoFitData(point);
	markers.push(marker);
	markerManager.addMarker(marker,0,17);
}

//AUTOFIT ALL DATAWITHIN BOUNDS
function autoFitData(pPoint){
	bounds.extend(pPoint);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	if(markers.length < 2){
		map.setZoom(map.getBoundsZoomLevel(bounds) - 3);
	}
	map.setCenter(bounds.getCenter());
}


// ====== Geocoding ======
function showAddress(pStore) {
	var mAddress = pStore.attributes['mapaddressfield'];
	var mBalloonHTML = pStore.attributes['balloonhtml'];
	// ====== Perform the Geocoding ======        
	geo.getLocations(mAddress, function (result){
							//map.clearOverlays(); 
							if (result.Status.code == G_GEO_SUCCESS) {
								// ===== If there was more than one result, "ask did you mean" on them all =====
								if (result.Placemark.length > 1) { 
									var p = result.Placemark[0].Point.coordinates;
									place(p[1],p[0],mBalloonHTML);
								}else {// ===== If there was a single marker =====
									var p = result.Placemark[0].Point.coordinates;
									place(p[1],p[0],mBalloonHTML);
								}
							}else {// ====== Decode the error status ======
								var reason="Code "+result.Status.code;
								if (reasons[result.Status.code]) {
									reason = reasons[result.Status.code]
								}
								uiManager.hasHiddenResults = true;
							}
						});
}

function createMarker(point,pBalloonHTML) {
	var mMarker = new GMarker(point,icons['stnd']);
	mMarker.tooltip = '<div class="tooltip">'+pBalloonHTML+'<\/div>';
	GEvent.addListener(mMarker, "click", function() {
										  mMarker.openInfoWindowHtml(pBalloonHTML);
										});
	return mMarker;
}



