// GENERATOR Tranquility_base rev 1.1.1
// FLASH COMMS

var jsReady = false;
var flashMovie;
var map;
var dragMarker;
var markerSet;
var lang = "en";
var langStrings;
var prevDragPoint;

function isReady() {
	return jsReady;
}

function pageInit() {
	// Flash gets the go-ahead
	jsReady = true;
	// establish a reference to the SWFObject
	flashMovie = document.getElementById("mstories");
	// now sort out the map!
	initMap();
}

function initMap()
{
	if (GBrowserIsCompatible()) 
	{	
    	map = new GMap2(document.getElementById("map"));
		var mapType = new GMapTypeControl();
		map.addControl(mapType);
		map.removeMapType(G_SATELLITE_MAP);
		map.addMapType(G_PHYSICAL_MAP);
		
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(38,-97), 5);
		//map.enableScrollWheelZoom();
		
		GEvent.addListener(map, "click", onMapClicked);
	}
}

function setSWFReady(language)
{
	lang = language;
}

/// OUTGOING :: JS -> SWF

function onMapClicked(overlay, latLng) 
{	
	if (overlay != null)
	{
		flashMovie.onMarkerClicked(overlay.id);
	} else
	{
		// now slide to the clicked point
		map.panTo(latLng);
	}
	
	if (dragMarker != null)
	{
		dragMarker.setPoint(latLng);
		onMarkerDragEnd(latLng.lat(), latLng.lng());
	}
}

function onMarkerDragEnd(lat, lng)
{
	flashMovie.onMarkerPlacement(lat, lng);
}

/// INCOMING :: SWF -> JS

function slideMap() 
{
	// initialise by placing the map over the IP of the user
	map.panTo(new GLatLng(38,-97));
}

function openMarker(id)
{
	// fake the click!
	GEvent.trigger(markerSet[id],'click');
}

function initDragMarker()
{
	map.clearOverlays();
	var geo = new GLatLng(38,-97);
	prevDragPoint = geo;
	map.setCenter(geo);
	map.setZoom(5);
	dragMarker = new GMarker(geo,  {draggable: true});
		
	GEvent.addListener(dragMarker, "dragstart", function() {
		map.closeInfoWindow();
		prevDragPoint = dragMarker.getPoint();
	});
		
	GEvent.addListener(dragMarker, "dragend", function() {
		
		var dropPoint = dragMarker.getPoint();
		
		var lat = dropPoint.lat();
		var lng = dropPoint.lng();
		if (lat > 85 || lat < -57)
		{
			var msg;
			if (lat < -85)
			{
				msg = "You must live on earth to post a Moon Safari Story. Aliens have other ways of telling us theirs."
			} else
			{
				msg = "Sorry, we aren't accepting Moon Safari stories from the Antarctic. Its nothing personal.";
			}
			alert(msg);
			var center = prevDragPoint;
			map.panTo(center);
			dragMarker.setPoint(prevDragPoint);
		} 
		else
		{
			var center = dropPoint;
			// tell the Flash Movie;
			map.panTo(center);
			onMarkerDragEnd(lat, lng);
		}
	
	});
	
	map.addOverlay(dragMarker);
	
	var html;
	if (lang == "en")
	{
		html = "<div style='font-size:small;width:350px;'><h2 style='padding:0;margin:0;'>How to use the map</h2><p>The map will start over the country you are in now.</p><ul></li><li>Click anywhere on the map to roughly position the marker</li><li>Get a more accurate position by zooming in (use the tools on the left), dragging and clicking the map, or by dragging the marker itself.</li></ul><p>When you submit your story, wherever your marker is will be saved.</p></div>";
		
	} 
	else
	{
		html = "<div style='font-size:small;width:350px;'><h2 style='padding:0;margin:0;'>Comment utiliser la carte</h2><p>La carte se positionnera au-dessus du votre pays.</p><ul></li><li>Cliquez n'importe où sur la carte pour placer le curseur.</li><li>Précisez votre position en utilisant le zoom (utilisez les outils du côté gauche), en déplaçant et en cliquant la carte.</li></ul><p>Quand vous envoyez votre histoire, votre position (indiqué par le curseur) sera enregistrée.</p></div>";
	}
	
	dragMarker.openInfoWindowHtml(html);
	
}

