var lngCheckFrequency = 100 // msecs

function ci() {
	try {
		hide(elementById("pageBody"));
		show(elementById("pageBodyHidden"));
	}
	catch(e) {
		logErr("ci", e)
	}
}

// move the row up one item
function mu(thisItem) {
	try {	

		var rowItem = findRowParent(thisItem);
		var intRow = rowItem.rowIndex
	
		if (intRow > 2) {
	
			// Find the questionOrder input fields
			var nodThisOrder = findChildIdStartingWith(tblQ.rows(intRow), "QO_");
			do {
	
				var nodPreviousOrder = findChildIdStartingWith(tblQ.rows(intRow-1), "QO_");
		
				// If the previous row has a QO_ child then swap the order numbers
				if (nodPreviousOrder != false) {
	
					// Find the questionOrder input fields
					var nodThisQuestion = findChildIdStartingWith(tblQ.rows(intRow), "QNQ_");
					var nodThisOrder = findChildIdStartingWith(tblQ.rows(intRow), "QO_");
					var nodPreviousQuestion = findChildIdStartingWith(tblQ.rows(intRow-1), "QNQ_");
		
					// Swap the order field values
					var strTempOrder = getValue(nodThisOrder);
					setValue(nodThisOrder, getValue(nodPreviousOrder));
					setValue(nodPreviousOrder, strTempOrder);
	
					// Update the display orders back on the server
					UpdateQuestionDisplayOrder(getValue(elementById("SurveyCode")), 
						getValue(nodThisQuestion), getValue(nodThisOrder), 
						getValue(nodPreviousQuestion), getValue(nodPreviousOrder))
			
				}
				
				tblQ.rows(intRow-1).swapNode(tblQ.rows(intRow));
				intRow--;
	
			} while (tblQ.rows(intRow-1).rt != "q" && intRow > 2)
	
			// checkQuestionParents(true, "", "0");
		}
	}
	catch(e) {
		logErr("mu", e)
	}
}

// move this question down one row
function md(thisItem) {

	try {	

		var rowItem = findRowParent(thisItem);
		var intRow = rowItem.rowIndex
	
		if (intRow < tblQ.rows.length-1) {
	
			// Find the questionOrder input fields
			var nodThisQuestion = findChildIdStartingWith(tblQ.rows(intRow), "QNQ_");
			var nodThisOrder = findChildIdStartingWith(tblQ.rows(intRow), "QO_");
			var nodNextQuestion = findChildIdStartingWith(tblQ.rows(intRow+1), "QNQ_");
			var nodNextOrder = findChildIdStartingWith(tblQ.rows(intRow+1), "QO_");
	
			// Don't update if this is the last in the included questions
			if (nodNextQuestion) {
				// Swap the order field values
				var strTempOrder = getValue(nodThisOrder);
				setValue(nodThisOrder, getValue(nodNextOrder));
				setValue(nodNextOrder, strTempOrder);
				
				// Update the display orders back on the server
				UpdateQuestionDisplayOrder(getValue(elementById("SurveyCode")), 
					getValue(nodThisQuestion), getValue(nodThisOrder), 
					getValue(nodNextQuestion), getValue(nodNextOrder))
		
				// Swap the rows
				tblQ.rows(intRow+1).swapNode(tblQ.rows(intRow));
			}
			// checkQuestionParents(true, "", "0");
		}
	}
	catch(e) {
		logErr("md", e)
	}
}

// Exclude this question from the questions in the survey
function me(thisItem) {
	try {	

		var rowItem = findRowParent(thisItem);
		var nodInclude = findChildIdStartingWith(rowItem, "QI_");
	
		if (nodInclude == false) {
			throw "Couldn't find include field"
		}
		else
		{
			// Update the question back on the server
			var nodThisQuestion = findChildIdStartingWith(rowItem, "QNQ_");
			UpdateQuestionInclusion(getValue(elementById("SurveyCode")), 
				getValue(nodThisQuestion), 0, 
				"false")
	
			nodInclude.value = "0";
			rowItem.style.display = "NONE";
		}
	}
	catch(e) {
		logErr("me", e)
	}
}

