//v2.0.6	|||||||||||||||||||   ©2006 Irondev LLC, Joel O'Neill   http://www.irondev.com  |||||||||||||||||||
//1/4/06	added Selected
//2/11/06	added simple HttpXml functions
//3/2/06	added id to Selected
//8/1/06	Window() added
//10/2/06	updated and added AJAX and form control
//12/19/06	SelectedValue, SelectedText
//10/28/08	added menu items

//declare vars
var temp1, temp2


//----------------------------------+ os/browser/version/offset testing +----------------------------------
var pos, searchString;
var ua = navigator.userAgent.toLowerCase();
var brOS, brName, brVersion, brHOffset, brVOffset;

if (BrTest('konqueror')) 		{brName = "Konqueror"; brOS = "Linux";	brHOffset = 0; 		brVOffset = 0;}
else if (BrTest('safari')) 		{brName = "Safari";						brHOffset = 8; 		brVOffset = 4;}
else if (BrTest('omniweb')) 	{brName = "OmniWeb";					brHOffset = 0; 		brVOffset = 0;}
else if (BrTest('opera')) 		{brName = "Opera";						brHOffset = 0; 		brVOffset = 0;}
else if (BrTest('webtv')) 		{brName = "WebTV";						brHOffset = 0; 		brVOffset = 0;}
else if (BrTest('icab')) 		{brName = "iCab";						brHOffset = 0; 		brVOffset = 0;}
else if (BrTest('msie')) 		{brName = "Internet Explorer";			brHOffset = 0; 		brVOffset = 0;}
else if (!BrTest('compatible'))	{brName = "Netscape Navigator";			brHOffset = 0; 		brVOffset = 0;}
else 							{brName = "An unknown brName";			brHOffset = 0; 		brVOffset = 0;}

if (!brVersion) {brVersion = ua.charAt(pos + searchString.length);}

if (!brOS)	
{
	if (BrTest('linux')) 		{brOS = "Linux";}
	else if (BrTest('x11')) 	{brOS = "Unix";}
	else if (BrTest('brOS x')) 	{brOS = "Mac OSX";}
	else if (BrTest('mac')) 	{brOS = "Mac";}
	else if (BrTest('win')) 	{brOS = "Windows";}
	else 						{brOS = "an unknown operating system";}
	if((brOS == 'Mac' || brOS == 'Mac OSX') && brName == "Internet Explorer") {brHOffset = 10; 		brVOffset = 15;}
}

function BrTest(str)
{
	pos = ua.indexOf(str) + 1;
	searchString = str;
	return pos;
}
//alert(brOS + ', ' + brName + ', ' + brVersion);
//----------------------------------+ os/browser/version/offset testing +----------------------------------


//returns obj by id
function ById(el)
{
	if(typeof(el) != 'object') {el = document.getElementById(el);}
	return el;
}