function endDragMarker()
{
	// don't let the user drag this anymore
	point = dragMarker.getPoint();
	map.removeOverlay(dragMarker);
	// replace with a static one
	var m = new GMarker(point);
	map.addOverlay(m);
}

function popMap(markerArray)
{
	// start by clearing existing markers
	map.clearOverlays();
	
	// and set up array to hold these new markers
	markerSet = new Array();
	
	// got to stretch the bounds to fit all the markers
	var bounds = new GLatLngBounds();
	
	// now loop through the marker objects
	for (var i = 0; i < markerArray.length; i++) {
		
		var data = markerArray[i];
		var point = new GLatLng(parseFloat(data.marker[0]),parseFloat(data.marker[1])); 
		bounds.extend(point);
		
		// NAME AND STORY		
		var infoHtml = '<h2>'+data.internaute+'</h2>';
		
		/// THUMBNAIL
		if (data.image != undefined && data.image != "") {
			var w = data.imagew; var h = data.imageh;
			var aspect = w/h; var thumbWidth; var thumbHeight;
			// check for the size
			if (w > 140) { thumbWidth = 140; thumbHeight = Math.round(140 / aspect); } else { thumbWidth = w; thumbHeight = h;}
			infoHtml += '<img class="popup_image" src="' + data.image + '" width="'+thumbWidth+'" height="'+thumbHeight+'" alt="" />';
			
			///  PHOTO
			var photoWidth; var photoHeight;
			if (w >= h) {
				// width is limiting factor
				if (w > 425) { photoWidth = 425; photoHeight = Math.round(425/aspect); } else { photoWidth = w; photoHeight = h;}
			} else {
				// height is limiting factor
				if (h > 350) { photoHeight = 350; photoWidth = Math.round(350*aspect); } else { photoHeight = h; photoWidth = w;}
			}
			var photoHtml = '<div class="popup_photo"><img src="' + data.image + '" width="'+photoWidth+'" height="'+photoHeight+'" alt="" /></div>';
		} else
		{
			var photoHtml = undefined;
		}
		
		var pClass;
		var charLimit;
		if (data.image != undefined && data.image != "")
		{
			charLimit = 1300;
		} else
		{
			charLimit = 1500;		
		}
		
		if (data.story.length < charLimit)
		{
			size = "small";
		} else
		{
			size = "x-small";
		}
		infoHtml += '<div style="font-size:'+size+';"><p>' + data.story + '</p></div>';
		
		/// TAGS
		
		var tagsTitle;
		if (lang == "en")
		{
			tagsTitle = "Tags for this story";
			siteTitle = "My web page";
		} else
		{
			tagsTitle = "Mots-clés pour cette histoire";
			siteTitle = "Mon site";
		}
		
		// If there are tags...
		if (data.tags.length > 0)
		{
			infoHtml += '<div class="popup_tags"><h3>'+tagsTitle+'</h3>';
			infoHtml += '<p>' + sortTags(data.tags) + '</p></div>';
		}
		
		
		/// URL LINK
		if (data.url != undefined)
		{
			infoHtml += '<div class="popup_tags"><h3>'+siteTitle+'</h3><p><a href='+data.url+'>' + data.url.split("http://")[1] + '</a></p></div>';
		}
		
		// create the marker now
		var labels = new Object();
		labels.en = ['Story', 'Photo', 'Video'];	
		labels.fr = ['Histoire', 'Photo', 'Video'];
			
		// have we a video?
		if (data.tube != undefined)
		{
			// YES - add another tab for it
			var videoHtml = '<object type="application/x-shockwave-flash" style="width:425px; height:350px;" data="'+data.tube+'"><param name="movie" value="'+data.tube+'" /></object>';
		} else { var videoHtml = undefined;}
		// 
		
		/// SO - let's see what we've got
		
		
		if (videoHtml != undefined && photoHtml != undefined)
		{
			// 3-tab layout
			var tmarker = newTabMarker(point, [ labels[lang][0], labels[lang][1], labels[lang][2] ], [infoHtml, photoHtml, videoHtml], i);
		} else if (videoHtml != undefined && photoHtml == undefined)
		{
			// 2 tab layout with video
			var tmarker = newTabMarker(point, [ labels[lang][0], labels[lang][2] ], [infoHtml, videoHtml], i);
		} else if (photoHtml != undefined && videoHtml == undefined)
		{
			// 2 tab layout with photo
			var tmarker = newTabMarker(point, [ labels[lang][0], labels[lang][1] ], [infoHtml, photoHtml], i);
		} else
		{
			// 1 tab layout
			var tmarker = newTabMarker(point, [ labels[lang][0] ], [infoHtml], i);
		}	
		
		map.addOverlay(tmarker); 
		markerSet.push(tmarker);
	}
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}

