//This file controls the google for the fgnet
//Created May 2008 Brannon Beames

if(GBrowserIsCompatible()) {
   // create the map
   var map = new GMap2(document.getElementById("fmap"));

   // load controls
   map.addControl(new GLargeMapControl());
   map.addControl(new GMapTypeControl());

   map.setCenter(new GLatLng(40.6,-112.2), 8);
   var overview = new GOverviewMapControl(new GSize(125,125));
   map.addControl(overview);

   // Create tooltip div
   // this div is used as a tooltip for station information when a user hovers over a station
   // the div will be repositioned to appear next to the station
   var globaltooltip = document.createElement("div");
   map.getPane(G_MAP_FLOAT_PANE).appendChild(globaltooltip);
   globaltooltip.style.visibility="hidden";

   //scroll wheel zoom, this is a new feature see
   //http://googlemapsapi.blogspot.com/2007/04/v278-go-ahead-scroll-your-mouse-wheels.html
   map.enableScrollWheelZoom();

   // Create message div
   // this div will appear when data is loading to notify the user
   var message = document.createElement("div");
   map.getPane(G_MAP_FLOAT_PANE).appendChild(message);
   message.style.visibility="hidden";
   message.innerHTML = "<div id=\"messdiv\">Stations Loading...</div>";
   
   // Create new icons
   // this icon will appear for each active fgnet station location
   var fgnet_icon = new GIcon();
   fgnet_icon.image = '../img/ballon/flashybug.gif';
   fgnet_icon.iconSize = new GSize(20, 20);
   fgnet_icon.iconAnchor = new GPoint(10, 20);
   fgnet_icon.infoWindowAnchor = new GPoint(5, 1);

   // Create Custom Marker
   // this will allow us to store additional information pertaining to a station marker
   // this is done by inheriting from the GMarker class to add extra functionality
   GMarker.prototype.addStationInfo = function(num,name,station_id) {
      this.stn_num = num;
      this.stn_name = name;
      this.stn_id = station_id;
   }

   // Add listener for move events
   // if the map is zoomed in far enough, stations are shown if the map is zoomed back out, the stations 
   // are removed to reduce clutter stations are also refreshed any time the map is panned to another location
   GEvent.addListener(map, "moveend", function() {
         if(map.getZoom() >= 8) {
               loadStations();
         } else {
            map.clearOverlays();
         }
   });

} else {
   alert("Sorry, your browser does not support the Google Maps API.  Upgrade your browser.");
}

//Functions  
  
// This function is called each time a station marker is added
// it formats the station's tooltip and adds event listeners for click, hover, etc.
function formatMarker(station) {
   var num = station.stn_num;
   var name = station.stn_name;
   var station_id = station.stn_id;
   var div_width = (7.9 * name.length) + 48;
   if(div_width < 110) div_width = 110;
   station.tooltip = "<div id=\"tooltip\" style=\"width:" + div_width + "px\">Id:"+num+'<br/>Name: ' + name + '</div>';
     
   // Add listener for marker click events
   // if a station icon is clicked, its corresponding id is displayed
   GEvent.addListener(station, "click", function() {
         close_mess();
         setPest(station);
         open_first();
         undoError();
         //undoDates("biodate","enddate");
         undoDates("enddate");
         close_second();
   });

   // Add listener for marker hover events
   // if the user hovers over a station icon, information about the station is displayed
   GEvent.addListener(station,"mouseover", function() {
         showTooltip(station);
   });
   GEvent.addListener(station,"mouseout", function() {
         globaltooltip.style.visibility="hidden";
   });
   return station;
}

// This is to open the div with the pest selection after a station is selected
function open_first() {
   var first  = document.getElementById('first');
   first.style.display = 'block';
}

// this function clears all the error that were left
// including background color and messages.
function undoError() {
   var theform = document.getElementById('pestForm');
   var len = theform.length;
   for (var n=0; n<len; n++) {
      if ((theform[n].type == "text") || (theform[n].type == "select-one"))
         theform[n].style.background = "white";
   }

   var id = "error";
   var x;
   if(document.getElementById) {
      x = document.getElementById(id);
      x.innerHTML = "";
   } else if (document.all) {
      x = document.all[id];
      x.innerHTML = "";
   }
}

//this clears the dates
function undoDates(element_id2) {
   //var elementId1 = document.getElementById(element_id1);
   var elementId2 = document.getElementById(element_id2);

   //elementId1.value = "";
   elementId2.value = "";
}

function tool() {
   var tool = document.getElementById('tool');
   tool.style.display = 'block';
   setTimeout('document.images["loading"].src = "./img/loading.gif"', 200);

   tool.style.backgroundImage = 'url(./img/loading.gif) no-repeat';

   //var tool = document.getElementById('tool');
   //tool.style.display = 'block';
}

