/*
  				wasql.js - used by WaSQL for menus, forms, etc.
  				----------------------------------------------
References:
	Events: http://www.quirksmode.org/js/events_advanced.html
		   http://www.quirksmode.org/js/eventexample.html
 		   http://www.quirksmode.org/js/introevents.html
  				----------------------------------------------
  	***********************************************************************
  	********************** Functions processed on load ********************
  	***********************************************************************
*/
var BrowserWidth=0;
var BrowserHeight=0;
var changeState = new Array();
var changeValue = new Array();
var MouseOver = new Array();
var MouseOut = new Array();
var MouseX=0;
var MouseY=0;
var OnLoad = "";
window.onload = function(){eval(OnLoad);}

if(document.addEventListener){
	document.addEventListener("mousedown",mouseMove,false);
    document.addEventListener("mousedup",mouseMove,false);
    document.addEventListener("mousemove",mouseMove,false);
	}
else if(document.onmousemove){
	document.onmousemove = mouseMove;
	}
else if(document.captureEvents){
	document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}

// Menu function to assign hover to li and hide w_select select tags on hover
sfHover = function() {
	//assign hover to li and hide w_select select tags on hover
	var navEls = GetElementsByAttribute('ul', 'id', 'w_nav');
	for (var n=0; n<navEls.length; n++) {
		var sfEls = navEls[n].getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
				showSelect(0);
				}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
				showSelect(1);
				}
			}
		}
	}
if (window.attachEvent){window.attachEvent("onload", sfHover);}

/* Code so that insertAdjacentHTML works in Mozilla Browsers*/
if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){
		switch (where){
			case 'beforeBegin':
				this.parentNode.insertBefore(parsedNode,this)
				break;
			case 'afterBegin':
				this.insertBefore(parsedNode,this.firstChild);
				break;
			case 'beforeEnd':
				this.appendChild(parsedNode);
				break;
			case 'afterEnd':
				if (this.nextSibling){
					this.parentNode.insertBefore(parsedNode,this.nextSibling);
					}
				else{this.parentNode.appendChild(parsedNode);}
				break;
			}
		}
	HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr){
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
		}
	HTMLElement.prototype.insertAdjacentText = function(where,txtStr){
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
		}
	}


//Drag
var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)
		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
}


/*
  	***********************************************************************
  	********************** Functions Defined for use ********************
  	***********************************************************************
*/

/* addDragToSelect - Adds a draggable img above select lists to select items in list */
function addSliderToSelect(sid){
	var obj = document.getElementById(sid);
	//get select object width.
	var dragimgobj = addSliderAbove(obj);
	var valcnt=obj.length;
	var w=Math.round(obj.offsetWidth-6);
	dragimgobj.onDrag = function(x, y) {
		var i=Math.round((x/w)*valcnt);
		if(i>= 0 && i < valcnt){obj[i].selected = true;}
		}
   	}

function addDragToTextarea(sid){
	var obj = document.getElementById(sid);
	//get select object width.
	var w=Math.round(obj.offsetWidth+10);
	var dragarea=obj.id+'_dragarea';
	var dragcheckbox=obj.id+'_dragcheckbox';
	var cx=findPosX(obj);
	var cy=findPosY(obj);
	var xpos=Math.round(cx+obj.offsetWidth-6);
	var ypos=Math.round(cy+obj.offsetHeight-12);
	var html = '<span parentid="'+sid+'" textareadrag="1" id="'+dragarea+'" style="position:absolute;left:'+xpos+'px;top:'+ypos+'px;cursor:crosshair;color:#7F9DB9;font-size:13pt;font-family:times;" title="Drag to adjust size">&#9688;</span>';
	var pobj=getParent(obj);
   	pobj.insertAdjacentHTML('beforeEnd',html);
   	var dragobj=document.getElementById(dragarea);
	Drag.init(dragobj);
	//var valcnt=obj.length;
	//var w=Math.round(obj.offsetWidth-6);
	dragobj.onDrag = function(x, y) {
		var pid = this.getAttribute('parentid');
		var obj = document.getElementById(pid);
		var w=Math.round(x-cx+6);
		var h=Math.round(y-cy+12);
		if(w > 0){obj.style.width = w+'px';}
		if(h > 0){obj.style.height = h+'px';}
		/*Look for any other dragable items and reset their position*/
  		var cid=this.id;
		var dragObjs = GetElementsByAttribute('span', 'textareadrag', '1');
  		for (var n=0; n<dragObjs.length; n++) {
	   		if(dragObjs[n].id != cid){
				var parentid = dragObjs[n].getAttribute('parentid');
				window.status=cid+","+dragObjs[n].id+","+parentid;
    				if(undefined != parentid){
					var cpobj = document.getElementById(parentid);
					var px=findPosX(cpobj);
					var py=findPosY(cpobj);
					var cxpos=Math.round(px+cpobj.offsetWidth-6);
					var cypos=Math.round(py+cpobj.offsetHeight-12);
					dragObjs[n].lastMouseX=cxpos;
					dragObjs[n].lastMouseY=cypos;
					dragObjs[n].style.left=cxpos+'px';
					dragObjs[n].style.top=cypos+'px';
		              }
		 		}
		 	}
		}
   	}

