﻿var proposedFIRMLayer = baseDataLayer + layerFirmPanels;
var proposedFloodZoneLayer = baseDataLayer + proposedFloodLayer; //todo move to config
var STRLayer = baseDataLayer + layerPLSS;
var firmQueryTask = new esri.tasks.QueryTask(proposedFIRMLayer);
var floodZoneQueryTask = new esri.tasks.QueryTask(proposedFloodZoneLayer);
var STRqueryTask = new esri.tasks.QueryTask(STRLayer);
var parcelQueryTask = new esri.tasks.QueryTask(baseDataLayer + allParcelsLayer);

//// Catch query task failures and handle
var queryTaskFailed = function(err) {
  Ext.MessageBox.hide();
  unmaskSearchForm();
  console.error(err.toString());
  Mapping.Ext.Esri.ErrorManager.esriError(err);
}

function openReportNew(mapPoint) {
  window.reportPointText = mapPoint.x + "," + mapPoint.y;

  // Query to see if user clicked in a building outline
  //var queryTask = new esri.tasks.QueryTask(buildingLayer);
  query = new esri.tasks.Query();
  query.returnGeometry = true;
  query.geometry = mapPoint;
  query.outFields = ["PARCEL"]; // need at least one field for query to work    
  query.geometry.spatialReference = map.spatialReference;

  //parcelQueryTask.execute(query, getReport);

  var returnDef = parcelQueryTask.execute(query);
  returnDef.addCallbacks(getReport, queryTaskFailed); 
}

function getReport(results){

    if(results.features.length < 1){
        alert("Please click inside a building outline to generate a report.");
        return;
    }
    
    window.buildingExtent = results.features[0].geometry.getExtent();        
    open("./report.htm");        
}

var reportClickHandler = null;
function activateReport(){
    if(reportClickHandler == null){
        reportClickHandler = dojo.connect(map, "onClick", openReport);
        SetMapCursor("pointer"); // in case came though hover activation        
    }
}

function disableReport(){
    if(reportClickHandler != null){    
        dojo.disconnect(reportClickHandler);    
        reportClickHandler = null;
    }
}

// --------- Functions used by report.htm
var mapReport = null;
function generateReport(){
  Ext.MessageBox.wait('Generating report...');

  dojo.subscribe('esri.Error', function(err) {
    Ext.MessageBox.hide();
    console.debug('esriError Code: ' + err.code);
    console.debug('Message: ' + err.code);
    console.debug('details: ' + err.details == null ? err.details.join("\n") : "No details");
    Ext.Msg.alert('Server Error', 'An unknown mapping server error has occurred. Please try your operation again or close your browser and open a new session.');
  }
  );
  
  var mre;
  if (window.opener.parcelGeom != null) {
    mre = window.opener.parcelGeom.getExtent().expand(1.1);
    mapReport = new esri.Map("map", { extent: mre, slider: false });

    var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(reportPrintMapLayer);
    mapReport.addLayer(dynamicMapServiceLayer);

    //query for attribute info
    dojo.connect(mapReport, "onLoad", function() {
      queryBuilding();
    }); 
  }
}

var buildingGeometry;
var qbuilding;
var spatialRef = defaultSpatialReference;
function queryBuilding() {
    var coords = window.opener.reportPointText;
    var coordSplit = coords.split(",");

    var mapPoint = new esri.geometry.Point(parseFloat(coordSplit[0]), parseFloat(coordSplit[1]), spatialRef);   
    query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.geometry = mapPoint;
    query.outFields = ["PARCEL", "BFE_AVG", "BFE_MIN", "BFE_MAX", "TXTBFE", "TXT10YR", "TXT2YR"];
    query.geometry.spatialReference = spatialRef;
    
    //parcelQueryTask.execute(query, reportResults);
    var returnDef = parcelQueryTask.execute(query);
    returnDef.addCallbacks(reportResults, queryTaskFailed);     
}

var proposedBFE=-9999;
var TXTBFE="Not Available";
var minBFE = -9999;
var maxBFE = -9999;
var PropStaticBFE=-9999;
var Parcel="Not Available";
var STR="";
var TXT10YR="Not Available";
var TXT2YR="Not Available";
var OFW="";
var graphic;

