/**
$Id: common.js 8827 2007-10-26 00:27:56Z dallbee $
*/

/**
 * The PINT object is the single global object used by PINT's JavaScript Library.  It
 * contains utility function for setting up namespaces and inheritance.
 * PINT.util and PINT.lib are namespaces
 * created automatically for and used by the library.
 * @module PINT
 * @title  PINT Global
 */

/**
 * The PINT global namespace object
 * @class PINT
 * @static
 */
if (typeof PINT == "undefined") {
    var PINT = {};
}

/**
 * Returns the namespace specified and creates it if it doesn't exist
 * <pre>
 * PINT.namespace("property.package");
 * PINT.namespace("PINT.property.package");
 * </pre>
 * Either of the above would create PINT.property, then
 * PINT.property.package
 *
 * Be careful when naming packages. Reserved words may work in some browsers
 * and not others. For instance, the following will fail in Safari:
 * <pre>
 * PINT.namespace("really.long.nested.namespace");
 * </pre>
 * This fails because "long" is a future reserved word in ECMAScript
 *
 * @method namespace
 * @static
 * @param  {String*} arguments 1-n namespaces to create
 * @return {Object}  A reference to the last namespace object created
 */
PINT.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; ++i) {
        d=a[i].split(".");
        o=PINT;

        // PINT is implied, so it is ignored if it is included
        for (j=(d[0] == "PINT") ? 1 : 0; j<d.length; ++j) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

/**
 * Utility to set up the prototype, constructor and superclass properties to
 * support an inheritance strategy that can chain constructors and methods.
 *
 * @method extend
 * @static
 * @param {Function} subc   the object to modify
 * @param {Function} superc the object to inherit
 * @param {String[]} overrides  additional properties/methods to add to the
 *                              subclass prototype.  These will override the
 *                              matching items obtained from the superclass
 *                              if present.
 */
PINT.extend = function(subc, superc, overrides) {
    var F = function() {};
    F.prototype=superc.prototype;
    subc.prototype=new F();
    subc.prototype.constructor=subc;
    subc.superclass=superc.prototype;
    if (superc.prototype.constructor == Object.prototype.constructor) {
        superc.prototype.constructor=superc;
    }

    if (overrides) {
        for (var i in overrides) {
            subc.prototype[i]=overrides[i];
        }
    }
};

/**
 * Applies all prototype properties in the supplier to the receiver if the
 * receiver does not have these properties yet.  Optionally, one or more
 * methods/properties can be specified (as additional parameters).  This
 * option will overwrite the property if receiver has it already.
 *
 * @method augment
 * @static
 * @param {Function} r  the object to receive the augmentation
 * @param {Function} s  the object that supplies the properties to augment
 * @param {String*}  arguments zero or more properties methods to augment the
 *                             receiver with.  If none specified, everything
 *                             in the supplier will be used unless it would
 *                             overwrite an existing property in the receiver
 */
PINT.augment = function(r, s) {
    var rp=r.prototype, sp=s.prototype, a=arguments, i, p;
    if (a[2]) {
        for (i=2; i<a.length; ++i) {
            rp[a[i]] = sp[a[i]];
        }
    } else {
        for (p in sp) {
            if (!rp[p]) {
                rp[p] = sp[p];
            }
        }
    }
};

PINT.namespace("util", "lib");



/* ******** Constants *********************************** */
var windowStatus = "";
var debugMode = false; // make sure this is false on deployment
setTimeout("try {if (window.opener && window.opener.top && window.opener.top.debugMode) top.debugMode = window.opener.top.debugMode; top.setDebugLinkTexts()}catch (e) {}", 1000);
/* ******** Common Window Settings ********************** */
var defaultStatus = "";

/**
 * PINT_GetEventSource()
 * Takes as an argument the first argument to an event handler, and
 * returns a reference to the object that generated the event
 *
 * @param e - first argument to an event handler
 *
 * @return reference to object that triggered event
 */
function PINT_GetEventSource(e)
{
	if ( e && e.target )
		{
		// HACK for NN 6 because NN 6 trigger event from text node
		var event = e && e.target;
		while (event && event.nodeType == 3)
			event = event.parentNode

		return (event);
		}

	if (window && window.event && window.event.srcElement)
		return (window && window.event && window.event.srcElement);

	return false;

/*	return ( //figure out where in the dom events come in on this browser
		(e && e.target) ||
		(window && window.event && window.event.srcElement)
*/
}

/**
 * PINT_GetElementById()
 * Tries to find an element in the document
 * by its id or name
 *
 * @param idname - id of element to locate
 */
function PINT_GetElementById(idname)
{
	var handle;

	if (document.getElementById) {
		handle = document.getElementById(idname);
		if (handle) return handle;
	}

	if (document.getElementByName) {
		handle = document.getElementByName(idname)[0];
		if (handle) return handle;
	}

	handle = document[idname];
	if (handle) return handle;

	if (document.all) {
		handle = document.all[idname];
		if (handle) return handle;
	}

	if (document.anchors) {
		handle = document.anchors[idname];
		if (handle) return handle;
	}

	if (document.links) {
		handle = document.links[idname];
		if (handle) return handle;
	}

	if (document.images) {
		handle = document.images[idname];
		if (handle) return handle;
	}

	if (document.embeds) {
		handle = document.embeds[idname];
		if (handle) return handle;
	}

	return handle;
}

/**
 * PINT_GetIdByElement()
 * Inverse of PINT_GetElementById, returns the id,
 * or name, of a given element
 *
 * @param element - object whose id to retrieve
 */
function PINT_GetIdByElement(element)
	{
	if (!(element)) return undefined;
	if (element.id) return element.id;
	if (element.name) return element.name;
	return undefined;
	}

/**
 * PINT_GetElementByNodeName()
 * starting with the event target this function
 * moves up the DOM until it finds the next
 * element with the specified node name
 *
 * @param e - first argument to an event handler
 * @param nodeName - nodeName you are looking for ..such as 'DIV' 'SPAN' etc.
 *
 * @return node
 */
function PINT_GetElementByNodeName(e,nodeName) {
   if(!e) var e = window.event;
	targ = (e.target) ? e.target : e.srcElement;
	while(targ.nodeName != nodeName) {
	  if(targ.parentNode) targ = targ.parentNode;
	  else break;
	}
	return targ;
}
/**
 * PINT_ChangePageTitle()
 * Change title of current page. Use when initial title
 * tag value is optimized for Search Engines, but you
 * want the title to be more descriptive for the visitor.
 *
 * @param   pageTitle  - new page title
 */
function PINT_ChangePageTitle( pageTitle )
	{
	if(document.title.readOnly == true) document.title = pageTitle;
	}

/**
 * PINT_GetCurrentFileName()
 * Get name of current file from path name
 */
function PINT_GetCurrentFileName()
	{
	var URL = unescape( window.location.pathname );
	var start = URL.lastIndexOf( "/" ) + 1;
	var end = ( URL.indexOf( "?" ) > 0 ) ? URL.indexOf( "?" ) : URL.length;
	return( URL.substring( start, end ) );
	}
/**
 * PINT_GetCurrentFilePath()
 * Get path to current file from path name
 */
function PINT_GetCurrentFilePath()
	{
	var URL = unescape( window.location.pathname );
	var start = URL.lastIndexOf( "/" );
	return( URL.substring( 0, start ) );
	}

/**
 * PINT_GetCurrentDirectory()
 * Get name of current directory from path name
 */
function PINT_GetCurrentDirectory()
	{
	var filePath = PINT_GetCurrentFilePath();
	var directories = filePath.split("/");
	return directories.length && directories[ directories.length-1 ] != "" ? directories[ directories.length-1 ] : "";
	}

/**
 * PINT_IsRootDirectory()
 * Determine if specified directory matches root directory
 *
 * @param directory - directory to check
 */
function PINT_IsRootDirectory( directory )
	{
	return directory.toLowerCase() == PINT_GetRootDirectory().toLowerCase() ? true : false;
	}

/**
 * PINT_IsDefaultFile()
 * Determine if file name is an index file
 *
 * @param fileName - file name to check
 */
function PINT_IsDefaultFile()
	{
	var fileName = typeof(PINT_IsDefaultFile.arguments[0]) != 'undefined' ? PINT_IsDefaultFile.arguments[0] : PINT_GetCurrentFileName();

	if (fileName == "")
		return true;

	// Get the List of Default Files
	var fileNameList = PINT_GetDefaultFile();
	// If the list is an object
	if ( eval( 'typeof(fileNameList)' ) == 'object' )
		{
		// Loop through array looking for filename.
		for (var fileNameListIndex = 0; fileNameListIndex < fileNameList.length; fileNameListIndex++)
			if ((fileName == fileNameList[fileNameListIndex])) return true;
		}
	return false;
	}

/**
 * PINT_GetDefaultFile()
 * Gets DefaultFile List global variable if defined.
 *
 * @return		default file name list.
 *
 */
function PINT_GetDefaultFile()
	{
	if( typeof( defaultFileList ) == 'undefined' )
		return "";
	else
		return defaultFileList.split(",");
	}

/**
 * PINT_SetWindowStatus()
 * Set status bar message from parameter or global variable.
 *
 * @param e		event
 * @return		True.
 *
 */
function PINT_SetWindowStatus()
	{
	// if no arguments are passed, look for global windowStatus varible
	if( PINT_SetWindowStatus.arguments.length == 0 )
		{
		if( typeof(windowStatus) != 'undefined' && windowStatus != "" )
			{
			window.status = windowStatus;
			windowStatus = "";
			}
		}
	else
		window.status = PINT_SetWindowStatus.arguments[0];
	return true;
	}


/**
 * PINT_GetRootDirectory()
 * Gets rootDirectory global variable if defined.
 *
 * @return		root directory path.
 *
 */
function PINT_GetRootDirectory()
	{
	if( typeof( rootDirectory ) == 'undefined' )
		return "";
	else
		return rootDirectory;
	}


/**
 * PINT_getElementsByClass(name)
 * Gets all elements that belong to a specific class
 *
 * @param name	string containing name of class
 * @return		array of objects
 *
 */
function PINT_getElementsByClass(name)
	{
	var all = document.all ? document.all : document.getElementsByTagName('*');
	var elements = new Array();
	for (var e = 0; e < all.length; e++)
		{
		if((name != '') && (all[e].className.indexOf(name) >= 0)) elements[elements.length] = all[e];
		}
	return elements;
	}


/**
 * PINT_getURLParam(name, defaultVal)
 * Gets a parameter's value from the url query string if it exists,
 * otherwise returns a default value
 *
 * @param name  name of url param
 * @param defaultVal value if the url param does not exist
 * @return string  value of url param
 *
 */
function PINT_getURLParam(name, defaultVal)
	{
	// default the param's value to the default value
	var paramVal = defaultVal;
	// make a regex for the specific param name
	var regex = new RegExp("\&" + name + "\=([^$\&]+)", "i");
	// check if there are any params in the url
	if(document.URL.indexOf('?') != -1)
		{
		// extract just the query string (prepend an & so the regex can find the first param)
		var qString = '&' + document.URL.substring((document.URL.indexOf('?') + 1), document.URL.length);
		// match the regex to the query string
		var urlMatches = qString.match(regex);
		// if it found a match, the second array element returned will be the value
		if((urlMatches != null) && (urlMatches.length == 2)) paramVal = urlMatches[1];
		}
	return paramVal;
	}


// BEGIN: PINT_OnChange ================================================================================
var PINT_OnChangeLinkType = new Array();
function PINT_OnChangeHandler(e)
	{
	var formElement

	e = (e) ? e : ((window.event) ? window.event : "")
	if (e)
		{
		var eventsource = PINT_GetEventSource(e);
		// Loop through all the forms looking for the onchange Event
		for (formIndex = 0; formIndex < document.forms.length; formIndex++)
			{
			formElement = document.forms[formIndex];
			// Loop through all the elements of the form looking for the onchange Event
			for (elementIndex = 0; elementIndex < formElement.elements.length; elementIndex++)
				{
				if (eventsource.name == formElement.elements[elementIndex].name)
					{
					if (PINT_OnChangeLinkType[eventsource.id] == "anchor" && formElement.elements[elementIndex].value != "" )
						window.location =  formElement.action + "#" + formElement.elements[elementIndex].value;
					else if (PINT_OnChangeLinkType[eventsource.id] == "page" && formElement.elements[elementIndex].value != "" )
						window.location =  formElement.elements[elementIndex].value;
					}
				}
			}
		}
	return true;
	}

/**
 * PINT_OnChangeInit()
 *
 * @pram trigger The name of the element triggering the event
 * @param linkType The type of link you are setting up in the on change
 *		- page, anchor
 *
 */

function PINT_OnChangeInit()
	{
	if (PINT_OnChangeInit.arguments.length != 2 ) return false
	if( document.getElementById )
		{
		var trigger = document.getElementById( PINT_OnChangeInit.arguments[0] ); // Gets the element that triggers the on change
		if( trigger )
			{
			PINT_OnChangeLinkType[trigger.id] = PINT_OnChangeInit.arguments[1];
			trigger.onchange = PINT_OnChangeHandler;
			}
		}
	return true;
	}
// END: PINT_OnChange ================================================================================


// focuses the first form field that is a text input
function focusFirstTextInput(){
	if (document.forms[0] && document.forms[0].elements.length){
		var element;
		for (var i=0; i<document.forms[0].elements.length; i++){
			element = document.forms[0].elements[i];
			if ((element.type == 'text') && !element.disabled){
				try {
					element.focus();
					break;
				}
				catch (e) {}
			}
		}
	}
}

// change the max rows of the current page
function setMaxList(url)
	{
	max = prompt("Enter number of items to display:","");
	if((max != null) && !isNaN(max) && max != "")
		{
		//var loc = url.replace("/&max_rows=\d/g",'');
		document.location = url + getUrlSeparator(url) +"max_rows=" + max;
		}
	}

// global variables
var g_iframesToReload = new Array();
var g_listSortBy = new Object();
var g_lastSortImage = new Array();
var g_allowListRowSelect = true; // HACK
var g_highlightCollection = false;

function PINT_httpRequest(url){
    // IE object
    if (window.ActiveXObject) xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();

   if (xmlhttp) {
        xmlhttp.onreadystatechange=PINT_checkRequestState;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
   }
}

function PINT_checkRequestState(){
    // if xmlhttp shows "loaded"
    if (xmlhttp.readyState==4){
        if (xmlhttp.status==200) eval(xmlhttp.responseText);
    }
}

/**
 * changes the location of a hidden iframe
 *
 * @param string id of allowed statement
 */

function doRPC(statementId, additionalUrlParams){
	var scriptLocation = PINT_GetRootDirectory() + '/rpc/rpc' + FILE_EXT + '?statementId=' + statementId + '&' + getRandomNumber() + '=' + getRandomNumber();
    if (additionalUrlParams) scriptLocation += additionalUrlParams;
	if (top.debugMode) window.open(scriptLocation + '&debugMode=1');
	//else createScriptTag(scriptLocation);
    else PINT_httpRequest(scriptLocation);
}

function createScriptTag(scriptLocation){
	var scriptTag = document.createElement('script');
	scriptTag.type = "text/javascript";
	scriptTag.src = scriptLocation;
	document.body.appendChild(scriptTag);
}

/**
 * update the lockTime and userAccessorId periodically
 *
 * @param string rpcid
 * @param int time interval
 */
function updateLock(rpcId, lockTTL) {
    doRPC(rpcId);
    setTimeout("updateLock('" + rpcId + "', " + lockTTL + ")", lockTTL);
}

/**
 * refresh iframe periodically
 *
 * @param int time interval
 */
var g_refreshRpcId=null;
function refreshLock(refreshTTL, rpcId) {
   g_refreshRpcId = rpcId;
   setInterval("checkRefresh('"+rpcId+"');", refreshTTL);
}

/**
 * iframe refresh
 * function runs on a set interval
 * the rpc checks if anything in the list has
 * been modified, if it has then we refresh
 *
 * @param rpcId
 */
var g_isListUpToDate = null;
function checkRefresh(rpcId, disallowRpc) {
	if (!top.debugMode) {
		if (!disallowRpc) doRPC(rpcId);
		if (g_isListUpToDate === null) setTimeout("checkRefresh('"+ rpcId + "', true)", 50);
		else {
	    	if(!g_isListUpToDate && !IsChildWinOpen()) PINT_safeReload();
			g_isListUpToDate = null;
		}
	}

}
function getRandomNumber(){
	return Math.floor(Math.random() * 10000000000000000).toString();
}

function getUrlSeparator(url){
	var separator = "?";
	if(url.indexOf('?') != -1) separator = "&";
	return separator;
}

// load multiple targets
function multipleTargetLink(srcArray, targetArray){
	for(var i=0; i<srcArray.length; i++){
		parent.document.getElementById(targetArray[i]).src = srcArray[i];
	}

}


// BEGIN: TABLE TOGGLE ===========================================================================================
// toggle a list item and change the icon of related list items
// i.e. indicate list items which has the same cid
var g_lastSelectedContainer = new Object();
var g_highlightCollection = false;

function TableToggleWorkflowRecord(idArray) {
    imgArray = new Array();
    for (var i=0; i < idArray.length; i++) {
        imgArray[i] = top.g_targetFrameWindow.document.getElementById('icon_workflow_' + idArray[i]);
        if (imgArray[i] == null) imgArray[i] = top.g_targetFrameWindow.document.getElementById('icon_list_item_highlighted_' + idArray[i]);
    }

    listItemsChooseImgIcon(imgArray, idArray);
    g_highlightCollection = true;
}

function listItemsChooseImgIcon(imgArray, idArray) {
    var img, imgId, divSystemId, img;

    for(i=0;i<imgArray.length;i++) {
        if (!imgArray[i]) break;
        img = imgArray[i];
        imgId = img.id;
        divSystemId = idArray[i];
        // Check to make sure the id isn't blank
        if (imgId) {
            if (imgId.search('workflow') >= 0 ) {
                img = eval('document.images["' + imgId  + '"]');
                img.src = (img.src).replace('workflow', 'list_item_highlighted');
                img.id = 'icon_list_item_highlighted_' + divSystemId;
            } else {
                img = eval('document.images["' + imgId  + '"]');
                img.src = (img.src).replace('list_item_highlighted', 'workflow');
                img.id = 'icon_workflow_' + divSystemId;
            }

        }
    }
}
// END: TABLE TOGGLE =============================================================================================


// BEGIN: DIV TOGGLE =============================================================================================
// toggle a checkbox and change the tr's class
var PINT_GlobalLastSelectedContainer = new Object;
var PINT_GlobalHighlightCollection = false;

function ToggleIsIndex()
	{
	if (ToggleIsIndex.arguments.length != 1) return false;

	var currentId = ToggleIsIndex.arguments[0];
	var indexElement = document.getElementById("_isIndex" + currentId);

	if (indexElement && indexElement.value) return true;
	else return false;
	}

function ToggleIsChecked()
	{
	if (ToggleIsChecked.arguments.length != 2) return false;

	var currentId = ToggleIsChecked.arguments[0];
	var currentElement = ToggleIsChecked.arguments[1];
	var radioElement = document.getElementById("radio" + currentId);

	if (radioElement)
		return radioElement.checked;
	else if (typeof(currentElement.elementChecked != "undefined"))
		return currentElement.elementChecked

	return false;
	}

function DivToggleWorkflowRecord(idArray)
	{
	for (var idIndex = 0; idIndex < idArray.length; idIndex++)
		{
		var currentId = idArray[idIndex];
		var container = document.getElementById("wrapper" + currentId);

		if (container)
			container.collectionHighlight = (container.collectionHighlight ? false: true);

		toggleDetermineClassDisplay(container, currentId);
		}

	// Prevent orginal toggle from happening
	PINT_GlobalHighlightCollection = true;
	}

function ToggleClickedRecord(container, input, type){
	if (g_allowListRowSelect && !PINT_GlobalHighlightCollection)
		{
		currentId = parseInt(input.id.replace("radio",""));
		input.checked = !input.checked;
		toggleDetermineClassDisplay(container, currentId)

		PINT_GlobalLastSelectedContainer = container;
		}

	// reset flag indicating collection highlight
	PINT_GlobalHighlightCollection = false;
}

function toggleDetermineClassDisplay()
	{
	if (toggleDetermineClassDisplay.arguments.length != 2) return false;

	var toggleElement = toggleDetermineClassDisplay.arguments[0];
	var toggleId = toggleDetermineClassDisplay.arguments[1];

	if (typeof(toggleElement.nativeClassName) == 'undefined') toggleElement.nativeClassName = toggleElement.className;

	if (toggleElement.collectionHighlight)
		{
		if (toggleElement.nativeClassName == "dragWrapperHidden")
			{
			if (ToggleIsChecked(toggleId, toggleElement )) toggleElement.className = "dragWrapperHiddenCollectionSelected";
			else toggleElement.className = "dragWrapperHiddenCollection";
			}
		else
			{
			if (ToggleIsChecked(toggleId, toggleElement )) toggleElement.className = "dragWrapperCollectionSelected";
			else toggleElement.className = "dragWrapperCollection";
			}
		}
	else if (toggleElement.nativeClassName == "dragWrapperIndex")
		{
		if (ToggleIsChecked(toggleId, toggleElement)) toggleElement.className = "dragWrapperIndexSelected";
		else toggleElement.className = "dragWrapperIndex";
		}
	else if (toggleElement.nativeClassName == "dragWrapperHidden")
		{
		if (ToggleIsChecked(toggleId, toggleElement)) toggleElement.className = "dragWrapperHiddenSelected";
		else toggleElement.className = "dragWrapperHidden";
		}
	else if (toggleElement.nativeClassName == 'dragWrapper')
		{
		if (ToggleIsChecked(toggleId, toggleElement)) toggleElement.className = "dragWrapperSelected";
		else toggleElement.className = "dragWrapper";
		}
	}

// toggle all checkbox's in a and change the tr's class
function DivToggleAllInFrame(iframeId, checked){
	// make sure there is a form
	if(window.frames[iframeId].document.forms[0].id){
		var field = window.frames[iframeId].document.forms[0].id;
		var selectedDiv;
		for (var i=0; i<field.length; i++){
			if(field[i].value != ""){
				field[i].checked = checked;
				selectedDiv = window.frames[iframeId].document.getElementById("wrapper" + field[i].value);
				selectedDiv.elementChecked = field[i].checked;
				if(selectedDiv){
					toggleDetermineClassDisplay(selectedDiv, field[i].value);
				}
			}
		}
	}
}
// END: DIV TOGGLE ===============================================================================================

 // send search parameters and values to an iframe on a form
 function searchIframeFromForm(iframeId, iframeSrc, keyName1, keyName2){
	// get the iframe we are to reload
	var iframe = document.getElementById(iframeId);

	var value1 =window.document.forms[0].elements[keyName1].value;
	var value2 = window.document.forms[0].elements[keyName2].value;
	args = keyName1 + '=' + value1 + '&' + keyName2 + '=' + value2;
	// reload the iframe with new order/sort
	var separator = "?";
	if(iframeSrc.indexOf('?') != -1) separator = "&";
	iframe.src = iframeSrc + separator + args;
}

// reload all iframes in the g_iframesToReload array
function reloadIframes(){
	var iframe;
	var iframes = g_iframesToReload;
	g_iframesToReload = new Array();
	for(var i=0; i<iframes.length; i++){
		//iframe = window.frames[iframes[i]];
		//iframe.location.reload(true);
		//alert(document.getElementById(iframes[i]).src);
		document.getElementById(iframes[i]).src = document.getElementById(iframes[i]).src;
	}
}

// reload all iframes in the g_iframesToReload array
function reloadSubscriptionIframe(cid){
	var source = parent.document.getElementById('subscriptionList').src;
	var seperator = "?";
	if(source.indexOf("?") != -1) seperator = "&";
	if(source.indexOf("&sCidList") != -1){
		source = source.substring(0,source.indexOf("&sCidList"));
	}
	if(source.indexOf("?sCidList") != -1){
		source = source.substring(0,source.indexOf("?sCidList"));
	}
	parent.document.getElementById('subscriptionList').src = source+seperator+"sCidList="+cid;
}

// click a tab or a next button
function changeFormScreen(requestedScreenIndex, formId){
	var wizardButtonClicked = changeFormScreen.arguments.length >= 3 ? changeFormScreen.arguments[2] : 0;
	var form = document.getElementById(formId);
	form.screenIndexDestination.value = requestedScreenIndex;
	if (wizardButtonClicked) form.wizardButtonClicked.value = wizardButtonClicked;

	// Checks to see if there is something binded to this event
	// if so run it.\
    submitForm(form, false);
}

// change form screens from form controls frame
function formControlsChangeFormScreen(offset, numScreens) {
	var currentIndex = getBodyFormField('screenIndexDestination');
	var nextIndex = parseInt(currentIndex) + parseInt(offset);
	// only switch screens if within the proper number of screens
	if ((nextIndex >= 0) && (nextIndex <= numScreens)) {
		setBodyFormField('screenIndexDestination',nextIndex);
		submitBodyForm(false, false, false);
	}
}

// adjust form controls next/back/finish buttons' styles appropiately
function enableFormControlsWizardButtons(screenIndex, numScreens) {
	var controlsDoc = parent.getFrameDocument("workspaceControls");
	backBtn   = controlsDoc.getElementById("_wscBtnBackDiv");
	nextBtn   = controlsDoc.getElementById("_wscBtnNextDiv");
	finishBtn = controlsDoc.getElementById("_wscBtnFinishDiv");
	if (screenIndex == 0) backBtn.className = "formControlButtondisable";
	else backBtn.className = "formControlButton";
	if (screenIndex == numScreens) {
		nextBtn.className   = "formControlButtonhidden";
		finishBtn.className = "formControlButton";
	}
	else {
		nextBtn.className   = "formControlButton";
		finishBtn.className = "formControlButtonhidden";
	}
}

// enable / disable form controls tabs as user navigates through them
function enableFormControlsTab(origin, destination) {
	var controlsDoc = parent.getFrameDocument("workspaceControls");
	originTab = controlsDoc.getElementById("_wscTab" + origin);
	destinationTab = controlsDoc.getElementById("_wscTab" + destination);
	originTab.className = "";
	destinationTab.className = "workbody_tabsOn";
}

// change order by of list and sort image
function changeIframeOrderBy(iframeId, iframeSrc, columnIndex){
	// get the iframe we are to reload
	var iframe = document.getElementById(iframeId);
	// get the next sort by for this iframe
	var sortBy = getNextSortBy(iframeId);
	// get the sort image we are going to change
	var sortImg = document.getElementById(iframeId + "_img_" + columnIndex);

	// get the last sort by image for this iframeId
	var lastSortImg = getLastSortImage(iframeId);
	// reload the iframe with new order/sort
	iframe.src = iframeSrc + getUrlSeparator(iframeSrc) + "order_by=" + columnIndex + "&sort_by=" + sortBy;

	// Check to see if the sort image exist.
	if (sortImg)
		{
		// change the image of the column we just clicked
		sortImg.src = rootDirectory + "/images/' + cmsTheme + '/img_arrow_" + sortBy + ".gif";
		// change the image of the last column we clicked unless it is the one we just clicked
		if(lastSortImg && (sortImg != lastSortImg)) lastSortImg.src = rootDirectory + "/images/space.gif";
		// save the image we just clicked
		setLastSortImage(iframeId, sortImg);
		}
	else lastSortImg.src = rootDirectory + "/images/space.gif";
}


// change order by of list and sort image
function changeOrderBy(frameHref, columnIndex, sortByValueAfterPageReload){
	// get the next sort by for the frame
	var sortBy = getNextSortBy('controls');
	// get the sort image we are going to change
	var sortImg = document.getElementById("order_img_" + columnIndex);
	// get the last sort by image for this iframeId
	var lastSortImg = getLastSortImage('controls');

    // this is for home tab -- sorting DIP list will reload the WHOLE page since list is in <div> instead of a frame
    // to remember the next sortBy value, we need to pass in this optional param (sortByValueAfterPageReload)
    if (typeof(sortByValueAfterPageReload) != 'undefined') sortBy = sortByValueAfterPageReload;

    // reload the frame with new order/sort
	parent.frames.workspaceBody.document.location.href = frameHref + getUrlSeparator(frameHref) + "order_by=" + columnIndex + "&sort_by=" + sortBy;

	// Check to see if the sort image exist.
	if (sortImg)
		{
		// change the image of the column we just clicked
		sortImg.src = rootDirectory + "/images/" + cmsTheme + "/img_arrow_" + sortBy + ".gif";
		// change the image of the last column we clicked unless it is the one we just clicked
		if(lastSortImg && (sortImg != lastSortImg)) lastSortImg.src = rootDirectory + "/images/space.gif";
		// save the image we just clicked
		setLastSortImage('controls', sortImg);
		}
	else if (lastSortImg) lastSortImg.src = rootDirectory + "/images/space.gif";
    // added if checking above to handle IE JS error when lastSortImg is null

}

// getLastSortImage
function getLastSortImage(iframeId){
	var img = null;
	if(typeof(g_lastSortImage[iframeId]) != "undefined") img = g_lastSortImage[iframeId];
	return img;
}

// setLastSortImage
function setLastSortImage(iframeId, sortImg){
	g_lastSortImage[iframeId] = sortImg;
}

function getNextSortBy(iframeId){
	var sortBy, nextSortBy;

	// if there is a sort stored for the iframe
	if(eval('typeof(g_listSortBy.' + iframeId + ')') != 'undefined') sortBy = eval('g_listSortBy.' + iframeId);
	else sortBy = 'asc';

	if(sortBy == 'asc') nextSortBy = 'desc';
	else nextSortBy = 'asc';

	// save the sort for this iframe
	eval('g_listSortBy.' + iframeId + ' = nextSortBy');
	return nextSortBy;
}

// formAddOptionToSelectFromText
function formAddOptionToSelectFromText(selectBoxId, textBoxId, hiddenFieldId){
	var selectBox = document.getElementById(selectBoxId);
	var textBox = document.getElementById(textBoxId);
	var hiddenField = document.getElementById(hiddenFieldId);

	if(textBox.value != ""){
		formAddOptionToSelect(selectBox, textBox.value, textBox.value)
		textBox.value = "";
		textBox.focus();
		formFieldValueFromOptions(selectBox, hiddenField);
	}
}


//change hidden text value on store form depending on dropdown selection.
function USA_CA_select(id, index, dynamicMapping){
	var value;
	value = document.getElementById(id.concat("List"));
	value = value[index].value;
	if(value == "Europe")
		document.getElementById("stateElement").parentNode.parentNode.style.display ="none";
	else
		document.getElementById("stateElement").parentNode.parentNode.style.display = "";
	document.getElementById(id.concat("TextField")).value=value;

	if(dynamicMapping){
		var mapImg = document.getElementById("mapImg");
		var country = "USA";
		if(value == "Europe"){
			country = "Eur";
		}
		else if(value == "Canada"){
			country = "Can";
		}
		var newSrc = "/sites/1_verrentscom/theme42/images/bg_location_"+country+".jpg";
		mapImg.src = newSrc;
	}
}


// formMoveOptionToSelectFromSelect
function formMoveOptionToSelectFromSelect(fromId, toId, idToGetValsFrom, hiddenFieldId){
	var fromSelectBox = document.getElementById(fromId);
	var toSelectBox = document.getElementById(toId);
	var selectToGetValsFrom = document.getElementById(idToGetValsFrom);
	var hiddenField = document.getElementById(hiddenFieldId);
	// optional args
	var lockedId = formMoveOptionToSelectFromSelect.arguments.length >= 5 ? formMoveOptionToSelectFromSelect.arguments[4] : null;

	var oldIndex = fromSelectBox.selectedIndex;

	if((fromSelectBox.selectedIndex >= 0) && fromSelectBox.options.length){
		while(fromSelectBox.selectedIndex >= 0){
			var text = fromSelectBox.options[fromSelectBox.selectedIndex].text;
			var title = fromSelectBox.options[fromSelectBox.selectedIndex].title;
			var value = fromSelectBox.options[fromSelectBox.selectedIndex].value;

			// XXX Huge hack to make news always a category on the category move-select
			if (value == lockedId) { alert(text + ' can not be removed'); return false; }

			// Find alphabetical insertion point
			var selectedIndex = 0;
			var selectedOption = null;
			for (i = 0; i < toSelectBox.options.length; i++) {
				// Lists are to be generated in a case-insensitive sorted order so we need to respect that here
				if ( text.toLowerCase() < toSelectBox.options[i].text.toLowerCase() ) {
					selectedIndex = i;
					selectedOption = toSelectBox.options[i];
					break;
				}
			}
			var option = new Option(text, value);
			option.title = title;
//			toSelectBox.options[toSelectBox.options.length] = option;
			// Insertion wrapped in a try/catch to handle W3C and IE differences
			// It might be better to detect IE rather than use exception handling
			try {
				toSelectBox.add(option,selectedOption);
			} catch (ex) {
				if ( selectedIndex ) {
					toSelectBox.add(option,selectedIndex);
				} else {
					toSelectBox.add(option);
				}
			}
			fromSelectBox.options[fromSelectBox.selectedIndex] = null;
			toSelectBox.selectedIndex = selectedIndex;	// Select the newly inserted option
		}

		fromSelectBox.focus();
		if(fromSelectBox.options.length) fromSelectBox.selectedIndex = oldIndex -1;
		formFieldValueFromOptions(selectToGetValsFrom, hiddenField);

	}
}

// formMoveOptionToSelectFromSelectMult
function formMoveOptionToSelectFromSelectMult(fromId, toId, firstIdToGetValsFrom, firstHiddenFieldId, secondIdToGetValsFrom, secondHiddenFieldId){
	var fromSelectBox = document.getElementById(fromId);
	var toSelectBox = document.getElementById(toId);
	var firstSelectToGetValsFrom = document.getElementById(firstIdToGetValsFrom);
	var firstHiddenField = document.getElementById(firstHiddenFieldId);
	var secondSelectToGetValsFrom = document.getElementById(secondIdToGetValsFrom);
	var secondHiddenField = document.getElementById(secondHiddenFieldId);

	if((fromSelectBox.selectedIndex >= 0) && fromSelectBox.options.length){
		while(fromSelectBox.selectedIndex >= 0){
			var text = fromSelectBox.options[fromSelectBox.selectedIndex].text;
			var value = fromSelectBox.options[fromSelectBox.selectedIndex].value;

			toSelectBox.options[toSelectBox.options.length] = new Option(text, value);
			fromSelectBox.options[fromSelectBox.selectedIndex] = null;
		}

		if(fromSelectBox.options.length) fromSelectBox.selectedIndex = 0;
		formFieldValueFromOptions(firstSelectToGetValsFrom, firstHiddenField);
		formFieldValueFromOptions(secondSelectToGetValsFrom, secondHiddenField);
	}
}

// formAddOptionToSelect
function formAddOptionToSelect(selectBox, label, value){
	selectBox.options[selectBox.options.length] = new Option(label, value);
}

// formRemoveSelectedOptions
function formRemoveSelectedOptions(selectBoxId, hiddenFieldId){
	var selectBox = document.getElementById(selectBoxId);
	var hiddenField = document.getElementById(hiddenFieldId);

	if((selectBox.selectedIndex >= 0) && selectBox.options.length){
		while(selectBox.selectedIndex >= 0){
			selectBox.options[selectBox.selectedIndex] = null;
		}
		if(selectBox.options.length) selectBox.selectedIndex = 0;
		formFieldValueFromOptions(selectBox, hiddenField);
	}
}

// formFieldValueFromOptions
function formFieldValueFromOptions(selectBox, field){
	field.value = "";
	for(var i=0; i<selectBox.options.length; i++){
		if(i > 0) field.value += ",";
		field.value += selectBox.options[i].value;
	}
	// if the hidden field exists, append its values always
	var hiddenField = document.getElementById(field.id + '_always_selected');
	if (hiddenField && (hiddenField.value != '')) {
		if (field.value != '') field.value += ',';
		field.value += hiddenField.value;
	}
}

// checkbox group value
function checkboxGroupValueUpdate(checkbox, hiddenField){

	var values = (hiddenField.value != '') ? hiddenField.value.split(",") : new Array;
	if (checkbox.checked) values.push(checkbox.value);
	else {
		var newValues = new Array;
		for (i=0; i<values.length; ++i){
			if (values[i] == checkbox.value) {
				values.splice(i, 1);
				break;
			}
		}
	}
	if (values.length) hiddenField.value = values.join(",");
	else hiddenField.value = '';
    alert(hiddenField.value + ":" + checkbox.id);
}

// clear a search form that has _filter* fields
function resetFilterFields(formId){
	var form = document.getElementById(formId);
	if (form) {
		var regex = /^_filter/;
		for (var i in form.elements) {
			if (regex.test(form.elements[i].name)) {
				if(form.elements[i].className == "radiobutton"){form.elements[i].checked = false;}
				else if (form.elements[i].selectedIndex) form.elements[i].selectedIndex = 0;
				else if (form.elements[i].value !== "") form.elements[i].value = "";

			}
		}
	}
}


// clears form errors
function clearFormErrors(){
	var errors = PINT_getElementsByClass("formError");
	for (var i in errors){
		errors[i].style.display = 'none';
	}
}

function actionOrdinalChange(ordinal, objectId, errorLocation, iFramesToReload)
{
	clearSystemMessages();

	parent.g_iframesToReload = iFramesToReload;

	document.location = PINT_GetRootDirectory() + "/object/action" + FILE_EXT + "?" +
	"apply=true"
	+ "&ordinal=" + ordinal
	+ "&errorLocation=" + PINT_GetRootDirectory() + '/reload_parent.htm'
	+ "&idList=" + objectId
	+ "&userAction=modify";
}


function getOffsetLeft(element){
	var offset_left_total = element.offsetLeft;
	while ((element = element.offsetParent) != null) offset_left_total += element.offsetLeft;
	return offset_left_total;
}

function getOffsetTop(element){
	var offset_top_total = element.offsetTop;
	while((element = element.offsetParent) != null) offset_top_total += element.offsetTop;
	return offset_top_total;
}

function getOffsetRight(element){
	var offset_left = getOffsetLeft(element);
	return offset_left + element.width;
}

function getOffsetBottom(element){
	var offset_top = getOffsetTop(element);
	return offset_top + element.height;
}

// if in debug mode, allow right clicking
function disableRightClick(){
	return top.debugMode;
}


function PINT_ContextMenuInit()
	{
	document.oncontextmenu = disableRightClick;
	}

function ChangeUploadRadioButtons(uploadElementName)
	{
	var elementName = uploadElementName.replace('upload', 'option');

	var fileOptionElement = document.getElementsByName(elementName);

	for(var fileOptionIndex = 0; fileOptionIndex < fileOptionElement.length; fileOptionIndex++)
		{
		if (fileOptionElement[fileOptionIndex].value == 'new_file')
			fileOptionElement[fileOptionIndex].checked = true;
		}
	}

function getProximateSystemMessageElement() {
	var element = null;
	var handle = window;
	while ((element = handle.document.getElementById('systemMessage')) == null) {
		// if handle has a parent frame
		if ((handle.parent) && (handle.parent != handle)) handle = handle.parent;
		// else if handle has a opener window
		else if (handle.opener) handle = handle.opener;
		else return null;
	}
	return element;
}

function setSystemMessage(message) {
	var systemMessage = getProximateSystemMessageElement();
	if (systemMessage == null) return;
	var newDiv = systemMessage.ownerDocument.createElement('div');
	newDiv.appendChild(systemMessage.ownerDocument.createTextNode(message));
	systemMessage.appendChild(newDiv);
}

function clearSystemMessages() {
	var systemMessage = getProximateSystemMessageElement();
	if (systemMessage == null) return;
	while (systemMessage.hasChildNodes()) systemMessage.removeChild(systemMessage.childNodes[0]);
}

var gbl_visibleOptionId = "";
function showOptionMenuItem(contentDataType) {
	var optionId = "__menu_" + contentDataType;
	// clear option
	hideOptionMenuItem();
	parent.gbl_visibleOptionId = optionId;
	option = parent.document.getElementById(optionId);
	//option.style.visibility = "visible";
	//option.style.position = "relative";
	option.style.display = "inline";
	//alert(optionId + ' display: ' + option.style.display);
}

function hideOptionMenuItem() {
	if (parent.gbl_visibleOptionId != '') {
		var option = parent.document.getElementById(parent.gbl_visibleOptionId);
		//option.style.visibility = "hidden";
		//option.style.position = "absolute";
		option.style.display = "none";
		parent.gbl_visibleOptionId = "";
	}
}

// sets the display style to the displayValue passed
// and any arguments following displayValue should be and element id
function setDisplayForElements(displayValue){
	for(var i=1; i < setDisplayForElements.arguments.length; i++) {
			document.getElementById(setDisplayForElements.arguments[i]).style.display=displayValue;
	}
}

// Browser Detection
isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
NS4 = (document.layers) ? true : false;
IEmac = ((document.all)&&(isMac)) ? true : false;
IE4plus = (document.all) ? true : false;
IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
ver4 = (NS4 || IE4plus) ? true : false;
NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;

// Body onload utility (supports multiple onload functions)
var gSafeOnload = new Array();
function safeAddOnload(f)
{
	if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
	{
		if (window.onload != SafeOnload)
		{
			// if there is an onload event for the window, save it for later execution
			if (window.onload) {
				var arr = window.onload.toString().match(/function\s*(\w+)/);
				//gSafeOnload[0] = arr[1] + "()";
			}
			window.onload = SafeOnload;
		}
		gSafeOnload[gSafeOnload.length] = f;
	}
}

function safePrependOnload(f) {
	if (!gSafeOnload.length) safeAddOnload(f);
	else gSafeOnload.unshift(f);
}

function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++) {
		if (gSafeOnload[i] != null) {
			eval(gSafeOnload[i]);
		}
	}
}