// reInclude this question in the survey
function mi(thisItem) {

	try {	

		var rowItem = findRowParent(thisItem);
		var nodInclude = findChildIdStartingWith(rowItem, "QI_");
	
		if (nodInclude == false) {
			alert("Couldn't find include field")
		}
		else {
			nodInclude.value = "1";
			
			// Shift the row up until it is before the deleted heading
			var intNewRow = moveUpRowUntilBefore(rowItem, "dqh");
			
			// Set the new order to 1 or 1 more than the last included question
			if (intNewRow <= 2) {
				var nodNewRowOrder = findChildIdStartingWith(tblQ.rows(intNewRow), "QO_");
				nodNewRowOrder.value = 1;
			}
			else {
				var nodPrevRowOrder = findChildIdStartingWith(tblQ.rows(intNewRow - 1), "QO_");
				var nodNewRowOrder = findChildIdStartingWith(tblQ.rows(intNewRow), "QO_");
				nodNewRowOrder.value = parseInt(nodPrevRowOrder.value) + 1;
			}
			
			// Update the question back on the server
			var nodThisQuestion = findChildIdStartingWith(rowItem, "QNQ_");
			var nodThisOrder = findChildIdStartingWith(rowItem, "QO_");
			UpdateQuestionInclusion(getValue(elementById("SurveyCode")), 
				getValue(nodThisQuestion), getValue(nodThisOrder), 
				"true")
	
			// Hide the cross
			var nodTickImage = findChildIdStartingWith(tblQ.rows(intNewRow), "QIi_");
			nodTickImage.style.display = "NONE"
			
			// Show the tick
			var nodCrossImage = findChildIdStartingWith(tblQ.rows(intNewRow), "QIe_");
			nodCrossImage.className = "img"
			
			// Show the move arrows
			var nodMoveItem = findChildIdStartingWith(tblQ.rows(intNewRow), "QOu_");
			nodMoveItem.className="img"
			nodMoveItem = findChildIdStartingWith(tblQ.rows(intNewRow), "QOd_");
			nodMoveItem.className="img"
			
			// Show the edit image
			var nodEdit = findChildIdStartingWith(tblQ.rows(intNewRow), "QE_");
			if (nodEdit != false) nodEdit.className = "Button";
			
			// Show the copy (duplicate) image
			var nodEdit = findChildIdStartingWith(tblQ.rows(intNewRow), "QD_");
			if (nodEdit != false) nodEdit.className = "Button";
			
			// Show the insert image
			var nodEdit = findChildIdStartingWith(tblQ.rows(intNewRow), "QC_");
			if (nodEdit != false) nodEdit.className = "Button";

			// checkQuestionParents(true, "", "0");
		}
	}
	catch(e) {
		logErr("mi", e)
	}
}

var objWindow = null
var intIntervalId
var strQuestion
var strQuestionOrder
var rowItem
var nodTable
var insertQuestion = false
var firstQuestion = false

// Create the first question in a new survey
function qf(thisItem) {

	try {	

		if (objWindow == null) {
		
			strQuestion = 0;
			strQuestionOrder = 0;
		
			objWindow = openWindow("question.asp?lite=yes&previousquestion=" + strQuestion, "_blank", "resizable=yes,scrollbars=yes,width=510,height=480");
			
			firstQuestion = true;

			intIntervalId = setInterval("checkWindow()", lngCheckFrequency); //
			
			return (false);
		}
		else {
			alert ("You can only edit / add one question at a time");
			return (false);
		}
		
	}
	catch(e) {
		logErr("qc", e)
	}
}

// Edit question in a new window
function qe(thisItem) {

	try {	

		if (objWindow == null) {
			rowItem = findRowParent(thisItem);
		
			disableFamily(rowItem);
		
			strQuestion = getValue(findChildIdStartingWith(rowItem, "QNQ_"));
		
			objWindow = openWindow("question.asp?lite=yes&question=" + strQuestion, "_blank", "resizable=yes,scrollbars=yes,width=510,height=480");
			
			insertQuestion = false;
			
			intIntervalId = setInterval("checkWindow()", lngCheckFrequency);
			
			return (false);
		}
		else {
			alert ("You can only edit / add one question at a time");
			return (false);
		}
		
	}
	catch(e) {
		logErr("qe", e)
	}
}

