/**
 *  ==================================================
 *  SoftChalk LessonBuilder
 *  Copyright 2003-2005 SoftChalk LLC
 *  All Rights Reserved.
 *
 *  ==================================================
 *  For additional information, please contact
 *  http://www.softchalk.com
 *  help@softchalk.com
 *
 *  ==================================================
 *  File date: September 18, 2006
 *
 *
 *
 *
 *	From lesson.js file:
 *
 *  tableToggle_array=new Array();
 *  feed=new Array();
 *  f_right=new Array();
 *  f_wrong=new Array();
 *  f_show_correct=new Array();
 *  f_done=new Array();
 *  f_partial=new Array();
 *
 *  scoreQ[]	indicates whether to include question in scoring
 *  q_done[]	indicates whether the question has been attempted to be answered
 *
 *	"no"        form and question number (which are the same)
 *	"mc_Items"  how many mc or matching items there are - value should be 0 for short answer, 2 for true-false
 *	"q_type"    1 for multiple choice, 2 for true-false, 3 for multiple answer, 4 for short answer, 5 for matching, 6 for ordering
 *
 *
 *
 *	In lesson html files that have no quizpoppers:
 *
 *  scoreQ[], and my_status are defined in header.
 *
 *
 *
 *	In lesson html files that have quizpoppers:
 *
 *  my_status is defined in header
 *  to prevent error msgbox if student
 *  quits lesson without answering any questions.
 */


startTimer();

var scorm = false					//unless overriden by scorm.js
var attempted_points = 0; //total points possible on questions attempted to be answered so far
var total_points = 0;			//total points possible for all questions to be scored for entire lesson
var my_score = 0;					//current cumulative number of points scored on all questions answered
var totalQ = 0;						//total questions to be scored for this lesson
var attempted_q = 0;			//total number of questions attempted to answer

var file_name = location.href.substring((location.href.lastIndexOf('/') + 1),location.href.length);
var BEEN_ANSWERED = "This question has already been answered correctly!";
var IN_RED = "<br><br>A section of the text which may be helful\n\n" +
						 "in understanding the correct response is highlighted in red.";
var CLOSE_THIS_WINDOW = "<a href='javascript:window.close()'>" +
												"<img src='close_feedback.gif' border='0' align='right' alt='Close Window'>" +
												"</a><br><br>";


var skip = new Array();				//monitors if question has already been answered correctly
var q_value = new Array();		//gets value of variable q_value from lesson.js and converts to value in this array

/**
 *  inline div ids
 */
var inlineIDs = new Array("feed","f_right","f_wrong","f_show_correct","f_done","f_partial","hint");



/**
 *  Determine which questions are scored
 *	and add to totalQ and total_points.
 */
for (var i = 1; i <= (scoreQ.length); i++) {
  if (scoreQ[i] == "yes") {
	  totalQ++;
	  skip[i] = false;
    q_value[i] = eval("q_value" + i);
    total_points += q_value[i];
	}
	else {
		q_value[i] = 0;
	}
}

/**
 *  Do same for activities.
 *
 *	Don't need an array to hold point values
 *	because that data comes from the flash variables
 */
for (var i = 1; i <= (scoreQa.length); i++) {
  if (scoreQa[i] == "yes") {
	  totalQ++;
    var a_value = eval("a_value" + i);
    total_points += a_value;
	}
}


/**
 *  Called when "Check Answer" button is clicked
 */
