/* event based javascript routines*/
/* - Required dependancies: common.js 			 */
/*----------------------------------------------*/

/* Capture mouse movement and set MouseX and MouseY to its x,y corordinates */
var MouseX=0;
var MouseY=0;
if(document.onmousemove){
	document.onmousemove = mouseMove;
	}
else if(document.addEventListener){
	document.addEventListener("mousedown",mouseMove,false);
    document.addEventListener("mousedup",mouseMove,false);
    document.addEventListener("mousemove",mouseMove,false);
	}
else if(document.captureEvents){
	document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}

function mouseMove(e) {
	if (!e) var e = window.event;
	if (e.pageX || e.pageY){
		MouseX = e.pageX;
		MouseY = e.pageY;
		}
	else if (e.clientX || e.clientY){
		if(document.body){
			if(document.documentElement){
				MouseX = e.clientX + document.body.scrollLeft
					+ document.documentElement.scrollLeft;
				MouseY = e.clientY + document.body.scrollTop
					+ document.documentElement.scrollTop;
				}
			}		
		}
	}

// 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";
				}
			sfEls[i].onmouseout=function(){
				this.className="";
				}
			}
		}
	}
// Add sfHover to the onLoad queue
if (window.addEventListener){window.addEventListener("load",sfHover,false);}
else if (window.attachEvent){window.attachEvent("onload",sfHover);}

/* initPin - function to assign hover to dom objects that have _behavior="pin" so they hide onMouseOut */
function initBehaviors(){
	//assign hover to li and hide w_select select tags on hover
	// 	_behavior="clock" id="clockid"
	//	<div _behavior="menu" display="menuid">MouseOve</div><br><div id="menuid">This is the menu that is displayed</div>
	//	<div _behavior="@math(one+(two*three))"></div>
	//	<div _behavior="@sum(one:two:three)"></div>
	//	<div _behavior="@raid(raidid)"></div><input type="text" name="raidid" value="123">
	var navEls = GetElementsByAttribute('*', '_behavior', '.+');
	for (var n=0; n<navEls.length; n++){
		var behavior=navEls[n].getAttribute('_behavior').toLowerCase();
		if(behavior=='pin'){
			navEls[n].onmouseout=function(e){
				if(undefined == e){e = fixE(e);}
				if(undefined != e){
					if(checkMouseLeave(this,e)){
						this.style.display='none';
						var onhide=this.getAttribute('onhide');
						if(onhide){eval(onhide);}
						}
					}
				}
        	}
        else if(behavior=='clock'){
  			var id=navEls[n].getAttribute('id');
			if(id){startClock(id,1);}
			}
		else if(behavior=="time"){
  			var id=navEls[n].getAttribute('id');
			if(id){startClock(id,0);}
			}
		else if(behavior=='menu'){
  			var dname=navEls[n].getAttribute('display');
			if(dname){
				navEls[n].onmouseover=function(e){
					var dname=this.getAttribute('display');
					dObj=getObject(dname);
					if(dObj){dObj.style.display='block'}
                	}
                navEls[n].onmouseout=function(e){
					if(undefined == e){e = fixE(e);}
					if(undefined != e){
						if(checkMouseLeave(this,e)){
							var dname=this.getAttribute('display');
							dObj=getObject(dname);
							if(dObj){dObj.style.display='none';}
							var onhide=this.getAttribute('onhide');
							if(onhide){eval(onhide);}
							}
						}
					}
            	}
			}
        else{
			/*	Check for @math(..)  @sum(..)
				@sum(one:two:three)
				@math(one+two+three)
				str.replace(/microsoft/, "W3Schools")
			*/
			var id=navEls[n].getAttribute('id');
			var re = new RegExp('^\@([a-z]+)[(](.+)[)]$', 'igm');
	        var res = re.exec(behavior);
	        if (res && res.length > 0){

				var func=res[1].toLowerCase();
				var str=res[2].toLowerCase();
				switch (func){
					case 'sum':
						var result=0;
						var sids=str.split(/[,:\s]+/);
						for (var s=0; s<sids.length; s++) {
							result += Math.round(getText(sids[s]));
	                    	}
	                    setText(navEls[n],result);
						break
					case 'math':
						doMath(id);
						break
					case 'raid':
						var cObj=getObject(str);
						if(typeof(cObj)=='object'){
							var val=getText(navEls[n]);
							setText(cObj,val);
							startRaid(id,str);
      						}
						break
					}
	        	}
	       }
		}
	}
// Add initBehaviors to the onLoad queue
if (window.addEventListener){window.addEventListener("load",initBehaviors,false);}
else if (window.attachEvent){window.attachEvent("onload",initBehaviors);}


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';
		              }
		 		}
		 	}
		}
   	}
// 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;}
}
/*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;
	}
/* timeClock - */
var TimoutArray=new Array();
function startClock(id,live){
    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";}
    var timestr='';
    if(h<10){timestr +="0";}
    timestr += h;
    timestr += ":";
    if(m<10){timestr +="0";}
    timestr += m;
	timestr += ":";
    if(s<10){timestr +="0";}
	timestr += s;
    timestr +=p;
    setText(id,timestr);
    if(live){
    	TimoutArray[id]=setTimeout("startClock('"+id+"',"+live+")",1000);
    	}
	}
function startRaid(id,raidid){
    setText(id,getText(raidid));
    TimoutArray[id]=setTimeout("startRaid('"+id+"','"+raidid+"')",250);
	}
function startSum(id,sumid){
	var sumIds = GetElementsByAttribute('*', 'id', sumid);
	var sum=0;
	for (var s=0; s<sumIds.length; s++) {
		var cval=getText(sumIds[s]);
		/*alert(cval);*/
    	var val=Math.round(cval);
    	sum=sum+val;
 		}
	setText(id,sum);
    TimoutArray[id]=setTimeout("startSum('"+id+"','"+sumid+"')",250);
	}
function doMath(id){
	/* 
		@math(one+two+three)  @math(one+(two*3))             one+(two*3)
	clearTimeout(TimoutArray[id]);
	*/
	var behavior=document.getElementById(id).getAttribute('_behavior').toLowerCase();
	var re = new RegExp('^\@([a-z]+)[(](.+)[)]$', 'igm');
	var str;
	var res=re.exec(behavior);
	if (res && res.length > 0){
		var func=res[1].toLowerCase();
		var str=res[2].toLowerCase();
		var result=0;
		var mre = new RegExp('([a-z0-9\_]+)', 'igm');
		while(mres=mre.exec(str)){
			if (mres && mres.length > 0){
				var mname=mres[1];
				var txt=getText(mres[1]);
				//alert('replace '+mname+' with '+txt);
				var evalstr='str.replace(/'+mname+'/,\''+txt+'\')';
				str=eval(evalstr);
				}
			}
		//window.status=str;
		try{
			str=eval(str);
			setText(id,str);
			}
		catch(err){
			setText(id,err);
        	}
		}
	}
function stopTimeout(id){
	clearTimeout(TimoutArray[id]);
	}

//CheckMouseEnter  - returns true if the mouse is over the element
function checkMouseEnter (element, evt) {
	   if (element.contains && evt.fromElement) {
	        return !element.contains(evt.fromElement);
		   }
	   else if (evt.relatedTarget) {
	   	   return !containsDOM(element, evt.relatedTarget);
		   }
	   }

// checkMouseLeave - returns true if the mouse is no longer over the element
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;
	   }
//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;
	}
}
/* 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);}
					}
				}			
			}
		}
	}