var currentSection = "";
var closeSymbol = "[&nbsp;&bull;&nbsp;]";
var openSymbol = "[&nbsp;&nbsp;&nbsp;]";
var clearControl = null;
var elementActionTimer = false;
var stopper = 0;
var filterTimer = 0;

var superSelect_timer = 0;
var superSelect_counter = 0;
var superSelect_update = 1;
var superSelect_limit = 200;
var superSelect_element = null;
var superSelect_id = null;
var superSelect_list = null;
var superSelect_formName = null;

/*
	the Array of animated items.
*/
var elementActionList = new Array();
var moveVal = 15;
var scaleVal = 50;
var animationSpeed = 1;
var output;

var menuOffScreen = -135;
var menuOnScreen = 0;
var closeShutter = 0;
var openShutter = 50;
var actionElements = new Array();
var bFool = false;

var startTime = null;
var pools = "";
var cmSections = new Array("meta","header","menu","body","footer");

var arCTClipboardElementFields = new Array();
var fCTClipboardCurrentField = null;
var pleaseWait = "<img id=\"pleaseWait\" src=\"/images/please-wait.gif\" alt=\"Please Wait\" border=\"0\" style=\"{margin:5px; text-align:center; display:block;}\" align=\"center\" />";
var currentPermSet = "";
var lastVisible = null;

var tabTimer = null;
var arArgs	= new Array();

var closeDialog = "<div style='width:100%; height:18px; line-height:18px; background-color:#ccc; display:block; text-align:right;' id='popOverControls'><a href='javascript:closePopovers();' style='font-weight:bold; padding:0px 5px 0px 5px;'>Close Dialog</a></div>";

var root;


function Init(availableModules, currentModule, actualModule)
{
	setActionElements();
	setDocumentState(actualModule);
	fixDocHeight(100);
	if( typeof(initDHTMLAPI) != "undefined" )
	{
		initDHTMLAPI();
	}

	if( document.getElementById("adRoot") )
	{
		document.getElementById("adRoot").dim = function()
		{
			Effect.Fade( "adRoot", {to:0.25} );

			var adRoot = document.getElementById("adRoot");
			var divs = adRoot.getElementsByTagName("div");
			var i;
			for(i=0;i<divs.length;i++)
			{
				if( divs[i].className.indexOf("scroll") > -1 )
				{
					divs[i].style.overflow = "hidden";
				}
			}
			var txts = adRoot.getElementsByTagName("textarea");
			for(i=0;i<txts.length;i++)
			{
				txts[i].style.overflow = "hidden";
			}
			var selects = adRoot.getElementsByTagName("select");
			for(i=0;i<selects.length;i++)
			{
				//only cache old style if was previously undefined, so we don't overwrite original (correct) value with a double-dim
				if (typeof(selects[i].cachedStyleDisplay) == "undefined")
				{
					selects[i].cachedStyleDisplay = selects[i].style.display;
				}
				selects[i].style.display = "none";
			}
		}
		document.getElementById("adRoot").undim = function()
		{
			Effect.Appear( "adRoot" );
			var adRoot = document.getElementById("adRoot");
			var divs = adRoot.getElementsByTagName("div");
			var i;
			for(i=0;i<divs.length;i++)
			{
				if( divs[i].className.indexOf("scroll") > -1 )
				{
					divs[i].style.overflow = "scroll";
				}
			}
			var txts = adRoot.getElementsByTagName("textarea");
			for(i=0;i<txts.length;i++)
			{
				txts[i].style.overflow = "scroll";
			}
			var selects = adRoot.getElementsByTagName("select");
			for(i=0;i<selects.length;i++)
			{
				// This breaks the display of the select boxes in Safari and can likely be removed 
				//if (typeof(selects[i].cachedStyleDisplay) != "undefined")
				if( false )
				{
					selects[i].style.display = selects[i].cachedStyleDisplay;
				}
				else
				{
					selects[i].style.display = "block";
				}
			}
		}
	}
}

function setActionElements( )
{
	/*
		load all items in this page which can have actions assigned.
	*/
	var tagList = new Array("div","tr","td","img","a","li");
	for(t=0;t<tagList.length;t++)
	{
		var arElements = document.getElementsByTagName( tagList[t] );
		for(a=0;a<arElements.length;a++)
		{
			if( arElements[a].id )
			{
				if( arElements[a].id.indexOf("_Action") > -1 )
				{
					actionElements[actionElements.length] = arElements[a];
				}
			}
		}
	}
	/*
		For clearing focus globally.
	*/
	clearControl = document.getElementById("clearControl");
}

function setDocumentState( forceModule )
{
	/*
		Close any open menus.
	*/
	var i;
	for(i=0;i<actionElements.length;i++)
	{
		if( actionElements[i].id.indexOf("toggleMenu") > -1 )
		{
			var theTarget = document.getElementById( fetchTarget(actionElements[i].id) );
			theTarget.style.left = menuOffScreen+"px";
			theTarget.style.display = "block";
		}
	}
	/*
		determine if we need to do a jump.
	*/
	var loc = document.location.href;
	if( loc != "undefined" &&
			typeof(loc) != "undefined" &&
			loc != null &&
			typeof(loc) != "object" )
	{
		if( loc.indexOf("?") > -1 )
		{
			var querystring = loc.split("?")[1];
			querystring = querystring.split("#")[0];
			var args = querystring.split("&");

			var i;
			for(i=0;i<args.length;i++)
			{
				arArgs[ args[i].split("=")[0] ] = args[i].split("=")[1];
			}
			if( arArgs["func"].indexOf("CoalMedia.editPage") > -1 ||
					arArgs["func"].indexOf("CoalBiz.editCategory") > -1 )
			{
				if( arArgs["func"].indexOf("CoalBiz.editCategory") > -1 )
				{
					if( typeof(arArgs["section"]) == "undefined" )
					{
						arArgs["section"] = "coalbiz";
					}
				}
				if( typeof(arArgs["section"]) != "undefined" )
				{
					currentSection = arArgs["section"];
					snapWithDataHeight( currentSection.toLowerCase()+"Section",true );
				}
				if( arArgs["CBProduct_id"] != "" &&
						typeof(arArgs["CBProduct_id"]) != "undefined" )
				{
					editProducts(arArgs["CBProduct_id"],arArgs["CMPage_id"]);
				}
				if( arArgs["CEElement_id"] != "" )
				{
					if( arArgs["CBProduct_id"] != "" )
					{
						showTab("tabProductElements",arArgs["CBProduct_id"],'coalbiz');
						loadEditElementForm( "edit"+arArgs["CEElement_id"], arArgs["CEElement_id"], -1, arArgs["section"], "" );
					}
					else
					{
						hideTarget("preview"+arArgs["CEElement_id"]);
						loadEditElementForm( "edit"+arArgs["CEElement_id"], arArgs["CEElement_id"], -1, arArgs["section"], "" );
					}
				}
				//initCTClipboard();
			}
			else if( arArgs["func"].indexOf("CoalElements.editElement") > -1 )
			{
				//initCTClipboard();
			}
		}
	}

	if( forceModule != "undefined" &&
			typeof(forceModule) != "undefined" &&
			forceModule != null )
	{
		/*
			Expand the module section.
		*/
		snapWithDataHeight( forceModule.toLowerCase()+"Section",true );
	}
}

function fixDocHeight( iVal )
{
	var theElement;
	theElement = document.getElementById("middle");
	if( theElement )
	{
		theElement.style.height = (theElement.clientHeight+(iVal/2))+"px";
	}
}

function toggleMenu( target )
{
	var theElement = fetchActionable( target );
	if( theElement )
	{
		var theTarget = document.getElementById( fetchTarget( theElement.id ) );
		if( theTarget.offsetLeft > menuOffScreen )
		{
			closeMenu( target );
		}else{
			openMenu( target );
		}
	}
}

/**
 * Function closeMenu
 * If the currently action'd menu is not already closed
 * then close it to the offscreen position.
 */
function closeMenu( target )
{
	var theElement = fetchActionable( target );
	if( theElement )
	{
		var theTarget = document.getElementById( fetchTarget( theElement.id ) );
		if( theTarget.offsetLeft > menuOffScreen )
		{
			addElementAction(theTarget.id,"move",
											 theTarget.offsetLeft,theTarget.offsetTop,
											 menuOffScreen,theTarget.offsetTop);
		}
	}
}

/**
 * Function openMenu
 * If the currently action'd menu is not already open
 * open it to the onscreen position.
 */
function openMenu( target )
{
	var theElement = fetchActionable( target );
	if( theElement )
	{
		var theTarget = document.getElementById( fetchTarget( theElement.id ) );
		if( theTarget.offsetLeft < menuOnScreen )
		{
			addElementAction(theTarget.id,"move",
											 theTarget.offsetLeft,theTarget.offsetTop,
											 menuOnScreen,theTarget.offsetTop);
		}
	}
}

/**
 * Function closeWithDataHeight
 * Closes the current div to the shutter close value.
 */
function closeWithDataHeight( target )
{
	var theElement 	= fetchActionable( target );
	var prefixId		= fetchTarget( theElement.id );
	var theTarget		= document.getElementById( prefixId );
	var srcElement 	= document.getElementById(prefixId+"_Data");
	if( srcElement && theTarget )
	{
		var newHeight	= srcElement.clientHeight;
		fixDocHeight( -1*newHeight );
		newHeight		= closeShutter;

		if( theTarget.clientHeight > closeShutter )
		{
			/*
			addElementAction(theTarget.id,"scaleheight",
											 theTarget.offsetLeft,theTarget.offsetTop,
											 theTarget.clientWidth,newHeight);
			*/
			theTarget.style.height = closeShutter+"px";
		}
	}
}

/**
 * Function openWithDataHeight
 * Opens the current div to the height of it's "data" child
 * with a remainder of one full scale move.
 */
function openWithDataHeight( target )
{
	var theElement 	= fetchActionable( target );
	var prefixId		= fetchTarget( theElement.id );
	var theTarget		= document.getElementById( prefixId );
	var srcElement 	= document.getElementById(prefixId+"_Data");
	if( srcElement && theTarget )
	{
		var newHeight = getSafeClientHeight( srcElement );
		if( newHeight > closeShutter )
		{
			newHeight		= (parseInt(newHeight/scaleVal)*scaleVal)+scaleVal;
		}
		else
		{
			newHeight		= openShutter;
		}

		fixDocHeight( newHeight );

		if( theTarget.clientHeight < newHeight )
		{
			/*
			addElementAction(theTarget.id,"scaleheight",
											 theTarget.offsetLeft,theTarget.offsetTop,
											 theTarget.clientWidth,newHeight);
			*/
			theTarget.style.height = newHeight+"px";
		}
	}
}

/**
 * Function toggleWithDataHeight
 * Reverses height of container object based on height of _Data child
 */
