//<![CDATA[


//- map.js      2009.07.15          JavaScript
//= DARRP       Ben Shorr, NOAA     J. Daniel Rutz, Genwest Systems, Inc.


// Constants:
var statPath = "../static/"
var dataFile = "ORRActivities20091007.xml";

var legendFile = statPath + "Legend09.png";
var legendAlt = "Legend";
var legendBackgroundColor = "#9bb6d3"

// The "nam" must match a record for darrpregion in the dataFile.
// The first word of "nam" must match the first word of document.title.
// For the Southwest Region, set the initial zoom to California ("zoom":2).
var regions = {
                "count":5
            , "subhead":"Zoom to Area:"
            ,    "rows":
    [ {"count":15 , "nam":"Northeast"                   , "zoom":0, "rows":
        [ {"nam":"Northeast Region"  , "lat": 33.8 , "lon": -73.4, "zoom": 4}
        , {"nam":"Connecticut"       , "lat": 41.6 , "lon": -72.6, "zoom": 8}
        , {"nam":"Delaware"          , "lat": 38.9 , "lon": -75.4, "zoom": 8}
        , {"nam":"Maryland"          , "lat": 38.9 , "lon": -77.0, "zoom": 7}
        , {"nam":"Maine"             , "lat": 44.8 , "lon": -68.8, "zoom": 6}
        , {"nam":"Massachusetts"     , "lat": 42.4 , "lon": -71.7, "zoom": 7}
        , {"nam":"New Hampshire"     , "lat": 43.9 , "lon": -71.7, "zoom": 7}
        , {"nam":"New Jersey"        , "lat": 40.1 , "lon": -74.3, "zoom": 7}
        , {"nam":"New York"          , "lat": 42.4 , "lon": -75.4, "zoom": 6}
        , {"nam":"Pennsylvania"      , "lat": 40.2 , "lon": -76.8, "zoom": 6}
        , {"nam":"Puerto Rico"       , "lat": 18.2 , "lon": -66.5, "zoom": 8}
        , {"nam":"Rhode Island"      , "lat": 41.6 , "lon": -71.4, "zoom": 9}
        , {"nam":"Vermont"           , "lat": 43.9 , "lon": -72.6, "zoom": 7}
        , {"nam":"Virgin Islands"    , "lat": 18.1 , "lon": -64.8, "zoom": 9}
        , {"nam":"Virginia"          , "lat": 38.1 , "lon": -78.8, "zoom": 6}
        ] }                                                              
    , {"count":11 , "nam":"Southeast"                   , "zoom":0, "rows":
        [ {"nam":"Southeast Region"  , "lat": 27.2 , "lon": -84.0, "zoom": 4}
        , {"nam":"Alabama"           , "lat": 32.7 , "lon": -86.7, "zoom": 6}
        , {"nam":"Florida"           , "lat": 28.1 , "lon": -82.7, "zoom": 6}
        , {"nam":"Georgia"           , "lat": 32.5 , "lon": -83.0, "zoom": 6}
        , {"nam":"Louisiana"         , "lat": 31.3 , "lon": -91.7, "zoom": 6}
        , {"nam":"Mississippi"       , "lat": 32.7 , "lon": -89.5, "zoom": 6}
        , {"nam":"North Carolina"    , "lat": 35.7 , "lon": -80.0, "zoom": 6}
        , {"nam":"Puerto Rico"       , "lat": 18.2 , "lon": -66.5, "zoom": 8}
        , {"nam":"South Carolina"    , "lat": 33.5 , "lon": -80.9, "zoom": 7}
        , {"nam":"Texas"             , "lat": 32.3 , "lon": -99.2, "zoom": 5}
        , {"nam":"Virgin Islands"    , "lat": 18.1 , "lon": -64.8, "zoom": 9}
        ] }                                                             
    , {"count":6 , "nam":"Southwest and Pacific Islands", "zoom":2, "rows":
        [ {"nam":"Southwest Region"  , "lat": 15.2 , "lon":-167.7, "zoom": 3}
        , {"nam":"American Samoa"    , "lat":-14.3 , "lon":-170.7, "zoom":11}
        , {"nam":"California"        , "lat": 37.1 , "lon":-120.1, "zoom": 5}
        , {"nam":"Guam"              , "lat": 13.45, "lon": 144.8, "zoom":10}
        , {"nam":"Hawaii"            , "lat": 20.0 , "lon":-157.5, "zoom": 7}
        , {"nam":"Northern Marianas" , "lat": 15.07, "lon": 145.7, "zoom":10}
        ] }
    , {"count":5 , "nam":"Northwest"                    , "zoom":0, "rows":
        [ {"nam":"Northwest Region"  , "lat": 56.2 , "lon":-140.9, "zoom": 3}
        , {"nam":"Alaska"            , "lat": 63.6 , "lon":-151.0, "zoom": 3}
        , {"nam":"Idaho"             , "lat": 45.4 , "lon":-114.3, "zoom": 6}
        , {"nam":"Oregon"            , "lat": 44.1 , "lon":-120.4, "zoom": 6}
        , {"nam":"Washington"        , "lat": 47.2 , "lon":-120.7, "zoom": 6}
        ] }                                                             
    , {"count":7 , "nam":"Great Lakes"                  , "zoom":0, "rows":
        [ {"nam":"Great Lakes Region", "lat": 44.1 , "lon": -83.7, "zoom": 5}
        , {"nam":"Illinois"          , "lat": 40.3 , "lon": -88.9, "zoom": 6}
        , {"nam":"Indiana"           , "lat": 39.9 , "lon": -85.9, "zoom": 6}
        , {"nam":"Michigan"          , "lat": 43.5 , "lon": -84.5, "zoom": 6}
        , {"nam":"New York"          , "lat": 42.4 , "lon": -75.4, "zoom": 6}
        , {"nam":"Ohio"              , "lat": 40.4 , "lon": -82.5, "zoom": 7}
        , {"nam":"Wisconsin"         , "lat": 44.9 , "lon": -89.5, "zoom": 6}
        ] }                                                            
    ]                                      
};

