var offsets = new Object();
offsets.x=-60;
offsets.y=20;
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
var relative_to_object = 0;
var tipobjInd = 0;
var tipobj=[];

function inpblur(o){o.style.background="#ffffff";}function inpfocus(o){o.style.background="#BFD3E6";}

function initHelp(){
	if(ie||ns6){
		tipobj[0]=document.all?document.all["dhtmltooltip"]:document.getElementById?document.getElementById("dhtmltooltip"):"";
		tipobj[1]=document.all?document.all["helptip"]:document.getElementById?document.getElementById("helptip"):"";
	}
}

function getOffset2(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

function imgSwap(obj,target,scale){
	var img = document.getElementById(target);
	var src = obj.src;
	var ind = src.indexOf("?");
	if(ind > 0){
		src = src.substr(0,ind);	
	}
	src += "?w=" + scale;
	img.src = src;
}

function ddrivetip(t,c,w,x2,y2,i,obj){
	tipobjInd=i;
	if(x2){offsets.x=x2;}
	if(y2){offsets.y=y2;}
	if(!(ns6||ie)){return;}
	if(typeof w!="undefined"&&w){tipobj[i].style.width=w+"px";}
	if(typeof c!="undefined"&&c!=""){tipobj[i].style.backgroundColor=c;}
	if(tipobjInd==0){tipobj[i].innerHTML=t;}else{tipobj[i].childNodes[3].innerHTML=t;}
	relative_to_object=obj;
	enabletip=true;
	return false;
}

function positiontip(e){
	i = tipobjInd;
	if(!enabletip){return}
	var B=(document.compatMode&&document.compatMode!="BackCompat")?document.documentElement:document.body;
	var curX=(ns6)?e.pageX:event.x+B.scrollLeft;
	var curY=(ns6)?e.pageY:event.y+B.scrollTop;
	var re=ie&&!window.opera? B.clientWidth-event.clientX-offsets.x:window.innerWidth-e.clientX-offsets.x-20
	var be=ie&&!window.opera? B.clientHeight-event.clientY-offsets.y:window.innerHeight-e.clientY-offsets.y-20
	var le=(offsets.x<0)? offsets.x*(-1):-1000;
	if(re<tipobj[i].offsetWidth){
		tipobj[i].style.left=ie? B.scrollLeft+event.clientX-tipobj[i].offsetWidth+"px":window.pageXOffset+e.clientX-tipobj[i].offsetWidth+"px";
	}else if(curX<le){
		tipobj[i].style.left="5px";
	}else{
		tipobj[i].style.left=curX+offsets.x+"px";
	}

	if(typeof(relative_to_object) == 'object'){ // this was done to patch ishop at home calendar rollovers...
		var offTop = getOffset2(relative_to_object,"top");
		var offLeft = getOffset2(relative_to_object,"left");

		//document.getElementById('dashboard_message').innerHTML = offTop + " - " + offLeft;

		if(1==1){
			tipobj[i].style.position = 'absolute';
			tipobj[i].style.top=offTop+50+"px";				
			tipobj[i].style.left=(offLeft-50)+"px";		
			if(re<tipobj[i].offsetWidth){
				tipobj[i].style.left=ie? B.scrollLeft+event.clientX-tipobj[i].offsetWidth+"px":window.pageXOffset+e.clientX-tipobj[i].offsetWidth+"px";
			}else if(curX<le){
				tipobj[i].style.left="5px";
			}
		}else{
			tipobj[i].style.top=offTop+offsets.y+50+"px";
		}		
	}else{
		tipobj[i].style.top=curY+offsets.y+"px"		
	}

	//tipobj[i].style.top=curY+offsets.y+"px"
	tipobj[i].style.visibility="visible";

//alert(tipobj[i].style.top);
//alert(tipobj[i].style.left);
}
function hideddrivetip(i){
	if(ns6||ie){
		tipobjInd=i;
		enabletip=false;
		tipobj[i].style.visibility="hidden";
		tipobj[i].style.left="-1000px";
		tipobj[i].style.backgroundColor='';
		tipobj[i].style.width='';
	}
}

document.onmousemove=positiontip;

if(typeof(XMLHttpRequest) == "undefined"){
  XMLHttpRequest = function() {
    try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}catch(e){}
    try{return new ActiveXObject("Msxml2.XMLHTTP.3.0");}catch(e){}
    try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}
    try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}
  };
}

CART = new Object();

function slideCart(dir){
	CART.ramp++;
	var unit = CART.ramp + CART.ramp;
	if((CART.cartSlideLeft - unit) < 1){
		unit = CART.cartSlideLeft;
	}
	CART.cartSlideLeft = (CART.cartSlideLeft - unit);
	var leftOff = parseInt(CART.cartInner.style.left);
	CART.cartInner.style.left = (dir == 'R') ?(leftOff + unit) + 'px': (leftOff - unit) + 'px';
	if(CART.cartSlideLeft < 1){
		window.clearInterval(CART.interval);
		var string = (dir == 'R')? ['S','H','O','W','&nbsp;','C','A','R','T']: ['H','I','D','E','&nbsp;','C','A','R','T'];
		for(x in CART.cartButton.childNodes){
			CART.cartButton.childNodes[x].innerHTML = string[x];
		}
		if(dir == 'R'){CART.cart.style.zIndex = 1;}
		try{
			var req = new XMLHttpRequest();
			var command = (dir == 'R')? 'hide': 'show';
			req.open("GET",'index.php?trans=crt|'+command);
			req.send("");
		}catch(e){}
	}
}

function hide_cart(obj,w,h){
	window.clearInterval(CART.interval);
	CART.cart = document.getElementById("cartCon");
	CART.cartInner = document.getElementById("cartInnerCon");
	CART.cartButton = document.getElementById("cartButH");
	CART.leftOff = getOffset2(CART.cart,'left');
	CART.leftOffInner = getOffset2(CART.cartInner,'left');
	CART.cartSlideLeft = w;
	CART.ramp = 3;
	var dir = (CART.leftOff == CART.leftOffInner)? 'R': 'L';
	if(dir == 'L'){CART.cart.style.zIndex = 40;}
	CART.interval = window.setInterval('slideCart("'+dir+'");',5);
}

function setCartStyle(){
	var bottomMarker = document.getElementById('cartStretchMarker');
	var offSetT = getOffset2(bottomMarker,'top');
	if(offSetT > (jH-250)){
		document.getElementById('searchCon').style.position = 'absolute';
		document.getElementById('cartCon').style.position = 'absolute';		
	}
	return false;
}


// COMPATIBILITY IS AN ISSUE... I AM NOT MOVING OVER THE FRAME CONTROLLER UNTIL IT'S BETTER TESTED...




//function objToString(o){s='';for(aProp in o){s += aProp + "\t";}return s;}
var cal_only=0;
var is_nav=0;
var Events = Array();

function set_day(day){
	if(cal_only==1){
		mt = document.getElementById('month');
		yr = document.getElementById('year');
		deptCond = window.opener.document.getElementById('deptDateCondensed');
		deptCond.value = yr.value + '/' + mt.value + '/' + day;
		window.close();
	}else if(is_nav!=1){
		clearTravelContent();
	}else{ // is_nav must equal one
		document.getElementById('mini_cal').submit();
	}

	return true;
}


function set_year(eventform){
	populateCalEvents(0,1,eventform);
}


function get_mycalFilter(){
	try{
		var MapKey = document.getElementById('mycal_filter').value;
	}catch(e){
		var MapKey = 'Events';
	}
	return MapKey;
}

function populateCalEvents(dir,update_only,eventform){
	// don't pass the month get it from the select box
	var yearId = '';
	var monthId = '';
	if(eventform == 1){
		var yearId = 'Submit';
		var monthId = 'Submit';		
		var y=document.getElementById('year'+yearId);
		var m=document.getElementById('month'+monthId);	
	}else{
		var y=document.getElementById('year');
		var m=document.getElementById('month');	
		
	}

	var mth=m.options[m.selectedIndex].value;
	var yr=y.options[y.selectedIndex].value;
	var MapKey = get_mycalFilter();
	if(!update_only){
		if(dir){//add
			mth++;
			if(mth>12){mth=1;yr++;}
		}else{
			mth--;
			if(mth==0){mth=12;yr--;}
		}
	}

	pm=mth;
	if(mth<10){mth="0"+mth;}
	ind = yr + "" + mth;
	p=-1;

	if(is_nav==1){
		for(x=0;x< Events[MapKey].length;x++){
			if(Events[MapKey][x][0]==ind){
				p=x;break;
			}
		}
		eveArr=(p!=-1)? Events[MapKey][p][1]: [];
		write_month(yr,mth,0,eveArr);
	}
	
	// set the month and year box ... if your in event submit mode you have two of them to set...
	for(x=0;x < m.options.length;x++){
		if(m.options[x].value == pm){m.selectedIndex=x;}
	}
	for(x=0;x < y.options.length;x++){
		if(y.options[x].value == yr){y.selectedIndex=x;}
	}	

	if(eventform == 1){
		var y=document.getElementById('year');
		var m=document.getElementById('month');
		for(x=0;x < m.options.length;x++){
			if(m.options[x].value == pm){m.selectedIndex=x;}
		}
		for(x=0;x < y.options.length;x++){
			if(y.options[x].value == yr){y.selectedIndex=x;}
		}			
	}else{
		try{
			var y=document.getElementById('yearSubmit');
			var m=document.getElementById('monthSubmit');
			for(x=0;x < m.options.length;x++){
				if(m.options[x].value == pm){m.selectedIndex=x;}
			}
			for(x=0;x < y.options.length;x++){
				if(y.options[x].value == yr){y.selectedIndex=x;}
			}			
		}catch(e){
			//alert('failed');		
		}		
	}


	if(is_nav!=1){
		set_month(1);
	}

}

function set_month(update_only,is_event_form){
	if(cal_only==1 || is_nav==1){
		populateCalEvents(0,1,is_event_form);
		return true;
		//m=document.getElementById('mini_cal');m.submit();return true;
	}
	var m=document.getElementById('month');
	var year=document.getElementById('year');
	var mth = m.value;
	if(mth.length==1){mth="0"+mth;}
	var yr=year.value;
	var highlight = [];
	var dept=(default_dept=='')?[document.getElementById('leavingFrom').value]:default_dept.split('|');
	var dest=document.getElementById('goingTo');
	DEST=(dest==null)? default_dest.split("|") : dest.value.split("|");
	s_i= yr+""+mth;
	var f = -1;
	var cL=0;
	var cR=0;
	for(d in DEST){
		for(w=0;w < dept.length;w++){
			for(x=0;x < Dept[pcfl][dept[w]].length;x++){
				if(Dept[pcfl][dept[w]][x][0] == DEST[d]){
					for(y=0;y < Dept[pcfl][dept[w]][x][4][0].length;y++){
						if(Dept[pcfl][dept[w]][x][4][0][y] == s_i){
							for(z in Dept[pcfl][dept[w]][x][4][1][y]){						
								highlight.push(Dept[pcfl][dept[w]][x][4][1][y][z]);
							}
							break;
						}
					}
					if(cL && cL > Dept[pcfl][dept[w]][x][4][2][0] || !cL){cL=Dept[pcfl][dept[w]][x][4][2][0];}
					if(cR && cR < Dept[pcfl][dept[w]][x][4][2][1] || !cR){cR=Dept[pcfl][dept[w]][x][4][2][1];}
					break;
				}
			}
		}
	}
	aR=document.getElementById('nav-month-right');
	aL=document.getElementById('nav-month-left');
	aL.style.display=(cL >= s_i || dest.value == 0)?'none':'inline';
	aR.style.display=(cR <= s_i || dest.value == 0)?'none':'inline';
	m.value = parseFloat(mth);
	year.value = yr;
	write_month(yr,mth,'POST',highlight);
	return true;
}



function isLeap(year){
 if ((year%400==0)||((year%4==0)&&(year%100!=0))) {return true;}
 else {return false;}
}


function write_month(yr,mth,mode,highlight){
	// we should have passed a standardized array of dates to highlight and the method for which we are posting those dates...
	// now we need to cycle through the calendar grid and write the appropriate code for each day...
	// alert('Year:'+yr+'   Month:'+mth+'   highlight:'+highlight);
	// we should be writing the calendar regardless of whether we have a highlight or not...
	// figure out what day the first is ex MON TUEs
	var myDate = new Date();
	myDate.setFullYear(yr,mth-1,1);
	var theFirst = myDate.getDay();
	ML=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	dayMax = ((mth-1)==1 && isLeap(yr))? ML[mth-1]+1: ML[mth-1];
	//alert(dayMax);
	// 7 == Saturday
	// wipe the grid clean
	day=0;
	for(z=1;z<43;z++){
		c=document.getElementById('cal-'+z);
		c.className = "empty_day_cell";
		c.innerHTML = '';
		if(z > theFirst && day < dayMax){
			day++;
			c.className = "day_cell";
			c.innerHTML = day
			for(var i=0;i<highlight.length;i++){
				if(highlight[i] == day){
					c.className = "travel_cell";
					c.innerHTML = "<input class='day_cell_input' type='submit' name='day' onclick='set_day("+day+");' value='"+day+"' />";
				}
			}

		}	
	}
}

function get_mini_cal(){
	if(document.getElementById){
		dept = document.getElementById('leavingFrom');
		if(default_dest!=''){
			destination = default_dest;
		}else{
			dest = document.getElementById('goingTo');
			destination = dest.value;
		}
		if(pcfl=='pc'){
			pack = document.getElementById('package_code');
		}else{
			pack = document.getElementById('flight_return');
		}
		if(!(dept.value  == '' || dept.value == 0) && !(destination == '' || destination == 0)){
			DeptDest = '&dept='+dept.value+'&dest='+destination+'&pcfl='+pcfl+'&pack='+pack.value;
		}else{
			DeptDest = '&dept=all&dest=all';
		}
	}
	window.open('index.php?page=mini_calendar'+DeptDest,'mini_cal', 'toolbar=no,width=250,height=200');
}

	function submitMonthYear() {
		document.monthYear.method = "post";
		document.monthYear.action = "index.php?month=" + document.monthYear.month.value + "&year=" + document.monthYear.year.value;
		document.monthYear.submit();
	}

	function postMessage(day, month, year) {
		var month = document.getElementById('month').value;
		var year = document.getElementById('year').value;	
		try{
			var day = document.getElementById('day').value;			
		}catch(e){
			var day = document.getElementById('today').value;
		}
		
		eval("page" + day + " = window.open('index.php?page=calendar&mode=post&d=" + day + "&m=" + month + "&y=" + year + "', 'postScreen', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=340,height=400');");
	}

	function openPosting(pId) {
		eval("page" + pId + " = window.open('index.php?page=calendar&mode=display&id=" + pId + "', 'mssgDisplay', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=340,height=400');");
	}

	function editPosting(pId) {
		eval("page" + pId + " = window.open('index.php?page=calendar&mode=eventform&id=" + pId + "', 'mssgDisplay', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=340,height=400');");
	}

	function editReminder(pId) { // took this out for now...
		var MapKey = get_mycalFilter();
		eval("page" + pId + " = window.open('index.php?page=calendar&filter="+MapKey+"&mode=reminder&id=" + pId + "', 'mssgDisplay', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=340,height=400');");
	}

	function deleteConfirm(eid,day,get_str) {
		var msg = "Are you Sure?";
		var get_str = (get_str != 'undefined')? get_str: '';
		y=document.getElementById('year');
		m=document.getElementById('month');
		mth=m.options[m.selectedIndex].value;
		yr=y.options[y.selectedIndex].value;
		if (confirm(msg)) {
			window.location = "index.php?"+get_str+"&mode=eventsubmit&flag=delete&id=" + eid + "&month="+mth+"&year="+yr+"&day="+day;
		} else {
			return;
		}
	}

	function getDates(){ //v3.0
		formDept = document.getElementById('leavingFrom');
		formDest = document.getElementById('goingTo');
		formOpt = document.getElementById('type_opt');
		formDur = document.getElementById('duration');
		dept = formDept.options[formDept.selectedIndex].value;
		if(formDest.options){
			dest = formDest.options[formDest.selectedIndex].value;
		}else{
			alert('Has No Options');
			dest = formDest.value;				
		}
		if(formOpt.options){
			opt = formOpt.options[formOpt.selectedIndex].value;
			ro=1;
		}else{
			opt='';
			if(formOpt.checked){
				ro=formDur.value;
				formDur.style.visibility='visible';		
			}else{
				ro='0';
				formDur.style.visibility='hidden';
			}
		}	
	}
