/*
   ajax.js

   Contains the functions associated with AJAX functionality.
*/

/*
   ajaxInit()

   Tests for an AJAX compliant browser.  If one is found, it
   returns an XML HTTP Request object.  If not, false is returned
   by this function.

   This is based off of code from http://www.w3schools.com/ajax/ajax_browsers.asp.
*/

function ajaxInit() {
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    xmlHttp.overrideMimeType('text/xml');
    return xmlHttp;
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      //xmlHttp.overrideMimeType('text/xml');
      return xmlHttp;
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        //xmlHttp.overrideMimeType('text/xml');
        return xmlHttp;
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }
}



/*
   submitTime()

   Grabs rainfall data for a pre-defined set of time intervals. 

   TODO: Remove the def flag
*/

function submitTime(def) {

   // Check input

   // Get form element values
   syear = document.getElementById('syear').value;
   smonth = document.getElementById('smonth').value;
   sday = document.getElementById('sday').value;
   shour = document.getElementById('shour').value;
   eyear = document.getElementById('eyear').value;
   emonth = document.getElementById('emonth').value;
   eday = document.getElementById('eday').value;
   ehour = document.getElementById('ehour').value;

   //alert('syear: ' + syear + '\neyear: ' + eyear + '\nsmonth: ' + smonth + '\nemonth: ' + emonth);
   // Make the request
   var xmlHttp = ajaxInit();

   if (xmlHttp) {

     xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState == 4) {
           // Update the google map and side bar
           var xmlDoc = xmlHttp.responseXML.documentElement;
           
           //var nmarkers = xmlDoc.getElementsByTagName("marker");
           //fillinmap(nmarkers);
           //highlightCol('total24');
           
           markers = xmlDoc.getElementsByTagName("marker");
           changeTime('total24', 'rt24hour');
           
           // Redsiplay the submit button
           enableSubmit();
           
           //alert(nmarkers.length);
           //alert(xmlHttp.responseXML.documentElement);
           //alert(xmlHttp.responseXML);
           //alert(xmlHttp.getResponseHeaders());
        }
     };
   
     try {
         disableSubmit();
         
		 xmlHttp.open("POST", "rain_data.php", true);
		 xmlHttp.setRequestHeader('Content-Type',  "text/xml");
		 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		 xmlHttp.send('syear='+syear+'&smonth='+smonth+'&sday='+sday+'&shour='+shour+'&eyear='+eyear+
			'&emonth='+emonth+'&eday='+eday+'&ehour='+ehour+'&def='+def);
     } catch (e) {
          alert("Unable to make request, please try later...");
          enableSubmit();
     }
     
   }

   return false;
}

/*
    customTime()

    Calling this function polls the form on index.php, and queries
    for rain data within the selected time period.  When the results
    are ready, the Google Map and side bar table are updated to
    reflect the user's query.

*/
function customTime() {

   // Get form element values
   syear = document.getElementById('syear').value;
   smonth = document.getElementById('smonth').value;
   sday = document.getElementById('sday').value;
   shour = document.getElementById('shour').value;
   eyear = document.getElementById('eyear').value;
   emonth = document.getElementById('emonth').value;
   eday = document.getElementById('eday').value;
   ehour = document.getElementById('ehour').value;
   
   //alert('syear: ' + syear + '\neyear: ' + eyear + '\nsmonth: ' + smonth + '\nemonth: ' + emonth);

   // Initialize the XMLHttpRequest object
   var xmlHttp = ajaxInit();

   if (xmlHttp) {

     // Define what to do when data is ready
     xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState == 4) {

           // Update the google map and side bar
           var xmlDoc = xmlHttp.responseXML.documentElement;
           var nmarkers = xmlDoc.getElementsByTagName("marker");
           
           //alert('Number of results: ' + nmarkers.length + '\nSome data: ' + nmarkers[0].getAttribute("number"));
           
           numCustom++;

           // Add new data to markers
           j=0;
           for(i = 0; i < markers.length; i++) {
               // Check that the retrieved gage ids atch with the existing gage ids
               if(j < nmarkers.length && markers[i].getAttribute("number") == nmarkers[j].getAttribute("number")) {
				   markers[i].setAttribute("rtcustom_" + numCustom, nmarkers[j].getAttribute("custom_total"));
				   markers[i].setAttribute("missingcustom_" + numCustom, nmarkers[j].getAttribute("custom_missing"));
				   markers[i].setAttribute("custom_" + numCustom + "_stime", nmarkers[j].getAttribute("custom_stime"));
				   markers[i].setAttribute("custom_" + numCustom + "_etime", nmarkers[j].getAttribute("custom_etime"));
				   j++;
               } 
               // If not, then there was no data for this time period
               else {
                   markers[i].setAttribute("rtcustom_" + numCustom, "0.00");
				   markers[i].setAttribute("missingcustom_" + numCustom, "100");
				   markers[i].setAttribute("custom_" + numCustom + "_stime", "");
				   markers[i].setAttribute("custom_" + numCustom + "_etime", "");
               }
           }

           // Re-display the map and table
           updateMarkers('rtcustom_' + numCustom);
           highlightCol('totalcustom');

           // Update display time
           //alert('syear: ' + syear + '\neyear: ' + eyear + '\nsmonth: ' + smonth + '\nemonth: ' + emonth);
           updateDisplayTime(monthToString(smonth) + " " + sday + ", " + syear + " " 
                             + militaryTo12Time(shour), 
                             monthToString(emonth) + " " + eday + ", " + eyear + " " 
                             + militaryTo12Time(ehour));
           
           // Redisplay the submit button
           enableSubmit();
        }
     };
   
     // Send the request...
     try {
         // Show the user that we are working...
         disableSubmit();
         
         // Open the request
         xmlHttp.open("POST", 'custom_data.php?syear='+syear+'&smonth='+smonth+'&sday='+sday+'&shour='+shour+'&eyear='+eyear+
		'&emonth='+emonth+'&eday='+eday+'&ehour='+ehour, true);
         xmlHttp.setRequestHeader('Content-Type',  "text/xml");
         xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
         
         //alert('seding to custom_data.php?syear='+syear+'&smonth='+smonth+'&sday='+sday+'&shour='+shour+'&eyear='+eyear+
		//'&emonth='+emonth+'&eday='+eday+'&ehour='+ehour);
		
		 xmlHttp.send(null);
         //xmlHttp.send('syear='+syear+'&smonth='+smonth+'&sday='+sday+'&shour='+shour+'&eyear='+eyear+
		//'&emonth='+emonth+'&eday='+eday+'&ehour='+ehour);
     } catch (e) {
          alert("Unable to make request, please try later...  Error:" + e.message);
          enableSubmit();
     }

   }

   // return false so as to not reload the page when submit is clicked
   return false;
}


function enableSubmit() {
	var sub = document.getElementById('submit_button');
	sub.disabled = false;
	sub.value = "Submit Time";
}

function disableSubmit() {
	var sub = document.getElementById('submit_button');
	sub.disabled = true;
	sub.value = "Loading...";
}

/*
 * initialize_website()
 *
 * Performs necessary intialization, such as setting
 * the date and making the first query for the initial
 * data set.
 */

function initialize_website() {

	init_date();
	submitTime(0);

}
