//<![CDATA[
var exportColor = "#E4AE93";
var continentColor = "#a7a7a5";
var activeColor = "#808000";
var phpScriptMapDataURL = "mapdata.php";
var phpScriptgetPolygonURL = "getpolygons.php";
var phpScriptgetTransfersURL = "gettransfers.php";
var world, map;
var activeCountry;
var mapClickListener;
var countryList = [];
var popupOpen = 0;

function loadMap() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    // För att inte ladda googles karta. http://groups.google.co.in/group/Google-Maps-API/browse_thread/thread/c865d5b38b7260ca?hl=en&pli=1
    G_NORMAL_MAP.getTileLayers()[0].getTileUrl = function(a,b){return "pics/bg-tile.png";} 
    map.setCenter(new GLatLng(20, 30), 2);
    map.addControl(new GSmallMapControl());
    $("#staticmap").click(removeStaticMap);
    GEvent.addListener(map, "tilesloaded", removeloading);
  //  GEvent.addListener(map, "click", closePopup);
    getStoredPolygons("all", 1980, 2008); // andra/tredje är start-/slutår, fjärde parametern är polygon, femte är infotext. 1 betyder hämta. 0 betyder hämta inte.
  //  var wikip = new GLayer("org.wikipedia.sv");
  //  map.addOverlay(wikip);
  } 
  else alert ("Din webbläsare är inte kompatibel med Google maps.");
}

function removeStaticMap() {  
    $("#staticmap").remove(); //css('zIndex', 0);
}

function removeloading() {  
    $("#loading").remove(); //css('zIndex', 0);
}


////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function drawPolygon(countryXml, color, clickable) {
	var points = [];
	var polygon;
	var i = 0;
	$("point", countryXml).each(function() {
		points[i] = new GPoint( $("lat", this).text(), $("lon", this).text() );
		// marker = new GMarker(poly[i]);
		i++;
	});
	points[points.length] = points[0];	//knyt ihop polygonen genom att lägga till den första punkten igen på slutet.
	polygon = new GPolygon(points, "#f33f00", 0, 1, color, 1);
	if (clickable) {
		GEvent.addListener(polygon, "mouseover", function(latlng) {
			if (popupOpen == 1) return false;
			polygon.color=activeColor; 
			polygon.redraw(true);
		});
		GEvent.addListener(polygon, "mouseout", function(latlng) {
			if (popupOpen == 1) return false;
			if (! (polygon == activeCountry)) {
				polygon.color=exportColor; 
				polygon.redraw(true);
			}
		});
		GEvent.addListener(polygon, "click", function(latlng) {
			if (popupOpen == 1) return false;
			if (activeCountry) {
				activeCountry.color = exportColor;
				activeCountry.redraw(true);
			}
			jqueryPopup($("code", countryXml).text(), latlng);
			activeCountry = polygon;
			polygon.color=activeColor; 
			polygon.redraw(true);
		});
	}
	map.addOverlay(polygon);


}

function closePopUp() {
	$("#closepopup").unbind('click'); 
	$(".popup").unbind('click'); 
	popupOpen = 0;
	$(".popup").remove();

}

// ===========================================================================
// TRANSFERS

function showTransfers(xml) {
	var html = "<tr><th>System</th><th>Information</th><th>Källa</th></tr>";
	$("transfer", xml).each(function() {
		html += "<tr><td>" + $("sys", this).text() + "</td>";
		// html += "<td>" + $("buy", this).text() + "</td>";
		html += "<td>" + $("desc", this).text() + "</td>";
		html += "<td>" + $("src", this).text() + "</td></tr>";
	});
	html = "<table>" + html + "</table>";
	html = 	"<a id='tableanchor'></a><h2>" + $("land", xml).text() + "</h2>" + html;
	$("#landdata").html(html);
	$("tr:even").addClass("alt");
	closePopUp();
}

function getTransfers(cC) {
	$("#landdata").html('<img src="pics/loading.gif" />');
	ajaxTransfers(cC);
}

function ajaxTransfers(cC, firstyear, lastyear) {
  jQuery.ajax({
                 type: "GET",
                 dataType: "xml",
                 url: phpScriptgetTransfersURL, 
                 data: "cC=" + cC + "&y1=" + firstyear + "&y2=" + lastyear, 
                 success: showTransfers,
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                   alert("Det gick tyvärr inte att hämta data för " + cC);
		   closePopUp();
		   $("#landdata").html("");
                 }  // end error function
  });  // end ajax call
} // end function getPolygons

