//Data Definition Variables
var ARRAYSIZE=100;
var requiredFieldsId=new Array(ARRAYSIZE);
var requiredFieldsDefault=new Array(ARRAYSIZE);
var requiredFieldsRequired=new Array(ARRAYSIZE);
var requiredFieldsRegEx=new Array(ARRAYSIZE);
var requiredFieldsName=new Array(ARRAYSIZE);
var requiredFieldsDataFormat=new Array(ARRAYSIZE);

var requiredString = '';
var requiredForm = '';

function toggleChildren(imgElem)
{
	var liElem = imgElem.parentNode.parentNode;
	var ulChildren = liElem.getElementsByTagName('ul');
	if(ulChildren.length > 0)
	{
		var firstUL = ulChildren[0];
		if(firstUL.style.display != 'none')
		{
			//hide it
			imgElem.src = '/cms/css/icons/plus.gif';
			firstUL.style.display = 'none';
		}
		else
		{
			//show it
			imgElem.src = '/cms/css/icons/minus.gif';
			firstUL.style.display = 'block';
		}
	}
}

function afterLeftnavResize()
{
	var width = getElemWidth('side-bar');
	if(document.getElementById('chooser-main'))
	{
		Set_Cookie('leftnav_chooser_size', width);
		width = width + 10;
		document.getElementById('chooser-main').style.paddingLeft = width + 'px';
	}
	else
	{
		Set_Cookie('leftnav_size', width);
		resizeScreen();
	}
}

function removeFontSpanClicked()
{
	if(document.getElementById('chkRemoveFontStyle').checked)
	{
		document.getElementById('chkFontAssignment').checked = false;
		document.getElementById('chkFontAssignment').disabled = true;
	}
	else
	{
		document.getElementById('chkFontAssignment').disabled = false;
	}
}

function showPageConfigInfo(id)
{
	if(document.getElementById('configInfoDivs'))
	{
		var configDivs = document.getElementById('configInfoDivs').getElementsByTagName("DIV");
		for(var i = 0; i < configDivs.length; i++)
		{
			var configDiv = configDivs[i];
			if(configDiv.className == 'configuration')
			{
				if(id == configDiv.getAttribute('id'))
				{
					configDiv.style.display = "block";
				}
				else
				{
					configDiv.style.display = "none";
				}
			}
		}
	}
	
	if(document.getElementById('configInfoLinks'))
	{
		var configLis = document.getElementById('configInfoLinks').getElementsByTagName("LI");
		for(var i = 0; i < configLis.length; i++)
		{
			var configLi = configLis[i];
			if(id == configLi.getAttribute('id'))
			{
				configLi.style.fontWeight = 'bold';
			}
			else
			{
				configLi.style.fontWeight = '';
			}
		}
	}
}

//--- For Asset factory plugins ---//


function addPlugin()
{
	var select = document.getElementById('pluginToAdd');
	var pluginClass = select.options[select.selectedIndex].value;
	document.getElementById('pluginMod').value = 'addPlugin';
	document.getElementById('pluginClass').value = pluginClass;
	submitStandardForm();
}

function addPluginParam(pluginIdx)
{
	var select = document.getElementById('availableParams-'+pluginIdx);
	var paramName = select.options[select.selectedIndex].value;
	document.getElementById('modPluginIdx').value = pluginIdx;
	document.getElementById('pluginMod').value = 'addParam';
	document.getElementById('paramName').value = paramName;
	submitStandardForm();
}

function removePluginParam(pluginIdx, paramIdx)
{
	document.getElementById('modPluginIdx').value = pluginIdx;
	document.getElementById('pluginMod').value = 'removeParam';
	document.getElementById('modParamIdx').value = paramIdx;
	submitStandardForm();
}

function removePlugin(pluginIdx)
{
	document.getElementById('modPluginIdx').value = pluginIdx;
	document.getElementById('pluginMod').value = 'removePlugin';
	submitStandardForm();
}

function onDataDefinitionSubmit()
{
    var toSubmit = true;
    toggleFormButtons();
    if(window.saveWysiwyg)
    	saveWysiwyg();
    	
	var firstError = null;
    var alertMessage = '';
    for(var i=0;i<ARRAYSIZE;i++) {
        if(requiredFieldsRequired[i] == true) {
            var itemValue = "";
            var thisItem = null;

            var thisItem = document.getElementById(requiredFieldsId[i]);
            itemValue = thisItem.value;

            var RegEx;
            if(!(requiredFieldsRegEx[i]))
				RegEx=/.*/;
            else
          		RegEx = requiredFieldsRegEx[i];
            if(itemValue == "") {
                alertMessage += requiredFieldsName[i]+" " + requiredString + "\n";
                toSubmit = false;
                if(firstError == null) {
                    firstError = thisItem;
                }
            }
            if(!RegEx.test(itemValue)) {
                alertMessage += requiredFieldsName[i]+" " + requiredForm + " " + requiredFieldsDataFormat[i] + "\n";
                toSubmit = false;
                if(firstError == null) {
                    firstError = thisItem;
                }
            }
        }
    }
    if(toSubmit) {
    	document.getElementById('editform').submit();
		//submitStandardForm();
    }
    else {
	    if(alertMessage != '')
	    	alert(alertMessage);
        firstError.focus();
        toggleFormButtons();
        return false;
    }
}

function submitStandardForm() {
	if(document.getElementById('editform')) {
		if(document.getElementById('editform').onsubmit){
			document.getElementById('editform').onsubmit();
		}
		document.getElementById('editform').submit();
		return true;
	}
	var forms = document.getElementsByTagName('FORM');
	if(forms[1]) {
		if(forms[1].onsubmit){
			forms[1].onsubmit();
		}
		forms[1].submit();
		return true;
	}
	if(forms[0]) { //Log in form
		if(forms[0].onsubmit){
			forms[0].onsubmit();
		}
		forms[0].submit();
		return true;
	}
	if(forms[2]) { //Precaution
		if(forms[2].onsubmit){
			forms[2].onsubmit();
		}
		forms[2].submit();
		return true;
	}
}

//---------- FOR WORKFLOW BUILDER -----------------//

/**
 * Dynamically updates the step/action label as the user
 * types in the label textfield
 */
function updateLabel(value, type, stepId, actionNum)
{
	var span;
	if(updateLabel.arguments.length == 4)
	{
		span = document.getElementById(type + "-header-label" + stepId + "-" + actionNum);
	}
	else if(updateLabel.arguments.length == 3)
	{
		span = document.getElementById(type + "-header-label" + stepId);
		var content = document.getElementById('center-stage');
		var selects = content.getElementsByTagName('select');
		if(selects)
		{
			var selLen = selects.length;
			for(var i = 0; i < selLen; i++)
			{
				var selectObj = selects[i];
				if(selectObj.className == 'step-select')
				{
					if(selectObj.options)
					{
						var optLen = selectObj.options.length;
						for(var j = 0; j < optLen; j++)
						{
							var optionObj = selectObj.options[j];
							if(optionObj.className == stepId)
							{
								optionObj.text = value;
							}
						}
					}
				}	
			}
		}
	}
	
	if(span)
	{
		if(span.firstChild)
		{
			span.firstChild.nodeValue = value;
		}
		else
		{
			span.appendChild(document.createTextNode(value));
		}
	}
}

/**
 * Shows/hides the respective chooser when the user clicks the
 * "restrict re-assignment" radio buttons
 */
function showRestrictChooser(type, id)
{
	if(type == 'user')
	{
		document.getElementById('restrict-user-chooser' + id).style.display = '';
		document.getElementById('restrict-group-chooser' + id).style.display = 'none';
		document.getElementById('restrict-role-chooser' + id).style.display = 'none';
	}
	else if(type == 'group')
	{
		document.getElementById('restrict-user-chooser' + id).style.display = 'none';
		document.getElementById('restrict-group-chooser' + id).style.display = '';
		document.getElementById('restrict-role-chooser' + id).style.display = 'none';
	}
	else if(type == 'role')
	{
		document.getElementById('restrict-user-chooser' + id).style.display = 'none';
		document.getElementById('restrict-group-chooser' + id).style.display = 'none';
		document.getElementById('restrict-role-chooser' + id).style.display = '';
	}
}

