var QuizControl = new (function() {
  var QuizControl = this,

    // cookie keys
    COMPLETE_CKEY = 'QuizControl_completed',
    GENDER_CKEY = 'lp_gender',
    PRODUCT_CKEY = 'lp_product',

    // array of DOMElement
    _sections = [], // 0-based
    _current_section = -1, // referencing _sections, valid index starts from 0

    _current_question = 0; // valid index starts from 1

  /**
   * @param sections array of DOMElements or jQuery selectors
   * @return bool whether custom content is started
   */
  this.init = function(sections) {

    var l = $('input[name=l]').val();
    if (l) COMPLETE_CKEY = 'L' + l;

    if (typeof sc_sentinel == 'function') {
      if (! sc_sentinel()) {
        return false;
      }
    }
    else if (Get_Cookie(COMPLETE_CKEY) == 'true') {
      $(Owlery).trigger('repopulate');
      return false;
    }

    // Register sections
    $.each(sections, function(idx, $section) {
      $section = $($section);
      if ($section.length) { // skip non-exist elements
        _sections.push($section.hide());
      }
    });

    // Bind event handlers
    $('a, .imagesubmit, .button_next', '#question_index').click(function(e) {
      e.preventDefault();
      QuizControl.nextSection();
    });

    $('#select_gender .button_next').click(function(e) {
      e.preventDefault();
      QuizControl.nextSection();
    });
    $('a#gender_m, a#gender_f', '#select_gender').click(function(e) {
      e.preventDefault();
      var gender = ('gender_m' == this.id ? 'm' : 'f');
      QuizControl.setGenderClass(gender);
      Set_Cookie(GENDER_CKEY, gender);
      QuizControl.nextSection();
    });

    $('#select_sign a').click(function(e) {
      e.preventDefault();
      QuizControl.nextSection();
    });

    $('#question_zone .answers').each(function(question_idx) {
      $(this).find('a').each(function(ans_idx) {
        $(this).click(function(e) {
          e.preventDefault();
          _tryEndCurrentQuestion(ans_idx);
        });
      });
    });


    $('#inputzone').hide();
    $('#container').removeClass('imagestep1');
    $('#docwrapper').removeClass('imagestep1').addClass('imagestep0');

    QuizControl.nextSection();

    return true;
  };

  /**
   * Move to next section
   */
  this.nextSection = function() {
    if (_current_section >= 0) { // hide previous section
      $('#docwrapper').removeClass('imagestep_pre' + (_current_section + 1));
      _sections[_current_section].hide();
    }

    if (++_current_section < _sections.length) { // show new section
      _sections[_current_section].show();
      $('#docwrapper').addClass('imagestep_pre' + (_current_section + 1));

      if (_sections[_current_section].attr('id') == 'question_zone') {
        _tryStartNextQuestion(); // show first question
      }
    }
    else {
      QuizControl.end();
    }
  };

  /********************************************************************************
   * Questions management:
   */

  function _tryEndCurrentQuestion(clicked_ans_idx) {
    if (QuizControlEvent.beforeEndQuestion(_current_question, clicked_ans_idx))
      QuizControl.endCurrentQuestion();
    // else The Layout should then manually call QuizControl.endCurrentQuestion().
  }

  /**
   * End the question indicated by _current_question
   */
  this.endCurrentQuestion = function() {
    $('#container').removeClass('showing_q' + _current_question);
    $('#question_zone #q' + _current_question).hide();

    _tryStartNextQuestion();
  };

  function _tryStartNextQuestion() {
    var next_question = _current_question + 1;
    if ($('#question_zone #q' + next_question).length) { // show next question
      _current_question = next_question;

      $('#question_zone #q' + _current_question).show();
      $('#container').addClass('showing_q' + _current_question);
      QuizControlEvent.afterStartQuestion(_current_question);
    }
    else {
      QuizControl.nextSection();
    }
  }

  /////////////////////////////////////////////////////

  this.end = function() {
    $('#docwrapper').removeClass('imagestep0').addClass('imagestep1');
    Set_Cookie(COMPLETE_CKEY, 'true');
    $('#inputzone').fadeIn('slow');
    $(Owlery).trigger('showMin', [true]);
  };

  /********************************************************************************
   * gender:
   */

  /**
   * @param gender string 'm' | 'f'
   */
  this.setGenderClass = function(gender) {
    gender = gender || 'm';
    if ('m' == gender || 'f' == gender) {
      $('#container').removeClass('gender_m gender_f').addClass('gender_' + gender);
    }
  };

  this.repopulateGender = function() {
    QuizControl.setGenderClass(Get_Cookie(GENDER_CKEY));
  };

  /********************************************************************************
   * product:
   */

  /**
   * @param product int >= 1
   */
  this.setProductClass = function(product) {
    product = product || 1;
    var $container = $('#container'), i;
    for (i=1; i<4; ++i)
      $container.removeClass('product_' + i);
    $container.addClass('product_' + product);
    Set_Cookie(PRODUCT_CKEY, product);
  };

  this.repopulateProduct = function() {
    var product = Get_Cookie(PRODUCT_CKEY);
    if (product) {
      QuizControl.setProductClass(product);
    }
  };
});

/* callback to be overwritten */
var QuizControlEvent = {
  /**
   * This event is triggered after a quiz answer is clicked and before such question is closed.
   * If this event handler (callback function) returns false, the close will be prevented
   * (The Layout should then manually call QuizControl.endCurrentQuestion()).
   * @param question_idx index of question to be ended (>= 1)
   * @param ans_idx index of answer clicked (>= 0)
   * @return bool
   */
  beforeEndQuestion: function(question_idx, ans_idx) { return true; },

  /**
   * @param question_idx index of question to be started (>= 1)
   */
  afterStartQuestion: function(question_idx) {}
};

landingControlHolder['precontroller'] = QuizControl;

