var originalContent = null;
var pendingQuestions = 0;
var color_correct   = "#66FF66";//"#44FF44";
var color_incorrect = "#FF6666";//"#FF4444";

// Element is undefined in IE.
//Element.prototype.getElementsByClassName = getElementsByClassName;

function removeBlanks(object)
{
  if (originalContent)
    {
      object.innerHTML = originalContent;
    }
}

function getElementsByClassName(element, className, result)
{
  if (!result) result = new Array();

  if (element.className == className) result.push(element);

  if (element.hasChildNodes())
    {
      var child;
      child = element.firstChild;
      do
        {
          getElementsByClassName(child, className, result);
          child = child.nextSibling;
        }
      while (child);
    }

  return result;
}

function insertTextFrom(text_document_url)
{
  var text_container;
  text_container = document.getElementById('questions');
  if (!text_container)
    text_container = document.getElementById('questions_container');

  try
    {
      var request;
      request = new XMLHttpRequest();
      request.open("GET", text_document_url, false);
      request.send(null);

      content = request.responseXML;
      if (content.getElementById("questions"))
        {
          text_container.setAttribute("id", "questions_container");
        }
      else
        {
          text_container.setAttribute("id", "questions");
        }

      content = content.getElementsByTagName("body")[0];
      while (content.firstChild)
        {
          text_container.appendChild(content.firstChild);
        }
    }
  catch (e)
    {
      text_container.appendChild(document.createTextNode(e));
    }
}

function makeBlanksFromPlainText(percentQuestionsPerPage, words, object)
{
  if (! originalContent)
    {
      originalContent = object.innerHTML;
    }
  var word_list;
  word_list = words.split(" ");
  var words_regexps;
  words_regexps = new Array();
  var word_prefix;
  var word_suffix;
  for (var i in word_list)
    {
      var word;
      word = word_list[i].replace(/_/g, "[ \t\n]+");

      if ("-" == word[0])
        {
          word_prefix = "(";
          word = word.substring(1);
        }
      else
        {
          word_prefix = "(\\b";
        }
      if ("-" == word[word.length - 1])
        {
          word_suffix = ")";
          word = word.substring(0, word.length - 1);
        }
      else
        {
          word_suffix = "\\b)";
        }

      if (word.indexOf("(") < 0) word = ")(" + word + ")(";
      else                       word = word.replace(/[()]/g, ")(");

      words_regexps.push(new RegExp(word_prefix + word + word_suffix, "g"));
    }

  var regexp;
  for (var i in words_regexps)
    {
      regexp = words_regexps[i];
      object.innerHTML = object.innerHTML.replace(regexp, "$1<span class='blank'>$2</span>$3");
    }
  makeBlanks(percentQuestionsPerPage, "blank", object);
}

function focusFirstBlank(container_node)
{
  var input_fields = container_node.getElementsByTagName("input");
  if (input_fields.length > 0)
    {
      window.first_blank = input_fields[0];
      window.setTimeout("window.first_blank.focus()", 100);
    }
}

function makeBlanks(percentQuestionsPerPage, className, object)
{
  if (! originalContent)
    {
      originalContent = object.innerHTML;
    }
  var elements;
  elements = getElementsByClassName(object, className, elements);

  convertElementsToBlanks(percentQuestionsPerPage, elements);

  focusFirstBlank(object.ownerDocument.getElementById("questions"));
}

function makeBlanksByTagName(percentQuestionsPerPage, tagName, object)
{
  if (! originalContent)
    {
      originalContent = object.innerHTML;
    }
  var elements;
  elements = object.getElementsByTagName(tagName);

  convertElementsToBlanks(percentQuestionsPerPage, elements);

  focusFirstBlank(object.ownerDocument.getElementById("questions"));
}