function showAssignChooser(type, id)
{
	if(type == 'user')
	{
		document.getElementById('default-user-chooser' + id).style.display = '';
		document.getElementById('default-group-chooser' + id).style.display = 'none';
	}
	else if(type == 'group')
	{
		document.getElementById('default-user-chooser' + id).style.display = 'none';
		document.getElementById('default-group-chooser' + id).style.display = '';
	}
}

function toggleRestrictReassign(stepId)
{
	var elem = document.getElementById('restrict-reassign-'+stepId);
	if(elem)
	{
		if(elem.style.display == 'none')
		{
			elem.style.display = '';
		}
		else if(elem.style.display == '')
		{
			elem.style.display = 'none';
			document.getElementById('restrict-user-chooser' + stepId).style.display = 'none';
			document.getElementById('restrict-group-chooser' + stepId).style.display = 'none';
			document.getElementById('restrict-role-chooser' + stepId).style.display = 'none';
		}
	}
}

function submitMod(mod, stepIdx, stepType, actionIdx, triggerIdx, paramIdx)
{
	if(submitMod.arguments.length == 3)
	{
		document.getElementById('stepMod').value = mod;
		document.getElementById('stepIdx').value = stepIdx;
		document.getElementById('modStepType').value = stepType;
	}
	else if(submitMod.arguments.length == 4)
	{
		document.getElementById('actionMod').value = mod;
		document.getElementById('stepIdx').value = stepIdx;
		document.getElementById('actionIdx').value = actionIdx;
		document.getElementById('modStepType').value = stepType;
	}
	else if(submitMod.arguments.length == 5)
	{
		document.getElementById('triggerMod').value = mod;
		document.getElementById('stepIdx').value = stepIdx;
		document.getElementById('actionIdx').value = actionIdx;
		document.getElementById('triggerIdx').value = triggerIdx;
		document.getElementById('modStepType').value = stepType;
	}
	else if(submitMod.arguments.length == 6)
	{
		document.getElementById('triggerMod').value = mod;
		document.getElementById('stepIdx').value = stepIdx;
		document.getElementById('actionIdx').value = actionIdx;
		document.getElementById('triggerIdx').value = triggerIdx;
		document.getElementById('paramIdx').value = paramIdx;
		document.getElementById('modStepType').value = stepType;
	}
	submitBuilderForm();
	return false;
}

/**
 * Submits the form for a dynamic modification
 */
function submitBuilderForm()
{
	var form = document.getElementById('builderform');
	if(form.onsubmit)
	{
		form.onsubmit();
	}
	form.submit();	
}

/**
 * When a the step type dropdown changes, check to see
 * if we should show/hide the assignment information
 */
function stepTypeUpdate(selectObj, id)
{
	var selectedOption = selectObj.options[selectObj.selectedIndex];
	if(selectedOption)
	{
		if(selectedOption.value == 'system')
		{
			document.getElementById('assign-info'+id).style.display = 'none';
		}
		else
		{
			document.getElementById('assign-info'+id).style.display = '';
		}
	}
}

function addTrigger(stepId, stepIdx, stepType, actionIdx)
{
	var selectObj = document.getElementById('trigClass'+stepId+'-'+actionIdx);
	if(selectObj)
	{
		var selectedOption = selectObj.options[selectObj.selectedIndex];
		if(selectedOption)
		{
			document.getElementById('triggerClass').value = selectedOption.value;
			submitMod('add',stepIdx,stepType,actionIdx,0);
		}
	}
}


function submitMetadataSetModification(action,where)
{
	var form = document.forms['editform'];
  			
	form.action = form.action + '?pane=dynamic&dynamicMod=' + action + '&dynamicLocation=' + where;
	if(form.onsubmit){
		form.onsubmit();
	}
	form.submit();
}
  		
/*
 * Does a form submit in order to modify the 
 * structured data in-memory
 */
function submitModification(pane,identifier,modification)
{
	var form = document.getElementById('editform');
	form.action = form.action + '?pane=' + pane + '&sdIdentifier=' + identifier + '&sdModification=' + modification;
	if(form.onsubmit)
	{
		form.onsubmit();
	}
	form.submit();
}	

/*
 * Instructs tinyMCE to save wysiwyg data in the corresponding textarea form fields
 */
function saveWysiwyg()
{
	if (document.tinyMCE)
	{
		tinyMCE.triggerSave();
	}
}

//--- KEYWORD CHOOSER CODE ---//

/** Opens the popup window for choosing keywords for a dublin metadata asset */
function openChooseKeywordsWindow(id)
{
	var keywords = document.getElementById(id).value;
	window.open('/cms/entity/choosekeywords.act?keywords=' + keywords, 'cascade_chooser', 'height=350,width=700,menubar=no,location=no,resizable=no,scrollbars=no,status=no');
	return false;
}

/** 
 * Combines the selected global and asset-local keywords into a string
 * and then inserts that comma-delimited string back into the proper form field
 */
function insertKeywords()
{
	var selectOptions = document.getElementById('assignedKeywords').options;
	if(selectOptions)
	{
		var str = "";
		for(var i = 0; i < selectOptions.length-1;i++)
		{
			str += selectOptions[i].value;
			str += ', ';
		}
		if(selectOptions.length > 0)
		{
			str += selectOptions[selectOptions.length-1].value
		}
	}
	
	var localKeywords = document.getElementById('localKeywords').value;
	if(localKeywords != "")
	{
		if(str != "")
		{
			str += ', ';
		}
		str += localKeywords;
	}
	window.opener.document.getElementById('metadata_keywords').value = str;
	window.close();
}

function recordCheckboxStateChange(checkboxName,hiddenFieldName,form)
{
	var checkbox=form[checkboxName];
	if (!checkbox)
	{
		alert('Could not record checkbox state change. No checkbox with name ' + checkboxName + ' could be found');
		return;
	}
	
	var hiddenField = document.getElementById(hiddenFieldName);
	if (checkbox.checked == true)
	{
		hiddenField.value="on";
	}
	else
	{
		hiddenField.value="off";
	}
}


function doFormSubmitForward(forwardStr)
{
	var form = document.getElementById('editform');
	forwardStr = forwardStr.replace(/&/g, "AMP");
	form.action = form.action + '?useForward=' + forwardStr;
	if(form.onsubmit)
	{
		form.onsubmit();
	}
	form.submit();
}

/*
 * Jumps to another location
 */
function jumpLocation(location,parameters)
{
	if (location)
	{
		document.location = location  + parameters;
	}
}
		
/*
 * Submits a form with a POST and action=value
 * (used in the submissions of the multiselect
 */
function submitForm(form, value)
{
	document.forms[form].action = value;
	document.forms[form].submit();
}

/*
** Control the behavior or the multiselect checkbox
*/
function multicheck(box)
{
	if (box.checked) {  selectAll('multiselect','selected'); } 
	else deselectAll('multiselect','selected');
}

/* CALLBACK CODE */

var INIT_CALLBACKS = new Array();
function registerOnloadCallback(callback)
{
	INIT_CALLBACKS[INIT_CALLBACKS.length] = callback;
}

function initializeOnloadCallbacks()
{	
	for (i=0; i < INIT_CALLBACKS.length; i++)
	{
		var initFunction = INIT_CALLBACKS[i];
		initFunction();
	}
}

/* finds the name of the onchoose function associated with that chooser and executes it */
function executeOnchoose(chooserFieldId)
{
	try
	{
		var element = document.getElementById("onchoose" + chooserFieldId);
		if (element)
		{
			//evaluate(execute) the function 
			eval(element.value + '(\'' + chooserFieldId + '\')');
		}
	}
	catch(error)
	{
		//alert("Error:" + error);
	}
}

/*
 * Refreshes the preview image when editing an image file
 */
function refreshPreview()
{
	document.images['preview'].src = document.images['preview'].src + '&amp;'+ (new Date().getTime());
}

/*
 * this function will first fill in the parent window's href field by using
 * the function then close the window
 */
function closeAndFill(path)
{
	window.opener.fillSrc(path)
	window.close();
}

/*
 * Sets the file to remove to the specified value and autosubmit
 *
 */
function setToRemove(elementId, value)
{
    var element = document.getElementById(elementId);
    if (element) element.setAttribute('value',value);
    submitStandardForm();
}
	