function check_q(no, mc_items, q_type) {
	if (!q_done[no]) {
		attempted_q++;
	  attempted_points = attempted_points + q_value[no];
	  q_done[no] = true;
	}

	var correct = "no";
	var feedback = "";
	var right_string = "";
	var checkedButton = "";
	var student_answer = "";
	var get_answers = new Array();
	var fieldno = eval("main.document.f" + no + ".q" + no); // input name
	var imageno = eval("main.document.check" + no);
	var which_array = eval("right_answers" + no);

  if (which_array.length == 1) {								//if single right answer for multiple choice and short answer
		if (q_type != 4) {													//if not short answer...
			for (var i = 0; i <= (mc_items-1); i++) {
				if (fieldno[i].checked == true) {				//for multiple choice
					checkedButton = fieldno[i].value;
     		}
    	}
	 	}
	 	else {
    	checkedButton = fieldno.value;  //for short answer
    }
    student_answer = checkedButton;
    if (checkedButton.toUpperCase() == which_array[0].toUpperCase()) {  //if answer is right...
      feedback = eval("feedbackRight" + no);
      correct = "yes";

      if (skip[no]) {
				feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
	    	skip[no] = true;
      }
    }
    else {
    	feedback = eval("feedbackWrong" + no);

      if (eval("showCorrect" + no) == "yes") {
        right_string = ' The correct response: ' + which_array[0] + '.';
        feedback = feedback + '<br><span style="font-size: 90%;">' + right_string + '</span>';
      }
      correct = "no";
      if (main.document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
      	main.document.getElementById(eval("feedbackHighlight" + no)).style.color = 'red';
        highlighted = eval("feedbackHighlight" + no);
        feedback = feedback + IN_RED;
      }
		}
	}

  if (which_array.length > 1) {						//if more than one right answer (short answer)
		if (q_type == 4) {										//if short answer...
    	correct = "no";											//unless answer is found in array...
    	student_answer = fieldno.value;
    	for (var i = 0; i <= (which_array.length - 1); i++) {
     		if (fieldno.value.toUpperCase() == which_array[i].toUpperCase()) {
       		feedback = eval("feedbackRight" + no);
       		correct = "yes";

       		if (skip[no]) {
       			feedback = BEEN_ANSWERED;
       		}
       		else {
          	my_score = my_score + q_value[no];
	          skip[no] = true;
					}
       		break;
				}
     	}

    	if (correct == "no") {
      	feedback = eval("feedbackWrong" + no);

      	if (eval("showCorrect" + no) == "yes") {
          right_string = ' The correct response(s): ' + which_array + '.';
          feedback = feedback + '<br><span style="font-size: 90%;">' + right_string + '</span>';
      	}
      	if (main.document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
        	main.document.getElementById(eval("feedbackHighlight" + no)).style.color = 'red';
        	highlighted = eval("feedbackHighlight" + no);
        	feedback = feedback + IN_RED;
      	}
    	}
    }
	}

  if (q_type == 3) {                              //if multiple answer...
		var my_answers = "";
  	for (var i = 0; i <= (mc_items - 1); i++) {
      if (fieldno[i].checked) {
        checkedButton = fieldno[i].value;
        my_answers = which_array[0];
        get_answers[get_answers.length] = checkedButton;

        if (my_answers.indexOf(checkedButton) != -1) {
          correct = "partial";
        }
      }
    }

    if (my_answers.length == 0) {
    	imageno.src = "spacer.gif";
    	alert("No answers have been selected.");
    	return;
    }
    student_answer = get_answers;
    if (get_answers == my_answers) {
    	correct = "yes";
      feedback = eval("feedbackRight" + no);

      if (skip[no]) {
        feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
	    	skip[no] = true;
      }
    }
    else {
      if (correct == "partial")  {
        feedback = eval("feedbackPartial" + no);
      }
      else {
      	correct = "no";
      	feedback = eval("feedbackWrong" + no);
      }

  	}

    if (correct == "no") {
      if (eval("showCorrect" + no) == "yes") {
        right_string = ' The correct response(s): ' + which_array + '.';
        feedback = feedback + '<br><span style="font-size: 90%;">' + right_string + '</span>';
      }
      if (main.document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
        main.document.getElementById(eval("feedbackHighlight" + no)).style.color = 'red';
        highlighted = eval("feedbackHighlight" + no);
        feedback = feedback + IN_RED;
      }
    }
  }

  if (q_type == 5) {                               //if matching...
		correctly_matched = new Array();
    correct_matches = new Array();
    student_answers = new Array();

  	for (var i = 1; i <= (mc_items); i++) {
  	  fieldno = eval("main.document.f" + no + ".q" + no + "_" + i);
  	  student_answers[(i-1)] = fieldno.options[fieldno.options.selectedIndex].value;
  	  correctField = fieldno.options[which_array[(i - 1)]].value;
  	  correct_matches[correct_matches.length] = " " + i + " = " + correctField;

      if(fieldno.options.selectedIndex == which_array[(i - 1)]){
        correctly_matched[correctly_matched.length] = i;
      }
    }
    if (correctly_matched.length == which_array.length){
      feedback = eval("feedbackRight" + no);
      feedback = feedback + " All items correctly matched!";
      correct = "yes";

      if (skip[no]) {
        feedback = BEEN_ANSWERED;
      }
      else {
				my_score = my_score + q_value[no];
	     	skip[no] = true;
      }
    }
    else {
      if (correctly_matched.length > 0) {
      	correct = "partial";
        feedback = eval("feedbackPartial" + no);
        feedback = feedback + " Correctly matched: " + correctly_matched;
      }
      else {
      	correct = "no";
        feedback = eval("feedbackWrong" + no);
        if (eval("showCorrect" + no) == "yes") {
        	right_string = ' The correct matchings: ' + correct_matches + '.';
        	feedback = feedback + '<br><span style="font-size: 90%;">' + right_string + '</span>';
        }
      }
    }
    student_answer = student_answers;
  }

	if (q_type == 6) {                               //if ordering...
    correctly_matched = new Array();
    correct_matches = new Array();
    student_answers = new Array();

  	for (var i = 1; i <= (mc_items); i++) {
  	  fieldno = eval("main.document.f" + no + ".q" + no + "_" + i);
  	  student_answers[(i - 1)] = fieldno.options[fieldno.options.selectedIndex].value;
  	  correctField = fieldno.options[which_array[(i - 1)]].value;
  	  correct_matches[correct_matches.length] = " " + i + " = " + correctField;

      if(fieldno.options.selectedIndex == which_array[(i - 1)]){
        correctly_matched[correctly_matched.length] = i;
      }
    }

    if (correctly_matched.length == which_array.length) {
    	feedback = eval("feedbackRight" + no);
      feedback = feedback + " All items correctly ordered!";
      correct = "yes";

      if (skip[no]) {
        feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
	    	skip[no] = true;
      }
    }
    else {
      if (correctly_matched.length > 0) {
        feedback = eval("feedbackPartial" + no);
        correct = "partial";
      }
      else {
        feedback = eval("feedbackWrong" + no);
        if (eval("showCorrect" + no) == "yes") {
        	right_string = ' The correct order: ' + correct_matches + '.';
        	feedback = feedback + '<br><span style="font-size: 90%;">' + right_string + '</span>';
        	correct = "no";
        }
      }
    }
    student_answer = student_answers;
	}
	if (correct == "yes") imageno.src = "check.gif";
	else imageno.src = "wrong.gif";

  myWin(feedback, correct, no, q_type, student_answer, right_string);

  //these are all local variables,
  //don't need to reset

	//correct = "";
	//feedback = "";
	//right_string = "";
	//checkedButton = "";                                //reset the values...
  //student_answer = "";
  //get_answers = "";
}


