var TabCtrl = Object.createObject();

TabCtrl.prototype =
{
   initialize: function(container)
     {
	this.container = $(container);
	
	this.tabs = null;
	
	this.onPaneActivate = null;
	
	this.drawTabs();
     }
   ,
     drawTabs: function()
       {
	  var panes = this.container.getElementsByClass("pane");
	  //alert(panes.length);
	  
	  if (this.tabs)
	    this.container.removeChild(this.tabs);
	  
	  this.tabs = $(document.createElement("ul"));
	  this.tabs.addClass("tabs");
	  
	  var makeHandler = function(tabCtrl, paneId)
	    {
	       return function(evt)
		 {
		    tabCtrl.activatePane(paneId);
		    tabCtrl.stopEventPropagation(evt);
		 };
	    };
	  var activePane;
	  
	  for (var i=0; i < panes.length; i++) 
	    {
	       var pane = $(panes[i]);
	       
	       var li = $(document.createElement("li"));
	       
	       if (pane.hasClass("activePane")) {
		 li.addClass("active");
		 activePane = pane;
	       }
	       
	       var a = $(document.createElement("a"));
	       a.setAttribute("href", "#" + pane.id);
	       a.setAttribute("onclick", "return false;"); // safari
	       
	       a.innerHTML = pane.id;
	       
	       if (pane.getAttribute("title")) {
		 a.innerHTML = pane.getAttribute("title");
		 pane.removeAttribute("title");
	       }
	       
	       a.addEvent("click", makeHandler(this, pane.id));

	       li.appendChild(a);
	       this.tabs.appendChild(li);
	    }
	  
	  this.container.insertBefore(this.tabs, this.container.firstChild);
	  //Workaround a Firefox quirk, where the contents of a text field are not moved with
	  //the field itself
	  activePane.hide();
	  activePane.display();
       }
   ,
     activatePane: function(paneId)
       {
	  var panes = this.container.getElementsByClass("pane");
	  
	  for (var i=0; i < panes.length; i++) 
	    {
	       var pane = $(panes[i]);
	       
	       if (pane.id == paneId) 
		 {
		    pane.addClass("activePane");
		 }
	       else 
		 {
		    pane.removeClass("activePane");
		 }
	    }
	  
	  var paneHref = "#" + paneId;
	  
	  for (var i=0; i < this.tabs.childNodes.length; i++)
	    {
	       var tab = this.tabs.childNodes[i];
	       var a = tab.firstChild;
	       
	       if (a.getAttribute("href") == paneHref)
		 {
		    tab.addClass("active");
		 }
	       else 
		 {
		    tab.removeClass("active");
		 }
	    }
	  
	  if (this.onPaneActivate)
	    {
	        var callback = function(tabCtrl, id)
		 {
		    tabCtrl.onPaneActivate(id);
		 };
	       
	       callback(this, paneId);
	    }
	  
       }
   ,
     stopEventPropagation: function(evt)
       {
	  if (evt.stopPropagation)
	    evt.stopPropagation();

	  if (evt.cancelBubble != undefined)
	    evt.cancelBubble = true;

	  if (evt.preventDefault)
	    evt.preventDefault();

	  evt.returnValue = false;

	  return false;
       }
   
}

// JavaScript Document
