﻿//**Adding Reference classes**//
dojo.require("esri.map");
dojo.require("esri.virtualearth.VEGeocoder");
dojo.require("esri.virtualearth.VETiledLayer");

dojo.require("dijit.form.Button");
dojo.require("dojo.parser");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("esri.dijit.Scalebar");
dojo.require("dojo.fx");
dojo.require("esri.layers.graphics");
dojo.require("esri.dijit.InfoWindowLite");

//**declare global variables
var map, navToolbar;
var veTiledLayer;
var timer, mapClick, elevation, BWS, tbl, AdaptedFloodZone = "NA";
var panel, floodZone, pmr_floodZone_FS;//featuresets for Panel ID, DFIRM FloodZone and PMR DFIRM Floodzone
var currentParish;//maintain values for current parish
var queryTaskUrl = "", PnlQueryTaskUrl = "", pmrQueryTaskUrl = "";
var loading;  //loading image. id
var layersLoaded; //variable to keep track of loaded layers
var BingMapsKey = 'AlduteqaR5NwBdOKa-xGt4mB-vQHrA7amfIi2qBDH154Km_k86Ot-6bOIfR3oXrR';
var currentBaseMapView = "streetsLayer";
var infoTemplate = new esri.InfoTemplate("Location Results: ", "Test");

dojo.addOnLoad(init); //acts as body onload event

function init() {
    /*******************************************
    * Patch for browser having scroll bar refresh problem
    * - call map.reposition() after map load
    * WARNING: this patch will NOT work beyond
    * version 1.4 of the ArcGIS JS API. 
    *******************************************/
    esri.Map.prototype.reposition = function() {
        var pos = dojo.coords(this.container, true),
              brdr = dojo._getBorderExtents(this.container);
        this.position.setX(pos.x + brdr.l);
        this.position.setY(pos.y + brdr.t);
        this.onReposition(this.position.x, this.position.y);
    };
    /***** END OF PATCH *****/
    
    //editing default configurations
    esri.config.defaults.map.slider = { left: "30px", top: "80px", width: null, height: "200px" };
    esri.config.defaults.map.sliderLabel = { tick: 5, labels: null, style: "width:2em; font-family:Verdana; font-size:75%;" };
    esri.config.defaults.map.panDuration = 1000; //The length of time in milliseconds that the map will take to pan from one extent to another. Default is 250
    esri.config.defaults.map.panRate = 50; //The length of time in milliseconds that the map will refresh as it pans to the next extent. Default is 25
    esri.config.defaults.map.zoomDuration = 500; //time in milliseconds; default is 250
    esri.config.defaults.map.zoomRate = 50; //refresh rate of zoom animation; default is 25

    //create the initial extent of louisiana as the maximum view when loading the base map
    //var startExtent = new esri.geometry.Extent({ xmin: -94.647329960938, ymin: 28.1275820820308, xmax: -88.154410039062, ymax: 33.7470889179692, spatialReference: new esri.SpatialReference({ wkid: 4269 }) });
    var startExtent = new esri.geometry.Extent({ "xmin": -10598845.56132645, "ymin": 3257577.620960132, "xmax": -9737858.874722457, "ymax": 3974251.198161751, "spatialReference": { "wkid": 102100} });
   
    //establish the levels of display so that user can't zoom in past lowest scale
    var lods = [    
      //{ "level": 0, "resolution": 156543.033928, "scale": 591657527.591555 },
      //{ "level": 1, "resolution": 78271.5169639999, "scale": 295828763.795777 },
      //{ "level": 2, "resolution": 39135.7584820001, "scale": 147914381.897889 },
      //{ "level": 3, "resolution": 19567.8792409999, "scale": 73957190.948944 },
      //{ "level": 4, "resolution": 9783.93962049996, "scale": 36978595.474472 },
      //{ "level": 5, "resolution": 4891.96981024998, "scale": 18489297.737236 },
      //{ "level": 6, "resolution": 2445.98490512499, "scale": 9244648.868618 },
      { "level": 7, "resolution": 1222.99245256249, "scale": 4622324.434309 },
      { "level": 8, "resolution": 611.49622628138, "scale": 2311162.217155 },
      { "level": 9, "resolution": 305.748113140558, "scale": 1155581.108577 },
      { "level": 10, "resolution": 152.874056570411, "scale": 577790.554289 },
      { "level": 11, "resolution": 76.4370282850732, "scale": 288895.277144 },
      { "level": 12, "resolution": 38.2185141425366, "scale": 144447.638572 },
      { "level": 13, "resolution": 19.1092570712683, "scale": 72223.819286 },
      { "level": 14, "resolution": 9.55462853563415, "scale": 36111.909643 },
      { "level": 15, "resolution": 4.77731426794937, "scale": 18055.954822 },
      { "level": 16, "resolution": 2.38865713397468, "scale": 9027.977411 },
      { "level": 17, "resolution": 1.19432856685505, "scale": 4513.988705 },
      { "level": 18, "resolution": 0.597164283559817, "scale": 2256.994353 }
      //,{ "level": 19, "resolution": 0.298582141647617, "scale": 1128.497176 }
    ];

    map = new esri.Map("mapDiv", { extent: startExtent, lods: lods });
    
    //setup infoTemplate. Do not use functions to fill title and content
    //infoTemplate = new esri.InfoTemplate("Location Results: ", "Test");
    
    //setup navigation toolbar
    navToolbar = new esri.toolbars.Navigation(map);

    loading = dojo.byId("loadingImg");
    layersLoaded = 0;
    dojo.byId("toolsDiv").style.visibility = "visible"; //show the tools div once dojo javascript is unloaded

    //Creates the Virtual Earth layer to add to the map
    veTiledLayer = new esri.virtualearth.VETiledLayer({
        bingMapsKey: BingMapsKey,
        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_ROAD
    });
    //Add layer to map
    map.addLayer(veTiledLayer, { id: "bingMapLayer" });

    dojo.connect(veTiledLayer, "onUpdateEnd", hideLoading);

    //resize the map when the browser resizes - view the 'Resizing and repositioning the map' section in
    //the following help topic for more details http://help.esri.com/EN/webapi/javascript/arcgis/help/jshelp_start.htm#jshelp/inside_guidelines.htm
    var resizeTimer;
    dojo.connect(map, 'onLoad', function(theMap) {
        var scalebar = new esri.dijit.Scalebar({
            attachTo: 'top-right',
            map: map,
            scalebarUnit: 'english'
        },
            dojo.byId("scalebar")
        );
        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);
        });
        dojo.connect(map.graphics, "onClick", displayInfoWindow);
    });
    
    //on resize of window mouse point reference is aligned with map point. use below code to resolve the issue.
    dojo.connect(window, "onresize", function() {
        if (typeof map == 'undefined') {
            return;
        }
        clearTimeout(timer);
        timer = setTimeout(function() { map.resize(); map.reposition(); }, 500);
    });

    dojo.connect(map, "onZoomStart", showLoading);
    dojo.connect(map, "onPanStart", showLoading);
    dojo.connect(map, "onUpdateStart", showLoading);
    dojo.connect(map, "onUpdateEnd", hideLoading);
    
    //When user enters a search address for the first time, clear the text
    dojo.connect(dojo.byId("txtAddress"), "onclick", function() {
        if (dojo.byId("txtAddress").value == "Enter your address here") {
            dojo.byId("txtAddress").value = "";
        }
    });

    //if url has any FIPS parameter with valid value then Zoom to the corresponding parish and add layers and set attributes
    var parameterFIPSValue = getParameter("FIPS");
    if (parameterFIPSValue != "") {
        //get parish extension and Zoom in the map to extent
        zoomInMapToParish(parameterFIPSValue);
    }

    var selectedIndex = 0;

    //add parishes from the Parishes JSON array object to drop down
    for (var i = 0; i < parishLayersDetails.Parishes.length; i++) {
        var y = document.createElement('option');
        y.text = parishLayersDetails.Parishes[i].name;
        y.value = parishLayersDetails.Parishes[i].FIPS;
        if (parseInt(parameterFIPSValue) === parishLayersDetails.Parishes[i].FIPS) { selectedIndex = i + 1; }
        var x = dojo.byId("parishes");
        try {
            x.add(y, null); // standards compliant
        }
        catch (ex) {
            x.add(y); // IE only
        }
    }
    dojo.byId("parishes").selectedIndex = selectedIndex;


    //when user clicks on map get the values of floodZone, Elevation and wind speed at the map point click.
    dojo.connect(map, "onClick", doQuery);


}

