//global variables
var request = new JsonRequest()
var binder = new DataBinder();
var markers = new Object();
var geocoder;
var photocube;
var gx;
var gxBounds = null;
var missionBounds = null;
var quest_middle;
var quest_radius;
var ge;
var showAirnote = AIRNOTE_ID;
var picmarkers = [];
var oldMapType = null;
var map = null;
var trophy = null;//pointer to HTML trophy popup
var trophy_position = 0;//number of pixels the trophy popup moved
var trophy_original = 0;//top pixel position where the trophy is initialized
var trophy_anchor_original = 0;//top pixel position where the anchor is initialized
var trophy_interval = -1;//window.interval to move the trophy
var trophy_running = false;//whether trophy show is running
var trophy_anchor = null;//pointer to HTML trophy button
var hide_me = false;//whether to hide the trophy popup
var slider = null;//pointer to slider node
var lasttimes = new Array();//array of the last position update times
var livemarkers = new Array();//player markers on the map
var playerids = new Array();
var num_playerids = 0;
var trophy_downloaded = false;

function OnTrophyDownload() {
	trophy_downloaded = true;
}

function ShowTrophy() {
	if(trophy_running) return;
	if(hide_me) {
		HideTrophy();
		return;
	}
	if(!trophy_downloaded) {
		window.setTimeout(ShowTrophy,100);
		return;
	}
	trophy_running = true;
	trophy_anchor = document.getElementById("trophy_anchor");
	trophy = document.getElementById("trophy-popup");
	trophy.style.display = "inline";
	var pos1 = $(trophy_anchor).position();
	if(jQuery.browser.msie && jQuery.browser.version < 7)
		trophy_original = pos1.top+trophy_anchor.offsetHeight+1;
	else
		trophy_original = pos1.top+trophy_anchor.offsetHeight+5;
	trophy.style.top = trophy_original+"px";
	trophy_position = 0;
	trophy_anchor.style.position = "absolute";
	if(jQuery.browser.safari) {
		trophy_anchor.style.left = "302px";
		trophy.style.left = "302px";
	} else {
		trophy_anchor.style.left = pos1.left+"px";
		trophy.style.left = pos1.left+"px";
	}
	trophy_anchor.style.top = pos1.top+"px";
	trophy_anchor_original = pos1.top;
	if(jQuery.browser.msie && jQuery.browser.version < 7)
		trophy_anchor.style.width = "168px";
	trophy_interval = window.setInterval(function() {MoveTrophy(true);},10);
}

function MoveTrophy(out) {
	trophy_position += 10;
	var done = false;
	if(trophy_position >= trophy.offsetHeight) {
		window.clearInterval(trophy_interval);
		trophy_interval = -1;
		trophy_position = trophy.offsetHeight;
		if(out) hide_me = true;
		else hide_me = false;
		done = true;
	}
	if(out) {
		trophy.style.top = trophy_original-trophy_position+"px";
		trophy_anchor.style.top = trophy_anchor_original-trophy_position+"px";
		if(done) {
			trophy_running = false;
			trophy_original -= trophy.offsetHeight;
			trophy_anchor_original -= trophy.offsetHeight;
		}
	} else {
		trophy.style.top = trophy_original+trophy_position+"px";
		trophy_anchor.style.top = trophy_anchor_original+trophy_position+"px";
		if(done) {
			trophy_running = false;
			if(!jQuery.browser.opera && !jQuery.browser.msie && !jQuery.browser.safari) 
				trophy_anchor.style.position = "static";
		}
	}
}

function HideTrophy() {
	trophy_position = 0;
	trophy_running = true;
	trophy_interval = window.setInterval(function() {MoveTrophy(false);},10);
}

function DisableLoopingIfPadded() {
	if(slider.padded) slider.DisableLooping();
	else slider.EnableLooping();
}

function PrepareLiveStream() {
	var center = map.getCenter();
	var radius = 0.5*map.getBounds().getSouthWest().distanceFrom(map.getBounds().getNorthEast());
	var url = BASE_URL+"/GetLatestActivePlayersData?lang="+LOCALE_STRING+"&radius="+radius
		+"&latitude="+center.lat()+"&longitude="+center.lng()+"&quest="+QUEST_ID;
	request.send(url,HandlePlayerList);
}

function OpenWorldHistory(url) {
	var fenster = window.open(url, "Usertrack", "width=535,height=440");
	fenster.focus();
}