/*
 * this function will first fill in the parent window's element id with a value as well as the element path, 
 * and then close this window
 */
function closeAndFill(elementId,path, chooserFieldId, chooserFieldPath)
{
	window.opener.setChooserId(elementId, chooserFieldId);
	window.opener.setChooserPath(path,chooserFieldPath);
	window.opener.setChooserLink(elementId, chooserFieldId, chooserFieldPath);
	window.opener.executeOnchoose(chooserFieldId);
	window.close();
}

function setChooserId (id, chooserFieldId) 
{
	//set the value of a chooser element with id of chooserFieldId to id
	document.getElementById(chooserFieldId).value = id;				 
}
	
function setChooserPath (path, chooserFieldPath) {
	//set the value of a chooser element with id of chooserFieldPath to path
	document.getElementById("link" + chooserFieldPath).value = path;
	document.getElementById(chooserFieldPath).value = path;
	if(document.getElementById("link" + chooserFieldPath).firstChild) 
    	document.getElementById("link" + chooserFieldPath).removeChild(document.getElementById("link" + chooserFieldPath).firstChild);
	var linkText=document.createTextNode("[" + path + "]");
	document.getElementById("link" + chooserFieldPath).appendChild(linkText);
}
					
function setChooserLink(elementId, chooserFieldId, chooserFieldPath)
{
	var newpath = document.getElementById("linkpath" + chooserFieldId).value + "&id=" + elementId;
	var windowproperties = document.getElementById("properties" + chooserFieldId).value;
	var assembledlink = "javascript: var cwindow=window.open('" + newpath + "','cascade_chooser','" + windowproperties + "');";
	document.getElementById("link" + chooserFieldPath).setAttribute('href',assembledlink);
	document.getElementById("link" + chooserFieldPath).removeAttribute('class');
	document.getElementById("link" + chooserFieldId).setAttribute('href',assembledlink);
}
						
function cancelChooserSelection(chooserFieldId, chooserFieldPath)
{
	setChooserPath('', chooserFieldPath);
	setChooserId('', chooserFieldId);
	var newpath = document.getElementById("linkpath" + chooserFieldId).value
	var windowproperties = document.getElementById("properties" + chooserFieldId).value;
	var assembledlink = "javascript: var cwindow=window.open('" + newpath + "','cascade_chooser','" + windowproperties + "');";
	document.getElementById("link" + chooserFieldId).setAttribute('href',assembledlink);
	document.getElementById("link" + chooserFieldPath).setAttribute('href',assembledlink);
	document.getElementById("link" + chooserFieldPath).removeAttribute('class');
}

/*
 * Makes a selection for a particular user or group field in a form
 */
function chooseUser(fieldId,username)
{
	var field = document.getElementById('field_'+fieldId);
	var hidden = document.getElementById('fieldhidden_'+fieldId);		
	field.innerHTML=username;
	hidden.value=username;
}

/*
 * Does a form submit in order to modify the 
 * structured data in-memory
 */
function submitConfigMod(pane,identifier,modification)
{
	var form = document.getElementById('editform');
	form.action = form.action + '?pane=' + pane + '&confName=' + identifier + '&confMod=' + modification;
	if(form.onsubmit)
	{
		form.onsubmit();
	}
	form.submit();
}

function strikeChooserLink(chooserId)
{
	var linkFieldId = 'link' + chooserId;
	var linkField = document.getElementById(linkFieldId);
	if(linkField)
	{
		if(linkField.getAttribute('style'))
		{
			linkField.removeAttribute('style');
		}
		else
		{
			linkField.setAttribute('style', 'text-decoration: line-through');
		}
	}
}

function toggleOverride(checked, chooserId, pathId)
{
	if(chooserId.indexOf('Block') != -1)
	{
		revertBlock(chooserId, 'true');
	}
	else if(chooserId.indexOf('Stylesheet') != -1)
	{
		revertStylesheet(chooserId, 'true');
	}
	
	if(checked)
	{
		//toggling on: set id to 'empty'
		setChooserId('empty', chooserId);
	}
	strikeChooserLink(pathId);
}

function revertBlock(chooserId, override)
{
	var confNum = chooserId.substring(chooserId.indexOf('[')+1, chooserId.indexOf(']'));
	var regionNum = chooserId.substring(chooserId.lastIndexOf('[')+1, chooserId.lastIndexOf(']'));
	
	var prevId = document.getElementById('prevBlockId' + confNum + 'r' + regionNum).value;
	var prevPath = document.getElementById('prevBlockPath' + confNum + 'r' + regionNum).value;
	
	document.getElementById('pageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedBlockId').value = prevId;
	document.getElementById('pageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedBlockPath').value = prevPath;
	document.getElementById('linkpageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedBlockPath').innerHTML = '[' + prevPath + ']';
	var prevBlockWhere = document.getElementById('prevBlockWhere' + confNum + 'r' + regionNum).value;
	if(prevBlockWhere && prevBlockWhere != "")
	{
		document.getElementById('blockWhereImg' + confNum + 'r' + regionNum).className = 'icon-' + prevBlockWhere;
	}
	else
	{
		document.getElementById('blockWhereImg' + confNum + 'r' + regionNum).className = '';
	}
	
	if(!override)
	{
		var chkNoBlock = document.getElementById('chkNoBlock' + confNum + 'r' + regionNum);
		chkNoBlock.removeAttribute('checked');
		chkNoBlock.checked = false;
	}
}

function revertStylesheet(chooserId, override)
{
	var confNum = chooserId.substring(chooserId.indexOf('[')+1, chooserId.indexOf(']'));
	var regionNum = chooserId.substring(chooserId.lastIndexOf('[')+1, chooserId.lastIndexOf(']'));
	
	var prevId = document.getElementById('prevStylesheetId' + confNum + 'r' + regionNum).value;
	var prevPath = document.getElementById('prevStylesheetPath' + confNum + 'r' + regionNum).value;
	
	document.getElementById('pageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedStylesheetId').value = prevId;
	document.getElementById('pageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedStylesheetPath').value = prevPath;
	document.getElementById('linkpageConfigurationInfoIdx[' + confNum + '].pageRegionInfoIdx[' + regionNum + '].assignedStylesheetPath').innerHTML = '[' + prevPath + ']';
	var prevStyleWhere = document.getElementById('prevStylesheetWhere' + confNum + 'r' + regionNum).value;
	if(prevStyleWhere && prevStyleWhere != "")
	{
		document.getElementById('stylesheetWhereImg' + confNum + 'r' + regionNum).className = 'icon-' + prevStyleWhere;
	}
	else
	{
		document.getElementById('stylesheetWhereImg' + confNum + 'r' + regionNum).className = '';
	}
	
	if(!override)
	{
		var chkNoStyle = document.getElementById('chkNoStyle' + confNum + 'r' + regionNum);
		chkNoStyle.removeAttribute('checked');
		chkNoStyle.checked = false;
	}
}

function updateIconPage(chooserId)
{
	var confNum = chooserId.substring(chooserId.indexOf('[')+1, chooserId.indexOf(']'));
	var regionNum = chooserId.substring(chooserId.lastIndexOf('[')+1, chooserId.lastIndexOf(']'));
	
	if(chooserId.indexOf('Block') != -1)
	{
		//update block icon
		document.getElementById('blockWhereImg' + confNum + 'r' + regionNum).className = 'icon-page';
		//clear out "no block" chkbox
		document.getElementById('chkNoBlock' + confNum + 'r' + regionNum).removeAttribute('checked');
		document.getElementById('chkNoBlock' + confNum + 'r' + regionNum).checked = false;
	}
	else if(chooserId.indexOf('Stylesheet') != -1)
	{
		//update stylesheet icon
		document.getElementById('stylesheetWhereImg' + confNum + 'r' + regionNum).className = 'icon-page';
		//clear out "no block" chkbox
		document.getElementById('chkNoStyle' + confNum + 'r' + regionNum).removeAttribute('checked');
		document.getElementById('chkNoStyle' + confNum + 'r' + regionNum).checked = false;
	}
}

