// Setup vars
var editMode = false; // Do not change. Place a Div with id "controlPanel" on page to enable edit mode
var positioningMode = false;
var map = null;
var pointFocusIndex = -1;
var guideLevel = 0;	// specifies depth level for guides. for now, 1 = guides, 0 = points for single guide only (default)
var framed = false; // specifies if map is shown in an iframe
var	frameLat = '';
var	frameLong = '';
var	frameZoom = '';

var siteLanguage = 0;
var guideLanguage = 0;
var preview = false;
var conversationID = '';

// Playback
var playingPointIndex = -1;
var currentPointSound = 0;
var playFullGuide = false;
//var guideStatus = 0; // 0 = "release", 1 = under construction
var prevFlag = false;

var hoverIndex = -1;

// Cross hair
var crossHair = null;
var crossHairIcon = null;
var onMoveCrossHair = null;

// Marker events
var onSelectMarker = null;
var onUnselectMarker = null;

// Language sensitive static strings
var stringPlay = "";
var stringPreviewPlay = "";
var stringPlayGuide = "";
var stringStop = "";
var stringPrevious = "";
var stringNext = "";

// Create lists to hold info about our points
var pointList = new Array();
var markerIconList = new Array();
var titleList = new Array();
var imageList = new Array();
var thumbimageList = new Array();
var pointAllImagesList = new Array();
var soundList = new Array();
var descList = new Array();
var linkList = new Array();
var statusList = new Array();
var previewDurationList = new Array();
var mapNumberList = new Array();

var markerList = new Array();
var hoverMarkerList = new Array();
var selectedMarkerList = new Array();

var selectedMarker = null;

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = "http://content.guidetome.se/shared/markershadow.png";
baseIcon.iconSize = new GSize(20, 20);
baseIcon.shadowSize = new GSize(40, 20);
baseIcon.iconAnchor = new GPoint(1, 20);
baseIcon.infoWindowAnchor = new GPoint(16, 10);
baseIcon.infoShadowAnchor = new GPoint(1, 8);

var selectedIcon = new GIcon();
selectedIcon.shadow = "http://content.guidetome.se/shared/markerhshadow.png";
selectedIcon.iconSize = new GSize(40, 40);
selectedIcon.shadowSize = new GSize(80, 40);
selectedIcon.iconAnchor = new GPoint(1, 40);
selectedIcon.infoWindowAnchor = new GPoint(16, 10);
selectedIcon.infoShadowAnchor = new GPoint(1, 8);

function MapGuideSetLanguages(languageId, guideLanguageId)
{
	siteLanguage = languageId;
	guideLanguage = guideLanguageId;
}

function MapGuideSetupFrame(isInIFrame, lat, long, zoom)
{
	framed = isInIFrame;
	frameLat = lat;
	frameLong = long;
	frameZoom = zoom;
}

function MapGuideSetStrings(play, previewPlay, playGuide, stop, previous, next)
{
	stringPlay = play;
	stringPreviewPlay = previewPlay;
	stringPlayGuide = playGuide;
	stringStop = stop;
	stringPrevious = previous;
	stringNext = next;
}

// Clear all points
function MapGuideClear()
{
	pointList = new Array();
	markerIconList = new Array();
	titleList = new Array();
	imageList = new Array();
	thumbimageList = new Array();
	pointAllImagesList = new Array();
	soundList = new Array();
	descList = new Array();
	linkList = new Array();
	previewDurationList = new Array();
	mapNumberList = new Array();
	
	if(guideLevel == 1)
		statusList = new Array();

	markerList = new Array();
	hoverMarkerList = new Array();
	selectedMarkerList = new Array();
	
	if (map != null)
		map.clearOverlays();

	clearPlaylist();
}

// Add point to map.
// NOTE: Don't forget to call MapGuideClear to remove all points before calling this for the first time,
//	 		then MapGuideCreateMarkers to add the points to the map after all points are added
function MapGuideAddPoint(title, markericonurl, mapNumber, clat, clong, imageurl, allimageurls, sounds, description, previewduration, morelinkurl, status)
{
//	if(clat=='' || clong=='')
//		return;
	
	titleList.push(title);
	markerIconList.push(markericonurl);
	mapNumberList.push(mapNumber);
	pointList.push(new GLatLng(clat, clong));
	imageList.push(imageurl);
	soundList.push(sounds);
	descList.push(description);
	linkList.push(morelinkurl);
	
	if(guideLevel == 1)
		statusList.push(status);
	
	previewDurationList.push(previewduration);
	
	var i = imageurl.lastIndexOf('/');
	thumbimageList.push(imageurl.substring(0, i+1) + "thumb_" + imageurl.substring(i+1));
	
	pointAllImagesList.push(allimageurls);

}