/* addDragToSelect - Adds a draggable img above select lists to select items in list */
function addSliderToText(sid,tvals,bvals){
	var obj = document.getElementById(sid);
	//get select object width.
	if(undefined != tvals){
		var topobj = addSliderAbove(obj);
		var valcnt=tvals.length;
		var w=Math.round(obj.offsetWidth-6);
		topobj.onDrag = function(x, y) {
			var i=Math.round((x/w)*valcnt);
			if(i>= 0 && i < valcnt){obj.value=tvals[i];}
			}
		}
	if(undefined != bvals){
		var botobj = addSliderBelow(obj);
		var valcnt=bvals.length;
		var w=Math.round(obj.offsetWidth-6);
		botobj.onDrag = function(x, y) {
			var i=Math.round((x/w)*valcnt);
			if(i>= 0 && i < valcnt){obj.value=bvals[i];}
			}
		}
   	}

/* timeClock - */
function addTimeClock(sid,live){
	if(undefined == live){live=1;}
	if(live == 1){this.setTimeout("addTimeClock('"+sid+"',1)",1000);}
     var dt = new Date();
     var h=dt.getHours();
     var m=dt.getMinutes();
     var s=dt.getSeconds();
     var p="AM";
     if(h > 12){h=h-12;p="PM";}
     setTimeBox(sid,h,m,s,p);
	}

/* addTimeSlider - Adds a draggable areas for hours and minutes */
function addTimeSlider(sid,ctime){
	var obj = document.getElementById(sid);
	if(undefined == ctime){addTimeClock(sid,0);}
	else{
		if(undefined != obj.value){obj.value=ctime;}
     	else if(undefined != obj.innerHTML){obj.innerHTML = ctime;}
	     }
	/* - Hours - */
	var topobj = addSliderAbove(obj,"&#8212;&#8212; Hours &#8212;&#8212;","Drag to adjust hours");
	var w=Math.round(obj.offsetWidth-6);
	topobj.onDrag = function(x, y) {
		var hr=Math.round(((x/w)*23)+1);
		var arr=obj.value.split(/[: ]/);
		var m=0;
		var s=0;
		var p="AM";
		if(undefined !=arr[1]){m=arr[1];}
		if(undefined !=arr[2]){s=arr[2];}
		if(undefined !=arr[3]){p=arr[3];}
		if(hr > 12){h=hr-12;p="PM";}
		else{h=hr;p="AM";}
		setTimeBox(sid,h,m,s,p);
		}
	/* - Bottom Slider - Minutes - */
	var botobj = addSliderBelow(obj,"&#8212;&#8212; Minutes &#8212;","Drag to adjust minutes");
	botobj.onDrag = function(x, y) {
		var m=Math.round((x/w)*59);
		var arr=obj.value.split(/[: ]/);
		var h=0;
		var s=0;
		var p="AM";
		if(undefined !=arr[0]){h=arr[0];}
		if(undefined !=arr[2]){s=arr[2];}
		if(undefined !=arr[3]){p=arr[3];}
		setTimeBox(sid,h,m,s,p);
		}
   	}
/*http://www.quirksmode.org/js/findpos.html*/
function findPosX(xobj){
	var curleft = 0;
	if (xobj.offsetParent){
		while (xobj.offsetParent){
			curleft += xobj.offsetLeft
			xobj = xobj.offsetParent;
			}
		}
	else if (xobj.x){curleft += xobj.x;}
	return curleft;
	}

function findPosY(yobj){
	var curtop = 0;
	if (yobj.offsetParent){
		while (yobj.offsetParent){
			curtop += yobj.offsetTop
			yobj = yobj.offsetParent;
			}
		}
	else if (yobj.y){curtop += yobj.y;}
	return curtop;
	}

function setTextWrap(sid,c){
     var obj = document.getElementById(sid);
     if(c){
		obj.setAttribute('wrap','off');
		}
     else{
		obj.setAttribute('wrap','hard');
		}
     return false;
	}