//general pop-up
//NW('relative path', 'name', width, height)
function NW(mypage, myname, w, h) {
	var offset = 0;
	if ((screen.width / screen.height) > 1.5) 
	{
		offset = screen.width / 4;//for duals
	}
	var winl = ((screen.width - w) / 2) - offset;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=no,resizable=yes'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}



//general pop-up with scrollbars
//NW('relative path', 'name', width, height)
function NWS(mypage, myname, w, h) {
	var offset = 0;
	if ((screen.width / screen.height) > 1.5) 
	{
		offset = screen.width / 4;//for duals
	}
	var winl = ((screen.width - w) / 2) - offset;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,resizable=yes'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}



//verify onclick
function Verify(msg){
    return confirm(msg);
}



//only allow numbers, delete, backspace tab
function OnlyNumbers()
{
	var k;
	k = event.keyCode;
	if ((k < 48 || k > 57) && k != 96 && k != 97 && k != 98 && k != 99 && k != 100 && k != 101 && k != 102 && k != 103 && k != 104 && k != 105 && k != 8 && k != 9 && k != 46 && k != 37 && k != 38 && k != 39 && k != 40)
	{
		event.returnValue = false;
	}
}



//only allow numbers, delete, backspace tab
function OnlyMoney()
{
	var k;
	k = event.keyCode;
	//alert(k);
	if ((k < 48 || k > 57) && k != 96 && k != 97 && k != 98 && k != 99 && k != 100 && k != 101 && k != 102 && k != 103 && k != 104 && k != 105 && k != 8 && k != 9 && k != 46 && k != 37 && k != 38 && k != 39 && k != 40 && k != 110 && k != 189 && k != 190)
	{
		event.returnValue = false;
	}
}



//serve a popup on bad email entered
function ValidEmail(email)
{
	var badCombos = /^@|^\.|@\.|@.*@|@$|\.$/;
	var badChars = /\s|\?|\(|\)|\[|\]|\{|\}|\<|\>|\||\\|\/|\:|\;|\,|\"|\'|\`|\=|\!|\#|\$|\%|\^|\&|\*/;
	var goodChars = /@.*\./;
	if (badCombos.test(email)||badChars.test(email)||!goodChars.test(email))
	{
		alert('You have entered an invalid email address');
	}
}



//retrieve the absolute overall page position of an element
function Pos(el)
{
	if(typeof(el) != 'object') {el = document.getElementById(el);}
	var ww = el.offsetWidth, hh = el.offsetHeight;
	for (var xx = 0,yy = 0; el != null; xx += el.offsetLeft,yy += el.offsetTop,el = el.offsetParent);
	return {Left:xx, Top:yy, Right:xx + ww, Bottom:yy + hh}
}



//returns windows vars
function Window()
{
	var w, h, sX, sY;
	if (brName == "Internet Explorer")
	{
		w = document.body.offsetWidth;
		h = document.body.offsetHeight;
		sX = document.body.scrollLeft;
		sY = document.body.scrollTop;
	}
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
		sX = pageXOffset;
		sY = pageYOffset;
	}
	return {Width:w, Height:h, ScrollX:sX, ScrollY:sY}
}



//overlays passed text next to passed element
function Overlay(atElement, text, w)
{
	if(typeof(atElement) != 'object') {atElement = document.getElementById(atElement);}
	//create new div to insert
	var objOverlay = document.createElement('div');
	objOverlay.id = 'overlay' + Pos(atElement).Left + Pos(atElement).Top;
	objOverlay.innerHTML = '<div align="right"><a href="#" onclick="RemoveOverlay(\'' + objOverlay.id + '\'); return false;" onmouseover="document.close' + objOverlay.id + '.src=\'/images/overlayClose_on.gif\'" onmouseout="document.close' + objOverlay.id + '.src=\'/images/overlayClose.gif\'" class=small><img src="/images/overlayClose.gif" border="0" name="close' + objOverlay.id + '"></a></div>' + text;
	objOverlay.className = 'overlay';
	objOverlay.align = 'left';
	objOverlay.style.width = w;
	
	//insert div
	atElement.parentNode.appendChild(objOverlay);
	
	//set location point for overlay text
	var posY = Pos(atElement).Top;
	if((posY - objOverlay.clientHeight) > 0) {posY = posY - objOverlay.clientHeight;}//not above the top of the page
	else {posY = Pos(atElement).Bottom;}
	var posX = Pos(atElement).Left;
	if((posX + objOverlay.clientWidth) > 770) {posX = Pos(atElement).Right - objOverlay.clientWidth;}//not longer than 770
	objOverlay.style.top = posY;
	objOverlay.style.left = posX;
}



//clears overlay
function RemoveOverlay(overlayElement)
{
	if(typeof(overlayElement) != 'object') {overlayElement = document.getElementById(overlayElement);}
	if(overlayElement != null)
	{
		overlayElement.parentNode.removeChild(overlayElement);
	}
}



//change visibility of element
function DisplayStyle(el, styleValue)
{
	if(typeof(el) != 'object') {el = document.getElementById(el);}
	el.style.display = styleValue;
}



//toggles the visibility of the display style
function ToggleDisplayStyle(el)
{
	if(typeof(el) != 'object') {el = document.getElementById(el);}
	if(el.style.display != "none") {el.style.display = "none";}
	else {el.style.display = "block";}
}



//******************************************************************************************************************************
//******************************************************* FORM FUNCTIONS *******************************************************
//******************************************************************************************************************************

//just extends the form select's selected option's values out
function Selected(selectElement)
{
	var s = ById(selectElement);
	var d = s.options[s.selectedIndex].id;
	var v = s.options[s.selectedIndex].value;
	var t = s.options[s.selectedIndex].text;
	var i = s.selectedIndex;
	return {id:d, value:v, text:t, index:i};
}


//select option by value
function SelectedValue(selectElement, val)
{
	var s = ById(selectElement);
	for(var i=0; i<s.options.length; i++)
	{
		if(s.options[i].value == val)
		{
			s.selectedIndex = i;
			break;
		}
	}
}


//select option by text
function SelectedText(selectElement, val)
{
	var s = ById(selectElement);
	for(var i=0; i<s.options.length; i++)
	{
		if(s.options[i].text == val)
		{
			s.selectedIndex = i;
			break;
		}
	}
}


//returns values of selected items in a select with multiple as an array
function MultiSelectValues(el)
{
	var o = ById(el);
	var s = '';
	for(i=0; i<o.length; i++)
	{
		if(o[i].selected)
		{
			if(s.length > 0){s += '|';}
			s += o[i].value;
		}
	}
	var arr = new Array();
	if(s.length > 0) {arr = s.split('|');}
	return arr;
}



//returns a name=value[&name=value ...n] strings URL encoded and unquoted for posting to a page via JS HTTP request type objects
function FormToPost(el)
{
	var j;
	var params = '';
	var frm = ById(el);
	if(frm != null)
	{
	for(j=0; j<frm.length; j++)
	{
		if(frm[j].name != '')
		{
			if(params != '') {params += '&';}
			params += frm[j].name + '=' + StringToPostValue(frm[j].value);
		}
	}
	}
	//return input as post data
	else
	{
		params = el;
	}
	return params;
}



//encode a value for use as a post data value
function StringToPostValue(str)
{
	return encodeURI(str).replace('&', '%26').replace(' ', '+') + '';
}



//disables all form elements
function DisableForm(el)
{
	var j;
	var frm = ById(el);
	for(j=0; j<frm.length; j++)
	{
		frm[j].disabled = true;
	}
}



//enables all form elements
function EnableForm(el)
{
	var j;
	var frm = ById(el);
	for(j=0; j<frm.length; j++)
	{
		frm[j].disabled = false;
	}
}



//set the specified element's value/HTML/selection to the specified value.
//if the element is a radio or select, it sets to the matching value (all options and radio's must therefore have a "value" attribute)
//checkbox set based on textual boolean and img sets the src
function SetVal(el, val)
{
	el = ById(el);
	val = val.toString();
	
	var tag = el.tagName.toLowerCase();
	if(tag == 'input')
	{
		var type = el.type.toLowerCase();
		if(type == 'radio')
		{
			var rads = document.forms[el.form.id].elements[el.name];
			for(i=0; i<rads.length; i++)
			{
				if(rads[i].value == val) {rads[i].checked = true;}
			}
		}
		else if(type == 'checkbox')
		{
			if(val == '0' || val.toLowerCase() == 'false' || val == '')
			{
				el.checked = false;
			}
			else
			{
				el.checked = true;
			}
		}
		else
		{
			el.value = val;
		}
	}
	else if(tag == 'select')
	{
		for(i=0; i<el.options.length; i++)
		{
			if(el.options[i].value == val){el.selectedIndex = i;}
		}
	}
	else if(tag == 'img')
	{
		el.src = val;
	}
	else
	{
		el.innerHTML = val;
	}
}



//get value from any element
function GetVal(el)
{
	el = ById(el);
	var val;
	
	var tag = el.tagName.toLowerCase();
	if(tag == 'input')
	{
		var type = el.type.toLowerCase();
		if(type == 'radio')
		{
			var rads = document.forms[el.form.id].elements[el.name];
			for(i=0; i<rads.length; i++)
			{
				if(rads[i].checked) {val = rads[i].value;}
			}
		}
		else if(type == 'checkbox')
		{
			val = el.checked;
		}
		else
		{
			val = el.value;
		}
	}
	else if(tag == 'select')
	{
		val = Selected(el).value;
	}
	else if(tag == 'img')
	{
		val = el.src;
	}
	else
	{
		val = el.innerHTML;
	}
	return val;
}



//******************************************************************************************************************************
//**************************************************** AJAX STYLE FUNCTIONS ****************************************************
//******************************************************************************************************************************
//GetHttp and PostHttp are the entry points for XML retrieval. They both call ProcessState as the state changes, on success
//ProcessState calls the absent function (to be written into the calling pages JavaScript) ProcessHttp which is passed the
//request object with results, the most commonly use being: obj.responseText


//reads from the page when passed a URL (usually with query string data). using post method even though this is a get
//since get seems to cache
function GetHttp(url, async) 
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest)
	{
        objReq = new XMLHttpobjRequest();
        objReq.onreadystatechange = ProcessState;
        objReq.open("POST", url, async);
        objReq.send(null);
    }
	// branch for IE/Windows ActiveX version
    else if (window.ActiveXObject)
	{
        objReq = new ActiveXObject("Microsoft.XMLHTTP");
        if (objReq)
		{
            objReq.onreadystatechange = ProcessState;
            objReq.open("POST", url, async);
            objReq.send();
        }
    }
}