// Body onUnload utility (supports multiple onUnload functions)
var gSafeOnUnload = new Array();
function safeAddOnUnload(fn){
	if (window.onunload != safeOnUnload) {
		if (window.onunload) gSafeOnUnload.push(window.onunload);
		window.onunload = safeOnUnload;
	}
	gSafeOnUnload.push(fn);
}

function safeOnUnload() {
	for (var i=0; i<gSafeOnUnload.length; i++) {
		if (gSafeOnUnload[i] != null) eval(gSafeOnUnload[i]);
	}
}


//  onResize utility (supports multiple onResize functions)
var gSafeOnResize = new Array();
function safeAddOnResize(fn){
	if (window.onresize != safeOnResize) {
		if (window.onresize) gSafeOnResize.push(window.onresize);
		window.onresize = safeOnResize;
	}
	gSafeOnResize.push(fn);
}

function safeOnResize() {
	for (var i=0; i<gSafeOnResize.length; i++) {
		if (gSafeOnResize[i] != null) eval(gSafeOnResize[i]);
	}
}



// BEGIN: DRAG FUNCTIONS ===============================================================================

// Global object to hold drag information.
var dragObj = new Object();
var dragStarted = false;

PINT.firstOrdinal = 0;

//function dragStart(event, id)
function dragStart(event, id, objectId, isOrderable) {
dragObj.zIndex = 10;
dragObj.newOrdinal = null;
// create highlightDiv
dragObj.hiNode = document.createElement("div");
dragObj.hiNode.id = "borderHighlight";
dragObj.hiNode.className = "highlightBorder";
dragObj.hiNode.style.position="absolute";
	if(!isOrderable) {
		if(document.all) {
			document.attachEvent("onmousemove", noDragAllowed);
			document.attachEvent("onmouseup",   noDragAllowedStop);
		}
		else {
			document.addEventListener("mousemove", noDragAllowed,   true);
			document.addEventListener("mouseup",   noDragAllowedStop, true);
		}
	}
	else {
		dragStarted = true;
		document.body.style.cursor = 'move';

	    if(!top.g_targetFrameWindow) top.g_targetFrameWindow = self;
		// call this function, which should be in the top frame with the context menu stuff, to de-select any items
		top.setSelectionAllElements("off");

		var el;
		var x, y;
		// create the 'drag' element that will attach to the cursor
		dragObj.elNode = document.createElement("div");
		dragObj.elNode.id = "XXX"+id;
		dragObj.elNode.className = document.getElementById(id).className;
		dragObj.origNodeId = id;
		dragObj.elNode.style.position="absolute";

		var origHTML = document.getElementById(id).innerHTML;
	    var newHTML = origHTML.replace("id=", "id=XXX");
		dragObj.elNode.innerHTML = newHTML;

		// Get cursor position with respect to the page.
		if (document.all) y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
		else y = event.clientY + window.scrollY;

		dragObj.elNode.style.top = document.getElementById(id).offsetTop+"px";
		// attach drag node to document
	    document.getElementById(id).parentNode.appendChild(dragObj.elNode);
		// attach highlight node too
		document.getElementById(id).parentNode.appendChild(dragObj.hiNode);
		dragObj.hiNode.style.display = "none";

		dragObj.origId = id;
		dragObj.origClassName = document.getElementById(id).className;
		document.getElementById(id).style.visibility="hidden";

		// Set the Transparent Class.
		dragObj.elNode.className = dragObj.elNode.className + " transparent";

		// Capture mousemove and mouseup events on the page.
		if (document.all) {
			document.attachEvent("onmousemove", dragGo);
			document.attachEvent("onmouseup",   dragStop);
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
	    else {
			document.addEventListener("mousemove", dragGo,   true);
			document.addEventListener("mouseup",   dragStop, true);
			event.preventDefault();
	   }
   }
}

function noDragAllowed(event) {
    if (document.all) document.detachEvent("onmousemove", noDragAllowed);
	else document.removeEventListener("mousemove", noDragAllowed,   true);
	if(confirm("You can not reorder items unless they are sorted by their display order.\n Would you like to resort these items by their display order?")) {
		var params = new Array();
		params['order_by'] = 'default';
		params['sort_by'] = 'asc';
	    var queryString = getUpdatedQueryString(document.location.search, params);
		document.location = document.location.pathname + queryString;
	}
}

function getUpdatedQueryString(queryString, params){
	var regex;
	queryString = queryString.replace(/^\?/, '');
	for (i in params){
		regex = new RegExp("(" + i + "\=)([^\&]+)", "i");
		if (queryString.match(regex)) queryString = queryString.replace(regex, "$1" + params[i]);
		else queryString += "&" + i + "=" + params[i];
	}
	return "?" + queryString;
}

function noDragAllowedStop(event) {
    if (document.all) {
		document.detachEvent("onmousemove", noDragAllowed);
		document.detachEvent("onmouseup", noDragAllowedStop);
	}
	else {
		document.removeEventListener("mousemove", noDragAllowed,   true);
		document.removeEventListener("mouseup", noDragAllowed,   true);
	}

}

function dragGo(event) {
	var x, y;
    // Get cursor position with respect to the page.
	if (document.all) y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	else y = event.clientY + window.scrollY;
	// set the location of the element you are dragging
	dragObj.elNode.style.top = y-(dragObj.elNode.offsetHeight/2)+ "px";
	dragObj.newOrdinal = null;
	dragObj.hiNode.style.display = "block";

	for(var i in orderableElements) {
	      // remove any highlights
		  dragObj.hiNode.style.visibility="hidden";
		  // if the cursor is inside this element
		  if (document.getElementById(i) && i != dragObj.origId && y >= document.getElementById(i).offsetTop && y <= (document.getElementById(i).offsetTop + document.getElementById(i).offsetHeight)) {
			  // if the cursor is over the top half
			  if(y <= (document.getElementById(i).offsetTop+(document.getElementById(i).offsetHeight/2))) {
				  dragObj.hiNode.style.top= document.getElementById(i).offsetTop+"px";
				  dragObj.hiNode.style.visibility="visible";
				  if(orderableElements[dragObj.origId] > orderableElements[i]) dragObj.newOrdinal = orderableElements[i];
				  else dragObj.newOrdinal = orderableElements[i]-1;
			  }
			  else { // cursor is over the bottom half
                dragObj.hiNode.style.top= document.getElementById(i).offsetTop + document.getElementById(i).offsetHeight+"px";
                dragObj.hiNode.style.visibility="visible";
                if(orderableElements[dragObj.origId] > orderableElements[i]) dragObj.newOrdinal = orderableElements[i]+1;
                else dragObj.newOrdinal = orderableElements[i];
			  }
			  break;
		  } // if we are above all the orderable elements, set the ordinal to 0
		  else if(orderableElements[i] == 1 && y <  document.getElementById(i).offsetTop) {
		          dragObj.hiNode.style.top= document.getElementById(i).offsetTop+"px";
				  dragObj.hiNode.style.visibility="visible";
				  dragObj.newOrdinal = 0;
				  break;
		  } // if we are below all the orderable elements set the ordinal to the lastOrdinal (highest ordinal)
		  else if (orderableElements[i] == lastOrdinal && y > (document.getElementById(i).offsetTop + document.getElementById(i).offsetHeight)) {
		          dragObj.hiNode.style.top= document.getElementById(i).offsetTop + document.getElementById(i).offsetHeight+"px";
				  dragObj.hiNode.style.visibility="visible";
				  dragObj.newOrdinal = lastOrdinal;
				  break;
		  }
	}

	if (document.all) {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	else event.preventDefault();
}

function dragStop(event) {
	dragStarted = false;
	document.body.style.cursor = 'default';
	// Get cursor position with respect to the page.
	if (document.all) y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	else y = event.clientY + window.scrollY;
	// Stop capturing mousemove and mouseup events.
  	if (document.all) {
    	document.detachEvent("onmousemove", dragGo);
    	document.detachEvent("onmouseup",   dragStop);
  	}
	else {
    	document.removeEventListener("mousemove", dragGo,   true);
    	document.removeEventListener("mouseup",   dragStop, true);
	}
	// get rid of the drag div and highlight div
	dragObj.hiNode.style.visibility = "hidden";
	dragObj.elNode.parentNode.removeChild(dragObj.elNode);
	dragObj.hiNode.parentNode.removeChild(dragObj.hiNode);

	// if we have a new ordinal
	if(dragObj.newOrdinal != null) {
	    var origOrdinal = orderableElements[dragObj.origId];
		var updatedOrdinal;
		var currentOrdinalElement;
		var elementToReplace;
		// loop through element/ordinal array and find your new position
		for (var i in orderableElements) {
		    // if ordinal needs to be updated this variable will contain the updated ordinal
		    updatedOrdinal = false;
			// find the div element displaying the ordinal
			currentOrdinalElement = document.getElementById(i+'_ordinal');
			// if this element has the ordinal that the 'drag' element is going to have then this is the element to replace
			if ((orderableElements[i] == dragObj.newOrdinal) || (dragObj.newOrdinal == 0 && orderableElements[i] == 1)) elementToReplace = i;
			// determine the ordinal position of this element and reset its value in orderableElements
			if (dragObj.newOrdinal > origOrdinal && (orderableElements[i] > origOrdinal && orderableElements[i] <= dragObj.newOrdinal)) {
				updatedOrdinal = orderableElements[i] - 1;
				orderableElements[i] = updatedOrdinal;
			}
			else if (dragObj.newOrdinal < origOrdinal && (orderableElements[i] < origOrdinal && orderableElements[i] >= dragObj.newOrdinal)) {
				updatedOrdinal = orderableElements[i] + 1;
				orderableElements[i] = updatedOrdinal;
			}
			// if updatedOrdinal is set then we need to display the new ordinal
			if(updatedOrdinal) {
				currentOrdinalElement.innerHTML = '';
				currentOrdinalElement.innerHTML = updatedOrdinal;
			}
	    }
		// set the updatedOrdinal for our 'drag' element
		if (dragObj.newOrdinal == 0) updatedOrdinal = 1;
		else updatedOrdinal = dragObj.newOrdinal;
		// find the div element displaying the ordinal and update
		currentOrdinalElement = document.getElementById(dragObj.origId+'_ordinal');
		currentOrdinalElement.innerHTML = '';
		currentOrdinalElement.innerHTML = updatedOrdinal;
		orderableElements[dragObj.origId] = updatedOrdinal;

		// set up duplicate of original element
		var newDiv = document.createElement("div");
		newDiv.className= dragObj.origClassName;
		newDiv.oncontextmenu = document.getElementById(dragObj.origId).oncontextmenu;
        newDiv.onclick = document.getElementById(dragObj.origId).onclick;
        newDiv.ondblclick = document.getElementById(dragObj.origId).ondblclick;
		newDiv.innerHTML = document.getElementById(dragObj.origId).innerHTML;
		//if the updatedOrdinal < origOrdinal or updatedOrdinal = 1 then insert node before elementToReplace otherwise it goes after
		if(updatedOrdinal < origOrdinal || updatedOrdinal == 1) document.getElementById(dragObj.origId).parentNode.insertBefore(newDiv, document.getElementById(elementToReplace));
		else document.getElementById(dragObj.origId).parentNode.insertBefore(newDiv, document.getElementById(elementToReplace).nextSibling);
		// remove the orginal element
		document.getElementById(dragObj.origId).parentNode.removeChild(document.getElementById(dragObj.origId));
		// give the new element the old elements id
		newDiv.id = dragObj.origId;
		// adjust ordinals in menu target elements
		top.adjustContextMenuTargetElementOrdinals(dragObj.origId, updatedOrdinal, false);
	}
     // set the element back to visible
	 document.getElementById(dragObj.origId).style.visibility="visible";
	 dragObj.newOrdinal = null;
}

// END: DRAG FUNCTIONS ===============================================================================

function PINT_SwapClassName() {
	if (!dragStarted) {
		if (PINT_SwapClassName.arguments.length != 3) return false;

		if (PINT_SwapClassName.arguments[0].className == PINT_SwapClassName.arguments[1]) PINT_SwapClassName.arguments[0].className = PINT_SwapClassName.arguments[2];
		else if (PINT_SwapClassName.arguments[0].className == PINT_SwapClassName.arguments[2]) PINT_SwapClassName.arguments[0].className = PINT_SwapClassName.arguments[1];
	}
}

function confirmSortPage() {
	if (confirm("To move this item the page needs to be sorted by ordinal. Would you like to reload this page?")){
	    parent.changeIframeOrderBy('doc_nav_list', '/cms/object/_list_pages/list_nav' + FILE_EXT, '4');
	}

	return false;
}

//------------------------------------------------------------------------------
// TODO -- change any where in cms using these fuynctions to use the
// generic titled 'selectItems' versions below
//
// Select Related Content Functions
//------------------------------------------------------------------------------

function setSelectedRelatedContentHiddenField(contentId, formId, fieldName) {
	var idArray = new Array();
	var e = eval("parent.document." + formId + "['" + fieldName + "']");
	if (e.value.length) idArray = e.value.split(",");
	idArray.push(contentId);
	e.value = idArray.join(",");
}

function unsetSelectedRelatedContentHiddenField(contentId, formId, fieldName) {
	var valueArray = new Array();
	var e = eval("parent.document." + formId + "['" + fieldName + "']");
	if (typeof(contentId) != 'undefined') {
		idArray = e.value.split(",");
		for (i=0; i<idArray.length; i++) {
			if (idArray[i] != contentId) valueArray.push(idArray[i]);
		}
	}
	e.value = valueArray.join(",");
}

/**
 * select related content for object
 * @param object form to search
 * @param string parent model id
 * @param string action page
 */
function selectRelatedContent(formId, fieldName, formAction, maxItems) {
	var idList = eval("document." + formId + "['" + fieldName + "']" + ".value");
	var theForm = eval("document." + formId);

	var numSelected = (idList != '') ? (idList.split(",")).length : 0;
	maxItems = parseInt(maxItems) ? parseInt(maxItems) : 9999;
	if (numSelected && (numSelected <= maxItems)){
		theForm.action = formAction;

		if(window.opener.top.debugMode) theForm.target = "_blank";
		else theForm.target = "selectHiddenFrame";

		// don't submit the form if there is an onsubmit and it returns false
		var doSubmit = true;
		if (theForm.onsubmit) doSubmit = theForm.onsubmit();
		if (doSubmit !== false) theForm.submit();
	}
	else {
		// alert error messages
		if ((maxItems == 9999) || (maxItems == 1)) { alert('You must select an item'); return false; }
		else if (maxItems < 9999) { alert('You must select between 1 and ' + maxItems + ' items'); return false; }
	}
	return true;
}

//------------------------------------------------------------------------------
// Select Related Items Functions
// these functions are for forms that use a list page (usually in an iframe) to select items
//------------------------------------------------------------------------------
function setSelectedRelatedItemHiddenField(itemId, formId, fieldName) {
	var idArray = new Array();
	var e = eval("parent.document." + formId + "." + fieldName);
	if (e.value.length) idArray = e.value.split(",");
	idArray.push(itemId);
	e.value = idArray.join(",");
}

function unsetSelectedRelatedItemHiddenField(itemId, formId, fieldName) {
	var valueArray = new Array();
	var e = eval("parent.document." + formId + "." + fieldName);
	if (typeof(itemId) != 'undefined') {
		idArray = e.value.split(",");
		for (i=0; i<idArray.length; i++) {
			if (idArray[i] != itemId) valueArray.push(idArray[i]);
		}
	}
	e.value = valueArray.join(",");
}
/**
 * select related items for object
 * @param object form to search
 * @param string filedName containing a list of ids
 * @param string action page
 * @param int maximum number of items allowed
 */
function selectRelatedItems(formId, fieldName, formAction, maxItems) {
	var idList = eval("document." + formId + "." + fieldName + ".value");
	var theForm = eval("document." + formId);

	var numSelected = (idList != '') ? (idList.split(",")).length : 0;
	maxItems = parseInt(maxItems) ? parseInt(maxItems) : 9999;
	if (numSelected && (numSelected <= maxItems)){
		theForm.action = formAction;

		if(window.opener.top.debugMode) theForm.target = "_blank";
		else theForm.target = "selectHiddenFrame";

		// don't submit the form if there is an onsubmit and it returns false
		var doSubmit = true;
		if (theForm.onsubmit) doSubmit = theForm.onsubmit();
		if (doSubmit !== false) theForm.submit();
	}
	else {
		// alert error messages
		if ((maxItems == 9999) || (maxItems == 1)) alert('You must select an item');
		else if (maxItems < 9999) alert('You must select between 1 and ' + maxItems + ' items');
	}
}



//------------------------------------------------------------------------------
// Classification Functions
//------------------------------------------------------------------------------

/**
 * select classification for an object
 * @param object form to search
 * @param string the meta class Id to change
 */
function selectClassification(formId, metaClassId) {
	var idList = eval("document." + formId + ".selectedClassificationId.value");
	var breadcrumb = eval("document." + formId + ".selectedClassificationBreadcrumb.value");

	var numSelected = (idList != '') ? (idList.split(",")).length : 0;
	if (numSelected == 1){
		var temp = top.opener.document.getElementById('classificationId-'+metaClassId);
		// for the main module page
		var temp1 = top.opener.document.getElementById('displayclassificationId-'+metaClassId);
		temp.value = idList;
		temp1.innerHTML = breadcrumb;
		return true;
	}
	else {
		// alert error messages
		alert('You must select a classification');
	}
		return false;
}

/**
 * select a (single) classification for an object, sets the display
 * breadcrumb and the hidden classification id field
 * @param string classificationId
 * @param string breadcrumb
 */
function setSelectedClassificationHiddenField(classificationId, breadcrumb) {
	// sets the hidden fields so they'll be saved when we hit done
	var e = parent.document.classificationSelectForm.selectedClassificationId;
	e.value = classificationId;
	var f = parent.document.classificationSelectForm.selectedClassificationBreadcrumb;
	f.value = breadcrumb;

	// displays breadcrumb on current screen
	var g = parent.document.getElementById('selectedBreadcrumb');
	g.innerHTML = breadcrumb;


}

/**
 * gets the classification id set in the hidden field
 * breadcrumb and the hidden classification id field
 * @param string classificationId
 * @param string breadcrumb
 */
function getSelectedClassificationHiddenField() {
	var e = parent.document.classificationSelectForm.selectedClassificationId;
	return e.value
}


//------------------------------------------------------------------------------
// Asset Functions
//------------------------------------------------------------------------------
function alertSelectedAsset(formId) {
	alert(eval("document." + formId + ".assetId.value"));

}

//// TODO -- convert these 3 asset related functions to use the
// generic titled 'selectItems' versions above
function setSelectedAssetHiddenField(assetId) {
	var idArray = new Array();
	var e = parent.document.assetSearchForm.assetId;
	if (e.value.length) idArray = e.value.split(",");
	idArray.push(assetId);
	e.value = idArray.join(",");
}

function unsetSelectedAssetHiddenField(assetId) {
	var valueArray = new Array();
	var e = parent.document.assetSearchForm.assetId;
	if (typeof(assetId) != 'undefined') {
		idArray = e.value.split(",");
		for (i=0; i<idArray.length; i++) {
			if (idArray[i] != assetId) valueArray.push(idArray[i]);
		}
	}

	e.value = valueArray.join(",");
}




/**
 * select asset for object
 * @param object form to search
 * @param string parent model id
 * @param string action page
 */
function selectAsset(formId, parentModelId, formAction, maxAssets) {
	var idList = eval("document." + formId + ".assetId.value");
	var numSelected = (idList != '') ? (idList.split(",")).length : 0;
	maxAssets = parseInt(maxAssets) ? parseInt(maxAssets) : 9999;
	if (numSelected && (numSelected <= maxAssets)){
		var actionUrl = formAction + getUrlSeparator(formAction) + 'parentModelId=' + parentModelId + '&userAction=add&idList=' + idList + '&maxAssets=' + maxAssets;
		if(window.opener.top.debugMode) window.open(actionUrl);
		else document.getElementById('hiddenFrame').src = actionUrl;
	}
	else {
		// alert error messages
		if ((maxAssets == 9999) || (maxAssets == 1)) alert('You must select an asset');
		else if (maxAssets < 9999) alert('You must select between 1 and ' + maxAssets + ' assets');
	}
}


/**
 * select list item
 * @param object form to search
 * @param string parent model id
 * @param string action page
 */
function selectListItem(formId, parentModelId, formAction, elementId) {
	var id = eval("document." + formId + "."+elementId+".value");
	var actionUrl = formAction + getUrlSeparator(formAction) + 'parentModelId=' + parentModelId + '&userAction=add&id=' + id;
	if(window.opener.top.debugMode) window.open(actionUrl);
	else document.getElementById('hiddenFrame').src = actionUrl;

}

function removeAsset(usage) {
    var assetPreview  = document.getElementById("_asset"+usage+"Preview");
    var assetFileInfo = document.getElementById("_asset"+usage+"FileInfo");
    var assetName     = document.getElementById("_asset"+usage+"Title");
    var assetEdit     = document.getElementById("_asset"+usage+"Edit");
    var assetAdd      = document.getElementById("_asset"+usage+"Add");

    assetPreview.src = PINT_GetRootDirectory() + "/images/space.gif";
    assetFileInfo.style.position = "absolute";
    assetFileInfo.style.visibility = "hidden";
    assetName.innerHTML = "";
    assetAdd.style.display = "";
    assetEdit.style.display = "none";
}

/**
 * updates asset preview image
 */
function updateAssetPreview(usage, assetPath, assetTitle){
    var assetPreview  =  document.getElementById("_asset"+usage+"Preview");
    var assetFileInfo =  document.getElementById("_asset"+usage+"FileInfo");
    var assetName     =  document.getElementById("_asset"+usage+"Title");
    var assetEdit   =  document.getElementById("_asset"+usage+"Edit");
    var assetAdd    =  document.getElementById("_asset"+usage+"Add");

    assetPreview.src = assetPath;
    assetFileInfo.style.position = "relative";
    assetFileInfo.style.visibility = "visible";
    assetName.innerHTML = assetTitle;

    assetAdd.style.display = "none";
    assetEdit.style.display = "";
}

/**
 * updates asset preview image
 */
function updateAssetModifierSelect(){
    var objSelSite = PINT_GetElementById(selectSiteId);
    var objSelModBy = PINT_GetElementById(selectModById);
    var currSiteId = currentSiteId;
    var currAssetModifiers = assetModifiers;
    var i=0;

    if(objSelSite && objSelModBy){
        objSelModBy.options.length = 0;
        objSelModBy.options[i++] = new Option('Anyone','anyone');

        if (currAssetModifiers && currentSiteId && (currentSiteId==objSelSite.value)){
            objSelModBy.options[i++] = new Option('Me',meId);
            for(j in currAssetModifiers) {
                objSelModBy.options[i++] = new Option(currAssetModifiers[j],j);
            }
        }
    }
}

// password verification
var g_retypeText;
var g_origText;
function retypePrompt(text){
	if (text.value != ''){
		var div = document.getElementById(text.id + '_retype_div');
		g_retypeText = document.getElementById(text.id + '_retype_text');
		div.style.visibility = 'visible';
		// this timeout was done b/c ie won't give focus unless there is a delay
		if (document.all) setTimeout("g_retypeText.focus()", 1);
		else g_retypeText.focus();
		disableAllForms();
	}
}

function setObjectGeneratedName(titleField, genNameFieldId){
    var genNameField = document.getElementById(genNameFieldId);
	if (genNameField && !genNameField.value) {
		var genVal = titleField.value.toLowerCase();
		// replace all - with a space
		genVal = genVal.replace(/-+/g, ' ');
		// remove everything but word chars and spaces
		genVal = genVal.replace(/[^\w ]+/g, '');
		// strip all leading/trailing spaces
		genVal = genVal.replace(/^\s*/g, '');
		genVal = genVal.replace(/\s*$/g, '');
		// replace all spaces w/ -
		genVal = genVal.replace(/\s+/g, '-');
		genNameField.value = genVal;
	}
	return true;
}

function requireEqualValues(text, retypeText){
	var div = document.getElementById(text.id + '_retype_div');
	g_origText = text;
	if (text.value != retypeText.value){
		alert('Values do not match');
		text.value= '';
		// this timeout was done b/c ie won't give focus unless there is a delay
		if (document.all) setTimeout("g_origText.focus()", 1);
		else g_origText.focus();
	}
	div.style.visibility = 'hidden';
	retypeText.value= '';
	enableAllForms();
}

// disable form functions
var g_disabledForms = new Array();
function disableAllForms(){
	for (var i=0; i<document.forms.length; i++){
		g_disabledForms[document.forms[i].id] = document.forms[i].onsubmit;
		document.forms[i].onsubmit = function(){return false;}
	}
}

function enableAllForms(){
	for (var i=0; i<document.forms.length; i++){
		document.forms[i].onsubmit = g_disabledForms[document.forms[i].id];
	}
}

var rot13map;
function rot13init()
	{
    var map = new Array();
    var s   = "abcdefghijklmnopqrstuvwxyz";
    for (i=0; i<s.length; i++) map[s.charAt(i)] = s.charAt((i+13)%26);
    for (i=0; i<s.length; i++) map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
    return map;
	}

function rot13(a)
	{
    if (!rot13map) rot13map=rot13init();
    var s = "";
    for (i=0; i<a.length; i++)
    {
        var b = a.charAt(i);
        s += (b>='A' && b<='Z' || b>='a' && b<='z' ? rot13map[b] : b);
    }
    return s;
	}


// named this for obfuscation
function print_e(user, domain)
	{
	var e = rot13(user) + "@" + rot13(domain);
	var out = '<a href="mailto:' + e + '">';
	out += e;
	out += '</a>';
	document.write(out);
	}


function DisableEventFormFields()
	{
	if (DisableEventFormFields.arguments.length <= 1) return false;
	var radioElementValue = DisableEventFormFields.arguments[0].value;

	for (var fieldIndex = 1; fieldIndex < DisableEventFormFields.arguments.length; fieldIndex++)
		{
		currentElement = document.getElementById(DisableEventFormFields.arguments[fieldIndex])

		if (currentElement)
			{
			if (radioElementValue == 1)
				{
				currentElement.disabled = false;
				currentElement.className = "textInput";
				}
			if (radioElementValue == 0)
				{
				currentElement.disabled = true;
				currentElement.className = "textInputDisabled";
				}
			}
		}
	}

function DisableEventFormFieldsOnload()
	{
	if (DisableEventFormFieldsOnload.arguments.length != 2) return false;
	document.getElementById(DisableEventFormFieldsOnload.arguments[0]).className = "textInputDisabled";
	document.getElementById(DisableEventFormFieldsOnload.arguments[1]).className = "textInputDisabled";
	}

function SetSendEmailOnUpdate()
	{
	if (SetSendEmailOnUpdate.arguments.length != 2) return false;
	var yesElement = document.getElementById(SetSendEmailOnUpdate.arguments[0]);
	var noElement = document.getElementById(SetSendEmailOnUpdate.arguments[1]);

	if (confirm("Would you like to notify subscribers that this content has been updated?\nPress OK to notify subscribers of the update.\nPress Cancel if you do not want to send a notification."))
		{
		yesElement.checked = true;
		noElement.checked = false;
		}
	else
		{
		yesElement.checked = false;
		noElement.checked = true;
		}
	}

// frame resize functions ===================================
function show(idList){
	var ids = idList.split(",");
	for (i in ids) document.getElementById(ids[i]).style.display = 'block';
}

function hide(idList){
	var ids = idList.split(",");
	for (i in ids) document.getElementById(ids[i]).style.display = 'none';
}

function changeFramesetRowHeight(framesetId, rowIndex, height){
	var frameset = top.document.getElementById(framesetId);
	// store the old frameset rows if it isn't already
	if (eval('typeof(frameset.origRows)') == 'undefined'){
		frameset.origRows = frameset.rows.split(",");
	}

	var newRows = copyArray(frameset.origRows);
	newRows[rowIndex] = height + "px";
	frameset.rows = newRows.join(",");
}

function restoreFramesetRowHeights(framesetId){
	var frameset = top.document.getElementById(framesetId);
	frameset.rows = frameset.origRows.join(",");
}

function changeFramesetColumnWidth(framesetId, colIndex, width){
	var frameset = top.document.getElementById(framesetId);
	// store the old frameset cols if it isn't already
	if (eval('typeof(frameset.origColumns)') == 'undefined'){
		frameset.origColumns = frameset.cols.split(",");
	}

	var newColumns = copyArray(frameset.origColumns);
	newColumns[colIndex] = width + "px";
    frameset.cols = newColumns.join(",");
}

function getWindowInnerDimensions() {
    var dim = new Object();
    if (self.innerHeight) {
    	dim.width = self.innerWidth;
    	dim.height = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        // Explorer 6 Strict Mode
    	dim.width = document.documentElement.clientWidth;
    	dim.height = document.documentElement.clientHeight;
    }
    else if (document.body) {
    	dim.width = document.body.clientWidth;
    	dim.height = document.body.clientHeight;
    }
    return dim;
}

function restoreFramesetColumnWidth(framesetId){
	var frameset = top.document.getElementById(framesetId);
	frameset.cols = frameset.origColumns.join(",");
}


function copyArray(orig) {
	var copy = new Array();
    for (i in orig) {
		if (typeof orig[i] == 'array') copy[i] = copyArray(orig[i]);
        else copy[i] = orig[i];
    }
	return copy;
}

// END frame resize functions ===================================

var g_bigNavButton = new Object;
var g_smallNavButton = new Object;
function highlightNavButtons(id){
	g_bigNavButton.className = 'buttons';
	g_smallNavButton.className = 'smallbuttons';
	var bigButton = document.getElementById(id);
	var smallButton = document.getElementById(id + "_small");
	bigButton.className = "buttonson";
	smallButton.className = "smallbuttonson";
	g_bigNavButton = bigButton;
	g_smallNavButton = smallButton;
}


function getFrameDocument(frameName, doc){
	if (!doc) doc = document;
	var frameWindow = getFrameWindow(frameName, doc);
	if (doc.all) var frameDocument = frameWindow.document;
	else var frameDocument = frameWindow.contentDocument;
	return frameDocument;
}

function getFrameWindow(frameName, doc){
	if (!doc) doc = document;
	if (doc.all) var frameWindow = doc.frames[frameName];
	else var frameWindow = doc.getElementById(frameName);
	return frameWindow;
}

function fixWorkspaceControlsWidth(){
    // if there is a scrollbar, add 16px to the right side of the controls body
    var controlsDoc = parent.getFrameDocument("workspaceControls");
    // just to make sure object is seen by browser
    if (controlsDoc && controlsDoc.body) {
        // ie always needs the padding
        if (document.all) controlsDoc.body.style.paddingRight = '16px';
        else if (document.documentElement.clientHeight) {
            // no scrollbar
            if (document.body.scrollHeight < document.documentElement.clientHeight) controlsDoc.body.style.paddingRight = '0px';
            // scrollbar
            else controlsDoc.body.style.paddingRight = '16px';
        }
    }
}

function reloadFileManagerControls(systemId){
	var controlsDoc = top.g_targetFrameWindow.parent.getFrameDocument("workspaceControls");
	var loc = controlsDoc.location.href.replace(/fileIndexPush=\d+/, '');
	loc = controlsDoc.location.href.replace(/dirPopCount=\d+/, '');
	loc = loc + getUrlSeparator(loc) + 'fileIndexPush=' + systemId;
	controlsDoc.location = loc;
}

// START context menu wrappers ==================================

function handleContextMenuTargetContextmenuWrapper(e){
	return top.handlerDispatcher('handleContextMenuTargetContextmenu', e, self);
}

function handleContextMenuTargetClickWrapper(e){
	return top.handlerDispatcher('handleContextMenuTargetClick', e, self);
}

function handleContextMenuTargetDblClickWrapper(e){
	return top.handlerDispatcher('handleContextMenuTargetDblClick', e, self);
}

function clickEventsWrapper(e){
	return top.handlerDispatcher('clickEvents', e, self);
}

function hideMenuWrapper(e){
	if(top) return top.handlerDispatcher('hideMenu', e, self);
}

function keyPressEventsWrapper(e){
	if(top.handlerDispatcher)  return top.handlerDispatcher('keyPressEvents', e, self);
}

function keyDownEventsWrapper(e){
	if(top.handlerDispatcher)  return top.handlerDispatcher('keyDownEvents', e, self);
}

function disableTextWrapper(e){
	return top.handlerDispatcher('disableText', e, self);
}

var g_contextMenus = new Array();
var g_currentSelectionGroup;
var g_contextMenuTargetElements = new Array();

function ContextMenu(){}
function ContextMenuTargetElement(){
	this.targetInfo = new Array();
}
function ContextMenuTargetElementInfo() {}
function SubMenu(){}
function MenuSeparator(){}
function MenuItem(){}


var menu = new Array(); // current context menu

document.onkeypress = keyPressEventsWrapper; // for mozilla/firefox
document.onkeydown = keyDownEventsWrapper;

function loadContextMenuEvents(){
	document.onclick = clickEventsWrapper;
	document.oncontextmenu = handleContextMenuTargetContextmenuWrapper;
	document.onblur = hideMenuWrapper;

	document.onselectstart = disableTextWrapper; // for ie
	document.onmousedown = disableTextWrapper;
}
// END context menu wrappers ==================================

// used from the controls frame to set a form field value in the body form
function setBodyFormField(fieldName, value, frameName) {
	if (typeof(frameName) == 'undefined') frameName = "workspaceBody";
	var body = getFrameDocument(frameName);
	eval("body.forms[0]." + fieldName).value = value;
}

function getBodyFormField(fieldName, frameName) {
	if (typeof(frameName) == 'undefined') frameName = "workspaceBody";
	var body = getFrameDocument(frameName);
	return eval("body.forms[0]." + fieldName).value;
}

//function to set the value fo the CaptionText element.
function setCaptionValue(caption)
{
		document.getElementById("CaptionText").value = caption;
}

// BEGIN form submitting functions =============================================

// Some more form submission functions, please consolidate if this is redundant,
// I just don't have time to look for similar functions right now
function submitForm(theForm, commit, preview) {
	var values =null;
	// TODO: FIX ME, this is a horrible hack, there has to be a better way
	// append commit to action because commit isn't a button on the form anymore
	if (commit && (theForm.action.indexOf('commit=1') == -1)) theForm.action = theForm.action + getUrlSeparator(theForm.action) + "commit=1";
    else if(!commit) theForm.action = theForm.action.replace(/commit=1/, '');
	if(preview && (theForm.action.indexOf('preview=1') == -1)) theForm.action = theForm.action + getUrlSeparator(theForm.action) + "preview=1";
	else if(!preview) theForm.action = theForm.action.replace(/preview=1/, '');
    // if the form is submitting to the hidden frame - check for debug mode
	if (theForm.target.indexOf('iddenFrame') > 0) {
		// if in debug mode, submit the form in a new window so we can debug
		if (top.debugMode) {
			// so firefox doesn't open a tab - make unique window name
			var winname = "formActionHiddenFrame" + getRandomNumber();
			window.open("/", winname);
			theForm.target = winname;
		}
	}
	// Loop through all the elements of the form and remove any new lines/carriage returns from input text fields
	var newLineRegEx = new RegExp("[\n\r]", "g");
	for (var i = 0; i < theForm.elements.length; i++){
		if (theForm.elements[i].type == "text"){
			theForm.elements[i].value = theForm.elements[i].value.replace(newLineRegEx," ");
			if (theForm.elements[i].name=="CaptionText") values=theForm.elements[i].value;
		}
	}
	// don't submit the form if there is an onsubmit and it returns false
	var doSubmit = true;
	if(theForm.onsubmit) doSubmit = theForm.onsubmit();
	if (doSubmit !== false) theForm.submit();
	return values;
}

// this assumes there is one form in the body
function submitBodyForm(commit, isSaved, isPreview, additionalUrlParams, isCodeEditor){
    if (typeof(isSaved) == "undefined") isSaved = false;
	if (typeof(isPreview) == "undefined") isPreview = false;
	if (typeof(additionalUrlParams) == "undefined") additionalUrlParams = "";
	// TEMP disabled save button check - uncomment next line to disable
	//isSaved = false;
	if (typeof(isCodeEditor) == "undefined") isCodeEditor = false;

	if (isPreview || isSaved === false) {
        if(commit !== false) commit = true;

        var body = getFrameDocument("workspaceBody");

        if (isCodeEditor === true) var pass = frames["workspaceBody"].toggle_switch();

        var forms = body.getElementsByTagName("form");

        if (isCodeEditor === true) frames["workspaceBody"].toggle_switch(pass);

		if (additionalUrlParams) {
			var origAction = forms[0].action;
			forms[0].action += getUrlSeparator(forms[0].action) + additionalUrlParams;
		}

        submitForm(forms[0], commit, isPreview);
		if (additionalUrlParams) {
			forms[0].action = origAction;
		}
    }
}

// this only submits to a form in the current document
function submitNamedForm(formId, commit, isSaved, isPreview) {
    if (typeof(isSaved) == "undefined") isSaved = false;
	if (typeof(isPreview) == "undefined") isPreview = false;
	// TEMP disabled save button check - uncomment next line to disable
	//isSaved = false;
	if (isPreview || isSaved === false) {
        var theForm = document.getElementById(formId);
        if(commit !== false) commit = true;
        submitForm(theForm, commit, isPreview);
    }
}


function submitNamedFormWRet(formId, commit, isSaved, isPreview) {
	if(document.getElementById('CaptionCheckBox').checked){
	    if (typeof(isSaved) == "undefined") isSaved = false;
		if (typeof(isPreview) == "undefined") isPreview = false;
		// TEMP disabled save button check - uncomment next line to disable
		//isSaved = false;
		if (isPreview || isSaved === false) {
	        var theForm = document.getElementById(formId);
	        if(commit !== false) commit = true;
	      	return submitForm(theForm, commit, isPreview);
		}
	}
	else
		return "";
}

function getAdditionalAssetParams()
{
    var useRestrictions = PINT_GetElementById('UseRestrictions').checked ? 1 : 0;
    var trackClicks = PINT_GetElementById('TrackAssetClicks').checked ? 1 : 0;
    var displayDownload = PINT_GetElementById('DisplayDownload').checked ? 1 : 0;
    return '&useRestrictions=' + useRestrictions + '&trackClicks=' + trackClicks + '&displayDownload=' + displayDownload;
}


function submitChangeSiteForm(currentSiteId, thePulldown){
	var newSiteId = thePulldown.options[thePulldown.selectedIndex].value;
	var previousIndex = getOptionIndexByValue(thePulldown, currentSiteId);
	if ((newSiteId == 'add') || (newSiteId == 'modify')){
		launchModalWindow(PINT_GetRootDirectory() + '/object/site/form' + FILE_EXT + '?userAction=' + newSiteId, 390, 300);
	}
	else if (newSiteId != '') {
		if (confirm('Are you sure you want to reload the application?')) top.changeApplicationSite(newSiteId);
	}
	thePulldown.selectedIndex = previousIndex;
	return false;
}

function changeApplicationSite(siteId){
	top.location = top.PINT_GetRootDirectory() + '/?siteId=' + siteId;
}

function getOptionIndexByValue(thePulldown, value){
	var index = 0;
	for (var i=0; i<thePulldown.options.length; i++){
		if (thePulldown.options[i].value == value) {
			index = i;
			break;
		}
	}
	return index;
}

// END form submitting functions =============================================

// BEGIN window register to reload functions ==============================

var g_windowToReloadRegistry = new Array();
/**
 * adds a reference to a window object to the registry
 *
 * @param object ref to window to reload
 * @param string name of page that can cause a reload of the win
 * @param string optional url to use instead of location.reload()
 */
function registerWindowToReload(win, pageName, url){
	var regWin = new Object();
	regWin.win = win;
	regWin.pageName = pageName;
	regWin.url = url;
	g_windowToReloadRegistry.push(regWin);
}

/**
 * removes a reference to a window object from the registry
 *
 * @param object ref to window to reload
 */
function unregisterWindowToReload(win){
	for (var i=0; i<g_windowToReloadRegistry.length; i++) {
		if (g_windowToReloadRegistry[i].win == win) {
			g_windowToReloadRegistry[i] = null;
			g_windowToReloadRegistry.splice(i, 1);
		}
	}
}

/**
 * reloads windows who are listening for the page name
 *
 * @param string name of page that can cause a reload of the win
 */
function reloadRegisteredWindows(pageName){
	for (var i=0; i<g_windowToReloadRegistry.length; i++) {
		if (g_windowToReloadRegistry[i].pageName == pageName) {
			if (g_windowToReloadRegistry[i].url.length) g_windowToReloadRegistry[i].win.location = g_windowToReloadRegistry[i].url;
			//changed this from location.reload(true) because firefox1.5 has issues with iframe src not resetting on reload
            else g_windowToReloadRegistry[i].win.location = g_windowToReloadRegistry[i].win.location;

		}
	}
}
// END window register to reload functions ==============================

// BEGIN system message display functions ==============================
var g_registeredSystemMessageWindow = window;
var g_allowRemoveSystemMessage = true;
var g_systemMessageTimeout;

function registerWindowToDisplaySystemMessage(win){
	g_registeredSystemMessageWindow = win;
}

function displaySystemMessage(msg){
	removeSystemMessage(0);
	var container = g_registeredSystemMessageWindow.document.createElement('div');
	container.id = 'systemMessageContainer';
	container.className = "systemMessageContainer";
	var message = g_registeredSystemMessageWindow.document.createElement('div');
	message.id = 'systemMessage';
	if (document.all) var rightOffset = 7;
	else var rightOffset = 2;
	var closeButton = '<img src="' + PINT_GetRootDirectory() + '/images/' + cmsTheme + '/icon_close.gif" border="0" style="position:absolute; right: ' + rightOffset + 'px; top: 2px;" onclick="removeSystemMessage(0);" width="11" height="11" alt="" title="Close" onmouseover="this.src=\'' + PINT_GetRootDirectory() + '/images/' + cmsTheme + '/icon_close_on.gif\'" onmouseout="this.src=\'' + PINT_GetRootDirectory() + '/images/' + cmsTheme + '/icon_close.gif\'" />';
	message.innerHTML = msg + closeButton;
	message.className = 'systemMessage';
	container.appendChild(message);
	container.onmouseover = restoreSystemMessage;
	container.onmouseout = scheduleRemoveSystemMessage;
	g_targetFrameWindow = g_registeredSystemMessageWindow; // this is done so the shadows work
	g_registeredSystemMessageWindow.document.body.appendChild(container);
	createShadowDiv(message, "menuShadow");
	var startLeft = Math.round((g_registeredSystemMessageWindow.document.body.clientWidth - container.offsetWidth) / 2);
	// TODO: make this a percentage
	container.style.left = startLeft + "px";
	var startTop = 0 - container.offsetHeight;
	positionSystemMessage(startTop);
	// if the getWorkspaceFrameChild function exists then reset g_targetFrameWindow
	if(top.getWorkspaceFrameChildWindow) g_targetFrameWindow = top.getWorkspaceFrameChildWindow("workspaceBody");
}

function positionSystemMessage(top){
	var container = g_registeredSystemMessageWindow.document.getElementById("systemMessageContainer");
	if (top < 3) {
		container.style.top = top + "px";
		var accel = 3 * top;
		if (accel < -50) accel = -50;
		g_systemMessageTimeout = setTimeout('positionSystemMessage(' + ++top + ')', (accel + 50));
	}
	else scheduleRemoveSystemMessage();
}

function scheduleRemoveSystemMessage(){
	if (g_systemMessageTimeout) clearTimeout(g_systemMessageTimeout);
	g_systemMessageTimeout = setTimeout('removeSystemMessage(100)', 5000);
}

function restoreSystemMessage(){
	if (g_systemMessageTimeout) clearTimeout(g_systemMessageTimeout);
	var container = g_registeredSystemMessageWindow.document.getElementById("systemMessageContainer");
	setElementOpacity(container, 100);
}


function removeSystemMessage(opacity){
	if (g_systemMessageTimeout) clearTimeout(g_systemMessageTimeout);
	var container = g_registeredSystemMessageWindow.document.getElementById("systemMessageContainer");
	if (opacity > 1) {
		setElementOpacity(container, opacity);
		g_systemMessageTimeout = setTimeout('removeSystemMessage(' + --opacity + ')', 50);
	}
	else if (container) g_registeredSystemMessageWindow.document.body.removeChild(container);
}

function setElementOpacity(element, opacity){
	if (element) {
		if (document.all) element.filters.alpha.opacity = opacity;
		element.style.MozOpacity = opacity / 100;
		element.style.opacity = opacity / 100;
	}
}


// END system message display functions ==============================


function toggleDebugMode(){
	debugMode = !debugMode;
	try {
	window.opener.top.toggleDebugMode();
	}
	catch (e){}
	setDebugLinkTexts();
}

function setDebugLinkTexts(){
	for (i in g_registeredDebugLinkTexts){
		try {
			g_registeredDebugLinkTexts[i].innerHTML = debugMode.toString().toUpperCase();
		}
		catch(e) {}
	}
}

g_registeredDebugLinkTexts = new Array();
function registerDebugLinkText(el){
	g_registeredDebugLinkTexts.push(el);
}

// BEGIN explorer tree functions =====================================
// set hidden form field value with select node value
function setDestinationObjectId(id) {
	var fieldName;
	if (typeof(parent.document.forms[0].aggregateVarName) != 'undefined') fieldName = parent.document.forms[0].aggregateVarName.value;
	else fieldName = 'destinationObjectId';
	eval('parent.document.forms[0].' + fieldName).value = id;
}

// set hidden form field value with select node value
function setObjectCid(id) {
	parent.document.forms[0].objectCid.value = id;
}

// load value from current cookie into hidden form field
// execute the function stored in the href of the currently selected tree node
function loadDestinationObjectId() {
	if (document.getElementById(getSavedLayerID())) eval(decodeURIComponent(document.getElementById(getSavedLayerID()).href));
}

// set privilege object cid and display correct privilege options
var g_previousPrivilegeNodeKey;
function selectPrivilegeNode(privilegeNodeIdValue, type, privilegeNodeIdKey) {
	// clear the previously selected id
	if (g_previousPrivilegeNodeKey) parent.document.getElementById(g_previousPrivilegeNodeKey).value = '';
	// set the hidden field's value to be what was just selected
	parent.document.getElementById(privilegeNodeIdKey).value = privilegeNodeIdValue;
	// save this key so it can be cleared next time
	g_previousPrivilegeNodeKey = privilegeNodeIdKey;
	//for user permissions check:
	setPermissionsBoxes(privilegeNodeIdValue, type);
}

var permissionRPC;
function setPermissionsBoxes(idValue, type){
	//set idValue into URL
	var additionalParam = '&siteID=' + idValue +'&siteType=' + type;

	doRPC(permissionRPC, additionalParam);

}

function getCookie(name) {
    var theCookies = document.cookie.split(/[; ]+/);
    for (var i = 0 ; i < theCookies.length; i++) {
        var aName = theCookies[i].substring(0,theCookies[i].indexOf('='));
        if (aName == name) {
            return theCookies[i];
        }
    }
}

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0)
		nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+cookieValue+ "; expires="+expire.toGMTString();
}

