/**
 * TabTable
 *
 *  object
 *
 * @author     Takashi Mizohata <takashi@firstbornmultimedia.com>
 * @copyright  2008 firstborn
 * @license    firstborn internal (pending)
 * @TODO       STRONGLY RECOMMENDED REFACTORING!
 */

var TabTable = function (dict)
{
  dict.set('aaa', this);

  this.length        = 0;     // int
  this.currentTitle  = '';    // string
  this.head          = {};    // object
  this.body          = {};    // object
  this.order         = [];    // array
  this.nyroTbody     = null;  // element
  this.nyroBody      = [];    // array

  var cls, c_len, elm, i, innode, jq_c, jq_h, node, title, tr;

try{

  // initialize headers
  jq_h        = $('#pageBody .tabHeader th');
  this.length = jq_h.length;
  if (this.length == 0)
  {
    return;
  }
  for (i = 0; i < this.length; ++i)
  {
    elm                           = jq_h.get(i);
    title                         = elm.getAttribute('title');
    this.order[this.order.length] = title;
    this.head[title]              = elm;
    cls                           = elm.className || elm.getAttribute('class');
    if (cls !== null && cls.indexOf('selected') !== -1)
    {
      this.currentTitle = title;
    }
    dict.set(elm, this);
  }

  // initilize contents
  jq_c  = $('#pageBody .tabContent');
  c_len = jq_c.length;
  for (i = 0; i < c_len; ++i)
  {
    elm              = jq_c.get(i);
    title            = elm.getAttribute('title');
    this.body[title] = elm;
    if (title != this.order[i])
    {
      throw new Error('Head order and contents order is different. This should not happen..');
    }
  }

  // initialize nyrotbody
  this.nyroTbody = $('#pageBody .tabHeader tbody').get(0);
  tr             = document.createElement('tr');
  this.nyroTbody.appendChild(tr);
  for (i = 0; i < this.length; ++i)
  {
    node = document.createElement('td');
    node.title = this.order[i];
    node.setAttribute('title', this.order[i]);
    // add class names
    if (i == 0)
    {
      node.className = 'first';
    }
    else if ((this.length - i) == 1)
    {
      node.className = 'last';
    }
    else
    {
      node.className = '';
    }

    // make liftContainer
    innode = document.createElement('div');
    innode.className = 'liftContainer';
    node.appendChild(innode);
    // append outcomes into parents
    this.nyroBody[this.nyroBody.length] = node;
    tr.appendChild(node);
    dict.set(node, this);
  }

  // initialize event
  jq_h.bind('click', {'type': 'ONCLICKTH'}, TabTable.dispatch);
  $('td', this.nyroTbody).bind('click', {'type': 'ONCLICKTD'}, TabTable.dispatch);

  this.activateNyro();

} catch(err) {console.log(err);}

}


// STATIC MEMBERS _________________________________________________________

TabTable.re_selected = new RegExp(/selected/);
TabTable.re_twospaces = new RegExp(/\s{2,}/);
TabTable.path_tab_right_bg = '/images/product/tab_header_bg_right.gif';
TabTable.path_tab_left_bg = '/images/product/tab_header_bg_left.gif';



// MEMBER METHODS _________________________________________________________

TabTable.prototype.clearNyros = function ()
{
  for (var i = 0; i < this.length; ++i)
  {
    var elm = $('div.liftContainer', this.nyroBody[i]).get(0);
    elm.innerHTML = "";

//    var elm = $('div.liftContainer', this.nyroBody[i]).get(0);
//    this.nyroBody[i].removeChild(elm);
//    var div = document.createElement('div');
//    div.className = 'liftContainer';
//    this.nyroBody[i].appendChild(div);

    //console.log(i + ': ' + this.nyroBody[i].innerHTML);
  }
}

TabTable.prototype.changeBodyTo = function (new_title)
{
  var old = this.body[this.currentTitle];
  old.className = 'tabContent';
  this.body[new_title].className = 'tabContent selected';
}

TabTable.prototype.changeHeaderTo = function (new_title)
{
  var old = this.head[this.currentTitle];
  var cls = old.className || old.getAttribute('class');
  switch (true)
  {
    case (cls.indexOf('first') != -1):
      old.className = 'first';
    break;

    case (cls.indexOf('last') != -1):
      old.className = 'last';
    break;

    default:
      old.className = '';
    break;
  }

  var neo = this.head[new_title];
  var neo_cls = neo.className || neo.getAttribute('class');
  neo.className = ((neo_cls == null) ? 'selected' : neo_cls + ' selected');
}


