/*Icons*/
var audioSwf = "/static-covermap/swf/player_mp3_maxi.swf";
var videoSwf = "/static-covermap/swf/player_flv.swf";
var rightIcon = "/static-covermap/icons/right.gif";
var leftIcon = "/static-covermap/icons/left.gif";
var newCityIcon = "/static-covermap/icons/newCity.png";
var oldCityIcon = "/static-covermap/icons/oldCity.png";

/*Messages*/
var noTestimoniesMessage = "S&eacute; el primero en dejar un testimonio en esta ciudad.<br/>Env&iacute;a un MMS video o vocal a red@orange.com.do";
var footerMessage = "Deja tu testimonio enviando un MMS<br/>video o vocal a red@orange.com.do<br/>";

/*Paths*/
var cityFolderPath = "/static-covermap/media/";
var servletHost = "http://www.orange.com.do/covermap-servlets/";

/*MISC configuration*/
var defaultBubble = "Santo_Domingo";
var bubbleWidth = 180;
var displayCoverage = false;


/*---------- Class Definitions ----------*/

/*Testimony Class*/
function Testimony(streamFile, personName, dateOfCreation, cityId)
{
	this.streamFile = streamFile;
	this.personName = personName;
	this.dateOfCreation = dateOfCreation;
	this.cityId = cityId;
}

/*City Class*/
function City(cityId, displayName, codeName, latitude, longitude, hasTestimonies, pointType)
{
	this.cityId = cityId;
	this.displayName = displayName;
	this.codeName = codeName;
	this.latitude = latitude;
	this.longitude = longitude;
	this.hasTestimonies = hasTestimonies;
	this.pointType = pointType;
}
/*---------- End Class Definitions ----------*/

/*------------- Global Variables ------------*/
/*The Map*/
var map = null;

/*Array of testimonies for currently opened marker*/
var currentTestimonies = null;

/*Bubble Resize Module*/
var enlarge = false;
var shorten = false;
var videoBubble = null;

/*tools*/
var once = true;

/*----------- End Global Variables -----------*/

jQuery(function() {
	if (location.protocol == 'https:')
		servletHost = "https://www.orange.com.do/covermap-servlets/";
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(18.83352, -70.15), 7);
		map.setUIToDefault();
		map.setMapType(G_PHYSICAL_MAP);
		
		if (displayCoverage){
			var boundaries = new GLatLngBounds(new GLatLng(17.56,-71.90), new GLatLng(19.94,-68.310));
			var oldmap = new GGroundOverlay("/static-covermap/cover.png", boundaries);
			map.addOverlay(oldmap);
		}

		var minmapscale = 7;
		var mapTypes = map.getMapTypes();
		for (var i=0; i<mapTypes.length; i++) {
			mapTypes[i].getMinimumResolution = function() {return minmapscale;};
		}

		GEvent.addListener(map, "infowindowbeforeclose", function() {
			var bubbleContent = document.getElementById("bubbleContent");
			if (bubbleContent != null)
				bubbleContent.innerHTML = "";
		});

		loadMarkers();

	}
});

function loadMarkers() {
	jQuery.get(servletHost + 'cities', function(data) {
		var cities = jQuery(data);
		var autoOpenCity = null;
		var markerManager = new GMarkerManager(map);
		cities.find('City').each( function() {
			var cityId = jQuery(this).find('CityId').text();
			var displayName = jQuery(this).find('DisplayName').text();
			var codeName = jQuery(this).find('CodeName').text();
			var lng = jQuery(this).find('Longitude').text();
			var lat = jQuery(this).find('Latitude').text();
			var hasTestimonies = jQuery(this).find('HasTestimonies').text();
			var pointType = jQuery(this).find('PointType').text(); 
			if (pointType == "0" || pointType == "1")
				createMarker(new City(cityId, displayName, codeName, lat, lng, hasTestimonies, pointType), markerManager);
		});
		markerManager.refresh();
		document.getElementById("map_canvas").style.visibility = "visible"; 
		document.getElementById("loading_message").style.visibility = "hidden";
	}, 'xml');
}

