/*
 * utils.js
 * author: Joel Stevick
 * date: 4.2.07
 * Copyright (c) 2007, CorData, Inc
 * Program Name: C.H.I.P. - CorData Hierarchical Inference Program
 */
/*
 * Display a popup div
 */
function Display_Popup_DIV(popupdivid, header, innerHTML)
{
	var popup = document.getElementById(popupdivid);
	popup.innerHTML = '';
	
	/*
	 * Raise the popup
	 */
	popup.style.display='block';
	var newdiv = document.createElement("div");
	newdiv.innerHTML =/* Header */
					'<div style="padding:2px;background-color:#333333;height:15px;'+
					' border-bottom-style:solid;border-bottom-width:1px;border-bottom-color:black;'+
					' ">'+
					'<table width=100% cellpadding=0 cellspacing=0><tr valign=top align=left><td><font style=font-weight:bold;font-size:8pt;>' 
				    + header +
					'</font></td><td align=right style=padding-right:5px;>' + 
					'<a href=javascript:void(0); ' + 
					' onclick="javascript:document.getElementById(\''+popupdivid+'\').style.display=\'none\';">' +
					'<font style=font-weight:bold;font-size:8pt;color:white;>Close</font></a>' +
					'</td>' +
					'</tr></table></div>' +
					'<div style=padding-top:20px;padding-left:10px;>' +
					innerHTML +
					'</div>';
	popup.appendChild(newdiv);					
}

/*
 * Do initialization series (part 4)
 */
function Do_Initialization_Series_4(completionObject)
{
	Create_Variable_Selection_Control_TABLE_RESULTS = completionObject.results;
	
	/*
	 * Do caller completion
	 */
	var caller_completionHandler = completionObject.caller_completionHandler;

	if (caller_completionHandler)
		caller_completionHandler();
}

/*
 * Do initialization series (part 3)
 */
function Do_Initialization_Series_3(completionObject)
{
	Create_Table_Selection_Control_TABLE_RESULTS = completionObject.results;

	/*
	 * Get the list of variables and place them into a selection control 
	 */
	var parameters = new Object;
	parameters['applicationid'] = completionObject.applicationid;

	completionObject.AjaxCompletion = Do_Initialization_Series_4;

	Ajax_Call_Web_Method_async('EnumerateVariablesByMessage', parameters, completionObject);
}

/*
 * Do initialization series (part 2)
 */
