// Global vars
var gMap;
var gBusyMarker, gHoverMarker;
var gMarkerMgr;
var gBusyIcon, gHoverIcon, gContestIcon;
var gStreetLevelZoom=15;
var gIsInfoOpen=false;
var gContest=null;
var gInitialLoad=1;
var gNextClue=new Object();
var gMarkers = new Object();
var gGeocoder;
var gAddrCleared=false;

function Contest(id, iconurl, iconsz, flickr_photosetid, zoom) {
this.id = id;
this.iconurl = iconurl;
this.iconsz = iconsz;
this.flickr_photosetid = flickr_photosetid;
this.zoom = zoom;
// to be set on initial load
this.totalmarks = null;
this.starttime = null;
this.numtagged = null;
}

function clearAddress() {
if (gAddrCleared) { return; }
document.findplaceform.findplace.value="";
gAddrCleared=true;
}

function showarrow(flag, num) {
	if (num == undefined) { return; }
	marker = gMarkers[num];
	if (marker == undefined) { return; }
	if (flag) {
		gHoverMarker = new GMarker(marker.getPoint(), { icon: gHoverIcon });
		gHoverMarker.markerId = num;
		gMap.addOverlay(gHoverMarker);
	} else {
		gHoverMarker.remove();
	}
}

function createIcon(url, size, shdurl, shdsize) {
	if (!url || !size) { return null; }
	var gicon = new GIcon();
	gicon.image = url;
	var arr = size.split(',');
	var w = parseInt(arr[0]);
	var h = parseInt(arr[1]);
	gicon.iconSize = new GSize(w,h);
	gicon.iconAnchor = new GPoint(w/2, h);
	gicon.infoWindowAnchor = new GPoint(w/2, 1);
	if (shdurl && shdsize) {
		gicon.shadow = shdurl;
		arr = shdsize.split(',');
		w = parseInt(arr[0]);
		h = parseInt(arr[1]);
		gicon.shadowSize = new GSize(w,h);
	}
	return gicon;
}

function markerNumClick(seqno) {
	markerClick(gMarkers[seqno]);
}

function markerClick(marker) {
	if (!marker || !marker.seqno) { return; }
	var html = '<b>'+marker.seqno+'. '+marker.title+'</b><br />';
	if (marker.photourl) {
		html += getClueImg(marker.photourl);
	}
	html += marker.clue;
	if (marker.notvisited) {
		html += '<br /><br /><input type="button" class="btn" value="Tag It" onclick="markFound();" />';
	}
	marker.openInfoWindowHtml('<div class="infoWindow">'+html+'</div>');
}