function addSliderAbove(obj,txt,title){
	//get select object width.
	var w=Math.round(obj.offsetWidth);
	var dragimg=obj.id+'_sliderimgTop';
	var dragbox=obj.id+'_sliderboxTop';
	var linex=Math.round(w/11);
	var line = '';
	if(undefined == title){title='';}
	if(undefined != txt){line=txt;}
	else{
		for(var x=0;x<linex;x++){line += '&#8212';}
		}
	var html = '<div title="'+title+'" id="'+dragbox+'" style="width:'+w+'px;font-size:9px;color:#7F9DB9;font-family:arial;visibility:hidden;" valign="bottom"><span id="'+dragimg+'" style="position:relative;cursor:crosshair;">&#9660;</span>'+line+'</div>';
	var pobj=getParent(obj)
   	pobj.insertAdjacentHTML('afterBegin',html);
   	var dragtopobj=document.getElementById(dragimg);
   	var dragbotbox=document.getElementById(dragbox);
   	/* onmouseover */
   	var efunc = pobj.getAttribute('msover');
   	if(efunc == null){efunc='';}
   	pobj.setAttribute('msover',efunc+"document.getElementById('"+dragbox+"').style.visibility='visible';");
   	pobj.onmouseover = function(){
          var efunc = this.getAttribute('msover');
          if(efunc.length){eval(efunc);}
	     }
	/* onmouseout */
     efunc = pobj.getAttribute('msout');
   	if(efunc == null){efunc='';}
   	pobj.setAttribute('msout',efunc+"document.getElementById('"+dragbox+"').style.visibility='hidden';");
   	pobj.onmouseout = function(){
          var efunc = this.getAttribute('msout');
          if(efunc.length){eval(efunc);}
	     }
	w=Math.round(w-6);
	Drag.init(dragtopobj, null,0,w,false,false);
	return dragtopobj;
   	}
function addSliderBelow(obj,txt,title){
	//get select object width.
	var w=Math.round(obj.offsetWidth);
	var dragimg=obj.id+'_sliderimgBot';
	var dragbox=obj.id+'_sliderboxBot';
	var linex=Math.round(w/12);
	var line = '';
	if(undefined == title){title='';}
	if(undefined != txt){line=txt;}
	else{
		for(var x=0;x<linex;x++){line += '&#8212';}
		}
	var html = '<div title="'+title+'" id="'+dragbox+'" style="width:'+w+'px;font-size:9px;color:#7F9DB9;font-family:arial;visibility:hidden;" valign="top"><span id="'+dragimg+'" style="position:relative;cursor:crosshair;">&#9650;</span>'+line+'</div>';
	var pobj=getParent(obj)
	pobj.insertAdjacentHTML('beforeEnd',html);
   	var dragbotobj=document.getElementById(dragimg);
   	var dragbotbox=document.getElementById(dragbox);
   	/* onmouseover */
   	var efunc = pobj.getAttribute('msover');
   	if(efunc == null){efunc='';}
   	pobj.setAttribute('msover',efunc+"document.getElementById('"+dragbox+"').style.visibility='visible';");
   	pobj.onmouseover = function(){
          var efunc = this.getAttribute('msover');
          if(efunc.length){eval(efunc);}
	     }
	/* onmouseout */
	efunc = pobj.getAttribute('msout');
   	if(efunc == null){efunc='';}
   	pobj.setAttribute('msout',efunc+"document.getElementById('"+dragbox+"').style.visibility='hidden';");
   	pobj.onmouseout = function(){
          var efunc = this.getAttribute('msout');
          if(efunc.length){eval(efunc);}
	     }
	w=Math.round(w-6);
	Drag.init(dragbotobj, null,0,w,false,false);
	return dragbotobj;
   	}

//apendText(fld,$val)
function appendText(fld,val,lf){
	var cval=trim(fld.value);
	fld.value=cval + val;
	if(lf){
		cval=trim(fld.value);
		fld.value=fld.value + "\r\n";
		}
	fld.focus();
	}

//checkAllByAttribute(tag, att, val)
function checkAllByAttribute(c,att, val){
	var list = GetElementsByAttribute('input', att, val);
          for(var i=0;i<list.length;i++){
		if(list[i].type == 'checkbox' || list[i].type == 'radio'){list[i].checked = c;}
		}
	}
//getCheckboxValues(tagname)
function getCheckedValues(tagname){
	var list = GetElementsByAttribute('input', 'name', tagname);
	var clist;
     for(var i=0;i<list.length;i++){
		if(list[i].type == 'checkbox' || list[i].type == 'radio'){
			var cval=list[i].value;
			if(list[i].checked && cval.length>0){clist += cval+':';}
			}
		}
	}

// checkAllElements - check/toggle all checkboxes that have an attribute of value
function checkAllElements(att,val,ck){
        //show all tags tag with attribute att that has a value of val
        //returns number of items checked
        var cust=GetElementsByAttribute('input',att,'^'+val+'$');
        var cnt = 0;
        for(var i=0;i<cust.length;i++){
	   	 if(cust[i].type=='checkbox'){cust[i].checked=ck;cnt++;}
           }
        if (ck){return cnt;}
	   return 0;
        }

//CheckMouseEnter
function checkMouseEnter (element, evt) {
	   if (element.contains && evt.fromElement) {
	        return !element.contains(evt.fromElement);
		   }
	   else if (evt.relatedTarget) {
	   	   return !containsDOM(element, evt.relatedTarget);
		   }
	   }