function toggleWithDataHeight( target )
{
	var theElement	= fetchActionable( target );
	var theTarget		= document.getElementById( fetchTarget(theElement.id) );
	var thePhrase		= target.innerHTML.split(" ");
	thePhrase[0] = "";
	thePhrase = thePhrase.join(" ");
	if( theTarget.clientHeight > 0 )
	{
		target.innerHTML = "Open "+thePhrase;
		closeWithDataHeight( target );
		try
		{
			target.innerText = "Open "+thePhrase;
		}catch(e){}
	}
	else
	{
		target.innerHTML = "Close "+thePhrase;
		openWithDataHeight( target );
		try
		{
			target.innerText = "Close "+thePhrase;
		}catch(e){}
	}
}

/**
 * Function toggleTargetVisible
 * Displays the target specified in namespace fashion
 * Example:
 *		popOver.subDiv
 * And takes arguments that the script will attempt to
 * set dynamically inside of a form contained within the
 * last div specified.
 * Example:
 *		popOver.subDiv:param1=value1;param2=value2
 */
function toggleTargetVisible( src, atThisPosition, params )
{
	if( params )
	{
		if( params.indexOf(":") > -1 )
		{
			var arTargets		= params.split(":")[0].split(".");
			var arParams		= params.split(":")[1].split(";");
		}
		else
		{
			var arTargets		= params.split(".");
		}
		var makeVisible	= false;
		var theTarget		= null;

		closePopovers();

		var i;
		for(i=0;i<arTargets.length;i++)
		{
			if( arTargets[i].indexOf("!") == 0 )
			{
				theTarget = document.getElementById(arTargets[i].substr(1,arTargets[i].length));
				if( theTarget )
				{
					theTarget.style.display = "none";
				}
			}else{
				theTarget = document.getElementById(arTargets[i]);
				if( theTarget )
				{
					if( i==0 )
					{
						if( theTarget.style.display == "none" ||
								theTarget.style.display == "" ||
								typeof(theTarget.style.display) == "undefined" )
						{
							makeVisible = true;
						}else{
							makeVisible = false;
						}
						if( atThisPosition )
						{
							theTarget.style.left = src.offsetLeft+"px";
							theTarget.style.top = (getElementPosition(src.id).top-50)+"px";
						}
					}

					if( makeVisible )
					{
						var theLayer = parseInt(theTarget.style.zIndex);
						theTarget.style.zIndex = theLayer+1;
						showTarget(theTarget.id);
					}
					else
					{
						hideTarget(theTarget.id);
					}
				}
			}
		}
		if( theTarget )
		{
			if( theTarget.tagName.toLowerCase() == "form" )
			{
				var i;
				for(i=0;i<arParams.length;i++)
				{
					var arParam = arParams[i].split("=");
					theTarget[arParam[0]].value=arParam[1];
				}
			}
		}
	}
	deactivate();
	return false;
}

function showTarget( target )
{
	var theTarget = document.getElementById(target);
	if( theTarget )
	{
		theTarget.style.display = "block";
	}
}

function hideTarget( target )
{
	var theTarget = document.getElementById(target);
	if( theTarget )
	{
		theTarget.style.display = "none";
	}
}

function copyContents(src, fromItem, toItem )
{
	var theSrc = document.getElementById( fromItem );
	var theTarget = document.getElementById( toItem );
	if( theSrc && theTarget )
	{
		theTarget.innerHTML = theSrc.innerHTML;
	}
	return false;
}

function handleFilePoolFilter( elem, target )
{
	if( elem && target )
	{
		var theTarget = document.getElementById(target);
		if( theTarget )
		{
			var arInputs = document.getElementsByTagName("input");
			var arPools = new Array();
			var i;
			for(i=0;i<arInputs.length;i++)
			{
				if( arInputs[i].id.indexOf("filter_") > -1 &&
						arInputs[i].checked )
				{
					arPools = pools.split(",");
					if( arPools[0] == "" )
					{
						arPools[0] = arInputs[i].value;
					}else{
						arPools.push(arInputs[i].value);
					}
					pools = arPools.join(",");
				}
			}
			loadExistingFileData( theTarget.id );
		}
	}
}

/*
	Function loadEditElementForm
	DEPRECATED - Will be phased out in no more than two versions.
*/
function loadEditElementForm( target, id, idx, sect, funcRdr )
{
	var theTarget = document.getElementById(target);
	if( theTarget )
	{
		var req = newHTR();
		var theTargetRedirect = document.getElementById(target+"_redirect");
		var funcRdr = theTargetRedirect.innerHTML;
		if (funcRdr.length > 0)
		{
			theTargetRedirect.innerHTML = "";
			theTarget.innerHTML = pleaseWait;
			req.onreadystatechange = function(){
				if(( req.readyState == 4 ) && (req.responseText))
				{
					theTarget.innerHTML = req.responseText;
					snapWithDataHeight(sect.toLowerCase());
					initCTClipboard();
				}
			}
			var ceidStr = "&CEElement_id="+id;
			var ceindexStr = "&currentElementIndex="+idx;
			var cesectStr = "&currentElementSection="+sect;
			var funcStr = "&func_redirect="+funcRdr;
			var theURL = "/xml/index.php?func=CoalElements.editElement"+ceidStr+ceindexStr+cesectStr+funcStr;
			req.open("GET",theURL,true);
			req.send(null);
		}
		else
		{
			snapWithDataHeight(sect.toLowerCase());
		}
		showTarget( target );
	}
}

function editElement( id, style, reloadAjaxFunction )
{
	showLargeFloatingBox(1);

	var target		= "largeFloatingBoxTier1";
	var theTarget	= document.getElementById(target);
	//var theTargetRedirect = document.getElementById("edit"+id+"_redirect");
	//var func_redirect;
	//func_redirect			= theTargetRedirect.innerHTML;
	if( theTarget )
	{
		var req			= newHTR();
		//theTarget.innerHTML = pleaseWait;
		req.onreadystatechange = function(){
			if( req.readyState == 4 )
			{
				theTarget.innerHTML = req.responseText;
				snapWithDataHeight(style.toLowerCase());
				initCTClipboard();
			}
		}
		var theURL = "/xml/ajax.php?func=CoalElements.editElement"
								+"&CEElement_id="+id
								+"&currentElementSection="+style
								+"&reloadAjaxFunction="+reloadAjaxFunction;
		req.open("GET",theURL,true);
		req.send(null);
	}
}

function previewElement( id,style )
{
	var target		= "elementContainer"+id;
	var theTarget = document.getElementById(target);
	var theTargetRedirect = document.getElementById("edit"+id+"_redirect");
	if( theTargetRedirect )
	{
		var func_redirect			= theTargetRedirect.innerHTML;
	}
	else
	{
		//go fishing.
		//func_redirectElementForm_377
		var theTargetRedirect	= document.getElementById("func_redirectElementForm_"+style+"_"+id);
		if( theTargetRedirect )
		{
			var func_redirect			= escape(theTargetRedirect.value);
		}
		else
		{
			theTargetRedirect		= document.getElementById("func_redirectElementForm"+377);
			if( theTargetRedirect )
			{
				var func_redirect	= escape(theTargetRedirect.value);
			}
		}
	}
	//prompt("func_redirect",func_redirect);
	if( theTarget )
	{
		var req = newHTR();
		theTarget.innerHTML = pleaseWait;
		req.onreadystatechange = function(){
		if(( req.readyState == 4 ) && (req.responseText))
			{
				theTarget.innerHTML = req.responseText;
				snapWithDataHeight(style.toLowerCase());
			}
		}
		var theURL = "/xml/index.php?func=CoalElements.inlineElementDisplay"
								+"&CEElement_id="+id
								+"&style="+style
								+"&func_redirect="+func_redirect;
		req.open("GET",theURL,true);
		req.send(null);
	}
}

function loadExistingFileData( target )
{
	var theTarget = document.getElementById(target);
	if( theTarget )
	{
		var req = newHTR();
		var theContents = theTarget.parentNode.innerHTML;
		theContents = theContents.substr(0,theContents.indexOf("<OPTION"));
		req.onreadystatechange = function(){
			if( req.readyState == 4 )
			{
				theContents = theContents+req.responseText+"</select>";
				theTarget.parentNode.innerHTML = theContents;
			}
		}
		var theURL = "/xml/index.php?func=CoalTools.fileSelector"
								 +((pools) ? "&pools="+pools : "");
		req.open("GET",theURL,true);
		req.send(null);
	}
}

/**
 * Function addNewModuleItem
 * Handles the query of a new module item form and preperation
 * of hiddenv ariables on that form.
 */
function addNewModuleItem( src, theForm, theModule, theWrapper, CMPage_id )
{
	var theBody = null;
	var popOver = document.getElementById("popOver");
	var theURL  = "/xml/index.php?func="+theModule+".renderAddNewModuleItemForm"
								+"&CMPage_id="+CMPage_id;
	if( theForm )
	{
		theBody = buildPOST(theForm);
	}
	try {
		popOver.innerHTML = pleaseWait;
		popOver.style.display = "block";
	} catch (e) {}
	var req = newHTR();
	req.onreadystatechange = function()
	{
		try {
			if( req.readyState < 3 )
			{
				popOver.innerHTML = pleaseWait;
			}
			if( req.readyState == 3 )
			{
				cleanPopovers();
			}
		} catch (e) {}
		if( req.readyState == 4 )
		{
			//prompt(theURL,req.responseText);
			try {
				popOver.innerHTML += req.responseText;
			} catch (e) {}
			if( src )
			{
				setPosition(src,"popOver");
			}
			hideWait();
		}
	}
	req.open("POST",theURL,true);
	req.send(theBody);
}

/**
 * Function addExistingModuleItem
 * Handles the query of items into a sublist and displaying of that list.
 * src, theForm, CDTable, CDField, CDRowId, styles, jsCallFunction,func_redirect
 */
function addExistingModuleItem( src, theForm, theModule, theWrapper, CMPage_id )
{
	/*
		The new form of popOver management is that each script
		calls the method cleanPopovers() which destroys all
		content inside the popOver div and then grabs a fresh
		set of controls from /scripts/popOverControls.txt and inserts
		that into the div.
	*/
	var theBody = null;
	var popOver = document.getElementById("popOver");
	if( theForm )
	{
		var theURL	= "/xml/index.php?func="+theModule+".renderAddExistingModuleList";
		theBody			= buildPost(theForm);
	}
	else
	{
		var theURL = "/xml/index.php?func="+theModule+".renderAddExistingModuleList"
								+"&CDRowId="+CMPage_id;
	}
	try {
		cleanPopovers();
		popOver.innerHTML += pleaseWait;
	} catch (e) {}
	var req = newHTR();
	req.onreadystatechange = function()
	{
		if( req.readyState == 4 )
		{
			//prompt("req",req.responseText);
			try {
				popOver.innerHTML += req.responseText;
				popOver.style.display = "block";
				popOver.style.left		= (getElementPosition(src.id).left-50)+"px";
				popOver.style.top			= (getElementPosition(src.id).top-50)+"px";
			} catch (e) {}
			//sortables_init();
		}
	}
	req.open("POST",theURL,true);
	req.send(theBody);
	cleanPopovers();
}