function MapGuideCreateMarkers()
{
	// Set standard playlist
	resetPlaylist();

	// Add markers
	markerList = new Array();
	hoverMarkerList = new Array();
	map.clearOverlays();
	for(var i = 0; i < pointList.length; i++)
	{
		MapGuideCreateMarker(i);			
	}

	if(guideLevel == 0)	
		initGuideSoundPlayer();
		
	GEvent.addListener(map, "click", function(marker) {
		if ((!marker) && (selectedMarker)) unselectMarker(selectedMarker);
	});
		
}

function MapGuideCreateMarker(i) {
	markerList.push(createMarker(pointList[i], markerIconList[i], i));
//	map.addOverlay(markerList[markerList.length - 1]);
	map.addOverlay(markerList[i]);

	hoverMarkerList.push(createHoverMarker(pointList[i], markerIconList[i], i));
	map.addOverlay(hoverMarkerList[i]);
	hoverMarkerList[i].hide();

	selectedMarkerList.push(createSelectedMarker(pointList[i], markerIconList[i], i));
	map.addOverlay(selectedMarkerList[i]);
	selectedMarkerList[i].hide();
	
//	Scroll buggfix, behövs ej i ie
//	if(BrowserDetect.browser == "Firefox" && framed != 1) {
	if(BrowserDetect.browser == "Firefox") {
		hoverMarkerList[i].showTooltip(); // funkar inte när firefox kör i iframe
//		hoverMarkerList[i].initTooltip();
		hoverMarkerList[i].hideTooltip();
	}

//	Show lower numbered markers above higher
	if(guideLevel == 0)
	{ 	
		setTimeout("setMarkerZ("+i+")", 300);
	}

//	Show status 0 markers above higher
	if(statusList[i] == "PUBLISHED")
	{ 	
		setTimeout("setMarkerZ("+i+")", 300);
	}
}

function setMarkerZ(i)
{
	markerList[i].setOriginalZIndex(50000-i);
}

// Called in body onload
function MapGuideInitialize(disableInput, divID, guidePreview) {
	if (GBrowserIsCompatible() || true) {

		if(!divID || divID == '')
			divID = 'map';
		
		// Initialize
		preview = guidePreview;
		map = new GMap2(document.getElementById(divID));
		GEvent.addListener(map, "infowindowopen", function() {
			updateButtonStatus();
		});
		
/*		if(divID == "map")
		{	
			GEvent.addListener(map, "click", function() {
				//stopGuideSoundPlayer();
			});
			GEvent.addListener(map, "dragstart", function() {
				//stopGuideSoundPlayer();
			});
		}
*/
/*		else if(divID == "mapindex")
		{
			GEvent.addListener(map, "click", function() {
				document.location="searchmap.html";
			});
		}		
*/						
		// Add gui controls
		if(disableInput == "true")
		{
			map.disableDragging();
			map.disableInfoWindow();
			map.disableDoubleClickZoom();
			map.disableContinuousZoom();
			map.disableScrollWheelZoom();
//			map.addControl(new GSmallMapControl());
		}
		else
		{
			map.addControl(new GLargeMapControl());
	
			map.enableScrollWheelZoom();
//			map.enableGoogleBar();
			map.enableContinuousZoom();
			
			// Normal, satellite, hybrid and so on
			//map.addControl(new GMapTypeControl());
		}
	
		// Set map functions in edit mode if controlPanel exists on page
/*		if(document.getElementById("controlPanel"))
			editMode = true;
*/				
		// Show first point
		//if(playlist.length > 0)
		//	showPoint(playlist[0]);
	}
}

function MapGuideSetTypeControl()
{
	map.addControl(new GMapTypeControl());
}

function MapGuideSetZoomLevel(level)
{
	map.setZoom(level);
}

function MapGuideSetGuideLevel(level)
{
	guideLevel = level;	
}

function updateControlPanel()
{
	if(!editMode)
		return;
	
	var controlPanelDiv = document.getElementById("controlPanel");
	
	var htmlString = "";
	
	if(playlist.length > 0)
		htmlString += "<input id='playPlaylist' type='button' value='Spela upp spellista' onclick='handlePlayPlaylistClick();' /><br>";

/*	if(pointPlaylistIndex != -1 && playlist.length > 0 && pointPlaylistIndex < playlist.length)
		htmlString += "<input id='playNext' type='button' value='Nästa punkt' onclick='handlePlayNextClick();' /><br>";
	*/
	if(playlist.length > 0)
		htmlString += "<input type='button'	value='Clear playlist' onclick='clearPlaylist(true);' /><br>";
	
	if(changedPlaylist)
		htmlString += "<input type='button' value='Reset playlist' onclick='resetPlaylist();' />";
	
	controlPanelDiv.innerHTML = htmlString;
}