function objToString(o){s='';for(aProp in o){s += aProp + "\t";}return s;}
function tohex(x){var s='',x_=!isNaN(Number(x))?Number(x):0;while(Boolean(x_)){s='0123456789ABCDEF'.charAt(x_&0xf)+s;x_>>>=4;}while(s.length&0x7){s='0'+s;}return(s);}
function encrypt(a,z,k){var t=new Array();t[0]=1;t[1]=new Number(a);t[2]=new Number(z);var s=0,d=0x9E3779B9,n=32;while(n-->0){t[1]=(t[1]+((t[2]<<4^((t[2]>>5)&0x07ffffff))+t[2]^s+k[(s&3)]))&0xffffffff;s=(s+d)&0xffffffff;t[2]=(t[2]+((t[1]<<4^((t[1]>>5)&0x07ffffff))+t[1]^s+k[(((s>>11)&0x001fffff)&3)]))&0xffffffff;}return(t);}
function cT(w,p){var v=0,h=0,u=null,g='',t,i,e="!!!!!!!\x0d\x0d!!!!!!!";t=''+String.fromCharCode((w.length/16777216)&0xFF)+String.fromCharCode((w.length/65536)&0xFF)+String.fromCharCode((w.length/256)&0xFF)+String.fromCharCode(w.length&0xFF);w=t+w;while(w.length&0x7){w+='\0';}i=0;while(p.length%16){p+=p.charAt(i++);}t=p;p=new Array(p.length/4);i=0;j=0;while(i<t.length)p[j++]=(((t.charCodeAt(i++)&0xFF)<<24)|((t.charCodeAt(i++)&0xFF)<<16)|((t.charCodeAt(i++)&0xFF)<<8)|((t.charCodeAt(i++)&0xFF)))&0xFFFFFFFF;i=0;j=0;k=new Array(4);l=w.length;while(i<l){m=p.length;if(j+4<=m){k[0]=p[j];k[1]=p[j+1];k[2]=p[j+2];k[3]=p[j+3];}else{k[0]=p[j%m];k[1]=p[(j+1)%m];k[2]=p[(j+2)%m];k[3]=p[(j+3)%m];}j=(j+4)%m;v=w.charCodeAt(i++)<<24;v|=w.charCodeAt(i++)<<16;v|=w.charCodeAt(i++)<<8;v|=w.charCodeAt(i++);v&=0xFFFFFFFF;h=w.charCodeAt(i++)<<24;h|=w.charCodeAt(i++)<<16;h|=w.charCodeAt(i++)<<8;h|=w.charCodeAt(i++);h&=0xFFFFFFFF;u=encrypt(v,h,k);g+=(u[0]?''+tohex(u[1])+tohex(u[2]):e);v=0;h=0;u=null;}return g;}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

ROWS=[]; // ----------------------- ??? ---- ??? ---- ??? ---- ???
RCLASS=[];
ROWSC=[];
ROWS.dir=0;
ROWS.srt=0;
ROWS.pn=1;

//
//ROWS['inbox'] = [];
//ROWS['inbox'].srt = 5;
//page=mail&pane=inbox&page_only=1&srt=5&dir=0&pn=2&rmi=inbox

CMS = new Object();
CMS.use_local = (typeof(JSON) == 'object' && typeof(localStorage) == 'object')? 1: 0;
CMS.CSS = [];
CMS.pLD = [];
CMS.rowMapKey = null;

stateMaps=[];
CHARTS=[];
TEMPLATES=[];
RECORD_MAPS=[];

FRMES=[];
NEW_RECORD_COUNTERS=[];
DRAG_TODO=[];
DRAG_TODO[1]=[];
DRAG_TODO[2]=[];
DRAG_TODO.p=0;
DRAG_TODO.block=null;
FS_PANEL=[];
BLUR_CACHE=[];
PANES=[];
PAGES=[];
CATS=[];
STAGES=[];
LOADER=null;
cacheVal=false;
cacheKey=false;

FILES_C = 0;

if(typeof(AUTOS) == 'undefined'){
	AUTOS=[];
}

isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers; // ---- YOU SHOULD REALLY TAKE A FEW SECONDS AND REMOVE THIS CRAP... ANYTHING WHICH REFERENCES NS4
isHot=false;

var conM = "Do you really want to delete this Record?";

var AUTO_SAVE = new Object();

var slideController = new Object();
var enableSlide = 0;


function chartCollapse(obj,state){
	var pane = obj.parentNode.parentNode.childNodes[1];
	pane.style.display = (pane.style.display == 'block')? 'none': 'block';
	obj.innerHTML = (pane.style.display == 'block')? 'collapse': 'expand';
}

function toggleDisplay(id,c,r,obj){
	try{
		var display = document.getElementById(id);
		var on = (display.style.display == 'block')? 1: 0;
		display.style.display = (on)? 'none': 'block';
		obj.className = (on)? c+'1': c+'2';
	}catch(e){
		alert(id+"="+e);
		return true;
	}
	return (r)? true: false;
}

function sendChart(id,key,mode,swit,is_reset){ // mode 1
	var obj = document.getElementById('chart-'+id);
	var OffL1 = getOffset(obj.childNodes[0],'left');
	var OffL2 = getOffset(obj.childNodes[1],'left');
	var width = OffL2 - OffL1;
	var height = parseInt(obj.style.height);
	var key = (typeof(key) != "undefined")? key: CHARTS[id][0][1];
	var mode = (typeof(mode) != "undefined")? mode: CHARTS[id][0][2];
	var swit = (typeof(swit) != "undefined")? swit: CHARTS[id][0][3];
	var sLBL = CHARTS[id][0][4];
	var sCHK = CHARTS[id][0][5];
	var chart = CHARTS[id][1][swit];
	var data = (typeof(CHARTS[id][key]) != "undefined" && typeof(CHARTS[id][key][mode]) != "undefined" && typeof(CHARTS[id][key][mode][swit]) != "undefined")? CHARTS[id][key][mode][swit]['data']: false;

	if(!width){return;}
	obj.childNodes[2].style.display = "block";
	obj.childNodes[2].style.height = height+"px";
	obj.childNodes[2].style.width = width+"px";

	//alert('php/graphics/pchart.php?c='+chart+'&w='+width+'&h='+height+data);
	if(data){
		var l = data.length;
		var data_str = '';
		var is_label = 0;

		for(var x = 0; x < l; x++){
			if(sLBL && (l-1) == x){
				is_label = 1;
				data_str += '&S=';		
			}else{
				data_str += (x==0)? '&L=': '&L'+x+'=';
			}
			if(x && sCHK && !is_label){
				var chkB = document.getElementById('chtC-'+(x-1)+'-CB');
				if(is_reset){
					chkB.checked = "checked"; 
				}else if(!Boolean(chkB.checked)){
					data_str += 'NULL';
					continue;
				}
			}
			data_str += data[x].join('|');
		}
		obj.childNodes[3].innerHTML = '<img onload="ChartLoaded(this);" src="php/graphics/pchart.php?c='+chart+'&w='+width+'&h='+height+data_str+'" style="width:100%;" border="0">';
		var avgs = CHARTS[id][key][mode][swit]['avgs'];
		try{
			for(x in avgs){
				document.getElementById(x).innerHTML = avgs[x];
			}
		}catch(e){alert(x+" = "+e);}
	}else{
		var command = "cht|"+id+"|"+key+"|"+mode+"|"+swit;
		//alert("command="+command);
		requestController(command,0,false,false,false);
	}
}

function loadChart(command,chart_id,date_key,mode,swit,arr){
	clearController(command);
	if(typeof(CHARTS[chart_id][date_key]) == 'undefined'){CHARTS[chart_id][date_key] = [];}
	if(typeof(CHARTS[chart_id][date_key][mode]) == 'undefined'){CHARTS[chart_id][date_key][mode] = [];}
	CHARTS[chart_id][date_key][mode][swit] = arr[chart_id][date_key][mode][swit];
	sendChart(chart_id,date_key,mode,swit);
}

function setChart(obj,id){
	var d = document.getElementById('stats_date[day]').value;
	var m = document.getElementById('stats_date[month]').value;
	var y = document.getElementById('stats_date[year]').value;
	var key = y+"/"+m+"/"+d;
	var mode = document.getElementById('stats_date_mode');
	mode = mode[mode.selectedIndex].value;
	var swit = document.getElementById('stats_switch_mode');
	swit = swit[swit.selectedIndex].value;
	var is_reset = (obj.nodeName=='SELECT')? 1: 0;
	sendChart(id,key,mode,swit,is_reset);
}

function ChartLoaded(obj){
	//obj.parentNode.style.height = null;
	obj.parentNode.parentNode.childNodes[2].style.display = "none";
}

function loadCharts(){
	if(typeof(CHARTS) != 'undefined'){
		for(x in CHARTS){
			sendChart(x);
		}
	}
}

function requestController(command,hook,is_post,no_busy,throbber,obj){

	try{
		var dm = document.getElementById('dashboard_message');
		dm.innerHTML='';
		dm.style.background = "none";
	}catch(e){}

	try{
		PANES[PANES.i].ownerDocument.getElementById('error_message').innerHTML='';
	}catch(e){}

	if(no_busy && 1==1){
		var req = new XMLHttpRequest();
		req.open("GET",'index.php?trans='+command);
		req.send("");
		return false;
	}

	if(throbber){// reserveClass
		var a = document.getElementById(command).childNodes[1];
		a.classNameCached = a.className;
		a.innerHTMLCached = a.innerHTML;
		a.innerHTML = '&nbsp;';
		a.className = throbber;
		a.blur();
	}

	var l,ind,fr;
	fr = top.frames;
	l = fr.length;
	//alert("L is="+l);
	if(l > 20){
		//alert("L is greater than 20 its="+l);
		for(x=0;x<l;x++){
			//alert("className="+fr[x].frameElement.className);
			//alert(objToString(fr[x]));
		}
		//top.location.replace(top.location.toString());
		return;
	}

	//	perhaps you should be setting a timeout on the frames... we need to clean these up as we go along... and we need to remove the limit...
	//	alert("length:"+l);

	for(var x=1; x < l; x++){ // skip the heartbeat...
		if(!FRMES[x]){FRMES[x]=[];} // move to an initializer...
		try{fr[x].test = x;}catch(e){continue;}
		if(FRMES[x]['busy']!=true && fr[x].frameElement.className == 'frameController'){
			FRMES[x]['busy']=true;
			FRMES[x]['command']=command;
			FRMES[x]['hook']=hook;		
			// eventually your going to want to store the command and resend in case of failure...
			try{
				PANES[PANES.i].ownerDocument.getElementById('loader').style.display='inline';
			}catch(e){}
			top.frames[x].id = 'RC'+x;
			if(is_post == 'POST'){
				return fr[x];
			}else{
				if(typeof(obj) == 'object'){
					FRMES[x].innerSTORE = obj.innerHTML;
					FRMES[x].caller = obj;
					FRMES[x].oldClass = obj.className;
					//obj.innerHTML = ''; // THIS IS CAUSING ISSUES WHEN A SECOND CHILD RECORD IS CALLED IN INTERNET EXPLORER ONLY...
					obj.className = obj.className+"X";
					obj.blur();
				}
				fr[x].location.replace('index.php?trans='+command);
				return false;
				return x;
			}
		}
	}

	var newframe;
	newframe = document.createElement("IFRAME");
	newframe.setAttribute('class','frameController');
	newframe.className = 'frameController';
	
	newframe.setAttribute('style','position:absolute;left:-500px;top:0px;');
	newframe.setAttribute('width','0px');
	newframe.setAttribute('height','0px');
	newframe.setAttribute('border','0px');

	//newframe.setAttribute('width','1000px');
	//newframe.setAttribute('height','1000px');

	document.body.appendChild(newframe);
	return requestController(command,hook,is_post,no_busy);
}

function switch_tab(obj,tab){
	var grp = document.getElementById(obj.id);
	var tab_set = document.getElementById(tab).childNodes;
	var y = grp.selectedIndex;
	var l = tab_set.length
	for(x=0;x < l;x++){
		if(x==y){
			tab_set[x].style.display = 'block';
		}else{
			tab_set[x].style.display = 'none';
		}
	}
}

function switch_rec_tab(rec_no,tab_no){
	x=1;
	for(var z = 0 ; z < 10; z ++){
		try{
			var tab_class = (tab_no == z)? 'aTabA': 'aTabB';
			document.getElementById('rec_tab_'+rec_no+'_'+z).className = tab_class;
			var tab_display = (tab_no == z)? 'block': 'none';
			document.getElementById('rec_pane_'+rec_no+'_'+z).style.display = tab_display;
		}catch(e){z=20;}
	}
	try{
		loadCharts();
	}catch(e){}
	return false;
}

function initAutoSave(){
	var id = document.getElementById('iAutoS').value;
	var freq = document.getElementById('iAutoSF').value;
	var mili = freq * 60000;
	AUTO_SAVE.setTimeout = setTimeout("runAutoSave()",5000);
}

function runAutoSave(lang){

	if(lang){
		//alert("CALL TO SAVE LANG");
		var activeLang = LANGS['active'][0];
		var activeServ = LANGS['active'][1];	
		var sect = 'lang';
		var pane = activeLang+"-"+activeServ;
		var id = document.getElementById('iLangS').value;
		var frame = document.getElementById(id+"___Frame");
		var content = frame.contentWindow;
		var html = content.FCK.GetXHTML();// FCKConfig.FormatSource 

		var rec_id = document.getElementById('rec_id').value;
		var rec_type = document.getElementById('rec_type').value;
		var lang_serv_key = "lang-"+activeLang+"-"+activeServ;
		//RECORDS[rec_type][rec_id][lang_serv_key] = [];
		//RECORDS[rec_type][rec_id][lang_serv_key][1] = arr[1][1];
		//RECORDS[rec_type][rec_id][lang_serv_key][2] = arr[1][2];
		RECORDS[rec_type][rec_id][lang_serv_key][3] = html;

		document.getElementById('in-3').value = html;
		element_whitelist=[];
		element_whitelist[0] = 'rec_id';
		element_whitelist[1] = 'rec_type';
		//element_whitelist[2] = 'iLangSV'; // replaced in favour of in-3
		element_whitelist[3] = 'rec_lang';
		var y = 4;
		for(x in RECORDS[rec_type][0]['cam']){
			element_whitelist[y++] = 'in-'+x;
		}
		savePane(sect,pane,'AUTO_SAVE',element_whitelist);
	}else{
		var sect = 'newsletter';
		var pane = 'newsletters';
		var id = document.getElementById('iAutoS').value;
		var frame = document.getElementById(id+"___Frame");
		var onOff = document.getElementById('iAutoST').value;
		if(onOff == 'off'){return;}
		var content = frame.contentWindow;
		var html = content.FCK.GetXHTML();// FCKConfig.FormatSource 
		if(html.replace(/^\s+|\s+$/g,"") == ""){
			var freq = document.getElementById('iAutoSF').value;
			var mili = freq * 60000;
			AUTO_SAVE.setTimeout = setTimeout("runAutoSave()",mili);	
			return;
		}
		document.getElementById('iAutoSV').value = html;
		element_whitelist=[];
		element_whitelist[0] = 'rec_id';
		element_whitelist[1] = 'rec_type';
		element_whitelist[2] = 'iAutoSV';
		savePane(sect,pane,'AUTO_SAVE',element_whitelist);
		var freq = document.getElementById('iAutoSF').value;
		var mili = freq * 60000;
		AUTO_SAVE.setTimeout = setTimeout("runAutoSave()",mili);
	}
}

