//	
//	
//	eval.js			11/09/2006
//
//
//	javascript routines called from eval.pl
//
//	2007-06-28	- added new error sound colors as a replication notice
//	2007-12-08	- added LOTS of code for ajax calling!
//	2007-12-13	- added another global for tripping the ajax call
//	2008-11-17	- now receives an XML success message and checks for it

var globalNbrOfErrorSounds	= 4	;	// check to see if this does this exist elsewhere?
var globalNbrOfAnlysRows	= 3	;	// check to see if this does this exist elsewhere?

var strXmlUrl			= '/cgi-bin/comptonProcessAllParms.pl';		// 2008-11-17


	/* these are the tooltips on the main window */
var global_grammar_error_text
	= 'Click here to enter the grammar errors.';

var global_spontaneous_speech_error_text
	= 'To transcribe spontaneous speech errors,<br />click here to locate the target phoneme.<br />Then enter the error sound';

function changeSpan ( divName, dummy )  {	// this will have up to four error sounds as parameters

	var startOfSounds = 1;

	for (var x=startOfSounds; x < changeSpan.arguments.length; x++ )
	{
		//	var thisIncr = parseInt(x) + 1;

		var varName	=	''    // create a variable to hold the hidden name
			+	globalErrorSoundHandle
			+	x
			+	globalPrefixSuffixSeparatorCharacter
			+	divName
			;

		document[globalFormName][varName].value		= changeSpan.arguments[x]	;	// set the hidden field name
		document.getElementById(varName).className	= globalErrorSoundNormalCss	;

//		if  ( navigator.appName == "Netscape" ) {
//			document.getElementById(varName).textContent	= changeSpan.arguments[x]	;	
//			document.getElementById(varName).textContent	= changeSpan.arguments[x]	;	
//		} else {		// ie
//			// if  ( x == 1 ) alert ( navigator.appName ) ;
//			// if  ( x == 1 ) alert ( 'varName=' + varName ) ;
//			// if  ( x == 1 ) alert ( document.all[varName] )	;	
//			if  ( x == 1 ) alert ( 'before innerText=' 	+ document.all[varName].innerText )	;	
//			document.all[varName].innerText			= changeSpan.arguments[x]	;	
//			if  ( x == 1 ) alert ( 'after innerText=' 	+ document.all[varName].innerText )	;	
//		};
//
//		//document.getElementById(varName).className	= globalErrorSoundNormalCss	;
//		//document[globalFormName][varName].value		= changeSpan.arguments[x]	;	// set the hidden field name
	};
};



var tableIdHolder = '';

function changeTableView(tableId )
{ 

  if (document.layers)
  {
    buildWorkTable(tableId);
    current = (document.layers[tableId].display == 'none') ? 'block' : 'none';
    if  (tableIdHolder)	{
	document.layers[tableIdHolder].display = 'none';
    };
    document.layers[tableIdHolder].display = current;
    tableIdHolder = tableId;
  }
  else if (document.all)	// micro$oft internet explorer part
  {
    buildWorkTable(tableId);
    current = (document.all[tableId].style.display == 'none') ? 'block' : 'none';
    if  (tableIdHolder)	{
	document.all[tableIdHolder].style.display = 'none';
    };
    document.all[tableId].style.display = current;
    tableIdHolder = tableId;
  }
  else if (document.getElementById)
  {
    buildWorkTable(tableId);
    current = (document.getElementById(tableId).style.display == 'none') ? 'block' : 'none';
    if  (tableIdHolder)	{
	document.getElementById(tableIdHolder).style.display = 'none';
    }
    document.getElementById(tableId).style.display = current;
    tableIdHolder = tableId;
  };

  //ajaxCallServer(tableIdHolder, 'eval') ;						// 2007-12-05
  tableIdHolder	= tableId;

};


var tableArray = new Array();

