JT_EFFECT_DURATION = 0.3;


JumboTests = new function() {

  this.init = function()
  {
    for (i in JumboTests) if (JumboTests[i].init) JumboTests[i].init();
  }

  this.load = function()
  {
    for (i in JumboTests) if (JumboTests[i].load) JumboTests[i].load();
  }

  this.getDocumentHash = function()
  {
    var hash = document.location.hash;
    var name = (typeof hash == 'string') ? hash.gsub('#', '') : '';
    return name.blank() ? null : name;
  },

  this.track_event = function(category, action, optional_label, optional_value)
  {
    try {
      window.jtTracker._trackEvent(category, action, optional_label, parseInt(optional_value));
    } catch(err) {}
    try {
      window.pageTracker._trackEvent(category, action, optional_label, parseInt(optional_value));
    } catch(err) {}
  }
};


JumboTests.AutoFocus = new function() {

  this.init = function()
  {
    $$('input[tabindex="1"]').invoke('focus');
  }

};


JumboTests.Quiz = {

  init : function()
  {
    if (!$('test_base_time')) return;
    $('test_pause_resume_anchor').observe('click', this.pauseOrResumeViaEvent);
    this.resume();
  },

  load : function()
  {
    if (!$('test_base_time')) return;
    new PeriodicalExecuter(this.cycleTimer, 1);
  },

  cycleTimer : function()
  {
    if (JumboTests.Quiz.isPaused()) return;
    var new_time = (JumboTests.Quiz.getBaseTime() - 1);
    JumboTests.Quiz.setBaseTime(new_time);
    JumboTests.Quiz.updateClockDisplay(new_time);
    JumboTests.Quiz.updateClockStatus(new_time);
  },

  updateClockDisplay : function(seconds)
  {
    $('test_timer_clock').update(JumboTests.Time.toString(Math.abs(seconds)));
  },

  updateClockStatus : function(seconds)
  {
    if (!this.hasTimeLimit()) return;
    if (this.isPastTimeLimit()) {
      $('test_timer').addClassName('over-time-limit');
      $('test_timer').removeClassName('under-time-limit');
    } else {
      $('test_timer').addClassName('under-time-limit');
      $('test_timer').removeClassName('over-time-limit');
    }
  },

  isPastTimeLimit : function()
  {
    return this.hasTimeLimit() ? this.getBaseTime() < 0 : false;
  },

  pauseOrResumeViaEvent : function(event)
  {
    var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
    JumboTests.track_event('Tests', 'Paused/Resumed Test', $("quiz_id").value, current_anchor.gsub("question_", ""));
    event.stop();
    JumboTests.Quiz.togglePauseResume();
  },

  togglePauseResume : function()
  {
    this.isPaused() ? this.resume() : this.pause();
  },

  getBaseTime : function()
  {
    return parseInt($F('test_base_time'));
  },

  setBaseTime : function(value)
  {
    $('test_base_time').value = value;
  },

  getTimeLimit : function()
  {
    if (!$('test_time_limit')) return 0;
    return parseInt($F('test_time_limit'));
  },

  hasTimeLimit : function()
  {
    return this.getTimeLimit() == 0 ? false : true;
  },

  isPaused : function()
  {
    return 'true' == $F('test_is_paused');
  },

  pause : function()
  {
    $('test_is_paused').value = 'true';
    $('test_timer').addClassName('is-paused');
    $('test_pause_resume_anchor').removeClassName('pause');
    $('test_pause_resume_anchor').addClassName('resume');
  },

  resume : function()
  {
    $('test_is_paused').value = 'false';
    $('test_timer').removeClassName('is-paused');
    $('test_pause_resume_anchor').removeClassName('resume');
    $('test_pause_resume_anchor').addClassName('pause');
  }

}


