/*
 * mapViewControl.js 
 *
 * Author: Joel Stevick
 *
 * Copyright (c) 2007, CorData, Inc
 * Program Name: C.H.I.P. - CorData Hierarchical  Inference Program
 */

/*
 * Global variable to track what messages exist
 */
var messageMap = new Array;
var questionMap = new Object;
var lookupNodeByMessageIDQuestionID = new Object;
var messageMapNodeExists = new Object;
var gReadOnly = false;
var gAdvanced_Programming_User = null;
var gServer_Admin = null;
var gAuto_Answer_Selection_Enabled = null;

/*
 * Global variables used to display selection state of map tree nodes
 */
var gCurrent_Selected_Node = null;
var gRestore_className;
var gRestore_onmouseout;
var gSelecting_Message_From_Map_Title = null;
var gSelecting_Message_From_Map_Value = null;
var gSelecting_Message_From_Map_Radio = null;
var gMessage_Nodes_In_Questions = new Object;
var gOld_messageid = null;
var copyquestionid = null;
var pastingFromOtherApplication = false;
var pastingFromOtherApplicationsBlocked = false;

/*
 * Global variable that indicates whether to popup up the edit answer panel
 */
var editanswerid = 0;

/*
 * Global variable that stores the the node for the current "Copied" question
 */
var Copied_questionid = null;

/*
 * Global variable that stores the "copied" answerid
 */
var Copied_answerid = null;

/*
 * Get the advanced user status (part 2)
 */
function
Get_Advanced_User_Status_2(completionObject)
{
	var rights = completionObject.results.split('\t');
	gAdvanced_Programming_User = rights[0] == 'true';
	gAuto_Answer_Selection_Enabled = rights[1] == 'true';
	gServer_Admin = rights[2] == 'true';
	/*
	 * Call the caller completion routine
	 */
	var caller_completionObject = completionObject.caller_completionObject
	caller_completionObject.AjaxCompletion(caller_completionObject);
	 
}

/*
 * Get the advanced user status
 */
function
Get_Advanced_User_Status(caller_completionObject)
{
	if (gAdvanced_Programming_User != null) {
		/*
		 * Have this in cache
		 */
		caller_completionObject.AjaxCompletion(caller_completionObject);
		return;
	}
	var parameters = new Object;

	/*
	 * Store content
	 */
	var completionObject = new Object;
	completionObject.caller_completionObject = caller_completionObject;
	completionObject.AjaxCompletion = Get_Advanced_User_Status_2;
	
	Ajax_Call_Web_Method_async("IsAdvancedUser", parameters, completionObject);
}

/*
 * Load the patterns that a user can add to a message, part 2
 */
function Load_Patterns_2(completionObject)
{
	/*
	 * Get a pointer to the DIV that will hold the list of patterns
	 */
	var patternsListDIV = document.getElementById('patternslistdiv');
	patternsListDIV.innerHTML = '';
	
	/*
	 * Parse the list 
	 */
	var count = 0;
	var patternsList = completionObject.results.split('\n');
	var prev_app_title = '';
	var prev_message_title = '';
	
	/*
	 * Enumerate the list to first determine application title uniqueness
	 */
	var application_title_references = new Object();
	
	for (i in patternsList)
	{	
		/*
		 * Padding above if not first entry
		 */
		if (count > 0)
			patternsListDIV.innerHTML += "<div style=padding-top:5px;></div>";
			
		/*
		 * Parse the pattern information
		 */
		var patternInfo = patternsList[i].split('\t');
		
		/*
		 * Skip null pattern
		 */
		if (patternInfo[0] == '')
			continue;
		
		/*
		 * Increment the references for this application title
		 */
		if (application_title_references[ patternInfo[1] ] == null)
			application_title_references[ patternInfo[1] ] = 1;
		else
			application_title_references[ patternInfo[1] ] ++;
	}
	/*
	 * Enumerate the list again, now that we have determined application title uniqueness
	 */
	for (i in patternsList)
	{	
		/*
		 * Padding above if not first entry
		 */
		if (count > 0)
			patternsListDIV.innerHTML += "<div style=padding-top:5px;></div>";
			
		/*
		 * Parse the pattern information
		 */
		var patternInfo = patternsList[i].split('\t');
		
		/*
		 * Skip null pattern
		 */
		if (patternInfo[0] == '')
			continue;
			
		/*
		 * Determine how much of the path to show.  Show everything if more than one pattern for this application
		 */
		var path = patternInfo[1];

		if (application_title_references[ patternInfo[1] ] > 1) {
			path = patternInfo[1] + " | " + patternInfo[2] + " | " + patternInfo[3];
		}
		/*
		 * Add this to the list
		 */
		patternsListDIV.innerHTML += "<div>" + (count + 1) + ". <a href=javascript:void(0); style=color:blue;font-size:8pt; title=\"Click to add this pattern to the current message.\" " +
								 " onclick=\"javascript:" +
			 					 " alternateDisplayText = \'<nobr>Loading a pattern may take several minutes, please wait.</nobr>\';" +
								 "  retriesAllowed = false;" +
							     "  document.getElementById(\'popupdiv\').style.display=\'none\'; " +
								/* Paste the question */
								" Paste_Question(" + completionObject.id + ", " + patternInfo[0] + ")  " +
								 "\"" +
								 ">" + 
								 path +
								 "</a></div>";	
		
		/*
		 * Keep track of how many patterns
		 */
		 count++;
		 
		 /*
		  * Track the context
		  */
		 prev_app_title = patternInfo[1];
		 prev_message_title = patternInfo[2];
		 
	}
	
	/*
	 * If no patterns, then tell the user
	 */
	if (count == 0) {
		patternsListDIV.innerHTML = '<div style=padding-left:200px;padding-top:40px;color:blue;>No patterns available</div>';
	}
		
}
/*
 * Load the patterns that a user can add to a message
 */
function Load_Patterns(id)
{
	var parameters = new Object;

	/*
	 * Store content
	 */
	var completionObject = new Object;
	completionObject.AjaxCompletion = Load_Patterns_2;
	completionObject.id = id;
	
	Ajax_Call_Web_Method_async("GetPatterns", parameters, completionObject);
}
/*
 * Determine if a message is visible elsewhere in the map
 */
function
Message_Is_Linked(node, messageid, nestingLevel)
{
	/*
	 * Sanity check the nesting level
	 */
	if (nestingLevel > 255)
		return true;
		
	/*
	 * Enumerate the children of this node
	 */
	for (var i = 0; i < node.childrenNodes.length; i++) {
		/*
		 * Is this node a message with the matching message id?
		 */
		if (node.childrenNodes[i].displayClass == 'message' && node.childrenNodes[i].messageid == messageid) {
			/*
			 * Yes, matched!
			 */
			return true;			
		}
		
		/*
		 * Recurse downward to descendant nodes
		 */
		if ( Message_Is_Linked(node.childrenNodes[i], messageid, nestingLevel+1) )
			return true;
	}
	
	return false;
}
/*
 * Make a dropdown selection by value
 */
function Select_Option_By_Value(selection, value)
{
	for (var i = 0; i < selection.options.length; i++) {
		if (selection.options[i].value == value) {
			selection.selectedIndex=i;
			if (selection.onchange != null)
				selection.onchange();
			break;
		}
	}
}
/*
 * Reset the fields in the add answer form
 */
function Reset_Add_Answer_Form()
{
	/*
	 * Formula #1
	 */
	document.getElementById('assignvariable_1').checked=false; 
	document.getElementById('resetVariables').checked=false; 
	document.getElementById('answerSemanticsString_1').checked=true; 
	document.getElementById('answerSemanticsString_1').onclick();
	
	selection = document.getElementById('variable0selection_1');
	selection.selectedIndex=0;
	selection.onchange();

	selection = document.getElementById('variable1selection_1');
	selection.selectedIndex=0;
	selection.onchange();

	selection = document.getElementById('variable2selection_1');
	selection.selectedIndex=0;
	selection.onchange();
	document.getElementById('variable2div_1').style.display='none'; /* need to do this since onchange displays it */
	
	selection = document.getElementById('operation_1');
	selection.selectedIndex=0;
	
	document.getElementById('variable0_1').value='';
	document.getElementById('variable1_1').value='';
	document.getElementById('variable2_1').value='';
	
	document.getElementById('roundup_1').checked = false;
	
	/*
	 * Formula #2-10
	 */
	for (i = 2; i <= 10; i++) {
		if (document.getElementById('assignvariable_'+i) == null)
			break;
			
		document.getElementById('assignvariable_'+i).checked=false; 
		document.getElementById('answerSemanticsString_'+i).checked=true; 
		document.getElementById('answerSemanticsString_'+i).onclick();
		
		selection = document.getElementById('variable0selection_'+i);
		selection.selectedIndex=0;
		selection.onchange();
	
		selection = document.getElementById('variable1selection_'+i);
		selection.selectedIndex=0;
		selection.onchange();
	
		selection = document.getElementById('variable2selection_'+i);
		selection.selectedIndex=0;
		selection.onchange();
		document.getElementById('variable2div_'+i).style.display='none'; /* need to do this since onchange displays it */
		
		selection = document.getElementById('operation_'+i);
		selection.selectedIndex=0;
		
		document.getElementById('variable0_'+i).value='';
		document.getElementById('variable1_'+i).value='';
		document.getElementById('variable2_'+i).value='';
		
		document.getElementById('roundup_'+i).checked = false;
		
		document.getElementById('additionalformuladiv_'+i).style.display='none'; 
	}
}
/*
 * Reset the formula-specific fields in the add answer form
 */
function Reset_Add_Answer_Form2(i)
{
	/*
	 * Formula #1
	 */
	document.getElementById('assignvariable_'+i).checked=false; 
	document.getElementById('answerSemanticsString_'+i).checked=true; 
	document.getElementById('answerSemanticsString_'+i).onclick();
	
	selection = document.getElementById('variable0selection_'+i);
	selection.selectedIndex=0;
	selection.onchange();

	selection = document.getElementById('variable1selection_'+i);
	selection.selectedIndex=0;
	selection.onchange();

	selection = document.getElementById('variable2selection_'+i);
	selection.selectedIndex=0;
	selection.onchange();
	document.getElementById('variable2div_'+i).style.display='none'; /* need to do this since onchange displays it */
	
	selection = document.getElementById('operation_'+i);
	selection.selectedIndex=0;
	
	document.getElementById('variable0_'+i).value='';
	document.getElementById('variable1_'+i).value='';
	document.getElementById('variable2_'+i).value='';
	
	document.getElementById('roundup_'+i).checked = false;
	
	if (document.getElementById('additionalformuladiv_'+(i+1)))
		document.getElementById('additionalformuladiv_'+(i+1)).style.display='none'; 
	/* 
	 * Change label from Retain --> Add
	 */
	document.getElementById('addformulalabel_'+i).innerHTML='Add variable assignment/formula ';
}
/*
 * Move an answer up in the list
 */
function Move_Answer_Up(answerid, questionid)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['answerid'] = answerid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Move_Answer_completion;
	completionObject.questionid=questionid;
	
	Ajax_Call_Web_Method_async("MoveAnswerUp", parameters, completionObject);

}

/*
 * Remove unlinked messages (part 2)
 */
function Remove_Unlinked_Messages_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	
    Populate_Message_Pick_List(questionid, 'answermessagepicklistselect'); 
}

/*
 * Remove unlinked messages
 */
function Remove_Unlinked_Messages(questionid)
{
	/*
	 * Call the server to get the list of messages for the application that is related to this question
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;
	
	var completionObject = new Object;
	completionObject.AjaxCompletion = Remove_Unlinked_Messages_2;
	completionObject.questionid=questionid;
	
	Ajax_Call_Web_Method_async('DeleteUnlinkedMessagesByQuestion', parameters, completionObject);

}

/*
 * Populate the message pick list dropdown control
 */
function Populate_Message_Pick_List(questionid, selectionID)
{
	/*
	 * Display a "Please wait..." message
	 */
	document.getElementById('answermessagepicklistselectdiv').style.display='none';
	document.getElementById('answermessagepicklistselectwaitdiv').style.display='block';

	/*
	 * Call the ajax routine after the windows display driver has had a chance to run
	 */
	setTimeout('Populate_Message_Pick_List2(\'' + questionid + '\', \'' + selectionID + '\')', 100);
	
}

/*
 * Version of message pick list routine that is called from the context of a timeout to give the
 * windows display driver a chance to run (part 2)
 */
function Populate_Message_Pick_List2_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var selectionID = completionObject.selectionID;

	/*
	 * Close the "Please wait..." message
	 */
	document.getElementById('answermessagepicklistselectdiv').style.display='block';
	document.getElementById('answermessagepicklistselectwaitdiv').style.display='none';
	
	/*
	 * Enable the control
	 */
	var selection = document.getElementById(selectionID);
	selection.disabled = false;
	selection.selectedIndex = 0;
	selection.length=1;
	
	/*
	 * Parse the string into an array (messageid, messagetitle, linked)
	 */
	var messageList = completionObject.results.split('\n');
	var unlinked = 0;
	var applications = 0;
	for (i in messageList)
	{	
		/*
		 * Add this to the list
		 */
		var messageInfo = messageList[i].split('\t');
		if (messageInfo.length == 4) {
			/*
			 * If this is an application, and it is the first one, then output
			 * a seperator in the options list
			 */
			if (applications == 0 && messageInfo[3] == 1) {
				var index = selection.length;
				selection.options[selection.length] = new Option("Or select application below:", 0, false, false);
				selection.options[index].style.backgroundColor='#333333';			
				selection.options[index].style.color='#f0f0f0';			
				
				applications++;
			}
			var index = selection.length;
			selection.options[selection.length] = new Option(messageInfo[1], messageInfo[0], false, false);
			
			/*
			 * If not linked, then make it gray
			 */
			if (messageInfo[2] == 0) {
				/*
				 * Not linked
				 */
				selection.options[index].style.color='#666666';			
				
				unlinked++;
			} else if (messageInfo[3] == 1) {
				/*
				 * This is a link to an application
				 */
				selection.options[index].style.backgroundColor='#e0e0e0';			
				selection.options[index].style.color='black';			
			}
			
		}
	}
	/*
	 * If there is an unlinked message, then add a pseudo entry for removing unlinked messages
	 */
	if (unlinked > 0) {
		var index = selection.length;
		selection.options[selection.length] = new Option('Remove unlinked messages', 'removeunlinkedmessages', false, false);
		selection.options[index].style.color='red';			
	}
}

/*
 * Version of message pick list routine that is called from the context of a timeout to give the
 * windows display driver a chance to run
 */
function Populate_Message_Pick_List2(questionid, selectionID)
{
	/*
	 * Call the server to get the list of messages for the application that is related to this question
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;
	
	var completionObject = new Object;
	completionObject.AjaxCompletion = Populate_Message_Pick_List2_2;
	completionObject.questionid=questionid;
	completionObject.selectionID=selectionID;
	Ajax_Call_Web_Method_async('EnumerateMessagesByQuestion', parameters, completionObject);

}
/*
 * Determine whether a question is multiple choice (part 2)
 */
function Question_Is_Multiple_Choice_2(completionObject)
{
	/* 
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var caller_completionObject = completionObject.caller_completionObject;
	
	/*
	 * Store the return value into the context
	 */
	caller_completionObject.isMultipleChoice = completionObject.results > 0;
	
	/*
	 * Complete to the caller
	 */
	caller_completionObject.AjaxCompletion(caller_completionObject);	 
}
/*
 * Determine whether a question is multiple choice
 */
function Question_Is_Multiple_Choice(questionid, caller_completionObject)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Question_Is_Multiple_Choice_2;
	completionObject.questionid=questionid;
	completionObject.caller_completionObject=caller_completionObject;
	
	Ajax_Call_Web_Method_async("QuestionIsMultipleChoice", parameters, completionObject);
	
}
/*
 * Move an answer (completion)
 */
function Move_Answer_completion(completionObject)
{
	/*
	 * Populate the answers list
	 */
	Populate_Answers_List(completionObject.questionid, document.getElementById('answerslistdiv'));	 
}

/*
 * Move an answer down in the list
 */
function Move_Answer_Down(answerid, questionid)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['answerid'] = answerid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Move_Answer_completion;
	completionObject.questionid=questionid;
	
	Ajax_Call_Web_Method_async("MoveAnswerDown", parameters, completionObject);
	
}

/*
 * Move a question up, part 3
 */
function Move_Question_Up_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var messageid = completionObject.messageid;
	var questionid = completionObject.questionid;
	
	/*
	 * Move this question up
	 */
	var node = lookupNodeByMessageIDQuestionID[messageid + '.' + questionid];
	
	displayOrder = 10;
	for (var i = 0; i < node.childrenNodes.length; i++) {
		node.childrenNodes[i].displayOrder=displayOrder*2;
		if (node.childrenNodes[i].questionid == questionid)
			node.childrenNodes[i].displayOrder -= 3;
		displayOrder++;
	}
	
	/*
	 * Re-render the tree
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	mapView.wasOpen = true;
	gNode_ID=0;
	mapView.Render(document.getElementById('mapViewContainer'));
}

/*
 * Move a question up, part 2
 */
