// Set custom icons
var shopIcon = new GIcon();
shopIcon.image = global_imgRoot + 'shop_icon.png';
shopIcon.shadow = global_imgRoot + 'shop_icon_shadow.png';
shopIcon.iconSize = new GSize(24, 34);
shopIcon.shadowSize = new GSize(34, 34);
shopIcon.iconAnchor = new GPoint(11, 33);
shopIcon.infoWindowAnchor = new GPoint(23, 0);

// Create and return a marker using a GLatLng and a string
function make_marker(point, shopTitle, shopHTML) {
	var marker = new PdMarker(point, {draggable: true, icon: shopIcon});

	marker.setTooltip(shopTitle);
	marker.setOpacity(90);
	marker.setHoverImage(global_imgRoot + 'shop_icon_hover.png');
	marker.setDetailWinHTML(shopHTML);
	marker.disableDragging()

	return marker;
}

// Shows locations as defined in the header on the GMap
function show_locations() {

	// Initialize bounds of the map
	var minLat = parseFloat(global_lat);
	var maxLat = parseFloat(global_lat);
	var minLon = parseFloat(global_lon);
	var maxLon = parseFloat(global_lon);

	if (typeof itemArray == 'undefined') return false;

	for(var i = 0; i < itemArray.length; i++) {

		var itemLat = parseFloat(itemArray[i]["lat"]);
		var itemLon = parseFloat(itemArray[i]["lon"]);
		var itemTitle = itemArray[i]["city"] + ", " + itemArray[i]["state"] + " (" + itemArray[i]["amount"] + ")";
		var itemHTML = "<span class=\"city\">" + itemArray[i]["city"] + ", " + itemArray[i]["state"] + "</span><span class=\"amount\">" + itemArray[i]["amount"] + "</span>";
		var itemLocation = new GLatLng(itemLat, itemLon);

		// Create a marker of the shop
		global_theMap.addOverlay(make_marker(itemLocation, itemTitle, itemHTML));

	}

}

// Starts the map
function start_GMap() {

	if (GBrowserIsCompatible()) {
		// Load map and add controls
		global_theMap = new GMap2(document.getElementById(global_mapElement));

		// Set the right zoom level and center if we need bounds
		if (typeof global_minlat != 'undefined' && typeof global_maxlat != 'undefined' && typeof global_minlon != 'undefined' && typeof global_maxlon != 'undefined') {
			var mapBounds = new GLatLngBounds(new GLatLng(global_minlat, global_minlon), new GLatLng(global_maxlat, global_maxlon));
			var mapCenter = new GLatLng((global_maxlat + global_minlat) / 2, (global_maxlon + global_minlon) / 2);
			global_theMap.setCenter(mapCenter, global_theMap.getBoundsZoomLevel(mapBounds));
		}
		// Else we know the exact zoom level and center
		else {
			global_theMap.setCenter(new GLatLng(global_lat,global_lon), global_zoom);
		}
		global_theMap.setMapType(eval(global_mapType));

		// Show locations on the map
		show_locations();

		// Add large control
		global_theMap.addControl(new GLargeMapControl());
		global_theMap.addControl(new GMapTypeControl(true));

	}

}

$(document).ready(function(){
	start_GMap();
});