//to change the base map layers
function toggleBaseLayers(value) {

    switch (value) {
        case "streetLayer":
            veTiledLayer.setMapStyle(esri.virtualearth.VETiledLayer.MAP_STYLE_ROAD);
            currentBaseMapView = "streetsLayer";
            break;
        case "aerialLayer":
            veTiledLayer.setMapStyle(esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL);
            currentBaseMapView = "aerialLayer";
            break;
        case "hybridLayer":
            veTiledLayer.setMapStyle(esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL_WITH_LABELS);
            currentBaseMapView = "hybridLayer";            
            break;
    }
}

//to locate the address on map
function locateAddress() {
    if (dojo.byId("txtAddress").value == "Enter your address here" || dojo.byId("txtAddress").value == "") {
        wipeIn("locationResult");
        dojo.byId("locationResult").innerHTML = "Location not found. <br/> Please enter a valid address. <br/>"
                                                + "<div style='width:100%' align='center'><input type='button' value='Ok' class='buttonsText'  onclick=\"wipeOut('locationResult');\" /></div>";
    } else {
        try {
            //find the x, y for the address location using virtul earth objects.
            
           var veGeocoder = new esri.virtualearth.VEGeocoder({ bingMapsKey: BingMapsKey });
            map.graphics.clear();

            veGeocoder.addressToLocations(dojo.byId("txtAddress").value, mapIt);

        } catch (Error) {
            alert(Error);
        }
    }
}