function displayMarkers(x1, y1, x2, y2) {
	if (!gMap || !gContest) { return; }

	removeNextClueMarker();
	var fitBounds=null;
	if (gInitialLoad) {
		fitBounds=new GLatLngBounds();
	}

	var action = "fun/tagplaces/getContestMarks.php";
	removeBusyMarker();
	var params = 'id='+gContest.id;
	params += '&b='+x1+','+y1+','+x2+','+y2;
	params += '&z='+gMap.getZoom();
	params += '&init='+gInitialLoad;
	// reset initialLoad flag

	showMapLoading(true);
	makeSecureRequest(action, params, function(data) {
		var xml = GXml.parse(data);
		var errorTag = xml.documentElement.getElementsByTagName("error");
		if (errorTag != undefined && errorTag.length > 0) {
			var errorcode = errorTag[0].getAttribute("code");
			if (errorcode == "3") { // severe error code
				showMapLoading(false);
				alert("We have encountered a Server Error. Please try again after some time");
				return;
			}
			if (errorcode == "4") { // login required
				showMapLoading(false);
				document.getElementById("headingid").innerHTML = '<a href="loginback.php">Login to start playing</a>';
				return;
			}
		}
		var summaryTag = xml.documentElement.getElementsByTagName("summary");
		if (summaryTag != undefined && summaryTag.length > 0) {
			tmp = summaryTag[0].getAttribute("totalmarks");
			if (tmp != undefined && tmp.length > 0) gContest.totalmarks = tmp;
			tmp = summaryTag[0].getAttribute("starttime");
			if (tmp != undefined && tmp.length > 0) gContest.starttime = parseInt(tmp);
			tmp = summaryTag[0].getAttribute("numtagged");
			if (tmp != undefined && tmp.length > 0) gContest.numtagged = tmp;
			tmp = summaryTag[0].getAttribute("currtime");
			if (tmp != undefined && tmp.length > 0) gContest.currtime = parseInt(tmp);
		}
		var completedTag = xml.documentElement.getElementsByTagName("completed");
		if (completedTag != undefined && completedTag.length > 0) {
			tmp = completedTag[0].getAttribute("endtime");
			if (tmp != undefined && tmp.length > 0) gContest.endtime = parseInt(tmp);
		}
		var nextclueTag = xml.documentElement.getElementsByTagName("nextclue");
		if (nextclueTag != undefined && nextclueTag.length > 0) {
			gNextClue=new Object();
			var clue = GXml.value(nextclueTag[0].getElementsByTagName("clue")[0]);
			clue = clue.slice(10, -4); // remove enclosing CDATA tags
			var seqno = nextclueTag[0].getAttribute("seqno");
			var found = nextclueTag[0].getAttribute("found");
			gNextClue.seqno = seqno;
			gNextClue.clue = clue;
			var photourl = GXml.value(nextclueTag[0].getElementsByTagName("photourl")[0]);
			gNextClue.photourl = photourl;
			gNextClue.found = found;
			if (found == "1") {
				var title = GXml.value(nextclueTag[0].getElementsByTagName("title")[0]);
				var lat = GXml.value(nextclueTag[0].getElementsByTagName("lat")[0]);
				var lng = GXml.value(nextclueTag[0].getElementsByTagName("lng")[0]);
				gNextClue.marker = new GMarker(new GLatLng(parseFloat(lat), parseFloat(lng)));
				gNextClue.marker.title = title;
				gNextClue.marker.seqno = seqno;
				gNextClue.marker.photourl = photourl;
				gNextClue.marker.clue = clue;
				gNextClue.marker.notvisited=true;
				gMap.addOverlay(gNextClue.marker);
			}
		}
		var markers = xml.documentElement.getElementsByTagName("usermark");
		var batch = [];
		for (var i = 0; i < markers.length; i++) {
			var marker = markers[i];
			var seqno = marker.getAttribute("seqno");
			var tagtime = marker.getAttribute("tagtime");

			var lat, lng;
			var title=null, clue=null, lat=null, lng=null, photourl=null;
			title = GXml.value(marker.getElementsByTagName("title")[0]);
			clue = GXml.value(marker.getElementsByTagName("clue")[0]);
			clue=clue.slice(10, -4); // remove enclosing CDATA tags
			lat = GXml.value(marker.getElementsByTagName("lat")[0]);
			lng = GXml.value(marker.getElementsByTagName("lng")[0]);
			photourl = GXml.value(marker.getElementsByTagName("photourl")[0]);

			var point = new GLatLng(lat, lng);

			var mapMarker = createMarker(point, seqno, title, clue, tagtime, photourl);
			if (fitBounds) { fitBounds.extend(point); }

			batch.push(mapMarker);
		}
		if (batch.length > 0) {
			bestFit(gMap, fitBounds);
			getMM().addMarkers(batch, 0);
			getMM().refresh();
		}
		fillSideBar(gInitialLoad);
		gInitialLoad=0;
		showMapLoading(false);
	});
}

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

function createMarker(point, seqno, title, clue, tagtime, photourl) {
	var micon = createIcon("images/numblue/marker"+seqno+".png", "20,34");
	var mapMarker = new GMarker(point, { title: title, icon: micon});
	mapMarker.seqno = seqno;
	mapMarker.tagtime = tagtime;
	mapMarker.title = title;
	mapMarker.clue = clue;
	mapMarker.photourl = photourl;
	gMarkers[seqno] = mapMarker;
	return mapMarker;
}

