//Initialize CARROT domain
var CARROT=new function(){
	//***** classes available *****
	this.cls={};
	
	
	//***** EVENT handling *****
	/*
		currently defined for:
		- tracker_complete - Execute when tracker submission is complete. 
		
	*/	
	this._listeners={};
	
	//***** MANAGE events *****
	this.addEventListener= function(event, callback) {
        this._listeners[event]={};
        this._listeners[event].call=callback;
    }
    this.removeEventListener= function(event) {
    	this._listeners[event]={};
    }
    this.dispatchEvent= function(e) {
        CARROT.std.debug('EVENT '+e.type+' = TRIGGERED');
        //event.type defines what event to call
        var type = e.type;
        e.target=this;
        if (typeof(this._listeners[type]) != 'undefined'){
        	if (typeof(this._listeners[type].call) == 'function'){
        		this._listeners[type].call(e);
       		}
        }
    }
	//***** end EVENT handling *****
	
	
	//***** MANAGE including of js files *****
	this.include=new function(){
		//files and their loaded state
		//file = filename
  		//state =
  		//  pending
   		//  processing
   		//  loaded
		this.files={};
		
		//pending scripts to be executed
		this.scripts=[];
		
		//load returns true if loaded, false if not loaded
		this.file=function(scriptName){
			CARROT.std.debug('CARROT.include.file='+scriptName+' STARTED');
			if(typeof(this.files[scriptName])=='undefined'){
				
				this.files[scriptName]='pending';
				//***** APPEND script to DOM *****
				//CARROT.std.debug('CARROT.include.file='+scriptName);
				var scr = document.createElement("script");  
   				scr.src = scriptName;  //window.location.protocol+'//'+CARROT.obj.URL_ROOT+
   				document.body.appendChild(scr);  
				return false;
			}else{
				//***** script already loaded *****
				if(this.files[scriptName]=='loaded'){
					//CARROT.std.debug('CARROT.include.file='+scriptName+' already LOADED');
					return true;
				}else{
					return false;
				}
			}
			
		}
		
		//sets the file state
		/*
		{
			"name":"scriptname.js"
			"state":"processing"
		}
		*/
		this.state=function(objState){
			CARROT.std.debug('CARROT.include.state STARTED objState='+objState+':name='+objState.name+':state=	'+objState.state);
			if(typeof(objState.name)!='undefined'){
				if(typeof(objState.state)!='undefined'){
					this.files[objState.name]=objState.state;
					CARROT.std.debug('CARROT.include.state setting'+objState.name+'=>'+objState.state);
					if(objState.state=='loaded'){
						this.execScripts();
					}
				}
			}
		}//state
		
		//defines the code to be executed
		this.script=function(scriptObj){
			CARROT.std.debug('CARROT.include.script STARTING');
			//CARROT.std.debug('script='+scriptObj.source);
			this.scripts.push(scriptObj);
			//CARROT.std.debug('CARROT.include.scripts.length='+CARROT.include.scripts.length);
			if(CARROT.browser.isIE){
				this.execScripts();
			}
			//!!!!! evaluate if the script should be run.
		}
		this.execScripts=function(){
			CARROT.std.debug('CARROT.include.execScripts STARTING');
			//find and run any code pending execution here
			var script={};
			var fileStr='';
			//CARROT.std.debug('CARROT.include.state script.length='+CARROT.include.scripts.length+':scripts='+CARROT.std.debug(CARROT.include.scripts));
			for (var i = 0; i < this.scripts.length; i++){ 
    			var runScript=true;
    			script=this.scripts[i];
    			if(typeof(script)=='object'){
     				//CARROT.std.debug('CARROT.include.state script.files type='+typeof(script.files));
     				for (var ii = 0; ii < script.files.length; ii++){ 
     					fileStr=script.files[ii];
     					//CARROT.std.debug('CARROT.include.state evaluating runScript file'+fileStr);
     					if(typeof(this.files[fileStr])=='undefined'){
     						//CARROT.std.debug('CARROT.include.state evaluating runScript files[fileStr]=undefined');
     						runScript=false;
     					}else{
     						if(this.files[fileStr]!='loaded'){
     							//CARROT.std.debug('CARROT.include.state evaluating runScript files[fileStr]!=loaded');
     							runScript=false;
     						}
     					}
     				}
     				if(runScript){
     					eval(script.source);
     					this.scripts[i].source='';
     					//empty script
     					//set script=false;
     						
     				}
    			}	
			}
		}
	}//CARROT.include
	
	//***** standard functions *****
	this.std=new function(){
		
		//***** eval the scripts within a div *****
		this.execDivScripts=function(theDiv){
			// div.innerHTML = innerHTML;  
			    var scriptsStarting=[];
			    var scripts = theDiv.getElementsByTagName("script"); 
			    var script={};//individual script  
			    var runScript=true;
			    var js='';
			    for( var i=0; i < scripts.length; i++) {  
			      script=scripts[i];
			      if(typeof(script.src)=='string'){
			      	if(script.src!=''){
			      		CARROT.std.debug('execDivScripts src="'+script.src);
			      		//document.write('<script type="text/javascript" src="'+script.src+'"><\/script>');
			      		
			      		//get script filename after the URL_ROOT
			      		var splitArr=[];
						splitArr=script.src.split(CARROT.obj.URL_ROOT);
						//CARROT.std.debug('splitArr length='+splitArr.length+':array='+CARROT.std.dump(splitArr));
			      		
			      		//***** lenght will be different between IE and other browsers ****
			      		var scriptName=splitArr[splitArr.length-1];
			      		if(!CARROT.include.file(scriptName)){
			      			runScript=false;
			      			scriptsStarting.push(scriptName);
			      		}
			      	}else{
			      		js +=script.text;
			      		//eval(script.text);  
			      	}
			      	
			      	
			      }else{
			      	js +=script.text;
			      	//eval(script.text); 
			      	
			      }
			      
			    }
				
				//run script or send to CARROT.include for processing
				if(runScript){
					CARROT.std.debug('runScript=true ');
					eval(js);
				}else{
					CARROT.std.debug('runScript=false');
					CARROT.include.script({"source":js,"files":scriptsStarting});
					
				}
		
		}//this.std.execDivScripts
	}//this.std
	
};


