// global google map vars
var imgpath		= "http://" + window.location.hostname + "/public/img/maps/";

// bechtler icon
var bechtlerIcon 				= new GIcon(G_DEFAULT_ICON);
bechtlerIcon.image 				= imgpath + "pin_bechtler.png";
bechtlerIcon.shadow 			= imgpath + "pin_bechtler_shadow.png";
bechtlerIcon.iconSize			= new GSize(39, 42);
bechtlerIcon.shadowSize         = new GSize(60, 44);
bechtlerIcon.iconAnchor 		= new GPoint(19, 42);
bechtlerIcon.infoWindowAnchor 	= new GPoint(19, 2);

// parking icon
var parkingIcon					= new GIcon(G_DEFAULT_ICON);
parkingIcon.image 				= imgpath + "pin_parking.png";
parkingIcon.shadow 				= imgpath + "pin_parking_shadow.png";
parkingIcon.iconSize 			= new GSize(11, 14);
parkingIcon.shadowSize         	= new GSize(19, 14);
parkingIcon.iconAnchor 			= new GPoint(5, 14);
parkingIcon.infoWindowAnchor 	= new GPoint(5, 2);

$(document).ready(function() {
    // prep the google map
    if (GBrowserIsCompatible()) {
		// ensure all maps get created
		var maplen = maps.length;
		if (maplen > 0) {
			for (var i = 0; i < maplen; i++) {
				createMap(maps[i]);
			}
		}
    }
});

function createMap(singleMap) {
		singleMap.map = new GMap2(document.getElementById(singleMap.mapContainerId), { size: new GSize(494, 288) });
        singleMap.map.setCenter(new GLatLng(0, 0), 13);
        // set custom UI
        var customUI = singleMap.map.getDefaultUI();
        customUI.controls.smallzoomcontrol3d    = false;
        customUI.controls.maptypecontrol        = true;
        customUI.controls.menumaptypecontrol    = true;
        customUI.controls.scalecontrol          = false;
        customUI.controls.largemapcontrol3d     = true;
        customUI.controls.scalecontrol          = false;
        customUI.maptypes.hybrid                = false;
        customUI.maptypes.physical              = false;
        singleMap.map.setUI(customUI);

		// load the map
		loadGoogleMap(singleMap);
}

/* load the google map */
function loadGoogleMap(singleMap) {
	// remove any markers yhat may exist
	singleMap.map.clearOverlays();
	// initialize map centerpoint
	singleMap.map.setCenter(new GLatLng(35.2244444, -80.84711), 4);
	// get all valid map points
	$.post('/maps/getMapPoints', { mapId : singleMap.mapId }, function(json) { displayMapPoints(json, singleMap); }, 'json');
}

/* display map point results on the map */
function displayMapPoints(json, singleMap) {
	if (json == 'error') {
		alert('An error occurred attempting to load map markers.');
		return false;
	} else {
		// clear overlays
		singleMap.map.clearOverlays();
		// add new markers
		var l = json.length;
		for (var i = 0; i < l; i++) {
			addMarker(json[i], singleMap, i);
		}
		// reposition map
		repositionMap(singleMap);
	}
}

/* add a marker on the map */
function addMarker(json, singleMap, index) {
	// set the pin type
	var icon;
	if (json.icon == '') {
		icon = new GIcon(G_DEFAULT_ICON);
	} else if (json.icon == 'bechtler') {
		icon = new GIcon(bechtlerIcon);
	} else if (json.icon == 'parking') {
		icon = new GIcon(parkingIcon);
	}

	// create option to store icon
	var options = { icon: icon };
    // create point
    var point = new GLatLng(json.lat, json.lon);
    // add to array of points
    singleMap.allpoints.push(point);
    // generate marker
    var marker = new GMarker(point, options);
	// handle tooltip
	if (json.show_tooltip == 1) {
		var tooltip = new Tooltip(marker, generateTooltipContent(json), 1);
		marker.tooltip = tooltip;
		marker.isInfoWindowOpen = false;
	}
	// add to array of markers
	singleMap.allmarkers.push(marker);

    // open custom window on click
	if (json.show_tooltip == 1) {

		// gererate the output
		var html = generateTooltipContent(json);

		GEvent.addListener(marker, "click", function() {
			this.openInfoWindowHtml(html);
			/*
			if (!this.isInfoWindowOpen && !this.isHidden()) {
				hideAllMarkers(singleMap);
				this.tooltip.show();
				this.isInfoWindowOpen = true;
				var pt = marker.getLatLng();
				var newpt = new GLatLng(parseFloat(pt.lat()) + .03, parseFloat(pt.lng()));
				singleMap.map.panTo(newpt);
			} else {
				this.tooltip.hide();
				this.isInfoWindowOpen = false;
			}
			*/
		});
	}

    // add pointer to map
    singleMap.map.addOverlay(marker);

	if (json.show_tooltip == 1) {
		singleMap.map.addOverlay(tooltip);
	}
}