// checkMouseLeave
function checkMouseLeave (element, evt) {
	   //window.status=evt;
	   //return;
	   if (element.contains && undefined != evt.toElement) {
	        return !element.contains(evt.toElement);
		   }
	   else if (evt.relatedTarget) {
		   return !containsDOM(element, evt.relatedTarget);
		   }
	   }

//containsDOM - does container have containee
function containsDOM (container, containee) {
	   var isParent = false;
	   do {
	        if ((isParent = container == containee)){break;}
		   containee = containee.parentNode;
		   }
 	   while (containee != null);
	   return isParent;
	   }
function fixE(e){
	if (typeof e == 'undefined'){e = window.event;}
	if (typeof e.layerX == 'undefined'){e.layerX = e.offsetX;}
	if (typeof e.layerY == 'undefined'){e.layerY = e.offsetY;}
	return e;
	}
// Get browser width and height
function getBrowserWH() {
	if(document.all) {
		BrowserWidth = document.body.offsetWidth;
		BrowserHeight = document.body.offsetHeight;
		}
	else{
		BrowserWidth = window.innerWidth;
		BrowserHeight = window.innerHeight;
		}
	}

// GetElementsByAttribute - returns an array of tags that have an attribute of value.
function GetElementsByAttribute(tag, att, val){
        //GetElementsByAttribute(tagname, attributename,stringtomatch)
        var a, list, found = new Array(), re = new RegExp(val, 'i');
        //if(undefined != document.getElementsByTagName(tag)){return found;}
        list = document.getElementsByTagName(tag);
        //alert("Found "+list.length+" tags with name of "+tag+" ,checking for "+att+" with a val of "+val);
        for (var i = 0; i < list.length; ++i) {
            a = list[i].getAttribute(att);
            if (undefined == a){a = list[i][att];}
            //alert(i+", a="+a+" type="+typeof(a));
            if (typeof(a)=='string' && (val.length==0 || a.search(re) != -1)) {
               found[found.length] = list[i];
               //alert("Found a match");
               }
            }
        return found;
        }
        
/* getParent - gets parent object or its parent if parent is P or FORM */
function getParent(obj){
	if(undefined == obj){return obj;}
	if(undefined == obj.parentNode){return obj;}
	var pobj=obj.parentNode;
	if(pobj.tagName != 'P' && pobj.tagName != 'FORM'){return pobj;}
	var type=typeof(pobj);
	if(type == "object"){return getParent(pobj);}
	}

//Resize textarea boxes to browser w,h
function growBox(fld){
	getBrowserWH();
	fld.style.width=BrowserWidth-40+"px";
	fld.style.height=BrowserHeight-MouseY-60+"px";
	}

// hideElements - hide all tags with an attribute of value
function hideElements(tag,att,val){
	var cust=GetElementsByAttribute(tag,att,'^'+val+'$');
     for(var i=0;i<cust.length;i++){
	     cust[i].style.display='none';
          }
	}

/* initDrop */
function initDrop(tagname,tagatt,attval){
	//make w_dropdown fields hide display on mouse out
	if(undefined == tagname){tagname='div';}
	if(undefined == tagatt){tagatt='behavior';}
	if(undefined == attval){attval='dropdown';}
	var navEls = GetElementsByAttribute(tagname,tagatt,attval);
	//alert(navEls.length+" "+tagname+" "+tagatt+" "+attval);
	for (var n=0; n<navEls.length; n++) {
		navEls[n].onmouseout=function(e) {
			if(undefined == e){e = fixE(e);}
			if(undefined != e){
				if(checkMouseLeave(this,e)){
					this.style.display='none';
					/*Check for onhide attribute*/
					var onhide=this.getAttribute('onhide');
					//window.status="onhide="+onhide;
					if(onhide){eval(onhide);}
					}
				}			
			}
		}
	}
/* initDrop */
function initPin(obj,minwidth,maxwidth){
	//make w_dropdown fields hide display on mouse out
	if(undefined == obj){return false;}
	obj.onmouseout=function(e) {
		if(undefined == e){e = fixE(e);}
		if(undefined != e){
			if(checkMouseLeave(this,e)){
				this.style.width=minwidth+'px';
				}
			}
		}
	obj.onmouseover=function(e) {
		if(undefined == e){e = fixE(e);}
		if(undefined != e){
			if(checkMouseEnter(this,e)){
				this.style.width=maxwidth+'px';
				}
			}
		}
	}

//Capture mouse movement and set MouseX and MouseY to its x,y corordinates
function mouseMove(e) {
	if(document.all) {
		MouseX = event.x + document.body.scrollLeft;
		MouseY = event.y + document.body.scrollTop;
		}
	else{
		MouseX = e.pageX;
		MouseY = e.pageY;
		}
	}