// Create question in a new window
function qc(thisItem) {

	try {	

		if (objWindow == null) {
			rowItem = findRowParent(thisItem);
		
			disableFamily(rowItem);
		
			strQuestion = getValue(findChildIdStartingWith(rowItem, "QNQ_"));
			strQuestionOrder = getValue(findChildIdStartingWith(rowItem, "QO_"));
		
			objWindow = openWindow("question.asp?lite=yes&previousquestion=" + strQuestion, "_blank", "resizable=yes,scrollbars=yes,width=510,height=480");
			
			insertQuestion = true;

			intIntervalId = setInterval("checkWindow()", lngCheckFrequency); //
			
			return (false);
		}
		else {
			alert ("You can only edit / add one question at a time");
			return (false);
		}
		
	}
	catch(e) {
		logErr("qc", e)
	}
}

// Copy (duplicate) this question in a new window
function qd(thisItem) {

	try {	

		if (objWindow == null) {
			rowItem = findRowParent(thisItem);
		
			disableFamily(rowItem);
		
			strQuestion = getValue(findChildIdStartingWith(rowItem, "QNQ_"));
			strQuestionOrder = getValue(findChildIdStartingWith(rowItem, "QO_"));
		
			objWindow = openWindow("question.asp?lite=yes&duplicate=yes&previousquestion=" + strQuestion, "_blank", "resizable=yes,scrollbars=yes,width=510,height=480");
			
			insertQuestion = true;

			intIntervalId = setInterval("checkWindow()", lngCheckFrequency); //
			
			return (false);
		}
		else {
			alert ("You can only edit / add one question at a time");
			return (false);
		}
		
	}
	catch(e) {
		logErr("qc", e)
	}
}

function openWindow(Url, WindowName, WindowFeatures) {

	try {	

		return (window.open(Url, WindowName, WindowFeatures)) // 
	}
	catch(e) {
		logErr("openWindow", e, " Url:" + Url + " WindowName:" + WindowName + " WindowFeatures:" + WindowFeatures)
	}
}

function checkWindow(thisItem) {

	try {	

		if (objWindow.closed) {
			clearInterval(intIntervalId);
			
			setTimeout("refreshQuestion()", 10);
		}
	}
	catch(e) {
		logErr("checkWindow", e)
	}
}

