// Can retarget using new PhasePick("/axis2/services/PhasePickService"); in phasePick.html
function PhasePick(target) {
 url = target;
}

var max_download_limit=30000;

var url;

var savedQueryForm = new Object();

var cancelled = {}; // map of cancelled requests.

var url = "/axis2/services/PhasePickService"; // see above.
// var url = "/ws/PhasePickService"; // for production
var queryTransformUrl = "phasePick/xsl/phasePickResults.xsl";
var downloadTransformUrl = "phasePick/xsl/downloadResults.xsl";
var emailTransformUrl = "phasePick/xsl/emailResults.xsl";
var dateTransformUrl = "phasePick/xsl/dateResults.xsl";
var availableDataTransformUrl = "phasePick/xsl/dateRange.xsl";
var downloadLimitTransformUrl = "phasePick/xsl/downloadLimitResults.xsl";
var panels = new Array();

var emailProblem = "If this problem persists, please contact <a href='mailto:ws@iris.washington.edu'>ws@iris.washington.edu</a>";
// var emailProblem = "If this problem persists, please contact <b>ws at iris.washington.edu</b>";

var DEFAULT_EARLIER_DAYS = 7;

function fillInDates() {
    // SOAPParser.invoke(url, "mostRecentUpdate", "", dateTransformUrl, true, dateForFormCallback);
    // set starting date to 1 month earlier than today.
    var startDate = new Date();
    startDate.setDate(startDate.getDate()-DEFAULT_EARLIER_DAYS);
    document.forms[0].startdate_Year_ID.value = startDate.getFullYear();
    document.forms[0].startdate_Month_ID.selectedIndex = startDate.getMonth();
    document.forms[0].startdate_Day_ID.selectedIndex = startDate.getDate() -1; // ??? Why do we have to subtract 1? 
    var today = new Date();
    document.forms[0].enddate_Year_ID.value = today.getFullYear();
    document.forms[0].enddate_Month_ID.selectedIndex = today.getMonth();
    document.forms[0].enddate_Day_ID.selectedIndex = today.getDate() -1; // ??? Why do we have to subtract 1? 
}

function getFormDate(inputName) {
	var year = document.getElementById(inputName+'_Year_ID').value;
	var month = document.getElementById(inputName+'_Month_ID').value;
	var day = document.getElementById(inputName+'_Day_ID').value;
	var date = new Date();
	date.setFullYear(year, month, day);
	return date;
}
	
function getDownloadLimit() {
    SOAPParser.invoke(url, "downloadLimit", "", downloadLimitTransformUrl, true, downloadLimitCallback);
}

function checkTheDates(theForm) {
	var start = getFormDate('startdate');
	var end = getFormDate('enddate');
	return end >= start;
}

function queryDays(theForm) {
	var start = getFormDate('startdate').getTime();
	var end = getFormDate('enddate').getTime();
	return parseInt((end-start) / (24 * 60 * 60 * 1000));
}

// not using this for now..
/*
function checkForLongQueries(theForm) {
	var queryLengthDays = queryDays(theForm);
	if ( theForm.allTime.checked || 
		 queryLengthDays > ( 2 * 365 ) ) {
		 alert("This is a potentially long query that may lead to timeouts in some browsers.");
	}
}
*/

function validateDate(fld) {
    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var errorMessage = 'The date entered is invalid:'+fld;
    if (fld.match(RegExPattern)) {
        return true;
    } else {
        alert(errorMessage);
        return false;
    }    
}

function buildGetAvailableDataXML(itemType, contributor) {
	var query = 
		"<checkItem>" +
			"<dataItemType>" + itemType + "</dataItemType>";
	if ( contributor != null ) {
		query += "<contributor>" + contributor + "</contributor>";
	}
	query += "</checkItem>";
    return query;
}

function resetPhaseDates() {
	var select = document.getElementById('pContrib');
	updatePhaseDates(select);
}

function updatePhaseDates(select) {
	var contributor = select.options[select.selectedIndex].value;
	if ( contributor == "%" ) { // "ALL" 
		contributor = null;
	}
	fetchPhaseDates(contributor);
}

function fetchPhaseDates(contributor) {
	var queryXML = buildGetAvailableDataXML("arrival", contributor);
    SOAPParser.invoke(url, "availableData", queryXML, availableDataTransformUrl, true, updatePhaseDatesCallback);
}