function Move_Question_Up_2(completionObject)
{
	/*
	 * Populate the questions list
	 */
	completionObject.AjaxCompletion = Move_Question_Up_3;
	Populate_Questions_List(completionObject.messageid, document.getElementById('questionslistdiv'), completionObject); 
	
}

/*
 * Move an question up in the list
 */
function Move_Question_Up(questionid, messageid)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Move_Question_Up_2;
	completionObject.questionid=questionid;
	completionObject.messageid=messageid;

	Ajax_Call_Web_Method_async("MoveQuestionUp", parameters, completionObject);

}

/*
 * Move a question down in the list, part 3
 */
function Move_Question_Down_3(completionObject)
{
	/*
	 * Recover the parameters
	 */
	var messageid  = completionObject.messageid;
	var questionid = completionObject.questionid;
	
	/*
	 * Move this question down
	 */
	var node = lookupNodeByMessageIDQuestionID[messageid + '.' + questionid];
	displayOrder = 10;
	for (var i = 0; i < node.childrenNodes.length; i++) {
		node.childrenNodes[i].displayOrder=displayOrder*2;
		if (node.childrenNodes[i].questionid == questionid) {
			node.childrenNodes[i].displayOrder += 3;
		}
		displayOrder++;
	}
	
	/*
	 * Re-render the tree
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	mapView.wasOpen = true;
	gNode_ID=0;
	mapView.Render(document.getElementById('mapViewContainer'));
}
/*
 * Move a question down in the list, part 2
 */
function Move_Question_Down_2(completionObject)
{
	/*
	 * Populate the questions list
	 */
	completionObject.AjaxCompletion = Move_Question_Down_3;
	
	Populate_Questions_List(completionObject.messageid, document.getElementById('questionslistdiv'), completionObject)	 

}
/*
 * Move a question down in the list
 */
function Move_Question_Down(questionid, messageid)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Move_Question_Down_2;
	completionObject.questionid=questionid;
	completionObject.messageid=messageid;

	Ajax_Call_Web_Method_async("MoveQuestionDown", parameters, completionObject);
	
}
/*
 * Toggle question pattern semantics, part 2
 */
function Toggle_Question_Pattern_Semantics_2(completionObject)
{
	/*
	 * Toggle the bold attribute for the link
	 */
	 if (completionObject.link.style.fontWeight == 'normal') {
		 completionObject.link.style.fontWeight='bold';
		 completionObject.link.title="This question is a pattern";
	 } else {
		 completionObject.link.style.fontWeight='normal';
		 completionObject.link.title="Click to make this question a pattern";
	 }
}
/*
 * Toggle question pattern semantics
 */
function Toggle_Question_Pattern_Semantics(questionid, messageid, link)
{
	/*
	 * Do the work on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Toggle_Question_Pattern_Semantics_2;
	completionObject.questionid=questionid;
	completionObject.messageid=messageid;
	completionObject.link=link;

	Ajax_Call_Web_Method_async("ToggleQuestionPatternSemantics", parameters, completionObject);
	
}

/*
 * Edit answer (part 3)
 */
function Edit_Answer_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var answerid = completionObject.answerid;
	var questionid = completionObject.questionid;
	var infoResults = completionObject.results;
	var info = infoResults.split("\t");

	var answertitle = info[0];
	var messageid = info[1];
	var messagetitle = info[9];
	var emailid = info[10]; // emailid for sending to user
	var emailid2 = info[11]; // emailid for sending to author
	
	/* 
	 * Formulas 
	 */
	var variable0_array = info[2].split("\n");
	var variable1_array = info[3].split("\n");
	var variable2_array = info[4].split("\n");
	var value1_array = info[5].split("\n");
	var value2_array = info[6].split("\n");
	var operation_array = info[7].split("\n");
	var semantics_array = info[8].split("\n");
	var roundup_array = info[13].split("\n");
	var resetVariables = info[14];
	
	/*
	 * Remember the old message id in a global variable so we can detect if it changed
	 */
	gOld_messageid = messageid;
	
	for (i = 1; i <= 10; i++) {
		/*
		 * Formula-specific properties
		 */
		var variable0 = variable0_array[i-1];
		var variable1 = variable1_array[i-1];
		var variable2 = variable2_array[i-1];
		var value1 = value1_array[i-1];
		var value2 = value2_array[i-1];
		var operation = operation_array[i-1];
		var semantics = semantics_array[i-1];
		var roundup = roundup_array[i-1];
		
		/*
		 * Check for end of list
		 */
		if (document.getElementById('variable0selection_'+i) == null)
			break;
			
		/*
		 * FORMULA #n: Populate the dropdown control that contains the variables for the current application
		 */
		var selectionControls = new Object;
		selectionControls[0] = document.getElementById('variable0selection_'+i);
		selectionControls[1] = document.getElementById('variable1selection_'+i);
		selectionControls[2] = document.getElementById('variable2selection_'+i);
		
		Populate_Variables_Dropdown(questionid, selectionControls, completionObject.variableList);
		if (parseInt(variable0) > 0 || parseInt(variable0) < -1) {
			/*
			 * Has a formula
			 */
			document.getElementById('assignvariable_'+i).checked=true; 
			
			/* 
			 * Change label from Add --> Retain
			 */
			document.getElementById('addformulalabel_'+i).innerHTML='Retain this variable assignment/formula ';
			
			/*
			 * Type (semantics) string | numeric
			 */
			if (semantics == 'string') {
				document.getElementById('answerSemanticsString_'+i).checked=true; 
				document.getElementById('answerSemanticsString_'+i).onclick();
			} else {
				document.getElementById('answerSemanticsNumeric_'+i).checked=true; 
				document.getElementById('answerSemanticsNumeric_'+i).onclick();
			}
				
			/*
			 * Variable0
			 */
			var selection = document.getElementById('variable0selection_'+i);
			Select_Option_By_Value(selection, variable0);
			document.getElementById('variable0_'+i).value = '';
			
			/*
			 * Variable1 or value1
			 */
			selection = document.getElementById('variable1selection_'+i);
			if (variable1 != 0) {
				Select_Option_By_Value(selection, variable1);
				
			} else {
				if (value1 != '') 
					document.getElementById('variable1_'+i).value = value1;
				
				if (selection.onchange != null)
					selection.onchange();
			}
			
			/*
			 * Variable2 or value2
			 */
			selection = document.getElementById('variable2selection_'+i);
			if (variable2 != 0) {
				Select_Option_By_Value(selection, variable2);
				
			} else {
				if (value2 != '') 
					document.getElementById('variable2_'+i).value = value2;
				
				if (selection.onchange != null) {
					selection.onchange();
					if (value2 == '') 
						document.getElementById('variable2div_'+i).style.display='none'; /* need to do this since onchange displays it */
				}
			}
			
			/*
			 * Operation
			 */
			selection = document.getElementById('operation_'+i);
			Select_Option_By_Value(selection, operation);
			
			/* 
			 * Round up
			 */
			document.getElementById('roundup_'+i).checked = roundup == 1;
				
		} else {
			/*
			 * No formula
			 */
			Reset_Add_Answer_Form2(i);
		}
		/*
		 * Execute the onclick handler for the Assign Variable DIV
		 */
		document.getElementById('assignvariable_'+i).onclick();
	} /* End formula-specific processing
	
	/*
	 * Dress up the Add Answer DIV for Edit semantics
	 */
	document.getElementById('AddAnswerMastheadLabel').innerHTML='Edit Answer';
	document.getElementById('answertitle').value=answertitle;
	document.getElementById('editmode').value=answerid;
	document.getElementById('selected_messageid').value=messageid; 
	document.getElementById('answermessageselected').checked=true; 
	document.getElementById('resetVariables').checked= resetVariables == 1; 
	document.getElementById('selected_message_title').innerHTML=messagetitle;
	document.getElementById('addanswerbutton').value='Update Answer';

	Display_Notification_DIV('Click a message to select it for this answer.', 'block'); 
	gSelecting_Message_From_Map_Title=document.getElementById('selected_message_title'); 
	gSelecting_Message_From_Map_Value=document.getElementById('selected_messageid'); 
	gSelecting_Message_From_Map_Radio=document.getElementById('answermessageselected');
	document.getElementById('answermessagepicklistselect').selectedIndex = 0;
	
	/*
	 * Email
	 */
	if (emailid > 0) {
		var emailSelection = document.getElementById('emailid');
		
		for (var i = 0; i < emailSelection.options.length; i++) {
			if (emailSelection.options[i].value == emailid) {
				emailSelection.selectedIndex = i;
				break;
			}
		}
	}
	if (emailid2 > 0) {
		var emailSelection2 = document.getElementById('emailid2');
		
		for (var i = 0; i < emailSelection2.options.length; i++) {
			if (emailSelection2.options[i].value == emailid2) {
				emailSelection2.selectedIndex = i;
				break;
			}
		}
	}
				
	/*
	 * Show the Edit/Add answer div
	 */
	document.getElementById('questiontype').style.display='none'; // or else bleed-thru
	document.getElementById('AddAnswerDIV').style.display='block';
}
/*
 * Edit answer (part 2)
 */
function Edit_Answer_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	
	/*
	 * Get the variables list for this question
	 */
	completionObject.AjaxCompletion = Edit_Answer_3;
	
	Get_Variables_List(questionid, completionObject);
	 
}
/*
 * Edit answer (new version)
 */
function Edit_Answer_New(answerid, questionid)
{
	/*
	 * Get the iframe object
	 */
	var iFrameElement = document.getElementById('autoansweriframe');
	
	if (iFrameElement == null)
		return;
	var iFrameDoc = Get_Iframe_Doc(iFrameElement);
	
	iFrameElement.style.visibility='visible';
	iFrameElement.style.display='block';
	
	
	/*
	 * Construct the url
	 */
	var url = 'editanswer.php?sessionid=' + ajax_sessionid + '&sessionkey=' + ajax_sessionkey + '&answerid=' + answerid + '&questionid=' + questionid;
	
	iFrameDoc.location = url;
}

/*
 * Edit answer
 */
function Edit_Answer(answerid, questionid)
{
	/*
	 * Get the information for this answer:
	 *    answertitle, messageid, variable0, variable1, variable2, value1, value2, operation, semantics, messagetitle
	 */
	var parameters = new Object;
	parameters['answerid'] = answerid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Edit_Answer_2;
	completionObject.answerid=answerid;
	completionObject.questionid=questionid;

	Ajax_Call_Web_Method_async("GetAnswerInfo", parameters, completionObject);

}
/*
 * Lookup a message node within a question
 */
function Lookup_Message_In_Question(questionid, messageid)
{
	if (gMessage_Nodes_In_Questions[questionid + "." + messageid] == undefined || gMessage_Nodes_In_Questions[questionid + "." + messageid] == null)
		return null;
	else
		return gMessage_Nodes_In_Questions[questionid + "." + messageid];
}
/*
 * Store a message node into a question
 */
function Store_Message_In_Question(messageNode)
{
	gMessage_Nodes_In_Questions[messageNode.questionid + "." + messageNode.messageid] = messageNode;
	
}
/*
 * Delete a message node from a question
 */
function Delete_Message_From_Question(messageNode)
{
	gMessage_Nodes_In_Questions[messageNode.questionid + "." + messageNode.messageid] = null;
}

/*
 * Display a notification DIV
 */
function Display_Notification_DIV(message, display)
{
	document.getElementById('notifydiv').innerHTML=message;
	document.getElementById('notifydiv').style.display=display;
}
/*
 * MapViewNode class
 */
function MapViewNode(parent, title, displayClass, databaseKey) 
{
	/*
	 * Default the displayClass
	 */
	if (displayClass == undefined)
		displayClass = '';
	/*
	 * Store data
	 */
	this.title=title;
	this.displayClass = displayClass;
	
	/*
	 * Initialize a list for the children
	 */
	this.childrenNodes = new Array;
	
	/*
	 * Methods
	 */
	this.Render = Render;
	this.Move_Duplicates_Primary_To_Top = Move_Duplicates_Primary_To_Top;
	this.Sift_Message_Nodes = Sift_Message_Nodes;
	
	/*
	 * Top level nodes do not have a parent
	 */
	if (parent != null) {
		/*
		 * Store the parent
		 */
		this.parent=parent;
		
		/*
		 * Add this to the list of children for the parent
		 */
		parent.childrenNodes[ parent.childrenNodes.length ] = this;
		
	} else {
		/*
		 * No parent
		 */
		this.parent = null;
	}
	
	/*
	 * Store the database key
	 */
	this.databaseKey = databaseKey;
	
	/*
	 * Store this node into the global list of messages/questions 
	 */
	if (displayClass == 'message') {
		/* Message */
		messageMap[messageMap.length] = this;
		messageMapNodeExists[databaseKey] = true;
		
	} else if (displayClass == 'question') {
		/* Question */
		questionMap[databaseKey] = this;
		lookupNodeByMessageIDQuestionID[parent.messageid+'.'+databaseKey] = parent;
	}
	/*
	 * Reference count 
	 */
	this.referenceCount = 1;
}

/*
 * Keep a global row index
 */
var gRow_ID = 0;
var gNode_ID = 0;

/*
 * Notify user if an error
 */
function Notify_On_Error(error)
{
	if (error.indexOf('Error: ') == 0) {
		alert(error);
		return true;
	} 
	
	return false;
}
/*
 * Toggle the view
 */
function Toggle_View(id)
{
	var rowid = 'row' + id;
	var imageId = 'toggleImage' + id;
	
	var row = document.getElementById(rowid);
	
	if (row.style.display == 'none') {
		row.style.display = '';
		document.getElementById(imageId).className=document.getElementById(imageId).openClass;
		row.node.wasOpen = true;
	} else {
		row.style.display = 'none';
		document.getElementById(imageId).className=document.getElementById(imageId).closedClass;
		row.node.wasOpen = false;
	}
		
	
}
/*
 * Delete a node from the map.  Don't render page
 */
function Delete_Node(node)
{

	/*
	 * Get the parent node
	 */
	var parent = node.parent;
	if (parent != null) {
		/*
		 * Remove this node from the parent's children
		 */
		var foundMatch = false;
		for (var i = 0; i < parent.childrenNodes.length; i++) {
			if (parent.childrenNodes[i] == node) {
				/*
				 * Skip
				 */
				foundMatch = true;
				continue;
			} else if (foundMatch) {
				/*
				 * Shift down one
				 */
				parent.childrenNodes[i-1] = parent.childrenNodes[i];
			}
			
		}
		/*
		 * Truncate the array
		 */
		parent.childrenNodes.length--;
	}
	/*
	 * Remove the message node from the question lookup cache
	 */
	Delete_Message_From_Question(node); 
}
 
/*
 * Delete a question by questionid (part 2)
 */
function Delete_Question_By_QuestionID_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var messageid = completionObject.messageid; // filled in by Delete_Question()
	
	/*
	 * Redisplay the popup
	 */
	document.getElementById('popupdiv').style.display='block';

	Populate_Questions_List(messageid, document.getElementById('questionslistdiv'));
}

/*
 * Delete a question by questionid
 */
function Delete_Question_By_QuestionID(questionid)
{
	var node = questionMap[questionid];
	if (node != undefined) {
		var completionObject = new Object;
		completionObject.AjaxCompletion = Delete_Question_By_QuestionID_2;
		completionObject.questionid = questionid;

		Delete_Question(node.cell.id.substr(4), completionObject);
	}
}
/*
 * Delete a question (part 2)
 */
function Delete_Question_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var messageid = completionObject.results;
	var caller_completionObject = completionObject.caller_completionObject;

		
	/*
	 * Delete the node from the tree
	 */
	Delete_Page(id);

	/*
	 * Restore the map page
	 */
	document.getElementById('mapViewContainer').style.height='475px';
	
	/*
	 * If there was a caller, then complete it to the caller
	 */
	if (caller_completionObject) {
		caller_completionObject.messageid = messageid; // needed by Delete_Question_By_QuestionID_2() etc.
		
		caller_completionObject.AjaxCompletion(caller_completionObject);
	}
		 
}
/*
 * Delete a question
 */
function Delete_Question(id, caller_completionObject)
{
	/*
	 * Get the node for this question
	 */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Remove from the database
	 */
	var parameters = new Object;
	parameters['questionid'] = node.questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Delete_Question_2;
	completionObject.id=id;
	completionObject.caller_completionObject=caller_completionObject;

	Ajax_Call_Web_Method_async("DeleteQuestion", parameters, completionObject);
}
/*
 * Delete a page
 */
