var users_decay_cache = null
var chat_decay = null
var users_decay = null

// on load
jQuery(function($) {
  // Ajoute la classe "error" aux labels dont l'input a la classe "error"
  $('label').copy_error_class_from_input()

  // Action cachée pour quitter l'interface live
  // en cliquant sur "Utilisateurs"
  $('#users h2').click(function() {
    if (confirm('Voulez-vous quitter le tchat ?'))
      window.location = './?disconnect'
  })

  // Mise-à-jour de la page chat-started toutes les 20 secondes
  // affiche le texte "Le chat a commencé !"
  if ($('#chat-started').size() > 0) {
    setInterval(function() {
      $.get('./?is_started', function(data) {
        if (data == '1')
          $('#chat-started').show();
      })
    }, 20 * 1000);
  }

  // Sur la page de chat
  if ($('#chat').size()) {

    $('#chat').scrollBottom()

    // Mises à jours automatiques des utilisateurs et du chat
    users_decay_cache = null
    users_decay = new Decay(update_users, { seconds: 50, decay: 1.3, max: 180 }).start()
    chat_decay  = new Decay(update_chat,  { seconds:  5, decay: 1.1, max: 20  }).start()

    // Remplace submit de la boîte de chat
    $('#chat-box').submit(submit_chat)



    // remove default text on focus
    $('#text').clearDefault()

    update_users_count();
  }

  // Functions



})


// Vide un champ de son texte par défaut
$.fn.clearDefault = function() {
  return $(this).each(function(i, elem) {
    var elem = $(elem)
    elem.attr('data-default', elem.val())
    elem.focus(function(e) {
      if (elem.val() == elem.attr('data-default'))
        elem.val('')
    })
  })
}


// Ajoute la classe "error" à l'élément si la classe "error" apparait sur un input associé
// (en cherchant dans l'attribut for="" ou ses enfants).
//
// Exemples:
//   <input id="bob" class="error" /> <label for="bob">Bob</label>
//   <script>$('label').copy_error_class_from_input()</script>
//   # => <input id="bob" class="error" /> <label for="bob" class="error">Bob</label>
//
//   <div><input class="error" /></div>
//   <script>$('div').copy_error_class_from_input()</script>
//   # => <div class="error"><input class="error" /></div>
$.fn.copy_error_class_from_input = function() {
  return $(this).each(function(i, elem) {
    var id_for = $(elem).attr('for');
    var input = id_for ? $('#'+id_for+'.error') : $(this).find('input.error');
    if (input.length > 0)
      $(this).addClass('error');
  });
}


// GETs the new messages to add to the chat
function update_chat() {
  var uri = $('#chat-box').attr('action') // we GET at the same URI we POST
  if (!$('#chat').size()) // no <li>, therefore the chat is probably finished
    window.location.reload();
  var since = $('#chat li:last').attr('data-stamp') // timestamp of the last message
  $.get(uri, { since: since }, insert_message_li)
}

// Inserts HTML to the chat list, coming from Ajax
function insert_message_li(html) {
  html = $.trim(html)
  if (html) {

    // remove the few unlucky duplicate message_id
    $(html).each(function(i, item) { $('#' + item.id).remove() })

    $('#chat ul').append(html)

    if (!$('#chat').hasClass('admin'))
      $('#chat').scrollBottom()

    chat_decay.reset() // starts decay back at the default time
  }
}

// Returns true if the html given for the user-list changed
// in-between calls. /!\ Relies on a global var users_decay_cache
function users_cache_changed(html) {
  html = html.replace(/\s/g, '')
  if (!users_decay_cache)
    users_decay_cache = html
  var changed = (html != users_decay_cache)
  if (changed)
    users_decay_cache = html
  return changed
}

// GETs the list of users in the sidebar
function update_users() {
  var ul = $('#users ul')
  ul.load(ul.attr('data-uri'), null, function(html) {
    if (users_cache_changed(html))
      users_decay.reset()


    // Update counter
    update_users_count()
  })
}


// Mets à jour le nombre d'utilisateurs selon le nombre de li.online
function update_users_count() {
  // var counter = $('#users li.online').size()
  // var text = $('#users h2').text()
  // text = text.replace(/^[0-9\W]* ?/, counter + ' ')
  // //text = text.replace(/s?$/, counter > 1 ? 's' : '') // pluralisation
  // $('#users h2').text(text)
}


// called when the user submits a new message
function submit_chat() {
  // find elements
  var form = $(this)
  var inputs = form.find('input,textarea')
  var text_input = $('#text')

  // find values
  var text = $.trim(text_input.attr('value'))
  var nickname = $('#nickname').size() ? $('#nickname').attr('value') : ''

  if (!text || text == text_input.attr('data-default'))
    return false;

  text_input.removeAttr('value')

  $('body').addClass('loading')

  $.post(form.attr('action'), { text: text, nickname: nickname }, function() {
    update_chat() // update the messages list
    $('#text-message').replace_with_fade_with_duration('#text-message-thanks', 10)

    text_input.focus()
    $('body').removeClass('loading');
  })

  return false
}
