//
// IF THE USER UNCHECKS THE CHECKBOX THEN WE ASK FOR A CONFIRMATION BECAUSE THIS MAY HAVE
// SIDE EFFECTS FOR CHILD PROPERTIES.
//
function ProcessCheckBoxClick (ParentProperty, ChildProperty, CurrentCheckBox)
{
	// USER UNCHECKS A CHECKBOX.
	// DISABLE ALL DEPEDENDENTS AND THEIR DEPENDENTS IF WE UNCHECK A PARENT CHECKBOX.
	//
	if (CurrentCheckBox.checked == false)
	{
		var continueToUncheck = true; //confirm("Removing this value from " + ParentProperty + " means that corresponding values in " + ChildProperty + " (and possibly others) must be deleted.  Click OK to uncheck this box or CANCEL to keep the box checked.");
		CurrentCheckBox.checked = !continueToUncheck;
		if (continueToUncheck)
		{
			VisitCheckBoxes(CurrentCheckBox, UncheckAndDisableCheckBox);
			CurrentCheckBox.disabled = false;
		}
	}
	//
	// USER CHECKS A CHECKBOX.
	// ENABLE THE IMMEDIATE CHILDREN OF THE CHECKBOX.
	//
	else
		VisitChildren(CurrentCheckBox, EnableCheckBox);
	
	//
	// WE NEED TO HIDE OR SHOW DEPENDENT VALUES.  THESE ARE PLACED IN A DIV ELEMENT.
	//
	ProcessCheckBoxVisibility(CurrentCheckBox);
	RefreshSelectedCriteria();
}


//
// HIDE OR SHOW THE DIV ELEMENT FOR THE CHECKBOX.
//
function ProcessCheckBoxVisibility (CurrentCheckBox)
{
	document.getElementById(CurrentCheckBox.id + "Table").style.display = (CurrentCheckBox.checked ? "block" : "none");
}

//RefreshSelectedCriteria refreshes the display of the SelectedCriteria box, 
//based on what checkboxes have been checked.
function RefreshSelectedCriteria()
{
	var listElement;
	var currentCriteriaSection;
	var currentSectionInputControls;
	var currentFormControl;
	
	for(var i = 0; i < categoryListHeaders.length; i++)
	{
		currentCriteriaSection = document.getElementById(categoryListHeaders[i]);
		listElement = document.getElementById(categoryListHeaders[i] + "UL");
	
		if(currentCriteriaSection && listElement)
		{
			//First clear any existing items under each criteria to refresh the list.
			while(listElement.hasChildNodes())
			{
				listElement.removeChild(listElement.firstChild);
			}		

			currentSectionInputControls = currentCriteriaSection.getElementsByTagName("input");
			for(var j = 0; j < currentSectionInputControls.length; j++)
			{
				currentFormControl = currentSectionInputControls[j];
				if(currentFormControl.type == "checkbox" && currentFormControl.checked && currentFormControl.IsATopLevelParentValue)
				{
					VisitCheckBoxes(currentFormControl, UpdateSelectedCriteria, listElement);
				}
			}

			if(listElement.childNodes.length == 0)
			{
				AddDefaultListItem(listElement);
			}
		}
	}
}
//UpdateSelectedCriteria modified the content of the 'Selected Criteria' list as checkboxes are clicked or unclicked.
function UpdateSelectedCriteria(docElement, listElement)
{	
	if(docElement && docElement.type == "checkbox" && docElement.checked)
	{
		var newLiNode = listElement.appendChild(document.createElement('li'));
		var newLiText = newLiNode.appendChild(document.createTextNode(docElement.title));
	}
}
//AddDefaultListItem adds a default text in the Selected Criteria section 
//for the LI of a criteria section that doesn't have any options selected yet.
function AddDefaultListItem(listElement)
{
	var newLiNode = listElement.appendChild(document.createElement('li'));
	var newLiText = newLiNode.appendChild(document.createTextNode("No options selected"));
}
//
// GIVEN A CHECKBOX AND A METHOD, OPERATE ON THE IMMEDIATE CHILDREN OF THE CHECKBOX ONLY.
//
function VisitChildren (ParentCheckBox, VisitorMethod)
{
	for (var i = 0; i < ParentCheckBox.Dependents.length; i++)
		VisitorMethod(ParentCheckBox.Dependents[i]);
}