//returns true if the current user has access to the
// passed permission (pageAdd, pageModify, or pageDelete ...)
//for the nodeId passed in to idValue
// permissions is set by RPC call to be a 2D array that has pairs of permission name and true/false value
//alert(permissionRPC);
//var test;
/*function userHasAccess(permission){
	//alert(permissionRPC);
	var timeOut =  setTimeout("alert(test)",2000);
	for(var i = 0; i < permissions.length; i++){
		//if this permission is found in the permissions array ret it's value with this user's access
		if(permission.equals(permissions[i][0]))
			return permissions[i][1];
	}
		return false;
}*/

// pass this function a valid system id to trigger the events associated with its folder in the explorer tree
function reloadExplorerTree(systemId) {
	top.getFrameDocument("navControlsFrame").location = PINT_GetRootDirectory() + "/object/_explorer/object/explorer" + FILE_EXT + "?systemId="+systemId
}
// END explorer tree functions =======================================


// BEGIN enable/disable save button functions ========================
var originalFormData = new Object();
var distinctFormFieldsChanged = new Object();
distinctFormFieldsChanged.length = 0;
var maxTextAreaSize = 50;

var gEventHandler = new Object();
gEventHandler['onblur'] = new Array();
gEventHandler['onchange'] = new Array();
gEventHandler['onclick'] = new Array();
gEventHandler['onfocus'] = new Array();
gEventHandler['onkeydown'] = new Array();
gEventHandler['onkeypress'] = new Array();
gEventHandler['onkeyup'] = new Array();
gEventHandler['onmouseup'] = new Array();
gEventHandler['onmousedown'] = new Array();
gEventHandler['onmouseover'] = new Array();
gEventHandler['onmouseout'] = new Array();