function Delete_Page(id)
{
	/*
	 * Close the popup
	 */
	document.getElementById('popupdiv').style.display='none';

	/*
	 * Get the node for this page
	 */
	var node = document.getElementById('node'+id).node;

	/*
	 * Get the parent node
	 */
	var parent = node.parent;
	if (parent != null) {
		/*
		 * Remove this node from the parent's children
		 */
		var foundMatch = false;
		for (var i = 0; i < parent.childrenNodes.length; i++) {
			if (parent.childrenNodes[i] == node) {
				/*
				 * Skip
				 */
				foundMatch = true;
				continue;
			} else if (foundMatch) {
				/*
				 * Shift down one
				 */
				parent.childrenNodes[i-1] = parent.childrenNodes[i];
			}
			
		}
		/*
		 * Truncate the array
		 */
		parent.childrenNodes.length--;
	}
	/*
	 * Re-render the tree
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	mapView.wasOpen = true;
	gNode_ID=0;
	mapView.Render(document.getElementById('mapViewContainer'));
}
/*
 * Update the message title (part 3)
 */
var Do_Full_Refresh_Upon_Message_Update_Completion = false;

function Update_Message_3(completionObject)
{
	if (Do_Full_Refresh_Upon_Message_Update_Completion == true) {
		/*
		 * Do a full refresh
		 */
		Do_Page_Refresh('&editmessageid=' + completionObject.messageid);
	} else {
		/* 
		 * Simply re-render the tree 
		 */
		document.getElementById('mapViewContainer').innerHTML='';
		gNode_ID=0;
		mapView.wasOpen = true;
		mapView.Render(document.getElementById('mapViewContainer'));
		
		alert('Message updated.');
	}
}

/*
 * Update the message title (part 2)
 */
function Update_Message_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var title = completionObject.title;
	var messagebody = completionObject.messagebody;
	var contentid = completionObject.contentid;

	/* 
	 * Get the node object
	 */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Update the node in the tree
	 */
	node.title = title;

	/*
	 * Update the title in duplicates
	 */
	for (i in messageMap) {
		var otherNode = messageMap[i];
		if (otherNode == node || otherNode.messageid != node.messageid)
			continue;
		otherNode.title = title;
		otherNode.cell.innerHTML=title;
	}
	
	/* 
	 * Update any message content 
	 */
	completionObject.AjaxCompletion = Update_Message_3;
	Update_Message_Content(node.messageid, completionObject);
	
}

/*
 * Update the message title
 */
function Update_Message(id, title, messagebody, contentid) {
   /*
    * Determine state of looping chekcbox
    */
    var loop = 0;
    if (document.getElementById('loop')) 
        loop = document.getElementById('loop').checked ? 1 : 0;
    
    /* 
    * Get the messageid from the node
    */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Update the database on the server
	 */
	var parameters = new Object;
	parameters['messageid'] = node.messageid;
	parameters['messagetitle'] = title;
	parameters['messagebody'] = messagebody;
	parameters['loop'] = loop;
	parameters['contentid'] = contentid;
	
	/*
	 * Store parameters into completion context
	 */
	var completionObject = new Object;
	completionObject.AjaxCompletion = Update_Message_2;
	completionObject.id=id;
	completionObject.title=title;
	completionObject.messagebody=messagebody;
	completionObject.contentid=contentid;
	completionObject.messageid =  node.messageid;

	Ajax_Call_Web_Method_async('UpdateMessage', parameters, completionObject);
	
}

/*
 * Update the question title (part 2)
 */
function Update_Question_Title_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var title = completionObject.title;
	var caller_completionObject = completionObject.caller_completionObject;
	
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Update the node in the tree
	 */
	node.title = title;

	/*
	 * Call the caller completion routine
	 */
	caller_completionObject.AjaxCompletion(caller_completionObject);
}

/*
 * Update the question title
 */
function Update_Question_Title(id, title, questiontypeid, caller_completionObject)
{
	/*
	 * Get the questionid from the node
	 */
	var node = document.getElementById('node'+id).node;

	/*
	 * Update the database on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = node.questionid;
	parameters['questiontitle'] = title;
	parameters['selected_messageid'] = document.getElementById('selected_messageid').value;
	parameters['questiontypeid'] = questiontypeid;
	
	var completionObject = new Object;
	completionObject.AjaxCompletion = Update_Question_Title_2;
	completionObject.id=id;
	completionObject.title=title;
	completionObject.caller_completionObject=caller_completionObject;

	Ajax_Call_Web_Method_async('UpdateQuestionTitle', parameters, completionObject);

}

/*
 * Update the question Type (part 3)
 */
function Update_Question_Type_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var type = completionObject.type;
	var node = document.getElementById('node'+id).node;
	var error = completionObject.results;

	/* 
	 * Re-render the tree 
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	gNode_ID=0;
	mapView.wasOpen = true;
	mapView.Render(document.getElementById('mapViewContainer'));
	
	/* 
	 * Re-compute the answers list 
	 */
	Populate_Answers_List(document.getElementById('node'+id +'').node.questionid, 
	   document.getElementById('answerslistdiv'));
	
	/*
	 * Refresh the page to force the map to be recomputed.  Return to this edit question panel
	 */
	Do_Page_Refresh('&editquestionid=' + node.questionid);
}
/*
 * Update the question Type (part 2)
 */
function Update_Question_Type_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var type = completionObject.type;
	var node = document.getElementById('node'+id).node;
	var error = completionObject.results;

	/*
	 * Update the question type in the node
	 */
	node.questionType = type;
	
	/* 
	 * Update the question name 
	 */
	completionObject.AjaxCompletion = Update_Question_Type_3;
	
	Update_Question_Title(id, document.getElementById('questiontitle').value, type, completionObject); 
		
}
/*
 * Update the question Type
 */
function Update_Question_Type(id, type)
{
	/*
	 * If this is a form question, validate the selected message
	 */
	if (type == 6 && (document.getElementById('answermessageselected').checked || document.getElementById('answermessagepicklist').checked)) {
		/*
		 * The user indicated that they wanted to select an existing message from the map, 
		 * so make sure that they did
		 */
		if (document.getElementById('selected_messageid').value == 0) {
			if (document.getElementById('answermessageselected').checked)
				alert('You must select a message from the map.');
			else
				alert('You must select a message from the list.');
			return false;
		}		
	}
	
	/*
	 * Get the questionid from the node
	 */
	var node = document.getElementById('node'+id).node;

	/*
	 * Update the database on the server
	 */
	var parameters = new Object;
	parameters['questionid'] = node.questionid;
	parameters['questiontypeid'] = type;
	
	/*
	 * Store parameters into completion context
	 */
	var completionObject = new Object;
	completionObject.AjaxCompletion = Update_Question_Type_2;
	completionObject.id=id;
	completionObject.type=type;

	Ajax_Call_Web_Method_async('UpdateQuestionType', parameters, completionObject);

}

/*
 * Add a new message to a question
 */
function Add_New_Message(id, title, messageid)
{
	
	/*
	 * Create a new node
	 */
	var node = document.getElementById('node'+id).node;
	addedNode = new MapViewNode(node, title, 'message', messageid);
	addedNode.wasOpen = true;
	
}
/*
 * Delete an answer (part 2)
 */
function Delete_Answer_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid ;
	var answerid = completionObject.answerid;
	var messageid = completionObject.results;

	/*
	 * Decrement the reference count for the message node within the question, 
	 * if zero, then delete the node
	 */
	var messageNode = Lookup_Message_In_Question(questionid, messageid);
	if (messageNode != null) {
		messageNode.referenceCount--;
		
		if (messageNode.referenceCount == 0) {
			/*
			 * No more references to this message node, delete it
			 */
			Delete_Node(messageNode);
		}
	}
	/*
	 * Refresh the map
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	gNode_ID=0;
	mapView.wasOpen = true;
	mapView.Render(document.getElementById('mapViewContainer'));
	
	/*
	 * Refresh the answer list
	 */
	Populate_Answers_List(questionid, document.getElementById('answerslistdiv'))	 
}

/*
 * Delete an answer
 */
function Delete_Answer(questionid, answerid)
{
	/*
	 * Call the server to create the answer within the question
	 */
	var parameters = new Object;
	parameters['answerid'] = answerid;
	
	var completionObject = new Object;
	completionObject.AjaxCompletion = Delete_Answer_2;
	completionObject.questionid=questionid;
	completionObject.answerid=answerid;
	Ajax_Call_Web_Method_async("DeleteAnswer", parameters, completionObject);
}

/*
 * Add a new question to a message (part 3)
 */
function Add_Question_3(completionObject)
{
	var QUESTION_TYPE_FORM = 6;

	/*
	 * Recover the parameters used for AddQuestion()
	 */
	var parameters = completionObject.parameters;

	/*
	 * If added a form, then we need to re-compute the map
	 */
	if (parameters['questiontype'] == QUESTION_TYPE_FORM) {
		/* 
		 * First execute the Apply button implicitly and request a full refresh upon completion
		 */
		Do_Full_Refresh_Upon_Message_Update_Completion = true;
	    document.getElementById('ApplyMessageButton').onclick();
	} else {
		/* 
		 * Was not a form, so simply execute the Apply button implicitly 
		 */
	    document.getElementById('ApplyMessageButton').onclick();
	}
}

/*
 * Add a new question to a message (part 2)
 */
function Add_Question_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var node = document.getElementById('node'+id).node;
	var questionid = completionObject.results;
	var parameters = completionObject.parameters;

	/*
	 * Create a new node
	 */
	var addedNode = new MapViewNode(node, document.getElementById('questiontitle').value, 'question', questionid);
	addedNode.wasOpen = true;

	/*
	 * Store the questionid into the node
	 */
	addedNode.questionid=questionid;
	
	/*
	 * Store the question type into the node
	 */
	addedNode.questionType = parameters['questiontype'];
	
	/* 
	 * Close the panel 
	 */
	document.getElementById('canceladdquestion').onclick();
	
	/* 
	 * Re-render the tree 
	 */
	document.getElementById('mapViewContainer').innerHTML='';
	gNode_ID=0;
	mapView.wasOpen = true;
	mapView.Render(document.getElementById('mapViewContainer'));
	
	/* 
	 * Populate the questions list 
	 */
	completionObject.AjaxCompletion = Add_Question_3;
	
	Populate_Questions_List(document.getElementById('node'+id +'').node.messageid, document.getElementById('questionslistdiv'), completionObject); 
}

/*
 * Add a new question to a message
 */
function Add_Question(id)
{
	/*
	 * Get the message node
	 */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Question title is required
	 */
	if (document.getElementById('questiontitle').value.replace(/ /g, '') == '') {
		alert('Question text is required.');
		return false;
	}

	/*
	 * Call the server to create the question within the message
	 */
	var parameters = new Object;
	var questionType = document.getElementById('questiontype');
	
	parameters['messageid'] = node.messageid;
	parameters['questiontitle'] = document.getElementById('questiontitle').value;
	parameters['questiontype'] = questionType.options[questionType.selectedIndex].value;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Add_Question_2;
	completionObject.id=id;
	completionObject.parameters = parameters;
	
	Ajax_Call_Web_Method_async("AddQuestion", parameters, completionObject);
}
/*
 * Paste a new answer to a question (part 2)
 */
function Paste_Answer_2(completionObject)
{
	/*
	 * Refresh the page to force the map to be recomputed.  Return to this edit question panel
	 */
	Do_Page_Refresh('&editquestionid=' + completionObject.questionid);
}
/*
 * Paste a new answer to a question
 */
function Paste_Answer(questionid)
{
	/*
	 * Call the server to paste the answer into the question
	 */
	var parameters = new Object;
	
	parameters['questionid'] = questionid;
	parameters['answerid'] = Copied_answerid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Paste_Answer_2;
	completionObject.questionid=questionid;
	completionObject.parameters = parameters;
	
	Ajax_Call_Web_Method_async("PasteAnswer", parameters, completionObject);
	
}
/*
 * Paste a question into a message (part 2)
 */
function Paste_Question_2(completionObject)
{
	/*
	 * Check for abort
	 */
	if (completionObject.timeoutAbort == true || completionObject.results != '') {
		alert('An error occurred pasting the question into this application: ' + completionObject.results);
	}
	/* 
	 * First execute the Apply button implicitly and request a full refresh upon completion
	 */
	Do_Full_Refresh_Upon_Message_Update_Completion = true;
	document.getElementById('ApplyMessageButton').onclick();
}

/*
 * Paste a new question to a message
 */
function Paste_Question(id, questionid)
{
	/*
	 * Get the message node
	 */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Call the server to paste the question into the message
	 */
	var parameters = new Object;
	
	parameters['messageid'] = node.messageid;
	if (questionid == 0)
		questionid = Copied_questionid;
		
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Paste_Question_2;
	completionObject.id=id;
	completionObject.messageid=node.messageid;
	completionObject.questionid=questionid;
	completionObject.parameters = parameters;
	
	Ajax_Call_Web_Method_async("PasteQuestion", parameters, completionObject);
}
/*
 * Add a new answer to a question (part 2)
 */
function Add_Answer_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var results = completionObject.results;
	var node = document.getElementById('node'+id).node;
	var duplicate = completionObject.duplicate;
	var relinkToExistingMessage = completionObject.relinkToExistingMessage;
	/*
	 * The results are returned as answerid, messageid, messagetitle, isApplicationMessage
	 */
	var resultsParsed = results.split('\t');
	var answerid = resultsParsed[0];
	messageid = resultsParsed[1];
	var messagetitle = resultsParsed[2];
	var isApplicationMessage =  resultsParsed[3];

	/*
	 * Does a message node already exist for this question ?
	 */
	var addedNode = Lookup_Message_In_Question(node.questionid, messageid);
	
	if (addedNode == null) {
		/*
		 * Create a new message node
		 */
		addedNode = new MapViewNode(node, messagetitle, 'message', messageid);
		addedNode.wasOpen = true;
		
		/*
		 * Store the messageid into the node
		 */
		addedNode.messageid=messageid;
		
		/*
		 * Store the parent questionid into the node
		 */
		addedNode.questionid=node.questionid;
		
		/*
		 * Store the message node into the lookup cache
		 */
		Store_Message_In_Question(addedNode);
		
		/*
		 * If this is a duplicate, then flag it here.  Note that if we have not identified this
		 * as a duplicate, we don't explicitly mark it "duplicate=false".  This is because our
		 * duplicate detection algorithm only looks for messages that were linked from outside
		 * this question.
		 */
		if (duplicate) {
			/*
			 * Duplicate
			 */
			addedNode.duplicate = true;
		} else if (relinkToExistingMessage){
			/*
			 * Not a duplicate, since this message was a relink to a previous message, then we 
			 * must refresh the page 
			 */
			Do_Page_Refresh('&editquestionid=' + node.questionid);
			return false;
		}
	} else {
		/*
		 * Node already exists, bump the reference count
		 */
		addedNode.referenceCount++;
		
	}
	/*
	 * ALWAYS REFRESH, for now
	 */
	Do_Page_Refresh(href += '&editquestionid=' + node.questionid);
	return false;

	/*
	 * Mark this node as being an application message, if this is the case
	 */
	addedNode.isApplicationMessage = isApplicationMessage;
	
	/*
	 * If edit mode and changed messages associated with this answer, then update
	 * the reference count on the old answer and possibly delete it
	 */
	if (gOld_messageid != null && gOld_messageid != messageid) {
		var messageNode = Lookup_Message_In_Question(node.questionid, gOld_messageid);
	
		if (messageNode != null) {
			messageNode.referenceCount--;
			
			if (messageNode.referenceCount == 0) {
				/*
				 * No more references to this message node, delete it
				 */
				Delete_Node(messageNode);
			}
		}
	}
	
	/* 
	 * Re-render the tree 
	 */
    document.getElementById('mapViewContainer').innerHTML='';
    gNode_ID=0;
    mapView.wasOpen = true;
    mapView.Render(document.getElementById('mapViewContainer'));
	
	/* 
	 * Populate the answers list 
	 */
	Populate_Answers_List(document.getElementById('node'+id +'').node.questionid, document.getElementById('answerslistdiv')); 
	
}


/*
 * Add a new answer to a question
 */
