/*==========================================================================//
//c// Copyright (c) 2005 Sellwood Associates - All Rights Reserved.
//c//
//c// THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF SELLWOOD ASSOCIATES, LLC
//c// The copyright notice above does not evidence any actual or
//c// intended publication of such source code.
//c//
//--------------------------------------------------------------------------//

  File Name: 
	ebookQuestionsAPI.js

  Author: 
	Pepper Williams <pepper@sellwoodassociates.com>

//--------------------------------------------------------------------------*/

// *************************************************************
function ______TEXT_QUERIES______() {}

var queryLetter = new Array("", "a", "b", "c", "d", "e", "f", "g");

var query;
var queryCorrect = new Array();
function WriteQuery() {
	// Initialize the query object
	query = new Object();
	
	// Sometimes we will just have 1 query, in which case the first argument will be 0.
	// Other times we will have more than 1, in which case the first argument will be a number.
	var number = arguments[0];
	// If number is 0 or 1, initialize the queryCorrect array
	// otherwise, we'll store queryCorrect[2-10] in the already-initialized array
	//if (number == 0 || number == 1) {
	//	queryCorrect = new Array();
	//}
	
	// Some sections have multiple questions, but we don't want them numbered.
	// So if number < 0, use the number as the index, but don't show the number.
	if (number < 0) {
		number *= -1;
		arguments[0] = 0;	// we check arguments[0] below to decide whether or not to show the number
	}
	
	// Read the other arguments: question is always arg 1; answers follow
	query.question = arguments[1];
	query.answers = new Array ();
	var j = 1;
	for (var i = 2; i < arguments.length; ++i) {
		// The "correct" arg indicates that the NEXT answer is the correct one
		if (arguments[i] == "correct") {
			queryCorrect[number] = j;
		} else {
			query.answers[j] = arguments[i];
			++j;
		}
	}
	
	// Now write the query
	main.document.write(selfQuizStart);		// config.js
	main.document.write('<div style="padding-bottom:5px">');
	// Check arguments[0] in the following, to allow for multiple unnumbered questions
	if (arguments[0] == 0) {
		main.document.write('<b>Self-Quiz:</b><br>', query.question);
	} else {
		main.document.write('<table border="0" cellspacing="0" cellpadding="0"><tr><td valign="top"><b>', number, '.</b>&nbsp;</td><td>', query.question, '</td></tr></table>');
	}
	main.document.write('</div>');
	
	// To fix vertical alignment problems, we have to insert the following text on the top
	// line of each cell.  For the answer, to be safe, we put it at the end of the answer
	// and try to substitute it for the first space in the answer
	var spacer = '<span class="super">&nbsp;</span>';
	
	main.document.write('<table cellspacing="0" cellpadding="0" border="0">');
	for (var i = 1; i < query.answers.length; ++i) {
		var modAns = query.answers[i].replace(/([^n<>]) /, '$1<span class="super">&nbsp;</span>');
		main.document.write ('<tr><td valign="top"><nobr><input type="radio" name="queryAnswers" onclick="top.CheckQueryAnswer(', number, ',', i, ')">', spacer, '</nobr></td>'
			, '<td valign="top"><nobr>', queryLetter[i], '.', spacer, '</nobr></td>'
			, '<td valign="top" width="95%">', modAns, spacer, '</td></tr>');
	}

	main.document.writeln('</table>'
		, '<div id="queryCorrect', number, '" style="display:none; color:#006600; font-weight:bold"><b>Correct!</b></div>'
		, '<div id="queryIncorrect', number, '" style="display:none; color:#990000; font-weight:bold">Incorrect</div>'
		, '</form>');
}

function CheckQueryAnswer(number, response) {
	if (response == queryCorrect[number]) {
		main.document.getElementById('queryIncorrect' + number).style.display = "none";
		main.document.getElementById('queryCorrect' + number).style.display = "block";
	} else {
		main.document.getElementById('queryCorrect' + number).style.display = "none";
		main.document.getElementById('queryIncorrect' + number).style.display = "block";
	}
}

// *************************************************************
function ______CHAPTER_SUMMARIES______() {}


var csIndex = 0;
var csAnswers = new Array();