var originalHiddenValues = new Object();
var ignoredElementIds = ["screenIndexOrigin", "screenIndexDestination", "modelId", "isSaveButtonEnabled", "wizardButtonClicked", "currentWorkflowStepId", "status", "testEmailAddress", "emailUpdateOptions"];
var ignoredElementClassNames = ["multiSelect"];
var g_saveButtonHiddenFieldIds = new Array();

function initFormForSaveButton() {
	// TEMP disable of save button check - uncomment next line to make sure it is not being called
	//alert('save button check not used');
	var isSaveButtonEnabled = document.getElementById("isSaveButtonEnabled");
    if (isSaveButtonEnabled.value == 0 || typeof(top.g_tabs) != 'undefined') storeInitFormValues();
}

function storeInitFormValues() {
    var myForm = document.forms[0];
    var ignoreNonHiddenFields = false;
    // if it's asset select form, don't compare search form values
    if (myForm.id == "assetSearchForm") ignoreNonHiddenFields = true;
    if (window.parent.distinctFormFieldsChanged.length > 0) {
        // form reload with errors in the form, so it gets the very original values
        originalFormData = window.parent.originalFormData;
        originalHiddenValues = window.parent.originalHiddenValues;
    }
    else storeOriginalFormDataForSaveButton(myForm, ignoreNonHiddenFields);
    assignEventHandlerForFormFields(myForm, ignoreNonHiddenFields);
}