//Function Name: mapIt
//Author: Henry Capello (modified original code by Neel Mallepally)
//Date: 3/23/2011
//Purpose: takes virtual earth geocode result, refines the top answers then sends the coordinates to the query to be processed for BWS, Floodzone and Elevation

function mapIt(places) {
    try {
        
        if (places != null) {
            if (places.length > 1) {
            
                var results = "<b>Did you mean:</b><br/>";
                for (var x = 0; x < places.length; x++) {
                    var pointMeters = esri.geometry.geographicToWebMercator(places[x].location);
                    results += "<span style=\" text-decoration: underline;color:'blue' \" onmouseover=\"this.style.color='red';this.style.cursor='pointer';\" onmouseout=\"this.style.color='blue';\" onclick='showPoint(" + pointMeters.x + "," + pointMeters.y + "," + dojo.toJson(places[x].bestView.toJson()) + ");wipeOut(\"locationResult\")';>" + places[x].address.formattedAddress + "</span><br/>";
                }
                results += "<div ><input type='button' class='buttonsText' value='Cancel' onclick=\"wipeOut('locationResult');\"/></div>";
                wipeIn("locationResult");
                dojo.byId("locationResult").innerHTML = results;
            }
            else {
                var pointMeters = esri.geometry.geographicToWebMercator(places[0].location);
                
                showPoint(pointMeters.x, pointMeters.y, places[0].bestView.toJson());
            }
        } else {
            wipeIn("locationResult");
        }
    }
    catch (Error) {
        alert(Error.message);
    }
}

//Function Name: showPoint
//Author: Henry Capello (modified original code by Neel Mallepally)
//Date: 3/23/2011
//Purpose: runs numerous functions to gather information then places point on map with reference to data
function showPoint(xCoor,yCoord,bestView) {
    try {
        var location = new esri.geometry.Point(parseFloat(xCoor), parseFloat(yCoord), new esri.SpatialReference(map.spatialReference));
        var bestExtent = new esri.geometry.Extent(bestView);
        
        var evt = { mapPoint: location };

        map.setExtent(esri.geometry.geographicToWebMercator(bestExtent));
        doQuery(evt);
        points = null;
    }
    catch (Error) {
        alert(Error.message);
    }
}

function wipeIn(thisDiv) {
    var wipeIn = dojo.fx.wipeIn({ node: thisDiv, duration: 1000 });
    var slideRight = dojo.fx.slideTo({ node: thisDiv, duration: 1000, left: 250, top: 4 });
    dojo.fx.combine([wipeIn, slideRight]).play();
}

function wipeOut(thisDiv) {
    var wipeOut = dojo.fx.wipeOut({ node: thisDiv, duration: 1000 });
    var slideLeft = dojo.fx.slideTo({ node: thisDiv, duration: 1000, left: 250, top: 0 });
    dojo.fx.combine([slideLeft, wipeOut]).play();
}