function InitializeCS() {
	csIndex = 0;
	csAnswers = new Array();
}

function WriteCSBlank(answer) {
	// Start a nobr tag for the item
	main.document.write('<nobr>');

	main.document.write('<span id="csInp', csIndex, '"><input onclick="top.ShiftCheckLink(this)" type="text" name="csq', csIndex, '" size="', (answer.length + 2), '"></span>');
	FinishCSItem(answer);
	
	csAnswers[csIndex] = answer;	
	++csIndex;
}

function WriteCSMC(answerString) {
	// answer string should be something like "3, choice 1, choice2, correct choice"
	var answers = answerString.split(/,\s*/);
	var correctChoice = answers[0] * 1;
	
	// Start a nobr tag for the item
	main.document.write('<nobr>');

	main.document.write('<span id="csInp', csIndex, '"><select onclick="top.ShiftCheckLink(this)" name="csq', csIndex, '" style="font-family:Verdana,sans-serif;font-size:12px">');
	main.document.write('<option value="-1">--------</option>');
	for (var j = 1; j < answers.length; ++j) {
		main.document.write('<option value="', j, '">', answers[j], '</option>');
	}
	main.document.write('</select></span>');
	FinishCSItem(answers[correctChoice]);
	
	csAnswers[csIndex] = correctChoice;	
	++csIndex;
}

function FinishCSItem(answer) {
	// Write the correct answer next to the form element, in a hidden span
	main.document.write('<span id="csCor', csIndex, '" style="color:#009900; font-weight:bold; display:none">', answer, '</span>');
	
	// Also write the red X image, also in a hidden span
	main.document.write('<a title="Click to show the correct answer." id="csInc', csIndex, '" style="display:none" href="Javascript:top.FillinCSAnswer(', csIndex, ');"><img alt="Click to show the correct answer." src="', urlStart, 'pics/cswrong.gif" width="15" height="18" border="0" align="top"></a>');
	
	// Close off the nobr tag for the item
	main.document.write('</nobr>');
}

// Write a link to check or show the items
function WriteCSCheck() {
	main.document.write('<div id="checkDiv" style="position:absolute; left:' + (textFarRight + 5) + '; text-align:center"><a href="Javascript:top.CheckCSAnswers()" title="Check your answers" class="rightMarginLink">[Check]</a>&nbsp;<a href="Javascript:top.ShowCSAnswers()" title="Show correct answers" class="rightMarginLink">[Show]</a><br><a href="Javascript:top.LoadSection(\'reload\')" title="Reset the blanks and pull-downs" class="rightMarginLink">[Reset]</a></div>');
}

// Shift the "Check" link to a position just to the right of the clicked-on input
function ShiftCheckLink(inp) {
	// Find scroll position of the input (adapted from http://www.quirksmode.org/js/findpos.html)
	if (inp.offsetParent) {		// Should be true for any v5+ browser
		var obj = inp;
		var top = 0;
		while (obj.offsetParent) {
			top += obj.offsetTop;
			obj = obj.offsetParent;
		}
		
		// And move the link appropriately
		main.document.getElementById("checkDiv").style.top = top + "px";
	}
}

function CheckCSAnswers(start, end) {
	// If no start, check all
	if (start == null) {
		start = 0;
		end = csIndex;
	}
	
	// Go through the range of questions
	for (var i = start; i < end; ++i) {
		// An already-filled-in question
		if (typeof csAnswers[i] != "string" && csAnswers[i] == -1) {
			continue;
			
		// A fill-in
		} else if (typeof csAnswers[i] == "string") {
			var ans = main.document.csForm["csq" + i].value;
			// answer check needs to be case-insensitive
			var CIuserAns = ans.toLowerCase();
			var CIrightAns = csAnswers[i].toLowerCase();
			GiveCSFeedback(i, ans == "", CIuserAns == CIrightAns);

		// Or a multiple choice
		} else {
			var ans = main.document.csForm["csq" + i].options[main.document.csForm["csq" + i].selectedIndex].value;
			GiveCSFeedback(i, ans == -1, ans == csAnswers[i]);
		}
	}
}