// Creates a marker whose info window displays info about the point
function createMarker(point, imageURL, index)
{
	// Create a lettered icon for this point using our icon class
	var numberIcon = new GIcon(baseIcon);

	numberIcon.image = imageURL;
	
/*	Move this serverside

	if(guideLevel == 0)
	{
		var indexNumber = index;
		
		if(guideStatus == "HIDDEN") {
			numberIcon.image = "http://content.guidetome.se/shared/markeruc.png";
		}
		else
		{
			numberIcon.image = "http://content.guidetome.se/shared/marker" + indexNumber + ".png";
		}
	}
	else
	{
		if(statusList[index] == "PUBLISHED") {
			numberIcon.image = "http://content.guidetome.se/shared/marker.png";
		}
		else
		{
			numberIcon.image = "http://content.guidetome.se/shared/markeruc.png";
		}
	}*/

	var marker = new PdMarker(point, numberIcon);
	
//	marker.setTooltip(titleList[index]);
//	marker.setHoverImage(hIcon.image);
//	marker.setOpacity(80);  //changed default in pdmarker.js instead
	
	GEvent.addListener(marker, "click", function() {
	
		if(positioningMode) {
				if (selectedMarker) unselectMarker(selectedMarker);
				selectMarker(marker);
		} 
		else if(guideLevel == 0)
		{		
			marker.hide();
			hoverMarkerList[index].show();
			hoverMarkerList[index].topMarkerZIndex();
			
			currentPointSound = 0;
			setPointFocusIndex(index);
			
			openInfoWindowHTML(hoverMarkerList[index],index);
			//hoverMarkerList[index].openInfoWindowHtml(buildWindowHTML(index));
			
//			Lightbox.init();
		}
		else
		{
			document.location=linkList[index];
		}
	});
		
	if (!positioningMode)
	{	
		GEvent.addListener(marker, "mouseover", function() {

			marker.hide();
			hoverMarkerList[index].show();
			hoverMarkerList[index].topMarkerZIndex();
			
			setTimeout("checkHoverIndex("+index+")", 100);			
		}); 
	}

	return marker;
}

// Creates a selected marker
function createSelectedMarker(point, imageURL, index)
{
	// Create a lettered icon for this point using our icon class
	var numberIcon = new GIcon(selectedIcon);

	numberIcon.image = imageURL;

/*	if(guideLevel == 0)
	{
		var indexNumber = index;
		
		if(guideStatus == "HIDDEN") {
			numberIcon.image = "http://content.guidetome.se/shared/markeruc.png";
		}
		else
		{
			numberIcon.image = "http://content.guidetome.se/shared/marker" + indexNumber + ".png";
		}
	}
	else
	{
		if(statusList[index] == "PUBLISHED") {
			numberIcon.image = "http://content.guidetome.se/shared/marker.png";
		}
		else
		{
			numberIcon.image = "http://content.guidetome.se/shared/markeruc.png";
		}
	}*/

	var marker = new PdMarker(point, numberIcon);
	
//	marker.setTooltip(titleList[index]);
//	marker.setHoverImage(hIcon.image);
//	marker.setOpacity(80);  //changed default in pdmarker.js instead
	
	GEvent.addListener(marker, "click", function() {
	
		if(positioningMode) {
			if (selectedMarker) unselectMarker(selectedMarker);
		}									
		else if(guideLevel == 0)
		{		
			marker.hide();
			hoverMarkerList[index].show();
			hoverMarkerList[index].topMarkerZIndex();
		
			currentPointSound = 0;
			setPointFocusIndex(index);
			openInfoWindowHTML(hoverMarkerList[index],index);
			//hoverMarkerList[index].openInfoWindowHtml(buildWindowHTML(index));
			
//			Lightbox.init();
		}
		else
		{
			document.location=linkList[index];
		}
	});
		
	if (!positioningMode)
	{	
		GEvent.addListener(marker, "mouseover", function() {

			marker.hide();
			hoverMarkerList[index].show();
			hoverMarkerList[index].topMarkerZIndex();
			
			setTimeout("checkHoverIndex("+index+")", 100);			
		}); 
	}

	return marker;
}

function checkHoverIndex(index)
{
	if (hoverIndex != index)
		{
			hoverMarkerList[index].hide();
			markerList[index].show();
		}
}

