var d=document;

// cookie expiry date
function setCookie(name, value, expires, path, domain, secure){
      var today = new Date();
      today.setTime( today.getTime() );
      if ( expires ){
           expires = expires * 1000 * 60 * 60 * 24;
      }
      var expiresdate = new Date( today.getTime() + (expires) );
      document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expiresdate.toUTCString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name)
{

    var dc = document.cookie;

    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return "";
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}




function formData2QueryString(docForm) {
	var strSubmitContent = '';
	var formElem;
	var strLastElemName = '';
	for (i = 0; i < docForm.elements.length; i++) {
		
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
				strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				break;
				
			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				}
				break;
				
			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					// Continuing multiple, same-name checkboxes
					if (formElem.name == strLastElemName) {
						// Strip of end ampersand if there is one
						if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) {
							strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
						}
						// Append value as comma-delimited string
						strSubmitContent += ',' + escape(formElem.value);
					}
					else {
						strSubmitContent += formElem.name + '=' + escape(formElem.value);
					}
					strSubmitContent += '&';
				}
				break;
				
		}
		strLastElemName = formElem.name
	}
	
	// Remove trailing separator
	strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
	return strSubmitContent;
}

var called = 0;
function xmlhttpPost(strSubmitURL, strSubmitContent, strResultFunc) {

	var xmlHttpReq = false;
	var strResponse = '';
	
	// Create new XMLHTTPRequest object
	// ----------------
	// Mozilla
	// IE

	if (window.ActiveXObject) {
		xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest) {
		xmlHttpReq = new XMLHttpRequest();
//		xmlHttpReq.overrideMimeType('text/xml');
	}



	xmlHttpReq.open('POST', strSubmitURL, true);
	xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttpReq.onreadystatechange = function() {
		if (xmlHttpReq.readyState == 4) {
			strResponse = xmlHttpReq.responseText;
			switch (xmlHttpReq.status) {
				// Page-not-found error
				case 404:
					alert('Error: Not Found. The requested URL ' + strSubmitURL + ' could not be found.');
					break;
				// Display results in a full window for server-side errors
				case 500:
					handleErrFullPage(strResponse);
					break;
				default:
					// Call JS alert for generated error or debug messages
					if (strResponse.indexOf('Error:') > -1 || strResponse.indexOf('Debug:') > -1) {
						alert(strResponse);
					}
					// Returns the data in a string 
					else { 
						eval(strResultFunc + '(strResponse);');
					}
					break;
			}
		} 
	}
	xmlHttpReq.send(strSubmitContent);
}


function handleErrFullPage(strIn) {

	var errorWin;

	// Try creating new window and displaying error
	try {
		// Open window
		errorWin = window.open('', 'errorWin');
		errorWin.document.body.innerHTML = '<pre>' + strIn + '</pre>';
	}
	// If pop-up gets blocked, inform user
	catch(e) {
		alert('An error occurred, but the error message cannot be' +
			' displayed because of your browser\'s pop-up blocker.\n' +
			'Please allow pop-ups from this Web site.');
	}
}



// To get the appropriate response - create a function to be called when it is done.
// var strSubmitContent = formData2QueryString(document.forms[0]);
// xmlhttpPost('/response.cgi', strSubmitContent, strResultFunc);

// example, xmlhttpPost('/response.cgi', 'yo yo yo', 'goAlert');
// function goAlert(strIn){ alert(strIn); }



function c(t){if(document.images){(new Image()).src="/$appSystemName/c?"+t;} return true;}



//
// uToggle - universal toggler
//
function uToggleInit(){
     dArray=getCookie('toggle').split("*");
     for(i=0; i<dArray.length-1; i++){
	ab = dArray[i].split("=");
    	  if (ab[1]){
            dVal = ab[1];
            switch(dVal){
              case 'i': dVal = 'inline'; break;
              case 'b': dVal = 'block'; break;
              case 'n': dVal = 'none'; break;
              default: dVal = 'inline';
            }
	  uToggle(ab[0],dVal,'',1);
       }    
     }
}


var previousCallId; var disableF = 0; var enableF = 0;
function fToggle(){
    if (d.getElementById(previousCallId + '_s') && disableF != 1 && enableF <= 1){
       	obj.style.display = curState = 'none';
	previousCallId = ''; disableF = 1; 
    }else{  enableF--; }
}



