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

var old_updated_at = null;
var pe = null;

document.observe('dom:loaded', function(event) { init(); });

function init()
{
   Editable.setupAll();
   startPE();
   reloadList();
}

function startPE()
{
  pe = new PeriodicalExecuter(poll, 3);  
}

function stopPE()
{
  pe.stop();
}

function reloadList()
{
  // activateFirstUncheckedTopic();
  reloadSortable();
}

function activateFirstUncheckedTopic()
{
  $$('ol#topics li').invoke('removeClassName', 'current');
  
  new Effect.Morph($$('ol#topics li:not(.done)')[0], { style: 'current', duration: 0.8 });
  // $$('ol#topics li:not(.done)')[0].addClassName('current');
}

function poll(meeting_id)
{  
  d = new Date;
  url = "/meetings/" + $F('meeting_id') + "/poll/" + $F('old_updated_at') + "?" + d.getTime();
  
  new Ajax.Request(url, { method: "get", onSuccess: function(transport) { handlePollSuccess(transport) }, onFailure: function(transport) { handlePollFailure(transport) } });
}

function check(topic_id)
{
  if($$('#topic_'+topic_id+' input.check')[0].checked)
  {
    return checkOff(topic_id);
  }
  else
  {
    return unCheck(topic_id);
  }
}

function unCheck(topic_id)
{
  url = "/topics/uncheck/?id="+topic_id;
  new Ajax.Request(url, { method: "post", onComplete: function() { $('topic_'+topic_id).removeClassName('done'); reloadList(); }});
}


function checkOff(topic_id)
{
  url = "/topics/check/?id="+topic_id;
  new Ajax.Request(url, { method: "post", onComplete: function() { $('topic_'+topic_id).addClassName('done'); reloadList(); }});
}

function handlePollSuccess(transport)
{
  var reload_list = false;
  var sort = false;
  var json = transport.responseText.evalJSON();
  
  if(json[0].updated_at > $F('old_updated_at'))
  {
    $('old_updated_at').setValue(json[0].updated_at);
  }
  
  json[0].topics.each(function(s)
  {

    // if topic already exists
    if($('topic_'+s.topic.id+'_title'))
    { 
      // update topic
      $('topic_'+s.topic.id+'_title').update(s.topic.title);
      
      // if is done
      if(s.topic.is_done)
      {
        // add done-class
        $('topic_'+s.topic.id).addClassName('done');
        $$('li#topic_'+s.topic.id+' input.check')[0].checked = true;

        reload_list = true;
      }
      else
      {
        $('topic_'+s.topic.id).removeClassName('done');
        $$('li#topic_'+s.topic.id+' input.check')[0].checked = false;
      }
      
      // if is archived
      if(s.topic.is_archived)
      {
        // add archived-class
        $('topic_'+s.topic.id+'_title').up().addClassName('archived');
        reload_list = true;
      }
      else
      {
        // check if the content was changed or just the position
        if(s.topic.updated_at != s.topic.revised_at)
        {
          // only the position was changed
          $('topic_'+s.topic.id+'_title').up().setAttribute('position', s.topic.position);
          sort = true;
          reload_list = true;
        }
        else
        {
          // the content was changed as well
          // todo: moet ie hier niet checken of de positioned anders is?
          // highlight
          $('topic_'+s.topic.id+'_title').highlight();
        }
      }
    }
    else
    {
      // append new topic
      url = "/topics/"+s.topic.id;
      new Ajax.Updater('topics', url, { method: 'get', insertion: Insertion.Bottom, onComplete: function() {
        $('topic_'+s.topic.id+'_title').highlight();
        Editable.create($('topic_'+s.topic.id+'_title'));
      } });
      
      /*
      var handle      = new Element('span', { 'class': 'handle' }).update('[drag]');
      var destroy     = new Element('a', { 'class': 'destroy', 'href': '/meetings/'+$F('meeting_id')+'/topics/'+s.topic.id, 'onclick': "if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '"+AUTH_TOKEN+"'); f.appendChild(s);f.submit(); };return false;" }).update('del');
      var check       = new Element('a', { 'class': 'check', 'href': '#', 'onclick': 'checkOff('+s.topic.id+'); return false;' }).update('done');
      var clear       = new Element('div', { 'class': 'clear' });
      
      var span  = new Element('span', { 'class': 'editable', 'id': 'topic_'+s.topic.id+'_title', 'rel': '/meetings/'+$F('meeting_id')+'/topics/'+s.topic.id }).update(s.topic.title);
      var li    = new Element('li', { 'id': 'topic_'+s.topic.id });
      
      Element.insert(li, { bottom: handle });
      Element.insert(li, { bottom: ' ' });
      Element.insert(li, { bottom: destroy });
      Element.insert(li, { bottom: ' ' });
      Element.insert(li, { bottom: check });
      Element.insert(li, { bottom: ' ' });
      Element.insert(li, { bottom: span });
      Element.insert(li, { bottom: clear });
      
      Element.insert($('topics'), { bottom: li });
      
    
      Editable.create($('topic_'+s.topic.id+'_title'));
      */
      
      reload_list = true;
    }
    
  });
  
  if(sort)
  {    
    var lis = $$('#topics li');

    // sort the list items based on the contents of a nested strong tag
    lis.sort(function(a, b) {
        a = parseInt(a.getAttribute('position'));
        b = parseInt(b.getAttribute('position'));    

        // you may want to process the text values further here, perhaps
        // running it through $.trim, reducing whitespace sequences with
        // a regular expression, or lower- or upper-casing letters to
        // make the comparison case-insensitive.

        return (a < b) ? -1 : ((a > b) ? 1 : 0);
    });

    // reinsert the list items in their new order
    lis.each(function(li) {
      Element.insert($('topics'), { bottom: li });
    });
  }
  
  if(reload_list)
  {
    // reload list
    reloadList();
  }

}

function reloadSortable()
{
  // todo: is this the right way?
  Sortable.create('topics', { handle:'handle', onUpdate:function() { stopPE(); new Ajax.Request('/topics/sort', { onComplete: function() { startPE(); reloadList(); }, asynchronous:true, evalScripts:true, parameters:Sortable.serialize("topics") + '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN) } ) } });
}

function handlePollFailure(transport)
{
  alert("Your change could not be saved.");
}