// <![CDATA[

var mooringIcon;
var mooringList = [];
var requestedSiteId;
var plotParameter;
var prevPlotEl;


GMap2.prototype.addOverlays = function(arr) {
  for(var k in arr) { 
    this.addOverlay(arr[k]);
  }
}


GMap2.prototype.initLayout = function() { 
  this.addMapType(G_PHYSICAL_MAP);
  this.addControl(new GSmallMapControl());
  this.setCenter(new GLatLng(33.3,-118.9), 7);
  this.setMapType(G_PHYSICAL_MAP);
}


GIcon.prototype.setStyleMooring = function() { 
  this.image = "../mooring_ico.png";
  this.iconSize = new GSize(36,36);
  this.iconAnchor = new GPoint(20,29);
  this.infoWindowAnchor = new GPoint(26,5);
  this.imageMap = [
    22,0, 30,4, 28,18, 34,27, 25,34,
    13,34, 0,26, 14,10, 15,1
  ];
}


// Uses: 
//  set_url_parameter(defaultUrl, key, value)
//  set_url_parameter(key,value) -- default to current url
function set_url_parameter(ru,ji,jk) { 
  if( typeof(jk) == "undefined" ) { 
    jk = ji;
    ji = ru;
    ru = window.location.href;
  }
  var ix = ru.indexOf('?');
  var bu = (ix>=0) ? ru.substring(0,ix) : ru;
  var is = "";

  var hu = (ix>=0) ? ru.substring(ix+1) : '';
  var gy = hu.split("&");
  var bFound = false;
  for(var i=0;i<gy.length;i++) { 
    if( gy[i]=="" ) { 
      continue;
    }
    var ft = gy[i].split("=");
    if( ft[0] == ji ) { 
      ft[1] = jk;
      bFound = true;
    }
    is = is + "&" + ft[0] + "=" + ft[1];
  }
  if( !bFound ) { 
    is += "&" + ji + "=" + jk;
  }
  is = is.substring(1); // remove first &
  return bu + '?' + is + window.location.hash;
}


function get_url_parameter(ru,ji) { 
  if( typeof(ji) == "undefined" ) { 
    ji = ru;
    ru = window.location.href;
  }
  var ix = ru.indexOf('?');
  if( ix<0 ) { 
    return;
  }

  var hu = ru.substring(ix+1);
  var gy = hu.split("&");
  for (var i=0;i<gy.length;i++) {
    var ft = gy[i].split("=");
    if (ft[0] == ji) {
      return ft[1];
    }
  }
}


function load_map() { 

  // Finally start to load the map
  if(!GBrowserIsCompatible()) {
    alert("Your browser is not compatible with Google Maps v2");
    return false;
  }

  map = new GMap2(document.getElementById("Gmap"));
  if( !map ) {
    alert("This page was not designed for Google Maps");
    return false;
  }
  map.initLayout();

  mooringIcon = new GIcon();
  mooringIcon.setStyleMooring();

  return true;
}


function getBookmarkUrl(el) { 
  var url = location.href;
  if( typeof(requestedSiteId) != "undefined" ) { 
    url = set_url_parameter(url,"sid",requestedSiteId);
  }
  url = set_url_parameter(url,"ts",getPlotParameter());

  if( typeof(el) != "undefined" ) { 
    el.setAttribute("href",url);
    return true;
  } else { 
    location.assign(url);
  }
}

function handleStationClick(sta) { 
  var sid  = sta.getAttribute("id");
  var lat  = parseFloat(sta.getAttribute("lat"));
  var lng  = 0 - parseFloat(sta.getAttribute("lon"));
  var name = sta.getAttribute("name");

  // Update global parameter
  requestedSiteId = sid;

  // Hide the site table
  // var siteTable = document.getElementById("siteTable");
  // siteTable.style.display = "none";

  // Force zoom-in if we can see too much
  if( map.getZoom() < 9 ) { 
    map.setZoom(9);
  }

  // Check map size.  Shrink map to make room for text on left
  var gSize = map.getSize();
  if( gSize.width > 310 ) { 
    var gmap = document.getElementById("Gmap");
    gmap.style.width = "310px";
    map.checkResize();
  }

  // Add site text and update display status
  var pSiteName = document.getElementById("pSiteName");
  pSiteName.innerHTML = name;
  var pSiteLocation = document.getElementById("pSiteLocation");
  pSiteLocation.innerHTML = lat+"&deg;N, "+lng+"&deg;W";
  var GmapText = document.getElementById("GmapText");
  GmapText.style.display = "block";

  showPlots();

  // Show the plots available.
  var plotListings = document.getElementById("plotListings");
  plotListings.style.display = "block";

  // Show the tiny site table.
  var tiny = document.getElementById("siteTableSmall");
  tiny.style.display = "block";
}