function HandlePlayerList(players) {
	for(var i = 0; i < players.length; i++) {
		var time = (new Date()).getTime()-10*60*1000;//last 10 minutes
		if(parseFloat(players[i].lastseen) >= time) {
			var id = players[i].id;
			livemarkers[id] = new Marker({"latitude":players[i].latitude,"longitude":players[i].longitude},null,281249,type.BLUE_PLAYER);
			var url = BASE_URL+"/showworldhistory.do?userId="+id+"&_locale="+LOCALE_STRING+"&header=1";
			AddOpenUrlListener(livemarkers[id],url);
			map.addOverlay(livemarkers[id]);
			lasttimes[id] = time;
			SendRequest(id);
			playerids.push(id);
			num_playerids++;
		}
	}
	var interval = -1;
	if(players.length > 0) interval = window.setInterval(SendRequests,30*1000);
	return interval;
}

function AddOpenUrlListener(marker,url) {
	GEvent.addListener(marker,"click",function() {OpenWorldHistory(url);});
}

function SendRequests() {
	for(var i = 0; i < num_playerids; i++)
		SendRequest(playerids[i]);
}

function SendRequest(id) {
	request.send(BASE_URL+"/GetWorldHistoryTracks?gameCharId="+id+"&from="+lasttimes[id],function(data) {HandleNewTrack(data,id);});
}

function HandleNewTrack(data,id) {
	for(var i = 0; i < data[0].length; i++) {
		var track_line_black = GPolyline.fromEncoded({color: "#000000",
			weight: 10,
			opacity: 1,
			points: data[0][i],
			zoomFactor: 32,
			levels: data[1][i],
			numLevels: 4});
		map.addOverlay(track_line_black);
		var track_line_yellow = GPolyline.fromEncoded({color: "#FFDA0B",
			weight: 3,
			opacity: 1,
			points: data[0][i],
			zoomFactor: 32,
			levels: data[1][i],
			numLevels: 4});
		map.addOverlay(track_line_yellow);
	}
	if(data[3] != null && data[3] != "") lasttimes[id] = data[3];
	livemarkers[id].setLatLng(new GLatLng(data[2][1],data[2][0]));
}

function AdjustInfoCellWidths() {
	var max = -1;
	for(var i = 0; i < 6; i++) {
		var cell = document.getElementById("ic"+i);
		if(cell.offsetWidth > max) max = cell.offsetWidth;
	}
	for(var i = 0; i < 6; i++) {
		var cell = document.getElementById("ic"+i);
		cell.style.width = (max-10)+"px";
		var data = document.getElementById("dc"+i);
		data.style.width = (230-max-10)+"px";
	}
}

function load() {
	AdjustInfoCellWidths();
	if(jQuery.browser.msie && jQuery.browser.version < 7)
		document.getElementById("trophy_anchor").style.width = "";
	if(jQuery.browser.safari) {
		document.getElementById("mempic").style.position = "relative";
		slider = new Slider("slider-anchor","slider-entry-template",
				BASE_URL+"/GetMemberPicturesData?quest="+QUEST_ID,null,direction.HORIZONTAL,
				["scroll-left scroll-left-safari","image-slider-list","scroll-right scroll-right-safari","image-entire-slider","slider_separator-mempics"]);
	} else {
		slider = new Slider("slider-anchor","slider-entry-template",
				BASE_URL+"/GetMemberPicturesData?quest="+QUEST_ID,null,direction.HORIZONTAL,
				["scroll-left","image-slider-list","scroll-right","image-entire-slider","slider_separator-mempics"]);
	}
	slider.DisableLooping();
	slider.ondownload = DisableLoopingIfPadded;
	initLogPopup();
	var anchor = document.getElementById("map");
	var maptemp = new Map();
	var dimension = {"width":473,"height":(document.getElementById('mcid').clientHeight+1)};
	maptemp.Initialize(anchor,dimension,CENTER,null,null,map_type.MISSION_DETAILS);
	map = maptemp.GetMap();
	anchor.style.top = "-1px";
	PrepareLiveStream();
    if (GBrowserIsCompatible()) {
		GEvent.addListener(map, "click", globalClickHandler);
		GEvent.addListener(map,'moveend',moveendlistener);
		if (SOLVED == false)
			gx = new GGeoXml(BASE_URL+'/missionregion.do?quest='+QUEST_ID,regionLoaded);
		loadQuests();
		updatePhoto();
		oldMapType = map.getCurrentMapType().getName();
	}
}

function openPicture(picnr) {
	if (picnr != -1) {
		var marker = picmarkers[picnr];
		removePopups();
		map.addOverlay(marker);
		map.photoIcon = marker;
		map.infoBox = marker.infoBox;
		map.addOverlay(map.infoBox);
		GEvent.addDomListener(document.getElementById("closebutton"),"click",removePopups); 
	}	
}