function refreshQuestion(thisItem) {

	try {
		var intLastHeadingLevel, blnLastParent

		// If this is the first question in the form then refresh it
		if (firstQuestion) {
			var objSave = elementById("Save");
			objSave.click();
		}
		// Has a new question been created
		else {
			
			nodTable = rowItem.parentNode
			if (insertQuestion) {
				var strFields = GetQuestionValuesByDisplayOrder(getValue(elementById("SurveyCode")),
							parseInt(strQuestionOrder) + 1);
				if (typeof(strFields) == "string") {
					if (strFields != "") {
						var arrItems = strFields.split("\t")
						
						// Create a new question row by cloning the previous row
						cloneRowAfter(rowItem, arrItems[0])			
						
						var nodNewRow = rowItem.parentNode.rows(rowItem.rowIndex + 1)
						
						// Update the values with those created for our new question
						setInnerHtml(findChildIdStartingWith(nodNewRow, "DQT_"), arrItems[1]);
						if (arrItems.length > 2)
							setInnerHtml(findChildIdStartingWith(nodNewRow, "DOl_"), arrItems[2]);
						if (arrItems.length > 3)
							setTitle(findChildIdStartingWith(nodNewRow, "DOl_"), arrItems[3]);
						if (arrItems.length > 4)
							setTitle(findChildIdStartingWith(nodNewRow, "DQT_"), arrItems[4]);
						if (arrItems.length > 5)
							setValue(findChildIdStartingWith(nodNewRow, "QNc_"), arrItems[5]);
						if (arrItems.length > 6)
							setValue(findChildIdStartingWith(nodNewRow, "QP_"), arrItems[6]);
						if (arrItems.length > 7)
							setValue(findChildIdStartingWith(nodNewRow, "QH_"), arrItems[7]);
						
						// Increment the display order of the new question and subsequent questions
						var i
						for (i=rowItem.rowIndex + 1; i < nodTable.rows.length; i++) {
							var nodOrder= findChildIdStartingWith(nodTable.rows(i), "QO_");
							if (nodOrder != null)
								nodOrder.value = parseInt(nodOrder.value) + 1;
						}

						// checkQuestionParents(true, "", "0");

						enableFamily(nodNewRow);
					}
					else {
						alert("New question not found");
					}
					intLastHeadingLevel = 0;
					blnLastParent = 0;
				}
				else {
					alert("New question not found");
				}
							
				enableFamily(rowItem);

			}
			// Has an existing question been edited
			else {
	
				intLastHeadingLevel = getValue(findChildIdStartingWith(rowItem, "QH_"));
				blnLastParent = getValue(findChildIdStartingWith(rowItem, "QP_"));

				var strFields = GetQuestionValuesFromServer(getValue(elementById("SurveyCode")),
								strQuestion);
				
				if (typeof(strFields) == "string") {
		
					var arrItems = strFields.split("\t");
					
					if (arrItems.length > 1)
						setInnerHtml(findChildIdStartingWith(rowItem, "DQT_"), arrItems[1]);
					if (arrItems.length > 2)
						setInnerHtml(findChildIdStartingWith(rowItem, "DOl_"), arrItems[2]);
					if (arrItems.length > 3)
						setTitle(findChildIdStartingWith(rowItem, "DOl_"), arrItems[3]);
					if (arrItems.length > 4)
						setTitle(findChildIdStartingWith(rowItem, "DQT_"), arrItems[4]);
					if (arrItems.length > 5)
						setValue(findChildIdStartingWith(rowItem, "QNc_"), arrItems[5]);
					if (arrItems.length > 6)
						setValue(findChildIdStartingWith(rowItem, "QP_"), arrItems[6]);
					if (arrItems.length > 7)
						setValue(findChildIdStartingWith(rowItem, "QH_"), arrItems[7]);
			
					// checkQuestionParents(true, "", "0");

				}
				enableFamily(rowItem);
			}
		}
		
		objWindow = null;
	}
	catch(e) {
		logErr("refreshQuestion", e)
	}
}

// Checks the parents of nested questions and updates if necessary
var i, strParentUpdate;
function unUsed_checkQuestionParents(blnStart, ParentQuestion, ParentLevel) {

	try {
	
		if (blnStart) {
			i = 0;
			strParentUpdate = "";
			strTrace = "";
		}

		while (i < nodTable.rows.length) {
	
			// Get the data for the row we are looking at
			var localRowItem = nodTable.rows(i);
			var nodQuestion = findChildIdStartingWith(localRowItem, "QNQ_");
			if (nodQuestion) {
				var strQuestionValue = getValue(nodQuestion);
				var strHeadingValue = getValue(findChildIdStartingWith(localRowItem, "QH_"));
				var strParentValue = getValue(findChildIdStartingWith(localRowItem, "QP_"));
				
				// If we have found a lower heading then return
				if (strHeadingValue > "0" && strHeadingValue <= ParentLevel)
					return;

				// If the parent is not correct then update it
				if (strParentValue != ParentQuestion)
					strParentUpdate += strQuestionValue + "," + ParentQuestion + ",";
		
				// If we have found a higher numbered heading with nest children
				if (strHeadingValue > "0" && strNestChildrenValue == "1") {
					
					// Start again from the next question
					i++;
					checkQuestionParents(false, strQuestionValue, strHeadingValue)

				}
				else
					 i++;
			}
			else
				 i++;
		}
		
		if (blnStart && strParentUpdate != '') {
		
			// Update the parents on the server
			UpdateQuestionParents(getValue(elementById("SurveyCode")), strParentUpdate);
			
			// and updated them locally.  Our array is a list of question / parent pairs
			var arrUpdates = strParentUpdate.split(",");
			for (var j = 0 ; j < arrUpdates.length - 1 ; j += 2)
				setValue(elementById("QP_" + arrUpdates[j]), arrUpdates[j+1]);
		}
	}
	catch(e) {
		logErr("checkQuestionParents", e)
	}
}

