//<![CDATA[

// {{{ Fault Div class
/*
function FaultDiv(html) {
    this.html = html ;
}
// subclass the GControl
FaultDiv.prototype = new GControl(true,false);
// create the div
FaultDiv.prototype.initialize = function(map) {
    var container = document.createElement("div");

    var faults_div = document.createElement("div");
    faults_div.innerHTML=this.html
    container.appendChild(faults_div);

    zoomInDiv.appendChild(document.createTextNode("Load/unload a fault zone"));
    GEvent.addDomListener(zoomInDiv, "click", function() {
        map.zoomIn();
    });

    map.getContainer().appendChild(container);
    return container;
}
// give it a default position
FaultDiv.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,260));
}
*/
// }}} Fault Div class

var polyline = [], map, minzoom = 13, staicon = {}, baseIcon = {}, color, mag, nowSecs, size, anzaMarkers = [], faultid, faultsect, sectname;

function createMarkerTabs(point, tab1, tab2, time, plotmag) {
    var mydate = (new Date()).getTime();
    nowSecs = parseInt(mydate / 1e3, 10);
    mag = Math.round(parseInt(plotmag, 10));
    if ((nowSecs - 6 * 60 * 60) < time) { // earthquake in the last 6 hours
        color = "red";
    } else if ((nowSecs - 12 * 60 * 60) < time) { // earthquake in the last 12 hours
        color = "orange";
    } else if ((nowSecs - 24 * 60 * 60) < time) { // earthquake in the last day
        color = "yellow";
    } else if ((nowSecs - 3 * 24 * 60 * 60) < time) { // earthquake in the last 3 days
        color = "green";
    } else if ((nowSecs - 7 * 24 * 60 * 60) < time) { // earthquake in the last week
        color = "blue";
    } else { // earthquake older than a week ago
        color = "gray";
    }
    if (mag === 10) {
        size = 92;
    } else if (mag === 9) {
        size = 76;
    } else if (mag === 8) {
        size = 62;
    } else if (mag === 7) {
        size = 50;
    } else if (mag === 6) {
        size = 40;
    } else if (mag === 5) {
        size = 32;
    } else if (mag === 4) {
        size = 25;
    } else if (mag === 3) {
        size = 19;
    } else if (mag === 2) {
        size = 14;
    } else if (mag === 1) {
        size = 9;
    } else {
        size = 7;
    }

    baseIcon.image = "http://eqinfo.ucsd.edu/images/googleicons/eqs/" + color + "_" + mag + ".gif";
    baseIcon.iconSize = new GSize(size, size);

    baseIcon.iconAnchor = new GPoint(11, 11);
    baseIcon.infoWindowAnchor = new GPoint(11, 11);

    var marker = new GMarker(point, baseIcon);
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowTabsHtml([new GInfoWindowTab("Date-Time", tab1), new GInfoWindowTab("Location", tab2)]);
    });
    return marker;
}

function unloaddata(id, sections) {
    if( sections > 0 ) {
        for (var i = 0;i < parseFloat(sections, 10);i++) {
            sectname = id + "_" + i;
            map.removeOverlay(polyline[sectname]);
        }
    } else {
        map.removeOverlay(polyline[id]);
    }
}

function loaddata(id) {
    var sections;
    $.ajax({
        type: "GET",
        url: "/xml/" + id + ".xml", 
        dataType: "xml",
        async: false,
        success: function (data) {
            $(data).find("markers").each(function () {
                sections = $(this).find("sections").length;
                if (sections === 0) {
                    var socalpoly = [];
                    $(this).find("marker").each(function () {
                        var fltmarkers = $(this);
                        var point = new GLatLng(parseFloat(fltmarkers.attr("lat"), 10), parseFloat(fltmarkers.attr("lng"), 10));
                        socalpoly.push(point);
                    });
                    polyline[id] = new GPolyline(socalpoly, "#990000", 4, 0.8);
                    var bubbletext = id.replace(/_/g, " ");
                    GEvent.addListener( polyline[id], "click", function( socalpoly ) {
                        map.openInfoWindow(socalpoly, '<p style="font-weight:bold;text-transform:uppercase;">'+bubbletext+'</p>' );
                    });
                    map.addOverlay(polyline[id]);
                } else {
                    var nsect = 0;
                    $(this).find("sections").each(function () {
                        var sect = [];
                        $(this).find("marker").each(function () {
                            var fltmarkers = $(this);
                            var point = new GLatLng(parseFloat(fltmarkers.attr("lat"), 10), parseFloat(fltmarkers.attr("lng"), 10));
                            sect.push(point);
                        });
                        var namesec = id + "_" + nsect;
                        polyline[namesec] = new GPolyline(sect, "#990000", 4, 0.8);
                        var bubbletext = id.replace(/_/g, " ");
                        GEvent.addListener( polyline[namesec], "click", function( sect ) {
                            map.openInfoWindow(sect, '<p style="font-weight:bold;text-transform:uppercase;">'+bubbletext+'</p>' );
                        });
                        map.addOverlay(polyline[namesec]);
                        nsect++;
                    });
                }
            });
        },
        timeout: function () {
            alert("Data request timed out. Please try later.");
        },
        error: function () {
            alert('Request resulted in error. Check XML file is retrievable.');
        }
    });
    return sections;
}