CARROT.browser={};
CARROT.browser.isIE= /(msie|internet explorer)/i.test(navigator.userAgent);
//***** data objects *****
CARROT.obj={};

CARROT.obj.charts=[];

CARROT.obj.menus={};

CARROT.cls.menu=function(inputObj){
	this.ID='default_menuID';
	this.classOn='defaultClassOn';
	this.classOff='defaultClassOff';
	this.targetID='defaultTargetID';
	this.selectedID='0';//select 1st menu if none are defined as selected
	this.selectedUrl='';//url of currently selected menu link
	this.links={};
	CARROT.std.debug('starting CARROT.cls.menu class');
	//assign inputObj properties to this
	for(var objKey in inputObj) {
     	//***** skip other properties *****
     	if(!inputObj.hasOwnProperty(objKey) ){
			continue;
		}
		this[objKey]=inputObj[objKey];
	}
	
	this.select=function(linkObj){
		/*
		linkObj={ID (string) ,url (string))
		*/
		CARROT.std.debug('Cmenu.select starting this.ID='+this.ID);
		
		var linkID=linkObj.ID;
		var url=linkObj.url;
		url=url.replace(/&amp;/gi, "&")
		//var subTabs = document.getElementsByName(name);
		var parentElement=document.getElementById(this.ID+'_items');
		var tabCount=parentElement.childNodes.length
		CARROT.std.debug('tabCount ='+tabCount);
		
		var tmpElement={};
		var tabNum=-1;
		//reset all tabs
		for (var x=0; x<tabCount; x++) {		
			tmpElement=parentElement.childNodes[x];
			//is element
			if(tmpElement.nodeType == 1){
				tabNum++;
				//set tab class
				if(tabNum==linkID){
					if(typeof(this.links[tabNum].classSelected)!='undefined'){
						tmpElement.className=this.links[tabNum].classSelected;
					}else{
						tmpElement.className=this.classOn;
					}
					CARROT.std.debug('tabNum==linkID: linkID='+linkID);
				}else{
					if(typeof(this.links[tabNum].classNotSelected)!='undefined'){
						tmpElement.className=this.links[tabNum].classNotSelected;
					}else{
						tmpElement.className=this.classOff;
					}
					CARROT.std.debug('tabNum NOT = linkID: linkID='+linkID);
				}
				
			}
			
		}
		CARROT.removeEventListener('tracker_complete');
//		alert(this.targetID);
		if (this.targetID=='modalContent'){
			contentload(this.targetID,url,0,1,'','true','','800');//,'','true'
		} else {
			contentload(this.targetID,url,0,1);//,'','true'
		}
		
	}
}
CARROT.std.pageLoading=function(target,selfClose,customMessage){
	if (target==undefined){
		popUpDiv('open','messageDiv[0]','backgroundScreen[0]');
		if (selfClose!=undefined) {
			setTimeout("popUpDiv('close','messageDiv[0]','backgroundScreen[0]')",selfClose);
		}
	} else if (target=="page") {
		var targetDiv=document.getElementById('messagePage[0]');
		tempHTML = '<div class="messageDiv messagePage" ><div class="messageDivSub messageDivDashSub" id="messagePage[0]Sub"><div class="noContent"><p id="messagePageSubMessage[0]" class="title">';
		if (customMessage!=undefined) {
			tempHTML += customMessage;
		} else {
			tempHTML += 'Loading...';
		}
		tempHTML += '</p><br class="brclear"></div></div></div>';
		targetDiv.innerHTML = tempHTML;
		popUpDiv('open','messagePage[0]','backgroundScreenPage[0]');
		if (selfClose!=undefined) {
			setTimeout("popUpDiv('close','messagePage[0]','backgroundScreenPage[0]')",selfClose);
		}
	}
}

CARROT.std.modalContent=function(windowTitle,windowWidth){
	var targetDiv=document.getElementById('messagePage[0]');
	if (windowWidth!=undefined) {
		var windowWidthTemp=windowWidth;
	} else {
		var windowWidthTemp='600';
	}
	var tempHTML= '<div id="modalWrap" class="messageDiv messagePage" style="width:'+windowWidthTemp+'px;">';
	tempHTML+='				<div class="dashModule">';
	tempHTML+='			<h3 class="dragHandle dragHandleTab"><span id="draghandle-2">'+windowTitle+'</span></h3>';
	tempHTML+='			<div class="dashModuleWrap" id="dashModuleWrapA52">';
	tempHTML+='				<div class="menuBarTabs trackerTab" >';
	tempHTML+='					<div class="menuItems">';
	tempHTML+='						<ul class="menuList line">';
	tempHTML+='							<li class="rounded link current" onclick="CARROT.std.closeModal();">Close</li>';
	tempHTML+='						</ul>';
	tempHTML+='					</div>';
	tempHTML+='				</div>';
	tempHTML+='				<div class="dashModuleBox">';
	tempHTML+='					<div id="modalContent">';
	tempHTML+='					</div>';
	tempHTML+='				</div>';
	tempHTML+='			</div>';
	tempHTML+='		</div></div>';
	targetDiv.innerHTML = tempHTML;
	
}

