//*************************************************************************
// This is the default config object for overlays, base layers and extents.
// Note: if testing a mapserver installation without tilecache, use the debug
//   version at the bottom of this file.
//*************************************************************************
var PortalConfig = function(){
	
	var server = "http://mapserver.conservationregistry.org";
	var tileCachePrefix = server + "/tilecache/tilecache.py/1.0.0/";
	var baseMapPrefix = server + "/tilecache/tilecache.py";
	var mapFile = "/home/ryan/public_html/mapserver/coa/registry.map";
	var mapserver = "/cgi-bin/mapserv";
	
	// Note: these depend on the map size and may need to be adjusted if this changes
	var extents ={'WCS' : {lat: 38.06539, lng: -97.734375, zoom: 4},
								'USA' : {lat: 38.06539, lng: -97.734375, zoom: 4},
								'CPCESU': {lat: 36.7213, lng: -108.9404, zoom: 6},
								'PCJV' : {lat: 36.73888412439431, lng: -140.44921875, zoom: 4},
								'USFWS_R1' : {lat: 36.73888412439431, lng: -140.44921875, zoom: 4},
								'POTOMAC' : {lat: 38.788345355085625, lng: -78.936767578125, zoom: 7},
								// States
								'ID': {lat: 45.4946, lng: -114.1433, zoom: 6},
								'OR': {lat: 44.1454, lng: -120.5834, zoom:6},
								'WA': {lat: 47.273, lng: -120.8825, zoom: 6},
								'AR': {lat: 34.7867391627025, lng: -92.35107421875, zoom: 7},
								'CA': {lat: 37.142803443716836, lng: -119.9267578125, zoom:6}};
	
	
	// OVERLAYS
	// Portal-specific overlays go here
	// NOTE: Make sure nced overlay is always last.
	var overlays = {'USA': [tileCacheOverlay('huc4', 'Watersheds (HUC 4)'),
													//tileCacheOverlay('TNC_ecoregions', 'TNC Ecoregions'),
													//tileCacheOverlay('TNC_priority_areas', 'TNC Priority Areas'),
													tileCacheOverlay('tnc_terr_ecoregions', 'TNC Ecoregions'),
													tileCacheOverlay('Omernik_ecoregions', 'Omernik Ecoregions'),
													new GTileLayerOverlay(createWMSTileLayer("TNC Priorities", "",
													'http://maps.tnc.org/ecadpubprod-anon/services/portfolio_anon_WM/MapServer/WMSServer',
													'0', 4, 17, {tileWidth:512, tileHeight:512, opacity: 0.6})),
													tileCacheOverlay('bird_conservation_regions', 'Bird Regions (BCRs)'),
													tileCacheOverlay('congressional_districts', 'Congressional Districts')],
									'OR' : [tileCacheOverlay('wv_synthesis', "Willamette Synthesis")],
									'WA' : [tileCacheOverlay('wa_priorities', "Biodiversity Areas")]

									//				tileCacheOverlay('nced_all_project_sites', "NCED Easements")],
									//'NCED' : [tileCacheOverlay('nced_all_project_sites', "PAD-US (Inactive)")]
	};
	
	var projectSites = tileCacheOverlay('all_project_sites_sm', 'All Project Sites');
	
	var portalProjectSites = {
		'USA' : projectSites,
		'CPCESU': tileCacheOverlay('cpcesu_all_project_sites', 'CPCESU Sites'),
		'NFWF': tileCacheOverlay('nfwf_all_project_sites', 'NFWF Sites'),
		'WCS': tileCacheOverlay('wcs_all_project_sites', 'WCS Sites'),
		'DEFENDERS' : tileCacheOverlay('defenders_all_project_sites', 'Defenders sites'),
		'PCJV' : tileCacheOverlay('pcjv_all_project_sites', "PCJV sites"),
		'USFWS_R1' : tileCacheOverlay('usfws_r1_all_project_sites', "USFWS Region 1 sites"),
		'PCJV' : tileCacheOverlay('pcjv_all_project_sites', "PCJV sites")};
		//'NCED' : tileCacheOverlay('nced_all_project_sites', "NCED Easements")
	//};
	
	
	function priorityAreas(){
		if(Prototype.Browser.IE && TOF.ConsRegistry.getIEVersion() <= 6.0){
			// NOTE: space at the end is significant; DO NOT REMOVE
			return tileCacheOverlay('SWAPS_ie6', 'Wildlife Action Plans '); 
		}
		else{
			return tileCacheOverlay('SWAPS', 'Wildlife Action Plans');
		}
	}
	
	
	// BASE LAYERS
	// Portal-specific base layers can be added here
	var baseLayers = {'USA': 
		 [// tileCacheBaseMap('topo', 'Topo'),
		 // createSimpleWMSMapType('Topo', 'Imagery by USGS/Web Service by TerraServer',
		 // 		 									 	"http://mapserver-sandbox.conservationregistry.org/tilecache/tilecache.cgi", 
		 // 														'topo', 4, 17, {format: "jpeg"}),
		 createSimpleWMSMapType('Topo', 'Imagery by USGS/Web Service by TerraServer',
		 		 									 			'http://www.terraserver-usa.com/ogcmap6.ashx', 
		 		 									 			'DRG', 4, 17, {format: "jpeg", tileWidth:512, tileHeight:512}),
		  createSimpleWMSMapType('Ownership', 
		 												'<a href="http://nationalatlas.gov/metadata/fedlanp020.faq.html">National Atlas</a>',								
		  														server + mapserver + "?map=" + mapFile,
		 												'state_shapes,federal_lands_base,state_outlines', 4, 17),
			// createSimpleWMSMapType('LandCover', 'USGS NLCD',
			// 											'http://ims.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDC_LandCover_NLCD_Merged?ServiceName=USGS_EDC_LandCover_NLCD_Merged',
			// 												'US_NLCD', 10, 17, {tileWidth:512, tileHeight:512, mercProj:54004})
			
			
			// createSimpleWMSMapType('LandCover', 'USGS NLCD',
			// 	'http://toposervices.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDNA_geo?',
			// 	'NLCD_1992_LANDCOVER', 9, 17, {tileWidth:512, tileHeight:512, mercProj:54004})
			createSimpleWMSMapType('LandCover', 'USGS NLCD',
				'http://toposervices.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDNA?',
				'EDNA.NLCD_CONUS', 4, 17, {tileWidth:512, tileHeight:512, mercProj:54004})
			]
	};
	// http://mapserver-staging.conservationregistry.org/cgi-bin/mapserv?map=/home/ryan/public_html/mapserver/coa/registry.map
	// UTILITY FUNCTIONS
	function tileCacheUrl(layer_name, isPng){
		var prefix = tileCachePrefix;
		var imgType;
		if(isPng){ imgType = "png";}
		else{imgType = "jpeg";}
		
		var suffix = "/{Z}/{X}/{Y}." + imgType + "?type=google";
		return prefix + layer_name + suffix;
	}


	function tileLayer(layer, opts){
		var opts = opts || {};
		var minRes = opts.minResolution || null;
		var maxRes = opts.maxResolution || null;
		var isPng = true;
		if(opts.isPng == false){isPng = false;}
		
		return new GTileLayer(null, minRes, maxRes, 
			{tileUrlTemplate : tileCacheUrl(layer, isPng), isPng: isPng});
	}
	
	function tileCacheOverlay(layer, name){
		var tl = tileLayer(layer);
		tl.name = name;
		return new GTileLayerOverlay(tl);
	}
	
	// TODO: add options parameter
	function tileCacheBaseMap(layer, name){
		var tl = tileLayer(layer, {minResolution:4, maxResolution: 17, isPng:false});
		return new GMapType([tl], G_SATELLITE_MAP.getProjection(), name);
	}
	
	return {extents:extents, overlays:overlays, projectSites:projectSites,
					priorityAreas:priorityAreas, baseLayers:baseLayers, 
					tileCacheOverlay:tileCacheOverlay, portalProjectSites:portalProjectSites};
}();