JumboTests.QuizAnswers = {

  init : function()
  {
    if (!$('test_answers')) return;
    var anchors = $$('.evaluation-question-list-item-anchor');
    if (0 == anchors.size()) return;
    anchors.invoke('observe', 'click', this.switchThruEvent);
    $('next_answer_button').observe('click', this.next);
    $('previous_answer_button').observe('click', this.previous);
    this.goToFirstAnswer();
    if(!$('facebook_share')) return;
    $('facebook_share').observe('click', function() {
      JumboTests.track_event('Tests', 'Clicked FB Share', '')
    });
  },

  switchThruEvent : function(event)
  {
    var anchor = event.findElement('a');
    JumboTests.QuizAnswers.switchToAnswerByAnchorName(anchor.hash.gsub('#', ''));
    event.stop();
  },

  switchToAnswerByAnchorName : function(name)
  {
    var answer_anchor = $$('a[name=' + name + ']')[0];
    var menu_anchor = $$('.quiz-question-list-item a[href=#' + name + ']')[0];
    if (!answer_anchor || !menu_anchor) return;
    var menu = menu_anchor.up('.quiz-question-list-item');
    var answer = answer_anchor.up();
    JumboTests.QuizAnswers.switchToAnswer(answer);
    JumboTests.QuizAnswers.activateMenuItem(menu);
  },

  switchToAnswer : function(answer)
  {
    $('test_answers').show();
    $$('.quiz-answer').invoke('hide');
    answer.show();
  },

  activateMenuItem : function(menu_item)
  {
    $$('.quiz-question-list-item').invoke('removeClassName', 'active');
    menu_item.addClassName('active');
  },

  switchToSummaryViaEvent : function(event)
  {
    event.stop();
    JumboTests.QuizAnswers.switchToSummary();
  },

  switchToSummary : function()
  {
    $$('.quiz-question-list-item').invoke('removeClassName', 'active');
    $('test_answers').hide();
    $('test_results_summary').show();
  },

  goToFirstAnswerViaEvent : function(event)
  {
    event.stop();
    JumboTests.QuizAnswers.goToFirstAnswer();
  },

  goToFirstAnswer : function()
  {
    var anchor = $$('.quiz-answer a[name]')[0];
    if (!anchor) return;
    JumboTests.QuizAnswers.switchToAnswerByAnchorName(anchor.readAttribute('name'));
  },

  goToLastAnswer : function()
  {
    var anchors = $$('.quiz-answer a[name]');
    var anchor = anchors[anchors.length - 1];
    if (!anchor) return;
    JumboTests.QuizAnswers.switchToAnswerByAnchorName(anchor.readAttribute('name'));
  },

  next : function(event)
  {
    event.stop();
    $$('.quiz-answer').each(function(answer_container) {
      if (!answer_container.visible()) return;
      var next_container = answer_container.nextSiblings()[0];
      if (!next_container) return;
      var next_anchors = next_container.select('a[name]');
      if (typeof next_anchors[0] == 'undefined') {
        JumboTests.QuizAnswers.goToFirstAnswer();
      } else {
        var name = next_anchors[0].name;
        JumboTests.QuizAnswers.switchToAnswerByAnchorName(name);
      }
      throw $break;
    });
  },

  previous : function(event)
  {
    event.stop();
    $$('.quiz-answer').each(function(answer_container) {
      if (!answer_container.visible()) return;
      var next_container = answer_container.previousSiblings()[0];
      if (!next_container) return;
      var next_anchors = next_container.select('a[name]');
      if (typeof next_anchors[0] == 'undefined') {
        JumboTests.QuizAnswers.goToLastAnswer();
      } else {
        var name = next_anchors[0].name;
        JumboTests.QuizAnswers.switchToAnswerByAnchorName(name);
      }
      throw $break;
    });
  }
}


