fy='1112'
SQLFieldNames=SQLTable=false
SQLChar='$'
DoExcel=false
ThisSession=rndtime()
User=''

var ajax=[]
var aj2=[] //keep aj2 separate for IE6

String.prototype.trim = function() {return this.replace(/(^\s*)|(\s*$)/g, "")}

function destroy(id){$(id).parentNode.removeChild($(id))}

function chr(x){return String.fromCharCode(x)}

function getParen(id) {
  if($t(id)>'') {
    var s= $t(id).split('(')
    s=s[s.length-1].replace(')','')
//        alert(s)
    return s
  }
  else return -1
} //getParen

function IE()     {return !window.Node}
function Firefox(){return  window.Node}

function SetInnerText(obj,s) {
  if(!window.Node) obj.innerText=s
  else obj.textContent=s
}

function GetInnerText(obj) {
  if(!window.Node) return obj.innerText
  else return obj.textContent
}

function rndtime() {
  var r=new Date()
  return r.getDate()+r.getMilliseconds()+Math.random()
}

function Ready(x) {return x.readyState==4 && x.status==200}

function AJAXWrapper(n,p1,p2,p3,p4,p5) {
  return function() {
//    if(dopost) try{alert(ajax[n].responseText)}catch(ee){}
    if(Ready(ajax[n])) {
      if(window.Node) try{ajax[n].responseXML.normalize()} catch(ee){} //FireFox limits to 4096 characters otherwise

      if(aj2[n].FieldNames) {
        var r=ajax[n].responseText.split('^^')[0].split('|')
        for(var i=0;i<r.length;i++) try{
          var z=r[i].replace(/[^a-zA-Z0-9]/g,'')
          if(z!='') eval(aj2[n].SQLChar+z+'='+i)
        }catch(ee){alert('AJAXWrapper: '+r[i])}
      }

      aj2[n].func(ajax[n],p1,p2,p3,p4,p5)
      aj2[n]=ajax[n]=null

    }
  }
} //AJAXWrapper

//var dopost=false

function AJAX(s,func,p1,p2,p3,p4,p5) {
  var n=ajax.length
  aj2[n]=new Object()
  aj2[n].FieldNames=SQLFieldNames; SQLFieldNames=false
  aj2[n].SQLChar=SQLChar;          SQLChar='$'

//  aj2[n].FieldNames=false
  ajax[n]=window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):null

//NOTES: Post doesn't cache; Get has a URL limit of 2083 characters in IE
  dopost=(s.length>1000) //& (s.indexOf('?')>0) & (s.toLowerCase().indexOf('.asp')>0)

  if(dopost) {
//    alert(123)
    var z=s.split('\?')
    ajax[n].open('POST',z[0],true)
    ajax[n].setRequestHeader("Content-type", "application/x-www-form-urlencoded")
//    ajax[n].setRequestHeader("Content-length", z[1].length)
//    ajax[n].setRequestHeader("Connection", "close")
  }
  else try{
    ajax[n].open('GET',s,true)
  }catch(ee){alert(s)}

  if(func) {
    aj2[n].func=func
    ajax[n].onreadystatechange=AJAXWrapper(n,p1,p2,p3,p4,p5)
  }

/*
  if(window.Node) {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    ajax[n].overrideMimeType('charset=x-user-defined')
  }
*/

  if(dopost) ajax[n].send(z[1])
  else       ajax[n].send(null)

  return ajax[n]
} //AJAX

function AJAXPage(page,div) {
  function Gotit(x) {div.innerHTML=x.responseText}
  AJAX(page+'?'+ThisSession,Gotit)
} //AJAXPage