//***************************************************************************
// This portal config object should be used when debugging mapserver/tilecache
// This version is with the layers using MapServer only (not Tilecache).
// Set this in the MapInitDefauls#init method  => new Portal(subdomain, PortalConfigDebug)
//***************************************************************************
var PortalConfigDebug = function(){
	
	//var mapserverPrefix = "http://mapserver-staging.conservationregistry.org/mapserv.cgi";
  var mapserverPrefix = "http://mapserver-sandbox.conservationregistry.org/cgi-bin/mapserv";
	var mapFilePrefix = "map=/home/ryan/public_html/mapserver/coa/";
	var defaultMapFile = mapFilePrefix + "registry.map";
	
	
	function restfulOverlay(urlPrefix, layer, name){
		var suffix = "/{Z}/{X}/{Y}.png";
		var tl = new GTileLayer(null, 4, 17, 
			{tileUrlTemplate : (urlPrefix + "/" + layer + suffix), isPng: true});
		tl.name = name;
		return new GTileLayerOverlay(tl);
	}
	
	function mapserverURL(mapFile){
		var mapConfig = mapFile || defaultMapFile;
		return mapserverPrefix + "?" + mapConfig;
	}
	
	var extents = PortalConfig.extents;
	
	// var overlays = {
	// 	'USA': [
	// 		new GTileLayerOverlay(createWMSTileLayer("Watersheds (Huc 4)", "", 
	// 		 mapserverURL(), "us_huc4", 4, 17)),
	// 		new GTileLayerOverlay(createWMSTileLayer("TNC Priority Areas", "", 
	// 		 mapserverURL(), "TNC_PNW_portfolio", 4, 17)),
	// 		new GTileLayerOverlay(createWMSTileLayer("TNC Ecoregions", "", mapserverURL(), "TNC_ecoregions", 4, 17)),
	// 		new GTileLayerOverlay(createWMSTileLayer("Omernik Ecoregions", "", mapserverURL(), "Omernik_ecoregions", 4, 17))
	// 		]
	// 	};
	
	// WARNING: since these are not copies...
	var overlays = PortalConfig.overlays;
// 	overlays.USA.push(new GTileLayerOverlay(createWMSTileLayer("TNC Priority Areas", "",
// //	'http://ecad.tnc.org/arcgisprod-anon/services/portfolio_anon/MapServer/WMSServer',
// //	'http://ecadtest.tnc.org/arcgistest-anon/services/conservation_projects_anon_WM/MapServer/WMSServer', // Mercator => mercProj: 102113
// //	'http://ecadtest.tnc.org/arcgistest-anon/services/port_anon_WB/MapServer/WMSServer',
// //	'http://ecadtest.tnc.org/arcgistest-anon/services/ConProSpatialAnon/MapServer/WMSServer',
// //	'http://ecadtest.tnc.org/arcgistest-anon/services/portfolio_anon/MapServer/WMSServer',
// 	'http://ecad.tnc.org/arcgisprod-anon/services/portfolio_anon/MapServer/WMSServer',
// 	'0', 4, 17, {tileWidth:512, tileHeight:512, opacity: 0.6})));
	
	// overlays.USA.push(restfulOverlay("http://ecad.tnc.org/arcgisprod-anon/rest/services/portfolio_anon/MapServer",
	// 									"tile", "TNC Priority Areas"));
	// var overlays = Object.clone(PortalConfig.overlays); // TODO: test this...
	
	// ...these need to be commented out when not in use
	// overlays['CPCESU'] = [
	// 	new GTileLayerOverlay(createWMSTileLayer("CPCESU Sites", "", mapserverURL(mapFilePrefix + "test_project_sites.map"), 
	// 	"cpcesu_all_points,cpcesu_project_sites_point,cpcesu_project_sites_line,cpcesu_project_sites_poly,cpcesu_project_sites_large_poly", 4, 17))
	// ];
	// overlays['NFWF'] = [
	// 	new GTileLayerOverlay(createWMSTileLayer("NFWF Sites", "", mapserverURL(mapFilePrefix + "test_project_sites.map"), 
	//  	"nfwf_all_points,nfwf_project_sites_point,nfwf_project_sites_line,nfwf_project_sites_poly,nfwf_project_sites_large_poly", 4, 17))];
	// overlays['WCS'] = [
	// 	new GTileLayerOverlay(createWMSTileLayer("WCS Sites", "", mapserverURL(mapFilePrefix + "test_project_sites.map"), 
	//  	"wcs_all_points,wcs_project_sites_point,wcs_project_sites_line,wcs_project_sites_poly,wcs_project_sites_large_poly", 4, 17))];

	
	var projectSites = PortalConfig.projectSites;
	// var projectSites = new GTileLayerOverlay(createWMSTileLayer('All Project Sites', '',
	// 											mapserverURL(mapFilePrefix + 'test_project_sites.map'),
	// 											'all_points,project_sites_point,project_sites_line,project_sites_poly,project_sites_large_poly',
	// 											4,17));
		
	var portalProjectSites = PortalConfig.portalProjectSites;
	var priorityAreas = PortalConfig.priorityAreas;
	var baseLayers = PortalConfig.baseLayers;
	

	
	return {extents:extents, overlays:overlays, projectSites:projectSites,
					priorityAreas:priorityAreas, baseLayers:baseLayers, mapserverURL:mapserverURL,
					portalProjectSites:portalProjectSites};
}();



