SQLFieldNames=SQLTable=false
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 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('$'+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].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>2000) //& (s.indexOf('?')>0) & (s.toLowerCase().indexOf('.asp')>0)

  if(dopost) {
    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 ajax[n].open('GET',s,true)

  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 ASQL(s,func,p1,p2,p3,p4,p5) {
//  s=s.replace(/\%/g,'%25').replace(/\&/g,'%26').replace(/\+/g,'%2B').replace(/\#/g,'%23')
  s=encodeURIComponent(s)
  s='http://aesl.ces.uga.edu/scripts/SQL.asp?db=aas&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
//  clipboard(s)
  AJAX(s,func,p1,p2,p3,p4,p5)
} //ASQL

function QSQL(s,func,p1,p2,p3,p4,p5) {
//  s=s.replace(/\%/g,'%25').replace(/\&/g,'%26').replace(/\+/g,'%2B').replace(/\#/g,'%23')
  s=encodeURIComponent(s)
  s='http://aesl.ces.uga.edu/scripts/SQL.asp?db=query&SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
//  clipboard(s)
  AJAX(s,func,p1,p2,p3,p4,p5)
} //QSQL

function SQL(s,func,p1,p2,p3,p4,p5) {
//  s=s.replace(/\%/g,'%25%').replace(/\&/g,'%26%').replace(/\+/g,'%2B%').replace(/\#/g,'%23')
  s=encodeURIComponent(s)
  s='http://aesl.ces.uga.edu/scripts/SQL.asp?SQL='+s+'&FieldNames='+SQLFieldNames+'&Excel='+DoExcel+'&table='+(SQLTable?1:0)+'&Session='+ThisSession+'&User='+User
//  clipboard(s); alert(s.length)
//  alert(p1)
  AJAX(s,func,p1,p2,p3,p4,p5)
} //SQL

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) {window.clipboardData.setData("Text",s)}
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(' ')
    for(var i=0;i<o.length;i++) $(o[i]).style.display='none'
  }
  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 $(id).options[$(id).selectedIndex].innerHTML.trim()
  }catch(ee){return ''}
}

function selSet(id,value){
  try{
    for(var i=0;i<$(id).options.length;i++) if($(id).options[i].innerHTML==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)) throw SyntaxError("invalid 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
