// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount>0)
      Effect.Appear('busy',{duration:0.5,queue:'end'});
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount==0)
      Effect.Fade('busy',{duration:0.5,queue:'end'});
  }
});

function findElement (element_class, category, text){
  search = $F(text).toLowerCase();
  which  = $F(category);
  $$(element_class).each(function(row) {
    row.hide();
    Element.classNames(row).each(function(name) { 
      n = name.split('_');
      if(search.length == 0 || (n[1] && n[0] == which && n[1].indexOf(search) == 0)) {
        row.show();
      }
    });
  });
}

function sortTable(tableId, trClass, columnIndex){
  unsortedRows = $$('tr.' + trClass); // document.getElementsByClassName(trClass, tableId);
  sortedRows = unsortedRows.sortBy(function(node, i){
    // feed the sortBy Enumerable method the column data to be compared
    return $A(node.getElementsByTagName("td"))[(columnIndex - 1)].innerHTML.toLowerCase();
  });
  // make the HTML
  sortedRowsHTML = "";
  sortedRows.each(function(node, i){
    sortedRowsHTML += "<tr id=\""+node.id+"\" class=\""+node.className+"\" style=\"display: "+(Element.visible(node) ? "" : "none") +";\">"+ node.innerHTML + "</tr>";
  });
  // write the HTML to the page
  Element.update($$("."+tableId+" tbody").first(), sortedRowsHTML);
}

function update_select_options( target, opts_array, clear_select_list ) {
   
    if( $(target).type.match("select" ) ){ // Confirm the target is a select box
        
        // Remove existing options from the target and the clear_select_list
        clear_select_list[clear_select_list.length] = target // Include the target in the clear list
        
        for( k=0;k < clear_select_list.length;k++){
            obj = $(clear_select_list[k]);
            if( obj.type.match("select") ){
                len = obj.childNodes.length;
                for( var i=0;i < len;i++){obj.removeChild(obj.firstChild);}
            }
        }
        
        // Populate the new options
        for(i=0;i < opts_array.length;i++){
            o = document.createElement( "option" );
            o.appendChild( document.createTextNode( opts_array[i][0] ) );
            o.setAttribute( "value", opts_array[i][1] );
            obj.appendChild(o);
        }
    }
}

function filterBy(tok, cls){
  $$("."+cls).each(function(row){
	if($A(Element.classNames(row)).indexOf($F(tok)) >= 0){
	  Element.show(row);
	} else {
	  Element.hide(row);
	}
  });
}