function convertElementsToBlanks(percent, elements)
{
  var index;
  var elementsLength;
  elementsLength = elements.length;
  if (elementsLength < 2)
    {
      alert("elementsLength = " + elementsLength);
      return;
    }

  var questionCount;
  questionCount = Math.floor(percent * elementsLength / 100);
  pendingQuestions = questionCount;

  var blankSize;
  var blankClass;
  var blankText;
  var node;
  var i = 0;
  while (i < questionCount && i < elementsLength)
    {
      index = Math.round(Math.random() * (elementsLength - 0.5));
      node = elements[index];
      //if (node.parentNode.nodeName == "SPAN" || node.parentNode.nodeName == "span") alert("Span parent: " + node.parentNode.nodeName);
      if (node.getElementsByTagName("input").length == 0)
        {
          blankSize = 6;// Minimum size.
          blankClass = "blank";
          blankText = node.innerHTML;
          if (blankText.length > blankSize) blankSize = blankText.length + 2;
          switch (node.nodeName)
            {
            case "td":
            case "TD":
              blankClass = "blank_table";
              break;
            default:
              if (node.previousSibling
                  && "#text" == node.previousSibling.nodeName
                  && node.previousSibling.nodeValue.match(/\w$/))
                {
                  blankText = "-" + blankText;
                  blankClass = "blank_suffix";
                }
              if (node.nextSibling
                  && "#text" == node.nextSibling.nodeName
                  && node.nextSibling.nodeValue.match(/^\w/))
                {
                  blankText = blankText + "-";
                  blankClass = "blank_prefix";
                }
              break;
            }

          ++i;
          elements[index].innerHTML
            = "<input"
            + " class='" + blankClass + "'"
            + " size='" + blankSize + "'"
            + " onchange='check(this, \"" + blankText + "\");'"
            + " onkeypress='keypress(event, this, \"" + blankText + "\");'"
            + "></input>";
        }
    }

  focusFirstBlank(node.ownerDocument.getElementById("questions"));
}

// The stupid IE does not send a change event when the user presses Enter,
// so we have to do this.
function keypress(event, blank, correctValue)
{
  if (event.keyCode == 13) check(blank, correctValue);
  return false;
}

function check(blank, correctValue)
{
  var help_requested;
  help_requested = false;

  if (blank.value && "?" == blank.value.charAt(blank.value.length - 1))
    {
      help_requested = true;
      blank.value = blank.value.substring(0, blank.value.length - 1);
    }

  if (canonical_form(blank.value) == canonical_form(correctValue))
    {
      var previous_color;
      previous_color = blank.style.backgroundColor;
      blank.style.backgroundColor = color_correct;
      if (blank.style.backgroundColor == previous_color)
        {
          if (help_requested)
            {
              alert("Ja, klar ist es \"" + correctValue + "\"!");
              //blank.focus();
            }
          //alert("Yu'cheatin', mon!");
        }
      else
        {
          if (help_requested)
            {
              alert("Ja, es ist \"" + correctValue + "\".");
            }
          // Display the most correct valid form.
          blank.value = correctValue.replace(/-/g, "");// Pre- and suffixes.
          //blank.focus();
          --pendingQuestions;

	  if (0 == pendingQuestions)
	  {
	    alert("Sehr gut!");
	  }
        }

      // Go to next blank:
      var blanks;
      blanks = blank.ownerDocument
        .getElementById("questions")
        .getElementsByTagName("input");
      var next_blank;
      for (var i = 0; i < blanks.length; ++i)
        {
          if (blanks[i] == blank)
            {
              if (i+1 < blanks.length) next_blank = blanks[i+1];
              else                     next_blank = document.getElementById('continue_button');//blanks[0];
	      if (next_blank) next_blank.focus();
              //next_blank.select();
              break;
            }
        }
    }
  else
    {
      blank.style.backgroundColor = color_incorrect;
      ++pendingQuestions;
      if (help_requested)
        {
          if (blank.value)
            {
              var givenAnswer;
              switch (blank.getAttribute("class"))
                {
                case "blank_prefix": givenAnswer = blank.value + "-"; break;
                case "blank_suffix": givenAnswer = "-" + blank.value; break;
                default:
                  givenAnswer = blank.value;
                  break;
                }
              alert("Es ist nicht \"" + givenAnswer
                    + "\", sondern \"" + correctValue + "\".");
            }
          else
            {
              alert("Hast du echt keine Ahnung, oder bist du einfach faul?\nEs ist \"" + correctValue + "\".");
            }
          blank.focus();
        }
    }
}

function canonical_form(string)
{
  return (string
          .replace(/ss/g, "ß")
          .replace(/oe/g, "ö")
          .replace(/ae/g, "ä")
          .replace(/ue/g, "ü")
          .replace(/-/g, "")// For pre- and suffixes.
          .replace(/ +/g, "")
          );
}

function reload()
{
  // There is no "window.reload()", but this seems to work.
  //window.location.href = window.location.href;
}
