/**
 * @author Trabajismo7
 */
/***
 * Create a Click Effect, that changes the Row CSS class of the row that is clicked.
 * Add to the Table the attribute RowClassOver to control the css class that will be
 * used when the row has been clicked.
 * @param {String} str_tableId 
 */
function xTableClicker(str_tableId)
{
  
 
  var theTable = $(str_tableId);
  
  var theRows = $ByTag('tr', str_tableId);
  
  for (var ix = 0; ix < theRows.length; ix++)
  {
    xAttr(theRows[ix], 'baseClass', theRows[ix].className ? theRows[ix].className : 'none');
  }
  
  var theFormElements = xGetAllFormElements(str_tableId);
  
  for (var ix=0;ix < theFormElements.length; ix++) {
    $ale(theFormElements[ix],'focus',doClick);
  }
  
  var str_RowClassOver = xAttr(theTable, 'rowclassover');

  var lastClickedCell = null;

  $ale(str_tableId, 'click', doClick);
  
  var me = this;
  
  //Free Memory, Always Free Memory!!!!!!!!!!!!
  $ale(window,'unload',_doUnload,false);
  
  /*Destroy Method*/
  this.UnLoad = function () {
    _doUnload();
  }
  
  function _doUnload() {
    for (var ix=0;ix < theFormElements.length; ix++) {
      $rle(theFormElements[ix],'focus',doClick);
    }
    $rle(str_tableId, 'click', doClick);
  }
  

/***
 * this function will be executed when the user makes click over a tr in a table
 * @param {Object} e
 */
  function doClick(e)
  {
  
    var xe = new xEvent(e);
    var row = findTR(xe.target, 5);

		if (typeof(xAttr(row, 'baseClass')) == 'undefined') return;

    if (lastClickedCell != null)
    {
			
      lastClickedCell.className = xAttr(lastClickedCell, 'baseClass');
    }

    lastClickedCell = row;
    if (lastClickedCell != null) lastClickedCell.className = str_RowClassOver;
  }

  function findTR(obj, limit)
  {
    var count = 0;

    while ((obj.tagName.toLowerCase() != 'tr') && (count < limit))
    {
      obj = obj.parentNode;
      count++;
    }

    return obj.tagName.toLowerCase() == 'tr' ? obj : null;
  }
}
function xGetAllFormElements(strDiv) {
    var arrInputs = $ByClass('FormText',$(strDiv),'INPUT');
	  var arrSelects = $ByClass('FormCbx',$(strDiv),'SELECT');
	  var arrTextAreas = $ByClass('FormText',$(strDiv),'TEXTAREA');
	  
	  var arrTotal = arrInputs;
	  if (arrSelects != null) {	  
	    for (var ix = 0; ix < arrSelects.length; ix++) {
	      arrTotal[arrTotal.length] = arrSelects[ix];
	    }
	  }
	  
	  if (arrTextAreas != null) {	  
	    for (var ix = 0; ix < arrTextAreas.length; ix++) {
	      arrTotal[arrTotal.length] = arrTextAreas[ix];
	    }
	  }
	  
	  return arrTotal;
}


function xTableClickerOnReady() {
   var divs = $ByClass('TableClickEffects', null, 'div');
  

  for (var xi = 0; xi < divs.length; xi++)
  {
    
    if (divs[xi].id != 'undefined' || divs[xi].id != null)
    {
      if (divs[xi].id == "") divs[xi].id = "xxx_table" + xi;
      var x = new xTableClicker(divs[xi].id);
    }
  }
}

YAHOO.util.Event.onDOMReady(xTableClickerOnReady);