function sortTags(tagsArray)
{
	var tagsHtml = "";
	var tagsSplit = tagsArray.split(",");
	for (i = 0; i < tagsSplit.length; i++)
	{
		tagsHtml += '<a href="/'+lang+'/story/#/tagged/'+tagsSplit[i]+'">' + tagsSplit[i] + '</a>&nbsp;';
	}
	return tagsHtml
}

function createMarker(point, id) {
	var icon = new GIcon();
	icon.image = "/assets/images/combi-dot.png";
	icon.shadow = "/assets/images/combi-shadow50.png";
	icon.iconSize = new GSize(37, 34);
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(12, 30);
	icon.infoWindowAnchor = new GPoint(13, 13);
	
	var marker = new GMarker(point, icon);
	marker.id = id;
	
	return marker;
}

function newTabMarker(point, labels, contents, id) {
		
	//var marker = getCustomMarker(point);
	var marker = new GMarker(point);
	marker.id = id;
	
	// first set up styling
	contents[0] = '<div id="popup">' + contents[0] + '</div>';
	// set up the marker
	GEvent.addListener(marker, "click", function() {
		// sort out the width
		if (contents.length > 2) {
			var tabWidth = contents.length*88 + 'px';
			contents[0] = '<div style="width:'+tabWidth+'">' + contents[0] + '</div>';
		}
		var tabs = [];
		for (var i=0; i < contents.length; i++) {
			tabs.push(new GInfoWindowTab(labels[i], contents[i]));
		}
		marker.openInfoWindowTabsHtml(tabs);
		
		// and zoom the map in if its too far out
		if (map.getZoom() < 5)
		{
			map.setZoom(5);
		}
	});
	
	return marker;
}

function getCustomMarker(point)
{
	var icon = new GIcon();
	icon.image = "/assets/images/monkey.png";
	icon.shadow = "/assets/images/monkey-shadow50px.png";
	icon.iconSize = new GSize(32, 32);
	icon.shadowSize = new GSize(50, 32);
	icon.iconAnchor = new GPoint(16, 16);
	icon.infoWindowAnchor = new GPoint(13, 0);
	
	var marker = new GMarker(point, icon);

	return marker;
}


function showCredits()
{
	flashMovie.showCredits();
}



// Various Marker Icons for Reference
/* COMBI 
var icon = new GIcon();
icon.image = "/assets/images/combi-dot.png";
icon.shadow = "/assets/images/combi-shadow50.png";
icon.iconSize = new GSize(37, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(12, 30);

// MONKEY!!
var icon = new GIcon();
icon.image = "/assets/images/monkey.png";
icon.shadow = "/assets/images/monkey-shadow50px.png";
icon.iconSize = new GSize(32, 32);
icon.shadowSize = new GSize(50, 32);
icon.iconAnchor = new GPoint(16, 16);

// NICO / JB!!
var icon = new GIcon();
icon.image = "/assets/images/nico_jb.png";
icon.shadow = "/assets/images/nico_jb-shadow.png";
icon.iconSize = new GSize(33, 56);
icon.shadowSize = new GSize(45, 56);
icon.iconAnchor = new GPoint(16, 56);
icon.infoWindowAnchor = new GPoint(13, 13);
*/
