//global constants

//global variables
var map = null;
var maptimer = 0;
var wayPointActive = null;
var wayPointLive = null;
var wayPointActiveLive = null;
var wayPoint = null;
var mouseovermap = false;
var curList = null;
var curIdx = 0;
var active_live_marker = null;
var active_not_live_marker = null;
var slider = null;
var activity_slider = null;
var active_entry = -1;
var map_mode = true;
var reload_interval = -1;
var active_class = "map_mode-active";
var inactive_class = "map_mode-passive";

// custom jquery fix for cleartype bug
(function($) {
	$.fn.ClearTypeFadeTo = function(options) {
		if (options)
			$(this)
				.show()
				.each(function() {
					if (jQuery.browser.msie) {
						// Save the original background color
						$(this).attr('oBgColor', $(this).css('background-color'));
						// Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text)
						$(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
					}
				})
				.fadeTo(options.speed, options.opacity, function() {
					if (jQuery.browser.msie) {
						// ClearType can only be turned back on if this is a full fade in or
						// fade out. Partial opacity will still have the problem because the
						// filter style must remain. So, in the latter case, we will leave the
						// background color and 'filter' style in place.
						if (options.opacity == 0 || options.opacity == 1) {
							// Reset the background color if we saved it previously
							$(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
							// Remove the 'filter' style to restore ClearType functionality.
							$(this).get(0).style.removeAttribute('filter');
						}
					}
					if (options.callback != undefined) options.callback();
				});
	};

	$.fn.ClearTypeFadeIn = function(options) {
		if (options)
			$(this)
				.css({ opacity: 0 })
				.ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
	};

	$.fn.ClearTypeFadeOut = function(options) {
		if (options)
			$(this)
				.css({ opacity: 1 })
				.ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
	};
})(jQuery);

function initActivityStream() {
	var maptemp = new Map();
	var anchor = document.getElementById("activitymap");
	var dimension = {"width":780,"height":144};
	if(KURZ) dimension = {"width":550,"height":144};
	var center = {"latitude":49.0087,"longitude":8.4104};
	map = maptemp.Initialize(anchor,dimension,center,4,false,map_type.ACTIVITY_STREAM);
	
	wayPoint = new GIcon(G_DEFAULT_ICON,BASE_URL+'/image/icons/mapmarkers/player_offline_inactive.png');
	wayPoint.iconSize = new GSize(25, 25);
	wayPoint.iconAnchor = new GPoint(10,10);
	wayPoint.shadowSize = new GSize(0, 0);
	
	wayPointLive = new GIcon(G_DEFAULT_ICON,MARKER_NOT_CURRENT_LIVE);
	wayPointLive.iconSize = new GSize(25, 25);
	wayPointLive.iconAnchor = new GPoint(10,10);
	wayPointLive.shadowSize = new GSize(0, 0);
	
	wayPointActive = new GIcon(G_DEFAULT_ICON,BASE_URL+'/image/icons/mapmarkers/player_offline_active.png');
	wayPointActive.iconSize = new GSize(25, 25);
	wayPointActive.iconAnchor = new GPoint(12,12);
	wayPointActive.shadowSize = new GSize(0, 0);
	
	wayPointActiveLive = new GIcon(G_DEFAULT_ICON,MARKER_CURRENT_LIVE);
	wayPointActiveLive.iconSize = new GSize(25, 25);
	wayPointActiveLive.iconAnchor = new GPoint(10,10);
	wayPointActiveLive.shadowSize = new GSize(0, 0);
	
	SwitchMode();
}

function SetupSliders() {
	var classes = ["scroll-left-activity-stream aslang","activity-stream-slider-list aslang","scroll-right-activity-stream aslang"];
	var mclasses = ["player-stream-scroll-left pslangsl","player-stream-slider-list pslang","player-stream-scroll-right pslangsr","","slider_separator-as"];
	if(KURZ) {
		classes = ["scroll-left-activity-stream askurz","activity-stream-slider-list askurz","scroll-right-activity-stream askurz"];
		mclasses = ["player-stream-scroll-left pskurzsl","player-stream-slider-list pskurz","player-stream-scroll-right pskurzsr","","slider_separator-as"];
	}
	if(map_mode) {
		slider = new Slider("slider-anchor","slider-entry-template-map",
				BASE_URL+"/GetLatestActivePlayersData?lang="+LOCALE_STRING,null,direction.HORIZONTAL,
				mclasses);
	} else {
		slider = new Slider("slider-anchor","slider-entry-template",
			BASE_URL+"/GetLatestActivePlayersData?lang="+LOCALE_STRING,null,direction.VERTICAL,classes);
		slider.EnableScrollbar("player-stream-scrollbar",266);
	}
	slider.DisableLooping();
	//slider.EnableCentering();
	if(!map_mode) {
		activity_slider = new Slider("activity-slider-anchor","activity-slider-entry-template",
				BASE_URL+"/QueryLatestActivities?lang="+LOCALE_STRING,null,direction.VERTICAL,classes);
		activity_slider.DisableLooping();
		activity_slider.EnableScrollbar("activity-stream-scrollbar",266);
		activity_slider.ondownload = ProcessActivityEntryTexts;
	}
	if(!jQuery.browser.msie) slider.ondownload = ProcessInitialSliderResponse;
}

function ProcessInitialSliderResponse(data) {
	var temp = new Array();
	for(var j = 3; j < data.length; j++)
		temp.push(data[j]);
	updateActivityStream(temp);
	slider.ondownload = null;
}
		
function reloadPlayers() {
	var clause = !mouseovermap && !slider.mouseover && !slider.sliding && !(slider.scrollbar != null && slider.scrollbar.active);
	if(!map_mode) clause = clause && !activity_slider.mouseover;
	if(clause) request.send(BASE_URL+"/GetLatestActivePlayersData?lang="+LOCALE_STRING,update)
}

function update(list) {
	slider.reset(list);
	if(!map_mode) activity_slider.reset();
	updateActivityStream(list);
}

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

function updateActivityStream(list) {
	curList = list;
	curIdx = 0;
	map.clearOverlays();
	map.selectedMarker = null;
	// process all players
	for (var i = 0; i < curList.length; i++) {
		// create marker on map
		var player = curList[i];
		if(curList[i].separator) continue;
		var newpos = new GLatLng(player.latitude, player.longitude);
		var image_to_use = wayPoint;
		if(player.active)
			image_to_use = wayPointLive;
		var marker = new GMarker(newpos,{'icon': image_to_use, 
											 'clickable': true, 'draggable': false, 'bouncy':false,
											 'zIndexProcess': function(){return 99;}});
		player.marker = marker;
		marker.player = player;
		map.addOverlay(player.marker);
		var url = player.onclick_bigmap;
		addEventToMarker(marker,i,url.substring(url.indexOf(";")+1));
	}
	scrollActivityStream();
}

function addEventToMarker(marker,i,url) {
	GEvent.addListener(marker,"mouseover",function() {setPlayer(i,true,true);});
	GEvent.addListener(marker,"click",function() {showBigMap(url);});
}

function setPlayer(i,slide,jump) {
	if(curList[i].separator) {
		i = 0;
		curIdx = 0;
	}
	if(slide == null) slide = true;
	if(jump == null) jump = false;
	if (map.eventlistener != null)
		GEvent.removeListener(map.eventlistener);
	var player = curList[i];
	if(slide) {
		slider.SlideTo(i,jump);
		if(active_entry >= 0) {
			if(!jQuery.browser.msie) document.getElementById(active_entry).setAttribute("class",inactive_class);
			else document.getElementById(active_entry).className = inactive_class;
		}
		if(!jQuery.browser.msie) document.getElementById(i).setAttribute("class",active_class);
		else document.getElementById(i).className = active_class;
		active_entry = i;
	}
	var newpos = new GLatLng(player.latitude,player.longitude);
	if (map.selectedMarker == null) {
		active_live_marker = new GMarker(newpos,{'icon': wayPointActiveLive, 
										 'clickable': true, 'draggable': false, 'bouncy':false,
										 'zIndexProcess': function(){return 100;}});
		active_not_live_marker = new GMarker(newpos,{'icon': wayPointActive, 
			 'clickable': true, 'draggable': false, 'bouncy':false,
			 'zIndexProcess': function(){return 100;}});
		active_live_marker.active = true;
		active_not_live_marker.active = false;
		map.selectedMarker = active_not_live_marker;
		map.addOverlay(map.selectedMarker);
	}
	if (map.oldPlayer != null)
		map.addOverlay(map.oldPlayer.marker);
	map.oldPlayer = player;
	if(player.active && !map.selectedMarker.active) {
		map.removeOverlay(map.selectedMarker);
		map.selectedMarker = active_live_marker;
		map.addOverlay(map.selectedMarker);
	} else if(!player.active && map.selectedMarker.active) {
		map.removeOverlay(map.selectedMarker);
		map.selectedMarker = active_not_live_marker;
		map.addOverlay(map.selectedMarker);
	}
	map.selectedMarker.setLatLng(newpos);
	map.removeOverlay(player.marker);
	var url = player.onclick_bigmap;
	map.eventlistener = GEvent.addListener(map.selectedMarker,"click",
			function() {showBigMap(url.substring(url.indexOf(";")+1));});
}
		
function scrollActivityStream() {
	if(mouseovermap || slider.mouseover || slider.sliding || slider.dragging || (slider.scrollbar != null && slider.scrollbar.active)) {
  		if (maptimer == 0) {
  			window.setTimeout(scrollActivityStreamTest,5000);
  			maptimer++;
  		}
  		return;
	}
	if(curList != null && curList.length > 0 && map.isLoaded() == true ) {
		var player = curList[curIdx];
		if(player.separator) player = curList[0];
		var newpos = new GLatLng(player.latitude, player.longitude);
		var curmid = map.fromLatLngToDivPixel(map.getCenter());
		var newmid = map.fromLatLngToDivPixel(newpos);
		var div = new GSize(curmid.x-newmid.x, curmid.y-newmid.y);
		setPlayer(curIdx);
		map.panBy(div);
		curIdx++;
		if (curIdx >= curList.length)
			curIdx = 0;
		if (maptimer == 0) {
  			window.setTimeout(scrollActivityStreamTest,5000);
  			maptimer++;
  		}
	}
}

function scrollActivityStreamTest() {
	maptimer--;
	scrollActivityStream();
}

function ActivityStreamGoTo(e,href) {
	CancelEvent(e);
	window.location = href;
}

function MouseOverEntry(entry) {
	if(entry.id == null || entry.id == "") return;
	if(activity_slider != null) {
		if(slider.dragging || activity_slider.dragging) return;
	} else if(slider.dragging) return;
			
	var player_id = parseInt(entry.id);
	var player = curList[player_id];
	if(player == null) return;
	if(active_entry >= 0) {
		if(!jQuery.browser.msie) document.getElementById(active_entry).setAttribute("class",inactive_class);
		else document.getElementById(active_entry).className = inactive_class;
	}
	if(!jQuery.browser.msie) entry.setAttribute("class",active_class);
	else entry.className = active_class;
	active_entry = player_id;
	var newpos = new GLatLng(player.latitude, player.longitude);
	var curmid = map.fromLatLngToDivPixel(map.getCenter());
	var newmid = map.fromLatLngToDivPixel(newpos);
	var div = new GSize(curmid.x-newmid.x, curmid.y-newmid.y);
	setPlayer(player_id,false);
	map.panBy(div);
}

function MouseOutEntry(entry) {
	
}

function SwitchMode() {
	var mode_button = document.getElementById("mode_button");
	while(mode_button.hasChildNodes()) mode_button.removeChild(mode_button.firstChild);
	if(slider != null) slider.Delete();
	if(activity_slider != null) activity_slider.Delete();
	if(map_mode) {
		map_mode = false;
		mode_button.appendChild(document.createTextNode("Map-Mode"));
		document.getElementById("activities-all").style.display = "inline";
		document.getElementById("players-title").style.display = "inline";
		document.getElementById("activitymap").style.height = "144px";
		active_class = "list_mode-active";
		inactive_class = "list_mode-passive";
	} else {
		map_mode = true;
		mode_button.appendChild(document.createTextNode("List-Mode"));
		document.getElementById("activities-all").style.display = "none";
		document.getElementById("players-title").style.display = "none";
		document.getElementById("activitymap").style.height = "360px";
		activity_slider = null;
		active_class = "map_mode-active";
		inactive_class = "map_mode-passive";
	}
	map.checkResize();
	SetupSliders();
	if(jQuery.browser.msie) reloadPlayers();
	if(reload_interval >= 0) window.clearInterval(reload_interval);
	reload_interval = window.setInterval(reloadPlayers,180000);
}

function ProcessActivityEntryTexts() {
	if(!KURZ) return;
	var list = document.getElementById(SLIDER_LIST_ID+activity_slider.slider_index);
	var maxlength = 20;
	for(var i = 0; i < list.childNodes.length; i++) {
		var node = null;
		if(jQuery.browser.msie) node = list.childNodes[i].childNodes[0].childNodes[1].childNodes[2].childNodes[0].childNodes[2];
		else node = list.childNodes[i].childNodes[1].childNodes[3].childNodes[5].childNodes[1].childNodes[2];
		var text = node.innerHTML;
		if(text.length > maxlength) {
			if(jQuery.browser.msie) node.innerHTML = "&nbsp;"+text.substring(0,maxlength-1)+"...";
			else node.innerHTML = text.substring(0,maxlength)+"...";
		}
	}
}

$(document).ready(initActivityStream);