function cloneRowAfter(rowItem, newQuestion) {
	try {	

		// Find the previous row number to create the new one
		var intOldRow = getItem(rowItem)
		var intNewRow = newQuestion // intOldRow + 1
		
		// Create a new row by cloning the previous row and its children
		var nodNewRow = rowItem.cloneNode(true);
	
		// Replace its ID with the new row ID
		nodNewRow.id = nodNewRow.id.replace("_" + intOldRow, "_" + intNewRow);
	
		// Change all the IDs and names of the following children and initialise their values
		changeNodeItemInit(nodNewRow, "QI_", intOldRow, intNewRow, "1");
		changeNodeItemInit(nodNewRow, "QNQ_", intOldRow, intNewRow, intNewRow);
		changeNodeItem(nodNewRow, "QO_", intOldRow, intNewRow);
		
		// Insert our new row after the current row
		var nodNewBlankRow = rowItem.parentNode.insertRow(rowItem.rowIndex + 1);
		var nodNewFilledRow = nodNewBlankRow.replaceNode(nodNewRow);
		
		// Add the new question to the list of existing questions back on the server
		var objQstn = document.getElementById("qstU")
		if (objQstn.value == "")
			objQstn.value = newQuestion
		else
			objQstn.value += "," + newQuestion;
	
		return (nodNewFilledRow);
	}
	catch(e) {
		logErr("cloneRowAfter", e)
	}
	
}

function makeRow(rowItem) {

	try {	

		// Find the previous row number to create the new one
		var intOldRow = getItem(rowItem)
		var intNewRow = intOldRow + 1
		
		// Create a new row by cloning the previous row and its children
		var nodNewRow = rowItem.cloneNode(true);
	
		// Replace its ID with the new row ID
		nodNewRow.id = nodNewRow.id.replace("_" + intOldRow, "_" + intNewRow);
	
		// Change all the IDs and names of the following children and initialise their values
		changeNodeItemInit(nodNewRow, "QF_", intOldRow, intNewRow, "0");
		changeNodeItemInit(nodNewRow, "QT_", intOldRow, intNewRow, "");
		changeNodeItemInit(nodNewRow, "QOl_", intOldRow, intNewRow, "0");
		changeNodeItemInit(nodNewRow, "QI_", intOldRow, intNewRow, "1");
		changeNodeItem(nodNewRow, "QNQ_", intOldRow, intNewRow);
		changeNodeItem(nodNewRow, "QO_", intOldRow, intNewRow);
		changeNodeItem(nodNewRow, "QOlI_", intOldRow, intNewRow);
		changeNodeItem(nodNewRow, "QIi_", intOldRow, intNewRow);
		changeNodeItem(nodNewRow, "QIe_", intOldRow, intNewRow);
		
		resetOptionList(nodNewRow);
		
		// Append our new row to the children of the original's parent
		rowItem.parentNode.appendChild(nodNewRow);
	
		// Set maxQuestion to the new row so that only a complete new row will trigger the creation of another row
		intMaxQuestion = intNewRow;
		
		// Add the new question to the list of new questions to be created back on the server
		var objQstn = document.getElementById("qstN")
		if (objQstn.value == "")
			objQstn.value = intOldRow
		else
			objQstn.value += "," + intOldRow;
	
		// Move our new row up so it is above the buttons
		mu(nodNewRow);
		
		// Hide the tick
		var nodTickImage = findChildIdStartingWith(rowItem, "QIi_");
		nodTickImage.style.display = "NONE"	// Use the style rather than the class so that it doesn't take up screen space
		
		// Show the cross
		var nodCrossImage = findChildIdStartingWith(rowItem, "QIe_");
		nodCrossImage.className = "img"
		
		// Move the completed row up so that it is in the body of the created rows
		mu(rowItem);
		
		// Hide the tick on the new item
		nodTickImage = findChildIdStartingWith(nodNewRow, "QIi_");
		nodTickImage.className = "Hidden"
		
		// Increment the row number
		var nodOrder= findChildIdStartingWith(nodNewRow, "QO_");
		nodOrder.value = parseInt(nodOrder.value) + 1;
	}
	catch(e) {
		logErr("makeRow", e)
	}
	
}