//reads from the page when passed a URL. the form data is gather from the specified form (frm) and processed into post data and sent to the URL
function PostHttp(url, frm, async) 
{	
	// branch for native XMLHttpRequest object
    if (window.XMLHttpRequest)
	{
        objReq = new XMLHttpRequest();
		if (objReq.overrideMimeType)
		{
			objReq.overrideMimeType('text/html');
		}
    }
	// branch for IE/Windows ActiveX version
    else if (window.ActiveXObject)
	{
        objReq = new ActiveXObject("Microsoft.XMLHTTP");
       
    }
	 if (objReq)
	{
		var params = FormToPost(frm);
		try
		{
			objReq.onreadystatechange = ProcessState;
			objReq.open("POST", url, async);
			objReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			objReq.setRequestHeader("Content-length", params.length);
			objReq.setRequestHeader("Connection", "close");
			objReq.send(params);
		}
		catch(e)
		{
			alert('error');
		}
	}
	else{alert('ERROR:[LoadHttp] could not instanciate HTTP Request');}
}



//the initial funciton called at each state/status change on loading during GetHttp/PostHttp this calls the user's function "ProcessHttp" upon success
function ProcessState() 
{
    // only if objReq shows "complete"
    if (objReq.readyState == 4)
	{
        // only if "OK"
        if (objReq.status == 200)
		{
            ProcessHttp(objReq);
        }
		else
		{
            alert("ERROR: [ProcessState] There was a problem retrieving the XML data:\r\n" + objReq.statusText);
			document.write(objReq.responseText);
        }
    }
}



