var lngWindowTimeout = 400; // msecs
var strPlus = "_image/plus.gif";
var strMinus = "_image/minus.gif";
var strSpace = "_image/space.gif";

var addStrImg = new Array();
addStrImg[0] = "_image/service.gif";
addStrImg[1] = "_image/list.gif";
addStrImg[2] = "_image/text.gif";
addStrImg[3] = "_image/radio.gif";
addStrImg[4] = "_image/checkbox.gif";
addStrImg[5] = "_image/dualRadio.gif";
addStrImg[6] = "_image/dualCheckbox.gif";
addStrImg[7] = "_image/comment.gif";
addStrImg[8] = "_image/heading.gif";
addStrImg[9] = "_image/multilist.gif";
addStrImg[10] = "_image/textarea.gif";

function ci() {
	try {
		hide(elementById("pageBody"));
		show(elementById("pageBodyHidden"));
	}
	catch(e) {
		logErr("ci", e)
		return (false);
	}
}

var strQuestion
var strService

var strTitleS
var strTitleQ  // Stores the initial title to the question menu that has the question appended

var blnHidePopup // Used by non-popup menus to prevent the popups from displaying

var intPopOutTimer = 0;

var objOutItemS // Used to store the object to be closed
var objOutItemQ

// Popup functions

var objItemQuestion

function popUpQ(objItem) { // Called when mouse alt selected on the question row

	try {

		addTraceObj("popUpQ", objItem);

		if (intPopOutTimer != 0) 
			window.clearTimeout(intPopOutTimer);

		clearReturnEvent();
		
		objItemQuestion = objItem;

		strQuestion = objItem.Qquestion;
		var objQuestion = elementById("Q_" + strQuestion);
		
		// Get children if they are not already there
		var objQuestionImage = elementById("Qp_" + strQuestion)
		if (typeof objQuestionImage.expanded == "undefined") {
			objShowChild = objQuestionImage;
			showChildItem();
		}
		
		var objCallout = elementById("pMenuQuestion");
		
		// Add the question text to the title
		if (!strTitleQ)
			strTitleQ = elementById("CreateService").innerHTML;
		elementById("CreateService").innerHTML = objItem.innerHTML + " " + strTitleQ; 
		
		// If it is the first question in the table then hide indent
		var objQuestionTable = findParentType(objQuestion, "table");
		var objQuestionRow = findParentType(objQuestion, "tr");
		var intRowIndex = objQuestionRow.rowIndex;
		
		if (intRowIndex ==0)
			hideIfExists(elementByIdIfExists("IndentQ"))
		else
			showIfExists(elementByIdIfExists("IndentQ"));
		
		// If it doesn't have a parent then hide unindent
		if (objQuestion.QparentQuestion == "")
			hideIfExists(elementByIdIfExists("UnIndentQ"))
		else
			showIfExists(elementByIdIfExists("UnIndentQ"));
		
		// If the display is a space then it is probably safe to delete
		if (isEndOf(elementById("Qp_" + strQuestion).src, "_image/space.gif"))
			showIfExists(elementByIdIfExists("DeleteQ"))
		else
			hideIfExists(elementByIdIfExists("DeleteQ"));

		// If it is a heading or comment then hide all the services options
		if (objQuestion.QformatType == "7" ||
			objQuestion.QformatType == "8") {
			hideIfExists(elementByIdIfExists("pMenuQuestionCreate"));
			hideIfExists(elementByIdIfExists("pMenuQuestionClone"));
			hideIfExists(elementByIdIfExists("pMenuQuestionHr1"));
			hideIfExists(elementByIdIfExists("pMenuQuestionHr2"));
			hideIfExists(elementByIdIfExists("AvailableServices"));
		}
		else {

			showIfExists(elementByIdIfExists("pMenuQuestionCreate"));
			showIfExists(elementByIdIfExists("pMenuQuestionHr1"));
			showIfExists(elementByIdIfExists("pMenuQuestionHr2"));
			
			if (elementByIdIfExists("AvailableServices") != null) {
				show(elementById("AvailableServices"));
	
				var colQuestionServiceNodes = elementById("Qs_" + strQuestion).childNodes;
				var colServiceNodes = elementById("AvailableServices").childNodes;
			
				for (var i=0; i<colServiceNodes.length; i++) {
					var objServiceNode = colServiceNodes[i];
					if (objServiceNode.tagName) {
						if (objServiceNode.tagName.toLowerCase() == "div") {
						
							if (objQuestion.QformatType == "7" ||
									objQuestion.QformatType == "8") {
	
								hide(objServiceNode);
	
							}
							else {
	
								show(objServiceNode);
								for (var j=0; j<colQuestionServiceNodes.length; j++) {
									if (objServiceNode.Sservice == colQuestionServiceNodes[j].Sservice)
										hide(objServiceNode);
	
								}
							}
						}
					}
				}
			}
		}

		positionAndShowWindow(objCallout, cursorX(), objectY(objItem)+7, false);		
		popItemOvBold(objItem);
		
		return(false);
	}
	catch(e) {
		logErrAndObj("popUpQ", objItem, e)
		return (false);
	}
}

var objItemService
function popUpS(objItem) { // Called when right click on service row

	try {

		addTraceObj("popUpS", objItem);

		clearReturnEvent();
		
		objItemService = objItem;

		objOutItemS = false;
		strService = objItem.Sservice;
		strQuestion = objItem.Squestion;
		
		// Add the service text to the title
		if (!strTitleS)
			strTitleS = elementById("EditService").innerHTML;

		objBaseService = elementById("Sf_" + objItem.Sservice)

		elementById("EditService").innerHTML = objBaseService.Stitle + " " + strTitleS; 
		
		positionAndShowWindow(elementById("pMenuService"), cursorX(), objectY(objItem)+7, false);
		popItemOvBold(objItem);
		
	}
	catch(e) {
		logErrAndObj("popUpS", objItem, e)
		return (false);
	}
}

function popUpOverQ(objItem) {  // Question Menu

	try {
		addTraceObj("popUpOverQ", objItem);
		objOutItemQ = false;
	}
	catch(e) {
		logErrAndObj("popUpOverQ", objItem, e)
		return (false);
	}
}

function popUpOverS(objItem) { // Service Menu

	try {
		addTraceObj("popUpOverS", objItem);
		objOutItemS = false;
	}
	catch(e) {
		logErr("popUpOverS", e)
		return (false);
	}
}

// Pop out functions

function popOutQ(objItem) { // Question row

	try {	
		addTraceObj("popOutQ", objItem);
		popItemOu(objItem);
		objOutItemQ = objItem;
		intPopOutTimer = window.setTimeout("popOutCloseQ()", lngWindowTimeout);
	}
	catch(e) {
		logErrAndObj("popOutQ", objItem, e)
		return (false);
	}
}

function popOutS(objItem) { // Called when mouse leaves service row

	try {	
		addTraceObj("popOutS", objItem);
		popItemOu(objItem);
		objOutItemS = objItem;
		intPopOutTimer = window.setTimeout("popOutCloseS()", lngWindowTimeout);
	}
	catch(e) {
		logErrAndObj("popOutS", objItem, e)
		return (false);
	}
}

function popUpOutQ(objItem) {  // Question menu

	try {	
		addTraceObj("popUpOutQ", objItem);
		objOutItemQ = objItem;
		intPopOutTimer = window.setTimeout("popOutCloseQ()", lngWindowTimeout);
	}
	catch(e) {
		logErrAndObj("popUpOutQ", objItem, e)
		return (false);
	}
}

function popUpOutS(objItem) {  // Service menu

	try {	
		addTraceObj("popUpOutS", objItem);
		objOutItemS = objItem;
		intPopOutTimer = window.setTimeout("popOutCloseS()", lngWindowTimeout);
	}
	catch(e) {
		logErrAndObj("popUpOutS", objItem, e)
		return (false);
	}
}

// Function called after left area timer expired

function popOutCloseQ(objItem) { // Called after the user has left the menu area for the window timeout period

	try {
		addTraceObj("popOutCloseQ", objItem);
		if (objOutItemQ)  {
			if (objItemQuestion) {
				if (!objItemQuestion.dontPopout) {
					popItemOu(objItemQuestion);
				}
			}

			var objWindow = elementById("pMenuQuestion");
			if (isVisible(objWindow))
				closeWindow(objWindow);
		}

	}
	catch(e) {
		logErrAndObj("popOutCloseQ", objItem, e)
		return (false);
	}
}

function popOutCloseS() { // Called after the user has left the menu area for the window timeout period

	try {
		addTrace("popOutCloseS", "");
		if (objOutItemS) {
			if (objItemService) {
				popItemOu(objItemService);
			}

			var objWindow = elementById("pMenuService");
			if (isVisible(objWindow))
				closeWindow(objWindow);
		}
	}
	catch(e) {
		logErr("popOutCloseS", e)
		return (false);
	}
}

// Window service functions

var objLastWindow = false;
var objWindowState
var arrWindows = new Array();
var arrWindowState = new Array();

function positionAndShowWindow(objWindow, x, y, disableMouseover, stackWindows) {

	try {

		addTraceObj("positionAndShowWindow", objWindow);
		if (intPopOutTimer != 0)
			window.clearTimeout(intPopOutTimer);

		// If we are stacking windows then
		if (stackWindows) {
			if (objLastWindow != false) {
				arrWindows.push(objLastWindow);
				arrWindowState.push(objWindowState);
			}
		}
		else {
			// If we already have a window open then close it
			if (objLastWindow != false)
				closeWindow(objLastWindow);
		}
	
		locateResultWide(objWindow, x, y, 0);		
		hideAffected(objWindow, false);
		show(objWindow);
		objLastWindow = objWindow;

		if (disableMouseover)
			blnHidePopup = true;
			
		objWindowState = arrHiddenItems;
		arrHiddenItems = new Array();

	}
	catch(e) {
		logErrAndObj("positionAndShowWindow", objWindow, e)
		return (false);
	}

}

function closeWindow(objWindow) {

	try {
		addTraceObj("closeWindow", objWindow);

		if (objWindow != objLastWindow)
			logErr("closeWindow", "Window to be closed (" + objWindow.id + ") doesn't match window opened (" + objLastWindow.id + ")");

		// If we have something already highlighted then unhighlight
		if (objItemQuestion) {
			objItemQuestion.dontPopout = false;
			popItemOu(objItemQuestion);
		}
	
		if (objItemService) {
			objItemService.dontPopout = false;
			popItemOu(objItemService);
		}
	
		arrHiddenItems = objWindowState;

		hide(objWindow);
		shiftTo(objWindow, 1, 1);
		showAffected();
		objLastWindow = false;
		blnHidePopup = false;

		// If we have stacked windows then close top window
		if (arrWindows.length > 0) {
			objLastWindow = arrWindows.pop();
			objWindowState = arrWindowState.pop();
		}

	}
	catch(e) {
		logErrAndObj("closeWindow", objWindow, e)
		return (false);
	}
}

// Functions invoked from menu options

// Create a new service and add to the question

function createService() { // Called when Create and Add service pressed on menu

	try {

		addTrace("createService", "");
		closeWindow(elementById("pMenuQuestion"));

		show(elementById("pServiceAdd"));
		show(elementById("btnAdd"));
		hide(elementById("pServiceEdit"));
		hide(elementById("btnSave"));

		setValue(elementById("ServiceTitle"), "");
		setValue(elementById("ServiceDescription"), "");
		setValue(elementById("ServiceType"), "0");
		setValue(elementById("Duration"), "");
		setValue(elementById("DurationUnit"), "0");
		setValue(elementById("Cost"), "");
//		setValue(elementById("Location"), "");
		setValue(elementById("ViewFrom"), "");
		setValue(elementById("ViewTo"), "");
		setValue(elementById("WebAddress"), "");
		
		elementById("ServiceTitle").EnterButton = "Adds";
		elementById("ServiceDescription").EnterButton = "Adds";
		elementById("ServiceType").EnterButton = "AddS";
		elementById("Duration").EnterButton = "AddS";
		elementById("DurationUnit").EnterButton = "AddS";
		elementById("Cost").EnterButton = "AddS";
//		elementById("Location").EnterButton = "AddS";
		elementById("ViewFrom").EnterButton = "Adds";
		elementById("ViewTo").EnterButton = "Adds";
		elementById("WebAddress").EnterButton = "Adds";

		positionAndShowWindow(elementById("pService"), cursorX(), cursorY(), true);		
		popItemOvBold(objItemQuestion);

		elementById("ServiceTitle").focus();	

	}
	catch(e) {
		logErr("createService", e)
		return (false);
	}
}

