// --------------------------------------------------------------------------------
// This file contains the javascript functions used by NHSS.
// --------------------------------------------------------------------------------

// This are the global variables
// Parameters for map information
var map;
var navToolbar;
var imageryPrime, streetMap, boundariesWorld;
var activeBase;

var hazards, visibleHaz = [];
var identifyTaskHaz, identifyParamsHaz;
var equakes, hurrs, volcs, ovolcs, wfires, perms, floods;

var weat, visibleWeat = [];
var identifyTaskWeat, identifyParamsWeat;
var weatwarns = 0;
var weatalerts = 0;
var weather;

var tidestns, visibleTideS = [];
var identifyTaskTideS, identifyParamsTideS;
var tides;

var info, visibleInfo = [];
var identifyTaskInfo, identifyParamsInfo;
var raws, sgages, flands; 
 
var shake;
var shkmpstate = 0;
 
var femadec;
var decstate = 0;

var femadrc;
var drcstate = 0;

//Parameters for identify results
var numTabs = 0; 
var tabName; 
 
//Parameters for using the nexrad service	
var nexradMap;
var nexradstate = "initial";
	
// Paramaters for auto redraw
var timerSet = "off";
var TimerID;
var mins = 0;
var secs = 0;

//Parameters for print function
var printMap;
var t = parent;
	
// Establish the WMS for NEXRAD 
dojo.declare("my.nexradWMSLayer", esri.layers.DynamicMapServiceLayer, { 
    constructor: function() { 
        this.initialExtent = this.fullExtent = new esri.geometry.Extent({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid: 4326}}); 
        this.spatialReference = new esri.SpatialReference({wkid:4326}); 
		this.loaded = true; 
        this.onLoad(this); 
    }, 
    getImageUrl: function(extent, width, height, callback) { 
        var params = { 
			request:"GetMap", 
            transparent:true, 
            format:"image/png", 
            bgcolor:"ffffff", 
            version:"1.1.1", 
            layers:"nexrad-n0r", 
            styles: "default,default", 
            exceptions: "application/vnd.ogc.se_xml", 
 
            //changing values 
            bbox:extent.xmin + "," + extent.ymin + "," + extent.xmax + "," + extent.ymax, 
            srs: "EPSG:" + extent.spatialReference.wkid, 
            width: width, 
            height: height 
          }; 
          callback("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi?" + dojo.objectToQuery(params)); 
        } 
      }) 
 
 