function assignEventHandlerForFormFields(myForm, ignoreNonHiddenFields) {
    for(var i = 0; i < myForm.length; i++) {
        var currElement = new Object();
        var fieldId = myForm.elements[i].id;
        currElement.type = myForm.elements[i].type;

        if (!isIgnoredField(fieldId, ignoredElementIds) && !(currElement.type == "select-multiple" && isIgnoredField(myForm.elements[i].className, ignoredElementClassNames))) {
            if (myForm.elements[i].type == 'hidden') {
                if (originalHiddenValues[fieldId] == null)  originalHiddenValues[fieldId] = myForm.elements[i].value;
				// add the hidden field's id to an array of ids to check in an interval
				g_saveButtonHiddenFieldIds.push(fieldId);
				// if this is the first item added to the id array, set an interval to check if any fields change
				if (g_saveButtonHiddenFieldIds.length == 1) setInterval("compareHiddenFieldValues()", 500);
            }
            else if (!ignoreNonHiddenFields) {
                // assign event hanlder
                var elementAction = getElementEventHandler(currElement.type);
                if(elementAction != null) {
                    currElement.event = elementAction;

                    // set event handler for form elements
                    eval("add" + elementAction + "('" + fieldId + "', 'updateSaveButtonHandler(e)')");
                    var action = "do" + elementAction;
                    eval("myForm.elements[" + i + "]." + elementAction.toLowerCase() + " = " + action);

                    if(currElement.type == "textarea" || currElement.type == "text")  {
                        addOnKeyUp(fieldId, 'updateSaveButtonHandler(e)');
                        myForm.elements[i].onkeyup = doOnKeyUp;

                        addOnMouseUp(fieldId, 'updateSaveButtonHandler(e)');
                        myForm.elements[i].onmouseup = doOnMouseUp;

                    }
                }
            }//done for non-hidden fields
        }// done for non-ignored field
    }
    // keep these very original values for usage in form reloads with error
    window.parent.originalHiddenValues = originalHiddenValues;
}

