/**
 * Classes used to represent a mercator projection and conversions
 * from lat/long in this projection to x/y on an image.  The top left
 * of the image is considered to be (0,0) and the image size is given
 * by a pair of integers (as this is expected to be used to represent
 * pixels, which are discrete.
 */
	var EQUATOR_RADIUS = 6378137;
	
	// Point object
	Point = function (x, y) {
		this.x = x;
		this.y = y;
	}
	
	Dimension = function ( width, height) {
		this.width = width;
		this.height = height;
	}

	/**
	 * MercatorProjection class
	 */
	MercatorProjection = function(top, left, bottom, right, size) {
		this.maxLong = this.toRadians(right);
		this.minLong = this.toRadians(left);
		this.maxLat  = this.toRadians(top);
		this.minLat  = this.toRadians(bottom);
		this.imageSize = size;	
		//this.EQUATOR_RADIUS = 6378137;
		this.init();	
	}
	
	
	/**
	 * Sets up some initial stuff, to reduce computations necessary later
	 */
	MercatorProjection.prototype.init = function() {
		//The central meridian of the projection
		this.cmerid = (this.minLong + this.maxLong) / 2;
	
		//The conversions will be of the form:
		// x = xScale * convertLong(lon) - xOff
		//this.xvar = convertLong(this.maxLong, this.cmerid);// - convertLong(this.minLong);
		
		this.xScale = (this.imageSize.width) / (this.convertLong(this.maxLong) - this.convertLong(this.minLong));
		this.xOff = (this.xScale * this.convertLong(this.minLong)); 	// = (xScale * getLong(minLong)) - 0;
		//alert(this.maxLong);
		// y = yScale * convertLat(lat) - yOff
		this.yScale = (-1*this.imageSize.height) / (this.convertLat(this.maxLat) - this.convertLat(this.minLat));
		this.yOff = (this.yScale * this.convertLat(this.minLat)) - this.imageSize.height;	// because image is indexed from topleft, not bottomleft
	
	  }	;
	  

	/**
	 * Converts a degree value to radians
	 */
	MercatorProjection.prototype.toRadians  = function( num) {
		return num * Math.PI / 180;
	};
	
	/**
	 * Converts a degree value to radians
	 */
	MercatorProjection.prototype.getMaxLong  = function( ) {
		return this.maxLong;
	};

	/**
	 * Converts a radian value to degrees
	 */
	MercatorProjection.prototype.toDegrees  = function( num) {
		return num * 180 / Math.PI;
	};
	
	/**
 	 * Convert the given longitude into an x value for this Projection
	 */
	MercatorProjection.prototype.getX  = function( dLong) {
		return ((this.xScale * this.convertLong(dLong)) - this.xOff);
	};

	/**
	 * Convert the given x value into a longitude for this Projection
	 */
	MercatorProjection.prototype.getLong  = function( dX) {
		//alert(this.convertX((dX + this.xOff) / this.xScale));
		return this.convertX((dX + this.xOff) / this.xScale);
	};

	/**
 	 * Convert the given latitude into a y value for this Projection
	 */
	MercatorProjection.prototype.getY  = function( dLat) {
		return ((this.yScale * this.convertLat(dLat)) - this.yOff);
	};

	/**
	 * Convert the given y value into a latitude for this Projection
	 */
	MercatorProjection.prototype.getLat  = function( dY) {
		return this.convertY((dY + this.yOff) / this.yScale);
	};
	

	/**
	 * Destandardise the lat.  Inverse function of convertLong
	 */
	MercatorProjection.prototype.convertX  = function( dX) {
		dX /= EQUATOR_RADIUS;
		dX += this.cmerid;
		while (dX < -Math.PI)
			dX += Math.PI*2;
		while (dX > Math.PI)
			dX -= Math.PI*2;
		return dX;
	};	

	/**
	 * Undo mercator stuff for the lat.  Inverse function of convertLat
	 */
	MercatorProjection.prototype.convertY  = function( dY) {
		return (2 * (Math.atan(Math.pow(Math.E, (dY / EQUATOR_RADIUS))) - (Math.PI/4)));
	};

	/**
 	 * Converts a lat/long point into an x/y point
	 */
	MercatorProjection.prototype.convertToXY  = function( lng,  lat) {
		return new Point(Math.round(this.getX(this.toRadians(lng))),
				 Math.round(this.getY(this.toRadians(lat))));
	};

	/**
	 * Converts an x value into a long value
	 */
	 MercatorProjection.prototype.convertToLong  = function( x) {
	 	//alert (this.getLong(x));
		return this.toDegrees(this.getLong(x));
	};

	/**
	 * Converts a y value into a lat value
	 */
	MercatorProjection.prototype.convertToLat = function( y) {
		return this.toDegrees(this.getLat(y));
	};
	

	MercatorProjection.prototype.convertLong = function( dLong) {	
		dLong -= this.cmerid;
		while (dLong < -Math.PI) 
			dLong += Math.PI*2;
		while (dLong > Math.PI) 
			dLong -= Math.PI*2;			
			//alert(this.EQUATOR_RADIUS);
		return (EQUATOR_RADIUS * dLong);
	};
	
	MercatorProjection.prototype.convertLat = function ( dLat) {
		return (EQUATOR_RADIUS * Math.log(Math.tan((Math.PI/4) + (.5 * dLat))));
	};
	