function reportResults(results) {
		 qbuilding=results;
    graphic = qbuilding.features[0]; 
    buildingGeometry = graphic.geometry;

		window.jsongraphic = graphic.toJson();
		//Customer request removing highlight, just outline		        
    if(mapReport != null){
        // highlightBuilding
        var reportSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NULL, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 2), new dojo.Color([239,186,0,0.50])); //rgb(239, 186, 0)
        graphic.setSymbol(reportSymbol);    
        mapReport.graphics.add(graphic);
    }
      
    var featureAttributes = graphic.attributes;
    minBFE = featureAttributes["BFE_MIN"];
    maxBFE = featureAttributes["BFE_MAX"];

    if((!featureAttributes["PARCEL"] || featureAttributes["PARCEL"] == "" || featureAttributes["PARCEL"] == " ")){
        Parcel = "Not Available";
    }else{        
        Parcel = featureAttributes["PARCEL"];
      } 
    if((!featureAttributes["BFE_AVG"] || featureAttributes["BFE_AVG"] == "" || featureAttributes["BFE_AVG"] == " ")){
        proposedBFE = -9999;
    }else{        
        proposedBFE = featureAttributes["TXTBFE"];
      } 
    if((!featureAttributes["TXT10YR"] || featureAttributes["TXT10YR"] == "" || featureAttributes["TXT10YR"] == " ")){
        TXT10YR = "Not Available";
    }else{        
        TXT10YR = featureAttributes["TXT10YR"];
      } 
    if((!featureAttributes["TXT2YR"] || featureAttributes["TXT2YR"] == "" || featureAttributes["TXT2YR"] == " ")){
        TXT2YR = "Not Available";
    }else{        
        TXT2YR = featureAttributes["TXT2YR"];
      } 

	GetSTRs();
	
}

function CreateProfileBody() {
		var profileBody = "";    
    var date = new Date();
    var dateStr = (parseInt(date.getMonth()) + 1) + "/" + parseInt(date.getDate()) + "/" + parseInt(date.getFullYear());
    
    profileBody += String(template).replace(/\{0\}/g, "Date: ").replace(/\{1\}/g, dateStr);
    profileBody += String(template).replace(/\{0\}/g, "Parcel: ").replace(/\{1\}/g, Parcel);
    profileBody += String(template).replace(/\{0\}/g, "County: ").replace(/\{1\}/g, window.opener.County);
    profileBody += String(template).replace(/\{0\}/g, "STR: ").replace(/\{1\}/g, STR);    
    profileBody += String(template).replace(/\{0\}/g, "Status: ").replace(/\{1\}/g, window.opener.MapStatus);
    
    window.profileBody = profileBody;
    dojo.byId("profile").innerHTML = profileBody;    
    
    createProposedBody();
    
}

var proposedBody = "";
function createProposedBody(){    
    var query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["FIRM_PAN"];
    
    // "geometry invalid" error occurs if we use the result geometry directly
    var json = buildingGeometry.toJson();
    var polygon = new esri.geometry.Polygon(json);     
    query.geometry = polygon;
    query.outSpatialReference = spatialRef;
    //firmQueryTask.execute(query, firmPans);

    var returnDef = firmQueryTask.execute(query);
    returnDef.addCallbacks(firmPans, queryTaskFailed);   
}

var firmPanNums = "";

function firmPans(featureSet) {      
    for (var i=0, il=featureSet.features.length; i<il; i++) {
        firmPanNums += featureSet.features[i].attributes["FIRM_PAN"];
        if(il > 1 && i < il-1){
         firmPanNums += ", ";
        }
    }

    query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["FLOODWAY", "FLD_ZONE", "STATIC_BFE"];
    
    query.geometry = buildingGeometry;
    //floodZoneQueryTask.execute(query, zones);

    var returnDef = floodZoneQueryTask.execute(query);
    returnDef.addCallbacks(zones, queryTaskFailed);    
}