TabTable.prototype.changeByElment = function (elm)
{
  //console.log("TabTable::changeByElment");
  this.clearNyros();
  var title = elm.getAttribute('title');

  this.changeHeaderTo(title);
  this.changeBodyTo(title);
  this.currentTitle = title;

  this.activateNyro();
}


TabTable.prototype.activateNyro = function ()
{
  var len = this.nyroBody.length;
  var on_right = true;
  for (var i = 0; i < len; ++i)
  {
    var prnt  = this.nyroBody[i];
    var cls   = prnt.className || prnt.getAttribute('class');
    var title = prnt.getAttribute('title');
    var cntr  = $('div.liftContainer', prnt).get(0);
    cls = (cls == null) ? '' : cls;

    if (title == this.currentTitle)
    {
      switch (true)
      {
        case (cls.indexOf('first') != -1):
          on_right = false;
          cntr.appendChild(TabTable.createContent(false));
          prnt.className = 'first selected';
        break;

        case (cls.indexOf('last') != -1):
          cntr.appendChild(TabTable.createContent(true));
          prnt.className = 'last selected';
        break;

        default:
          on_right = false;
          cntr.appendChild(TabTable.createContent(true));
          cntr.appendChild(TabTable.createContent(false));
          prnt.className = 'selected';
        break;
      }
    }
    else
    {
      switch (true)
      {
        case (cls.indexOf('first') != -1):
          prnt.className = 'first';
        break;

        case (cls.indexOf('last') != -1):
          prnt.className = 'last';
        break;

        default:
          if (on_right)
          {
            cntr.appendChild(TabTable.createContent(true));
          }
          else
          {
            cntr.appendChild(TabTable.createContent(false));
          }
          prnt.className = '';
        break;
      }
    }
  }
}



// STATIC METHODS _________________________________________________________

TabTable.createContent = function (left)
{
  var result = document.createElement('div');
  var img = document.createElement('img');
  result.appendChild(img);
  left = left | false; // if no arg, will be left.
  if (left)
  {
    result.className = 'leftAlign';
    img.src = TabTable.path_tab_left_bg;
  }
  else
  {
    result.className = 'rightAlign';
    img.src = TabTable.path_tab_right_bg;
  }
  return result;
}


// DISPATCH EVENT _________________________________________________________

TabTable.dispatch = function (ev)
{
  //console.log('TabTable::dispatch() ' + ev.data.type);

  switch (ev.data.type)
  {
    case 'ONCLICKTD':
      TabTable.dispatchNyroClick(ev);
    break;

    case 'ONCLICKTH':
      TabTable.dispatchHeadClick(ev);
    break;

    default:
      //throw new Error('event type not defined.');
    break;
  }
}


// EACH_EVENT IMPLE _______________________________________________________

TabTable.dispatchNyroClick = function (ev)
{
  //console.log('TabTable::dispatchNyroClick: ' + ev.target.tagName);

  var target;
  switch((ev.target.tagName).toLowerCase())
  {
    case 'div':
      target = ev.target.parentNode;
    break;

    case 'img':
      return;
    break;

    default:
      console.log('NyroClick: ' + ev.target.tagName + ((ev.target.className) ? ev.target.className:ev.target.getAttribute('class')));
      return;
    break;
  }

  var tab = Controller.getInstance().dictionary.get(target);
  if (target.getAttribute('title') != tab.currentTitle)
  {
    tab.changeByElment(target);
  }
}


TabTable.dispatchHeadClick = function (ev)
{
  //console.log('TabTable::dispatchHeadClick: ' + ev.target.tagName);

  var target;
  switch((ev.target.tagName).toLowerCase())
  {
    case 'th':
      target = ev.target;
    break;

    default:
      console.log('HeadClick: ' + ev.target.tagName + ((ev.target.className) ? ev.target.className:ev.target.getAttribute('class')));
      return;
    break;
  }

  var tab = Controller.getInstance().dictionary.get(target);
  if (target.getAttribute('title') != tab.currentTitle)
  {
    tab.changeByElment(target);
  }
}


