
////////////////////////////////////////////////////////////
//                                                        //
// Functions called from the HTML page                    //
//                                                        //
////////////////////////////////////////////////////////////



var currImage = new Object();
var cancel = 0;

/*
*  run some javascript from request
*  params:
*     request -- the product server request string
*/
function evalMyRequest (request) {
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
               var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updatePlot(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
}
}


function evalMapImageRequest (request) {
             
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
                       var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updateDataArea(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
	     }
}

function evalProfileRequest (request) {
  					
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
               var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updateProfileArea(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
  }
}

function evalTrajectoryPlot (request) {
  					
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
               var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updateTrajectoryArea(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
  }
}

function evalDataRequest (request) {
  					
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
               var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updateDataDiv(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
  }
}

function evalCancelRequest (request) {
  					
              var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {updateCancelDiv(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
}

function getGERequest (request) {
  					
  	      if (cancel == "1") {
		cancelRequest(request);
		cancel = 0;				
              } else {
              var bindArgs = {                           url: request,
                       mimetype: "text/plain",
                       preventCache:true,
                       error: function(type,error) {alert('Yo: ' +error.type + ' ' + error.message);},
                       load: function(type,data,event) {getGE(data,request);}
                };
               var request = dojo.io.bind(bindArgs);
  }
}




function getProfilePlot(myId, myVar) {

 Req.setOperation('osmc_profile_plot','LAS7');
 Req.removeConstraints();
 Req.addTextConstraint("p.platform_code", "=", myId );
 Req.setVariable('OSMC_new_schema', myVar);
 var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
 //window.open(URL,"OSMC_profile","status=1");
 evalProfileRequest(URL);

}

function getTSPlot(myId, myVar) {

 Req.setOperation('osmc_ts_plot','LAS7');
 Req.removeConstraints();
 Req.addTextConstraint("p.platform_code", "=", myId );
 Req.setVariable('OSMC_new_schema', myVar);
 Req.setProperty("ferret","use_ref_map", "true")
 var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
 //window.open(URL,"OSMC_profile","status=1");

 evalProfileRequest(URL);

}

function getTrajectoryPlot(myId, myVar, whatToPlot,myPlatform) {

 Req.setOperation('Extract_trajectories','LAS7');
 Req.removeConstraints();
 Req.addTextConstraint("ds.platform_code", "=", myId );
 if (myPlatform == 'XBT') {
        Req.addTextConstraint("sensor_type", "=", myPlatform);
 }
 Req.setVariable('OSMC_new_schema', myVar);
 Req.setProperty("ferret","use_ref_map", "true")
 Req.setProperty("ferret","colorBy", whatToPlot);
 // Req.setProperty("ferret","bathy", "detailed");
 Req.setProperty("ferret","topo", "detailed");
 var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
 evalTrajectoryPlot(URL);
// window.open(URL,"OSMC_profile","status=1");

 
}


function updateProfileArea(strJson,request) {
   if (strJson.indexOf("running") > 0) {
      hideDIV('dataWindow');
      hideDIV('profilePlot');
      turnOnWaitGif("waiting");
      setTimeout("evalProfileRequest('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
   } else if (strJson.indexOf("rror") > 0) {
      alert ("There was a problem getting the data");
      turnOffWaitGif("waiting");    
   } else {
      turnOffWaitGif("waiting");
      hideMapSelect();
      showDIV('profilePlot');
      document.getElementById('profilePlot').innerHTML=strJson;
   }
}

function updateTrajectoryArea(strJson,request) {
   if (strJson.indexOf("running") > 0) {
      hideDIV('dataWindow');
      hideDIV('profilePlot');
      hideDIV('trajectoryPlot');
      turnOnWaitGif("waiting");
      setTimeout("evalTrajectoryPlot('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
   } else if (strJson.indexOf("rror") > 0) {
      alert ("There was a problem getting the data");
      turnOffWaitGif("waiting");    
   } else {
      turnOffWaitGif("waiting");
      hideMapSelect();
      showDIV('trajectoryPlot');
      document.getElementById('trajectoryPlot').innerHTML=strJson;
   }
}



function closeProfileWindow() {
      hideDIV('profilePlot');
      showMapSelect();
}  

function closeTrajectoryWindow() {
      hideDIV('trajectoryPlot');
      showMapSelect();
}  

function updateDataDiv(strJson,request) {
   if (strJson.indexOf("waiting") > 0) {
      hideDIV('dataWindow');
      turnOnWaitGif("waiting");
      setTimeout("evalDataRequest('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
   } else if (strJson.indexOf("rror") > 0) {
      alert ("There was a Problem getting the profile plot");
      turnOffWaitGif("waiting");    
   } else {
      turnOffWaitGif("waiting");
      hideMapSelect();
      showDIV('dataWindow');
      document.getElementById('dataWindow').innerHTML=strJson;
   }
}

function updateCancelDiv(strJson,request) {
   if (strJson.indexOf("cancel") > 0) {
    //  hideMapSelect();
    //  showDIV('cancelWindow');
    //  document.getElementById('cancelWindow').innerHTML=strJson;
    //  alert ("Request cancelled");
   } else if (strJson.indexOf("rror") > 0) {
      alert ("There was a problem cancelling the request")
   } else {
     setTimeout("evalDataRequest(request)",1500);
 }
}

function closeDataWindow() {
      hideDIV('dataWindow');
      showMapSelect();

}  

function closeAboutWindow() {
      hideDIV('aboutOSMC');
      showMapSelect();
}  



function showAboutWindow() {
      hideMapSelect();
      showDIV('aboutOSMC');

}


function hideMapSelect() {
      myMapWidget.disable();
      myMapWidget.rubberBand.style.visibility = "hidden";
      myMapWidget.rubberBand_c.style.visibility = "hidden";
}

function showMapSelect() {
      myMapWidget.rubberBand.style.visibility = "visible";
      myMapWidget.rubberBand_c.style.visibility = "visible";
      myMapWidget.enable();
}


function getPlatformDataFromOSMC(myId, myVar)  {
 Req.setOperation('Insitu_extract_data_NQ','LAS7');
 Req.removeConstraints();
 Req.addTextConstraint("p.platform_code", "=", myId );
 Req.setVariable('OSMC_new_schema', myVar);
    var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
//    evalMapImageRequest(URL);
    evalDataRequest(URL);

}




function updateDataArea(strJson,request) {
   if (cancel == "1") {
          hideDIV('preWaiting');
	  hideDIV('waiting');
          myMapWidget.enable();    
          cancel = 0;     
   } else {
      if (strJson.indexOf("waiting") > 0) {
       document.getElementById('metaInformation').style["display"]="none";
 
       turnOnWaitGif("waiting");
       setTimeout("evalMapImageRequest('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
      } else {
       turnOffWaitGif("waiting");
       document.getElementById('metaInformation').style["display"]="block";
      document.getElementById('metaInformation').innerHTML=strJson;
     }
 }
}

function getGE(strJson,request) {
   if (strJson.indexOf("waiting") > 0) {
      turnOnWaitGif("waiting");
      setTimeout("getGERequest('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
   } else {
      turnOffWaitGif("waiting");
      URL = '../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString());
      window.open(URL,"ge","width=700,height=600");
//       document.location = URL;
//      window.location = URL;
//      window.location.reload();
//      alert(strJson);
   }
}



function setPlatSelect(choice) {
    document.getElementById("inputForm").platformSelect[choice].checked = true;
}

/*
* Either we get an error, a waiting status, or an actuall dojo response
* this function deals w/ all of them
*/
function updatePlot(strJson,request) {
   //alert(strJson);
   newImage = eval("(" + strJson + ")");
   var waitImg = document.getElementById('waiting');
   var ie = (document.all) ? 1 : 0;
   var myUserAgent = navigator.userAgent;
   var p = "display";
   var largeOffset = 0;
   if (cancel == "1") {
          hideDIV('preWaiting');
	  hideDIV('waiting');
          myMapWidget.enable();    
          cancel = 0;     
   } else {

    if (newImage.state == "error" ) {
      alert("Error in User Request");
      if (waitImg) {
          hideDIV('preWaiting');
	  hideDIV('waiting');
      }
      myMapWidget.enable();
      //setMyOperation('Insitu_extract_plot');
      //document.getElementById('inputForm').xy_range[0].selected = true;
      //submitML('OSMCImage', this.form);
      //setCoords('30','-90','390','90','g_box');
    } else if (newImage.state == "waiting") {
      if (waitImg) {
          //hideDIV('preWaiting');
          //showDIV('waiting');
          turnOffWaitGif('preWaiting');
          turnOnWaitGif('waiting');
      }
      if (notFirstTime) {
         myMapWidget.disable();
      }
      setTimeout("evalMyRequest('../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString()))",1500);
    } else if (newImage.state == "complete") {
         var args = {
                   'DOMNode' : document.getElementById('mapWidget'), // the container Node
                   'ondraw' : function () {displayMyCoords()},
                   'onafterdraw' : function () {setUpZoom()},
                   'plot_area' : {                                                       // defining the plot region within the image
                           'offX' : newImage.offX,
                           'offY' : newImage.offY,
                           'width' : newImage.width,
                           'height' : newImage.height
                   },
                   'img' : {                                                                //the image
                           'src' : newImage.url,
                           'width' : newImage.wholeImageWidth,
                           'height' :newImage.wholeImageHeight,
                           'extent' : {                                                     //coordinate extent of the image being passed
                               'x' : {
                                   'min' : newImage.lowX,
                                   'max' : newImage.highX
                               },
                               'y' : {
                                   'min' : newImage.lowY,
                                   'max' : newImage.highY
                               }
                           }
                       }
                  };


         myDBUrl = newImage.dburl;
         myNetCDFUrl = newImage.netCDF;
         if (debug == "true")  showDIV('showSQL');

// clear out old map Widget, unless it is the first time through
         if (notFirstTime)  myMapWidget.destroy();
         myMapWidget = {};
         myMapWidget = new MapWidget(args);
         notFirstTime="1";

/*
* turn off the animated waiting gif
*/
       hideDIV('waiting');
       hideDIV('preWaiting');


/*
* if this was a zoom from the map selection, turn on the zoom back button
*/
   var zoomButton = document.getElementById('zoom_button');
   if (zoomButton) {
    if (previousXRegionsLo[0]) {
     zoomButton.style["display"] = "block"
//     document.getElementById('zoomInfo').style["display"]="none";
    } else {
     zoomButton.style["display"] = "none"
//     document.getElementById('zoomInfo').style["display"]="block";
   }
  }


/*
* check to see if we need to display a legend that contains the underlay levels, ie the reynolds sst error levels
*/
  checkUnderlayStatus();
  checkValueLegendStatus();
  
/*
* blank out the metadata/data frame
*/
      clearMetaWindow();   
  }
 }
}


function checkUnderlayStatus() {

  var myReq = Req.toString();
//  var xmlhttp = new XMLHttpRequest();
//  xmlhttp.open("GET", "../output/5AB28A1B449E405409EB198111912A4F_plot_image.image_colorbar", false);
//  xmlhttp.onreadystatechange=function() {
//   if  (xmlhttp.readyState == 4) {/
//	if (xmlhtt.status==200) alert ("URL Exists");
 //       else alert("Boo");
  //  }
  //}
//  xmlhttp.send(null);
  if (myReq.match("reynoldsERR")) {
      showDIV('underlayLegend')
  }  else  {
      hideDIV('underlayLegend')
  }

}


function checkValueLegendStatus() {

  var myReq = Req.toString();
//  var xmlhttp = new XMLHttpRequest();
//  xmlhttp.open("GET", "../output/5AB28A1B449E405409EB198111912A4F_plot_image.image_colorbar", false);
//  xmlhttp.onreadystatechange=function() {
//   if  (xmlhttp.readyState == 4) {/
//	if (xmlhtt.status==200) alert ("URL Exists");
 //       else alert("Boo");
  //  }
  //}
//  xmlhttp.send(null);
  if (myReq.match("value")) {
      showDIV('valueLegend')
  }  else  {
      hideDIV('valueLegend')
  }

}

function setUpZoom () {
    zooming = 1;


}

function cancelZoom () {
    zooming = 0;


}

function displayMyCoords () {
	document.getElementById("inputForm").latitudeNorth.value=Math.round(myMapWidget.getSelectionGridYMax());
	document.getElementById("inputForm").latitudeSouth.value=Math.round(myMapWidget.getSelectionGridYMin());
	document.getElementById("inputForm").longitudeEast.value=Math.round(myMapWidget.getSelectionGridXMax());
	document.getElementById("inputForm").longitudeWest.value=Math.round(myMapWidget.getSelectionGridXMin());
        document.getElementById('inputForm').xy_range[16].selected = true;
}


function setMapRegionValues () {

  if (document.getElementById("inputForm").xy_range.value == 'Global')  {
      setMapCoordinates(30,390,-90,90);
  } else if (document.getElementById("inputForm").xy_range.value == 'atlantic')  {
      setMapCoordinates(280,380,-80,80);
      myMapWidget.setDrawingArea(80,-10,100,10);      
      myMapWidget.displayBox(true);
  } else if (document.getElementById("inputForm").xy_range.value == 'atlantic_north')  {
      setMapCoordinates(280,380,20,70)
  } else if (document.getElementById("inputForm").xy_range.value == 'atlantic_equatorial')  {
      setMapCoordinates(280,380,-30,30)
  } else if (document.getElementById("inputForm").xy_range.value == 'atlantic_south')  {
      setMapCoordinates(280,380,-70,-20)
  } else if (document.getElementById("inputForm").xy_range.value == 'pacific_north')  {
      setMapCoordinates(120,260,20,80)
  } else if (document.getElementById("inputForm").xy_range.value == 'pacific_equatorial')  {
      setMapCoordinates(135,285,-30,30)
  } else if (document.getElementById("inputForm").xy_range.value == 'pacific_south')  {
      setMapCoordinates(150,290,-80,-20)
  } else if (document.getElementById("inputForm").xy_range.value == 'indian')  {
      setMapCoordinates(30,120,-80,30)
  } else if (document.getElementById("inputForm").xy_range.value == 'Pacific') {
      setMapCoordinates(90,290,-50,55)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_coastal') {
      setMapCoordinates(200,296,17,65)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_east') {
      setMapCoordinates(278,294,23,48)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_west') {
      setMapCoordinates(234,243,31,50)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_gulf') {
      setMapCoordinates(262,279,24,33)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_alaska') {
      setMapCoordinates(191,216,53,71)
  } else if (document.getElementById("inputForm").xy_range.value == 'us_hawaii') {
      setMapCoordinates(198,208,18,23)
  }

}

function setMapCoordinates (xlo,xhi,ylo,yhi) {
 
 var bbox = "";

  // DOMAIN -- spatial
 document.getElementById("inputForm").latitudeNorth.value=yhi
 document.getElementById("inputForm").latitudeSouth.value=ylo
 document.getElementById("inputForm").longitudeEast.value=xhi
 document.getElementById("inputForm").longitudeWest.value=xlo
 if (notFirstTime) {
    var pbox = myMapWidget.clone(myMapWidget.extents.plot.grid);  
    var bbox = myMapWidget.clone(myMapWidget.extents.selection.grid);  
    bbox.x.min = xlo;
    bbox.x.max = xhi;
    bbox.y.max = yhi;
    bbox.y.min = ylo;
    
    myMapWidget.displayBox(false);
    myMapWidget.displayCentralBox(false);

    if ((bbox.x.min >= pbox.x.min) && (bbox.x.max <= pbox.x.max) && (bbox.y.min >= pbox.y.min) && (bbox.y.max <= pbox.y.max)) {
        myMapWidget.setSelectionGridBBox(bbox);
        myMapWidget.displayBox(true);
        myMapWidget.displayCentralBox(true);
    }
 }
/*
* Now we need to fully cleary out the previous region arrays
*/
zooming = 0;
 previousXRegionsLo = new Array();
 previousYRegionsLo = new Array();
 previousXRegionsHi = new Array();
 previousYRegionsHi = new Array();
 document.getElementById('zoom_button').style["display"]="none";

}

function clearMetaWindow() {
      dataW = document.getElementById("metaInformation");
      if (dataW) {
          dataW.style["display"]="none";
      }
      hideDIV('profilePlot');
      hideDIV('dataWindow');
      hideDIV('underlayLegendWindow');
}

function turnOnWaitGif(myDiv) {
      showDIV('waiting');
      document.getElementById('waiting').src='images/await.gif';
      if (notFirstTime) {
         myMapWidget.disable();
      }
}

function turnOffWaitGif(myDiv) {
      hideDIV('preWaiting');
      hideDIV('waiting');
      if (notFirstTime) {
         myMapWidget.enable();
      }

}


function showDIV(divTag) {
     document.getElementById(divTag).style.visibility = "visible";
     document.getElementById(divTag).style["display"] = "block";

}

function hideDIV(divTag) {
     document.getElementById(divTag).style.visibility = "hidden";
     document.getElementById(divTag).style["display"] = "none";

}


function getPlatformInformation() {

  document.getElementById("preWaiting").style["display"] = "block";

//  if (zooming) {
//    previousXRegionsLo.push(Req.getRangeLo('x'));
//    previousXRegionsHi.push(Req.getRangeHi('x'));
//    previousYRegionsLo.push(Req.getRangeLo('y'));
//    previousYRegionsHi.push(Req.getRangeHi('y'));
//    zooming = 0;
//  }
  addFerretProps()
  if (debug == "true") Req.setProperty("las","sqlDebug","true");
  Req.setRange('y',document.getElementById("inputForm").latitudeSouth.value,document.getElementById("inputForm").latitudeNorth.value)
  Req.setRange('x',document.getElementById("inputForm").longitudeWest.value,document.getElementById("inputForm").longitudeEast.value)
  Req.setOperation('Insitu_extract_metadata_NQ','LAS7');
  var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
  evalMapImageRequest(URL);
//  window.open(URL);
}

function getPlatformData() {
  Req.setRange('y',document.getElementById("inputForm").latitudeSouth.value,document.getElementById("inputForm").latitudeNorth.value)
  Req.setRange('x',document.getElementById("inputForm").longitudeWest.value,document.getElementById("inputForm").longitudeEast.value)
    Req.setOperation('Insitu_extract_data_NQ','LAS7');
    var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
    evalMapImageRequest(URL);
//    window.open(URL)
}


function cancelRequest() {
  var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString()) + '&cancel=Cancel&UI_SessionID='+sessionId;
  evalCancelRequest(URL)
// window.open(URL);
  turnOffWaitGif("waiting");


}
function setCancel() {
  cancel = 1;

}




function submitZoomXML() {

   if (myMapWidget.extents.selection.grid.x.min) {
       Req.setRange('x',myMapWidget.extents.selection.grid.x.min,myMapWidget.extents.selection.grid.x.max);
       Req.setRange('y',myMapWidget.extents.selection.grid.y.min,myMapWidget.extents.selection.grid.y.max);
     }

  document.getElementById("inputForm").xy_range[16].selected="true";
  if (document.getElementById("clickMap").click_map[2].checked) {
     Req.setOperation('Insitu_extract_plot_new','LAS7');
     var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
     evalMyRequest(URL);
   } else {
         if (document.getElementById("clickMap").click_map[0].checked) {
               Req.setOperation('Insitu_extract_metadata_NQ','LAS7');
         } else {
               Req.setOperation('Insitu_extract_data_NQ','LAS7');
         }
         var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
         evalMapImageRequest(URL);
   }
}



/*
* pop the previous regions of region stack and zoom back to that image
*/
function submitZoomOutXML(myForm) {
     var tmpForm = myForm;
     var myXLo = previousXRegionsLo.pop();
     var myXHi = previousXRegionsHi.pop();
     var myYLo = previousYRegionsLo.pop();
     var myYHi = previousYRegionsHi.pop();
     Req.setRange('y',myYLo,myYHi);
     Req.setRange('x',myXLo,myXHi);
     document.getElementById("inputForm").latitudeNorth.value=myYHi;
     document.getElementById("inputForm").latitudeSouth.value=myYLo;
     document.getElementById("inputForm").longitudeEast.value=myXHi;
     document.getElementById("inputForm").longitudeWest.value=myXLo;
     if (document.getElementById("inputForm").displayBy[0].selected) {
       Req.setOperation('Insitu_extract_and_plot_LastOb','LAS7');
     } else {
       Req.setOperation('Insitu_extract_plot_new','LAS7');
     }
   if (document.getElementById("inputForm").iconSize[0].selected) {
     autoIconSize()
   } else {
     Req.setProperty("ferret","iconSize", document.getElementById("inputForm").iconSize.value);
   }

  if ( addFerretProps(tmpForm)) {

     var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
     evalMyRequest(URL);

}

}



function initializeLASRequest() {
  Req = new LASRequest('');
  Req.setVariable('OSMC_demo',"id");
  Req.setRange('y',-90,90);
  Req.setRange('x',30,390);

  Req.setOperation('Insitu_extract_plot','LAS7');
  Req.setProperty("ferret","UsePlatform", "_all");     
  Req.setProperty("ferret","tail", "zzzzz");     
  Req.setProperty("ferret","colorBy", "country");
  Req.setProperty("ferret","mapSize", "small");
  Req.setProperty("ferret","iconSize", "mediumIcon");
  Req.setProperty("ferret","topo", "simple");
  Req.setProperty("ferret","graticule", "no");
  Req.setProperty("ferret","bathy", "simple");
  Req.setProperty("ferret","poli", "no");
  Req.setRange('t','2007-04-23 00:00:00', DW.getDate2_Ferret() + '2007-04-22 23:59:59');
  clearMetaWindow();
  setMapCoordinates(30,390,-90,00);

  submitXML('OSMCImage', this.form);

}






 function submitXML(Target, myForm) {
//function submitXML() {
  // Ferret properties need to be added just before you call toString().
  // Here we always scale upthe size of the output plot but you could
  // have some javascript code here that grabbed values from a set of
  // checkboxes and added them as Ferret properties one at a time.




  showDIV('preWaiting');

  if (zooming) {
    previousXRegionsLo.push(Req.getRangeLo('x'));
    previousXRegionsHi.push(Req.getRangeHi('x'));
    previousYRegionsLo.push(Req.getRangeLo('y'));
    previousYRegionsHi.push(Req.getRangeHi('y'));
    zooming = 0;
 }
  Req = new LASRequest('');
//  var newTarget = Target;
  var tmpForm = myForm;
  var ok = 1;
  var usingGoogle = "false";
  //if (tmpForm)
  setBoundingBox("false");  

  if ( addFerretProps(tmpForm)) {

    var URL = '..//ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString());
    evalMyRequest(URL);
  }


}

 function submitXMLtoGoogleEarth(Target, myForm) {
  // Ferret properties need to be added just before you call toString().
  // Here we always scale up the size of the output plot but you could
  // have some javascript code here that grabbed values from a set of
  // checkboxes and added them as Ferret properties one at a time.



  Req = new LASRequest('');
  var tmpForm = myForm;
  var ok = 1;
  var usingGoogle = "true";
  setBoundingBox("true");  
  addFerretProps(tmpForm);
  if (document.getElementById("inputForm").displayBy[0].selected) {
	Req.setOperation('OSMC_placemarks_lastOb','LAS7');
  } else {
    var myPlatform = document.getElementById("inputForm").selectPlatform.value;
    if (myPlatform == "XBT") {
	Req.setOperation('OSMC_placemarks_all_XBT','LAS7');
    } else {
	Req.setOperation('OSMC_placemarks','LAS7');
    }
  }
  if (Target == "animate") {
       Req.setProperty("ferret","animateGE","true");
//       Req.setProperty("ferret","regrid_hours", "4");
       Req.setOperation('OSMC_ge_animation','LAS7');
  } else {
       Req.setProperty("ferret","animateGE","false");
  }
  var URL = '../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString());
  getGERequest(URL);




}
function submitXMLtoGoogleMaps(Target, myForm) {
  // Ferret properties need to be added just before you call toString().
  // Here we always scale up the size of the output plot but you could
  // have some javascript code here that grabbed values from a set of
  // checkboxes and added them as Ferret properties one at a time.



  Req = new LASRequest('');
  var tmpForm = myForm;
  var usingGoogle = "true";
  var ok = 1;
  setBoundingBox("true");  
  addFerretProps(tmpForm);
//  if (document.getElementById("inputForm").displayBy[0].selected) {
//	Req.setOperation('OSMC_placemarks_lastOb','LAS7');
//  } else {
//	Req.setOperation('OSMC_placemarks','LAS7');
//  }
  Req.setOperation('OSMC_gmap', 'LAS7');
  var URL = '../ProductServer.do?JSESSIONID=' + sessionId + '&xml=' + escape(Req.toString());
  newWindow(URL);




}





function setBoundingBox(usingGoogle) {
  var google = usingGoogle;

  var myLatLo = document.getElementById("inputForm").latitudeSouth.value;
  var myLatHi = document.getElementById("inputForm").latitudeNorth.value;
  var myLongLo = document.getElementById("inputForm").longitudeWest.value;
  var myLongHi = document.getElementById("inputForm").longitudeEast.value;

  var latDiff = myLatHi - myLatLo;
  var lonDiff = myLongHi - myLongLo;

  if (google == "false") {
   if ((latDiff*2) < lonDiff) {
     var deltaY = lonDiff/2;
     latDiff = deltaY - latDiff;
     myLatHi = myLatHi*1 + latDiff/2;
     myLatLo = myLatLo*1 - latDiff/2;
     if (myLatHi > 90) {
          myLatLo = myLatLo - (myLatHi - 90);
          myLatHi = 90;
     } else if (Math.abs(myLatLo) > 90) {
          myLatHi = myLatHi + (Math.abs(myLatLo) - 90);
          myLatLo = -90;
      }
   } else if ((latDiff*2) > lonDiff)  {
     var deltaX = (2*latDiff) - lonDiff;
     myLongLo = myLongLo*1 - deltaX/2;
     myLongHi = myLongHi*1 + deltaX/2;
     if (myLongHi > 390){
         myLongLo = myLongLo - (myLongHi - 390);
         myLongHi = 390;
     } else if (myLongLo < 30) {
         myLongHi = myLongHi + ( 30 - myLongLo);
         myLongLo = 30;
     }
   }
  }
     document.getElementById("inputForm").latitudeSouth.value = Math.round(myLatLo);
     document.getElementById("inputForm").latitudeNorth.value = Math.round(myLatHi);
     document.getElementById("inputForm").longitudeWest.value = Math.round(myLongLo);
     document.getElementById("inputForm").longitudeEast.value = Math.round(myLongHi);

  Req.setRange('y',myLatLo, myLatHi);
  Req.setRange('x',myLongLo,myLongHi);

}


function addFerretProps(myForm){


  Req.removeConstraints();

// Check for tail
   var inputForm = myForm;

  if (document.getElementById("inputForm").displayBy[0].selected) {
    Req.setOperation('Insitu_extract_and_plot_LastOb','LAS7');
   } else {
    var myPlatform = document.getElementById("inputForm").selectPlatform.value;
    if (myPlatform == "XBT") {
      Req.setOperation('Insitu_extract_plot_all_XBT','LAS7');
    } else {
      Req.setOperation('Insitu_extract_plot_new','LAS7');
    }
  }

  if (document.getElementById("inputForm").variable[11].selected || document.getElementById("inputForm").selectPlatform.value == "UNDERWAY CARBON SHIPS") {
    Req.setOperation('Insitu_extract_and_plot_carbon','LAS7');
  }

  Req.setRange('t',DW.getDate1_Ferret() + ' 00:00:00', DW.getDate2_Ferret() + ' 23:59:59');

if (document.getElementById("inputForm").map_options_topo.checked) {
    Req.setProperty("ferret","topo", "detailed");
  } else {
    Req.setProperty("ferret","topo", "simple");
}

if (document.getElementById("inputForm").map_options_grid.checked) {
    Req.setProperty("ferret","graticule", "yes");
  } else {
    Req.setProperty("ferret","graticule", "no");
}

if (document.getElementById("inputForm").map_options_bathy.checked) {
  if (document.getElementById("inputForm").variable.value == "SST") {
    Req.setProperty("ferret","bathy", document.getElementById("inputForm").bathySelect.value);
  } else {
    Req.setProperty("ferret","bathy", document.getElementById("inputForm").bathySelect1.value);
  }
} else {
    Req.setProperty("ferret","bathy", "simple");
}

if (document.getElementById("inputForm").map_options_political.checked) {
    Req.setProperty("ferret","poli", "usePoli");
  } else {
    Req.setProperty("ferret","poli", "no");
}

if (document.getElementById("inputForm").displayBy[2].selected) {
    Req.setProperty("ferret","useTrackLine", "yes");
  } else {
    Req.setProperty("ferret","useTrackLine", "no");
}




  if (document.getElementById("inputForm").variable.value == "ID" || document.getElementById("inputForm").variable.value == "ZTMP" || document.getElementById("inputForm").variable.value == "ZSAL") {
    for (var i=0; i < document.getElementById("inputForm").colorBy.length; i++) {
      if (document.getElementById("inputForm").colorBy[i].selected) {
            Req.setProperty("ferret","colorBy", document.getElementById("inputForm").colorBy[i].value);
      }
    } 
  } else {
    for (var i=0; i < document.getElementById("inputForm").colorByValue.length; i++) {
      if (document.getElementById("inputForm").colorByValue[i].selected) {
            Req.setProperty("ferret","colorBy", document.getElementById("inputForm").colorByValue[i].value);
      }
    } 
  }

  if (document.getElementById("inputForm").mapSize[0].selected) {
         Req.setProperty("ferret","mapSize", "large");
  } else  {
         Req.setProperty("ferret","mapSize", "small");
  }

   Req.setProperty("ferret","mapSize", document.getElementById("inputForm").mapSize.value);
   if (document.getElementById("inputForm").iconSize[0].selected) {
     autoIconSize()
   } else {
     Req.setProperty("ferret","iconSize", document.getElementById("inputForm").iconSize.value);
   }


  if (document.getElementById("inputForm").platformSelect[1].checked) {
     if ( document.getElementById("inputForm").platformSelectValue.value ) {
        Req.addTextConstraint("platform_code", "=", document.getElementById("inputForm").platformSelectValue.value );
     } else {
        alert ("Please enter a valid WMO ID");
        hideDIV('preWaiting');
        return 0;
     }
  } else {
    var myPlatform = document.getElementById("inputForm").selectPlatform.value;
    if (myPlatform == 'xxx') {
        alert("The following Platforms are not yet available:\n\tBaromoter Drifters\n\tWeather Buoys\n\tTropical Moored Buoys\n\tGeocentrically Located Tide Gauge Stations\n\n\nPlease select another platform from the platform menu");
        return 0;
    } else {
        Req.setProperty("ferret","UsePlatform", myPlatform);
    }

    if (myPlatform != '_all') {
      if (myPlatform == 'XBT') {
        Req.addTextConstraint("ds.sensor_type", "=", myPlatform);
      } else {
        Req.addTextConstraint("platform_type_name", "=", document.getElementById("inputForm").selectPlatform.value);
      }
    }
  }


  if (!(document.getElementById("inputForm").selectProgram[0].selected)) {
     Req.addTextConstraint("prog.name", "=", document.getElementById("inputForm").selectProgram.value);
  }

  if (document.getElementById("inputForm").country.value != "all") Req.addTextConstraint("country_name", "=", document.getElementById("inputForm").country.value);



// Check for Variable

  var myVar = document.getElementById("inputForm").variable.value;
  Req.setVariable('OSMC_new_schema',myVar);



  return 1;

}


function clearWMOId() {
   document.getElementById("inputForm").platformSelectValue.value = "";

 }


function alertXML(myForm) {
  // Same added property as above

  Req = new LASRequest('');
  var tmpForm = myForm;
  if (tmpForm) addFerretProps(tmpForm);
  var xml = Req.toString();
  alert(xml);
}

function setOneDay(myForm) {
  var inputForm=myForm;
  var myMonthLo = document.getElementById("inputForm").MonthLo.value;
  var myDayLo = document.getElementById("inputForm").DayLo.value;
  var myYearLo = document.getElementById("inputForm").YearLo.value;

  var myDate = myMonthLo + "-" +myDayLo + "-" + myYearLo;

  var myDayHi = myDayLo;
  myDayHi++;
  var myDateH1 = myMonthLo + "-" + myDayHi + "-" + myYearLo;
  Req.setRange('t',myDate,myDateH1);

}

function setTime(myForm) {
  var inputForm=myForm;
  var myMonthLo = document.getElementById("inputForm").Month1.value;
  var myDayLo = document.getElementById("inputForm").Day1.value;
  var myYearLo = document.getElementById("inputForm").Year1.value;
  var myDateLo = myDayLo + "-" + myMonthLo + "-" + myYearLo + " 00:00:00";

  var myMonthHi = document.getElementById("inputForm").Month2.value;
  var myDayHi = document.getElementById("inputForm").Day2.value;
  var myYearHi = document.getElementById("inputForm").Year2.value;
  var myDateHi = myDayHi + "-" + myMonthHi + "-" + myYearHi + " 23:59:59";

   Req.setRange('t',myDateLo,myDateHi);

}

function newWindow(newURL) {

  window.open(newURL,"osmc", "width=778,height=687");
}

function openClock(newURL) {

  window.open(newURL,"", "width=500,height=550");
}


function checkPlatform() {

  var myPlatform = document.getElementById("inputForm").selectPlatform.value;
  if (myPlatform == 'xxx') {
      alert("The following Platforms are not yet available:\n\tBaromoter Drifters\n\tWeather Buoys\n\tTropical Moored Buoys\n\tGeocentrically Located Tide Gauge Stations\n\n\nPlease select another platform from the platform menu");
  document.getElementById("inputForm").selectPlatform[0].selected="true";

 }


}


function checkMapOptions() {
  var myVar= document.getElementById("inputForm").variable.value;
  if (myVar == 'SST') {
    showDIV('showSSToptions');
    hideDIV('showOceanBathyOnly');
  } else {
    hideDIV('showSSToptions');
    showDIV('showOceanBathyOnly');
  }
  if (myVar == 'ID' || myVar == 'ZTMP' || myVar=='ZSAL') {
    showDIV('noColorByValue');
    hideDIV('showColorByValue');
  } else {
    hideDIV('noColorByValue');
    showDIV('showColorByValue');
  }

}

function initializeDateWidget() {
  DW = new DateWidget(document.inputForm, '2007-01-01 00:00:00', 'TWODAYSAGO', '360');
  DW.setDateRange('TWODAYSAGO', 'TWODAYSAGO');
//  DW.setDateRange('2009-08-02 00:00:00', '2009-08-01 00:00:00');
  document.getElementById('zoom_button').style["display"] = "none";

  
}


function myPrint() {

//  }
// var URL = '../ProductServer.do?JSESSIONID='+ sessionId + '&xml=' + escape(Req.toString());
//  document.getElementById("mapWidget").contentWindow.print();
   alert("The image will be displayed in a new window\nfrom which it can be printed");
   window.open(myMapWidget.img.src);

}

function autoIconSize() {

    var myLatLo = document.getElementById("inputForm").latitudeSouth.value;
    var myLatHi = document.getElementById("inputForm").latitudeNorth.value;
    var myLongLo = document.getElementById("inputForm").longitudeWest.value;
    var myLongHi = document.getElementById("inputForm").longitudeEast.value;

    var totalArea = (myLatHi - myLatLo) + (myLongHi - myLongLo);
    if (Math.abs(totalArea*1) < 100 ) {
      Req.setProperty("ferret","iconSize", "largeIcon");
    } else if (Math.abs(totalArea*1) < 350) {
         Req.setProperty("ferret","iconSize", "mediumIcon");
    } else {
      Req.setProperty("ferret","iconSize", "smallIcon");
    }

}

function setMyOperation(op) {
    Req.setOperation(op,'LAS7');

}

function setDomainMenuGlobal() {
   document.getElementById("inputForm").xy_range[0].selected = true;
}


function setPointer(view) {
   if (myMapWidget) myMapWidget.setView(view);
}

function showLegend() {
      showDIV('underlayLegendWindow');
      if (ie) {        
	   document.getElementById('underlayLegendWindow').innerHTML="<img src='"+newImage.colorbar+"'><br><input style=\"background-color:#AAFFAA;border-top: 1px solid #000000;border-bottom: 1px solid #000000;border-left: 1px solid #000000;border-right: 1px solid #000000;\" class=\"consoleTextSmallBold\" name=\"hideLegend\"  type=\"button\" onClick=\"hideDIV(\'underlayLegendWindow\')\" value=\"Close Legend\">";
      } else {
           document.getElementById('underlayLegendWindow').childNodes[1].src=newImage.colorbar;
      }
}
function showValueLegend() {
      showDIV('underlayLegendWindow');
      if (ie) {
	   document.getElementById('underlayLegendWindow').innerHTML="<img src='"+newImage.colorbar_scattered+"'><br><input style=\"background-color:#AAFFAA;border-top: 1px solid #000000;border-bottom: 1px solid #000000;border-left: 1px solid #000000;border-right: 1px solid #000000;\" class=\"consoleTextSmallBold\" name=\"hideLegend\"  type=\"button\" onClick=\"hideDIV(\'underlayLegendWindow\')\" value=\"Close Legend\">";
      } else {
           document.getElementById('underlayLegendWindow').childNodes[1].src=newImage.colorbar_scattered;
      }
}


function changeGMWarning() {
  if (document.getElementById('showGMWarning').checked) {
	GMwarning = "0";
  } else {
	GMwarning = "1";
  }
}

/* Do we need to put up a warning when trying to get to google maps? */
function checkForGMWarning (myForm) {
  var theForm = myForm
  var Xlo= parseFloat(document.getElementById("inputForm").longitudeWest.value);
  var Xhi= parseFloat(document.getElementById("inputForm").longitudeEast.value);
  
  if ((GMwarning == "0") || (Xhi-Xlo <= 100))  {
	Req.setRange('t',DW.getDate1_Ferret() + ' 00:00:00', DW.getDate2_Ferret() + ' 23:59:59');
        submitXMLtoGoogleMaps('OSMCImage', theForm);
  } else {
	showDIV('googleMapWarning');
 }
}


function showSQL(dbURL) {
   window.open(dbURL)

}