function cloneService() { // Called when Create and Add service like last pressed on menu

	try {

		addTrace("cloneService", "");
		closeWindow(elementById("pMenuQuestion"));

		show(elementById("pServiceAdd"));
		show(elementById("btnAdd"));
		hide(elementById("pServiceEdit"));
		hide(elementById("btnSave"));

		elementById("ServiceTitle").EnterButton = "AddS";
		elementById("ServiceDescription").EnterButton = "AddS";
		elementById("ServiceType").EnterButton = "AddS";
		elementById("Duration").EnterButton = "AddS";
		elementById("DurationUnit").EnterButton = "AddS";
		elementById("Cost").EnterButton = "AddS";
//		elementById("Location").EnterButton = "AddS";
		elementById("ViewFrom").EnterButton = "AddS";
		elementById("ViewTo").EnterButton = "AddS";
		elementById("WebAddress").EnterButton = "AddS";

		positionAndShowWindow(elementById("pService"), cursorX(), cursorY(), true);		
		popItemOvBold(objItemQuestion);

		elementById("ServiceTitle").focus();	

	}
	catch(e) {
		logErr("cloneService", e)
		return (false);
	}
}

// Edits a service
function editService(objItem) {

	try {	

		addTraceObj("editService", objItem);
		if (intPopOutTimer != 0)
			window.clearTimeout(intPopOutTimer);

		blnHidePopup = true;
		
		closeWindow(elementById("pMenuService"));
		
		hide(elementById("pServiceAdd"));
		hide(elementById("btnAdd"));
		show(elementById("pServiceEdit"));
		show(elementById("btnSave"));
		
		var objService = elementById("Sf_" + strService);
		setValue(elementById("ServiceTitle"), objService.Stitle);
		setValue(elementById("ServiceDescription"), objService.Sdescription);
		setValue(elementById("ServiceType"), objService.SserviceType);
		setValue(elementById("Duration"), objService.Sduration);
		setValue(elementById("DurationUnit"), objService.SdurationUnit);
		setValue(elementById("Cost"), objService.Scost);
//		setValue(elementById("Location"), objService.Slocation);
		setValue(elementById("ViewFrom"), objService.SviewDateStart);
		setValue(elementById("ViewTo"), objService.SviewDateEnd);
		setValue(elementById("WebAddress"), objService.SwebAddress);

		elementById("ServiceTitle").EnterButton = "SaveS";
		elementById("ServiceDescription").EnterButton = "SaveS";
		elementById("ServiceType").EnterButton = "SaveS";
		elementById("Duration").EnterButton = "SaveS";
		elementById("DurationUnit").EnterButton = "SaveS";
		elementById("Cost").EnterButton = "SaveS";
//		elementById("Location").EnterButton = "SaveS";
		elementById("ViewFrom").EnterButton = "SaveS";
		elementById("ViewTo").EnterButton = "SaveS";
		elementById("WebAddress").EnterButton = "SaveS";
		
		positionAndShowWindow(elementById("pService"), cursorX(), cursorY(), true);		
		popItemOvBold(objItemService);

		elementById("ServiceTitle").focus();	

	}
	catch(e) {
		logErrAndObj("editService", objItem, e)
		return (false);
	}

}

var blnInitialQuestion
var blnCreateQuestion
function createQuestion(blnInitial) { // Called when Create a new question pressed on menu

	try {
		blnCreateQuestion = true;
		blnInitialQuestion = blnInitial;
		if (!blnInitial)
			closeWindow(elementById("pMenuQuestion"));

		show(elementById("pQuestionAdd"));
		show(elementById("btnAddQ"));
		hide(elementById("pQuestionEdit"));
		hide(elementById("btnSaveQ"));

		elementById("QuestionText").EnterButton = "AddQ";
		elementById("SurveyQuestionMaster").EnterButton = "AddQ";

		var objQuestionText = elementById("QuestionText");
		setValue(objQuestionText, "");
		clearErrorField(objQuestionText);
		
		var objSurveyQuestionMaster = elementById("SurveyQuestionMaster");
		if (objSurveyQuestionMaster.options.length > 1) {
			setValue(objSurveyQuestionMaster, "0");
			show(elementById("SurveyQuestionMaster_row"));
			clearErrorField(objSurveyQuestionMaster);
		}
		else {
			hide(elementById("SurveyQuestionMaster_row"));
		}

		hide(elementById("Page_row"));
		hide(elementById("Description_row"));
		hide(elementById("FormatType_row"));
		hide(elementById("LayoutType_row"));
		hide(elementById("OptionList_row"));
		hide(elementById("OptionList2_row"));
		hide(elementById("OptionTitle_row"));
		hide(elementById("OptionTitle2_row"));
		hide(elementById("HeadingLevel_row"));
		hide(elementById("Length_row"));
		hide(elementById("Height_row"));
		hide(elementById("ValidateRule_row"));
		hide(elementById("IndentRule_row"));
		hide(elementById("MasterTitle_row"));

		hide(elementById("Preview"));

		if (blnInitial) {
			positionAndShowWindow(elementById("pQuestion"), 230, 220, true);	
		}
		else {
			positionAndShowWindow(elementById("pQuestion"), cursorX(), cursorY(), true);	
			popItemOvBold(objItemQuestion);
		}
		
		elementById("QuestionText").focus();	

	}
	catch(e) {
		logErr("createQuestion", e)
		return (false);
	}
}

var objPage
var objQuestionText
var objDescription
var objSurveyQuestionMaster
var objFormatType
var objLayoutType
var objOptionList
var objOptionList2
var objOptionTitle
var objOptionTitle2
var objHeadingLevel
var objLength
var objHeight
var objValidateRule
var objIndentRule
var objMasterTitle

function editQuestion() { // Called when edit question pressed on menu

	try {
	
	/*	var objDownload = elementById("download")
		showPopup(objDownload, 200, 400);
		// showPopup(objDownload, cursorX(), cursorY());
		showBusy(objDownload);
		window.setTimeout("showChildItem()", 10);
		showBusy(objDownload); */

		if (typeof objQuestionText == "undefined")
			setupScreenFields();

		closeWindow(elementById("pMenuQuestion"));
		
		blnCreateQuestion = false;

		var objQuestion = elementById("Q_" + strQuestion);

		hide(elementById("pQuestionAdd"));
		hide(elementById("btnAddQ"));
		show(elementById("pQuestionEdit"));
		show(elementById("btnSaveQ"));

		objPage.EnterButton = "SaveQ";
		objQuestionText.EnterButton = "SaveQ";
		objDescription.EnterButton = "SaveQ";
		objSurveyQuestionMaster.EnterButton = "SaveQ";
		objFormatType.EnterButton = "SaveQ";
		objLayoutType.EnterButton = "SaveQ";
		objOptionList.EnterButton = "SaveQ";
		objOptionList2.EnterButton = "SaveQ";
		objOptionTitle.EnterButton = "SaveQ";
		objOptionTitle2.EnterButton = "SaveQ";
		objHeadingLevel.EnterButton = "SaveQ";
		objLength.EnterButton = "SaveQ";
		objHeight.EnterButton = "SaveQ";
		objValidateRule.EnterButton = "SaveQ";
		objIndentRule.EnterButton = "SaveQ";
		objMasterTitle.EnterButton = "SaveQ";

		setValue(objPage, objQuestion.Qpage);
		setValue(objQuestionText, objQuestion.QquestionText);
		setValue(objDescription, objQuestion.Qdescription);
		setValue(objMasterTitle, objQuestion.QmasterTitle);

//		var objSurveyQuestionMaster = objSurveyQuestionMaster;
		if (objSurveyQuestionMaster.options.length > 1) {
			if (objQuestion.QsurveyQuestionMaster == "") 
				setValue(objSurveyQuestionMaster, 0)
			else
				setValue(objSurveyQuestionMaster, objQuestion.QsurveyQuestionMaster);
			clearErrorField(objSurveyQuestionMaster);
		}
		else {
			setValue(objSurveyQuestionMaster, 0)
			hide(elementById("SurveyQuestionMaster_row"));
		}

		hide(elementById("Preview"));

		if (objQuestion.QvalidateRule == "") 
			setValue(elementById("ValidateRule"), 0)
		else
			setValue(elementById("ValidateRule"), objQuestion.QvalidateRule);

		if (objQuestion.QindentRule == "") 
			setValue(elementById("IndentRule"), 0)
		else
			setValue(elementById("IndentRule"), objQuestion.QindentRule);

		setValue(elementById("HeadingLevel"), objQuestion.Qheading);
		setValue(elementById("FormatType"), objQuestion.QformatType);
		if (objQuestion.QlayoutType != "")
			setValue(elementById("LayoutType"), objQuestion.QlayoutType)
		else
			setValue(elementById("LayoutType"), 1);
		setValue(elementById("OptionList"), objQuestion.QoptionList);
		setValue(elementById("OptionList2"), objQuestion.QoptionList2);
		setValue(elementById("OptionTitle"), objQuestion.QoptionTitle);
		setValue(elementById("OptionTitle2"), objQuestion.QoptionTitle2);
		setValue(elementById("Length"), objQuestion.Qlength);
		setValue(elementById("Height"), objQuestion.Qheight);

		// Can be left in error if previous use was cancelled
		validateAndSetFirstError(objPage);
		validateAndSetFirstError(objQuestionText);
		validateAndSetFirstError(objDescription);
		validateAndSetFirstError(objSurveyQuestionMaster);
		validateAndSetFirstError(objFormatType);
		validateAndSetFirstError(objLayoutType);
		validateAndSetFirstError(objOptionList);
		validateAndSetFirstError(objOptionList2);
		validateAndSetFirstError(objOptionTitle);
		validateAndSetFirstError(objOptionTitle2);
		validateAndSetFirstError(objHeadingLevel);
		validateAndSetFirstError(objLength);
		validateAndSetFirstError(objHeight);
		validateAndSetFirstError(objValidateRule);
		validateAndSetFirstError(objIndentRule);
		validateAndSetFirstError(objMasterTitle);

		showQuestionPropertiesRows();
		
		positionAndShowWindow(elementById("pQuestion"), cursorX(), cursorY(), true);	
		popItemOvBold(objItemQuestion);
		
		elementById("QuestionText").focus();
		
/*		hideBusy(objDownload); */

	}
	catch(e) {
		logErr("editQuestion", e)
		return (false);
	}
}

function setupScreenFields() {
	try {
		objPage = elementById("Page");
		objQuestionText = elementById("QuestionText");
		objDescription = elementById("Description");
		objSurveyQuestionMaster = elementById("SurveyQuestionMaster");
		objFormatType = elementById("FormatType");
		objLayoutType = elementById("LayoutType");
		objOptionList = elementById("OptionList");
		objOptionList2 = elementById("OptionList2");
		objOptionTitle = elementById("OptionTitle");
		objOptionTitle2 = elementById("OptionTitle2");
		objHeadingLevel = elementById("HeadingLevel");
		objLength = elementById("Length");
		objHeight = elementById("Height");
		objValidateRule = elementById("ValidateRule");
		objIndentRule = elementById("IndentRule");
		objMasterTitle = elementById("MasterTitle");
	}
	catch(e) {
		logErr("setupScreenFields", e)
		return (false);
	}
}

function deleteQuestion() {
	try {
	
		if (!isEndOf(elementById("Qp_" + strQuestion).src, "_image/space.gif"))
			alert("You need to delete all services and child questions before you can delete this question");
		else {
			if (confirm("Press OK to delete this question and any responses")) {
				var intRes = DeleteQuestionOnServer(getValue(elementById("SurveyCode")), strQuestion);
				switch (intRes) {
					case 0:
						elementById("tblQuestions").deleteRow(elementById("Qr1_" + strQuestion).rowIndex);
						elementById("tblQuestions").deleteRow(elementById("Qr_" + strQuestion).rowIndex);
						break;
					case -2:
						alert("Question could not be deleted as your session has expired.  Press refresh and log on again.");
						break;
					case -3:
						alert("Your browser session is out of sync with the server.  Press refresh and try again.");
						break;
					case -4:
						alert("You are not authorised to delete this question. Contact the survey administrator if you require access.");
						break;
					case -5:
						alert("Question could not be deleted as it has child questions. Delete child questions and redo.");
						break;
					case -6:
						alert("Question could not be deleted as it has services for other service providers assigned. Delete these services and redo.");
						break;
				} 
				
				// See if this is a master question
				var objMasterSpan = elementByIdIfExists("QM_" + strQuestion);
				if (objMasterSpan != null) {
					objMasterSpan.removeNode();
					var colOptions = elementById("SurveyQuestionMaster").options;
					for (var i=1; i < colOptions.length; i++) {
						if (colOptions[i].value == strQuestion) {
							colOptions.remove(i);
							break;
						}
					}
				}

			}
		}
		return(closeWindow(elementById("pMenuQuestion")));

	}
	catch(e) {
		logErr("deleteQuestion", e)
		return (false);
	}
}

function changeQuestionPropertiesRows() {
	try {

		showQuestionPropertiesRows();

		hideAffected(elementById("pQuestion"), true)
		
	}
	catch(e) {
		logErr("changeQuestionPropertiesRows", e)
		return (false);
	}
}