function resetOriginalValuesForSaveButton() {
    originalFormData = new Object();
    originalHiddenValues = new Object();
    window.parent.originalHiddenValues = new Object();
    window.parent.distinctFormFieldsChanged = new Object();
    window.parent.distinctFormFieldsChanged.length = 0;
}
function storeOriginalFormDataForSaveButton(myForm, ignoreNonHiddenFields) {
    for(var i = 0; i < myForm.length; i++) {
        var currElement = new Object();
        currElement.value = new Array();
        currElement.type = myForm.elements[i].type;
        var fieldId = myForm.elements[i].id;

        if (!isIgnoredField(fieldId, ignoredElementIds) && !(currElement.type == "select-multiple" && isIgnoredField(myForm.elements[i].className, ignoredElementClassNames))) {
            if (myForm.elements[i].type == 'hidden') {
                // for form onload; or after saving form changes without form reload where hidden value array is reset to empty in resetOriginalValuesForSaveButton()
                if (originalHiddenValues[fieldId] == null)  originalHiddenValues[fieldId] = myForm.elements[i].value;
            }
            else if (!ignoreNonHiddenFields) {
                if (getElementEventHandler(currElement.type) != null) {
                    if(currElement.type == "radio" || currElement.type == "checkbox" || currElement.type == "select-one" || currElement.type == "select-multiple") {
                        currElement.value = getValue(myForm.elements[i]);
                    }
                    else currElement.value[0] = myForm.elements[i].value;

                    // store new element with default value into associative array
                    if (currElement.type == "radio" ) {
                        if(currElement.value[0] != null && originalFormData[myForm.elements[i].name] == null) {
                            originalFormData[myForm.elements[i].name] = currElement;
                        }
                    }
                    else {
                        if(currElement.value[0] != null && originalFormData[fieldId] == null) {
                            originalFormData[fieldId] = currElement;
                        }
                    }
                }
            }
        }
    }
    // keep these very original values for usage in form reloads with error
    window.parent.originalFormData = originalFormData;
    window.parent.originalHiddenValues = originalHiddenValues;
}

function getValue(formField) {
    var values = new Array();
    switch (formField.type) {
        case "radio":
            values[0] = getRadioValue(formField);
        break;
        case "checkbox":
            values[0] = getCheckboxValue(formField);
        break;
        case "select-one":
            values[0] = getSelectValue(formField);
        break;
        case "select-multiple":
            values = getSelectMultipleValue(formField);
        break;
    }
    return values;
}

function getRadioValue(formField) {
    if(formField.checked) return formField.value;
    else return null;
}

function getCheckboxValue(formField) {
    if(formField.checked) return 1;
    else return "";
}

function getSelectValue(formField) {
	try{
    	return formField.options[formField.selectedIndex].value;
	}
	catch(err){
		return null;
	}
}

function getSelectMultipleValue(formField) {
    var selectedValues = new Array();
    for (var q = 0; q < formField.options.length; q++) {
        if(formField.options[q].selected) selectedValues.push(formField.options[q].value);
    }
    return selectedValues;
}

function getElementEventHandler(etype) {
    var handler = null;

    switch(etype) {
        case "textarea":
            handler = "OnChange";
        break;
        case "text":
            handler = "OnChange";
        break;
        case "password":
            handler = "OnChange";
        break;
        case "radio":
            handler = "OnClick";
        break;
        case "checkbox":
            handler = "OnClick";
        break;
        case "select-one":
            handler = "OnChange";
        break;
        case "select-multiple":
            handler = "OnChange";
        break;
        case "file":
            handler = "OnChange";
        break;
    }
    return handler;
}

function updateSaveButtonHandler(e){
    var currField;
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    if (currField.htmlFor) currField = document.getElementById(currField.htmlFor);

    var currFormFieldId = currField.id;
    var currFormFieldValue = currField.value;
    var currFormFieldType = currField.type;
    var currFormFieldName = currField.name;

    var hasChanged = isFieldValueChanged(currFormFieldId, currFormFieldValue, currFormFieldType, currFormFieldName);

    if (currFormFieldType == "radio")  updateDistinctFormFieldsChanged(currFormFieldName, hasChanged);
    else updateDistinctFormFieldsChanged(currFormFieldId, hasChanged);

    // decide enable or disable save button
    if (window.parent.distinctFormFieldsChanged.length > 0) enableSaveButton();
    else disableSaveButton();
}

function updateDistinctFormFieldsChanged(fid, hasChanged) {
    fid = getDistinctFormFieldName(fid, self.name);
    if(inArray(window.parent.distinctFormFieldsChanged, fid)) {
        if(hasChanged) { window.parent.distinctFormFieldsChanged[fid].count++; }
        else {
            delete window.parent.distinctFormFieldsChanged[fid];
            window.parent.distinctFormFieldsChanged.length--;
        }
    }
    else {
        if (hasChanged) {
            var item = new Array();
            item.fid = fid;
            item.count = 1;
            window.parent.distinctFormFieldsChanged[fid] = item;
            window.parent.distinctFormFieldsChanged.length++;
        }
    }
}

function getDistinctFormFieldName(fieldId, frameName){
    return fieldId + "_" + frameName;
}

function inArray(myArray, item) {
    if (typeof(myArray[item]) != 'undefined') return true;
    else return false;
}

function isFieldValueChanged(currFormFieldId, currFormFieldValue, currFormFieldType, currFormFieldName) {
    if(currFormFieldType == "checkbox") {
        if (document.getElementById(currFormFieldId).checked) currFormFieldValue = 1;
        else currFormFieldValue = 0;
    }else if (currFormFieldType == "select-one") {
        if (document.getElementById(currFormFieldId)) currField = document.getElementById(currFormFieldId);
        else currField = document.getElementsByName(currFormFieldId)[0];
        currFormFieldValue = currField.options[currField.selectedIndex].value;
    }else if (currFormFieldType == "select-multiple") {
        var newSelectValues = getSelectMultipleValue(document.getElementById(currFormFieldId));
    }

    if(currFormFieldType == "select-multiple") {
        var originalValues = new Array();
        if (originalFormData[currFormFieldId]) originalValues = originalFormData[currFormFieldId].value;
        else originalValues.length = 0;
        var diffValueCount = 0;

        if(newSelectValues.length != originalValues.length) return true;
        else {
            for(j = 0; j < newSelectValues.length; j++) {
                var found = false;
                for(k = 0; k < originalValues.length; k++) {
                    if(newSelectValues[j] == originalValues[k]) found = true;
                    if(found) break;
                }
                if(!found) diffValueCount++;
                if(diffValueCount > 0) break;
            }
            if (diffValueCount == 0) return false;
            else return true;
        }
    }else {
        if (currFormFieldType == "radio") {
            if ((originalFormData[currFormFieldId] == null && currFormFieldValue == null) || currFormFieldValue == originalFormData[currFormFieldName].value[0]) return false;
            else return true;
        }
        else {
            if (originalFormData[currFormFieldId] == null || currFormFieldValue == originalFormData[currFormFieldId].value[0]) return false;
            else return true;
        }
    }
}

