var myDomain=document.domain;

var MyURLGeo;

/* if (myDomain.indexOf("192.168.1.106")>-1) {
        MyURLGeo='http://192.168.1.106:8484';
} else {
        MyURLGeo='http://127.0.0.1:8484';
} */

if (myDomain.indexOf("figis02")>-1 ||myDomain.indexOf("193.43.36.238")>-1||myDomain.indexOf("www-data.fao.org")>-1) {
	MyURLGeo='http://193.43.36.238:8484';
} else {
	MyURLGeo='http://www.fao.org';
}

/* myRequest, mapDiv, projection */

function mapGeneratorFS(myRequest, mapDiv, projection) {
	
	if (projection == 3349)
	  projection = 900913; // use google spherical mercator ...
	
	var myMap, myOptions, myBounds;
	
	if (projection==3031){
		myBounds = new OpenLayers.Bounds(-10000000,-10000000,10000000,10000000);
		myOptions = {
			maxExtent: myBounds,
			units:'m', 
			projection:"EPSG:3031",
			maxResolution: 39062.5
		  };
	} else if (projection==900913){
		myBounds = new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
		myOptions = {
			maxExtent: myBounds,
			units: "m",
			projection:"EPSG:900913",
			maxResolution: 78271.516953125
			//maxResolution: 156543.03390625
		};
	} else {
		/*maxresolution for GWC is 0.703125*/
		myBounds = new OpenLayers.Bounds(-180,-90,180,90);
		myOptions = {
			maxExtent: myBounds,
			units: 'degrees',
			projection: "EPSG:4326",
			maxResolution: 0.703125
		  };
	}

	myMap = new OpenLayers.Map(mapDiv, myOptions);
	myMap.addControl(new OpenLayers.Control.LayerSwitcher());
	
	var loadingpanel = new OpenLayers.Control.LoadingPanel();
	myMap.addControl(loadingpanel);
	
	if (projection!=3031){
		myMap.addControl(new OpenLayers.Control.ScaleLine());
	}	

	OpenLayers.ProxyHost = "/figis/proxy/cgi-bin/proxy.cgi?url=";
	
	var position0=0;

	var ThePresentLayers = new Array();
	var ThePresentFilters = new Array();
	var h=0;
	
	var myRequestItems = myRequest.split('/');
	
	for ( var i = 0; i < myRequestItems.length; i++ ) if (myRequestItems[i].indexOf('-') > 0 ) {
		var myRC = myRequestItems[i].split('-');
		ThePresentLayers.push( myRC.shift() );
		ThePresentFilters.push( myRC.join('-') );
		h++;
	}
	
	ThePresentFilters.push('');
	ThePresentLayers.push("fifao:UN_CONTINENT");
	
	h++;
	/*################################
	To verify if a land area if listed in the layers
	It needs to be the last layer available */
	var j=99;
	for (var i=0; i<h; ++i) {
		/*SHAPEFILE*/
		/*if(ThePresentLayers[i]=='fifao:ln1xcb3'){*/
		/*ORACLE*/
		if(ThePresentLayers[i]=='fifao:ISO3_COUNTRY') {
			j=i;
			break;
		}
	}
	if (j!=99){
		ThePresentFilters.push(ThePresentFilters[j]);
		ThePresentLayers.push(ThePresentLayers[j]);
		ThePresentLayers.splice(j, 1);
		ThePresentFilters.splice(j, 1);
	}
	
	/*################################*/
	var TheWMS = new Array();
	
	for (var i=0; i<h; ++i) {
		/*JPEG for transparency issue in IE*/
		var myWMS;
			if (ThePresentFilters[i] !='') {
				/* GWC doesn't work with CQL filter */
				if (projection != 3031){
					if (ThePresentLayers[i]=='fifao:FAO_MAJOR' && i==(h-2) ){
					/*TO DISPLAY IN BLUE THE MAIN FAO AREAS WHEN PRIMARY*/
						myWMS = new OpenLayers.Layer.WMS(ThePresentLayers[i].substr(ThePresentLayers[i].indexOf(":")+1),MyURLGeo + "/figis/geoserver/wms?",
										{
											layers: ThePresentLayers[i],
											format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
											styles:'all_fao_areas_style',
											transparent: 'true',
											TILED: 'true',
											TILESORIGIN: [myBounds.left, myBounds.bottom],
											BUFFER: 0,
											BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top],
											//palette: 'web_safe_palette_colors',
											cql_filter:  ThePresentFilters[i]
										},
										{
											wrapDateLine: true,
											//singleTile: true,
											ratio: 1
										}
									);
					} else {
						myWMS = new OpenLayers.Layer.WMS(ThePresentLayers[i].substr(ThePresentLayers[i].indexOf(":")+1),MyURLGeo + "/figis/geoserver/wms?",
										{
											layers: ThePresentLayers[i],
											format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
											transparent:"true",
											TILED: 'true',
											TILESORIGIN: [myBounds.left, myBounds.bottom],
											BUFFER: 0,
											BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top],
											//palette: 'web_safe_palette_colors',
											cql_filter: ThePresentFilters[i]
										},
										{
											wrapDateLine: true,
											//singleTile: true,
											ratio: 1
										}
									);
					}
				} else {
					myWMS = new OpenLayers.Layer.WMS(ThePresentLayers[i].substr(ThePresentLayers[i].indexOf(":")+1),MyURLGeo + "/figis/geoserver/wms?",
									{
										layers: ThePresentLayers[i],
										format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
										transparent:"true",
										TILED: 'true',
										TILESORIGIN: [myBounds.left, myBounds.bottom],
										BUFFER: 0,
										BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top],
										//palette: 'web_safe_palette_colors',
										cql_filter:  ThePresentFilters[i]
									},
									{
										wrapDateLine: true,
										//singleTile: false,
										ratio: 1
									}
								);
				}
			} else {
				if (projection != 3031 && projection != 900913){
						/*GWC only work with a gif output format*/
						/*Problem with wrapDateLine AND singleTile: true*/
						/*gwc/service to be removed if trouble in th display*/
						myWMS = new OpenLayers.Layer.WMS(ThePresentLayers[i].substr(ThePresentLayers[i].indexOf(":")+1),MyURLGeo + "/figis/geoserver/gwc/service/wms?",
									{
										layers: ThePresentLayers[i],
										format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
										transparent: "true",
										TILED: 'true',
										TILESORIGIN: [myBounds.left, myBounds.bottom],
										BUFFER: 0,
										BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top]
									},
									{
										wrapDateLine: true,
										ratio: 1
									}
								);
				} else {
						/*GWC only work with a gif output format*/
						/*GWC only works with EPSG: 4326*/
						myWMS = new OpenLayers.Layer.WMS(ThePresentLayers[i].substr(ThePresentLayers[i].indexOf(":")+1),MyURLGeo + "/figis/geoserver/wms?",
									{
										layers: ThePresentLayers[i],
										format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
										//palette: 'web_safe_palette_colors',
										transparent: "true",
										TILED: 'true',
										TILESORIGIN: [myBounds.left, myBounds.bottom],
										BUFFER: 0,
										BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top]
									},
									{
										wrapDateLine: true,
										ratio: 1
									}
								);
				}
			}
			
			/*The singletile for the polar projection change the display.*/
			/*Problem with wrapDateLine AND singleTile: true*/
			/*SingleTileTrue and gwc does not work together*/
			/*if (projection != 3031){
				myWMS.addOptions({singleTile: true});
			}*/
			
			if (i==0){						
				myWMS.addOptions({buffer: 0,isBaseLayer: true});
			} else {			
				myWMS.addOptions({buffer: 0,isBaseLayer: false});
			}		
		TheWMS.push(myWMS);	
	}	

	for (var i=0; i<h; ++i) {
		myMap.addLayer(TheWMS[i]);
	}		
	/*Use of the version 1.0.0 ofr the wms in order to have the zoom working with the script*/
	var FilterAltWFS;
	var FilterAltWFS1;
	var FilterWFS;
	var FilterWFS1;		

	if (h>1 && projection != 3031 && projection != 900913){
		var IntersectingAreaIndex = 1;
		for ( var i = 0; i < h; i++ ) {
			if ( ThePresentLayers[i].indexOf('SPECIES_DIST') > 0 ) {
				IntersectingAreaIndex++;
			} else {
				break;
			}
		}
		var WaterAreaIndex = IntersectingAreaIndex -1;
		
		FilterAltWFS1=ThePresentFilters[ IntersectingAreaIndex ];
		FilterWFS1=FilterAltWFS1.replace(/ /g,"%20");
		if(mapDiv=="mapPSM") {
			OpenLayers.loadURL(
				MyURLGeo + "/figis/geoserver/wfs?request=GetFeature&version=1.0.0&typename=" + ThePresentLayers[ IntersectingAreaIndex ]  + "&cql_filter=(" + FilterWFS1 + ")",
				"",
				null,
				function(req) { parseData(req,myMap) }
			);
		} else {
			if (ThePresentFilters[ WaterAreaIndex ]!='') {
				/*To remove white spaces from the filter which crash with the proxy*/
				FilterAltWFS=ThePresentFilters[ WaterAreaIndex ];
				FilterWFS=FilterAltWFS.replace(/ /g,"%20");
				OpenLayers.loadURL(
					MyURLGeo + "/figis/geoserver/wfs?request=GetFeature&version=1.0.0&typename=" + ThePresentLayers[ WaterAreaIndex ]  + "&cql_filter=(" + FilterWFS + ")",
					"",
					null,
					function(req) { parseData(req,myMap) }
				);
			} else {
				/*To remove white spaces from the filter which crash with the proxy*/
				/*Imply that the layer [1] always ahev a filter: countries
				FilterAltWFS1=ThePresentFilters["1"];	
				FilterWFS1=FilterAltWFS1.replace(/ /g,"%20");*/
				OpenLayers.loadURL(
					MyURLGeo + "/figis/geoserver/wfs?request=GetFeature&version=1.0.0&typename=" + ThePresentLayers[ IntersectingAreaIndex ]  + "&cql_filter=(" +  FilterWFS1 + ")",
					"",
					null,
					function(req) { parseData(req,myMap) }
				);
			}
		}
	} else {
		myMap.zoomToMaxExtent();
		if (projection == 3031)
			myMap.setCenter(new OpenLayers.LonLat(156250.0, 703256.0));
		else if (projection == 900913)
			myMap.setCenter(new OpenLayers.LonLat(20037508.34, 4226661.92));
	}
	
}

