// Search Expert JavaScript Functions
// File:    searchExpert.js
// Author:  Eric Baars
// WEBCAT:  2.2
// Version: 1.0
// History:
//    20 Jan 2001  Initial creation
//    14 Feb 2001  Sort populated prompt options...ETB
//    26 Feb 2001  Required prompt processing
//    12 Mar 2001  Presort populated options...ETB
//    16 May 2001  New secondary window API...ETB
//     6 Aug 2001  Eliminate populated prompt...ETB
//    28 Aug 2001  Added actionType = "Find" for find button handler.
//                 (Need to know difference bw find and search)...CJF
//     8 Nov 2001  Modified the result of loaded search to be 1/2/3 - KEY_1/2/3...CJF
//    16 Nov 2001  Added feature to call expert search from an expert search...CJF
//    13 Dec 2001  Added flag to submitSearchRequest...CJF
//    01 Feb 2002  Fixed problem with netscape 6.0 and find button...CJF
//    23 Aug 2002  Modified pointer expansion to use POST (for Unicode search)...CJF
//    19 Sep 2002  Modified doSaveSearch to work with new submitSearchRequest function...CJF
//    11 Jul 2005  Added a line of code to set the selecting variable appropriately...WFH

// Majority of JavaScript code moved out of XSL file to speed processing.

// Utility: Verify that required fields have a value
// SearchExpert always ignores required directives, so always true
function validateRequiredPrompts() {
	return true;
}

// Access point handling
//-----------------------------------------------------------------------------
// Handler (button onClick): Clear all access buttons for reset
function resetButtons(flag) {
	for (var i = 0; i < document.SearchForm.elements.length; i++) {
		var e = document.SearchForm.elements[i];
		if (e.type == "button" &&
			(flag || e.value.substr(0,3) == "   ") &&
			parseInt(e.name.substr(1),10) > 0) e.value = "";
	}
}

// Handler (dropdown onChange):
// When access point selected from dropdown list, setup textbox and button.
function changePrompt(selectionField) {
	// Loop form, get the 'Select' index, and store in 'i'
	var posn = -1;
	for (var i = 0; i < document.SearchForm.elements.length; i++) {
		var e = document.SearchForm.elements[i];
		if (e.name == selectionField.name) {
			posn = i;
			break;
		}
	}
	
	if (posn == -1) return;
	// Set variables
	var selectField = document.SearchForm.elements[ posn ] ;
	var textField = document.SearchForm.elements[ posn + 1 ] ;
	var actionButton = document.SearchForm.elements[ posn + 2 ] ;
	// Clear Value input (the textbox)
	textField.value = "";
	// Set name on Value input; used in search request
	selectedOption = selectField.options[selectionField.selectedIndex];

	// Set title of Select button
	// If text/empty/key, button disabled
	// If Populated pointer, "show list" button
	// If Unpopulated pointer, "select target" button
	var check = selectedOption.value.substring(3,selectedOption.value.indexOf('_'));
	if (check == "30") {
		actionButton.value = txt_showlist;
	} else if (check == "31") {
		actionButton.value = txt_selecttarget ;
	} else {
		actionButton.value = "";
	}
	// *** DON'T REMOVE THIS *** 
	// Netscape 6 moves all elements renamed to the bottom
	// This code forces elements to stay together by renaming them in
	// the order that they need to remain together in.
	selectField.name = selectField.name ;
	textField.name = selectField.name.substr(1) + selectedOption.value;
	actionButton.name = actionButton.name ;
	// *** END DON'T REMOVE THIS *** 
}

// Handler (text onFocus): Editing search parameter
function changeValue(textField) {
	// If it contains keys, delete the keys
	if (textField.value.indexOf("KEY_") != -1) {
		textField.value = textField.value.substring(0,textField.value.indexOf("-") - 1);
	}
}