function enableSaveButton() {
	if (document.getElementById("isSaveButtonEnabled")) {
		document.getElementById("isSaveButtonEnabled").value = 1;
	    // handle dialog form and page form differently
	    if (isDialogWindow()) updateSaveButtonForDialog(false, 'button');
	    else updateSaveButtonForFormPage(false, "formControlButton", true);
	}

}

function disableSaveButton() {
	document.getElementById("isSaveButtonEnabled").value = 0;

    // handle dialog form and page form differently
    if (isDialogWindow()) updateSaveButtonForDialog(true, 'buttonDisabled');
    else updateSaveButtonForFormPage(true, "formControlButtondisable", false);

}

// update OK button style and class if it's a dialog
function updateSaveButtonForDialog(disabled, className) {
    if (document.getElementsByName('commit')[0]) {
        document.getElementsByName('commit')[0].disabled = disabled;
        document.getElementsByName('commit')[0].className = className;
    }
    else if (document.getElementsByName('next')[0]) {
        document.getElementsByName('next')[0].disabled = disabled;
        document.getElementsByName('next')[0].className = className;
    }
}

// update Save button and tabname style if it's a form
function updateSaveButtonForFormPage(isSaved, buttonClassName, isCommit) {
    var tabIndex = top.getTabIndexByChildWindow(self);
    var workspaceControlsWindow = top.getWorkspaceFrameChildWindow("workspaceControls", tabIndex);

    // only take action if save button state changes, no need to repeat same action if the state is the same
    if (workspaceControlsWindow && workspaceControlsWindow.document.getElementById('_wscBtnSaveDiv') && workspaceControlsWindow.document.getElementById('_wscBtnSaveDiv').className != buttonClassName) {

        // change italic style of tabname
        top.g_tabs[tabIndex].isSaved = isSaved;
        top.redrawTabs();

        // change saveButton div class
        workspaceControlsWindow.document.getElementById('_wscBtnSaveDiv').className = buttonClassName;
    }
}

function setCharCounter(textField, counterField, maxlimit) {
    var textField = document.getElementById(textField);
    if (textField.value.length > maxlimit) textField.value = textField.value.substring(0, maxlimit);
    else document.getElementById(counterField).value = maxlimit - textField.value.length;
}