function init() {
    //Turn off map slider labels and position the slider
    esriConfig.defaults.map.sliderLabel = null;
    esriConfig.defaults.map.slider = { right:"10px", top:"5px", width:null, height:"150px" };
	
	//Set the initial map extent and create the map
    var USextent = new esri.geometry.Extent({"xmin":-19923361.83,"ymin":226177.53,"xmax":35875.00,"ymax":11966905.07,"spatialReference":{"wkid":102100}});
	map = new esri.Map("map",{wrapAround180:true,extent:USextent,logo:false});
    	
	//Establish the loading icon
	dojo.connect(map,"onLoad",showLoading); 
	//dojo.connect(map,"onUpdateStart",showLoading); 
    dojo.connect(map,"onUpdateEnd",hideLoading); 
	
	//Establish the identify functionality
	dojo.connect(map, "onLoad", initFunctionality);
   
	//Add the base map services
	imageryPrime = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer", {id:"imageryPrime"});
    map.addLayer(imageryPrime);
	activeBase = 'imageryPrime';
		
	streetMap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer", {id:"streetMap"});
    map.addLayer(streetMap);
	streetMap.hide();		
		
	boundariesWorld = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer", {id:"boundariesWorld"});
	map.addLayer(boundariesWorld);
	boundariesWorld.hide();
	
	//Add the dynamic map services
	tidestns = new esri.layers.ArcGISDynamicMapServiceLayer("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_glbdata/MapServer", {id:"tidestns"});
	visibleTideS = [];
	tidestns.setVisibleLayers(visibleTideS);
	map.addLayer(tidestns);
	
	info = new esri.layers.ArcGISDynamicMapServiceLayer("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_usdata/MapServer", {id:"info"});
	visibleInfo = [];
	info.setVisibleLayers(visibleInfo);
	map.addLayer(info);
	
	femadec = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis.fema.gov/REST/services/FEMA/DECs/MapServer", {id:"femadec", "opacity":0.4});
	map.addLayer(femadec);
	femadec.hide();
	
	femadrc = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis.fema.gov/REST/services/FEMA/DRC/MapServer", {id:"femadrc", "opacity":0.4});
	map.addLayer(femadrc);
	femadrc.hide();
	
	shake = new esri.layers.ArcGISDynamicMapServiceLayer("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_shakemaps/MapServer", {id:"shake", "opacity":0.6});
	map.addLayer(shake);	
	shake.hide();
    
	weat = new esri.layers.ArcGISDynamicMapServiceLayer("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_weat/MapServer", {id:"weat", "opacity":0.4});
	visibleWeat = [0];
	weatwarns = 1;
	weat.setVisibleLayers(visibleWeat);
	map.addLayer(weat);	

	hazards = new esri.layers.ArcGISDynamicMapServiceLayer("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_haz/MapServer", {id:"hazards"});
	visibleHaz = [0,1,2,3,4,5];
	hazards.setVisibleLayers(visibleHaz);
	map.addLayer(hazards);
 
	//Display the navigation toolbar
	navToolbar = new esri.toolbars.Navigation(map);

	//resize the map when the browser resizes 
    var resizeTimer; 
    dojo.connect(map, 'onLoad', function(theMap) { 
        dojo.connect(dijit.byId('map'), 'resize', function() { //resize the map if the div is resized 
            clearTimeout(resizeTimer); 
            resizeTimer = setTimeout(function() { 
              map.resize(); 
              map.reposition(); 
            }, 500); 
        }); 
    }); 
 
	//Establish event to display identify results window
	dojo.connect(map.infoWindow, "onShow", function() {
		dijit.byId("tabs").resize();
	});
	
	//Turn off client caching of the hazards and weather layers so that they can be automatically
	hazards.setDisableClientCaching(true);
	weat.setDisableClientCaching(true);

	//Establish and initalize print parameters and functions
	var mapState = dojo.byId("layers");
	printMap = new PrintMap(map, mapState);
	dojo.connect(map, "onZoomEnd", dojo.hitch(printMap, printMap.updateExtent));
} //end init
 
function MM_swapImage(Name) { //v3.0
  	var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
    	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}//end MM_swapImage
	
function MM_swapImgRestore(Name) { //v3.0
    	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
} //end MM_swapImgRestore

function MM_preloadImages() { //v3.0
  	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}//end MM_preloadImages

function MM_findObj(n, d) { //v4.01
  	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  	if(!x && d.getElementById) x=d.getElementById(n); return x;
}//end MM_findObj
 
function showLoading() {
	var loading = dojo.byId("loadingImg");
	esri.show(loading);
	map.hideZoomSlider(); 
} //end showLoading
	
function hideLoading() {
	var loading = dojo.byId("loadingImg");
	esri.hide(loading);
	map.showZoomSlider(); 
} //end hideLoading
	
function ZoomUSExtent(){
	var USExtent = new esri.geometry.Extent(-19923361.83,226177.53,35875.00,11966905.07,new esri.SpatialReference({"wkid":102100}));
	map.setExtent(USExtent);
} //end ZoomInitialExtent

function ZoomWorldExtent(){
	var WExtent = new esri.geometry.Extent(-19962497.59,-8735911.16,19955976.06,14745543.92,new esri.SpatialReference({"wkid":102100}));
	map.setExtent(WExtent);
} //end ZoomFullExtent
		
