/**
 *  ==================================================
 *  SoftChalk Lesson Builder
 *  Copyright 2003-2004 SoftChalk LLC
 *  All Rights Reserved.
 *
 *  ==================================================
 *  For additional information, please contact
 *  http://www.softchalk.com
 *  help@softchalk.com
 *
 *  ==================================================
 *  File date: December 16, 2004
 */

/**
 *	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
 *  rand_no 	random number set by lessonbuilder when file is created for unique cookie names
 *
 *	"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[], rand_no, 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 student_answer = "";	//what the student submitted

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>";


skip = new Array();				//monitors if question has already been answered correctly
q_value = new Array();		//gets value of variable q_value from lesson.js and converts to value in this array


/**
 *  Determined which questions are to be scored
 */
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 = total_points + q_value[i];
	}
}


/**
 *  If the cookies exist, get their data
 */
var attempted_points_cookie = GetCookie('attempted_points_cookie' + rand_no);
if (attempted_points_cookie) {
	attempted_points = parseInt(attempted_points_cookie);
}

var attempted_q_cookie = GetCookie('attempted_q_cookie' + rand_no);
if (attempted_q_cookie) {
	attempted_q = parseInt(attempted_q_cookie);

}

var my_score_cookie = GetCookie('my_score_cookie' + rand_no);
if (my_score_cookie) {
	my_score_cookie = parseInt(my_score_cookie);
	if (my_score_cookie > my_score) {
		my_score = my_score_cookie;
	}
}


/**
 *  Called when "Check Answer" button is clicked
 */