function updatePhaseDatesCallback(error, outputString) {
	if ( error == null ) {
		setAvailableData(outputString);
    } else {
		errorMsg(outputString);
    }
}

function errorMsg(msg) {
	document.getElementById ('outputTable' ).innerHTML = msg;
}

var dataAvailableText = " phase data available";

function setAvailableData(msg) {
	var select = document.getElementById('pContrib');
	var who = dataAvailableText;
	if ( select && select.selectedIndex > 0 ) {
    	who = select.options[select.selectedIndex].text + who;
    }
    document.getElementById ('phasesAvailableElement').innerHTML = who;
    var start = "";
    var end = "";
    if ( msg ) {
    	var idx = msg.indexOf( " and" );
		start = msg.substring(0, idx);
		end = msg.substring( idx );
    }
	document.getElementById ('availablePhaseDatesStartElement').innerHTML = start;
	document.getElementById ('availablePhaseDatesEndElement').innerHTML = end;
}

function viewResults(theForm) {
	var queryKey = new Date().getTime();
    savedQueryForm = theForm;
    if ( ! checkTheDates(theForm)) {
        alert("The start date must be equal to or earlier than the end date.");
        return;
    }
    // checkForLongQueries(theForm);
    cursor_wait();
    var paramXML = buildXmlRequest(theForm);
    tellThemToWait("Please wait while we process your request", queryKey);
    // We've ruled Safari 2 out at the get go (phasePick.jsp) so we don't have to worry about all this.
    // see version 1.22 or before.
    SOAPParser.invoke(url, "eventQuery", paramXML, queryTransformUrl, true, displayResultsCallback, queryKey);
}

function viewNextResults(key, pos) {
    cursor_wait();
    var paramXML = buildXmlNextRequest(key, pos);
    tellThemToWait("Please wait while we fetch the next set.");
    SOAPParser.invoke(url, "next", paramXML, queryTransformUrl, true, displayResultsCallback);
}

function validEmailAddress(eAddr) {
	if ( eAddr != null && 
	     eAddr != "" && 
	     eAddr.indexOf("@" > 0 )) {
	     	return true;
	} else {
		return false;
	}
}

function download(theForm) {
    if (theForm.emailResults.checked) {
    	if ( ! validEmailAddress( theForm.emailAddress.value )) {
        	alert("Please enter a valid email address.");
        	return;
        }
    }
    cursor_wait();
    var paramXML = buildXmlDownloadRequest(theForm, savedQueryForm);
    tellThemToWait("Please wait while we process your request");

    if (theForm.emailResults.checked) {
        SOAPParser.invoke(url, "emailDownload", paramXML, emailTransformUrl, true, downloadResultsCallback);
    } else {
        SOAPParser.invoke(url, "eventDownload", paramXML, downloadTransformUrl, true, downloadResultsCallback);
    }
}

// Changes the cursor to an hourglass
function cursor_wait() {
    document.body.style.cursor = 'wait';
}

// Returns the cursor to the default pointer
function cursor_clear() {
    document.body.style.cursor = 'default';
}

function tellThemToWait(waitMsg, key) {
    var id = "waitPnl";
    var waitTable = "<table id='wait'><tr><th>" + waitMsg + "</th></tr>" +
        "<tr ><td class='loadIcon'><img src='phasePick/ajax-loader.gif'/></td></tr>" +
        "<tr><td align='right'><input type='button' onClick='javascript:cancelQuery("+key+")' value='Cancel'/></td></tr></table>";

    var newMod;
    var isNew = true;
    if (panels[id]) {
        isNew = false;
        newMod = panels[id];
        newMod.setBody(waitTable);
        newMod.cfg.setProperty('visible', true);
        newMod.bringToTop();
    } else {
        newMod = new YAHOO.widget.Panel("waitPnl",
            { width:"400px",
            context:["tableCorner","tl","bl"],
            //fixedcenter: true,
            underlay:"shadow",
            close:false,
            visible:true,
            iframe:true,
            draggable:true} );

        newMod.setBody(waitTable);
        newMod.hideMacGeckoScrollbars();
        panels[id] = newMod;
        newMod.render(document.body);
    }
}

function cancelQuery(queryKey) {
	// alert("queryKey:"+queryKey);
	if ( queryKey ) {
    	cancelled[queryKey] = true;
    }
	doneWaiting();
	cursor_clear();
}

