var kmlUrl = 'http://klamathinstitute.org/tissue/kml.php';
var map;
var markerregistry = [];
var startbbox = new google.maps.LatLngBounds(
                    new google.maps.LatLng(40.5000, -124.0000),
                    new google.maps.LatLng(42.5000, -122.0000)
                );

window.onload = function() {
    var mapOptions = {
      center: new google.maps.LatLng(40, -120), zoom: 2,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);

    // add the KMZ of the basin region
    new google.maps.KmlLayer('http://klamathinstitute.org/bluegreen/basin.kmz', {map:map, preserveViewport:true, suppressInfoWindows:true } );

    // with the selector already set to the default, load the default as if it had been selected
    selectDate();
}

function selectMatrix() {
    var matrix = $('matrix').options[$('matrix').selectedIndex].value;

    new Ajax.Request('matrixdates.php', {
        method:'get',
        parameters: { matrix:matrix },
        onSuccess: function(req) {
            // purge the existing date choices
            $('date').options.length = 0;

            // populate the date selector with the new set of dates, appropriate for the new matrix
            var xml = req.responseXML;
            var dates = xml.getElementsByTagName('date');
            for (var i=0,l=dates.length ; i<l ; i++) {
                var date = dates[i].getAttribute('date');
                $('date').options[$('date').options.length] = new Option(date,date);
            }

            // select the first date on the list for them
            selectDate();
        }
    });
}

function selectDate() {
    var date = document.getElementById('date');
    date = date.options[date.selectedIndex].value;

    // delete the old markers from the map
    for (var i=0; i<markerregistry.length; i++) markerregistry[i].setMap(null);
    markerregistry.length = 0;

    // load the new KML and parse it into Markers; too bad GMJSAPIv3's KmlLayer doesn't work!
    var url = kmlUrl + '?' + Math.random() + '&date=' + date;
    downloadUrl(url, function(data) {
        var markers = data.documentElement.getElementsByTagName("Placemark");
        for (var i=0; i<markers.length; i++) {
            var marker = markers[i];
            var name = marker.getElementsByTagName('name')[0].firstChild.nodeValue;
            var description = marker.getElementsByTagName('description')[0];
            description = description.childNodes[1] ? description.childNodes[1].nodeValue : description.firstChild.nodeValue;
            var coords = marker.getElementsByTagName('Point')[0].getElementsByTagName('coordinates')[0].firstChild.nodeValue;
            var lon = parseFloat(coords.split(',')[0]);
            var lat = parseFloat(coords.split(',')[1]);
            var icon = marker.getElementsByTagName('Icon')[0].getElementsByTagName('href')[0].firstChild.nodeValue;

            // create the marker: location, custom icon, infowindow
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat,lon),
                title: name,
                icon: icon,
                description: description
            });
            google.maps.event.addListener(marker, "click", function() {
                var infowindow = new google.maps.InfoWindow({ content:this.description });
                infowindow.open(map, this);
            });
            marker.setMap(map);

            // add the marker to the registry for later deletion
            markerregistry[markerregistry.length] = marker;
        }
    });

    // fetch a new report from the server and render it in the box
    new Ajax.Updater('report', 'report.php', { method:'get', parameters:{date:date} });

    // reset the map's extent to the starting point so they can see everything
    map.fitBounds(startbbox);
}

function dateForward() {
    var date = document.getElementById('date');
    if (date.selectedIndex >= date.options.length) return false;
    date.selectedIndex++;
    selectDate();
}
function dateBackward() {
    var date = document.getElementById('date');
    if (date.selectedIndex <= 0) return false;
    date.selectedIndex--;
    selectDate();
}

function zoomTo(lat,lon) {
    var center = new google.maps.LatLng(lat,lon);
    map.setCenter(center);
    map.setZoom(17);
}