var floodway = "No";
var comma = ", ";
function zones(featureSet){
    var floodZonesFound = new Array();
    var floodZones = "";    
    var SHA = "No";
    var floodZone;
    var BFE_NA = true;
    var isBFE = new RegExp("A\\d+|V\\d+");
    var staticbfe;
    for (var i=0, il=featureSet.features.length; i<il; i++) {
        floodZone = featureSet.features[i].attributes["FLD_ZONE"];
        staticbfe = featureSet.features[i].attributes["STATIC_BFE"];  
        if (staticbfe>PropStaticBFE) {
        		PropStaticBFE = staticbfe;  
        		
        if (proposedBFE == -9999 || proposedBFE == "Not Available") {
        		proposedBFE = PropStaticBFE + " (feet)";
	}
	else {
		if (PropStaticBFE < minBFE)
			proposedBFE = PropStaticBFE + " - " + Math.round(maxBFE*10)/10 + " (feet)";
		if (PropStaticBFE > maxBFE)
			proposedBFE = Math.round(minBFE*10)/10 + " - " + PropStaticBFE + " (feet)";
		}
	}
                    
        // check if we already have it
        var floodZoneExists = false;
        for(var j=0; j < floodZonesFound.length; j++){
            if(floodZonesFound[j].indexOf(floodZone) == 0){
                floodZoneExists = true;
            }
        }
            
        if(!floodZoneExists){            
            floodZonesFound.push(floodZone);
        
            floodZones += floodZone;        
            if(il > 1 && i < il-1){
             floodZones += comma;
            }
            
            var isBFE = new RegExp("A\\d+|V\\d+");
            //FLD_ZONE field is either AE, AH, A1 through A30, V, VE or V1 through V30, then what is the Base Flood Elevation (BFE), otherwise N/A.
            if(floodZone == "AE" || floodZone == "AH" || isBFE.test(floodZone) || floodZone == "V" || floodZone == "VE"){
                BFE_NA = false;
            } 
            
            if (floodZone.indexOf("A") == 0 || floodZone.indexOf("V") == 0){
                SHA = "Yes";
            }
        }
        
        var floodwayValue = featureSet.features[i].attributes["FLOODWAY"];
        if(floodwayValue == "FLOODWAY"){            
            floodway = "Yes";            
        }        
    }
    
    proposedBody += String(template).replace(/\{0\}/g, "FIRM Panel: ").replace(/\{1\}/g, firmPanNums);
    proposedBody += String(template).replace(/\{0\}/g, "SFHA: ").replace(/\{1\}/g, SHA);
    
    var lastCommaIndex = floodZones.lastIndexOf(comma);
    if(lastCommaIndex != -1 && lastCommaIndex ==  floodZones.length-2){
        floodZones = floodZones.substring(0, lastCommaIndex);
    }
    proposedBody += String(template).replace(/\{0\}/g, "Zone: ").replace(/\{1\}/g, floodZones);

    if(BFE_NA){ 
        proposedBody += String(template).replace(/\{0\}/g, "100YR Elev (BFE): ").replace(/\{1\}/g, "Not Available");        
    }else{
        if(parseInt(proposedBFE) == -9999){
            proposedBody += String(template).replace(/\{0\}/g, "100YR Elev (BFE): ").replace(/\{1\}/g, "Not Available");
        }else{
            proposedBody += String(template).replace(/\{0\}/g, "100YR Elev (BFE): ").replace(/\{1\}/g, proposedBFE);
        }
    }
    
     proposedBody += String(template).replace(/\{0\}/g, "Floodway: ").replace(/\{1\}/g, floodway);
     proposedBody += String(template).replace(/\{0\}/g, "10YR Elev: ").replace(/\{1\}/g, TXT10YR);
     proposedBody += String(template).replace(/\{0\}/g, "2YR Elev: ").replace(/\{1\}/g, TXT2YR);         
     //proposedBody += String(template).replace(/\{0\}/g, "<br />Outstanding Florida Waters: ").replace(/\{1\}/g, OFW);  
         
    window.proposedBody = proposedBody;
    dojo.byId("proposed").innerHTML = proposedBody;
    
    zoneDescription(floodZones.split(", ")); 
}