function doneWaiting() {
    var id = 'waitPnl';
    if (panels[id]) {
        // make the wait panel invisible and kill it. Necessary for
        // getting loading correct, and to avoid the gif running in
        // the background.
        panels[id].cfg.setProperty('visible', false);
        panels[id].setBody[""];
        panels[id] = null;
    }
}

PhasePick.wsdlErrorAlert = function(msg) {
    // alert( msg );
    document.getElementById ('outputTable').innerHTML = "<font style='color:red;'>Warning: " + msg + "</font>";
    cursor_clear();
}

function Error(number, description) {
    this.number = number;
    this.description = description;
}


function displayResultsCallback(error, outputString, queryKey) {
  if ( queryKey && cancelled[queryKey] ) { 
  	cancelled[queryKey] = null;
  	return;
  } 
  doneWaiting();
  cursor_clear();
  if (error != null) {
    var errorMsg = "<div id='error'>A service error has occurred: " + error.description + "<br>" +
               emailProblem + "</div>";
    document.getElementById ('outputTable').innerHTML = errorMsg;
  }
  else {
    document.getElementById ('outputTable').innerHTML = outputString;
  }
}

function downloadResultsCallback(error, outputString) {
   doneWaiting();
   cursor_clear();
   // var pnl = document.getElementById('downloadPnl');
   // There is a problem if the user closes the download popup panel before the results are in.
   if (error == null) {
       document.getElementById('downloadLink').innerHTML = outputString;
     } else {
         errorMsg = "<div id='error'>There was a problem processing your request:<br>" +
                 error.description+ "</div>";
         document.getElementById('downloadLink').innerHTML = errorMsg;
     }
}

function dateForFormCallback(error, outputString) {
    if (error == null) {
        // first find the date string - different xsl processors produce different output
        divIndex = outputString.indexOf("<div>");
        if (divIndex < 0)
            divIndex = outputString.indexOf("<DIV>");

        var lastDate = outputString.substring(divIndex + 5, divIndex + 15);
        // alert("lastDate:"+lastDate);
        
        var loadEndDate = new Date();
        var dateChunks = lastDate.split('-');
        
        var endYear = dateChunks[0];
        var endMonth = dateChunks[1]-1;
        var endDay = dateChunks[2];
        
        loadEndDate.setFullYear(endYear, endMonth, endDay);
        // alert("loadEndDate:"+loadEndDate);
        
        var loadStartDate = new Date();
        loadStartDate.setTime(loadEndDate.getTime());
        loadStartDate.setMonth(loadStartDate.getMonth()-1);
        // alert("loadStartDate:"+loadStartDate);
        
        if ( loadStartDate.getDate() != loadEndDate.getDate() ) {
            loadStartDate.setDate( loadStartDate.getDate() - 1 );
        }
        
        document.forms[0].startdate_Year_ID.value = loadStartDate.getFullYear();
        document.forms[0].startdate_Month_ID.selectedIndex = loadStartDate.getMonth();
        document.forms[0].startdate_Day_ID.selectedIndex = loadStartDate.getDate() -1;
        // alert("startdate:"+document.forms[0].startdate);
        
        document.forms[0].enddate_Year_ID.value = loadStartDate.getFullYear();
        document.forms[0].enddate_Month_ID.selectedIndex = loadEndDate.getMonth();
        document.forms[0].enddate_Day_ID.selectedIndex = loadEndDate.getDate() -1;
        // alert("startdate:"+document.forms[0].enddate);
    }
}

function downloadLimitCallback(error, outputString) {
   if (error == null) {
           // first find the date string - different xsl processors produce different output
           startIndex = outputString.indexOf("<limit>");
           if (startIndex < 0)
               startIndex = outputString.indexOf("<LIMIT>");
           endIndex = outputString.indexOf("</limit>");
           if (endIndex < 0)
               endIndex = outputString.indexOf("</LIMIT>");
        downloadLimit = outputString.substring(startIndex + 7, endIndex );
    } else {
         errorMsg = "<div id='error'>" + error.description +"<br>" + emailProblem + "</div>";
         document.getElementById('outputTable').innerHTML = errorMsg;
     }
}