function updateLayerVisibility(layerID) {
	var visible = [], input;
	weatwarns = 0;
	weatalerts = 0;
	if (layerID == "hazards"){
    	var inputs = dojo.query(".haz_layers");
 	} else if (layerID == "weat") {
		var inputs = dojo.query(".weat_layers");
	} else if (layerID == "tide") {
		var inputs = dojo.query(".tide_layers");	
	} else if (layerID == "info") {
		var inputs = dojo.query(".info_layers");
	} 
	
	for (var i=0, il=inputs.length; i<il; i++) {
		if (inputs[i].checked) {
    		visible.push(i);
			if (inputs[i].id == "Watches/Warnings") {
				weatwarns = 1;
			} else if (inputs[i].id == "Alerts/Advisories") {
				weatalerts = 1;
			}
		}
	}	
	if (layerID == "hazards"){
		visibleHaz = visible;	
		//alert('haz' + layerID + visibleHaz);
        hazards.setVisibleLayers(visibleHaz);
	} else if (layerID == "weat") {
		visibleWeat = visible;
		//alert('weat' + layerID + visible);
		weat.setVisibleLayers(visibleWeat);
	} else if (layerID == "tide") {	
		visibleTideS = visible;
		//alert('tide' + layerID + visible);
		tidestns.setVisibleLayers(visibleTideS);	
	} else if (layerID == "info") {	
		visibleInfo = visible;
		//alert('info' + layerID + visible);
        info.setVisibleLayers(visibleInfo);
	} 
} //end updateLayerVisibility	  

function changeBase(layers) {
	hideImageTiledLayers(layers);
	for (var i=0; i<layers.length; i++) {
		layers[i].show();
	}
	activeBase = layers[0].id;
} //end changeBase
 
function hideImageTiledLayers(layers) {
	for (var j=0, jl=map.layerIds.length; j<jl; j++) {
		var layer = map.getLayer(map.layerIds[j]);
		if (dojo.indexOf(layers, layer) == -1 && (layer.id == "streetMap" )|| (layer.id == "imageryPrime") || (layer.id =="boundariesWorld")) {
			layer.hide();
		}
	}
} //end hideImageTiledLayers

function changeFema(layerID) {
	if (layerID == "dec") {		  
		if (decstate == 0) {
			femadec.show();
			decstate = 1;
		} else {
			femadec.hide();
			decstate = 0;
		}
	} else if (layerID == "drc") {
		if (drcstate == 0) {
			femadrc.show();
			drcstate = 1;
		} else {
			femadrc.hide();
			drcstate = 0;
		}	
	}
} //end changeFema

function changeShakemaps() {
	if (shkmpstate == 0) {
		shake.show();
		shkmpstate = 1;
	} else {
		shake.hide();
		shkmpstate = 0;
	}
} //end changeShakemaps

function initFunctionality(map) {
	mapScales = [];
    var lods = map.getLayer(map.layerIds[0]).tileInfo.lods;
	
	//establish the map scale information
    for (var i = 0, il = lods.length; i < il; i++) {
    	mapScales[i] = lods[i].scale;
    }
    var level = map.getLevel();
    var scale = mapScales[level];	
	dojo.byId('mapScale').innerHTML = 'Map Scale: 1 : '+ addCommas(scale.toFixed(0));
	dojo.connect(map, "onExtentChange", onMapExtentChange);	
	
	//establish the identify event 
	dojo.connect(map, "onClick", doIdentify);
	
	//establish the parameters for the identify on the hazards service
	identifyTaskHaz = new esri.tasks.IdentifyTask("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_haz/MapServer");
	identifyParamsHaz = new esri.tasks.IdentifyParameters();
	identifyParamsHaz.tolerance = 2;
	identifyParamsHaz.returnGeometry = false;
	identifyParamsHaz.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
	
	//establish the parameters for the identify on the weather
	identifyTaskWeat = new esri.tasks.IdentifyTask("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_weat/MapServer");
	identifyParamsWeat = new esri.tasks.IdentifyParameters();
	identifyParamsWeat.tolerance = 1;
	identifyParamsWeat.returnGeometry = false;
	identifyParamsWeat.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
	
	//establish the parameters for the identify on the global tide stations service
	identifyTaskTideS = new esri.tasks.IdentifyTask("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_glbdata/MapServer");
	identifyParamsTideS = new esri.tasks.IdentifyParameters();
	identifyParamsTideS.tolerance = 2;
	identifyParamsTideS.returnGeometry = false;
	identifyParamsTideS.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
	
	//establish the parameters for the identify on the U.S. data service
	identifyTaskInfo = new esri.tasks.IdentifyTask("http://rmgsc.cr.usgs.gov/ArcGIS/rest/services/nhss_usdata/MapServer");
	identifyParamsInfo = new esri.tasks.IdentifyParameters();
	identifyParamsInfo.tolerance = 2;
	identifyParamsInfo.returnGeometry = false;
	identifyParamsInfo.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;

	map.infoWindow.resize(380, 200);
	map.infoWindow.setContent(dijit.byId("tabs").domNode);
	map.infoWindow.setTitle("Data Information");   
} //end initFunctionality 