function buildWorkTable(tableId)	{
  var myTest = false;


  for ( i in tableArray )	{
	if  ( tableArray[i] == tableId )	{
		myTest = true;
		break;
	};
  };
//	did we get all the way thru the loop without breaking?
  if  ( myTest == false )	{
	var myJscript	= new Array();

	var mySplitChar	=	'';
	if  ( 1 == 2 )	{			//
	} else if ( navigator.appName.indexOf("Netscape") > -1 )	{
		mySplitChar	=	"\n";
	} else if ( navigator.appName.indexOf("Microsoft") > -1 )	{
		mySplitChar	=	' ';	// micro$oft splits with spaces
	} else {
		alert
		(	'Sorry, but we are not supporting this browser '
		+	navigator.appName.text
		)
		;
	};
	myJscript	=	document.getElementById(tableId).innerHTML.split(mySplitChar);


	var myHtmlResults	= '';
	for ( i in myJscript )	{
	    if  ( myJscript[i].length > 1 )	{	// added 2007-02-16 - skip carriage returns
		myHtmlResults	+=	eval(myJscript[i]);
	    }
	};
	    
	var myFinalResults	=	''
		//			+	'<table align="center" border="5">'	2007-02-16
		+	'<table'		//	start the table tag
		+	' class='		//	table class
		+	'"'			// 	double quote
		+	'evalWordTableClass'	//	name of css class
		+	'"'			//	double quote
		+	'>'			//	stop the table tag
		+	myHtmlResults
		+	'</table>'
		;
	document.getElementById(tableId).innerHTML
		=	myFinalResults
		;

		// save results so next time thru we skip this
	tableArray[tableArray.length] = tableId;
	//	alert( document.getElementById(tableId).innerHTML );
  };
};


var saveLink = '';
function changeLink(fieldValue)	{
	if  ( saveLink )	{
		// document.getElementById(saveLink).style.fontWeight	= 'none';
		document.getElementById(saveLink).style.fontWeight	= 'normal';
		document.getElementById(saveLink).style.color		= 'blue';
	};
	if  ( saveLink != fieldValue )	{
		document.getElementById(fieldValue).style.fontWeight	= 'bold';
		document.getElementById(fieldValue).style.color		= 'red';
		saveLink = fieldValue;
	} else {
		saveLink = '';
	}
};


		// added 2007-05-30, called from onClick trigger created in evalHtmlTableCells.js htmlWorkTableRow function
function evalErrorSoundsFunction
		(	myErrorSoundVar			// 01
		,	myHtmlAnchorElement		// 02
		,	xPosition			// 03
		,	yPosition			// 04
		)
{

	// initPhonemeGrid('myEvalForm',myErrorSoundVar);
	initPhonemeGrid(globalFormName, myErrorSoundVar);
	if  ( checkForReplication(myErrorSoundVar))	{
		return overlay(myHtmlAnchorElement, 'myPhonemeGrid', xPosition, yPosition, -10, -20 );
	} else {
		return false;		// otherwise we go back to the login screen
	};
};


function checkForReplication(soundName)	{

		//alert ( document.getElementById(soundName).className  ) ;
	// if  ( document.getElementById(soundName).innerHTML == document[globalFormName][soundName].value		)
	if  ( document.getElementById(soundName).className  == globalErrorSoundReplicCss	)
	{
		document.getElementById(soundName).disabled	= false				;
		document.getElementById(soundName).readonly	= true				;
		document.getElementById(soundName).className	= globalErrorSoundNormalCss	;
		return false;
	} else {
		return true;					// dont open drop-down phoneme grid since we just provided
	};
};
	

//
//
//	everything below came from 2007-12-05
//
//
//

function  getXMLHTTPRequest() {
	try	{
		req = new XMLHttpRequest();
	} catch(err1) {
		try	{
			req = new ActiveObject("Msxm12.XMLHTTP");
		} catch(err2) {
			try	{
				req = new ActiveObject("Microsoft.XMLHTTP");
			} catch (err3) {
				req = false;
			}
		}
	}
	return req;
};

//	var self = false;

var globalSaveSubmitButton = '';

pausingImage 		= new Image(100,22);
pausingImage.src	= '/images/pausing.gif';	// this will 'cache' the pausing image (hopefully)