function GiveCSFeedback(index, blank, correct) {
	// Blank: hide the X (couldn't be blank if the correct answer was showing!)
	if (blank) {
		main.document.getElementById("csInc" + index).style.display = "none";
	// Correct: show the correct answer; hide the form element and X
	} else if (correct) {
		FillinCSAnswer(index);
	// Incorrect: show the X
	} else {
		main.document.getElementById("csInc" + index).style.display = "inline";
	}
}

function FillinCSAnswer(index) {
	main.document.getElementById("csInp" + index).style.display = "none";
	main.document.getElementById("csInc" + index).style.display = "none";
	main.document.getElementById("csCor" + index).style.display = "inline";
	
	// Once the answer is filled in, make sure it doesn't get marked incorrect later
	csAnswers[index] = -1;
}

function ShowCSAnswers(start, end) {
	// If no range, check all
	if (start == null) {
		start = 0;
		end = csIndex;
		
		// If we're showing all answers, hide the check/show link
		// NO - because now we have a "reset" link
		// main.document.getElementById("checkDiv").style.display = "none";
	}
	
	// Go through the range of questions
	for (var i = start; i < end; ++i) {
		FillinCSAnswer(i);
	}
}

// *************************************************************
function ______DISCUSSION_QUESTIONS______ () {}

var dqs = new Array();

// Convert a given dq number, which could include spaces or other characters
// (e.g. "CYA 2-1.1a") into a valid object attribute name
function DQNumberId(n) {
	// convert to string
	n = "" + n;

	// replace non-word characters with _
	n = n.replace(/\W/g, "_");
	
	// PW: was starting with a word char, but turns out that's not necessary and
	// is problematic for backwards-compatibility
	// n = "dq_" + n;
	
	return n;
}

// Establish a dqs record, if it needs to be established
function CreateDQRecord(c, n) {
	// Establish the chapter array if necessary
	if (dqs[c] == null) {
		// PW: this used to be a numeric array, but to accommodate
		// non-numeric question "numbers", I've made it an object (associative array)
		dqs[c] = new Object();
	}

	// Establish the individual question array if necessary
	var nid;
	
	// Krugman method; now used by others
	nid = DQNumberId(n);
	if (dqs[c][nid] == null) {
		dqs[c][nid] = new Object();
		// Record the untransformed number
		dqs[c][nid].n = n;
	}

	return nid;
}

function WriteDQShowLink(showInline) {
	// If "true" is passed in, don't set the "top" attribute, so that the link
	// will show up inline where the js function is called.
	var top;
	if (showInline == true) {
		top = "";
	} else {
		top = "top:75px;"
	}
	// dqLinkLeftPos in in defaults.js
	main.document.write('<div id="showDiv" style="text-align:center; position:absolute; left:540; ' + top + '">');
	main.document.write('<a class="rightMarginLink" href="Javascript:top.ShowDQPrintable()" title="Show your answers in a printable window.">[Show Printable<br>Answers]</a>');
	// main.document.write('&nbsp;<a style="color:#ffffff" href="Javascript:top.ShowCSAnswers()" title="Show correct answers">[Submit]</a>');
	main.document.write('</div>');
}