// Global variables:
var region, map, tooltip, gicons = [], gmarkers = [];

setKey();

function setKey() {
    // 20090727jdr Set up the Google Maps key.

    //= This "if" copied from http://maps.forum.nu/key.js
    if (top.location != location) {
        // 20090529jdr Try to understand how this code works and why it might be useful/necessary.
        // alert("top.location: " + top.location + ". location: " + location + ". top.location.href: " + top.location.href + ". document.location.href: " + document.location.href + ".");
        top.location.href = document.location.href ;
    }

    //= Key copied from the one used in Ben's work in/before 2008
    //{ var myKey = 'ABQIAAAA0aLYzrb5aBzfV6B1vLUpAhT7wlOBrqW_zBt-W5UZuVbOdm59aRRuXEtKYLCfPFZhCd_dIpRtrZfeFQ';
    //= Key copied from the one IMSG put in at http://beta.darrp.noaa.gov/static/map.js
    //var myKey = 'ABQIAAAAJMkRmWxNa4CB8npAEameCxSTBvto71siV878NO8Q9b2i4rBO6BRgxliW2cYRvjVjg3PfHltzs0AHZQ';
    var myKey = 'ABQIAAAAoRNr03UW1E22eX3gu056zhQeyM-D8JF2ii1q4n1XrJtdI9tMmhS8loeXMF0qWNbWMCu6MWzvuAOZCg';

    var scriptTag = '<' + 'script src="http://maps.google.com/maps?'
            + 'file=api&v=2.100&key=' + myKey + '">' + '<' + '/script>';
    document.write(scriptTag);
}

function initPage() {
    if (!GBrowserIsCompatible()) return;

    getRegion();
    initMapView();
    // GDownloadUrl("map_markers", loadMarkers);
    initSymbols(gicons);  // HTML legend table is returned but not used now.
    initZoom();
    //regionform('regions.xml');
    initData();
}

function exitPage() {
    GUnload();
}