function ajaxCallServer() {

			// save original HTML for redisplay when this is all done!
	globalSaveSubmitButton = document.getElementById('submitButtonDiv').innerHTML;

	document.getElementById('submitButtonDiv').innerHTML = '<img src="/images/pausing.gif" width="100" height="22" alt="" />';

	var XML = new XMLWriter();
	XML.BeginNode	( 'root'			)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_client_name'	,	 escape(document[globalFormName].Param_client_name.value)	)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_teacher_name'	,	 escape(document[globalFormName].Param_teacher_name.value)	)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_session_name'	,	 escape(document[globalFormName].Param_session_name.value)	)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_layout_name'	,	 escape(document[globalFormName].Param_layout_name.value)	)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_crypt_name'	,	document[globalFormName].Param_teacher_crypt.value		)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_language_name'	,	 escape(document[globalFormName].Param_language_name.value)	)	;
	XML.pushString	( "\n" 				)	;
	XML.Node	( 'Param_email_name'	,	document[globalFormName].Param_email_name.value		)	;
	XML.pushString	( "\n" 				)	;

	XML.Node	(	'errorNote'
			,	( 	( typeof(errorNote) != 'undefined' )
				?	escape(errorNote)	// errorNote is a global created from include_anlys_perl_2_jscript.pl
				:	''
				)
			)
			;

	XML.pushString	( "\n\n" 				)	;

	XML.BeginNode	( 'EvalErrorSounds'		)	;
	traverseEvalStructure( XML, document[globalFormName] );
	XML.EndNode	()	;

	XML.pushString	( "\n\n" 				)	;

	XML.BeginNode	( 'AnlysErrorSounds'		)	;
	convertAnlysToXml( XML )	;
	XML.EndNode	()	;

	XML.Close()						;

	if  ( document.getElementsByName('Param_jscript_debug')[0] )	{
	    if  ( document.getElementsByName('Param_jscript_debug')[0].value == 'yes' )	{
		alert  ( XML.ToString(XML)  ) ;
	    };
	};

	var myRand = parseInt(Math.random()*999999999999);

	// var xmlHttpReq = getXMLHTTPRequest();


	var self = getXMLHTTPRequest();

	var timeStamp = new Date();
	var millisecondsSince1970 = timeStamp.getTime() ;
						// this will make our URL random so
						// it does not get 'cached' and subsequently
						// ignored - this is a problem in some browsers
	var modurl = strXmlUrl
		+	'?'			// universal symbol to start url parameters!
		+	'rndNbr='
		+	myRand
		+	'&'			// universal symbol to appen url parameters
		+	'rndTime='
		+	millisecondsSince1970
		;

	self.open('POST', modurl, true);
	self.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.onreadystatechange = function() { useHttpResponse(self) }  ;
	self.send( XML.ToString(XML) );
};

function useHttpResponse(self2)
{
	if (self2.readyState == 4) {

		document.getElementById('submitButtonDiv').innerHTML = globalSaveSubmitButton;
		globalSaveSubmitButton = '';

		if  (self2.status == 200 )	{
									// 2008-11-17
			if  ( self2.responseXML.getElementsByTagName("results")[0].getElementsByTagName("status")[0].childNodes[0].nodeValue == 'Success!' )
			{
				document.myEvalForm.Param_teacher_crypt.value
					= self2.responseXML.getElementsByTagName("results")[0].getElementsByTagName("param_teacher_crypt")[0].childNodes[0].nodeValue;
				clearTimeout ( setTimeoutId );							// 2008-11-17 - eliminate the last timer!
				setTimeoutId = setTimeout('sessionTimeout();' , setTimeoutMilliseconds )	// 2008-11-17 - should match the one inside of eval.pl

				if  ( document.getElementsByName('Param_jscript_debug')[0].value == 'yes' )
				{
					insertResults = self2.responseXML.getElementsByTagName("results")[0].getElementsByTagName("inserts")[0];
					updateResults = self2.responseXML.getElementsByTagName("results")[0].getElementsByTagName("updates")[0];
					deleteResults = self2.responseXML.getElementsByTagName("results")[0].getElementsByTagName("deletes")[0];
					alert	( 'results:'

						+ "\n"
						+ '  inserts:'

						+ "\n"
						+ '      master: '
						+ insertResults.getElementsByTagName('master')[0].childNodes[0].nodeValue

						+ "\n"
						+ '      anlys: '
						+ insertResults.getElementsByTagName('anlys')[0].childNodes[0].nodeValue

						+ "\n"
						+ '      eval: '
						+ insertResults.getElementsByTagName('eval')[0].childNodes[0].nodeValue

						+ "\n"
						+ '  updates: '
						+ updateResults.getElementsByTagName('master')[0].childNodes[0].nodeValue

						+ "\n"
						+ '  deletes: '
						+ deleteResults.getElementsByTagName('anlys')[0].childNodes[0].nodeValue

						+ "\n"
						+ '  purges: '
						+ self2.responseXML.getElementsByTagName('results')[0].getElementsByTagName('purges')[0].childNodes[0].nodeValue

						+ "\n"
						+ 'date: '
						+ self2.responseXML.getElementsByTagName('results')[0].getElementsByTagName('dateLastModified')[0].childNodes[0].nodeValue
						);
				};
			} else {
				alert	( 'return status not success.'
					+ "\n"
					+ 'Please contact technical support'
					+ "\n"
					+ 'and note the following message:'
					+ "\n"
					+ self2.responseText
					+ ':'
					);
									// 2008-11-17
			}
		} else {
			alert	( 'http return status code not 200.'
				+ "\n"
				+ 'Please contact technical support'
				+ "\n"
				+ 'and note the following:'
				+ "\n"
				+ self2.status
				+ ':'
				+ self2.statusText
				);
		};
	} else {
		// alert ( 'readyState = ' + self2.readyState);
	};
}