function zoomInMapToParish(FIPSValue) {

    try {

        //remove any flood layers exist before zooming in the map to a parish
        removeFloodLayers();
        dojo.byId("lblCoastalParishNote").innerHTML = "";
        if (typeof map.graphics != 'undefined' && map.graphics != null) {
            map.graphics.clear();
            dojo.byId("dataPoints").innerHTML = "";
        }
        if (FIPSValue != 0) {
            //loop through parishes JSON object get attributes values of the corresponding parish
            var i = 0;
            while (FIPSValue != parishLayersDetails.Parishes[i].FIPS) {
                i++;
            }
            var parish = parishLayersDetails.Parishes[i];
            dojo.byId("currentParish").innerHTML = parish.name + " Interactive Flood Mapping Site";
            var parishExtent = new esri.geometry.Extent({ xmin: parish.extension.xmin, ymin: parish.extension.ymin, xmax: parish.extension.xmax, ymax: parish.extension.ymax, spatialReference: { "wkid": 4269} });
            map.setExtent(esri.geometry.geographicToWebMercator(parishExtent));
            
            
            if (typeof parish.queryTaskLayer != 'undefined') { queryTaskUrl = parish.queryTaskLayer; }
            if (typeof parish.FIRMPanelLayer != 'undefined') { PnlQueryTaskUrl = parish.FIRMPanelLayer; }
            if (typeof parish.pmrQueryTaskLayer != 'undefined') { pmrQueryTaskUrl = parish.pmrQueryTaskLayer; }
            
            if (parish.FIRM.exist === "true") {
                addFloodLayer(parish.FIRM.layerType, parish.FIRM.url, "effFirmLayer");
                dojo.byId("firmDIV").style.display = "block"; //display that Scanned map available
                dojo.byId("legendBtn").style.display = "block"; //if Scanned map available a link to display its legend has to be made visible
                //If there is no DFIRM or PMR, then this will be the only layer, so turn it on
                if (parish.DFIRM.exist === "true") {
                    map.getLayer("effFirmLayer").hide(); //Turn off Layer, by default it is visible
                }
                else {
                    dijit.byId("cbFIRM").setChecked(true);
                }
                
                //dijit.byId("cbFIRM").set('checked', false);
                if (parish.DFIRM.exist === "false") {
                    dojo.byId("msgDiv1").style.display = "block";
                } else {
                    dojo.byId("msgDiv1").style.display = "none";
                }

            } else {
                dojo.byId("firmDIV").style.display = "none";
                dojo.byId("legendBtn").style.display = "none";
            }
            
            // If there is a Preliminary or Effective DFIRM, turn this layer on, and enable the legends and other information
            if (parish.DFIRM.exist === "true") {
                addFloodLayer(parish.DFIRM.layerType, parish.DFIRM.url, "pfirmLayer");
                //This layer is turned on if no Partial Map Revision exists
                //Also note that there is no PMR unless there is an existing DFIRM
                if (typeof parish.PDFIRM != 'undefined' && parish.PDFIRM.exist === "true") {
                    dijit.byId("cbDFIRM").setChecked(false); //by default this layer is turned on, but I will not turn it on if there is a preliminary in effect
                    map.getLayer("pfirmLayer").hide(); //This layer is hidden if there is a PMR, by default it is visible
                }
                else {
                    dijit.byId("cbDFIRM").setChecked(true); //by default this layer is  turned on
                    
                }
                
                dojo.byId("dfirmDIV").style.display = "block";
                dojo.byId("legendTD").style.height = "200px"; //if DFIRM avaialble, show the Legend
                //the JSON file (ParishFloodLayers) will have an effective DFIRM Date. If this date exists, then it is either Future (Adopted) or Effective
                if (parish.DFIRM.EffectiveDate != undefined && parish.DFIRM.EffectiveDate != "" && parish.DFIRM.EffectiveDate != "Preliminary") {
                    //The DFIRM Effective date is adopted (Future) 6 months before it is effective, so if today's date is earlier than the effective date,
                    // then it is only adopted.
                    if (new Date() < new Date(parish.DFIRM.EffectiveDate)) {
                        dojo.byId("lblDFIRM").innerHTML = "Future DFIRM";
                        dojo.byId("lblScannedFIRM").innerHTML = "Effective FIRM";
                    } else {
                        dojo.byId("lblDFIRM").innerHTML = "Effective DFIRM";
                        dojo.byId("lblScannedFIRM").innerHTML = "Historical FIRM";
                    }
                } else {
                    dojo.byId("lblDFIRM").innerHTML = "Preliminary DFIRM";
                    dojo.byId("lblScannedFIRM").innerHTML = "Effective FIRM";
                }

            }
            else {
                dojo.byId("dfirmDIV").style.display = "none";
                dojo.byId("legendTD").style.height = "0px"; //hide the DFIRM legend
                dojo.byId("lblScannedFIRM").innerHTML = "Effective FIRM";
            }
            // if a parish partial DFIRM / Partial Map Revision, this layer goes on top
            if (typeof parish.PDFIRM != 'undefined' && parish.PDFIRM.exist === "true") {
                addFloodLayer(parish.PDFIRM.layerType, parish.PDFIRM.url, "pdfirmLayer");
                dojo.byId("pdfirmDIV").style.display = "block"; //display that ABFE layer available.
                dijit.byId("cbPDFIRM").setChecked(true);
            }
            else {
                dojo.byId("pdfirmDIV").style.display = "none";
            }
            if (parish.ABFE.exist === "true") {
                addFloodLayer(parish.ABFE.layerType, parish.ABFE.url, "abfeLayer");
                dojo.byId("abfeDIV").style.display = "block"; //display that ABFE layer available.
                map.getLayer("abfeLayer").hide(); //by default this layer is visible, hide it 
                dijit.byId("cbABFE").set('checked', false);
            }
            else {
                dojo.byId("abfeDIV").style.display = "none";
            }            

            
            //to display a message when a parish is selected whose flood maps are not hosted by LSU AgCenter
            if (parish.host != "LSU AgCenter") {

                var host = "";
                var msgToDisplay = "";
                host += parish.host;
                var note = "Use <b>this</b> LSU AgCenter site to obtain ground elevation and basic wind speed.<br/>"
                            + "At present, flood maps for " + parish.name + " parish are available on ";
                if (host.match("lamappingproject")) {
                    if (parish.FIRM.exist === "true") {
                        dojo.byId("lblCoastalParishNote").innerHTML = "Preliminary DFIRM is available on <a href=\"" + parish.host + "\" target=\"blank\">LaMP web site</a>";
                    } else {
                        wipeIn("locationResult");
                        dojo.byId("lblCoastalParishNote").innerHTML = "Maps are available on <a href=\"" + parish.host + "\" target=\"blank\">LaMP web site</a>";
                        msgToDisplay = note + "<a href=\"" + parish.host + "\"> LaMP web site</a>";
                    }
                } else {
                    wipeIn("locationResult");
                    msgToDisplay = note + "<a href=\"" + parish.host + "\"> FEMA Map Service Center</a>";
                }

                dojo.byId("locationResult").innerHTML = msgToDisplay
                                                + "<div style='width:100%' align='center'><input type='button' value='Ok' class='buttonsText'  onclick=\"wipeOut('locationResult');\" /></div>";
            } else {
                wipeOut("locationResult");
            }

            //get meetings info and events info
            var meetingsInfo = "<ul style='padding-left:15px;'>";
            for (var i = 0; i < parish.meetings.length; i++) {
                meetingsInfo += "<li>" + parish.meetings[i] + "</li>";
            }
            meetingsInfo += "</ul>";
            dojo.byId("meetings").innerHTML = meetingsInfo;

            var eventsInfo = "<ul style='padding-left:15px;'>";
            for (var i = 0; i < parish.events.length; i++) {
                eventsInfo += "<li>" + parish.events[i] + "</li>";
            }
            eventsInfo += "</ul>";
            dojo.byId("events").innerHTML = eventsInfo;
            //for flood insurance study text document

            dojo.byId("floodInsStudyText").href = parish.documents[0];

            dojo.byId("floodInsStudyText").target = "_blank";


        }
    } catch (Error) {
        alert(Error);
    }
}