//returns a JSON object from json text
function ParseJson(json)
{
	json  = 'json = ' + json;
	eval(json);
	return json;
}




//******************************************************************************************************************************
//******************************************************* MENU CONTROLS ********************************************************
//******************************************************************************************************************************

var currentParent;
var currentMenu;
var currentMenuRight;
var menuToHide;
var fadestep;
var cleared = true;
var browserdetect;


function ShowMenu(thisitem, menu, isRight)
{
	cleared = false;
	currentParent = thisitem;
	currentMenuRight = isRight;
	if(typeof(menu) != 'object')
		{menu = document.getElementById(menu);}
	if(currentMenu == menu)
		{
			if (!cleared) clearInterval(fadestep);
			currentMenu = null;
		}
	else if(currentMenu != null)
		{
			InstantHide(currentMenu);
			if (!cleared) clearInterval(fadestep);
			currentMenu = null;
		}
	currentMenu = menu;
	browserdetect=menu.filters? "ie" : typeof(menu.style.MozOpacity) == "string" ? "mz" : ""
	if (browserdetect == "ie")
		{currentMenu.filters.alpha.opacity = 100}
	else if (browserdetect == "mz")
		{currentMenu.style.MozOpacity = 1}
	if(!currentMenuRight)
	{
		currentMenu.style.left = Pos(currentParent).Left;
		currentMenu.style.top = Pos(currentParent).Bottom;
	}
	else
	{
		currentMenu.style.left = Pos(currentParent).Right;
		currentMenu.style.top = Pos(currentParent).Top;
	}
	currentMenu.style.visibility = 'visible';
}


function HoldMenu()
{
	ShowMenu(currentParent, currentMenu, currentMenuRight);
}


function HideMenu(hideMenu)
{
	if(typeof(hideMenu) != 'object')
		{hideMenu = document.getElementById(hideMenu);}
	if(menuToHide != hideMenu && menuToHide != null)
		{InstantHide(menuToHide);}
	menuToHide = hideMenu;
	FadeMenu();
}

function FadeMenu()
{
	fadestep=setInterval("FadeLevel()",25);
}

function FadeLevel()
{
	if (browserdetect == "ie")
		{menuToHide.filters.alpha.opacity-=10;}
	else if (browserdetect == "mz")
		{menuToHide.style.MozOpacity-=.1;}
	else
		{menuToHide.style.visibility = 'hidden';}
		
	if ((menuToHide.style.MozOpacity == 0.0)||(menuToHide.filters.alpha.opacity == 0))
		{
			InstantHide(menuToHide);
			menuToHide = null;
		}
}

function InstantHide(iHideMenu) {
	clearInterval(fadestep);
	cleared=true;
	iHideMenu.style.visibility = 'hidden';
}
	
	


function msdelay(mseconds) { //delay by the input milliseconds
	starttime = new Date();
	while (1) {
		nowtime = new Date();
		diff = nowtime-starttime;
		if( diff > mseconds ) {break;}
	}
}