function showQuestionPropertiesRows() {
	try {

		var objQuestion = elementById("Q_" + strQuestion);

		// We only want to show the additional properties if we are editing a question
		if (!blnCreateQuestion)
			show(elementById("Description_row"));
		
		hide(elementById("FormatType_row"));
		hide(elementById("LayoutType_row"));
		hide(elementById("OptionList_row"));
		hide(elementById("OptionList2_row"));
		hide(elementById("OptionTitle_row"));
		hide(elementById("OptionTitle2_row"));
		hide(elementById("HeadingLevel_row"));
		hide(elementById("Length_row"));
		hide(elementById("Height_row"));
		hide(elementById("ValidateRule_row"));
		hide(elementById("IndentRule_row"));
		hide(elementById("MasterTitle_row"));

		if (typeof objQuestionText == "undefined")
			setupScreenFields();

//		if (typeof objSurveyQuestionMaster == "undefined")
//			objSurveyQuestionMaster = elementById("SurveyQuestionMaster");

		var strSurveyQuestionMaster = getValue(objSurveyQuestionMaster);
		var strFormatType = getValue(objFormatType);
		var strLayoutType = getValue(objLayoutType);

		if (strSurveyQuestionMaster == "0" || 
			strSurveyQuestionMaster == "") {
			
			if (objSurveyQuestionMaster.options.length > 1)
				show(elementById("SurveyQuestionMaster_row"));

			// We only want to show the additional properties if we are editing a question
			if (!blnCreateQuestion) {

				show(elementById("FormatType_row"));
	
				switch (strFormatType) {
					case "1":
					case "9":
						show(elementById("LayoutType_row"));
						show(elementById("OptionList_row"));
						show(elementById("ValidateRule_row"));
						break;
					case "3":
					case "4":
						show(elementById("LayoutType_row"));
						show(elementById("OptionList_row"));
						show(elementById("ValidateRule_row"));
						break;
					case "2":
						show(elementById("LayoutType_row"));
						show(elementById("Length_row"));
						show(elementById("ValidateRule_row"));
						break;
					case "5":
					case "6":
						show(elementById("LayoutType_row"));
						show(elementById("OptionList_row"));
						show(elementById("OptionList2_row"));
						show(elementById("OptionTitle_row"));
						show(elementById("OptionTitle2_row"));
						show(elementById("ValidateRule_row"));
						break;
					case "7":
						break;
					case "8":
						show(elementById("HeadingLevel_row"));
						break;
					case "10":
						show(elementById("LayoutType_row"));
						show(elementById("Length_row"));
						show(elementById("Height_row"));
						show(elementById("ValidateRule_row"));
						break;
				}
				show(elementById("IndentRule_row"))
				show(elementById("MasterTitle_row"));
				
			}

		}

	}
	catch(e) {
		logErr("showQuestionPropertiesRows", e)
		return (false);
	}
}

// Service Functions

function addNewService() { // Called when Add button pressed on create form

	try {

		// Check that all the fields are correct
		clearFirstError();
		var strError = validateAndSetFirstError(elementById("ServiceTitle"), false) +
			validateAndSetFirstError(elementById("ServiceDescription"), false) +
			validateAndSetFirstError(elementById("ServiceType"), false) +
			validateAndSetFirstError(elementById("Duration"), false) +
			validateAndSetFirstError(elementById("DurationUnit"), false) +
			validateAndSetFirstError(elementById("Cost"), false) +
			validateAndSetFirstError(elementById("ViewFrom"), false) +
			validateAndSetFirstError(elementById("ViewTo"), false) +
			validateAndSetFirstError(elementById("WebAddress"), false)
			
		if (strError != "") {
			alert(strError + "\nPlease correct before proceeding");
			getFirstError().focus();
			return(false);
		}
		else {
			var strTitle = getValue(elementById("ServiceTitle"));
			var strDescription = getValue(elementById("ServiceDescription"));
			var strServiceType = getValue(elementById("ServiceType"));
			var strDuration = getValue(elementById("Duration"));
			var strDurationUnit = getValue(elementById("DurationUnit"));
			var strCost = getValue(elementById("Cost"));
			// var strLocation = getValue(elementById("Location"));
			var strViewFrom = getValue(elementById("ViewFrom"));
			var strViewTo = getValue(elementById("ViewTo"));
			var strWebAddress = getValue(elementById("WebAddress"));
	
			var strNewService = AddNewServiceSurveyQuestionOnServer(getValue(elementById("SurveyCode")),
							strQuestion,
							getValue(elementById("ServiceProvider")),
							strTitle,
							strDescription,
							strServiceType,
							strDuration,
							strDurationUnit,
							strCost,
							"NULL",
							strViewFrom,
							strViewTo,
							strWebAddress);
							
			if (!strNewService) {
				var arrNewServiceItems = strNewService.split("\t");
				if (arrNewServiceItems.length != 15)
					throw ("addNewService: Number of items in strNewService: " + strNewService + " does not match the expected 15");
	
				var strNewServiceId = arrNewServiceItems[1]
			
				// Create a new service and add it to the popup menu table
				var objNewService = document.createElement("<div id='Sf_" + strNewServiceId + "' class='PopItem'>");
	
				addServiceAttributes(objNewService, arrNewServiceItems);
	
				formatServiceCell(objNewService);
	
				var objAvailableServices = elementById("AvailableServices");
				objAvailableServices.appendChild(objNewService);
				
				// Add the new service to the question in the table
				addServiceToQuestion(strQuestion, strNewServiceId);
				
				var objQuestionPlus = elementById("Qp_" + strQuestion);
				if (isEndOf(objQuestionPlus.src, strSpace))
					objQuestionPlus.src = strMinus;
		
				return(closeServiceWindow());
			}
		}

	}
	catch(e) {
		logErr("addNewService", e)
		return (false);
	}
}

// Question Functions

// Called when any of the fields on the question change that may effect the preview
function chFieldQ() {

	try {
		hide(elementById("Preview"));
		elementById("ifrPreview").src = "";
	}
	catch(e) {
		logErr("chFieldQ", e)
		return (false);
	}
}

function addNewQuestion() { // Called when Add button pressed on create form

	try {

		// Check that all the fields are correct
		clearFirstError();
		var strError = validateAndSetFirstError(elementById("QuestionText"), false) +
			validateAndSetFirstError(elementById("SurveyQuestionMaster"), false)
			
		if (strError != "") {
			alert(strError + "\nPlease correct before proceeding");
			getFirstError().focus();
			return(false);
		}
		else {
			var strQuestionText = getValue(elementById("QuestionText"));
			var strSurveyQuestionMaster = getValue(elementById("SurveyQuestionMaster"));
			var strDescription = "";

			var objQuestionTable;
			var intNewRowPosition;
			var strParentQuestion;
			
			if (blnInitialQuestion) {
				objQuestionTable = elementById("tblQuestions");
				strQuestion = "0";
				intNewRowPosition = -1;
			}
			else {
				var objPreviousQuestion = elementById("Q_" + strQuestion);
				 strParentQuestion = objPreviousQuestion.QparentQuestion
				
				objQuestionTable = findParentType(elementById("Qr_" + strQuestion), "table");
				intNewRowPosition = elementById("Qr_" + strQuestion).rowIndex+1;
			}	

			// Create a new question and add it to the question table
			var strNewQuestion = AddNewSurveyQuestionAfterQuestionOnServer(getValue(elementById("SurveyCode")),
							strQuestion,
							getValue(elementById("ServiceProviderID")),
							strParentQuestion,
							strQuestionText,
							strSurveyQuestionMaster);
			
			addQuestionRow(objQuestionTable, intNewRowPosition, strNewQuestion)
			
			return(closeQuestionWindow());
		
		}

	}
	catch(e) {
		logErr("addNewQuestion", e)
		return (false);
	}
}

function saveQuestion() { // Called when Save button pressed on edit question form

	try {
	//	var objDownload = elementById("download")
	//	var objSave = elementById("SaveQ")
	//	showPopup(objDownload, objectX(objSave), objectY(objSave));
		window.setTimeout("saveQuestionTimer()", 10);
		return (false);
	}
	catch(e) {
		logErr("saveQuestion", e)
		return (false);
	}
}

function saveQuestionTimer() { // Called when Save button pressed on edit question form

	try {
		if (saveQuestionItems()) {
	//		closePopup(elementById("download"));
			return(closeQuestionWindow());
		}
		else {
	//		closePopup(elementById("download"));
			return(false);
		}

	}
	catch(e) {
		logErr("saveQuestionTimer", e)
		return (false);
	}
}

function previewQuestion() { // Called when Preview button pressed on edit question form

	try {
		if (saveQuestionItems()) {

			elementById("ifrPreview").src = "doSurvey.asp?lite=yes&QuestionPreview=" + strQuestion;
		
			show(elementById("Preview"));
		}

		return(false);

	}
	catch(e) {
		logErr("saveQuestion", e)
		return (false);
	}
}