function doIdentify(evt) {
    //clear any previous identify results 
	map.graphics.clear();
	for (var j=0, jl=numTabs; j<jl; j++) {
		tabName = 'Tab' + j;
		clearTab(tabName);
	}
	numTabs = 0;
	map.infoWindow.hide();
			
	// identify only visible hazards layers
	identifyParamsHaz.layerIds = visibleHaz;
	//alert('haz layers ' + visibleHaz);
	identifyParamsHaz.geometry = evt.mapPoint;
	identifyParamsHaz.mapExtent = map.extent;
	identifyTaskHaz.execute(identifyParamsHaz, function(idResults) { addToMapHaz(idResults, evt); });
	
	// identify the appropriate weather information
	identifyParamsWeat.layerIds = 0;
	//alert(identifyParamsWeat.layerIds);
	identifyParamsWeat.geometry = evt.mapPoint;
	identifyParamsWeat.mapExtent = map.extent;
	identifyTaskWeat.execute(identifyParamsWeat, function(idResults) { addToMapWeat(idResults, evt); });	
	
	// identify only visible global tide station layer
	identifyParamsTideS.layerIds = visibleTideS;
	//alert('info layers ' + visibleInfo);
	identifyParamsTideS.geometry = evt.mapPoint;
	identifyParamsTideS.mapExtent = map.extent;
	identifyTaskTideS.execute(identifyParamsTideS, function(idResults) { addToMapTideS(idResults, evt); });	
	
	// identify only visible U.S. data 
	identifyParamsInfo.layerIds = visibleInfo;
	//alert('info layers ' + visibleInfo);
	identifyParamsInfo.geometry = evt.mapPoint;
	identifyParamsInfo.mapExtent = map.extent;
	identifyTaskInfo.execute(identifyParamsInfo, function(idResults) { addToMapInfo(idResults, evt); });
} //end doIdentify