function removetool() {
   var tool = document.getElementById('tool');
   tool.style.display = 'none';
}

//this sets end date to today
function todays_date(element_id) {
   var elementId = document.getElementById(element_id);
   var d = new Date();
   
   var month = d.getMonth()+1;
   if (month < 10) { month = "0"+month; }
   
   var day = d.getDate();
   if (day < 10) { day = "0"+day; }

   var year = d.getFullYear();
   var today = month + "-" + day + "-" + year;

   elementId.value = today;
}

// This is called on includes/ajax.php when a station pest is selected
function open_second(pest_id) {

   undoError();
   undoDates("enddate");
   //undoDates("biodate", "enddate");
   
   if(pest_id == "") {
      close_second();
   } else {

      var HTTP = {};
      // This is a list of XMLHttpRequest-creation factiory functions to try
      HTTP._factories = [
         function() {return new XMLHttpRequest(); },
         function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
         function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
      ];

      // When we find a factory that works, store it here.
      HTTP.factory = null;

      // Create and return a new XMLHttpRequest object.
      //
      // The first time we're called, try the list of factory functions until
      // we find one that returns a nonnull value and does not throw an
      // exception.  Once we find a working factory, remember it for later use.
      HTTP.newRequest = function() {
         if (HTTP._factory != null) return HTTP._factory();

         for(var i = 0; i < HTTP._factories.length; i++) {
            try {
               var factory = HTTP._factories[i];
               var request = factory();
               if (request != null) {
                  HTTP._factory = factory;
                  return request;
               }
            } catch(e) {
               continue;
            }
         }

         // If we get here, none of the factory candidates succeeded,
         // so throw an exception now and for all future calls.
         HTTP._factory = function() {
            throw new Error("XMLHttpRequest not supported");
         }
         HTTP._factory(); // Throw an error
      };

      // Create an XMLHttpRequest using the uitlity defined earlier
      var request = HTTP.newRequest();

      // Register an event handler to recieve asynchronous notifications.
      // This code says what to do with the response, and it appears in a nested
      // function her before we have even submitted the request
      request.onreadystatechange = function() {
         if (request.readyState == 4) { // If the request is finished
            if (request.status == 200) // If it was sucessful
               document.getElementById('bd').innerHTML=request.responseText;
            }
      } 

      var mystation_id = document.getElementById('station_id').value;
      var url = "includes/ajax2.php?station_id="+mystation_id +"&pest_id=" +pest_id;
      // make a Get request for a given URL. We don't pass a third argument,
      // so this is an asynchronous request
      request.open("GET", url, true);

      // We could set additional request headers here if we needed to.

      // Now send the request. Since it isa GET request, we pass null for
      // the body.  Since it is asyncvhronous, send() does not block but
      // returns immediately.
      request.send(null);

       var second = document.getElementById('second');
       second.style.display = 'block';

      
      // This will create todays date in the enddate id
      todays_date("enddate"); // the function need the id handed to it
      //if start date not biofix, make sure start_date has correct year
      var start_date = document.getElementById("biodate");
      changeStartYear();
   
   }
}

// this function opens that dates div (it must be block these are divs)
function close_second() {
   var second = document.getElementById('second');
   second.style.display = 'none';
}

// this closed the mess div that says select station
function close_mess() {
   var mess = document.getElementById('mess');
   mess.style.display = 'none';
}
   
// This function is called when the user hovers over a station marker
// the tooltip div is repositioned near the marker and becomes visible
function showTooltip(station) {
   globaltooltip.innerHTML = station.tooltip;
   globaltooltip.style.width = $("tooltip").style.width;
   var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
   var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(station.getPoint(),map.getZoom());
   var anchor = station.getIcon().iconAnchor;
   var width = station.getIcon().iconSize.width;
   var height = globaltooltip.clientHeight;
   var x = offset.x - point.x - anchor.x + width;
   var y = offset.y - point.y - anchor.y - height;
   var centerPoint = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getCenter(),map.getZoom());
   var mapWidth = map.getSize().width;
   var mapHeight = map.getSize().height;
   var ttWidthDOM = $("tooltip").style.width;
   var tooltipWidth = Math.floor(ttWidthDOM.substr(0,ttWidthDOM.length-2));
   if (offset.y - height - anchor.y < centerPoint.y - mapHeight/2 )
      y = y + height + anchor.y;
   if (offset.x + tooltipWidth - anchor.x + width > centerPoint.x + mapWidth/2)
      x = x - tooltipWidth - width; 
   var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
   pos.apply(globaltooltip);
   globaltooltip.style.visibility = "visible";
}
   