// This function gets an updated survey question from the server
function GetQuestionValuesFromServer(SurveyCode, Question) {

	try {	

		var co = aspObject.rsGetQuestionValues(SurveyCode, Question)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("GetQuestionFromServer", e)
	}
}

// This function gets an updated survey question from the server
function GetQuestionChildrenValuesFromServer(SurveyCode, Question) {

	try {	

		var co = aspObject.rsGetQuestionChildrenValues(SurveyCode, Question)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("GetQuestionChildrenValuesFromServer", e)
	}
}

// This function gets a new question from the server based on its display order
function GetQuestionValuesByDisplayOrder(SurveyCode, DisplayOrder) {

	try {	

		var co = aspObject.rsGetQuestionValuesByDisplayOrder(SurveyCode, DisplayOrder)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("GetQuestionValuesByDisplayOrder", e)
	}
}

// This function gets a new question from the server based on its display order
function UpdateQuestionDisplayOrder(SurveyCode, Question1, DisplayOrder1, Question2, DisplayOrder2) {

	try {	

		var co = aspObject.rsUpdateQuestionDisplayOrder(SurveyCode, Question1, DisplayOrder1, Question2, DisplayOrder2)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("UpdateQuestionDisplayOrder", e)
	}
}

// This function sends a list questions and parents to the server for updating
function UpdateQuestionParents(SurveyCode, QuestionParentList) {

	try {	

		var co = aspObject.rsUpdateQuestionParents(SurveyCode, QuestionParentList)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("UpdateQuestionParents", e)
	}
}

// This function gets a new question from the server based on its display order
function UpdateQuestionInclusion(SurveyCode, Question, DisplayOrder, IncludeStatus) {

	try {	

		var co = aspObject.rsUpdateQuestionInclusion(SurveyCode, Question, DisplayOrder, IncludeStatus)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			return(co.return_value)
		}
	}
	catch(e) {
		logErr("UpdateQuestionInclusion", e)
	}
}

// Function to run when any data element changes
function cs() {
	// If we are in lite mode then there will be no left column selectors
	if (elementByIdIfExists("Select_MaintainSurvey") != null) {
		disable(elementById("Select_MaintainSurvey"));
		disable(elementById("ShowFieldDescriptions"));
		disable(elementById("Chnge"));
	}
}

function moveUpRowUntilBefore(nodRow, strType) {
	var rowItem = findRowParent(nodRow);
	var intRow = rowItem.rowIndex;

	// Keep moving the row up until it is before the rowType passed
	do {
		tblQ.rows(intRow-1).swapNode(tblQ.rows(intRow));
		intRow--;

	} while (tblQ.rows(intRow + 1).rt != strType &&
		intRow > 2);

	return intRow++;
	
}

function getItem(nodNode) {
	return parseInt(nodNode.id.substring(nodNode.id.lastIndexOf("_")+1))
}

function changeNodeItemInit(nodStart, strPrefix, strOld, strNew, strInit) {
	var nodNew = changeNodeItem(nodStart, strPrefix, strOld, strNew);
	if (nodNew != false) {
		nodNew.value = strInit;
	}
}