function parseData(req,theMap) {
	var options = {returnBbox: 'true'};
	var g =  new OpenLayers.Format.GML();
	features = g.read(req.responseText, options);
  
	/*var bounds;
	if (features.constructor != Array) {
		features = [features];
	}
	for(var i=0; i<features.length; ++i) {
	
		if (!bounds) {
			bounds = features[i].geometry.getBounds();
		} else {
			bounds.extend(features[i].geometry.getBounds());
		}
	}	
	if (features.length>0){
		theMap.zoomToExtent(bounds); 
	} else{
		theMap.zoomToMaxExtent();
	}*/

	if (features && features.bbox){
		theMap.zoomToExtent(features.bbox);
	} else{
		theMap.zoomToMaxExtent();
	}	

}

function generate_map(value_code, value_text) {
	if (value_code =='None') 
	{
		alert ("Choose a species");
	}
	else 	
	{	
		window.location.href="/figis/web-maps/species-maps/species-maps-result.html?3AC=" + value_code +"&name=" + value_text.replace(' ', '_') ;		
	}
}

function mapGeneratorSpecies(param_code,rectangle_extension) {
	/*maxresolution for GWC is 0.703125*/
	var myBounds = new OpenLayers.Bounds(-180,-90,180,90);
	var options = { maxExtent: myBounds,
					units: 'degrees',
					projection: "EPSG:4326",					
					maxResolution: 0.703125								
				  };		
	var myMap = new OpenLayers.Map('mapSpecies',options);
	
	//myMap.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')}));
	myMap.addControl(new OpenLayers.Control.LayerSwitcher());
	myMap.addControl(new OpenLayers.Control.ScaleLine());
	//myMap.addControl(new OpenLayers.Control.OverviewMap());
	var loadingpanel = new OpenLayers.Control.LoadingPanel();
	myMap.addControl(loadingpanel);
											
	OpenLayers.ProxyHost = "/figis/proxy/cgi-bin/proxy.cgi?url=";
		
	var wms_species_marine = new OpenLayers.Layer.WMS("Background",MyURLGeo + "/figis/geoserver/wms?",
									{
										layers: 'fifao:SPECIES_DIST',
										cql_filter: "ALPHACODE='"+ param_code + "' and ECOLOGY=1",
										//palette: 'web_safe_palette_colors',
										format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
										TILED: 'true',
										TILESORIGIN: [myBounds.left, myBounds.bottom],
										BUFFER: 0,
										BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top]
									},
									{
										buffer:0, 
										isBaseLayer: true,
										ratio: 1
									} /*, wrapDateLine: true*/
								);
	/*gwc/service/*/
	/*gwc/service to be removed if trouble in th display*/
	var wms_continent = new OpenLayers.Layer.WMS("Continent",MyURLGeo + "/figis/geoserver/gwc/service/wms?",
								{
									layers: 'fifao:UN_CONTINENT',
									transparent: true,
									format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
									TILED: 'true',
									TILESORIGIN: [myBounds.left, myBounds.bottom],
									BUFFER: 0,
									BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top]
								},
								{
									buffer:0, 
									isBaseLayer: false,
									ratio: 1
								}
							);			
  /*, wrapDateLine: true*/
	var wms_species_freshwater = new OpenLayers.Layer.WMS("Background",MyURLGeo + "/figis/geoserver/wms?",
									{
										layers: 'fifao:SPECIES_DIST',
										cql_filter: "ALPHACODE='"+ param_code + "' and ECOLOGY=2",
										transparent: true,
										//palette: 'web_safe_palette_colors',
										format: OpenLayers.Util.alphaHack() ? "image/gif": "image/png",
										TILED: 'true',
										TILESORIGIN: [myBounds.left, myBounds.bottom],
										BUFFER: 0,
										BBOX: [myBounds.left, myBounds.bottom, myBounds.right, myBounds.top]
									},
									{
										buffer:0, 
										isBaseLayer: false,
										ratio: 1
									}
								);	
	 /*, wrapDateLine: true*/
	myMap.addLayer(wms_species_marine);
	myMap.addLayer(wms_continent);
	myMap.addLayer(wms_species_freshwater);	
		
	if (rectangle_extension=='true') {
		/*EXTREMELY TIME CONSUMING*/	
		OpenLayers.loadURL(
			MyURLGeo + "/figis/geoserver/wfs?request=GetFeature&version=1.0.0&typename=fifao:SPECIES_DIST&cql_filter=(ALPHACODE='"+ param_code + "')",
			"", 
			null, 
			function(req) {parseDataRectangle(req,myMap);}
		);
	}
	else {
		myMap.zoomToMaxExtent();
	}

}
function parseDataRectangle(req,theMap) {
	var options = {returnBbox: 'true'};
	var g =  new OpenLayers.Format.GML();
	features = g.read(req.responseText, options);
					
	/*for (var i=0;i<features.length;i++) {
		var feature = features[i];
		var bounds = feature.geometry.getBounds();
		if (i==0){
			var minx=bounds.left;
			var miny=bounds.bottom;
			var maxx=bounds.right;
			var maxy=bounds.top;
		}
		
		minx = Math.min(minx, bounds.left);
		miny = Math.min(miny, bounds.bottom);
		maxx = Math.max(maxx, bounds.right);
		maxy = Math.max(maxy, bounds.top);												
	}*/
	
	var bounds = features.bbox;
	var minx=bounds.left;
	var miny=bounds.bottom;
	var maxx=bounds.right;
	var maxy=bounds.top;
			
	if (maxx-minx<200){
		var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry");											
		var style_polygon = {
			strokeColor: "black",
			strokeOpacity: 1,
			strokeWidth: 1,
			fillOpacity:0
		};		
		var pointList = [];
		if (maxx-minx<12){
			minx=minx-2;
			miny=miny-2
			maxx=maxx+2;
			maxy=maxy+2;												
		}												
		var newPoint1 = new OpenLayers.Geometry.Point(minx, miny);
		pointList.push(newPoint1);
		var newPoint2 = new OpenLayers.Geometry.Point(minx, maxy);
		pointList.push(newPoint2);
		var newPoint3 = new OpenLayers.Geometry.Point(maxx, maxy);
		pointList.push(newPoint3);
		var newPoint4 = new OpenLayers.Geometry.Point(maxx, miny);
		pointList.push(newPoint4);
		
		pointList.push(pointList[0]);

		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		polygonFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null,style_polygon);										  	
		theMap.addLayer(vectorLayer);
		vectorLayer.addFeatures([ polygonFeature]);
	}

	theMap.zoomToMaxExtent();
}