/*********************************************************************
* script for drawing a selection rectangle over a map 
* and show the coordinates of the selected area in the 
* input boxes
***********************************************************************/

// variables
	//map lat lon constants 
	var MIN_LAT = -49;
	var MAX_LAT = -32;
	var MIN_LON = 164;
	var MAX_LON = 184;
	
	
	//The array that keeps track of all the date fields
	var dateFieldNames = new Array("start","end");
	var dates = new Array();

	//map top left corner
    var mapX0 = 0;
    var mapY0 = 0;
    //the map properties							  
    var mapelement ;
	var mapcontainer ;	
	var mapheight; //339
	var mapwidth; //302
    
    //the selected box on the map for coordinate
	var aoibox ; //area of interest
	//the input box in the page to receive the selected coordinates
	var minLatTextbox  ;
	var maxLatTextbox  ;
	var minLonTextbox ;
	var maxLonTextbox ;	
	
	//coordinate option selection box
	var coordSelBox
	
	//global mouse position
	var  globalX ;  
    var  globalY;  
    //var  xMousePos = 0; // Horizontal position of the mouse on the screen
	//var  yMousePos = 0; // Vertical position of the mouse on the screen
	var  xMousePosMax = 0; // Width of the page
	var  yMousePosMax = 0; // Height of the page

	//drawing variables
	var doDraw = false;  
    var xWidth = 0;
    var xHeight = 0;
    
    //projection
   var proj;
    
   var isIE = false; 
   var ieVersion = -1;
  
	//form fields stuff
	var searchForm ;
	var monthFromSelect;
	var monthToSelect;
	var outputFormat;
	var btnSubmit;
	
	/*** when window resizes, the map position parameters need update *****/
	window.onresize = function (){
		updateMapPosition();
	}

    //initialize variables
    window.onload = init;  
  
   /** initialization */
   function init() {
   
     //alert(" window.opener=" + window.opener + " window.location=" + window.location);
   	 var browserName = navigator.appName; 
   	 
   	 if (browserName.indexOf( "Microsoft" ) != -1 )  {//Microsoft Internet Explorer
   		isIE = true; 
   		var ua = navigator.userAgent;
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null){
		    ieVersion = 1*parseFloat(RegExp.$1); 
         }
   	 }
	
	 coordSelBox = document.getElementById('coordOption');
	 	
     /*** 
     *** 1. stuff for drawing search area on the location map 
     *** lancelot container, these are the id of the doc elements that holds the map 
     ****/
     prepareDrawing();
	
	 /** 2. event registered for all the fields  **/  
	 registerEvents();  
	 
	 //test
	 //scheduleSessionStatusCheck(); 
   }   
   
    /*** 
     *** stuff for drawing search area on the location map 
     *** lancelot container, these are the id of the doc elements that holds the map 
     ****/
   function prepareDrawing(){	   	
	   	/** the embeded location map **/
	   	mapelement = document.getElementById('lancelot');
   	    mapcontainer = document.getElementById('container'); 
	   	if(mapelement){
	   	 	 //register events to  functions   	
		   	 mapelement.onmousedown = draw;
		   	 mapelement.onmousemove = move;
		   	 mapelement.onmouseup = stopDraw;
		   	 //update map Position
		   	 updateMapPosition();		
	   	 }
	   	/** append drawings to location map **/
	   	aoibox = document.getElementById('aoi');
	   	if(!aoibox){
	   		aoibox = document.createElement("div");// id='aoi' style='position:absolute;background:#ffeeFF transparent;border:solid 1px #ff0000;display:none;font-size:1px'></div>");
			aoibox.setAttribute('id','aoi');		
			aoibox.setAttribute('style','position:absolute;background:#ffeeFF transparent;border:solid 1px #ff0000;display:none;font-size:1px');
			mapelement.appendChild(aoibox); 
			//mapelement.innerHTML += "";
			//mapelement.innerHTML = aoibox;
		}
    }
    
     /*** 
     *** register events for all the fields
     ****/
    function registerEvents(){
    	//submit button
		btnSubmit = document.getElementById("btnSubmit") ;
		//get form
		searchForm = document.getElementById("searchForm") ;
	  	if(searchForm){
	  		//phase 2 no need to validate by js
	  		searchForm.onsubmit = checkSubmit;
	   		//searchForm.onsubmit = validateInput;
	    }
	    //do select event
	    monthFromSelect = document.getElementById("monthFrom") ;
	    if(monthFromSelect){
	    	monthFromSelect.onchange = checkStartDays;    	
	    }
	     monthToSelect = document.getElementById("monthTo") ;
	    if(monthToSelect){
	    	monthToSelect.onchange = checkEndDays;
	    }
	    //checkDays('dayFrom', 'monthFrom', 'yrFrom');
	     var dayFrom =  document.getElementById("dayFrom") ;
	     var dayTo =  document.getElementById("dayTo") ;
	     var yrFrom =  document.getElementById("yrFrom") ;
	     var yrTo =  document.getElementById("yrTo") ;
	     
	     if(dayFrom){
	     	dayFrom.onchange = resetSubmit;
	     }    
	     if(dayTo){
	     	dayTo.onchange = resetSubmit;
	     }
	     
	     //init the arrays for days checks
	   	if(yrFrom && monthFromSelect && dayFrom){
	   		yrFrom.onkeypress = checkNum;
	   		yrFrom.onchange = checkStartDays;    
	   		
	    	addDate(dateFieldNames[0], dayFrom, monthFromSelect, yrFrom, 1, 0);
	    }
	    if(yrTo && monthToSelect && dayTo){
	    	yrTo.onkeypress = checkNum;
	   		yrTo.onchange = checkEndDays;  
	   		
	    	addDate(dateFieldNames[1], dayTo, monthToSelect, yrTo, 1, 0);
	    }
		//the clear buttons;
		var btnDateClear = document.getElementById('btnDateClear');
		var btnLocationClear = document.getElementById('btnLocationClear'); 
		
		if(btnDateClear){
			btnDateClear.onclick = clearDateFields;
		}
		if(btnLocationClear){
			btnLocationClear.onclick = clearCoordinateFields;
		}	
		
		//the coordinates
		minLatTextbox = document.getElementById('minLat');
		maxLatTextbox = document.getElementById('maxLat');
		minLonTextbox = document.getElementById('minLon');
		maxLonTextbox = document.getElementById('maxLon');	
		
		 if(minLatTextbox){
	     	minLatTextbox.onchange = resetSubmit;
	     }
	     
	     if(maxLatTextbox){
	     	maxLatTextbox.onchange = resetSubmit;
	     }
	     
	     if(minLonTextbox){
	     	minLonTextbox.onchange = resetSubmit;
	     }
	     
	     if(maxLonTextbox){
	     	maxLonTextbox.onchange = resetSubmit;
	     }	
		
		//the depth, magnitude
		//minDepth, maxDepth, minMag, maxMag
		var minDepth = document.getElementById('minDepth');
		var maxDepth = document.getElementById('maxDepth');
		var minMag = document.getElementById('minMag');
		var maxMag = document.getElementById('maxMag');
		
		 if(minDepth){
	     	minDepth.onchange = resetSubmit;
	     }
	     if(maxDepth){
	     	maxDepth.onchange = resetSubmit;
	     }
	     if(minMag){
	     	minMag.onchange = resetSubmit;
	     }
	     if(maxMag){
	     	maxMag.onchange = resetSubmit;
	     }
	     
	     //the errors etc. maxStdError minNumPhases minNumStations outputFormat
		var maxStdError = document.getElementById('maxStdError');
		var minNumPhases = document.getElementById('minNumPhases');
		var minNumStations = document.getElementById('minNumStations');
		outputFormat = document.getElementById('outputFormat');
		if(maxStdError){
	     	maxStdError.onchange = resetSubmit;
	     }
	     if(minNumPhases){
	     	minNumPhases.onchange = resetSubmit;
	     }
	     if(minNumStations){
	     	minNumStations.onchange = resetSubmit;
	     }
	     if(outputFormat){
	     	outputFormat.onchange = resetSubmit;
	     }
    }
    
   /*check the input of a texbox and change the selection box accordingly */	
	function checkCoordInput() { 
		var totalLen = 0;
		if(minLatTextbox){
			totalLen += checkStringIsNumber ( minLatTextbox.value);	
		}	
		if(maxLatTextbox){
			totalLen += checkStringIsNumber ( maxLatTextbox.value);	
		}
		if(minLonTextbox){
			totalLen += checkStringIsNumber ( minLonTextbox.value);	
		}
		if(maxLonTextbox){
			totalLen += checkStringIsNumber ( maxLonTextbox.value);	
		}	
		//set the selctionbox for coordinate to item 1
		if(totalLen >= 4){//if all 4 textboxes have number value
			 setCoordSelItem(1);
		}else{
			 setCoordSelItem(0);
		}
		//alert("text=" + text);
	}

  /** update Global position parameters */
   function updateMapPosition () { 
    	//map top left corner
    if(mapelement){
	    mapX0 = mapelement.offsetLeft ;  
	    mapY0 = mapelement.offsetTop;   
	  	//			+ mapcontainer.offsetLeft + ", " 
	   
	    if(mapcontainer){
			if (isIE == true )  {//Microsoft Internet Explorer
			    if(ieVersion < 8){//check IE version
				   mapX0 = mapelement.offsetLeft + mapcontainer.offsetLeft ; 
			  	   mapY0 = mapelement.offsetTop + mapcontainer.offsetTop ;  
			  	 } 
			 } 
		}
	   	
	   	 //onmousemove="move(event)" onmouseup="stopDraw(event)"
	   	 mapheight = parseInt(mapelement.style.height);
	   	 mapwidth = parseInt(mapelement.style.width);
	   	 
	   	 //creatre the projection
	   	 var d = new Dimension(mapwidth, mapheight);
	   	 //maxLat, minLon, minLat, maxLon
		 proj = new MercatorProjection(MAX_LAT, MIN_LON, MIN_LAT, MAX_LON, d);
	}
  }
		     
    /** get Global position */
   function getPosition (e) { 
   	   if (e.pageX || e.pageY) {  //netacape
            globalX = e.pageX;  
            globalY = e.pageY;  
        } else if (e.clientX || e.clientY) { 
        	 globalX = e.clientX  ;  
             globalY = e.clientY  ; 
        	if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			    //DOM compliant
			    globalX = e.clientX + document.body.scrollLeft;  
            	globalY = e.clientY + document.body.scrollTop;   
			  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			    //IE6 standards compliant mode
			    globalX = e.clientX + document.documentElement.scrollLeft;  
            	globalY = e.clientY + document.documentElement.scrollTop;   
			  }  
        }  
   }
   
    /**  draw the selection rectangle onmousedown */
    function draw(e) {  
        xWidth=0;
        xHeight=0; 
        aoibox.style.width = xWidth + "px";
        aoibox.style.height = xHeight + "px";
        if (!e) {  
            e = window.event;  
        }  
  		//get global position
        getPosition(e);
  		
  		 /**  ***************
  		if(debug){
  			debug.value = "draw. e.pageX, e.pagey, e.clientX,e.clienty=" +e.pageX + ", " +e.pageY + ", "  + e.clientX + ", " + e.clientY ;  
  		}
  		if(debug1){
  			debug1.value = "draw. globalX, y=" +globalX + ", " +globalY  +  " document.body/documentElement.scrollLeft, top=" +document.body.scrollLeft + ", " +document.body.scrollTop 
  			+ ", "  + document.documentElement.scrollLeft + ", " +document.documentElement.scrollTop ;        
  		}
  		 */
  		 
        startX = globalX;  
        startY = globalY;  
  
        aoibox.style.top = globalY + "px";
        aoibox.style.left = globalX + "px";
        aoibox.style.display = 'inline';  
  
        doDraw = true;  
           //set the selctionbox for coordinate to item 1
        setCoordSelItem(1); 
    }  
  
 /**  move the selection rectangle */
    function move(e) {
        if (!e) {  
            e = window.event;  
        }  
  		//
        getPosition(e);
  
        if (doDraw) { 
            xWidth = globalX - startX;  
            xHeight =globalY - startY; 
            //show coordinates 
  			showLatLon(); 
  		 
            doNormal = true;  
  
            if (xWidth < 0) {  
                doNormal = false;  
                xWidth = startX - globalX;  
                xHeight = globalY - startY;  
  
                aoibox.style.left = globalX + "px";  
  
                if (xHeight < 0) {  
                    xHeight = startY - globalY;  
                    aoibox.style.top = globalY + "px"; 
                }  
                aoibox.style.width = xWidth + "px";   
                aoibox.style.height = xHeight + "px";  
                return;  
            }   
  
            if (xHeight < 0) { 
                doNormal = false;  
                xHeight = startY - globalY;  
                aoibox.style.top = globalY + "px";  
                aoibox.style.width = xWidth + "px";  
                aoibox.style.height = xHeight + "px"; 
                return;  
               }   
                         
            if (doNormal == true) { 
                xWidth = globalX - startX ;
                xHeight = globalY - startY;  
                aoibox.style.left = startX + "px";  
                aoibox.style.top = startY + "px";    
                aoibox.style.width = xWidth + "px";   
                aoibox.style.height = xHeight + "px";  
            }  
           
        }  
    }  
  
   /**  stop drawing the selection rectangle */
    function stopDraw(e) {  
    	xWidth = globalX - startX;  
        xHeight =globalY - startY;  
    	if((xWidth == 0) && (xHeight == 0)){//clear box
			aoibox.style.display = 'none'; 
			//
			clearCoordinateFields();		 	
		 	//
	 		setCoordSelItem(0);
		}
  			
        if (!e) {  
            e = window.event;  
        }  
        
  		 doDraw = false;   	
  		 
  		//some debug stuff for testing purpose aoibox.style.left = startX;  
               // aoibox.style.top = startY;    
                //aoibox.style.width = xWidth;  
               // aoibox.style.height = xHeight;  
  		      
    }  
  
  /** show latetude logitude on the relative input box*/
  function showLatLon() {
  	var mapheight = parseInt(mapelement.style.height);
 	var x1 = startX;
 	var x2 = globalX;
 	if(globalX < startX){
 		x1 = globalX;
 		x2 = startX;
 	}
 	var y1 = startY;
 	var y2 = globalY;
 	if(globalY < startY){
 		y1 = globalY;
 		y2 = startY;
 	}
 	//calc latlon selected
 	var maxlat , minlat, minlon , maxlon ;
 	
 	if(proj){//do  projection proj
	 	maxlat = proj.convertToLat(y1- mapY0);
	 	minlat = proj.convertToLat(y2 - mapY0);
		minlon = proj.convertToLong(x1 - mapX0);
		maxlon = proj.convertToLong(x2 - mapX0);
	}else{//a rough transformation from pixel to latlon	
		maxlat = MAX_LAT - (MAX_LAT - MIN_LAT)*(y1 - mapY0)/mapheight;
	 	minlat = MAX_LAT - (MAX_LAT - MIN_LAT)*(y2 - mapY0)/mapheight;
	 	minlon = MIN_LON + (MAX_LON - MIN_LON)*(x1 - mapX0)/mapwidth;
	 	maxlon = MIN_LON + (MAX_LON - MIN_LON)*(x2 - mapX0)/mapwidth;
	 	//check longitude 
	 	if(minlon > 180){
	 		minlon -= 360;
	 	}
	 	if(maxlon > 180){
	 		maxlon -= 360;
	 	}
	}
	
	//show coordinates	
 	if(maxLatTextbox) maxLatTextbox.value = maxlat.toFixed(5);
 	if(minLatTextbox) minLatTextbox.value = minlat.toFixed(5);
   	if(minLonTextbox) minLonTextbox.value = minlon.toFixed(5);
 	if(maxLonTextbox) maxLonTextbox.value = maxlon.toFixed(5);
 	
 	} 
 	
  /** clearCoordinateFields */	
	function  clearCoordinateFields(){
		if(maxLatTextbox) maxLatTextbox.value = '';
	 	if(minLatTextbox) minLatTextbox.value = '';
	   	if(minLonTextbox) minLonTextbox.value = '';
	 	if(maxLonTextbox) maxLonTextbox.value = '';
	 	//resetSubmit();
	 	resetSubmit();
	}

 /** set the selectionbox to specified item */	
  function setCoordSelItem(num) {
	if(coordSelBox) coordSelBox.selectedIndex = num;	
	//resetSubmit();
	resetSubmit();
  } 
  
 function deSelection() { 
  var c = document.body.createTextRange(); 
  var d = c.duplicate(); 
  c.collapse();
  c.setEndPoint("EndToStart", d); 
  c.select(); 
 } 
 
 
 /** check if a string is a number */
  function checkStringIsNumber (text) { 
   if((text)&&(text.length > 0)&&(!isNaN(text))){ 
		return 1; 
	}else{
       	return 0; 
       }
   }
  
   /** check number is valid */  
 function validateNumber(value, required){ 	
	if(!value || value.length == 0){//empty value
		return !required;
	}
 	
 	//check format
 	return checkStringIsNumber(value) > 0;
 }
 
  /** prevent multiple submit */
 var submitCount = 0; 
 
  /** prevent multiple submit, and submit the form */
 function checkSubmit(){
    //if(submitCount++ > 0){
    	//alert("You have already submitted a search request. \nPlease wait for the process to finish, and refresh the page or click 'Reset submit' if you want to do another search.");
    	//return false;
    //}
     if(btnSubmit){
    	btnSubmit.disabled = true;
    	btnSubmit.style.color="#dddddd";
    }
    if(searchForm && outputFormat){
    	if( (outputFormat.selectedIndex <= 3)|| (outputFormat.selectedIndex == 7)){//csv,kml no need for a separate window
    		searchForm.target = '';
    	}else{//map, ims
    	    //open separate window
    		searchForm.target = 'GEONET_QUAKE_SEARCH_RESULT';
    	}
    }
    //arange sessiont status check
    scheduleSessionStatusCheck();
   // return sendForm(searchForm);
 	return true;
 }
 
  /** submit the form by open a new window */
 function sendForm(fm) {
	if (fm.target != '') {		
		window.open('','GEONET_QUAKE_SEARCH_RESULT','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=600');
	}
	return true;
   
}
 
  /** 
    * reset to enable submit, when the page is submitted, the submit button is disabled
    * and it is enabled again when any of the input changes
    */
 function resetSubmit(){
    submitCount = 0;
   // alert("resetSubmit");
    if(btnSubmit){
    	btnSubmit.disabled = false;
    	btnSubmit.style.color="#000000";
    }
 }
 
 
  /** validate form input */	
  function validateInput(){
    var valid = true;
    var errorMsg = "";
    //check coordinate
    if(coordSelBox && coordSelBox.selectedIndex != 0){
    	if((!validateNumber(maxLatTextbox.value, true))
    		|| (!validateNumber(minLatTextbox.value, true))
    		)
    	{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Latitude.";
    	}
    }
    
     if(coordSelBox && coordSelBox.selectedIndex != 0){
    	if( (!validateNumber(maxLonTextbox.value, true))
    		|| (!validateNumber(minLonTextbox.value, true))
    		)
    	{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Longitude.";
    	}
    }
    
    //check depth
    var depthSelBox = document.getElementById('depthOption');
    var minDepthBox = document.getElementById('minDepth');
    var maxDepthBox = document.getElementById('maxDepth');
    if(depthSelBox && depthSelBox.selectedIndex != 0){
    	if((minDepthBox && !validateNumber(minDepthBox.value, true))
    		|| (maxDepthBox && !validateNumber(maxDepthBox.value, true)))
    		{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Depth.";
    	}
    }
    
    //check magnitude
    var magSelBox = document.getElementById('magOption');
    var minMagBox = document.getElementById('minMag');
    var maxMagBox = document.getElementById('maxMag');
    if(magSelBox && magSelBox.selectedIndex != 0){
    	if((minMagBox && !validateNumber(minMagBox.value, true))
    		|| (maxMagBox && !validateNumber(maxMagBox.value, true)))
    		{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Magnitude.";
    	}
    }
    
     //check quality
    var qualitySelBox = document.getElementById('qualityOption');
    var maxStdErrorBox = document.getElementById('maxStdError');
    var minNumPhasesBox = document.getElementById('minNumPhases');
    var minNumStationsBox = document.getElementById('minNumStations');     
   
    if(qualitySelBox && qualitySelBox.selectedIndex != 0){
    	if(maxStdErrorBox && !validateNumber(maxStdErrorBox.value, true))
    		{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Maximum standard error.";
    	}
    	if(minNumPhasesBox && !validateNumber(minNumPhasesBox.value, true))
    		{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Minimum number of phases.";
    	}
    	if(minNumStationsBox && !validateNumber(minNumStationsBox.value, true))
    		{
    		valid = false;
    		errorMsg += "\nYou must enter a numeric value for Minimum number of stations.";
    	}
    	
    	
    }    
    //
    if(!valid){
    	alert("Please correct the following error(s):" + errorMsg);
    	return false;
    }
   	return true;	
   		
   }
 
 /*****************************************************
 ***Functions to help with date drop boxes    *********
 *****************************************************/
 /* check the start days selectionbox for days based on year and month selected */
  function checkStartDays() { 
    	//submitHelpForm();
    	//alert("checkStartDays");
    	resetSubmit();
    	updateDays('start');
    	//
    	
    }
 
     function checkEndDays() { 
     	//submitHelpForm();
     	//alert("checkEndDays");
     	resetSubmit(); 
     	updateDays('end');
     	//
     	    	
    } 