function toggleAutoSave(obj){
	var onOff = document.getElementById('iAutoST');
	if(onOff.value == 'off'){
		onOff.value = 'on';
		obj.innerHTML = 'Enabled';
		var freq = document.getElementById('iAutoSF').value;
		var mili = freq * 60000;
		AUTO_SAVE.setTimeout = setTimeout("runAutoSave()",mili);
	}else{
		onOff.value = 'off';
		obj.innerHTML = 'Disabled';
		clearTimeout(AUTO_SAVE.setTimeout);
	}
}

function restoreAutoSave(){
	var sect = 'newsletter';
	var pane = 'newsletters';
	element_whitelist=[];
	element_whitelist[0] = 'rec_id';
	element_whitelist[1] = 'rec_type';
	savePane(sect,pane,'RESTORE_SAVE',element_whitelist);
}

function setLangLock(t){
	setTimeout("LANGS['lock'] = 0;",t);
}

function restoreLang(lang,ver,mode,anchor){

	if(LANGS['lock']){ // KLUDGE // Required because a fast double click causes the wrong record to overwrite from cache...
		return;
	}
	LANGS['lock'] = 1;
	setLangLock(1000);

	// mode 2 is a reque...
	// mode 0 is a switch, or load...

	// SHOULD THESE BE NAME VALUE PAIRS???
	// alert("RESTORE LANG="+lang + " " + ver + " " + mode);
	var sect = 'lang';
	var pane = lang+"-"+ver;
	var activeLang = (!mode)? lang:LANGS['active'][0];
	var activeServ = (!mode)? ver:LANGS['active'][1];
	var rec_id = document.getElementById("rec_id").value;
	var rec_type = document.getElementById("rec_type").value;
	var rec_lang = document.getElementById("rec_lang").value;
	var lang_serv_key = "lang-"+lang+"-"+ver;
	if(!mode){
		// I need to cache stored...
		// alert("active="+LANGS['active'][0]+" "+LANGS['active'][1]);

		var id = document.getElementById('iLangS').value;
		var frame = document.getElementById(id+"___Frame");
		var content = frame.contentWindow;
		var default_lang = LANGS[0];
		var var_sect = document.getElementById('var_sect').value;
		var form = document.getElementById(var_sect);

		// ALWAYS STORE CHANGES
		var lang_store_key = "lang-"+LANGS['active'][0]+"-"+LANGS['active'][1];

		//alert(lang_store_key);
		var html = content.FCK.GetXHTML();
		for(x in RECORDS[rec_type][0]['cam']){
			var store_value = (x == 3)? html: document.getElementById('in-'+x).value;
			RECORDS[rec_type][rec_id][lang_store_key][x] = store_value;	
			var lang_input_key = lang_store_key+'-'+x;
			try{
				var input = document.getElementById(lang_input_key).value = store_value;
			}catch(e){
				var input = document.createElement('INPUT');
				input.setAttribute('id',lang_input_key);
				input.setAttribute('name',lang_input_key);
				input.setAttribute('type','hidden');
				input.value = store_value;
				form.appendChild(input);
			}
		}
		// I WANT TO CHECK THE LANG MAPS TO SEE IF ITS BEEN STORED OR NOT... and reload from stored.
		if(LANGS[2][lang_serv_key][2]){
			//alert("RESTORE("+lang_serv_key+")="+objToString(RECORDS[rec_type][rec_id][lang_serv_key]));
			for(x in RECORDS[rec_type][0]['cam']){
				if(x == 3){
					content.FCK.SetData(RECORDS[rec_type][rec_id][lang_serv_key][x]);
				}else{
					document.getElementById('in-'+x).value = RECORDS[rec_type][rec_id][lang_serv_key][x];
				}
			}
			LANGS['active'] = [lang,ver];
			toggle_lang_switches();
			return;
		}
		//alert("ITS NOT LOADED REQUEST FROM SERVER="+lang_serv_key);
	}

	var com = 'rl'+mode;
	var command = com+"|"+activeLang+"|"+activeServ+"|"+rec_type+"|"+rec_id;
	requestController(command,0,false,false,false);
}

function loadAutoSave(sect,data,mode,arr){ // called when a frame returns content...
	// WHAT HAPPENS WHEN YOU'VE BEEN LOGGED OUT DUE TO INACTIVITY? CLEAR COOKIES AND FIND OUT...
	var hook = clearController(sect);
	if(mode == 'AUTO_SAVE'){
		document.getElementById('auto_save_time').innerHTML = data;
	}else if(mode == 'RESTORE_SAVE'){
		var id = document.getElementById('iAutoS').value;
		var frame = document.getElementById(id+"___Frame");
		var onOff = document.getElementById('iAutoST').value;
		if(onOff == 'off'){return;}
		var content = frame.contentWindow;
		//alert(data);
		content.FCK.SetData(arr[1][3]);
	}else if(mode == 'LANG_SAVE'){
		var lang_key = "lang-"+arr[0][0];
		var lang_serv_key = "lang-"+arr[0][0]+"-"+arr[0][1];
		LANGS[3][lang_key][1] = arr[0][1];
		LANGS[2][lang_serv_key][1] = 1;
		LANGS[2][lang_serv_key][4] = 0;
		toggle_lang_switches();
	}else if(mode == 'RESTORE_LANG'){
		var rec_id = document.getElementById('rec_id').value;
		var rec_type = document.getElementById('rec_type').value;
		var lang_key = "lang-"+arr[0][0];
		var lang_serv_key = "lang-"+arr[0][0]+"-"+arr[0][1];
		var is_preferred = arr[2][1];
		//alert("lang_serv_key="+objToString(RECORDS[rec_type][rec_id][lang_serv_key]));
		RECORDS[rec_type][rec_id][lang_serv_key] = [];
		RECORDS[rec_type][rec_id][lang_serv_key][1] = arr[1][1];
		RECORDS[rec_type][rec_id][lang_serv_key][2] = arr[1][2];
		RECORDS[rec_type][rec_id][lang_serv_key][3] = arr[1][3];
		//alert("lang_serv_key="+objToString(RECORDS[rec_type][rec_id][lang_serv_key]));
		LANGS[2][lang_serv_key][2] = 1;
		var id = document.getElementById('iLangS').value;
		var frame = document.getElementById(id+"___Frame");
		var content = frame.contentWindow;
		for(x in RECORDS[rec_type][0]['cam']){
			if(x == 3){
				content.FCK.SetData(arr[1][3]);
			}else{
				document.getElementById('in-'+x).value = RECORDS[rec_type][rec_id][lang_serv_key][x];
			}
		}

		//alert("LOAD AUTO SAVE="+lang_serv_key);
		//alert(LANGS[2][lang_serv_key]);
		LANGS[2][lang_serv_key][1] = arr[2][1];
		LANGS[2][lang_serv_key][3] = arr[2][3];
		LANGS[2][lang_serv_key][4] = arr[2][4];
		if(is_preferred == 1){
			LANGS[3][lang_key][1] = arr[0][1];
		}		

		//alert(LANGS[2][lang_serv_key]);

		LANGS['active'] = [arr[0][0],arr[0][1]];
		toggle_lang_switches();
	}
}

// I NEED A LANG OBJECT FOR TOGGLING PURPOSES...

function toggle_lang_switches(){
	var lang_box = document.getElementById("lang_box");
	var arr = LANGS['active'];
	var this_lang = "lang-"+arr[0]+"-"+arr[1];
	var this_sect = "lang-"+arr[0];
	var styles = ['proofA','proofIA','proofAP','proofIAP','proofIN','proofIAN','proofAE','proofE','proofIAE','proofIE'];
	document.getElementById("rec_lang").value = arr[0]+"-"+arr[1];
	//alert(LANGS['active'][0] +" "+ LANGS['active'][1]);
	var lang_key,active,lang_button,lang_sect_key,ex,panel_set;
	//alert(this_lang);
	for(x in LANGS[2]){
		ex = x.split("-");
		var lang_pref = LANGS[2][x];
		var lang_control = LANGS[3]['lang-'+ex[1]];
		var B1 = document.getElementById(x);

		if(lang_pref[4] > 0){
			B1.className = (x == this_lang)? styles[8]: styles[9];
			if(!lang_control[0] && ex[2] == lang_control[1] && lang_pref[3] == 1){
				B1.className = (x == this_lang)? styles[6]: styles[7];
			}else if(lang_control[1] && ex[2] == lang_control[1] && lang_pref[3] > 1){
				B1.className = (x == this_lang)? styles[6]: styles[7];
			}
		}else if(!lang_control[0] && ex[2] == lang_control[1] && lang_pref[3] == 1){ // its preferred...
			B1.className = (x == this_lang)? styles[2]: styles[3];
		}else if(lang_control[1] && ex[2] == lang_control[1] && lang_pref[3] > 1){ // strict Proofing Preferred
			B1.className = (x == this_lang)? styles[2]: styles[3];
		}else if(lang_pref[3] == 0){
			B1.className = (x == this_lang)? styles[5]: styles[4];
		}else{
			B1.className = (x == this_lang)? styles[0]: styles[1];
		}

		if(ex[2] != 0){
			if(ex[1] == arr[0]){
				if(panel_set == 1){continue;}
				panel_set = 1;
			}
			active = ((ex[0]+"-"+ex[1]) == this_sect)? 1: 0;
			//alert("FOUND ACTIVE="+"("+ex[0]+"+ +"+ex[1]+") == "+this_sect);
			lang_sect = document.getElementById("lang-"+ex[1]);
			var lC0 = lang_sect.childNodes[1].childNodes[0];
			var lC1 = lang_sect.childNodes[1].childNodes[1];
			lC0.className = (active)? "proofIA":"";
			lC0.style.display = (active)? "inline":"none";
			lC1.className = (active)? "proofIA":"";
			lC1.style.display = (active)? "inline":"none";
		}
	}
}

function switch_widget(obj,tab){
	//obj.parentNode.parentNode.(obj.options.selectedIndex);
	var inp = obj.parentNode.parentNode.childNodes[1].childNodes[0];
	if(obj.options.selectedIndex && obj.options[obj.options.selectedIndex].text.indexOf('Is') == -1){
		inp.disabled = 0;
		inp.focus();
	}else{
		inp.disabled = 1;
		inp.value = '';
	}
}

function goto_pn(obj,i,s,rowMapIndex,paneIndex){

	var sort = 0;
	var filters = false;
	var paneFind = false;
	var paneFindVal = '';

	if(obj.id === 'page_select'){	
		var i = obj.options[obj.selectedIndex].value;
	}else if(i == 'n'){
		var i = 1+parseInt(ROWSC[rowMapIndex].pn);
	}else if(i == 'p'){
		var i = parseInt(ROWSC[rowMapIndex].pn)-1;
	}else if(i == 'c'){
		sort = 1;
		var d = (ROWSC[rowMapIndex].dir == 1)? 0: 1;
		var i = parseInt(ROWSC[rowMapIndex].pn);
	}else if(i == 'f'){ // filter
		var i = parseInt(ROWSC[rowMapIndex].pn);
		var filters = true;
	}else if(i == 's'){ // search
		var i = parseInt(ROWSC[rowMapIndex].pn);
		var paneFindVal = obj.parentNode.childNodes[1].value;
		paneFind = true;
	}

	if(!sort){
		s = ROWSC[rowMapIndex].srt;
		d = ROWSC[rowMapIndex].dir;
	}

	//str += 'pn=' + i;
	var checkF = '';
	if(filters){
		var checkFilters = document.getElementById('check_filters');
		for(x in checkFilters.childNodes){
			var input = checkFilters.childNodes[x];
			if(input.nodeName == 'INPUT'){
				checkF += (input.checked)? '1':'0';
			}
		}
	}

	var do_find = (paneFind)? 1: 0;
 	var command = 'row|'+sort+"|"+s+"|"+d+"|"+i+"|"+rowMapIndex+"|"+do_find+"|"+paneFindVal+"|"+paneIndex+"|"+checkF;
	requestController(command,1,false);
	obj.blur();
	return false;
}

function checkbox(obj){
	var pane = PANES.i.substr(2);
	obj.className = "checkC";
	element_whitelist=[];
	element_whitelist[0] = obj.childNodes[0].id;
	element_whitelist[1] = 'SAVE';
	element_whitelist[2] = 'record_id';
	savePane('erp',pane,'CHECKBOX',element_whitelist);
}

function checkboxReturn(objName,objValue){
	var obj = document.getElementById(objName);
	obj.parentNode.className = (objValue > 0)? "checkB": "checkA";
	obj.value = objValue;
}

function to_do_drag(obj,mode){

	// we need to cycle through all the to dos and understand thier co-ordinates...
	var toDoBlock = obj.parentNode.parentNode.parentNode;
	DRAG_TODO.block = toDoBlock;

	var l = (mode == 1)? toDoBlock.childNodes.length:toDoBlock.childNodes.length-2; // we skip the add to... and the hidden textarea...
	var bTop = getOffset(toDoBlock,'top');
	var oTop = getOffset(obj,'top');
	var z = 0;
	for(x = 0; x < l; x++){
		childNode = toDoBlock.childNodes[x];
		ttop = getOffset(childNode,'top') - oTop;
		DRAG_TODO[1][x] = ttop;
		DRAG_TODO[2][x] = childNode;
		DRAG_TODO.l = x;
		if(!ttop){DRAG_TODO.p = x;}
		childNode.style.zIndex = (!ttop)? "100": "10";
	}

	var minY = DRAG_TODO[1][0]; // this is position of the item in relation to the mainblock... in negative numbers...
	var maxY = DRAG_TODO[1][(l-1)];
	var toDo = obj.parentNode.parentNode;

	Drag.init(toDo,null,-5,5,minY,maxY);
	Drag.oHeight = DRAG_TODO[1][DRAG_TODO.p+1]; // find the height of the object...
	Drag.oHeight = 24;

	toDo.onDrag = function(x, y){
		for(z=0;z<l;z++){
			var oby = DRAG_TODO[1][z];
			if(!oby){continue;}
			if(y > 0){
				DRAG_TODO[2][z].style.top = (y >= oby && oby > 0)? Drag.oHeight * -1 + "px": "0px";
			}else if(y < 0){
				DRAG_TODO[2][z].style.top = (y <= oby && oby < 0)? Drag.oHeight + "px": "0px";
			}
		}
	}

	toDo.onDragEnd = function(x, y){
		var l = DRAG_TODO.l;
		var block = DRAG_TODO.block;
		var clones=[];
		var positions=[];
		var ups = 0;
		var downs = 0;
		for(x=0;x<=l;x++){
			obj = DRAG_TODO[2][x];
			var pos = parseInt(obj.style.top);
			if(pos < 0){
				i = x-1;if(x != DRAG_TODO.p){ups++;}
			}else if(pos > 0){
				i = x+1;if(x != DRAG_TODO.p){downs++;}
			}else{
				i = x;
			}
			positions[x] = i;
			obj.style.top = "0px";
			obj.style.left = "0px";
			clones[x] = obj.cloneNode(true);
			block.removeChild(obj);
		}
		positions[DRAG_TODO.p] = (ups)? DRAG_TODO.p+ups: DRAG_TODO.p-downs;
		cadence=[];
		for(x=0;x<=l;x++){
			cadence[positions[x]] = x;
		}
		//alert(positions);
		var c = 0;
		var str = "";
		for(x=0;x<=l;x++){
			block.insertBefore(clones[cadence[x]],block.childNodes[c]);
			var s = clones[cadence[x]].id.split("-");
			var p = (mode == 1)? s.length-1: s.length-2;
			str += s[p] + "-";
			c++;
		}

		var command = (mode == 1)? 'Otl|': 'Otd|';
		command += rtrim(str,"-");
		requestController(command,0,false,true);
	}
}