function moveEndCB() {
	if (!gMap) { return; }
	if (gIsInfoOpen) { return; } // dont refresh map if the moveend is caused by an open infowindow
	setCookie("smLastPos", gMap.getCenter().lat()+","+gMap.getCenter().lng()+","+gMap.getZoom());
	refreshMap();
}

function markFound() {
	gNextClue.marker.closeInfoWindow();
	makeSecureRequest("fun/tagplaces/contestPlay.php", "id="+gContest.id+"&action=found&seqno="+gNextClue.marker.seqno, function(data) {
		setTimeout('refreshMap();', 600);
	});
}

function removeNextClueMarker() {
	if (gNextClue && gNextClue.marker) {
		gNextClue.marker.remove();
		gNextClue.marker=null;
	}
	gNextClue=null;
}

function getMM() {
	if (!gMarkerMgr || gMarkerMgr == undefined) {
		gMarkerMgr = new MarkerManager(gMap);
	}
	return gMarkerMgr;
}

function initMap() {
	if (!gMap) { return; }
	getMM().clearMarkers();
	gMap.clearOverlays();
	refreshMap();
}

function refreshMap(bounds) {
	var zoomdiv = document.getElementById("zoomid");
	if (gMap && zoomdiv) {
		var zoom = gMap.getZoom();
		if (zoom >= gContest.zoom) { zoomdiv.style.background = "#33FF00"; }
		else { zoomdiv.style.background = "#ff9966"; }
		zoomdiv.innerHTML = "Zoom: "+gMap.getZoom();
	}
	refreshGrids(bounds);
}

function refreshGrids(bounds) {
	if (!gMap) { return; }

	if (!bounds || bounds == undefined) {
		bounds = gMap.getBounds();
	}
	//showMsg('ajax/getMarkers.php?sw='+bounds.getSouthWest().toUrlValue(6)+'&ne='+bounds.getNorthEast().toUrlValue(6)+'&z='+gMap.getZoom());
	var x1 = bounds.getSouthWest().lat();
	var y1 = bounds.getSouthWest().lng();
	var x2 = bounds.getNorthEast().lat();
	var y2 = bounds.getNorthEast().lng();
	if (y1 > y2) { y2 = y2+360; }

	displayMarkers(x1, y1, x2, y2);

	gPrevBounds = new GLatLngBounds(new GLatLng(x1,y1), new GLatLng(x2,y2));
}

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

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);

	// create hover icon
	gHoverIcon = new GIcon();
	gHoverIcon.image = getFullUrl("images/mapicons/himark.gif");
	gHoverIcon.iconSize = new GSize(32,32);
	gHoverIcon.iconAnchor = new GPoint(16,32);

	// create contest icon
	gContestIcon = new GIcon();
	gContestIcon.image = getFullUrl("images/mapicons/dnarrow.png");
	gContestIcon.iconSize = new GSize(24,24);
	gContestIcon.iconAnchor = new GPoint(12,12);

	gMap = new GMap2(document.getElementById("gmap"));
	gMap.addControl(new GLargeMapControl());
	gMap.addControl(new GMapTypeControl());
	gMap.setMapType(G_SATELLITE_MAP);

	// if the user is logged in and the home location is set, then go to the home location

	var mydiv = document.getElementById("mydiv").innerHTML;
	if (mydiv != undefined && mydiv != null) {
		var mydivarr = mydiv.split(',');
		if (mydivarr[0] == "contest") {
			gContest=new Contest(mydivarr[1],mydivarr[2],mydivarr[3],mydivarr[4],mydivarr[5]);
		}
	}

	// read the cookie for the last position
	gMap.setCenter(new GLatLng(22.998852,79.277344), 1); // world view

	initMap();

	GEvent.addListener(gMap, "infowindowopen", function() {
		gIsInfoOpen=true;
//		gInfoOpenCenter=gMap.getCenter();
	});
	GEvent.addListener(gMap, "infowindowclose", function() {
		gIsInfoOpen=false;
//		gMap.setCenter(gInfoOpenCenter);
	});
	GEvent.addListener(gMap, "moveend", moveEndCB);
	GEvent.addListener(gMap, "click", function(marker, point, overlaypoint) {
		if (overlaypoint) { point = overlaypoint; }
		if (marker) { markerClick(marker); }
	});
}

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