function saveQuestionItems() { // Saves the values to the server

	try {

		// Check that all the fields are correct
		var objQuestion = elementById("Q_" + strQuestion);
		
		clearFirstError();
		var strError = validateAndSetFirstError(elementById("QuestionText"), false) +
			validateAndSetFirstError(elementById("Page"), false) +
			validateAndSetFirstError(elementById("Description"), false) +
			validateAndSetFirstError(elementById("SurveyQuestionMaster"), false)
		
		var strSurveyQuestionMaster = getValue(elementById("SurveyQuestionMaster"));
		var strFormatType = getValue(elementById("FormatType"));
		var strLayoutType = getValue(elementById("LayoutType"));

		var strPage, strQuestionText, strDescription, strValidateRule, strIndentRule, strHeadingLevel
		var strOptionList, strOptionList2, strOptionTitle, strOptionTitle2, strLength, strHeight
		var strMasterTitle

		if (strError != "") {
			alert(strError + "\nPlease correct before proceeding");
			getFirstError().focus();
			return(false);
		}
		else {
			if (strSurveyQuestionMaster == "" || strSurveyQuestionMaster == "0") {
			
				strError += validateAndSetFirstError(elementById("FormatType"), false) +
							validateAndSetFirstError(elementById("ValidateRule"), false) +
							validateAndSetFirstError(elementById("IndentRule"), false) +
							validateAndSetFirstError(elementById("MasterTitle"), false);
	
				switch (strFormatType) {
					case "1":
					case "9":
						strError += validateAndSetFirstError(elementById("OptionList"));
						break;
					case "3":
					case "4":
						strError += validateAndSetFirstError(elementById("OptionList"));
						strError += validateAndSetFirstError(elementById("LayoutType"));
						break;
					case "2":
						strError += validateAndSetFirstError(elementById("Length"));
						break;
					case "5":
					case "6":
						strError += validateAndSetFirstError(elementById("LayoutType")) +
									validateAndSetFirstError(elementById("OptionList")) +
									validateAndSetFirstError(elementById("OptionList2")) +
									validateAndSetFirstError(elementById("OptionTitle")) +
									validateAndSetFirstError(elementById("OptionTitle2"));
						break;
					case "7":
						break;
					case "8":
						strError += validateAndSetFirstError(elementById("HeadingLevel"), false)
						break;
					case "10":
						show(elementById("Length"));
						show(elementById("Height"));
						break;
				}
	
				if (strError != "") {
					alert(strError + "\nPlease correct before proceeding");
					getFirstError().focus();
					return(false);
				}

				strPage = getValue(elementById("Page"));
				strQuestionText = getValue(elementById("QuestionText"));
				strDescription = getValue(elementById("Description"));
				
				strOptionList = getValue(elementById("OptionList"));
				strOptionList2 = getValue(elementById("OptionList2"));
				strOptionTitle = getValue(elementById("OptionTitle"));
				strOptionTitle2 = getValue(elementById("OptionTitle2"));
		
				strFormatType = getValue(elementById("FormatType"));
				strLayoutType = getValue(elementById("LayoutType"));
				
				strValidateRule = getValue(elementById("ValidateRule"));
				strIndentRule = getValue(elementById("IndentRule"));
				
				strHeadingLevel = getValue(elementById("HeadingLevel"));
				strLength = getValue(elementById("Length"));
				strHeight = getValue(elementById("Height"));
		
				strMasterTitle = getValue(elementById("MasterTitle"));

			}
			else {
				var objSurveyQuestionMaster = elementById("QM_" + strSurveyQuestionMaster);

				strPage = getValue(elementById("Page"));
				strQuestionText = getValue(elementById("QuestionText"));
				strDescription = getValue(elementById("Description"));
				
				strOptionList = objSurveyQuestionMaster.QoptionList;
				strOptionList2 = objSurveyQuestionMaster.QoptionList2;
				strOptionTitle = objSurveyQuestionMaster.QoptionTitle;
				strOptionTitle2 = objSurveyQuestionMaster.QoptionTitle2;
		
				strFormatType = objSurveyQuestionMaster.QformatType;
				strLayoutType = objSurveyQuestionMaster.QlayoutType;
				
				strValidateRule = objSurveyQuestionMaster.QvalidateRule;
				strIndentRule = objSurveyQuestionMaster.QindentRule;
		
				strHeadingLevel = objSurveyQuestionMaster.Qheading;
				strLength = objSurveyQuestionMaster.Qlength;
				strHeight = objSurveyQuestionMaster.Qheight;

				strMasterTitle = "";
			}
		}

		var objQuestion = elementById("Q_" + strQuestion);
		
		// Update the on the server and in the question table
		var strResult = UpdateQuestionOnServer(getValue(elementById("SurveyCode")),
						strQuestion,
						strPage,
						strQuestionText,
						strDescription,
						strOptionList, 
						strOptionList2, 
						strOptionTitle, 
						strOptionTitle2 , 
						objQuestion.QdisplayOrder, 
						strSurveyQuestionMaster,
						strFormatType, 
						strLayoutType, 
						objQuestion.QparentQuestion, 
						strValidateRule, 
						strIndentRule, 
						strHeadingLevel, 
						strLength, 
						strHeight, 
						objQuestion.QtextArea,
						objQuestion.Qrequired,
						objQuestion.Qmoderated,
						strMasterTitle);
						
		if (typeof strResult == "string") {
			if (strResult.substr(0,2) == "OK") {
			
				if (objQuestion.QmasterTitle != strMasterTitle) {

					var colOptions = elementById("SurveyQuestionMaster").options;

					// If there was an old master, remove it from the option list
					if (objQuestion.QmasterTitle != "") {
						for (var i=1; i < colOptions.length; i++) {
							if (colOptions[i].innerHTML == objQuestion.QmasterTitle) {
								colOptions.remove(i);
								break;
							}
						}
					}

					// If there is a new master, add it to the option list
					if (strMasterTitle != "") {
						var i
						for (i=1; i < colOptions.length; i++) {
							if (strMasterTitle < colOptions[i].innerHTML) {
								i--;
								break;
							}
						}
						var objOptNew = document.createElement("<OPTION>");
						elementById("SurveyQuestionMaster").options.add(objOptNew, i + 1);
						objOptNew.value = strQuestion;
						objOptNew.innerText = strMasterTitle;
					}
					
					// If this is a new master create it in the master div
					if (objQuestion.QmasterTitle == "") {
						var objDivMasterQuestions = elementById("divMasterQuestions");
						var objSpan = document.createElement("<span>");
						objSpan.id = "QM_" + strQuestion;
						objSpan.Qquestion = strQuestion;
						objDivMasterQuestions.appendChild(objSpan);
					}
					
					// If a master has been deleted remove it from the master div			
					if (strMasterTitle == "") {
						var objSpan = elementById("QM_" + strQuestion);
						objSpan.removeNode();
					}
				
				}
				
				objQuestion.Qpage = strPage;
				objQuestion.QquestionText = strQuestionText;
				objQuestion.Qdescription = strDescription;
				objQuestion.QoptionList = strOptionList;
				objQuestion.QoptionList2 = strOptionList2;
				objQuestion.QoptionTitle = strOptionTitle; 
				objQuestion.QoptionTitle2 = strOptionTitle2;
				objQuestion.QsurveyQuestionMaster = strSurveyQuestionMaster;
				objQuestion.QformatType = strFormatType;
				objQuestion.QlayoutType = strLayoutType;
				objQuestion.QvalidateRule = strValidateRule;
				objQuestion.QindentRule = strIndentRule;
				objQuestion.Qheading = strHeadingLevel;
				objQuestion.Qlength = strLength; 
				objQuestion.Qheight = strHeight;
				objQuestion.QmasterTitle = strMasterTitle;
				
				elementById("Qi_" + strQuestion).src = addStrImg[strFormatType];
				elementById("Qpg_" + strQuestion).innerHTML = strPage;

				objQuestion.innerHTML = strQuestionText;
				
				if (strMasterTitle != "") {
					var objMasterQuestion = elementById("QM_" + strQuestion);
					objMasterQuestion.QoptionList = strOptionList;
					objMasterQuestion.QoptionList2 = strOptionList2;
					objMasterQuestion.QoptionTitle = strOptionTitle; 
					objMasterQuestion.QoptionTitle2 = strOptionTitle2;
					objMasterQuestion.QformatType = strFormatType;
					objMasterQuestion.QlayoutType = strLayoutType;
					objMasterQuestion.QvalidateRule = strValidateRule;
					objMasterQuestion.QindentRule = strIndentRule;
					objMasterQuestion.Qheading = strHeadingLevel;
					objMasterQuestion.Qlength = strLength; 
					objMasterQuestion.Qheight = strHeight;
				}
				
				// Change any other questions that use this question as their master
				
				var objQuestionTable = elementById("tblQuestions");
				var colTdNodes = objQuestionTable.getElementsByTagName("TD");
				for (var i = 0; i < colTdNodes.length; i++) {
					var objTd = colTdNodes[i];
					if (typeof objTd.QsurveyQuestionMaster == "string") {
						if (objTd.QsurveyQuestionMaster == strQuestion) {
							// If we have cleared the master title then remove from all questions that previously had used it
							if (strMasterTitle == "")
								objTd.QsurveyQuestionMaster = ""
							else {
								objTd.QoptionList = objMasterQuestion.QoptionList;
								objTd.QoptionList2 = objMasterQuestion.QoptionList2;
								objTd.QoptionTitle = objMasterQuestion.QoptionTitle; 
								objTd.QoptionTitle2 = objMasterQuestion.QoptionTitle2;
								objTd.QformatType = objMasterQuestion.QformatType;
								objTd.QlayoutType = objMasterQuestion.QlayoutType;
								objTd.QvalidateRule = objMasterQuestion.QvalidateRule;
								objTd.QindentRule = objMasterQuestion.QindentRule;
								objTd.Qheading = objMasterQuestion.Qheading;
								objTd.Qlength = objMasterQuestion.Qlength; 
								objTd.Qheight = objMasterQuestion.Qheight;
							}
						}
					}
				}
			}
			return (true);
		}
		
	}
	catch(e) {
		logErr("saveQuestionItems", e)
		return (false);
	}
}

// Option List Functions
var intOptionList
function editOptionList(intThisOptionList) { // Called when the edit options list button is pressed on the question form

	try {
		intOptionList = intThisOptionList;
		hide(elementById("pOptionListAdd"));
		hide(elementById("btnAddO"));
		show(elementById("pOptionListEdit"));
		show(elementById("btnSaveO"));

		elementById("OptionListTitle").EnterButton = "SaveO";
		elementById("OptionListCurrent").EnterButton = "SaveO";
		if (elementByIdIfExists("OptionListGeneral") != null)
			elementById("OptionListGeneral").EnterButton = "SaveO";

		// Get the option list from the server
		var strOptionListAndValues = (intOptionList == 1) ? 
					GetOptionListFromServer(elementById("OptionList").value) :
					GetOptionListFromServer(elementById("OptionList2").value);

		if (strOptionListAndValues) {
			// Populate the fields
			var arrOptionListValues = strOptionListAndValues.split("\f");
			if (arrOptionListValues.length == 0)
				throw ("editOptionList: Number of items in strOptionListAndValues: " + strOptionListAndValues + " is 0");
	
			// Populate the Option List fields
			var arrOptionList = arrOptionListValues[1].split("\t");
			if (arrOptionList.length != 3)
				throw ("editOptionList: Number of items in arrOptionListValues[1]: " + arrOptionListValues[1] + " is not what is expected 3");
			
			setValue(elementById("OptionListTitle"), arrOptionList[0]);
			elementById("OptionListCurrent").checked = (arrOptionList[1] == "1") ? true : false;
			if (elementByIdIfExists("OptionListGeneral") != null)
				elementById("OptionListGeneral").checked = (arrOptionList[2] == "1") ? true : false;
				
			intNewOptionListOrder = 0;
			
			// Populate the OptionListValues
			var objTblOptionListValues = elementById("tblOptionListValues");
			while (objTblOptionListValues.rows.length > 3)
				objTblOptionListValues.deleteRow(3);
				
			for (var i=2; i < arrOptionListValues.length; i++) {
	
				var arrOptionListValue = arrOptionListValues[i].split("\t");
				if (arrOptionListValue.length != 5)
					throw ("Number of items in arrOptionListValues[" + i + "]: " + arrOptionListValues[i] + " is not what is expected 5");
	
				var objRow = objTblOptionListValues.insertRow();
				
				var objCellItem = objRow.insertCell();
				var objChkCurr = document.createElement("<input name='Current' type='checkbox' value='1' class='defCheckbox'>");
				objChkCurr.id = "C_" + arrOptionListValue[0];
				objChkCurr.name = "C_" + arrOptionListValue[0];
				objChkCurr.EnterButton = "SaveO";
				objCellItem.appendChild(objChkCurr);
				if (arrOptionListValue[4] == "1")
					objChkCurr.checked = true;
				objChkCurr.onkeypress = function(){ku(this)};
	
				objCellItem = objRow.insertCell();
				var objTxtOrder = document.createElement("<input name='Order' type='text' valType='Integer' size='1' style='width:2em;'>");
				objTxtOrder.id = "O_" + arrOptionListValue[0];
				objTxtOrder.value = arrOptionListValue[1];
				objTxtOrder.EnterButton = "SaveO";
				objCellItem.appendChild(objTxtOrder);
				objTxtOrder.onblur = function(){validate(this)};
				objTxtOrder.onkeypress = function(){ku(this)};
				
				if (parseInt(arrOptionListValue[1]) > intNewOptionListOrder)
					intNewOptionListOrder = parseInt(arrOptionListValue[1]);
	
				objCellItem = objRow.insertCell();
				var objTxtTitle = document.createElement("<input name='ValueDisplayed' type='text' size='1000' style='width:20em;'>");
				objTxtTitle.id = "T_" + arrOptionListValue[0];
				objTxtTitle.value = arrOptionListValue[2];
				objTxtTitle.EnterButton = "SaveO";
				objCellItem.appendChild(objTxtTitle);
				objTxtTitle.onkeypress = function(){ku(this)};
	
				objCellItem = objRow.insertCell();
				var objTxtHelp = document.createElement("<input name='HelpDisplayed' type='text' size='1000' style='width:20em;'>");
				objTxtHelp.id = "H_" + arrOptionListValue[0];
				objTxtHelp.value = arrOptionListValue[3];
				objTxtHelp.EnterButton = "SaveO";
				objCellItem.appendChild(objTxtHelp);
				objTxtHelp.onkeypress = function(){ku(this)};
	
			}
			
			intNewOptionListOrder++;
			addNewOptionListRow(false, false);
			
			// Open the Option List window
			positionAndShowWindow(elementById("pOptionList"), cursorX(), cursorY()+2, true, true);	
			
			elementById("OptionListTitle").focus();	
		}
		
		return(false);
	}
	catch(e) {
		logErr("editOptionList", e)
		return (false);
	}
}

function newOptionList(intThisOptionList) { // Called when the new options list button is pressed on the question form

	try {
		intOptionList = intThisOptionList;
		show(elementById("pOptionListAdd"));
		show(elementById("btnAddO"));
		hide(elementById("pOptionListEdit"));
		hide(elementById("btnSaveO"));

		elementById("OptionListTitle").EnterButton = "AddO";
		elementById("OptionListCurrent").EnterButton = "AddO";
		if (elementByIdIfExists("OptionListGeneral") != null)
			elementById("OptionListGeneral").EnterButton = "AddO";

		// Clear the fields
		setValue(elementById("OptionListTitle"), "");
		elementById("OptionListCurrent").checked = true;
		if (elementByIdIfExists("OptionListGeneral") != null)
			elementById("OptionListGeneral").checked = false;
			
		// Populate the OptionListValues
		var objTblOptionListValues = elementById("tblOptionListValues");
		while (objTblOptionListValues.rows.length > 3)
			objTblOptionListValues.deleteRow(3);
			
		intNewOptionListOrder = 1;
		
		addNewOptionListRow(false, false);
		
		// Open the Option List window
		positionAndShowWindow(elementById("pOptionList"), cursorX(), cursorY()+2, true, true);	
		
		elementById("OptionListTitle").focus();	
		
		return(false);
	}
	catch(e) {
		logErr("newOptionList", e)
		return (false);
	}
}