function WriteDQField(n, printShowLink, win, prompt, givenAnswer) {
	// By default, use main of this window
	if (win == null) {
		win = main;
	}
	
	var c = CurrentChapter();
	var nid = CreateDQRecord(c, n);	// n may be transformed to deal with non-word chars
	// for now, unless this is Krugman, n=nid

	// If we already have a user answer, put it in the text field and display it.
	var answer = "";
	var style = ' style="display:block"';
	if (dqs[c][nid].answer != null && dqs[c][nid].answer != "") {
		answer = dqs[c][nid].answer;
	// If we don't have an answer, don't initially show the answer field
	// -- unless we have a prompt, in which case we'll assume that we always want to show it
	} else if (prompt == null) {
		style = ' style="display:none"'
	}
	
	var rrSmall = false;
	
	// KC: this is if we want to seed text field with arg from WriteDQField
	if (answer == null || answer == "") {
		// KT: need to stop from showing givenAnswer field in R&R when I overload the var.
		if (givenAnswer == "rrTextareaSmall"){ // some weird string nobody will ever type
			answer = "";
		} else if (givenAnswer != null) {
			answer = givenAnswer;
		}
	}
	
	//KT - determine if this is a small box or not.
	//     not done above because there may be an answer and then the comparison wont be made.
	if(givenAnswer == "rrTextareaSmall"){
		rrSmall = true;
	}
	
	// Show a link to view the answer field
	// -- unless we have a prompt, in which case it'll always be showing
	if (prompt == null) {
		win.document.write('<div id="dqtl"', nid, '" class="dqtl"><a class="ba" href="JavaScript:top.ShowDQField(\'', n, '\')">[Answer Field]</a></div>');
	}
	
	if (win == main) {
		;
	} else {
		// win.document.write('<div class="dqtl"><b>Answer Field:</b></div>');
		win.document.write('<input type="hidden" id="dqtanum" value="',nid,'">');
	}
	
	win.document.write('<div id="q', nid, '" class="dqtad"', style, '>');
	// write prompt, if given
	// dqpromptStart is defined as "" in defaults.js, and can be overridden in config.js
	if (prompt != null && prompt != false) {
		win.document.write('<div class="dqprompt">', dqpromptStart, prompt, '</div>');
	}

	// KT: now set the textarea size based on what we learned above..
	if(rrSmall && bookId == 'reflectrelate1e'){
		// KT: treat this as a small (marginal) textarea using a different class to size the field smaller...
		//     class="dqtaS" -- the S is for small
		//     This is for McCornack 1e (R&R)
		win.document.write('<textarea id="ta' + nid + '" class="dqtas" onclick="top.ShiftDQShowLink(this)" onfocus="top.ShiftDQShowLink(this)" onblur="top.RegisterDQAnswer(' + CurrentChapter() + ',\'' + n + '\',this)" rows="2" cols="40" style="overflow:hidden;overflow-y: scroll;overflow-x: hidden;overflow:-moz-scrollbars-vertical;" autocomplete="off" >');
	} else {
		win.document.write('<textarea id="ta', nid, '" class="dqta" onclick="top.ShiftDQShowLink(this)" onfocus="top.ShiftDQShowLink(this)" onblur="top.RegisterDQAnswer(', CurrentChapter(), ',\'', n, '\',this)" rows="2" cols="40" autocomplete="off" >');
	}
	win.document.write(answer);	
	win.document.write('</textarea>');
	if (printShowLink == true) {
		// alert(printShowLink);
		win.document.write('<div style="margin:2px 0 5px 0"><a class="ba" href="Javascript:top.ShowDQPrintable()" title="Show your answers in a printable window.">[Show Printable Answers]</a></div>');
	}

	// if some special links are set in config.js (see, e.g., theguide8e), show them
	if (WriteDQLinks != null) {
		WriteDQLinks(win, n);
	}

	win.document.write('</div>');
}

function printText(content) {

var regExp=/\n/gi;
content = content.replace(regExp,'<br>');


w = window.open('','', 'location=no,scrollbars=no,menubar=no,toolbar=no,width=400,height=200');
w.document.open();
w.document.write('<html><body onload="print()">')
w.document.write(content);
w.document.write('</body></html>');
w.document.close();
}

function ShowDQField(n) {
	var nid = DQNumberId(n);
	SetDisplay(main.document.getElementById('q' + nid));
	var d = main.document.getElementById('ta' + nid);
	if (d != null && d.style.display == "block") {
		d.focus();
	}
}

// Shift the "Show Printable" link to a position just to the right of the clicked-on input
function ShiftDQShowLink(inp) {
	// Find scroll position of the input 
	// (adapted from http://www.quirksmode.org/js/findpos.html)
	if (inp.offsetParent) {		// Should be true for any v5+ browser
		var obj = inp;
		var top = 0;
		while (obj.offsetParent) {
			top += obj.offsetTop;
			obj = obj.offsetParent;
		}
		
		// alert("Shifting " + inp);
		
		// And move the link appropriately
		if (main.document.getElementById("showDiv") != null) {
			main.document.getElementById("showDiv").style.top = top + "px";
		}
	} else {
		// alert ("inp.offsetParent is not defined");
	}
}