JumboTests.QuizQuestions = {
  load : function()
  {
    if ($('view_url')) this.update_view_count();
    if (!$('test_answer_choices_form')) return;
    $('test_answer_choices_form').observe('submit', this.disableForm);
    var anchors = $$('.evaluation-question-list-item-anchor');
    if (0 == anchors.size()) return;
    anchors.invoke('observe', 'click', this.switchThruEvent);
    $('quiz_next_button').observe('click', this.next);
    $('quiz_previous_button').observe('click', this.previous);
    $('quiz_question_highlight_anchor').observe('click', this.highlight);
    this.switchToQuestionByAnchorName(JumboTests.getDocumentHash());
    $$('.jt-test-question-answer-choice-radio').invoke('observe', 'change', this.markCompleted);
    $('jt_end_test_now_anchor').observe('click', this.endTestNowAnchorHasBeenClicked);
    this.question_count = $$('.question-title').length;
    $$('.question-title').each(function(el, index) { el.update('Question ' + (1 + index) + " of " + this.question_count); }, this);
    this.hasLoaded();
  },

  disableForm : function(event)
  {
    $('quiz_finalize_button').disabled = true;
  },

  endTestNowAnchorHasBeenClicked : function(event)
  {
    var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
    JumboTests.track_event('Tests', 'End Test Clicked', $("quiz_id").value, current_anchor.gsub("question_", ""));
    event.stop();
    if (confirm('Do you wish to end this test without answering all the questions?'))
      $('quiz_finalize_button').click();
  },

  hasLoaded : function()
  {
    $('test_loading_message').remove();
    $('test_question_fieldsets', 'test_sidebar_controls').
      invoke('appear', { duration : 1.0 });
  },

  markCompleted : function(event)
  {
    event.stop();
    var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
    if (!current_anchor) return;
    var menu = JumboTests.QuizQuestions.menuItemForQuestionAnchorName(current_anchor);
    menu.addClassName('completed');
    $('quiz_next_button').focus();
    $('quiz_next_button').highlight();
    JumboTests.track_event('Tests', 'Answer Selected', $("quiz_id").value, current_anchor.gsub("question_", ""));
  },

  highlight : function(event)
  {
    event.stop();
    var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
    JumboTests.track_event('Tests', 'Highlighted Current Question', $("quiz_id").value, current_anchor.gsub('#question_', ''));
    if (!current_anchor) return;
    var menu = JumboTests.QuizQuestions.menuItemForQuestionAnchorName(current_anchor);
    menu.toggleClassName('highlight');
  },

  currentQuestionAnchorName : function()
  {
    var visible_question = $$('.attempted-quiz-question-fields').findAll(function(element) {
      return element.visible();
    })[0];
    if (!visible_question) return null;
    return visible_question.select('a[name]')[0].readAttribute('name');
  },

  switchThruEvent : function(event)
  {
    var anchor = event.findElement('a');
    JumboTests.track_event('Tests', 'Switch Question By Number', $("quiz_id").value, anchor.hash.gsub('#question_', ''));
    JumboTests.QuizQuestions.switchToQuestionByAnchorName(anchor.hash.gsub('#', ''));
    event.stop();
  },

  switchToQuestionByAnchorName : function(name)
  {
    var question_anchor = $$('a[name=' + name + ']')[0];
    var menu_anchor = $$('.quiz-question-list-item a[href=#' + name + ']')[0];
    if (!question_anchor || !menu_anchor) return;
    var menu = menu_anchor.up('.quiz-question-list-item');
    var question = question_anchor.up();
    JumboTests.QuizQuestions.switchToQuestion(question);
    JumboTests.QuizQuestions.activateMenuItem(menu);
  },

  switchToQuestion : function(question)
  {
    JumboTests.Quiz.resume();
    $('test_question_fieldsets').show();
    $('test_review_message').hide();
    $$('.attempted-quiz-question-fields').invoke('hide');
    question.show();
  },

  menuItemForQuestionAnchorName : function(anchor_name)
  {
    var menu_anchor = $$('.quiz-question-list-item a[href=#' + anchor_name + ']')[0];
    return menu_anchor.up('.quiz-question-list-item');
  },

  activateMenuItem : function(menu_item)
  {
    $$('.quiz-question-list-item').invoke('removeClassName', 'active');
    menu_item.addClassName('active');
  },

  switchToReviewViaEvent : function(event)
  {
    event.stop();
    JumboTests.QuizQuestions.switchToReview();
  },

  switchToReview : function()
  {
    JumboTests.Quiz.pause();
    $('test_question_fieldsets').hide();
    $('test_review_message').blindDown({ duration : JT_EFFECT_DURATION });
    $('quiz_finalize_button').focus();
  },

  next : function(event)
  {
    event.stop();
    $$('.attempted-quiz-question-fields').each(function(question_container) {
      if (!question_container.visible()) return;
      var next_container = question_container.nextSiblings()[0];
      if (next_container.className != 'attempted-quiz-question-fields') {
        JumboTests.QuizQuestions.switchToReview();
      } else {
        var next_anchors = next_container.select('a');
        var action_name = document.URL.split("/")[4];
        var name = next_anchors[0].name;
        JumboTests.QuizQuestions.switchToQuestionByAnchorName(name);
        var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
        JumboTests.track_event('Tests', 'Next Question', $("quiz_id").value, current_anchor.gsub("question_", ""));
      }
      throw $break;
    });
  },

  previous : function(event)
  {
    event.stop();
    $$('.attempted-quiz-question-fields').each(function(question_container) {
      if (!question_container.visible()) return;
      var next_container = question_container.previousSiblings()[0];
      if (!next_container) return;
      var next_anchors = next_container.select('a');
      if (typeof next_anchors[0] == 'undefined') {
        JumboTests.QuizQuestions.switchToReview();
      } else {
        var name = next_anchors[0].name;
        JumboTests.QuizQuestions.switchToQuestionByAnchorName(name);
        var current_anchor = JumboTests.QuizQuestions.currentQuestionAnchorName();
        JumboTests.track_event('Tests', 'Previous Question', $("quiz_id").value, current_anchor.gsub("question_", ""));
      }
      throw $break;
    });
  },

  update_view_count : function()
  {
    new Ajax.Request($('view_url').value, {
      method : 'post'
    });
  }
}


JumboTests.Time = {

  padZero : function(number)
  {
    return (number < 10) ? ('0' + number) : number;
  },

  toString : function(seconds)
  {
    var t = this.split(seconds);
    return [t[0], this.padZero(t[1]), this.padZero(t[2])].join(':');
  },

  split : function(seconds)
  {
    var secs = parseInt(seconds);
    var s = secs % 60;
    var m = Math.floor(secs / 60) % 60;
    var h = Math.floor(secs / 60 / 60) % 60;
    return [h, m, s];
  },

  splitSeconds : function(seconds)
  {
    t = this.split(seconds);
    return { 'hours' : t[0], 'minutes' : t[1], 'seconds' : t[2] };
  }

};


document.observe('dom:loaded', JumboTests.init);
Event.observe(window, 'load', JumboTests.load);