function addToMapHaz(idResults, evt) {
	// Seperate the identify results into layer based features arrays
	equakes = {displayFieldName:null,features:[]};
	hurrs = {displayFieldName:null,features:[]};
	volcs = {displayFieldName:null,features:[]};
	ovolcs = {displayFieldName:null,features:[]};
	wfires = {displayFieldName:null,features:[]};
	perms = {displayFieldName:null,features:[]};
	floods = {displayFieldName:null,features:[]};
	
	for (var i=0, il=idResults.length; i<il; i++) {
		var idResult = idResults[i];
		if (idResult.layerName === "Earthquakes") {
			if (!equakes.displayFieldName) {equakes.displayFieldName = idResult.displayFieldName};
			equakes.features.push(idResult.feature);
		} else if (idResult.layerName === "Hurricanes") {
			if (!hurrs.displayFieldName) {hurrs.displayFieldName = idResult.displayFieldName};
           		hurrs.features.push(idResult.feature);
		} else if (idResult.layerName === "U.S. Volcanoes") {
			if (!volcs.displayFieldName) {volcs.displayFieldName = idResult.displayFieldName};
			volcs.features.push(idResult.feature);
		} else if (idResult.layerName === "Other Volcanoes") {
			if (!ovolcs.displayFieldName) {ovolcs.displayFieldName = idResult.displayFieldName};
			ovolcs.features.push(idResult.feature);	
		} else if (idResult.layerName === "Wildfires") {
			if (!wfires.displayFieldName) {wfires.displayFieldName = idResult.displayFieldName};
			wfires.features.push(idResult.feature);		  
		} else if (idResult.layerName === "Wildfire Perimeters") {
			if (!perms.displayFieldName) {perms.displayFieldName = idResult.displayFieldName};
			perms.features.push(idResult.feature);  
		} else if (idResult.layerName === "Floods") {
			if ( (idResult.feature.attributes['CLASS']) === 'Above Flood Stage') {
				if (!floods.displayFieldName) {floods.displayFieldName = idResult.displayFieldName};
				floods.features.push(idResult.feature);
			}	
		}
	} //end for
		
	// Create the needed tabs and add the layer based feature array information
	if (idResults.length>0){
		if (equakes.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Earthquakes');
			dijit.byId(tabName).setContent(layerTabContent(equakes,"Earthquakes")); 
			numTabs = numTabs+1; 
		}
		if (hurrs.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Hurricanes');
			dijit.byId(tabName).setContent(layerTabContent(hurrs,"Hurricanes")); 
			numTabs = numTabs+1; 
		}	
		if (volcs.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'US Volcanoes');
			dijit.byId(tabName).setContent(layerTabContent(volcs,"U.S. Volcanoes")); 
			numTabs = numTabs+1; 
		}
		if (ovolcs.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Volcanoes');
			dijit.byId(tabName).setContent(layerTabContent(ovolcs,"Other Volcanoes")); 
			numTabs = numTabs+1; 
		}
		if (wfires.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Wildfires');
			dijit.byId(tabName).setContent(layerTabContent(wfires,"Wildfires")); 
			numTabs = numTabs+1; 
		}
		if (perms.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Fire Perimeters');
			dijit.byId(tabName).setContent(layerTabContent(perms,"Wildfire Perimeters")); 
			numTabs = numTabs+1; 
		}
		if (floods.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Floods');
			dijit.byId(tabName).setContent(layerTabContent(floods,"Stream Floods")); 
			numTabs = numTabs+1; 
		}
	}
		
	// Display the identify window if results were found
	if (numTabs > 0){
	map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
	}
} //end addToMapHaz
	 
function addToMapWeat(idResults, evt) {
	// Seperate the identify results into layer based features arrays
	weather = {displayFieldName:null,features:[]};
	
	for (var i=0, il=idResults.length; i<il; i++) {
		var idResult = idResults[i];
		if ( (weatwarns == 1) && (weatalerts == 0)) {
			if ( ((idResult.feature.attributes['EVENT'].search('WARNING')) != -1) || 
			     ((idResult.feature.attributes['EVENT'].search('WATCH')) != -1) ) {
				if (!weather.displayFieldName) {weather.displayFieldName = idResult.displayFieldName};
				weather.features.push(idResult.feature);	
			}
		} else if ( (weatwarns == 0) && (weatalerts == 1)) {
			if ( ((idResult.feature.attributes['EVENT'].search('ALERT')) != -1) || 
			     ((idResult.feature.attributes['EVENT'].search('ADVISORY')) != -1) ) {
				if (!weather.displayFieldName) {weather.displayFieldName = idResult.displayFieldName};
				weather.features.push(idResult.feature);	
			}
		} else if ( (weatwarns == 1) && (weatalerts == 1)) {
			if ( ((idResult.feature.attributes['EVENT'].search('WARNING')) != -1) || 
				 ((idResult.feature.attributes['EVENT'].search('WATCH')) != -1) || 
				 ((idResult.feature.attributes['EVENT'].search('ALERT')) != -1) || 
				 ((idResult.feature.attributes['EVENT'].search('ADVISORY')) != -1)) {
				if (!weather.displayFieldName) {weather.displayFieldName = idResult.displayFieldName};
				weather.features.push(idResult.feature);	
			}
		}
	} //end for
	
	// Create the needed tabs and add the layer based feature array information
	if (weather.features.length>0){
		tabName = 'Tab' + numTabs
		addTab(tabName, 'Weather');
		dijit.byId(tabName).setContent(layerTabContent(weather,"Weather")); 
		numTabs = numTabs+1;  
	}
	
	// Display the identify window if results were found
	if (numTabs > 0){
		map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
	}
} //end addToMapWeat

