// Dialogue Handling JavaScript Functions
// File:    dialogue.js
// Author:  Eric Baars
// WEBCAT:  2.2
// Version: 2.0
// History:
//     1 Feb 2000  V1.0: Initial creation.
//    21 Feb 2000  Remove testing button
//                 Handle prompt-level dialogues...ETB
//    23 Feb 2000  Message formatting...ETB
//    24 Feb 2000  V2.0: Display all messages after window displayed...ETB
//    28 Feb 2000  Possible multiple prompt/row dialogues...ETB
//    29 Feb 2000  Position dialogue at mid-screen...TY
//     7 Mar 2000  Resize/scrollbars...TY
//     9 Mar 2000  Message text unescaped for record/prompt dialogues...ETB
//    24 Apr 2000  Only process dialogues if first one not empty...ETB
//    26 Apr 2000  Still needs unmacro...ETB
//    17 May 2000  Replace field delimiter ";" with "|"...ETB
//    23 May 2000  Prompt dialogues deal with single mv, batch row...ETB
//    24 May 2000  Move unmacro to showHelp...ETB
//    13 Jun 2000  Deal with batch dialogue rows...ETB
//    19 Jun 2000  Status messages may not have row number...ETB
//    19 Feb 2001  Do not assume unmacro in top frame...ETB
//    22 May 2001  Make sure dialogue window remains in front...ETB
//	  18 Jan 2002  Added addChildWindow call so that will close on exit...CJF
//	  29 Jul 2002  Added check to confirm that parent window is not closed before referring to it...CJF
//

//-- Usage notes
//-------------------------------------------------------------------
// (0) HTML page which load dialogue.js also need showHelp.js (unmacro).
// (1) Include this .js in the SCRIPT section of the XSL
// (2) You have to set up the infoDlg, infoDlgPrompt arrays with data.
//     You can follow the example of Login.xsl (using XSL)
//                                or EntrySingle.xsl (using Java).
// (3) Add the following form to the page before the EntryForm (or equivalent).
/*
    <FORM NAME="DialogueForm">
      <INPUT TYPE="hidden" NAME="Action" VALUE=""/>
	</FORM>
*/
// (4a) To build record-level dialogues, call buildRecordDialogue()
//      at the start of the form (pageHeader SCRIPT area is good).
// (4b) To build prompt-level dialogues, call buildPromptDialogue()
//      as the prompt is being constructed.
// (5) In the pageFooter SCRIPT area, start dialogue display
//     and processing with:
/*
	  // call dialogue handler
	  startDialogues();
*/
//-------------------------------------------------------------------
// Dialogues display after page has been rendered.
// If a dialogue is closed without clicking a button, the dialogue will
// automatically re-display.
// Only the list actions considered valid; there must be a handler for
// each one in displayDialogue().

//-- Available actions
// Clicking any response button closes the dialogue window
// CONTINUE    - closes dialogue window and nothing more
// CLEARRECORD - EntrySingle: clears values from all prompts
//             - EntryBatch: clears values from prompts on row
// CLEARPROMPT - clear value from current prompt and row

//-------------------------------------------------------------------
// Dialogue data
var dlmDlg = '***';
var infoDlg = new Array();
var iDlg = 0;
var infoDlgPrompt = new Array();
var iDlgPrompt = 0;
var openerClosing = 0;

// Handle dialogue display and dismissal
var dialogueContent = new Array();
var iDialogue = 0;
var responseTimer = null;
var flagResponseTimer = false;
var whndDlg = null;

// Control: Stop dialogue display
function stopDialogues() {
	if (responseTimer != null) clearInterval(responseTimer);
	flagResponseTimer = false;
}

// Control: Begin dialogue display
function startDialogues() {
	stopDialogues();
	flagResponseTimer = true;
	iDialogue = 0;
	if (dialogueContent[0] != "") {
		displayDialogue();
		responseTimer = setInterval(displayDialogue,1000);
	}
}

// Display: Check for correctly answered dialogue; either redisplay or go to next
function displayDialogue() {
	var action = document.DialogueForm.Action.value.split('|');
	if (action[0] == iDialogue.toString() && !whndDlg.closed) { // button has not yet been selected
		whndDlg.focus();  // make sure dialogue window remains in front
                return;
	}
	// action handlers
	if (action[0] == "CONTINUE") iDialogue++;      // move to next dialogue
	if (action[0] == "CLEARRECORD") {              // clear all data prompts; stop dialogues
		clearRecord(action[1]);
		// only skip remaining dialogues if no record
		iDialogue = (action[1] == 0) ? dialogueContent.length+1 : iDialogue+1;
	}
	if (action[0] == "CLEARPROMPT") {              // clear current data prompt; move to next dialogue
		_uiArray[action[2]].setValue(action[1],"|");
//		var found = false;
//		var index = parseInt(action[1],10);
//		while (!found) {
//			var e = eval("document.EntryForm.elements["+index+"]"); // get prompt
//			if (e.name != "POI"+action[2]+"_"+promptID) {
//				found = true;
//			} else {
//				index++;
//			}
//		}
//		if (action[2] == '1') e.value = ""; // clear text prompt
//		if (action[2] == '30') {
//			e.value = ""; // clear pointer
//		}
//		if (action[2] == '31') {
//			e.value = ""; // clear prompt id
//			var e2 = eval("document.EntryForm.elements["+(index-1)+"]");
//			e2.value = ""; // clear prompt txt
//		}
		iDialogue++;
	}
        // if finished with last dialogue, stop processing
	if (iDialogue >= dialogueContent.length) {     // finished dialogues
		stopDialogues();
		return;
	}
	// display dialogue from list
	document.DialogueForm.Action.value = iDialogue;
	var windowFeatures = 'titlebar=no,hotkeys=no,dependent=yes,resizable=yes,scrollbars=yes'
	windowFeatures += ',left=' + screen.availWidth/4;
	windowFeatures += ',top=' + screen.availHeight/4;
	windowFeatures += ',width=' + screen.availWidth/2;
	windowFeatures += ',height=' + screen.availHeight/2;
    whndDlg = window.open('','Status',windowFeatures);
	if ( !openerClosing ) {
		addChildWindow( whndDlg ) ;
	}
	whndDlg.focus();
	whndDlg.document.open();
	whndDlg.document.writeln(dialogueContent[iDialogue]);
	whndDlg.document.close();
}