var intNewOptionListOrder
function addNewOptionListRow(setFocus, blnIncrement) {
	try {
		var objTblOptionListValues = elementById("tblOptionListValues");
		var objRow = objTblOptionListValues.insertRow();
		
		var strEnterField = elementById("OptionListTitle").EnterButton;
		
		var objCellItem = objRow.insertCell();
		var objChkCurr = document.createElement("<input name='Current' type='checkbox' value='1' class='defCheckbox'>");
		objChkCurr.id = "C_new_" + intNewOptionListOrder;
		objCellItem.appendChild(objChkCurr);
		objChkCurr.checked = true;
		objChkCurr.EnterButton = strEnterField
		objChkCurr.onkeypress = function(){ku(this)};

		objCellItem = objRow.insertCell();
		var objTxtOrder = document.createElement("<input name='Order' type='text' size='1' valType='Integer' style='width:2em;'>");
		objTxtOrder.id = "O_new_" + intNewOptionListOrder;
		objCellItem.appendChild(objTxtOrder);
		objTxtOrder.value = intNewOptionListOrder;
		objTxtOrder.onblur = function(){validate(this)};
		objTxtOrder.EnterButton = strEnterField
		objTxtOrder.onkeypress = function(){ku(this)};

		objCellItem = objRow.insertCell();
		var objTxtTitle = document.createElement("<input name='ValueDisplayed' type='text' size='1000' style='width:20em;'>");
		objTxtTitle.id = "T_new_" + intNewOptionListOrder;
		objCellItem.appendChild(objTxtTitle);
		objTxtTitle.onblur = function(){checkForNewLine()};
		objTxtTitle.EnterButton = strEnterField
		objTxtTitle.onkeypress = function(){ku(this)};
		
		objCellItem = objRow.insertCell();
		var objTxtHelp = document.createElement("<input name='HelpDisplayed' type='text' size='1000' style='width:20em;'>");
		objTxtHelp.id = "H_new_" + intNewOptionListOrder;
		objCellItem.appendChild(objTxtHelp);
		objTxtHelp.onblur = function(){checkForNewLine()};
		objTxtHelp.EnterButton = strEnterField
		objTxtHelp.onkeypress = function(){ku(this)};
		
		if (setFocus)
			try {
				objTxtTitle.focus();
			}
			catch (e) {
				// ignore as we are trying to focus on a field that has been hidden
			}
		
		intNewOptionListOrder++;

		hideAffected(elementById("pOptionList"), blnIncrement);

	}
	catch(e) {
		logErr("addNewOptionListRow", e)
		return (false);
	}
}

function addNewOptionList() {
	try {

		var strError = validateOptionListPage();
		if (strError != "") {
			alert(strError + "\nPlease correct before proceeding");
			getFirstError().focus();
			return(false);
		}

		var strResult = formatOptionList("new");
		
		var strReturned = SaveOptionListToServer(strResult);
		
		var arrReturned = strReturned.split("\t");
		if (arrReturned.length != 5)
			throw ("addNewOptionList: Number of items in " + strReturned + " is not what is expected 5");

		// Add new option list in option list selectors
		
		var colOptionList = elementById("OptionList").options;
		var i = 0;
		while (i < colOptionList.length && 
				arrReturned[3].toLowerCase() > colOptionList[i].innerHTML.toLowerCase())
			i++;
		var objOption1 = document.createElement("<option value='" + arrReturned[2] +"'>");
		colOptionList.add(objOption1, i);
		objOption1.innerHTML = arrReturned[3];
		
		var colOptionList2 = elementById("OptionList2").options;
		var objOption2 = document.createElement("<option value='" + arrReturned[2] +"'>");
		colOptionList2.add(objOption2, i);
		objOption2.innerHTML = arrReturned[3];
		
		if (intOptionList == 1)
			elementById("OptionList").value = arrReturned[2];
		if (intOptionList == 2)
			elementById("OptionList2").value = arrReturned[2];
			
		return(closeOptionListWindow());

	}
	catch(e) {
		logErr("addNewOptionList", e)
		return (false);
	}
}

function saveOptionList() {
	try {

		var strError = validateOptionListPage();
		if (strError != "") {
			alert(strError + "\nPlease correct before proceeding");
			getFirstError().focus();
			return(false);
		}

		var objOptionList = (intOptionList == 1) ? 
								elementById("OptionList") :
								elementById("OptionList2");
		
		var strResult = formatOptionList(objOptionList.value);
		
		SaveOptionListToServer(strResult);
		
		// Update option list title in option list selectors
		strOptionList = objOptionList.value;
		
		var colOptionList = elementById("OptionList").options;
		for (var i=0; i<colOptionList.length; i++) {
			if (colOptionList[i].value == strOptionList )
				colOptionList[i].innerHTML = getValue(elementById("OptionListTitle"));
		}
		var colOptionList2 = elementById("OptionList2").options;
		for (var i=0; i<colOptionList2.length; i++) {
			if (colOptionList2[i].value == strOptionList )
				colOptionList2[i].innerHTML = getValue(elementById("OptionListTitle"));
		}
		
		return(closeOptionListWindow());

	}
	catch(e) {
		logErr("saveOptionList", e)
		return (false);
	}
}

function formatOptionList(strOptionList) {
	try {

		var strResult = strOptionList + "\t" +
				getValue(elementById("OptionListTitle")) + "\t" + 
				(elementById("OptionListCurrent").checked ? "1" : "0") + "\t"
		if (elementByIdIfExists("OptionListGeneral") != null)
			strResult += (elementById("OptionListGeneral").checked ? "1" : "0") + "\f"
		else
			strResult += "0\f";
	
		var objTblOptionListValues = elementById("tblOptionListValues");
		for (i=3; i < objTblOptionListValues.rows.length; i++) {
			var colObjects = objTblOptionListValues.rows(i).getElementsByTagName("INPUT");
			var strOptionListValue = "", strDisplayOrder = "", strItemText = "", strItemHelp = "", strItemCurrent = ""
			for (j = 0; j < colObjects.length; j++) {
				var objInput = colObjects(j);
				strOptionListValue = objInput.id.substr(2);
				switch (objInput.id.substr(0,2)) {
					case "C_": 
						strItemCurrent = objInput.checked ? "1" : "0";
						break;
					case "O_": 
						strDisplayOrder = objInput.value;
						break;
					case "T_": 
						strItemText = objInput.value;
						break;
					case "H_": 
						strItemHelp = objInput.value;
						break;
					default:
						throw ("Unknown data Option List Value type " + objInput.id);
				}
			}
			if (objInput.id.substr(2,3) != "new" ||
				strItemText != "")

				strResult += strOptionListValue + "\t" +
							strDisplayOrder + "\t" +
							strItemText + "\t" +
							strItemHelp + "\t" +
							strItemCurrent + "\f";
							
		}
		return(strResult);
	}
	catch(e) {
		logErr("saveOptionList", e)
		return ("");
	}
}

function validateOptionListPage() {
	try {

		clearFirstError();
		var strError = validateAndSetFirstError(elementById("OptionListTitle"), false) +
			validateAndSetFirstError(elementById("OptionListCurrent"), false)
		if (elementByIdIfExists("OptionListGeneral") != null)
			strError += validateAndSetFirstError(elementById("OptionListGeneral"), false)
		
		var objTblOptionListValues = elementById("tblOptionListValues");
		var blnFoundOption = false;
		var objFirstOption = null;
		for (i=3; i < objTblOptionListValues.rows.length; i++) {
			var colObjects = objTblOptionListValues.rows(i).getElementsByTagName("INPUT");
			for (j = 0; j < colObjects.length; j++) {
				var objInput = colObjects(j);
				strOptionListValue = objInput.id.substr(2);
				switch (objInput.id.substr(0,2)) {
					case "C_": 
					case "O_": 
						strError += validateAndSetFirstError(objInput, false);
						break;
					case "T_":
						if (objFirstOption == null)
							objFirstOption = objInput;
						strError += validateAndSetFirstError(objInput, false);
						if (objInput.value != "")
							blnFoundOption = true;
						break;
					case "H_":
						if (objFirstOption == null)
							objFirstOption = objInput;
						strError += validateAndSetFirstError(objInput, false);
						break;
					default:
						throw ("Unknown data Option List Value type " + objInput.id);
				}
			}
		}
		if (!blnFoundOption) {
			setFirstError(objFirstOption);
			strError += "There has to be at least one answer in an answer list";
		}
		return (strError);
	}
	catch(e) {
		logErr("validateOptionListPage", e)
		return ("");
	}

}

function cancelOptionList() {
	try {

		return(closeOptionListWindow());

	}
	catch(e) {
		logErr("cancelOptionList", e)
		return (false);
	}
}

function closeOptionListWindow() {
	try {

		closeWindow(elementById("pOptionList"));
		return false;
	}
	catch(e) {
		logErr("closeOptionListWindow", e)
		return (false);
	}
}

function checkForNewLine() {
	try {
		var objTblOptionListValues = elementById("tblOptionListValues");
		var colObjects = objTblOptionListValues.rows(objTblOptionListValues.rows.length-1).getElementsByTagName("INPUT");
		var strOptionListValue = "", strDisplayOrder = "", strItemText = "", strItemHelp = "", strItemCurrent = ""
		for (j = 0; j < colObjects.length; j++) {
			var objInput = colObjects(j);
			strOptionListValue = objInput.id.substr(2);
			switch (objInput.id.substr(0,2)) {
				case "C_": 
					strItemCurrent = objInput.checked ? "1" : "0";
					break;
				case "O_": 
					strDisplayOrder = objInput.value;
					break;
				case "T_": 
					strItemText = objInput.value;
					break;
				case "H_": 
					strItemHelp = objInput.value;
					break;
				default:
					throw ("Unknown data Option List Value type " + objInput.id);
			}
		}
		if (strDisplayOrder != "" &&
			strItemText != "")
			addNewOptionListRow(true, true);
	}
	catch(e) {
		logErr("checkForNewLine", e)
		return (false);
	}
}

function saveService() { // Called when Save button pressed on create form

	try {

		var strTitle = getValue(elementById("ServiceTitle"));
		var strDescription = getValue(elementById("ServiceDescription"));
		var strServiceType = getValue(elementById("ServiceType"));
		var strDuration = getValue(elementById("Duration"));
		var strDurationUnit = getValue(elementById("DurationUnit"));
		var strCost = getValue(elementById("Cost"));
		var strLocation = "NULL";
		var strViewFrom = getValue(elementById("ViewFrom"));
		var strViewTo = getValue(elementById("ViewTo"));
		var strWebAddress = getValue(elementById("WebAddress"));

		var strNewService = SaveServiceOnServer(strService,
						strTitle,
						strDescription,
						strServiceType, 
						strDuration, 
						strDurationUnit, 
						strCost, 
						strLocation, 
						strViewFrom,
						strViewTo,
						strWebAddress)
						
		// Find the service and update it in the popup menu table
		var objService = elementById("Sf_" + strService);

		// Save the attributes for editing the service
		objService.Stitle = strTitle;
		objService.Sdescription = strDescription;
		objService.SserviceType = strServiceType;
		objService.Sduration = strDuration;
		objService.SdurationUnit = strDurationUnit;
		objService.Scost = strCost;
		objService.Slocation = strLocation;
		objService.SviewDateStart = strViewFrom;
		objService.SviewDateEnd = strViewTo;
		objService.SwebAddress = strWebAddress;

		// Save the formatting attributes
		objService.innerHTML = "Add " + strTitle;
		objService.sLabel = strTitle;
		objService.sTitle = strDescription;
		if (strViewFrom != "" || strViewTo != "") {
			objService.sTitle += "\rDisplay";
			if (strViewFrom != "")
				objService.sTitle += " from " + strViewFrom;
			if (strViewTo != "")
				objService.sTitle += " to " + strViewTo;
		}

		// Find all the questions in the question table that use this service and update their values
		updateChildServiceDetails(elementById("tblQuestions"), objService)		

		return(closeServiceWindow());

	}
	catch(e) {
		logErr("addNewService", e)
		return (false);
	}
}

function clearNewService() { // Called when Clear button pressed on create form

	try {
		setValue(elementById("ServiceTitle"), "");
		setValue(elementById("ServiceDescription"), "");
		setValue(elementById("ServiceType"), "0");
		setValue(elementById("Duration"), "");
		setValue(elementById("DurationUnit"), "0");
		setValue(elementById("Cost"), "");
		// var strLocation = "NULL";
		setValue(elementById("ViewFrom"), "");
		setValue(elementById("ViewTo"), "");
		setValue(elementById("WebAddress"), "");

		return false;
	}
	catch(e) {
		logErr("clearNewService", e)
		return (false);
	}
}

function cancelNewService() { // Called when Cancel button is pressed on create form

	try {
		return(closeServiceWindow());
	}
	catch(e) {
		logErr("cancelNewService", e)
		return (false);
	}
}

function cancelNewQuestion() { // Called when Cancel button is pressed on create form

	try {
		return(closeQuestionWindow());
	}
	catch(e) {
		logErr("cancelNewQuestion", e)
		return (false);
	}
}

function closeServiceWindow() {
	try {

		hide(elementById("btnAdd"));
		hide(elementById("btnSave"));

		// service window can  be initiated from service of question row

		if (objItemQuestion) {
			objItemQuestion.dontPopout = false;
			popItemOu(objItemQuestion);
		}
		
		if (objItemService) {
			objItemService.dontPopout = false;
			popItemOu(objItemService);
		}

		closeWindow(elementById("pService"));

		return false;
	}
	catch(e) {
		logErr("closeServiceWindow", e)
		return (false);
	}
}

function closeQuestionWindow() {
	try {

		hide(elementById("btnAddQ"));
		hide(elementById("btnSaveQ"));

		// close the question popup if it has been used
		if (typeof objItemQuestion != "undefined") {
			objItemQuestion.dontPopout = false;
			popItemOu(objItemQuestion);
		}

		closeWindow(elementById("pQuestion"));
		return false;
	}
	catch(e) {
		logErr("closeQuestionWindow", e)
		return (false);
	}
}