//Replace text in a textarea
function replaceText(fld,s,r,i){
	var opt = 'ig';
	if(i){opt = 'g';}
	var regexp = new RegExp(s,opt);
	var body=fld.value;
	var newval = body.replace(regexp,r);
	fld.value=newval;
	}

/* showDrop */
function showDrop(oid,h){
	var navEls = GetElementsByAttribute('div','id',oid);
	for (var i=0; i<navEls.length; i++) {
          if(undefined != h){
			if(h==1){navEls[i].style.display='none';}
			}
          else if(navEls[i].style.display=='block'){navEls[i].style.display='none';}
          else{navEls[i].style.display='block';}
	     }
     return false;
	}

// showElements - show all tags with an attribute of value
function showElements(tag,att,val){
        var cust=GetElementsByAttribute(tag,att,'^'+val+'$');
        for(var i=0;i<cust.length;i++){
           cust[i].style.display='block';
           }
        }

// showProperties - shows the properties of any element
function showProperties(obj){
	var str="Properties that have values for :" + obj + "\n";
	var namestr='';
	for(name in obj){
		if(obj[name]){
			//typeof returns "number" "string" "boolean" "function" "undefined" "object"
			var type=typeof(obj[name]);
			if(type != "object" && type != "function"){str += "[" + name + "]["+type+"] = " + obj[name] + "\n";}

			}
		namestr += name + ", ";
		}
	str += "\n\n Click OK to show all possible values\n\n";
	var y=confirm(str);
	if(y){alert(namestr);}
  	}
  	
/* showSelect */
function showSelect(t){
	//show-hide select tags where id="w_select", if t==1, then show, else hide
	var selEls = GetElementsByAttribute('select', 'id', 'w_select');
	for (var s=0; s<selEls.length; s++) {
		if(t){selEls[s].style.visibility='visible';}
		else{selEls[s].style.visibility='hidden';}
		}
	}

//submitForm -- parses through theForm and validates input based in additonal field attributes
// Possible attributes are: required="1" mask="^[0-9]" maskmsg="Age must begin with a number" maxlength="23"
function submitForm(theForm){
	if(undefined == theForm){return false;}
	//alert("theForm type="+typeof(theForm));
	if(theForm.length ==0){return false;}
	for(var i=0;i<theForm.length;i++){
		var dname=theForm[i].name;
		if(theForm[i].getAttribute('displayname')){dname=theForm[i].getAttribute('displayname');}
		var msg=dname+" is required";
	    if(theForm[i].getAttribute('requiredmsg')){msg=theForm[i].getAttribute('requiredmsg');}
	  	/* Password confirm */
	  	if(dname == 'password_confirm'){continue;}
	  	if(dname == 'password'){
			if(undefined != theForm.password_confirm){
				var confirm=1;
				if(undefined != theForm.is_register){
					var val=theForm.is_register.value;
					if(val.length==0 || val != 1){confirm=0;}
					//alert("val="+val+', confirm='+confirm);
					}
				if(confirm == 1){
			  		if(theForm.password_confirm.value.length == 0){
						alert('Password confirmation is required');
		                if(theForm[i].type!='hidden'){theForm[i].focus();}
		                return false;
		            	}
		            if(theForm[i].value.length == 0){
						alert('Password is required');
		                if(theForm[i].type!='hidden'){theForm[i].focus();}
		                return false;
		            	}
		            if(theForm[i].value != theForm.password_confirm.value){
						alert('Passwords do not match.  Please retype password.');
		                if(theForm[i].type!='hidden'){theForm[i].focus();}
		                return false;
		            	}
		  			}
	  			}
			}

        //check for required attribute
        if(theForm[i].getAttribute('required') && theForm[i].getAttribute('required') == 1){
			var showalert=0;
			if(theForm[i].type=='checkbox'){
				if(!theForm[i].checked){showalert=1;}
				}
			else if (theForm[i].value==''){showalert=1;}
			if(showalert){
				alert(msg);
	            if(theForm[i].type!='hidden'){theForm[i].focus();}
	            return false;
	            }
            }
            //check for mask attribute - a filter to test input against
            if(theForm[i].getAttribute('mask') && theForm[i].getAttribute('mask').value != '' && theForm[i].value != ''){
                var mask=theForm[i].getAttribute('mask');
                if(mask != 'searchandreplace'){
                //alert("mask="+mask);
                var re = new RegExp(mask, 'i');
                if(re.test(theForm[i].value) == false){
                    var msg = dname+" must be of type "+mask;
                    if(theForm[i].getAttribute('maskmsg')){msg=theForm[i].getAttribute('maskmsg');}
                    alert(msg);
                    if(theForm[i].type!='hidden'){theForm[i].focus();}
                    return false;
                    }
           	}
                }
            //check for length attribute on textarea fields
            //alert(theForm[i].type);
            if(theForm[i].type == 'textarea' && theForm[i].getAttribute('maxlength')){
                var len=theForm[i].value.length;
                var max=Math.abs(theForm[i].getAttribute('maxlength'));
                if(len > max){
                    var msg = dname+" must be less than "+max+" characters\nYou entered "+len+" characters.";
                    alert(msg);
                    if(theForm[i].type!='hidden'){theForm[i].focus();}
                    return false;
                    }
                }
            }
        return true;
	}