function getParameter(parameterName) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + parameterName + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var parameterValue = regex.exec(window.location.href);

    if (parameterValue == null) {
        return "";
    }
    else {
        return parameterValue[1];
    }

}
function addFloodLayer(layerType, url, layerName) {
    switch (layerType) {
        case "Tiled":
            map.addLayer(new esri.layers.ArcGISTiledMapServiceLayer(url, { id: layerName, "opacity": 1.0 }));
            break;
        case "Dynamic":
            map.addLayer(new esri.layers.ArcGISDynamicMapServiceLayer(url, { id: layerName, "opacity": 1.0 }));
            break;
    }
}
function removeFloodLayers() {
    var l = map.layerIds.length;
    for (var i = 0; i < map.layerIds.length; i++) {
        for (var j = 0; j < map.layerIds.length; j++) {
            var layer = map.getLayer(map.layerIds[j]);
            if (layer.id == "pfirmLayer" || layer.id == "abfeLayer" || layer.id == "effFirmLayer" || layer.id == "adfirmLayer") {
                map.removeLayer(layer);
            }
        }

    }
}
function checkedChanged(obj) {
    showLoading();

    switch (obj.id) {
        case "cbDFIRM":
            if (obj.checked) {
                map.getLayer("pfirmLayer").show();
            } else {
                map.getLayer("pfirmLayer").hide();
            }
            break;
        case "cbPDFIRM":
            if (obj.checked) {
                map.getLayer("pdfirmLayer").show();
            } else {
                map.getLayer("pdfirmLayer").hide();
            }
            break;            
        case "cbADFIRM":
            if (obj.checked) {
                map.getLayer("adfirmLayer").show();
            } else {
                map.getLayer("adfirmLayer").hide();
            }
            break;
        case "cbABFE":
            if (obj.checked) {

                map.getLayer("abfeLayer").show();
            } else {
                map.getLayer("abfeLayer").hide();
            }
            break;
        case "cbFIRM":
            if (obj.checked) {
                map.getLayer("effFirmLayer").show();
                showLoading();
                dojo.connect(map.getLayer("effFirmLayer"), "onUpdateEnd", function() { hideLoading(); });
                wipeIn("locationResult");
                dojo.byId("locationResult").innerHTML = "The FIRM layer is a scanned image of old paper map panels that have been<br/> edge-matched."
                                                        + "The image has been manipulated to create an overlay that aligns<br/> better with newer, more accurate ground information."
                                                        + "Location of features shown<br/> on the FIRM layer is only approximate."
                                                        + "<div style='width:100%' align='center'><input type='button' value='Ok' class='buttonsText'  onclick=\"wipeOut('locationResult');\" /></div>";
            } else {
                map.getLayer("effFirmLayer").hide();
                wipeOut("locationResult");
            }
            break;
    }
    hideLoading();
}
function doQuery(evt) {
    showLoading(); //to show loading icon until all services returns results
    mapClick = evt.mapPoint; //set reference point to where user clicked map or geocode result coordinate system is wkid 4326
   
    var pointMeters = esri.geometry.webMercatorToGeographic(mapClick); //have to convert point from web mercator to geographic for web services (Elevation, BWS)

    //if no parish is selected no query is available to get flood zone
    // Notes: queryTaskUrl is a global variable and its value comes from JSON file when one of the parishes is selected from the layers tab
    currentParish = parishLayersDetails.Parishes[dojo.byId("parishes").selectedIndex - 1];
    
    if (!queryTaskUrl || queryTaskUrl == "") {
        //Query task is undefined or empty means thant DFIRM layer is not available for the parish. 
        //if Scanned FIRM available,display Flood Zone as 'read from map' else Visit FEMA MSC.
        floodZone = "Read from map";

        if (currentParish) {
            if (currentParish.DFIRM.exist == "false" && currentParish.FIRM.exist == "false") {
                floodZone = "Visit FEMA MSC"; //if any parish does not has DFIRM or FIRM, it's flood maps can be viewed in FEMA MSC.
            }
        }
            WebService.set_timeout(2000);
            //** If time exceeds 20 seconds in getting  elevation, ElevationFailedCallback is called
            WebService.getElevation(pointMeters.x, pointMeters.y, ElevationSucceededCallback, ElevationFailedCallback);
       
        }
    
        else {
           queryTask = new esri.tasks.QueryTask(queryTaskUrl);
           queryTask.execute(constructQuery(new Array("FLD_ZONE", "FLOODWAY"), evt.mapPoint), FloodZone);
        }

    //to get Panel id
    if (typeof PnlQueryTaskUrl == 'undefined' || PnlQueryTaskUrl == "") {
        panel = "N/A";
    }
    else {
        var PnlQueryTask = new esri.tasks.QueryTask(PnlQueryTaskUrl);
        setTimeout(function() { PnlQueryTask.execute(constructQuery(new Array("PANEL"), evt.mapPoint), getPanelId); }, 100);
    }

    //to get PMR DFIRM if exists
    if (typeof pmrQueryTaskUrl  != 'undefined' && pmrQueryTaskUrl  != "") {
        var pmrQueryTask = new esri.tasks.QueryTask(pmrQueryTaskUrl);

        setTimeout(function() { pmrQueryTask.execute(constructQuery(new Array("FLD_ZONE", "FLOODWAY"), evt.mapPoint), pmrFloodZone); }, 100);
    }    


    //TODO: Create a global boolean variable for each of the web services to indicate when they are retrieving values, 
    //      then remove addGraphic from get BWS service and place it here in a while not loop
    //var t = setTimeout("addGraphic()", 2500);
}
function getPanelId(featureSet) {
    var features = featureSet.features;
    if (features.length == 0) {
        panel = "N/A";
    } else {
        panel = features[0].attributes.PANEL;
    }

}
function FloodZone(featureSet) {
    floodZone = getFloodZone(featureSet);

    var pointMeters = esri.geometry.webMercatorToGeographic(mapClick); //have to convert point from web mercator to geographic
    WebService.set_timeout(10000);
    WebService.getElevation(pointMeters.x, pointMeters.y, ElevationSucceededCallback, ElevationFailedCallback);
    //** If time exceeds 10 seconds in getting  elevation, ElevationFailedCallback is called
    //addGraphic();
}