// Show child questions and services
var objShowChild
function showChild(objItem) {
	try {
		objShowChild = objItem;
		
		// If we haven't expanded the children then do so
		if (typeof objItem.expanded == "undefined") {
			var objDownload = elementById("download")
			showPopup(objDownload, objectX(objItem), objectY(objItem));
			// showBusy(objDownload);
			window.setTimeout("showChildItem()", 10);
		}
		// Otherwise hide or show them
		else {
			if (!isEndOf(objItem.src, strPlus)) {
				// Hide children
				hide(elementById("Qs_" + objItem.Qquestion));
				objItem.src = strPlus;
			}
			else {
				// Show children
				show(elementById("Qs_" + objItem.Qquestion));
				objItem.src = strMinus;
			}
		}
	}
	catch(e) {
		logErrAndObj("showChild", objItem, e)
		return (false);
	}
}

/* var intUpTo, objBusy, tmrBusy

function showBusy(objItem) {
	try {
		intUpTo = 0;
		objBusy = objItem;
		tmrBusy = window.setTimeout("showBusyItem()", 500);
	}
	catch(e) {
		logErrAndObj("showBusy", objItem, e)
		return (false);
	}
}

function showBusyItem() {
	try {
		intUpTo++;
		objBusy.innerHTML += " .";
		tmrBusy = window.setTimeout("showBusyItem()", 500);
	}
	catch(e) {
		logErr("showBusyItem", e)
		return (false);
	}
}

function hideBusy(objItem) {
	try {
		hide(objItem)
		window.clearTimeout(tmrBusy);
	}
	catch(e) {
		logErr("hideBusy", e)
		return (false);
	}
}
*/
var arrQuestions
var objQuestionServices
var objNewTable
var intQuestionIndex

function showChildItem() {

	try {
		var objItem =  objShowChild;
		addTraceObj("showChildItem", objItem);
		
		// Get child services and questions from the server
		var intItemsLoaded;
		var strServices = GetChildServiceIDsFromServer(objItem.Qquestion)
		if (strServices.substr(0,2) == "OK" ) { 
			// Add to the table
			var arrServices = strServices.split("\t");
			
			intItemsLoaded = arrServices.length-1;
			
			for (var i=1; i < arrServices.length; i++) {
			
				var strService = arrServices[i];
	
				// Add the new service to the question in the table
				addServiceToQuestion(objItem.Qquestion, strService);
		
			}
		}
		else {
			logErr("showChild: Bad response received from server" + strService);
		}		

		var strQuestions = GetChildQuestionsFromServer(objItem.Qquestion)
		// Add to the table
		if (strQuestions.substr(0,2) == "OK" ) { 
			// Add to the table
			arrQuestions = strQuestions.split("\f")
			
			intItemsLoaded += arrQuestions.length-1;

			if (arrQuestions.length > 1) {
			
				objNewTable = createQuestionTable(elementById("Qs_" + objItem.Qquestion), objItem.Qquestion);

				intQuestionIndex = 1;
				
				createChildQuestion();
		
			}
		}
		else {
			logErr("showChildItem: Bad response received from server" + strService);
		}
		
		objItem.expanded = true;	

		if (intItemsLoaded > 0)
			objItem.src = strMinus
		else
			objItem.src = strSpace;
			
		closePopup(elementById("download"));
		
	}
	catch(e) {
		logErr("showChildItem", e)
		return (false);
	}
}

function createChildQuestion() {

	try {

		if (intQuestionIndex < arrQuestions.length) {
			var arrQuestion = arrQuestions[intQuestionIndex].split("\t")
	
			createChildQuestionItems(arrQuestion, objNewTable, -1);
			
			if (++intQuestionIndex < arrQuestions.length)
				window.setTimeout("createChildQuestion()", 10);
		}
			
	}
	catch(e) {
		logErr("createChildQuestion", e)
		return (false);
	}
}

function createChildQuestionItems(arrQuestion, objTable, intIndex) {

	try {

		if (arrQuestion.length != 26)
			throw ("createChildQuestionItems: Number of items in " + arrQuestion.join("\t") + " does not match the expected 26");

		// Create Question Row
		var objQuestionRow = (intIndex == -1) ? objTable.insertRow() : objTable.insertRow(intIndex);
		objQuestionRow.id = "Qr1_" + arrQuestion[0];
		
		// Create plus sign cell
		var objPlusTd = objQuestionRow.insertCell();
		var objPlusImg = document.createElement("<img>");
		objPlusImg.id = "Qp_" + arrQuestion[0];
		objPlusImg.Qquestion = arrQuestion[0];
		if (arrQuestion[22] > 0 ||
			arrQuestion[23] > 0)
			objPlusImg.src = strPlus
		else
			objPlusImg.src = strSpace;
		objPlusImg.width="9";
		objPlusImg.height="9";
		objPlusImg.onclick = function(){showChild(this)};
		objPlusTd.appendChild(objPlusImg);
		
		// Create Page number
		var objPageTd = objQuestionRow.insertCell();
		objPageTd.id = "Qpg_" + arrQuestion[0];
		objPageTd.innerHTML = arrQuestion[25];

		// Create Question Icon
		var objTypeTd = objQuestionRow.insertCell();
		var objIconImg = document.createElement("<img>");
		objIconImg.id = "Qi_" + arrQuestion[0];
		objIconImg.Qquestion = arrQuestion[0];
		objIconImg.src = addStrImg[arrQuestion[11]];
		objIconImg.width="10";
		objIconImg.height="10";
		objIconImg.ondragstart = function(){dragStart(this)};
		objIconImg.ondragend = function(){dragEnd(this)};
		objTypeTd.appendChild(objIconImg);

		// Create Question cell
		var objQuestionTd =objQuestionRow.insertCell();
		objQuestionTd.id = "Q_" + arrQuestion[0];
		var j = 0;
		objQuestionTd.Qquestion = arrQuestion[j++];
		objQuestionTd.QquestionText = arrQuestion[j++];
		objQuestionTd.Qdescription = arrQuestion[j++];
		objQuestionTd.QoptionList = arrQuestion[j++];
		objQuestionTd.QoptionList2 = arrQuestion[j++];		
		objQuestionTd.QoptionListTitle = arrQuestion[j++];
		objQuestionTd.QoptionListTitle2 = arrQuestion[j++];
		objQuestionTd.QoptionTitle = arrQuestion[j++];
		objQuestionTd.QoptionTitle2 = arrQuestion[j++];
		
		objQuestionTd.QdisplayOrder = arrQuestion[j++];
		objQuestionTd.QsurveyQuestionMaster = arrQuestion[j++];
		objQuestionTd.QformatType = arrQuestion[j++];
		objQuestionTd.QlayoutType = arrQuestion[j++];
		objQuestionTd.QparentQuestion = arrQuestion[j++];
		objQuestionTd.QvalidateRule = arrQuestion[j++];
		objQuestionTd.QindentRule = arrQuestion[j++];
		objQuestionTd.Qheading = arrQuestion[j++];
		objQuestionTd.Qlength = arrQuestion[j++];
		objQuestionTd.Qheight = arrQuestion[j++];
		objQuestionTd.QtextArea = arrQuestion[j++];
		objQuestionTd.Qrequired = arrQuestion[j++];
		objQuestionTd.Qmoderated = arrQuestion[j++];
		
		objQuestionTd.QmasterTitle = arrQuestion[j++];

		objQuestionTd.QquestionServicesCount = arrQuestion[j++];
		objQuestionTd.QquestionQuestionsCount = arrQuestion[j++];

		objQuestionTd.Qpage = arrQuestion[j++];

		objQuestionTd.onmouseover = function(){popItemOv(this)};
		objQuestionTd.onmouseout = function(){popItemOu(this)};
		objQuestionTd.oncontextmenu = function(){popUpQ(this)};
		objQuestionTd.oncontextmenu = function(){popUpQ(this)};
		objQuestionTd.ondragenter = function(){dragEnter(this)};
		objQuestionTd.ondragleave = function(){dragLeave(this)};
		objQuestionTd.ondragover = function(){dragOver(this)};
		
		formatQuestionCell(objQuestionTd);
		objQuestionTd.innerHTML = objQuestionTd.QquestionText;

		// Create Services & nested questions row
		var objServicesRow = (intIndex == -1) ? objTable.insertRow() : objTable.insertRow(intIndex+1);
		objServicesRow.id = "Qr_" + arrQuestion[0];

		// Create spacers for  plus and type
		var objServicesSp = objServicesRow.insertCell();
		objServicesSp.colSpan = 2;

		// Create services and nested questions cell
		var objServicesTd = objServicesRow.insertCell();
		objServicesTd.id = "Qs_" + arrQuestion[0];
		
	}
	catch(e) {
		logErrAndObj("createChildQuestionItems", objTable, e)
		return (false);
	}
}

function createQuestionTable(objInsertCell, strQuestion) {

	try {
		// Create Question table
		objQuestionServices = elementById("Qs_" + strQuestion);
		var objNewTableO = objInsertCell.appendChild(document.createElement("<table>"));
		objNewTableO.id = "Qt_" + strQuestion;
		return (objNewTableO.appendChild(document.createElement("<tbody>")));
	}
	catch(e) {
		logErrAndObj("createQuestionTable", objInsertCell, e)
		return (false);
	}
}

function makePropertiesArray(objItem) {
	try {
		var arrQuestion = new Array()
		var j = 0;
		arrQuestion[j++] = objItem.Qquestion;
		arrQuestion[j++] = objItem.QquestionText;
		arrQuestion[j++] = objItem.Qdescription;
		arrQuestion[j++] = objItem.QoptionList;
		arrQuestion[j++] = objItem.QoptionList2;
		arrQuestion[j++] = objItem.QoptionListTitle;
		arrQuestion[j++] = objItem.QoptionListTitle2;
		arrQuestion[j++] = objItem.QoptionTitle;
		arrQuestion[j++] = objItem.QoptionTitle2;
		arrQuestion[j++] = objItem.QdisplayOrder;
		arrQuestion[j++] = objItem.QsurveyQuestionMaster;
		arrQuestion[j++] = objItem.QformatType;
		arrQuestion[j++] = objItem.QlayoutType;
		arrQuestion[j++] = objItem.QparentQuestion;
		arrQuestion[j++] = objItem.QvalidateRule;
		arrQuestion[j++] = objItem.QindentRule;
		arrQuestion[j++] = objItem.Qheading;
		arrQuestion[j++] = objItem.Qlength;
		arrQuestion[j++] = objItem.Qheight;
		arrQuestion[j++] = objItem.QtextArea;
		arrQuestion[j++] = objItem.Qrequired;
		arrQuestion[j++] = objItem.Qmoderated;
		arrQuestion[j++] = objItem.QmasterTitle;
		arrQuestion[j++] = objItem.QquestionServicesCount;
		arrQuestion[j++] = objItem.QquestionQuestionsCount;
		arrQuestion[j++] = objItem.Qpage;
		
		return(arrQuestion);
	
	}
	catch(e) {
		logErrAndObj("makePropertiesArray", objItem, e)
		return (false);
	}
}
 
// Move questions around by draging and dropping

var objDragStart, objDragEnd;
var blnDragCurrent;

function dragStart(objItem) {

	try {
		addTraceObj("dragStart", objItem);

		objDragStart = objItem

		var objDataTransfer = window.event.dataTransfer
		objDataTransfer.effectAllowed = "linkMove";
		objDataTransfer.dropEffect = "move";
		
		popItemOvBold(elementById("Q_" + objItem.Qquestion));
	}
	catch(e) {
		logErrAndObj("dragStart", objItem, e)
		return (false);
	}
}

function dragEnter(objItem) {

	try {	
		addTraceObj("dragEnter", objItem);

		objDragEnd = objItem;
		blnDragCurrent = true;

		objItem.style.borderBottomColor = "#999999";
		objItem.style.borderBottomWidth = "2px";
		objItem.style.borderBottomStyle = "solid";

	}
	catch(e) {
		logErrAndObj("dragEnter", objItem, e)
		return (false);
	}
}

function dragLeave(objItem) {

	try {	
		addTraceObj("dragLeave", objItem);
		blnDragCurrent = false;
		objItem.style.borderBottomStyle = "none";
		window.event.returnValue = false;

	}
	catch(e) {
		logErrAndObj("dragLeave", objItem, e)
		return (false);
	}
}

function dragOver(objItem) {

	try {	
	//	addTraceObj("dragOver", objItem);
		window.event.returnValue = false;
	}
	catch(e) {
		logErrAndObj("dragOver", objItem, e)
		return (false);
	}
}