//
//Figures out if the given year is a leap year
function isLeap(year) {
	if (Math.floor(year/2000) == year/2000)
		return true;
	else if (Math.floor(year/100) == year/100)
		return false;
	else if (Math.floor(year/4) == year/4)
		return true;
	else
		return false;
}

//Either Feb or a change of month
function getDays(year, month) {
		var nDays=31;	
//		alert('month is: '+month+', year is: '+year+', has blank is: '+thisDate.hasBlank);
		switch(month) {
			case 1: if (!parseInt(year))
					nDays = 29
				else if (isLeap(year))
					nDays = 29;
				else
					nDays = 28;
				break;
			case 3:
			case 5:
			case 8:
			case 10:
				nDays = 30;
				break;
		}
	return nDays;
}
		


//Adds a new date the array of dates we are taking care of.
function addDate(name, cDay, cMonth, cYear, hasBlank, showDay) {
	dates[name] = new Array();
	var thisDate = dates[name];
	thisDate.cDay = cDay;
	thisDate.cMonth = cMonth;
	thisDate.cYear = cYear;
	thisDate.currMon = 1 + hasBlank;		//if Jan then 31 days is right
	thisDate.hasBlank = hasBlank;
	thisDate.showDay = showDay;
	if (cYear.options) 
		//It's a select box
		thisDate.currYea = cYear.options[cYear.selectedIndex].text;
	else 
		thisDate.currYea = cYear.value;
	if (cDay) {
		thisDate.currDay = cDay.selectedIndex;
		thisDate.currDays = 31;
		updateDays(name);
	}
}

