﻿
TabControl = function(id)
{
  this.build(id);
}
TabControl.prototype.build = function(id)
{
  this._element = $(id);
  this._control = this;
  this.cells = this._element.cells || this._element.tBodies[0].rows[0].childNodes;
  
  var selectedIdx = -1;
  var selectedCell = null;
  for (var i=0,j=this.cells.length,k=0;i<j;i++)
  {
    var cell = $(this.cells[i]);
    if (cell.nodeType!=1)
      continue;
    if (k++ == 0)
      selectedCell= cell;
    cell.tabPageIndex = k;
    
    if (cell.hasClassName('Spacer'))
      continue;
    if (cell.hasClassName('SelectedTab'))
      selectedCell = cell;   
     else
      cell.addClassName('UnselectedTab');
    cell.value = cell.readAttribute('value'); 
      
    cell.observe('click', this.TabPageClicked.bind(this, cell));
  }
  this.TabPageClicked(selectedCell);    
}
TabControl.prototype.TabPageClicked = function(cell)
{
  if (this._selectedCell == cell)
    return;
  if (this._selectedCell!=null)
  {
    this._selectedCell.removeClassName('SelectedTab');
    this._selectedCell.addClassName('UnselectedTab');
    this._selectedCell.checked = false;
  }
  if (cell!=null)
  {
    cell.removeClassName('UnselectedTab');
    cell.addClassName('SelectedTab');
    cell.checked = true;
  }
  this._selectedCell = cell;
  if (this.OnSelectionChanged)
    this.OnSelectionChanged(cell);
}
TabControl.prototype.GetValue = function()
{
  return this._selectedCell && this._selectedCell.value;
}
TabControl.prototype.SetValue = function(v)
{
  var cells = this._element.cells;
  for (var i=0,j=this.cells.length;i<j;i++)
  {
    var cell = $(this.cells[i]);
    if (cell.value==v)
    {
      this.TabPageClicked(cell);
      return;
    }
  }
}