function startPlaying() {
	var params="id="+gContest.id+"&action=start";
	makeSecureRequest("fun/tagplaces/contestPlay.php", params, function(data) {
		document.getElementById("headingid").innerHTML='';
		setTimeout('refreshMap()', 600);
	});
}

function reloadDone() {
	var loadingdiv = document.getElementById("msgloading");
	loadingdiv.innerHTML = "Messages refreshed !!!";
	setTimeout('document.getElementById("msgloading").innerHTML=""', 1200);
}

function reloadMsgs() {
	var div = document.getElementById("msglist");
	var loadingdiv = document.getElementById("msgloading");
	loadingdiv.innerHTML = getLoadingHTML();
	setTimeout('reloadWithDelay()', 1000);
}

function reloadWithDelay() {
	var params="id="+gContest.id;
	makeSecureRequest("fun/tagplaces/getContestMsgs.php", params, function(data) {
		var div = document.getElementById("msglist");
		div.innerHTML = data;
		setTimeout('reloadDone()', 300);
	});
	return false;
}

function postMsgDone() {
	hideShowDiv("post2", "post1");
	reloadMsgs();
}

function fillSideBar(init) {
	if (!gContest) { return; }
   	var nextcluediv = document.getElementById("nextclueid");
   	var marksfounddiv = document.getElementById("marksfoundid");

	if (!gContest.starttime) {
		document.getElementById("nextclueid").innerHTML='<input style="font-size:20px;" type="button" onclick="startPlaying();" class="startbtn" value="Click to Start" />';
		return;
	}
	if (gContest.endtime) {
		var timediff = new Date(gContest.endtime) - new Date(gContest.starttime);
		document.getElementById("nextclueid").innerHTML='All clues found in ' + getTimeInterval(timediff);
		document.getElementById("headingid").innerHTML='Congratulations !!!';
	} else {
		var timediff = new Date(gContest.currtime) - new Date(gContest.starttime);
		document.getElementById("headingid").innerHTML='Elapsed time: ' + getTimeInterval(timediff);
	}

	if (gNextClue) {
		var html = '<span style="background:#f0e05a;font-weight:bold;padding:3px;">Next Clue:</span><br />';
		if (gNextClue.photourl) {
			html += getClueImg(gNextClue.photourl);
		}
		html += gNextClue.clue;
		nextcluediv.innerHTML = html;
	}

	// always refresh the found markers list
	var html = "";
	for (seqno in gMarkers) {
		var marker = gMarkers[seqno];
		html += '<p><a style="vertical-align:bottom;" href="javascript:{}" onclick=markerNumClick('+marker.seqno+') title="Click to show this on the map">'+marker.seqno+'. '+marker.title+'</a></p>';
	}
	if (html != "") { // unhide the marksfound div
		document.getElementById("marksfound").style.display="block";
	}
	marksfounddiv.innerHTML = html;
}

function getClueImg(photourl) {
purl_s = photourl.replace(".jpg", "_t.jpg");
$html = '<a style="font-weight:normal;font-size:12px;" target="_blank" href="'+photourl+'">Click to enlarge</a><br />';
$html += '<a target="_blank" href="'+photourl+'"><img align="left" src="'+purl_s+'" style="margin-right:5px;" /></a>';
return $html;
}

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

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

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

function showAddress() {
	var address = document.findplaceform.findplace.value;
	gGeocoder.getLatLng(address, function(point) {
		if (!point) {
			alert(address + " not found. Please try to be more specific.");
		} else {
			gMap.setCenter(point, 12);
		}
	});
	return false;
}