function hint(no) {
  my_hint = eval("hint" + no);
  my_hint_highlight = eval("hintHighlight" + no);

  if (main.document.getElementById && (my_hint_highlight != 'none')) {
    main.document.getElementById(my_hint_highlight).style.color = 'red';
    highlighted = my_hint_highlight;
  }

  if (!eval('inline_feedback' + no)) {
    winSpecs = 'width=400,height=200,resizable=yes,scrollbars=yes';
    win = window.open ("", 'pic', winSpecs);
    win.document.open();
    win.document.clear();
    win.document.write("<html><head><title>Hint:</title></head><body style='font-family: Verdana, Helvetica, sans-serif;'>");
    win.document.write(CLOSE_THIS_WINDOW);
    win.document.write(my_hint);
    win.document.write("</body></html>");
    win.document.close();
    win.focus();
  }
  else {
  	clearMe(no);
    main.document.getElementById("hint" + no).innerHTML = my_hint;
    hint[no] = true;
    togglefeed(no,"hint", false);
  }
}


function clear_highlight(no, mc_items, q_type) {
	var imageno = eval("main.document.check" + no);
	imageno.src = "spacer.gif";

	if (highlighted != "none") {
  	if(main.document.getElementById) {
  		main.document.getElementById(highlighted).style.color = 'black';
  	}
  }

  if (q_type == 5 || q_type == 6) {	                 //if matching or ordering...
  	for (var i = 1; i <= (mc_items); i++) {
  		fieldno = eval("main.document.f" + no + ".q" + no + "_" + i);
  	  fieldno.options.selectedIndex = 0;
    }
  }
  else {
    fieldno = eval("main.document.f" + no + ".q" + no);

    for (var i = 0; i <= (mc_items - 1); i++) {
      if (fieldno[i].checked == true) {
  	    fieldno[i].checked = false;
      }
    }
    if (fieldno.value){fieldno.value = "";}
  }

  if (eval('inline_feedback' + no)) {
  	for (i = 0; i < inlineIDs.length; i++) {
	  	togglefeed(no, inlineIDs[i], true);
	  }
	}
}


function toggletable(which) {                    //hides or displays quiz question
  if (tableToggle_array[which]) {
    tableToggle_array[which] = false;
    setShow(which, false);
  }
  else {
    tableToggle_array[which] = true;
    setShow(which, true);
  }
}