function removeChildren(node) {
  if( node.hasChildNodes() ) {
    for( var i=node.childNodes.length;i>0;i--) {
      if( node.childNodes[i-1].hasChildNodes() ) {
        removeChildren(node.childNodes[i-1]); 
      }
      node.removeChild(node.childNodes[i-1]);
    }
  } 
} 

function Loader() { 
  this.initialize();
}
Loader.prototype = new Object();


Loader.prototype.initialize = function() { 
  this.semiphor = 0;
  this.visible  = 0;
  this.container = null;
  this.statusText = "Loading...";
  this.createLoadingObject();
}

Loader.prototype.createLoadingObject = function() { 
  if( typeof(this.obj) != "undefined" ) { 
    delete(this.obj);
  }

  var i0 = document.createElement("img");
      i0.setAttribute("src","loader.gif");

  var h = document.createElement("h4");
  h.appendChild(document.createTextNode(this.statusText));
  h.style.margin = "0 auto";
  h.style.padding = "0";
  h.style.color = "white";
  h.style.verticalAlign = "middle";
  h.style.textAlign = "center";

  this.obj = document.createElement("div");
  this.obj.style.textAlign = "center";
  this.obj.style.display = "block";
  this.obj.style.margin = "2em 1em";

  this.obj.appendChild(i0);
  this.obj.appendChild(h);
}


Loader.prototype.setStatusText = function(txt) { 
  this.statusText = txt;
  this.createLoadingObject();
}

Loader.prototype.increment = function(n) { 
  if( !n ) { 
    n = 1;
  }
  this.semiphor += n;
  this.redraw();
  return true;
}

Loader.prototype.decrement = function(n) { 
  if( !n ) { 
    n = 1;
  }
  this.semiphor -= n;
  this.redraw();
  return true;
}

Loader.prototype.redraw = function() { 
  if( !this.container ) { 
    alert("no container assigned");
    return false;
  }
  if( this.semiphor <= 0 ) { 
    if( this.obj.parentNode != null ) { 
      this.container.removeChild(this.obj);
    }
    this.visible = 0;
  }
  if( this.semiphor > 0 && !this.visible ) { 
    this.container.appendChild(this.obj);
    this.visible = 1;
  }
  return true;
}

Loader.prototype.setContainer = function(p) { 
  this.container = p;
}


function showPlots() { 
  var vars = ["temp","salt","v","u"];
  var pc = document.getElementById("PlotContainer");
  if( !pc ) { 
    return false;
  }
  pc.style.display = "none";
  removeChildren(pc);
  if( typeof(requestedSiteId) == "undefined" ) { 
    return true;
  }

  // Add a loader icon... 
  var loader = new Loader();
  loader.setContainer(pc);
  loader.setStatusText("Generating...");
  pc.style.display = "block";

  var ts0 = getPlotParameter();
  var ts1;
  if( ts0.indexOf(",") >= 0 ) { 
    var tmp = ts0.split(",");
    ts0 = tmp[0];
    ts1 = tmp[1];
  }

  for(var i=0,n=vars.length; i<n; i++ ) { 
    loader.increment();
    var obj = document.createElement("img");
    obj.setAttribute("height","200");
    obj.setAttribute("width","500");
    obj.setAttribute("alt",vars[i]);
    obj.setAttribute("title",vars[i]);
    obj.setAttribute("src",imageUrl(requestedSiteId,vars[i],ts0,ts1));
    obj.onload = function() { 
      loader.decrement();
    }
    pc.appendChild(obj);
  }
  return true;
}


function imageUrl(id,vid,ts0,ts1) {
  var url = "pcolor.php?id="+id+"&vid="+vid;
  if( typeof(ts0) != "undefined" ) {
    url += "&ts0="+ts0;
  }
  if( typeof(ts1) != "undefined" ) {
    url += "&ts1="+ts1;
  }
  return url;
}


function createMooring(station) { 
  var sid  = station.getAttribute("id");
  var lat  = parseFloat(station.getAttribute("lat"));
  var lng  = parseFloat(station.getAttribute("lon"));
  var name = station.getAttribute("name");

  var Otero = new GMarker(new GLatLng(lat,lng), mooringIcon);
  GEvent.addListener(Otero,"click",function() { 
    handleStationClick(station);
    var html = "<div class=\"infoWindow\">"+name+"</div>";
    Otero.openInfoWindow(html);
  });

  return Otero;
}


