// tutor.js
// copyright 2010 by S&S Software
// all rights reservied

// holds an instance of XMLHttpRequestUSING_JAVA_SCRIPT
var xmlHttp = createXmlHttpRequestObject();

var g_fragment = null;
var g_targetId = null;
var g_oper = 0;
var g_num1 = 0;
var g_num2 = 0;
var g_num3 = 0;
var g_num4 = 0;
var g_numFrames = 0;
var g_curFrame = 0;
var g_frames = Array();

var g_canvas = null;
var g_context = null;

var g_maxRows = 0;
var g_maxCols = 0;
var g_blackBoard = null;
var g_prompt1, g_prompt2, g_promt3 = null;
var g_theProb = null;
var g_i1, g_i2, g_i3, g_i4, g_i5, g_i6;



// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp) {
	// may want more usr friendly error message and control here....
    //alert("Error creating the XMLHttpRequest object.");
	USING_JAVA_SCRIPT = false;
  }	
  else 
    return xmlHttp;
}



function initTutor(targetId) {
	g_targetId = targetId;
}

function initProblem(oper, num1, num2, num3, num4) {

	g_oper = oper;
	g_num1 = num1;
	g_num2 = num2;
	g_num3 = num3;
	g_num4 = num4;
	
	
	if(xmlHttp) {
		
		var params = "state=" + "doTutor" + "&"
			+ "oper=" + g_oper + "&"
			+ "num1=" + g_num1 + "&" 
			+ "num2=" + g_num2 + "&" 
			+ "num3=" + g_num3 + "&" 
			+ "num4=" + g_num4;
		
		
		try {
				 
			xmlHttp.open("GET", "handleAjax.php?" + params, true);
			xmlHttp.onreadystatechange = handleRequestStateChange;

			var url = document.URL;
			xmlHttp.setRequestHeader("Referer",url);


			xmlHttp.send(null);
			
		} catch(e) {
			alert("can not connect to server.");	
		}
	}
	

}

function handleRequestStateChange() {
	if(xmlHttp.readyState == 4) {

		if(xmlHttp.status == 200) {
				//alert("Hit requestStateChange");	
				try {
					handleServerResponse();
				} catch(e) {
					alert("Error reading the response: " + e.toString());
				}
				
		} else {
			alert("There was a problem retrieving the data:\n" + xmlhttp.statusText);
		}
		
	}
}


function handleServerResponse() {
  // retrieve the server's response packaged as an XML DOM object
	var xmlResponse = xmlHttp.responseText;	
	initFrames(xmlResponse);	
}