function OpenPicture(latitude,longitude,date,time,author,url) {
	var marker = new Marker({"latitude":latitude,"longitude":longitude},null,null,type.PHOTO_CUBE);
	var data = {
		"date":date,
		"time":time,
		"author":author,
		"url":url
	};
	marker.CreateInfoBox(data);
	removePopups();
	map.addOverlay(marker);
	map.photoIcon = marker;
	map.infoBox = marker.infoBox;
	map.addOverlay(map.infoBox);
	GEvent.addDomListener(document.getElementById("closebutton"),"click",removePopups);
}

function regionLoaded() {
	if (gx.hasLoaded() && gx.loadedCorrectly()) {
		map.addOverlay(gx);
		gxBounds = gx.getDefaultBounds();
		allignAndZoomMap();
	}
}

function globalClickHandler(marker, point) {
	if (marker) {
		// remove all popups and icons
		removePopups();
		
		if(marker.type == type.PHOTO_CUBE) {
			map.addOverlay(marker);
			map.photoIcon = marker;
		}
		
		// if clicked marker has an infobox open it
		if (marker.infoBox) {
			map.addOverlay(marker.infoBox);
			map.infoBox = marker.infoBox;
			GEvent.addDomListener(document.getElementById("closebutton"),"click",removePopups);	 
		}
	}
}

function updateImages(list) {
	for( var i=0; i < list.length; i++) {
    	var mark = new Marker({"latitude":list[i].latitude,"longitude":list[i].longitude},null,null,type.PHOTO_CUBE);
		var data = {
			"date":list[i].date,
			"time":list[i].time,
			"author":list[i].author,
			"url":list[i].url
		};
		mark.CreateInfoBox(data);
		picmarkers[i] = mark;
		if (list[i].active == true)
			openPicture(i);
	}
}

function updatePhoto() {
	request.send(BASE_URL+'/QueryQuestImages?questID='+QUEST_ID+'&anId='+showAirnote+'&lang='+LOCALE_STRING,updateImages);
}

function shrinkText(str, len) {
	var output = "";
	if (str.length <= len)
		output = str;
	else 
		output =  str.substring(0,len-3) + "...";
	return output;
}

function updateQuests(list) {
 	var bounds = new GLatLngBounds();
 	var linepoints = new Array();
 	var cubemarkers = [];
	var photocubes = [];
 	var waypointcount = 0;

	// draw photocubes
	for(var i = 0; i < list.length; i++) {
		if (list[i].type == "PhotoTask") {
			var photomarker = new Marker({"latitude":list[i].latitude,"longitude":list[i].longitude},(new Marker()).GetPhotoIcon(),null,type.MISSION_DETAILS);
			var data = {
				"title":list[i].title,
				"img":list[i].imgId,
				"text":shrinkText(list[i].text,140)
			};
			photomarker.CreateInfoBox(data);
			map.addOverlay(photomarker);
		}
	}

 	// go through list to determine the viewport and do some precalculations
 	for(var i=0; i<list.length; i++) {
		var position = new GLatLng(list[i].latitude,list[i].longitude);
		bounds.extend(position);
 	}
	missionBounds = bounds;

	allignAndZoomMap();
 	
 	// store data for character data
 	quest_middle = bounds.getCenter();
 	quest_range = map.getBounds().getSouthWest().distanceFrom(map.getBounds().getNorthEast());

 	// draw waypoints
 	for(var i=0;i<list.length;i++) {
		var position = new GLatLng(list[i].latitude,list[i].longitude);
 		if (list[i].type == "LocationRiddle" || list[i].type == "Goal" || list[i].type == "MissionEntry") {
 			waypointcount++;
	 		// create countmarker
	 		var name = BASE_URL+"/image/circ_" + (waypointcount) +".png";
	 		var counticon = new GIcon(G_DEFAULT_ICON,name);
		 	counticon.iconSize = new GSize(19,19);
	    	counticon.iconAnchor = new GPoint(9,9);
	    	counticon.shadowSize = new GSize(0,0);
	 		var countmarker = new Marker({"latitude":list[i].latitude,"longitude":list[i].longitude},counticon,-3000,type.MISSION_DETAILS);
	 		var data = {
					"title":list[i].title,
					"img":list[i].imgId,
					"text":shrinkText(list[i].text,140)
				};
			countmarker.CreateInfoBox(data);
			if (list.length > 1)
				map.addOverlay(countmarker);
			// add linepoints
 			linepoints.push(position);
 		}
	}

	// draw route-line
	var polyline2 = new GPolyline(linepoints,"#F58812",4,1);
	map.addOverlay(polyline2);
 	var polyline = new GPolyline(linepoints,"#FFF451",3,1);
	map.addOverlay(polyline);

	var filteredcubes = [];
	for(var i = 0; i < list.length; i++) {
		if (list[i].type == "MissionEntry" || list[i].type == "Goal" || list[i].type == "LocationRiddle")
			filteredcubes.push(list[i]);
	}
	for (var i = 0; i < filteredcubes.length; i++) {
		var marker = null;
		var center = {"latitude":filteredcubes[i].latitude,"longitude":filteredcubes[i].longitude};
		if(filteredcubes[i].type == "MissionEntry")
			marker = new Marker(center,null,null,type.MISSION_ENTRY);
		else if (filteredcubes[i].type == "LocationRiddle")
			marker = new Marker(center,null,null,type.CHECKPOINT);
		else if (filteredcubes[i].type == "Goal")
			marker = new Marker(center,null,null,type.GOAL);
		var data = {
			"title":filteredcubes[i].title,
			"img":filteredcubes[i].imgId,
			"text":shrinkText(filteredcubes[i].text,140)
		};
		marker.CreateInfoBox(data);
		map.addOverlay(marker);
	}
    if (SHOWN_AIRNOTE != null)
    	OpenPicture(SHOWN_AIRNOTE.latitude,SHOWN_AIRNOTE.longitude,SHOWN_AIRNOTE.date,SHOWN_AIRNOTE.time,SHOWN_AIRNOTE.author,SHOWN_AIRNOTE.url);
}	

