var map;
var myTileOverlay;
var legendOverlay;
var gSeamapLayerOpacity = 1.0;
var layer_name = "distribution_all";	// Default

var gUrlMapserver = "http://seamap.env.duke.edu/cgi-bin/mapserv";
var gRootUrl = 'http://seamap.env.duke.edu/prod/';
var gMapProcessUrl = gRootUrl + "services/coml/map_processes.php";

var map_path = "/var/www/prod/mapservice/maps/seamap_distribution.map";

var gClickedPoint;
var autoHideLegend;

var buttonBackgroundColor = "#C3D9FF";

function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("map"), {draggableCursor:"default"});
		map.addControl(new GLargeMapControl());
		map.addControl(new GHierarchicalMapTypeControl());

		map.setCenter(new GLatLng(10, 0), 1, G_SATELLITE_MAP);
		$('map').setStyle({"background-color": '#1D1C56'});	// Set GM's background color to the dark ocean color.

		var copyright = new GCopyright(1,
		   new GLatLngBounds(new GLatLng(23,122),new GLatLng(46,151) ),
		    1, "OBIS-SEAMAP");
		
		var copyrightCollection = new GCopyrightCollection('SEAMAP Distribution');
		copyrightCollection.addCopyright(copyright);
		
		var myTileLayer = new GTileLayer(copyrightCollection, 1, 16);
		myTileLayer.getTileUrl = myGetTileUrl;
		myTileLayer.getOpacity = function() { return gSeamapLayerOpacity; }
		myTileLayer.isPng = function() { return true; }
		
		myTileOverlay = new GTileLayerOverlay(myTileLayer);
		
		map.addOverlay(myTileOverlay);

		var legendUrl = "http://seamap.env.duke.edu/icons/distribution_legend.png";
		legendOverlay = new GScreenOverlay(legendUrl, new GScreenPoint(73, 28), new GScreenPoint(1, 1), new GScreenSize(130, 117));
		map.addOverlay(legendOverlay);
		autoHideLegend = setTimeout(hideLegend, 8000);		// 10 seconds

		var control = new AllControl();
		map.addControl(control);
		var control = new AvesControl();
		map.addControl(control);
		var control = new MammalControl();
		map.addControl(control);
		var control = new ReptileControl();
		map.addControl(control);
		var control = new LegendControl();
		map.addControl(control);

		GEvent.addListener(map, "click", on_click_identify);

	}
}

function hideLegend() {
	legendOverlay.hide();
	clearTimeout(autoHideLegend);
	$$("div.legend_control").each(function (item) {item.style.backgroundColor = '#ffffff';});
}

/***** Mapserver layer definition *****/
// Return URL to get a tile image from Mapserver.
function myGetTileUrl(tile, zoom) {

    // max zoom plus 1
    var projection = new GMercatorProjection(18);

    // Four vertices location in pixcel in GPoint coordinates
    var p1 = new GPoint(tile.x*256,tile.y*256);
    var p2 = new GPoint(p1.x+256,p1.y+256);

    // latitude/longitude of four vertices location in decimal degree
    var latlng1 = projection.fromPixelToLatLng(p1,zoom);
    var latlng2 = projection.fromPixelToLatLng(p2,zoom);

    var lat1 = latlng1.lat();
    var lon1 = latlng1.lng();
    var lat2 = latlng2.lat();
    var lon2 = latlng2.lng();

    // binding box for mapserver
    var minlat = Math.min(lat1,lat2);
    var minlon = Math.min(lon1,lon2);
    var maxlat = Math.max(lat1,lat2);
    var maxlon = Math.max(lon1,lon2);
	var bbox = minlon + "," + minlat + "," + maxlon + "," + maxlat;

	var mapext = minlon + "+" + minlat + "+" + maxlon + "+" + maxlat;

	var url = gUrlMapserver + "?map=" + map_path;

	var mapserver_request = url + "&mode=map&mapsize=256+256";
	mapserver_request += "&mapext=" + mapext;
	mapserver_request += "&LAYER=" + layer_name;

	// Add random parameter, so the image is not cached by browser
	//var random_parm = (new Date()).format('mmddyyyyhhnnss');
    //return mapserver_request + "&" + random_parm;
    return mapserver_request;
}

function AllControl () {
}

AllControl.prototype = new GControl();

AllControl.prototype.initialize = function(map) {
	var ControlDiv = document.createElement("div");
	$(ControlDiv).addClassName('normal');
	this.setButtonStyle_(ControlDiv);
	ControlDiv.style.backgroundColor = buttonBackgroundColor;
	//ControlDiv.appendChild(document.createTextNode("All"));
	var image = document.createElement("IMG");
	image.src = "http://seamap.env.duke.edu/prod/images/icons/all.png";
	ControlDiv.appendChild(image);
	GEvent.addDomListener(ControlDiv, "click", function() {
	        layer_name = "distribution_all";
			myTileOverlay.refresh();
			$$("div.normal").each(function (item) {item.style.backgroundColor = '#ffffff';});
			this.style.backgroundColor = buttonBackgroundColor;
	      });
	map.getContainer().appendChild(ControlDiv);
	return ControlDiv;
}

AllControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 6));
}

AllControl.prototype.setButtonStyle_ = setButtonStyle;

/***** For Aves *****/
function AvesControl () {
}

AvesControl.prototype = new GControl();

AvesControl.prototype.initialize = function(map) {
	var ControlDiv = document.createElement("div");
	$(ControlDiv).addClassName('normal');
	this.setButtonStyle_(ControlDiv);
	//ControlDiv.appendChild(document.createTextNode("Birds"));
	var image = document.createElement("IMG");
	image.src = "http://seamap.env.duke.edu/prod/images/icons/seabirds.png";
	ControlDiv.appendChild(image);
	GEvent.addDomListener(ControlDiv, "click", function() {
	        layer_name = "distribution_aves";
			myTileOverlay.refresh();
			$$("div.normal").each(function (item) {item.style.backgroundColor = '#ffffff';});
			this.style.backgroundColor = buttonBackgroundColor;
	      });
	map.getContainer().appendChild(ControlDiv);
	return ControlDiv;
}

AvesControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(147, 6));
}

AvesControl.prototype.setButtonStyle_ = setButtonStyle;


/***** For Mammals *****/
function MammalControl () {
}

MammalControl.prototype = new GControl();

MammalControl.prototype.initialize = function(map) {
	var ControlDiv = document.createElement("div");
	$(ControlDiv).addClassName('normal');
	this.setButtonStyle_(ControlDiv);
	//ControlDiv.appendChild(document.createTextNode("Mammal"));
	var image = document.createElement("IMG");
	image.src = "http://seamap.env.duke.edu/prod/images/icons/marine_mammals.png";
	ControlDiv.appendChild(image);
	GEvent.addDomListener(ControlDiv, "click", function() {
	        layer_name = "distribution_mammalia";
			myTileOverlay.refresh();
			$$("div.normal").each(function (item) {item.style.backgroundColor = '#ffffff';});
			this.style.backgroundColor = buttonBackgroundColor;
	      });
	map.getContainer().appendChild(ControlDiv);
	return ControlDiv;
}

MammalControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(224, 6));
}

MammalControl.prototype.setButtonStyle_ = setButtonStyle;

/***** For Reptile *****/
function ReptileControl () {
}

ReptileControl.prototype = new GControl();

ReptileControl.prototype.initialize = function(map) {
	var ControlDiv = document.createElement("div");
	$(ControlDiv).addClassName('normal');
	this.setButtonStyle_(ControlDiv);
	//ControlDiv.appendChild(document.createTextNode("Turtle"));
	var image = document.createElement("IMG");
	image.src = "http://seamap.env.duke.edu/prod/images/icons/sea_turtles.png";
	ControlDiv.appendChild(image);
	GEvent.addDomListener(ControlDiv, "click", function() {
	        layer_name = "distribution_reptilia";
			myTileOverlay.refresh();
			$$("div.normal").each(function (item) {item.style.backgroundColor = '#ffffff';});
			this.style.backgroundColor = buttonBackgroundColor;
	      });
	map.getContainer().appendChild(ControlDiv);
	return ControlDiv;
}

ReptileControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(301, 6));
}

ReptileControl.prototype.setButtonStyle_ = setButtonStyle;


/***** For Legend *****/
function LegendControl () {
}

LegendControl.prototype = new GControl();

LegendControl.prototype.initialize = function(map) {
	var ControlDiv = document.createElement("div");
	$(ControlDiv).addClassName('legend_control');
	this.setButtonStyle_(ControlDiv);
	ControlDiv.style.backgroundColor = buttonBackgroundColor;
	ControlDiv.appendChild(document.createTextNode("Legend"));
	GEvent.addDomListener(ControlDiv, "click", function() {
			//this.style.backgroundColor = buttonBackgroundColor;
			if (legendOverlay.isHidden()) {
				legendOverlay.show();
				this.style.backgroundColor = buttonBackgroundColor;
				autoHideLegend = setTimeout(hideLegend, 8000);		// 10 seconds
			} else {
				//hideLegend();
			}
	      });
	map.getContainer().appendChild(ControlDiv);
	return ControlDiv;
}

LegendControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
}

LegendControl.prototype.setButtonStyle_ = setButtonStyle;


function setButtonStyle(button) {
	button.style.display = "inline";
	button.style.textDecoration = "none";
	button.style.backgroundColor = "white";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "75px";
	button.style.cursor = "pointer";
}

/***** Identeify start *****/
var popup_script;
function on_click_identify(overlay, point) {
	// GM's default polygon click passes point as undefined, so ignore the event.
	// Custom polygon click event listener passes both overlay and point.
	if (overlay && typeof(point) == 'undefined') {
		return false;
	}

	//$('please_wait').show();
	gClickedPoint = point;
	var lat = point.lat();
	var lon = point.lng();
	var parameters = "mode=identify&latitude=" + lat + "&longitude=" + lon;
	parameters += "&mapfile=" + map_path;
	parameters += "&layers=distribution_all";

	if(popup_script) {
		document.body.removeChild(popup_script);
	}
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = gMapProcessUrl + "?" + parameters;
	document.body.appendChild(script);
}

/***** Identeify end *****/