//--Submit form using ajax
function ajaxSubmitForm(theform,sid,tmeout) {
	if(undefined == theform){
		alert("No form object passed to submitForm");
		return false;
		}
	/* submitForm first*/
	var ok=submitForm(theform);
	if(!ok){return false;}
	if(undefined == tmeout || tmeout < 15000){tmeout=15000;}
	var status = AjaxRequest.submit(
		theform,{
			'groupName':sid
			,'timeout':tmeout
			,'onSuccess':function(req){
				var sid=this.groupName;
				if(undefined != sid){
					//alert(req.responseText);
					//alert(sidObj.innerHTML);
					var val=trim(req.responseText);
					if(document.getElementById(sid)){document.getElementById(sid).innerHTML = val;}
					else{alert('ajaxSubmitForm could not find sid:'+sid);}
					}
				else if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = 'Cant Find sid:'+sid;}
				}
			,'onGroupBegin':function(req){
				if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = 'Submiting ...';}
	               }
          	,'onGroupEnd':function(req){
				if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = ' ';}
	               }
	     	,'onTimeout':function(req){
				if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = 'Timed out';}
				else{alert('Ajax timed out'+req.statusText);}
				}
	     	,'onError':function(req){
				if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = 'Error:'+req.statusText+req.responseText;}
				else{alert('Error:'+req.statusText+req.responseText);}
				}
  			}
	  	);
	return status;
	}


//Ajax get call
function callWaSQL(id,name,params){
	//get GUID cookie and pass it in
	var guid=getCookie('GUID');
	AjaxRequest.get(
 		{
    		'url':'/cgi-bin/wasql.pl?'+id+'&guid='+guid+params
    		,'onSuccess':function(req){
  		     var name = this.groupName;
			document.getElementById(name).innerHTML = req.responseText;
			}
    		,'timeout':15000
		,'groupName':name
		,'onGroupBegin':function(req){
			if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = 'Loading ...';}
               }
          ,'onGroupEnd':function(req){
			if(document.getElementById('ajaxstatus')){document.getElementById('ajaxstatus').innerHTML = ' ';}
               }
    		,'onTimeout':function(req){
			var name = this.groupName;
			document.getElementById(name).innerHTML = "<b style=\"color:red\">Timed Out Error</b>";
			}
  		}
		);
	return false;
	}
/*checkPerl*/
function checkPerl(field,value){
	if(undefined == document._perlcheck){
		alert('document._perlcheck does not exist.');
		return false;
		}
	var pfield=field+"_perlcheck";
	if(undefined == value){
		alert('Nothing to check.');
		return false;
		}
	if(value.length ==0){
		alert('Nothing to check.');
		return false;
		}
	document.getElementById(pfield).innerHTML ='<img src="/wfiles/busy.gif" title="checking Perl syntax" border="0" width="12" height="12">';
	document._perlcheck.perlcheck.value=value;
	ajaxSubmitForm(document._perlcheck,pfield,5);
	return false;
	}
//getUrl - use ajax to get url
function getUrl(url,msg,gid,msgid){
	if(undefined == gid){gid='ajaxcontent';}
	if(undefined == document.getElementById(gid)){
		alert("getUrl Error: "+gid+" is not defined");
		return false;
	        }
	if(undefined == msgid){msgid='ajaxstatus';}
	if(undefined == msg){msg='Loading...';}
	AjaxRequest.get(
 		{
    		'url':url
    		,'onSuccess':function(req){
			var name = this.groupName;
			document.getElementById(gid).innerHTML = req.responseText;
			}
    		,'timeout':5000
		,'groupName':url
		,'onGroupBegin':function(req){
			if(document.getElementById(msgid)){document.getElementById(msgid).innerHTML = msg;}
               		}
               ,'onGroupEnd':function(req){
			if(document.getElementById(msgid)){document.getElementById(msgid).innerHTML = ' ';}
               		}
    		,'onTimeout':function(req){
			var name = this.groupName;
			document.getElementById(gid).innerHTML = "<b style=\"color:red\">Timed Out Error:"+name+" not found.</b>";
			}
		,'onFailure':function(req){
			var name = this.groupName;
			document.getElementById(gid).innerHTML = "<b style=\"color:red\">"+name+" not found.</b>";
			}
  		}
		);
	return false;
	}
	