function loadAddExistingModuleItem( theModule, theWrapper, CMPage_id )
{
	target		= document.getElementById("moduleData");
	subtarget = document.getElementById("addExisting"+theWrapper);
	subform 	= document.getElementById("addExisting"+theWrapper+"_FormControls");
	q					= subform.q.value;

	if( target )
	{
		target.innerHTML = pleaseWait;

		var req = newHTR();
		req.onreadystatechange = function(){
			if( req.readyState == 4 )
			{
				target.innerHTML = req.responseText;
				subtarget = document.getElementById("addExisting"+theWrapper);
				if( subtarget )
				{
					subtarget.style.display = "block";
				}
			}
		}
		if( q == "Search" )
		{
			q = "";
		}
		var theURL = "/xml/index.php?func=CoalBiz.renderAddExistingModuleList"
								+"&q="+q
								+"&CMPage_id="+CMPage_id;
		req.open("GET",theURL,true);
		req.send(null);
	}
}

/**
 * Function manageBatchRemoveListItemField
 * Adds and removes id from field.value
 */
function manageBatchRemoveListItemField( src, id, index, target )
{
	//`$activeElement.CEElement_id`:`$arrayIndex`
	/* target = 'form.field' */
	/*if( target.indexOf(".") > 0 )
	{
		var targetList = target.split(".");
		var frm = document.getElementById( targetList[0] );
		var fld;
		var i;
		for(i=0;i<frm.length;i++)
		{
			if( frm[i].name == targetList[1] )
			{
				fld = frm[i];
			}
		}
	}
	else
	{
		var fld = document.getElementById( target );
	}*/

	var txt = target.value;
	if(txt != "")
	{
		txt = txt+";";
	}
	if( src.checked == false )
	{
		txt = ";"+txt;
		var txtList = txt.split(";"+id+":"+index+";");
		txt = txtList.join(";");
	}
	else
	{
		txt = txt+id+":"+index;
	}

	if(txt.substr(0,1) == ";")
	{
		txt = txt.substr(1,txt.length);
	}

	if( txt.substr(txt.length-1,1) == ";" )
	{
		txt = txt.substr(0,txt.length-1);
	}

	target.value = txt;
}

/**
 * Function manageModuleItemInField
 * Adds and removes id from field.value
 */
function manageModuleItemInField( src, id, target )
{
	/* target = 'form.field' */
	if( target.indexOf(".") > 0 )
	{
		var targetList = target.split(".");
		var frm = document.getElementById( targetList[0] );
		var fld;
		var i;
		for(i=0;i<frm.length;i++)
		{
			if( frm[i].name == targetList[1] )
			{
				fld = frm[i];
			}
		}
	}
	else
	{
		var fld = document.getElementById( target );
	}

	var txt = fld.value;
	if(txt != "")
	{
		txt = txt+",";
	}
	if( src.checked == false )
	{
		txt = ","+txt;
		var txtList = txt.split(","+id+",");
		txt = txtList.join(",");
	}
	else
	{
		txt = txt+id;
	}

	if(txt.substr(0,1) == ",")
	{
		txt = txt.substr(1,txt.length);
	}

	if( txt.substr(txt.length-1,1) == "," )
	{
		txt = txt.substr(0,txt.length-1);
	}

	fld.value = txt;
}

/**
 * Function submitBatchRemoveModuleItems
 * Submits the form to remove batch items.
 */
function submitBatchRemoveModuleItems( target )
{
	/* target = 'form.field' */
	if( target.indexOf(".") > 0 )
	{
		var targetList = target.split(".");
		var frm = document.getElementById( targetList[0] );
		var fld;
		var i;
		for(i=0;i<frm.length;i++)
		{
			if( frm[i].name == targetList[1] )
			{
				fld = frm[i];
			}
		}
	}
	else
	{
		var fld = document.getElementById( target );
	}

	if( confirm("Will Remove: " + fld.value) )
	{
		if( fld.value.length > 0 )
		{
			frm.submit();
		}
	}
}

/**
 * Function submitBatchRemoveModuleItems
 * Submits the form to remove batch items.
 */
function submitBatchRemoveSectionElements( target )
{
	/* target = 'form.field' */
	if( target.indexOf(".") > 0 )
	{
		var targetList = target.split(".");
		var frm = document.getElementById( targetList[0] );
		var fld;
		var i;
		for(i=0;i<frm.length;i++)
		{
			if( frm[i].name == targetList[1] )
			{
				fld = frm[i];
			}
		}
	}
	else
	{
		var fld = document.getElementById( target );
	}

	if( confirm("Will Remove: " + fld.value) )
	{
		if( fld.value.length > 0 )
		{
			frm.submit();
		}
	}
}

/**
 * Function setupNewModuleItem
 * @param <string> Section
 */
function setNewModuleItem( src, theModule, theWrapper, CMPage_id )
{
	target		= document.getElementById("moduleData");
	subtarget = document.getElementById("addNew"+theWrapper);

	if( target )
	{
		if( target.style.display == "block" )
		{
			closePopovers();
		}
		else
		{
			toggleTargetVisible(src,true,'popOver.'
																	 +subtarget.id/*+'.'
																	 +subform.id*/
																	 +':section='+theModule.toLowerCase());
			//loadAddExistingModuleItem( theModule, theWrapper, CMPage_id );
		}
	}
}

function loadNewModuleItem( theModule, theWrapper, CMPage_id )
{

}


function previewModuleItem( theModuleFunction, theModule, id )
{
	var target = document.getElementById("theModuleItem"+id);
	if( target )
	{
		target.innerHTML = pleaseWait;
		var req = newHTR();
		var theURL = "/xml/index.php?func="+theModuleFunction+id;
		req.onreadystatechange = function(){
			if( req.readyState == 4 )
			{
				target.innerHTML = req.responseText;
				snapWithDataHeight( theModule+"Section",true );
				//sortables_init();
			}
		}
		req.open("GET",theURL,true);
		req.send(null);
	}
}

function editModuleItem( theModuleFunction,theModule,id, CMPage_id, callMethod )
{
	var target = document.getElementById("theModuleItem"+id);
	if( target )
	{
		target.innerHTML = pleaseWait;
		var req = newHTR();
		var theURL = "/xml/index.php?func="+theModuleFunction
								+id
								+"&CMPage_id="+CMPage_id;
		req.onreadystatechange = function(){
			if( req.readyState == 4 )
			{
				target.innerHTML = req.responseText;
				snapWithDataHeight( theModule,"Section",true );
				if( callMethod )
				{
					eval( callMethod );
				}
			}
		}
		req.open("GET",theURL,true);
		req.send(null);
	}
}

function handleElementsPoolFilter( elem )
{
	pools = "";
	var arInputs = document.getElementsByTagName("input");
	var i;
	for(i=0;i<arInputs.length;i++)
	{
		if( arInputs[i].name.indexOf("filter_newElement") > -1 && arInputs[i].checked )
		{
			arPools = pools.split(",");
			if( arPools[0] == "" )
			{
				arPools[0] = arInputs[i].value;
			}else{
				arPools.push(arInputs[i].value);
			}
			pools = arPools.join(",");
		}
	}
	loadAddExistingElementData( );
}

function loadAddExistingElementData( tblRecordSet )
{
	var tblRecordSet = document.getElementById("AddExistingElement_RecordSet");
	tblRecordSet.innerHTML = pleaseWait;
	if( tblRecordSet )
	{
		var frm = document.getElementById("hiddenExistingElementForm");

		req = newHTR();
		req.onreadystatechange=function() {
			if (req.readyState==4) {
			 tblRecordSet.innerHTML = req.responseText;
			}
		}
		var theQue = document.getElementById("que");
		if( theQue )
		{
			theQue = theQue.value;
		}
		if( theQue == "Search" )
		{
			theQue = "";
		}
		/*
		if( frm.section.value.toLowerCase() != "CoalMedia" )
		{
			frm.section.value = "body";
		}
		*/
		var theURL ="/xml/index.php?func=CoalElements.elementSelector"
								+((frm.section.value) ? "&section="+frm.section.value : "")
								+((pools) ? "&pools="+pools : "")
								+"&que="+theQue;
		req.open("GET", theURL, true);
		req.send(null);
	}
}

function addNewElement( src, theForm, CDTable, CDField, CDRowId, styles, jsCallFunction,func_redirect )
{
	//alert("func_redirect: "+func_redirect);
	var popOver = document.getElementById("popOver");
	if( theForm || src )
	{
		//alert(jsCallFunction);
		var req			= newHTR();
		var theURL	= "/xml/index.php?func=CoalElements.renderNewElementForm"
									+"&CDTable="+CDTable
									+"&CDField="+CDField
									+"&CDRowId="+CDRowId
									+"&styles="+styles
									+"&jsCallFunction="+escape(jsCallFunction)
									+"&func_redirect="+escape(func_redirect);
		if( theForm )
		{
			var theBody = buildPOST(theForm);
		}

		cleanPopovers();

		req.onreadystatechange = function()
		{
			if( req.readyState == 4 )
			{
				try {
					popOver.innerHTML += req.responseText;
					popOver.style.display = "block";
					centerOnWindow('popOver');
				} catch (e) {}
				//prompt("popOver",popOver.innerHTML);
				/*
				if( src )
				{
					if( src.id )
					{
						var pos = getElementPosition(src.id);
						popOver.style.left = pos.left-50+"px";
						popOver.style.top = pos.top-50+"px";
					}
				}
				*/
			}
		}
		if( theForm )
		{
			req.open("POST", theURL, true);
			req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			req.send(theBody);
		}
		else
		{
			req.open("GET",theURL,true);
			req.send(null);
		}
	}
}

function setElementTypes( theSection )
{

	var theSelect = document.getElementById("elementType_New");
	if( theSelect )
	{
		req = newHTR();
		req.onreadystatechange=function() {
			if (req.readyState==4) {
				theSelect.innerHTML = "<select name=\"elementType\" onchange=\"setNewElementType('ElementForm_New');\"><option value=\"\">Select a Template</option>"+req.responseText+"</select>";
			}
		}
		var theURL ="/xml/index.php?func=CoalElements.renderNewElementForm&styles="
								+theSection;
		req.open("GET", theURL, true);
		req.send(null);
	}
}