function dragEnd(objItem) {

	try {

		var objStartQuestion = elementById("Q_" + objDragStart.Qquestion);
		objStartQuestion.dontPopout = false;
		popItemOu(objStartQuestion);
				
		if (typeof objDragEnd == "undefined")
			addTraceObj("dragEnd:Nothing dragged over", objItem)

		else {
		
			if (objDragStart.Qquestion != objDragEnd.Qquestion) {
	
				if (blnDragCurrent) {
					addTraceObj("dragEnd:OK", objItem);
					testAspObject();
					var co = aspObject.rsMoveQuestionDisplayOrder(getValue(elementById("SurveyCode")), objDragStart.Qquestion, objDragEnd.Qquestion);
	
					if (co.status != 0) 
						myCallBack(co)
					else {
						switch (co.return_value) {
							case -2:
								alert(strTimeout);
								return(false);
								break;
							case -3:
								alert(strSync);
								return(false);
								break;
							case -4:
								alert("You are not authorised to move questions. Contact the survey administrator if you require access.");
								return(false);
								break;
							default:
								var objEndQuestion = elementById("Q_" + objDragEnd.Qquestion);
				
								// Increment the display order of all the questions after this one by one
								incrementDisplayOrder(objStartQuestion.QdisplayOrder, 1)
								
								// Decrement all the questions after the one we are going to remove by one
								incrementDisplayOrder(objEndQuestion.QdisplayOrder, -1)
								
								// Get the question properties
								var arrQuestion = makePropertiesArray(objStartQuestion);
								
								// Delete the old question
								var objStartQuestionRow = findParentType(objStartQuestion, "tr");
								objStartQuestionTable = findParentType(objStartQuestion, "table");
								var intRowIndex = objStartQuestionRow.rowIndex;
								objStartQuestionTable.deleteRow(intRowIndex);
								objStartQuestionTable.deleteRow(intRowIndex);
								
								// Create our new question
								var objEndQuestionRow = elementById("Qr_" + objDragEnd.Qquestion)
								var objQuestionTable = findParentType(objEndQuestionRow, "table");
								createChildQuestionItems(arrQuestion, objQuestionTable, objEndQuestionRow.rowIndex+1)
								
								break;
						} 
						
					}
				}

			}
			else
				addTraceObj("dragEnd:null", objItem);

			objDragEnd.style.borderBottomStyle = "none";
			objDragEnd = null;
								
			
		}

	}
	catch(e) {
		logErrAndObj("dragEnd", objItem, e)
		return (false);
	}
}

function incrementDisplayOrder(intStartOrder, intAmount) {
	try {	

		var colItems = document.body.getElementsByTagName("TD");
		for (var i=0; i< colItems.length ; i++) {
			var objTdItem = colItems[i];
			if (typeof objTdItem.id == "string") {
				if (objTdItem.id.substring(0,1) == "Q_") {
					if (objTdItem.QdisplayOrder > intStartOrder) {
						objTdItem.QdisplayOrder += intAmount;
					}
				}
			}
		}

	}
	catch(e) {
		logErr("incrementDisplayOrder", e)
		return (false);
	}
}

// Indent and unindent function

function indentQuestion() {
	try {	
		
		// This question
		var objQuestion = elementById("Q_" + strQuestion);
		
		var objQuestionRow = findParentType(objQuestion, "tr");
		var objQuestionTable = findParentType(objQuestionRow, "table");
		var intRowIndex = objQuestionRow.rowIndex;
		
		// Get the previous question
		var objPreviousQuestion = findChildIdStartingWith(objQuestionTable.rows(intRowIndex-2), "Q_")
		
		// Get parents children if they are not already there
		var objPreviousQuestionImage = elementById("Qp_" + objPreviousQuestion.Qquestion)
		if (typeof objPreviousQuestionImage.expanded == "undefined") {
			objShowChild = objPreviousQuestionImage;
			showChildItem();
		}
		
		// Update server setting question parent the previous question
		testAspObject();
		var co = aspObject.rsUpdateQuestionParent(getValue(elementById("SurveyCode")), strQuestion, objPreviousQuestion.Qquestion);
		
		// Get the question properties
		var arrQuestion = makePropertiesArray(objQuestion);
		
		// Add this question to the children of the previous question
		objPreviousQuestionTable = elementByIdIfExists("Qt_" + objPreviousQuestion.Qquestion);
		if (objPreviousQuestionTable == null)
			objPreviousQuestionTable = createQuestionTable(elementById("Qs_" + objPreviousQuestion.Qquestion), objPreviousQuestion.Qquestion);
		createChildQuestionItems(arrQuestion, objPreviousQuestionTable, -1);
	
		// Delete the old question
		var objStartQuestionRow = findParentType(objQuestion, "tr");
		objStartQuestionTable = findParentType(objStartQuestionRow, "table");
		var intRowIndex = objStartQuestionRow.rowIndex;
		objStartQuestionTable.deleteRow(intRowIndex);
		objStartQuestionTable.deleteRow(intRowIndex);

		// Update our new parent
		var objNewQuestion = elementById("Q_" + strQuestion);
		objNewQuestion.QparentQuestion = objPreviousQuestion.Qquestion;

		elementById("Qp_" + objPreviousQuestion.Qquestion).src = strMinus;

		return(closeWindow(elementById("pMenuQuestion")));

	}
	catch(e) {
		logErr("indentQuestion", e)
		return (false);
	}
}

function unIndentQuestion() {
	try {	
		
		// This question
		var objQuestion = elementById("Q_" + strQuestion);
		
		var objQuestionRow = findParentType(objQuestion, "tr");
		var objQuestionTable = findParentType(objQuestionRow, "table");
		var intRowIndex = objQuestionRow.rowIndex;
		
		// Get the parent question
		if (objQuestion.QparentQuestion != "") {
			var objNewParentInsertTable, intPosition
			
			var objQuestionParent = elementById("Q_" + objQuestion.QparentQuestion);
			var objQuestionParentRow = findParentType(objQuestionParent, "tr");
						
			strNewParent = objQuestionParent.QparentQuestion;
			if (strNewParent != "") {
				objNewParentInsertTable = elementByIdIfExists("Qt_" + strNewParent);
				if (objNewParentInsertTable == null)
					objNewParentInsertTable = createQuestionTable(elementById("Qs_" + strNewParent), strNewParent);
			}
			else {
				strNewParent = "NULL"
				objNewParentInsertTable = elementById("tblQuestions")
				intPosition = objQuestionRow.rowIndex + 2;
			}

			intPosition = objQuestionParentRow.rowIndex + 2;
				
		}
	
		// Update server setting question parent the previous question
		testAspObject();
		var co = aspObject.rsUpdateQuestionParent(getValue(elementById("SurveyCode")), strQuestion, strNewParent);

		// Get the question properties
		var arrQuestion = makePropertiesArray(objQuestion);
	
		// Add this question to the children of the previous question
		createChildQuestionItems(arrQuestion, objNewParentInsertTable, intPosition);

		// Delete the old question
		objQuestionTable.deleteRow(intRowIndex);
		objQuestionTable.deleteRow(intRowIndex);

		// Update our new parent
		var objNewQuestion = elementById("Q_" + strQuestion);
		objNewQuestion.QparentQuestion = strNewParent;

		// If there are no child services or questions for the old parent make the plus a space
		if (!hasChildQuestions(objQuestion.QparentQuestion) &&
			!hasChildServices(objQuestion.QparentQuestion))
			elementById("Qp_" + objQuestion.QparentQuestion).src = strSpace;

		return(closeWindow(elementById("pMenuQuestion")));

	}
	catch(e) {
		logErr("unIndentQuestion", e)
		return (false);
	}
}

function hasChildServices(strQuestion) {
	try {	

		var objChildQuestions = elementById("Qs_" + strQuestion).childNodes;
		for (var i=0; i < objChildQuestions.length; i++) {
			if (objChildQuestions[i].tagName == "DIV")
				return (true);
		}
		return (false);
	}
	catch(e) {
		logErr("hasChildServices", e)
		return (false);
	}
}

function hasChildQuestions(strQuestion) {
	try {	

		var objChildQuestions = elementByIdIfExists("Qt_" + strQuestion);
		if (objChildQuestions == null)
			return (false)
		else {
			if (objChildQuestions.rows.length > 0)
				return (true)
			else
				return (false);
		}
	}
	catch(e) {
		logErr("hasChildServices", e)
		return (false);
	}
}

// Support functions

function addQuestionRow(objQuestionTable, intNewRowPosition, strNewQuestion) {

	try {	

		var arrNewQuestionItems = strNewQuestion.split("\t");
		if (arrNewQuestionItems.length != 27)
			throw ("addQuestionRow: Number of items in " + strNewQuestion + " does not match the expected 27");
		
		// Remove the OK from the first element
		var arrQuestion = arrNewQuestionItems.slice(1)
		
		createChildQuestionItems(arrQuestion, objQuestionTable, intNewRowPosition)
			
	}
	catch(e) {
		logErrAndObj("addQuestionRow", objQuestionTable, e)
		return (false);
	}

}

function updateChildServiceDetails(objItem, objService) {

	try {
		var colChildNodes = objItem.childNodes;
	
		for (var i=0; i<colChildNodes.length; i++) {

			var objChildNode = colChildNodes[i];

			if (objChildNode.Sservice) {

				if (objChildNode.Sservice == strService) {
				
					formatServiceCell(objChildNode);

				}
			}
			else // update this nodes children
				updateChildServiceDetails(objChildNode, objService) 
		}
	}
	catch(e) {
		logErrAndObj("updateChildServiceDetails", objItem, e)
		return (false);
	}
}

// This function sends the new service details to the server where it is created added to the question and the service number returned
function AddNewServiceSurveyQuestionOnServer(SurveyCode, Question, ServiceProvider, Title, Description, ServiceType, Duration, DurationUnit, Cost, Location, ViewFrom, ViewTo, WebAddress) {

	try {	

		testAspObject();
		var co = aspObject.rsAddNewServiceSurveyQuestion(SurveyCode, Question, ServiceProvider, Title, Description, ServiceType, Duration, DurationUnit, Cost, Location, ViewFrom, ViewTo, WebAddress)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			switch (co.return_value) {
				case -2:
					alert(strTimeout);
					return(false);
					break;
				case -3:
					alert(strSync);
					return(false);
					break;
				case -4:
					alert("You are not authorised to add services. Contact the survey administrator if you require access.");
					return(false);
					break;
				default:
					return(co.return_value)
					break;
			} 
			
		}
	}
	catch(e) {
		logErr("AddNewServiceSurveyQuestionOnServer", e)
		return (false);
	}
}

function AddNewSurveyQuestionAfterQuestionOnServer(SurveyCode, Question, ServiceProvider, ParentQuestion, QuestionText, SurveyQuestionMaster) {

	try {	

		testAspObject();
		var co = aspObject.rsAddNewSurveyQuestionAfterQuestionOnServer(SurveyCode, Question, ServiceProvider, ParentQuestion, QuestionText, SurveyQuestionMaster)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout);
				return "";
			}
			else {
				if (co.return_value.substr(0,2) == "OK")
					return(co.return_value)
				else
					throw("Invalid return from server " + co.return_value + " when creating Survey " + SurveyCode + " Question " + Question)
			}
		}
	}
	catch(e) {
		logErr("AddNewSurveyQuestionAfterQuestionOnServer", e);
		throw (e);
	}
}

function GetChildServiceIDsFromServer(Question) {

	try {	

		testAspObject();
		var co = aspObject.rsGetChildServiceIDsFromServer(getValue(elementById("SurveyCode")), 
						Question,
						getValue(elementById("ServiceProviderID")))
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout)
				return "";
			}
			else {
				if (co.return_value.substr(0,2) == "OK")
					return(co.return_value)
				else
					throw("Invalid return from server " + co.return_value + " when getting child services Survey " + SurveyCode + " Question " + Question);
			}
		}
	}
	catch(e) {
		logErr("GetChildServiceIDsFromServer", e);
		throw (e);
	}
}

function GetOptionListFromServer(OptionList) {

	try {	

		testAspObject();
		var co = aspObject.rsGetOptionListFromServer(getValue(elementById("SurveyCode")), OptionList)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
		
			switch (co.return_value) {
				case -2:
					alert(strTimeout);
					return(false);
					break;
				case -3:
					alert(strSync);
					return(false);
					break;
				case -4:
					alert("You are not authorised to change this answer list. You will need to create your own.");
					return(false);
					break;
				default:
					if (co.return_value.substr(0,2) == "OK")
						return(co.return_value)
					else
						throw("Invalid return from server " + co.return_value + " when saving OptionListToServer " + OptionListValues);
			} 
		}
	}
	catch(e) {
		logErr("GetOptionListFromServer", e);
		throw (e);
	}
}

function SaveOptionListToServer(OptionListValues) {

	try {	

		testAspObject();
		var co = aspObject.rsSaveOptionListToServer(getValue(elementById("SurveyCode")), OptionListValues)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			switch (co.return_value) {
				case -2:
					alert(strTimeout);
					return(false);
					break;
				case -3:
					alert(strSync);
					return(false);
					break;
				case -4:
					alert("You are not authorised to change this answer list. You will need to create your own.");
					return(false);
					break;
				default:
					if (co.return_value.substr(0,2) == "OK")
						return(co.return_value)
					else
						throw("Invalid return from server " + co.return_value + " when saving OptionListToServer " + OptionListValues);
			} 
		}
	}
	catch(e) {
		logErr("SaveOptionListToServer", e);
		throw (e);
	}
}