//*********************************************************
// Main object instantiated in the map initialization file
// Params: 
// 	subdomain => string for lookup purposes
// 	config => optional; default is PortalConfig, but use 
//			      PortalConfigDebug for debugging MapServer/Tilecache
//*********************************************************
function Portal(subdomain, config){
	this.subdomain = subdomain;
	this.config = config || PortalConfig; // PortalConfigDebug;
}

Portal.prototype.getExtent = function(){
	var extent = this.config.extents[this.subdomain];
	if(extent){ return extent; }
	else{ return this.config.extents['USA'];}
}



Portal.prototype.getOverlays = function(include_project_sites){
	var priorityAreas = [this.config.priorityAreas()];
	var usa_overlays  = this.config.overlays["USA"];
	if(this.subdomain == "NCED"){ usa_overlays.pop(); }
	var standardOverlays = priorityAreas.concat(usa_overlays);
	var overlays;

	if(this.subdomain != "USA" && this.config.overlays[this.subdomain]){
		overlays = standardOverlays.concat(this.config.overlays[this.subdomain]);
	}
	else{
		overlays = standardOverlays;
	}
	
	
	if(include_project_sites){
		return [this.config.projectSites].concat(overlays);
	}
	else{
		return overlays;
	}
}
	
	
Portal.prototype.getBaseLayers = function(){
	var USBaseLayers = this.config.baseLayers["USA"];
	if(this.subdomain != "USA" && this.config.baseLayers[this.subdomain]){
		return USBaseLayers.concat(this.config.baseLayers[this.subdomain]);
	}
	else{ return USBaseLayers; }
}

Portal.prototype.allProjectSites = function(){
	return this.config.projectSites;
}

Portal.prototype.portalProjectSites = function(){
	return this.config.portalProjectSites[this.subdomain];
}
	