function getRegion() {
    // 20090727jdr Determine which region we're in and set the global region variable.
    for (var i = 0; i < regions.count; i++) {
        // If the first word of the title equals the first word of the nam...
        if (document.title.split(" ")[0] == regions.rows[i].nam.split(" ")[0]) {
            region = regions.rows[i];
            break;
        }
    }
}

function initMapView() {
    var mapdiv = document.getElementById("mapd");
    map = new GMap2(mapdiv);
    map.enableScrollWheelZoom();// 20090915jdr Per Ben's request
    // GEvent.addListener(map, "click", handleMapClick);
    map.addMapType(G_PHYSICAL_MAP);
    // map.addControl(new GMapTypeControl());
    map.addControl(new GMenuMapTypeControl());
    map.addControl(new GLargeMapControl());  // With +/- and slider zoom.
    // map.addControl(new GSmallMapControl());  // With +/- zoom only.
    map.addControl(new GOverviewMapControl());

    // Copied from incidentNews.js
    GEvent.addListener(map, "click", handleMapClick);

    // Set the initial map center/zoom.
    var subr = region.rows[region.zoom];
    map.setCenter(new GLatLng(subr.lat, subr.lon), subr.zoom);

    //setMapType must come afer setCenter
    map.setMapType(G_PHYSICAL_MAP);

    // ====== set up marker mouseover tooltip div ======
    tooltip = document.createElement("div");
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility="hidden";
}

function initSymbols(ai) {
    //- 20090601jdr Populate an array of information (ai) about icons for
    //- incident types; set up the legend HTML.

    var symb = {   "count":5
                ,"subhead":"DARRP Priority Cases FY2009"
                ,    "sha":statPath + "shadow-"  // Shadow file path
                ,   "rows":  // h/v - icon horizontal and vertical size; ah/av icon anchor; sh/sv shadow size; ih/iv info window anchor
        [ {"nam":"Hazardous Waste Site"       , "fil":"hazwastesite"  , "h":15, "v":13, "ah": 7, "av": 6, "sh":22, "sv":13, "ih": 7, "iv":6}
        , {"nam":"Oil Spill Case"                  , "fil":"oilspill"      , "h":15, "v":15, "ah": 8, "av": 8, "sh":23, "sv":15, "ih": 8, "iv":8}
        , {"nam":"Hazardous Materials Release", "fil":"hazmatrelease" , "h":15, "v":14, "ah": 7, "av": 7, "sh":23, "sv":14, "ih": 7, "iv":7}
        , {"nam":"Special Project"            , "fil":"specialproject", "h":12, "v":13, "ah": 6, "av": 6, "sh":19, "sv":13, "ih": 6, "iv":6}
        , {"nam":"Ship Grounding"             , "fil":"shipgrounding" , "h":23, "v":15, "ah":20, "av":10, "sh":31, "sv":15, "ih":11, "iv":7}
        ]  // Need to fix the iconAnchor, Shadow image, shadowSize and infoWindowAnchor. Since when??
    };

    var th, nam, fil, td;
    th  = '<tr>';
    th +=     '<th align="center" colspan="2">';
    th +=         symb.subhead;
    th +=         '<hr style="margin: 0px;" />';
    th +=     '</th>';
    th += '</tr>';

    for (var i=0; i<symb.count; i++) {
        nam = symb.rows[i].nam;
        fil = symb.rows[i].fil;
        ai[nam]                  = new GIcon(G_DEFAULT_ICON
                                 , statPath + fil + ".png");
        ai[nam].image            = statPath + fil + ".png";
        ai[nam].printImage       = statPath + fil + ".gif";
        // ai[nam].mozPrintImage    = statPath + fil + ".moz.gif";
        ai[nam].mozPrintImage    = statPath + fil + ".gif";
        ai[nam].iconshadow       = symb.sha + fil + ".png";
        ai[nam].printShadow      = symb.sha + fil + ".gif";
        ai[nam].iconSize         = new  GSize(symb.rows[i].h , symb.rows[i].v );
        ai[nam].iconAnchor       = new GPoint(symb.rows[i].ah, symb.rows[i].av);
        ai[nam].shadowSize       = new  GSize(symb.rows[i].sh, symb.rows[i].sv);
        ai[nam].infoWindowAnchor = new GPoint(symb.rows[i].ih, symb.rows[i].iv);

        td  = '<tr>';
        td +=     '<td align="right"><img src="' + ai[nam].image + '" /></td>';
        td +=     '<td>' + nam                                   +     '</td>';
        td += '</tr>';
    }

    return '<table border="0">' + th + td + '</table>';
}