function createHoverMarker(point, imageURL, index)
{
	// Create a lettered icon for this point using our icon class
	var hIcon = new GIcon(selectedIcon);
	
	hIcon.image = imageURL;
	
/*	if(guideLevel == 0)
	{
		var indexNumber = index;
		
		if(guideStatus == "HIDDEN") {
			hIcon.image = "http://content.guidetome.se/shared/markeruch.png";
		}
		else
		{
			hIcon.image = "http://content.guidetome.se/shared/markerh" + indexNumber + ".png";
		}
	}
	else
	{
		if(statusList[index] == "PUBLISHED") {
			hIcon.image = "http://content.guidetome.se/shared/markerh.png";
		}
		else
		{
			hIcon.image = "http://content.guidetome.se/shared/markeruch.png";
		}
	}*/

	var marker = new PdMarker(point, hIcon);	
	
//	if(framed != 1) // firefox fix
		marker.setTooltip(titleList[index]);
	
	GEvent.addListener(marker, "click", function() {
		
		if(guideLevel == 0)
		{		
			currentPointSound = 0;
			setPointFocusIndex(index);
			openInfoWindowHTML(marker,index);
			//marker.openInfoWindowHtml(buildWindowHTML(index));
			
//			Lightbox.init();
		}
		else
		{
			document.location=linkList[index];
		}
	});
	
	GEvent.addListener(marker, "mouseover", function() {
		hoverIndex = index;
	}); 
	
	GEvent.addListener(marker, "mouseout", function() {
		
		if(pointFocusIndex != index)
		{
			marker.hide();
			markerList[index].show();
			hoverIndex = -1;
		}
	});
	
	GEvent.addListener(marker, "infowindowclose", function() {
			if(pointFocusIndex == index)
				pointFocusIndex = -1;
			marker.hide();
			markerList[index].show();
			hoverIndex = -1;
			marker.restoreMarkerZIndex();
		});
	
	return marker;
}

function showPoint(index)
{
	focusPoint(index);
}

function openInfoWindowHTML(marker,index) 
{
	// check height
	var image = new Image();
	var url = thumbimageList[index];
	if (url != 'thumb_') {
		image.onload = function() {
			openInfoWindowHTMLCallback(marker,index,image.height);
		}
		image.onerror = function() {
			openInfoWindowHTMLCallback(marker,index,image.height);
		}
		image.src = url;
	} else {
		openInfoWindowHTMLCallback(marker,index,0);
	}
}

function openInfoWindowHTMLCallback(marker,index,imageHeight) 
{
	marker.openInfoWindowHtml(buildWindowHTML(index,imageHeight));
}