function addToMapTideS(idResults, evt) {
	// Seperate the identify results into layer based features arrays
	tide = {displayFieldName:null,features:[]};
		
	for (var i=0, il=idResults.length; i<il; i++) {
		var idResult = idResults[i];
		if (idResult.layerName === "Tide Stations") {
			if (!tide.displayFieldName) {tide.displayFieldName = idResult.displayFieldName};
			tide.features.push(idResult.feature);  
		}
	} //end for
	//alert('sgages' + sgages.features.length + 'raws' + raws.features.length + 'tide' + tide.features.length);
		
	// Create the needed tabs and add the layer based feature array information
	if (idResults.length>0){
		if (tide.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Tide Data');
			dijit.byId(tabName).setContent(layerTabContent(tide,"Tide Stations")); 
			numTabs = numTabs+1; 
		}
	}
		 
	// Display the identify window if results were found
	if(numTabs > 0){
		map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
	}
} //end addToMapTideS

function addToMapInfo(idResults, evt) {
	// Seperate the identify results into layer based features arrays
	raws = {displayFieldName:null,features:[]};
	sgages = {displayFieldName:null,features:[]};
	flands = {displayFieldName:null,features:[]};
	
	for (var i=0, il=idResults.length; i<il; i++) {
		var idResult = idResults[i];
		if (idResult.layerName === "RAWS") {
			if (!raws.displayFieldName) {raws.displayFieldName = idResult.displayFieldName};
			raws.features.push(idResult.feature);  
		} else if (idResult.layerName === "Stream Flow Stations") {
			if (!sgages.displayFieldName) {sgages.displayFieldName = idResult.displayFieldName};
			sgages.features.push(idResult.feature);  
		} else if (idResult.layerName === "Federal Lands") {
			if (!flands.displayFieldName) {flands.displayFieldName = idResult.displayFieldName};
			flands.features.push(idResult.feature);  
		}
	} //end for
	//alert('sgages' + sgages.features.length + 'raws' + raws.features.length + 'flands' + flands.features.length);
		
	// Create the needed tabs and add the layer based feature array information
	if (idResults.length>0){
		if (raws.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'RAWS');
			dijit.byId(tabName).setContent(layerTabContent(raws,"RAWS")); 
			numTabs = numTabs+1; 
		}
		if (sgages.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Stream Gages');
			dijit.byId(tabName).setContent(layerTabContent(sgages,"Stream Gages")); 
			numTabs = numTabs+1; 
		}
		if (flands.features.length>0){
			tabName = 'Tab' + numTabs
			addTab(tabName, 'Federal Lands');
			dijit.byId(tabName).setContent(layerTabContent(flands,"Federal Lands")); 
			numTabs = numTabs+1; 
		}
	}
		 
	// Display the identify window if results were found
	if(numTabs > 0){
		map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
	}
} //end addToMapInfo