function Add_Answer(id)
{
	/*
	 * Get the question node
	 */
	var node = document.getElementById('node'+id).node;
	
	/*
	 * Answer title is required
	 */
	if (document.getElementById('answertitle').value.replace(/ /g, '') == '') {
		alert('Answer text is required.');
		return false;
	}

	/*
	 * Make sure that any new variable name is not already in the list
	 */
	for (i = 1; i <= 10; i++) {
		var variable0selection = document.getElementById('variable0selection_' + i);
		if (variable0selection == null)
			break;
		
		/*
		 * If the "Add variable assignment/formula" is not checked, skip it
		 */
		var assignvariable = document.getElementById('assignvariable_' + i);
		
		if (assignvariable.checked == false)
			continue;
			
		/*
		 * Did the user select "Assign new variable" ?
		 */
		if (variable0selection.selectedIndex == 0) {
			/*
			 * Yes, using new variable name 
			 */			
			var value0 = document.getElementById('variable0_' + i).value;
			
			/*
			 * Make sure it is not blank
			 */
			if (value0.replace(/ /g, '') != '') {
				/*
				 * Compare with other variables that are already in the list
				 */
				for (j = 0; j < variable0selection.length; j++) {
					if (value0.toLowerCase() == variable0selection.options[j].text.toLowerCase()) {
						/*
						 * Already in use
						 */
						alert('The variable name \'' + value0 + '\' is already in use.\r\nPlease enter a new variable name or select one from the list.');
						return false;
					}
				}
			}
		}
	}
	/* 
	 * Get the selected message id
	 */
	messageid = 0;
	
	if (document.getElementById('answermessageselected').checked || document.getElementById('answermessagepicklist').checked) {
		/*
		 * The user indicated that they wanted to select an existing message from the map, 
		 * so make sure that they did
		 */
		if (document.getElementById('selected_messageid').value == 0) {
			if (document.getElementById('answermessageselected').checked)
				alert('You must select a message from the map.');
			else
				alert('You must select a message from the list.');
			return false;
		}
		
		messageid = document.getElementById('selected_messageid').value;
	}
	
	/*
	 * Determine if we are assigning to an existing message that is not under this question, if so
	 * then it is a duplicate
	 */
	var duplicate = false;
	var relinkToExistingMessage = false;
	if (messageid) {
		/*
		 * Does this message already existin under this question ?
		 */
		if (Lookup_Message_In_Question(node.questionid, messageid) == null 
			&& messageMapNodeExists[messageid] == true
			&& Message_Is_Linked(mapView, messageid, 0)
			) {
			/*
			 * No, so this is a duplicate
			 */
			duplicate = true;
		}
		
		/*
		 * This is a relink to an existing message
		 */
		relinkToExistingMessage = true;
	}
	 
	/*
	 * FORMULA #1: Determine whether we are assigning a variable as part of the selection of this answer
	 * by the user
	 */
	var semantics_1 = "numeric";
	var variable0_1 = 0;
	var value0_1 = '';
	var variable1_1 = 0;
	var value1_1 = '';
	var variable2_1 = 0;
	var value2_1 = '';
	var operation_1 = '';
	
	if (document.getElementById('assignvariable_1').checked) {
		/*
		 * Get the type: numeric or string
		 */
		semantics_1 = "numeric";
		if (document.getElementById('answerSemanticsString_1').checked)
			semantics_1 = "string";
	
		/*
		 * Get the ASSIGNMENT new variable name or current variableid
		 */
		var variable0selection_1 = document.getElementById('variable0selection_1');
		if (variable0selection_1.selectedIndex == 0) {
			/*
			 * New variable
			 */
			if (document.getElementById('variable0_1').value.replace(/ /g, '') == '') {
				alert('You must enter a new variable name.');
				return false;
			}
			value0_1 = document.getElementById('variable0_1').value;
		} else {
			/*
			 * Existing variable
			 */
			variable0_1 = variable0selection_1.options[variable0selection_1.selectedIndex].value;
	
		}
		/*
		 * Get the VAR1 variableid or value
		 */
		var variable1selection_1 = document.getElementById('variable1selection_1');
		if (variable1selection_1.selectedIndex == 0) {
			/*
			 * Value
			 */
			value1_1 = document.getElementById('variable1_1').value;
		} else {
			/*
			 * Existing variable
			 */
			variable1_1 = variable1selection_1.options[variable1selection_1.selectedIndex].value;
		}
		/*
		 * Get the VAR2 variableid or value
		 */
		var variable2selection_1 = document.getElementById('variable2selection_1');
		if (variable2selection_1.selectedIndex == 0) {
			/*
			 * Value
			 */
			value2_1 = document.getElementById('variable2_1').value;
		} else {
			/*
			 * Existing variable
			 */
			variable2_1 = variable1selection_1.options[variable2selection_1.selectedIndex].value;
		}
		
		/*
		 * Get the operation
		 */
		var operationSelection_1 = document.getElementById('operation_1');
		operation_1 = operationSelection_1.options[operationSelection_1.selectedIndex].value;
	} /* End if assigning a variable FORMULA #1*/

	/*
	 * Define the parameters object for the ajax call to the server
	 */
	var parameters = new Object;

	/*
	 * FORMULA #N: Determine whether we are assigning a variable as part of the selection of this answer
	 * by the user
	 */
	for (i = 2; i <= 10; i++) {
		var semantics = "numeric";
		var variable0 = 0;
		var value0 = '';
		var variable1 = 0;
		var value1 = '';
		var variable2 = 0;
		var value2 = '';
		var operation = '';
		
		if (document.getElementById('assignvariable_'+i) == null)
			break;
										
		if (document.getElementById('assignvariable_'+i).checked) {
			/*
			 * Get the type: numeric or string
			 */
			semantics = "numeric";
			if (document.getElementById('answerSemanticsString_'+i).checked)
				semantics = "string";
		
			/*
			 * Get the ASSIGNMENT new variable name or current variableid
			 */
			var variable0selection = document.getElementById('variable0selection_'+i);
			if (variable0selection.selectedIndex == 0) {
				/*
				 * New variable
				 */
				if (document.getElementById('variable0_'+i).value.replace(/ /g, '') == '') {
					alert('You must enter a new variable name.');
					return false;
				}
				value0 = document.getElementById('variable0_'+i).value;
			} else {
				/*
				 * Existing variable
				 */
				variable0 = variable0selection.options[variable0selection.selectedIndex].value;
		
			}
			/*
			 * Get the VAR1 variableid or value
			 */
			var variable1selection = document.getElementById('variable1selection_'+i);
			if (variable1selection.selectedIndex == 0) {
				/*
				 * Value
				 */
				value1 = document.getElementById('variable1_'+i).value;
			} else {
				/*
				 * Existing variable
				 */
				variable1 = variable1selection.options[variable1selection.selectedIndex].value;
			}
			/*
			 * Get the VAR2 variableid or value
			 */
			var variable2selection = document.getElementById('variable2selection_'+i);
			if (variable2selection.selectedIndex == 0) {
				/*
				 * Value
				 */
				value2 = document.getElementById('variable2_'+i).value;
			} else {
				/*
				 * Existing variable
				 */
				variable2 = variable1selection.options[variable2selection.selectedIndex].value;
			}
			
			/*
			 * Get the operation
			 */
			var operationSelection = document.getElementById('operation_'+i);
			operation = operationSelection.options[operationSelection.selectedIndex].value;
			/*
			 * FORMULA #N ajax parameters
			 */
			parameters['variable0_'+i] = variable0;
			parameters['variable1_'+i] = variable1;
			parameters['variable2_'+i] = variable2;
			parameters['value0_'+i] = value0;
			parameters['value1_'+i] = value1;
			parameters['value2_'+i] = value2;
			parameters['semantics_'+i] = semantics;
			parameters['operation_'+i] = operation;
			parameters['roundup_'+i] = document.getElementById('roundup_'+i).checked ? 1 : 0;
		} /* End if assigning a variable FORMULA #N*/
	} // End enumerating formulas 2..10
	
	/*
	 * Call the server to create the answer within the question
	 */
	parameters['questionid'] = node.questionid;
	parameters['answertitle'] = document.getElementById('answertitle').value;
	parameters['messageid'] = messageid;
	parameters['editmode'] = document.getElementById('editmode').value;
	parameters['resetVariables'] = document.getElementById('resetVariables').checked ? 1 : 0;	
	
	/*
	 * FORMULA #1
	 */
	parameters['variable0_1'] = variable0_1;
	parameters['variable1_1'] = variable1_1;
	parameters['variable2_1'] = variable2_1;
	parameters['value0_1'] = value0_1;
	parameters['value1_1'] = value1_1;
	parameters['value2_1'] = value2_1;
	parameters['semantics_1'] = semantics_1;
	parameters['operation_1'] = operation_1;
	parameters['roundup_1'] = document.getElementById('roundup_1').checked ? 1 : 0;	
	
	var emailSelection = document.getElementById('emailid');	
	parameters['emailid'] = emailSelection.options[emailSelection.selectedIndex].value;

	var emailSelection2 = document.getElementById('emailid2');	
	parameters['emailid2'] = emailSelection2.options[emailSelection2.selectedIndex].value;

	var completionObject = new Object;
	completionObject.AjaxCompletion = Add_Answer_2;
	completionObject.id=id;
	completionObject.duplicate = duplicate;
	completionObject.relinkToExistingMessage = relinkToExistingMessage;

	Ajax_Call_Web_Method_async("AddAnswer", parameters, completionObject);
	
}
/*
 * Store the caret position within a text area
 */
function storeCaret (textEl) {
   if (textEl.createTextRange) 
	 textEl.caretPos = document.selection.createRange().duplicate();
}

/*
 * Insert a table tag into
 * the message body (within a textarea control).
 */
function Insert_Table_Into_Text_Area(textarea)
{

	var table_tag = '[TABLE]';
	
	if (document.selection) {
		var caretPos = textarea.caretPos;
		if (caretPos == null) {
			textarea.value += table_tag;
		} else {
			caretPos.text =
			  caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
						 table_tag + ' ' : table_tag;	
		}
	}

	//Mozilla/Firefox/Netscape 7+ support
	else if (textarea.selectionStart || textarea.selectionStart == '0') {

		//Here we get the start and end points of the
		//selection. Then we create substrings up to the
		//start of the selection and from the end point
		//of the selection to the end of the field value.
		//Then we concatenate the first substring, myValue,
		//and the second substring to get the new value.
		var startPos = textarea.selectionStart;
		var endPos = textarea.selectionEnd;
		textarea.value = textarea.value.substring(0, startPos)+ table_tag+ textarea.value.substring(endPos, textarea.value.length);
	} else {
		textarea.value += table_tag;
	}
	
	selection.selectedIndex = 0;
}
/*
 * Apply the format selection for a variable
 */
var selectedVariableID = 0;
var messageBodyTextArea;

function Apply_Variable_Display_Format()
{
	/*
	 * Hide the format selection popup DIV
	 */	
	if (document.getElementById('formatdiv') != null)
		document.getElementById('formatdiv').style.display='none';
	
	/*
	 * Create the replacement string based upon which radio control was selected
	 */
	var variable_name_1 = '[VARIABLEID' + 
					  selectedVariableID + 
					  '/X=';
	var variable_name_2 = variable_name_1;
	
	if (document.getElementById('displayformatstring').checked == true) {
		
		variable_name_2 = '[VARIABLEID' + 
					  selectedVariableID + 
					  '/0=';
	} else  if (document.getElementById('displayformatinteger').checked == true) {
		variable_name_2 = '[VARIABLEID' + 
					  selectedVariableID + 
					  '/1=';
	} else  if (document.getElementById('displayformatfloat').checked == true) {
		variable_name_2 = '[VARIABLEID' + 
					  selectedVariableID + 
					  '/2=';
	}
	/*
	 * Do the string replacement in the message body
	 */
	var sanity = 0;
	while (messageBodyTextArea.value.indexOf(variable_name_1) >= 0 && sanity++ < 100) {
		messageBodyTextArea.value =
			messageBodyTextArea.value.replace(variable_name_1, variable_name_2);
	}
	/*
	 * Reset the default selected format to "string"
	 */
	document.getElementById('displayformatstring').checked = true;
}
/*
 * Insert a user selected variable from a dropdown control into
 * the message body (within a textarea control).
 */
function Insert_Variable_Into_Message_Body(selection, textarea)
{
							  
	if (selection.selectedIndex <= 0 || selection.options[selection.selectedIndex].value == 0) {
		selection.selectedIndex = 0;
		return;
	}
		
	var variable_name = '[VARIABLEID' + 
						  selection.options[selection.selectedIndex].value + 
						  '/X=' + selection.options[selection.selectedIndex].text + ']';
	
	if (document.selection) {
		var caretPos = textarea.caretPos;
		if (caretPos == null) {
			textarea.value += variable_name;
		} else {
			caretPos.text =
			  caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
						 variable_name + ' ' : variable_name;	
		}
	}

	//Mozilla/Firefox/Netscape 7+ support
	else if (textarea.selectionStart || textarea.selectionStart == '0') {

		//Here we get the start and end points of the
		//selection. Then we create substrings up to the
		//start of the selection and from the end point
		//of the selection to the end of the field value.
		//Then we concatenate the first substring, myValue,
		//and the second substring to get the new value.
		var startPos = textarea.selectionStart;
		var endPos = textarea.selectionEnd;
		textarea.value = textarea.value.substring(0, startPos)+ variable_name+ textarea.value.substring(endPos, textarea.value.length);
	} else {
		textarea.value += variable_name;
	}
	
	/*
	 * Display the format-selection div for this variable
	 */
	selectedVariableID = selection.options[selection.selectedIndex].value;
	
	messageBodyTextArea = textarea;
	
	if (document.getElementById('formatdiv') != null)
		document.getElementById('formatdiv').style.display='block';	
	
	/*
	 * Reset the selection control
	 */
	selection.selectedIndex = 0;
	 
}
/*
 * Insert a user selected table from a dropdown control into
 * the message body (within a textarea control).
 */
function Insert_Table_Into_Message_Body(selection, textarea)
{
							  
	if (selection.selectedIndex <= 0)
		return;
		
	var table_name = '[TABLEID' + 
						  selection.options[selection.selectedIndex].value + 
						  '=' + selection.options[selection.selectedIndex].text + ']';
	
	if (document.selection) {
		var caretPos = textarea.caretPos;
		if (caretPos == null) {
			textarea.value += table_name;
		} else {
			caretPos.text =
			  caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
						 table_name + ' ' : table_name;	
		}
	}

	//Mozilla/Firefox/Netscape 7+ support
	else if (textarea.selectionStart || textarea.selectionStart == '0') {

		//Here we get the start and end points of the
		//selection. Then we create substrings up to the
		//start of the selection and from the end point
		//of the selection to the end of the field value.
		//Then we concatenate the first substring, myValue,
		//and the second substring to get the new value.
		var startPos = textarea.selectionStart;
		var endPos = textarea.selectionEnd;
		textarea.value = textarea.value.substring(0, startPos)+ table_name+ textarea.value.substring(endPos, textarea.value.length);
	} else {
		textarea.value += table_name;
	}
	
	selection.selectedIndex = 0;
}
/*
 * Raise the popup div for a message (part 8)
 */