function createTinyTableRecord(tab,sta) { 
  var tbody = (tab.getElementsByTagName("tbody"))[0];
  // Create new record
  var tr = document.createElement("tr");

  // Station name
  var td = document.createElement("td");
  var a = document.createElement("a");
  a.setAttribute("href","?sid="+sta.getAttribute("id"));
  a.setAttribute("onclick", "javascript:triggerClick('"+
    sta.getAttribute("id")+"');return false;");
  a.appendChild(document.createTextNode(sta.getAttribute("name")));

  td.appendChild(a);
  tr.appendChild(td);
  tbody.appendChild(tr);
  return true;
}

function createTableRecord(tab,sta) { 
  var tbody = (tab.getElementsByTagName("tbody"))[0];

  // Create new record
  var tr = document.createElement("tr");

  // Station name
  var td = document.createElement("td");
  var a = document.createElement("a");
  a.setAttribute("href","?sid="+sta.getAttribute("id"));
  a.setAttribute("onclick", "javascript:triggerClick('"+
    sta.getAttribute("id")+"');return false;");
  a.appendChild(document.createTextNode(sta.getAttribute("name")));
  td.appendChild(a);
  tr.appendChild(td);

  // Lat
  td = document.createElement("td");
  td.appendChild(document.createTextNode(sta.getAttribute("lat")));
  tr.appendChild(td);

  // Lon
  td = document.createElement("td");
  td.appendChild(document.createTextNode(sta.getAttribute("lon")));
  tr.appendChild(td);

  // Add row
  tbody.appendChild(tr);
  return true;
}

function load_url_params() { 
  // Initialize the station
  var sid = get_url_parameter("sid");
  if( typeof(sid) != "undefined" ) { 
    requestedSiteId = sid;
  }

  // Initialize the time range
  var obj = document.getElementById("plotListings");
  var links = obj.getElementsByTagName("a");
  var ts = get_url_parameter("ts");
  if( typeof(ts) != "undefined" ) {
    var bSelected = false;
    for(var i=0;i<links.length;i++) {
      if( ts == getPlotParameter(links[i]) ) {
        selectPlot(links[i]);
        bSelected = true;
        break;
      }
    }
    if( !bSelected ) {
      selectPlot(links[0]);
    }
  } else {  
    selectPlot(links[0]);
  } 
  return true;
}


function load_moorings() { 
  var tab = document.getElementById("siteTable");
  if( !tab ) { 
    alert("no siteTable found.");
    return false;
  }
  var tiny = document.getElementById("siteTableSmall");
  if( !tiny ) { 
    alert("no siteTableSmall found.");
    return false;
  }

  // Get XML document with list of mooring locations.
  var url = "query.php?func=stations";
  GDownloadUrl(url,function(data,code) {
    var dom = GXml.parse(data);
    var stations = dom.getElementsByTagName("station");
    var moorings = new Array();
    for(var i=0,n=stations.length;i<n;i++) { 
      var sid = stations[i].getAttribute("id");
      mooringList[sid] = createMooring(stations[i]);
      createTableRecord(tab,stations[i]);
      createTinyTableRecord(tiny,stations[i]);
    }
    map.addOverlays(mooringList);
    if( typeof(requestedSiteId) != "undefined" ) { 
      triggerClick(requestedSiteId);
    }
  });
}



// Function: triggerClick(siteId)
// Executes a click on the GMarker object presented by siteId
function triggerClick(sid) { 
  GEvent.trigger(mooringList[sid],"click");
}


function getPlotParameter(link) { 
  if( typeof(link) == "undefined" ) { 
    link = prevPlotEl;
  }
  var href = link.getAttribute("href");
  return href.substring(href.indexOf("#")+1);
}

function selectPlot(el) { 
  el.className = "active";

  if( typeof(prevPlotEl) != "undefined" ) { 
    prevPlotEl.className = "";
    prevPlotEl.removeAttribute("class");
    prevPlotEl.removeAttribute("className");
  }
  prevPlotEl = el;
  showPlots();
}


/*
 * 1) Initialize a map, centered on sccoos
 * 2) Load the moorings via ajax.
 *    3) If sid present in moorings list, trigger click
 *       4) if zoom level < 9, zoom to 9
 *       5) if active plot is null, activate 2 week recent profiles
 */
function init_page() { 
  load_url_params();
  load_map();
  load_moorings();
}

window.onload = init_page;
// ]]>