function initZoom() {
    var html, subr, zoomdiv, zoomtd;
    html  = '<span class="lege">' + regions.subhead + '</span><br />';
    html += '<select id="regionpicker" name="subregion" size="' + region.count + '" style="max-width: 144;" onclick="regionchange(this)">';
          
    for (var i=0; i<region.count; i++) {
        subr = region.rows[i];
        html += '<option value="map.setCenter(new GLatLng(' + subr.lat + ', ' + subr.lon + '), ' + subr.zoom + ');"' + ((i == region.zoom) ? 'selected="selected"' : '') + '>'
             +      subr.nam
             +  '</option>';
    }
    html += '</select>';
    //document.getElementById("zoomto").style.maxWidth=134;
    zoomdiv = document.getElementById("zoomto")
    zoomdiv.innerHTML = html;
    zoomdiv.parentNode.style.backgroundColor = legendBackgroundColor;

    // Find the legend file.
    document.getElementById("Legend").src = legendFile;

}

function regionform(file) {
    // 20080524 jdr
    // import the region information from the given xml file; write a form object; insert an option for each region
    // NOTE: the JavaScript of the Google Maps api command is stored in the value of the select option
    var regionsxml = getxml(file);
    if (! regionsxml) {
        // Browser does not support XMLHttpRequest object
        return;
    }
    var regions = regionsxml.getElementsByTagName("region");
    var subhead, lat, lon, zoom;
    subhead = regionsxml.documentElement.attributes[0].childNodes[0].nodeValue;

    var html = '<b>' + subhead + '</b><br />';
    html += '<select id="regionpicker" name="regions" size="6" onclick="regionchange(this)">';

    for (var i=0; i<regions.length; i++) {
        lat =       regions[i].attributes[1].childNodes[0].nodeValue * 1;
        lon =       regions[i].attributes[2].childNodes[0].nodeValue * 1;
        zoom =      regions[i].attributes[3].childNodes[0].nodeValue * 1;
        html +=     '<option value="map.setCenter(new GLatLng(' + lat + ', ' + lon + '), ' + zoom + ');">';
        html +=         regions[i].attributes[0].childNodes[0].nodeValue;
        html +=     '</option>';
    }
    html += '</select>';
    document.getElementById("navi").innerHTML = html;
}

function regionchange(selectbox) {
    // 20080623 jdr
    // called by selection of region from picklist.
    // the JavaScript zoom-to lat/long/zoom instructions are stored in the value column of the picklist
    eval(selectbox.options[selectbox.selectedIndex].value);
}

function getxml(xmlfile) {
    //- 20080622jdr Load an xml document and return the document object.
    try {           // Internet Explorer
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    }
    catch(e) {
        try {       // Firefox, Mozilla, Opera, etc.
            xmlDoc = document.implementation.createDocument("", "" ,null);
        }
        catch(e) {
            alert(e.message);
            return false;
        }
    }
    xmlDoc.async=false;
    xmlDoc.load(xmlfile);
    return xmlDoc;
}


var request;

function initData() {
    // Read the data from the .xml file
    request = GXmlHttp.create();
    request.open("GET", dataFile, true);
    request.onreadystatechange = handleHttpResponse;
    request.send(null);
}