//get Cookie with said name
function getCookie(name){
	name = trim(name);
	var cookies = document.cookie.split(";");
	var tmp;
	for (var i=0; i<cookies.length; i++){
		tmp = cookies[i].split("=");
		if (trim(tmp[0]) == name){return unescape(trim(tmp[1]));}
		}
	return null;
	}

// showAtMouse - show object at current mouse position.  Adjust position for browser edges.
function showAtMouse(obj){
    if(undefined == obj){
		alert('Error in placeObj\nnot a valid object');
		return;
    	}
    //Determine browser width,height
    var bw=getWidth(window);
	var bh=getHeight(window);
	//determine obj width
    var ow=getWidth(obj);
	var oh=getHeight(obj);
	//Get Mouse position
	var x=MouseX;
	if((MouseX+ow) > bw){x=bw-ow;}
	var y=MouseY;
	if((MouseY+oh) > bh){y=bh-oh;}
	obj.style.position='absolute';
	obj.style.top=y+'px';
	obj.style.left=x+'px';
	obj.style.display='block';
    }

//trim - remove beginning and ending spaces
function trim(value){
	if (null != value && undefined != value && "" != value){
	     return value.replace(/^\s\0\r\n\t*|\s\0\r\n\t*$/g,"");
		}
	else{return "";}
	}
// -- processMultiComboBox
function processMultiComboBox(tid,cid,tcnt,cm,showvalues){
     var tbox=document.getElementById(tid);
	var cbox=document.getElementById(cid);
	if(cm && cbox){
	     if(cbox.checked){cbox.checked = false;}
		else{cbox.checked = true;}
		}
	var list = GetElementsByAttribute('input','name',tid);
	var cnt=0;
	var val='';
	for(var i=0;i<list.length;i++){
		if(list[i].checked){
			if(showvalues){val += list[i].value+",";}
			cnt++;
			}
		}
	if(showvalues){tbox.value=val;}
	else{tbox.value=cnt+"/"+tcnt+" selected";}
	}

//Determine if an objects value has changed
function setChangeState(tid){
     var el=document.getElementById(tid);
     changeState[tid]=el.value;
     //alert(changeState[tid]);
     }

function setChangeValue(tid,val){
     changeValue[tid]=val;
     }

function evalChange(tid){
	eval(changeValue[tid]);
	}

function hasChanged(tid){
     var el=document.getElementById(tid);
     var changed=0;
     var val=el.value;
     var old=changeState[tid];
     if(val != old){changed++;}
     if(changed){return true;}
     return false;
     }

function setTimeBox(sid,h,m,p){
     var box=document.getElementById(sid);
     if(undefined == box){alert("no box in setTimeBox");return false;}
     var timestr='';
     h=Math.round(h);
     m=Math.round(m);
     if(h<10){timestr +="0";}
     timestr += h;
     timestr += ":";
     if(m<10){timestr +="0";}
     timestr += m;
     timestr +=p;
     if(undefined != box.value){box.value=timestr;}
     else if(undefined != box.innerHTML){box.innerHTML = timestr;}
     //alert(timestr);
	return;
	}
/*http://forum.context.cx/Themes/default/script.js*/

var smf_formSubmitted = false;

// Define document.getElementById for Internet Explorer 4.
if (typeof(document.getElementById) == "undefined")
	document.getElementById = function (id)
	{
		// Just return the corresponding index of all.
		return document.all[id];
	}