// ===========================================================================

function appendCountryInfo(infoXml, cC) {
		var cName = "", cInfo = "";
		if (cC in countryList) { // om den andra parametern är "success" så har funktionen anropats som callback från funktionen som hämtar från databasen.
			cName = countryList[cC].name;
			cInfo = countryList[cC].infotext;
		} else {
			cName = $("name", infoXml).text();
			cInfo = $("info", infoXml).text();
			cC = $("code", infoXml).text();
			countryList[cC] = new Object ();
			countryList[cC].name = cName;
			countryList[cC].infotext = cInfo;
		}
		$(".popup").append("<div class='popuppil' />");
		$(".popup").append("<div class='popuptextarea'><p style='float:right' class='popuptext'><a id='closepopup'>Stäng [x]</a></p><h3 class='popuprubrik'>" + cName + "</h3>"
				  +"<p class='popuptext'>" + cInfo + "</p>"
				  +"<hr />"
				  +"<p class='popuptext'><a id='readmorelink' href='#tableanchor'>Läs mer</a></p></div>");
		popupOpen = 1;
		$("#readmorelink").click(function(event) {
			event.stopPropagation();
			event.preventDefault();
			$("#readmorelink").unbind('click');
			$("#readmorelink").remove();
			getTransfers(cC);
		});
		$("#closepopup").click(function(event) {
			event.stopPropagation();
			event.preventDefault();
			closePopUp();
		});
		/*mapClickListener = GEvent.addListener(map, "click", function(overlay, latlng) {
			if (latlng) { 
				activeCountry.color = exportColor;
				activeCountry.redraw(true);
				activeCountry = null;
				GEvent.removeListener(mapClickListener);
			}
		});*/
		// $("#landdata").slideDown("slow");
		// polygon.openInfoWindow('<div id="tab1" class="bubble">Click the "Location" tab to see the minimap</div>'); polygoner har inte infowindows.
}

function drawAllPolygons(xml) {
	$("country", xml).each(function() {
		if ($("code", this).text().substring(0,4) != "CONT") {
			drawPolygon($(this), exportColor, 1); //sista parametern avgör om den ska vara klickbar.
		} else {
			drawPolygon($(this), continentColor, 0);
		}
	});
}

function getStoredPolygons(cC, firstyear, lastyear) {
  jQuery.ajax({
                 type: "GET",
                 dataType: "xml",
                 url: phpScriptgetPolygonURL, 
                 data: "cC=" + cC + "&y1=" + firstyear + "&y2=" + lastyear, 
                 success: drawAllPolygons,
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                   alert("error");

                 }  // end error function
  });  // end ajax call
} // end function getPolygons

function getCountryInfo(cC, firstyear, lastyear) {
	// http://www.bram.us/2008/02/01/javascript-isarray-check-if-an-elementobject-is-an-array/
	if (cC in countryList) {
		appendCountryInfo(null, cC);
	} else {
		jQuery.ajax({
			type: "GET",
			dataType: "xml",
			url: phpScriptMapDataURL, 
			data: "i=1&n=1&cC=" + cC + "&lim=1&y1=" + firstyear + "&y2=" + lastyear, 
			success: appendCountryInfo,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("error: " + textStatus);
			}  // end error function
		});  // end ajax call
	} // end else.
} // end function getPolygons

function stayOnTop (event) {
	agent = jQuery.browser;
	if(agent.msie) {
		event.cancelBubble = true;
	} else {
		event.stopPropagation();
	}
}

function jqueryPopup(cC, latlng) {	// se: http://marcgrabanski.com/article/jquery-google-maps-tutorial-basics
      $(".popup").unbind();
      $(".popup").remove();
      var popHtml = '<div class="popup" style="display:none;"></div>';
  //    $(popHtml).click(stayOnTop);
      $(map.getPane(G_MAP_FLOAT_SHADOW_PANE)).append(popHtml);
      getCountryInfo(cC, 1980, 2008);
      map.panTo(latlng);
      var offset = map.fromLatLngToDivPixel(latlng);
      offset.x = offset.x + 40;
      offset.y = offset.y - 60;
      $(".popup").fadeIn(800).css({ top:offset.y, left:offset.x });
}


$(document).ready(function(){
  $("body").unload(function() {GUnload(); unset(countryList);});
});

//]]>