function togglefeed(no, which, hide) {						//hides or displays inline feedback
  my_item_value = eval(which + "[" + no + "]");
  if (!hide) {
    if (!my_item_value) {
      setState(no, which, true);
      setShow(which + no, false);
    }
    else {
      setState(no, which, false);
      setShow(which + no, true);
    }
	}
  else {
    for (i = 0; i < inlineIDs.length; i++) {
	  	setState(no, inlineIDs[i], false);
	  }
    setShow(which + no, false);
  }
}


function setState(no, which, state) {
	if (which == "feed") {feed[no] = state;}
  else if (which == "f_right") {f_right[no] = state;}
  else if (which == "f_wrong") {f_wrong[no] = state;}
  else if (which == "f_show_correct") {f_show_correct[no] = state;}
  else if (which == "f_done") {f_done[no] = state;}
  else if (which == "f_partial") {f_partial[no] = state;}
  else if (which == "hint") {hint[no] = state;}
}


function setShow(elemId, show) {
	var elem = main.document.getElementById(elemId);
	if (show) {
		elem.style.position = 'relative';
		elem.style.visibility = 'visible';
		elem.style.display= 'block';
	}
	else {
		elem.style.position = 'absolute';
		elem.style.visibility = 'hidden';
		elem.style.display= 'none';
	}
}


function clearMe(no) {
	for (i = 0; i < inlineIDs.length; i++) {
  	setShow(inlineIDs[i] + no, false);
  }
}


function myWin(stuff, correct, no, q_type, student_answer, right_string) {
	var this_q_points = 0;
	var total_score = Math.round((my_score / total_points) * 100);

  if ((correct == "yes") && (stuff != BEEN_ANSWERED)) {
  	this_q_points = q_value[no];
  }

	if (!eval('inline_feedback' + no)) {
    winSpecs = 'width=400,height=200,resizable=yes,scrollbars=yes';
    win = window.open("", 'pic', winSpecs);
    win.document.open();
    win.document.clear();
    win.document.write("<html>\n<head>\n<title>Feedback:</title>\n</head>\n<body style='font-family: Arial, Helvetica, sans-serif;'>\n");
    win.document.write(CLOSE_THIS_WINDOW);
    win.document.write(stuff);
    if (q_value[no] > 0) {
      win.document.write("<div style=\"font-size: 90%; font-family: 'Comic Sans MS'; border-top: 1px solid #000000; margin-top: 10px;\"><br>\n" +
      									 "Points scored this item: <span style=\"font-weight: bold;\">" + this_q_points + "</span>.\n" +
      									 //<br>\n" +
												 //"Total points scored: <span style=\"font-weight: bold;\">" + my_score + " of " + total_points + "</span>.<br>\n" +
												 //"Percent correct: <span style=\"font-weight: bold;\">" + total_score + "</span>.\n" +
												 "</div>\n");
    }
    win.document.write("</body>\n</html>");
    win.document.close();
    win.focus();
  }
  else {
    clearMe(no);

   	if (stuff != BEEN_ANSWERED) {
   		if (correct == "partial") {
   			main.document.getElementById("f_partial" + no).innerHTML = eval("feedbackPartial" + no);
     		f_partial[no] = true;
     		togglefeed(no,"f_partial", false);
   		}
     	else if (correct == "yes") {
     		main.document.getElementById("f_right" + no).innerHTML = eval("feedbackRight" + no);
     		f_right[no] = true;
     		togglefeed(no, "f_right", false);
     	}
     	else {
     		main.document.getElementById("f_wrong" + no).innerHTML = eval("feedbackWrong" + no);
     		f_wrong[no] = true;
     		togglefeed(no, "f_wrong", false);

				if (eval("showCorrect" + no) == "yes") {
					main.document.getElementById("f_show_correct" + no).innerHTML = right_string;
					f_show_correct[no] = true;
     			togglefeed(no, "f_show_correct", false);
				}
   		}
   	}
   	else {
   		this_q_points = q_value[no];
   		main.document.getElementById("f_done" + no).innerHTML = BEEN_ANSWERED;
     	f_done[no] = true;
     	togglefeed(no, "f_done", false);
   	}

		if (q_value[no] > 0) {
			main.document.getElementById("feed" + no).innerHTML = "<br>Points scored this item: <b>" + this_q_points + "</b>.";
			feed[no] = true;
			togglefeed(no, "feed", false);
    }
  }

  if (q_value[no] > 0) {
		main.stayTopLeft();
		main.document.getElementById("floatingscore").style.visibility = "visible";
		main.document.getElementById("my_score_span").innerHTML = "Score:<br><b>" + my_score + ' of ' + total_points;
  }

  my_status = "incomplete";
  if (attempted_q == totalQ) {
   if (scorm_completed_status == true) {
  	 my_status = "completed";
   }
  }
  if (scorm) {
  	var  act_type = 0; // just a place holder
  	var  act_percent = 0; // just a place holder
  	sendScorm(my_status, total_points, my_score, no, q_type, act_type, student_answer, correct, act_percent);
  }
}