CARROT.std.closeModal=function(){
	popUpDiv('close','messagePage[0]','backgroundScreenPage[0]');
}

CARROT.std.pageLoaded=function(){
	popUpDiv('close','messageDiv[0]','backgroundScreen[0]');
}

// configure sidebar date picker
YAHOO.namespace("myCarrotDatePicker.calendar");
YAHOO.myCarrotDatePicker.calendar.init = function() {
	
	var handleSelectViaAjax = true; // process selected dates via ajax by default
	
	function handleSelect(type,args,obj) {		
		var handleSelectViaAjax = YAHOO.myCarrotDatePicker.calendar.init.handleSelectViaAjax;
		var dates = args[0];
		var date = dates[0];
		var year = date[0], month = date[1], day = date[2];
		date = month+"/"+day+"/"+year;
		if (handleSelectViaAjax) {
			script="./index.ajax.php?m=cal&a=event&modMode=dayDetail&date="+date;
			contentload('cal_display_large',script,'','true','','');
		} else {
			script="./index.php?m=cal&a=event&modMode=calLoader&date="+date;
			window.location=script;
		}
	}
	
	YAHOO.myCarrotDatePicker.calendar.myCarrotDatePickerCal = new YAHOO.widget.CalendarGroup("myCarrotDatePickerCal","myCarrotDatePickerContainer", { 
												pages:1, 
												close: false,
												navigator:true
											} 
										);

	// Display calendar
	YAHOO.myCarrotDatePicker.calendar.myCarrotDatePickerCal.render();

	// Listener to handle the select of a date
	YAHOO.myCarrotDatePicker.calendar.myCarrotDatePickerCal.selectEvent.subscribe(handleSelect, YAHOO.myCarrotDatePicker.calendar.myCarrotDatePickerCal, true);
		
}

/*
function ShowCalendarEvents(type,args,obj) {
	// display icons and dots on calendar days with events
	// function in development
	
	function handleCalendarEventsSelect(type,args,obj) {		
		var handleSelectViaAjax = YAHOO.myCarrotDatePicker.calendar.init.handleSelectViaAjax;
		var dates = args[0];
		var date = dates[0];
		var year = date[0], month = date[1], day = date[2];
		date = month+"/"+day+"/"+year;
		if (handleSelectViaAjax) {
			script="./index.ajax.php?m=cal&a=event&modMode=dayDetail&date="+date;
			contentload('cal_display_large',script,'','true','','');
		} else {
			script="./index.php?m=cal&a=event&modMode=calLoader&date="+date;
			window.location=script;
		}
	}
}

*/

function carrotSubmenu(loc,selected,script,name,onClass,offClass) {
	
	var subTabs = document.getElementsByName(name);
	//childNodes.length
	//***** clear tracker event *****
	CARROT.removeEventListener('tracker_complete');
	//reset all tabs
	for (var x=0; x<subTabs.length; x++) {		
		the_id=name+'_'+x;			
		document.getElementById(the_id).className=offClass;
	}
	//select the selected tab
	document.getElementById(selected).className=onClass;
	
	if (loc == 'window') {
		window.location=script;
	} else {
		contentload(loc,script,'','true','','true');	
	}
}

CARROT.std.fixMenu=function(){ // temporary fix for journal
	var selected='subTab_2';
	var name='subTab';
	var onClass='rounded link current';
	var offClass='rounded link notCurrent';

	var subTabs = document.getElementsByName(name);
	//childNodes.length
	if (subTabs){
		//***** clear tracker event *****
		CARROT.removeEventListener('tracker_complete');
		//reset all tabs
		for (var x=0; x<subTabs.length; x++) {		
			the_id=name+'_'+x;			
			document.getElementById(the_id).className=offClass;
		}
		//select the selected tab
		document.getElementById(selected).className=onClass;
	}
}

function checkboxToggle(rowToCheck,rowClassValue){
	document.getElementById(rowToCheck).className=rowClassValue;
}

function checkboxAndImageToggle(id,imagesOnly){
	if (!document.getElementById){ return; }
	if (!document.getElementsByTagName){ return; }
	if (!imagesOnly){
		var inputs = document.getElementById(id).getElementsByTagName("input");
		for(var x=0; x < inputs.length; x++) {
			if (inputs[x].type == 'checkbox'){
				inputs[x].checked = !inputs[x].checked;
			}
		}
	}
	var divTargetTemp = id+'-image';
	var divTarget = document.getElementById(divTargetTemp);
	var divTargetTemp = id+'-image_sel';
	var divTarget2 = document.getElementById(divTargetTemp);
	if (divTarget.style.display =='none') {
		divTarget.style.display ='block';
		divTarget2.style.display ='none';
	} else {
		divTarget.style.display ='none';
		divTarget2.style.display ='block';
	}
}