function zoneDescription(zones){
    var ZoneDesc = "";
    
    zoneX = false;
    zoneA = false;
    zoneAE = false;
    zoneAH = false;
    zoneAO = false;
    zoneAR = false;
    zoneA99 = false;
    zoneV = false;
    zoneVE = false;
    zoneD = false;
    zoneXShaded = false;
    var i =0;
    for (i=0;i<=zones.length-1;i++){
      var s = zones[i];
        switch (s){
	        case "B":
	        case "C":
	        case "X":
	            zoneX = true;
	            break;
	        case "A":
	            zoneA = true;
	            break;
	    }
	    if (s.indexOf("AE") >= 0 || s.indexOf("A1") >= 0 || s.indexOf("A2") >= 0 || s.indexOf("A3") >= 0){
	        zoneAE = true;
	    }
	    switch (s){
	        case "AH":
	            zoneAH = true;
	            break;
	        case "AO":
	            zoneAO = true;
	            break;
	        case "AR":
	            zoneAR = true;
	            break;
	        case "A99":
	            zoneA99 = true;
	            break;
	        case "V":
	            zoneV = true;
	            break;
	    }
	    if (s.indexOf("VE") >= 0 || s.indexOf("V1") >= 0 || s.indexOf("V2") >= 0 || s.indexOf("V3") >= 0)
	        zoneVE = true;
	    if (s == "D")
	        zoneD = true;
	    if (s.indexOf("0.2") >= 0)
	        zoneXShaded = true;
	}
	
    if (proposedBFE != "Not Available"){

        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">Base Flood Elevation (BFE)</div><div class=\"ZoneContent\">The elevation shown on the Flood Insurance Rate Map for Zones AE, AH, A1-A30, AR, AO, V1-V30, and VE that indicates the water surface elevation resulting from a flood that has a one percent chance of equaling or exceeding that level in any given year. </div></div>";        
    }
            
    if (zoneX == true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">B, C, and X </div><div class=\"ZoneContent\">Areas outside the 1-percent annual chance floodplain, areas of 1% annual chance sheet flow flooding where average depths are less than 1 foot, areas of 1% annual chance stream flooding where the contributing drainage area is less than 1 square mile, or areas protected from the 1% annual chance flood by levees. No Base Flood Elevations or depths are shown within this zone. Insurance purchase is not required in these zones. </div>";
    
    if (zoneA==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">A </div><div class=\"ZoneContent\">Areas with a 1% annual chance of flooding and a 26% chance of flooding over the life of a 30-year mortgage. Because detailed analyses are not performed for such areas; no depths or base flood elevations are shown within these zones. </div>";
    
    if (zoneAE==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">AE, A1-A30 </div><div class=\"ZoneContent\">Areas with a 1% annual chance of flooding and a 26% chance of flooding over the life of a 30-year mortgage. In most instances, base flood elevations derived from detailed analyses are shown at selected intervals within these zones. </div>";
    
    if (zoneAH==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">AH </div><div class=\"ZoneContent\">Areas with a 1% annual chance of shallow flooding, usually in the form of a pond, with an average depth ranging from 1 to 3 feet. These areas have a 26% chance of flooding over the life of a 30-year mortgage. Base flood elevations derived from detailed analyses are shown at selected intervals within these zones. </div>";
    
    if (zoneAO==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">AO </div><div class=\"ZoneContent\">River or stream flood hazard areas, and areas with a 1% or greater chance of shallow flooding each year, usually in the form of sheet flow, with an average depth ranging from 1 to 3 feet. These areas have a 26% chance of flooding over the life of a 30-year mortgage. Average flood depths derived from detailed analyses are shown within these zones. </div>";
    
    if (zoneAR==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">AR </div><div class=\"ZoneContent\">Areas with a temporarily increased flood risk due to the building or restoration of a flood control system (such as a levee or a dam). Mandatory flood insurance purchase requirements will apply, but rates will not exceed the rates for unnumbered A zones if the structure is built or restored in compliance with Zone AR floodplain management regulations. </div>";
    
    if (zoneA99==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">A99 </div><div class=\"ZoneContent\">Areas with a 1% annual chance of flooding that will be protected by a Federal flood control system where construction has reached specified legal requirements. No depths or base flood elevations are shown within these zones. </div>";
    
    if (zoneV==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">V </div><div class=\"ZoneContent\">Coastal areas with a 1% or greater chance of flooding and an additional hazard associated with storm waves. These areas have a 26% chance of flooding over the life of a 30-year mortgage. No base flood elevations are shown within these zones. </div>";
    
    if (zoneVE==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">VE, V1-V30 </div><div class=\"ZoneContent\">Coastal areas with a 1% or greater chance of flooding and an additional hazard associated with storm waves. These areas have a 26% chance of flooding over the life of a 30-year mortgage. Base flood elevations derived from detailed analyses are shown at selected intervals within these zones. </div>";
    
    if (zoneD==true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">D </div><div class=\"ZoneContent\">Areas with possible but undetermined flood hazards. No flood hazard analysis has been conducted. Flood insurance rates are commensurate with the uncertainty of the flood risk. </div>";
    
    if (zoneXShaded == true)
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">0.2 PCT ANNUAL CHANCE FLOOD HAZARD - X (Shaded) </div><div class=\"ZoneContent\">Areas outside the 1-percent annual chance floodplain, areas of 1% annual chance sheet flow flooding where average depths are less than 1 foot, areas of 1% annual chance stream flooding where the contributing drainage area is less than 1 square mile, or areas protected from the 1% annual chance flood by levees. No Base Flood Elevations or depths are shown within this zone. Insurance purchase is not required in these zones. However, detailed studies have been performed, and the area has been determined to be within the 0.2 percent annual chance floodplain.  </div>";
    
    if (floodway == "Yes")    
        ZoneDesc = ZoneDesc + "<div class=\"ZoneTitle\">FLOODWAYS </div><div class=\"ZoneContent\">The channel of a river or other watercourse and the adjacent land areas that must be reserved in order to discharge the base flood (1% annual chance flood event). The floodway must be kept open so that floods can proceed downstream and not be obstructed or diverted onto other properties.<br><br>Please note, if you develop within the regulatory floodway, you will need to contact your Local Government and the Suwannee River Water Management District prior to commencing with the activity.  Please contact the District at 800.226.1066.  </div>";
	
    if (ZoneDesc == "")
        ZoneDesc = "<div class=\"ZoneContent\">This parcel is not in a flood zone.</div>";
    
    window.ZoneDesc1 = ZoneDesc;
    window.ZoneDesc2 = "";    
    if (ZoneDesc.length>1000) {
    	var ind = ZoneDesc.indexOf(" ", 1000);
    	window.ZoneDesc1 = ZoneDesc.substring(0, ind) + "</div>";
    	window.ZoneDesc2 = "<div class=\"ZoneContent\">" + ZoneDesc.substring(ind+1);
    }

    dojo.byId("ZoneDescription").innerHTML = ZoneDesc;

    //final task complete
    Ext.MessageBox.hide();
}

function GetSTRs() {
  console.debug('in GetSTRs');
    var query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["SEC", "TWN", "RNG"];
    
    // "geometry invalid" error occurs if we use the result geometry directly
    var json = buildingGeometry.toJson();
    var polygon = new esri.geometry.Polygon(json);     
    query.geometry = polygon;
    query.outSpatialReference = spatialRef;

    //STRqueryTask.execute(query, STRs);
    var returnDef = STRqueryTask.execute(query);
    returnDef.addCallbacks(STRs, queryTaskFailed);
        
}

function STRs(featureSet){
    for (var i=0, il=featureSet.features.length; i<il; i++) {
      STR += "S" + featureSet.features[i].attributes["SEC"] + " T" + featureSet.features[i].attributes["TWN"] + " R" + featureSet.features[i].attributes["RNG"];
        if(il > 1 && i < il-1){
         STR += ",";
        }
    	}

  	if (STR=="") STR="Not Available";

  	CreateProfileBody();
}

function OpenFriendlyReport() {
	window.mapserver = window.opener.mapserver;
	window.buildingExtent = window.opener.buildingExtent;
	window.mapcontents = dojo.byId("map").innerHTML;
	window.zoneDescr = "one zone descrip";
	open("ReportPrint.htm");
}

