/*
  $Id: base.js,v 1.2 2009-02-06 13:00:07 jasper Exp $
  $Name:  $
*/

// TODO: Uitzoeken of we kunnen uitzoeken of er voor desktop gerenderd wordt (buiten het Javascript)

function TrinidadJsExtras(){
  var obj = this;


  this.bindRowClickListeners = function(){
    function clickHandler(e){
      var target = e.target || e.srcElement;
      var row = $(this);
      $("td:first-child input:radio, td:first-child input:checkbox", this).each(function(){
        if (target.nodeName != "INPUT" && target.nodeName != "A") {
          this.click();
          if (this.checked) row.addClass("checked");
          else row.removeClass("checked");
        }
      });
    }

    function mouseoverHandler(e){ $(this).addClass("hover"); }
    function mouseoutHandler(e){ $(this).removeClass("hover"); }

    function handleRowInput(){
      var cell = $(this).parent();

      $(":radio, :checkbox", cell)
        .parent().parent()
        .addClass("tjxRowClick")
        .bind("click", clickHandler)
        .bind("mouseover", mouseoverHandler)
        .bind("mouseout", mouseoutHandler)
      ;
      $(":checked", cell).parent().parent().addClass("checked");
    }

    $("tr:not(.tjxRowClick) > td:first-child > input").each(handleRowInput);

    obj.handleMultiSelectA();
  }


  this.handleMultiSelectA = function(){
    function handleA(){
      var link = $(this);
      if (link.attr("onclick").toString().indexOf(".multiSelect(") > 0) {
        link.addClass("tjxMultiSelect").click(obj.markChecked);
      }
    }

    $("a[onclick]:not(.tjxMultiSelect)").each(handleA);
  }


  this.bindListeners = function(){
    obj.bindRowClickListeners();
  }


  this.markChecked = function(){
    function handleRow(){
      var cell = $(this).parent();
      $(":radio, :checkbox", cell).parent().parent().removeClass("checked");
      $(":checked", cell).parent().parent().addClass("checked");
    }

    $("tr > td:first-child > input").each(handleRow);
  }


  this.bindListeners();

  return this;
}



$(document).ready(function(){
  var tjx = new TrinidadJsExtras();

  TrPage.getInstance().getRequestQueue().addStateChangeListener(function(state){
    if (state == TrRequestQueue.STATE_READY) tjx.bindListeners();
  });
});

