/**
 * Called after an answer is selected out of a set of predefined values
 */
function triggerAnswered(id, value) {
  dimQuestion(id);
  useAnswer(id, value);
  markAsAnswered(id);

  enableSubmit();
}

/**
 * Insert this answer into text of other questions
 */
function useAnswer(id, answerValue) {
  var questionTag = new RegExp('%QUESTION_'+id+'[^%]*%', 'g');
  // %QUESTION_1562|This was the answer%

  /*
   * If this is an answer from a predefined set of options then the format is like this:
   * sequence|value
   * Store only the real value.
   */
  var pipePosition = answerValue.indexOf('|');
  if (pipePosition)
    answerValue = answerValue.substr(pipePosition+1, answerValue.length - pipePosition - 1);

  /*
   * Traverse all children and check whether just answered question isn't among their parents
   */
  for (var childId in linkedQuestionsChildren) {
    var arrayParents = linkedQuestionsChildren[ childId ];

    for (var i in arrayParents) {
      /*
       * If just answered question is a parent of this child
       * then regexp it's question text for %QUESTION_?|value%
       */
      if (arrayParents[i] == id) {
        var templateElement = document.getElementById('template_'+childId);
        var templateValue = templateElement.innerHTML;
//        var templateValue = templateElement.firstChild.nodeValue;
        templateValue = templateValue.replace(questionTag, '%QUESTION_'+id+'|'+answerValue+'%');
        templateElement.innerHTML = templateValue;
//        templateElement.firstChild.nodeValue = templateValue;

        updateQuestion(childId);
        break;
      }
    }
  }
}

/**
 * Manages lists of unanswered questions and dependancies for linked questions
 */
function markAsAnswered(id) {
  /*
   * Remove this question from unanswered questions list
   */
  unansweredQuestions = removeItem(unansweredQuestions, id);
  
  /*
   * Remove question from the list of dependencies so that dependant questions can be revealed
   */
  for (var childId in linkedQuestions) {
    var originalLength = linkedQuestions[ childId ].length;
    linkedQuestions[ childId ] = removeItem(linkedQuestions[ childId ], id);
    var newLength = linkedQuestions[ childId ].length;

    /*
     * Just answered question was the last of this child's parents
     */
    if ( (originalLength != newLength) && (newLength == 0) )
      showQuestion(childId);
  }
}

/**
 * Updates question text with template text without %QUESTION... tags
 */
function updateQuestion(id) {
  var questionTag = new RegExp('%QUESTION_[0-9]+\\|?([^%]*)%', 'g');
  // %QUESTION_1562|(This was the answer)%
  
  var templateElement = document.getElementById('template_'+id);
  var questionText = templateElement.innerHTML;
//  var questionText = templateElement.firstChild.nodeValue;
  questionText = questionText.replace(questionTag, '$1');
  
  var questionElement = document.getElementById('question_'+id);
  questionElement.innerHTML = questionText;
//  questionElement.firstChild.nodeValue = questionText;
}


/**
 * Unhides question text and options
 */
function showQuestion(id) {
  question = document.getElementById('question_'+id);
  question.style.display = 'block';

  answer = document.getElementById('answer_'+id);
  answer.style.display = 'block';
}

/**
 * Dims answered question
 */
function dimQuestion(id) {
  question = document.getElementById('question_'+id);
  question.className = 'questionnaire_question_answered';
 
  answer = document.getElementById('answer_'+id);
  answer.className = 'questionnaire_answer_answered';
}

/**
 * Removes given value from given array
 * @return modified array
 */
function removeItem(sourceArray, itemValue) {
  var outputArray = new Array(0);
  for (var i in sourceArray) {
    if (sourceArray[i] == itemValue) {
      continue;
    } else {
      outputArray[++outputArray.length - 1] = sourceArray[i];
    }
  }
  return outputArray;
}

/**
 * Enables Submit button after all obligatory questions are answered
 */
function enableSubmit() {
  submitButton = document.getElementById('submit');
  
  /*
   * Don't do anything until the whole page is loaded
   */
  if (submitButton == null)
    return;

  if (unansweredQuestions.length <= 0) {
    window.status = 'You have answered all obligatory questions. Now scroll down and click the Submit button.';

    submitButton.disabled = false;
    submitButton.value = 'Submit your answers';

  } else {
    helpText = 'You have yet ' + unansweredQuestions.length + ' obligatory ';
    if (unansweredQuestions.length == 1) helpText += 'question';
     else helpText += 'questions';
    helpText += ' to anwer.';

    window.status = helpText;

    submitButton.disabled = true;
    submitButton.value = helpText;
  }
}