function pmrFloodZone(featureSet) {
    pmr_floodZone_FS = getFloodZone(featureSet);
}

function getFloodZone(featureSet) {
    var features = featureSet.features;
    var feature, attributes;
    var fldZONE;
    //window.alert(features.length);
    if (features.length == 0) {
        fldZONE = "Out of parish";
    }
    else {
        for (var i = 0; i < features.length; i++) {
            var floodway;
            feature = features[i];
            attributes = feature.attributes;
            floodway = attributes.FLOODWAY;
            if (floodway.replace(/\s/g, "") != "") {
                fldZONE = attributes.FLD_ZONE + ", " + floodway; //include if the flood zone has any floodways from the query
            }
            else {
                fldZONE = attributes.FLD_ZONE
            }
        }
    }
    return fldZONE;
}

function ElevationSucceededCallback(result, eventArgs) {
    elevation = result;
    // call getWindSpeed function to get BWS after the elevation service return is succes  
    try {
        getBasicWindSpeed(mapClick);
    }
    catch (Error) {
        alert(Error.description);
    }

}
function ElevationFailedCallback() {
    elevation = "USGS Service Not Responding";
    // call getWindSpeed function to get BWS   
    try {
        getBasicWindSpeed(mapClick);
    }
    catch (Error) {
        alert(Error.description);
    }
}
function getBasicWindSpeed(click) {
    var speedQueryTask = new esri.tasks.QueryTask("http://maps.lsuagcenter.com/ArcGIS/rest/services/LAWinds/LABWS/MapServer/0");
    speedQueryTask.execute(constructQuery(new Array("Speed"), click), function(featureSet) {
        var features = featureSet.features;
        var feature, attributes;
         
        if (features.length == 0) {
            BWS = "Unknown";
        }
        else {
            for (var i = 0; i < features.length; i++) {
                feature = features[i];
                attributes = feature.attributes;
                BWS = parseInt(attributes.Speed) + " mph";
            }
        }
        map.infoWindow.resize(290, 200);
        map.infoWindow.show();
        addGraphic();
    });
}

function constructQuery(outFields, point) {
    var query = new esri.tasks.Query();
    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    query.outFields = outFields;
    query.geometry = point;
    query.returnGeometry = false;
    return query;
}