function selectTrackerPopup(mode,id,name) {
	var selectedListHTML="";
	var selectedIDs="";
	var trkrsNames=""; 
	
	//alert(mode+' tracker id:'+id+', '+name);
	index=trac.length;

	if (mode=='add') {
		// test if unique
		var unique=1;
		for (row = 0; row < trac . length; ++ row) {
			if (trac[row].id == id) {
				unique=0;
			}
		}
		if (unique) {
			trac[index] = new Array();
			trac[index].id=id;
			trac[index].name=name;
		}
	} else if (mode=='del') {
		//alert('del')
		trac.splice(id,1);
	}
	//alert('trac.length='+trac.length);
	for (row = 0; row < trac . length; ++ row) { 
		selectedListHTML+="<a href=#><span onClick=\"selectTrackerPopup('del','"+row+"','')\">"+trac[row].name+"<br>\n";
		trkrsNames+=trac[row].name;
		selectedIDs+=trac[row].id;
		if (row < trac.length-1) {
			selectedIDs+=",";
			trkrsNames+=", ";
		}
	}
	document.getElementById('selectedList').innerHTML = selectedListHTML;
	if (mode=='save') {
		//alert('save')
		document.getElementById('trkrs').value = selectedIDs;
		document.getElementById('trkrsNames').innerHTML = trkrsNames;
		popup('','close','tracker_');
	}
}