function updateIconConfigSet(chooserId)
{
	var confNum = chooserId.substring(chooserId.indexOf('[')+1, chooserId.indexOf(']'));
	var regionNum = chooserId.substring(chooserId.lastIndexOf('[')+1, chooserId.lastIndexOf(']'));
	
	if(chooserId.indexOf('Block') != -1)
	{
		//update block icon
		document.getElementById('blockWhereImg' + confNum + 'r' + regionNum).className = 'icon-pageconfigurationset';
		document.getElementById('chkNoBlock' + confNum + 'r' + regionNum).removeAttribute('checked');
		document.getElementById('chkNoBlock' + confNum + 'r' + regionNum).checked = false;
	}
	else if(chooserId.indexOf('Stylesheet') != -1)
	{
		//update stylesheet icon
		document.getElementById('stylesheetWhereImg' + confNum + 'r' + regionNum).className = 'icon-pageconfigurationset';
		document.getElementById('chkNoStyle' + confNum + 'r' + regionNum).removeAttribute('checked');
		document.getElementById('chkNoStyle' + confNum + 'r' + regionNum).checked = false;
	}
}

function multiselect_move(srcId, destId)
{
	moveSelectedOptions(document.getElementById(srcId),document.getElementById(destId));
}

function selectAllAssigned(assignedIds)
{
	for(var i = 0; i < assignedIds.length; i++)
	{
		selectAllOptions(document.getElementById(assignedIds[i]));
	}
}

        	
var showHiddenFormSubmit = true;

function makeHiddenFormSubmitField(input) {
	if(showHiddenFormSubmit) {
		showHiddenFormSubmit = false;
		var hiddenFormSubmit = document.createElement('INPUT');
		hiddenFormSubmit.type = "hidden";
		hiddenFormSubmit.name = "formsubmit";
		hiddenFormSubmit.value = "true";
		if(input.parentNode) {
			var currentParentNode = input.parentNode;
			currentParentNode.insertBefore(hiddenFormSubmit, input);
		}
	}
}
        	
function toggleFormButtonsOff() {
    aInput = document.getElementsByTagName("input");
    for(i = 0; i < aInput.length; i++) {
        if(aInput[i].type == "button" || aInput[i].type == "submit") {
        	aInput[i].disabled = true;
        	makeHiddenFormSubmitField(aInput[i]);
        }
    }

	submitStandardForm();
}

function toggleFormButtons() {
    aInput = document.getElementsByTagName("input");
    for(i = 0; i < aInput.length; i++) {
        if(aInput[i].type == "button" || aInput[i].type == "submit") {
        	if(aInput[i].disabled == true)
        		aInput[i].disabled = false;
        	else
        		aInput[i].disabled = true;
        }
    }
	return true;
}


function toggleOptions() {
	var toggleOptions = document.getElementById('toggle-options');

	if(toggleOptions) {
		var contentBody = toggleOptions.getElementsByTagName('SPAN')[0];

		if(contentBody.style.display=='none') {
			contentBody.style.display='inline';
	
			Set_Cookie('toggleOptions','true',30,'/','','');
		}
		else{
			contentBody.style.display='none';
			
			Set_Cookie('toggleOptions','false',30,'/','','');
		}
	}
}



/*

HTMLHttpRequest v1.0 beta2
(c) 2001-2005 Angus Turnbull, TwinHelix Designs http://www.twinhelix.com

Licensed under the CC-GNU LGPL, version 2.1 or later:
http://creativecommons.org/licenses/LGPL/2.1/
This is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/



// Syntax:
//   addEvent(object_reference, 'name_of_event', function_reference, legacy);
// 'name_of_event' is without the 'on' prefix, e.g. 'load', 'click' or 'mouseover'.
// 'legacy' disables addEventListener if true.
// You can add multiple events to one object, and in MSIE all are removed onunload.

var aeOL = [];
function addEvent(o, n, f, l)
{
 var a = 'addEventListener', h = 'on'+n, b = '', s = '';
 if (o[a] && !l) return o[a](n, f, false);
 o._c |= 0;
 if (o[h])
 {
  b = '_f' + o._c++;
  o[b] = o[h];
 }
 s = '_f' + o._c++;
 o[s] = f;
 o[h] = function(e)
 {
  e = e || window.event;
  var r = true;
  if (b) r = o[b](e) != false && r;
  r = o[s](e) != false && r;
  return r;
 };
 aeOL[aeOL.length] = { o: o, h: h };
};
addEvent(window, 'unload', function() {
 for (var i = 0; i < aeOL.length; i++) with (aeOL[i])
 {
  o[h] = null;
  for (var c = 0; o['_f' + c]; c++) o['_f' + c] = null;
 }
});

function cancelEvent(e, c)
{
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};



// SYNTAX INSTRUCTIONS for HTMLHttpRequest:
//
// function callback_function(DOMDocument) { /* Parse DOM document here */ }
//
// var objectName = new HTMLHttpRequest('objectName', callback_function);

function HTMLHttpRequest(myName, callback) { with (this)
{
 this.myName = myName;
 this.callback = callback;

 // 'xmlhttp': Our preferred request object. Accepted wherever HTML is sold.
 this.xmlhttp = null;
 // 'iframe' is our fallback: a reference to a dynamically created IFRAME buffer.
 this.iframe = null;
 window._ifr_buf_count |= 0;
 this.iframeID = 'iframebuffer' + window._ifr_buf_count++;
 // A loading flag, set to the requested URI when loading.
 this.loadingURI = '';

 // Attempt to init an XMLHttpRequest object where supported.
 if (window.XMLHttpRequest && !BrowserDetect.browser.toLowerCase().match("explorer"))
 {
  xmlhttp = new XMLHttpRequest();
  // Force it to attempt to parse all documents as XML.
  if (xmlhttp.overrideMimeType) xmlhttp.overrideMimeType('text/xml');
 }

 if (!xmlhttp)
 {
  // In MSIE or browsers with no XMLHttpRequest support: fallback to IFRAMEs buffers.
  // I'm using IFRAMEs in MSIE due to XMLHTTP not parsing text/html to a DOM.
  // Also used in IE5/Mac, Opera 7.x, Safari <1.2, some Konqueror versions, etc.
  if (document.createElement && document.documentElement &&
   (window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1))
  {
   var ifr = document.createElement('iframe');
   ifr.setAttribute('id', iframeID);
   ifr.setAttribute('name', iframeID);
   ifr.setAttribute('src', '/cms/entity/listfactories.act');
   // Hide with visibility instead of display to fix Safari bug.
   ifr.style.visibility = 'hidden';
   ifr.style.position = 'absolute';
   ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';
   iframe = document.getElementsByTagName('body')[0].appendChild(ifr);
  }
  else if (document.body && document.body.insertAdjacentHTML)
  {
   // IE5.0 doesn't like createElement'd frames (won't script them) and IE4 just plain
   // doesn't support it. Luckily, this will fix them both:
   document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID +
    '" id="' + iframeID + '" style="display: none"></iframe>');
  }
  // This helps most IE versions regardless of the creation method:
  if (window.frames && window.frames[iframeID]) iframe = window.frames[iframeID];
  iframe.name = iframeID;
 }

 return this;
}};



HTMLHttpRequest.prototype.parseForm = function(form) { with (this)
{
 // Parses a form DOM reference to an escaped string suitable for GET/POSTing.

 var str = '', gE = 'getElementsByTagName', inputs = [
  (form[gE] ? form[gE]('input') : form.all ? form.all.tags('input') : []),
  (form[gE] ? form[gE]('select') : form.all ? form.all.tags('select') : []),
  (form[gE] ? form[gE]('textarea') : form.all ? form.all.tags('textarea') : [])
 ];

 // Loop through each list of tags, constructing our string.
 for (var i = 0; i < inputs.length; i++)
  for (j = 0; j < inputs[i].length; j++)
   if (inputs[i][j])
   {
    var plus = '++'.substring(0,1); // CodeTrim fix.
    str += escape(inputs[i][j].getAttribute('name')).replace(plus, '%2B') +
     '=' + escape(inputs[i][j].value).replace(plus, '%2B') + '&';
   }

 // Strip trailing ampersand, because we can :)
 return str.substring(0, str.length - 1);
}};