function initFrames(stream) {
	g_frames = stream.split("¶");
	g_numFrames = g_frames.length -2;	
	
	// get max size from last frame
	var frame = g_frames[g_numFrames];
	var chunks = frame.split("µ");
	var prob = chunks[9];
	var parts = prob.split(";");
	g_maxRows = parts[0];
	g_maxCols = parts[1];

	var oTutorContainer = document.getElementById(g_targetId);	
	// save the contents of the target container...
	g_fragment = document.createDocumentFragment();
	var aClone = oTutorContainer.cloneNode(true);
	g_fragment.appendChild(aClone);	
	
	oTutorContainer.innerHTML = "";


	var w = '70%';
	var m = '15%';
	
	if(g_maxCols > 14) {
		w = "90%";
		m = '5%';
	} else if(g_maxCols > 11) {
		w = "80%";
		m = '10%';
	} else if(g_maxCols < 4) {
		w = '50%';
		m = '25%';
	}
	
	
	var oProbView = document.createElement('div');
	oTutorContainer.appendChild(oProbView);
	oProbView.id = 'problemView';
	oProbView.style.width = w;
	oProbView.style.marginLeft = m;
	oProbView.style.height = 6 + Number(g_maxRows) * 1.1 + "em";
	
	
	var oProbControl = document.createElement('div');
	oTutorContainer.appendChild(oProbControl);
	oProbControl.id = 'probControl';
	oProbControl.style.width = w;
	oProbControl.style.marginLeft = m;	

	oProbControl.innerHTML = "";	

	oProbControl.innerHTML += "<table width='100%'><tr><td width='90%'><input id='previousButton' type='button' value='<--Previous' onclick='stepBack();' /><input id='nextButton' type='button' value='Next-->' onclick='stepForward();' /></td><td><input id='quitButton' type='button' value='Quit' onclick='quitTutor();' /></td></tr></table>";		


	var aButton = document.getElementById("previousButton");	
	aButton.disabled = true;

	var oProbView = document.getElementById('problemView');

	// the blackboard	
	var blackBoard = document.createElement('div');
	oProbView.appendChild(blackBoard);	
	blackBoard.id = 'blackboard';
	blackBoard.style.position = 'relative';
	blackBoard.style.marginLeft = '10%';
	
	//blackBoard.style.border = 'thin black solid';	
	g_blackBoard = blackBoard;


	// the top prompt
	var prompt1 = document.createElement('div');
	g_blackBoard.appendChild(prompt1);	
	prompt1.id = 'prompt1';
	prompt1.style.position = 'absolute';
	prompt1.style.top = '0em';
	prompt1.style.left = '0em';
	prompt1.style.height = '1em';
	//prompt1.style.textAlign = 'center';
	//prompt1.style.border = 'thin black solid';	
	g_prompt1 = prompt1;


	// the problem	
	var theProb = document.createElement('div');
	g_blackBoard.appendChild(theProb);
	theProb.id = 'problem';
	theProb.style.position = 'absolute';
	theProb.style.top = '2em';
	theProb.style.left = '0em';		
	theProb.style.width = (g_maxCols * .9) + "em";
	theProb.style.height = (g_maxRows * 1.1) + "em";				
	//theProb.style.border = 'thin black solid';
	g_theProb = theProb;



	// the instructions
	var theInstrBox = document.createElement('div');
	g_blackBoard.appendChild(theInstrBox);
	theInstrBox.id = 'instr';
	theInstrBox.style.position = 'absolute';
	theInstrBox.style.top = '2em';
	theInstrBox.style.left = Number(g_maxCols) + 1 + 'em';		
	theInstrBox.style.width = "auto";
	theInstrBox.style.height = (g_maxRows * 1.1) + "em";				
	//theInstrBox.style.border = 'thin black solid';
	g_theInstrBox = theInstrBox;

		
	var i1 = document.createElement('div');
	g_theInstrBox.appendChild(i1);
	i1.id = 'instr1';
	i1.style.position = 'relative';
	i1.style.top = '0em';
	i1.style.left = '0em';
	g_i1 = i1;



	var i2 = document.createElement('div');
	g_theInstrBox.appendChild(i2);
	i2.id = 'instr2';
	i2.style.position = 'relative';
	i2.style.top = '0em';
	i2.style.left = '0em';
	g_i2 = i2;

	var i3 = document.createElement('div');
	g_theInstrBox.appendChild(i3);
	i3.id = 'instr3';
	i3.style.position = 'relative';
	i3.style.top = '0em';
	i3.style.left = '0em';
	g_i3 = i3;

	var i4 = document.createElement('div');
	g_theInstrBox.appendChild(i4);
	i4.id = 'instr4';
	i4.style.position = 'relative';
	i4.style.top = '0em';
	i4.style.left = '0em';
	g_i4 = i4;
	
	var i5 = document.createElement('div');
	g_theInstrBox.appendChild(i5);
	i5.id = 'instr5';
	i5.style.position = 'relative';
	i5.style.top = '0em';
	i5.style.left = '0em';
	g_i5 = i5;
		
	var i6 = document.createElement('div');
	g_theInstrBox.appendChild(i6);
	i6.id = 'instr6';
	i6.style.position = 'relative';
	i6.style.top = '0em';
	i6.style.left = '0em';
	g_i6 = i6;

	// the bottom prompts
	var prompt2 = document.createElement('div');
	g_blackBoard.appendChild(prompt2);	
	prompt2.id = 'prompt2';
	prompt2.style.position = 'absolute';
	prompt2.style.top = Number(g_maxRows * 1.1) + 3 + 'em';
	prompt2.style.left = '0em';
	prompt2.style.height = '1.2em';
	//prompt2.style.border = 'thin black solid';	
	g_prompt2 = prompt2;
	

	var prompt3 = document.createElement('div');
	g_blackBoard.appendChild(prompt3);	
	prompt3.id = 'prompt3';
	prompt3.style.position = 'absolute';
	prompt3.style.top = Number(g_maxRows * 1.1) + 4.2 + 'em';
	prompt3.style.left = '0em';
	prompt3.style.height = '1.2em';
	//prompt3.style.border = 'thin black solid';	
	g_prompt3 = prompt3;

	for(var r = 0; r < g_maxRows; r++) {
		for(var c = 0; c  < g_maxCols; c++) {
			var id =  "c" + r + "" + c;
			var aCell = document.createElement('div');
			g_theProb.appendChild(aCell);
			aCell.id =id;
			aCell.className = 'cell';
			aCell.style.position = 'absolute';
			aCell.style.top = (Number(r) * 1.1) +'em';
			aCell.style.left = (Number(c)) * .9 + 'em';		
		}
	}
	frame2html();
}

function stepForward() {
	g_curFrame++;
	
	frame2html();
	var oProblemView = document.getElementById('problemView');

	
	if(g_curFrame >= g_numFrames) {
		var aButton = document.getElementById("nextButton");
		aButton.disabled = true;
	}	
	var aButton = document.getElementById("previousButton");	
	if(aButton.disabled)
		aButton.disabled = false;		
}