function selectClass(loc,script) {
	selectedClass=document.getElementById('tracClass').selectedIndex;
	selectedClassID=document.getElementById('tracClass').options[selectedClass].value;			

	script+="&tracClassID="+selectedClassID;
	contentload(loc,script);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function popUpDiv(state,target,background,transparency,layer) {
	if (!target){target='tracker_bg';}
	if (!background){background='backgroundScreenTracker[0]';}
	var divTarget=document.getElementById(target);
	var divBackground=document.getElementById(background);
	if (divTarget && divBackground){
	//	if (!state){
	//		if (divTarget.style.display == 'none'){
	//			var state='1';
	//		}
	//	}
		if (state=='open'){
			divTarget.style.display = "block";
			divBackground.style.display = "block";
//			if (divBackground.parentNode.tagName=='BODY'){divBackground.style.height = divBackground.parentNode.offsetHeight +"px";};
			if (layer){
//			alert('here');
				divTarget.style.zIndex = layer;
				divBackground.style.zIndex = layer-10;
			}
			if (transparency=='solid'){
				divBackground.className = "backgroundScreenSolid";
			} else if (transparency=='transparent'){
				divBackground.className = "backgroundScreen";
			}
		} else {
			divTarget.style.display = "none";
			divBackground.style.display = "none";
		}
	}
}

function tracker(script,mode,loc) {
	document.getElementById('draghandle_1').innerHTML='';
//	document.getElementById('tracker_content').innerHTML='Loading...';
	bgdiv = document.getElementById(loc+'bg');	
	contentdiv = document.getElementById(loc+"content");	
	frame = window.frames["trackerFrame"]; 
	default_content_height = "320px";
	
	var trackerMod='true';//implements page screening with pop-up div
	
	
	if ((mode == "show") || (mode == "edit")) {
		var cw=f_clientWidth();
		var ch=f_clientHeight(); 
		var st=f_scrollTop();
				
		// adjust y pos for y scrolling
		bgdiv.style.top = 50+st+"px";
		
		// clear tracker iframe 
		frame.document.body.innerHTML = "<div style='font-family:Arial,Helvetica,sans-serif; font-size: large; padding: 30px 10px 5px; color: #CEDDE8; text-align: center;'><p style='font-size: 1.4em; padding: 20px 0px;'>Loading...</p><br class='brclear' /></div>"; 
		
		// reset height of content section
		contentdiv.style.height = default_content_height;
		
		if (trackerMod=='true'){popUpDiv('open');}
		
		// show the bg, the content will show because it is not hidden to begin with
		// new Effect.Appear('tracker_bg', { duration: .125 });


		// populate tracker iframe with tracker content
		document.getElementById('trackerFrame').src=script;

	} else if (mode == "close") {
	
		// hide the bg
		bgdiv.style.display = "none";	
		
		if (trackerMod=='true'){popUpDiv('close');}
		
		// clear tracker iframe 
		frame.document.body.innerHTML = ""; 
				
		// reset height of content section
		contentdiv.style.height = default_content_height;		
	}
}

function disableEnterKey(e) {
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}

function selectPackage(nodeNum) {
	msg ='nodeNum='+nodeNum+'\n';
	//alert(msg);

	packagesArray = nodes[nodeNum].packagesArray;
	densitiesArray = nodes[nodeNum].densitiesArray;

	msg+='packagesArray=\n'
	for (x = 0; x < packagesArray.length; ++ x) {
		msg+='['+x+'] '+packagesArray[x]+'\n';
	} 
	msg+='\n';
	msg+='densitiesArray=\n'
	for (x = 0; x < densitiesArray.length; ++ x) {
		msg+='['+x+'] '+densitiesArray[x]+'\n';
	} 
	
	//alert(msg);
	msg="";
		
	theform = document.getElementById('trackerForm');	
	selected=document.getElementById('pkgIDuomID_'+nodeNum).selectedIndex;

	msg+='selected='+selected+'\n';
		
	selectedPkg=document.getElementById('pkgIDuomID_'+nodeNum).selectedIndex;
	pkgIDuomID=document.getElementById('pkgIDuomID_'+nodeNum).options[selectedPkg].value;
		
	pkgID=pkgIDuomID.split("-")[0];
	uomID=pkgIDuomID.split("-")[1];

	msg+='pkgID='+pkgID+'\nuomID='+uomID+'\n';
	
	pkgType = packagesArray [selected] [2];

	msg+='pkgType='+pkgType+'\n';
	
	//alert(msg);
	msg="";
		
	// note, added (pkgType == "d") for exercise
	if ((pkgType == "v") || (pkgType == "d"))  {
		msg="showing density options";
		//alert(msg);
		msg="";
		
		if (densitiesArray . length > 0) {
			newhtml = "<select class=usrdata name=densityID[] id=densityID_"+nodeNum+">\n";
			for (row = 0; row < densitiesArray . length; ++ row) {
				newhtml+= "<option value=" + densitiesArray [row] [0] + " >" + densitiesArray [row] [1] + "</option>\n";
			}
			newhtml+= "</select>\n";
		} else {
			newhtml = "<input type=hidden name=densityID[] id=densityID_"+nodeNum+" value=\"\">\n";
		}
				
	} else {
		newhtml = "<input type=hidden name=densityID[] id=densityID_"+nodeNum+" value=0>";
	}

	//  update the hidden fields with new pkg & uom info
	document.getElementById('packageID_'+nodeNum).value=pkgID;
	document.getElementById('uomID_'+nodeNum).value=uomID;	
	
	// update the UI, putting a select list of densities OR a hidden field with densityID=0
	document.getElementById('nodeDensity_'+nodeNum).innerHTML = newhtml
	
}

function chTab(id,loc,script,tabCount) {
		
	// switch off tab 1
	tab1=document.getElementById('usrNodes_tab1');
	tab1.className='trackerlist_tab_off';

	// switch off tab 2
	tab2=document.getElementById('usrNodes_tab2');
	tab2.className='trackerlist_tab_off';
	
	if (tabCount > 2) {
		// switch off tab 3
		tab3=document.getElementById('usrNodes_tab3');
		tab3.className='trackerlist_tab_off';
	}	
	
	// switch on clicked tab
	clicked_tab=document.getElementById(id);
	clicked_tab.className='trackerlist_tab_on';
		
	// which tab was clicked?
	if (id=='usrNodes_tab1') {				
		// hide search form
		document.getElementById('searchForm_container').style.visibility='hidden';
		document.getElementById('searchForm_container').style.display='none';

		// load favorites
		contentload(loc,script,'true');		
		return;
	} else if (id=='usrNodes_tab2') {
		// clear out favorites display
		document.getElementById(loc).innerHTML = "";
			
		// show search form
		document.getElementById('searchForm_container').style.visibility='visible';
		document.getElementById('searchForm_container').style.display='block';

		return;	
	} else if (id=='usrNodes_tab3') {
		//alert(id);
		// hide search form
		document.getElementById('searchForm_container').style.visibility='hidden';
		document.getElementById('searchForm_container').style.display='none';

		// load favorites
		contentload(loc,script,'true');		
		return;
	}
}


function loadCal(loc,script) {

	// first close tracker if it is open
	div = document.getElementById('tracker_bg');
	if (div.style.visibility == "visible") {
		popUpDiv('close');
		div.innerHTML = "";	
	}	
		
	if (js_debug) {
		msg = "Running loadCal...";
		log(msg);
		msg='loc='+loc;
		log(msg);
		msg='script='+script;
		log(msg);
		msg='----------------------';
		log(msg);
	}
	
	newtext = "<table width=100% height=100% cellpadding=0 cellspacing=0 border=0><tr><td style=\"text-align:center;\"><img src=images/template/v_1.2/loading_2.gif class='loading'></td></tr></center>";
	document.getElementById(loc).innerHTML = newtext;
	contentload(loc,script,'true');
}

function popup(script,mode,loc) {
	bgdiv = document.getElementById(loc+'bg');	
	contentdiv = document.getElementById(loc+"content");	
	default_content_height = "250px";
	contentdiv.style.overflowY='auto';
	
	if ((mode == "show") || (mode == "edit")) {
		var cw=f_clientWidth();
		var ch=f_clientHeight(); 
		var st=f_scrollTop();
		
		if (js_debug) {
			alert('width='+cw+', height='+ch+', scrollTop='+st);
		}
		
		// adjust y pos for y scrolling
		// bgdiv.style.top = 50+st+"px";
				
		// reset height of content section
		contentdiv.style.height = default_content_height;
		
		// show the bg, the content will show because it is not hidden to begin with
		new Effect.Appear(loc+'bg', { duration: .125 });
				
		// populate content		
		contentload(loc+"content",script,'','true');
		
	} else if (mode == "close") {
	
		// hide the bg
		bgdiv.style.display = "none";	
				
		// reset height of content section
		contentdiv.style.height = default_content_height;		
	}
}

function gup(name,url) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( url );
	if( results == null ) { 
		return "null";
	} else {
		return results[1];
	}
}

function subscribeTracker(loc,script,mode,loc2,script2) {
			
	// switch it on or off and update the ui
	// then update the userToolbox trackers list
	contentload2(loc,script,'false',loc2,script2,'false');
		
}


function loadFavsList(mode,loc,script) {
	selected = document.getElementById('nodeClassIDList').selectedIndex;
	nodeClassID = document.getElementById('nodeClassIDList').options[selected].value;
	nodeClassName = document.getElementById('nodeClassIDList').options[selected].text;
	script=script+"&nodeClassID="+nodeClassID+"&nodeClassName="+nodeClassName;
	
	contentload(loc,script,'','true');
}