HTMLHttpRequest.prototype.xmlhttpSend = function(uri, formStr) { with (this)
{
 // Use XMLHttpRequest to asynchronously open a URI, and optionally POST a provided
 // form string if any (otherwise, performs a GET).

 xmlhttp.open(formStr ? 'POST' : 'GET', uri, true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4)
  {
   var doc = xmlhttp.responseXML;
   // If you are getting an error where 'doc' is null in your own code, try changing
   // the MIME type returned by the server: setting it to text/xml usually works well!
   if (callback) callback(doc, loadingURI);
   loadingURI = '';
  }
 };
 if (formStr && xmlhttp.setRequestHeader)
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send(formStr);
 loadingURI = uri;
 return true;
}};


HTMLHttpRequest.prototype.iframeSend = function(uri, formRef) { with (this)
{
 // Routes a request through our hidden IFRAME. Pass a URI, and optionally a
 // reference to a submitting form. Requires proprietary 'readyState' property.

 if (!document.readyState) return false;

 // Opera fix: force the frame to render before setting it as a target.
 if (document.getElementById) var o = document.getElementById(iframeID).offsetWidth;

 // Either route the form submission to the IFRAME (easy!)...
 if (formRef) formRef.setAttribute('target', iframeID);
 else
 {
  // ...or load the provided URI in the IFRAME, checking for browser bugs:
  // 1) Safari only works well using 'document.location'.
  // 2) Opera needs the 'src' explicitly set!
  // 3) Konqueror 3.1 seems to think ifrDoc's location = window.location, so watch that too.
  var ifrDoc = iframe.contentDocument || iframe.document;

  if (!window.opera && ifrDoc.location &&
   ifrDoc.location.href != location.href) ifrDoc.location.replace(uri);
  else iframe.src = uri;
 }

 // Either way, set the loading flag and start the readyState checking loop.
 // Opera likes a longer initial timeout with multiple frames running...
 loadingURI = uri;
 setTimeout(myName + '.iframeCheck()', (window.opera ? 250 : 100));
 return true;
}};


HTMLHttpRequest.prototype.iframeCheck = function() { with (this)
{
 // Called after a timeout, periodically calls itself until the load is complete.
 // Get a reference to the loaded document, using either W3 contentDocument or IE's DOM.

 doc = iframe.contentDocument || iframe.document;
 // Check the IFRAME's .readyState property and callback() if load complete.
 // IE4 only seems to advance to 'interactive' so let it proceed from there.
 var il = iframe.location, dr = doc.readyState;
 if ((il && il.href ? il.href.match(loadingURI) : 1) &&
     (dr == 'complete' || (!document.getElementById && dr == 'interactive')))
 {
  if (callback) callback((doc.documentElement || doc), loadingURI);
  loadingURI = '';
 }
 else setTimeout(myName + '.iframeCheck()', 50);
}};


// *** PUBLIC METHODS ***

HTMLHttpRequest.prototype.load = function(uri) { with (this)
{
 // Call with a URI to load a plain text document.

 if (!uri || (!xmlhttp && !iframe)) return false;
 // Route the GET through an available transport layer.
 if (xmlhttp) return xmlhttpSend(uri, '');
 else if (iframe) return iframeSend(uri, null);
 else return false;
}};


HTMLHttpRequest.prototype.submit = function(formRef, evt) { with (this)
{
 // Pass a reference to a (submitting) form DOM node and an event object.

 evt = evt || window.event;
 if (!formRef || (!xmlhttp && !iframe)) return false;

 // Retrieve form information then decide what to do with it.
 var method = formRef.getAttribute('method'), uri = formRef.getAttribute('action');

 if (method && method.toLowerCase() == 'post')
 {
  // Send the URI and either a parsed form or a form reference to the transports.
  // Note we only cancel form for XMLHTTP, as IFRAMEs still need it to submit.
  if (xmlhttp) { cancelEvent(evt); return xmlhttpSend(uri, parseForm(formRef)) }
  else if (iframe) return iframeSend(uri, formRef);
  else return false;
 }
 else
 {
  // For GET requests, append ?querystring or &querystring to the GET uri and
  // forward it to the load() function. Always cancel form submit().
  return load(uri + (uri.indexOf('?') == -1 ? '?' : '&') + parseForm(formRef));
  cancelEvent(evt);
 }
}};

function RemoteFileLoader(myName)
{
 this.myName = myName;
 this.threads = [];
 this.loadingIDs = {};
 this.onload = null;
};


RemoteFileLoader.prototype.getThread = function(destId) { with (this)
{
 // Locates a thread that's EITHER: loading into the specified destination, OR: idle.
 // If none are match that condition, create a new one.

 var thr = -1;

 for (var id in loadingIDs)
 {
  // Same destination?
  if (id == destId)
  {
   thr = loadingIDs[id];
   break;
  }
 }
 if (thr == -1) for (var t = 0; t < threads.length; t++)
 {
  // Idle?
  if (!threads[t].loadingURI)
  {
   thr = t;
   break;
  }
 }
 if (thr == -1)
 {
  // Create a new HTMLHttpRequest with its own name as a reference to its array entry,
  // and no callback function as yet ;).
  thr = threads.length;
  threads[thr] = new HTMLHttpRequest(myName + '.threads[' + thr + ']', null);
  // Record this thread as loading for this destination, so it can be aborted later.
  loadingIDs[destId] = thr;
 }

 // Assign our callback function; it passed the destination to copyContent.
 threads[thr].callback = new Function('doc', 'uri', 'with (' + myName + ') { ' +
  'copyContent(doc, "' + destId + '"); if (onload) onload(doc, uri, "' + destId + '") }');

 return threads[thr];
}};


RemoteFileLoader.prototype.loadInto = function(uri, destId)
{
 // Pass the file onto the load method of the selected thread.
 return this.getThread(destId).load(uri);
};


RemoteFileLoader.prototype.submitInto = function(formRef, destId, event)
{
 // Pass the file onto the submit method of the selected thread.
 return this.getThread(destId).submit(formRef, event);
};


RemoteFileLoader.prototype.copyContent = function(domDoc, destId)
{
 // This copies the <body> content of the loaded DOM document into an element in the
 // current page with a specified ID.
 
 // Make sure the user session hasn't expired on Firefox
 if (domDoc && domDoc.getElementById && domDoc.getElementById('log-in'))
 	return;
	 	
 // Retrieve references to the loaded BODY. You might want to modify this so that you
 // load content from <div id="content"> within the loaded document perhaps?	 	
 if(domDoc.getElementsByTagName || domDoc.body) {
	 var src = domDoc.getElementsByTagName ? domDoc.getElementsByTagName('body')[0] :
	  (domDoc.body ? domDoc.body : null);
	 var dest = document.getElementById ? document.getElementById(destId) :
	  (document.all ? document.all[destId] : null);
	 if (!src || !dest) return;
	 // innerHTML is still a little more reliable than importNode across browsers.
	 if (src.innerHTML) dest.innerHTML = src.innerHTML;
	 else if (document.importNode)
	 {
	  while (dest.firstChild) dest.removeChild(dest.firstChild);
	  for (var i = 0; i < src.childNodes.length; i++)
	   dest.appendChild(document.importNode(src.childNodes.item(i), true));
	 }
 }
 else
 	return;
 	
};


var AJAXGlobalNav = new RemoteFileLoader('AJAXGlobalNav');

var isAJAXMenuLoaded = false;
 
function getAJAXMenu() {
	if(!isAJAXMenuLoaded) {
		if(AJAXGlobalNav.loadInto('/cms/entity/listfactories.act', 'global-nav')) {
			AJAXGlobalNav.onload = showAJAXMenu;
			isAJAXMenuLoaded = true;
		}
	}
}

function showAJAXMenu() {
	if(document.getElementById('ajax-menu')) {
		DynarchMenu.setup('ajax-menu', { lazy: true });
		loadHelpNewWindow();
	}
}




/*
(C) www.dhtmlgoodies.com, September 2005
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
*/
var languageCode = 'en';	// Possible values: 	en,ge,no,nl,es,pt-br,fr	
							// en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)
					
var todayStringFormat = '[todayString] [dayString]. [day]. [monthString] [year]';						
var pathToImages = '/cms/css/images/';	// Relative to your HTML file



var calendar_offsetTop = 0;		// Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0;	// Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;

var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;