// AJAX call for loading station icons
// getweatherStationXml.php queries the database for all stations
// within the current map bounds
// the results are sent back to the parseXml function as XML
function loadStations() {
   map.clearOverlays();

   // show "Loading Stations" message
   var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
   var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getCenter(),map.getZoom());
   var pos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - point.x - 95,offset.y - point.y - 25));
   pos.apply(message);
   message.style.visibility="visible";

   var bounds = map.getBounds();
   var sw = bounds.getSouthWest();
   var ne = bounds.getNorthEast();
   var url = 'includes/getfruitStationsXML.php';  //This path is referenced starting at the parent file not the .js file.
   var pars = 'ne=' + ne.toUrlValue() + '&sw=' + sw.toUrlValue();

   var myAjax = new Ajax.Request(
         url,
         {
            method: 'post',
            parameters: pars,
            onComplete: parseXml
         });
}

// receives the XML results of the loadStations() AJAX call
// These results are parsed and used to create icons for the stations
// on the map
function parseXml(request)
{
   var responseData = request.responseXML;
   markers = responseData.getElementsByTagName("marker");

   for(var i=0; i<markers.length; i++) {
      var loc = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
            parseFloat(markers[i].getAttribute("lon")));
      var num = markers[i].getAttribute("num");
      var name = markers[i].getAttribute("name");
      var station_id = markers[i].getAttribute("st_id");
      var icontype = fgnet_icon;
      var station = new GMarker(loc,icontype);
      station.addStationInfo(num,name,station_id);
      map.addOverlay(formatMarker(station));
   }
   message.style.visibility="hidden";
}
   
// Resets the map to original state 
// this function is called when the user clicks to reset the map
function resetMap() {
   map.setCenter(new GLatLng(39.6,-111.5), 7);
}

// This function is called when a pest is selected from the google map
function setPest(station) {
   
   var HTTP = {};
   // This is a list of XMLHttpRequest-creation factory functions to try
   HTTP._factories = [
      function() {return new XMLHttpRequest(); },
      function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
      function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
   ];

   // When we find a factory that works, store it here.
   HTTP.factory = null;

   // Create and return a new XMLHttpRequest object.
   //
   // The first time we're called, try the list of factory functions until
   // we find one that returns a nonnull value and does not throw an
   // exception.  Once we find a working factory, remember it for later use.
   HTTP.newRequest = function() {
      if (HTTP._factory != null) return HTTP._factory();

      for(var i = 0; i < HTTP._factories.length; i++) {
         try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
               HTTP._factory = factory;
               return request;
            }
         } catch(e) {
            continue;
         }
      }

      // If we get here, none of the factory candidates succeeded,
      // so throw an exception now and for all future calls.
      HTTP._factory = function() {
         throw new Error("XMLHttpRequest not supported");
      }
      HTTP._factory(); // Throw an error
   };

   // Create an XMLHttpRequest using the uitlity defined earlier
   var request = HTTP.newRequest();

   // Register an event handler to recieve asynchronous notifications.
   // This code says what to do with the response, and it appears in a nested
   // function her before we have even submitted the request
   request.onreadystatechange = function() {
      if (request.readyState == 4) { // If the request is finished
         if (request.status == 200) { // If it was sucessful
            var spanElement = document.getElementById('ppest');
            spanElement.innerHTML = '';
            try {
               spanElement.innerHTML = request.responseText;
            } catch (e) {
               var wrappingElement = document.createElement('div');
               wrappingElement.innerHTML = request.responseText;
               spanElement.appendChild(wrappingElement);
            }
         }
      } 
   }

   var station_id = station.stn_id;
   var url = "includes/ajax.php?station="+station_id;
   // make a Get request for a given URL. We don't pass a third argument,
   // so this is an asynchronous request
   request.open("GET", url, true);

   // We could set additional request headers here if we needed to.

   // Now send the request. Since it isa GET request, we pass null for
   // the body.  Since it is asyncvhronous, send() does not block but
   // returns immediately.
   request.send(null);

   var mystation = document.getElementById('p_s_id');
   var mystation_id = document.getElementById('station_id');
   var mystation_name = document.getElementById('station_name');
   mystation.innerHTML = "Station: " + station.stn_name;
   mystation_id.value = station.stn_id;
   mystation_name.value = station.stn_name;
}

//This function changes the year of the start date based on the chosen end date.
function changeStartYear()
{
   var start_date = document.getElementById("biodate");
   if(start_date && start_date.type == "hidden") {
      var end_date = document.getElementById("enddate");
      if (end_date.value.length == 10) {
         var disabled_biodate = document.getElementById("biodateshown");
         start_date.value = start_date.value.substring(0,6) + end_date.value.substring(6,10);
         disabled_biodate.value = start_date.value;
      }
   }
}