// onkeyup
function addOnKeyUp(fieldId, functionName) {
    if (typeof(gEventHandler['onkeyup'][fieldId]) == 'undefined') gEventHandler['onkeyup'][fieldId] = new Array();
    // add in onkeyup scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onkeyup) { gEventHandler['onkeyup'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onkeyup.toString())); }
    gEventHandler['onkeyup'][fieldId].push(functionName);
}
function doOnKeyUp(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onkeyup'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onkeydown
function addOnKeyDown(fieldId, functionName) {
    if (typeof(gEventHandler['onkeydown'][fieldId]) == 'undefined') gEventHandler['onkeydown'][fieldId] = new Array();
    // add in onkeydown scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onkeydown) { gEventHandler['onkeydown'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onkeydown.toString())); }
    gEventHandler['onkeydown'][fieldId].push(functionName);
}
function doOnKeyDown(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onkeydown'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onkeypress
function addOnKeyPress(fieldId, functionName) {
    if (typeof(gEventHandler['onkeypress'][fieldId]) == 'undefined') gEventHandler['onkeypress'][fieldId] = new Array();
    // add in onkeypress scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onkeypress) { gEventHandler['onkeypress'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onkeypress.toString())); }
    gEventHandler['onkeypress'][fieldId].push(functionName);
}
function doOnKeyPress(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onkeypress'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onblur
function addOnBlur(fieldId, functionName) {
    if (typeof(gEventHandler['onblur'][fieldId]) == 'undefined') gEventHandler['onblur'][fieldId] = new Array();
    // add in onblur scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onblur) { gEventHandler['onblur'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onblur.toString())); }
    gEventHandler['onblur'][fieldId].push(functionName);
}
function doOnBlur(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onblur'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onfocus
function addOnFocus(fieldId, functionName) {
    if (typeof(gEventHandler['onfocus'][fieldId]) == 'undefined') gEventHandler['onfocus'][fieldId] = new Array();
    // add in onfocus scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onfocus) { gEventHandler['onfocus'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onfocus.toString())); }
    gEventHandler['onfocus'][fieldId].push(functionName);
}
function doOnFocus(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onfocus'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onclick
function addOnClick(fieldId, functionName) {
    if (typeof(gEventHandler['onclick'][fieldId]) == 'undefined') gEventHandler['onclick'][fieldId] = new Array();
    // add in onclick scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onclick) { gEventHandler['onclick'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onclick.toString())); }
    gEventHandler['onclick'][fieldId].push(functionName);
}
function doOnClick(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    if (currField.htmlFor) var fieldId = currField.htmlFor;
    else var fieldId = currField.id;

    var functionNames = gEventHandler['onclick'][fieldId];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onchange
function addOnChange(fieldId, functionName) {
    if (typeof(gEventHandler['onchange'][fieldId]) == 'undefined') gEventHandler['onchange'][fieldId] = new Array();
    // add in onchange scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onchange) { gEventHandler['onchange'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onchange.toString())); }
    gEventHandler['onchange'][fieldId].push(functionName);
}
function doOnChange(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onchange'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// onmouseup
function addOnMouseUp(fieldId, functionName) {
    if (typeof(gEventHandler['onmouseup'][fieldId]) == 'undefined') gEventHandler['onmouseup'][fieldId] = new Array();
    // add in onmouseup scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onmouseup) { gEventHandler['onmouseup'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onmouseup.toString())); }
    gEventHandler['onmouseup'][fieldId].push(functionName);
}
function doOnMouseUp(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onmouseup'][currField.id];
    // adding if stmt check to make sure IE doesn't pout when user drags mouse over date field data to highlight text
    if (functionNames) {
        for(var i = 0; i < functionNames.length; i++) {
            if(functionNames[i] != null) eval(functionNames[i]);
        }
    }
}

// onmousedown
function addOnMouseDown(fieldId, functionName) {
    if (typeof(gEventHandler['onmousedown'][fieldId]) == 'undefined') gEventHandler['onmousedown'][fieldId] = new Array();
    // add in onmousedown scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onmousedown) { gEventHandler['onmousedown'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onmousedown.toString())); }
    gEventHandler['onmousedown'][fieldId].push(functionName);
}
function doOnMouseDown(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onmousedown'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// on mouseover
function addOnMouseOver(fieldId, functionName) {
    if (typeof(gEventHandler['onmouseover'][fieldId]) == 'undefined') gEventHandler['onmouseover'][fieldId] = new Array();
    // add in onmouseover scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onmouseover) { gEventHandler['onmouseover'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onmouseover.toString())); }
    gEventHandler['onmouseover'][fieldId].push(functionName);
}
function doOnMouseOver(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onmouseover'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// on mouseout
function addOnMouseOut(fieldId, functionName) {
    if (typeof(gEventHandler['onmouseout'][fieldId]) == 'undefined') gEventHandler['onmouseout'][fieldId] = new Array();
    // add in onmouseout scripts assigned to this object from somwhere else in the php code
    // so that all scripts for this event can be fired
    if (document.getElementById(fieldId).onmouseout) { gEventHandler['onmouseout'][fieldId].push(extractFunctionName(document.getElementById(fieldId).onmouseout.toString())); }
    gEventHandler['onmouseout'][fieldId].push(functionName);
}
function doOnMouseOut(e) {
    if (!e) var e = window.event;
    if(e.srcElement) currField = e.srcElement;
    else if (e.target) currField = e.target;

    var functionNames = gEventHandler['onmouseout'][currField.id];
    for(var i = 0; i < functionNames.length; i++) {
        if(functionNames[i] != null) eval(functionNames[i]);
    }
}

// extract only the body of function
function extractFunctionName(originalFunction) {
    var leftBraceLocation = originalFunction.indexOf("{");
	var rightBraceLocation;
	for (i=originalFunction.length-1; i>=0; i--) {
		if (originalFunction.charAt(i) == "}") {
			rightBraceLocation = i;
			break;
		}
	}

	return originalFunction.substring(leftBraceLocation + 1, rightBraceLocation - 1);
}

function compareHiddenFieldValues() {
	var inCurrentTab = true;

    // check if now is in active tab
    if (!isDialogWindow()) {
        var tabIndex = top.getTabIndexByChildWindow(self);
        if (tabIndex != top.g_selectedTabIndex) inCurrentTab = false;
    }
	if (inCurrentTab) {
		var newValue, fieldId;
		for (var i=0; i<g_saveButtonHiddenFieldIds.length; i++) {
			fieldId = g_saveButtonHiddenFieldIds[i];
	    	newValue = document.getElementById(fieldId).value;
	        if (originalHiddenValues[fieldId] == newValue) updateDistinctFormFieldsChanged(fieldId, false);
	        else updateDistinctFormFieldsChanged(fieldId, true);
		}
        // decide enable or disable save button
        if (window.parent.distinctFormFieldsChanged.length > 0) enableSaveButton();
        else disableSaveButton();
	}

}


function isIgnoredField(fieldId, ignoredElements) {
    for (var i = 0; i < ignoredElements.length; i++) {
        if (fieldId == ignoredElements[i]) return true;
    }
    return false;
}
// END enable/disable save button functions ========================


// MISC
// 04.15.05 - B. Wetter: fires eventToFire of elementId
function fireElementEvent(elementId, eventToFire) {
	var el = document.getElementById(elementId);
	if (el) {
		if(document.all) el.fireEvent(eventToFire);
		else {
			var e = document.createEvent('MouseEvents');
			e.initEvent(eventToFire.replace('on',''), true, false);
			el.dispatchEvent(e);
		}
	}
}

// check textArea maxlength
function checkLimit(field, limit)
{
    if (field.value.length > limit)
    {
        alert(field.name + " limited to " + limit + " characters");
        // Truncate at the limit
        var revertField = field.value.slice(0, limit);
        field.value = revertField;
        field.focus();
    }
}

// disable all dialog buttons when any button is clicked
function disableAllDialogButtons(disableTargetIds) {
    // disableTargetIds is set only if it's dialog button -- other buttons will have disableTargetIds.length == 0
    if (disableTargetIds.length > 0) {
        // get an array of dialog button ids to be disabled
        var targetButtonIds = disableTargetIds.split(',');
        for (var i=0; i < targetButtonIds.length; i++) {
            var currElement = document.getElementById(targetButtonIds[i]);
            currElement.disabled = 'disabled';
            currElement.className += ' buttonDisabled';
        }
    }
}

// disable all dialog buttons when any button is clicked
function enableAllDialogButtons(enableTargetIds) {
    // disableTargetIds is set only if it's dialog button -- other buttons will have disableTargetIds.length == 0
    if (enableTargetIds.length > 0) {
        // get an array of dialog button ids to be disabled
        var targetButtonIds = enableTargetIds.split(',');
        for (var i=0; i < targetButtonIds.length; i++) {
            var currElement = document.getElementById(targetButtonIds[i]);
            currElement.disabled = false;
            currElement.className = currElement.className.replace('buttonDisabled','');
        }
    }
}


function launchOverlayWindow(url) {

        var width   = launchOverlayWindow.arguments.length >= 2 ? launchOverlayWindow.arguments[1] : 0;
        var height  = launchOverlayWindow.arguments.length >= 3 ? launchOverlayWindow.arguments[2] : 0;
        var win  = launchOverlayWindow.arguments.length >= 4 ? launchOverlayWindow.arguments[3] : window;
        var useOverlays = false;
        if(!useOverlays){
                launchModalWindow(url, width, height, win);
                return;
        }

}


// BEGIN: workflow functions

/**
 * setWorkflowOption()
 * Set correct hidden field for selected workflow option.
 * It could be either the status or the current workflow step id.
 * The first token is the form field, the second is the value.
 *
 * @param formField - select object
 * @param formId - id of form containing select
 */
function setWorkflowOption(formField, formId, rpcId) {
	var tokens = (formField.options[formField.selectedIndex].value).split('|');
	var theForm = document.getElementById(formId);
	var additionalUrlParams;
	if (tokens.length == 2) {
		eval("theForm." + tokens[0]).value = tokens[1];
		// if selecting a workflow step, switch the status field to draft (0)
		// and set the additional parameters for when we invoke rpc
		if (tokens[0] == 'currentWorkflowStepId') {
			theForm.status.value = 0;
			additionalUrlParams = '&status=0&currentWorkflowStepId=' + tokens[1];
		}
		else if (tokens[0] == 'status') {
			theForm.status.value = tokens[1];
			additionalUrlParams = '&status=' +tokens[1];
		}
	}
	// TODO: invoke rpc to set new value in model data
	if(rpcId) doRPC(rpcId, additionalUrlParams);
}


/**
 * DIPHighlightWorkflowStep()
 * Highlight selected workflow button and set hidden form field to
 * new workflow step id
 *
 * @param object img
 * @param int id of object
 * @param int number of workflow steps
 * @param int workflow step id
 */
function DIPHighlightWorkflowStep(img, id, numSteps, stepId) {
	DIPResetWorkflowSteps(id, numSteps);
	// if the image src doesn't contain "selected", add _on.
	// "selected" means that's the default image
	if ((img.src).search('_current') < 0) img.src = (img.src).replace('.gif', '_moveto.gif');
	DIPSetWorkflowStep(stepId, id);
}

/**
 * DIPResetWorkflowStep()
 * Reset all buttons to original state. If a workflow step id
 * is specified, reset the hidden form field to that value.
 *
 * @param object img
 * @param int id of object
 * @param int number of workflow steps
 * @param int workflow step id
 */
function DIPResetWorkflowSteps(id, numSteps) {
	var img;
	for (var i = 0; i < numSteps; i++) {
		img = eval('document.images["wfs' + id + '_' + i + '"]');
		img.src = (img.src).replace('_moveto.gif', '.gif');
	}
	// reset hidden field value
	if (typeof(DIPResetWorkflowSteps.arguments[2]) != 'undefined')
		DIPSetWorkflowStep(DIPResetWorkflowSteps.arguments[2], id);
}

/**
 * DIPSetWorkflowStep()
 * Set hidden field corresponding to object id specified
 *
 * @param int id of object
 * @param int workflow step id
 */
function DIPSetWorkflowStep(stepId, id) {
	eval('document.taskListSearchForm.workflowStepId_' + id).value = stepId;
}

// END: workflow

/**
 * showPagesInExplorerList()
 * If the checkbox passed in is not checked this function
 * changes the url parameters of an iframe (that should
 * contain an explorer.php page) and reloads the iframe
 * with the new parameters
 *
 * @param string id of iframe
 * @param object checkbox form element
 */

function showPagesInExplorerList(frameId, checkBox) {
	var fr=document.getElementById(frameId);
	var src=fr.src; src=src.replace(/\&?typeList=[^&]+/, '');
	src += getUrlSeparator(src) + 'typeList=section';
	if (!checkBox.checked) {
		if (confirm('Depending on the number of pages it could take awhile for the list to load.\n\nPlease wait for the list to finish loading before making any changes.')) {
			src += ',page';
			fr.src = src;
		} else checkBox.checked = 1;
	}
	else if(checkBox.checked) fr.src = src;
}

/**
 * setEmailUpdateOption()
 * Set correct hidden field for selected email update option.
 * The first token is the form field, the second is the value.
 *
 * @param formField - select object
 * @param formId - id of form containing select
 */
function setEmailUpdateOption(formField, formId, rpcId) {
    var theForm = document.getElementById(formId);
    var selectedValue = formField.options[formField.selectedIndex].value;
    theForm.emailUpdateOptions.value = selectedValue;
    var additionalUrlParams = '&emailUpdate=' + selectedValue;
    if(rpcId) doRPC(rpcId, additionalUrlParams);
}



// BEGIN: spec selection function ================================================================================
 function specCheckDown(el){
     var cbs = document.getElementsByTagName('input');
     var pattern = new RegExp(".*");
	 for (var i=0; i<cbs.length; i++){
		pattern.compile(el.id + "-[\d]*");
         if ((cbs[i].id != el.id) && pattern.test(cbs[i].id)) {
             cbs[i].checked = el.checked;
             specChangeRelatedStates(cbs[i]);
         }
     }
 }

 function specCheckUp(el, breadcrumb){
     // only check, don't uncheck
     if (el.checked) {
         // make all possible ids of parents using the breadcrumb
         var stopLevel = breadcrumb.length - 1;
         var id = 'spec';
         var cb;
         for (var i=0; i<stopLevel; i++){
             id += '-' + breadcrumb[i];
             cb = document.getElementById(id);
             cb.checked = true;
             specChangeRelatedStates(cb);
         }
     }
 }

 function specChangeRelatedStates(el){
     var className = 'specTable';
     if (el.checked) className = 'specTableSelected';
     document.getElementById(el.id + 'td').className = className;
     var d = document.getElementById(el.id + 'detailCell');
     if (d) d.className = className;
     var c = document.getElementById(el.id + 'customCell');
     if (c) c.className = className;
     var textarea = document.getElementById(el.id + 'customDetail');
     if (textarea) textarea.disabled = !el.checked;
     var sel = document.getElementById(el.id + 'useCustomDetail');
     if (sel) sel.disabled = !el.checked;
 }

 function specToggleIsCustom(el, id){
     if (el.options[el.selectedIndex].value > 0) {
         document.getElementById(id + 'customBlock').className = '';
         document.getElementById(id + 'defaultBlock').className = 'displayNone';
     }
     else {
         document.getElementById(id + 'customBlock').className = 'displayNone';
         document.getElementById(id + 'defaultBlock').className = '';
     }
 }

// END: spec selection function ===============================================================================

function toggle( targetId ){
  if (document.getElementById){
        target = document.getElementById( targetId );
           if (target.style.display == "none"){
              target.style.display = "";
           } else {
              target.style.display = "none";
           }
     }
}

function forcedToggle( targetId, toggleForce) {
    if (document.getElementById){
        target = document.getElementById( targetId );
        if (toggleForce){
            target.style.display = "";
        } else {
            target.style.display = "none";
        }
    }
}

function PINT_safeReload() {
    window.location = window.location;
}

/*
 * PINT_disableFormElements()
 * Sets form elements disable state according to enableFormElements value
 * The element ids to disable should be passed in as arguments after enableFormElements
 *
 * @param bool enableFormsElements -- true/false
 */
function PINT_disableFormElements(enableFormElements) {
    // if there are element ids passed in then we lop through them
   if (PINT_disableFormElements.arguments.length > 1) {
        for (var i = 1; i <  PINT_disableFormElements.arguments.length; i++) {
            // get the element by the id passed in then enable/disbale that element
            var elem = document.getElementById(PINT_disableFormElements.arguments[i]);
            if (elem) elem.disabled = enableFormElements;
        }
   }
}

/**
 * used for hiding an element that contains a wysiwygpro. this needs special considerations for firefox becuase display:none throws errors
 *
 * @param id
 */
function hideElementWithEditor(id){
	var d =	document.getElementById(id);
	if (document.all) d.style.display = 'none';
	else {
	 	d.style.height = '0px';
		d.style.overflow = 'hidden';
	}
}

/**
 * used for showing an element that contains a wysiwygpro. this needs special considerations for firefox becuase display:none throws errors
 *
 * @param id
 */
function showElementWithEditor(id, height){
	var d =	document.getElementById(id);
	if (document.all) d.style.display = 'block';
	else {
		d.style.height = height;
		d.style.overflow = 'visible';
	}
}
/**
 * handles submission of export search form
 *
 */
function submitExportForm(formName, action) {
   if (action == 'export_new' || action == 'export_all') {
        var theForm = document.getElementById(formName);
        var formAction = document.getElementById('userAction').value;
        var formTarget = theForm.target
        if (document.all) theForm.target="_blank";
        document.getElementById('userAction').value = action;
        submitNamedForm(formName,0);
        document.getElementById('userAction').value = formAction;
        theForm.target = formTarget;
    }
}

function changeSearchExportForm(currentSearch, formName, el, destination) {
   var previousIndex = getOptionIndexByValue(el, currentSearch);
   if (!isNaN(parseInt(el.value))) submitNamedForm(formName,0);
   else if (el.value == 'addSearch') {
        launchModalWindow(destination, '350', '150');
        el.selectedIndex = previousIndex;
   }
   else el.selectedIndex = previousIndex;
   return false;
}
// flash functions
PINT_FlashObject=function(swf,id,w,h,defaultImage,ver,imageMap,c){this.swf=swf;this.id=id;this.width=w;this.height=h;this.imageMap=imageMap;this.version=ver||6;this.align="middle";this.codebase=this.version+",0,0,0";this.redirect="";this.sq=document.location.search.split("?")[1]||"";this.defaultImage=defaultImage;this.altTxt="Please <a href='http://www.macromedia.com/go/getflashplayer'>upgrade your Flash Player</a>.";this.bypassTxt="";this.params=new Object();this.variables=new Object();if(c)this.color=this.addParam('bgcolor',c);this.addParam('quality','high');this.doDetect=getQueryParamValue('detectflash');};PINT_FlashObject.prototype.addParam=function(name,value){this.params[name]=value};PINT_FlashObject.prototype.getParams=function(){return this.params};PINT_FlashObject.prototype.getParam=function(name){return this.params[name]};PINT_FlashObject.prototype.addVariable=function(name,value){this.variables[name]=value};PINT_FlashObject.prototype.getVariable=function(name){return this.variables[name]};PINT_FlashObject.prototype.getVariables=function(){return this.variables};PINT_FlashObject.prototype.getParamTags=function(){var paramTags="";for(var param in this.getParams()){paramTags+='<param name="'+param+'" value="'+this.getParam(param)+'" />'}if(paramTags==""){paramTags=null}return paramTags};PINT_FlashObject.prototype.getHTML=function(){var flashHTML="";if(window.ActiveXObject&&navigator.userAgent.indexOf('Mac')==-1){flashHTML+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.codebase+'" width="'+this.width+'" height="'+this.height+'" id="'+this.id+'" align="'+this.align+'">';flashHTML+='<param name="movie" value="'+this.swf+'" />';if(this.getParamTags()!=null){flashHTML+=this.getParamTags();}if(this.getVariablePairs()!=null){flashHTML+='<param name="flashVars" value="'+this.getVariablePairs()+'" />'}flashHTML+='</object>'}else{flashHTML+='<embed type="application/x-shockwave-flash" src="'+this.swf+'" width="'+this.width+'" height="'+this.height+'" id="'+this.id+'" align="'+this.align+'"';for(var param in this.getParams()){flashHTML+=' '+param+'="'+this.getParam(param)+'"'}if(this.getVariablePairs()!=null){flashHTML+=' flashVars="'+this.getVariablePairs()+'"'}flashHTML+='></embed>'}return flashHTML};PINT_FlashObject.prototype.getVariablePairs=function(){var variablePairs=new Array();for(var name in this.getVariables()){variablePairs.push(name+"="+escape(this.getVariable(name)));}if(variablePairs.length>0){return variablePairs.join("&");}else{return null}};PINT_FlashObject.prototype.write=function(elementId){if(detectFlash(this.version)||this.doDetect=='false'){if(elementId){document.getElementById(elementId).innerHTML=this.getHTML();}else{document.write(this.getHTML());}}else{if(this.redirect!=""){document.location.replace(this.redirect);}else if(this.defaultImage!=""){imageString="<img src=\""+this.defaultImage+"\" width=\""+this.width+"\" height=\""+this.height+"\" border=\"0\" alt=\"\"";if(eval('typeof(this.imageMap)')!="undefined"&&this.imageMap!="")imageString+=" usemap=\"#"+this.imageMap+"\" ";imageString+=" class=\"inlineimage\" />";document.write(imageString);}else document.write(this.altTxt+""+this.bypassTxt);}};function getFlashVersion(){var flashversion=0;if(navigator.plugins&&navigator.plugins.length){var x=navigator.plugins["Shockwave Flash"];if(x){if(x.description){var y=x.description;var aDescription = y.split(" ");var aMajorVersion = aDescription[2].split(".");flashversion = aMajorVersion[0];}}}else{result=false;for(var i=15;i>=3&&result!=true;i--){execScript('on error resume next: result = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+i+'"))','VBScript');flashversion=i}}return flashversion}function detectFlash(ver){if(getFlashVersion()>=ver){return true;}else{return false;}}function getQueryParamValue(param){var q=document.location.search;var detectIndex=q.indexOf(param);if(q.length>1&&detectIndex!=-1){return q.substring(q.indexOf("=",detectIndex)+1,q.indexOf("&",detectIndex));}else{return true;}}

//FCKEditor functions
function checkEditorChange(editorInstance) {

        // if the editor thinks the content has not changed but the origContent does not match the
        // current content then we need to tell the CMS that content has changed
        if(!parent.distinctFormFieldsChanged.length) {
            //eval("parent.distinctFormFieldsChanged."+editorInstance.Name+"= true");
    		parent.distinctFormFieldsChanged.length++;
        }

}

function PINT_subscriptionNodeOnclick(cid, object, type){
	parent.document.getElementById('subscriptionCidHidden').value=cid;
	reloadSubscriptionIframe(cid);
}

function PINT_subscriptionFormNodeOnclick(cid, object, type){
	parent.document.getElementById('subscriptionFormCidHidden').value=cid;
}

function FCKeditor_OnComplete(editorInstance) {
     // only check for changes if the isSaveButtonEnabled element exists
    if (document.getElementById("isSaveButtonEnabled")) {
       editorInstance.Events.AttachEvent('OnSelectionChange', checkEditorChange);
       editorInstance.Events.AttachEvent('OnAfterSetHTML', checkEditorChange);
       //editorInstance.Events.AttachEvent('OnPaste', checkEditorChange);
    }

}

function changeHiddenFieldForBox(fieldId, boxId){
	var box = document.getElementById(boxId);
	var value = box.value;
	var field = document.getElementById(fieldId);
	var oldVal = field.value;
			
	oldValSearch = ","+oldVal+",";
	var newVal = oldVal;
	if(box.checked){
		if(oldVal.length == 0) newVal = value;
		else if(oldValSearch.indexOf(","+value+",") ) newVal = oldVal+","+value;
	}
	else{
		var found = false;
		var pos = oldValSearch.indexOf(","+value+",");
		var count = 0;
		while(pos != -1){
			found = true;
			oldValSearch = oldValSearch.substring(0, oldValSearch.indexOf((","+value+",")))+","+oldValSearch.substring((oldValSearch.indexOf((","+value+","))+(","+value+",").length), oldValSearch.length );
			count++;
			if(count > 10 ) break;
			pos = oldValSearch.indexOf(","+value+",");
		}
		if(oldValSearch == ",") oldValSearch = ",,"
		if(found) newVal = oldValSearch.substring(1, oldValSearch.length-1);
	}
	
	field.value = newVal;

}

function displayThemeThumb(basePath, selectedIndex){
	var value;
	value = document.getElementsByName('cmsTheme');
	value = value[0];
	value = value[selectedIndex].value;
	basePath = basePath.substring(0,basePath.length-1);


	newImage = basePath+value+"/themePreview.gif";
	document.getElementById('themeImage').src = newImage;
}


function displayUserThemeThumb(basePath, selectedIndex){
	var value;
	value = document.getElementsByName('userTheme');
	value = value[0];
	value = value[selectedIndex].value;
	basePath = basePath.substring(0,basePath.length-1);


	newImage = basePath+value+"/themePreview.gif";
	document.getElementById('themeImage').src = newImage;
}

function loadCartInvoicesForPrinting(statementId, hiddenFrameId) {
    var fr = document.getElementById(hiddenFrameId);
    document.getElementById('invoicePleaseWait').innerHTML = 'Loading invoices to print. Please wait...';
    fr.src = PINT_GetRootDirectory() + '/rpc/rpc' + FILE_EXT + '?statementId=' + statementId + '&' + getRandomNumber() + '=' + getRandomNumber();
    fr.style.visibility = 'visible';
}

function printCartInvoices(hiddenFrameName) {
    window.frames[hiddenFrameName].focus();
    window.frames[hiddenFrameName].print();

    var waitEl = document.getElementById('invoicePleaseWait');
    if (waitEl) waitEl.innerHTML = '';
    // the frame should have an id that matches the name
    var fr = document.getElementById(hiddenFrameName)
    if (fr) fr.style.visibility = 'hidden';
}

var targetItems="";
var discountItems="";
var discountItems2="";

function updateSummary(discount, targetList, promoType) {
    var summary = "";
    var discountType = top.document.getElementById("discountType").value;
    var discountValue = top.document.getElementById("discountValue").value;

    var iString = "";
    if(discount == 1){
        iString = top.discountItems;
        if(top.discountItems == "None Selected")
            iString = top.targetItems;
    }
    else{
        iString = top.discountItems2;
        if(top.discountItems2 == "None Selected")
            iString = top.targetItems;
    }

    if(promoType == 'cart')
    {
        iString = targetList;
    }

    if(top.document.getElementById("discountType2") != null)
        var discountType2 = top.document.getElementById("discountType2").value;
    if(top.document.getElementById("discountValue2") != null)
        var discountValue2 = top.document.getElementById("discountValue2").value;
    var discountTarget = "items";
    var discountTarget2 = "order";

    if(top.document.getElementById("discountItems").checked)
        discountTarget = "items";
    else if(top.document.getElementById("discountOrder").checked)
        discountTarget = "order";
    else if(top.document.getElementById("discountShipping").checked)
        discountTarget = "shipping";
    else if(top.document.getElementById("discountModule").checked)
        discountTarget = "module";
        

    if(top.document.getElementById("discountItems2") != null && top.document.getElementById("discountItems2").checked)
        discountTarget2 = "items";
    else if(top.document.getElementById("discountOrder2") != null && top.document.getElementById("discountOrder2").checked)
        discountTarget2 = "order";
    else if(top.document.getElementById("discountShipping2") != null && top.document.getElementById("discountShipping2").checked)
        discountTarget2 = "shipping";
    else if(top.document.getElementById("discountModule2") != null && top.document.getElementById("discountModule2").checked)
        discountTarget2 = "module";

    if(discount == 1){
        type = (discountType=="percentage")?(discountValue+"%"):("$"+discountValue);
        if(discountTarget == "items"){
            summary = type+" off all of the following items: "+iString+".";
        }
        else if(discountTarget == "order"){
            summary = type+" off the entire order.";
        }
        else if(discountTarget == "shipping"){
            summary = type+" off the shipping for this order.";
        }
        else if(discountTarget == "module"){
            prodType = document.getElementById("discountModuleSelect").value;
            if (prodType=='product') prodType = 'all';
            summary = type+" off " + prodType + " products.";
        }
        top.document.getElementById("discount1Summary").innerHTML = summary;
    }
    else if(discount != -1){
        type = (discountType2=="percentage")?(discountValue2+"%"):("$"+discountValue2);
        if(discountTarget2 == "items"){
            summary = type+" off all of the following items: "+iString+".";
        }
        else if(discountTarget2 == "order"){
            summary = type+" off the entire order.";
        }
        else if(discountTarget2 == "shipping"){
            summary = type+" off the shipping for this order.";
        }
        else if(discountTarget2 == "module"){
            prodType = document.getElementById("discountModuleSelect2").value;
            if (prodType=='product') prodType = 'all';
            summary = type+" off " + prodType + " products.";
        }
        if(top.document.getElementById("discount2Summary") != null)
            top.document.getElementById("discount2Summary").innerHTML = summary;
    }
}
function setXYCoords(evnt){
	//mouse position
	xy = getEventOffsetXY( evnt );
	document.getElementById('xCoord').value = xy[0];
	document.getElementById('yCoord').value = xy[1];

	//create pushpin and remove any old pins from current div
	var doc1 = document.getElementById('ibox_wrapper');
	var oldPin = getElementsByClass('mapPushPin', doc1, null);
	for(var i=1; i<oldPin.length; i++){
		oldPin[i].parentNode.removeChild(oldPin[i]);
	}
	oldPin = getElementsByClass('mapPushPin', doc1, null);
	oldPin[0].style['position'] = "absolute";
	oldPin[0].style['left'] = (xy[0]-6)+"px";
	oldPin[0].style['top'] = (xy[1]-6)+"px";
	oldPin[0].style['display'] = "block";

	//create pushpin and remove any old pins from hidden div
	doc2 = document.getElementById('mapImgDiv');
	oldPin = getElementsByClass('mapPushPin', doc2, null);
	for(var i=1; i<oldPin.length; i++){
		oldPin[i].parentNode.removeChild(oldPin[i]);
	}
	oldPin[0].style['position'] = "absolute";
	oldPin[0].style['left'] = (xy[0]-6)+"px";
	oldPin[0].style['top'] = (xy[1]-6)+"px";
	oldPin[0].style['display'] = "block";

	//update hidden fields
	updateDistinctFormFieldsChanged('xCoord', true);
	updateDistinctFormFieldsChanged('yCoord', true);
	enableSaveButton();
}

function getEventOffsetXY( evt )
{
	//ie
	if ( evt.offsetX != null )
		return [ evt.offsetX , evt.offsetY ];
	//mozilla/netscape
    return [ evt.layerX, evt.layerY];
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function updateCountField(fieldNum, page, listCount){

}