switch(languageCode){
	case "en":	/* English */
		var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
		var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
		var weekString = 'Week';
		var todayString = 'Today is';
		break;
	case "ge":	/* German */
		var monthArray = ['J?nner','Februar','M?rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
		var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];	
		var weekString = 'Woche';
		var todayString = 'Heute';		
		break;
	case "no":	/* Norwegian */
		var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
		var dayArray = ['Man','Tir','Ons','Tor','Fre','L&oslash;r','S&oslash;n'];	
		var weekString = 'Uke';
		var todayString = 'Dagen i dag er';
		break;	
	case "nl":	/* Dutch */
		var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
		var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
		var weekString = 'Week';
		var todayString = 'Vandaag';
		break;	
	case "es": /* Spanish */
		var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
		var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
		var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
		var weekString = 'Semana';
		var todayString = 'Hoy es';
		break; 	
	case "pt-br":  /* Brazilian portuguese (pt-br) */
		var monthArray = ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
		var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
		var dayArray = ['Seg','Ter','Qua','Qui','Sex','S&aacute;b','Dom'];
		var weekString = 'Sem.';
		var todayString = 'Hoje &eacute;';
		break;
	case "fr":      /* French */
		var monthArray = ['Janvier','F?vrier','Mars','Avril','Mai','Juin','Juillet','Ao?t','Septembre','Octobre','Novembre','D?cembre'];		
		var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
		var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
		var weekString = 'Sem';
		var todayString = "Aujourd'hui";
		break; 	
	case "ru":	/* Russian - Remember to use encoding windows-1251 , i.e. the <meta> tag. */
		var monthArray = ['??????','???????','????','??????','???','????','????','??????','????????','???????','??????','???????'];
		var monthArrayShort = ['???','???','???','???','???','???','???','???','???','???','???','???'];
		var dayArray = ['??','??','??','??','??','??','??'];
		var weekString = '#';
		var todayString = '???????';
		break;		
	case "da": /*Danish*/
		var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
		var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
		var dayArray = ['man','tirs','ons','tors','fre','l?r','s?n']
		var weekString = 'Uge';
		var todayString = 'I dag er den';
		break;	
	case "hu":	/* Hungarian  - Remember to use UTF-8 encoding, i.e. the <meta> tag */
		var monthArray = ['Janu??r','Febru??r','M??rcius','??prilis','M??jus','J??nius','J??lius','Augusztus','Szeptember','Okt??ber','November','December'];
		var monthArrayShort = ['Jan','Feb','M??rc','??pr','M??j','J??n','J??l','Aug','Szep','Okt','Nov','Dec'];
		var dayArray = ['H??','Ke','Sze','Cs','P??','Szo','Vas'];
		var weekString = 'H??t';
		var todayString = 'Mai nap';	
	case "it":	/* Italian*/
		var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
		var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
		var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
		var weekString = 'Settimana';
		var todayString = 'Oggi &egrave; il';
		break;

}


var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var iframeObj = false;

var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;

var inputYear;
var inputMonth;
var inputDay;

var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
function cancelCalendarEvent()
{
	return false;
}
function isLeapYear(inputYear)
{
	if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
	return false;	
	
}
var activeSelectBoxMonth = false;

function highlightMonthYear()
{
	if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
	
	if(this.className=='monthYearActive'){
		this.className='';	
	}else{
		this.className = 'monthYearActive';
		activeSelectBoxMonth = this;
	}
}

function showMonthDropDown()
{
	if(document.getElementById('monthDropDown').style.display=='block'){
		document.getElementById('monthDropDown').style.display='none';	
	}else{
		document.getElementById('monthDropDown').style.display='block';		
		document.getElementById('yearDropDown').style.display='none';
	}
}

function showYearDropDown()
{
	if(document.getElementById('yearDropDown').style.display=='block'){
		document.getElementById('yearDropDown').style.display='none';	
	}else{
		document.getElementById('yearDropDown').style.display='block';	
		document.getElementById('monthDropDown').style.display='none';	
	}		

}

function selectMonth()
{
	document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
	currentMonth = this.id.replace(/[^\d]/g,'');

	document.getElementById('monthDropDown').style.display='none';
	for(var no=0;no<monthArray.length;no++){
		document.getElementById('monthDiv_'+no).style.color='';	
	}
	this.style.color = selectBoxHighlightColor;
	activeSelectBoxMonth = this;
	writeCalendarContent();
	
}

function selectYear()
{
	document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
	currentYear = this.innerHTML.replace(/[^\d]/g,'');
	document.getElementById('yearDropDown').style.display='none';
	if(activeSelectBoxYear){
		activeSelectBoxYear.style.color='';
	}
	activeSelectBoxYear=this;
	this.style.color = selectBoxHighlightColor;
	writeCalendarContent();
	
}

function switchMonth()
{
	if(this.src.indexOf('left')>=0){
		currentMonth=currentMonth-1;;
		if(currentMonth<0){
			currentMonth=11;
			currentYear=currentYear-1;
		}
	}else{
		currentMonth=currentMonth+1;;
		if(currentMonth>11){
			currentMonth=0;
			currentYear=currentYear/1+1;
		}	
	}	
	
	writeCalendarContent();	
	
	
}

function createMonthDiv(){
	var div = document.createElement('DIV');
	div.className='monthYearPicker';
	div.id = 'monthPicker';
	
	for(var no=0;no<monthArray.length;no++){
		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = monthArray[no];
		subDiv.onmouseover = highlightMonthYear;
		subDiv.onmouseout = highlightMonthYear;
		subDiv.onclick = selectMonth;
		subDiv.id = 'monthDiv_' + no;
		subDiv.style.width = '56px';
		subDiv.onselectstart = cancelCalendarEvent;		
		div.appendChild(subDiv);
		if(currentMonth && currentMonth==no){
			subDiv.style.color = selectBoxHighlightColor;
			activeSelectBoxMonth = subDiv;
		}				
		
	}	
	return div;
	
}

function changeSelectBoxYear()
{

	var yearItems = this.parentNode.getElementsByTagName('DIV');
	if(this.innerHTML.indexOf('-')>=0){
		var startYear = yearItems[1].innerHTML/1 -1;
		if(activeSelectBoxYear){
			activeSelectBoxYear.style.color='';
		}
	}else{
		var startYear = yearItems[1].innerHTML/1 +1;
		if(activeSelectBoxYear){
			activeSelectBoxYear.style.color='';

		}			
	}

	for(var no=1;no<yearItems.length-1;no++){
		yearItems[no].innerHTML = startYear+no-1;	
		yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);	
		
	}		
	if(activeSelectBoxYear){
		activeSelectBoxYear.style.color='';
		if(document.getElementById('yearDiv'+currentYear)){
			activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
			activeSelectBoxYear.style.color=selectBoxHighlightColor;;
		}
	}
}

function updateYearDiv()
{
	var div = document.getElementById('yearDropDown');
	var yearItems = div.getElementsByTagName('DIV');
	for(var no=1;no<yearItems.length-1;no++){
		yearItems[no].innerHTML = currentYear/1 -6 + no;	
		if(currentYear==(currentYear/1 -6 + no)){
			yearItems[no].style.color = selectBoxHighlightColor;
			activeSelectBoxYear = yearItems[no];				
		}else{
			yearItems[no].style.color = '';
		}
	}		
}

function updateMonthDiv()
{
	for(no=0;no<12;no++){
		document.getElementById('monthDiv_' + no).style.color = '';
	}		
	document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
	activeSelectBoxMonth = 	document.getElementById('monthDiv_' + currentMonth);
}