function over_to_do_item(obj){
	this.className = 'toDoRowO';
}

function out_to_do_item(obj){
	this.className = 'toDoRow';
}

function reorderLists(obj){
	var state = (obj.innerHTML == "Re-Order Lists")? 1: 0;
	var paneForm = document.getElementById("F-to_do_lists-project_to_do_lists").childNodes[0];
	var l = paneForm.childNodes.length;
	for(x=0;x<l;x++){
		var toDoBlock = paneForm.childNodes[x];
		toDoBlock.childNodes[2].style.display = (state)? "none":"block";		
		toDoBlock.childNodes[0].childNodes[0].className = (state)? "toDoDragA": "toDoDrag";
	}
	obj.innerHTML = (state)? "Click to Finish Re-Order": "Re-Order Lists";
	obj.className = (state)? "mMinpY":"mMinpI";
}

function requestRecord(obj,rec_type,rec_id,parent_id,parent_rec_index){

	if(!isInitDone){
		return false;
	}

	// CHECK TO SEE IF WE HAVE LOADED THE TEMPLATE...
	// TEMPLATES NEED TO FAIL GRACEFULLY OR ROUTE OTHERWISE ON FULL SCREEN RECORD LOAD...
	// IF IT'S A CALL TO A NEW RECORD WE CAN SKIP THE CALL TO SERVER...

	var state = (rec_id == 'N')? "new":"edit";
		// alert("rec_type="+rec_type+" state="+state);
	var stateMap = stateMaps[rec_type][state];
	var request_template = (typeof(TEMPLATES[rec_type]) == 'undefined' || typeof(TEMPLATES[rec_type][stateMap.tmpl]) == 'undefined')? 1: 0;

	if(!request_template && state == "new"){
		var arr=[];
		return loadRecord(false,rec_type,rec_id,parent_id,arr,null,null,state);
	}

	var command = 'rec|'+rec_type+"|"+rec_id+"|"+parent_id+"|"+request_template+"|"+parent_rec_index;
	// alert(command);
	requestController(command,null,false,false,false,obj);
}

// THIS NEEDS TO BE A CLEAN ALGO... I NEED TO BE ABLE TO THROW ANYTHING AT IT SERVER SIDE AND HAVE IT RETURN TO THE SERVER IN TACT...

function loadRecord(command,rec_type,rec_id,parent_id,arr,tmpl,rM,state,autos,load_type,record_index){

	var hook = 0;
	if(command){
		hook = clearController(command);
		try{
			FRMES[hook].caller.innerHTML = FRMES[hook].innerSTORE;
			FRMES[hook].caller.className = FRMES[hook].oldClass;
			FRMES[hook].caller.style.border = (rec_type == 'ERROR')? "1px solid #F00":"none";
		}catch(e){}
	}

	if(rec_type == 'ERROR'){
		// WHEN THIS THROWS... THE ERROR FIELDS IF ANY SHOULD ALSO HIGHLIGHT...
		displayError(0,rec_id);
		return;
	}else{
		displayError(100,"");
	}

	// alert(tmpl);
	// alert(rM);

	if(state == 'deleted'){
		//document.getElementById(rec_type+"-"+rec_id).style.display = "none";
		//Delete Record:child,options,0,N1,DELETE
		//alert("Delete Record - "+split[1]+"-"+split[2]+"-"+split[3]+"-ROW");
		//alert("child-"+rec_type+"-"+parent_id+"-"+rec_id+"-ROW");
		var childTable = document.getElementById("child-"+rec_type+"-"+parent_id+"-"+rec_id+"-ROW");
		childTable.parentNode.removeChild(childTable);
		return;
	}

	if(typeof(autos) != 'undefined'){// ---------------- THIS MAY NEED A CLONE FUNCTION ---------------------------------------
		for(x in autos){
			AUTOS[x] = autos[x];
		}
	}

	//alert(rM);
	//alert(rec_type);
	//alert(state);

	stateMap = stateMaps[rec_type][state];

	// IF A TEMPLATE HAS BEEN RETURNED... CACHE IT...
	// I ALSO NEED A MAP... WHICH TRANSLATES THE DATA KEYS TO THE TEMPLATE WIDGETS...

	if(typeof(RECORD_MAPS[rec_type]) == 'undefined'){
		RECORD_MAPS[rec_type] = rM;
	}else{
		rM = RECORD_MAPS[rec_type];
	}

	if(typeof(TEMPLATES[rec_type]) == 'undefined' || typeof(TEMPLATES[rec_type][stateMap.tmpl]) == 'undefined'){
		if(typeof(TEMPLATES[rec_type]) == 'undefined'){
			TEMPLATES[rec_type] = [];
		}
		TEMPLATES[rec_type][stateMap.tmpl] = tmpl;
	}else{
		tmpl = TEMPLATES[rec_type][stateMap.tmpl];
	}

	// alert(stateMap.tmpl);
	// alert(rec_id);
	// alert(rec_type.substr(0,6));

	if(rec_id == 'N' && rec_type != 'to_do'){
		if(typeof(NEW_RECORD_COUNTERS[rec_type]) == 'undefined'){NEW_RECORD_COUNTERS[rec_type] = 0;}
		NEW_RECORD_COUNTERS[rec_type]++;
		rec_child_index = rec_id + NEW_RECORD_COUNTERS[rec_type];
		rec_child_name_index = rec_child_index;
	}else{
		rec_child_index = rec_id;
		rec_child_name_index = 0;
	}

	// Still need form stamps...

	rM.recordType = {"0":"record_type","hidden":{"FN":true}};
	rM.record_id = {"0":"record_id","hidden":{"FN":true}};
	rM.parent_id = {"0":"parent_id","hidden":{"FN":true}};
	rM.form_stamp = {"0":"form_stamp","hidden":{}};
	rM.CANCL = {"0":"CANCEL","eh":{"tag":"A","event":"onclick","func":"close_record(this)","text":"Cancel"}};
	rM.SAVE = {"0":"SAVE","eh":{"tag":"A","event":"onclick","func":"save_record(this)","text":"Save"}};
	rM.DELETE = {"0":"DELETE","eh":{"tag":"A","event":"onclick","func":"delete_record(this)","text":"","className":"delRec","title":"delete"}};

	// THE PLAIN TEXT IS NOT REFRESHING AFTER AN EDIT/SAVE

	arr['record_type'] = rec_type;
	arr['parent_id'] = parent_id;
	arr['record_id'] = rec_id;
	arr['form_stamp'] = '';
	arr['CANCEL'] = rec_id;
	arr['SAVE'] = rec_id;

	// alert(load_type);

	if(load_type == 1){ // this is a call to fill the record interface...
		//alert("load_type="+load_type);
		
		// I want to know all the element ids... from there they all get plugged with new values...
		
		// alert(arr);
		var activeLang = LANGS['active'][0];
		var activeServ = LANGS['active'][1];
		var lang_serv_key = "lang-"+activeLang+"-"+activeServ;
		
		// alert(arr[lang_serv_key+'-1']);
		// alert("rec_type="+record_index+" rec_id="+rec_id);
		
		if(typeof(RECORDS[record_index][rec_id]) == 'undefined'){
			RECORDS[record_index][rec_id] = [];
			RECORDS[record_index][rec_id][lang_serv_key] = [];
		}

		var string = '';
		for(x in RECORDS[record_index][0].cam){ // THIS NEED TO EXPAND TO LOAD CRUMBS, AND WYSIWYG, AND PERMISSIONS, AND EVERYTHING...
			string = arr[lang_serv_key+'-'+x];
			document.getElementById('in-'+x).value = string;
			RECORDS[record_index][rec_id][lang_serv_key][x] = string;
		}

		return;
	}

	var str = tmpl;
	var objCache=[];

	c = 0;
	for(x in rM){
		//alert(x+" = "+rM[x]);
		z = 0;
		for(y in rM[x]){

			if(z == 1){

				var objD = document.createElement("DIV");
				var obj = null;
				var field = rM[x][y];
				var field_name = rM[x][0];
				var att_id = rec_type+"-"+parent_id+"-"+rec_id+"-"+field_name;
				//var att_name = "child-"+rec_type+"["+field_name+"|"+rec_id+"]";
				//var att_name = rec_type+"["+rec_id+"]["+field_name+"|0]";
				var att_name = rec_type+"["+field_name+"|"+rec_child_name_index+"]";
				var val = (state == 'new' && !rM[x][y].FN)? null: arr[field_name]; // it might be better to set defaults for new records...
				var addLabel = false;
				var skipAppend = false;

				// alert(y+" = "+rM[x][y] +" field_name="+field_name);

				if(y == 'input'){
					//alert(field + " = " + field_name + " = " + x);
					obj = fill_input(val,stateMap);
					addLabel = true;
				}else if(y == 'textarea'){
					obj = fill_textarea(val,stateMap);
					addLabel = true;
				}else if(y == 'select'){
					//alert("OBJECT TO STRING");
					//alert(y+" = "+ x +" = "+field_name+" select_index="+field.select_index);
					//alert(objToString(field));
					//att_name = "child-"+rec_type+"[S|"+field_name+"|"+rec_id+"]";
					//att_name = rec_type+"["+rec_id+"][S|"+field_name+"|0]";
					att_name = rec_type+"[S|"+field_name+"|"+rec_child_name_index+"]";
					obj = fill_select(val,field,stateMap,false);
					addLabel = true;
				}else if(y == 'boolean'){
					obj = fill_boolean(val,stateMap);
					addLabel = true;
				}else if(y == 'static'){
					obj = fill_static(val,stateMap);
					addLabel = true;
				}else if(y == 'hidden'){
					if(field_name == 'parent_id'){
						att_name = rec_type+"["+field_name+"]";
					}
					obj = fill_hidden(val,rec_id,stateMap);
				}else if(y == 'eh'){
					var att_id = rec_type+"-"+parent_id+"-"+rec_child_index+"-"+field_name;
					//var att_name = "child-"+rec_type+"["+parent_id+"]["+field_name+"|"+rec_id+"]";
					//var att_name = rec_type+"["+parent_id+"]["+rec_id+"]["+field_name+"|0]";
					var att_name = rec_type+"["+parent_id+"]["+field_name+"|"+rec_child_name_index+"]";
					obj = fill_eh(val,rM[x]);
				}else if(y == 'image_selector'){
					//alert("HOWDY"+field_name);
					str = str.replace(/{{{img_instance_id}}}/g,rec_child_name_index);
					continue;
				}else if(y == 'date_selector'){
					// alert("UNSUPPORTED DATE SELECTOR FOUND");
					var label = document.createElement("SPAN");
					label.className = (y == 'boolean')? "ckchktxt":"cklabel";
					label.innerHTML = x;
					objD.appendChild(label);
					str = str.replace('{{{'+field_name+'}}}',objD.innerHTML);

					// <select class="" name="deptDate|807099149[month]" id="deptDate|807099149[month]">
					// <select name="child-options[S|deptDate|N1]" id="child-options-0-N-deptDate">
				
					var objD = document.createElement("DIV");
					att_name = field_name+"|"+rec_child_name_index+"[day]"; //	<select class="" name="deptDate|1329460218[day]" id="deptDate|1329460218[day]">
					obj = fill_select(val,field,stateMap,"d");
					obj.setAttribute("id",att_id);
					obj.setAttribute("name",att_name);
					objD.appendChild(obj);
					str = str.replace('{{{'+field_name+'-d}}}',objD.innerHTML);

					var objD = document.createElement("DIV");
					att_name = field_name+"|"+rec_child_name_index+"[month]";
					obj = fill_select(val,field,stateMap,"m");
					obj.setAttribute("id",att_id);
					obj.setAttribute("name",att_name);
					objD.appendChild(obj);
					str = str.replace('{{{'+field_name+'-m}}}',objD.innerHTML);

					var objD = document.createElement("DIV");
					att_name = field_name+"|"+rec_child_name_index+"[year]";
					obj = fill_select(val,field,stateMap,"y");
					obj.setAttribute("id",att_id);
					obj.setAttribute("name",att_name);
					objD.appendChild(obj);
					str = str.replace('{{{'+field_name+'-y}}}',objD.innerHTML);
					skipAppend = true;
				}else{
					alert("UNKNOWN DATA TYPE:"+y+" = "+rM[x][y] +" - " +field_name);
					continue;
				}

				if(addLabel && stateMap.labels){
					var label = document.createElement("SPAN");
					label.className = (y == 'boolean')? "ckchktxt":"cklabel";
					label.innerHTML = x;
					objD.appendChild(label);
				}
				
				if(!skipAppend){
					obj.setAttribute("id",att_id);
					obj.setAttribute("name",att_name);
					// alert(c+" = "+obj.staticFill);
					objCache[c] = obj.staticFill;
					objD.appendChild(obj);
					// if(field_name == 'DELETE'){
					//  alert(objD.innerHTML);
					// }
					// alert(field_name);
					str = str.replace('{{{'+field_name+'}}}',objD.innerHTML);
				}
			}
			z++;
		}
		c++;
	}

	str = str.replace(/{{{id}}}/gi,rec_child_index);
	str = str.replace(/{{{parent_record_id}}}/gi,parent_id);

	// alert("rec_id="+rec_id);
	// alert("state="+state);
	
	// edits are not updating...
	// new records are not closing...

	if(state == 'savedNew'){
		// alert("savedNew= "+rec_type+"-"+parent_id+"-"+rec_child_index+"-CANCEL");
		// to_do-0-107-CANCEL
		var addBlock = append_child_record(parent_id,rec_type,rec_id);
		var lastNewId = NEW_RECORD_COUNTERS[rec_type];// --------------------------------------- THIS WILL CAUSE PROBLEMS WHEN MULTIPLE ITEMS ARE OPEN...
		var to_do = document.getElementById(rec_type+"-"+parent_id+"-N-CANCEL");
		close_record(to_do);
	}else if(state == 'savedEdit'){
		// alert("savedEdit= "+rec_type+"-"+parent_id+"-"+rec_child_index+"-CANCEL");
		var to_do = document.getElementById(rec_type+"-"+parent_id+"-"+rec_child_index+"-CANCEL");
		close_record(to_do);
		// alert('child-'+rec_type+'-'+parent_id+'-'+rec_id+'-ROW');
		var addBlock = document.getElementById('child-'+rec_type+'-'+parent_id+'-'+rec_id+'-ROW');
		addBlock.childNodes[2].childNodes[0].childNodes[0].innerHTML = objCache[1];
		addBlock.childNodes[3].innerHTML = objCache[0];
		return;
	}else if(state == 'edit'){
		var addBlock = document.getElementById(rec_type+'-'+rec_id+'-ADD');
		if(rec_type == 'to_do' && rec_id != 'N'){
			block = addBlock.parentNode;
			block.childNodes[2].style.display = "none";
			block.childNodes[3].style.display = "none";
			block.childNodes[4].style.display = "none";
			block.childNodes[5].style.display = "none";
		}
	}else if(state == 'new'){ // this appends a new record to the bottom of the list
		// alert(rec_type+'-Table-'+parent_id);
		var block = document.getElementById(rec_type+'-Table-'+parent_id);
		var l = block.childNodes.length;
		if(rec_type == 'to_do'){
			block.childNodes[(l-2)].style.display = 'none';
			var addBlock = block.childNodes[(l-1)];
		}else{
			var addBlock = document.createElement("DIV");
			addBlock.setAttribute("id",rec_type+"-"+parent_id+"-"+rec_child_index+"-ROW");
			block.appendChild(addBlock);
		}
	}else{
		alert("COULD NOT CATCH STATE");
	}


	addBlock.innerHTML = str;
	addBlock.style.display = 'block';
	if(rec_type == 'to_do'){
		addBlock.childNodes[1].focus();
	}
	//alert("FIN");
	// make a makeshift map...
}