function log(message) {
    if (!log.window_ || log.window_.closed) {
        var win = window.open("", null, "width=600,height=300," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body style=\"font-family: arial; font-size: 12px;\"><font face=arial size=2></body></html>");
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement("div");
    logLine.appendChild(log.window_.document.createTextNode(message));
    log.window_.document.body.appendChild(logLine);
    //log.window_.focus();
}

function clearFormField(field) {
  if (field.defaultValue==field.value) field.value = ""
}

/*
contentload 
	- tmpElement can be either a STRING or an OBJECT
	tmpElement (object) specifications
	{
		target: dom ID to replace (required) 
		url: url to retrieve data (required)
		evalJS : evaluate javascript after loading dom (default=true)
		message : (pending) if true (boolean) then show default message. if string set target to string.
		onComplete : (pending) function to run upon completion 
	
	}
	-- !! evaluate if target='' or undefined to load the page for the url.
*/
function contentload(tmpElement,theurl,evalJS,evalJSAfter,browser,showLoading,modalTitle,modalWidth) {
	if(typeof(tmpElement)=='object'){
		//***** INITIALIZE object *****
		CARROT.std.debug('contentload = OBJECT ');
		theelement=tmpElement.target
		theurl=tmpElement.url
		if(typeof(tmpElement.evalJS)=='undefined'){
			evalJSAfter=true;
		}else{
			evalJSAfter=tmpElement.evalJS;
		}
		evalJS=false;
		if (showLoading=='undefined'){
			if(typeof(tmpElement.message)=='undefined'){
				showLoading=false;
			}else{
				showLoading='true';
			}
		}
		if(typeof(tmpElement.onComplete)=='function'){
			onComplete=tmpElement.onComplete;
		}else{
			onComplete=false;
		}
	}else{
		
		theelement=tmpElement.replace(/&amp;/gi, "&");
		CARROT.std.debug('contentload = '+typeof(theelement));
		onComplete=false;
	}	
	var error=0;
	if (showLoading == "true") {
			if (document.getElementById('messageDiv[0]_Trackers') && theelement=='dashModuleContent_Trackers'){ // make this work for trackers only for now
				popUpDiv('open','messageDiv[0]_Trackers','backgroundScreen[0]_Trackers');
//				setTimeout("popUpDiv('close','messageDiv[0]_Trackers','backgroundScreen[0]_Trackers')",1000);
			} else if (document.getElementById('messageDiv[0]')) { // make this work for trackers only for now *** && (theelement=='myCarrotContent' || theelement=='settingsContent')
				CARROT.std.pageLoading();
			} else if (tmpElement=='modalContent') {
				CARROT.std.pageLoading('page');
				if (modalTitle && modalWidth) {
					CARROT.std.modalContent(modalTitle,modalWidth); 
				}
			} else {
				//alert(theelement);
				newtext = "<div class='dashModuleBox'><div class='noContent'><p class='title'>Loading...</p><br class='brclear' /></div></div>";
				document.getElementById(theelement).innerHTML = newtext;
			}
		
	}
	
	AjaxRequest.get(
  		{
			'url':theurl,
			'onSuccess':function(req){ 

			if (browser == "Safari" && req.responseText.length > 20208) {
				alert('There is a bug with this browser when viewing a long date range with a lot of data.\nPlease try a different browser or a shorter date range.');
				error=1;
			}
			
			var tmpDiv=document.getElementById(theelement);
			
			if (evalJS && error!=1) {
				 CARROT.std.debug('contentLoad:starting evalJS');
				  
				  //CARROT.std.execDivScripts(tmpDiv);
				  
				  // RegExp from prototype.sonio.net
				  var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
				           
				  var match    = new RegExp(ScriptFragment, 'img');
				  var scripts  = req.responseText.match(match);
				
				    if(scripts) {
				        var js = '';
				        for(var s = 0; s < scripts.length; s++) {
				            var match = new RegExp(ScriptFragment, 'im');
				            js += scripts[s].match(match)[1];
				        }
				        eval(js);
				    }
				   
			}
			//***** SET target div
			//document.getElementById(theelement).innerHTML = req.responseText;
			if(CARROT.browser.isIE){
				tmpDiv.innerHTML = '<span  style="display: none;">&nbsp</span>'+req.responseText;
			}else{
				tmpDiv.innerHTML = req.responseText;
			}
			
			
			if (evalJSAfter && error!=1) {
				CARROT.std.debug('contentLoad:starting evalJSAfter');
				  
				CARROT.std.execDivScripts(tmpDiv);
				  
				  // RegExp from prototype.sonio.net
				  /*
				  var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
				           
				  var match    = new RegExp(ScriptFragment, 'img');
				  var scripts  = req.responseText.match(match);
				
				    if(scripts) {
				        var js = '';
				        for(var s = 0; s < scripts.length; s++) {
				            var match = new RegExp(ScriptFragment, 'im');
				            CARROT.std.debug('evalJS match = '+CARROT.std.dump(scripts[s].match(match)));
				            js += scripts[s].match(match)[1];
				        }				        
				        //CARROT.std.debug('evalJS after = '+js);
				        eval(js);
				    }
				    
				    */
			}
									
			},
			'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
		}
	);
}

function contentload2(theelement,theurl,evalJS,theelement2,theurl2,evalJS2) {

	AjaxRequest.get(
  		{
			'url':theurl,
			'onSuccess':function(req){ 
			if (evalJS) {
				  // RegExp from prototype.sonio.net
				  var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
				           
				  var match    = new RegExp(ScriptFragment, 'img');
				  var scripts  = req.responseText.match(match);
				
				    if(scripts) {
				        var js = '';
				        for(var s = 0; s < scripts.length; s++) {
				            var match = new RegExp(ScriptFragment, 'im');
				            js += scripts[s].match(match)[1];
				        }
				        eval(js);
				    }
			}
			document.getElementById(theelement).innerHTML = req.responseText;
						
			if ((theelement2.length > 0) && (theurl2.length > 0)) {
				//alert('theelement2='+theelement2);
				contentload(theelement2,theurl2,evalJS2);
			}
			
			},
			'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
		}
	);
}



function submitForm(theform,theelement,evalJS,evalJSAfter) {				
	var status = AjaxRequest.submit(
		theform,{
			'onSuccess':function(req){
			   if (evalJS || evalJSAfter) {
				  // RegExp from prototype.sonio.net
				  var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
				           
				  var match    = new RegExp(ScriptFragment, 'img');
				  var scripts  = req.responseText.match(match);
				
				     if(scripts && (evalJS || evalJSAfter)) {
				        var js = '';
				        for(var s = 0; s < scripts.length; s++) {
				            var match = new RegExp(ScriptFragment, 'im');
				            js += scripts[s].match(match)[1];
				        }
				    }
				}
			   
			   if (evalJS) {
				   eval(js);
			   }
			   			     
			   if (theelement != '') {
					var tgtDiv=document.getElementById(theelement)
					CARROT.std.debug('submitForm tgtDiv='+theelement+':typeOf(tgtDiv)='+typeof(tgtDiv));
					if(typeof(tgtDiv)=='object'){
				   		tgtDiv.innerHTML = req.responseText;
					}
				   
				//	if (document.getElementById('messageDashboardSub')){
				//		document.getElementById('messageDashboardSub').innerHTML = req.responseText;
				//		setTimeout("popUpDiv('close','messageDiv[0]','backgroundScreen[0]')",1000);
				//	} else {
				//		document.getElementById(theelement).innerHTML = req.responseText;
				//	}
				}
				   			     
			   if (evalJSAfter) {
				   eval(js);
			   } 
			}
		}
	);
	
	return status;

}

function submitFormPopup(theform,theelement) {
	alert('submitFormPopup');
	
	var status = AjaxRequest.submit(
		theform,{
			'onSuccess':function(req){
				 //document.getElementById(theelement).innerHTML = req.responseText;
				 window.carrotPopup.getElementById(theelement).innerHTML = req.responseText;
			}
		}
	);
	
	return status;

}

function newWindowPopup(URL) {
	if(window.carrotPopup) {
		//window.carrotPopup.location='./';
		window.carrotPopup.focus();
	} else {
		newWindowPopupURL= URL;
		var carrotPopup=window.open(URL,"carrotPopup",'top=7,screenY=7,left=7,screenX=7,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=615,height=440');
		if(navigator.appName.substring(0,8)=="Netscape" || navigator.appName=="Microsoft Internet Explorer") {
    		popup.location=URL;
    		popup.opener=self;
		}
		carrotPopup.focus();
   }
}

function setTag(theTag){
	var theform=document.forms['formSearch'];
	if(theform.search.value==""){
		theform.search.value = theTag;
	}else{
		theform.search.value=theform.search.value + ", " +theTag;
	}
	
	document.formSearch.submit();
}

function usrNodeSearchSubmit(mode,loc,script,e,fieldID) {
	if (mode == 'search') {
		search_string = document.getElementById(fieldID).value;
		script+='&search_string='+search_string;
	} else {
		search_string = '';
	}
	var key;     
	if(window.event)
    	key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     
	
	msg ='mode='+mode+'\n';
	msg+='loc='+loc+'\n';
	msg+='script='+script+'\n';
	msg+='search_string='+search_string+'\n';
	msg+='key='+key+'\n';
	//alert(msg);

	if ((key == 13) || (key == 1)) {
		// hide search form
		document.getElementById('searchForm_container').style.visibility='hidden';
		document.getElementById('searchForm_container').style.display='none';
	
		contentload(loc,script,'true');
		
		return false;
	}
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function openOptions(divToOpen,divToClose){
	
	if (document.getElementById(divToOpen).style.display != 'none'){
		Effect.BlindUp(divToOpen, { duration: .5 });
	} else {
		if (divToClose){ 
			if (document.getElementById(divToClose).style.display != 'none'){
				Effect.BlindUp(divToClose, { duration: .5 });
			}
		}
		Effect.BlindDown(divToOpen, { duration: .5 });
	}
	
}
function toggleDivOpen(divToToggle,buttonSwitch,buttonClass,closeOnly){
	if (document.getElementById(divToToggle).style.display != 'none'){
		Effect.Fade(divToToggle);
		if (buttonClass && buttonSwitch){
			buttonClass=buttonClass+"-off";
			document.getElementById(buttonSwitch).setAttribute("class",buttonClass);
		}
	} else {
		if (closeOnly=='true') { closeOnly='false' } else {
			Effect.Appear(divToToggle);
			if (buttonClass && buttonSwitch){
				document.getElementById(buttonSwitch).setAttribute("class",buttonClass);
			}
		}
	}
	
}

function toggleDivOpenSubmit(divToToggle,buttonSwitch,buttonClass,closeOnly,formToSubmit,formTarget){
	if (document.getElementById(divToToggle).style.display == 'none'){
		submitForm(formToSubmit,formTarget);
	}
	toggleDivOpen(divToToggle,buttonSwitch,buttonClass,closeOnly)
	
}

CARROT.std.dump=function (arr,level) {
	var dumped_text = "";
	if(!level){
		level = 0;
	}
	dumped_text +='<table>';
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "	";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
 		for(var item in arr) {
  			//do not output parents as this will cause recursive issues. add an options array for the function to support exclusions.
  			if(!arr.hasOwnProperty(item) || item=='parent'){
				continue;
			}
	  		var value = arr[item];
	  
	  		if(typeof(value) == 'object') { //If it is an array,
	   			dumped_text +=   "<tr><td valign='top'>" + item + '<br>('+typeof(value)+")</td><td>" + CARROT.std.dump(value,level+1)+ "</td></tr>";
	  		} else {
	   			dumped_text += "<tr><td>" +  item + "</td><td>" + value + "</td></tr>";
	  		}
 		}
	} else { //Stings/Chars/Numbers etc.
 		dumped_text = "<tr><td>"+arr+"</td><td>"+typeof(arr)+"</td></tr>";
	}
	dumped_text +='</table>';
	return dumped_text;
} 


// Copyright (C) 2005-2008 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Re-distribute this code or any part of it.
//     Instead, you may link to the homepage of this code:
//     http://www.php-development.ru/javascripts/dropdown.php
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as part of another product.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind.
// You expressly acknowledge and agree that use of this code is at your own risk.


// ***** Popup Control *********************************************************

// ***** at_show_aux *****

function at_show_aux(parent, child)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child );

  var top  = (c["at_position"] == "y") ? p.offsetHeight +8: 0;
  var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;
  var bottom  = (c["at_position"] == "y") ? -c.offsetHeight -2 : 0;