//updates the number of days in the cDay box according
//to the contents of the other two (month year).
function updateDays(name) {
	var thisDate = dates[name];
	if (thisDate.currDay || thisDate.currDay == 0) {
//		alert('selectedIndex of thisDate.cMonth is: '+thisDate.cMonth.selectedIndex);
		var month = thisDate.cMonth.selectedIndex - thisDate.hasBlank;
		//alert(name + ":" + thisDate.currMon + ":" + month);
		//Are we looking at only a change of year, and it isn't Feb
		if (!thisDate.showDay && (thisDate.currMon == month) && (thisDate.currMon != 1))
			return;

		thisDate.currMon = month;

		//Either Feb or a change of month
		
		//Get the year
		if (thisDate.cYear.options) 
			year = thisDate.cYear.options[thisDate.cYear.selectedIndex].text;
		else
			year = thisDate.cYear.value;
		
		var nDays= getDays(year, month);
		
		//Has it changed
		if (!thisDate.showDay && thisDate.currDays == nDays)
			return;
		else {
			oldSelected = thisDate.cDay.selectedIndex;
			if (thisDate.showDay) {
				//Need to redraw the whole box
				thisDate.cDay.options.length = 0;
				if (thisDate.hasBlank)
					thisDate.cDay.options[0] = new Option("Day", "-");
				for (var i=0; i<nDays; i++) {
					var dd = i+1;
					var d = new Date(year, month, dd);
					var dayIndex = d.getDay();
					var dayString = (thisDate.showDay < 3) ? daysAbbr[dayIndex] : days[dayIndex];
					if (thisDate.showDay == 1 || thisDate.showDay == 3)
						dayString += ", " + dd;
					else
						dayString = dd + ", " + dayString;
					thisDate.cDay.options[i+thisDate.hasBlank] = new Option((month > -1 && (dayIndex || dayIndex == 0)) ? dayString : dd, dd);
				}
			} else if (nDays < thisDate.currDays) 
				thisDate.cDay.length=nDays + thisDate.hasBlank;
			else {
				for (var i=thisDate.currDays; i<nDays; i++) 
					thisDate.cDay.options[i+thisDate.hasBlank] = new Option(i+1)
			}
			if (oldSelected > thisDate.cDay.options.length-1)
				thisDate.cDay.selectedIndex = thisDate.cDay.options.length-1;
			else
				thisDate.cDay.selectedIndex = oldSelected;
		}
		thisDate.currDays = nDays;
	}
	//
	
}

