
/*
SortableList, ordenando listas com javascript (http://gujs.com.br).
by Matheus Zeuch (http://webhorizon.com.br/matheus)
maiores informacores (http://gujs.com.br).
2007-03-27
*/

function $(id) { return document.getElementById(id); }

function SortableList(ul, options) {
  var self    = this;
  self.ul     = ul ? ul : null;
  self.li     = (ul) ? ul.getElementsByTagName('li') : null;
  self.list   = [];

  self.options = options ? options : {};
  self.options.rotate     = (self.options.rotate===true || self.options.rotate===false) ? self.options.rotate : true;
  self.options.onComplete = self.options.onComplete ? self.options.onComplete : null;

  self.init = function() {
    if (!self.ul || !self.li.length) return 0;
    for (var i=0; i<self.li.length; i++) {
      self.list.push(self.li[i].id);
    }
    return 1;
  }

  self.search = function(q) {
    var i = self.list.length;
    while (i>=0) if (self.list[i]==q) break; else i--;
    return i;
  }

  self.sort = function(ifrom, ito) {
    var newlist = [];
    for (var i=0; i<self.list.length; i++) {
      switch(i) {
        case ifrom:
          newlist.push(self.list[ito]);
          break;
        case ito:
          newlist.push(self.list[ifrom]);
          break;
        default:
          newlist.push(self.list[i]);
      }
    }
    self.write(newlist);
  }

  self.write = function(list) {
    var li = [];
    var childNodes, el;
    for (var i=0; i<list.length; i++) {
      el = document.createElement('LI');
      el.id = list[i];
      el.innerHTML = $(list[i]) ? $(list[i]).innerHTML : '';
      li.push(el);
    }
    for (var i=0; i<self.li.length;) self.ul.removeChild(self.li[0]);
    for (var i=0; i<list.length; i++) self.ul.appendChild(li[i]);
    self.list = list;
    self.li = ul.getElementsByTagName('li');
  }

  self.onComplete = function() {
    if (typeof self.options.onComplete == 'function') self.options.onComplete();
  }

  self.up = function(id) {
    var ifrom = self.search(id);
    if (self.options.rotate) {
      var ito = (ifrom == 0) ? self.list.length-1 : ifrom-1;
    } else {
      var ito = (ifrom == 0) ? ifrom : ifrom-1;
    }
    self.sort(ifrom, ito);
    self.onComplete();
  }

  self.down = function(id) {
    var ifrom = self.search(id);
    if (self.options.rotate) {
      var ito = (ifrom == self.list.length-1) ? 0 : ifrom+1;
    } else {
      var ito = (ifrom == self.list.length-1) ? ifrom : ifrom+1;
    }
    self.sort(ifrom, ito);
    self.onComplete();
  }

  self.init();
}