function createYearDiv()
{

	if(!document.getElementById('yearDropDown')){
		var div = document.createElement('DIV');
		div.className='monthYearPicker';
	}else{
		var div = document.getElementById('yearDropDown');
		var subDivs = div.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++){
			subDivs[no].parentNode.removeChild(subDivs[no]);	
		}	
	}	
	
	
	var d = new Date();
	if(currentYear){
		d.setFullYear(currentYear);	
	}

	var startYear = d.getFullYear()/1 - 5;

	
	var subDiv = document.createElement('DIV');
	subDiv.innerHTML = '&nbsp;&nbsp;- ';
	subDiv.onclick = changeSelectBoxYear;
	subDiv.onmouseover = highlightMonthYear;
	subDiv.onmouseout = highlightMonthYear;	
	subDiv.onselectstart = cancelCalendarEvent;			
	div.appendChild(subDiv);
	
	for(var no=startYear;no<(startYear+10);no++){
		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = no;
		subDiv.onmouseover = highlightMonthYear;
		subDiv.onmouseout = highlightMonthYear;		
		subDiv.onclick = selectYear;		
		subDiv.id = 'yearDiv' + no;	
		subDiv.onselectstart = cancelCalendarEvent;	
		div.appendChild(subDiv);
		if(currentYear && currentYear==no){
			subDiv.style.color = selectBoxHighlightColor;
			activeSelectBoxYear = subDiv;
		}			
	}
	var subDiv = document.createElement('DIV');
	subDiv.innerHTML = '&nbsp;&nbsp;+ ';
	subDiv.onclick = changeSelectBoxYear;
	subDiv.onmouseover = highlightMonthYear;
	subDiv.onmouseout = highlightMonthYear;		
	subDiv.onselectstart = cancelCalendarEvent;			
	div.appendChild(subDiv);		

	
	return div;
}

function highlightSelect()
{
	if(this.className=='selectBox'){
		this.className = 'selectBoxOver';	
		this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif';
	}else{
		this.className = 'selectBox';	
		this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif';			
	}
	
}

function highlightArrow()
{
	if(this.src.indexOf('over')>=0){
		if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif';	
		if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif';				
	}else{
		if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif';	
		if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif';	
	}
}

function highlightClose()
{
	if(this.src.indexOf('over')>=0){
		this.src = pathToImages + 'close.gif';
	}else{
		this.src = pathToImages + 'close_over.gif';	
	}	

}

function closeCalendar()
{
	document.getElementById('yearDropDown').style.display='none';
	document.getElementById('monthDropDown').style.display='none';
		
	calendarDiv.style.display='none';
	if(iframeObj)iframeObj.style.display='none';
	if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
	if(activeSelectBoxYear)activeSelectBoxYear.className='';
	
}

function writeTopBar()
{

	var topBar = document.createElement('DIV');
	topBar.className = 'topBar';
	topBar.id = 'topBar';
	calendarDiv.appendChild(topBar);
	
	// Left arrow
	var leftDiv = document.createElement('DIV');
	leftDiv.style.marginRight = '1px';
	var img = document.createElement('IMG');
	img.src = pathToImages + 'left.gif';
	img.onmouseover = highlightArrow;
	img.onclick = switchMonth;
	img.onmouseout = highlightArrow;
	leftDiv.appendChild(img);	
	topBar.appendChild(leftDiv);
	if(Opera)leftDiv.style.width = '16px';
	
	// Right arrow
	var rightDiv = document.createElement('DIV');
	rightDiv.style.marginRight = '1px';
	var img = document.createElement('IMG');
	img.src = pathToImages + 'right.gif';
	img.onclick = switchMonth;
	img.onmouseover = highlightArrow;
	img.onmouseout = highlightArrow;
	rightDiv.appendChild(img);
	if(Opera)rightDiv.style.width = '16px';
	topBar.appendChild(rightDiv);		

			
	// Month selector
	var monthDiv = document.createElement('DIV');
	monthDiv.id = 'monthSelect';
	monthDiv.onmouseover = highlightSelect;
	monthDiv.onmouseout = highlightSelect;
	monthDiv.onclick = showMonthDropDown;
	var span = document.createElement('SPAN');		
	span.innerHTML = monthArray[currentMonth];
	span.id = 'calendar_month_txt';
	monthDiv.appendChild(span);

	var img = document.createElement('IMG');
	img.src = pathToImages + 'down.gif';
	img.style.position = 'absolute';
	img.style.right = '0px';
	monthDiv.appendChild(img);
	monthDiv.className = 'selectBox';
	if(Opera){
		img.style.cssText = 'float:right;position:relative';
		img.style.position = 'relative';
		img.style.styleFloat = 'right';
	}
	topBar.appendChild(monthDiv);

	var monthPicker = createMonthDiv();
	monthPicker.style.left = '37px';
	monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
	monthPicker.style.width ='60px';
	monthPicker.id = 'monthDropDown';
	
	calendarDiv.appendChild(monthPicker);
			
	// Year selector
	var yearDiv = document.createElement('DIV');
	yearDiv.onmouseover = highlightSelect;
	yearDiv.onmouseout = highlightSelect;
	yearDiv.onclick = showYearDropDown;
	var span = document.createElement('SPAN');		
	span.innerHTML = currentYear;
	span.id = 'calendar_year_txt';
	yearDiv.appendChild(span);
	topBar.appendChild(yearDiv);
	
	var img = document.createElement('IMG');
	img.src = pathToImages + 'down.gif';
	yearDiv.appendChild(img);
	yearDiv.className = 'selectBox';
	
	if(Opera){
		yearDiv.style.width = '50px';
		img.style.cssText = 'float:right';
		img.style.position = 'relative';
		img.style.styleFloat = 'right';
	}	
	
	var yearPicker = createYearDiv();
	yearPicker.style.left = '113px';
	yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
	yearPicker.style.width = '35px';
	yearPicker.id = 'yearDropDown';
	calendarDiv.appendChild(yearPicker);
	
		
	var img = document.createElement('IMG');
	img.src = pathToImages + 'close.gif';
	img.style.styleFloat = 'right';
	img.onmouseover = highlightClose;
	img.onmouseout = highlightClose;
	img.onclick = closeCalendar;
	topBar.appendChild(img);
	if(!document.all){
		img.style.position = 'absolute';
		img.style.right = '2px';
	}
	
	

}

function writeCalendarContent()
{
	var calendarContentDivExists = true;
	if(!calendarContentDiv){
		calendarContentDiv = document.createElement('DIV');
		calendarDiv.appendChild(calendarContentDiv);
		calendarContentDivExists = false;
	}
	currentMonth = currentMonth/1;
	var d = new Date();	
	
	d.setFullYear(currentYear);		
	d.setDate(1);		
	d.setMonth(currentMonth);
	
	var dayStartOfMonth = d.getDay();
	if(dayStartOfMonth==0)dayStartOfMonth=7;
	dayStartOfMonth--;
	
	document.getElementById('calendar_year_txt').innerHTML = currentYear;
	document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
	
	var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
	if(existingTable.length>0){
		calendarContentDiv.removeChild(existingTable[0]);
	}
	
	var calTable = document.createElement('TABLE');
	calTable.cellSpacing = '0';
	calendarContentDiv.appendChild(calTable);
	var calTBody = document.createElement('TBODY');
	calTable.appendChild(calTBody);
	var row = calTBody.insertRow(-1);
	var cell = row.insertCell(-1);
	cell.innerHTML = weekString;
	cell.style.backgroundColor = selectBoxRolloverBgColor;
	
	for(var no=0;no<dayArray.length;no++){
		var cell = row.insertCell(-1);
		cell.innerHTML = dayArray[no]; 
	}
	
	var row = calTBody.insertRow(-1);
	var cell = row.insertCell(-1);
	cell.style.backgroundColor = selectBoxRolloverBgColor;
	var week = getWeek(currentYear,currentMonth,1);
	cell.innerHTML = week;		// Week
	for(var no=0;no<dayStartOfMonth;no++){
		var cell = row.insertCell(-1);
		cell.innerHTML = '&nbsp;';
	}

	var colCounter = dayStartOfMonth;
	var daysInMonth = daysInMonthArray[currentMonth];
	if(daysInMonth==28){
		if(isLeapYear(currentYear))daysInMonth=29;
	}
	
	for(var no=1;no<=daysInMonth;no++){
		d.setDate(no-1);
		if(colCounter>0 && colCounter%7==0){
			var row = calTBody.insertRow(-1);
			var cell = row.insertCell(-1);
			var week = getWeek(currentYear,currentMonth,no);
			cell.innerHTML = week;		// Week	
			cell.style.backgroundColor = selectBoxRolloverBgColor;			
		}
		var cell = row.insertCell(-1);
		if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
			cell.className='activeDay';	
		}
		cell.innerHTML = no;
		cell.onclick = pickDate;
		colCounter++;
	}
	
	
	if(!document.all){
		if(calendarContentDiv.offsetHeight)
			document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
		else{
			document.getElementById('topBar').style.top = '';
			document.getElementById('topBar').style.bottom = '0px';
		}
			
	}
	
	if(iframeObj){
		if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
	}
		
	
}