function Raise_Popup_DIV_Message_8(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	var results = completionObject.results;
	var messageBody = completionObject.messageBody;
	var variablesSelectionControl =	completionObject.variablesSelectionControl;
	var tablesSelectionControl = completionObject.tablesSelectionControl;
	var contentSelectionControl = completionObject.contentSelectionControl;
	var loopControl = completionObject.loopControl;
	/*
	 * If readonly, then disable the apply button
	 */
	var Apply_Disabled = '';
	if (gReadOnly == true)
		Apply_Disabled = ' DISABLED ';

	/*
	 * Raise the popup
	 */
	popup.style.display='block';

	popup.innerHTML=/* Header */
					'<div class=popupHeader  style=background-color:#ccffcc;color:black;>'+
					'<table width=100% cellpadding=0 cellspacing=0><tr align=left><td><span title="messageid=' + completionObject.messageid + '">Edit Message</span</td><td align=right style=padding-right:15px;>' +
					/* Close link */
					'<a style=color:blue; href=javascript:void(0); onclick=document.getElementById("popupdiv").style.display="none";>' +
					'Close</a>' +
					'</td></tr></table>' +
					'</div>' +
					'<div style=padding-top:20px;padding-left:10px;>' +
					'<table cellpadding=0 cellspacing=0><tr align=left valign=bottom>' +
					/* Edit message title */
					'<td>' +
					'Message Title:<br><input type=text  class=textInput name=messagetitle id=messagetitle value="'  + node.title + '">' +
					'</td><td style=padding-left:20px;>' +
					/* Edit message content */
					'</td><td>' +
					'Content: ' + loopControl  + '<br>' + contentSelectionControl +
					'</td><td style=padding-left:160px;>' +
					/* Apply button */
					'<input type=button id=ApplyMessageButton value="Update" style=width:60px; ' + Apply_Disabled +
					' onclick="javascript:' +
					'     if (Ajax_In_Use) return; ' +
					'     var typeSelection = document.getElementById(\'questiontype\'); ' +
					'     var contentSelection = document.getElementById(\'contentcontrol\'); ' +
					'	  var contentid = 0; ' +
					'     if (contentSelection) { ' +
					'         if (contentSelection.selectedIndex < 0) contentSelection.selectedIndex = 0; ' +
					'         contentid = contentSelection.options[contentSelection.selectedIndex].value; ' +
					'     } ' +
					/* Update name and body */
					'     if (document.getElementById(\'messagetitle\').value.length > 0) ' +
					'         Update_Message(' + id + ', document.getElementById(\'messagetitle\').value,  document.getElementById(\'messagebody\').value, contentid,document.getElementById(\'questiontype\')); ' + 					
					'">' +
					'</td></tr></table><br>' +
					/* Edit message body */
					'Message Body:' + variablesSelectionControl + tablesSelectionControl +
					'<br><textarea ' +
					' ONSELECT="storeCaret(this);" ' +
					' ONCLICK="storeCaret(this);" ' +
					' ONKEYUP="storeCaret(this);" ' +
					/* onfocus = enable insertion of variables */
					' onfocus="javascript:if (document.getElementById(\'variablesinsertcontrol\') != null) ' +
					'     document.getElementById(\'variablesinsertcontrol\').disabled=false;" ' +
					' style=width:550px;height:100px;background-color:white;background-image:none;overflow-x:hidden; class=messageBody name=messagebody id=messagebody>'  + 
					messageBody + '</textarea><br>' +
					/* Variable display format selection popup */
					'<div     style=display:none;border-style:solid;border-color:black;border-width:1px;position:absolute;z-index:10px;top:120px;left:100px;background-color:#666666;font-size:8pt;color:white;width:300px;padding:5px;  id=formatdiv>Select the display format for this variable:<br>' +
					'<input type=radio name=displayformat id=displayformatstring CHECKED value=0> String<br>' +
					'<input type=radio name=displayformat id=displayformatinteger value=1> Integer<br>' +
					'<input type=radio name=displayformat id=displayformatfloat value=2> Decimal<br>' +
					'<br>' +
					'<input type=button value=Update onclick=javascript:Apply_Variable_Display_Format();>&nbsp;' +
					'<xinput type=button value=Close onclick=javascript:document.getElementById(\'formatdiv\').style.display=\'none\';>' +
					'</div>' +
					 
					/* Alternate DIV for display notification when not allowed to add questions to the div */
					'<div id=addquestiondivalt style=display:none;color:#999999;>You cannot add questions to this message; it is a duplicate entry.</div>' +

					/* Add question DIV */
					'<div class=AddQuestionDIV id=addquestiondiv>' + 
					/* Add question masthead */
					'<div style=padding:1px;padding-bottom:10px;>' +
					'<div class=masthead2><table cellpadding=0 cellspacing=0 width=100%><tr align=left valign=top>' +
					'<td>Add Question</td>' +
					'<td align=right>' +
					/* Add question button */
					'<input type=button id=addquestionbutton value=\"Add Question\" ' + Apply_Disabled +
					' onclick=\"javascript:' +
				    '   if (Ajax_In_Use) return; ' +
						/* Add the question */
					'   if (Add_Question(' + id + ') == false) return; ' +
					' \">&nbsp;&nbsp;' +
					/* Cancel button */
					'<input type=button value=Cancel id=canceladdquestion onclick=\"javascript:' +
					' document.getElementById(\'addquestiondiv\').style.display=\'none\';">' +
					'</td>' +
					'</tr></table></div>' +
					/* End of add question masthead */
					'</div>' +
					'<div style=padding:3px;>' +
					'<div class=questionSubDIV>' +
					/* Question text */
					'<table cellpadding=0 cellspacing=0><tr valign=top>' + 
					'<td><b><span id=questiontextlabel>Enter Question Text</span>:</b><br><input type="text"  class=textInput id=questiontitle name=questiontitle style=width:165px;></td>' +
					/* Question type */
					'<td style=padding-left:50px;>&nbsp;</td>' +
					'<td style=padding-left:10px;border-left-style:solid;border-left-color:white;border-left-width:2px;>' +
					'<b>Question Type:</b><br>' +
/* Question Type */
					'<select id=questiontype name=questiontype ' +
					' onchange="javascript: var span=document.getElementById(\'questiontextlabel\'); ' +
					'    if (this.selectedIndex == 0) span.innerHTML=\'Enter Question Text\'; else span.innerHTML=\'Enter Prompt Text\'; ' +
					' " ' +
					'>'+
					'<option value=1>Multiple Choice</option>' +
					'<option value=3>Text: Multiple Lines</option>' +
					'<option value=4>Text: Single Line</option>' +
					'<option value=6>Form</option>' +
					'</select>' +
					'</tr></table>' +
					'</div>' +
					/* End of add question DIV */
					'</div>' +
					'</div></div></div></div>' +
					/* Patterns DIV */
					'<div class=AddQuestionDIV style=height:170px; id=patternsdiv>' + 
					/* Patterns masthead */
					'<div style=padding:1px;padding-bottom:10px;>' +
					'<div class=masthead2><table cellpadding=0 cellspacing=0 width=100%><tr align=left valign=top>' +
					'<td>Patterns</td>' +
					'<td align=right>' +
					/* Close button */
					'<input type=button value=Close id=canceladdquestion onclick=\"javascript:' +
					' document.getElementById(\'patternsdiv\').style.display=\'none\';">' +
					'</td>' +
					'</tr></table></div>' +
					/* End of add Patterns masthead */
					'</div>' +
					/* DIV that will hold the patterns */
					'<div style=padding:3px;color:#666666;font-size:8pt;>Click a pattern to add it to this message:</div>' +
					'<div style=padding:3px;overflow:auto;height:160px;color:#666666; id=patternslistdiv><div style=padding-top:20px;padding-left:100px;>Loading...</div></div>' +
					/* End of patterns DIV */
					'</div>' +
					'';
					
	/*
	 * Determine if the paste question button should be enabled
	 */
	var pasteQuestionDisabled = "";
	
	if (Copied_questionid == null || gReadOnly) {
		pasteQuestionDisabled = " disabled ";
	}
	
	/*
	 * Add the DIV for displaying questions for this message
	 */
	popup.innerHTML +='<br><div style=padding-left:10px;><div id=questionsdiv class=questionsDIV>' +
					/* Questions DIV masthead */
					'<div class=questionsDIVmasthead ' +
					' style=padding-bottom:3px;><table cellpadding=0 cellspacing=0 width=100%><tr align=left valign=top>' +
					'<td>Questions:</td>' +
					'<td align=right>' +
					/* Patterns button */
					'<input type=button value=\"Patterns\" ' + Apply_Disabled + 
					' onclick=\"javascript:' +
					/* onClick: display the DIV */
					' document.getElementById(\'patternsdiv\').style.display=\'block\';'+
					' Load_Patterns(' + id + '); ' +
					'\">&nbsp;&nbsp;' +
					/* Paste question button */
					'<input type=button value=\"Paste Question\" ' + pasteQuestionDisabled + 
					' onclick=\"javascript:' +
					/* onClick: check for ajax in use */
				    'if (Ajax_In_Use) return; ' +
					/* If pasting from other applications is blocked, warn the user */
					'if (pastingFromOtherApplicationsBlocked == true) { alert (\'You do not have permission to copy-and-paste across applications.\'); return;}' + 
					/* Warn the user that this will load tables, email and variables from source application */
					'retriesAllowed = false;' +
					'if (pastingFromOtherApplication == true) {' + 
					'    if (confirm(\'Pasting a question from another application will load all of the email, tables and variables from that application into this application.\\r\\n\\r\\nContinue?\') == false) return; ' +
					'    alternateDisplayText = \'<nobr>Pasting a question from another application</nobr><br><nobr>may take several minutes, please wait.</nobr>\';' +
					'    document.getElementById(\'popupdiv\').style.display=\'none\';' +
					'}' +
					/* Paste the question */
					'if (Paste_Question(' + id + ', 0) == false) return; ' +
					'\">&nbsp;&nbsp;' +
					/* Add question button */
					'<input type=button value=\"Add Question\" ' + Apply_Disabled + 
					' onclick=\"javascript:' +
					/* onClick: display the DIV */
					' document.getElementById(\'questiontitle\').value=\'\';' + 
					' var selection = document.getElementById(\'questiontype\');selection.selectedIndex=0;'+
					' document.getElementById(\'addquestiondiv\').style.display=\'block\';'+
					'\">' +
					'</td>' +
					'</tr></table>' +
					/* End of questions DIV masthead */
					'</div>' +
					/* Questions list DIV */
					'<div id=questionslistdiv class=questionsListDIV>' +
					/* End of questions list DIV */
					'</div>' +
					/* Terminate the questions DIV */
					'</div></div>';
					
	/*
	 * Terminate the edit message DIV
	 */
	popup.innerHTML +=
					'</div>';
					

	/* 
	 * Don't allow questions to be edited from duplicate message nodes
	 */
	if (node.duplicate == true) {
		/*
		 * Don't allow editing questions
		 */
		document.getElementById('patternsdiv').style.display='none';
		document.getElementById('addquestiondiv').style.display='none';
		document.getElementById('addquestiondivalt').style.display='block';
		document.getElementById('questionsdiv').style.display='none';

	} else {
		/*
		 * Populate the questions list for this message
		 */
		Populate_Questions_List(document.getElementById('node'+id).node.messageid, document.getElementById('questionslistdiv'));		
	}
	/*
	 * Close the auto-answer iframe
	 */
	document.getElementById('autoansweriframe').style.visibility='hidden';
	document.getElementById('autoansweriframe').style.display='none';
		
}
/*
 * Raise the popup div for a message (part 7)
 */
function Raise_Popup_DIV_Message_7(completionObject)
{
	completionObject.AjaxCompletion = Raise_Popup_DIV_Message_8;

	Get_Advanced_User_Status(completionObject);
}

/*
 * Raise the popup div for a message (part 6)
 */
function Raise_Popup_DIV_Message_6(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	var contentURL = completionObject.results;
	var messageBody = completionObject.messageBody;
	var variablesSelectionControl =	completionObject.variablesSelectionControl;
	var tablesSelectionControl = completionObject.tablesSelectionControl;

	var expandedContentURL = contentURL + '&semantics=expandedcontent2';
	
	if (contentURL == "") {
		contentURL = 'blank.html';
		expandedContentURL = 'blank.html';
	}
	
	/*
	 * Refresh the iFrame
	 */
	setTimeout('Load_Iframe(\'messagecontentiframe\', \'' + contentURL + '\')', 500);
	
	/*
	 * Update the Expand link
	 */
	document.getElementById('expandlink').onclick=function () { Open_Iframe_In_Browser(expandedContentURL); };
	
	/*
	 * Go straight to part 7
	 */
	Raise_Popup_DIV_Message_7(completionObject);		
}
/*
 * Raise the popup div for a message (part 5)
 */
function Raise_Popup_DIV_Message_5(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	var results = completionObject.results;
	var messageBody = completionObject.messageBody;
	var variablesSelectionControl =	completionObject.variablesSelectionControl;
	var tablesSelectionControl = completionObject.tablesSelectionControl;

	/*
	 * Split the content into an array (contentid, content name, selected)
	 */
	var contentList = results.split('\n');
	var count = 0;
	var loopControl = "";
	var contentSelectionControl = '<font color=#999999>No content available</font>';
	var options = '<option value=0>Select Content</option>';

	var hasMessageContent = false;
	
	/*
	 * Enumerate the content from the array and construct the options list
	 */
	var semantics;
	var has_content_selected = false;
	for (i in contentList) {
	    /*
	     * First row is special, contains semantics like whether or not looping
	     */
	    if (i == 0) {
	         semantics = contentList[i].split("\t");
	        continue;
	    }
		if (contentList[i] == '')
			continue;
		
		var IdValuePair = contentList[i].split("\t");
		
		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		options += '<option value="' + IdValuePair[0] + '" ' + (IdValuePair[2] != 0 ? ' SELECTED' : '') + ' >' + optionText + '</option>';

		if (IdValuePair[2] != 0)
		    has_content_selected = true;
		    
		count++;
		
		if (IdValuePair[2] != 0) 	
			hasMessageContent = true;
	}
	
	/*
	 * If there is any content, then construct the selection dropdown control.  Also, display
	 * an option for making the content repeatable.
	 */
	if (count > 0) {
		contentSelectionControl = 
		  '<span style=padding-left:0px;></span><select onchange=Content_Selection_Changed() id=contentcontrol style=font-size:9pt;width:200px;>' +
		  options +
		  '</select>';

		loopControl = "<span title=\"Loop is only meaningful for videos.\"><input " + (semantics == "1" ? " CHECKED " : "") + " style=height:10px;width:10px;position:relative;top:-3px; " + (has_content_selected ? "" : "disabled=true") + " type=checkbox id=loop>&nbsp;<span id=loopLabel style=color:#999999;>Loop</span></span>";
		if (has_content_selected)
		    loopControl = loopControl.replace(/#999999/g, "#ffffff");
	}
	
	/*
	 * Retain context
	 */
	completionObject.contentSelectionControl = contentSelectionControl;
	completionObject.loopControl = loopControl;
	
	/*
	 * If there is message-specific content, then get the URL and refresh the message content iframe
	 */
	if (hasMessageContent) {
		/*
		 * Get message content
		 */
		parameters = new Object;
		parameters['messageid'] = node.messageid;
	
		completionObject.AjaxCompletion = Raise_Popup_DIV_Message_6;
		
		Ajax_Call_Web_Method_async('GetMessageContentURL', parameters, completionObject);
	} else {
		/*
		 * No message content 
		 */
		 
		/*
		 * Refresh the iFrame
		 */
		setTimeout('Load_Iframe(\'messagecontentiframe\', \'blank.html\')', 500);
		
		/*
		 * Update the Expand link
		 */
		document.getElementById('expandlink').onclick=function () { Open_Iframe_In_Browser('blank.html'); };
		
		/* 
		 * Go to part 7
		 */
		Raise_Popup_DIV_Message_7(completionObject);		
	}
}

/*
 * Raise the popup div for a message (part 4)
 */
function Raise_Popup_DIV_Message_4(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	var results = completionObject.results;
	var messageBody = completionObject.messageBody;
	var variablesSelectionControl =	completionObject.variablesSelectionControl;
	
	/*
	 * Split the tables into an array
	 */
	var tablesList = results.split('\n');
	var count = 0;
	var tablesSelectionControl = '';
	var options = '<option>Insert Table</option>';
	
	/*
	 * Enumerate the tables from the array and construct the options list
	 */
	for (i in tablesList)
	{
		if (tablesList[i] == '')
			continue;
		
		var IdValuePair = tablesList[i].split("\t");
		
		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		options += '<option value="' + IdValuePair[0] + '">' + optionText + '</option>';
		
		count++;
	}
	
	/*
	 * If there are any tables, then construct the selection dropdown control
	 */
	if (count > 0) {
		tablesSelectionControl = 
		  '<span style=padding-left:10px;></span><select id=tablesinsertcontrol ' +
		  ' onchange="javascript:Insert_Table_Into_Message_Body(this, document.getElementById(\'messagebody\'));">' +
		  options +
		  '</select>';
	}

	/*
	 * Get the list of content and place them into a selection control that
	 * can be used to relate the content to the message body
	 */
	var parameters = new Object;
	parameters['messageid'] = node.messageid;
	
	completionObject.tablesSelectionControl = tablesSelectionControl;
	completionObject.AjaxCompletion = Raise_Popup_DIV_Message_5;
	
	Ajax_Call_Web_Method_async('EnumerateContentByMessage', parameters, completionObject);
}
/*
 * Raise the popup div for a message (part 3)
 */
function Raise_Popup_DIV_Message_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	var results = completionObject.results;
	var messageBody = completionObject.messageBody;
	 
	/*
	 * Split the variables into an array
	 */
	var variablesList = results.split('\n');
	var count = 0;
	var variablesSelectionControl = '';
	var options = '<option>Insert Variable</option>';
	
	/*
	 * Enumerate the variables from the array and construct the options list
	 */
	var RegistrationVars = 0;
	
	var CheckUniqueVariableId = new Object;
	
	for (i in variablesList)
	{
		if (variablesList[i] == '')
			continue;
			
		/*
		 * Parse the variableid, variable name
		 */
		var IdValuePair = variablesList[i].split("\t");
		
		/*
		 * Do a uniqueness check on the variable id
		 */
		if (IdValuePair[0] > 0) {
			if (CheckUniqueVariableId[IdValuePair[0]] == true)
				continue;
			CheckUniqueVariableId[IdValuePair[0]] = true;
		}
		
		/*
		 * Encode special characters <>
		 */
		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		/*
		 * If this is the first registration variable, add a delimiter
		 */
		if (IdValuePair[0] < 0) 
			RegistrationVars++;
		
		var optionColor = '';
		
		if (RegistrationVars == 1) {
			/*
			 * Registration header
			 */
			options += '<option style=background-color:#cccccc;color:black; value=0>Registration:</option>';
			
		} else if (IdValuePair[0] == 0) {
			/*
			 * Some other header (Application Variables, Domain Variables etc)
			 */
			optionColor = '#cccccc';
		}
		/*
		 * Add this option
		 */
		options += '<option style=background-color:' + optionColor + '; value="' + IdValuePair[0] + '">' + optionText + '</option>';
		
		count++;
	}
	
	/*
	 * If there are any variables, then construct the selection dropdown control
	 */
	if (count > 0) {
		variablesSelectionControl = 
		  '<span style=padding-left:10px;></span><select id=variablesinsertcontrol ' +
		  ' onchange="javascript:Insert_Variable_Into_Message_Body(this, document.getElementById(\'messagebody\'));">' +
		  options +
		  '</select>';
	}

	/*
	 * Get the list of tables and place them into a selection control that
	 * can be used to insert tables into the message body
	 */
	var parameters = new Object;
	parameters['messageid'] = node.messageid;

	completionObject.AjaxCompletion = Raise_Popup_DIV_Message_4;
	completionObject.variablesSelectionControl = variablesSelectionControl;

	Ajax_Call_Web_Method_async('EnumerateTablesByMessage', parameters, completionObject);

}
/*
 * Raise the popup div for a message (part 2)
 */