function Do_Initialization_Series_2(completionObject)
{
	/*
	 * Split the variables into an array
	 */
	Variable_List_For_Table = completionObject.results.split('\n');
	
	/*
	 * 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['applicationid'] = completionObject.applicationid;
	completionObject.AjaxCompletion = Do_Initialization_Series_3;
	
	Ajax_Call_Web_Method_async('EnumerateTablesByMessage', parameters, completionObject);
}
/*
 * Do initialization series 
 */
function Do_Initialization_Series(applicationid, caller_completionHandler)
{
	/*
	 * Create context
	 */
	var completionObject = new Object;
	completionObject.AjaxCompletion = Do_Initialization_Series_2;
	completionObject.applicationid=applicationid;
	completionObject.caller_completionHandler = caller_completionHandler;
	
	/*
	 * 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['applicationid'] = applicationid;
	parameters['nopseudovariables'] = '1';
	Ajax_Call_Web_Method_async('EnumerateVariablesByMessage', parameters, completionObject);

}
/*
 * Construct a dropdown control that can be used to select a variable
 */
var Variable_List_For_Table = null;

function Construct_Variable_List_For_Table(applicationid, selectedVariableid, row, col)
{
	/*
	 * Wait for initialization to complete
	 */
	if (Variable_List_For_Table == null) {
		alert('Connecting to CHIP [1].  Please wait.');
		return;
	}
	var count = 0;
	var variablesSelectionControl = '';
	var options = '<option value=0>Select Variable</option>';
	/*
	 * Enuerate the variables from the array and construct the options list
	 */
	for (i in Variable_List_For_Table)
	{
		if (Variable_List_For_Table[i] == '')
			continue;
		
		var IdValuePair = Variable_List_For_Table[i].split("\t");
		
		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		options += '<option ' + (selectedVariableid == IdValuePair[0] ? ' SELECTED ' : '') + ' value="' + row + '.' + col + '.' + IdValuePair[0] + '">' + optionText + '</option>';
		
		count++;
	}
	
	/*
	 * If there are any variables, then construct the selection dropdown control
	 */
	if (count > 0) {
		variablesSelectionControl = 
		  '<div style=width:160px;><select style=width:154px; name=rowcolumns[]> ' +
		  options +
		  '</select></div>';
	}
	
	return variablesSelectionControl;
}
/*
 * Move a row up in a table up one by its key
 */
function Move_Table_Row_Up_By_Key(tableid, key)
{
	var table = document.getElementById(tableid);
	
	for (var index = 0; index < table.rows.length; index++) {
		if (table.rows[index].key == key && index > 0) {
			swapRowUp(tableid, table.rows[index]);			
			break;
		}
	}
}
/*
 * Move a row down in a table up one by its key
 */
function Move_Table_Row_Down_By_Key(tableid, key)
{
	var table = document.getElementById(tableid);
	
	for (var index = 0; index < table.rows.length; index++) {
		if (table.rows[index].key == key && index < table.rows.length - 1) {
			swapRowDown(tableid, table.rows[index]);			
			break;
		}
	}
}
/*
 * Delete a row from a table by key
 */
function Delete_Table_Row_By_Key(tableid, key)
{
	var table = document.getElementById(tableid);
	
	for (var index = 0; index < table.rows.length; index++) {
		if (table.rows[index].key == key) {
			table.deleteRow(index);
			break;
		}
	}
}
/*
 * Insert a row into a table
 */
var Table_Row_Key = 0;
function Insert_Table_Row(applicationid,
						  tableid, 
						  quantityVariableid, 
						  partnumberVariableid,
						  descriptionVariableid,
						  optionalVariableid,
						  unitpriceVariableid
						  )
{
	/*
	 * Create a new row within the table object
	 */
	var table = document.getElementById(tableid);
	
	var row = table.insertRow(table.rows.length);
	row.valign='bottom';
	row.key = Table_Row_Key;
	
	/* Quantity */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML=Construct_Variable_List_For_Table(applicationid, quantityVariableid, Table_Row_Key, 'quantity');

	/* Part # */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML=Construct_Variable_List_For_Table(applicationid, partnumberVariableid, Table_Row_Key, 'partnumber');

	/* Description */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML=Construct_Variable_List_For_Table(applicationid, descriptionVariableid, Table_Row_Key, 'description');
	
	/* Optional */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML=Construct_Variable_List_For_Table(applicationid, optionalVariableid, Table_Row_Key, 'optional');
	
	/* Unit Price */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML=Construct_Variable_List_For_Table(applicationid, unitpriceVariableid, Table_Row_Key, 'unitprice');
		
	/* Up link */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML='<a href=javascript:void(0); title=\"Move this row up.\" onclick=\"javascript:' +
				   '    Move_Table_Row_Up_By_Key(\'' + tableid + '\', ' + Table_Row_Key + '); '  +
			       '\"><font style=font-size:8pt;color:blue;>Up</font></a><font color=#666666>&nbsp;|&nbsp;</font>';
	/* Down link */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML='<a href=javascript:void(0); title=\"Move this row down.\" onclick=\"javascript:' +
				   '    Move_Table_Row_Down_By_Key(\'' + tableid + '\', ' + Table_Row_Key + '); '  +
			       '\"><font style=font-size:8pt;color:blue;>Down</font></a><font color=#666666>&nbsp;|&nbsp;</font>';
	/* Delete link */
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML='<a href=javascript:void(0); title=\"Delete this row from the table.\" onclick=\"javascript:' +
				   'if (confirm(\'Delete this row?\') == true) { ' +
				   '    Delete_Table_Row_By_Key(\'' + tableid + '\', ' + Table_Row_Key + '); '  +
				   '}' +
			       '\"><font style=font-size:8pt;color:blue;>Delete</font></a>';
	Table_Row_Key++;
}
/*
 * Create the table selection control
 */
var Create_Table_Selection_Control_TABLE_RESULTS = null;

function
Create_Table_Selection_Control(applicationid, textid)
{

	/*
	 * Get the list of tables and place them into a selection control that
	 * can be used to insert tables into the message body
	 */
	if (Create_Table_Selection_Control_TABLE_RESULTS == null) {
		alert('Connecting to CHIP [2].  Please wait.');
		return;
	} 
	
	/*
	 * Split the tables into an array
	 */
	var tablesList = Create_Table_Selection_Control_TABLE_RESULTS.split('\n');
	var count = 0;
	var tablesSelectionControl = '';
	var options = '<option>Insert Table</option>';
	
	/*
	 * Enuerate 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(\'' + textid + '\'));">' +
		  options +
		  '</select>';
	}
	return tablesSelectionControl;
}
/*
 * Create the variable selection control 
 */
var Create_Variable_Selection_Control_TABLE_RESULTS = null;

function
Create_Variable_Selection_Control(applicationid, textid)
{
	/*
	 * Get the list of variables and place them into a selection control that
	 * can be used to insert variables into the text body
	 */
	if (Create_Variable_Selection_Control_TABLE_RESULTS == null) {
		alert('Connecting to CHIP [3].  Please wait.');
		return;
	}
	/*
	 * Split the variables into an array
	 */
	var variablesList = Create_Variable_Selection_Control_TABLE_RESULTS.split('\n');
	var count = 0;
	var variablesSelectionControl = '';
	var options = '<option>Insert Variable</option>';
	
	/*
	 * Enuerate the variables from the array and construct the options list
	 */
	var RegistrationVars = 0;
	
	for (i in variablesList)
	{
		if (variablesList[i] == '')
			continue;
		
		/*
		 * Parse variableid, variable name
		 */
		var IdValuePair = variablesList[i].split("\t");

		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(\'' + textid + '\'));">' +
		  options +
		  '</select>';
	}
	
	return variablesSelectionControl;

}
/*
 * This version creates a selection control that can be used to simply assign a variable
 */
function
Create_Variable_Selection_Control2(applicationid, selectionid, subjectvariableid)
{
	/*
	 * Get the list of variables and place them into a selection control 
	 */
	if (Create_Variable_Selection_Control_TABLE_RESULTS == null) {
		alert('Connecting to CHIP  [4].  Please wait.');
		return;
	}
	
	/*
	 * Split the variables into an array
	 */
	var variablesList = Create_Variable_Selection_Control_TABLE_RESULTS.split('\n');
	var count = 0;
	var variablesSelectionControl = '';
	var options = '<option value=0>Select Variable</option>';
	
	/*
	 * Enuerate the variables from the array and construct the options list
	 */
	var RegistrationVars = 0;
	
	for (i in variablesList)
	{
		if (variablesList[i] == '')
			continue;
		/*
		 * Parse variableid, variable name
		 */
		var IdValuePair = variablesList[i].split("\t");

		var optionText = IdValuePair[1].replace(/</g,'&lt;');
		optionText = optionText.replace(/>/g,'&gt;');
		
		/*
		 * Ignore pseudo variables
		 */
		if (IdValuePair[0] < 0) 
			continue;
		
		var optionColor = '';

		/*
		 * Determine if this is a preselected option
		 */
		var selected = parseInt(subjectvariableid) == parseInt(IdValuePair[0]) ? " SELECTED " : "";
		
		/*
		 * Add this option
		 */
		options += '<option style=background-color:' + optionColor + '; ' + selected + ' 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=' + selectionid + ' name=' + selectionid + '>' +
		  options +
		  '</select>';
	}
	
	return variablesSelectionControl;

}

/*
 * String reverse
 */
function string_reverse(str)
{
   var retStr = ""; 
   for (i=str.length - 1 ; i > - 1 ; i--){ 
      retStr += str.substr(i,1); 
   } 
   return retStr; 
}

/*
 * Swap a row upward in a table
 */
function swapRowUp(tableid, chosenRow){
	if (chosenRow.rowIndex != 0) {
    	moveRow(tableid, chosenRow, chosenRow.rowIndex-1);
  	}
}

/*
 * Swap a row downward in a table
 */
function swapRowDown(tableid, chosenRow) {                                                
 	/*
	 * Establish proper reference to the table
	 */
 	var table = document.getElementById(tableid);

	if (chosenRow.rowIndex != table.rows.length-1) {                           
   		moveRow(tableid, chosenRow, chosenRow.rowIndex+1);
 	}                                                                              
}                                                                                

/*
 * Moves the target row object to the input row index
 */
function moveRow(tableid, targetRow, newIndex) {

	/*
	 * Since we are not actually swapping
 	 * but simulating a swap, have to "skip over"
 	 * the current index
	 */
 	if (newIndex > targetRow.rowIndex) {
   		newIndex++;
 	}

 	/*
	 * Establish proper reference to the table
	 */
 	var table = document.getElementById(tableid);

 	/*
	 * Insert a new row at the new row index
	 */
 	var theCopiedRow = table.insertRow(newIndex);
	theCopiedRow.key = targetRow.key;

 	/*
	 * Copy all the cells from the row to move
   	 * into the new row
	 */
	for (var i=0; i<targetRow.cells.length; i++) {
   		var oldCell = targetRow.cells[i];
   		var newCell = document.createElement("TD");
   		newCell.innerHTML = oldCell.innerHTML;
   		theCopiedRow.appendChild(newCell);
 	}

 	//delete the old row
 	table.deleteRow(targetRow.rowIndex);
}