function createMarker(city, markerManager) {

	var markerIcon = new GIcon(G_DEFAULT_ICON);
	if (city.hasTestimonies != '0')
	{
		markerIcon.image = newCityIcon;
		var size = 8;
		markerIcon.iconSize = new GSize(size, size);
		markerIcon.iconAnchor = new GPoint(size / 2, size / 2);
		markerIcon.infoWindowAnchor = new GPoint(size / 2, size / 2);
	}
	else
	{
		markerIcon.image = oldCityIcon;
		var size = 6;
		markerIcon.iconSize = new GSize(size, size);
		markerIcon.iconAnchor = new GPoint(size / 2, size / 2);
		markerIcon.infoWindowAnchor = new GPoint(size / 2, size / 2);
		
	}
	markerIcon.shadow = "";

	var position = new GLatLng(city.latitude, city.longitude);
	var marker = new GMarker(position, {title:city.displayName, icon:markerIcon});

	if (city.pointType == "0")
	{
		map.addOverlay(marker);
		if (city.codeName == defaultBubble)
			onMarkerClick(marker, city);
	}
	else if (city.pointType == "1")
		markerManager.addMarker(marker, 10);
	GEvent.addListener(marker, "click", function() {
  		onMarkerClick(marker, city);
	});
}


function onMarkerClick(marker, city)
{
	if (city.hasTestimonies == '0')
		openEmptyBubble(city.displayName, marker);
	else
	{
		jQuery.get(servletHost + 'testimonies?city_id=' + city.cityId,
				function(data) {
			var i = 0;
			var t = new Array();
			var testimonies = jQuery(data);
			testimonies.find('Testimony').each(function() {
				var name = jQuery(this).find('Name').text();
				var streamFile = jQuery(this).find('StreamFile').text();
				var date = jQuery(this).find('Date').text();
				var cityId = jQuery(this).find('CityId').text();
				t[i] = new Testimony(streamFile, name, date, cityId);
				i++;});
			openNewBubble(city, marker, t);
		}, 'xml');
	}
}

function openEmptyBubble(cityName, marker)
{
	var htmlCode = "<div id='style' style='text-align:left'>";
	htmlCode += "<label class='cityName'>" + cityName + "</label><br/><br/>";
	htmlCode += "<p>" + noTestimoniesMessage + "</p></div>";
	generateInfoWindow(cityName, marker, htmlCode, 1);
}

function openNewBubble(city, marker, t)
{
	videoBubble = null;
	currentTestimonies = t;
	var contentString = getGeneratedHtml(city.codeName, city.displayName, t.length - 1);
	generateInfoWindow(city.displayName, marker, contentString, 0);
}

var currentMarker;

function generateInfoWindow(cityName, marker, contentString, isEmpty)
{
	if (isEmpty == 1)
		marker.openInfoWindowHtml(contentString);
	else
		marker.openInfoWindowHtml("<div id='bubbleContent'>" + contentString + "</div>", {maxWidth:bubbleWidth});
	currentMarker = marker;
}

function changeInfoWindowHTML(codeName, displayName, pageNbr)
{
	var tableIndex = pageNbr - 1;
	var newContent = getGeneratedHtml(codeName, displayName, tableIndex);
	document.getElementById("bubbleContent").innerHTML = newContent;
	var infoWindow = map.getInfoWindow();
	var point = infoWindow.getPoint();
	if (enlarge)
	{
		infoWindow.reset(point, null, new GSize(bubbleWidth, 257));
		var offset = map.getBounds().getNorthEast().lat() - currentMarker.getLatLng().lat();
		var zoom = map.getZoom() - 6;
		if (zoom == 1 && offset < 3.86 || zoom == 2 && offset < 1.95 || zoom == 3 && offset < 0.98 ||
		    zoom == 4 && offset < 0.49 || zoom == 5 && offset < 0.24 || zoom == 6 && offset < 0.122 ||
		    zoom == 7 && offset < 0.061 || zoom == 8 && offset < 0.0306 ||zoom == 9 && offset < 0.0153)
			map.panBy(new GSize(0, - 95 * offset * pow(2, zoom - 1) + 375));
	}
	if (shorten)
		infoWindow.reset(point, null, new GSize(bubbleWidth, 152));
	enlarge = false;
	shorten = false;
}