function updatePictureListLength() {
 	var e =document.getElementById('imglist');
 	var count = 0;
 	for (var i = 0; i< e.childNodes.length;i++) {
 		if (e.childNodes[i].id == 'imgcontainer')
 			count += 1;
 	}
 	document.getElementById('debug').innerHTML += "cn:"+ e.childNodes.length + " determined:"+count;
 	e.style.width = (count*89) + "px";
}
 
function loadQuests() {
 	request.send(BASE_URL+'/QueryQuestRiddles?questID='+QUEST_ID,updateQuests);
}
 
function loadImages() {
	request.send(BASE_URL+'/QueryQuestImages?questID='+QUEST_ID,updateImages);
}

function getEarthInstanceCB(object) {
	ge = object;
	// You can now manipulate ge using the full Google Earth API.
}
	
function maptypelistener() {
	var newMap = map.getCurrentMapType().getName();
	if (newMap == "Earth" && oldMapType != "Earth") {
		map.clearOverlays();
		loadQuests();
	} else if (newMap != "Earth" && oldMapType == "Earth") {
		map.clearOverlays();
		loadQuests();
	}
	oldMapType = newMap;
}
	
function moveendlistener() {}

function removePopups() {
	if (map.infoBox) {
		map.removeOverlay(map.infoBox);
		map.infoBox = null;
	}
	if (map.photoIcon) {
		map.removeOverlay(map.photoIcon);
		map.photoIcon = null;
	}
}

function allignAndZoomMap() {
	var bounds;
	if (missionBounds != null)
		bounds = missionBounds;
	else
		bounds = new GLatLngBounds();
	if(gxBounds != null) {
		bounds.extend(gxBounds.getSouthWest());
		bounds.extend(gxBounds.getNorthEast());
	}
	// set map viewport
	var zoomlevel = map.getBoundsZoomLevel(bounds);
	if (zoomlevel >= 16)
		zoomlevel = 16;
	map.setZoom(zoomlevel);
	map.setCenter(bounds.getCenter());
	// align map
	// check if all points have enough space to borders
	var mapbounds = map.getBounds();
	var msw = mapbounds.getSouthWest();
	var mne = mapbounds.getNorthEast();
	var bsw = bounds.getSouthWest();
	var bne = bounds.getNorthEast();
	var mapsw = map.fromLatLngToDivPixel(msw);
	var mapne = map.fromLatLngToDivPixel(mne);
	var markersw = map.fromLatLngToDivPixel(bsw);
	var markerne = map.fromLatLngToDivPixel(bne);
	var swdiff = Math.min(Math.abs(mapsw.x - markersw.x),Math.abs(mapsw.y - markersw.y));
	var nediff = Math.min(Math.abs(mapne.x - markerne.x),Math.abs(mapne.y - markerne.y));
	// if not: zoom out
	if (swdiff < 60 || nediff < 60)
		map.zoomOut();
}

function FeatureMission(id,featured) {
	if(featured) return;
	var url = BASE_URL+"/multiadmin/featureMission.do?quest="+id;
	request.send(url,OnFeatureMission);
}

function OnFeatureMission(data) {
	if(data.error) alert(data.error);
	else {
		var button = document.getElementById("feature_button");
		button.style.opacity = 0.5;
		button.style.filter = "alpha(opacity=50)";
	}
}