// Handler (button onClick): Perform correct action for access point type
function selectButton(button)   {
	// by the way, we are selecting for a pointer access prompt (WFH)
	top.selecting = true;
	// Get the index of the selected option of the Prompt
	// (selection list) corresponding to this button
	for (var i = 0; i < document.SearchForm.elements.length; i++) {
		var e = document.SearchForm.elements[i];
		if (e.name == "S"+button.name.substr(1)) {
			break;
		}
	}
        var iPos = -1 ;
	selectionField = document.SearchForm.elements[i];
	selectedOption = selectionField.options[selectionField.selectedIndex];
        // Determine the position of the currently selected pointer search prompt.
        for ( var x = 0 ; x < top.aSProcessNameArray.length ; x++ )
        {
            if ( selectedOption.value == top.aSProcessNameArray[ x ] )
            {
                iPos = x ;
               break ;
            }
            //alert( aWindowInfo[x] + " " + x ) ;
        }

	// Perform appropriate button action for access point type
	var check = selectedOption.value.substring(3,selectedOption.value.indexOf('_'));
	if (check == '30') {
		// Populated pointer access point: show list
		doShowList(i,selectedOption);
		return false;
	} else if (check == '31') {
		// Unpopulated pointer access point: select target
                //alert( aWindowInfo[iPos] + " " + iPos) ;
		doSelectTarget(i,aWindowInfo[iPos],iPos);
		return false;
	} else {
		// Text access point: do nothing
		return false;
	}
}

// Utility: Perform action for populated pointer access point
function doShowList(promptPosn,selOption) {
	var parentTargetFieldIndex = promptPosn + 1;

	// setup "OK" processing
	var actionCode = 'var cSelect = "/";\n';
	actionCode += 'if (document.ControlForm.elements[2].checked) cSelect = " ";\n';   // "AND" selected
	actionCode += 'var sResult="";\n';
	actionCode += 'var cboList = parent.SecDataFrame.document.DataForm.elements[0];\n';
	actionCode += 'for (var i = 0; i < cboList.length; i++) {\n';
	actionCode += '  if (cboList[i].selected) sResult += ((sResult=="") ? "" : cSelect) + cboList[i].value;} \n';
	actionCode += 'top.opener.document.SearchForm.elements[' + parentTargetFieldIndex + '].value = sResult;\n';
	//actionCode += 'top.close();\n';

	// construct HTML for edit field
	var dfContent = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n';
	dfContent += '<HTML>\n<HEAD>\n<TITLE><\/TITLE>\n<\/HEAD>\n';
	dfContent += '<BODY STYLE="background-color:gray;text-align:center;">\n';
	dfContent += '<FORM NAME="DataForm" STYLE="text-align:center;">';
	var currentSelectedOptions = " " + document.SearchForm.elements[parentTargetFieldIndex].value.split('/').join(' ') + " ";
	var startflag = false;
	var aryOption = new Array();
	var iO = 0;
	for (var iOption = 0; iOption < dataArray.length; iOption++) {
		var test = dataArray[iOption].split('_');
		if (test[0] == selOption.text && test[1] == "Start") {
			startflag = true;
			continue;
		}
		if (test[0] == selOption.text && test[1] == "End") {
			break;
		}
		if (startflag) {
			aryOption[iO++] = dataArray[iOption];
		}
	}
	aryOption.sort(usingField2);
	dfContent += generatePopulatedPointerPrompt("0",aryOption,"8",false,currentSelectedOptions);
	dfContent += '<\/FORM>\n';
	dfContent += '<\/BODY><\/HTML>\n';

	// display edit window
	var labels = new Array(6);
	labels[0] = txt_showlist + " " + selOption.text;
	labels[1] = txt_take;
	labels[2] = txt_close;
	labels[3] = "or";
	labels[4] = txt_and;
	labels[5] = txt_or;
	var winHandle = top.openSecondaryFrames(labels,actionCode,dfContent);
}