function Raise_Popup_DIV_Message_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	var popup = completionObject.popup;
	var node = completionObject.node;
	 
	var messageBody = completionObject.results;
	
	messageBody = messageBody.replace(/"/g, '&quot;');
	messageBody = messageBody.replace(/</g, '&lt;');
	messageBody = messageBody.replace(/>/g, '&gt;');
	
	/* 
	 * Retain the message body in the context
	 */
	completionObject.messageBody = messageBody;
	
	/*
	 * Get the list of variables and place them into a selection control that
	 * can be used to insert variables into the message body
	 */
	var parameters = new Object;
	parameters['messageid'] = node.messageid;
	
	completionObject.AjaxCompletion = Raise_Popup_DIV_Message_3;
	
	Ajax_Call_Web_Method_async('EnumerateVariablesByMessage', parameters, completionObject);

}
/*
 * Raise the popup div for a message
 */
function Raise_Popup_DIV_Message(id)
{
	try {
		/*
		 * Display the popup div
		 */
		isMSIE = navigator.appName.indexOf('Microsoft') >= 0;
		var popup = document.getElementById('popupdiv');
		popup.style.top="250px";
		popup.style.width="600px";
		popup.style.left="90px";
		popup.style.height="400px";
		popup.style.backgroundColor="#3a3a3a";
		popup.style.borderWidth="1px";
		popup.style.borderColor="white";
		popup.style.borderStyle="solid";
		
		/*
		 * Allow full height for map
		 */
		document.getElementById('mapViewContainer').style.height='475px';
		
		var node = document.getElementById('node'+id).node;
	
		/*
		 * Store parameters into completion context
		 */
		var completionObject = new Object;
		completionObject.AjaxCompletion = Raise_Popup_DIV_Message_2;
		completionObject.id=id;
		completionObject.popup=popup;
		completionObject.node=node;
		completionObject.messageid = node.messageid;

		/*
		 * Get the message body 
		 */
		var parameters = new Object;
		parameters['messageid'] = node.messageid;
		
		Ajax_Call_Web_Method_async('GetMessageBody', parameters, completionObject);
		
	} 
	catch (ex) 
	{
		alert('Failed to connect to the server.  Please try again. ' + ex);
	}
}
/*
 * Populate the answers list in the Edit Question panel (part 3)
 */
function Populate_Answers_List_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var answerslistdiv = completionObject.answerslistdiv;
	var count = completionObject.count;
	var isMultipleChoice = completionObject.isMultipleChoice;
	
	if (count > 0) {
		/*
		 * There is at least one answer
		 */
		if (isMultipleChoice) {
			/*
			 * Since this is a multiple choice question, enable Add Answer
			 */
			document.getElementById('AddAnswerButton0').disabled=gReadOnly; // should be disabled if readonly
			document.getElementById('AnswerText').style.display='block';
			document.getElementById('AnswerText2').style.display='block';
			document.getElementById('AnswerText3').style.display='block';
			document.getElementById('answertitle').value='';
		} else {
			document.getElementById('AddAnswerButton0').disabled=true;
			document.getElementById('AnswerText').style.display='block';
			document.getElementById('AnswerText2').style.display='block';
			document.getElementById('AnswerText3').style.display='block';
			document.getElementById('answertitle').value='';
		}
	} else {
		/*
		 * Currently no answers, enable Add Answer
		 */
		document.getElementById('AddAnswerButton0').disabled=false;
		if (isMultipleChoice) {
			/*
			 * This is multiple choice, so reset answer title and display the answer title
			 */
			document.getElementById('answertitle').value='';
			document.getElementById('AnswerText').style.display='block';
			document.getElementById('AnswerText2').style.display='block';
			document.getElementById('AnswerText3').style.display='block';
		} else {
			/*
			 * This is NOT multiple choice, so set answer title to default and hide it
			 */
			document.getElementById('answertitle').value='';
			document.getElementById('AnswerText').style.display='block';
			document.getElementById('AnswerText2').style.display='block';
			document.getElementById('AnswerText3').style.display='block';
		}
	}

	/*
	 * If vertical content too much, then force a vertical scroll bar.  This fixes an IE bug
	 */
	answerslistdiv.style.overflowY='scroll';	
}

/*
 * Display the auto-answer iframe
 */
function Display_Auto_Answer_Iframe(answerid)
{
	/*
	 * Get the iframe object
	 */
	var iFrameElement = document.getElementById('autoansweriframe');
	
	if (iFrameElement == null)
		return;
	var iFrameDoc = Get_Iframe_Doc(iFrameElement);
	
	iFrameElement.style.visibility='visible';
	iFrameElement.style.display='block';
	
	/*
	 * Construct the url
	 */
	var url = 'autoanswerrules.php?sessionid=' + ajax_sessionid + '&sessionkey=' + ajax_sessionkey + '&answerid=' + answerid;
	
	iFrameDoc.location = url;
}
/*
 * Populate the answers list in the Edit Question panel (part 2)
 */
function Populate_Answers_List_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var answerslistdiv = completionObject.answerslistdiv;
	
	/*
	 * Truncate the div
	 */
	answerslistdiv.innerHTML = '';
	var table = document.createElement('table');
	table.width='95%';
	answerslistdiv.appendChild(table);
	
	/*
	 * Column header
	 */
	var row = table.insertRow(table.rows.length);

	var cell = row.insertCell(row.cells.length);
	cell.className='answersListHeader';
	cell.innerHTML='&nbsp;';
	
	cell = row.insertCell(row.cells.length);
	cell.className='answersListHeader';
	cell.innerHTML='Answer';
	
	cell = row.insertCell(row.cells.length);
	cell.className='answersListHeader';
	cell.innerHTML='<nobr>Link To Message</nobr>';
	
	cell = row.insertCell(row.cells.length);
	cell.className='answersListHeader';
	cell.innerHTML='Variables';
	
	cell = row.insertCell(row.cells.length);
	cell.className='answersListHeader';
	cell.innerHTML='&nbsp;';
	
	
	/*
	 * Parse the string into an array (answerid, answertitle, messagetitle, variablename)
	 */
	var answerList = completionObject.results.split('\n');
	var count = 0;
	for (i in answerList)
	{	
		/*
		 * Add this to the list
		 */
		var answerInfo = answerList[i].split('\t');
		if (answerInfo.length == 5) {
			row = table.insertRow(table.rows.length);
			row.vAlign='top';
			
			/* row count */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<font style=font-size:8pt;>' +(count+1) + '.</font>';
			
			/* answer title */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<font style=font-size:8pt;>' + answerInfo[1] + '</font>';
			
			/* message title */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<div style=width:200px;font-size:8pt;width:150px; class=messageMouseOut>' + answerInfo[2] + '</div>';
			
			/* variable name */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<font style=font-size:8pt;>' + answerInfo[3].replace(/,/g,',<br>') + '</font>';
			cell.valign='center';
			
			/* Has auto answer rules */			
			var hasAutoAnswerRules = answerInfo[4] > 0;
			var autoAnswerRulesBoldOn = "";
			var autoAnswerRulesBoldOff = "";
			
			/* If auto answer disabled for this question, then change the font */
			var autoAnswerQuestionDisabled = "";
			var autoAnswerQuestionLinkFontColor = "blue";
			var autoAnswerJustReturn = "";

			if (answerInfo[4] < 0) {
				autoAnswerQuestionDisabled = " DISABLED ";
				autoAnswerQuestionLinkFontColor = "#999999";
				autoAnswerJustReturn = " alert(\'Auto-answer rules are only supported for multiple-choice questions.\'); return; ";
			}
			
			var autoAnswerDisplayLinkLabel = '';
			var autoAnswerDisplayLinkPipe = '';
			if (gAuto_Answer_Selection_Enabled == true) {
				autoAnswerDisplayLinkLabel = 'Auto';
				autoAnswerDisplayLinkPipe = ' | ';
			} 
			
			if (hasAutoAnswerRules == true) {
				autoAnswerRulesBoldOn = "<b>";
				autoAnswerRulesBoldOff = "</b>";
			}
			/* Edit | Up | Down | Delete */
			cell = row.insertCell(row.cells.length);
			
			var answerTitle = answerInfo[1].replace(/'/g,' ');
			
			if (gReadOnly == false) {
				cell.innerHTML=
				  "" + 
				  /* Edit */
				  "<nobr><a href=javascript:void(0); title=\"Edit this answer.\"" +
				  " onclick=\"javascript:  " +
				  "   if (Ajax_In_Use) return; " +
				  "   Edit_Answer_New(" + answerInfo[0] + ", " + questionid + "); " +  
				  " \"><font style=font-size:8pt;color:blue;>Edit</font></a><font style=font-size:8pt; color=#999999> | </font>" +
				  /* Auto */
				  "<a href=javascript:void(0); title=\"Configure auto-answer rules.\" " + autoAnswerQuestionDisabled + 
				  " onclick=\"javascript:" + autoAnswerJustReturn + 
				  "   if (Ajax_In_Use) return; " +
				  "   Display_Auto_Answer_Iframe(" + answerInfo[0] + "); " +  
				  " \"><font style=font-size:8pt;color:" + autoAnswerQuestionLinkFontColor + ";>" 
				  + autoAnswerRulesBoldOn 
				  + "<span id=autoanswerlinkdiv" + answerInfo[0] + ">" + autoAnswerDisplayLinkLabel + "</span>"
				  + autoAnswerRulesBoldOff + 
				 "     </font></a><font style=font-size:8pt; color=#999999>" + autoAnswerDisplayLinkPipe + "</font>" +
				  /* Copy */
				  "<a href=javascript:void(0); title=\"Select this answer to be copied.\" " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Copied_answerid = " + answerInfo[0] + "; " +  
				  "   document.getElementById('pasteAnswerButton').disabled=false; " +
				  "   alert('You may now add a copy of this answer to this question or any another question within this application.\\r\\nTo add a copy, use the Paste link in the Edit Question panel.'); " +
				  " \"><font color=blue>Copy</font></a><font style=font-size:8pt; color=#999999> | </font>" +
				  /* Up */
				  "<a href=javascript:void(0); title=\"Move this answer up in the list.\" " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Move_Answer_Up(" + answerInfo[0] + ", " + questionid + "); " +  
				  " \"><font style=font-size:8pt;color:blue;>Up</font></a><font style=font-size:8pt; color=#999999> | </font>" +
				  /* Down */
				  "<a href=javascript:void(0); title=\"Move this answer down in the list.\" " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Move_Answer_Down(" + answerInfo[0] + ", " + questionid + "); " +  
				  " \"><font style=font-size:8pt;color:blue;>Down</font></a><font style=font-size:8pt; color=#999999> | </font>" +
				  /* Delete */
				  "<a href=javascript:void(0); title=\"Delete this answer from the list.\"" +
				  " onclick=\"javascript: " +
				  "   if (Ajax_In_Use) return; " +
				  "   if (confirm('Delete answer: " + answerTitle + "') == true) { " +
				  "       Delete_Answer(" + questionid + ", " + answerInfo[0] + "); " +  
				  "   }" +
				  " \"><font  style=font-size:8pt;color:blue;>Delete</font></a>" +
				  "</nobr>";
			}
			count++;
		}
	}

	/*
	 * Retain context
	 */
	completionObject.count = count;
	
	/*
	 * If this question has at least one answer, then determine whether this question should be 
	 * allowed to have more than one answer.  If not, then disable the Add Answer button
	 */
	completionObject.AjaxCompletion = Populate_Answers_List_3;
	
	Question_Is_Multiple_Choice(questionid, completionObject);
}

/*
 * Populate the answers list in the Edit Question panel
 */
function Populate_Answers_List(questionid, answerslistdiv)
{
	/*
	 * Call the server to get the list of answers for this question
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;

	var completionObject = new Object;
	completionObject.questionid = questionid;
	completionObject.answerslistdiv = answerslistdiv;
	completionObject.AjaxCompletion = Populate_Answers_List_2;

	Ajax_Call_Web_Method_async('EnumerateAnswersByQuestion', parameters, completionObject);

}
/*
 * Populate the questions list in the Edit Message panel (part 2)
 */
function Populate_Questions_List_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var messageid = completionObject.messageid;
	var questionslistdiv = completionObject.questionslistdiv;
	var caller_completionObject = completionObject.caller_completionObject;
	var table = completionObject.table;
	
	var questionList = completionObject.results.split('\n');
	
	/*
	 * Parse the string into an array (questionid, questiontitle, questiontype)
	 */
	var count = 1;
	for (i in questionList)
	{	
		/*
		 * Add this to the list
		 */
		var questionInfo = questionList[i].split('\t');
		if (questionInfo.length == 4) {
			row = table.insertRow(table.rows.length);
			
			/* row count */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<font style=font-size:8pt;>' + count + '</font>.';
			
			/* question title */
			cell = row.insertCell(row.cells.length);
			cell.innerHTML='<div style=padding-right:10px;><div style=width:250px;font-size:8pt; class=questionMouseOut>' + questionInfo[1] + '</div></div>';
			
			/* question type */
			cell = row.insertCell(row.cells.length);			
			cell.innerHTML='<font style=font-size:8pt;>' + questionInfo[2] + '</font>';
					
			/* Edit | Up | Down | Delete */
			cell = row.insertCell(row.cells.length);
			
			var questionTitle = questionInfo[1].replace(/'/g,'\\\'');
			
			var deleteLink_title = "Delete";
			var downLink_title = "Down";
			var font_size = "8pt";
		
			if (gServer_Admin) {
				deleteLink_title = "Del";
				downLink_title = "Dn";
				font_size = "7.5pt";
			}


			if (gReadOnly == false) {
				cell.innerHTML=
				  /* Edit */
				  "<nobr><a href=javascript:void(0); title=\"Edit this question.\"" +
				  " onclick=\"javascript:  " +
				  "   Edit_Question(" + questionInfo[0] + ");return false; " +  
				  " \"><font style=font-size:" + font_size + ";color:blue;>Edit</font></a><font style=font-size:" + font_size + "; color=#999999> | </font>" +
				  /* Up */
				  "<a href=javascript:void(0); title=\"Move this question up in the list.\" " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Move_Question_Up(" + questionInfo[0] + ", " + messageid + ");return false; " +  
				  " \"><font style=font-size:" + font_size + ";color:blue;>Up</font></a><font style=font-size:" + font_size + "; color=#999999> | </font>" +
				  /* Down */
				  "<a href=javascript:void(0); title=\"Move this question down in the list.\" " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Move_Question_Down(" + questionInfo[0] + ", " + messageid + ");return false; " +  
				  " \"><font style=font-size:" + font_size + ";color:blue;>" + downLink_title + "</font></a><font style=font-size:" + font_size + "; color=#999999> | </font>";

				cell.innerHTML += 
				  /* Delete */
				  "<a href=javascript:void(0); title=\"Delete this question from the list.\"" +
				  " onclick=\"javascript: " +
				  "   if (Ajax_In_Use) return; " +
				  "   if (confirm('Delete question: " + questionTitle + "') == true) { " +
				  "       Delete_Question_By_QuestionID(" + questionInfo[0] + ");return false; " +  
				  "   }" +
				  " \"><font  style=font-size:" + font_size + ";color:blue;>" + deleteLink_title + "</font></a>";
				  
				cell.innerHTML += 
				  "</nobr>";
				  
				if (gServer_Admin) {
				  var title;
				  if (questionInfo[3] == "0")
				  	title = "Click to make this question a pattern";
				  else
				  	title = "This question is a pattern";
				  cell.innerHTML += 
				  /* Pattern */
				  "<font style=font-size:" + font_size + "; color=#999999> | </font>" +
				  "<a href=javascript:void(0); title=\"" + title + "\" style=font-weight:" + (questionInfo[3] == "0" ? "normal" : "bold"  ) + "; " +
				  " onclick=\"javascript:" +
				  "   if (Ajax_In_Use) return; " +
				  "   Toggle_Question_Pattern_Semantics(" + questionInfo[0] + ", " + messageid + ", this);return false; " +  
				  " \"><font style=font-size:" + font_size + ";color:blue;>Pattern</font></a>";
				}
			}
		}
		count++;
	}

	/*
	 * If more than 5 questions, then force scrolling
	 */
	if (parseInt(count) > 5) {
		questionslistdiv.style.overflow='scroll';
	}
	
	/*
	 * Do caller completion
	 */
	if (caller_completionObject != null) {
		caller_completionObject.AjaxCompletion(caller_completionObject);
	}
}
/*
 * Populate the questions list in the Edit Message panel
 */