function append_child_record(parent_id,rec_type,rec_id){ // this loads a placeholder for an editing template...
	var todoTable = document.getElementById(rec_type+'-Table-'+parent_id);
	var l = todoTable.childNodes.length;
	var addBlock = document.createElement("DIV");
	addBlock.className = "toDoRow";
	addBlock.id = "child-"+rec_type+"-"+parent_id+"-"+rec_id+"-ROW";
	addBlock.onmouseover = over_to_do_item;
	addBlock.onmouseout = out_to_do_item;
	var toDoBlock = todoTable.childNodes[(l-1)];
	toDoBlock.childNodes[1].value = "";
	toDoBlock.childNodes[(toDoBlock.childNodes.length-1)].className = "";
	todoTable.insertBefore(addBlock,todoTable.childNodes[(l-2)]);
	return addBlock;
}

function close_record(obj){ // THIS IS ATTACHED TO THE ANCHOR... NOT A GOOD IDEA...
	var split = obj.id.split("-");
	var rec_type = split[0];
	var parent_id = split[1];
	var rec_id = split[2];
	var block = obj.parentNode.parentNode.parentNode;
	var block = document.getElementById('child-'+rec_type+'-'+parent_id+'-'+rec_id+'-ROW');

	var l = block.childNodes.length;
	if(rec_id == 'N'){
		block.style.display = 'block';
		var addItemBlock = document.getElementById('to_do-'+parent_id+'-N-ADD');
		addItemBlock.style.display = 'none';
	}else{
		block.childNodes[(l-1)].childNodes[1].value = '';
		block.childNodes[(l-1)].style.display = 'none';
		block.childNodes[(l-2)].style.display = 'block';
		block.childNodes[(l-3)].style.display = 'block';
		block.childNodes[(l-4)].style.display = 'block';
		block.childNodes[(l-5)].style.display = 'block';
	}
	return false;
}

function delete_record(obj){ // the delete is wrapped in a span
	var split = obj.parentNode.id.split("-");
	//alert("Delete Record:" + split[3]);
	//alert("Delete Record (Parent Node):" + obj.parentNode.id);
	//alert(RECORD_INDEX);
	if(split[3].substr(0,1) == "N" || split[3].substr(0,1) == ""){
		//Delete Record:child,options,0,N1,DELETE
		//alert("Delete Record - "+split[1]+"-"+split[2]+"-"+split[3]+"-ROW");
		var childTable = document.getElementById("child-"+split[1]+"-"+split[2]+"-"+split[3]+"-ROW");
		childTable.parentNode.removeChild(childTable);
		return;
	}
	var command = "Del|"+split[2]+"|"+split[0]+"|"+split[1]+"|D|"+RECORD_INDEX;
	var x = requestController(command,0,false,false);
	var obj = obj.parentNode;
	FRMES[x].innerSTORE = obj.innerHTML;
	FRMES[x].caller = obj;
	FRMES[x].oldClass = obj.className;
	obj.className = obj.className+"X";
	obj.blur();
}

function save_record(obj){ // THESE NEED TO CALL ITEMS BASED ON IDS... NOT BASED ON LOCATION...
	var block = obj.parentNode.parentNode;
	
	//alert(block.id);
	
	var sect = 'erp';
	var pane = 'to_do_lists-project_to_do_lists';
	var textarea = block.childNodes[1];
	var select = block.childNodes[3];
	var checkbox = block.childNodes[4];
	var record_id = block.childNodes[5];
	var record_type = block.childNodes[6];
	var parent_id = block.childNodes[7];

	//alert(parent_id.id);
	//alert(block.innerHTML);

	var l = block.childNodes.length;
	var linkBar = block.childNodes[(l-1)];
	if(textarea.value.length < 6){textarea.focus();return;}
	linkBar.className = "add_item_send_active";
	element_whitelist=[];
	element_whitelist[0] = textarea.id;
	element_whitelist[1] = select.id;
	element_whitelist[2] = checkbox.id;
	element_whitelist[3] = record_id.id;
	element_whitelist[4] = record_type.id;
	element_whitelist[5] = parent_id.id;
	savePane(sect,pane,'RECORD',element_whitelist);
	return false;
}

function fill_eh(val,map){
	//alert(objToString(map.eh));
	var obj = document.createElement(map.eh.tag);
	var text = document.createTextNode(map.eh.text);
	if(map.eh.func && map.eh.event){
		obj.setAttribute(map.eh.event,map.eh.func);
	}
	obj.appendChild(text);

	if(map.eh.className){
		var wrapSpan = document.createElement("SPAN");
		wrapSpan.className = map.eh.className;
		wrapSpan.title = map.eh.title;
		wrapSpan.appendChild(obj);
		return wrapSpan;
	}
	return obj;
}

function fill_input(val,stateMap){
	if(stateMap.plainText){
		var span = document.createElement("SPAN");
		var text = document.createTextNode(val);
		span.appendChild(text);
		return span;
	}
	var input = document.createElement("INPUT");
	input.value = (val !== null)?val:'';
	input.className = "ckinp";
	return input;
}

function fill_textarea(val,state){
	if(stateMap.plainText){
		var span = document.createElement("SPAN");
		var text = document.createTextNode(val);
		span.appendChild(text);
		span.staticFill = val;
		return span;
	}
	var textarea = document.createElement("TEXTAREA");
	var text = document.createTextNode(val);
	textarea.appendChild(text);
	textarea.staticFill = val;
	return textarea;
}

// THERE IS A WRITE SELECT AND A FILL SELECT OPTION... THEY NEED TO MERGE OVER TIME... SCRIPT_LISTS vs AUTOS

function fill_select(val,field,state,date_multi_key){

	//alert("select index="+index);
	//alert(AUTOS);
	if(typeof(AUTOS[field.select_index]) != 'undefined'){
		var l = AUTOS[field.select_index].length;
		var select = document.createElement("SELECT");
		if(typeof(field.is_multi) != 'undefined' && field.is_multi > 1){
			select.setAttribute("multiple","multiple");
			select.setAttribute("size",field.is_multi);
		}
		var z=0;

		if(!date_multi_key){
			for(x in AUTOS[field.select_index]){
				var opt = document.createElement("OPTION");
				var selval = (x.substr(0,1) == 0)? parseInt(x,10): x;
				select.options[z++] = new Option(AUTOS[field.select_index][x].toString(),selval);
			}
		}else if(typeof(AUTOS[field.select_index][date_multi_key]) != 'undefined'){
			for(x in AUTOS[field.select_index][date_multi_key]){
				var opt = document.createElement("OPTION");
				var selval = (x.substr(0,1) == 0)? parseInt(x,10): x;
				select.options[z++] = new Option(AUTOS[field.select_index][date_multi_key][x].toString(),selval);
			}		
		}
		//AUTOS[field.select_index] = select.cloneNode(true);
	}else{
		//var select = AUTOS[field.select_index].cloneNode(true);
	}

	//alert("FIN val="+val);

	if(val){
		var l = select.options.length;
		for(var x=0;x<l;x++){
			if(select.options[x].value == val){
				select.selectedIndex = x;
				select.options[x].setAttribute("selected","selected");
				select.staticFill = select.options[x].text;
				break;
			}
		}
	}
	if(stateMap.plainText){
		var span = document.createElement("SPAN");
		var val = select.options[select.selectedIndex].text;
		var text = document.createTextNode(val);
		span.appendChild(text);
		span.staticFill = val;
		return span;
	}
	return select;
}

function fill_boolean(val,state){
	if(stateMap.plainText){
		var span = document.createElement("SPAN");
		var text = document.createTextNode(val);
		span.appendChild(text);
		return span;
	}
	var checkbox = document.createElement("INPUT");
	checkbox.setAttribute("type","checkbox");
	if(val > 0){
		checkbox.setAttribute("checked","checked");
	}
	return checkbox;
}

function fill_hidden(val){
	var input = document.createElement("INPUT");
	input.setAttribute("type","hidden");
	input.value = val;
	return input;
}

function fill_static(val){
	var input = document.createElement("DIV");
	input.innerHTML = val;
	return input;
}

function validate_widget(obj,type){
	if(type == 1){ // number
		var val = obj.value;
		var parse = parseFloat(val);
		obj.style.backgroundColor = (val.length && parse != val)? "#F00":null;
	}
}

function adjustTextarea(textarea, collapsed) {
	var lines = textarea.value.split("\n");
	var count = lines.length;
	var l = lines.length;
	for(x=1;x < l;x++){
		count += parseInt(lines[x].length / 70);
	}
	var rows = parseInt(collapsed / 20);
	if (count > rows) {textarea.style.height = (collapsed * 2) + 'px';}
	if (count <= rows) {textarea.style.height = collapsed + 'px';}
}

function fileStat(mode,count,filesize){
	if(mode == 'FIN'){
		alert('FILE FINISHED UPLOADING=' + mode);
	}else if(mode == 'FILESTAT'){
		//alert("THIS IS A REPORT FROM THE FILE CHECKER... filesize="+filesize);
		var listSize = document.getElementById('listSize'+count);
		listSize.innerHTML = filesize;
		var command = "FILECHECK="+count;
		clearController(command);
		//setTimeout("xhReq=new XMLHttpRequest();xhReq.open('GET','index.php?trans="+command+"',false);xhReq.send(null);alert(xhReq.responseText)",2000);
		setTimeout("requestController('"+command+"')",2000);
	}
	return false;
}

function onFileRemove(obj){
	var par = obj.parentNode;
	var keyArr = par.id.split("");
	var ind = keyArr[(keyArr.length-1)];
	var upInp = document.getElementById("uploader"+ind);
	upInp.parentNode.removeChild(upInp);
	par.parentNode.removeChild(par);
}

function onFileSelect(sect,pane,mode,selectorObj,fileList,fileInputs){

	var fileNo = FILES_C;
	var list = document.getElementById(fileList);
	var div = document.createElement("DIV");
	div.setAttribute('id','listFile'+fileNo);
	div.setAttribute('class','listFileRow');
	var arr = selectorObj.value.split(".");
	var ext = arr[arr.length-1];
	var mime = MIMES['default'];
	var l = MIMES['mimes'].length;
	for(x=0;x<l;x++){
		if(MIMES['mimes'][x] == ext){
			mime = MIMES['mimes'][x];
			x = l;
		}
	}
	div.setAttribute('style','background:url('+MIMES["path"]+'32/'+mime+'.png) no-repeat;');
	list.appendChild(div);
	var a = document.createElement("A");
	a.setAttribute('onclick',"onFileRemove(this);");
	var span = document.createElement("span");
	div.appendChild(span);
	div.appendChild(a);
	span.innerHTML = selectorObj.value;
	a.innerHTML = 'remove';

	var div = document.createElement("DIV");
	div.setAttribute('id','listSize'+fileNo);
	div.setAttribute('class','listSizeRow');
	list.appendChild(div);	
	
	selectorObj.setAttribute('style','position:absolute;left:-500px;top:0px;');

	FILES_C++;

	// create a new file uploader...
	var holder = document.getElementById(fileInputs);
	var inp = document.createElement("INPUT");	
	inp.setAttribute('name','uploader['+FILES_C+']');
	inp.setAttribute('type','file');
	inp.setAttribute('id','uploader'+FILES_C);
	inp.setAttribute('onchange',"onFileSelect('erp','dashboard-message','FILE',this,'fileList','fileInputs')");
	holder.appendChild(inp);	

	//setTimeout("savePane('"+sect+"','"+pane+"','"+mode+"')",500);
	//setTimeout("requestController('FILECHECK="+FILES_C+"')",2000);

	return false;
}

function keyup(obj){
	var ele,ind,spl,key,command,key_ind;
	key = obj.value.toUpperCase();
	key_ind = obj.parentNode.childNodes[0];

	if(key.length < 2){
		// check for an open select and close it...
		if(AUTOS.key && AUTOS.ind){
			//alert(AUTOS.key);
			AUTOS[AUTOS.ind].div.style.display = 'none';
			AUTOS.key = null;
			AUTOS.ind = null;
		}		
	}else if(key.length==2){
		ele = key_ind.name;
		spl = ele.split("|");		
		ind = spl[0];
		if(!AUTOS[ind]){AUTOS[ind]=[];}
		//if(!AUTOS[ind][key]){AUTOS[ind][key]=[];}		
		if(AUTOS[ind][key]){
			AUTOS.key = key;
			AUTOS.ind = ind;
			write_select();
			AUTOS[ind].div.style.display = 'block';
		}else{
			AUTOS[ind].obj = obj;
			// send a request for the element...
			// do not set this until we have it returned...
			command = 'dds|'+ind+"|"+key;
			requestController(command);
		}
	}else if(key.length > 2){
		// we cycle through the indexes until we find matches...
		key = key.toUpperCase();
		ele = key_ind.name;
		spl = ele.split("|");		
		ind = spl[0];	
		ikey = key.substring(0,2);
		lc = key.length;
		//alert(ikey); // you always referencing the master array which could lead to slow downs...
		
		master = AUTOS[ind][ikey];
		if(!AUTOS[ind][key]){
			AUTOS[ind][key]=[];
		}
		for(x in master){
			//alert(objToString(master[x]));
			if(master[x].substr(0,lc).toUpperCase() == key){
				AUTOS[ind][key][x] = master[x];
			}
		}

		AUTOS.key = key;
		write_select();

		//alert('new aray');
		//alert(AUTOS[ind][key]);
		
	}
}

// you obviously had this figured out at one point... use it...

function requestReceiver(command,result){
	var hook = clearController(command);
	var c = command.split("|");
	if(c[0] == "dds"){
		fill_auto(c[1],c[2],result);
	}
 	return;
}


// this is trggerd by the select

function ddsClick(){
	
	// grab the value...
	// transfer it to the hidden and visible input
	var x = this.parentNode.ddsInput;
	x.isfocused = false;
 	x.value = AUTOS[AUTOS.ind][AUTOS.key][this.value];
	x.parentNode.childNodes[0].value = this.value;
	// hide the object for later
	this.parentNode.style.display = 'none';
	x.focus();
}

// this fills the div with the select information

function write_select(){

	// you will probably get faster performance by first hiding the div and then redisplaying it...
	val = AUTOS[AUTOS.ind][AUTOS.key];
	sel = AUTOS[AUTOS.ind].div.childNodes[0];
	// alert(objToString(sel));
	// AUTOS[AUTOS.ind].div.style.display = 'block';
	sel.options.length = 0;
	var c = 0;
	for(x in val){
		sel.options[c++]=new Option(val[x],x);
		//opt = document.createElement("OPTION");
		//opt.value = val[1][x]; 
		//opt.text = val[0][x];
		//sel.options.add(opt,x);
	}
	AUTOS[AUTOS.ind].div.style.display = (c)? 'block':'none';
}

function checkautofillclose(){
	if(!this.isfocused){
		AUTOS[AUTOS.ind].div.style.display = 'none';
	}
}