// Utility: Perform action for unpopulated pointer access point
function doSelectTarget(promptPosn,inWindowInfo,inIPos) {
        // Get search terms in text input
	var textField = document.SearchForm.elements[promptPosn+1];
	// Exclude keys from search string; null search string treated as "all"
	var searchText = "";
	if (textField.value == "") {
                // Call the full search screen.
                var sSearchProcess = top.aSProcessIDArray[ inIPos ] ;
                var sSearchType = top.aSTypeArray[ inIPos ] ;
                var sSearchName = top.aSProcessNameArray[ inIPos ] ;
                if ( sSearchType == 1 )
                {
                    var sExpSearchURL = "" ;
                    top.tableID = "";
                    var sExpSearchURL = cmd_action ;
                    var temp = cmd_action.split("?");
                    var sExpSearchURL = temp[0].substring(0,temp[0].indexOf("Action"));
                    temp = temp[1].split("&");
                    for (var i = 0; i < temp.length; i++) {
                            if (temp[i].indexOf("ClientSession") != -1) break;
                    }
                    sExpSearchURL += "DoMenuRequest?" + temp[i] + "&";
                    sExpSearchURL += "TemplateProcessID=" + sSearchProcess ;
                    top.bPrimary = true ;
                    window.TextFieldIndex = promptPosn+1;
                    var wFeatures = new windowProperties( inWindowInfo ) ;
                    winHandle = wFeatures.openNewWindow( 'exp', sExpSearchURL ) ;
                    return ;
                }
                else
                {
		    searchText = "*";
                }
                // Want to call another expert search...
	} else if (textField.value.indexOf("KEY_") != -1) {
		searchText = textField.value.substring(0,textField.value.indexOf("-") - 1);
		textField.value = searchText;
	} else {
		searchText = textField.value;
	}
	//var searchURI = cmd_action
	//	+ "&CMD_(PointerExpansion)="
	//	+ "&PromptID="
	//	+ textField.name.substring(textField.name.indexOf("_") + 1,textField.name.length)
	//	+ "&PromptText="
	//	+ escape(searchText);
	document.ExpandForm.elements[2].value = textField.name.substring(textField.name.indexOf("_") + 1,textField.name.length) ;
	document.ExpandForm.elements[2].name = "PromptID" ;
	document.ExpandForm.elements[1].value = searchText ;
	document.ExpandForm.elements[1].name = "PromptText" ;
	// store textbox position for secondary window to update
	window.TextFieldIndex = promptPosn+1;

	// Perform pointer expansion in standard secondary window
	tableID = "";
    actionType="Find" ;
    var aWinProperties = new windowProperties( inWindowInfo ) ;
    //var winHandle = aWinProperties.openNewWindow('exp',searchURI) ;
	var winHandle = aWinProperties.openNewWindow('exp','') ;
	document.ExpandForm.target = winHandle.name ;
	document.ExpandForm.submit( ) ;
}

// Logic/SaveSearch handling
//-----------------------------------------------------------------------------
// Handler (button onClick): Submit request to display list of logics to load/delete
function submitGetLogicsRequest(cmdname) {
	actionType = cmdname; // global variable
	var getLogicURL = cmd_action;
	getLogicURL += "&CMD_(GetLogicsRequest)=";
	//openSecondaryProcessWindow("log",getLogicURL);
	var aWinProperties = new windowProperties( "||||||||50|25|25|50|||" ) ;
	var aWHandle = aWinProperties.openNewWindow( "log", getLogicURL ) ;
        aWHandle.focus( ) ;
}

// Handler (button onClick): Display save search dialogue
function doSaveSearch(cmdName) {
	// setup "OK" processing
	var actionCode = 'var sLogicName=parent.SecDataFrame.document.DataForm.name.value;\n';
	actionCode += 'var bOverwrite=parent.SecDataFrame.document.DataForm.overwrite.checked;\n';
	actionCode += 'if (sLogicName == "") {\n';
	actionCode += '  alert("' + txt_nologicname + '");\n';
	actionCode += '} else {\n';
	actionCode += '  top.opener.document.SearchForm.LogicName.value = sLogicName;\n';
	actionCode += '  if (!bOverwrite) top.opener.document.SearchForm.LogicID.value = "";\n';
	actionCode += '  top.opener.document.SearchForm.target = top.name ; ' ;
	actionCode += '  top.opener.submitSearchRequest("'+cmdName+'");\n';
	actionCode += '}\n';

	// construct HTML for save options
	var dfContent = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ';
	dfContent += '<HTML>\n<HEAD>\n<TITLE><\/TITLE>\n';
	dfContent += '<STYLE TYPE="text/css">\n';
	dfContent += '.prompt {\n';
	dfContent += '  font-family     : "Verdana", "Arial", "Geneva", sans-serif;\n';
	dfContent += '  font-size       : 10pt;\n';
	dfContent += '  font-weight     : bold;\n';
	dfContent += '  vertical-align  : top;\n';
	dfContent += '  text-align      : left;\n';
	dfContent += '}\n';
	dfContent += '<\/STYLE>\n';
	dfContent += '<\/HEAD>\n';
	dfContent += '<BODY STYLE="background-color:#FFFFFF;text-align:center;">\n';
	dfContent += '<FORM NAME="DataForm" STYLE="text-align:center;">';
	dfContent += '<TABLE>\n';
	dfContent += '  <TR><TD CLASS="prompt">' + txt_logicname + '<\/TD><\/TR>\n';
	dfContent += '  <TR><TD>\n';
	dfContent += '    <INPUT NAME="name" TYPE="text" SIZE="35" ';
	dfContent += 'VALUE="' + document.SearchForm.LogicName.value + '">\n';
	dfContent += '  <\/TR><\/TD>\n';
	dfContent += '  <TR><TD CLASS="prompt">\n';
	dfContent += '    ' + txt_overwrite + '\n';
	dfContent += '    <INPUT NAME="overwrite" TYPE="checkbox"';
	if (document.SearchForm.LogicID.value != "") dfContent += ' CHECKED';
	dfContent += '>\n';
	dfContent += '  <\/TR><\/TD>\n';
	dfContent += '<\/TABLE>\n';
	dfContent += '<\/FORM>\n';
	dfContent += '<\/BODY><\/HTML>\n';

	// display save window
	var labels = new Array();
	labels[0] = txt_savesearch;
	labels[1] = txt_okay;
	labels[2] = txt_close;
	var winHandle = top.openSecondaryFrames(labels,actionCode,dfContent);
}