function handleHttpResponse() {
    if (request.readyState == 4) {
        var xmlDoc = GXml.parse(request.responseText);

        // get the array of markers and loop through it
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

        for (var i=0; i<markers.length; i++) {
            // obtain the attribues of each marker
            function gAt(attr) {return markers[i].getAttribute(attr);}
            // darrpregion is Northeast, Southeast, Southwest and Pacific Islands, Northwest or Great Lakes
            if (gAt("darrpregion") == region.nam) {
                var name = gAt("html");
                var lat = parseFloat(gAt("lat"));
                var lng = parseFloat(gAt("lng"));
                //= 20090921jdr Exclude zero lat/longs.
                if ((lat == 0) && (lng == 0)) continue;
                var point = new GLatLng(lat, lng);
                var icontype = gAt("icontype");

                // repparty seems to be included in repname... var repparty    = gAt("repparty");

                var html = '<table>';

                html += htRow('Name:'                  , htA(gAt("DARRPURL"), name));
                html += htRow('Incident Type:'         , icontype);
                html += htRow('Latitude:'              , lat);
                html += htRow('Longitude:'             , lng);
                html += htRow('City:'                  , gAt("city"));
                html += htRow('County:'                , gAt("county"));
                html += htRow('State:'                 , gAt("state"));
                html += htRow('DARRP Region:'          , gAt("darrpregion"));
                html += htRow('EPA Region:'            , gAt("epa"));
                html += htRow('EPA Facility ID:'       , gAt("EPAFacID"));
                html += htRow('NOAA Waste Site Report:', htA(gAt("wsrurl"), 'Waste Site Report'));
                html += htRow('Coast Guard Region:'    , gAt("coastguard"));
                html += htRow('Congressional District:', gAt("congdist"));
                //{ 20090923jdr Removed Representative and Senators from display in the bubble.
                //{ html += htRow('Representative:', htA(gAt("repurl") , gAt("repname")));
                //{ html += htRow('Senator:'       , htA(gAt("Sen1URL"), gAt("Sen1"), gAt("Sen1Party")));
                //{ html += htRow('Senator:'       , htA(gAt("sen2URL"), gAt("Sen2"), gAt("Sen2Party")));

                html += '</table>';
                createMarker(point, name, html, icontype, gAt("category"));
            }
        }
    }
}

function createMarker(point, name, html, icontype, category) {
    var marker = new GMarker(point, gicons[icontype]);
    marker.myname = name;
    marker.tooltip = '<div class="tooltip"><nobr>' + name + '<\/nobr><\/div>';
    marker.mycategory = category;
    GEvent.addListener(marker, "click"    , function() { marker.openInfoWindowHtml(html)  ; });
    gmarkers.push(marker);
    map.addOverlay(marker);
    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker, "mouseover", function() { showTooltip(marker)              ; });        
    GEvent.addListener(marker, "mouseout" , function() { tooltip.style.visibility="hidden"; });        
}

function showTooltip(marker) {
    // ====== This function displays the tooltip ======
    // it can be called from an icon mousover or a side_bar mouseover
    tooltip.innerHTML = marker.tooltip;
    var point  = map.getCurrentMapType().getProjection().fromLatLngToPixel(
            map.fromDivPixelToLatLng(new GPoint(0,0), true), map.getZoom());
    var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(
            marker.getPoint(), map.getZoom());
    var anchor = marker.getIcon().iconAnchor;
    var width  = marker.getIcon().iconSize.width;
    var height = tooltip.clientHeight;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(
              offset.x - point.x - anchor.x + width
            , offset.y - point.y - anchor.y - height)); 
    pos.apply(tooltip);
    tooltip.style.visibility = "visible";
}

function htRow(label, value) {
    // 20081010 jdr
    // Produce an HTML table row for the Google map balloon that appears when users click an icon on the map.
    // Eventually these filters should be moved to the routine that produces the xml file.
    if ((typeof(value) != "number") && (value==""))           return "";
    if ((typeof(value) != "number") && (value==" "))          return "";
    // if (label=="Latitude:" && value=="0") return "";
    if (label=="EPA Region:"      && value=="0")              return "";
    if (label=="EPA Facility ID:" && value=="?")              return "";
    if (label=="EPA Facility ID:" && value=="NA")             return "";
    if (label=="EPA Facility ID:" && value=="No Facility ID") return "";
        /*
*/
    return '<tr><td>' + label + '</td><td>' +  value + '</td></tr>';
}