function fill_auto(ind,key,val){
	if(AUTOS[ind].div && AUTOS[ind][key]){
		//alert('reusing key: this should never happen... but it does...');
		AUTOS.key = key;
		AUTOS.ind = ind;
		write_select();
	}else{
		var obj = AUTOS[ind].obj;
		Offx = getOffset(obj,'left') - 2;
		Offy = getOffset(obj,'top') + 18;
		obj.onblur = function(){this.isfocused = false;setTimeout("checkautofillclose()",500);}
		obj.onmousedown = function(){this.isfocused = true;}
		obj.key = key;
		obj.ind = ind;
		
		w = obj.offsetWidth;
		if(!AUTOS[ind].div){ // you can probably initialize this when the page is sent rather than with javascript...
			div = document.createElement("DIV");	
			//div.setAttribute('style','position:absolute;top:'+Offy+'px;left:'+Offx+'px;width:'+w+'px;');
			div.style.position = "absolute";
			div.style.top = Offy+'px';
			div.style.left = Offx+'px';
			document.body.appendChild(div);
			sel = document.createElement("SELECT");
			sel.setAttribute('class','AdminSelectMult');
			sel.setAttribute('size','8');
			sel.onclick = ddsClick;
			div.appendChild(sel);			
			div.ddsInput = AUTOS[ind].obj;
			AUTOS[ind].div = div;
		}
		AUTOS.key = key;
		AUTOS.ind = ind;
		AUTOS[ind][key] = val;
		write_select();
	}
	return;
	//	newselect.setAttribute('class','AdminSelectMult');
	//	newselect.setAttribute('size','8');
	//	newselect.setAttribute('id','grabass');
	//	newselect.setAttribute('multiple','multiple');	
	//	sel = document.body.appendChild(newselect);
	//	sel = document.getElementById('grabass');
	//	alert(AUTOS[ind][key]['values']);
	//	var t = AUTOS[ind][key]['values'];
	//	var l = t[0].length; 
	//	for(var x=0; x < l; x++){
	//		sel.options[y]=new Option(t[1][x],t[0][x]);
	//		opt = document.createElement("OPTION");
	//		opt.value = t[1][x]; 
	//		opt.text = t[0][x];
	//		alert("value:"+ t[0][x]+"   Text:"+t[1][x]);
	//		newselect.options.add(opt,x);
	//	}
	//	obj.innerHTML = AUTOS[ind][key]['values'];
	//	alert(AUTOS[ind][key]['values']);
}

// This is an unmodified function taken from the drop down menu script
function getOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

function dofocus(obj){
	obj.className=obj.className+'B';
	if(obj.className == 'cknuminpCB'){
		BLUR_CACHE[obj.name] = obj.value;
		obj.value = '';
	}
}

function doblur(obj){
	c = obj.className;
	if(obj.className == 'f_errB'){
		obj.className=c.substr(0,(c.length-1))+'C';
	}else{
		obj.className=c.substr(0,(c.length-1));
		if(obj.className == 'cknuminpC' && obj.value == ''){
			obj.value = BLUR_CACHE[obj.name];
		}
	}
}

function initAnchor(){
	var hrf = window.location.toString();
	var ind = hrf.indexOf("#");
	if(ind != -1){
		//location.hash = hrf.substring((ind+1));
	}
}

// you need to hide the help buttons and such for open and closed states

function slideCollapsablePane(dir){
	slideController.count += (dir)? -10:10;
	if(slideController.count < 0){slideController.count = 0;}
	slideController.pane.parentNode.childNodes[1].style.height= slideController.count+'px';
	if(dir && slideController.count <= slideController.MaxCount){
		slideController.pane.parentNode.childNodes[1].style.display='none';
		clearInterval(slideController.timer);
	}else if(!dir && slideController.count >= slideController.MaxCount){
		clearInterval(slideController.timer);
	}
}

function collapsePane(obj){
	if(obj.parentNode.childNodes[1].style.display=='none'){
	obj.parentNode.childNodes[1].style.display='';
	obj.parentNode.childNodes[2].value = 0;
		if(enableSlide){
			obj.parentNode.childNodes[1].style.height='0px';
			obj.parentNode.childNodes[1].style.overflow='hidden';
			slideController.count = 0;
			slideController.MaxCount = 100;
			slideController.pane = obj;
			slideController.timer = setInterval('slideCollapsablePane(0);',1);
		}
	}else{
		obj.parentNode.childNodes[2].value = 1;
		if(enableSlide){
			obj.parentNode.childNodes[1].style.overflow='hidden';
			slideController.count = 100;
			slideController.MaxCount = 0;
			slideController.pane = obj;
			slideController.timer = setInterval('slideCollapsablePane(1);',5);
		}else{
			obj.parentNode.childNodes[1].style.display='none';
		}
	}	
}

// When the arrows are used to populate the calendar via javascript you need to have a redirect in place.
// otherwise you'll be using the same static get str that you had in place when the page loaded.

function redirectAdminCrumb(page,mode){
	var page_only_str = (undefined!==window.page_only)? '&page_only=1': '';
	if(page=='mycal'){
		if(mode=='month'){
			document.location.href = 'index.php?page=mycal'+page_only_str;
		}else if(mode=='day'){
			var year = document.getElementById('year').value;
			var month = document.getElementById('month').value;
			var day = document.getElementById('day').value;
			//alert('index.php?page=mycal&year='+year+'&month='+month +'&day='+day+page_only_str);
			document.location.href = 'index.php?page=mycal&year='+year+'&month='+month +'&day='+day+page_only_str;
		}		
	}
	return;
}

function iNitAdmin(){
	PANES.var_sect = document.getElementById('var_sect').value; // sect and panes are one and the same...
	PANES.i = PANES.var_sect;
	PANES['containers']=[];
	PANES['containers'][0] = document.getElementById('var_wrap');
	PANES[PANES.i] = PANES['containers'][0].childNodes[0];
}

function iNitFrame(val,doc){
	PANES.var_sect = val; // sect and panes are one and the same...
	PANES.i = PANES.var_sect;
	PANES['containers']=[];
	PANES['containers'][0] = doc;
	PANES[PANES.i] = PANES['containers'][0].childNodes[0];
}

function setOpacity(obj,level){
	if (obj.filters){
		obj.filters.alpha.opacity=level;
	}else if (obj.style.MozOpacity){
		obj.style.MozOpacity=level/101;
	}else{
		obj.style.opacity=level/100;	
	}
}

function fadeStage(stage_id,dir){
	var dir = parseInt(dir);
	var level = STAGES[stage_id].stageOpacity += (dir)? 10: -10;
	setOpacity(STAGES[stage_id],level);
	if((level > 0 && !dir) || (level < 100 && dir)){
		setTimeout("fadeStage('"+stage_id+"',"+dir+")",30);
	}
}

function callTransition(caller,transition,cat_id,rec_type,rec_id){

	//alert("cat_id="+cat_id+" rec_id="+rec_id+" rec_type="+rec_type+" transition="+transition);
	if(typeof(RECORDS) == 'undefined'){
		RECORDS=[];
	}

	if(typeof(RECORDS[rec_type]) == 'undefined'){
		RECORDS[rec_type]=[];
	}

	var is_search = (rec_id == 918 && rec_type == 54)? 1: 0;

	if(rec_type == RECORD_INDEX && rec_id == RECORD_ID && !is_search){
		//alert(rec_type +" == "+ RECORD_INDEX +" && "+ rec_id +" == "+ RECORD_ID);
		top.scrollTo(0,0);
		return false;
	}

	var stage_id = 'INC-'+RECORD_INDEX+'-'+RECORD_ID;

	STAGES[stage_id] = document.getElementById(stage_id);
	STAGES[stage_id].transition = transition;

	if(transition == 2){ // fade
		STAGES[stage_id].stageOpacity = 100;
		STAGES[stage_id].style.display = 'block';
		fadeStage(stage_id,0);
	}

	var search_string = '';
	if(is_search){
		search_string = escape(document.getElementById('search').value);
	}

	var fs_panel_str = '';
	var flag = '';
	for(var x = 1;x < 13; x++){
		flag = (typeof(FS_PANEL[x]) != 'undefined')? '1': '0';
		fs_panel_str += flag;
		if(flag == '1' && typeof(CMS.pLD[x]) != 'undefined'){
			FS_PANEL[x] = '<div id="FSP-'+x+'">'+document.getElementById('FSP-'+x).innerHTML+'</div>';
		}
	}
	
	if(rec_type == 49){
		caller.parentNode.parentNode.parentNode.parentNode.style.backgroundColor = '';
		if(typeof(ROWSC[CMS.rowMapKey]) != 'undefined'){
			try{
				var rowObj = ROWSC[CMS.rowMapKey];
				var rRows = ROWS[rowObj.pane][rowObj.rowMapKey][rowObj.key]
				for(x in rRows){if(rRows[x] == rec_id){RCLASS[rowObj.pane][rowObj.rowMapKey][rowObj.key][x] = 1;break;}}
			}catch(e){alert('did not set RCLASS = '+e);}
		}
	}

	//alert(objToString(FS_PANEL));

	var page_only = (top.location.href.indexOf('page_only=1') > 0)? 1: 0;
	var command = 'rec|'+rec_type+"|"+rec_id+"|"+cat_id+"|A|"+RECORD_INDEX+"|"+RECORD_ID+'|'+page_only+'|'+search_string+'|'+fs_panel_str;
	var loc_key = 'RECORDS-'+rec_type+'-'+rec_id;
	var loadStore = 0;

	localStorage.clear();

	if(CMS.use_local && localStorage.getItem(loc_key) != null){
		var arr = JSON.parse(localStorage.getItem(loc_key));
		if(CMS.timestamp < arr[0][12]){
			loadStore = 1;
		}
	}else if(typeof(RECORDS[rec_type][rec_id]) != 'undefined'){
		var arr = RECORDS[rec_type][rec_id];
		loadStore = 1;
		//alert("rec_type="+rec_type+" rec_id="+rec_id);
	}

	if(loadStore){
		arr[0][0] = RECORD_INDEX;
		arr[0][1] = RECORD_ID;
		arr[0][2] = rec_type;
		arr[0][3] = rec_id;
		arr[1][stage_id] = arr[1][arr[0][6]];
		if(stage_id != arr[0][6]){
			delete arr[1][arr[0][6]];
		}
		delete arr[3][arr[0][6]];
		arr[3][stage_id] = 'INC-' + rec_type + '-' + rec_id;
		arr[0][6] = stage_id;
		loadTransition(command,arr);
	}else{
		var sendSaller = (1==2)? caller: 0;
		//alert("command="+command);
		var RC = requestController(command,null,false,false,false,sendSaller);
	}

	caller.blur();// this causes the object class to disappear...
	return false;
}

function setSidePanelHighlight(x,RECORD_ID,RECORD_INDEX){
	if(x==2){
		return;
	}
	var key = (x==8)? 'P'+x+'-'+RECORD_INDEX+'-'+RECORD_ID:'P'+x+'-'+RECORD_ID;
	//alert(key);
	var a = document.getElementById(key);
	if(CMS.panelHighlightKey){
		var b = document.getElementById(CMS.panelHighlightKey);
		if(b){
			b.className = "FSli1";
		}
	}
	if(a){
		a.className = "FSliA1";
		CMS.panelHighlightKey = key;
		a.parentNode.style.display = 'block';
	}
	// alert(a.className);
	// alert(key);
}

// When the pane loads... I store the section in the container... and I associate the container keys with the pane loaded...
// When it's a second time... the check is made for the container piece...
// Requests for containers DO NOT have to be sent seperately with each page request...
// rec|54|905|0|A|54|904|1| 

function loadTransition(command,arr){

	clearController(command);
	var caller_record_index = arr[0][0];
	var caller_record_id = arr[0][1];

	RECORD_INDEX = arr[0][2];
	RECORD_ID = arr[0][3];
	RECORDS[RECORD_INDEX][RECORD_ID] = arr;

	try{
		top.document.title = arr[0][7];
	}catch(e){
		alert("FAILED TO LOAD DOCUMENT TITLE="+arr[0][7]+" ERROR="+e);
	}

	try{
		document.getElementById(TAB_INDEX).className = arr[0][4];
		TAB_INDEX = arr[0][5];
	}catch(e){
		alert("FAILED TO LOAD TAB_INDEX="+TAB_INDEX+" ERROR="+e);
	}

	try{
		if(typeof(arr[0][8]) != 'undefined'){
			document.getElementById(ICON_ID).id = arr[0][8];
			ICON_ID = arr[0][8];
		}
	}catch(e){
		alert("FAILED TO LOAD ICON_ID="+ICON_ID+" ERROR="+e);
	}

	// I may need to pull the panel before each new request...
	// At the very least... the first panel sent out needs to be stored in pLD

	try{
		var fsPanelStr = '';
		var p1 = 0;
		var p2 = 0;
		var pLD = [];
		if(typeof(arr[0][9]) != 'undefined'){
			for(x in arr[0][9]){
				if(typeof(FS_PANEL[x]) == 'undefined'){
					FS_PANEL[x] = arr[0][9][x];
				}
				fsPanelStr += FS_PANEL[x];
				pLD[x] = 1;
			}
			CMS.pLD = pLD;
			document.getElementById('FS_PANEL').innerHTML = fsPanelStr;
			for(x in CMS.pLD){
				setSidePanelHighlight(x,RECORD_ID,RECORD_INDEX);
			}
		}
	}catch(e){
		alert("FAILED TO LOAD FS_PANEL ERROR="+e);
	}

	try{
		if(typeof(arr[0][10]) != 'undefined'){
			for(x in arr[0][10]){
				if(typeof(CMS.CSS[x]) == 'undefined'){
					loadInclude(arr[0][10][x],x);
					CMS.CSS[x] = true;
				}
			}
		}
	}catch(e){
		alert("FAILED TO LOAD FS_PANEL ERROR="+e);
	}

	try{
		if(typeof(arr[0][11]) != 'undefined'){
			loadArw(arr[0][11]);
		}
	}catch(e){alert(e);}

	stage_id = 'INC-'+caller_record_index+'-'+caller_record_id;
	var stage = STAGES[stage_id];

	if(stage.transition == 2){
		if(stage.stageOpacity > 0){
			stage.arr = arr;
			setTimeout("loadTransition('"+command+"',STAGES['"+stage_id+"'].arr)",100);
			return;
		}else{
			fadeStage(stage_id,1);
		}
	}

	if(getScrollY() > 100){
		top.scrollTo(0,0);
	}

	for(x in arr[1]){
		try{
			document.getElementById(x).innerHTML = arr[1][x];
		}catch(e){
			alert("FAILED TO LOAD="+x+" ERROR="+e);
		}
	}

	for(x in arr[2]){
		try{
			//alert("Change id="+x+" to Class="+arr[2][x]);
			document.getElementById(x).className = arr[2][x];
		}catch(e){
			alert("FAILED TO Change Class="+x+" ERROR="+e);
		}
	}
	for(x in arr[3]){
		try{
			document.getElementById(x).id = arr[3][x];
		}catch(e){
			alert("FAILED TO Change ID="+x+" ERROR="+e);
		}
	}

	if(CMS.use_local){
		var loc_key = 'RECORDS-'+RECORD_INDEX+'-'+RECORD_ID;
		localStorage.setItem(loc_key,JSON.stringify(arr));
	}

	// parent.loadTransition('rec|5|270|0|A|3|21',arr);
	// parent.loadTransition('rec|5|270|0|A|3|21',arr);

	// Take some time to do this right... 
	// elimiate the lengthy keys in the pnaes.php
	// make an initializer to store the interface elements inside the object itself...
	// maybe go so far as to fix the naming scheme on rowMapIndex vs rowMapKey...

	try{
		for(x in arr[0][14]){
			if(typeof(ROWSC[x]) == 'undefined'){continue;}
			setRowInterface(x);
		}
	}catch(e){alert(e);}

	try{
		for(x in arr[0][15]['PLOT']){
			sendChart(arr[0][15]['PLOT'][x]);
		}
	}catch(e){}

}