//-- Render access points (with data)
//-----------------------------------------------------------------------------
// Environment variables
var PROMPT = 0;
var TYPE = 1;
var SEARCH = 2;
var aDataTuples = new Array( ) ;
var iDT = 0;
var aWindowInfo = new Array( ) ;
var wDT = 0;

var aOptions;
var lstOptions = new list();
var sPromptOptions = '<OPTION VALUE=""><\/OPTION>\n';

// Utility: Add specified options to access point dropdown
function addDropdownOption(promptID,promptLabel) {
	if (lstOptions.isFound(promptID)) return;
	lstOptions.add(promptID);
	sPromptOptions += '<OPTION VALUE="'+promptID+'">'+promptLabel+'<\/OPTION>\n';
}

// Utility: Render access point dropdown
function buildPromptDropdown(identifier) {
	document.writeln('<SELECT TABINDEX="1" NAME="S'+identifier+'" ONCHANGE="changePrompt(this);">\n');
	document.writeln(sPromptOptions);
	document.writeln('<\/SELECT>\n');
}

// Utility: Build search expert access points
function buildAccessPointRows() {
	// setup
	var nDataTuples = aDataTuples.length;
	var nMaxAccessPoints = 10 + nDataTuples;
	aOptions = lstOptions.toArray();
	// build rows containing data
	for (var row = 1; row < nDataTuples + 1; row++) {
		buildAccessPoint(row);
		var posn = locatePromptInOptions(aDataTuples[row-1][PROMPT]);
		if (posn != -1) {
			ePosn = document.SearchForm.elements.length - 3; // dropdown
			document.SearchForm.elements[ePosn].options.selectedIndex = posn+1;
			changePrompt(document.SearchForm.elements[ePosn]);
			var searchTerm = aDataTuples[row-1][SEARCH];
                        if ( searchTerm == "" )
                        {
                              nMaxAccessPoints-- ;
                        }
                        else
                        {
                              if (aDataTuples[row-1][TYPE] == "31") {
                                  searchTerm = searchTerm + " - KEY_" + searchTerm ; // .split("/").join(" ")
                              }
                        }
			document.SearchForm.elements[ePosn+1].value = searchTerm;
		}
	}
	// build blank rows
	for (var row = nDataTuples + 1; row < nMaxAccessPoints + 1; row++) {
		buildAccessPoint(row);
	}
}

// Utility: Finds prompt in list of options
function locatePromptInOptions(promptID) {
	var p = -1;
	for (var i = 0; i < aOptions.length; i++) {
		if (promptID == aOptions[i]) {
			p = i;
			break;
		}
	}
	return p;
}

// Utility: Render a single access point row
function buildAccessPoint(row) {
	document.writeln('<TR>\n');
	document.writeln('<TD ALIGN="right">'+row+'<\/TD>\n');
	document.writeln('<TD>\n');
	buildPromptDropdown(row);
	document.writeln('</TD>\n');
	document.writeln('<TD></TD>\n');
	document.writeln('<TD>\n');
	document.writeln('<INPUT TABINDEX="1" NAME="T'+row+'" TYPE="text" ONFOCUS="changeValue(this);" SIZE="20">\n');
	document.writeln('<\/TD>\n');
        document.writeln('<TD></TD>\n');
	document.writeln('<TD>\n');
	document.writeln('<INPUT TABINDEX="1" NAME="B'+row+'" TYPE="button" ');
	document.writeln('ONCLICK="return selectButton(this);" VALUE="              ">\n');
	document.writeln('<\/TD>\n');
	document.writeln('<\/TR>\n');
}