function convertAnlysToXml(XML )	{		// 2007-12-19

    for  ( var Anlys_detail_auto_incr = 0 ; Anlys_detail_auto_incr <= dataArray.length ; Anlys_detail_auto_incr++ )
    {
      if  ( dataArray[Anlys_detail_auto_incr] )
      {

	for ( var incrRows = 1 ; incrRows <= globalNbrOfAnlysRows; incrRows++ )	{
		if	( dataArray[Anlys_detail_auto_incr][incrRows]	)
		{
			XML.pushString	( "\n" 							)	;
			XML.BeginNode	('AnlysSoundRow'					)	;
			XML.Attrib	('Key'	,	Anlys_detail_auto_incr.toString()	)	;
			XML.Attrib	('Row'	,	incrRows.toString()			)	;

			if  ( dataArray[Anlys_detail_auto_incr][incrRows]['Client_anlys_detail_error_speaking_count'] > 0	)	{
			    XML.Node	(	'AnlysSoundSpeakCount'
					,	dataArray[Anlys_detail_auto_incr][incrRows]['Client_anlys_detail_error_speaking_count'].toString()
					);
			};
			if  ( dataArray[Anlys_detail_auto_incr][incrRows]['Client_anlys_detail_error_notes'] > '' )	{
			    XML.Node	(	'AnlysSoundNotes'
					,	dataArray[Anlys_detail_auto_incr][incrRows]['Client_anlys_detail_error_notes']
					);
			};
			for ( var incrCols = 1 ; incrCols <= globalNbrOfErrorSounds; incrCols++ )
			{
				// XML.pushString	( "\n" 											)	;
				XML.BeginNode	( 'AnlysSoundCol'									)	;
				XML.Attrib	( 'Col'	,	incrCols.toString()							)	;

				var columnVariable = 'Client_anlys_detail_error_sound_' + incrCols.toString();

				if  ( dataArray[Anlys_detail_auto_incr][incrRows][columnVariable] > ''	)
					XML.WriteString
					(	convert_to_http_pretty
						(	dataArray[Anlys_detail_auto_incr][incrRows][columnVariable].toString()
						)
					);
					XML.EndNode();

			};
			XML.EndNode();
		};
	};
    };
  };

	return;
};									// 2007-12-19

function traverseEvalStructure(XML, node) { 
	//	since the eval stuff is (currently) embedded in the master structure, we
	//	are forced to 'crawl' thru it recursively, looking for node types that
	//	are hidden.  then we also have to look for antying defined as ErrorSound#__#

	//&&	( node.type	== 'hidden'	)		// old - when the variables were all hidden
  //	var returnXml = '';

  if	(	( node.nodeType		== 1				)
			  // nodeType one is html element
			  // type three is some odd text type
	&&	( node.type		== 'text'			)
	&&	( node.className	== globalErrorSoundNormalCss	)	// must not be set to replicate!
	)
  {
	var errorSoundPattern = new RegExp("^\ErrorSound\([1-4]\)_{2}\([0-9]+\)$" );
		//	the error sound looks like:   ErrorSound   #  _ _  ###  we capture the digits
		//	or:		ErrorSound
		//			#		- error number  - 1, 2, 3 or four
		//			__
		//			###		- mysql unique index number


	if  ( node.name.match(errorSoundPattern)	)	{
		XML.BeginNode	( 'ErrorSound'			)	;
		XML.Attrib	( 'Key'	,	RegExp.$2	)	;
		XML.Attrib	( 'Nbr'	,	RegExp.$1	)	;
		if  ( node.value )	{
			XML.WriteString
			(	convert_to_http_pretty
				(	node.value
				)
			)
			;
		};
		XML.EndNode()						;
	};
  }
    if (node.childNodes != null) {
        for (var i=0; i < node.childNodes.length; i++) {
	      //	returnXml += traverseEvalStructure(node.childNodes.item(i));
	      traverseEvalStructure(XML, node.childNodes.item(i));
	}
    }
    //	return returnXml;
    return;
}

function convert_to_http_pretty	(	inputSound	)
	// if this number is higher than the largest ascii sound, 
	// make it look like &#123;  if the value is less than a lowercased 'z'
{
	return	( 	( inputSound <= 'z' )
		?	inputSound
		:	(	'&#'
			+	inputSound.charCodeAt(0)
			+	';'
			)
		)
		;
};

function jscript_debug_function(jscript_debug_param_name)	{
	if  ( document.getElementsByName(jscript_debug_param_name)[0].value == '' )	{
		document.getElementsByName(jscript_debug_param_name)[0].value = 'yes' ;
		alert ('debug is enabled');
	} else {
		document.getElementsByName(jscript_debug_param_name)[0].value = '' ;
		alert ('debug is disabled');
	};
}