function Populate_Questions_List(messageid, questionslistdiv, caller_completionObject)
{
	/*
	 * Truncate the div
	 */
	questionslistdiv.innerHTML = '';
	var table = document.createElement('table');
	table.width='100%';
	questionslistdiv.appendChild(table);
	
	/*
	 * Column header
	 */
	var row = table.insertRow(table.rows.length);

	var cell = row.insertCell(row.cells.length);
	cell.className='questionsListHeader';
	cell.innerHTML='&nbsp;';
	
	cell = row.insertCell(row.cells.length);
	cell.className='questionsListHeader';
	cell.innerHTML='Question';
	
	cell = row.insertCell(row.cells.length);
	cell.className='questionsListHeader';
	cell.innerHTML='<nobr>Type</nobr>';
	
	cell = row.insertCell(row.cells.length);
	cell.className='questionsListHeader';
	cell.innerHTML='&nbsp;';
	
	/*
	 * Call the server to get the list of questions for this message
	 */
	var parameters = new Object;
	parameters['messageid'] = messageid;

	var completionObject = new Object;
	completionObject.questionslistdiv = questionslistdiv;
	completionObject.messageid = messageid;
	completionObject.AjaxCompletion = Populate_Questions_List_2;
	completionObject.caller_completionObject = caller_completionObject;
	completionObject.table = table;

	Ajax_Call_Web_Method_async('EnumerateQuestionsByMessage', parameters, completionObject);
	
}

/*
 * Get the variables list for a question (part 2)
 */
function Get_Variables_List_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var caller_completionObject = completionObject.caller_completionObject;
	
	/*
	 * Post results to caller
	 */
	caller_completionObject.variableList = completionObject.results.split('\n');
	caller_completionObject.AjaxCompletion(caller_completionObject);
}

/*
 * Get the variables list for a question
 */
function Get_Variables_List(questionid, caller_completionObject)
{
	/*
	 * Call the server to get the list of variables for this question
	 */
	var parameters = new Object;
	parameters['questionid'] = questionid;
	
	var completionObject = new Object;
	completionObject.questionid = questionid;
	completionObject.AjaxCompletion = Get_Variables_List_2;
	completionObject.caller_completionObject = caller_completionObject;

	Ajax_Call_Web_Method_async('EnumerateVariablesByQuestion', parameters, completionObject);

}
/*
 * Populate the variables dropdown given an question id
 */
function Populate_Variables_Dropdown(questionid, selectionControls, variableList)
{
	/*
	 * Truncate the selection controls
	 */
	for (i in selectionControls) { 
		selection = selectionControls[i];
		selection.length=1; 
	}
	
	for (i in variableList)
	{	
		/*
		 * Add this to the list
		 */
		var variableInfo = variableList[i].split(',');
		if (variableInfo.length == 2) {
			for (j in selectionControls) { 
				selection = selectionControls[j];
				var newIndex = selection.length;
				selection.options[newIndex] = new Option(variableInfo[1], variableInfo[0], false, false);
				
				/*
				 * Special background for section delimiters
				 */
				if (variableInfo[0] == 0) {
					selection.options[newIndex].style.color='white';
					selection.options[newIndex].style.backgroundColor='#666666';
				}
					
			}
		}
	}
}

/*
 * Do a page refresh
 */
function Do_Page_Refresh(appendString)
{
	var href = window.location.href;

	/*
	 * Remove editquestionid
	 */
	var index = href.indexOf('&editquestionid=');
	if (index >= 0)
		href = href.substr(0, index);
	
	/*
	 * Remove editmessageid
	 */
	index = href.indexOf('&editmessageid=');
	if (index >= 0)
		href = href.substr(0, index);

	/*
	 * Remove copyanswerid
	 */
	index = href.indexOf('&copyanswerid=');
	if (index >= 0)
		href = href.substr(0, index);

	/*
	 * Remove copyquestionid
	 */
	index = href.indexOf('&copyquestionid=');
	if (index >= 0)
		href = href.substr(0, index);

	/*
	 * If there is a paste question, then retain it in the URL
	 */
	if (Copied_questionid != null) {		
		appendString += "&copyquestionid=" + Copied_questionid;		
	}
	/*
	 * If there is a paste answer, then retain it in the URL
	 */
	if (Copied_answerid != null) {
		appendString += "&copyanswerid=" + Copied_answerid;		
	}
	 
	/*
	 * Append the string to the URL
	 */
	href += appendString;
	
	/*
	 * Execute the page transition
	 */
	window.location.href = href;
}
/*
 * Edit question
 */
function Edit_Question(questionid)
{
	/*
	 * Do a page transition
	 */
	Do_Page_Refresh('&editquestionid=' + questionid);
	
}
/*
 * Get the email templates that are available (part 3)
 */
function Get_Email_Selection_Control_3(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	var emailid = completionObject.emailid;
	var caller_completionObject = completionObject.caller_completionObject;	
	
	/*
	 * Split the email into an array
	 */
	var emailList = Get_Email_Selection_Control_RESULTS.split('\n');
	var count = 0;
	var emailSelectionControl = '';
	var emailSelectionControl2 = '';
	var options = '<option value=0>None</option>';
	
	/*
	 * Enuerate the email from the array and construct the options list
	 */
	for (i in emailList)
	{
		if (emailList[i] == '')
			continue;
		var IdValuePair = emailList[i].split("\t");
		
		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		options += '<option ' + (emailid == IdValuePair[0] ? " SELECTED " : "") +
				   ' value="' + IdValuePair[0] + '">' + optionText + '</option>';
			
		count++;
	}
	
	/*
	 * If there are any email, then construct the selection dropdown control
	 */
	if (count > 0) {
		emailSelectionControl = 
		  '<span style=padding-left:10px;></span><select id=emailid ' +
		  '> ' +
		  options +
		  '</select>';
		emailSelectionControl2 = 
		  '<span style=padding-left:10px;></span><select id=emailid2 ' +
		  '> ' +
		  options +
		  '</select>';
	} else {
		emailSelectionControl = 
		  '<span style=padding-left:10px;></span><select disabled id=emailid> ' +
		  '<option value=0>Email not configured for this application</option>' +
		  '</select>';
		emailSelectionControl2 = 
		  '<span style=padding-left:10px;></span><select disabled id=emailid2> ' +
		  '<option value=0>Email not configured for this application</option>' +
		  '</select>';
	}
	
	/*
	 * Store the completion value into the context
	 */
	caller_completionObject.emailSelectionControl = emailSelectionControl;
	caller_completionObject.emailSelectionControl2 = emailSelectionControl2;
	
	/*
	 * Call the caller's completion routine
	 */
	caller_completionObject.AjaxCompletion(caller_completionObject);
}

/*
 * Get the email templates that are available (part 2)
 */
function Get_Email_Selection_Control_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	Get_Email_Selection_Control_RESULTS = completionObject.results;

	/*
	 * Go to step 3
	 */
	Get_Email_Selection_Control_3(completionObject);
}

/*
 * Get the email templates that are available
 */
var Get_Email_Selection_Control_RESULTS = null;

function Get_Email_Selection_Control(questionid, emailid, caller_completionObject)
{
	/*
	 * Retain context
	 */
	var completionObject = new Object;
	completionObject.questionid = questionid;
	completionObject.emailid = emailid;
	
	completionObject.caller_completionObject = caller_completionObject;
		
	/*
	 * If we don't already have this information, then get the list of email templates and place them into a selection control 
	 */
	if (Get_Email_Selection_Control_RESULTS == null) {
		var parameters = new Object;
		parameters['questionid'] = questionid;
	
		completionObject.AjaxCompletion = Get_Email_Selection_Control_2;
		
		Get_Email_Selection_Control_RESULTS = Ajax_Call_Web_Method_async('EnumerateEmailByQuestion', parameters, completionObject);
		
		return;
	} 
	
	/*
	 * Go straight to step 3
	 */
	Get_Email_Selection_Control_3(completionObject);
}

/*
 * Raise the popup div for a question (part 2)
 */
function Raise_Popup_DIV_Question_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var id = completionObject.id;
	
	/*
	 * Get popup object
	 */
	isMSIE = navigator.appName.indexOf('Microsoft') >= 0;
	var popup = document.getElementById('popupdiv');
	popup.style.top="400px";
	popup.style.width="712px";
	if (isMSIE) {
		popup.style.left="10px";
	} else {
		popup.style.left="8px";
	}

	popup.style.height="408px";
	popup.style.borderWidth="1px";
	popup.style.borderColor="white";
	popup.style.borderStyle="solid";

	popup.style.backgroundColor="#3a3a3a";

	/*
	 * Get the node object for this question
	 */
	var node = document.getElementById('node'+id).node;

	/*
	 * Get the question type from the node object
	 */
	var questionType = node.questionType;

	/*
	 * Compute preselection
	 */
	var questionType1Selected = questionType == 1 ? ' selected ' : ' ';
	var questionType2Selected = questionType == 2 ? ' selected ' : ' ';
	var questionType3Selected = questionType == 3 ? ' selected ' : ' ';
	var questionType4Selected = questionType == 4 ? ' selected ' : ' ';
	var questionType6Selected = questionType == 6 ? ' selected ' : ' ';
	/*
	 * If readonly, then disable the apply button
	 */
	var Apply_Disabled = '';
	addVariableAssignmentDisabled = ' DISABLED ';
	if (gReadOnly == true) {		
		Apply_Disabled = ' DISABLED ';
	}
	
	/*
	 * Determine if this is an advanced user
	 */	
	if (gAdvanced_Programming_User == true) {
		addVariableAssignmentDisabled = '';
	}		

	/*
	 * Determine whether paste-answer is disabled
	 */
	pasteAnswerDisabled = " DISABLED ";
	if (Copied_answerid != null)
		pasteAnswerDisabled = " ";
		
	/*
	 * Raise the popup
	 */
	var innerHTML=/* Header */
					'<div class=popupHeader style=background-color:yellow;color:black;>'+
					/* Masthead title */
					'<table width=100% cellpadding=0 cellspacing=0><tr align=left><td>Edit Question</td><td align=right style=padding-right:15px;>' +
					/* Copy link */
					'<a style=color:blue; href=javascript:void(0); ' +
					' onclick="document.getElementById(\'popupdiv\').style.display=\'none\'; ' +
					' document.getElementById(\'mapViewContainer\').style.height=\'475px\';' +
					' if (Ajax_In_Use) return; ' +
					' Store_QuestionID_Into_Copy_Buffer(' + id + ');' +
					' ">' +
					'Copy</a>&nbsp;<span style=font-size:7.5pt;color:#666666;font-weight:normal;position:relative;top:-1px;>|</span>&nbsp;' +
					/* Close link */
					'<a style=color:blue; href=javascript:void(0); ' +
					' onclick="document.getElementById(\'popupdiv\').style.display=\'none\'; ' +
					' document.getElementById(\'mapViewContainer\').style.height=\'475px\';' +
					/* Turn off selection-mode for the tree */
					'  Display_Notification_DIV(\'\', \'none\'); ' +
					'  gSelecting_Message_From_Map_Title=null; ' + 
					'  document.getElementById(\'answermessagepicklistselect\').disabled=true; '+
					' ">' +
					'Close</a>' +
					'</td></tr></table>' +
					'</div>' +
					'<div style=padding-top:20px;padding-left:10px;>' +
					/* Edit question title */
					'<table cellpadding=0 cellspacing=0><tr valign=top>' +
					'<td>Title:<br><input type=text ' +
					' class=textInput style=width:300px; name=questiontitle id=questiontitle value="'  + node.title + '"></td>' +
					/* Edit question type */
					'<td style=padding-left:10px;>Type:<br><select id=questiontype name=questiontype ' +
						/* onChange for question type TURNED OFF FOR NOW */
				    '   onchange="javascript: return;' +
					'     document.getElementById(\'LinkToMessageDIV\').style.display = this.options[this.selectedIndex].value == 6 ? \'block\' : \'none\'; ' +
					'   "' +
					' >'+
					'<option ' + questionType1Selected + ' value=1>Multiple Choice</option>' +
					'<option ' + questionType3Selected + ' value=3>Text: Multiple Lines</option>' +
					'<option ' + questionType4Selected + ' value=4>Text: Single Line</option>' +
					'<option ' + questionType6Selected + ' value=6>Form</option>' +
					'</select></td>' +
					/* Apply button */
					'<td valign=bottom style=padding-left:10px;><input type=button value="Update" style=width:60px; ' + Apply_Disabled + 
					' onclick="javascript:' +
					'  if (Ajax_In_Use) return; ' +
					'  if (document.getElementById(\'questiontitle\').value.length == 0) {alert(\'Question title is required.\');return;} ' +
					'  var questiontype = document.getElementById(\'questiontype\');' +
					/* Update question type */
					'  Update_Question_Type(' + id + ', questiontype.options[questiontype.selectedIndex].value); ' + 
					
					'"></td>' +
					/* 
					 * Delete question button 
					 */
					'<td valign=bottom style=padding-left:37px;>' +
					'<input type=button value="Delete Question" ' + Apply_Disabled +
					' onclick="javascript:if (Ajax_In_Use) return; ' +
					'          if (confirm(\'Delete this question?\') == false) return false;Delete_Question(' + id + ');" ' + 
					'></td>' +
					/* End of question data */
					'</tr></table><br>' +
					'</div></div></div></div>' +
					/* Link to message DIV, used for Forms */
					'<div id=LinkToMessageDIV style=padding-bottom:10px;padding-left:10px;display:none;>' +
					'<div style=padding:3px;border-style:solid;border-color:white;border-width:1px;width:644px;>' +
					'<table><tr align=left valign=bottom>' +
					'<td >' +
					' <b>Link To Message: </b><br>' +
					'<nobr><input type=radio checked  name=answermessageid value=0 id=answermessagenew ' +
					' onclick="document.getElementById(\'answermessagepicklistselect\').selectedIndex=0; ' +
					'  document.getElementById(\'selected_messageid\').value = 0; ' +
					'  document.getElementById(\'selected_message_title\').innerHTML = \'Select from the map\'; ' +
					/* Turn off selection-mode for the tree */
					'  Display_Notification_DIV(\'\', \'none\'); ' +
					'  gSelecting_Message_From_Map_Title=null; ' + 
					'  document.getElementById(\'answermessagepicklistselect\').disabled=true;" '+
					'><label for=answermessagenew> New message </label></nobr>' +
					'</td>' + 
					/* Answer message: selected from above list */
					'<td width=1%>' +
					'<input type=radio name=answermessageid value=0 id=answermessageselected '+
					' onclick="document.getElementById(\'answermessagepicklistselect\').selectedIndex=0; ' +
					'  Display_Notification_DIV(\'Click a message to select it for this question.\', \'block\'); ' +
					'  gSelecting_Message_From_Map_Title=document.getElementById(\'selected_message_title\'); ' + 
				    '  gSelecting_Message_From_Map_Value=document.getElementById(\'selected_messageid\'); ' +
					'  gSelecting_Message_From_Map_Radio=document.getElementById(\'answermessageselected\'); ' +
					'  document.getElementById(\'answermessagepicklistselect\').disabled=true;" '+
					'></td>' +
					'<td>' + 
					'<div style=padding-left:0px;font-size:7.5pt;padding-bottom:1px;>Click below to reassign</div>' +
					'<div id=answermessageselectedtitle>' +
					/* Selected message title */
					'<label for=answermessageselected><div id=selected_message_title class=messageListFormat>Select from the map</div></label></div>' + 
					/* Hidden variable to indicate edit mode (versus add) */
					'<input type=hidden id=editmode value=0>' +
					/* Selected message id */
					'<input type=hidden id=selected_messageid value=0>' +
					'</td>' + 
					/* Question message: pick list */
					'<td  width=1%><nobr>' +
					'<input type=radio name=answermessageid value=0 id=answermessagepicklist '+
					' onclick=" ' +
					/* Turn off selection-mode for the tree */
					'   gSelecting_Message_From_Map_Title=null; ' + 
					' 	Display_Notification_DIV(\'\', \'none\'); ' +
					/* Populate the pick list */
					'   Populate_Message_Pick_List(' + node.questionid + ', \'answermessagepicklistselect\');" '+
					' >' +
					'</td><td valign=bottom style=padding-left:5px;>' +
					/* Please wait...*/
					'<div id=answermessagepicklistselectwaitdiv class=refreshWaitDIV style=display:none;>Please wait, refreshing list...</div>' +
					/* pick list dropdown */
					'<div id=answermessagepicklistselectdiv>' +
					'<select ' +
					' onchange="javascript:' +
					' if (Ajax_In_Use) return; ' +
					' if (this.options[this.selectedIndex].value == \'removeunlinkedmessages\') { ' +
					'     Remove_Unlinked_Messages(' + node.questionid + '); ' +
					' } else { ' +
					'     document.getElementById(\'selected_messageid\').value=this.options[this.selectedIndex].value; ' +
					' } ' +
					' " ' +
					' disabled id=answermessagepicklistselect class=pickList>' +
					'<option value="">Select from list</option>' +
					'</select></div>' + 
					'</nobr>' +
					'</td>' + 
					'</tr></table></div></div>' +
					/* Answers DIV */
					'<div style=padding-left:10px;><div class=answersDIV>' +
					/* Answers DIV masthead */
					'<div class=answersDIVmasthead ' +
					' style=padding-bottom:3px;><table cellpadding=0 cellspacing=0 width=100%><tr align=left valign=top>' +
					'<td>Answers:</td>' +
					'<td align=right>' +
					/* Paste answer button */
					'<input type=button value=\"Paste Answer\" id=pasteAnswerButton ' + pasteAnswerDisabled + 
					' onclick=\"javascript:' +
					/* onClick: check for ajax in use */
				    '   if (Ajax_In_Use) return; ' +
						/* Paste the answer */
					'   if (Paste_Answer(' +  node.questionid + ') == false) return; ' +
					'\">&nbsp;&nbsp;' +
					/* Add answer button */
					'<input type=button value=\"Add Answer\" id=AddAnswerButton0 ' + Apply_Disabled +
					' onclick=\"javascript:' +
					' Edit_Answer_New(0, ' +  node.questionid + ');' +
					'\">' +
					'</td>' +
					'</tr></table>' +
					/* End of answers DIV masthead */
					'</div>' +
					/* Answers list DIV */
					'<div id=answerslistdiv class=answersListDIV>' +
					/* End of answers list DIV */
					'</div>' +
					/* Terminate the answers DIV */
					'</div></div>' +
					'' +
					
	/*
	 * Terminate the popup DIV
	 */
					'</div>' +
					'';
					
	popup.innerHTML = innerHTML;
	popup.style.display='block';
	
	/*
	 * Populate the answers list
	 */
	Populate_Answers_List(node.questionid, document.getElementById('answerslistdiv'));	 
	
	/*
	 * Shrink the height for map
	 */
	document.getElementById('mapViewContainer').style.height='213px';
	
	/*
	 * Close the auto-answer iframe
	 */
	document.getElementById('autoansweriframe').style.visibility='hidden';
	document.getElementById('autoansweriframe').style.display='none';

	/*
	 * If question is a Form, then display the Link To Message DIV
	 */
	if (questionType == 6) {
		/*
		 * Display the "Link to Message:" DIV
		 */
		document.getElementById('LinkToMessageDIV').style.display='block';
		
		/*
		 * Initialize the link to message selection controls
		 */
		if (node.selected_messageid == 0) {
			/*
			 * No message assignment, yet
			 */
			document.getElementById('answermessagenew').onclick();
			
		} else {
			/*
			 * Linked to an existing message
			 */
			document.getElementById('answermessageselected').checked = true;
			
			document.getElementById('selected_message_title').innerHTML = node.selected_messageid_title;
			
			document.getElementById('selected_messageid').value = node.selected_messageid;
		}
	}
	/*
	 * Check for need to raise the edit answer iframe
	 */
	if (editanswerid > 0) {
		Edit_Answer_New(editanswerid, node.questionid);
	}
	
	
}