// Handler: Build record-level dialogue content
function buildRecordDialogue(title,isOpenerClosing) {
	if (infoDlg.length < 1) return;
	if (title == "") title = 'Record dialogue';
	openerClosing = isOpenerClosing ;
	var i = 0;
	while (i < infoDlg.length) {
		// setup display
		var content = '<HTML>\n<HEAD>\n<TITLE>';
		content += title;
		content += '</TITLE>\n';
		content += '</HEAD>\n';
		content += '<BODY STYLE="font-family:Verdana,Arial,Geneva,sans-serif;color:black;background-color:white;text-align:center;">\n'; /* STYLE="text-align:center;background-color:yellow;"*/
		content += '<FORM NAME="LocalForm"><TABLE>\n';
		// display message
		var temp = infoDlg[i++].split("|");
		if (temp.length < 2) {
			var row = 0;
			var message = temp;
		} else {
			var row = temp[0];
			var message = temp[1];
		}
		if (row > 0) {
			// batch multirow
			content += '<H1>#' + row + '</H1>';
		}

		content += '<P STYLE="font-size:120%;text-align:left;">';
		content += unescape(unmacro(message));
//		content += unescape(message);
		content += '<BR></P>\n';
		// display all buttons
		content += '<P STYLE="text-align:center;">\n';
		while (infoDlg[i] != dlmDlg) {
			content += '<INPUT TYPE="button" VALUE="' + infoDlg[i++] + '" ';
            content += 'onClick="';
			if ( !isOpenerClosing ){
				content += 'if ( opener.document.DialogueForm ) { opener.document.DialogueForm.Action.value = \'';
				content += infoDlg[i] + "|" + row;
				content += '\';}';
			}
			i++ ;
			content += ' window.close();';
			content += '">\n';
		}
		i++; // step over delimiter
		// finish display
		content += '</P>\n';
		content += '</FORM></BODY></HTML>\n';
		dialogueContent[iDialogue++] = content;
	}
}

// Handler: Build prompt-level dialogue content
function buildPromptDialogue(hui,row,bSingleItem,title,posn) {
	if (infoDlgPrompt.length < 1) return -2;  // no data at all
	if (bSingleItem) {  // if Single Entry Window
		datarow = 0;
		mvrow = row;
	} else {            // if Multi Entry Window
		datarow = row;
		mvrow = 1;
	}
	if (title == "") title = 'Prompt dialogue';
	if (posn > infoDlgPrompt.length) {
		var errMessage = "Dialogue::buildPromptDialogue:\n"
				+ "Prompt posn/row out of bounds ("+posn+">"+infoDlgPrompt.length+" ["+row+"])\n"
				+ "No action taken";
		alert(errMessage);
		return -1;
	}
	var promptID = hui.getID();
	var promptLabel = hui.getLabel();
        //alert(promptID+"|"+datarow+"|"+mvrow + "==" + infoDlgPrompt[posn + 1] ) ;
	while (promptID+"|"+datarow+"|"+mvrow == infoDlgPrompt[posn++]) {
		var content = '<HTML>\n<HEAD>\n<TITLE>';
		content += title + ': ' + promptLabel;
		content += '</TITLE>\n';
		content += '</HEAD>\n';
		content += '<BODY STYLE="text-align:center;background-color:yellow;">\n';
		content += '<FORM NAME="LocalForm">\n';
		// add message
		content += '<H1>' + promptLabel + ' ['+(bSingleItem?mvrow:datarow)+']</H1>\n';
		content += '<P STYLE="font-size:120%;text-align:left;">';
		content += unescape(unmacro(infoDlgPrompt[posn++]));
		content += '<BR></P>\n';
		// add all buttons
		content += '<P STYLE="text-align:center;">\n';
		while (infoDlgPrompt[posn] != dlmDlg && posn <= infoDlgPrompt.length) {
			content += '<INPUT TYPE="button" VALUE="' + infoDlgPrompt[posn++] + '" ';
			content += 'onClick="';
			content += 'if ( !opener.closed && opener.document.DialogueForm ) { opener.document.DialogueForm.Action.value = \'';
			content += infoDlgPrompt[posn++];
			content += '|' + datarow;
			content += '|' + hui.$rui;
			content += '\'; } window.close();';
			content += '">\n';
		}
		posn++; // step over delimiter
		content += '</P>\n';
		content += '</FORM></BODY></HTML>\n';
		dialogueContent[iDialogue] = content;
                iDialogue++ ;
	}
	return 1;
}