function check_q(no, mc_items, q_type) {
	if (q_done[no] == false) {
		if (GetCookie(('done_q' + no + rand_no)) != "true") {
			attempted_q++;
	   	attempted_points = attempted_points + q_value[no];
	   	SetCookie("attempted_points_cookie" + rand_no, attempted_points);
	   	SetCookie("attempted_q_cookie" + rand_no, attempted_q);
      my_done = true;
	   	SetCookie(('done_q' + no + rand_no), my_done);
	   	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("document.f" + no + ".q" + no); // input name
	var imageno = eval("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 (GetCookie(('skip' + no + rand_no)) == "true") {
				feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
        my_skip=true;
	      SetCookie(('skip' + no + rand_no), my_skip);
	      SetCookie("my_score_cookie" + rand_no, my_score);
	      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 (document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
      	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 (GetCookie(('skip' + no + rand_no)) == "true") {
       			feedback = BEEN_ANSWERED;
       		}
       		else {
          	my_score = my_score + q_value[no];
            my_skip = true;
	          SetCookie(('skip' + no + rand_no), my_skip);
	          SetCookie("my_score_cookie" + rand_no, my_score);
	          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 (document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
        	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 == true) {
        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 (GetCookie(('skip' + no + rand_no)) == "true") {
        feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
        my_skip = true;
	    	SetCookie(('skip' + no + rand_no), my_skip);
	    	SetCookie("my_score_cookie" + rand_no, my_score);
	    	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 (document.getElementById && (eval("feedbackHighlight" + no) != "none")) {
        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("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 (GetCookie(('skip' + no + rand_no)) == "true") {
        feedback = BEEN_ANSWERED;
      }
      else {
				my_score = my_score + q_value[no];
        my_skip=true;
	     	SetCookie (('skip' + no + rand_no), my_skip);
	     	SetCookie ("my_score_cookie" + rand_no, my_score);
	     	skip[no] = true;
	     	//imageno.src = "check.gif";
      }
    }
    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("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 (GetCookie(('skip' + no + rand_no)) == "true") {
        feedback = BEEN_ANSWERED;
      }
      else {
      	my_score = my_score + q_value[no];
        my_skip = true;
	     	SetCookie(('skip' + no + rand_no), my_skip);
	     	SetCookie("my_score_cookie" + rand_no, my_score);
	     	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);
	correct = "";
	feedback = "";
	right_string = "";
	checkedButton = "";                                //reset the values...
  student_answer = "";
  get_answers = "";
  my_done = false;
  my_skip = false;
}

function hint(no) {
  my_hint = eval("hint" + no);
  my_hint_highlight = eval("hintHighlight" + no);

  if (document.getElementById && (my_hint_highlight != 'none')) {
    document.getElementById(my_hint_highlight).style.color = 'red';
    highlighted = my_hint_highlight;
  }
  if (eval('inline_feedback' + no) != true) {
    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: Arial, 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 {
    the_hint = "hint" + no;
    temp = document.getElementById(the_hint);
    temp.style.position = 'relative';
    temp.style.visibility = 'visible';
    temp.style.display = 'block';
  }
}

function clear_highlight(no, mc_items, q_type) {
	var imageno = eval("document.check" + no);
	imageno.src = "spacer.gif";

	if (highlighted != "none") {
  	if(document.getElementById) {
  		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("document.f" + no + ".q" + no + "_" + i);
  	  fieldno.options.selectedIndex = 0;
    }
  }
  else {
    fieldno = eval("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) == true) {
    togglefeed(no, "feed", true);
    togglefeed(no, "f_right", true);
    togglefeed(no, "f_wrong", true);
    togglefeed(no, "f_show_correct", true);
    togglefeed(no, "f_done", true);
    togglefeed(no, "hint", true);
    togglefeed(no, "f_partial", true);
   }
}

function toggletable(which) {                    //hides or displays quiz question
  temp = document.getElementById(which);

  if (tableToggle_array[which] == true) {
    tableToggle_array[which] = false;
    temp.style.position = 'absolute';
    temp.style.visibility = 'hidden';
    temp.style.display= 'none';
  }
  else {
    tableToggle_array[which] = true;
    temp.style.position = 'relative';
    temp.style.visibility = 'visible';
    temp.style.display= 'block';
  }
}

function togglefeed(no, which, hide) {						//hides or displays inline feedback
  my_item_value = eval(which + "[" + no + "]");
  temp = document.getElementById(which + no);
  if (hide == false) {
    if (my_item_value == false) {
      setState(which, true);
      temp.style.position = 'absolute';
      temp.style.visibility = 'hidden';
      temp.style.display = 'none';
    }
    else {
      setState(which, false);
      temp.style.position = 'relative';
      temp.style.visibility = 'visible';
      temp.style.display = 'block';
    }
	}
  else {
    feed[no] = false;
    f_right[no] = false;
    f_wrong[no] = false;
    f_show_correct[no] = false;
    f_done[no] = false;
    f_partial[no] = false;
    hint[no] = false;
    temp.style.position = 'absolute';
    temp.style.visibility = 'hidden';
    temp.style.display= 'none';
  }
}

function setState(no, which, state) {
	if (which == "feed") {feed[no] = state;}
  if (which == "f_right") {f_right[no] = state;}
  if (which == "f_wrong") {f_wrong[no] = state;}
  if (which == "f_show_correct") {f_show_correct[no] = state;}
  if (which == "f_done") {f_done[no] = state;}
  if (which == "f_partial") {f_partial[no] = state;}
  if (which == "hint") {hint[no] = state;}
}

function clearMe(no) {
    document.getElementById("feed" + no).style.position = 'absolute';
    document.getElementById("feed" + no).style.visibility = 'hidden';
    document.getElementById("feed" + no).style.display= 'none';
    document.getElementById("f_right" + no).style.position = 'absolute';
    document.getElementById("f_right" + no).style.visibility = 'hidden';
    document.getElementById("f_right" + no).style.display= 'none';
    document.getElementById("f_wrong" + no).style.position = 'absolute';
    document.getElementById("f_wrong" + no).style.visibility = 'hidden';
    document.getElementById("f_wrong" + no).style.display= 'none';
    document.getElementById("f_show_correct" + no).style.position = 'absolute';
    document.getElementById("f_show_correct" + no).style.visibility = 'hidden';
    document.getElementById("f_show_correct" + no).style.display= 'none';
    document.getElementById("f_done" + no).style.position = 'absolute';
    document.getElementById("f_done" + no).style.visibility = 'hidden';
    document.getElementById("f_done" + no).style.display= 'none';
    document.getElementById("f_partial" + no).style.position = 'absolute';
    document.getElementById("f_partial" + no).style.visibility = 'hidden';
    document.getElementById("f_partial" + no).style.display= 'none';
    document.getElementById("hint" + no).style.position = 'absolute';
    document.getElementById("hint" + no).style.visibility = 'hidden';
    document.getElementById("hint" + no).style.display= 'none';
}

function myWin(stuff, correct, no, q_type, student_answer, right_string) {
	var this_q_points = 0;

  my_score_cookie = GetCookie('my_score_cookie' + rand_no);
  my_score_cookie = parseInt(my_score_cookie);
  if (my_score_cookie > my_score) {
  	my_score = my_score_cookie;
  }

  attempted_points_cookie = GetCookie('attempted_points_cookie' + rand_no);
  if (attempted_points_cookie) {
  	attempted_points = parseInt(attempted_points_cookie);
  }

  percent = Math.round((my_score / attempted_points) * 100);

  if ((correct == "yes") && (stuff != BEEN_ANSWERED)) {
  	this_q_points = q_value[no];
  }

	if (eval('inline_feedback' + no) != true) {
    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>Feedback:</title></head><body style='font-family: Arial, Helvetica, sans-serif;'>");
    win.document.write(CLOSE_THIS_WINDOW);
    win.document.write(stuff);
    if (q_value[no] > 0) {
      win.document.write('<br><br><div style="text-align: center; font-size: 90%; border-top: 1px solid #000000;">' +
      									 'Points scored: ' + this_q_points + '.<br>' +
												 'Total points scored: ' + my_score + '. Percent correct: ' + percent + '.</div>');
    }
    win.document.write("</body></html>");
    win.document.close();
    win.focus();
  }
  else {
    clearMe(no);

    if (q_value[no] > 0) {
    	if (stuff != BEEN_ANSWERED) {
    		if (correct == "partial") {
       		f_partial[no] = true;
       		togglefeed(no,"f_partial",false);
     		}
      	else if (correct == "yes") {
      		f_right[no] = true;
       		togglefeed(no, "f_right", false);
      	}
      	else {
       		f_wrong[no] = true;
       		togglefeed(no, "f_wrong", false);
       		if (eval("showCorrect" + no) == "yes") {
						document.getElementById("show_correct" + no).lastChild.nodeValue = right_string;
						f_show_correct[no] = true;
       			togglefeed(no, "f_show_correct", false);
					}
     		}
    	}
    	else {
    		this_q_points = q_value[no];
      	f_done[no] = true;
      	togglefeed(no, "f_done", false);
    	}

     	document.getElementById("this_q_points_span" + no).lastChild.nodeValue = this_q_points;
     	document.getElementById("my_score_span" + no).lastChild.nodeValue = my_score;
     	document.getElementById("percent_span" + no).lastChild.nodeValue = percent;
     	feed[no] = true;
     	togglefeed(no, "feed", false);
    }
  }
  my_status = "incomplete";
  if (attempted_q == totalQ) {
  	my_status = "completed";
  }
  if (scorm == true) {
  	sendScorm(my_status, total_points, my_score, no, q_type, student_answer, correct);
  }
}

function quit_lesson() {
	if (scorm == true) {
    ScormOnunload();
	}
	else {
		window.opener = top;
  	window.close();
	}
}

function SetCookie(name, value) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name) {
  annoNo = document.cookie.length;
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal(j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return  "";
}
function startTimer() {
  startDate = new Date().getTime();
  SetCookie("my_date" + rand_no, startDate);
}

function getTime() {
  startDate = parseInt(GetCookie('my_date' + rand_no));
  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"
   }
  }
  else {
  	my_time = "0";
  }
  return my_time;
}