function uToggle(mId, forceState, defaultState, noSave, oneOnly){
    if(!defaultState){defaultState='block';}

    if(oneOnly){ 
	if(previousCallId && previousCallId!=mId){ fToggle(); }
	previousCallId = mId;
	disableF = 0;	enableF = 2;
    }else{
	enableF = 2;
    }	



    if (d.getElementById(mId + '_s')){
     obj  = d.getElementById(mId + '_s');
     objI = d.getElementById(mId + '_i');

     if(typeof forceState != 'undefined' && forceState != ''){
       obj.style.display = forceState;
       if (objI){ if(forceState != 'none'){objI.className = 'o';}else{objI.className = 'c';} }
       return false;
     }

     if((obj.style.display == 'none') || ((obj.style.display=='') && (obj.offsetWidth==0))){
       	obj.style.display = curState = defaultState;
       	if(objI){objI.className = "o";}
       	ieULfix(obj);
     } else {
       	obj.style.display = curState = 'none';
       	if(objI){objI.className = "c";}
     }



     switch(curState){
            case 'inline': saveState = 'i'; break;
            case 'block': saveState = 'b'; break;
            case 'none': saveState = 'n'; break;
            default: saveState = 'i';
     }
     if(!noSave){ saveSetting(mId, saveState, 'toggle', '/'); }
  }
  return false;
}

function ieULfix(ieUL){
	if(document.all&&document.getElementById){
		if(!obj.className.match(/ieULfix/)){ obj.className += " ieULfix"; }
		var ieMat = document.createElement('iframe');
		ieUL.insertBefore(ieMat,ieUL.firstChild);
		ieMat.style.width=ieUL.offsetWidth+"px";
		ieMat.style.height=ieUL.offsetHeight+"px";	
		ieUL.style.zIndex="1";
	}
}









function saveSetting(name, val, cname, path, domain){
     var newSetting = name + "=" + val + "*";
     var cD = getCookie(cname);
     var oldval = getSetting(name, cname);
     var cD2 = "";     

     if (cD && cD.indexOf(name) > -1){ 
          var oldSetting = name + "=" + oldval + "*";
	  cD2 = cD.replace(oldSetting, newSetting);
     } else { 
          cD2 = cD + newSetting;
     }
       setCookie(cname, cD2, 365, path, domain);
}

function getSetting(name, cname){
     var cD = getCookie(cname);
     if (!cD || cD == null){ return ""; }
     var start = cD.indexOf(name+"=");
     var len = start + name.length + 1;
     if (start == -1) return "";
     var end = cD.indexOf("*",start);
     if(end==-1) end = cD.length;
     if (len == end ) { return ""; }
     else{ return unescape(cD.substring(len, end)); }
}

function toggleRunThrough(){
     var settings = getCookie("toggle");
     var settingsArr = settings.split("*");
     var i = 0;
     for(i=0; i < settingsArr.length; i++){
          var nameval = (settingsArr[i]).split("=");
	  if(nameval[0] != "" && nameval[1] != ""){
	       toggleDiv(nameval[0], nameval[1]);
	  }
     }    
}



function showhide(x){ex = d.getElementById(x).style;ex.display=(ex.display=='block')?'none':'block';}
function show(x){ ex = d.getElementById(x).style; ex.display='inline';  }
function hide(x){ ex = d.getElementById(x).style; ex.display='none';  }





//
// Tree Functions (for ul/li)
//
var treeCount=0;
var treeArray = new Array();

function treeToggle(objId){
  e=obj.parentNode;
  ulNodeDisplay = e.childNodes[2].style.display;
  ulNodeDisplay = (ulNodeDisplay == 'none') ? 'block' : 'none';	
  e.childNodes[2].style.display = ulNodeDisplay
  obj.firstChild.src=(ulNodeDisplay == 'none') ?  "/img/plus.gif" : '/img/minus.gif';
//  saveTreeSettings();
  saveSetting(objId, curState, 'treeToggle', '/');
  return false;
}

function treeToggleX(obj){
  e=obj.parentNode;
  ulNodeDisplay = e.childNodes[2].style.display;
  ulNodeDisplay = (ulNodeDisplay == 'none') ? 'block' : 'none';	
  e.childNodes[2].style.display = ulNodeDisplay
  obj.firstChild.src=(ulNodeDisplay == 'none') ?  "/img/plus.gif" : '/img/minus.gif';
  saveTreeSettings();
  return false;
}

// run through entire list of id and saves those that are closed
function saveTreeSettings(){
  allCatArray = allCat.split(" ");
  var newTreeToggleList = "";
  for(i=1;i < allCatArray.length; i++){
	curE = d.getElementById(allCatArray[i]);
	if (i < 2){
//	  alert(allCatArray[i] + " " +  curE.nodeName + " " +curE.childNodes.length + curE.childNodes[1].nodeName);
	}
	if (curE.childNodes[2]){
	  displayState = curE.childNodes[2].style.display;
  	  if (displayState == 'none'){
	    newTreeToggleList += curE.id + "i";
	  }
        }
  }
 setCookie("treeToggle", newTreeToggleList, 180);
// alert( newTreeToggleList );
}