function createStaMarker(stapoint, stacontent) {
    var stamarkerIcon = new GIcon(staicon);
    var stamarkerOptions = {icon: stamarkerIcon};
    var stamarker = new GMarker(stapoint, stamarkerOptions);
    GEvent.addListener(stamarker, 'click', function () {
        stamarker.openInfoWindowHtml(stacontent);
    });
    return stamarker;
}

function loadStas() {
    $.ajax({
        type: "GET",
        url: "/xml/anza_stas.xml",
        dataType: "xml",
        success: function (stas) {
            $(stas).find("station").each(function () {
                var stapoint = new GLatLng($(this).find("lat").text(), $(this).find("lon").text());
                var stacontent = "<p><strong>Station " + $(this).attr('name') + "</strong><br/>" + $(this).find("staname").text() + "</p>";
                var stamarker = createStaMarker(stapoint, stacontent);
                anzaMarkers.push(stamarker);
                map.addOverlay(stamarker);
            });
        },
        error: function () {
            alert("Could not load Anza station locations");
        }
    });
}

function loadquakes() {
    $.ajax({
        type: "GET",
        url: "/xml/anza_dbrecenteqs.xml",
        dataType: "xml",
        success: function (data) {
            $(data).find("hypocenter").each(function () {
                var event = $(this);
                var mag = event.find("magnitude").text();
                var magrnd = Math.round(mag);
                var auth = event.find("auth").text();
                var depth = event.find("depth").text();
                var localtime = event.find("local_timestring").text();
                var utctime = event.find("utc_timestring").text();
                var unixtime = Math.round(event.find("time").text());
                var lat = event.find("lat").text();
                var lng = event.find("lon").text();
                var eventpoint = new GLatLng(lat, lng);
                var eventmarker = createMarkerTabs(eventpoint, "<table class='googleMap'><tr><th>Local Time</th><td>" + localtime + "</td></tr><tr><th>UTC Time</th><td>" + utctime + "</td></tr></table>", "<table class='googleMap'><tr><th>Longitude</th><td>" + lng + "</td></tr><tr><th>Latitude</th><td>" + lat + "</td></tr><tr><th>Magnitude</th><td>" + mag + "</td></tr><tr><th>Depth (km)</th><td>" + depth + "</td></tr><tr><th>Author</th><td>" + auth + "</td></tr></table>", unixtime, magrnd);
                map.addOverlay(eventmarker);
            });
        },
        timeout: function () {
            alert("Data request for recent earthquakes timed out. Please try later.");
        },
        error: function () {
            alert("Could not load recent earthquakes. Check XML file is retrievable.");
        }
    });
}

function setupAnzaMarkers() {
    var mgr = new GMarkerManager(map);
    mgr.addMarkers(anzaMarkers, 0, 12);
    mgr.refresh();
}

// Create container for security warning
function HtmlControl(html) {
    this.html = html;
}

function load() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("googlemap"));
        map.addControl(new GScaleControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addMapType(G_PHYSICAL_MAP);
        var minimap = new GOverviewMapControl(new GSize(100, 100)); 
        map.addControl(minimap);
        map.setCenter(new GLatLng(33.5, -117), 8, G_PHYSICAL_MAP);
        map.enableDoubleClickZoom();
        map.enableScrollWheelZoom();
        baseIcon = new GIcon();

        staicon = new GIcon();
        staicon.image = "/deployments/anza/images/station_icon_ok.gif";
        staicon.iconSize = new GSize(26, 26);
        staicon.iconAnchor = new GPoint(8, 8);
        staicon.infoWindowAnchor = new GPoint(8, 17);

        HtmlControl.prototype = new GControl(true, false);
        HtmlControl.prototype.initialize = function (map) {
            var container = document.createElement('div');
            var extra = document.createElement('div');
            extra.innerHTML = this.html;
            container.appendChild(extra);
            map.getContainer().appendChild(container);
            return container;
        };

        // hide/show div based on zoom level
        var securityContent = new HtmlControl('<div id="securityLabel">For security reasons the locations of the stations have been removed for this level of zoom</div>' );
        GEvent.addListener(map, "zoomend", function(oldzoom,zoom){ 
            if (zoom >= minzoom){ 
                map.addControl(securityContent, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(20, 40)) );
            } else {
                map.removeControl(securityContent);
            } 
        });

        loadStas();
        loadquakes();
        window.setTimeout(setupAnzaMarkers, 0);

        $("input:checkbox").attr('checked', false);
        $("input:checkbox").click( function () {
            if( $(this).attr('checked') === true ) {
                faultid = $(this).attr("id");
                sect = loaddata(faultid);
                $(this).attr('checked', true);
                $(this).attr('rel', sect);
            } else {
                $(this).attr('checked', false);
                faultid = $(this).attr("id");
                faultsect = $(this).attr("rel");
                unloaddata( faultid, faultsect );
            }
        });
    }
}
//]]>
