// Global vars
var gMap;
var gBusyMarker;
var gBusyIcon;
var gMarkerMgr;
var gBaseUrl=null;
var gPoints=null;
var gCount=0;
var gPolygon=null;
var gWards=new Object();
var gShowAll=false;
var gDefaultMsg="Click on the map to get the Ward information";

function showMapLoading(flag) {
	if (flag) {
		gBusyMarker = new GMarker(gMap.getCenter(), gBusyIcon);
		gMap.addOverlay(gBusyMarker);
	} else {
		// add a little delay before removing the busy-marker
		setTimeout('removeBusyMarker()', 600);
	}
}

function removeBusyMarker() {
	gBusyMarker.remove();
}


function getLoadingHTML() {
	return '<img src="images/loading.gif"/>&nbsp;<i>Loading - Please Wait...</i>';
}

function getFullUrl(suburl) {
if (gBaseUrl) return gBaseUrl + "/" + suburl;
else return suburl;
}

function moveEndCB() {
	if (!gMap) { return; }
	setCookie("smLastPos", gMap.getCenter().lat()+","+gMap.getCenter().lng()+","+gMap.getZoom());
}

function loadMap() {

	// create mapbusy icon
	gBusyIcon = new GIcon();
	gBusyIcon.image = getFullUrl("images/mapbusy.gif");
	gBusyIcon.iconSize = new GSize(48, 48);
	gBusyIcon.iconAnchor = new GPoint(24, 24);
	gBusyIcon.infoWindowAnchor = new GPoint(5, 1);

	gMap = new GMap2(document.getElementById("wardmap"));
	gMap.addControl(new GLargeMapControl());
	gMap.addControl(new GMapTypeControl());
//	gMap.addControl(new google.maps.LocalSearch());
	var smLastPos = getCookie("smLastPos");
//	if (smLastPos) {
//		var arr = smLastPos.split(',');
//		gMap.setCenter(new GLatLng(parseFloat(arr[0]), parseFloat(arr[1])), parseInt(arr[2]));
//	} else {
		gMap.setCenter(new GLatLng(18.535769,73.852072), 12); // center around Pune
//	}

	GEvent.addListener(gMap, "click", function(marker, point, overlaypoint) {
if (point) pip(point);
	});
	GEvent.addListener(gMap, "moveend", moveEndCB);
}

function pip(point) {
	makeSecureRequest("getAreaClicked.php", "lat="+point.lat()+"&lng="+point.lng(), function(data) {
		parseArea(point, data);
	});
}

function load() {
	if (GBrowserIsCompatible()) {
		loadMap();
		showAll();
	} else {
		alert("Browser is not compatible: Supported browsers are Firefox v2 and IE v6 and above");
	}
}

function showPoly(poly) {
	if (poly) {
	gMap.addOverlay(poly);
//		if (!gShowAll) {
//			var bounds = poly.getBounds();
//			bestFit(gMap, bounds);
//		}
	}
}

function parseArea(point, data) {
	var lines = data.split("\n");
	var id=null, areatype=null, title=null, details=null, points=null;
	for (var i=0; i<lines.length; ++i) {
		if (lines[i] == "") { continue; }
		var idx=lines[i].indexOf("=");
		var key = lines[i].substr(0,idx);
		var val = lines[i].substr(idx+1);
		if (key == "id") { id = val; }
		if (key == "areatype") { areatype = val; }
		if (key == "title") { title = val; }
		if (key == "details") { details = val; }
		if (key == "points") { points = val; }
	}
	if (id != null && areatype != null && title != null && details != null && points != null) {
		var poly = gWards[":"+id];
		if (!poly) {
			var parr = points.split(":");
			for (var i=0; i<parr.length; ++i) {
				var larr = parr[i].split(",");
				parr[i] = new GLatLng(parseFloat(larr[0]),parseFloat(larr[1]));
			}
			poly = createPolygon(id,areatype,title,details,parr,false,"#0000ff","#0000ff");
			if (!gShowAll) { showPoly(poly); }
			gWards[":"+id] = poly;
		}
		polyClick(poly);
	} else {
		postLog("2", "showArea error for areaid:"+id+" data="+data);
		alert("Problem displaying the selected area - we have recorded this issue. Please try again later.");
	}
}

function createPolygon(id,areatype,title,details,parr,editable,linecolor,shadecolor) {
	var poly = new GPolygon(parr, linecolor, 1, 1, shadecolor, 0.2);
	poly.areaid=id;
	poly.areatype=areatype;
	poly.title=title;
	poly.details=details;
	if (editable) { poly.enableEditing(); }
	if (title) {
//	GEvent.addListener(poly, "mouseover", function() { polyClick(poly); });
//	GEvent.addListener(poly, "mouseout", function() { gMap.closeInfoWindow(); });
	GEvent.addListener(poly, "click", function(point) { polyClick(poly); });
	}
	return poly;
}

function polyClick(poly) {
GDownloadUrl("/getWardProps.php?areaid="+poly.areaid, function(data, responseCode) {
var html='<div class="infoWindow"><b>'+poly.title+"</b>"+"<br /><br />"+data+"</div>";
gMap.openInfoWindowHtml(poly.getBounds().getCenter(), html);
});
}

function bestFit(map, bounds) {
if (!bounds) { return; }
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(bounds.getCenter());
}

function showAllWards() {
	showMapLoading(true);
	GDownloadUrl("getArea.php", function(data, responseCode) {
		var lines = data.split("\n");
		for (i=0; i<lines.length; ++i) {
			if (lines[i] == "") { continue; }
			var areaid = lines[i];
			if (!areaid || areaid == "") { continue; }
			showArea(areaid);
		}
		showMapLoading(false);
	});
}

function showAll(areatype) {
areatype=2;
	var fitBounds=new GLatLngBounds();
	gMap.clearOverlays();
	gShowAll=true;
	showMapLoading(true);
	makeSecureRequest("getArea.php", "t="+areatype, function(data) {
		var lines = data.split("\n");
		var id=null, areatype=null, title=null, details=null, points=null;
		for (var i=0; i<lines.length; ++i) {
			if (lines[i] == "") { continue; }
			var idx=lines[i].indexOf("=");
			var key = lines[i].substr(0,idx);
			var val = lines[i].substr(idx+1);
			if (key == "id") { id = val; }
			if (key == "areatype") { areatype = val; }
			if (key == "title") { title = val; }
			if (key == "details") { details = val; }
			if (key == "points") { points = val; }
			if (key == "end" && id != null && areatype != null && title != null && details != null && points != null) {
				var parr = points.split(":");
				for (var j=0; j<parr.length; ++j) {
					var larr = parr[j].split(",");
					parr[j] = new GLatLng(parseFloat(larr[0]),parseFloat(larr[1]));
				}
				var poly = createPolygon(id,areatype,title,details,parr,false,"#0000ff","#0000ff");
				showPoly(poly);
//				fitBounds.extend(poly.getVertex(1));
			}
		}
		gShowAll=false;
//		gMap.setZoom(gMap.getBoundsZoomLevel(fitBounds));
//		gMap.setCenter(fitBounds.getCenter());
		showMapLoading(false);
	});
}