function initTree(){
  cooCatArray = getCookie("treeToggle").split("*");
  for(i=0;i<cooCatArray.length-1;i++){
	curE = d.getElementById(cooCatArray[i]);
	if (curE){
  	  curE.childNodes[2].style.display = "none"; 
	  curE.firstChild.firstChild.src = "/img/plus.gif"; 
	}
  }
}


//
// End Tree Functions
//




var output="";
function doutput(out){
  var text_field = d.getElementById("t");
  if(out){ text_field.value += "*" + out; } else { text_field.value += "*" + output; }
}

var iPrefetchArr=new Array();
var iPrefetchCount=0;
function iPrefetch(iUrl){
    iPrefetchArr[iPrefetchCount] = new Image();
    iPrefetchArr[iPrefetchCount].src = iUrl;
    iPrefetchCount++;
}





function initRoll(){
	if(!d.getElementById) return;
	var iArr = d.getElementsByTagName('img');
	for(i=0;i<iArr.length;i++){
		thisI = iArr[i];
		thisIClass=thisI.className;
		if(thisIClass.indexOf('rollto')!=-1){
			thisI.setAttribute('osrc',thisI.src);
			thisI.setAttribute('isrc',thisI.className.match(/rollto (\S+)/)[1]);
			thisI.onmouseover=function(){ this.setAttribute('src',this.getAttribute('isrc')); }
			thisI.onmouseout =function(){ this.setAttribute('src',this.getAttribute('osrc')); }
		}
	}
}

function domRollover() {
	if (navigator.userAgent.match(/Opera (\S+)/)) {
		var operaVersion = parseInt(navigator.userAgent.match(/Opera (\S+)/)[1]);
	}
	if (!document.getElementById||operaVersion <7) return;
	var imgarr=document.getElementsByTagName('img');

	var imgSrc=new Array();
	var imgClass=new Array();
	for (i=0;i<imgarr.length;i++){
		if (imgarr[i].className.indexOf('domroll')!=-1){
			imgSrc[i]=imgarr[i].getAttribute('src');
			imgClass[i]=imgarr[i].className;
			imgPreload[i]=new Image();
			if (imgClass[i].match(/domroll (\S+)/)) {
				imgPreload[i].src = imgClass[i].match(/domroll (\S+)/)[1]
			}
			imgarr[i].setAttribute('xsrc', imgSrc[i]);
			imgarr[i].onmouseover=function(){
				this.setAttribute('src',this.className.match(/domroll (\S+)/)[1])
			}
			imgarr[i].onmouseout=function(){
				this.setAttribute('src',this.getAttribute('xsrc'))
			}
		}
	}
}
// domRollover();







function initJs(){
  uToggleInit();
  initRoll();

// prefetch images
  iPrefetch("http://beta.myhq.com/img/tab_sm_blue_open.gif");
  iPrefetch("http://beta.myhq.com/img/tab_sm_blue_open_over.gif");
  iPrefetch("http://beta.myhq.com/img/tab_sm_blue_close.gif");
  iPrefetch("http://beta.myhq.com/img/tab_sm_blue_close_over.gif");

  iPrefetch("http://beta.myhq.com/img/tab_xl_blue_open.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_blue_open_over.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_blue_close.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_blue_close_over.gif");

  iPrefetch("http://beta.myhq.com/img/tab_xl_green_open.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_green_open_over.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_green_close.gif");
  iPrefetch("http://beta.myhq.com/img/tab_xl_green_close_over.gif");

  iPrefetch("http://beta.myhq.com/img/pulldown_green.gif");
  iPrefetch("http://beta.myhq.com/img/pulldown_green_over.gif");
  iPrefetch("http://beta.myhq.com/img/pulldown_blue.gif");
  iPrefetch("http://beta.myhq.com/img/pulldown_blue_over.gif");

  iPrefetch("http://beta.myhq.com/img/folder_plus.gif");
  iPrefetch("http://beta.myhq.com/img/folder_plus_over.gif");
  iPrefetch("http://beta.myhq.com/img/folder_minus.gif");
  iPrefetch("http://beta.myhq.com/img/folder_minus_over.gif");
}



// Form methods - turn_on - makes a field visible. turn_off -makes it dissapear
// select_all, selects all checkboxed items within the form
function turn_on (oname) {
 var box = document.getElementById(oname);
 box.removeAttribute('disabled');
 box.className="visible";
}