function setNewElementType( theFormId )
{
	if( theFormId )
	{
		var theTarget = document.getElementById("AddNewElement_RecordSet");
		theTarget.innerHTML = "";


		var theForm 	= document.getElementById("AddNewElement_FormControls");
		var thePageId = theForm.CMPage_id.value;
		var theElementType = theForm.elementType[theForm.elementType.selectedIndex].value;
		var theElementSection = theForm.section.value;
		var theURL 	="/xml/index.php?func=CoalElements.addElement&funcsub=blankForm"
								 +"&elementType="+theElementType
								 +"&elementSection="+theElementSection;
		var theBody	= ("?func=CoalMedia.addPageElement&status=clearCache"
									+"&elementAdded=[ELEMENT_ID]"
									+((thePageId)
														? ("&CMPage_id="+thePageId) : "" )
									+((theElementType)
														? ("&elementType="+theElementType) : "" )
									+((theElementSection)
														? ("&section="+theElementSection.toLowerCase()) : "" ) );

		req = newHTR();
		req.onreadystatechange=function() {
			if (req.readyState==4) {
			 theTarget.innerHTML += req.responseText;
			 var frm = document.getElementById( theFormId );
			 frm.func_redirect.value = theBody;
			}
		}
		req.open("POST", theURL, true);
		req.send(null);
	}
	else
	{
	}
}

function repaintWindow()
{
	document.scrollTo(window.pageXOffset,window.pageYOffset+1);
	document.scrollTo(window.pageXOffset,window.pageYOffset-1);
}

function fetchTarget( target )
{
	return target.substr(0,target.indexOf("_Action"));
}

/**
 * Nested menu control
 */
function toggleMenuGroupVisibility( target )
{
	/**
	 * replace getElementById with a multi browser getElementById
	 */
	var theElement = document.getElementById(target);
	if( theElement )
	{
		var theIndicator = document.getElementById(target+"_Indicator");
		if( theElement.style.display == "none" )
		{
			theElement.style.display = "block";
			theIndicator.innerHTML = openSymbol;
		}else{
			theElement.style.display = "none";
			theIndicator.innerHTML = closeSymbol;
		}
		clearControl.focus();
		clearControl.blur();
	}
}

/**
 * Cookie control
 */
function addKey( setName, keyValue )
{
	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	if( getCookie(setName) ){
		arSet = getCookie(setName).split(".");
	}else{
		arSet = new Array();
	}
	arSet[arSet.length] = (keyValue);
	setCookie(setName,arSet.join("."),now);
}
/**
 * I'm the cookie monster
 */
function delKey( setName, keyValue )
{
	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

	arSet = getCookie(setName).split(".");
	if( !arSet.length ){ arSet = new Array(); }
	arSet = filterArray( arSet, keyValue );
	strSet = arSet.join(".");
	if( strSet == "" )
	{
		deleteCookie(setName);
	}
	setCookie(setName,strSet,now);
}

/**
 * Non animated expansion of page sections - COALMEDIA
 * Will Only Open
 * target must contain "Section" or it will attempt to match.
 */
function snapWithDataHeight( target )
{
	if( typeof(target) == "undefined" || target == "" )
	{
		target = currentSection.toLowerCase()+"Section";
	}
	if( target )
	{
		if( target.indexOf("Section") == -1 )
		{
			target = target.toLowerCase()+"Section";
		}
		var theElement = document.getElementById(target);
		if( theElement )
		{
			var arChildren = theElement.childNodes;
			var i;
			for(i=0;i<arChildren.length;i++)
			{
				var obj = arChildren[i];
				if( obj.id )
				{
					if( obj.id.indexOf("_Data") > -1 )
					{
						var openVal = getSafeClientHeight( obj );
						openVal = parseInt(openVal/(scaleVal))*(scaleVal)+(scaleVal*2);
						break;
					}
				}else{
					openVal = openShutter;
				}
			}
			if( theElement.clientHeight+openVal >= theElement.clientHeight )
			{
				fixDocHeight( openVal );
			}
			else
			{
				fixDocHeight( openVal*-1 );
			}
			theElement.style.height = openVal+"px";
		}
	}
}

/**
 * invisible form submission for adding an existing element to a page -> COALMEDIA
 */
function sendAddExistingElement( elementID )
{
	if( elementID )
	{
		var frm = document.getElementById("hiddenExistingElementForm");
		frm.elementAdded.value = elementID;
		frm.submit();
	}
}

/**
 * toggle highlight -- needs investigation
 *
 * this is used for highlights on mouse over, probably
 * needs to be refactored in such a way that if the currently
 * moused-over element is able to be highlighted, then
 * highlight, otherwise, do nothing (but always remove the last
 * highlight)
 *
 */
function hiliteRow( target )
{
	var theElement = document.getElementById(fetchTarget(target.id));
	var arElements = document.getElementsByTagName("tr");
	var i;
	for(i=0;i<arElements.length;i++)
	{
		if( arElements[i].id != target )
		{
			if( arElements[i].className.indexOf(" hilite") > -1 )
			{
				arElements[i].className =
							arElements[i].className.substr(
														0,
														arElements[i].className.indexOf(" hilite")
																						);
			}
		}
	}

	if( theElement.className.indexOf(" hilite") == -1 )
	{
		theElement.className += " hilite";
	}
}

/**
 * Function cleanPopovers()
 * Scrubs the contents of popOver except for tpopOverControls.
 */
function cleanPopovers()
{
	var popOver = document.getElementById("popOver");
	try {
		popOver.innerHTML = closeDialog;
	}catch(e){}
	/*
	var req = newHTR()
	var theURL = "/scripts/popOverControls.txt";
	req.onreadystatechange = function()
	{
		if( req.readyState == 4 && req.responseText )
		{
			//prompt(theURL,req.responseText);
			popOver.innerHTML = req.responseText;
		}
	}
	req.open("POST",theURL,false);
	req.send(null);
	*/
}

/**
 * hides the "popOver" element
 */
function closePopovers()
{
	var popOver = document.getElementById("popOver");
	if( popOver )
	{
		popOver.style.display = "none";
		var i;
		for(i=0;i<popOver.childNodes.length;i++)
		{
			if( typeof(popOver.childNodes[i].id) != "undefined"
					&& popOver.childNodes[i].id != "undefined" )
			{
				if( popOver.childNodes[i].id.toLowerCase().indexOf("add") == 0 )
				{
					popOver.childNodes[i].style.display = "none";
				}
			}
		}
	}
	var moduleData = document.getElementById("moduleData");
	if( moduleData )
	{
		var i;
		for(i=0;i<moduleData.childNodes.length;i++)
		{
			if( typeof(moduleData.childNodes[i].id) != "undefined"
					&& moduleData.childNodes[i].id != "undefined" )
			{
				if( moduleData.childNodes[i].id.toLowerCase().indexOf("add") == 0 )
				{
					moduleData.childNodes[i].style.display = "none";
				}
			}
		}
	}
}

function formReload( theForm, theTarget, func )
{
	var theForm = document.getElementById(theForm);
	var theTarget = document.getElementById(theTarget);
	if( theForm && theTarget )
	{
		var req = newHTR();
		if( func )
		{
			var theURL = "/xml/index.php?func="+func;
		}
		else
		{
			var theURL = "/xml/index.php?func="+theForm.CTForm_func.value;
		}
		var theBody= buildPOST(theForm.id,req);
		theTarget.innerHTML = pleaseWait;
		req.onreadystatechange = function()
		{
			if( req.readyState==4 )
			{
				var renderable = req.responseText;
				if( renderable.indexOf('<div id="'+theTarget.id+'">') > -1 )
				{
					var renderArray = renderable.split("\n");
					renderArray[0] = "";
					renderArray[ renderArray.length ] = "";
					renderable = renderArray.join("");
				}
				theTarget.innerHTML = renderable;
				//sortables_init();
			}
		}
		req.open("POST",theURL,true);
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		req.send(theBody);
	}
	else
	{
		alert("Invalid reference to dom object.");
	}
	return false;
	/*
	CTForm_submitId=5h10qmt29xntj78
	&CTForm_formId=toolsDBSearchForm
	&CTForm_func=CoalTools.searchForm
	&CDTable=log_table
	&CDFieldName[]=ident
	&CDFieldOperator[]=%3D
	&CDFieldValue[]=CError
	&CDOrderBy=id
	&CDOrderDirection=DESC
	&LimitOffset=0
	&LimitLength=10
	&LooseQuery=
	*/
}


/* Function ManageColumnVisibility
 * @param field
 */
function ManageColumnVisibility( fromTable, theField )
{
	var isCell = 0;
	var theTable = document.getElementById(fromTable);
	var i;
	for(i=0;i<theTable.childNodes.length;i++)
	{
		if(theTable.childNodes[i].tagName == "TBODY" )
		{
			for(r=0;r<theTable.childNodes[i].childNodes.length;r++)
			{
				if( theTable.childNodes[i].childNodes[r].tagName == "TR" )
				{
					isCell = 0;
					for(c=0;c<theTable.childNodes[i].childNodes[r].childNodes.length;c++)
					{
						if( c == ((theField+1)*2) &&
								theTable.childNodes[i].childNodes[r].childNodes[c].tagName == "TD" )
						{
							if(getObjectWidth(theTable.childNodes[i].childNodes[r].childNodes[c]) > 22)
							{
								theTable.childNodes[i].childNodes[r].childNodes[c].style.width = "22px";
							}
							else
							{
								theTable.childNodes[i].childNodes[r].childNodes[c].style.width = "100px";
							}
						}
						isCell = isCell+1;
					}
				}
			}
		}
	}
}

/*
function escapeEnter( src )
{
	var e = event;
	alert(e.keyCode);
	event.cancelBubble();
	return false;
}
*/

/*
 *	Function send_form_reload
 *	@param formId					- the form you are submitting.
 *	@param reloadIntoDiv	- the div into which you want the content drawn.
 */
function send_form_reload( formId, reloadIntoDiv )
{
	formId = ''+formId+'';
	var theForm = document.getElementById(formId);
	if( reloadIntoDiv.indexOf(":") == -1 )
	{
		var theDiv = document.getElementById( reloadIntoDiv );
	}
	if( typeof(theForm) != "undefined" )
	{
		var theURL 	= "/xml/index.php?func="+theForm.CTForm_func.value;
		var req			= newHTR();
		var theBody	= buildPOST( formId, req );
		theForm.style.display = "none";
		if( reloadIntoDiv.indexOf(":") == -1 )
		{
			//alert(formId);
			//return false;
			theDiv.innerHTML += pleaseWait;
		}
		req.onreadystatechange = function() {
			if( req.readyState == 4 )
			{
				if( req.responseText.indexOf("ERROR") > -1 )
				{
					alert("XML Request Error"+req.responseText);
				}
				else
				{
					//alert(reloadIntoDiv);
					if( reloadIntoDiv.indexOf(":") > -1 )
					{
						var method = reloadIntoDiv.split(":");
						if( method[0] == "call" )
						{
							var theMethod = method[1]+";";
							theMethod = theMethod.replace("#","\'");
							eval( theMethod );
						}
					}
					else
					{
						try {
							if( typeof(theDiv) == "undefined" )
							{
								var theDiv = document.getElementById("popOver");
								cleanPopovers();
								theDiv.innerHTML += req.responseText;
							}
							else
							{
								theDiv.innerHTML = req.responseText;
							}
						} catch (e) {}
						//sortables_init();
					}
				}
			}
		}

		req.open("POST", theURL, true);
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		req.send(theBody);
	}
	return false;
}