/* check a number is entered, for year value */
function checkNum(e) {
	//alert(e);
	e = e||window.event;
    var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode;
    //alert(charCode);
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
    }   
    return true;
}


 /** clearDateFields */	
	function  clearDateFields(){
		for (var i=0; i < dateFieldNames.length; i++) {
			var thisDate = dates[dateFieldNames[i]];
			if (thisDate ) {
				thisDate.cYear.value = "";
				thisDate.cDay.selectedIndex = 0;
				thisDate.cMonth.selectedIndex = 0;
			}
		}
		//resetSubmit
		resetSubmit();		
  }



 /** #############################################################
 ****  check session status  and reset the submit button
 ****#############################################################
 */	
var http_request_status = false;
var sessionStatus = false;
var timerId = 0;

function createRequest( ) {
   var http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
   return http_request;
}
 
function queryStatus() {
	  //clear the timer
	  clearTimeout (timerId );
	  
	  sessionStatus = false;
      var url = window.location.href;
	  var stop = url.lastIndexOf('/');
	  if(stop > 0)
		url = url.substring(0,stop);
		//alert ("url=" + url);
	   //the url for the status servlet
	   url = url + "/status";
 	 
       http_request_status = false;
       http_request_status = createRequest();
      if (!http_request_status) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request_status.onreadystatechange = getStatus;
      //alert(url);
      http_request_status.open('GET', url , true);
      http_request_status.send("qs");
      //
      
}

/*
*/
function getStatus() { 
      if (http_request_status && http_request_status.readyState == 4) {
         if (http_request_status.status && http_request_status.status == 200) {
         	sessionStatus = (http_request_status.responseText);
	       //check status
			checkStatus();
         }
         //alert(http_request_status.readyState);
	}
}

/*
* arange check session status, check every minute
*/
function scheduleSessionStatusCheck() { 
   //wait a minute
	timerId = setTimeout ( 'queryStatus()', 30000 );	
}




//check the status, if status ready, reset submit button to allow another search resuest
function checkStatus() { 
   //alert(sessionStatus);
	if(sessionStatus && parseInt(sessionStatus) == 0){
	  resetSubmit();
	}else{//arange check again
		scheduleSessionStatusCheck();
	} 
}


   