// Open a new window in a smaller popup.
function reqWin(desktopURL, alternateWidth, alternateHeight)
{
	window.open(desktopURL, 'requested_popup', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=' + (alternateWidth ? alternateWidth : 480) + ',height=' + (alternateHeight ? alternateHeight : 220) + ',resizable=no');

	// Return false so the click won't follow the link ;).
	return false;
}

// Remember the current position.
function storeCaret(text)
{
	// Only bother if it will be useful.
	if (typeof(text.createTextRange) != 'undefined')
		text.caretPos = document.selection.createRange().duplicate();
}

// Replaces the currently selected text with the passed text.
function replaceText(text, textarea)
{
	// Attempt to create a text range (IE).
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
			textarea.focus();
			textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put it on the end.
	else
	{
		textarea.value += text;
		textarea.focus(textarea.value.length - 1);
	}
}

// Surrounds the selected text with text1 and text2.
function surroundText(text1, text2, textarea)
{
	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
		caretPos.select();
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}

// Checks if the passed input's value is nothing.
function isEmptyText(theField)
{
	// Copy the value so changes can be made..
	var theValue = theField.value;

	// Strip whitespace off the left side.
	while (theValue.length > 0 && (theValue.charAt(0) == ' ' || theValue.charAt(0) == '\t'))
		theValue = theValue.substring(1, theValue.length);
	// Strip whitespace off the right side.
	while (theValue.length > 0 && (theValue.charAt(theValue.length - 1) == ' ' || theValue.charAt(theValue.length - 1) == '\t'))
		theValue = theValue.substring(0, theValue.length - 1);

	if (theValue == '')
		return true;
	else
		return false;
}

// Set the "inside" HTML of an element.
function setInnerHTML(element, toValue)
{
	// IE has this built in...
	if (typeof(element.innerHTML) != 'undefined')
		element.innerHTML = toValue;
	else
	{
		var range = document.createRange();
		range.selectNodeContents(element);
		range.deleteContents();
		element.appendChild(range.createContextualFragment(toValue));
	}
}

// Set the "outer" HTML of an element.
function setOuterHTML(element, toValue)
{
	if (typeof(element.outerHTML) != 'undefined')
		element.outerHTML = toValue;
	else
	{
		var range = document.createRange();
		range.setStartBefore(element);
		element.parentNode.replaceChild(range.createContextualFragment(toValue), element);
	}
}

// Get the inner HTML of an element.
function getInnerHTML(element)
{
	if (typeof(element.innerHTML) != 'undefined')
		return element.innerHTML;
	else
	{
		var returnStr = '';
		for (var i = 0; i < element.childNodes.length; i++)
			returnStr += getOuterHTML(element.childNodes[i]);

		return returnStr;
	}
}

function getOuterHTML(node)
{
	if (typeof(node.outerHTML) != 'undefined')
		return node.outerHTML;

	var str = '';

	switch (node.nodeType)
	{
		// An element.
		case 1:
			str += '<' + node.nodeName;

			for (var i = 0; i < node.attributes.length; i++)
			{
				if (node.attributes[i].nodeValue != null)
					str += ' ' + node.attributes[i].nodeName + '="' + node.attributes[i].nodeValue + '"';
			}

			if (node.childNodes.length == 0 && in_array(node.nodeName.toLowerCase(), ['hr', 'input', 'img', 'link', 'meta', 'br']))
				str += ' />';
			else
				str += '>' + getInnerHTML(node) + '</' + node.nodeName + '>';
			break;

		// 2 is an attribute.

		// Just some text..
		case 3:
			str += node.nodeValue;
			break;

		// A CDATA section.
		case 4:
			str += '<![CDATA' + '[' + node.nodeValue + ']' + ']>';
			break;

		// Entity reference..
		case 5:
			str += '&' + node.nodeName + ';';
			break;

		// 6 is an actual entity, 7 is a PI.

		// Comment.
		case 8:
			str += '<!--' + node.nodeValue + '-->';
			break;
	}

	return str;
}

// Checks for variable in theArray.
function in_array(variable, theArray)
{
	for (var i = 0; i < theArray.length; i++)
	{
		if (theArray[i] == variable)
			return true;
	}
	return false;
}

/*isBDReservedWord*/
function isDBReservedWord(word){
	var reservedwords = new String("add;all;allfields;alter;and;as;asc;auto_increment;between;bigint;bit;binary;blob;both;by;cascade;char;character;change;check;column;columns;create;data;database;databases;date;datetime;day;day_hour;day_minute;day_second;dayofweek;dec;decimal;default;delete;desc;describe;distinct;double;drop;escaped;enclosed;enum;explain;fields;float;float4;float8;foreign;from;for;full;grant;group;having;hour;hour_minute;hour_second;ignore;in;index;infile;insert;int;integer;interval;int1;int2;int3;int4;int8;into;is;inshift;join;key;keys;leading;left;like;lines;limit;lock;load;long;longblob;longtext;match;mediumblob;mediumtext;mediumint;middleint;minute;minute_second;mod;month;natural;numeric;no;not;null;on;option;optionally;or;order;outer;outfile;partial;precision;primary;procedure;privileges;read;real;references;rename;regexp;repeat;replace;restrict;rlike;select;set;show;smallint;sql_big_tables;sql_big_selects;sql_select_limit;sql_log_off;straight_join;starting;table;tables;terminated;text;time;timestamp;tinyblob;tinytext;tinyint;trailing;to;use;using;unique;unlock;unsigned;update;usage;values;varchar;varying;varbinary;with;write;where;year;year_month;zerofill");
	var reserved = reservedwords.split(";")
	if(in_array(word,reserved)){
		alert(word+' is a reserved word');
		return true;
     	}
     return false;
	}

function urlEncode(text) {
	//http://wmtdev.avincimovie.com/fonts/futura.swf?txt=hello%3Ca+href=%22ksl.com%22%3Eksl%3C/a%3E
	text=text.replace(/\//g,"%2F");
	text=text.replace(/\?/g,"%3F");
	text=text.replace(/\</g,"%3C");
	text=text.replace(/\>/g,"%3E");
	text=text.replace(/\"/g,"%22");
	text=text.replace(/=/g,"%3D");
	text=text.replace(/&/g,"%26");
	//text=text.replace(/\s/g,"+");
    return text;
	}