function openDownloadWidget(numResults) {

    var id = 'downloadPnl';
    var body = populateDownload(numResults);
    var header = 'Download';
    var args = {};
    args.visible = true;
    args.constraintoviewport = true;
    args.iframe = true;
    args.fixedcenter = true;
    args.draggable = false;
    args.modal = false;
    args.close = false;
    args.underlay = "none";
    args.width = "659px";
    args.context = ["tableCorner","tl","bl"];

    var newMod;
    var isNew = true;

    if (false) { // body will depend on numResults...
        newMod = panels[id];
        newMod.cfg.applyConfig(args);
        isNew = false;
    } else {
        newMod = new YAHOO.widget.Panel(id, args);
        panels[id] = newMod;
    }

    newMod.setHeader(header);
    if (body) {
        newMod.setBody(body);
    }
    if (isNew) {
        newMod.render(document.body);
    } else {
        newMod.render();
    }

}

function closeDownload() {
    var id = 'downloadPnl';
    if (panels[id]) {
            panels[id].cfg.setProperty('visible', false);
    }
}

function getValue(value, defaultValue)
{
    if ( value && value.length > 0 ) {
        return value;
    } else {
        return defaultValue;
    }
}

function buildXmlRequest(theForm) {
    var requestStr = buildXmlEventQuery(theForm);
  requestStr += "<returnCount>"+getValue(theForm.returnCount.value,"10")+"</returnCount>";
  return requestStr;
}

function buildXmlDownloadRequest(theForm, savedQueryForm) {

    // Get the download format
    var formatValue = '';
    if (theForm.downloadFormat.length > 0) {
        for (var i=0; i < theForm.downloadFormat.length; i++) {
               if (theForm.downloadFormat[i].checked) {
                  formatValue = theForm.downloadFormat[i].value;
              }
        }
    } else {
        formatValue = theForm.downloadFormat.value;
    }

    // build request string
    var requestStr = buildXmlEventQuery(savedQueryForm);
    requestStr += "<format>"+formatValue+'</format>';
    if (theForm.emailResults.checked) {
        requestStr += "<emailAddress>"+theForm.emailAddress.value+"</emailAddress>";
        lastEmailAddress = theForm.emailAddress.value;
    }
    return requestStr;
}

function buildXmlEventQuery(theForm) {
  var noDates = theForm.allTime.checked;
  var minDateStr = buildDate(theForm.startdate_Year_ID.value, 
  							 theForm.startdate_Month_ID.selectedIndex+1, 
  							 theForm.startdate_Day_ID.selectedIndex+1);
  var maxDateStr = buildDate(theForm.enddate_Year_ID.value, 
  							 theForm.enddate_Month_ID.selectedIndex+1, 
  							 theForm.enddate_Day_ID.selectedIndex+1);
  var oContrib = getValue(theForm.oContrib.value,"%");
  var pContrib = getValue(theForm.pContrib.value,"%");
  var oAuthor = getValue(theForm.oAuthor.value,"%");
  
  var feName = getValue(theForm.regionName.value,"nil");
  var feRegion = getValue(theForm.seismicRegion.value,"nil");
  var feSubcode = getValue(theForm.regionSubcode.value,"nil");
  var noRegion = feName == "nil" && feRegion == "nil" && feSubcode == "nil";
  
  var eventStr = "<query>"+
  		   ( noDates ? "" :
               "<dateRange><startDate>"+minDateStr+"</startDate><stopDate>"+maxDateStr+"</stopDate></dateRange>" ) +
           "<areaBox>"+
               "<minLat>"+getValue(theForm.minLat.value,"-180")+"</minLat>"+
               "<maxLat>"+getValue(theForm.maxLat.value,"-180")+"</maxLat>"+
               "<minLon>"+getValue(theForm.minLon.value,"-180")+"</minLon>"+
               "<maxLon>"+getValue(theForm.maxLon.value,"180")+"</maxLon>"+
           "</areaBox>"+
           ( noRegion ?  "" :
               "<feRegion>"+
               	   ( feName == "nil" ? "" :  "<regionName>"+feName+"</regionName>" ) +
                   ( feRegion == "nil" ? "" : "<seismicRegion>"+feRegion+"</seismicRegion>" ) +
                   ( feSubcode ==  "nil" ? "" : "<regionSubcode>"+feSubcode+"</regionSubcode>" ) +
               "</feRegion>" ) +
           "<magQuery>"+
               "<magType>" + theForm.magtype.value + "</magType>"+
               "<minMag>"+getValue(theForm.minMag.value,"0")+"</minMag>"+
               "<maxMag>"+getValue(theForm.maxMag.value,"10")+"</maxMag>"+
               "<includeUnknowns>"+( theForm.includeUnknowns ? theForm.includeUnknowns.checked : false )+"</includeUnknowns>"+
           "</magQuery>" +
           "<depthRange>" +
               "<units>km</units>"+
               "<maxDepth>"+getValue(theForm.minDepthKm.value,"0")+"</maxDepth>"+
               "<minDepth>"+getValue(theForm.maxDepthKm.value,"6371")+"</minDepth>"+
           "</depthRange>"+
           "<originAuthor>"+oAuthor+"</originAuthor>"+
           "<originContributor>"+oContrib+"</originContributor>"+
           "<phaseContributor>"+pContrib+"</phaseContributor>"+
           "<includePhases>"+theForm.showPhases.checked+"</includePhases>"+
           "</query>";
    return eventStr;
}

