var ajaxCallOn = 0;
var ajaxCallOff = 0;
var maintainanceArr = new Array();

function encodeStr(str){
	if(isNaN(str) && !isArray(str)) {
		str = str.replace(/&/g, '##AND##');		
		str = str.replace(/=/g, '##EQUAL##');
		str = str.replace('?', '##QUESTION##');
		str = str.replace('%', '##PERCENT##');
	}
	return str;
}
function decodeStr(str){
	str = str.replace('##AND##', '&');
	str = str.replace('##EQUAL##', '=');
	str = str.replace('##QUESTION##', '?');
	str = str.replace('##PERCENT##', '%');
	
	return str;
}
function AjaxInit(){
	var AjaxObj = false;
	if(window.XMLHttpRequest){
		AjaxObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		AjaxObj=new ActiveXObject("Msxml2.XMLHTTP");
		if (!AjaxObj){
			AjaxObj=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return(AjaxObj);
}
function ajaxVars(){
	this.vars = new Array();
	this.fnVars = new Array();
	this.dbVars = new Array();
	this.sendMethod = 'POST';
	this.gotoFunction = '';
	this.xmlData = '';	
	this.status = 'loadingDiv';
	this.AjaxPostSQL = AjaxPostSQL;
	this.createData = createData;
	this.errorData = errorData;
	this.sqlTracer = sqlTracer;	
	this.xmlOpener = xmlOpener;
	this.maintainance = maintainance;
	this.externalErrors = externalErrors;	
	this.phpFile = GLDocRoot+"lib/ajax.data.php";
}

function AjaxPostSQL(){
	var pageUrl = this.phpFile;
	if(pageUrl.indexOf('?') < 0) {
		pageUrl += '?';
	}else{
		pageUrl += '&';
	}

	pageUrl += 'random=' + Math.random();
	
	var queryStr = '&dbVars=' + this.dbVars;
	for(key in this.vars){
		queryStr += '&' + key + '='  + encodeStr(this.vars[key]);
	}
	if(this.sendMethod == 'GET') {
			pageUrl += queryStr;
	}
	var Ajax = AjaxInit();
	try{
		var callObj = this;
		Ajax.open(this.sendMethod, pageUrl);
		Ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		str = '';
		for(key in Ajax) {
			str += key + "\n";
		}
		Ajax.onreadystatechange = function(){
			var loadingObj = document.getElementById(callObj.status);
			if (Ajax.readyState == 4 && Ajax.status == 200) {
				if(loadingObj){
					loadingObj.innerHTML = 'Done.';
				}
				handleAjax(Ajax, callObj);
			}else if(Ajax.readyState == 1){
				if(loadingObj){
					loadingObj.innerHTML = 'Connecting to server. Please wait...';
				}
			}else if(Ajax.readyState < 4){
				if(loadingObj){
					loadingObj.innerHTML = 'Loading data. Please wait...';
				}
			}else{
				var statusLostObj = document.getElementById('statusLost');
				if(statusLostObj){
					statusLostObj.style.visibility = 'visible';
					statusLostObj.style.display = 'block';
				}
			}
		}
// 		alert(queryStr);
		Ajax.send(queryStr);
	}
	catch(e){
		alert('Error: Unable to contact the server.');
	}
}
function handleAjax(Ajax, callObj){
// 	alert(Ajax.responseXML.documentElement);
	var response = Ajax.responseXML.documentElement;
	var dataObj = response.getElementsByTagName('row');
	var errorObj = response.getElementsByTagName('sqlerror');
	var textObj = response.getElementsByTagName('textdata');
	
	switch(callObj.vars['action']) {
		case "update":
		case "modify":
			if(Ajax.responseText.indexOf('maintainance()') >= 0){
				callObj.maintainance();
				break;
			}
	}	
	dataArr = callObj.createData(dataObj,textObj);
	callObj.errorData(errorObj, dataObj, textObj);
	callObj.xmlData = Ajax.responseText;
	
	
	var xmlLinkObj = document.getElementById('xmlLink');
	if(xmlLinkObj) {
		xmlLinkObj.href = "javascript:void(0);";
		xmlLinkObj.mainObj = callObj;
		xmlLinkObj.onclick = function(e) {
			var hiddenObj = document.getElementById('xmlajaxdata');
			hiddenObj.value = this.mainObj.xmlData;
			this.mainObj.xmlOpener();
		}
	}
	eval(callObj.gotoFunction + '(dataArr, callObj.fnVars)');
}
function createData(rowObj, textObj){
	if(rowObj.length > 0) {
		var str = '';
		var dataArr = new Array();
		var str = '';
		for(var i=0; i<rowObj.length; i++){
			var colObj = rowObj[i].getElementsByTagName('column');
			for(var j=0; j<colObj.length; j++){
				var fieldName = colObj[j].getAttribute('name');
				switch(this.vars['action']) {
					case "update":
					case "modify":
					case 'db_fetch_array':
						if(!dataArr[fieldName]) dataArr[fieldName] = new Array();
						if(!dataArr[j]) dataArr[j] = new Array();
						dataArr[fieldName][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
						dataArr[j][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
					
					case 'db_fetch_row':
						if(!dataArr[j]) dataArr[j] = new Array();
						dataArr[j][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
					
					case 'db_fetch_assoc':
						if(!dataArr[fieldName]) dataArr[fieldName] = new Array();
						dataArr[fieldName][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
				}
			}
		}
		return dataArr;
	}else{
		return textObj[0].firstChild.nodeValue;
	}
}
function externalErrors(){
	var debugDivObj = document.getElementById('debugSql');
	var errorTags = document.getElementsByTagName('p');
	if(errorTags.length > 0) {
		var errLen = errorTags.length;
		for(var i=0; i<errLen; i++){
			var attName = errorTags[0].getAttribute('name');
			if(attName == 'sqlerror'){
				errorTags[0].name = 'ajaxsqlerror';
				errorTags[0].setAttribute('name', 'ajaxsqlerror');
				
				var errorDiv = document.createElement('DIV');
				errorDiv.innerHTML = errorTags[0].innerHTML;
				errorDiv.style.fontFamily = errorTags[0].style.fontFamily;
				errorDiv.style.fontSize = errorTags[0].style.fontSize;				
				errorDiv.style.backgroundColor = errorTags[0].style.backgroundColor;								
				errorDiv.style.color = errorTags[0].style.color;
				errorDiv.style.padding = '5px';				
				errorDiv.setAttribute('name', 'ajaxsqlerror');				

				debugDivObj.insertBefore(errorDiv, debugDivObj.firstChild);
				
				errorTags[0].parentNode.removeChild(errorTags[0]);				
			}
		}
	}
}
function errorData(dataObj, rowObj, textObj){
if (GLDebug==1){
	this.sqlTracer();
	showHideDiv('debugDiv', true);
	
	var debugWinObj = document.getElementById('debugDiv');
	var debugDivObj = document.getElementById('debugSql');
	var debugObj = document.getElementById('debugData');
	
	if(dataObj.length > 0) {
		
		this.externalErrors();
				
		for(key=0; key<dataObj.length; key++){
			var errorData = dataObj[key].getElementsByTagName('p');
			if(errorData[0].firstChild.nodeValue) {
				var errorText = "<DIV NAME=\"ajaxsqlerror\" STYLE=\"padding:5px;"+errorData[0].getAttribute('style')+"\">";
				errorText += errorData[0].firstChild.nodeValue;
				errorText += "</DIV>";
				debugDivObj.innerHTML = errorText + debugDivObj.innerHTML;
			}
		}
		var newOut = '';
		if(rowObj.length) {
			for(var i=0; i<rowObj.length; i++){
				var colObj = rowObj[i].getElementsByTagName('column');
				newOut += '<hr />';
				for(var j=0; j<colObj.length; j++){
					var fieldName = colObj[j].getAttribute('name');
					newOut += '<span style="color: #F00; font-family: arial; font-size:11px;">' + fieldName + '</span>';
					newOut += '<span style="color: #000; font-family: arial;font-size:11px;">=</span>';
					newOut += '<span style="color: #00F; font-family: arial;font-size:11px;">' + colObj[j].firstChild.nodeValue + '</span>';
					newOut += '<br />';
				}
			}
		}else{
			newOut += '<hr />';			
			newOut += '<span style="color: #FF0; font-family: arial;font-size:11px;">' + textObj[0].firstChild.nodeValue + '</span>';
		}
		var debugObj = document.getElementById('debugData');
		if(debugObj) {
			debugObj.innerHTML = newOut + debugObj.innerHTML;
		}
	}
}else{	
	showHideDiv('debugDiv', false);
}		
}

function sqlTracer(){
	
	var debugWinObj = document.getElementById('debugDiv');
	var debugDivObj = document.getElementById('debugSql');
	var debugObj = document.getElementById('debugData');
	var bodyObj = document.getElementsByTagName('BODY')[0];
	
	var formObj = document.createElement('FORM');
	formObj.target = '_blank';
	formObj.method = 'POST';
	formObj.name = 'xmldata';
	formObj.id = 'xmldata';
	formObj.action = GLDocRoot+'index/echodata.php';
	
	var hiddenObj = document.createElement('INPUT');
	hiddenObj.type = 'hidden';
	hiddenObj.name = 'data';
	hiddenObj.id = 'xmlajaxdata';
	formObj.appendChild(hiddenObj);
	
	var hiddenObj = document.createElement('INPUT');
	hiddenObj.type = 'hidden';
	hiddenObj.name = 'filename';
	hiddenObj.value = 'xmldata.xml';
	hiddenObj.id = 'xmlfilename';	
	formObj.appendChild(hiddenObj);
	
	bodyObj.appendChild(formObj);
		
	if(!debugWinObj) {
		var debugWinObj = document.createElement('DIV');
		debugWinObj.id = 'debugDiv';
		debugWinObj.style.position = 'absolute';
		debugWinObj.style.top = '0px';
		debugWinObj.style.width = '40%';
		debugWinObj.style.height = '80%';
		debugWinObj.style.backgroundColor = '#CCCCCC';
		debugWinObj.style.cursor = 'default';
		bodyObj.appendChild(debugWinObj);
			
		var dragDivObj = document.createElement('DIV');
		dragDivObj.id = 'debugDrag';
		dragDivObj.style.backgroundColor = 'buttonFace';
		dragDivObj.style.padding = '2px 10px 2px 10px';
		dragDivObj.style.border = "1px outset buttonShadow";
		dragDivObj.style.cursor = 'move';
		dragDivObj.style.fontSize = '12px';
		dragDivObj.style.fontFamily = 'arial';
		dragDivObj.innerHTML = '<B>SQL Tracer</B>';
		dragDivObj.onmousedown = function(e) {
			var divDrag = new drag;
			moveDiv(e, divDrag, this.parentNode.id);
		}
		dragDivObj.open = true;
		dragDivObj.ondblclick = function(e) {
			if(dragDivObj.open) {
				dragDivObj.open = false;
				showHideDiv('debugSql', false);
				showHideDiv('tracerSpacer', false);
				showHideDiv('debugData', false);
				this.parentNode.style.height = this.parentNode.firstChild.offsetHeight + 'px';
			}else{
				dragDivObj.open = true;
				showHideDiv('debugSql', true);
				showHideDiv('tracerSpacer', true);
				showHideDiv('debugData', true);
				this.parentNode.style.height = '80%';
			}
		}
		debugWinObj.appendChild(dragDivObj);
			
		var debugDivObj = document.createElement('DIV');
		debugDivObj.id = 'debugSql';
		debugDivObj.style.height = '40%';
		debugDivObj.style.padding = '10px';
		debugDivObj.style.overflow = 'auto';
		debugDivObj.style.backgroundColor = '#CCCCCC';
		debugWinObj.appendChild(debugDivObj);
		
		var spacerDivObj = document.createElement('DIV');
		spacerDivObj.id = 'tracerSpacer';
		
		var xmlLinkObj = document.createElement('A');
		xmlLinkObj.href = "javascript:void(0);";
		xmlLinkObj.innerHTML = 'XML output';
		xmlLinkObj.style.fontSize = '11px';
		xmlLinkObj.style.fontFamily = 'arial';
		
		xmlLinkObj.mainObj = this;
		xmlLinkObj.id = 'xmlLink';
		xmlLinkObj.onclick = function(e) {
			this.mainObj.xmlOpener();
		}
		
		spacerDivObj.appendChild(xmlLinkObj);
		
		spacerDivObj.style.textAlign = 'right';		
		spacerDivObj.style.padding = '5px 10px 5px 0px';				
		debugWinObj.appendChild(spacerDivObj);
		
		var newHeight = debugWinObj.offsetHeight - dragDivObj.offsetHeight - dragDivObj.offsetHeight - debugDivObj.offsetHeight - spacerDivObj.offsetHeight;
		
		var debugObj = document.createElement('DIV');
		debugObj.id = 'debugData';
		debugObj.style.backgroundColor = '#CCCCCC';
		debugObj.style.height = newHeight + 'px';
		debugObj.style.padding = '10px';
		debugObj.style.overflow = 'auto';
		debugWinObj.appendChild(debugObj);
	}
	showHideDiv('debugDiv', true);
}

function xmlOpener(){
	var formObj = document.getElementById('xmldata');
}
function empty(){
	ajaxCallOff++;
	hideStatus();
}
function maintainance(){
	if(maintainanceArr[location.href] != 1) {
		maintainanceArr[location.href] = 1;
		alert('Sorry! Data cannot be saved at this moment. Maintainance program is running in one of the branches.');
	}
	hideStatus();
}
function resetMaintainance(){
	maintainanceArr[location.href] = 0;
}
function isArray(obj) {
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false; 
	else 
		return true; 
}
function showHideDiv(id, status){
	var divObj = document.getElementById(id);
	if(divObj) {
		if(status) {
			divObj.style.visibility = "visible"; 
			divObj.style.display = "block"; 
		}else{
			divObj.style.visibility = "hidden"; 
			divObj.style.display = "none"; 
		}
	}
}

function showStatus(){
	document.getElementsByTagName('BODY')[0].style.cursor = 'wait';
	var onObj = document.getElementById('statusOn');
	var offObj = document.getElementById('statusOff');
	if(onObj) {
		onObj.style.visibility = 'visible';
		onObj.style.display = 'block';
	}
	if(offObj) {
		offObj.style.visibility = 'hidden';
		offObj.style.display = 'none';
	}
}

function hideStatus(){
	document.getElementsByTagName('BODY')[0].style.cursor = 'default';
	var onObj = document.getElementById('statusOn');
	var offObj = document.getElementById('statusOff');
	if(offObj) {
		offObj.style.visibility = 'visible';
		offObj.style.display = 'block';
	}
	if(onObj) {
		onObj.style.visibility = 'hidden';
		onObj.style.display = 'none';
	}
}


//** Animated Collapsible DIV v2.0- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** May 24th, 08'- Script rewritten and updated to 2.0.
//** June 4th, 08'- Version 2.01: Bug fix to work with jquery 1.2.6 (which changed the way attr() behaves).
//** March 5th, 09'- Version 2.2, which adds the following:
			//1) ontoggle($, divobj, state) event that fires each time a DIV is expanded/collapsed, including when the page 1st loads
			//2) Ability to expand a DIV via a URL parameter string, ie: index.htm?expanddiv=jason or index.htm?expanddiv=jason,kelly

//** March 9th, 09'- Version 2.2.1: Optimized ontoggle event handler slightly.

var animatedcollapse={
divholders: {}, //structure: {div.id, div.attrs, div.$divref}
divgroups: {}, //structure: {groupname.count, groupname.lastactivedivid}
statusholders: {}, //structure: {[statuselement.id, stype, [opensrc, closedsrc]], $target}
lastactiveingroup: {}, //structure: {lastactivediv.id}


show:function(divids){ //public method
	if (typeof divids=="object"){
		for (var i=0; i<divids.length; i++)
			this.showhide(divids[i], "show")
	}
	else
		this.showhide(divids, "show")
},

hide:function(divids){ //public method
	if (typeof divids=="object"){
		for (var i=0; i<divids.length; i++)
			this.showhide(divids[i], "hide")
	}
	else
		this.showhide(divids, "hide")
},

toggle:function(divid){ //public method
	if (typeof divid=="object")
		divid=divid[0]
	this.showhide(divid, "toggle")
},

addDiv:function(divid, attrstring){ //public function
	this.divholders[divid]=({id: divid, $divref: null, attrs: attrstring})
	this.divholders[divid].getAttr=function(name){ //assign getAttr() function to each divholder object
		var attr=new RegExp(name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
		return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null //return value portion (string), or 0 (false) if none found
	}
	this.currentid=divid //keep track of current div object being manipulated (in the event of chaining)
	return this
},

showhide:function(divid, action){
	var $divref=this.divholders[divid].$divref //reference collapsible DIV
	
	if (this.divholders[divid] && $divref.length==1){ //if DIV exists
		var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any)
		if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group
			if (targetgroup.lastactivedivid && targetgroup.lastactivedivid != divid){ //if last active DIV is set
				this.slideengine(targetgroup.lastactivedivid, 'hide') 
				//alert(targetgroup.lastactivedivid);
				this.LoopSubDiv(targetgroup.lastactivedivid);
			}//hide last active DIV within group first
			this.slideengine(divid, 'show')
			targetgroup.lastactivedivid = divid //remember last active DIV
		}
		else{
			// hide div
			this.LoopSubDiv(divid);
			this.slideengine(divid, action)
		}		
	}
},

CloseSubDivs:function(ldivid){
	var childnodsObj = document.getElementById(ldivid);
	alert(childnodsObj.childNodes.length);
	for(var ix=0; ix < childnodsObj.childNodes.length; ix++){
		alert(childnodsObj.childNodes[ix].innerHTML);
	}
	//var oj = '';
	//var childnodsObj = document.getElementById(ldivid);
	// for(var ix=0; ix < childnodsObj.childNodes.length; ix++){
		// oj = childnodsObj.childNodes[ix];
		// alert(oj.innerHTML);
	// }
	// if(childnodsObj.indexOf("")){
		
	// }
},

LoopSubDiv:function(ldivid){
	var subnodsObj = document.getElementById(ldivid);
	var oj = '';
	var ChildHTML ='';
	var backRefs = new Array();	
	var ClickedIds = '';
		
	if(subnodsObj){
	
		for(var ix=0; ix < subnodsObj.childNodes.length; ix++){
		
			oj = subnodsObj.childNodes[ix];
			ChildHTML = subnodsObj.childNodes[ix].innerHTML;
			
			var browser=navigator.appName;
			var b_version=navigator.appVersion;
			var version=parseFloat(b_version);
			
			if (browser=="Microsoft Internet Explorer"){
				if(b_version.indexOf('Trident')>-1){				
					var re = /IMG id=(.*[^>]) class=hand onclick=/g;
				}else{
					
					var re = /IMG class=hand id=(.*[^>]) onclick=/g;	
				}
			}else{
				var re = /img class="hand" id="(.*[^>])" src=/g;
			}
				   
		    while (matches = re.exec(ChildHTML)) {
			   
			    backRefs.push(matches);
		    }
		    
			var tstring = ''; 
			var Arr = '';
		   for(var y=0;y<backRefs.length;y++){
				
			  	tstring = backRefs[y].toString();
			    Arr = tstring.split(',');
			    if(document.getElementById(Arr[1])){
					//alert(document.getElementById(Arr[1]).src.indexOf('downarrow.gif'));
					
				    if(document.getElementById(Arr[1]).src.indexOf('downarrow.gif') > -1 ){			
						if(ClickedIds.indexOf(document.getElementById(Arr[1]).id) < 0 ){
							ClickedIds += ','+document.getElementById(Arr[1]).id;											
					    	var ImgFunc = document.getElementById(Arr[1]).onclick;
// 							alert(document.getElementById(Arr[1]).id+'--'+document.getElementById(Arr[1]).onclick);	
							
					    	ImgFunc();
						}	
			    	}
			    }
		   } 
		}
	}
	
// 	var Imgobj =document.getElementsByTagName("img");
// 			for(var i=0; i < Imgobj.length; i++){
// 				CurrImg=Imgobj[i]; 			 
// 				 if(CurrImg.src.indexOf('downarrow.gif')>-1){
// 					var OnclickJS = CurrImg.onclick;
// 					 	OnclickJS();
// 				 }				 	
// 		 	}			 
	
},

slideengine:function(divid, action){
	var $divref=this.divholders[divid].$divref
	if (this.divholders[divid] && $divref.length==1){ //if this DIV exists
		var animateSetting={height: action}
		if ($divref.attr('fade'))
			animateSetting.opacity=action
		$divref.animate(animateSetting, $divref.attr('speed')? parseInt($divref.attr('speed')) : 500, function(){
			if (animatedcollapse.ontoggle){
				try{
					animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display'))
				}
				catch(e){
					alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.")
				}
			}
		})
		return false
	}
},

generatemap:function(){
	var map={}
	for (var i=0; i<arguments.length; i++){
		if (arguments[i][1]!=null){ //do not generate name/value pair if value is null
			map[arguments[i][0]]=arguments[i][1]
		}
	}
	return map
},

init:function(){
	var ac=this
	jQuery(document).ready(function($){
		animatedcollapse.ontoggle=animatedcollapse.ontoggle || null
		var urlparamopenids=animatedcollapse.urlparamselect() //Get div ids that should be expanded based on the url (['div1','div2',etc])
		var persistopenids=ac.getCookie('acopendivids') //Get list of div ids that should be expanded due to persistence ('div1,div2,etc')
		var groupswithpersist=ac.getCookie('acgroupswithpersist') //Get list of group names that have 1 or more divs with "persist" attribute defined
// 		alert('init'+persistopenids+'--'+groupswithpersist);
		if (persistopenids!=null) //if cookie isn't null (is null if first time page loads, and cookie hasnt been set yet)
		persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',') //if no divs are persisted, set to empty array, else, array of div ids
		groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',') //Get list of groups with divs that are persisted

		jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object
			this.$divref=$('#'+this.id)
// 			alert(this.getAttr('persist')+'--'+this.id); 
			if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){ //if this div carries a user "persist" setting, or belong to a group with at least one div that does
				var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none'
			}
			else{
				var cssdisplay=this.getAttr('hide')? 'none' : null
			}
			if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains the single array element "all", or this div's ID
				cssdisplay='block' //set div to "block", overriding any other setting
			}
			else if (urlparamopenids[0]=="none"){
				cssdisplay='none' //set div to "none", overriding any other setting
			}
			this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay]))
			this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')]))
			if (this.getAttr('group')){ //if this DIV has the "group" attr defined
				var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={}) //Get settings for this group, or if it no settings exist yet, create blank object to store them in
				targetgroup.count=(targetgroup.count||0)+1 //count # of DIVs within this group
				if (jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains this div's ID
					targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded). Overrides other settings
					targetgroup.overridepersist=1 //Indicate to override persisted div that would have been expanded
				}
				if (!targetgroup.lastactivedivid && this.$divref.css('display')!='none' || cssdisplay=="block" && typeof targetgroup.overridepersist=="undefined") //if this DIV was open by default or should be open due to persistence								
					targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded)
				this.$divref.css({display:'none'}) //hide any DIV that's part of said group for now
			}
		}) //end divholders.each
		jQuery.each(ac.divgroups, function(){ //loop through each group
 			if (this.lastactivedivid && urlparamopenids[0]!="none"){ //show last "active" DIV within each group (one that should be expanded), unless url param="none" 			
				ac.divholders[this.lastactivedivid].$divref.hide()
			}
		})
		if (animatedcollapse.ontoggle){
			jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object and fire ontoggle event
				animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display'))
			})
		}