/* generates tooltip HTML */
function generateTooltipContent(json) {
	var html = [];
	//html.push('<div class="top"></div>');
	html.push('<div class="tooltip-content">');
	html.push('<h5>' + json.title + '</h5>');
	html.push('<p>');
	html.push(json.address + '<br />');
	if (json.address2 != null && json.address2.length > 0) html.push(json.address2 + '<br />');
	html.push(json.city + ', ' + json.state + ' ' + json.zip + '<br />');
	html.push('</p>');
	if (json.description != null && json.description.length > 0) html.push('<p>' + json.description + '</p>');
	var directionStr = json.address;
	directionStr += ', ';
	if (json.address2 != null && json.address2.length > 0) {
		directionStr += json.address2 + ', ';
	}
	directionStr += json.city + ', ' + json.state + ' ' + json.zip;
	html.push('<a href="http://maps.google.com/maps?saddr=&daddr=' + encodeURI(directionStr) + '" target="_blank">get driving directions</a>');
	html.push('</div>');
	//html.push('<div class="bottom"></div>');
	return html.join("");
}

/* reposition the map to show all pointers */
function repositionMap(singleMap) {
    var count = 0;
    var x, y, minX, maxX, minY, maxY, span;
    var numPoints = singleMap.allpoints.length;
    for (var i = 0; i < numPoints; i++) {
        curPoint = singleMap.allpoints[i];
        x = singleMap.allpoints[i].lat();
        y = singleMap.allpoints[i].lng();
        if (count == 0) {
            minX = maxX = x;
            minY = maxY = y;
        } else {
            if (x < minX) minX = x;
            if (x > maxX) maxX = x;
            if (y < minY) minY = y;
            if (y > maxY) maxY = y;
        }
        count++;
    }

    if (count == 1) {
        singleMap.map.checkResize();
        singleMap.map.setCenter(new GLatLng(x,y), singleMap.map.getZoom());
    } else if (count > 1) {
		var center 	= new GLatLng((minX + maxX) / 2, (minY + maxY) / 2)
		span 		= new GSize(Math.abs(maxX - minX), Math.abs(maxY - minY));
        slopWid     = (span.width * 10) / 200;   // 5 percent
        slopHgt     = (span.height * 10) / 200;  // 5 percent
        span.width  *= 1 + 2 / 100;
        span.height *= 1 + 2 / 100;
		deltaHgt 	= (span.height * 10) / 100;    // 10 percent
		center 		= new GLatLng(center.lat() + deltaHgt, center.lng());
		var bounds 	= new GLatLngBounds(new GLatLng(minX-slopHgt, minY-slopWid), new GLatLng(maxX+slopHgt, maxY+slopWid)); // sw, ne
        singleMap.map.checkResize();
		var zoom = singleMap.map.getBoundsZoomLevel(bounds);
        singleMap.map.setCenter(center, zoom);
    }
}

function hideAllMarkers(singleMap) {
	var markerlen = singleMap.allmarkers.length;
	for (var i = 0; i < markerlen; i++) {
		if (singleMap.allmarkers[i].isInfoWindowOpen == true) {
			singleMap.allmarkers[i].isInfoWindowOpen = false;
			singleMap.allmarkers[i].tooltip.hide();
		}
	}
}