function buildXmlNextRequest(key,pos) {
  var requestStr = "<key>"+key+"</key>" +
      "<position>"+pos+"</position>";
  return requestStr;
}

function buildDate( year, month, day ) {
  if (month.length == 1 || month < 10 ) { month = "0" + month; }
  if (day.length == 1 || day < 10 ) { day = "0" + day; }
  var dateStr = year + "-" + month + "-" + day + "T00:00:00.00+00:00";
  return dateStr;
}

function populateDownload(numResults) {
  var formHead = "<form action='javascript:void()' method='post' id='download_form'>"+
               "<table align='center' CELLPADDING='1' CELLSPACING='1' id='download'>" +
               "<tr><td><table>";

  var sizeRestriction =  "<tr><td colspan='5' ><em>NOTE: Total downloads are limited to "  + max_download_limit + " events.</em></td></tr>";
  
  var formats =  "<tr><td colspan='2'>Download Format :</td>"+
                 "<td colspan='2'><input type='radio' name='downloadFormat' value='ISF' checked>ISF (will always include available phase picks)</input> </td> </tr>"+
			     "<tr><td/><td/><td colspan='2'> <input type='radio' name='downloadFormat' value='XML'>XML</input> </td></tr>"+
                 "<tr><td/><td/><td colspan='2'> <input type='radio' name='downloadFormat' value='CSV'>CSV</input> </td> </tr>";

  var emailOnly = "<tr><td><div id='cb' style='visibility: hidden;'><input type='checkbox' name='emailResults' checked/></div></td>"+  // hidden checkbox
                  "<td>Email address: </td><td><input type='text' id='emailAddress' name='emailAddress' maxlength='50'/></td></tr>"+
                  // "<tr><td colspan='2'/><td colspan='3'><em>Only email notification is available for result sets > "  + downloadLimit + "</em></td></tr>"+
                  "<tr><td colspan='5' align='right'><em>Only email notification is available for result sets > "  + downloadLimit + "</em></td></tr>"+
                  "<tr><td colspan='2' align='right'><input type='button' id='downloadButton' onclick='download(this.form)' value='Send Email'/></td>";

  var emailSelect = "<tr><td> Email results : </td><td><input type='checkbox' name='emailResults' onclick='enableEmail(this)'/></td>"+
                    "<td>Email address : </td><td><input type='text' id='emailAddress' name='emailAddress' maxlength='50' disabled='true'/></td></tr>"+
                    "<tr><td colspan='2' align='right'><input type='button' id='downloadButton' onclick='download(this.form)' value='Generate File'/></td>";

  var formEnd = "<td colspan='2' align='left'><input type='button' id='newQueryButton' onclick='closeDownload()' value='Close'/></td></tr>" +
                "<tr><td colspan='5'></td></tr>" +
                "<tr><td colspan='5'><div id='downloadLink'></div></td></tr>"+
                "</table></td></tr></table></form>";

   if (numResults <= downloadLimit ) {
      return formHead + formats + emailSelect + formEnd;
   } else {
   		// NOTE: max_download_limit (defined above) must be kept in sync with PhaseQueryEngine ABS_MAX_NUM_EVENTS
   		if ( numResults > max_download_limit ) {  
          return formHead + sizeRestriction + formats + emailOnly + formEnd;
   		}
   		else {
          return formHead + formats + emailOnly + formEnd;
 		}  		
   }
}