function buildWindowHTML(pointIndex,imageHeight)
{
	// height with or without image
	var height = 60;
	if (imageList[pointIndex] != '') {
		height += imageHeight;
	}

	// check if point is in playlist
	var inPlaylist = (findPointInPlaylist(pointIndex) != -1);
	
	// Containing div (to prevent infowindow from autosizing to huge)
	htmlString = "<div style='width: 220px;height:" + height + "px;'>";
	
	// Title (links are created if that info exists)
	if(guideLevel == 1)
	{
		if(linkList[pointIndex] && linkList[pointIndex] != '' && !playFullGuide /*&& preview == false*/)
			htmlString += "<a href='" + linkList[pointIndex] +"'><b>" + titleList[pointIndex] + "</b></a><br>";
		else
			htmlString += "<b>" + titleList[pointIndex] + "</b><br>";
	}
	else if(guideLevel == 0)
	{
		htmlString += "<div class='infowindowtitlediv'>";
	
		if((descList[pointIndex] != '' || imageList[pointIndex] != '') && !playFullGuide && framed != 1 /*&& preview == false*/)
			htmlString += "<a href='" + linkList[pointIndex] +"'><b>" + mapNumberList[pointIndex] + ". " + titleList[pointIndex] + "</b></a><br>";
		else
			htmlString += "<b>" + mapNumberList[pointIndex] + ". " + titleList[pointIndex] + "</b><br>";
		
		htmlString += "</div>";
	}
	
	// Images
	if(imageList[pointIndex] != '')
	{
		htmlString += "<div class='infowindowimagediv'>"

		if (framed == 1)
			htmlString += "<img class='infowindowimage' src='" + thumbimageList[pointIndex] + "'/>";
		else
		{
			if(BrowserDetect.browser == "Explorer")
				htmlString += "<a href='" + imageList[pointIndex] + "' onclick='myLightbox.start(this); return false;' rel='lightbox[iw]' title='" + titleList[pointIndex] + "'><img class='infowindowimage' src='" + thumbimageList[pointIndex] + "' /></a>";
			else
				htmlString += "<a href='" + imageList[pointIndex] + "' rel='lightbox[iw]' title='" + titleList[pointIndex] + "'><img class='infowindowimage' src='" + thumbimageList[pointIndex] + "' /></a>";
		}
		
		if (framed != 1)
		{
			for(var i = 1; i < pointAllImagesList[pointIndex].length; i++)
			{
					htmlString += "<a style='display:none;' href='" + pointAllImagesList[pointIndex][i] + "' rel='lightbox[iw]' title='" + titleList[pointIndex] + "'></a>";
			}
		}
		
		htmlString += "</div>";	
	}
		
	// Description
//	htmlString += descList[pointIndex] + "<br/>";

	var soundavailable = (soundList[pointIndex] && soundList[pointIndex].length > 0 && soundList[pointIndex][currentPointSound] != '');
	
	htmlString += "<div style='padding-top: 5px; clear: both;'>";
	// Play
	if(soundavailable && !playFullGuide)
	{
		if(isSoundPlaying())
			htmlString += "<div style='float: left;'><img id='playstatus' src='/img/map/stop.png' /> <a id='listen" + pointIndex + "' href='javascript:handleListenClick(" + pointIndex + ");'>" + stringStop + "</a></div>";
		else
		{
			if(previewDurationList[pointIndex] > 0)
				htmlString += "<div style='float: left;'><img id='playstatus' src='/img/map/play.png' /> <a id='listen" + pointIndex + "' href='javascript:handleListenClick(" + pointIndex + ");'>" + stringPreviewPlay + "</a></div>";
			else
				htmlString += "<div style='float: left;'><img id='playstatus' src='/img/map/play.png' /> <a id='listen" + pointIndex + "' href='javascript:handleListenClick(" + pointIndex + ");'>" + stringPlay + "</a></div>";
		}
	}
	// show buttons according to context
	if(inPlaylist && playlist.length > 1)
	{
		if (!playFullGuide)
		{
			// Next point
			htmlString += "<div style='float: right'><img src='/img/map/next.png' /> <a id='playNext' href='javascript:handleShowNextClick();'>" + stringNext + "</a></div>";			  
			// Previous point
			htmlString += "<div style='float: right; padding-right:2px'><a id='playNext' href='javascript:handleShowPrevClick();'>" + stringPrevious + "</a> <img src='/img/map/prev.png' /></div>";
		}
	}
	else
	{
		// Add to playlist
		// htmlString += "<div style='float: right'><img src='/img/map/add.png' /> <a id='addToPlaylist" + pointIndex + "' href='javascript:addPointIndexToPlaylist(" + pointIndex + ");'>Add to Playlist</a></div>";
	}

	htmlString += "</div>";
	htmlString += "</div>";
	
	return htmlString;
}

function closeCurrentInfoWindow()
{
	if(pointFocusIndex < 0 || pointFocusIndex >= markerList.length)
		return;

	hoverMarkerList[pointFocusIndex].closeInfoWindow();
}

function findPointInPlaylist(pointIndex)
{
	var playlistIndex = -1;
	for(var i = 0; i < playlist.length; i++)
	{
		if(pointIndex == playlist[i])
		{
			playlistIndex = i;
			break;
		}
	}
	
	return playlistIndex;
}

function setPointFocusIndex(index)
{
	pointFocusIndex = index;
	
	var playlistIndex = findPointInPlaylist(pointFocusIndex);
	setPointPlaylistIndex(playlistIndex);
}

function focusNext()
{
	if(pointPlaylistIndex == -1)
		return;

	prevFlag = false;

	pointPlaylistIndex++;
	if(pointPlaylistIndex > playlist.length - 1)
	{
		setPointPlaylistIndex(0);
	}
	setPointFocusIndex(playlist[pointPlaylistIndex]);
	focusPoint(pointPlaylistIndex);
}

function focusPrev()
{
	if(pointPlaylistIndex == -1)
		return;

	prevFlag = true;

	pointPlaylistIndex--;
	if(pointPlaylistIndex < 0) { setPointPlaylistIndex(playlist.length - 1); }
	
	setPointFocusIndex(playlist[pointPlaylistIndex]);
	focusPoint(pointPlaylistIndex);
}

function focusPoint(playlistIndex)
{
	markerList[playlistIndex].hide();
	hoverMarkerList[playlistIndex].show();
	hoverMarkerList[playlistIndex].topMarkerZIndex();
	
/*	if(guideStatus == "HIDDEN")
	{
		openInfoWindowHtml(hoverMarkerList[playlistIndex],playlistIndex);
		//hoverMarkerList[playlistIndex].openInfoWindowHtml(buildWindowHTML(playlistIndex));
	}
	else
	{*/
		GEvent.trigger(hoverMarkerList[playlistIndex], "click");
//	}	
	
	if(isGuidePlaying())
	{
		currentPointSound = 0;
		if(!playPoint(pointFocusIndex, currentPointSound))
		{
			if(playFullGuide)
			{	
				GEvent.trigger(hoverMarkerList[playlistIndex], "infowindowclose");
				if (prevFlag)
				{
					prevFlag = false;
					focusPrev();
				}
				else
					focusNext();
			}
			else
				stopPointPlayback();
//			stopGuideSoundPlayer();
		}
	}	
}