function getPane(sect,hook,c,p){ // this function has been linearized... it used to be... getPane(sect,pane,num,act)

	if(hook == 1){
		myLightbox.hideElements();
	}

	PANES.hook = hook;
	PANES.c = c;
	PANES.p = p;
	if(typeof(sect) == 'object'){// this is happening with links injected into the loaded page content...
		sect = sect.getAttribute('rev');
	}

	if(hook == 1){
		PANES['containers'][1] = document.getElementById('pageContainer');
		PANES['containers'][1].style.overflow = 'auto';
	}

	if(typeof(PANES[sect]) == 'undefined'){
		//alert('requesting controller');
		requestController(sect,hook);
	}else{
		//alert('ITS ALREADY LOADED... sect='+sect+ ' panes.i='+PANES.i);
		hidePane(PANES.i);
		showPane(sect);
	}
	return false;
}

function clearController(sect){
	try{
		var a = document.getElementById(sect).childNodes[1];
		if(typeof(a.classNameCached) != 'undefined'){
			a.className = a.classNameCached;
			a.innerHTML = a.innerHTMLCached;
		}
	}catch(e){}
	var len = FRMES.length;
	//alert('length='+ len);
	for(x = 1; x < len; x++){ // the first frame is always the statistics tracker
		//alert(sect +'  ==  '+ FRMES[x]['command']);
		
		if(sect == FRMES[x]['command']){
			//alert('SET TO FALSE');
			FRMES[x]['busy']=false;
			try{
				PANES[PANES.i].ownerDocument.getElementById('loader').style.display='none';
			}catch(e){}
			return x;
			//alert('load pane - match found - resetting controller to free');
		}
	}
}

function loadInclude(mode,filename){
	if(mode=='js'){
		var f=document.createElement('script');
		f.setAttribute("type","text/javascript");
		f.setAttribute("src", filename);
	}else if(mode=='css'){
		var f=document.createElement("link");
		f.setAttribute("rel", "stylesheet");
		f.setAttribute("type", "text/css");
		f.setAttribute("href", filename);
		f.setAttribute("onload", "onloadSS()");
	}
	if(typeof(f)!="undefined"){
		document.getElementsByTagName("head")[0].appendChild(f);
	}
}

function loadArw(arr,Arw){
	for(var x=0;x<2;x++){
		var Arw = document.getElementById('Arw-'+x);
		if(typeof(arr[x]) !== 'undefined'){
			Arw.style.display = 'block';
			ARW[x] = arr[x];
		}else{
			Arw.style.display = 'none';
		}
	}
}
			
function doArw(caller,ind){
	// load the variables from the array... with that info call the transition...
	var arr = ARW[ind];
	var transition = 1;
	var cat_id = 1;
	var rec_type = 3;
	var rec_id = arr['id'];
	return callTransition(caller,transition,cat_id,rec_type,rec_id);
}

// WE WILL SET THE TRANSPORT TO USE SSL...

function loadPane(sect,html,arr,loc,shake,insert_id,pairs){ // called when a frame returns content...
	// WHAT HAPPENS WHEN YOU'VE BEEN LOGGED OUT DUE TO INACTIVITY? CLEAR COOKIES AND FIND OUT...
	var hook = clearController(sect);
	hidePane(PANES.i);
	//alert(html);
	if(typeof(loc) == 'string'){
		//alert('Loc'+loc);
		top.location.replace(loc);
		return true;
	}else if(typeof(arr) == 'object'){
		try{displayError(arr['success'],arr['message'])}catch(e){}
		// we need to know the name... the status... and any new value...
		if(arr['success'] == 1){
			//alert('PASS NEED TO SHOW MESSAGE... OR LOAD A NEW PAGE...');
			if(typeof(arr['booleans']) == 'object'){
				for(field in arr['booleans']){
					checkboxReturn(field,arr['booleans'][field]);
				}
			}
		}else{
			for(field in arr['fields']){
				// -----
				//alert(objToString(arr['fields'][field]));
				if(arr['fields'][field][1]){
					if(!shake){
						document.getElementById(field).style.border="solid 2px #F00";
					}else if(shake == 1){ // highlight label...
						var label = document.getElementById('label-'+field);
						label.className="cklabel_error";
						var widget = document.getElementById(field);
						widget.labelObj = label;
						//label.onmouseover = ddrivetip;//("Invalid Range of characters. The forward slash operator is not permitted.","",0,10,20,0);
						//label.onmouseout = hideddrivetip;//(0);
						//
						//alert(arr['fields'][field][1]);
					}
				}
			}
			if(!shake){
				PANES[sect].ownerDocument.getElementById('error_message').innerHTML=arr['message'];
			}else if(shake == 1){
				PANES[sect].ownerDocument.getElementById('dashboard_message').innerHTML=arr['message'];
			}
		}
	}else if(insert_id){
		if(typeof(pairs) == 'object'){
			for(x in pairs){
				for(y in pairs[x]){
					if(y==1){
						document.getElementById(x).className = pairs[x][y];
					}else if(y==2){
						document.getElementById(x).innerHTML = pairs[x][y];
					}				
				}
			}
		}else{
			try{
				if(html.length){
					document.getElementById(insert_id).innerHTML = html;
				}
			}catch(e){}
		}
		return;
	}else{
		PANES[sect].innerHTML = html;
	}

	//alert('hook assignment='+hook);
	PANES[sect].hook = hook; // you may have incorrectly assigned the hook to the section because the section is not dependant on a hook...
	showPane(sect);
}

function stackRCLASS(pane,rowMapKey,rClas){
	if(typeof(RCLASS[pane]) === 'undefined'){RCLASS[pane]=[];}
	if(typeof(RCLASS[pane][rowMapKey]) === 'undefined'){RCLASS[pane][rowMapKey]=[];}
	for(x in rClas){RCLASS[pane][rowMapKey][x] = rClas[x];}
}

function stackROWS(pane,rowMapKey,rRows){
	if(typeof(ROWS[pane]) === 'undefined'){ROWS[pane]=[];}
	if(typeof(ROWS[pane][rowMapKey]) === 'undefined'){ROWS[pane][rowMapKey]=[];}
	for(x in rRows){ROWS[pane][rowMapKey][x] = rRows[x];}
}

function stackROWSC(rowMapKey,rowObj){
	ROWSC[rowMapKey] = rowObj;
	CMS.rowMapKey = rowMapKey;
}

function loadRows(sect,rRows,rClas,rowObj){

	var split = sect.split('|');
	try{
		document.getElementById('rF4').style.display = (split[7].length)? '': 'none';
	}catch(e){}

	var hook = clearController(sect);

	var pane = rowObj.pane;
	var rowMapKey = rowObj.rowMapKey;
	var sortDir = rowObj.dir;
	var sort = rowObj.srt;
	var pn = rowObj.pn;
	var key = rowObj.key;

	stackROWS(pane,rowMapKey,rRows);
	stackRCLASS(pane,rowMapKey,rClas);

	var rowTable = document.getElementById('rowTable-'+rowMapKey);
	var rows = rowTable.childNodes[0].childNodes;
	var L1 = rows.length;
	var LS = rowObj.start_record_number;
	var LE = rowObj.end_record_number; 
	var LT = rowObj.total_records;
	var LP = (rowObj.total_pages);
	var LH = (rowObj.rowHeight+1);

	//alert("recNS="+recNS+" recNE="+recNE+" recNT="+recNT);

	if(pn >= LP){
		pn=0;
	}

	//var key = "s"+sort+"-d"+sortDir+"-n"+pn;
	if(typeof(ROWS[pane][rowMapKey][key]) === 'undefined'){
		alert('internal script error... bad index on row sort in admin.js... shut off fast rows in page preferences...');
		alert(key);
		alert(objToString(ROWS[pane][rowMapKey]));
	}else{
		var ind = ROWS[pane][rowMapKey][key];
	}

	var cols,L2,rowClassStat,filled,do_fill,ind,val;

	// This should at some point reference a template...

	for(x=1;x<LH;x++){
		cols = rows[x].childNodes;
		L2 = cols.length;
		rowClassStat = RCLASS[pane][rowMapKey][key][(x-1)];
		rows[x].style.background = (rowClassStat == 1 || rowClassStat == 3)? '#ddd': '#ccc';
		rows[x].className = (rowClassStat == 2 || rowClassStat == 3)? 'AdminTableRow highPriority': 'AdminTableRow';
		filled = 1;
		do_fill = (typeof(ind[(x-1)]) !== 'undefined')? 1: 0;
		indX = ind[(x-1)];
		for(y=0;y<L2;y++){
			try{
				if(do_fill){
					val = ROWS[pane][rowMapKey][indX][y];
					val = val.replace(/&gt;/g, ">");
					val = val.replace(/&lt;/g, "<");
					val = val.replace(/&amp;/g, "&");
					val = val.replace(/&quot;/g, '"');
				}else{
					val = '&nbsp;';
					filled = 0;
				}
				cols[y].childNodes[0].innerHTML = val;
			}catch(e){
				alert("L2="+L2+" LH="+LH+" indX="+indX+" ERROR FILLING ROW " + e);
			}
		}
		rows[x].style.display = (!filled && pn < 1)? 'none': '';
	}

	stackROWSC(rowMapKey,rowObj);

	setRowInterface(rowMapKey);
}

function setRowInterface(rowMapKey){

	var rowTable = document.getElementById('rowTable-'+rowMapKey);
	var rows = rowTable.childNodes[0].childNodes;
	var rowObj = ROWSC[rowMapKey];
	var LS = rowObj.start_record_number;
	var LE = rowObj.end_record_number; 
	var LT = rowObj.total_records;
	var LP = rowObj.total_pages;
	var LH = (rowObj.rowHeight+1);
	var pane = rowObj.pane;
	var key = rowObj.key;

	for(x=1;x<LH;x++){
		rowClassStat = RCLASS[pane][rowMapKey][key][(x-1)];
		rows[x].style.background = (rowClassStat == 1 || rowClassStat == 3)? '#ddd': '#ccc';
		rows[x].className = (rowClassStat == 2 || rowClassStat == 3)? 'AdminTableRow highPriority': 'AdminTableRow';	
	}

	try{
		document.getElementById('rowTable-'+rowMapKey+'-message').style.display = (LT == 0)? 'block':'none';
	}catch(e){}

	// reset the arrow icon...
	var cols = rows[0].childNodes;
	var L2 = cols.length;
	for(y=0;y < L2;y++){
		if(typeof(cols[y].childNodes[0]) === 'undefined'){continue;}
		var col_id = cols[y].id.substr(2);
		if(ROWSC[rowObj.rowMapKey].srt == col_id){
			cols[y].className = (ROWSC[rowObj.rowMapKey].dir==1)? 'but_in_up':'but_in_down';
		}else{
			cols[y].className = (cols[y].className == 'but_dis')? 'but_dis': 'but_out';
		}
	}

	// CAN I SEND A GENERIC ID => VALUE pair object to cycle through to insert values?

	try{
		document.getElementById('recNS').innerHTML = LS;
		document.getElementById('recNE').innerHTML = LE;
		document.getElementById('recNT').innerHTML = LT;
	}catch(e){}

	var pn = parseInt(ROWSC[rowObj.rowMapKey].pn);
	var ps = document.getElementById('page_select');
	ps.options.selectedIndex = parseInt(ROWSC[rowObj.rowMapKey].pn);
	var total_page_count = LP;

	try{
		var p_prev = document.getElementById('page_prev').childNodes[0];
		p_prev.style.display = (pn == 0)? 'none': 'block';
	}catch(e){}

	try{
		var p_next = document.getElementById('page_next').childNodes[0];
		p_next.style.display = ((pn+1) >= total_page_count)? 'none': 'block';
	}catch(e){}

	try{
		var page_nums = document.getElementById('page_nums');
		var s_cap = 1;
		var e_cap = (pn + 4);
		if(e_cap > total_page_count){e_cap = total_page_count;s_cap = e_cap - 6;}else{s_cap = pn - 2;}
		if(s_cap < 1){s_cap = 1;e_cap = 7;}
		if(e_cap > total_page_count){e_cap = total_page_count;}
		for(y=0;y < 7;y++){
			if(typeof(page_nums.childNodes[y]) === 'undefined'){continue;}
			var but = page_nums.childNodes[y].childNodes[0];
			but.style.textDecoration = ((s_cap-1) == pn)? 'underline':'none';
			but.innerHTML = s_cap;
			but.setAttribute('rel',(s_cap-1));
			but.style.display = (y >= total_page_count)? "none": "";
			s_cap++;
		}
	}catch(e){}

	try{
		var page_nums = document.getElementById('page_select');
		var l = page_nums.length;
		var x = (total_page_count>l)? total_page_count: l;
		for(y=0;y<x;y++){
			if(typeof(page_nums.options[y]) == 'undefined'){
				page_nums.options[x] = new Option(x-1,x.toString());
			}else{
				page_nums.options[y].style.display = (y >= total_page_count)? 'none':'';
			}
		}
	}catch(e){}
	
	//alert("ROW LOADER FINISHED");	
}

function hidePane(sect){
	return false;
	PANES[sect].style.display = 'none';
}

function closeWindow(sect){
	if(typeof(sect) == 'string'){
		var winCon = top.document.getElementById("winCon"); // DOES NOT SUPPORT MULTI WINDOWS AT THE MOMENT
		document.body.removeChild(winCon);			
	}else{
		document.body.removeChild(this.parentNode.parentNode);	
	}
}

function getScrollY(){
	return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
}

function getViewportWidth(){
	return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}