function layerTabContent(layerResults, layerName) {
    var content = "";
    switch (layerName) {
	case "Earthquakes":
    	if (layerResults.features.length>0) {
			content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Location</th><th class=\"info_h\">Mag.</th><th class=\"info_h\">Time</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
				content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['TITLE']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['MAGNITUDE']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['DATETIME']+"</td></tr>";
			}
		} 
		content+="</table>";
		break;
	case "Hurricanes":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Name</th><th class=\"info_h\">Movement</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
			    content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['NAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['MOVEMENT']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "U.S. Volcanoes":
		if (layerResults.features.length>0) {
			content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Name</th><th class=\"info_h\">Warning</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['NAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['WARNING']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Other Volcanoes":
		if (layerResults.features.length>0) {
			content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Event</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['DESCRIPTION']+"</a></td></tr>";
			}
		}
		content+="</table>";  
        break;	
	case "Wildfires":
		if (layerResults.features.length>0) {
       		content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Name</th><th class=\"info_h\">Acres</th><th class=\"info_h\">Report Date</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['HOTLINK']+"\" target=\"_blank\">"+layerResults.features[i].attributes['FIRE_NAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['ACRES']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['REPORT_DATE']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Wildfire Perimeters":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Name</th><th class=\"info_h\">Agency</th><th>Acres</th><th class=\"info_h\">Active</th><th class=\"info_h\">Report Date</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
				content+="<tr><td class=\"info_v\">"+layerResults.features[i].attributes['FIRE_NAME']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['AGENCY']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['ACRES']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['ACTIVE']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['DATE_']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
    case "Stream Floods":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Station Name</th><th class=\"info_h\">Stage</th><th class=\"info_h\">Class</th><th class=\"info_h\">Date</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['STANAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['STAGE']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['CLASS']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['TIME']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Weather":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Event</th><th class=\"info_h\">Effective</th><th class=\"info_h\">Expires</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['WEB']+"\" target=\"_blank\">"+layerResults.features[i].attributes['EVENT']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['EFFECTIVE']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['EXPIRES']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "RAWS":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Station Name</th><th class=\"info_h\">Agency</th><th class=\"info_h\">Status</th><th class=\"info_h\">Elevation</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		    	content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['HOTLINK']+"\" target=\"_blank\">"+layerResults.features[i].attributes['NAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['AGENCY']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['STATUS']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['ELEV']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Stream Gages":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Station Name</th><th class=\"info_h\">Stage</th><th class=\"info_h\">Class</th><th class=\"info_h\">Date</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['STANAME']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['STAGE']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['CLASS']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['TIME']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Tide Stations":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Station ID</th><th class=\"info_h\">Station Type</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\"><a href=\""+layerResults.features[i].attributes['URL']+"\" target=\"_blank\">"+layerResults.features[i].attributes['STATIONID']+"</a></td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['STATIONTYP']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	case "Federal Lands":
		if (layerResults.features.length>0) {
        	content = "<i>Total features returned: " + layerResults.features.length + "</i>";
			content += "<table border='1'><tr><th class=\"info_h\">Agency</th><th class=\"info_h\">Name</th></tr>";
			for (var i=0, il=layerResults.features.length; i<il; i++) {
		        content+="<tr><td class=\"info_v\">"+layerResults.features[i].attributes['FEATURE1']+"</td>";
				content+="<td class=\"info_v\">"+layerResults.features[i].attributes['NAME1']+"</td></tr>";
			}
		}
		content+="</table>";  
        break;
	}

    return content;
} //end layerTabContent
	  
function addTab(tabId, tabTitle) {
	var nt = new dijit.layout.ContentPane({id:tabId, title:tabTitle});
	var tabContainer = dijit.byId('tabs');
	tabContainer.addChild(nt);  
	//alert('tab added' + tabId + tabTitle);
} // end of addTab

function clearTab(tabId) {
	var tabContainer = dijit.byId('tabs');
	var dt = new dijit.byId(tabId);
	tabContainer.removeChild(dt); 
	dt.destroyRecursive(); 
	//alert('tab cleared' + tabId);
} //end clearTab
 
function ViewerHelp() {
	window.open("viewerhelp.shtml", "viewerhelp", "width=725,height=800,scrollbars=yes,resizable=yes"); 	  
} //end of ViewerHelp

function Nexrad_layer(new_state){
	if ( (nexradstate == "initial") && (new_state == "on") ) {  
		nexradMap = new my.nexradWMSLayer();
		map.addLayer(nexradMap);	
		nexradstate = "on";
	} else if ( (nexradstate == "off") && (new_state == "on") ) {
		nexradMap.show();
		nexradstate = "on";
	} else if ( (nexradstate == "on") && (new_state == "off") ) {
		nexradMap.hide();		
		nexradstate = "off";
	}
} //end Nexrad_layer

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
    return x1 + x2;
} //end addCommas

function onMapExtentChange(extent, delta, levelChange, lod){
	var level = map.getLevel();
	var scale = mapScales[level];
	var inputs;
	var content = "";

	dojo.byId('mapScale').innerHTML = 'Map Scale: 1 : '+addCommas(scale.toFixed(0));
		
	//if the map scale is greater then 20 million, make the scale dependant layers unavailable and turn them off if needed
	if (scale.toFixed(0) > 20000000) {
	    visibleInfo = [];
	    info.setVisibleLayers(visibleInfo);	
	    content="<input type=\"checkbox\" disabled class=\"info_layers\" id=\"Stream Gages\" onclick=\"updateLayerVisibility('info');\"/><label for=\"Stream Gages\"><span style=\"color:grey;\">Stream Gages</span></label><br>";
	    content+="<input type=\"checkbox\" disabled class=\"info_layers\" id=\"RAWS\" onclick=\"updateLayerVisibility('info');\"/><label for=\"RAWS\"><span style=\"color:grey;\">RAWS</span></label><br>";
	    content+="<input type=\"checkbox\" disabled class=\"info_layers\" id=\"Federal Lands\" onclick=\"updateLayerVisibility('info');\"/><label for=\"Federal Lands\"><span style=\"color:grey;\">Federal Lands</span></label><br>";
	} else {
	//otherwise, make the scale dependant layers available and keep their existing visibility and checkbox status	
		inputs = dojo.query(".info_layers");
		if (inputs[0].checked) {	
		    content="<input type=\"checkbox\" class=\"info_layers\" id=\"Stream Gages\" CHECKED onclick=\"updateLayerVisibility('info');\"/><label for=\"Stream Gages\"><span style=\"color:black;\">Stream Gages</span></label><br>";
		} else {
		    content="<input type=\"checkbox\" class=\"info_layers\" id=\"Stream Gages\" onclick=\"updateLayerVisibility('info');\"/><label for=\"Stream Gages\"><span style=\"color:black;\">Stream Gages</span></label><br>";
		}
		if (inputs[1].checked) {
		    content+="<input type=\"checkbox\" class=\"info_layers\" id=\"RAWS\" CHECKED onclick=\"updateLayerVisibility('info');\"/><label for=\"RAWS\"><span style=\"color:black;\">RAWS</span></label><br>";
		} else {
		    content+="<input type=\"checkbox\" class=\"info_layers\" id=\"RAWS\" onclick=\"updateLayerVisibility('info');\"/><label for=\"RAWS\"><span style=\"color:black;\">RAWS</span></label><br>";
		}
		if (inputs[2].checked) {
		    content+="<input type=\"checkbox\" class=\"info_layers\" id=\"Federal Lands\" CHECKED onclick=\"updateLayerVisibility('info');\"/><label for=\"Federal Lands\"><span style=\"color:black;\">Federal Lands</span></label><br>";
		} else {
		    content+="<input type=\"checkbox\" class=\"info_layers\" id=\"Federal Lands\" onclick=\"updateLayerVisibility('info');\"/><label for=\"Federal Lands\"><span style=\"color:black;\">Federal Lands</span></label><br>";
		}     
	}
	dojo.byId('us_other').innerHTML = content;
} //end onMapExtentChange

function startTimer() {
	TimerID = self.setTimeout("startTimer()",1000); 
	window.status="Hazards and Weather will automatically update in mins:secs: " + mins + ":" + secs;	
	if (mins == 0 && secs == 0) {  
		hazards.refresh();
		weat.refresh();
		mins=10;
		secs=0;
	}
	if (secs == 0 ) {
		mins--;
		secs=60;
	}
	 secs--;	
} //end startTimer		

function auto_refresh(auto_state) {
	if ( (auto_state == "on") && (timerSet == "off") ) {		  
		timerSet = "on";
		startTimer(); 
	} else if ( (auto_state == "off") && (timerSet == "on") ) {
		window.status="";	
		timerSet = "off";		  
		clearTimeout(TimerID);
		mins=10;
		secs=0;
	}
} //end auto_refresh

function callPrintForm() {
	t.updatePrint();
	dijit.byId('printMapForm').show();	
} //end of callPrintForm
		
function updatePrint() {
	printMap.updateExtent(map.extent);
}//end of updatePrint