function RegisterDQAnswer(c, n, inp) {
	if (inp == null) {
		alert('no inp: ' + c + "/" + n);
	}
	var nid = RecordDQAnswer(c, n, inp.value);
	// alert("rdqa: " + inp);
	
	// If the answer came in from the supplemental window, make sure it's set
	// in the main window.
	if (c == CurrentChapter()) {
		var d = main.document.getElementById('ta' + nid);
		if (d != null && d != inp) {
			d.value = inp.value;
			if (inp.value != "") {
			//	SetDisplay(main.document.getElementById('q' + nid), 'block');
			}
		}
	}
	
	// Automatically submit the answer to the server
	Servercom("submitDQ"
		+ "&chapter=" + c
		+ "&dqNumber=" + n		// the server wants the untransformed number
		+ "&answer=" + escape(EncodeProblemCharacters(inp.value))
	);
}

// This function can be called by RegisterDQAnswer above, 
// or from text.php when the book is first loading
function RecordDQAnswer(c, n, answer) {
	var nid = CreateDQRecord(c, n);	// n may be transformed to deal with non-word chars
	dqs[c][nid].answer = answer;
	return nid;
}

var monthStrings = new Array("January", "February", "March", "April", "May", "June"
	, "July", "August", "September", "October", "November", "December");
	
function ShowDQPrintable(c) {
	if (c == null) {
		c = CurrentChapter();
	}
	

	// PW 4/27/2007: Used to dynamically write a popup window; now use
	// a php page to write everything out.
	var win;
	win = window.open(urlStart + 'common/allanswers.php?chapterType=' + chapterType + '&chapter=' + c + '&accountId=' + accountId, "QuestionAnswers", "top=10,left=50,width=600,height=500,menubar,resizable,scrollbars,status", true);
	return;
	
	win.document.open();
	win.document.write('<html>'
					 , '<head>'
					 , '<style type="text/css">'
					 , 'ol {margin-bottom:0px; margin-top:0px; padding-bottom:0px; padding-top:0px} '
					 , 'body {margin:10px; font-family:Verdana, sans-serif; font-size:12px; width:550px}'
					 , 'ol.first {padding-top:10px}'
					 , 'ol.answer {border-top:1px solid #999999; padding-top:5px; margin-top:5px}'
					 , '</style>'
					 , '<title>' 
					 , firstName, ' ', lastName
					 , ' - ', bookTitle, ', ', chapterType, ' ', c, ' Questions'
					 , '</title>'
					 , '</head>'
					 , '<body>'
	);

	// Start the document
	win.document.write('<b>', firstName, " ", lastName, '</b><br>');
	win.document.write('<i>', bookTitle, '</i>, ', chapterType, ' ', c, ' Questions<br>');
	
	// Get and format the date
	var d = new Date();
	var date = monthStrings[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
	win.document.write(date, "<br>");
	
	var somethingWritten = false;
	
	// Write all the questions and answers for the chapter
	
	// answer "numbers" could have letters (e.g. "p1b"), so we have to sort the keys
/*	var numberKeys = new Array();
	for (var i in dqs[c]) {
		numberKeys[numberKeys.length] = i;
	}
	numberKeys.sort(
*/	
	var liClass = ' class="first"';
	for (var i = 1; i < dqs[c].length; ++i) {
		if (dqs[c][i] != null && dqs[c][i].answer != null && dqs[c][i].answer != "") {
			if (somethingWritten) {
				liClass = ' class="answer"';
			}
			somethingWritten = true;
			
			var answer = dqs[c][i].answer;
			answer = answer.replace(/\r\n/g, "\n");
			answer = answer.replace(/\n/g, "<br>");
			// Enclose the question and answer in a bullet point
			win.document.write('<ol', liClass, ' type="1" start="', i, '">'
				, '<li>'
				, answer
				, '</li></ol>');
		}
	}
	
	// If no notes written, send a message to this effect.
	if (!somethingWritten) {
		win.document.write('<p>No answers have been registered for this chapter.</p>');
	}
	
	// Close the window
	win.document.write('</body></html>');
	win.document.close();
}

function SaveProfEmail(profEmail) {
	Servercom("saveProfEmail"
		+ "&profEmail=" + escape(profEmail)
	);
}
