var ListInterface = Class.create();

ListInterface.prototype = {
 initialize: function(list) {
  this.list = $(list);
  // TODO: Needs to also use the ajax query parameters (see sort)
  if (this.list.getAttribute('location')) {
   this.location = this.list.getAttribute('location', 2);
  } else if(window.ajaxLocation) {
   this.location = window.ajaxLocation;
  } else {
   this.location = window.location.pathname;
  }
  body = $A(this.list.getElementsByTagName('tbody'));
  this.data = body.find(function(element) {
   if(element.hasClassName('data')) return true;
  });
  this.elements = this.list.childNodes;
  this.process(this.elements);
 },

 // TODO: This needs to only process the thead!!!!!!! It takes to long
 // to process everything!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 process: function(nodes) {
  for(var i = 0; i < nodes.length; i++) {
   element = nodes[i];
   if (element.tagName && element.tagName.toLowerCase() == 'th') {
    id = element.id;
    if ((id.length > 0) && this.data) {
     element.onmouseover = this.highlight.bindAsEventListener(element);
     element.onmouseout  = this.revert.bindAsEventListener(element);
     element.onclick = this.sort.bindAsEventListener(this);
    }
   }
   this.process(element.childNodes);
  }
 },

 sort: function(event) {
  element = Event.element(event);
  params = $H(window.location.search.toQueryParams());
  params['sort'] = element.id;
  // TODO: Make this use class names "asc" and "desc"
  if (element.hasClassName('sorted')) {
   if (element.hasClassName('desc')) {
    element.removeClassName('desc');
   } else {
    element.addClassName('desc');
    params['order'] = 'desc';
   }
  } else {
   document.getElementsByClassName('sorted').each(function(prev) {
    prev.removeClassName('sorted');
   });
   element.addClassName('sorted');
  }
  new Ajax.Updater(this.data,
                   this.location + '?' + params.toQueryString(),
		   {asynchronous:true, evalScripts:true});
 },

 highlight: function(event) {
  Element.addClassName(this, 'over');
 },

 revert: function(event) {
  Element.removeClassName(this, 'over');
 }
}
