	  dojo.require("esri.map");
      dojo.require("esri.tasks.identify");
      dojo.require("dijit.form.Button");
      dojo.require("esri.dijit.Scalebar");

      var map, identifyParams, symbol, timer;
	  //var identifyTask2009, identifyTask2006, identifyTask1996, identifyTask1995, identifyTask1990, identifyTask1946, identifyTaskAll;
	  var identifyTask2010, identifyTask2000, identifyTask1990, identifyTaskPre1990, identifyTaskAll;
      var tiledGenericBase, tiledHybridBase, tiledHybridBaseOverlay;
      var tiledGenericBaseURL, tiledHybridBaseURL, tiledHybridBaseOverlayURL, tmslFloodPhoto2009URL, tmslFloodPhoto2006URL;
	  //var tmslFloodPhoto1996URL, tmslFloodPhoto1995URL, tmslFloodPhoto1990URL, tmslFloodPhoto1946URL, tmslFloodPhotoAllURL;	  
      //var tmslFloodPhoto2009, tmslFloodPhoto2006, tmslFloodPhoto1996, tmslFloodPhoto1995, tmslFloodPhoto1990, tmslFloodPhoto1946, tmslFloodPhotoAll;
	  var tmslFloodPhoto2010URL, tmslFloodPhoto2000URL, tmslFloodPhoto1990URL, tmslFloodPhotoPre1990URL, tmslFloodPhotoAllURL;	  
      var tmslFloodPhoto2010, tmslFloodPhoto2000, tmslFloodPhoto1990, tmslFloodPhotoPre1990, tmslFloodPhotoAll;
      var layer2results;
      var fc;
      var mapLoad;
	  var selectedPhotoSet = "All";
	  tiledGenericBaseURL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/BaseMaps/KingCo_GenericBase/MapServer";
	  tiledHybridBaseURL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/BaseMaps/KingCo_Aerial_2009/MapServer";
	  tiledHybridBaseOverlayURL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/BaseMaps/KingCo_Aerial_Overlay/MapServer";      
      
	  //tmslFloodPhoto2010URL = "http://gismaps.kingcounty.gov/ArcGIS/rest/services/WLRD/flood_photo_2010_decade/MapServer";
	  tmslFloodPhoto2000URL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_2000_decade/MapServer";
	  tmslFloodPhoto1990URL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_1990_decade/MapServer";
	  tmslFloodPhotoPre1990URL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_pre_1990_decade/MapServer";
	  tmslFloodPhotoAllURL = "http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo/MapServer";
	  	        
      var initialPhotoSet = "";


        var isIE6 = false;
        var is7up = false;
        if (dojo.isIE==6) {
          isIE6 = true;
          //dojo.byId("btnHybridBase").style.display = 'none';
        }

      
     // mapLoad = dojo.connect(map, "onLoad", init);

      function init() {
      
        var basemap = getURLParam('basemap');
		initialPhotoSet = getURLParam('photoset');

      // check for extents passed through the URL
        var xmin = (parseFloat(getURLParam('xmin')));
        var ymin = (parseFloat(getURLParam('ymin')));
        var xmax = (parseFloat(getURLParam('xmax')));
        var ymax = (parseFloat(getURLParam('ymax')));

        if ((isNaN(xmin) == false) && (isNaN(ymin) == false) && (isNaN(xmax) == false) && (isNaN(ymax) == false)) {
            var startExtent = new esri.geometry.Extent(xmin, ymin, xmax, ymax, new esri.SpatialReference({ wkid: 102100 }));
        } else {
            // if no extents were passed in the URL, then use the full county extent
            var startExtent = new esri.geometry.Extent(-13659182.299015194, 5979420.302405863, -13468395.476415321, 6071144.73634811, new esri.SpatialReference({ wkid: 102100 }));
        }

 
        map = new esri.Map("map", {extent:startExtent,logo:false});
         // NOTE:  Seems that if you connect to the onLoad AFTER you add map layers, it won't fire the map.onLoad even
         // in IE after you leave and return via the back button.
        maponload_handler = dojo.connect(map, "onLoad", initFunctionality);
         
        //set up and add the map services. ID's match the button names for base maps
        tiledGenericBase = new esri.layers.ArcGISTiledMapServiceLayer(tiledGenericBaseURL, {id:"Map"} );
        map.addLayer(tiledGenericBase);
        
        tiledHybridBase = new esri.layers.ArcGISTiledMapServiceLayer(tiledHybridBaseURL, {id:"Aerial"});
        map.addLayer(tiledHybridBase);
        
        tiledHybridBaseOverlay = new esri.layers.ArcGISTiledMapServiceLayer(tiledHybridBaseOverlayURL, {id:"Hybrid"});
        tiledHybridBaseOverlay.hide();
        map.addLayer(tiledHybridBaseOverlay); 
        
        //add scalebar	
		  var scalebar = new esri.dijit.Scalebar({
            map: map,
            scalebarUnit:'english'
          });
		                        
//        //=============

        //tmslFloodPhotoAll = new esri.layers.ArcGISTiledMapServiceLayer("http://kcgis-ags10/ArcGIS/rest/services/kang/flood_photo_All/MapServer", "tmslFloodPhotoAll");
        tmslFloodPhotoAll = new esri.layers.ArcGISDynamicMapServiceLayer(tmslFloodPhotoAllURL, {id:"PhotoAll"});
        map.addLayer(tmslFloodPhotoAll);
		
      	//tmslFloodPhoto2010 = new esri.layers.ArcGISTiledMapServiceLayer(tmslFloodPhoto2010URL, {id:"Photo2010"});
        //map.addLayer(tmslFloodPhoto2010);
		//tmslFloodPhoto2010.hide();
		
        tmslFloodPhoto2000 = new esri.layers.ArcGISTiledMapServiceLayer(tmslFloodPhoto2000URL, {id:"Photo2000"});
        map.addLayer(tmslFloodPhoto2000);
		//tmslFloodPhoto2000.hide();
		
        tmslFloodPhoto1990 = new esri.layers.ArcGISTiledMapServiceLayer(tmslFloodPhoto1990URL, {id:"Photo1990"});
        map.addLayer(tmslFloodPhoto1990);
		//tmslFloodPhoto1990.hide();
		
        tmslFloodPhotoPre1990 = new esri.layers.ArcGISTiledMapServiceLayer(tmslFloodPhotoPre1990URL, {id:"PhotoPre1990"});
        map.addLayer(tmslFloodPhotoPre1990);
		//tmslFloodPhotoPre1990.hide();
		
			
        
                     
        //honor URL parameters if present, else go to default
        if (basemap !== "") {
            changeBaseMap(basemap);
        }else{    
            changeBaseMap(tiledGenericBase);
        }
        if (initialPhotoSet == "2000") {
			changePhotoSet("tmslFloodPhoto2000");
			//alert("initialPhotoSet: 2000");
		}else if (initialPhotoSet == "1990") {
				changePhotoSet("tmslFloodPhoto1990");
		}else if (initialPhotoSet == "Pre1990") {
				changePhotoSet("tmslFloodPhotoPre1990");
		}else if (initialPhotoSet == "All") {
				changePhotoSet("tmslFloodPhotoAll");
		//}else if (initialPhotoSet == "2010") {
		//		changePhotoSet("tmslFloodPhoto2010");
		//}else{
			//changeBaseMap("tiledNone");
			//changePhotoSet("tiledNone");
			//alert("initialPhotoSet: None");
		} 		
       //console.log("initialPhotoSet:" +initialPhotoSet); 		


      }

      function initFunctionality(map) {
	  		initIdentify();
     }

        function initIdentify() {

            var maponClick_handler = dojo.connect(map, "onClick", doIdentify);
						
			//identifyTask2010 = new esri.tasks.IdentifyTask("http://gismaps.kingcounty.gov/ArcGIS/rest/services/WLRD/flood_photo_2010_decade/MapServer");
            identifyTask2000 = new esri.tasks.IdentifyTask("http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_2000_decade/MapServer");
            identifyTask1990 = new esri.tasks.IdentifyTask("http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_1990_decade/MapServer");
            identifyTaskPre1990 = new esri.tasks.IdentifyTask("http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo_pre_1990_decade/MapServer");
            identifyTaskAll = new esri.tasks.IdentifyTask("http://gismaps.kingcounty.gov/ArcGIS10/rest/services/WLRD/flood_photo/MapServer");					

            identifyParams = new esri.tasks.IdentifyParameters();
            identifyParams.tolerance = 3;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = [0];
            identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

            map.infoWindow.resize(275, 280);
            symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 7, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));
      }
    
    

      function doIdentify(evt) {
        //console.log("clicked:  "+selectedPhotoSet);
        map.infoWindow.hide();
        map.graphics.clear();
        identifyParams.geometry = evt.mapPoint;
        identifyParams.mapExtent = map.extent;
        
		
		if (selectedPhotoSet == "2000"){
			map.infoWindow.setTitle("2000-2009 Flood Photos");
			identifyTask2000.execute(identifyParams, function(idResults){
				addToMap(idResults, evt);
			});	
		}else if (selectedPhotoSet == "1990"){
			map.infoWindow.setTitle("1990-1999 Flood Photos");
			identifyTask1990.execute(identifyParams, function(idResults){
				addToMap(idResults, evt);
			});	
		}else if (selectedPhotoSet == "Pre1990"){
			map.infoWindow.setTitle("Pre-1990 Flood Photos");
			identifyTaskPre1990.execute(identifyParams, function(idResults){
				addToMap(idResults, evt);
			});	
		/*
		}else if (selectedPhotoSet == "2010"){
			map.infoWindow.setTitle("Post 2010 Flood Photos");
			identifyTask2010.execute(identifyParams, function(idResults){
				addToMap(idResults, evt);
			});		
*/
		}else if (selectedPhotoSet == "All"){
			map.infoWindow.setTitle("All Flood photos");
			identifyTaskAll.execute(identifyParams, function(idResults){
				addToMap(idResults, evt);
			});			
		}
		
		
    
	
	
	  }

      function addToMap(idResults, evt) {
//console.log("beginning addToMap");	  	
        layer2results = {displayFieldName:null,features:[]};
//console.log(idResults);

        for (var i=0, il=idResults.length; i<il; i++) {
          var idResult = idResults[i];
          if (idResult.layerId === 0) {
            if (!layer2results.displayFieldName) {layer2results.displayFieldName = idResult.displayFieldName};
            layer2results.features.push(idResult.feature);
          }
        }
        map.infoWindow.setContent(layerTabContent(layer2results,"layer2results"));
 			//console.log("fc=" + fc);
        if (fc > 0) {
            map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
        }        
      }

      function layerTabContent(layerResults, layerName) {
        var content = "";
//            console.log(layerName);
//            content = "<i>Total features/photos returned: " + layerResults.features.length + "</i>";
//            fc = layerResults.features.length;
//            content += "<table border='1'><tr><th>River</th><th>Photo</th></tr>";
//            for (var i=0, il=layerResults.features.length; i<il; i++) {
//             var fp = layerResults.features[i].attributes['URL_LINK'];
//             content+="<tr><td width='50'><a href=javascript:showPhoto('" + fp + ".jpg')> large photo</a> or <a href='#' onclick='showFeature(" + layerName + ".features[" + i + "]); return false;'>show feature</a></td>";
//             content+="<td>"+" <img src='http://your.kingcounty.gov/dnrp/library/water-and-land/flooding/photos/"+layerResults.features[i].attributes['URL_LINK']+".jpg' height='200px' width='250px' alt='Flood Photo' /></td>";
//            }
//            content+="</tr></table>";
            
            fc = layerResults.features.length;
            content += "<div class='photoWrapper'>"; 
            for (var i=0, il=layerResults.features.length; i<il; i++) {
             var fp = layerResults.features[i].attributes['URL_LINK'];
             
             var d = new Date(layerResults.features[i].attributes['PHOTO_DATE']);
             var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
             var dt;

             dt = (monthname[d.getMonth()] + " ");
             dt = dt + (d.getDate() + ", ");
             dt = dt + (d.getFullYear());
                       
			 content+="<div class='titleLeftText'>"+layerResults.features[i].attributes['WTRBDYNAME']+ ":&nbsp;<br/>";
             //content+=layerResults.features[i].attributes['PHOTO_DATE']+"</div>";
             content+= dt +"</div>";
			 content+="<div class='titleRightText'> <a href=javascript:showPhoto('" + fp + ".jpg')>enlarge</a></div>";
            
			 
			 
			 var wh_river_photos = layerResults.features[i].attributes['FOLDERNAME'];
			 //add photo credit to white river 1/10/2009 photos
			 if (wh_river_photos == "DVD9") {
			    content+="<div class='thumbnailPhoto2'> <img onClick=showPhoto('" + fp + ".jpg') title= 'Click photo to see larger version'  src='http://your.kingcounty.gov/dnrp/library/water-and-land/flooding/photos/"+layerResults.features[i].attributes['URL_LINK']+".jpg' height='200px' width='250px' alt='Flood Photo' /></div>";
                content+="<div class='photoCourtesyText'>Photo courtesy of U.S. Army Corps of Engineers<br/>";
                map.infoWindow.resize(275, 295);  //resize length to show photo credit
             }else{
                content+="<div class='thumbnailPhoto'> <img onClick=showPhoto('" + fp + ".jpg') title= 'Click photo to see larger version'  src='http://your.kingcounty.gov/dnrp/library/water-and-land/flooding/photos/"+layerResults.features[i].attributes['URL_LINK']+".jpg' height='200px' width='250px' alt='Flood Photo' /></div>";    
                map.infoWindow.resize(275, 280);
             }
			 
			 content+="</div>";

            }

        return content;
      }
      
      function showFeature(feature) {
        map.graphics.clear();
        feature.setSymbol(symbol);
        map.graphics.add(feature);
      }

      function showPhoto(photo){
		newWindow = window.open('http://your.kingcounty.gov/dnrp/library/water-and-land/flooding/photos/' + photo, 'photo', 'status=no,location=no,scrollbars=no,width=625,height=500,resizable=no,top=10,left=70');
	    newWindow.focus();
      }
      
      function formatDate(sdate){
        var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
             var dt;

             dt = (monthname[d.getMonth()] + " ");
             dt = dt + (d.getDate() + ", ");
             dt = dt + (d.getFullYear());
             //alert(dt);
      }
      
      function initLayer(url, id) {
        var layer = new esri.layers.ArcGISTiledMapServiceLayer(url, {id:id});
        identifyTaskLayer = dojo.connect(layer, "onLoad", function() {
          map.addLayer(layer);
          layer.hide();
		  //console.log("Loaded: " + layer.id);
        });
        return layer;
      }

	function changePhotoSet(photoSetName){
	  	map.infoWindow.hide();
        switch (photoSetName) {
			case "tmslFloodPhoto2000":
			case "Photo2000":
			case "photo2000":
				
				SwitchLayers(tmslFloodPhoto2000);

				//dojo.byId("btn2000Photo").checked = true; //if using radio button
				//need to set the selectedIndex value if photoset passed in the url
				dojo.byId("op2000").selected = true;
				//document.getElementById("op2000").selected = true;
				selectedPhotoSet = "2000";
				//console.log(tmslFloodPhoto2000);
				//alert("changePhotoSet: 2000");
				break;
			case "tmslFloodPhoto1990":
			case "Photo1990":
			case "photo1990":
				
				SwitchLayers(tmslFloodPhoto1990);

				//dojo.byId("btn1990Photo").checked = true; //if using radio button
				document.getElementById("op1990").selected = true;
				selectedPhotoSet = "1990";
				//console.log("tmslFloodPhoto1990"); 
				//alert("changePhotoSet: 1990");
				break;
			case "tmslFloodPhotoPre1990":
			case "PhotoPre1990":
			case "photoPre1990":
				//alert("Pre1990 photo");
				
				SwitchLayers(tmslFloodPhotoPre1990);

				document.getElementById("opPre1990").selected = true;
				selectedPhotoSet = "Pre1990";
				break;
			/*
			case "tmslFloodPhoto2010":
			case "Photo2010":
			case "photo2010":
				
				SwitchLayers(tmslFloodPhoto2010);
				
				document.getElementById("op2010").selected = true;
				selectedPhotoSet = "2010";
				break;
*/
			case "tmslFloodPhotoAll":
			case "PhotoAll":
			case "photoAll":
				
				//SwitchLayers(tmslFloodPhotoAll);
				//tmslFloodPhoto2010.show();
				tmslFloodPhoto2000.show();
				tmslFloodPhoto1990.show();
				tmslFloodPhotoPre1990.show();
				tmslFloodPhotoAll.show();
				
				document.getElementById("opAll").selected = true;
				selectedPhotoSet = "All";
				break;
  		}
		
	
}

      function changeBaseMap(baselayer){
	  	map.infoWindow.hide();
        switch(baselayer){
            case tiledGenericBase: case "Map": case "map": default:
				//alert('Base');
				tiledHybridBase.hide();
				tiledHybridBaseOverlay.hide();
				tiledGenericBase.show();
				setActiveButton("btnGenericBase");
				
				/*
				if (initialPhotoSet == "2010") {
					tmslFloodPhoto2010.show();
				}
*/
				if (initialPhotoSet == "2000") {
					tmslFloodPhoto2000.show();
				}
				if (initialPhotoSet == "1990") {
					tmslFloodPhoto1990.show();
				}
				if (initialPhotoSet == "Pre1990") {
					tmslFloodPhotoPre1990.show();
				}
				if (initialPhotoSet == "All") {
					tmslFloodPhotoAll.show();
				}
	            
                break;
            case tiledHybridBase: case "Aerial": case "aerial":
                tiledHybridBase.show();
                tiledHybridBaseOverlay.hide();
                tiledGenericBase.hide();
                setActiveButton("btnAerial");
                break; 
            case tiledHybridBaseOverlay: case "Hybrid": case "hybrid":
                if (isIE6) {
                    tiledHybridBase.show();
                    tiledGenericBase.hide();
					tiledHybridBaseOverlay.hide();
                    setActiveButton("btnAerial"); //change to aerial                   
                }else{
                    tiledHybridBase.show();
					tiledHybridBaseOverlay.show();
                    tiledGenericBase.hide();					
                    setActiveButton("btnHybridBase");
                }            
                break;    				


        }    
    }
    
	
	
    function setActiveButton(buttonName){
        // set up an array of your base map button IDs.
        if (isIE6) {
              var btnArray = ["btnGenericBase","btnAerial"];
        }else{
            var btnArray = ["btnGenericBase","btnAerial","btnHybridBase"];
        }        
        dojo.forEach(btnArray, function(buttonName){dojo.removeClass(buttonName,"baseMapButtonActive")});
        dojo.addClass(buttonName,"baseMapButtonActive");
        map.infoWindow.hide(); //to avoid unnecessary popping up
    }

    //function to get parameters passed in the URL
    function getURLParam( name ) {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }
    
    function createURLForCurrentExtent() {
        var baseURL= document.location.host + document.location.pathname;
        var params = "?xmin=" + map.extent.xmin + "&ymin=" + map.extent.ymin + "&xmax=" + map.extent.xmax + "&ymax=" + map.extent.ymax;
        if (tiledGenericBase.visible===true){
            params += "&basemap=Map"
        }else if (tiledHybridBaseOverlay.visible===true){
            params += "&basemap=Hybrid"
        }else if (tiledHybridBase.visible===true){
            params += "&basemap=Aerial"        
        }
		 params += "&photoset=" + selectedPhotoSet;        
        //return extentURL;
        var extentURL = "http://" + baseURL + params;
        dojo.byId("txtLink").value = extentURL;
        dojo.byId("linkDiv").style.display = "block";
        return extentURL;
    }

    function toggle(id) {
		var state = dojo.byId(id).style.display;
			if (state == 'block') {
				dojo.byId(id).style.display = 'none';
				dojo.byId('btnLink').value = 'Create URL';
			} else {
				dojo.byId(id).style.display = 'block';
				dojo.byId('btnLink').value = 'Hide URL';
			}
	}
function closeLinkDiv() {
    dojo.byId("linkDiv").style.display = "none";
}

function SelectAll(id){
    dojo.byId(id).focus();
    dojo.byId(id).select();
}
         windowResize_handler = dojo.connect(window, "onresize", function() {
            clearTimeout(timer);
            timer = setTimeout(function() { map.resize(); map.reposition(); }, 500);}); 

      dojo.addOnLoad(init);
	  
function SwitchLayers(photoid){	
	HideAllLayers();
	ShowLayer(photoid);
}

function HideAllLayers(){
	//tmslFloodPhoto2010.hide();
	tmslFloodPhoto2000.hide();
	tmslFloodPhoto1990.hide();
	tmslFloodPhotoPre1990.hide();
	tmslFloodPhotoAll.hide();
}

function ShowLayer(photoid){
	photoid.show();
}