function pow(a, b)
{
	if (b == 0)
	  return 1;
	else
	  return a * pow(a, b - 1);
}

function isVideo(fileName)
{
	var tmp = new Array();
	tmp = fileName.split('.');
	if(tmp[tmp.length - 1] == "flv")
		return true;
	return false;
}

function resizeInfoWindow(contentElementId, width, height) {
    var infoWindow = map.getInfoWindow();
    var point = infoWindow.getPoint();
    infoWindow.reset(point, null, new GSize(width,height));
}

function verifyResize(fileLocation)
{
	if (videoBubble == null)
	{
		if(isVideo(fileLocation))
			videoBubble = true;
		else
			videoBubble = false;
	}
	else
	{
		if(isVideo(fileLocation))
		{	
			if (videoBubble == false)
				enlarge = true;
			videoBubble = true;
		}
		else
		{
			if (videoBubble == true)
				shorten = true;
			videoBubble = false;
		}
	}	
}

function getGeneratedHtml(codeName, displayName, tbleIndex)
{
	var testimony = currentTestimonies[tbleIndex];
	var fileLocation = cityFolderPath + codeName + "-" + testimony.cityId + "/" + testimony.streamFile;
	var htmlCode = "<div id='style' style='width:200px;'>";
	htmlCode += "<label class='cityName'>" + displayName + "</label><br/><br/>";
	htmlCode += "<label>" + testimony.personName + ", " + testimony.dateOfCreation + "</label><br/>";

	if(isVideo(fileLocation))
		htmlCode +=
		"<center><div style='height:125px;width:100%;padding-top:5px;padding-bottom:5px;'><object type='application/x-shockwave-flash' data='" + videoSwf + "' width='100%' height='100%'>" +
		"<param name='movie' value='" + videoSwf + "' />" +
		"<param name='wmode' value='transparent' />" +
		"<param name='FlashVars' value='flv=" + fileLocation + "&amp;autonext=0&amp;playonload=1&amp;margin=0&amp;loadingcolor=ff6600&amp;bgcolor1=000000&amp;showvolume=1&amp;showopen=0&amp;showplayer=always&amp;playercolor=333333&amp;playeralpha=75&amp;buttonovercolor=ff6600&amp;sliderovercolor=cccccc&amp;showiconplay=1&amp;iconplaycolor=cccccc&amp;iconplaybgcolor=ff6600&amp;iconplaybgalpha=50'> "+
		"</object></div></center>";
	else
		htmlCode += "<div style='height:20px;width:100%;padding-top:5px;padding-bottom:5px;'><object type='application/x-shockwave-flash' data='" + audioSwf + "' width='100%' height='100%'>"
			+ "<param name='movie' value='" + audioSwf + "' />"
		       + "<param name='wmode' value='transparent' />" 
			+ "<param name='FlashVars' value='mp3=" + fileLocation + "&amp;showstop=1&amp;buttonovercolor=ff6600&amp;sliderovercolor=ff6600&amp;loadingcolor=ff6600' />"
			+ " </object></div>";

	if (currentTestimonies.length >= 2)
	{
		htmlCode += "<table style='width:100%'><tr>";
		htmlCode += "<td style='text-align:left'>";
		if (tbleIndex == 0)
			htmlCode += "&nbsp;";
		else
			htmlCode += "<a href=\"javascript:changeInfoWindowHTML('" + codeName + "', '" + displayName +"', "+ tbleIndex + ")\">"
			+ "<img border='0' src='" + leftIcon + "'> anterior</a>";
		htmlCode += "</td>";

		htmlCode += "<td style='text-align:right'>";
		if (tbleIndex == currentTestimonies.length - 1)
			htmlCode += "&nbsp;";
		else
			htmlCode += "<a href=\"javascript:changeInfoWindowHTML('" + codeName + "', '" + displayName +"', "+ (tbleIndex + 2) + ")\">"
			+ "siguiente <img border='0' src='" + rightIcon + "'></a>";
		htmlCode += "</td>";
		htmlCode += "</tr></table>";
	}
	else
		htmlCode +="<br/>";
	htmlCode += "<label class='subMsg'>" + footerMessage + "</label></div>";
	verifyResize(fileLocation);
	return htmlCode;
}