function GetChildQuestionsFromServer(strQuestion) {

	try {	

		var strSurveyCode = getValue(elementById("SurveyCode"))
		var strServiceProviderID = getValue(elementById("ServiceProviderID"))
		testAspObject();
		var co = aspObject.rsGetChildQuestionsFromServer(strSurveyCode, strQuestion, strServiceProviderID)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout)
				return "";
			}
			else {
				if (co.return_value.substr(0,2) == "OK")
					return(co.return_value)
				else
					throw("Invalid return from server " + co.return_value + " when getting child questions Survey " + strSurveyCode + " Question " + strQuestion)
			}
		}
	}
	catch(e) {
		logErr("GetChildQuestionsFromServer", e);
		throw (e);
	}
}

// This function sends the changed service details to the server where it is updated
function SaveServiceOnServer(Service, Title, Description, ServiceType, Duration, DurationUnit, Cost, Location, ViewFrom, ViewTo, WebAddress) {

	try {	

		testAspObject();
		var co = aspObject.rsSaveService(Service, Title, Description, ServiceType, Duration, DurationUnit, Cost, Location, ViewFrom, ViewTo, WebAddress)
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout);
				return "";
			}
			else
				return(co.return_value)
		}
	}
	catch(e) {
		logErr("SaveServiceOnServer", e)
		return (false);
	}
}

// Add existing services
function addService(objItem) {

	try {	
		// Send a message to the server to add the service
		strService = objItem.Sservice;
		var res = AddServiceSurveyQuestion(getValue(elementById("SurveyCode")),
						strQuestion,
						strService);
						
		if (res != -1) {
			// Add the new service to the question in the table
			addServiceToQuestion(strQuestion, strService);
			
			var objQuestionPlus = elementById("Qp_" + strQuestion);
			if (isEndOf(objQuestionPlus.src, strSpace))
				objQuestionPlus.src = strMinus;
		}

		return(closeWindow(elementById("pMenuQuestion")));

	}
	catch(e) {
		logErrAndObj("addService", objItem, e)
		return (false);
	}
}

function addServiceToQuestion(Question, Service) {

	try {	

		// Create a new service element and add it to the question table
		var objQuestionServices = elementById("Qs_" + Question);
		var objService = elementById("Sf_" + Service);
		var objNewService = document.createElement("<div divType='QS'>");
		objNewService.Sservice = Service;
		objNewService.Squestion = Question;
		
		formatServiceCell(objNewService);
		
		objQuestionServices.appendChild(objNewService);

	}
	catch(e) {
		logErr("addServiceToQuestion", e);
		return (false);
	}
}

// This function adds a service to a question
function AddServiceSurveyQuestion(SurveyCode, Question, Service) {

	try {	

		testAspObject();
		var co = aspObject.rsAddServiceSurveyQuestion(SurveyCode, Question, Service);
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			switch (co.return_value) {
				case -2:
					alert(strTimeout);
					return(-1);
					break;
				case -3:
					alert(strSync);
					return(-1);
					break;
				case -4:
					alert("You are not authorised to add services. Contact the survey administrator if you require access.");
					return(-1);
					break;
				default:
					return(co.return_value)
					break;
			}
		}

	}
	catch(e) {
		logErr("AddServiceSurveyQuestion", e)
		return (false);
	}
}

// Remove a service from the question
function removeService(objItem) {

	try {	
		// Send a message to the server to remove the service
		var res = removeServiceSurveyQuestion(getValue(elementById("SurveyCode")),
						strQuestion,
						strService);
						
		// Remove the service from the question in the table
		removeServiceQuestion(strQuestion, strService);
		
		// If there are no child services or questions for the question make the plus a space
		if (!hasChildQuestions(strQuestion) &&
			!hasChildServices(strQuestion))
			elementById("Qp_" + strQuestion).src = strSpace;

		closeWindow(elementById("pMenuService"));

	}
	catch(e) {
		logErrAndObj("removeService", objItem, e)
		return (false);
	}
}

function removeServiceQuestion(Question, Service) {

	try {	

		// Find the service element and remove it from the question table
		var objQuestionServiceNodes = elementById("Qs_" + Question).childNodes;
		
		for (var i=0; i<objQuestionServiceNodes.length; i++) {
			var objQuestionServiceNode = objQuestionServiceNodes[i];
			if (objQuestionServiceNode.Sservice == Service) {
				objQuestionServiceNode.removeNode(true);
			}
		}
		
	}
	catch(e) {
		logErr("removeServiceQuestion", e);
		return (false);
	}
}

// This function removes a service from a question
function removeServiceSurveyQuestion(SurveyCode, Question, Service) {

	try {
	
		testAspObject();
		var co = aspObject.rsRemoveServiceSurveyQuestion(SurveyCode, Question, Service);
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout)
				return "";
			}
			else
				return(co.return_value)
		}
	}
	catch(e) {
		logErr("RemoveServiceSurveyQuestion", e)
		return (false);
	}
}

// This function updates a question in the server
function UpdateQuestionOnServer(strSurveyCode, strQuestion, strPage, strQuestionText, strDescription, strOptionList, strOptionList2, strOptionTitle, strOptionTitle2, strDisplayOrder, strSurveyQuestionMaster, strFormatType, strLayoutType, strParentQuestion, strValidateRule, strIndentRule, strHeading, strLength, strHeight, strTextArea, strRequired, strModerated, strMasterTitle) {

	try {	

		testAspObject();
		var co = aspObject.rsUpdateQuestionOnServer(strSurveyCode, strQuestion, strPage, strQuestionText, strDescription, strOptionList, strOptionList2, strOptionTitle, strOptionTitle2, strDisplayOrder, strSurveyQuestionMaster, strFormatType, strLayoutType, strParentQuestion, strValidateRule, strIndentRule, strHeading, strLength, strHeight, strTextArea, strRequired, strModerated, strMasterTitle);
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout)
				return "";
			}
			else
				return(co.return_value)
		}
	}
	catch(e) {
		logErr("UpdateQuestionOnServer", e)
		return (false);
	}
}

// This function updates a question in the server
function DeleteQuestionOnServer(strSurveyCode, strQuestion) {

	try {	

		testAspObject();
		var co = aspObject.rsDeleteQuestionOnServer(strSurveyCode, strQuestion);
		
		if (co.status != 0) 
			myCallBack(co)
		else {
			if (co.return_value == -2) {
				alert(strTimeout)
				return "";
			}
			else
				return(co.return_value)
		}
	}
	catch(e) {
		logErr("DeleteQuestionOnServer", e)
		return (false);
	}
}



function formatAllQuestions() {
	try {	

		var objQuestionTable = elementById("tblQuestions");
		if (objQuestionTable.rows.length == 0 && getValue(elementById("SurveyCode")) != "") {
			createQuestion(true);
		}
		else {
			for (var intRowIndex=0; intRowIndex < objQuestionTable.rows.length; intRowIndex++) {
	
				var objQuestion = findChildIdStartingWith(objQuestionTable.rows(intRowIndex), "Q_");
				
				if (objQuestion)
					formatQuestionCell(objQuestion);
			}
		}
	}
	catch(e) {
		logErr("formatAllQuestions", e)
		return (false);
	}
}

function formatQuestionCell(objQuestionCell) {
	try {	

		switch (objQuestionCell.QformatType) {
			case "1":
				objQuestionCell.title = "List: " + objQuestionCell.QoptionTitle;
				break;
			case "5":
				if (objQuestionCell.QlayoutType == '1')
					objQuestionCell.title = "DualRadio(Columns): "
				else
					objQuestionCell.title = "DualRadio(Rows): ";
				objQuestionCell.title = objQuestionCell.QoptionListTitle + " / " + objQuestionCell.QoptionListTitle2 ;
				objQuestionCell.title += "\nAnswer titles: " + objQuestionCell.QoptionTitle + " / " + objQuestionCell.QoptionTitle2;
				break;
			case "8":
				objQuestionCell.title = "Heading: " + objQuestionCell.Qheading;
				break;
			default:
				objQuestionCell.title = "Unknown: " + objQuestionCell.QformatType;
				break;
		}
		if (objQuestionCell.QparentQuestion != "") {
			var objParent = elementById("Q_" + objQuestionCell.QparentQuestion);
			objQuestionCell.title += "\nChild question below: " + objParent.QquestionText;
		}
		if (objQuestionCell.Qdescription != "")
			objQuestionCell.title += "\nDescription: " + objQuestionCell.Qdescription

		objQuestionCell.title += "\r\rRight click on this line for options."

	}
	catch(e) {
		logErrAndObj("formatQuestionCell", objQuestionCell, e)
		return (false);
	}
}

// This function adds the service attributes to the service
function addServiceAttributes(objServiceCell, arrNewServiceItems) {

	try {	

		var i = 1;
		objServiceCell.Sservice = arrNewServiceItems[i++];
		objServiceCell.SserviceProvider = arrNewServiceItems[i++];
		objServiceCell.Stitle = arrNewServiceItems[i++];
		objServiceCell.Sdescription = arrNewServiceItems[i++];
		objServiceCell.SserviceType = arrNewServiceItems[i++];
		objServiceCell.Sduration = arrNewServiceItems[i++];
		objServiceCell.SdurationUnit = arrNewServiceItems[i++];
		objServiceCell.Scost = arrNewServiceItems[i++];
		objServiceCell.Slocation = arrNewServiceItems[i++];
		objServiceCell.Sthreshold = arrNewServiceItems[i++];
		objServiceCell.SviewDateStart = arrNewServiceItems[i++];
		objServiceCell.SviewDateEnd = arrNewServiceItems[i++];
		objServiceCell.SwebAddress = arrNewServiceItems[i++];
		objServiceCell.Sactive = arrNewServiceItems[i++];

	}
	catch(e) {
		logErrAndObj("addServiceAttributes", objServiceCell, e)
		return (false);
	}
}

function formatAllServices() {
	try {	

		// Format any cells that have been assigned to questions
		var nodDivs = document.body.getElementsByTagName("DIV");
		for (var intIndex=0; intIndex < nodDivs.length; intIndex++) {
			var objDiv = nodDivs(intIndex);
			if (objDiv.divType == "S" ||
					objDiv.divType == "QS")
				formatServiceCell(objDiv);
		}
	}
	catch(e) {
		logErr("formatAllServices", e)
		return (false);
	}
}

function formatServiceCell(objService) {
	try {	
	
		var objBaseService
		
		if (objService.divType == "QS") {
			objBaseService = elementById("Sf_" + objService.Sservice)
			objService.innerHTML = "<IMG src='_image/service.gif'>" + objBaseService.Stitle;
			objService.oncontextmenu = function(){popUpS(this)};
		}
		else {
			objBaseService = objService;
			objService.innerHTML = "Add " + objBaseService.Stitle;
			objService.onclick= function(){addService(this)};
		}

		// Setup the formatting attributes
		objService.Stooltip = "";
		objService.Stooltip += "Description: " + objBaseService.Sdescription;
		objService.Stooltip += "\rWeb site: " + objBaseService.SwebAddress;
		if (objBaseService.SserviceType != "0")
			objService.Stooltip += "\rService type: " + selectText(elementById("ServiceType"), objBaseService.SserviceType);
		if (objBaseService.Sduration != "")
			objService.Stooltip += "\rDuration: " + objBaseService.Sduration + " " + selectText(elementById("DurationUnit"), objBaseService.SdurationUnit);
		if (objBaseService.Scost != "")
			objService.Stooltip += "\rCost: " + objBaseService.Scost;
		if (objBaseService.SviewDateStart != "" || objBaseService.SviewDateEnd != "") {
			objService.Stooltip += "\rDisplay:";
			if (objBaseService.SviewDateStart != "")
				objService.Stooltip += " from " + objBaseService.SviewDateStart;
			if (objBaseService.SviewDateEnd != "")
				objService.Stooltip += " to " + objBaseService.SviewDateEnd;
		}
		
		// We need to add the other options here
		
		if (objService.divType == "QS")
			objService.Stooltip += "\r\rRight click on this line for options."

		if (objService.Stooltip != "")
			objService.title = objService.Stooltip;

		objService.onmouseover = function(){popItemOv(this)};
		objService.onmouseout = function(){popItemOu(this)};

	}
	catch(e) {
		logErrAndObj("formatServiceCell", objService, e)
		return (false);
	}
}

function formatQuestionCell(objItem) {
	try {	
		objItem.innerHTML = objItem.QquestionText;
	}
	catch(e) {
		logErrAndObj("formatQuestionCell", objItem, e)
		return (false);
	}
}

var blnOldHidePopout;
function showPopup(objPopup, intX, intY) {
	try {	
		addTraceObj("showPopup", objPopup);

		locateResultWide(objPopup, intX, intY, 0);		
		hideAffected(objPopup, false);
		show(objPopup);
		blnOldHidePopout = blnHidePopup;
		blnHidePopup = true;
	}
	catch(e) {
		logErrAndObj("showPopup", objPopup, e)
		return (false);
	}
}

function closePopup(objPopup) {

	try {
		addTraceObj("closePopup", objPopup);

		hide(objPopup);
		shiftTo(objPopup, 1, 1);
		showAffected();
		blnHidePopup = blnOldHidePopout;
	}
	catch(e) {
		logErrAndObj("closePopup", objPopup, e)
		return (false);
	}
}