function htA(target, value, more) {
    // 20081010 jdr
    // Produce an HTML "a" tag for the Google map balloon that appears when users click an icon on the map.
    // more is used for the Senator party affiliation, if applicable.
    if (value=="") return "";
    if (value==" ") return "";
    
    var noWSR = (value=="Waste Site Report") ? "" : value;  // In the case of a self-reference URL (per this list) eturn the Name, Representative or Senator as plain text but don't bother returning "Waste Site Report" as plain text.
    if (target=="http://www.darrp.noaa.gov/greatlakes/index.html") return noWSR;
    if (target=="http://www.darrp.noaa.gov/northeast/index.html")  return noWSR;
    if (target=="http://www.darrp.noaa.gov/northwest/index.html")  return noWSR;
    if (target=="http://www.darrp.noaa.gov/southeast/index.html")  return noWSR;
    if (target=="http://www.darrp.noaa.gov/southwest/index.html")  return noWSR;
        /* 20090917jdr Now that the database has empty wsrurl fields, check for
                   these as well and don't include that line in the bubble. */
    if (target=="") return noWSR;

    return '<a href="' + target
        + '" target="_BLANK">' + value
        + ( (more) ? ' (' + more + ')' : '' )
        + '</a>';
}


/******************************
* Copied from incidentNews.js
******************************/

    function handleMapClick(overlay, point)
{
	// Handle user clicks on the map
	// code idea from http://mapki.com/wiki/Marker_Optimization_Tips
	
	// we need a check in case the overlay is the info window
	// only our markers will have a .orr_id property
	
	if (overlay && overlay.orr_id)
	{
		//overlay.openInfoWindowHtml(overlay.orr_id);
		var index = marker_ids[overlay.orr_id];
		overlay.openInfoWindowHtml(marker_info[index]);
	}
	else if (point)
	{
		showClickPt(point);
	}
}

function showClickPt(point)
{
	// show (lat,lon) user's click position on the map
	if (point)
	{
		var latabs = Math.abs(point.y);
		var lngabs = Math.abs(point.x);
		var latdeg = Math.floor(latabs);
		var lngdeg = Math.floor(lngabs);
		var latmin = (latabs - latdeg) * 60;
		var lngmin = (lngabs - lngdeg) * 60;
		var lathem = (point.y > 0) ? "N" : "S";
		var lnghem = (point.x > 0) ? "E" : "W";
						
		var msg = "Click point:&nbsp;";
		msg += latdeg+"&deg; "+latmin.toFixed(2)+"' "+lathem+" ("+point.y.toFixed(6)+")&nbsp;&nbsp;";
		msg += lngdeg+"&deg; "+lngmin.toFixed(2)+"' "+lnghem+" ("+point.x.toFixed(6)+")";
		
        // 20090804jdr lat/lon decimal-degrees-only click point for George
		//{ 20090915jdr Removed &deg;
        //{ msg = "Click point: " + point.y.toFixed(6) + "&deg;," + point.x.toFixed(6) + "&deg;";
        msg = "Click point: " + point.y.toFixed(6) + "," + point.x.toFixed(6);
        
        //= 20090915jdr Ben requested a table.
        msg  = "<table><tr>"
        msg +=     "<th>Click point (lat/long):&nbsp;</th>"
        msg +=     "<td>" + point.y.toFixed(6)    + "</td>"
        msg +=     "<td>" + point.x.toFixed(6)    + "</td>"
        msg += "</tr></table>"
        
        // Functions for finding the center and zoom of the map.
        var y = map.getCenter().lat();
        var x = map.getCenter().lng();
        var z = map.getZoom();
        // msg += "&nbsp;&nbsp;&nbsp;(Map center: " + y.toFixed(1) + "," + x.toFixed(1) + "; Map zoom: " + z + ")"

		document.getElementById("clickLoc").innerHTML = msg;
	}
}



//]]>