function getViewportHeight(){
	return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

function drag(){
	this.divCov = this.parentNode.childNodes[0];
	this.divCov.style.height = "1000px";
	Drag.init(this.parentNode,null,0,getViewportWidth(),0,10000);
	this.parentNode.onDragEnd = function(x, y){
		this.childNodes[0].style.height = "0px";
	}
}

function launchPageFrame(sect,page){
	clearController(sect);
	// THESE VARS HAVE TO PASS UP WITH THE COMMAND... width,height,throbberclass
	var width = 550;
	var height = 375;
	var scrollY = getScrollY();
	var viewportHeight = getViewportHeight();
	var viewportWidth = getViewportWidth();
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

	//alert("window.pageYOffset="+window.pageYOffset +" document.body.scrollTop="+document.body.scrollTop+" document.documentElement.scrollTop="+document.documentElement.scrollTop);
	//alert("window.innerHeight="+window.innerHeight+" document.documentElement.clientHeight="+document.documentElement.clientHeight + " document.body.clientHeight="+document.body.clientHeight);
	//alert("window.innerWidth="+window.innerWidth+" document.documentElement.clientWidth="+document.documentElement.clientWidth + " document.body.clientWidth="+document.body.clientWidth);

	var centerX = parseInt(parseInt(viewportWidth) / 2);
	var centerY = (isIE6)? parseInt(parseInt(viewportHeight) / 2) + parseInt(scrollY): parseInt(parseInt(viewportHeight) / 2);
	var div = document.createElement("DIV");
	div.className = "winCon";
	div.setAttribute("id","winCon");
	div.style.top = (centerY-((height+20)/2)) +"px"; // THIS IS NOT RELATIVE TO THE CENTER OF SCREEN...
	div.style.left = (centerX-(width/2)) +"px";
	div.style.height = (height+20)+"px";
	div.style.width = width+"px";
	var div2 = document.createElement("DIV");
	div2.className = "winCov";
	div.appendChild(div2);
	var div3 = document.createElement("DIV");
	div3.className = "thrbL";
	div.appendChild(div3);
	var div4 = document.createElement("DIV");
	div4.className = "winBar";
	div4.onmousedown = drag;
	div.appendChild(div4);
	var div5 = document.createElement("DIV");
	div5.onclick = closeWindow;
	div5.onmousedown = drag;
	div5.className = "winBarClose";
	div5.id = "winBarClose";
	div4.appendChild(div5);
	var frame = document.createElement("IFRAME");
	frame.style.width = width+"px";
	frame.style.height = height+"px";
	frame.style.border = "none";
	var frameID = "pop-1";
	frame.setAttribute("id",frameID);
	frame.setAttribute("scrolling","no");
	frame.setAttribute("frameborder","0");
	frame.frameContainer = div;
	div.appendChild(frame);
	document.body.appendChild(div);
	frame.src = page+"&content_only=99";
	frame.throbber = div3;
	frame.areaHeight = height;
	//frame.onload = clearFrameThrobber;
	startFrameThrobber(frame);
	if(isIE6){window.onscroll = fixedIE;}
}



function fixedIE(){
	try{
		var fixedElement = document.getElementById("winCon");
		fixedElement.style.top = (parseInt(getScrollY()) + "px");   
	}catch(e){}
} 

function startFrameThrobber(frm){
	frm.throbber.style.height = frm.areaHeight+"px";
	frm.throbber.style.display = 'block';
}

function clearFrameThrobber(id){
	document.getElementById(id).throbber.style.display = "none";
}

function showPane(sect){ // make the container creator in here???

	PANES.i = sect;
	if(PANES.hook == 1){
		myLightbox.showPage();
	}
}

function importPane(sect,pane,mode){ // this is obviously a big mistake...
	if(pane == 'batch_importer'){
		var myfile = document.getElementById('myfile').value;
		var record_type = document.getElementById('record_type').value;
		var file_type = document.getElementById('file_type').value;
		if(myfile==''){
			displayError(0,'Please Choose a File');
			return false;
		}else if(record_type==''){
			displayError(0,'Please Choose a Record Type');
			return false;			
		}else if(file_type==''){
			displayError(0,'Please Choose a File Type');
			return false;			
		}		
	}
}

function displayError(success,message){
	try{
		var dash = document.getElementById('dashboard_message');
		dash.innerHTML = message;
		var message_color = (success)? "#00ff00": "#ff0000";
		dash.style.backgroundColor = (success == 100)? null:message_color;
	}catch(e){}
}

function savePane(sect,pane,mode,element_whitelist){

	//alert('SavePane() --- PANES.i= ' + PANES.i + ' sect= ' + sect + ' pane= ' + pane);
	//	return false;
	if(PANES.i.substr(0,2) == 'F-'){
		PANES[PANES.i].paneform = document.getElementById(PANES.i);		
	}else{
		PANES[PANES.i].paneform = PANES[PANES.i].ownerDocument.getElementById('content_form_'+sect);
	}

	var hook = 0;
	if(hook == 1){
		myLightbox.hideElements();
	}

	var RC = requestController(PANES.i,hook,'POST');
	RCD = RC.document;
	Tform = RCD.createElement("FORM");
	Tform.setAttribute("id","trans_form");
	Tform.setAttribute("method","post");
	if(mode == 'FILE'){
		Tform.setAttribute("enctype","multipart/form-data");
	}
	var loc = PANES[PANES.i].ownerDocument.location.toString();
	var thepath = loc.substr(0,loc.lastIndexOf('/'));
	// I DONT KNOW WHY YOU HAD THIS AS ABSOLUTE BUT FIRFOX THROWS ERRORS WITH HTTPS ABSOLUTE PATHS...
	Tform.setAttribute('action',loc);	
	//Tform.setAttribute('action','?trans='+PANES.i);	
	//alert(thepath+'/index.php?trans='+PANES.i);

	var form_stamp = false;
	try{
		form_stamp = document.getElementById('form_stamp').value;	
	}catch(e){}

	var c = PANES[PANES.i].paneform.elements.length;
	var cacheVals=[];
	var cacheVal = false;
	//alert('elements length='+c);

	var check_whitelist = false;
	if(typeof(element_whitelist) == 'object'){
		check_whitelist = true;
	}

	for(x=0;x < c; x++){
		var ele = PANES[PANES.i].paneform.elements[x];
		if(mode == 'FILE' && ele.type != 'file' && ele.id != 'form_stamp'){
			continue;
		}

		if(check_whitelist && element_whitelist.length){
			var check = ele.id;
			var pass = false;
			for(z in element_whitelist){
				if(element_whitelist[z] === check){
					pass = true;
				}
			}
			if(!pass){continue;}
			//alert(check);
		}

		if(ele.nodeName == 'TEXTAREA'){
			//alert(ele.textContent);
			var temp = RCD.createElement("TEXTAREA");
			var n = ele.name;
			if((n.substr(0,4)=='new_' && mode == 'SAVE') || (n.substr(0,4)!='new_' && mode == 'ADD')){continue;}
			temp.setAttribute('name',n);
			temp.value = ele.value;
			//temp.setAttribute('value',ele.value);
			Tform.appendChild(temp);
		}else if(ele.nodeName == 'SELECT'){
			var temp = RCD.createElement("SELECT");
			var n = ele.name;
			temp.setAttribute('name',n);
			if(ele.options.length){
				var val = ele.options[ele.selectedIndex].value;
				var temp2 = RCD.createElement("OPTION");
				temp2.setAttribute('value',ele.value);
				temp2.setAttribute('selected','selected');
				temp.appendChild(temp2);
				Tform.appendChild(temp);
			}
		}else if(ele.nodeName == 'INPUT'){
			if(ele.alt == 'ckey'){
				cacheKey = ele;//alert('CACHE KEY');
			}else if(ele.alt == 'cval'){
				cacheVal = true;
				cacheVals[cacheVals.length] = ele;//alert('CACHE VAL');
			}else if(ele.type == 'checkbox'){
				if(ele.checked){
					var temp = RCD.createElement("INPUT");
					var n = ele.name;
					if((n.substr(0,4)=='new_' && mode == 'SAVE') || (n.substr(0,4)!='new_' && mode == 'ADD')){continue;}
					temp.setAttribute('name',n);
					temp.setAttribute('value',ele.value);
					Tform.appendChild(temp);
				}
			}else if(ele.type == 'text' || ele.type == 'submit' || ele.type == 'hidden' || ele.type == 'password'){
				var temp = RCD.createElement("INPUT");
				var n = ele.name;
				var val = ele.value;
				if((n.substr(0,4)=='new_' && mode == 'SAVE') || (n.substr(0,4)!='new_' && mode == 'ADD')){continue;}
				temp.setAttribute('name',n);
				if(ele.type == 'password'){
					val = val.replace(/^\s+|\s+$/g, '');
					if(val.length > 0 && form_stamp){					
						val = cT(val,form_stamp);
					}
				}
				if(typeof(ele.labelObj) == 'object'){
					ele.labelObj.className = 'cklabel';
				}
				temp.setAttribute('value',val);
				Tform.appendChild(temp);				
			}else if(mode == 'FILE' && ele.type == 'file'){
				temp = ele.cloneNode(true);
				Tform.appendChild(temp);
			}else{
				alert('Unknown Input Type=' + ele.type);
			}
		}else{
			alert('Unknown Element Type=' + ele.nodeName);
		}
	}

	//getUserData
	if(typeof(cacheKey) == 'object' && cacheVal){
		ckey = cacheKey.value.replace(/^\s+|\s+$/g, '');
		if(ckey.length == 0){ckey="0";}
		if(cacheKey.name == 'uid'){
			var temp = RCD.createElement("INPUT");
			temp.setAttribute('name','hint');
			if(((ckey.indexOf("@") > 1) || parseInt(ckey) == ckey)){
				temp.setAttribute('value',ckey.substr(0,1)+""+ckey.substr(ckey.length-1));	
				Tform.appendChild(temp);
			}
		}

		cval = cacheVals[0].value.replace(/^\s+|\s+$/g, '');
		var temp = RCD.createElement("INPUT");
		temp.setAttribute('name',cacheKey.name);
		if(cval.length == 0){cval="0";}
		temp.setAttribute('value',cT(ckey,cval));
		Tform.appendChild(temp);
		var l = cacheVals.length;

		for(x=0;x < l;x++){
			cval = cacheVals[x].value.replace(/^\s+|\s+$/g, '');
			var temp = RCD.createElement("INPUT");
			temp.setAttribute('name',cacheVals[x].name);
			temp.setAttribute('value',cT(cval,ckey));	
			Tform.appendChild(temp);
		}
	}

	var temp = RCD.createElement("INPUT");
	temp.setAttribute('name','trans');
	temp.setAttribute('value','trans');	
	Tform.appendChild(temp);
	var temp = RCD.createElement("INPUT");
	temp.setAttribute('name','panesi');
	temp.setAttribute('value',PANES.i);	
	Tform.appendChild(temp);
	var temp = RCD.createElement("INPUT");
	temp.setAttribute('name','pane');
	temp.setAttribute('value',pane);
	Tform.appendChild(temp);
	var temp = RCD.createElement("INPUT");
	temp.setAttribute('name','sect');
	temp.setAttribute('value',sect);
	Tform.appendChild(temp);
	var temp = RCD.createElement("INPUT");
	temp.setAttribute('name','trans_action'); // This used to be action but it conflicted with the form action event...
	temp.setAttribute('value',mode);
	Tform.appendChild(temp);
//	if(top != self){ // DOESN'T WORK
//		var temp = RCD.createElement("INPUT");
//		temp.setAttribute('name','trans_source'); // This used to be action but it conflicted with the form action event...
//		temp.setAttribute('value','iframe');
//		Tform.appendChild(temp);		
//	}
	// IE
	if(!RC.document.body){
		var temp = RCD.createElement("BODY");
		RCD.appendChild(temp);
	}
	RC.document.body.appendChild(Tform);

	//alert(Tform.action);
	//Tform.submit();

	RC.document.getElementById('trans_form').submit();
	return false;
}

function ddInit(e){
  topDog=isIE ? "BODY" : "HTML";
  whichDog=isIE ? document.all.theLayer : document.getElementById("theLayer");  
  hotDog=isIE ? event.srcElement : e.target;  
  while (hotDog.id!="titleBar"&&hotDog.tagName!=topDog){
    hotDog=isIE ? hotDog.parentElement : hotDog.parentNode;
  }  
  if (hotDog.id=="titleBar"){
    offsetx=isIE ? event.clientX : e.clientX;
    offsety=isIE ? event.clientY : e.clientY;
    nowX=parseInt(whichDog.style.left);
    nowY=parseInt(whichDog.style.top);
    ddEnabled=true;
    document.onmousemove=dd;
  }
}

function dd(e){
  if (!ddEnabled) return;
  whichDog.style.left=isIE ? nowX+event.clientX-offsetx : nowX+e.clientX-offsetx; 
  whichDog.style.top=isIE ? nowY+event.clientY-offsety : nowY+e.clientY-offsety;
  return false;  
}

function hideMe(){
  if (isIE||isNN) whichDog.style.visibility="hidden";
  else if (isN4) document.theLayer.visibility="hide";
}

function showMe(){
  if (isIE||isNN) whichDog.style.visibility="visible";
  else if (isN4) document.theLayer.visibility="show";
}

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;
	}
};


var cssdropdown={aa:250,ab:false,ac:1,dmo:null,ie:document.all,ff:document.getElementById&&!document.all,st:undefined,bc:0,g:function(w,ot){var to=(ot=="left")?w.offsetLeft:w.offsetTop;
var p=w.offsetParent;return to=(ot=="left")? to+p.offsetLeft:to+p.offsetTop;},se:function(){if(this.bc<parseInt(this.dmo.offsetHeight)){this.bc+=10+(this.bc/10);
this.dmo.style.clip="rect(0 auto "+this.bc+"px 0)";}else{return;
}this.st=setTimeout("cssdropdown.se()",10);},sh:function(obj,e){if(this.ie||this.ff){this.dmo.style.left=this.dmo.style.top="-500px"}
if(e.type=="click"&&obj.visibility==hidden||e.type=="mouseover"){if(this.ac==1){if(typeof this.st!="undefined"){clearTimeout(this.st);}obj.clip="rect(0 auto 0 0)";
this.bc=0;this.se();}obj.visibility="visible";
}else if(e.type=="click"){obj.visibility="hidden";
}else if(e.type=="focus"){obj.visibility="visible";
}},iec:function(){return(document.cm&&document.cm!="BackCompat")?document.documentElement:document.body;
},ce:function(obj,w){var ed=0;
if(w=="rightedge"){var we=this.ie&&!window.opera?this.iec().scrollLeft+this.iec().clientWidth-15:window.pageXOffset+window.innerWidth-15;
this.dmo.cm=this.dmo.offsetWidth;
if (we-this.dmo.x < this.dmo.cm){ed=this.dmo.cm-obj.offsetWidth;
}}else{var te=this.ie && !window.opera? this.iec().scrollTop:window.pageYOffset;
var we=this.ie && !window.opera? this.iec().scrollTop+this.iec().clientHeight-15:window.pageYOffset+window.innerHeight-18;
this.dmo.cm=this.dmo.offsetHeight;
if (we-this.dmo.y < this.dmo.cm){ed=this.dmo.cm+obj.offsetHeight;
if((this.dmo.y-te)<this.dmo.cm);
ed=this.dmo.y+obj.offsetHeight-te;
}}return ed;
},di:function(obj,e,did){if(this.dmo!=null){this.dmo.style.visibility="hidden";
}this.ch();
if(this.ie||this.ff){obj.onmouseout=function(){cssdropdown.dhm()};

this.dmo=document.getElementById(did);
obj.onmousedown=function(){setTimeout("cssdropdown.dmo.style.visibility='hidden';",50);return !cssdropdown.ab;};

this.dmo.onmouseover=function(){cssdropdown.ch()};
this.dmo.onmouseout=function(e){cssdropdown.dh(e)};
this.dmo.onclick=function(){cssdropdown.dhm()};
this.sh(this.dmo.style, e);
this.dmo.x=this.g(obj.parentNode,"left");
this.dmo.y=(typeof DDMFIXEDOFFSETHEIGHT == "undefined")?this.g(obj,"top"):this.g(obj.parentNode.parentNode,"top");
this.dmo.style.left=this.dmo.x-this.ce(obj,"rightedge")+"px";
var chromemenuT = document.getElementById("chromemenu");
var bottomEdgeTest = this.ce(obj,"bottomedge");
var topPos = (typeof DDMFIXEDTOP == "undefined")? chromemenuT.offsetTop:DDMFIXEDTOP;
var offSetHeight = (typeof DDMFIXEDOFFSETHEIGHT == "undefined")? obj.offsetHeight: DDMFIXEDOFFSETHEIGHT;
this.dmo.style.top=topPos+obj.offsetTop+offSetHeight+1+"px";
/* PUT BOTTOM TEST <--- BACK FOR SNAP TO TOP if(bottomEdgeTest != 0){this.dmo.style.left = parseInt(this.dmo.style.left) + 150 + "px";}*/
}},cff:function(a,b){while(b.parentNode){if((b=b.parentNode)==a){return true;
}}return false;
},dh:function(e){var evtobj=window.event?window.event:e;
if(this.ie&&!this.dmo.contains(evtobj.toElement)){this.dhm();
}else if (this.ff&&e.currentTarget!= evtobj.relatedTarget&& !this.cff(evtobj.currentTarget,evtobj.relatedTarget)){this.dhm();
}},dhm:function(){this.delayhide=setTimeout("cssdropdown.dmo.style.visibility='hidden';",this.aa);
},ch:function(){if (this.delayhide!="undefined"){clearTimeout(this.delayhide);
}},startchrome:function(){for(var ids=0;
ids<arguments.length;
ids++){var mi=document.getElementById(arguments[ids]).getElementsByTagName("a");
for(var i=0;i<mi.length; i++){if(mi[i].getAttribute("rel")){
mi[i].onfocus=function(e){var event=typeof e!="undefined"?e:window.event;
cssdropdown.di(this,event,this.getAttribute("rel"));
}
mi[i].onmouseover=function(e){var event=typeof e!="undefined"?e:window.event;
cssdropdown.di(this,event,this.getAttribute("rel"));
}}}}}}