// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function getChat(){
  $j.getJSON(window.jsonUrl, function(data){
    var highlight = ($j('#questions_container li').length > 0);
    $j.each(data, function(i, question){
      question.show_question = (question.status != 3);

      // Handle questions/answers separatly not inline like in rails
      var answers = question.answers;
      question.answers = '';

      if ($j('#question_container_'+question.id).length == 0){
        $j('#questions_container').append($j.mustache(window.question_template, question));

        // Hightlight if not the initial load
        if (highlight){
          $('question_container_'+question.id).highlight({ duration: 5.0 }); // yeah I just used prototype.
        }
      }

      $j.each(answers, function(n, answer){
        if ($j('#answer_container_'+answer.id).length == 0){
          if (answer.moderator_small_headshot){
            answer.moderator_image = '<img src="'+answer.moderator_small_headshot+'" alt="'+answer.moderator_name+'" />'
          }
          $j('#question_container_'+question.id).append($j.mustache(window.answer_template, answer));

          // Hightlight if not the initial load or if the question is a comment from the moderator
          if (highlight && question.status == 3){
            $('question_container_'+question.id).highlight({ duration: 5.0 }); // yeah I just used prototype.
          }
        }
      });
    })
  });
}

function setRefresh(interval){
  console.log("setting interval: "+interval);
  if (window.getChatInterval) window.clearInterval(window.getChatInterval);
  window.interval = interval;
  if (interval != 0){
    getChat();
    window.getChatInterval = window.setInterval(getChat, window.interval);

    // Expire after 1 hour
    window.setTimeout(function(){
      window.clearInterval(window.getChatInterval);
      if (confirm('Auto-refresh has expired, would you like to reload the page?')) {
        window.location.reload();
      }
    }, 3600000);
  }
}

function setCurrent(node, time){
  console.log('setCurrent: '+time);
  $j('#auto-refresh li').removeClass('current');
  $j(node).addClass('current');
  setRefresh(time);
  return false;
}