function SSQL(s,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&db=soildata&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //SSQL

function ASQL(s,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&db=aas&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //ASQL

function ASQL2(s,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&db=aas2&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //ASQL2

function SQL(s,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //SQL

function SQLPage(s,start,rows,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&SQL='+s+'&FieldNames='+SQLFieldNames+'&rows='+rows+'&start='+start+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //SQLPage

function QSQL(s,func,p1,p2,p3,p4,p5) {
//  s=encodeURIComponent(s).replace(/select/g,'tceles').replace(/Select/g,'tceleS').replace(/union/g,'noinu').replace(/count/g,'tnuoc').replace(/%20from%20/g,'%20morf%20').replace(/distinct/g,'tcnitsid')
  s=encodeURIComponent(s.split('').reverse().join(''))
  s='/scripts/SQL.asp?rev=true&db=query&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
  AJAX(s,func,p1,p2,p3,p4,p5)
} //QSQL

DTSQL=SQL

document.getElementsByClassName = function(cl) {
  var retnode = []
  var myclass = new RegExp('\\b'+cl+'\\b')
  var elem = this.getElementsByTagName('*')
  for (var i=0; i<elem.length; i++) {
    var classes = elem[i].className
    if (myclass.test(classes)) retnode.push(elem[i])
  }
  return retnode
}

function getElementsByClassName2(className, tag, elm){
  var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
  var tag = tag || "*";
  var elm = elm || document;
  var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
  var returnElements = [];
  var current;
  var length = elements.length;
  for(var i=0; i<length; i++){
          current = elements[i];
          if(testClass.test(current.className)){
                  returnElements.push(current);
          }
  }
  return returnElements;
}


function clipboard(s) {try{window.clipboardData.setData("Text",s)}catch(ee){}}
function getClipboard() {return window.clipboardData.getData("Text")}

function DOM(x,level,o) {
  if(!o) o=''
  if(level>0) {
    var s=''
    var to
    var val
    try {
      for(var i in x) {
        to=typeof x[i]
        if(to!='boolean' && to!='number' && to!='function') {
          if(i!='innerHTML' && i!='outerHTML' && i!='currentStyle' && i!='lastChild' && i!='firstChild' && i!='parentNode' && i!='previousSibling' && i!='nextSibling' && i!='attributes' && i!='all' && i!='childNodes' &&
             i!='activeElement' && i!='children' && i!='ownerDocument' && i!='offsetParent' && i!='parentElement' && i!='parentTextEdit' && i!='parentWindow' && i!='style' && i!='runtimeStyle' && i!='outerText' && i!='document' &&
             i!='contentEditable' && i!='readyState' && i!='nodeName' && i!='scopeName'
             ) {

            val=o+i+':'+to
            if(to=='string') {
              if(!x[i]) val=''
              else val+=':'+x[i].replace(/\</g,'&lt;')
            }
            if(val>'') {
              if(to=='object') s+=DOM(x[i],level-1,o+i+'.')+'\n' //s+='<li>'+val+'<ul>'+DOM(x[i],level-1,o+i+'.')+'</ul>\n'
              else s+='<li>'+val+'\n'
            }
          }
        }
      }
      for(var i=0;x.all[i];i++) s+=DOM(x.all[i],level-1,o+i+'.')+'\n'
    } catch(ee) {}
    return s
  }
  else return ''
} //DOM

function WalkDOM(x,level,o) {
  if(!level) level=2
  clipboard('<ul>'+DOM(x,level,o)+'</ul>')
  alert('z')
} //WalkDOM

function $(id) {return document.getElementById(id)}
function $v(id) {
  try{
    if($(id).tagName=='SELECT') return selValue(id)
    else if($(id).type.toUpperCase()=='RADIO') return RadioValue(id)
    else return $(id).value
  }
  catch(ee){alert('Error: '+id)}
}
function $t(id) {return $v(id).trim()}

function Print(s){
  try{
    var pf=document.createElement("IFRAME")
    pf.style.position='absolute'; pf.style.height='1px'; pf.style.width='1px'; pf.style.overflow='hidden'
    document.body.appendChild(pf);
    var oDoc = pf.contentWindow || pf.contentDocument; if(oDoc.document) oDoc=oDoc.document

    oDoc.write("<html><head><title></title></head><body onload='this.focus(); this.print();' style='font-family:Times New Roman;font-size:12pt'>"+s+"</body></html>")
    oDoc.close()
    pf.removeNode(true)
  }
  catch(e){window.print()}
} //Print

function updateAllDOMFields(theForm){
  var inputNodes= getAllFormFields(theForm)
  for(x=0; x<inputNodes.length; x++) updateDOM(inputNodes[x])
}  //updateAllDOMFields

function getAllFormFields(theForm){
  try{
    var inputFields = theForm.getElementsByTagName("input")
    var selectFields = theForm.getElementsByTagName("select")
    var textFields = theForm.getElementsByTagName("textarea")
    var array = new Array(inputFields + selectFields + textFields)
    for(i=0; i<array.length; i++) {
      for(x=0; x<inputFields.length; x++)  array[i++]= inputFields[x]
      for(a=0; a<selectFields.length; a++) array[i++]= selectFields[a]
      for(t=0; t<textFields.length; t++)   array[i++]= textFields[t]
    }
  }
  catch(e){alert("Error when evoking getAllFormFields(): \nSomething is probably wrong with the form you passed in\n\n"+e.message)}
  return array
}

function updateDOM(inputField) {    // if the inputField ID string has been passed in, get the inputField object
  if(typeof inputField == "string") inputField = document.getElementById(inputField)
  if(inputField.type == "select-one") {
    for(var i=0; i<inputField.options.length; i++)
      if(i==inputField.selectedIndex) inputField.options[inputField.selectedIndex].setAttribute("selected","selected")
  }
  else if(inputField.type=="text" || inputField.type=="textarea")
    inputField.setAttribute("value",inputField.value)
  else if(inputField.type=="checkbox" || inputField.type=="radio") {
    if(inputField.checked) inputField.setAttribute("checked","checked")
    else inputField.removeAttribute("checked")
  }
} //updateDOM

function purge(d) {
  var a = d.attributes, n
  if (a) {
    for(var i=0; i<a.length; i++) {
      n = a[i].name;
      if (typeof d[n]==='function') d[n]=null
    }
    a=d.childNodes;
    if(a) for (i=0; i<a.length; i++) purge(d.childNodes[i])
  }
} //purge

function RadioValue(obj) {
  var o=document.getElementsByName(obj)
  for(var i=0;i<o.length;i++) if(o[i].checked) return o[i].value
  return ''
} //RadioValue

function DefaultDisplay(o) {
  if(' ADDRESS BLOCKQUOTE BODY CENTER COL COLGROUP DD DIR DIV DL DT FIELDSET FORM hn HR IFRAME LEGEND LISTING MARQUEE MENU OL P PLAINTEXT PRE TABLE TD TH TR UL XMP '.indexOf(' '+o.tagName+' ')>-1) return 'block'
  else return 'inline'
} //DefaultDisplay

function ToggleDisplay(o) {
  if(typeof(o)=='string') {
    o=o.split(' ')
    for(var i=0;i<o.length;i++) {
      $(o[i]).style.display=$(o[i]).style.display=='none'?DefaultDisplay($(o[i])):'none'
    }
  }
  else if(o instanceof Array) {
    for(var i=0;i<o.length;i++) o[i].style.display=o[i].style.display=='none'?DefaultDisplay(o[i]):'none'
  }
  else {
    o.style.display=o.style.display=='none'?DefaultDisplay(o):'none'
  }
} //ToggleDisplay


function Hide(o) {
  if(o instanceof Array) {
    for(var i=0;i<o.length;i++) o[i].style.display='none'
  }
  else if(typeof(o)=='string') {
    o=o.split(' ')
    try{
      for(var i=0;i<o.length;i++) $(o[i]).style.display='none'
    }catch(ee){alert(o[i])}
  }
  else o.style.display='none'
} //Hide

function Show(o) {
  if(o instanceof Array) {
    for(var i=0;i<o.length;i++) o[i].style.display=DefaultDisplay(o[i])
  }
  else if(typeof(o)=='string') {
    o=o.split(' ')
    for(var i=0;i<o.length;i++) $(o[i]).style.display=DefaultDisplay($(o[i]))
  }
  else o.style.display=DefaultDisplay(o)
} //Show

function InputPrompt(inp,msg) {
//  if(typeof ip=='object') if(ip.value==omsg) ip.value=''
  omsg=msg
  ip=$(inp)
  ip.value=msg
  ip.focus()
  ip.z=0
  ip.si=setInterval(
          function(){
            if(ip.z++==10) {
              clearInterval(ip.si)
              ip.style.background='white'
              ip.select()
            }
            else {
              ip.style.background='#'+((ip.z*256+ip.z*16).toString(16))
            }
          }
          ,20)
} //InputPrompt

function ConfirmInput(inp,msg,b) {
  if(typeof b=='boolean') {
    if(b) return true
    alert(msg)
    InputPrompt(inp,$v(inp))
    return false
  }
  else {
    if($t(inp)>'' && $t(inp)!=msg) return true
    InputPrompt(inp,msg)
  }
  return false
} //ConfirmInput

function japp() {
 if(arguments.length<3) return
 var tmp=arguments[0]
 for(var i=1; i<arguments.length-1; i+=2) tmp[arguments[i]] = arguments[i+1]
}

function getMouseXY(e) {
  if(IE()) {
    x= e.clientX + document.body.scrollLeft
    y= e.clientY + document.body.scrollTop
  } else {
    x= e.pageX
    y= e.pageY
  }
  if (x<0){x= 0}
  if (y<0){y= 0}
  return {x:x,y:y}
}

function selValue(id){
  try{
    return GetInnerText($(id).options[$(id).selectedIndex]).trim()
  }catch(ee){return ''}
}

function selSet(id,value){
  try{
    for(var i=0;i<$(id).options.length;i++) if($(id).options[i].innerHTML.trim()==value) {
      $(id).selectedIndex=i
      return
    }
  }catch(ee){alert('selSet: '+id)}
}

function validDate(d) {
  var c=d.trim().split('/')
  if(c.length!=3) return false
  d=new Date(d)
  return (d.getMonth()+1==c[0]) && (d.getDate()==c[1]) && (d.getFullYear()==c[2])
} //validDate

function validTime(d) {
  d=d.trim().toUpperCase()
  d=d.replace('A',' A').replace('P',' P').replace('M','').replace(/\./g,'').replace(/ +/g,' ')

  var c=d.trim().split(':')
  if(c.length!=2) return false
  var h=c[0]*1
  if(h<1 || h>23) return false
  var z=c[1].split(' ')
  if(h<13 && z.length!=2) return false
  z[0]*=1
  if(z[0]<0 || z[0]>59) return false
  if(h<13 && z[1]!='A' && z[1]!='P') return false

  FixTime=h+':'+c[1]+'M'  //(z[1]>''?z[1]+'m':'')

  return true
} //validTime

function validDateTime(d) {
  var c=d.trim().split(' ')
  if     (c.length==2) return ValidDate(c[0]) && ValidTime(c[1])
  else if(c.length==3) return ValidDate(c[0]) && ValidTime(c[1]+' '+c[2])
  else return false
} //validDateTime

function cancelEvent(e){
  if (!e) var e = window.event
  e.cancelBubble = true
  if (e.stopPropagation) e.stopPropagation()
  e.returnValue = false
} //cancelEvent

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary

		date = date ? new Date(date) : new Date;

//              if (isNaN(date)) alert("invalid date: "+date)

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
}

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
}

// For convenience...
Date.prototype.format = function (mask, utc) {
  return dateFormat(this, mask, utc);
}

function toTable(x){
  var r=x.responseText.split('^^'); r.shift(); r.pop()
  for(var i in r) r[i]=r[i].split('|')
  return r
} //toTable

var emopts=[]
var emqtimer
function email(opts){
  if(!($('em_'))) {
    var s=[]
    s.push('<div style="display:none">')
    s.push(' <form id="em_" method="post" target="em_frame" action="/scripts/email.asp?">')
    s.push('  <input id="em_from"    name="em_from">')
    s.push('  <input id="em_to"      name="em_to">')
    s.push('  <input id="em_cc"      name="em_cc">')
    s.push('  <input id="em_bcc"     name="em_bcc">')
    s.push('  <input id="em_subject" name="em_subject">')
    s.push('  <textarea id="em_message" name="em_message"></textarea>')
    s.push('  <input type="submit" id="em_submit">')
    s.push(' </form>')
    s.push(' <iframe name="em_frame" zonload="emq()"></iframe>')
    s.push('</div>')
    var div=document.createElement('DIV')
    div.innerHTML=s.join('')
    document.body.appendChild(div)
  }

  emopts.push(opts)
//  if(emopts.length==1) {
    clearTimeout(emqtimer); emqtimer=setTimeout(emq,100)
//  }
} //email

function emq(){ //hopefully escape is not required

  function wrap(s){ //prevents exclamation points (!) at line wraps
//    return s.split('<').join('\n<')
    return s
  } //wrap

  if(emopts.length>0) {
    var opts=emopts.shift()
    $('em_').action+='1'
    $('em_from').value   =opts.from?opts.from:''
    $('em_to').value     =opts.to?opts.to:''
    $('em_cc').value     =opts.cc?opts.cc:''
    $('em_bcc').value    =opts.bcc?opts.bcc:''
    $('em_subject').value=opts.subject?opts.subject:''

    if(opts.id) $('em_message').value=wrap($(opts.id).innerHTML)
    else        $('em_message').value=wrap(opts.message?opts.message:'')

    if(opts.statusid) $(opts.statusid).innerHTML=opts.statusmsg

    $('em_submit').click()
    clearTimeout(emqtimer); emqtimer=setTimeout(emq,100)
  }
} //emq

function sortNumber(a,b) {return a-b}

function Simplify(a){
  function out(){
    if(lab1==lab2) s.push(lab1)
    else           s.push(lab1+'-'+lab2)
    lab1=lab2=a[i]
  } //out

  if(typeof a=='string') a=a.trim().replace(/,/g,' ').split(/[\s]+/g)
  if(a.length==0) return ''
  var a=a.sort(sortNumber)
  var lab1=lab2=a[0]*1
  var s=[]
  for(var i in a) {
    a[i]*=1
    if(i>0 && a[i]!=a[i-1]+1) {
      out()
    }
    lab2=a[i]*1
  }
  out()
  return s.join(', ').trim()
} //Simplify

function Separate(s){
  var l=[]
  var labs=s.trim().replace(/[\s]*\-[\s]*/g,'-')
  labs=labs.replace(/,/g,' ').split(/[\s]+/g)
  for(var j in labs){
    var ll=labs[j].split('-')
    if(ll.length==1) l.push(ll)
    else for(var k=ll[0]*1;k<=ll[1]*1;k++) l.push(k)
  }
  l.sort(sortNumber)
  return l
} //Separate

function parentTagName(obj,tag){
  while(obj.tagName!=tag) obj=obj.parentNode
  return obj
} //parentTagName

function right(x,len){while(x.toString().length<len) x='0'+x; return x.toString()}

function FYSelect(id,start,end,func,style){
  var s=['<select id="'+id+'" onchange="'+func+'" style="'+style+'">']
  var fy1=start.substr(2)
  var fy2=end.substr(2)
  for(var i=fy2;i>=fy1;i--) s.push('<option>'+right(i-1,2)+right(i,2))
  s.push('</select>')
  return s.join('')
} //FYSelect

function initDB(func){

  afy=fy.substr(2); if(afy.length==1) afy='0'+afy
  afyo=right(afy-1,2)
  fyo=right(afy-2,2)+''+right(afy-1,2)

  maxlab=[]
  SQL('select "So",max(lab) from So'+fy+' union all '+
      'select "An",max(lab) from An'+fy+' union all '+
      'select "Fe",max(lab) from Fe'+fy+' union all '+
      'select "Gr",max(lab) from Gr'+fy+' union all '+
      'select "Mi",max(lab) from Mi'+fy+' union all '+
      'select "Pe",max(lab) from Pe'+fy+' union all '+
      'select "Pl",max(lab) from Pl'+fy+' union all '+
      'select "Rc",max(lab) from Rc'+fy+' union all '+
      'select "Rs",max(lab) from Rs'+fy+' union all '+
      'select "So",max(lab) from So'+fy+' union all '+
      'select "Sp",max(lab) from Sp'+fy+' union all '+
      'select "To",max(lab) from To'+fy+' union all '+
      'select "Wa",max(lab) from Wa'+fy+' union all '+
      'select "Ww",max(lab) from Ww'+fy,
      function(x){
        var r=x.responseText.split('^^'); r.pop()
        for(var i in r) {
          var rec=r[i].split('|')
          maxlab[rec[0]]=rec[1]*1
        }
        maxlab['Soil']=Math.max(maxlab['Gr'],maxlab['So'],maxlab['Rs'],maxlab['To'])
        maxlab['FEW']=Math.max(maxlab['Fe'],maxlab['Mi'],maxlab['Ww'])
        if(func) func()
      }
     )
} //initDB

function ReadICP(file,fnc,opt){
  function fix1(v){
    v=v.replace('L','<')
    var lt=v.indexOf('<')>-1?'<':''
    v=v.replace('<','')
    return '<td>'+lt+(v*1).toFixed(dec)
  } //fix1

  if(opt) {
    var exc=opt.exclude
    if(exc) exc=' '+exc+' '
    else exc=''

    var dec=opt.dec
    if(!dec) dec=2
  }
  else {
    exc=''
    dec=2
  }

  AJAX(file,
       function(x){
        var r=x.responseText.split('Method:')
        var s=[]
        var first=true
        var d=[]

        for(var i in r){
          if(r[i].indexOf('Sample Name:')>-1){
            if(first){
              var units
              if(r[i].indexOf('LBS/ACRE')>-1) units='lbs/acre'
              else if(r[i].indexOf('ppm')>-1) units='ppm'
              else units='???'

              first=false
              var el=r[i].split('Elem')
              var els=''
              for(var j=1;j<el.length;j++) els+=el[j].split('\r')[0]
              els=els.trim().replace(/[ ]+/g,' ').split(' ')
              for(var j in els) els[j]=els[j].substr(0,2).replace('_','')

              s.push('<table style="border:1px solid black;margin:auto">')
              s.push('<tr><th colspan="2" style="border-right:1px solid black">Raw Data<th colspan="'+els.length+'">'+units)
              s.push('<tr><th style="background:#def">Date<th style="background:#def;border-right:1px solid black">Sample')
              for(var j in els) if(exc.indexOf(' '+els[j]+' ')==-1) s.push('<th style="background:#def">'+els[j])
            }

            var tim=r[i].split('Run Time: ')[1].split('\r')[0]
            var smp=r[i].split('Sample Name: ')[1].replace('Operator:','').split('\r')[0].replace(/[ ]+1/g,'').trim()

            var v=r[i].split('#1')
            var vs=''
            for(var j=1;j<v.length;j++) vs+=v[j].split('\r')[0]
            vs=vs.trim().replace(/[ ]+/g,' ').replace(/H/g,'').replace(/Q/g,'').replace(/L/g,'<').split(' ')

            var vv=[]
            for(var j in els) if(exc.indexOf(' '+els[j]+' ')==-1) vv.push(vs[j])
            var vs=vv

            s.push('<tr style="text-align:right"><td style="font-size:80%">'+tim+'<td style="text-align:left;border-right:1px solid black">'+smp)
            for(var j in vs) s.push(fix1(vs[j]))

            d.push({})
            var dl=d.length-1
            d[dl]['Time']=tim
            d[dl]['Samp']=smp
            d[dl].data=vs

            var k=0
            for(var j in els) {
              if(exc.indexOf(' '+els[j]+' ')==-1) d[dl][els[j]]=vs[k++]
            }
          }
        }

        var el=[]
        for(var j in els) if(exc.indexOf(' '+els[j]+' ')==-1) el.push(els[j])
        els=el

        s.push('</table>')
        if(fnc) fnc({html:s.join(''),elem:els,units:units,rec:d})
       }
      )
} //ReadICP

function findPos(obj) {
  var curleft = curtop = 0
  if (obj.offsetParent) do {
    curleft+= obj.offsetLeft
    curtop += obj.offsetTop
  } while (obj=obj.offsetParent)
  return [curleft,curtop]
} //findPos