//
// TRAVERSES ON A SET OF CHECKBOX FORM CONTROLS.  THIS IS SIMILAR TO THE VISITOR PATTERN (BUT IT ISN'T A VISITOR PATTERN).
//
function VisitCheckBoxes (ParentCheckBox, VisitorMethod, additionalParam)
{
	VisitorMethod(ParentCheckBox, additionalParam);

	for (var i = 0; i < ParentCheckBox.Dependents.length; i++)
		VisitCheckBoxes(ParentCheckBox.Dependents[i], VisitorMethod, additionalParam);
}


//
// UNCHECKS AND DISABLES A CHECKBOX CONTROL
//
function UncheckAndDisableCheckBox (CheckBox)
{
	CheckBox.checked = false;
	CheckBox.disabled = true;
	
	if (CheckBox.IsAParentValue)
		ProcessCheckBoxVisibility(CheckBox);
}


//
// CHECKS AND ENABLES A CHECKBOX CONTROL
//
function EnableCheckBox (CheckBox)
{
	CheckBox.disabled = false;
}


//
// INITIALIZES THE CHECKBOXES - SETTING THE APPROPRIATE CHECKBOXES TO DISABLED ON THE META DATA FORM WHEN THE PAGE IS FIRST LOADED.
//
function InitializeForm (MetaDataFormName, ajaxFileName)
{
	//
	// GET A REFERENCE TO THE META DATA FORM.
	//
	var MetaDataForm = document.getElementById(MetaDataFormName);
	
	//
	// GO THROUGH EVERY FORM ELEMENT AVAILABLE.
	//
	for (var i = 0; i < MetaDataForm.elements.length; i++)
	{
		var CurrentFormControl = MetaDataForm.elements[i];
		
		//
		// PROCESS ONLY CHECKBOXES.
		// WE ASSUME THAT THE DEPENDENTS ARRAY HAS BEEN BUILT FOR EVERY CHECKBOX.
		//
		if(CurrentFormControl.type == "checkbox")
		{
			//
			// WE ONLY CARE ABOUT THE FOLLOWING 2 COMPOUND CASES:
			// 1. IF THE CHECKBOX IS CHECKED AND IF IT'S A PARENT VALUE THEN WE ENABLE ITS CHILD CHECKBOXES.
			// 2. IF THE CHECKBOX IS NOT CHECKED AND IF IT'S A TOP LEVEL PARENT VALUE THEN UNCHECK AND DISABLE ALL OF ITS DESCENDANTS.
			// KEEP IN MIND THAT WE ARE NOT PERFORMING A RECURSIVE TRAVERSAL HERE.  THIS IS A STRAIGHT SEQUENTIAL ITERATION THROUGH THE FORM'S ELEMENTS ARRAY.
			// THIS PROBABLY WON'T WORK IF A CHILD CHECKBOX IS LISTED BEFORE ITS PARENT.
			//
			if (CurrentFormControl.checked && CurrentFormControl.IsAParentValue)
				VisitChildren(CurrentFormControl, EnableCheckBox);
			else if (!CurrentFormControl.checked && CurrentFormControl.IsATopLevelParentValue)
			{
				//
				// UNCHECK AND DISABLE CHILD VALUES FOR OTHER PROPERTIES.
				// THIS DISABLES THE PARENT VALUES ALSO (WHICH ISN'T GOOD, SO WE FIX IT RIGHT BELOW).
				//
				VisitCheckBoxes(CurrentFormControl, UncheckAndDisableCheckBox);
				CurrentFormControl.disabled = false;
			}

			//
			// INITIALIZE THE VISIBILITY OF THE CHECKBOX
			//
			if (CurrentFormControl.IsAParentValue)
				ProcessCheckBoxVisibility(CurrentFormControl);
		}
	}
	
	setFormItemDisabled(checkboxesToDisable, true);
	RefreshSelectedCriteria()
	updateCount(MetaDataFormName, 'searchCount', ajaxFileName);
}


