//Javascript code for the Pacific Institute Water Conflict Chrononology Google Map Page
//Created by Matthew Heberger, August 2009
//Dependencies: JSON, Google Maps API

//Initialize Global variables for map and geocoder so we can use them outside of functions
var map = null;
var jstr = null;
var zoomLevel = 2;
var midPoint = new GLatLng(0,0);
var gmarkers =[];

function initialize() {
// This function is tied to the body onload() event and will run when the page is loaded
  if (GBrowserIsCompatible()) {
    resizeMapDiv();
    map = new GMap2(document.getElementById("map"));
    map.enableScrollWheelZoom();
    map.setCenter(midPoint, zoomLevel);
    map.addControl(new GLargeMapControl());
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_PHYSICAL_MAP);
    map.addControl(new GMapTypeControl());
    
    //add points to the map
    loadNewData();
    }
  else{
    str = "<p><strong>This page needs javascript enable to show Google Maps.</strong></p>"
    document.getElementById('map_canvas').innerHTML=str;
    }
}

function createMarker(point,name,html, i) {
  // Create our numbered marker icon
  var numIcon = new GIcon(G_DEFAULT_ICON);
  z = i + 1;
  numIcon.image = "../images/markers/" + z + ".png";

  // Set up our GMarkerOptions object
  markerOptions = { icon:numIcon };
  var marker = new GMarker(point, markerOptions);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html, {maxWidth:500});
  });
  return marker;
}

//This function shows or hides the AJAX load image
function showImage(bShow){
  if (bShow){
    document.getElementById("ajaximg").style.display = 'block';}
  else{
    document.getElementById("ajaximg").style.display = 'none';}
}

function  writeBounds(b) {
//Just for debugging purposes
  x = document.getElementById('txt');
  var sw = b.getSouthWest();
  var ne = b.getNorthEast();
  str = "T: " + ne.lat() + ", B: " + sw.lat() + "; L: " + sw.lng() + ", R: " + ne.lng();
  x.innerHTML = x.innerHTML + "<br />" + str;
}
function  append(str) {
//Just for debugging purposes
  x = document.getElementById('txt');
  x.innerHTML = x.innerHTML + "<br />" + str;
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
  GEvent.trigger(gmarkers[i], "click");
}


function addpoints(markers){
gmarkers = [];
  for (var i=0; i<markers.length; i++) {
          var point = new GLatLng(markers[i].lat, markers[i].lng);
          if (i==0){
            map.setCenter(point,6);
            var bounds = new GLatLngBounds();
            bounds = map.getBounds();
          }
          var marker = createMarker(point, markers[i].label, markers[i].html, i);
          map.addOverlay(marker);
          gmarkers.push(marker);
          bounds.extend(point);
        }
  if (markers.length>0){
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var midLat = (ne.lat() + sw.lat())/2;
    var midLng = (ne.lng() + sw.lng())/2;
    
    midPoint = new GLatLng(midLat, midLng);
    zoomLevel = map.getBoundsZoomLevel(bounds);
    
    map.setCenter(midPoint,zoomLevel);

    }
}


function process_it(doc) {
    //Parse the JSON document
    var jsonData = JSON.parse(doc);

    //Write the number of results returned
    document.getElementById('num').innerHTML=jsonData.num;

    //Plot the markers
    addpoints(jsonData.markers);
    
    //Write out the list of points
    document.getElementById('txt').innerHTML = jsonData.html;
    
    //turn off the AJAX loader image
    showImage(false);

}


function loadNewData(){
  
  //First, remove any existing markers
  map.clearOverlays();
  
  //Figure out the viewport of the map
  //var bounds = map.getBounds();
  //var extent = {};
  //var southWest = bounds.getSouthWest();
  //var northEast = bounds.getNorthEast();
  //extent.top = northEast.lat();
  //extent.right=northEast.lng();
  //extent.bottom = southWest.lat();
  //extent.left = southWest.lng();
  
  //Read in the user's selection from the form
  var params = {}
  params.region=document.getElementById('region').value;
  params.conftype = document.getElementById('conftype').value;
  params.epoch = document.getElementById('epoch').value;
  
  //glom together into a single object
  var jstr = JSON.stringify(params);

  var url = '../../php/maplist.php?jstr='+jstr;
  GDownloadUrl(url, process_it);
  
  //Turn on the AJAX loader image
  showImage(true);
}

function ZoomToPoint(myLat, myLng, myZoom){
//re-centers the map and sets the zoom level to an appropriate level for a point
    var myPoint = new GLatLng(myLat, myLng);
    map.setCenter(myPoint,myZoom);
    
}

function ZoomFull(){
  map.setCenter(midPoint, zoomLevel);
  map.getInfoWindow();
  map.closeInfoWindow();
}

function getWindowHeight() {
    if (window.self&&self.innerHeight) {
        return self.innerHeight;
    }
    if (document.documentElement&&document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}

function resizeMapDiv() {
  //Resize the height of the div containing the map.
  //Do not call any map methods here as the resize is called before the map is created.
  var d=document.getElementById("map");
    var offsetTop=0;
    for (var elem=d; elem!=null; elem=elem.offsetParent) {
        offsetTop+=elem.offsetTop;
    }
    var height=getWindowHeight()-offsetTop-5;
    if (height>=0) {
        d.style.height=height+"px";
    }
  
  var d=document.getElementById("txt");
    var offsetTop=0;
    for (var elem=d; elem!=null; elem=elem.offsetParent) {
        offsetTop+=elem.offsetTop;
    }
    var height=getWindowHeight()-offsetTop-16;
    if (height>=0) {
        d.style.height=height+"px";
  }

}