/* //reserved for future implementation
		var $allcontrols=$('a[rel]').filter('[@rel^="collapse["], [@rel^="expand["], [@rel^="toggle["]') //get all elements on page with rel="collapse[]", "expand[]" and "toggle[]"
		$allcontrols.each(function(){ //loop though each control link
			this._divids=this.getAttribute('rel').replace(/(^\w+)|(\s+)/g, "").replace(/[\[\]']/g, "") //cache value 'div1,div2,etc' within identifier[div1,div2,etc]
			$(this).click(function(){ //assign click behavior to each control link
				var relattr=this.getAttribute('rel')
				var divids=(this._divids=="")? [] : this._divids.split(',') //convert 'div1,div2,etc' to array 
				if (divids.length>0){
					animatedcollapse[/expand/i.test(relattr)? 'show' : /collapse/i.test(relattr)? 'hide' : 'toggle'](divids) //call corresponding public function
					return false
				}
			}) //end control.click
		})// end control.each
*/
		$(window).bind('unload', function(){
// 			ac.uninit()
		})
	}) //end doc.ready()
},

uninit:function(){
	
	var opendivids='', groupswithpersist=''
	jQuery.each(this.divholders, function(){
		if(this.$divref){		
			if (this.$divref.css('display')!='none'){
				opendivids+=this.id+',' //store ids of DIVs that are expanded when page unloads: 'div1,div2,etc'
			}
			if (this.getAttr('group') && this.getAttr('persist'))
				groupswithpersist+=this.getAttr('group')+',' //store groups with which at least one DIV has persistance enabled: 'group1,group2,etc'
		}	
	})
	
	opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '')
	groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '')
	opendivids = '';
	groupswithpersist = '';
// 	alert(opendivids+'--'+groupswithpersist);
	this.setCookie('acopendivids', opendivids)
	this.setCookie('acgroupswithpersist', groupswithpersist)
},

getCookie:function(Name){ 
	var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
},

setCookie:function(name, value, days){
	if (typeof days!="undefined"){ //if set persistent cookie
		var expireDate = new Date()
		expireDate.setDate(expireDate.getDate()+days)
		document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString()
	}
	else //else if this is a session only cookie
		document.cookie = name+"="+value+"; path=/"
},

urlparamselect:function(){
	window.location.search.match(/expanddiv=([\w\-_,]+)/i) //search for expanddiv=divid or divid1,divid2,etc
	return (RegExp.$1!="")? RegExp.$1.split(",") : []
}

}