/**
 * Toggles the display of "Add Existing Element" -> COALMEDIA
 */
function addElementPopover( evt, actionType )
{
	var popOver = document.getElementById("popOver");
	var source	= document.getElementById(actionType+"_Action");
	var theTop	= evt.clientY+10;
	try {
		popOver.style.left	= source.offsetLeft+"px";
		popOver.style.top		= (theTop)+"px";
	} catch (e) {}
	if( actionType.indexOf("AddNewElement") > -1 )
	{
		var theForm = document.getElementById("AddNewElement_Wrapper");
		var theWink = document.getElementById("AddExistingElement_Wrapper");
		if(theForm.style.display == "block")
		{
			try {
				popOver.style.display = "none";
			} catch (e) {}
			theForm.style.display = "none";
		}else{
			theForm.style.display = "block";
			try {
				popOver.style.display = "block";
			} catch (e) {}
		}
		theWink.style.display = "none";
	}else{
		var theForm = document.getElementById("AddExistingElement_Wrapper");
		var theWink = document.getElementById("AddNewElement_Wrapper");
		if(theForm.style.display == "block")
		{
			try {
				popOver.style.display = "none";
			} catch (e) {}
			theForm.style.display = "none";
		}else{
			theForm.style.display = "block";
			try {
				popOver.style.display = "block";
			} catch (e) {}
		}
		theWink.style.display = "none";
	}
}

/**
 * debugger
 */
function toolbarMouseOver( target )
{
	alert(target);
}

/**
 * returns nearest parent (or this object) that is actionable
 *
 * needs to be rewritten for proper functionality
 */
function fetchActionable( target )
{
	var actionID = (target.name) ? target.name : target.id;
	while( typeof(actionID)=="undefined" )
	{
		target = target.parentNode;
		actionID = (target.name) ? target.name : target.id;
	}
	if( actionID.indexOf("_Action") > -1 )
	{
		return target;
	}
	return false;
}

/**
 * Adds (or replaces) an action to the action queue)
 *
 * Starts timer if timer is not already active
 */
function addElementAction( id, method, x, y, nx, ny, nextAction )
{
	var i;
	for(i=0;i<elementActionList.length;i++)
	{
		if( elementActionList[i] )
		{
			if( elementActionList[i].actionItem == id )
			{
				elementActionList.splice(i,1);
			}
		}
	}
	elementActionList[elementActionList.length] =
		{actionItem:id,actionMethod:method,sx:x,sy:y,tx:nx,ty:ny};
	if( elementActionTimer == false )
	{
		elementActionTimer = setInterval(timerAction,animationSpeed);
	}
}

/**
 * mother of all action handlers
 */
function timerAction()
{
	/*
		sorts through an array of actions:
		[i] = {actionItem:"id",actionMethod:"move|scale",x:"srcX",y:"srcY",tX:"targetX",tY:"targetY"}
	*/
	var i;
	for(i=0;i<elementActionList.length;i++)
	{
		var theElementItem = elementActionList[i];
		if( theElementItem )
		{
			var theElement = document.getElementById( theElementItem.actionItem );
			if( theElementItem.actionMethod == "move" )
			{

				if( parseInt(theElement.offsetLeft) > parseInt(theElementItem.tx) )
				{
					theElement.style.left = (theElement.offsetLeft-moveVal)+"px";
				}else if(parseInt(theElement.offsetLeft) < parseInt(theElementItem.tx)){
					theElement.style.left = (theElement.offsetLeft+moveVal)+"px";
				}
				if(theElement.offsetTop > theElementItem.ty )
				{
					theElement.style.top = theElement.offsetTop-moveVal+"px";
				}else if(theElement.offsetTop < theElementItem.ty){
					theElement.style.top = theElement.offsetTop+moveVal+"px";
				}
				if( (theElement.offsetLeft == elementActionList[i].tx) &&
						theElement.offsetTop == elementActionList[i].ty )
				{

					elementActionList[i] = false;
				}
			}else if( theElementItem.actionMethod.indexOf("scale") > -1 ){
				if( theElementItem.actionMethod.indexOf("height") > -1 )
				{
					if( theElement.clientHeight < theElementItem.ty )
					{
						theElement.style.height = (theElement.clientHeight+(scaleVal))+"px";
					}else if( theElement.clientHeight > theElementItem.ty ){
						theElement.style.height = (theElement.clientHeight-(scaleVal))+"px";
					}
					if( theElement.clientHeight == theElementItem.ty )
					{
						elementActionList[i] = false;
					}
				}
			}
		}
	}
	elementActionList = filterArray(elementActionList,false);
	if( elementActionList.length == 0 )
	{

		clearInterval( elementActionTimer );
		elementActionTimer = false;
	}
}

function filterArray( theList, theItem )
{
	var i;
	for(i=0;i<theList.length;i++)
	{
		if( theList[i] == theItem )
		{
			theList.splice(i,1);
		}
	}
	return theList;
}

function inArray( theList, theItem )
{
	var i;
	for(i=0;i<theList.length;i++)
	{
		if( theList[i] == theItem )
		{
			return i;
		}
	}
	return -1;
}

function deactivate()
{
	clearControl.focus();
	clearControl.blur();
}



/********************************************************************
 ** CONTRIBUTED *****************************************************
 ********************************************************************
 *******************************************************************/

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

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

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

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}


function getElementPosition(elemID) {
	var offsetTrail = document.getElementById(elemID);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 &&
		typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop};
}

function getSafeClientHeight( theObject )
{
	var nav = navigator.userAgent.indexOf("MSIE");
	if( nav > -1 )
	{
		return theObject.offsetHeight;
	}else{
		return theObject.clientHeight;
	}
}

function inspect( theElement )
{
	str = "";
	for( var elem in theElement.getAttributes() )
	{
		str += elem + "::" + theElement.getAttribute(elem);
	}
	alert(str);
}