function addGraphic() {
    var symbol = new esri.symbol.PictureMarkerSymbol('images/round_PushPin_red.gif', 30, 30);

    var textSymbolFont = new esri.symbol.Font("8pt", esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_BOLD);
    var point = new esri.geometry.Point(map.spatialReference);
    point.setX(mapClick.x);
    point.setY(mapClick.y);    
    
    var pointMeters = esri.geometry.webMercatorToGeographic(point); //have to convert point from web mercator to geographic
    
 
    if (symbol) {
        symbol = eval(symbol);
    }
    
    //if parish is selected, then use current parish details to fill in info window.
    currentParish = parishLayersDetails.Parishes[dojo.byId("parishes").selectedIndex - 1];

    if (typeof currentParish === 'undefined') {
        //User made it to the app without choosing a parish. When they search or click the map, do not query floodzone
        
    }
    else{
        
        
        //if (map.graphics.graphics.length === 0){ var pointIndex = 1;  }
        //else 
        var pointIndex = map.graphics.graphics.length / 2 + 1; 
        
        if (currentParish.DFIRM.exist == "true") {
            if (pmr_floodZone_FS != '' && pmr_floodZone_FS != 'undefined') {
                var attributes = { Index: pointIndex, Xval: pointMeters.x.toFixed(5), Yval: pointMeters.y.toFixed(5), DFIRMFloodZone: floodZone, PDFIRMFloodZone: pmr_floodZone_FS, FIRMFloodZone: "Read from map", Elevation: elevation, WindSpeed: BWS, Panel: panel };
            }
            else {
                var attributes = { Index: pointIndex, Xval: pointMeters.x.toFixed(5), Yval: pointMeters.y.toFixed(5), DFIRMFloodZone: floodZone, FIRMFloodZone: "Read from map", Elevation: elevation, WindSpeed: BWS, Panel: panel };
            }
        }
        else {
            var attributes = { Index: pointIndex, Xval: pointMeters.x.toFixed(5), Yval: pointMeters.y.toFixed(5), DFIRMFloodZone: "N/A", FIRMFloodZone: "Read from map", Elevation: elevation, WindSpeed: BWS, Panel: panel };
        }
        
        var graphic = new esri.Graphic(point, symbol, attributes, infoTemplate);

        map.graphics.add(graphic);

        //add another text graphic at the same point which looks as label for the graphic
        var g = map.graphics.graphics; //graphics array from graphic layer (map.graphics)
        
        var textSymbol = new esri.symbol.TextSymbol(String((g.length + 1) / 2), textSymbolFont);
        textSymbol.setOffset(-6, 0); // (0, -5); //

        var mapGraphic = new esri.Graphic(point, textSymbol, attributes, infoTemplate);
        map.graphics.add(mapGraphic);
  
        //build table to display in left column from the array of graphics
        
        tbl = "<div style='width:80%' align='left'><input type='button' value='Clear points' style=\"font:bold 80% 'trebuchet ms',helvetica,sans-serif; border:1px solid; width:80px;\" onclick=\"map.graphics.clear();dojo.byId('dataPoints').innerHTML='';\"/></div><table class=\"fooBar\">";
        for (var x = 0; x < g.length; x += 2) {
            if (x % 2 == 0) {
                tbl += "<tr><td><b>Point " + (x + 2) / 2 + "</b><br/>Latitude:" + g[x].attributes.Yval + "<br/>Longitude:" + g[x].attributes.Xval + "";
                tbl += (currentParish.DFIRM.exist == "true") ? "<br/>DFIRM Flood Zone:" + g[x].attributes.DFIRMFloodZone : "";
                tbl += (typeof currentParish.ADOPTED_DFIRM != 'undefined') ? "<br/>Future DFIRM: " + g[x].attributes.AdoptedDFIRM : "";
                tbl += (currentParish.DFIRM.exist == "true") ? "<br/>Panel Id:" + g[x].attributes.Panel: "";
                tbl += (currentParish.FIRM.exist == "true") ? "<br/>FIRM Flood Zone:" + g[x].attributes.FIRMFloodZone : "";
                tbl += "<br/>Ground Elevation:" + g[x].attributes.Elevation + "<br/>Wind Speed:" + g[x].attributes.WindSpeed;
                tbl += "</td></tr>";
            }

        }
        tbl += "</table>";
        dojo.byId("dataPoints").innerHTML = tbl;

        
        hideLoading(); //hide the loading icon after the result is diplayed.
    } //end if parish is selected

}


function showLoading() {
    esri.show(loading);
}

function hideLoading() {
    esri.hide(loading);
}