// Sound management functions
var guidePlaying = false
var playingSoundID = "";

function guideobjectListPlay(soundID, soundURL)
{
	if(isSoundPlaying())
	{
		stopPointPlayback();
	}
	
	$('play_'+soundID).setStyle({"display" : "none"});
	$('stop_'+soundID).setStyle({"display" : "inline"});
	
	playingSoundID = soundID;
	
	Seam.Component.getInstance("guideSession").statisticsHitAudio(currentGuideId, guideLanguageId, null, null, soundURL);
	
	soundManager.createSound({
		id:playingSoundID,
		url:soundURL,
		autoLoad:true,
		autoPlay:true,
		onfinish:function() {
			onGuideobjectListPlayFinished();
		}
	});
	
	updateButtonStatus();
}

function guideobjectListStop()
{
	onGuideobjectListPlayFinished();
}

function onGuideobjectListPlayFinished()
{ 
	if ($('play_'+playingSoundID) != null)
		$('play_'+playingSoundID).setStyle({"display" : "inline"});
	if ($('stop_'+playingSoundID) != null)
		$('stop_'+playingSoundID).setStyle({"display" : "none"});
	destroySound(playingSoundID);
}

function handleListenClick(index)
{
	setPointFocusIndex(index);
	togglePlaying();
}

function handlePlayPlaylistClick()
{
	if(playlist.length == 0)
		return;
	
	if(pointPlaylistIndex == -1)
		setPointPlaylistIndex(0);
	
	togglePlaying();
}

function handleShowNextClick()
{
	if(playFullGuide)
	{
		pointPlaylistIndex = playingPointIndex;
	}
		
	focusNext();
}

function handleShowPrevClick()
{
	if(playFullGuide)
	{
		pointPlaylistIndex = playingPointIndex;
	}

	focusPrev();
}

function isGuidePlaying()
{
	return guidePlaying;
}

function isSoundPlaying()
{
	return (playingSoundID != "");
}

function togglePlaying()
{
	if(isSoundPlaying())
	{
		stopPointPlayback();
	}
	else
	{
		if(pointPlaylistIndex != -1)
			playPoint(playlist[pointPlaylistIndex], currentPointSound);
		else
			playPoint(pointFocusIndex, currentPointSound);
	}

	updateButtonStatus();
}

function updateButtonStatus()
{
	var listenButton = document.getElementById("listen" + pointFocusIndex);
	var playPlaylistButton = document.getElementById("playPlaylist");
	var playstatus = document.getElementById("playstatus");

	if(isSoundPlaying())
	{
		if(listenButton)
			listenButton.innerHTML=stringStop;
		if(playPlaylistButton)
			playPlaylistButton.value=stringStop;
		if(playstatus)
			playstatus.src = "/img/map/stop.png";
	}
	else
	{
		if(listenButton)
		{
			if(previewDurationList[pointFocusIndex] > 0)
				listenButton.innerHTML=stringPreviewPlay;
			else
				listenButton.innerHTML=stringPlay;
		}
		if(playPlaylistButton)
			playPlaylistButton.value='Spela upp spellista';
		if(playstatus)
			playstatus.src = "/img/map/play.png";
	}
}

function playPoint(pointIndex, sound)
{
	if(isSoundPlaying())
		destroySound(playingSoundID);
	
	playingSoundID = 'soundid' + pointIndex + "_" + sound;
	var soundURL = soundList[pointIndex][sound];
	
	if(!soundURL || soundURL == '')
	{
		return false;
	}
	
	Seam.Component.getInstance("guideSession").statisticsHitAudio(currentGuideId, guideLanguageId, pointIndex, sound, soundURL);
	
	soundManager.createSound({
		id:playingSoundID,
		url:soundURL,
		autoLoad:true,
		autoPlay:true,
		onfinish:function() {
			onPlayFinished();
		}
	});
	
	guidePlaying = true;
	
	var d = new Date(); 
	playingPointIndex = pointIndex;
	
	updateButtonStatus();
	
	return true;
}