/*
*/
function newHTR()
{
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function validateElement( src )
{
	var src = document.getElementById(src);

	if( src )
	{
		if( src.CEElement_copy ){
			var doTest	= src.CEElement_copy[src.CEElement_copy.selectedIndex].value;
		}
		else
		{
			var doTest = -1;
		}
		var formFunc = src.CTForm_func.value;
		if( doTest == -1 &&
				formFunc.indexOf("addElement") == -1 )
		{
			return true;
		}
		else
		{
			if( src.CEElement_title.value != '' )
			{
				var theURL = "/xml/index.php?func=CoalElements.validateTitle&newtitle="
										+escape(src.CEElement_title.value);
				req = newHTR();
				req.onreadystatechange=function() {
					if (req.readyState==4) {
						if( req.responseText.indexOf("true") > -1 )
						{
							src.Submit.disabled = false;
							return true;
						}
						else
						{
							alert("Element Title Conflict!\n"
										+"\tThe Element you are editing conflicts\n"
										+"\twith another element already in the system.\n"
										+"\tPlease choose a new `Element Title`\n"
										+"\tfor this element and proceed.\n");
							src.Submit.disabled = true;
							return false;
						}
					}
				}

				req.open("GET", theURL, false);
				req.send(null);
			}
		}
	}
}
//			 showAddExistingElement('coalbizSectionAddExistingElement_Action','cbproducts','CBProduct_elements','1','html,body','');
function showAddExistingElement(src, CDTable, CDField, CDRowId, style, filterOut,reloadFunc)
{
	/*

	*/
	if( typeof(src) == "string" )
	{
		src = document.getElementById(src);
	}
	if( CDTable &&
			CDField &&
			CDRowId &&
			style )
	{
		//alert("Required Parameters Sent");
		var req = newHTR();
		var theForm = document.getElementById("searchExistingElements");
		if( typeof(theForm) != "undefined" &&
				theForm != "undefined" &&
				theForm != null )
		{
			//alert("Form Submitted");
			var hideDiv = document.getElementById("AddExistingElementWrapper");
			var i;
			for(i=0;i<hideDiv.childNodes.length;i++)
			{
				if( hideDiv.childNodes[i].style )
				{
					hideDiv.childNodes[i].style.display = "none";
				}
			}
			var theURL = "/xml/index.php?func="+theForm.CTForm_func.value;
			theForm.style.value = style;
			theForm.filter.value = filterOut;
			var theBody= buildPOST( "searchExistingElements", req );
			theForm.style.display = "none";
		}
		else
		{
			//alert("No valid form, initializing reloadFunc: "+reloadFunc);
			if( reloadFunc == "undefined" ||
					typeof(reloadFunc) == "undefined" ||
					reloadFunc == null )
			{
				if( CDField )
				{
					if( CDField.indexOf("CMPage_") > -1 )
					{
						theSection = CDField.substring(7,CDField.indexOf("Elements"));
						//remove #Section
						var currentLoc = document.location.href;
						currentLoc = currentLoc.split("#");
						currentLoc = currentLoc[0];
						reloadFunc = "call:document.location.href="
												+")("+currentLoc
												+"&section="+theSection+")(";
					}
					else
					{
						reloadFunc = "call:document.location.href=document.location.href";
					}
					//alert(reloadFunc);
				}
				else
				{
					reloadFunc = "call:document.location.href=document.location.href";
				}
			}
			var theURL = "/xml/index.php?func=CoalElements.renderAddExistingElementForm"
									+"&CDTable="+CDTable
									+"&CDField="+CDField
									+"&CDRowId="+CDRowId
									+"&style="+style
									+"&filter="+filterOut
									+"&reloadFunc="+escape(reloadFunc);
		}
		//prompt("theURL",theURL);
		try {
			var popOver = document.getElementById("popOver");
			popOver.innerHTML = pleaseWait;
			popOver.style.display = "block";
			setPosition(src,"popOver");
		} catch (e) {}
		req.onreadystatechange = function() {
			if( req.readyState == 3 )
			{
				//alert("Cleaning Popovers");
				cleanPopovers();
			}
			if( req.readyState == 4 )
			{
				//prompt(theURL,req.responseText);
				cleanPopovers();
				try {
					popOver.innerHTML = popOver.innerHTML+req.responseText;
				} catch (e) {}
				hideWait();
				//sortables_init();
			}
		}
		if( theBody )
		{
			//alert("Posting");
			req.open("POST",theURL,true);
			req.send(theBody);
		}
		else
		{
			//alert("Getting");
			req.open("GET",theURL,true);
			req.send(null);
		}
	}
}

function hideWait()
{
	var waitImage = document.getElementById("pleaseWait");
	if( waitImage )
	{
		if( waitImage.style )
		{
			waitImage.style.display = "none";
		}
	}
}

function submitAddExistingElements( theFormName, reloadCommand )
{
	var theForm = document.getElementById( theFormName );
	if( theForm )
	{
		var theURL 	= "/xml/index.php?func=CoalElements.addExistingElements";
		var req			= newHTR();
		var theBody	= buildPOST( theFormName, req );
		req.onreadystatechange = function() {
			if( req.readyState == 4 )
			{
				if( req.responseText.indexOf("ERROR") > -1 )
				{
					//prompt("The Following is Error Output Information","XML Request Response: "+req.responseText+"\nURL: "+theURL+"\nBody: "+theBody+"\n\n");
					//alert("Failure: "+ req.responseText );
					document.location.href = document.location.href;
				}
				else
				{
					/*
					Tuesday, May 3, 2005 8:57:04 PM TCI
						When this form is drawn we pass a reloadFunc
						to recurse this method into xmlhtr.
						Nice, eh?
					*/
					if( typeof(reloadCommand) == "string" && reloadCommand != "" )
					{
						//alert(reloadCommand);
						if( reloadCommand.indexOf("call:") > -1 )
						{
							reloadCommand = reloadCommand.substring(5,reloadCommand.length);
						}
						if( reloadCommand.indexOf(")(") > -1 )
						{
							reloadArray = reloadCommand.split(")(");
							reloadCommand = reloadArray.join("'");
						}
						/*
						document.location.href
							=
								'http://gtdev.coalmarch.com/admin/index.php?func=CoalMedia.editPage
																													 &id=1
																													 &section=Menu#MenuLOC
																													 &section=menu&section=menu'
						*/
						if( reloadCommand.indexOf(";") < 0 )
						{
							reloadCommand = reloadCommand+";";
						}
						eval(reloadCommand);
						//alert("submitAddExistingElements: "+reloadCommand);
					}
					else
					{
						document.location.href = document.location.href;
					}
				}
			}
		}

		req.open("POST",theURL,true);
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		req.send(theBody);
	}
	else
	{
		alert("Cannot Find Form Input: "+theFormName);
	}
	return false;
}

/*
 *	Function sendPageRank
 *	@param CMPage_id
 *	@param Offset
 */
function sendPageRank(CMPage_id,Offset)
{
	if( typeof(Offset) != "undefined" &&
			Offset != "undefined" &&
			Offset != null )
	{
		var req			= newHTR();
		var theURL	= "/xml/index.php?func=CoalMedia.quickRank"
									+"&CMPage_id="+CMPage_id
									+"&newValue="+Offset;
		req.onreadystatechange = function()
		{
			if( req.readyState == 4 )
			{
				//prompt(theURL,req.responseText);
				if( req.responseText.indexOf("ERROR") > -1 )
				{
					alert("The Page Rank could not be Updated");
				}
				else
				{
					//alert("The Page Rank has been Updated.");
				}
			}
		}

		req.open("GET",theURL,true);
		req.send(null);
	}
}

/*
 *
 */
function hideElement( id, index )
{
	var target	= document.getElementById("sectionElementGroup"+id+"_"+index);
	if( target )
	{
		target.style.display = "none";
	}
	else
	{
		alert("sectionElementGroup"+id+"_"+index+" Cannot be found.");
	}
}

/*
 * Function submitElementMove
 * Reloads the current page to cause all
 * relevant elements to reorder themselves.
 */
function submitElementMove( src, CDTable, CDField, CDRowId, CEElement_id, CurrentIndex, Offset, reloadCommand )
{
	var theURL = "/xml/index.php?func=CoalElements.moveElement"
							+"&CDTable="+CDTable
							+"&CDField="+CDField
							+"&CDRowId="+CDRowId
							+"&CEElement_id="+CEElement_id
							+"&CurrentIndex="+CurrentIndex
							+"&Offset="+Offset;
	var req		= newHTR();
	req.onreadystatechange = function() {
		if( req.readyState == 4 )
		{
			if( req.responseText.indexOf("ERROR") > -1 )
			{
				prompt(theURL, req.responseText );
			}
			else
			{
				if( typeof(reloadCommand) == "string" )
				{
					if( reloadCommand.indexOf("#") > -1 )
					{
						reloadArray = reloadCommand.split("#");
						reloadCommand = reloadArray.join("'");
					}
					reloadArray = reloadCommand.split(";");
					var i;
					for(i=0;i<reloadArray.length;i++)
					{
						//alert(reloadArray[i]);
						if( reloadArray[i] != "" )
						{
							eval(reloadArray[i]+";");
						}
					}
				}
				else
				{
					document.location.href = document.location.href;
				}
			}
		}
	}
	req.open("GET",theURL,true);
	req.send(null);
}

function setPosition( theSrc, theTarget )
{
	var target = document.getElementById(theTarget);
	if( target && theSrc )
	{
		target.style.left = theSrc.offsetLeft+"px";
		target.style.top = (getElementPosition(theSrc.id).top-50)+"px";
	}
}

function pageOffset()
{
	if (window.pageYOffset)
	{
	pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
	pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
	pos = document.body.scrollTop
	}
}

function showTab( tabPrefix, id, theModule )
{
	if( tabPrefix != '' && id != '' )
	{
		var target = document.getElementById( tabPrefix+"_"+id );
		var closeTargets = document.getElementsByTagName("div");
		var i;
		for(i=0;i<closeTargets.length;i++)
		{
			var tabName = closeTargets[i].id;
			if( tabName )
			{
				if( tabName.indexOf("tab") == 0 &&
						tabName.indexOf("_"+id) > -1 )
				{
					closeTargets[i].style.display = "none";
				}
			}
		}
		if( target )
		{
			target.style.display = "block";
		}
		snapWithDataHeight( theModule+"Section",true );
	}
}

function toggleCheckBox( id )
{
	if( id )
	{
		var target = document.getElementById(id);
		if( target )
		{
			target.checked = !target.checked;
		}
	}
}

/*> Required for CTForm CMSelect <*/

/**
 * On key down, clear the current timer and start a new one.
 * After a period of one full second has elapsed without the timer being
 * reset, fire the filter action.
 */
function CMSelectPrimeTimer(element,id,list,formName)
{
	clearInterval( superSelect_timer );
	superSelect_element = element.id;
	superSelect_id = id;
	superSelect_list = list;
	superSelect_formName = formName;
	superSelect_timer = setInterval( CMSelectTimerInc, 10 );
}
function CMSelectTimerInc()
{
	superSelect_counter = superSelect_counter+superSelect_update;
	if( superSelect_counter > superSelect_limit )
	{
		superSelect_element = document.getElementById(superSelect_element);
		timedFilter( superSelect_element, superSelect_id, superSelect_list, superSelect_formName );
		superSelect_counter = 0;
		clearInterval( superSelect_timer );
	}
}

/**
 * toggleHiddenList
 * Produces the prefix needed to enable the hiding and showing of
 * the CMSelect control.
 * @param HTMLNode element A Pointer to the hiddenList master div.
 */
function toggleHiddenList( element, formName )
{
	var arrID = element.id.split("_SS_");
	var prefix = arrID[0];
	eval("var expandedHeight = expandedHeight_SS_"+prefix+"_SS_"+formName+";");
	eval("var retractedHeight = retractedHeight_SS_"+prefix+"_SS_"+formName+";");
	if( expandedHeight.length == 0 )
	{
			var expandedHeight 	= "135px";
			var retractedHeight = "8px";
	}
	var currentHeight = ((element.style.height) ? (element.style.height) : (element.clientHeight+"px"));
	var scrollbox = document.getElementById(prefix+"_SS_CMSelectScrollBox");

	if( currentHeight == retractedHeight )
	{
		showExtendedElement( element, scrollbox, prefix );
	}
	else
	{
		hideExtendedElement( element, scrollbox, prefix );
	}
}

/**
 * showExtendedElement
 * Shows the hiddenList and the scrollbox within it.
 */
function showExtendedElement( element, scrollbox, prefix, formName )
{
	eval("var expandedHeight = expandedHeight_SS_"+prefix+"_SS_"+formName+";");
	element.style.height = expandedHeight;
	scrollbox.style.height = expandedHeight;
	scrollbox.style.display = "block";
	scrollbox.style.overflow = "scroll";
}

/**
 * hideExtendedElement
 * Hides the hiddenList and the scrollbox within it.
 */
function hideExtendedElement( element, scrollbox, prefix, formName )
{
	/*
	eval("var retractedHeight = retractedHeight_SS_"+prefix+"_SS_"+formName+";");
	element.style.height = retractedHeight;
	scrollbox.style.height = retractedHeight;
	scrollbox.style.display = "none";
	*/
}

function cancelEnter(src,event)
{
	if( !event || typeof(event) == "undefined" )
	{
		event = window.event;
	}
	if( event.keyCode == 13 )
	{
		event.cancelBubble = true;
		event.returnValue = false;
		return false;
	}
}

/**
 * CMSelectFocus
 * Causes the CMSelect to expand.
 */
function CMSelectFocus( element,formName )
{
	//alert(element.id + " ::: " + formName);
	var theID = element.id;
	var arrID = theID.split("_SS_");
	var prefix = arrID[0];

	var setupValuesKey = prefix+"_SS_"+formName+"_SS_setupValues";
	var setupPostActionKey = prefix+"_SS_"+formName+"_SS_setupPostAction";
	var setupValues = document.getElementById(setupValuesKey);
	var setupPostAction = document.getElementById(setupPostActionKey);

	try
	{
		eval("var lSetupComplete = setupComplete_SS_"+prefix+"_SS_"+formName+";");
		if( lSetupComplete == false )
		{
			eval(setupValues.value);
			eval(setupPostAction.value);
			eval("setupComplete_SS_"+prefix+"_SS_"+formName+" = true;");
		}
	}
	catch(e)
	{
		eval(setupValues.value);
		eval(setupPostAction.value);
	}

	setupValues.value = "";
	//CMSelectDraw(prefix, "database_SS_"+prefix, formName);
}

/**
 * isCheckedSort
 * Compares two records for the checked property, returning checked items first.
 */
function isCheckedSort( a, b )
{
	if( a.checked )
	{
		return -1;
	}
	return 1;
}

/**
 * CMSelectRows
 * Creates nodes for the list supplied by data.
 * @param string prefix - The form name.
 * @param array data - The data set.
 * @return array<HTMLTableRows>
 */
function CMSelectRows( prefix, data, formName )
{
	var rows = new Array();
	rows[rows.length] = document.createElement("TR");
	var i;
	eval("var multiSelect = multiSelect_SS_"+prefix+"_SS_"+formName+";");
	if( !multiSelect )
	{
		var tr  = document.createElement("TR");
		tr.setAttribute("id",prefix+"_SS_"+formName+"_list_row_");
		tr.setAttribute("onmouseover","zebraHiliteRow(this);");
		tr.setAttribute("onmouseout","zebraResetRow(this);");
		var tda = CMSelectDeselectRadio( prefix, formName );
		var tdb = CMSelectDeselectText( prefix, formName );
		var tdc = CMSelectDeselectRank( prefix, formName );
		tr.appendChild( tda );
		tr.appendChild( tdb );
		tr.appendChild( tdc );
		rows[rows.length] = tr;
	}
	for(i=0;i<data.length;i++)
	{
		if( data[i] )
		{
			var id   = data[i].id;
			var text = data[i].text;
			var rank = data[i].rank;
			var visible = data[i].visible;
			var checked = data[i].checked;
			if( visible || checked )
			{
				var tr  = document.createElement("TR");
				tr.setAttribute("id",prefix+"_SS_"+formName+"_list_row_"+id);
				tr.setAttribute("onmouseover","zebraHiliteRow(this);");
				tr.setAttribute("onmouseout","zebraResetRow(this);");
				var tda = CMSelectCellCheckbox( prefix, formName, id, checked );
				var tdb = CMSelectCellText( prefix, formName, id, text );
				var tdc = CMSelectCellRank( prefix, formName, id, rank );
				//tr.setAttribute("onclick","selectRow();");
				tr.appendChild( tda );
				tr.appendChild( tdb );
				tr.appendChild( tdc );
				rows[rows.length] = tr;
			}
		}
	}
	/*
	tr = document.createElement("TR");
	td = document.createElement("TD");
	td.setAttribute("style","{height:22px;}");
	br = document.createElement("HR");
	td.setAttribute("colspan","3");
	td.appendChild(br);
	tr.appendChild(td);

	//rows[rows.length] = tr;
	*/
	return rows;
}

/**
 * CMSelectDeselectText
 * Create the text to identify the deselect used to deselect items
 * @return HTMLTableCell
 */
function CMSelectDeselectText(prefix, formName )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cellb_");
	var a = document.createElement("a");
	a.setAttribute("href","javascript:selectRow('"+prefix+"','','database_SS_"+prefix+"','"+formName+"');");
	a.setAttribute("style","display:block;width:80%;");
	var txt = document.createTextNode("No Selection");
	a.appendChild(txt);
	td.appendChild(a);
	return td;
}