function searchKeyPress(e, obj) {

    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //FF
    if (key == 13) {
        switch (obj.id) {
            case "txtAddress":
                dojo.byId("btnLocate").onclick();
                break;
            case "txtPrintTitle":
                //dojo.byId("btnPreview").onclick();
                break;
        }

    }
    return (key != 13);

}
function openPreview() {
    var graphicData = ""; //=dojo.byId("dataPoints").innerHTML ;
    var tit = dojo.byId("txtPrintTitle").value;

    var g = map.graphics.graphics;
    for (var x = 0; x < g.length; x += 2) {
        if (x % 2 == 0) {
            graphicData += "Long:" + g[x].attributes.Xval + ";Lat:" + g[x].attributes.Yval + ";FloodZone:" + g[x].attributes.DFIRMFloodZone + ";pFloodZone:" + g[x].attributes.PDFIRMFloodZone + ";Elevation:" + g[x].attributes.Elevation + ";BWS: " + g[x].attributes.WindSpeed + ";PanelId:" + g[x].attributes.Panel + "_";
        }
    }
    var layers = "";
    layers += currentBaseMapView;

    for (var lay = 1; lay < map.layerIds.length; lay++) {
        if (map.getLayer(map.layerIds[lay]).visible) {
            layers += "," + map.getLayer(map.layerIds[lay]).id;
        }
    }

    var s = "";
    s = "XMin=" + map.extent.xmin
      + "&YMin=" + map.extent.ymin
      + "&XMax=" + map.extent.xmax
      + "&YMax=" + map.extent.ymax
      + "&graphicData=" + graphicData + "&l=" + layers;
    if (tit !== "") {
        s += "&t=" + tit;
    }
    //** pass the xmlnode number for the parish selected
    if (dojo.byId("parishes").selectedIndex !== 0) {

        s += "&node=" + dojo.byId("parishes").selectedIndex;
    }

    //var Xmin, Ymin, Xmax, Ymax, layer1, layer2, g1x, g1y, g2x, g2y;
    //var winPrint = window.open('printMap.htm?' + s, '', '');

    if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
        var winPrint = window.open('printMap.htm?' + s, '', '');
    } else {
        var winPrint = window.open('printMap.aspx?' + s, '', '');
    }
}

function showScannedFIRMLegend() {
    var infoWindow = window.open('scannedmapLegend.htm', '', 'left=0,top=0,width=500,toolbar=no,scrollbars=yes');
}

function displayInfoWindow(evt) {


    map.infoWindow.setTitle(getInfoTemplateTitle(evt.graphic));
    map.infoWindow.setContent(getInfoTemplateContent(evt.graphic));
    map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));

}

function getInfoTemplateTitle(graphic) {
    //attributes = Title, Xval, Yval, DFIRMFloodZone, FIRMFloodZone, Elevation, WindSpeed, BWS, Panel};
    var infoTemplateTitle = "<b>Point " + graphic.attributes.Index + " Information </b>";
    return infoTemplateTitle;
}

function getInfoTemplateContent(graphic) {
    //reference for graphic attributes:
    //attributes = Title, Xval, Yval, DFIRMFloodZone, FIRMFloodZone, Elevation, WindSpeed, Panel};

    var infoTemplateContent = "<b>Latitude:</b> " + graphic.attributes.Yval + "<br/>"
                            + "<b>Longitude:</b> " + graphic.attributes.Xval + "<br/>";

//    infoTemplateContent += "<b>DFIRM Flood zone:</b> " + graphic.attributes.DFIRMFloodZone + "<br/>"
//                         + "<b>PMR Flood zone:</b> " + graphic.attributes.PDFIRMFloodZone + "<br/>"
//                         + "<b>DFIRM Panel:</b> "  + graphic.attributes.Panel + "<br/>"
//                         + "<b>FIRM Flood zone:</b> Read from map <br/>";

    infoTemplateContent += (currentParish.DFIRM.exist == "true") ? "<b>Effective Flood Hazard:</b>" + graphic.attributes.DFIRMFloodZone + "<br/>" : "";
    infoTemplateContent += (typeof currentParish.ADOPTED_DFIRM != 'undefined') ? "<b>Future DFIRM:</b>" + graphic.attributes.AdoptedDFIRM + "<br/>" : "";
    infoTemplateContent += (typeof currentParish.PDFIRM != 'undefined' && currentParish.PDFIRM.exist == "true") ? "<b>Preliminary Flood Hazard:</b> " + graphic.attributes.PDFIRMFloodZone + "<br/>" : "";
    infoTemplateContent += (currentParish.DFIRM.exist == "true") ? "<b>FIRM Panel (Date):</b> " + graphic.attributes.Panel + " (" + currentParish.DFIRM.EffectiveDate + ")<br/>" : "";
    infoTemplateContent += (currentParish.FIRM.exist == "true" && currentParish.DFIRM.exist == "false") ? "<b>Effective Flood Hazard:</b>" + graphic.attributes.FIRMFloodZone + "<br/>" : "";
    infoTemplateContent += (currentParish.FIRM.exist == "true" && currentParish.DFIRM.exist == "true") ? "<b>Historical Flood Hazard:</b>" + graphic.attributes.FIRMFloodZone + "<br/>" : "";
                         

    //or this if floodzone = "N/A"
    //infoTemplateContent += "<b>FIRM Flood zone:</b> Read from map <br/>";


    infoTemplateContent += "<b>Ground Elevation<sup>1</sup>:</b> " + graphic.attributes.Elevation + "<br/>"
                            + "<b>Basic WindSpeed<sup>2</sup>:</b> " + graphic.attributes.WindSpeed + "<br/><br/>"
                            + "<span class='esriInfoWindow'>1. Provided by USGS Web Service.<br/>"
                            + "2. Provided by LSU AgCenter Basic Wind Speed Service.</span> <br/>";
                            
    return infoTemplateContent;
}
function reloadFIPS (newFIPS) {
    var gotoFIPS = "?FIPS="
    gotoFIPS = gotoFIPS + newFIPS;
window.location.href = gotoFIPS; 
}