// moved from phasePick.html
function enableMagQuery(checkbox)
{
	var minMag = document.getElementById( 'minMag' );
	var maxMag = document.getElementById( 'maxMag' );
	var magtype = document.getElementById( 'magtype' );
	var allMags = checkbox.checked;
	if ( allMags ) {
		lastMin = minMag.value;
		lastMax = maxMag.value;
		minMag.value = '';
		maxMag.value = '';
		minMag.style.backgroundColor = 'lightgrey';
		maxMag.style.backgroundColor = 'lightgrey';
	}
	else {
		minMag.value = lastMin;
		maxMag.value = lastMax;
		minMag.style.backgroundColor = '#ffffff';
		maxMag.style.backgroundColor = '#ffffff';
	}
	minMag.disabled = allMags;
	maxMag.disabled = allMags;
	magtype.disabled = allMags;
}

function enableDates(checkbox)
{
	var disable = checkbox.checked;
    document.forms[0].startdate_Year_ID.disabled = disable;
    document.forms[0].startdate_Month_ID.disabled = disable;
    document.forms[0].startdate_Day_ID.disabled = disable;
    document.forms[0].enddate_Year_ID.disabled = disable;
    document.forms[0].enddate_Month_ID.disabled = disable;
    document.forms[0].enddate_Day_ID.disabled = disable;
}

function enableEmail(checkbox)
{
	var emailAddress = document.getElementById( 'emailAddress' );
	var showEmail = checkbox.checked;
	if (showEmail) {
		emailAddress.value = lastEmailAddress;
		emailAddress.style.backgroundColor = '#ffffff';
		document.forms[1].downloadButton.value = 'Send Email';
	} else {
		lastEmailAddress = emailAddress.value;
		emailAddress.value = '';
		emailAddress.style.backgroundColor = 'lightgrey';
		document.forms[1].downloadButton.value = 'Generate File';
	}
	emailAddress.disabled = ! showEmail;
}
function resetForm(theForm)
{
	theForm.reset();
	var minMag = document.getElementById( 'minMag' );
	var maxMag = document.getElementById( 'maxMag' );
	var magtype = document.getElementById( 'magtype' );
	minMag.style.backgroundColor = '#ffffff';
	maxMag.style.backgroundColor = '#ffffff';
	minMag.disabled = false;
	maxMag.disabled = false;
	magtype.disabled = false;
	setAvailableData("");
	theForm.startdate_Year_ID.disabled = false;
	theForm.startdate_Month_ID.disabled = false;
	theForm.startdate_Day_ID.disabled = false;
	theForm.enddate_Year_ID.disabled = false;
	theForm.enddate_Month_ID.disabled = false;
	theForm.enddate_Day_ID.disabled = false;
	fillInDates();
	fetchPhaseDates(null);
}

function deny(evt)
{
	if ( evt.returnValue ) {
		evt.returnValue = false;
	} else if ( evt.preventDefault ) {
		evt.preventDefault();
	} else {
		return false;
	}
}

function checkNumeric(evt,textbox)
{
    evt = (evt) ? evt : ((event) ? event : null );
    if ( evt ) {
	    var charCode = ( evt.charCode || evt.charCode == 0 ) ? evt.charCode :
	    				(( evt.keyCode ) ? evt.keyCode : evt.which );
    	// alert("type:"+evt.type + ",code:"+evt.keyCode + ",char:"+evt.charCode);
    	if ( textbox && charCode == 46 ) { // decimal value allowed
    		var text = textbox.value;
    		if ( text.indexOf( '.' ) >= 0 ) {
    			return deny(evt);
    		}
    	}
    	else if ( charCode > 13 && (charCode < 48 || charCode > 57 )) {
    		return deny(evt);
    	}
    }
    return true;
}
// checks the display count against that allowed by the server
function checkDisplayCount(evt, textbox )
{
		if (checkNumeric(evt, textbox) ) {
			if (textbox.value > displayLimit) {
				textbox.value = displayLimit;
			}
		}
}

function checkBrowser() {
	try {
		var testProcessor = new XSLTProcessor();
	} catch (e) {
	  var safariTxt = "<h3> Our apologies, but your browser does not support XSLT processing.</h3>" +
		"It is a core core requirement for this web application. Some browsers with this capability are: "+
		"<a href='http://www.mozilla.com/'>Firefox</a>, " +
		"<a href='http://www.caminobrowser.org/'>Camino</a> or " +
		"<a href='http://www.apple.com/safari/'>Safari 3 beta</a>.<br/>";
		document.getElementById ('inputTable').innerHTML = safariTxt;
		document.getElementById ('outputTable').innerHTML = "";
	}
}