function turn_off (oname) {
 var box = document.getElementById(oname);
 box.setAttribute('disabled', 'disabled');
 box.className="hidden";
}

function select_all(e) {
 var f = e.form;
 var x = 0;
 for(x=0; x<f.length;x++){
   if(f[x].type == 'checkbox' && f[x].name != 'selectall'){
      f[x].checked = e.checked;
   }
 }
}








/// XHR FACTORY -  http://blogs.pathf.com/agileajax/2006/08/object_pooling_.html
var XHRFactory = (function(){
 // static private member
 var stack = new Array();
 var poolSize = 10;
 
 var nullFunction = function() {}; // for nuking the onreadystatechange
 
 // private static methods
 
 function createXHR() {
     if (window.ActiveXObject) {
       return new ActiveXObject('Microsoft.XMLHTTP')
     }else if (window.XMLHttpRequest) {
       return new XMLHttpRequest();
     } 
    }

 // cache a few for use
 for (var i = 0; i < poolSize; i++) {
  stack.push(createXHR());
 }
 
 // shared instance methods
 return ({
  release:function(xhr){
   xhr.onreadystatechange = nullFunction;
   stack.push(xhr);
  },
  getInstance:function(){
   if (stack.length < 1) {
    return createXHR();
   } else {
    return stack.pop();
   }
  },
  toString:function(){
   return "stack size = " + stack.length;
  }
 });
})();

function xmlhttpPost2(strSubmitURL, strSubmitContent, strResultFunc) {
var xhr = XHRFactory.getInstance();
var strResp = '';

xhr.onreadystatechange = function() {
        if (xhr.readyState==4) {
                // if "OK"
		strResp = xhr.responseText;
                if (xhr.status==200) {
                // process the response
		  eval(strResultFunc + '(strSubmitContent+strResp);');
	        }	
                XHRFactory.release(xhr);
        }
};
xhr.open("POST", strSubmitURL, true);
xhr.send(strSubmitContent);

}



//
// FROM lixlpixel.org.
//
// position of the tooltip relative to the mouse in pixel //
var offsetx = 14;
var offsety =  10;

function newelement(newid)
{ 
    if(document.createElement)
    { 
        var el = document.createElement('div'); 
        el.id = newid;     
        with(el.style)
        { 
            display = 'none';
            position = 'absolute';
        } 
        el.innerHTML = '&nbsp;'; 
        document.body.appendChild(el); 
    } 
} 
var ie5 = (document.getElementById && document.all); 
var ns6 = (document.getElementById && !document.all); 
var ua = navigator.userAgent.toLowerCase();
var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
function getmouseposition(e)
{
    if(document.getElementById)
    {
        var iebody=(document.compatMode && 
        	document.compatMode != 'BackCompat') ? 
        		document.documentElement : document.body;
        pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
        pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
        mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
        mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;

        var lixlpixel_tooltip = document.getElementById('tooltip');


if (navigator.userAgent.indexOf("MSIE")!=-1){

	var xx = getMouseXPos(e) + offsetx + pagex;
	var yy = getMouseYPos(e) + offsety + pagey;
        lixlpixel_tooltip.style.left = xx + 'px';
        lixlpixel_tooltip.style.top =  yy + 'px';

}else{
        lixlpixel_tooltip.style.left = (mousex+pagex+offsetx) + 'px';
       lixlpixel_tooltip.style.top = (mousey+pagey+offsety) + 'px';
}
    }
}



// Get the horizontal position of the mouse
function getMouseXPos(e) {
  if (document.layers||ns6) {
    return parseInt(e.pageX+10)
  } else {
    return (parseInt(event.clientX+10) + parseInt(document.body.scrollLeft))
  }
}
// Get the vartical position of the mouse
function getMouseYPos(e) {
  if (document.layers||ns6) {
    return parseInt(e.pageY)
  } else {
    return (parseInt(event.clientY) + parseInt(document.body.scrollTop))
  }
}



function tt(tip)
{
    if(!document.getElementById('tooltip')) newelement('tooltip');
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.innerHTML = tip;
    lixlpixel_tooltip.style.display = 'block';
    lixlpixel_tooltip.style.zIndex = 99;
    document.onmousemove = getmouseposition;
}
function ttout()
{
    document.getElementById('tooltip').style.display = 'none';
}

function pop(theUrl, wName)
{
    window.open(theUrl, wName, 'height=' + screen.height + ',width=' + screen.width +' status=no,menubar=no,location=no,scrollbars=yes,fullscreen');
}