function onPlayFinished()
{
	if(pointPlaylistIndex == -1)
		guidePlaying = false;

	destroySound(playingSoundID);
	
	if(soundList[playlist[pointPlaylistIndex]].length > currentPointSound + 1)
	{
		currentPointSound++;
		if(!playPoint(playlist[pointPlaylistIndex], currentPointSound))
			togglePlaying();
	}
	else if (playFullGuide)
	{
		if (pointPlaylistIndex == playlist.length - 1)
		{
			stopGuideSoundPlayer();
			closeCurrentInfoWindow();
		}
		else
		{
//			showPoint(pointPlaylistIndex);
			pointPlaylistIndex = playingPointIndex;
			focusNext();
		}
	}
}

function stopPointPlayback()
{
	playFullGuide = false;
	guidePlaying = false;
	currentPointSound = 0;	
	if (playingSoundID.substring(0,3) == "go_") {
		if ($('play_'+playingSoundID) != null)
			$('play_'+playingSoundID).setStyle({"display" : "inline"});
		if ($('stop_'+playingSoundID) != null)
			$('stop_'+playingSoundID).setStyle({"display" : "none"});
	}
	destroySound(playingSoundID);
}

function destroySound(id)
{
	if(id == "")
		return;

	soundManager.destroySound(playingSoundID);
	playingSoundID = "";
	updateButtonStatus();
}

// Playlist functions
var pointPlaylistIndex = -1;
var playlist = null;
var changedPlaylist = false;

function addPointIndexToPlaylist(index)
{
	// Check if point is already added
	playlistIndex = -1;
	for(var i = 0; i < playlist.length; i++)
	{
		if(index == playlist[i])
		{
			return;
		}
	}

	playlist.push(index);
	setPointPlaylistIndex(playlist.length - 1);
	
	closeCurrentInfoWindow();
	updateControlPanel();
}

function removePointIndexFromPlaylist(index)
{
	setChangedPlaylist(true);

	playlist.splice(index, 1);
	
	if(pointPlaylistIndex == index)
		setPointPlaylistIndex(index);
	else
		updatePlaylist();
}

function clearPlaylist(reportPlaylistChange)
{
	playlist = new Array();
	setPointPlaylistIndex(-1);
	if(reportPlaylistChange)
	{
		setChangedPlaylist(true);
	}

	closeCurrentInfoWindow();
}

function setPointPlaylistIndex(index)
{
	if(index > playlist.length - 1)
		index = playlist.length - 1;
		
	if(index < 0 && playlist.length > 0)
		index = 0;
	
	if(index < -1 && playlist.length == 0)
		index = -1;
	
	pointPlaylistIndex = index;
	updatePlaylist();
}

function resetPlaylist()
{
	clearPlaylist(false);
	for(var i = 0; i < pointList.length; i++)
		playlist.push(i);

	setPointPlaylistIndex(0);
	setChangedPlaylist(false);
}

function setChangedPlaylist(changed)
{
	changedPlaylist = changed;
	updateControlPanel();
}

function updatePlaylist()
{
	var playlistDiv = document.getElementById("playlist");
	if(!playlistDiv)
		return;
	
	var playlistString = "<table>";

	if(editMode)
	{
		for(var i = 0; i < playlist.length; i++)
		{
			if(i == pointPlaylistIndex)
			{
				playlistString += "<tr><td><b>Punkt " + (playlist[i] + 1) + "</b></td><td><input type='button' value='Ta bort' onclick='removePointIndexFromPlaylist(" + i + ");' /></td></tr>";
			}
			else
			{
				playlistString += "<tr><td><a href='javascript:showPoint(" + playlist[i] + ")'>Punkt " + (playlist[i] + 1) + "</a></td><td><input type='button' value='Ta bort' onclick='removePointIndexFromPlaylist(" + i + ");' /></td></tr>";
			}
		}
	}
	else
	{
		for(var i = 0; i < playlist.length; i++)
		{
			if(i == pointPlaylistIndex)
			{
				playlistString += "<tr><td><b>Punkt " + (playlist[i] + 1) + "</b></td></tr>";
			}
			else
			{
				playlistString += "<tr><td><a href='javascript:showPoint(" + playlist[i] + ")'>Punkt " + (playlist[i] + 1) + "</a></td></tr>";
			}
		}
	}
	
	playlistString += "</table>";
	playlistDiv.innerHTML = playlistString;
}