/*
 * Raise the popup div for a question (part 1.2)
 */
function Raise_Popup_DIV_Question_1_2(completionObject)
{
	/*
	 * Recover parameters
	 */
	var questionid = completionObject.questionid;
	
	/*
	 * Get the variables list for this question
	 */
	completionObject.AjaxCompletion = Raise_Popup_DIV_Question_2;
	
	Get_Variables_List(questionid, completionObject);
	 
}
/*
 * Raise the popup div for a question (part 1.1)
 */
function Raise_Popup_DIV_Question_1_1(completionObject)
{
	completionObject.AjaxCompletion = Raise_Popup_DIV_Question_1_2;

	Get_Advanced_User_Status(completionObject);
}

/*
 * Load the question form
 */
function GoTo_Question_Form(id)
{
	/*
	 * Get the node
	 */
	var node = document.getElementById('node'+id).node;
	
	Edit_Question(node.questionid);
	
}
/*
 * Raise the popup div for a question
 */
function Raise_Popup_DIV_Question(id)
{
	try 
	{
		/*
		 * Get the node
		 */
		var node = document.getElementById('node'+id).node;

		/*
		 * Retain context
		 */
		var completionObject = new Object;
		completionObject.id = id;
		completionObject.questionid = node.questionid;
		
		completionObject.AjaxCompletion = Raise_Popup_DIV_Question_1_2;
	
		/*
		 * Get the advanced user status
		 */
		Get_Advanced_User_Status(completionObject);
	
	} 
	catch (ex) 
	{
		alert('Failed to connect to the server.  Please try again.' + ex);
	}
}
/*
 * Arrays that store message nodes for the purpose of bubbling primary nodes to the top and in front
 */
var messageNodes_primary = null;
var messageNodes_duplicate = null;
var trace = "";
/*
 * Recurse the node tree, placing message nodes into the appropriate array
 */
function Sift_Message_Nodes(level)
{
	/*
	 * Sanity check the nesting level
	 */
	if (level > 255)
		return;
		
	/*
	 * Sort the children by display order
	 */
	this.childrenNodes.sort(function (a,b) 
							{
								if (a == null || a.displayOrder == null) return 0;
								if (b == null || b.displayOrder == null) return 0;
								else return a.displayOrder - b.displayOrder;
							});
							
	/*
	 * Enumerate the child nodes for this parent
	 */
	for (var i = 0; i < this.childrenNodes.length; i++) {
		/*
		 * Get the child node
		 */
		var child = this.childrenNodes[i];
		
		/*
		 * If this is a question node, then recurse down
		 */
		if (child.displayClass == 'question') {
			/*
			 * Question, recurse down
			 */
			child.Sift_Message_Nodes(level+1);
			
		} else if (child.displayClass == 'message') {
			/*
			 * Message, sift this node into the right list and then recurse down
			 */
			var arrayEntry = new Object();
			if (child.duplicate) {
				var index = messageNodes_duplicate.length;
				messageNodes_duplicate[ index ] = arrayEntry;
				
			} else {
				var index = messageNodes_primary.length;
				messageNodes_primary[ index ] = arrayEntry;
			}
			/*
			 * Store metadata about this child node into the array entry
			 */
			arrayEntry.node = child;
			arrayEntry.parent = this;
			arrayEntry.parentChildNodeIndex = i;
			arrayEntry.level = level;
			
			/*
			 * Recurse downward to pick up descendant nodes
			 */
			child.Sift_Message_Nodes(level+1);
		}
	}
}
/*
 * For nodes that have duplicates, move the primary to the highest level and first
 */
function Move_Duplicates_Primary_To_Top()
{
	try {
		/*
		 * Get each message node into one of two arrays.  The first array stores
		 * non-dups, the second stores message nodes that are dups.
		 */
		messageNodes_primary = new Array();
		messageNodes_duplicate = new Array();
	
		this.Sift_Message_Nodes(0);
		
		/*
		 * For each primary, find the duplicate (if any) with the lowest nesting level and then
		 * swap
		 */
		for (var i = 0; i < messageNodes_primary.length; i++) {
			/*
			 * Find the duplicate with the lowest nesting level
			 */
			var duplicate_with_lowest_level = null;
			
			for (var j = 0; j < messageNodes_duplicate.length; j++) {
				/*
				 * Skip if not the same message node
				 */
				var primary = messageNodes_primary[i];
				var duplicate =  messageNodes_duplicate[j];
				
				if (primary.node.messageid != duplicate.node.messageid)
					continue;
					
				/*
				 * Skip if the primary is at a lower level than the duplicate or is at the same level, but after it in the list
				 */
				if (primary.level < duplicate.level || (primary.level == duplicate.level && primary.parentChildNodeIndex < duplicate.parentChildNodeIndex))
					continue;
					
				if (duplicate_with_lowest_level == null || duplicate_with_lowest_level.level < duplicate.level) {
					/*
					 * Found a duplicate at a lower nesting level
					 */
					duplicate_with_lowest_level =  duplicate;
				}
			}
			
			/*
			 * If no duplicate found, then go to next message
			 */
			if (duplicate_with_lowest_level == null)
				continue;
				
			/*
			 * Swap the primary with the duplicate
			 */
			primary.parent.childrenNodes[ primary.parentChildNodeIndex ] = duplicate_with_lowest_level.node;
			duplicate_with_lowest_level.parent.childrenNodes[ duplicate_with_lowest_level.parentChildNodeIndex ] = primary.node;
		}
		 
	} catch (ex) {
		/*
		 * Exception
		 */
		alert(ex + ", trace=" + trace);
	}
	/*
	 * Free resources
	 */
	messageNodes_primary = null;
	messageNodes_duplicate = null;
	
}
/*
 * Render the map view control
 */
function Render(displayInParent)
{
	/*
	 * Create a new table
	 */
	this.table = document.createElement('table');
	var table = this.table;
	table.cellPadding=1;
	table.cellSpacing=0;
	table.border=0;
	
	/*
	 * Sort the children by display order
	 */
	this.childrenNodes.sort(function (a,b) 
							{
								if (a == null || a.displayOrder == null) return 0;
								if (b == null || b.displayOrder == null) return 0;
								else return a.displayOrder - b.displayOrder;
							});
							
	/*
	 * Add a table to the parent
	 */
	displayInParent.appendChild(table);

	for (var i = 0; i < this.childrenNodes.length; i++) {
		/*
		 * Select the image
		 */
		var child = this.childrenNodes[i];
		var openClass= '', closedClass = '';
		
		if (child.childrenNodes.length > 0) {
			/*
			 * Child node has Children
			 */
			if (i < this.childrenNodes.length-1) {
				/*
				 * Not the last node
				 */
				closedClass='ClosedHasChildrenNotLastNode';
				openClass='OpenHasChildrenNotLastNode';
			} else {
				/*
				 * Last Node
				 */
				closedClass='ClosedHasChildrenLastNode';
				openClass='OpenHasChildrenLastNode';
			}
		} else {
			/*
			 * Node has no children
			 */
			if (i < this.childrenNodes.length-1) {
				/*
				 * Not the last node
				 */
				closedClass='NoChildrenNotLastNode';
				openClass='NoChildrenNotLastNode';
			} else {
				/*
				 * Last Node
				 */
				closedClass='NoChildrenLastNode';
				openClass='NoChildrenLastNode';
			}
		} /* End selecting the image */
		
		/*
		 * Add a row for this child to the construction of the tree
		 */
		var row = table.insertRow(table.rows.length);
		var cell = row.insertCell(row.cells.length);
		
		/*
		 * Select the class based upon whether this node defaults open or closed
		 */
		if (child.wasOpen == true)
			cell.className=openClass;
		else
			cell.className=closedClass;
		cell.id='toggleImage' + gRow_ID;
		
		cell.openClass = openClass;
		cell.closedClass = closedClass;
		cell.node = child;
		child.cell=cell;
		
		/* 
		 * Link for toggling open and closed
		 */
		if (child.childrenNodes.length > 0)
			cell.innerHTML = '<a href="javascript:void(0);" onclick="javascript:Toggle_View(\'' 
							 + gRow_ID + '\');">&nbsp;&nbsp;&nbsp;</a>';
		else
			cell.innerHTML='&nbsp;';
		
		/*
		 * Special treatment for semantics = questionAction
		 */
		 var icon = '';
		 if (child.displayClass == 'questionAction') {
			 icon = '<div class="actionIcon" style="position:relative;top:-4px;left:-4px;"><font style="font-size:7.5pt;font-weight:normal;">A</font></div>';
		 }
		 
		/*
		 * Insert this cell into the row
		 */
		cell = row.insertCell(row.cells.length);
		var messageType = '';
		if (child.isApplicationMessage > 0)
			messageType = 'App';
		else if (child.duplicate)
			messageType = 'Dup';
			
		cell.innerHTML='<table cellpadding=0 cellspacing=0><tr align=left valign=top><td><div id=div'+gNode_ID + ' class="' + child.displayClass + messageType +'MouseOut" ' +
					   ' onmouseover="javascript:this.className=\'' + child.displayClass + messageType + 'MouseOver\';" ' +
					   ' onmouseout="javascript:this.className=\'' + child.displayClass + messageType + 'MouseOut\';" ' +
					   ' onclick="javascript:' +
					   '     if (Ajax_In_Use) return; ' +
					   /* If selecting an entry from the map into an answer, then simply update the answer-related visual control */
					   '     if (gSelecting_Message_From_Map_Title != null) { ' +
					   '		if (document.getElementById(\'node' + gNode_ID + '\').node.displayClass == \'message\') { ' +
						   '		gSelecting_Message_From_Map_Title.innerHTML=document.getElementById(\'node' + gNode_ID + '\').node.title;' +
						   '		gSelecting_Message_From_Map_Value.value=document.getElementById(\'node' + gNode_ID + '\').node.messageid;' +
						   '		gSelecting_Message_From_Map_Radio.checked=true;' +
					   '        } else {' +
					   /* User tried to click in a non-message while in selection mode, help them out with a notification */
					   '            alert(\'You cannot select a question until you close the \'+document.getElementById(\'AddAnswerMastheadLabel\').innerHTML+\' panel below.\');' +
					   '        }' +
					   
					   '     } else if (\'' + child.isApplicationMessage + '\' == \'1\') { '+
					   '		 alert(\'You cannot edit this application from here.\');' +
					   '     } else {' +
					   /* Selecting new node */
						   '	 if (gCurrent_Selected_Node != null) { ' +
						   '         gCurrent_Selected_Node.className=gRestore_className; ' +
						   '         gCurrent_Selected_Node.onmouseout=gRestore_onmouseout; ' +
						   '     }' +
						   '     if (\'' + child.displayClass + '\' == \'message\') ' +
						   '         Raise_Popup_DIV_Message(' + gNode_ID + '); ' +
						   '     else if (\'' + child.displayClass + '\' == \'question\')  ' +
						   '         Raise_Popup_DIV_Question(' + gNode_ID + '); ' +
						   '     gCurrent_Selected_Node = this; ' +
						   '	 gRestore_className = \'' + child.displayClass + messageType + 'MouseOut\'; ' +
						   '     gRestore_onmouseout = this.onmouseout; ' +
						   '	 this.onmouseout=this.onmouseover; ' +
					   '      }' +
					   '"><nobr>' +
					   child.title + '</nobr></div></td><td>' + icon + '</td></tr></table>';
		/*
		 * Store the id, title and a pointer in the cell back to the node in the abstract tree
		 */
		cell.id='node' + gNode_ID;
		
		cell.node=child;
		child.cell = cell;

		if (messageType == 'Dup')
			cell.title='Click to select this message. This is a duplicate message.  You cannot add questions here.';
		else if (messageType == 'App')
			cell.title='This message is a link to an application.';
		else if (child.displayClass == 'message')
			cell.title='Click to select this message.';
		else
			cell.title='Click to select this question.';
		
		/*
		 * If there is a copyquestionid initialized in the javascript, and Copied_questionid is null, 
		 * and this cell represents a question, then we need to set Copied_questionid to the current value of gNode_ID.questionid
		 */
		if (copyquestionid != null && Copied_questionid == null && child.questionid == copyquestionid) {
			Copied_questionid = copyquestionid;
		}
		/*
		 * Allocate a new node ID
		 */
		gNode_ID++;
		
		/*
		 * If this child has children, render it recursively
		 */
		if (child.childrenNodes.length > 0) {
			/*
			 * Create an outer column with a vertical bar for this child
			 */
			var row = table.insertRow(table.rows.length);
			row.id = 'row' + (gRow_ID++);		
			row.node=child;
			var cell = row.insertCell(row.cells.length);
			
			if (i < this.childrenNodes.length-1) 
				cell.className='VerticalBar';
			cell.innerHTML = '&nbsp;';
			
			cell = row.insertCell(row.cells.length);

			if (child.wasOpen != true)
				row.style.display='none';
				
			/*
			 * Add a subtable for this child
			 */
			this.childrenNodes[i].Render(cell);
		} else {			
			/*
			 *  Increment the rowid
			 */
			gRow_ID++;
		}
	}
	
}
 
/*
 * Store the questionid for a question that has been placed into the "copy buffer"
 */
function Store_QuestionID_Into_Copy_Buffer_2(completionObject)
{
	Copied_questionid = completionObject.questionid;
    alert('You may now add a copy of this question to another message.\r\n\r\nTo add a copy, use the Paste link in the Edit Message panel.');
}

function Store_QuestionID_Into_Copy_Buffer(id)
{
	try 
	{
		/*
		 * Get the node
		 */
		var node = document.getElementById('node'+id).node;

		/*
		 * Retain context
		 */
		var completionObject = new Object;
		completionObject.questionid = node.questionid;
		
		completionObject.AjaxCompletion = Store_QuestionID_Into_Copy_Buffer_2;
	
		/*
		 * Send the questionid to the server
		 */
		var parameters = new Object;
		parameters["questionid"] = node.questionid;
			
		Ajax_Call_Web_Method_async("CopyBufferQuestionID", parameters, completionObject);
	
	} 
	catch (ex) 
	{
		alert('Failed to connect to the server.  Please try again.' + ex);
	}
}

/*
 * Content selection control changed
 */
function Content_Selection_Changed() {
    var selection = document.getElementById('contentcontrol');
    var loopControl = document.getElementById('loop');
    var loopLabel = document.getElementById('loopLabel');
    
    if (selection.selectedIndex > 0) {
        loopControl.disabled = false;
        loopLabel.style.color = "white";
    } else {
        loopControl.disabled = true;
        loopLabel.style.color = "#999999";
    }
}
