﻿
function openReport(evt){    
    SetMapCursor(currentMapCursor);
    
    mapPoint = evt.mapPoint;
    if(map.getLevel() < infoZoomLevel){
        if(confirm("Zoom to a scale where buildings are visible to generate a report?")){            
            map.centerAt(mapPoint);                        
            window.setTimeout("map.setLevel("+infoZoomLevel+")",300);                                          
            return; 
        }else{
            return;
        }
    }    
    
    dojo.byId("loadingImg").style.display ="block";
    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;
    queryTask.execute(query, getReport);
}

function getReport(results){
    dojo.byId("loadingImg").style.display ="none";
    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;
var isFirefox2 = false;
function generateReport(){    

    // Firefox 2 doesn't print the map    
    var agent = navigator.userAgent;
    if ((versionOffset=agent.indexOf("Firefox"))!=-1) {        
        var fullVersion  = parseFloat(agent.substring(versionOffset+8));
        if(fullVersion < 3){
            isFirefox2 = true;
        }
    }
    if(!isFirefox2){      
        var mre=window.opener.buildingExtent; 
        var mapReportExtent=new esri.geometry.Extent(mre.xmin-0.001, mre.ymin-0.001, mre.xmax+0.001, mre.ymax+0.001);
        mapReport = new esri.Map("map", {extent: mapReportExtent, slider: false}); 
        var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer(mapserver);
        mapReport.addLayer(tiledMapServiceLayer); 
    }else{
        var geometry = window.opener.buildingExtent;
        var factor = 0.000005;   
        var xmin = parseFloat(geometry.xmin) - (parseFloat(geometry.xmin) * factor);
        var ymin = parseFloat(geometry.ymin) - (parseFloat(geometry.ymin) * factor);
        var xmax = parseFloat(geometry.xmax) + (parseFloat(geometry.xmax) * factor);
        var ymax = parseFloat(geometry.ymax) + (parseFloat(geometry.ymax) * factor);
    
        var extent = xmin + "," + ymin + "," + xmax + "," + ymax;
        var imageFormat = "jpg";
        var imageHref = mapserver + "/export?bbox=" + extent + "&format=" + imageFormat + "&f=image&size=295,224"        
        var imageDiv = dojo.byId("map");        
        imageDiv.innerHTML = "<img src=\"" + imageHref + "\"/>"; 
    }
    
    // Need to run query again as the building geometry passed via window.opener is considered invalid
    queryBuilding();
}


var spatialRef;
var buildingGeometry;
var qbuilding;

function queryBuilding(){
    var coords = window.opener.reportPointText;
    var coordSplit = coords.split(",");
    
    // spatialRef hardcoded if map does not have this value yet    
    if(mapReport == null || mapReport.spatialReference == null)    
        spatialRef = new esri.SpatialReference({wkid: '4326'});
    else
        spatialRef = mapReport.spatialReference;
        
    var mapPoint = new esri.geometry.Point(parseFloat(coordSplit[0]), parseFloat(coordSplit[1]), spatialRef);

    var queryTask = new esri.tasks.QueryTask(buildingLayer);    
    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;    
    queryTask.execute(query, reportResults);    

}

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="";

function reportResults(results){
		
		qbuilding=results;
    var graphic = qbuilding.features[0]; 
    buildingGeometry = graphic.geometry;

		window.jsongraphic = graphic.toJson();
		        
    if(mapReport != null){
        // highlightBuilding
        var reportSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, 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 queryTask = new esri.tasks.QueryTask(proposedFIRMLayer);
    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;          
    queryTask.execute(query, firmPans);    
}

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 += ", ";
        }
    }
   
    
    var queryTask = new esri.tasks.QueryTask(proposedFloodZoneLayer);
    query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["FLOODWAY", "FLD_ZONE", "STATIC_BFE"];
    
    // "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;
            
    queryTask.execute(query, zones);    
}

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;

    for (var i in zones){
        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;
}

function GetSTRs(){

    var queryTask = new esri.tasks.QueryTask(STRLayer);
    var query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["SECT_NO", "TWP", "RANGE"];
    
    // "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;  

    queryTask.execute(query, STRs);    
}

function STRs(featureSet){ 

    for (var i=0, il=featureSet.features.length; i<il; i++) {
        STR += "S"+featureSet.features[i].attributes["SECT_NO"]+" T"+featureSet.features[i].attributes["TWP"]+" R"+featureSet.features[i].attributes["RANGE"];
        if(il > 1 && i < il-1){
         STR += ",";
        }
    	}

  	if (STR=="") STR="Not Available";

  	GetOFWs();
}

function GetOFWs(){
        
    var queryTask = new esri.tasks.QueryTask(OFWLayer);
    var query = new esri.tasks.Query();
    query.returnGeometry = false;
    query.outFields = ["NAME"];
    
    // "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;  
    queryTask.execute(query, OFWs);    
}

function OFWs(featureSet){    
    for (var i=0, il=featureSet.features.length; i<il; i++) {
        OFW += featureSet.features[i].attributes["NAME"]+"";
        if(il > 1 && i < il-1){
         OFW += ",";
        }
    }
    if (OFW=="") OFW="None";

  	CreateProfileBody();
}

function OpenFriendlyReport() {
	window.mapserver = window.opener.mapserver;
	window.buildingExtent = window.opener.buildingExtent;
//	window.mapcontents = dojo.byId("map").innerHTML;
	open("ReportPrint.htm");
}