function stepBack() {
	for(var r = 0; r < g_maxRows; r++) {
		for(var c = 0; c  < g_maxCols; c++) {
			var id =  "c" + r + "" + c;
			var aCell = document.getElementById(id);						
			aCell.innerHTML = "";			
			aCell.style.background = 'none';
			aCell.style.borderBottom = 'none';			
		}
	}	
	
	
	g_curFrame--;
	frame2html();
	var oProblemView = document.getElementById('problemView');
		
	if(g_curFrame <= 0) {
		var aButton = document.getElementById("previousButton");
		aButton.disabled = true;
	} 
	var aButton = document.getElementById("nextButton");	
	if(aButton.disabled)
		aButton.disabled = false;
}

// doesn't work because screen is not updated each pass...
function fastForward() {
	if(g_curFrame >= g_numFrames) {
		var aButton = document.getElementById("nextButton");
		aButton.disabled = true;	
	} else {
		g_curFrame++;
		frame2html();
		//var oProblemView = document.getElementById('problemView');
		// must be able to force screen update here, or this doesn't work...	
		setTimeout("fastForward();",1);
	}
}



function frame2html() {
	var htmlProb = "";		
	var frame = "";
	var prompt = "";
	var inst1 = "";
	var inst2 = "";
	var inst3 = "";
	var inst4 = "";
	var inst5 = "";
	var inst6 = "";
	var inst7 = "";
	var inst8 = "";
	var prob = "";
	var frame = g_frames[g_curFrame];
	var chunks = frame.split("µ");
	var prompt = chunks[0];
	var inst1 = chunks[1];
	var inst2 = chunks[2];
	var inst3 = chunks[3];
	var inst4 = chunks[4];
	var inst5 = chunks[5];
	var inst6 = chunks[6];
	var inst7 = chunks[7]; // instructions2
	var inst8 = chunks[8]; // instructions2
	var prob = chunks[9];
	var parts = prob.split(";");
	var tall = parts[0];
	var wide = parts[1];
	var numLines = parts[2];
	var lineDefs = parts[3];	
	var lines = lineDefs.split(",");	
	var lineParts;	
	var lineH;
	var lineV;
	var numCells;;
	var lineNum = 0;
	var probDefs = parts[4];
	var probParts = probDefs.split(",");
	var numParts = probParts.length -1;
	var used = 0;	
	var htmlProb = "";	

	var oProbView = document.getElementById('problemView');
	g_prompt1.innerHTML = prompt;
	g_i1.innerHTML = inst1;
	g_i2.innerHTML = inst2;
	g_i3.innerHTML = inst3;
	g_i4.innerHTML = inst4;
	g_i5.innerHTML = inst5;
	g_i6.innerHTML = inst6;
	g_prompt2.innerHTML = inst7;
	g_prompt3.innerHTML = inst8;
			
	// the problem
	for(r = 0; r < tall; r++) {		
		if( lineNum < numLines) {
			lineParts = lines[lineNum].split(" ");
			lineH = lineParts[0];
			lineV = lineParts[1];
			numCells = lineParts[2];
		}
		var stop = Number(lineH) + Number(numCells);				
		var isUL = false;
			
		for(c = 0; c < wide; c++) {						
			cellParts = probParts[used].split(":");
			num = cellParts[0];
			attribute = cellParts[1];
			highlight = attribute & 1;
			colorText = attribute & 2;
			borrowedFrom = attribute & 4;
			borrowedTo = attribute & 8;
			decCol = attribute & 16;
			isNumerator = attribute & 32;
			isDenominator = attribute & 64;	

			var id =  "c" + r + "" + c;
			var aCell = document.getElementById(id);						
			if(num == "") {
				aCell.innerHTML = "&nbsp";
			} else {
				aCell.innerHTML = num;				
			}	

			if(((r == lineV) && (c >= lineH)) && (c < stop)) {
				aCell.style.borderBottom = 'thin black solid';
				isUL = true;					
			}
					
			if(highlight)
				aCell.style.background = 'yellow';
			else
				aCell.style.background = 'none';
						
			if(borrowedFrom) {
				var x = document.createElement('div');
				aCell.appendChild(x);
				x.style.position = 'absolute';
				x.style.top = '0px';
				x.style.left = '0px';
				x.style.color = 'red';
				x.innerHTML = "X";				
			}		
											
			if(borrowedTo) {
				var b = document.createElement('div');
				aCell.appendChild(b);
				b.style.position = 'absolute';
				b.style.top = '-.5em';
				b.style.left = '-.2em';
				b.style.color = 'red';
				b.style.fontSize = '11px';
				b.innerHTML = "1";
			}

		
			if((g_oper < 3 ) && (r == 0)) { // addition, subtraction, or multiplication
				if(num > 0 ) {
					aCell.style.color = 'red';
					//aCell.style.fontWeight = '10';
				}
			}
			
			if(isUL) {
				isUL = false;
			}					
			used++;
		}		
		if(r == lineV)
			lineNum++;						
	}	
}



function quitTutor() {		
	var oTutorContainer = document.getElementById(g_targetId);
	var theParent = oTutorContainer.parentNode;
	theParent.replaceChild(g_fragment,oTutorContainer);
	g_fragment = null;	
	g_curFrame = 0;	
	quitTutorShell();
}