function LoadStoredGuides()
{
	MapGuideClear();
	
	var i;
	for(i=0; i<stored_guides.length; i++)
	{
		var link = '';
		if(framed == 1)
			link = '/' + siteLanguage + '/frameguide/'+stored_guides[i].languageCode+'/'+stored_guides[i].id;
		else
			link = '/' + siteLanguage + '/guide/'+stored_guides[i].languageCode+'/'+stored_guides[i].id+'/'+stored_guides[i].cleanTitle;
		
		MapGuideAddPoint(stored_guides[i].title, stored_guides[i].markerURL, stored_guides[i].mapNumber, stored_guides[i].latitude, stored_guides[i].longitude, stored_guides[i].imageurl,stored_guides[i].allimageurls, stored_guides[i].sounds, stored_guides[i].description, 0, link, stored_guides[i].status);
	}
	
	if(framed == 1 && frameLat && frameLong && zoom)
	{
		map.setCenter(new GLatLng(frameLat, frameLong), zoom);
		MapGuideCreateMarkers();
	}
	else
	{
		map.setCenter(new GLatLng(58.285275, 14.954615), 6);
		MapGuideCreateMarkers();
		
	//	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		map.zoomToMarkers(5,2);
		map.savePosition();
	}
}

function LoadGuides(disableInput, divID, guidePreview)
{
	MapGuideSetGuideLevel(1); // Show guides not points
	
	// Initialze map
	MapGuideInitialize(disableInput, divID, guidePreview);
			
	// Add points
//	Seam.Component.getInstance("guideSession").getAllGuideMapWindowDatas(languageId, LoadGuidesCallback);
	LoadStoredGuides();
}

var currentGuideId = -1;

function LoadGuidepointsCallback(guidepoints)
{
	MapGuideClear();
	var i;
	for(i=0; i<guidepoints.length; i++)
	{
		MapGuideAddPoint(guidepoints[i].title, guidepoints[i].markerURL, guidepoints[i].mapNumber, guidepoints[i].latitude,
						 guidepoints[i].longitude, guidepoints[i].imageurl, guidepoints[i].allimageurls, guidepoints[i].sounds,
						 guidepoints[i].description, guidepoints[i].ispreview,
						 '/' + siteLanguage + '/point/' + guideLanguage + '/'+currentGuideId+'/'+guidepoints[i].id+'?preview=' + preview + '&cid=' + conversationID);
	}
	
	map.setCenter(new GLatLng(58.285275, 14.954615), 6);
	
	MapGuideCreateMarkers(); 
	
	map.zoomToMarkers(7);
	if (playlist.length == 1)
		map.setZoom(12);
	map.savePosition();	
}

function LoadGuidepoints(guideId, disableInput, divID, guidePreview, cid)
{
	// Initialze map
	MapGuideInitialize(disableInput, divID, guidePreview);
	
	// Settings
	MapGuideSetGuideLevel(0);
	
	currentGuideId = guideId;
	conversationID = cid;
	
//	Seam.Component.getInstance("guideSession").getAllGuidepointMapWindowDatas(currentGuideId, guideLanguageId, LoadGuidepointsCallback);
	LoadGuidepointsCallback(stored_guidepoints);
}

function initGuideSoundPlayer()
{
	var soundListLength = 0;
	
	for(var i = 0; i < soundList.length; i++)
	{
		soundListLength += soundList[i].length;
	}
	
	if (soundListLength > 0)
	{
		updateGuideSoundPlayer();
	}
	else
	{
		var gPlayer = document.getElementById('guideSoundPlayer');
		if (gPlayer != null)
		{
			gPlayer.innerHTML = "";
		}
	}
}

function playGuideSoundPlayer()
{
	if (isSoundPlaying())
	{
		togglePlaying();
	}
	playFullGuide = true;
	showPoint(0);
	handleListenClick(0);
	updateGuideSoundPlayer();
}

function stopGuideSoundPlayer()
{
	if (playFullGuide)
	{
		stopPointPlayback();
		closeCurrentInfoWindow();
		updateGuideSoundPlayer();
	}
}

function updateGuideSoundPlayer()
{
	var gPlayer = document.getElementById('guideSoundPlayer');
	if (gPlayer != null)
	{
		if (isSoundPlaying())
		{
			gPlayer.innerHTML = "<p id='playButton'>" +
				"<div style='float: left; height: 20px; padding-right:40px'><img src='/img/map/stop.png' /> <a href='javascript:stopGuideSoundPlayer();'>" + stringStop + "</a></div>";
				if(playlist.length > 1)
				{
					gPlayer.innerHTML += "<div style='float: left; height: 20px; padding-right:2px'><a id='playNext' href='javascript:handleShowPrevClick();'>" + stringPrevious + "</a> <img src='/img/map/prev.png' /></div>" +
					"<div style='float: left; height: 20px;'><img src='/img/map/next.png' /> <a id='playNext' href='javascript:handleShowNextClick();'>" + stringNext + "</a></div>";
				}
				gPlayer.innerHTML +=  "</p>";
		}
		else
		{
			gPlayer.innerHTML = "<p id='playButton'>" +
				"<img src='/img/map/play.png' /> <a href='javascript:playGuideSoundPlayer();'>" + stringPlayGuide + "</a>" +
				"</p>";
		}
	}
}