//
// ALLOWS THE USER TO COLLAPSE OR EXPAND A TOP-LEVEL PARENT.
//
function ToggleTableBodyDisplay (TableBodyId, TableBodySpanId, TableBodyShowHideButtonId)
{
	var TableBody = document.getElementById(TableBodyId);
	TableBody.style.display = (TableBody.style.display == "none" ? "block" : "none");
		
	ToggleShowHideButtonDisplay(TableBodyId, TableBodySpanId, TableBodyShowHideButtonId);
}
//ToggleShowHideButtonDisplay controls which image is displayed for each Property header,
//depending on whether that property's list is expanded or collapsed.
function ToggleShowHideButtonDisplay(TableBodyId, TableBodySpanId, TableBodyShowHideButtonId)
{
	var TableBody = document.getElementById(TableBodyId);	
	var buttonImage = document.getElementById(TableBodyShowHideButtonId);
	var buttonSpan = document.getElementById(TableBodySpanId);
	
	if(TableBody.style.display != "none")
	{
		buttonImage.src = buttonImage.src.replace(/button-\w+\.gif/, "button-hide.gif");
		buttonSpan.style.display = "none";
	}
	else
	{
		buttonImage.src = buttonImage.src.replace(/button-\w+\.gif/, "button-show.gif");
		buttonSpan.style.display = "inline";
	}
}


//
//
//
function InitializePage ()
{
	InitializeForm('ArticleMetaData');
}

function updateForm(formId, targetId, ajaxFileName)
{
	updateCount(formId, targetId, ajaxFileName);
	winnowForm(formId, ajaxFileName)
}

function updateCount(formId, targetId, ajaxFileName)
{
	var frm = document.getElementById(formId);
	
	if (frm)
	{
		var opt = {
			method: 'post',
			postBody: 'method=Count&' + Form.serialize(frm)
		}

		new Ajax.Updater(targetId, ajaxFileName, opt);
		return true;
	}
	return false;
}

function winnowForm(formId, ajaxFileName)
{
	var frm = document.getElementById(formId);
	
	if (frm)
	{
		var opt = {
			method: 'post',
			postBody: 'method=Disable&' + Form.serialize(frm),
			onSuccess: function(t) {
				//alert(t.responseText);
				updateFormItems(t.responseText);
			},
			on404: function(t) {
				alert('Error 404: location "' + t.statusText + '" was not found.');
			},
			onFailure: function(t) {
				alert('Error ' + t.status + ': ' + t.statusText);
			}
		}
		//alert('method=Disable&' + Form.serialize(frm));

		new Ajax.Request(ajaxFileName, opt);
		return true;
	}
	return false;
}

function updateFormItems(elementList)
{
	var checkboxList = elementList.split('|');
	for(var i = 0; i < checkboxList.length; i++)
	{
		if(i == 0)
		{
			setFormItemDisabled(checkboxList[i], true);
		}
		else if(i == 1)
		{
			setFormItemDisabled(checkboxList[i], false);
		}
	}
}

function setFormItemDisabled(checkboxList, isDisabled)
{
	var checkboxListArray = checkboxList.split(',');
	for(var i = 0; i < checkboxListArray.length; i++)
	{
		var currentCheckBox = document.getElementById(trimString(checkboxListArray[i]));
		if(currentCheckBox)
		{
			currentCheckBox.disabled = isDisabled;
		}
	}
}

function trimString(str)
{
	return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}