function resizeIframe()
{
	iframeObj.style.width = calendarDiv.offsetWidth + 'px';
	iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;	
	
	
}

function pickTodaysDate()
{
	var d = new Date();
	currentMonth = d.getMonth();
	currentYear = d.getFullYear();
	pickDate(false,d.getDate());
	
}

function pickDate(e,inputDay)
{
	var month = currentMonth/1 +1;
	if(month<10)month = '0' + month;
	var day;
	if(!inputDay && this)day = this.innerHTML; else day = inputDay;
	
	if(day/1<10)day = '0' + day;
	if(returnFormat){
		returnFormat = returnFormat.replace('dd',day);
		returnFormat = returnFormat.replace('mm',month);
		returnFormat = returnFormat.replace('yyyy',currentYear);
		returnDateTo.value = returnFormat;
	}else{
		for(var no=0;no<returnDateToYear.options.length;no++){
			if(returnDateToYear.options[no].value==currentYear){
				returnDateToYear.selectedIndex=no;
				break;
			}				
		}
		for(var no=0;no<returnDateToMonth.options.length;no++){
			if(returnDateToMonth.options[no].value==month){
				returnDateToMonth.selectedIndex=no;
				break;
			}				
		}
		for(var no=0;no<returnDateToDay.options.length;no++){
			if(returnDateToDay.options[no].value==day){
				returnDateToDay.selectedIndex=no;
				break;
			}				
		}
		
		
	}
	closeCalendar();
	
}

// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
	day = day/1;
	year = year /1;
    month = month/1 + 1; //use 1-12
    var a = Math.floor((14-(month))/12);
    var y = year+4800-a;
    var m = (month)+(12*a)-3;
    var jd = day + Math.floor(((153*m)+2)/5) + 
                 (365*y) + Math.floor(y/4) - Math.floor(y/100) + 
                 Math.floor(y/400) - 32045;      // (gregorian calendar)
    var d4 = (jd+31741-(jd%7))%146097%36524%1461;
    var L = Math.floor(d4/1460);
    var d1 = ((d4-L)%365)+L;
    NumberOfWeek = Math.floor(d1/7) + 1;
    return NumberOfWeek;        
}

function writeBottomBar()
{
	var d = new Date();
	var topBar = document.createElement('DIV');
	topBar.id = 'bottomBar';
	topBar.onclick = pickTodaysDate;
	topBar.style.cursor = 'pointer';
	topBar.className = 'todaysDate';
	// var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]';	;;
	
	var day = d.getDay();
	if(day==0)day = 7;
	day--;
	
	var bottomString = todayStringFormat;
	bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
	bottomString = bottomString.replace('[day]',d.getDate());
	bottomString = bottomString.replace('[year]',d.getFullYear());
	bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
	bottomString = bottomString.replace('[todayString]',todayString);
	
	
	topBar.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' +  d.getFullYear() ;
	topBar.innerHTML = bottomString ;
	calendarDiv.appendChild(topBar);	
	
	
		
}

/**
 * original idea taken from http://www.sitepoint.com/article/scroll-smoothly-javascript/2
 * used to get the actual "top" position from the main-wrapper (will be 0 unless the user has scrolled down)
 */
function getCurrentScrollPos() {
	// get the content element
	var middle = document.getElementById('main-wrapper');
	if (middle.scrollTop) 
		return middle.scrollTop; 
	return 0; 
}
function getTopPos(inputObj)
{
	/**
	 * Fixed on 3/27/2007 by Ben Ku to handle scrolled offsets so that if the item is below the fold the calendar still shows up in the right place
	 **/
	var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
	while((inputObj = inputObj.offsetParent) != null)
	{
		returnValue += inputObj.offsetTop;
	}
	returnValue += calendar_offsetTop;
	// adjust for scrolling
	returnValue -= getCurrentScrollPos();
	return returnValue;
}

function getleftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue + calendar_offsetLeft;
}

function positionCalendar(inputObj)
{
	calendarDiv.style.left = getleftPos(inputObj) + 'px';
	calendarDiv.style.top = getTopPos(inputObj) + 'px';
	if(iframeObj){
		iframeObj.style.left = calendarDiv.style.left;
		iframeObj.style.top =  calendarDiv.style.top;
	}
		
}
	
function initCalendar()
{
	if(MSIE){
		iframeObj = document.createElement('IFRAME');
		iframeObj.style.position = 'absolute';
		iframeObj.border='0px';
		iframeObj.style.border = '0px';
		iframeObj.style.backgroundColor = '#FF0000';
		document.body.appendChild(iframeObj);
	}
		
	calendarDiv = document.createElement('DIV');	
	calendarDiv.id = 'calendarDiv';
	calendarDiv.style.zIndex = 1000;
	
	document.body.appendChild(calendarDiv);
	writeBottomBar();
	writeTopBar();
	

	
	if(!currentYear){
		var d = new Date();
		currentMonth = d.getMonth();
		currentYear = d.getFullYear();
	}
	writeCalendarContent();	


		
}


function displayCalendar(inputField,format,buttonObj)
{
	/*Added by HH so that you can pass an 'id' attribute in*/
	if(document.getElementById(inputField))
		inputField = document.getElementById(inputField);
		
	if(inputField.value.length==format.length){
		var monthPos = format.indexOf('mm');
		currentMonth = inputField.value.substr(monthPos,2)/1 -1;	
		var yearPos = format.indexOf('yyyy');
		currentYear = inputField.value.substr(yearPos,4);		
		var dayPos = format.indexOf('dd');
		tmpDay = inputField.value.substr(dayPos,2);	
	}else{
		var d = new Date();
		currentMonth = d.getMonth();
		currentYear = d.getFullYear();
		tmpDay = d.getDate();
	}
	
	inputYear = currentYear;
	inputMonth = currentMonth;
	inputDay = tmpDay/1;
	
	if(!calendarDiv){
		initCalendar();			
	}else{
		if(calendarDiv.style.display=='block'){
			closeCalendar();
			return false;
		}
		writeCalendarContent();
	}			
	returnFormat = format;
	returnDateTo = inputField;
	positionCalendar(buttonObj);
	calendarDiv.style.visibility = 'visible';	
	calendarDiv.style.display = 'block';	
	if(iframeObj){
		iframeObj.style.display = '';
		iframeObj.style.height = '140px';
		iframeObj.style.width = '195px';
	}
	updateYearDiv();
	updateMonthDiv();
	
}

function displayCalendarSelectBox(yearInput,monthInput,dayInput,buttonObj)
{
	currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
	currentYear = yearInput.options[yearInput.selectedIndex].value;

	inputYear = yearInput.options[yearInput.selectedIndex].value;
	inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
	inputDay = dayInput.options[dayInput.selectedIndex].value/1;
			
	if(!calendarDiv){
		initCalendar();			
	}else{
		writeCalendarContent();
	}		

	returnDateToYear = yearInput;
	returnDateToMonth = monthInput;
	returnDateToDay = dayInput;

	returnFormat = false;
	returnDateTo = false;
	positionCalendar(buttonObj);
	calendarDiv.style.visibility = 'visible';	
	calendarDiv.style.display = 'block';
	if(iframeObj){
		iframeObj.style.display = '';
		iframeObj.style.height = calendarDiv.offsetHeight + 'px';
		iframeObj.style.width = calendarDiv.offsetWidth + 'px';	
	}
	updateYearDiv();
	updateMonthDiv();
		
}




// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/

// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}
		
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
	
// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}
	
// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
			}
		}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.text, o.value, false, false);
				}
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
		}
	}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}
	
// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) { 
	if (!hasOptions(from)) { return; }
	if (from.type=="select-one") {
		from.options[from.selectedIndex] = null;
		}
	else {
		for (var i=(from.options.length-1); i>=0; i--) { 
			var o=from.options[i]; 
			if (o.selected) { 
				from.options[i] = null; 
				} 
			}
		}
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) { 
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		from.options[i] = null; 
		} 
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list
// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}