function quit_lesson() {
	if (scorm) {
    ScormOnunload();
	}
	else {
		window.opener = top;
  	window.close();
	}
}


function startTimer() {
  startDate = new Date().getTime();
  my_date=startDate;
}


function getLessonTime() {
  var startDate = my_date;
  var my_time = "0";
  if ( startDate != 0 ) {
  	var currentDate = new Date().getTime();
    var elapsed_Seconds = ((currentDate - startDate) / 1000);
    if (elapsed_Seconds < 60) {
      my_time = Math.round(elapsed_Seconds) + " seconds";
    }
    else if (elapsed_Seconds > 3600) {
    	var whole_hours = Math.round(elapsed_Seconds / 3600);
    	var whole_secs = (whole_hours * 3600);
    	var rem_minutes = (elapsed_Seconds - whole_secs) / 60;
    	rem_minutes = Math.round(rem_minutes);
    	if (rem_minutes > 0) {
      	my_time = whole_hours + " hours and " + rem_minutes + " minutes";
    	}
    	else {
    		my_time = whole_hours + " hours";
    	}
		}
		else {
			my_time = Math.round(elapsed_Seconds / 60) + " minutes";
  	}
  }
  return my_time;
}


function lessonReport(which) {
	var userName = main.document.send_form.user_name.value;

	if (userName == "") {
		alert("Please type your name into the form field.");
		main.document.send_form.user_name.focus();
		return false;
	}

  var total_score = Math.round((my_score / total_points) * 100);

  if (which == "email") {
  	main.document.send_form.my_lesson.value = parent.document.title;
	  main.document.send_form.my_attempted_points.value = attempted_points;
	  main.document.send_form.my_score.value = total_score;
	  main.document.send_form.my_time_spent.value = getLessonTime();
	  main.document.send_form.total_points.value = total_points;
	  main.document.send_form.my_scored_points.value = my_score;
		return true;
  }

	if (which == "certificate" && (total_score < passing_score)) {
		alert("Your score of " + total_score + "% does not meet the passing score of " + passing_score +
					"%.\nPlease try to improve your score.");
		return false;
	}


  var winTitle;
  var getstring;
  var flName = which;

  if (which == "certificate") {
    winTitle = "Certificate";
    getstring = "&name=" + userName;
  }
  else {
  	winTitle = "Score Summary";
		getstring = "&name=" + userName + "&points=" + total_points + "&timespent=" +
								getLessonTime() + "&attempted=" + attempted_points + "&correct=" + my_score + "&score=" + total_score;
  }

	var obWidth = "925";
	var obHeight = "775";
	var winSpecs = "width=700,height=500,resizable=yes,scrollbars=yes,menubar=yes";
	win = window.open("", "pic", winSpecs);
  win.document.open();
  win.document.clear();
  win.document.write("<html>\n<head>\n<title>" + winTitle + "</title>\n" +
										 "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />\n" +
										 "</head>\n" +
										 "<body>\n" +
										 "<p align='center'>\n" +
										 "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' " +
										 "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' " +
										 "width='" + obWidth + "' height='" + obHeight + "' align='middle' id='" + flName + "'>\n" +
  									 "<param name='allowScriptAccess' value='sameDomain' />\n" +
										 "<param name='movie' value='" + flName + ".swf' />\n" +
										 "<param name='quality' value='high' />\n" +
										 "<param name='bgcolor' value='#ffffff' />\n" +
										 "<param name=FlashVars value='" + getstring + "' />\n" +
										 "<embed src='" + flName + ".swf' name='" + flName + "' " +
										 "quality='high' bgcolor='#ffffff' " +
										 "width='" + obWidth + "' height='" + obHeight + "' align='middle' " +
										 "FlashVars='" + getstring + "' " +
										 "allowScriptAccess='sameDomain' type='application/x-shockwave-flash' " +
										 "pluginspage='http://www.macromedia.com/go/getflashplayer' />\n" +
										 "</object>\n" +
										 "</p>\n" +
										 "</body>\n</html>\n");
  win.document.close();
  win.focus();
	return true;
}
