var _setupTables = function(rootNode) {

  //hide reset fields
  $(rootNode).find('.pp-reset-field').hide();

  //bind reset fields
  $(rootNode).find('.pp-reset-field').click(function(e){
    var field = $(this).parent().find('.pp-text');
    field.value('');
    // remove this fields class from the TRs
    removeSearchTerm(field);
    $(this).hide();
    e.returnValue = false;
    if($().isFirefox()){
      e.preventDefault();
    }
    return false;
  });

  $(rootNode).find('.pp-text').keyup(function(){
    if(this.value.length > 0){
      $(this).parent().parent().find('.pp-reset-field').show();
      $(this).parent().parent().find('.pp-reset-field-list').show();
    }else{
      $(this).parent().parent().find('.pp-reset-field').hide();
      $(this).parent().parent().find('.pp-reset-field-list').hide();
    }
  });

  //
  // Filter table content as you type
  //
  var fieldFilters = $(rootNode).find('.pp-field-filter');
  for(var i = 0; i < fieldFilters.elements.length; i++) {
    fieldFilters.elements[i].style.display = "block";
  }
  
  fieldFilters = $(rootNode).find('.pp-field-filter-inline');
  for(var i = 0; i < fieldFilters.elements.length; i++) {
    fieldFilters.elements[i].style.display = "inline";
  }
  
  $(rootNode).find('.pp-date-filter').change(function(){
	var month = $(rootNode).find('.pp-date-filter-month').value();
	var year = $(rootNode).find('.pp-date-filter-year').value();
	
	var field      = $(this);
	
	if(isNaN(year))
		doTableSearch(field, month);
	else
		doTableSearch(field, month + " " + year);
		
  });

  $('.pp-filter').keyup(function() {
    var field      = $(this);
    doTableSearch(field, field.value());
  });

  $(rootNode).find('.pp-select-filter').change(function() {
    var field      = $(this);
    var value = field.text();
    value = value.replace("&", "&amp;");
    if(value == "All types") {
      value = "";
    }
    doTableSearch(field, value);
  });

  function removeSearchTerm(field) {
    // get all of the pp-filters for this table
    var searchValues = [],
    table = field.parentWithSelector('table'),
    table_body = table.find('tbody'),
    search_field_class = field.parentWithSelector("th").getClass(0),
    column     = table_body.find("."+search_field_class);
    column.each(function(cell) {
      var cell = $(cell),
          row  = cell.parent();
          row.removeClass(search_field_class+"-search");
    });
    hideRows(table_body);
  }

  function doTableSearch(field, value) {
 
    // get all of the pp-filters for this table
    var searchValues = [],
    table = field.parentWithSelector('table'),
    table_body = table.find('tbody'),
    search_field_class = field.parentWithSelector("th").getClass(0),
    column     = table_body.find("."+search_field_class);
    column.each(function(cell) {
      var cell = $(cell),
          row  = cell.parent();
        if(cell.contains(value)) {
          row.removeClass(search_field_class+"-search");
        } else {
          row.addClass(search_field_class+"-search");
        }
    });
    hideRows(table_body);
  }

  function hideRows(table_body) {
    var rows = table_body.find("tr");
    for(var i = 0, t = rows.length();i<t;i++) {
      var row = rows.elements[i],
      class_name = row.className;
      if($().isIE()) {
        class_name = class_name.replace("pp-even", "");
        class_name = class_name.replace("pp-odd", "");
        class_name = class_name.replace(" ", "");
      }
      if(class_name == "") {
        $(row).show();
      } else {
        $(row).hide();
      }
    }
  }

  $(rootNode).find('.pp-table-search').keyup(function(){
    var field = $(this);
  });

  function columnSearch(columns, value) {
    columns.each(function(cell) {
      var cell = $(cell),
      row  = cell.parent();
      cell.contains(value) ? row.show() : row.hide();
    });
  }

  //
  // Sort table by column
  //
  function toggleSelectedColumn(header) {
    $('.pp-selected').removeClass('pp-selected');
    header.addClass('pp-selected');
  };

  $(rootNode).find('.pp-sort').click(function() {
    doTableSort(this);
  });
  
  //  GB002209 17/5/2011
  //  Bugzilla 4559
  //  Format for the date should be MMM YY. Enforce this rule.
  //  If date is too long set to a defeult date.
  //  If month is not a correct name set to a default date.
  //  Format that the date parse function requires is "mmm n(n), yyyy".
  //  The case of the month is not significant, tested it with Jan and jan.
  // 
  function correctDateFormat(d) {
 	
 	var month=d.substring(0,3);
	var year="2000";
	
	if (d.length>6){
		return ("Dec 30, 1949");
	}	
	
	if (		(month!="Jan")&&
		  	(month!="Feb")&&
		  	(month!="Mar")&&
		  	(month!="Apr")&&
		  	(month!="May")&&
		  	(month!="Jun")&&
		  	(month!="Jul")&&
		  	(month!="Aug")&&
		  	(month!="Sep")&&
		  	(month!="Oct")&&
		  	(month!="Nov")&&
		  	(month!="Dec")&&
		  	(month!="jan")&&
		  	(month!="feb")&&
		  	(month!="mar")&&
		  	(month!="apr")&&
		  	(month!="may")&&
		  	(month!="jun")&&
		  	(month!="jul")&&
		  	(month!="aug")&&
		  	(month!="sep")&&
		  	(month!="oct")&&
		  	(month!="nov")&&
		  	(month!="dec")) {
		  	
			  return ("Dec 31, 1949");
	} else {
	
   		if (d.substring(4,6)>="50"){
   			year="19"+d.substring(4,6);
   		} else {
  			year="20"+d.substring(4,6);
   		}
		
   	}
	
	return(month + " 1, "+year);

 }

  //  GB002209 17/5/2011
  //  Bugzilla 4559
  //  custom sort function for date sorting
  //
  function _datesort(a,b){
  	return ( Date.parse(correctDateFormat(a)) - Date.parse(correctDateFormat(b)) );
  }

  function doTableSort(label) {

    var label          = $(label),
        //table          = label.parents('table'), // Removed due to IE issue, to be fixed...
        table          = label.parentWithSelector('table'),
        table_body     = table.find('tbody'),
        header         = label.parentWithSelector('th'),
        column         = table_body.find("."+header.getClass(0)),
        original_order_values = [],
        original_order = [],
        new_order_values = [],
        new_order      = [],
        nodes          = [];

    toggleSelectedColumn( header );

    // Collect content
    column.each(function(cell) {
      var cell = $(cell);
      original_order.push( cell.stripTags() );
      new_order.push( cell.stripTags() );
    });

    //FIXME: this does not work in chrome when reversing
    new_order = label.parent().hasClass('pp-col-date') ? new_order.sort(_datesort) : new_order.sort();
        
    // Sort/reverse
    if( $().array.compare(new_order, original_order) ) new_order.reverse();

    // Adjust to reflect new order
    column.each(function(cell) {
      var cell  = $(cell),
          row   = cell.parent(),
          index = (Array.indexOf) ? new_order.indexOf( cell.stripTags() ) : $().array.indexOf(new_order, cell.stripTags());
          if(cell.first().nodeName == "TD") {
            nodes[index]     = row.first();
            new_order[index] = "--removed--";
            row.remove();
          }
    });

    // Re-inject nodes
    for(var index = 0; index < nodes.length; index++) {
       if(nodes[index] != undefined) {
         table_body.first().appendChild( nodes[index] );
       }
    }
  }
 
}

$(document).ready(function(){
	window.SetupTables(document);
});

window.SetupTables = function(rootNode){
	_setupTables(rootNode);
}