function changeNodeItem(nodStart, strPrefix, strOld, strNew) {
	
	try {
		// find the node that is a child of where we are starting and the prefix passed
		var nodChangeItem = findChildIdStartingWith(nodStart, strPrefix);
		
		if (nodChangeItem != false) {
			// create a new element based on the original with the _question replaced with the new question
			var re = /_\d+/g
			var strChangeItem = nodChangeItem.outerHTML.replace(re, "_" + strNew);
			
			// create the new element based on the original with the new question number
			var nodNew =  document.createElement(strChangeItem);
			
			// move any child elements of the original to the new
			while (nodChangeItem.children.length > 0)
				nodNew.appendChild(nodChangeItem.children(0));
				
			// replace the original node with the shiny new one
			nodChangeItem.replaceNode(nodNew);
			
			return nodNew;
		}
		else {
			logErr("Couldn't find [" + strPrefix + "] in " + nodStart.outerHTML);
			return false;
		}
	
	}
	catch(e) {
		logErr("changeNodeItem", e)
	}
	
}

// This function will delete any option list items after the first one and hide the first value
function resetOptionList(nodRow) {

	// Hide the first optionList input and remove any optionList items that have been created
	var nodOptionListTable = findChildIdStartingWith(nodRow, "QOlT_");
	while (nodOptionListTable.rows.length > 1)
		nodOptionListTable.deleteRow(1);
	var nodInput = findChildIdStartingWith(nodOptionListTable.rows(0), "QOlI_");
	nodInput.value = "";
	nodInput.className = "Hidden";
	
	// Rename the input node to the first sequence number
	strNewName = nodInput.id.substring(0, nodInput.id.lastIndexOf("_")) + "_1";
	renameNode(nodInput, strNewName);

}

// This function finds the parent of the element type passed
function findParent(thisItem, strElement) {
	
	var objItem = thisItem; // The current item that we are up to in the search
	var strElementLower = strElement.toLowerCase(); // The element in lower case
	
	// while the current element is not what we are looking for
	while (objItem.tagName.toLowerCase() != strElementLower)
		// move up the tree to our parent
		objItem = objItem.parentElement;
	return objItem;
}

// This function finds the row that that this item is a part of.
// Note it skips any nested tables by searching for the rt attribute with a value of "q" which is defined for question rows
function findRowParent(thisItem) {
	var objItem = thisItem
	while (objItem.tagName.toLowerCase() != "tr" ||
		objItem.rt != "q")
		objItem = objItem.parentElement;
	return objItem;
}

function findChildIdStartingWith(nodStart, strPrefix) {
	var strPrefixLower = strPrefix.toLowerCase();
	var colNodes = nodStart.childNodes;
	var i;
	for (i=0; i<colNodes.length; i++) {
		var nodNode = colNodes[i];
		try {
			if (nodNode.id.substring(0,strPrefix.length).toLowerCase() == strPrefixLower) {
				return nodNode;
			}
		}
		catch (e) {
		}

		var nodChildNode = findChildIdStartingWith(nodNode, strPrefix);
		if (nodChildNode != false) {
			return nodChildNode;
		}
	}
	return false;
}

function findChildTagStartingWith(nodStart, strPrefix) {
	var strPrefixLower = strPrefix.toLowerCase();
	var colNodes = nodStart.childNodes;
	var i;
	for (i=0; i<colNodes.length; i++) {
		var nodNode = colNodes[i];
		try {
			if (nodNode.tagName.substring(0,strPrefix.length).toLowerCase() == strPrefixLower) {
				return nodNode;
			}
		}
		catch (e) {
		}

		var nodChildNode = findChildTagStartingWith(nodNode, strPrefix);
		if (nodChildNode != false) {
			return nodChildNode;
		}
	}
	return false;
}

function renameNode(nodNode, strName) {

	var strNewNode = nodNode.outerHTML;
	var strOldName = nodNode.id;
	
	// Get the old id and replace it with the new
	strNewNode = strNewNode.replace("id=" + strOldName, "id=" + strName);
	strNewNode = strNewNode.replace("name=" + strOldName, "name=" + strName);
	var nodNewNode = document.createElement(strNewNode);
	
	// move any child elements of the original to the new
	while (nodNode.children.length > 0)
		nodNewNode.appendChild(nodNode.children(0));
		
	// replace the original node with the shiny new one
	nodNode.parentNode.replaceChild(nodNewNode, nodNode);

}