/**
 * CMSelectDeselectRank
 * Create the rank to identify the deselect used to deselect items
 * @return HTMLTableCell
 */
function CMSelectDeselectRank( prefix, formName )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cellc_");
	td.setAttribute("style","height:14px;width:10%;");

	var txt = document.createTextNode("0");
	td.appendChild(txt);

	return td;
}

/**
 * CMSelectDeselectRadio
 * Create the radio button used to deselect items
 * @return HTMLTableCell [ HTMLInput <radio> ] or ''
 */
function CMSelectDeselectRadio( prefix, formName )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cella_");
	td.setAttribute("style","width:10%;");
	var chk = document.createElement("input");
	chk.setAttribute("type","radio");
	chk.setAttribute("name",prefix);
	chk.setAttribute("value","");
	chk.setAttribute("onchange","selectRow('"+prefix+"','','database_SS_"+prefix+"','"+formName+"');");
	chk.setAttribute("id",prefix+"_SS_"+formName+"_selectionCheckbox");
	td.appendChild(chk);
	return td;
}

/**
 * CMSelectCellText
 * Creates a table cell containing the text value as a link.
 * @param string prefix - The form nam.e
 * @param string id - The record id
 * @param string value - The text value.
 * @return HTMLTableCell
 */
function CMSelectCellText(prefix, formName, id, value )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cellb_"+id);
	var a = document.createElement("a");
	a.setAttribute("href","javascript:selectRow('"+prefix+"','"+id+"','database_SS_"+prefix+"','"+formName+"');");
	a.setAttribute("style","display:block;width:80%;");
	var txt = document.createTextNode(value);
	a.appendChild(txt);
	td.appendChild(a);
	return td;
}

/**
 * CMSelectCellRank
 * Creates a table cell containing the extended value as text.
 * @param string prefix - The form name
 * @param string id - The record id
 * @param string value - The text value.
 * @return HTMLTableCell
 */
function CMSelectCellRank( prefix, formName, id, value )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cellc_"+id);
	td.setAttribute("style","height:14px;width:10%;");

	if (value.indexOf("IMG::") > -1)
	{
		var anchor = document.createElement("A");
		var img = document.createElement("IMG");
		img.border=0;
		imgsrc = value.split("::");
		img.src = imgsrc[1];
		popupid = imgsrc[2];
		anchor.href = "javascript:createCTPopup('/xml/index.php?func=CoalTools.openDialog&dialog="+popupid+"', 'js:CMSelectFocus(document.getElementById(\\'"+prefix+"_SS_"+formName+"_SS_searchVal\\'),\\'"+formName+"\\');selectRow(\\'"+prefix+"\\',\\'"+id+"\\',\\'database_SS_"+prefix+"\\',\\'"+formName+"\\');');";
		anchor.appendChild(img);
		td.appendChild(anchor);
	}
	else if (value.indexOf("HREF::") > -1)
	{
		var anchor = document.createElement("A");
		anchorhref = value.split("::");
		anchor.href = anchorhref[1];
		linkText = document.createTextNode("Download");
		anchor.appendChild(linkText);
		td.appendChild(anchor);
	}
	else
	{
		var txt = document.createTextNode(value);
		td.appendChild(txt);
	}

	return td;
}

/**
 * CMSelectCellCheckbox
 * Conditionally creates either a checkbox or a radio button of the class for name.
 * It's value is then set to the id of the recordset.
 * @param string prefix - The form name
 * @param string id - The record id
 * @param boolean checked - Whether or not to check the item by default.
 * @return HTMLTableCell [ HTMLInput <checkbox|radio> ]
 */
function CMSelectCellCheckbox( prefix, formName, id, checked )
{
	var td = document.createElement("TD");
	td.setAttribute("id",prefix+"_SS_"+formName+"_List_cella_"+id);
	td.setAttribute("style","width:10%;");
	var chk = document.createElement("input");
	eval("var multiSelect = multiSelect_SS_"+prefix+"_SS_"+formName+";");
	//alert("multiSelect_SS_"+prefix+"_SS_"+formName+": "+multiSelect);
	if( multiSelect )
	{
		chk.setAttribute("type","checkbox");
		chk.setAttribute("name",prefix+"[]");
	}
	else
	{
		chk.setAttribute("type","radio");
		chk.setAttribute("name",prefix);
	}
	chk.setAttribute("value",id);
	chk.setAttribute("onchange","selectRow('"+prefix+"','"+id+"','database_SS_"+prefix+"','"+formName+"');");
	if( checked )
	{
		chk.setAttribute("checked","checked");
	}
	chk.setAttribute("id",prefix+"_SS_"+formName+"_selectionCheckbox"+id);
	td.appendChild(chk);
	return td;
}

/**
 * DEPRECATED.
 * Attempts to return the source item from an event object. Non-standard
 * browser implimentation makes this function unreliable at best.
 */
function getTargetElement(evt) {
	var elem;
	if (evt.target) {
		elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
	} else {
		elem = evt.srcElement;
	}
	return elem;
}