// offset height removed
  for (; p; p = p.offsetParent)
  {
    left += p.offsetLeft;
  }

  c.style.position   = "absolute";
  c.style.bottom        = bottom+'px';
//  c.style.top        = top+'px';
  c.style.left       = 0+'px';// changed from "left"
  c.style.visibility = "visible";
}

// ***** at_show *****

function at_show()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  at_show_aux(p.id, c.id);
  clearTimeout(c["at_timeout"]);
}

// ***** at_hide *****

function at_hide()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ***** at_click *****

function at_click()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
  return false;
}

// ***** CARROT.std.at_attach *****

// PARAMETERS:
// parent   - id of the parent html element
// child    - id of the child  html element that should be droped down
// showtype - "click" = drop down child html element on mouse click
//            "hover" = drop down child html element on mouse over
// position - "x" = display the child html element to the right
//            "y" = display the child html element below
// cursor   - omit to use default cursor or specify CSS cursor name

CARROT.std.at_attach=function(parent, child, showtype, position, cursor)
{

	if (child == undefined) child = parent+"_child";

	var p = document.getElementById(parent);
	var c = document.getElementById(child);
	if (p && c){
	  if (position == undefined) position = "y";
	  if (showtype == undefined) showtype = "hover";
	
	  p["at_parent"]     = p.id;
	  c["at_parent"]     = p.id;
	  p["at_child"]      = c.id;
	  c["at_child"]      = c.id;
	  p["at_position"]   = position;
	  c["at_position"]   = position;
	
	  c.style.position   = "absolute";
	  c.style.visibility = "hidden";
	
	  if (cursor != undefined) p.style.cursor = cursor; else p.style.cursor = "pointer";
	
	  switch (showtype)
	  {
	    case "click":
	      p.onclick     = at_click;
	      p.onmouseout  = at_hide;
	      c.onmouseover = at_show;
	      c.onmouseout  = at_hide;
	      c.onclick     = at_hide;
	      break;
	    case "hover":
	      p.onmouseover = at_show;
	      p.onmouseout  = at_hide;
	      c.onmouseover = at_show;
	      c.onmouseout  = at_hide;
	      c.onclick     = at_hide;
	      break;
	  }
	}
}


CARROT.std.DomChildNodesDelete= function (ctrl){
  while (ctrl.childNodes[0]){
    ctrl.removeChild(ctrl.childNodes[0]);
  }
}


//make 2 divs equal height
/*
function fixH(one,two) {
if (document.getElementById(one)) {
var lh=document.getElementById(one).offsetHeight;
var rh=document.getElementById(two).offsetHeight;
var nh = Math.max(lh, rh);
document.getElementById(one).style.height=nh+"px";
document.getElementById(two).style.height=nh+"px";
}
}
*/
//make 3 divs equal height
/*
function sortNum(a,b) { return b-a}
*/
/*
function fixH2(one,two,three) {
if (document.getElementById(one)) {
var obj=new Array(3);
var option=[one,two,three];
for(var i=0; i<option.length; i++) {
document.getElementById(option[i]).style.height="auto";
obj[i]=document.getElementById(option[i]).offsetHeight;
nh=obj.sort(sortNum);
}
nh1=nh.splice(1,2);
for(var i=0; i<option.length; i++) {
document.getElementById(option[i]).style.height=nh+"px";
}
}
}
*/
//


//***** Local debug window function *****
CARROT.std.debug=function(msg){
	var target = document.getElementById('debugPane');
	if (target){
		target.innerHTML += msg + ' <br />';
	}
}

/*
function setPageStructure(){
	var a = document.getElementById('leftSide');
	var b = document.getElementById('targetDiv');
	if (a && b){
		b.className = "dashboardWrap"
	} else if (b) {
		b.className = "dashboardWrap noPageSidebar"
	}
}

*/