/** TODO: FOLLOWING ADDED BY KEVIN IN A WAY THAT SHOULD PROBABLY BE CLEANED UP **/
		function selectRow( prefix, id, list, formName )
		{
			eval("var database = "+list+"_SS_"+formName+";");
			if (database)
			{
				eval("var multiSelect = multiSelect_SS_"+prefix+"_SS_"+formName+";");
				if( !multiSelect )
				{
					var i;
					for(i=0;i<database.length;i++)
					{
						var chkid = database[i].id;
						database[i].checked = false;
						var theCheckbox = document.getElementById(prefix+"_SS_"+formName+"_selectionCheckbox"+chkid);
						if( theCheckbox )
						{
							theCheckbox.checked = false;
						}
					}
				}
				var checkBox = document.getElementById(prefix+"_SS_"+formName+"_selectionCheckbox"+id);
				if(id != "")
				{
					database[ getRecordIndex(id, list, formName) ].checked = !database[ getRecordIndex(id, list, formName) ].checked;
					checkBox.checked = database[getRecordIndex(id, list, formName)].checked;
				}
				showExtendedElement( document.getElementById(prefix+"_SS_"+formName+"_SS_hiddenList"),
														 document.getElementById(prefix+"_SS_"+formName+"_SS_CMSelectScrollBox"),
														 prefix,
														 formName );
			}
			return;
		}

		function getRecordIndex( id, list, formName )
		{
			eval("var database = "+list+"_SS_"+formName+";");
			if (database)
			{
				var i;
				for(i=0;i<database.length;i++)
				{
					if( database[i] == null )
					{
					}
					else
					{
						if( database[i].id == id )
						{
							return i;
						}
					}
				}
			}
			return -1;
		}

		function timedFilter(element,id,list,formName)
		{
			eval("var database = "+list+"_SS_"+formName+";");
			if (database)
			{
				//database.sort(isCheckedSort);
				var compString = element.value.toLowerCase();
				if(element.value.length > 0)
				{
					var i;
					for(i=0;i<database.length;i++)
					{
						if( database[i].text.toLowerCase().indexOf(compString) > -1
								|| database[i].checked )
						{
							database[i].visible = true;
						}
						else
						{
							database[i].visible = false;
						}
					}
				}
				else
				{
					var i;
					for(i=0;i<database.length;i++)
					{
						database[i].visible = true;
					}
				}
				CMSelectDraw(id, list, formName);
			}
		}

		function applyLocalFilter( element, id, list, formName )
		{
			timedFilter(element,id,list,formName);
		}

		function fetchExternalData( prefix, formName, list, theURL )
		{
			//alert("fetchExternalData prefix: "+prefix+" formName: "+formName+" list: "+list+" theURL: "+theURL);
			eval("var database = "+list+"_SS_"+formName+";");
			if (database)
			{
				var searchField = document.getElementById(prefix+
																									"_SS_"+
																									formName+
																									"_SS_searchVal");
				searchVal		= searchField.value;
				/*
					Prune the local array to only contain those items which are
					checked.
				*/
				database.sort(isCheckedSort);

				var i;
				for(i=0;i<database.length;i++)
				{
					if( database[i].checked == false )
					{
						database.splice(i,database.length);
						break;
					}
				}

				/*
					Perform search on db and return list of pages
					matching query.

					var theURL = "/xml/index.php?func=CoalMedia.getPageList"
				*/
				var req = newHTR();
				/*
					 "&q="+searchVal;
				*/
				theURL = theURL + "&q=" + searchVal;
				req.onreadystatechange = function(){
					if(( req.readyState == 4 ) && (req.responseText))
					{
						var records = req.responseText.split("\n");
						var i;
						for(i=0;i<records.length;i++)
						{
							if (records[i].length > 3)
							{
								var fields = records[i].split("\t");
								var recordExists = getRecordIndex(fields[0], list, formName);
								if( recordExists > -1 )
								{
								}
								else
								{
									database[database.length] = {id:fields[0],text:fields[1],lowertext:fields[1].toLowerCase(),rank:fields[2],visible:true,checked:false};
								}
							}
						}
						CMSelectDraw(prefix, list, formName);
					}
				}
				req.open("GET",theURL,true);
				req.send(null);
			}
		}

		function CMSelectDraw( prefix, list, formName )
		{
			eval("var database = "+list+"_SS_"+formName+";");
			//{$id}_SS_{$formName}_SS_CMSelectScrollBox
			//{$id}_SS_{$formName}_SS_List_table
			var elem = document.getElementById(prefix+"_SS_"+formName+"_SS_CMSelectScrollBox");
			//alert(elem.scrollTop);
			var scrollTop = elem.scrollTop;

			if (database)
			{
				var theID = prefix+"_SS_"+formName+"_SS_List_table";
				var table = document.getElementById(theID);
				if( table.innerHTML.toUpperCase().indexOf("TBODY") > -1 )
				{
					var tbody = table.getElementsByTagName("tbody");
					tbody = tbody[0];
					while (tbody.rows.length > 0) {
						tbody.removeChild(tbody.firstChild);
					}
				}
				else
				{
					table.innerHTML = "";
				}
				var tr = document.createElement("TR");
				var th = document.createElement("TH");
				tr.appendChild(th);
				th = document.createElement("TH");
				th.setAttribute("class","noclick")
				th.setAttribute("style","height:14px;width:90%;");
				var txt = document.createTextNode("Name");
				th.appendChild(txt);
				tr.appendChild(th);
				th = document.createElement("TH");
				th.setAttribute("style","height:14px;width:10%;");
				th.setAttribute("class","noclick")
				txt = document.createTextNode("Ext");
				th.appendChild(txt);
				tr.appendChild(th);

				var tableBody = CMSelectRows(prefix,database,formName);
				if( table.innerHTML.toUpperCase().indexOf("TBODY") > -1 )
				{
					var tbody = table.getElementsByTagName("tbody");
					tbody = tbody[0];
					tbody.appendChild(tr);
					var i;
					for(i=0;i<tableBody.length;i++)
					{
						if (i%2 == 0)
						{
							tableBody[i].setAttribute("class","evenRow");
						}
						else
						{
							tableBody[i].setAttribute("class","oddRow");
						}
						tbody.appendChild(tableBody[i]);
					}
				}
				else
				{
					table.appendChild(tr);
					var i;
					for(i=0;i<tableBody.length;i++)
					{
						if (i%2 == 0)
						{
							tableBody[i].setAttribute("class","evenRow");
						}
						else
						{
							tableBody[i].setAttribute("class","oddRow");
						}
						table.appendChild(tableBody[i]);
					}
				}

				var i;
				var tableHeight;
				tableHeight = 16;
				for(i=0;i<database.length;i++)
				{
					if( database[i] )
					{
						var theCheckbox = document.getElementById(prefix+"_SS_"+formName+"_selectionCheckbox"+database[i].id);
						if( theCheckbox )
						{
							theCheckbox.checked = database[i].checked;
						}
						if( database[i].checked )
						{
							tableHeight = tableHeight+16;
						}
					}
				}
				if(tableHeight > 16)
				{
					tableHeight = tableHeight+(80);
				}
				var element = document.getElementById(prefix+"_SS_"+formName+"_SS_hiddenList");
				var scrollbox	= document.getElementById(prefix+"_SS_"+formName+"_SS_CMSelectScrollBox");
				showExtendedElement( element, scrollbox, prefix, formName );
				//sortables_init();
				elem.scrollTop = tableHeight;
			}
		}

/* the following functionality is for ctpopups */
var CTPopupWindow = null;
var CTPopupWindow_return = null;
function createCTPopup(url, returnFn, height, width)
{
	if (height == null || height < 0) {
		height=340;
	}
	if (width == null || width < 0) {
		width=340;
	}
    CTPopupWindow=window.open(url,null,'height='+height+',width='+width+',scrollbars=no,menubar=no,resizable=no,toolbar=no,location=no,status=no');
    if (window.focus) {CTPopupWindow.focus()}
    if (returnFn.length > 0)
    {
            CTPopupWindow_return = returnFn;
    }
    else
    {
            CTPopupWindow_return = null;
    }
}
function CTPopupReturn(value)
{
        if (CTPopupWindow_return && value && value.length > 0)
        {
                if (CTPopupWindow_return.indexOf("js:") == 0)                {
                        var fnCall = CTPopupWindow_return.substring(3);
                        fnCall = fnCall.replace(/\[RETURN\]/g, "'"+value+"'");
                        //alert(fnCall);
                        eval(fnCall);
                }
                else
                {
                        eval(CTPopupWindow_return + ' = "'+value+'";');
                }
        }
}
function checkForCTPopup()
{
        if (CTPopupWindow && !CTPopupWindow.closed)
        {
                CTPopupWindow.focus();
        }
}
function setUploadResult(value, formName, fieldName) {
	//alert(value +" : "+formName);
	ctfileid = value.split("/")[1];
	value = value.split("/")[0];
	sels = document.getElementsByTagName("input");
	for(i=0;i<sels.length;i++)
	{
		if (sels[i].id.indexOf("Uploaded_Filename_")>-1 && sels[i].id.indexOf(formName)>-1 && sels[i].id.indexOf(fieldName)>-1) {
			sels[i].value = value;
		}
		if (sels[i].id.indexOf("Uploaded_CTFile_id_")>-1 && sels[i].id.indexOf(formName)>-1 && sels[i].id.indexOf(fieldName)>-1) {
			sels[i].value = ctfileid;
		}
		if (sels[i].id.indexOf("radio_")>-1 && sels[i].id.indexOf("1"+formName)>-1 && sels[i].id.indexOf(fieldName)>-1) {
			sels[i].checked = true;
		}
	}

}

function closeUploadAppletWindow() {
	passbackValue = "'"+document.uploadApplet.getFileName()+"'";
	window.opener.CTPopupReturn(passbackValue);
    window.close();
}

function productReviewManagementSetSelects( value )
{
	sels = document.getElementsByTagName("select");
	for(i=0;i<sels.length;i++)
	{
		if(sels[i].name.indexOf("action") > -1)
		{
			sels[i].selectedIndex = value;
		}
	}
}

/*
 Function batchProcess
 Iterate selected items and send xmlhttprequests for each operation until list is empty.
 Then reload the page with the current section set as open.
*/
function batchProcess( theSection, operation, pageId, pageName, defaultAffected )
{
	if( pageId == "" || operation == "" )
	{
		return false;
	}
	var inputArray = document.getElementsByTagName("input");
	var executeArray = new Array();
	var confirmArray = new Array();
	var resultString = "";
	for(i=0;i<inputArray.length;i++)
	{
		var theElement = inputArray[i];
		if( theElement.id.indexOf("processElement_"+theSection) > -1 && theElement.id.indexOf("_value") == -1 )
		{
			if( operation == "selectAll" || operation == "selectNone" || operation == "toggleAll" )
			{
				if( operation == "selectAll" ){
					theElement.checked = true;
				}
				else if( operation == "selectNone" )
				{
					theElement.checked = false;
				}
				else
				{
					theElement.checked = !theElement.checked;
				}
			}
			else if( theElement.checked )
			{
				executeArray[ executeArray.length ] = theElement.value;
				confirmArray[ confirmArray.length ] = document.getElementById(theElement.id+"_value").value;
			}
		}
	}
	var confirmString = "The following elements on "+pageName+" will be affected by the batch operation ["+operation+"]:\n\t"+confirmArray.join("\n\t");
	if( operation == "replaceInChildren" )
	{
		confirmString +="\n**Note: Replace in Sub-Pages will replace by type and as such only the last element in this list will be left in position.";
	}
	var func = false;
	var doProcess = false;
	if( executeArray.length > 0 )
	{
		doProcess = window.confirm(confirmString);
	}
	else if(operation == "selectAll"  ||
					operation == "selectNone" ||
					operation == "toggleAll" )
	{
		doProcess = false;
	}
	else
	{
		//operating on a single item using defaultAffected
		executeArray[executeArray.length] = defaultAffected;
		doProcess = window.confirm(confirmString);
	}

	if( doProcess == false )
	{
		return false;
	}
	else
	{
		var baseURL = "/xml/index.php";
		for(i=0;i<executeArray.length;i++)
		{
			if( operation == "remove" )
			{
				func = "?func=CoalMedia.unassignElements";
				var elementId = executeArray[i].split(",")[1];
				var req		= newHTR();
				req.onreadystatechange = function(){
					if(( req.readyState == 4 ) && (req.responseText))
					{
						resultString += req.responseText;
					}
				}
				var theURL = baseURL+func+"&CMPage_id="+pageId+
																	"&elementsSection="+theSection+
																	"&elementsAppend="+elementId+
																	"&func_redirect=PAGEID";
				req.open("GET",theURL,false);
				req.send(null);
			}
			else if( operation == "addToChildren" )
			{
				///admin/index.php?func=CoalMedia.addElementToChildren&id=3&section=Body&replicateIndex=1
				//this mother trucker doesn't take an id, but rather an index and does all the lifting
				//on the backend.
				func = "?func=CoalMedia.addElementToChildren";
				var opTag = executeArray[i].split(",");
				var elementId = opTag[1];
				var elementIndex = opTag[0];
				var req		= newHTR();
				var theURL = baseURL+func+"&id="+pageId+
																	"&section="+theSection+
																	"&replicateIndex="+elementIndex;
				req.open("GET",theURL,false);
				req.send(null);
			}
			else if( operation == "replaceInChildren" )
			{
				func = "?func=CoalMedia.publishElementToChildren";
				var opTag = executeArray[i].split(",");
				var elementId = opTag[1];
				var elementIndex = opTag[0];
				var req		= newHTR();
				var theURL = baseURL+func+"&id="+pageId+
																	"&section="+theSection+
																	"&replicateIndex="+elementIndex;
				req.open("GET",theURL,false);
				req.send(null);
			}
			else if( operation == "removeFromChildren" )
			{
				func = "?func=CoalMedia.removeElementFromChildren";
				var opTag = executeArray[i].split(",");
				var elementId = opTag[1];
				var elementIndex = opTag[0];
				var req		= newHTR();
				var theURL = baseURL+func+"&id="+pageId+
																	"&section="+theSection+
																	"&replicateIndex="+elementIndex;
				req.open("GET",theURL,false);
				req.send(null);
			}
		}
		//window.alert( resultString )
		//{
			var docURL = document.location.href;
			docURL = docURL.split("#")[0];
			document.location.href = docURL;
		//}
	}
}
