/**
 *
 * createDataTable
 * 
 * Build a scrollable, sortable data table from JSON data
 *
 * data - a Javascript object containing the row data and options
 *        (see the JSONTable class for more info)
 * output - indicates what form the output should take:
 *          if output is "dump", the raw HTML for the
 *          table is written to the screen.
 *          If output is an element name, the table HTML
 *          is placed in the innerHTML of that element.
 *          Otherwise, the output element DOM element is
 *          returned.
 */

var num_page_data_tables = 0;
function createDataTable (data, output) {

   // Increment the # of data tables on the page,
   // in case we have to use that # for an ID
   num_page_data_tables++;
   
   // Create the container DIV to hold the header table
   // and content table
   var container = document.createElement('div');
   container.className = 'listTable';
 
   // Create the content table DOM element
   var table = document.createElement('table');   
   table.className='maintable';
   
   // Assign an ID to the content table
   if (data.options.id) {
      table.id = data.options.id;
   } else {
      table.id = 'dataTable'+num_page_data_tables;
   }
   
   // Generate an ID for the container based on the table ID
   container.id = table.id+'_container';   
   // Save the data into the table element
   table.data = data;
   
   // The container is the element which will hold all the
   // HTML we generate, so we'll declare that as the 
   // output element to return later.
   var output_element = container;
   
   // Create the header table element
   var header_table = document.createElement('table');   
   header_table.className = 'headertable';
   header_table.setAttribute('cellpadding',0);   
   header_table.setAttribute('cellspacing',0);
   header_table.setAttribute('border',0);      
   
   // Append it to the container
   container.appendChild(header_table);   
   
   // Add the headings to the heading table
   var tr = document.createElement('tr');
   header_table.appendChild(tr);
   
   for (var i = 0; i < data.headings.length; i++) {
      th = document.createElement('th');
      tr.appendChild(th);

      // Set style options depending on the column order
      if (i == 0) {
         th.style['white-space'] = 'nowrap';
      } else if (i == (data.headings.length - 1)) {
         th.className = 'last';
      }

      // If the column is declared sortable, add an 'onclick' to it
      if (data.options.sortcols && data.options.sortcols.contains(i)) {
         th.setAttribute('onClick', "sortDataTable('"+table.id+"',"+i+")");
         th.className+=' sortable';
      }
      th.setAttribute('align','left');
      
      // Set the header text in a div, so that we can use CSS to create the right border
      div = document.createElement('div');
      th.appendChild(div);
      div.innerHTML = data.headings[i].text;
   }
   
   // Create bottom header row (header shadow)
   tr = document.createElement('tr');
   header_table.appendChild(tr);
   tr.className = 'shadow';
   // Add spacer images to fix the row widths
   for (var i = 0; i < data.headings.length; i++) {
      th = document.createElement('th');
      th.innerHTML = "<img src='/common/images/sp.gif' width='"+data.options.col_widths[i]+"' height='1' />";
      header_table.appendChild(th);
   }
   
   // Create the main table container div, that will be scrollable
   var div = document.createElement('div');
   div.className = 'content';
   container.appendChild(div);
   // Append the main table to the div
   div.appendChild(table);

   table.setAttribute('cellpadding',0);   
   table.setAttribute('cellspacing',0);
   table.setAttribute('border',0);  
         
   var tr; var th; var td; var thead; var tbody;
   
   // Get a handle to the row data
   var rows_array = data['rows'];      

   // Create the <tbody> and append it to the maintable
   tbody = document.createElement('tbody');
   tbody.className = 'content';
   table.appendChild(tbody);

   // Create the spacer row which will fix the column widths
   tr = document.createElement('tr');
   tbody.appendChild(tr);
   for (var i = 0; i < data.headings.length - 1; i++) {
      var td = document.createElement('td');
      td.innerHTML = "<img src='/common/images/sp.gif' width='"+data.options.col_widths[i]+"' height='1' />";
      tr.appendChild(td);
   }
   // Set the last column to have variable width, so that it squeezes for the scrollbar
   var td = document.createElement('td');   
   td.setAttribute('width','100%');
   tr.appendChild(td);

   // Add the rows to the tbody
   for (var row = 0; row < rows_array.length; row++) {

      var row_obj = rows_array[row];

      // If this row is a separator...
      if (row_obj.options.separator) {
         tr = document.createElement('tr');
         tbody.appendChild(tr);
         tr.className = 'separator';
         td = document.createElement('td');
         tr.appendChild(td);
         td.setAttribute('colspan',data.headings.length);
         continue;
      }
      
      // Otherwise...
      tr = document.createElement('tr');
      // Give the row a unique ID for sorting purposes
      tr.id = table.id+"_row_"+row;
      tbody.appendChild(tr);
      // Stripe the rows
      if (row % 2 == 1) {
         tr.className = 'odd';
      } else {
         tr.className = 'even';
      }
      
      // Set up row style and options based on the user options provided
      if (row_obj.options.className) {
         tr.className+=' '+row_obj.options.className;
      }
      if (row_obj.options.style) {
         tr.setAttribute('style',row_obj.options.style);
      }
      if (row_obj.options.onmouseover) {
         tr.setAttribute('onMouseover',row_obj.options.onmouseover);
      }
      if (row_obj.options.onmouseout) {
         tr.setAttribute('onMouseout',row_obj.options.onmouseout);
      }
      if (row_obj.options.onclick) {
         tr.setAttribute('onClick',row_obj.options.onclick);
      }

      // Add the columns data to the row
      for (var col = 0; col < data.headings.length; col++) {
      
         var col_obj = rows_array[row].cols[col];
         td = document.createElement('td');
         tr.appendChild(td);
         if (col == 0) {
            td.className = 'first';
         } else if (col == (data.headings.length - 1)) {
            td.className = 'last';
         }
         
         // If this col spans multiple columns, set it up and increment
         // the col variable accordingly
         if (col_obj.options.colspan) {
            td.setAttribute('colSpan', col_obj.colspan);
            col += (col_obj.options.colspan - 1);
         }
         
         // If a class was supplied for the column
         if (col_obj.options.className) {
            td.className+=' '+col_obj.options.className;
         }
         
         // If there is a default class for this column, and another one hasn't been specified, use it
         else if (data.options.default_col_classes && data.options.default_col_classes[col]) {
            td.className+=' '+data.options.default_col_classes[col];
         }
       
         // Add whatever optional style characteristics into this <TD>
         if (col_obj.options.style) {
            td.setAttribute('style',col_obj.options.style);
         }
         
         // Finally, add the text for the column
         td.innerHTML = '<div>'+col_obj.text+'</div>';
         
      }
      
   }
      
   // Create the footer
   var foot = document.createElement('div');
   foot.className='bottomBar';
   foot.innerHTML = '<div>&nbsp;</div>';
   container.appendChild(foot);
   
   // If 'output' is set, append the table to the document
   if (output && output == 'dump') {      
      var temp_el = document.createElement('div');
      temp_el.appendChild(output_element);
      document.writeln(temp_el.innerHTML);
      $(table.id).data = data;
   } else if (output) {      
      var temp_el = document.createElement('div');
      temp_el.appendChild(output_element);
      $(output).innerHTML = temp_el.innerHTML;
      temp_el = null;
      output_element = null;
   } 
   else {
      return output_element;
   }
      
   
}

var SORT_COLUMN_INDEX;
function sortDataTable(table_id,colnum,dir) {

   var table = $(table_id);
   var data = table.data;
   
   var main_tbody = table.getElementsByTagName('tbody')[0];
   
   if (colnum == null) {
      colnum = 0;
   }
   
   if (data.sort_col != null && data.sort_col == colnum) {
      if (dir == null) {
         dir = data.sort_dir == 1 ? -1 : 1;
      }
   }

   else if (dir == null) {
      dir = -1;
   }
   //alert(dir);
   // Get the data from the column we want
   var col_data = new Array();
   for (var i = 0; i < data.rows.length; i++) {
      var rowstr = (i < 10 ? '0'+i : i);
      col_data[i] = {rownum: i, data: data.rows[i].cols[colnum].data+rowstr};
   }
   SORT_COLUMN_INDEX = colnum;
   col_data.sort(sortCompareFunction);
   if (dir == -1) {
      col_data.reverse();
   }
   var new_tbody = document.createElement('tbody');
   // Insert the spacer row
   
   new_tbody.appendChild(main_tbody.getElementsByTagName('tr')[0].cloneNode(true));
   new_tbody.className = 'content';
   var new_rows = new Array;
   for (var i = (data.rows.length - 1); i >= 0;  i--) {
      var rownum = i;
      //var tr = main_tbody.getElementsByTagName('tr')[col_data[rownum].rownum].cloneNode(true);
      //alert (table.id+"_row_"+i);
      var tr = document.getElementById(table.id+"_row_"+col_data[i].rownum).cloneNode(true);
      
      //new_rows[i] = data.rows[col_data[i].rownum];
      
      if ((i + (dir == 1 ? 0 : 1)) % 2 == 1) {
         if (tr.className.indexOf('even') == -1) {
            tr.className = tr.className.replace(/\s*odd/,'even');
         } 
      } else {
            tr.className = tr.className.replace(/\s*even/,'odd');
      }
      new_tbody.appendChild(tr);
   }

   table.data.sort_col = colnum;
   table.data.sort_dir = dir;
   //table.replaceChild(new_tbody,main_tbody);
   table.removeChild(main_tbody);
   var newTable = table.cloneNode(true);   
   newTable.data = table.data;
   newTable.appendChild(new_tbody);
   table.parentNode.replaceChild(newTable,table);
   //table.replaceChild(new_tbody,main_tbody);
   //table.data.rows = new_rows;
      
};   
   
function sortCompareFunction (a,b) {
    if (a.data == b.data) return 0;
    if (a.data < b.data) return -1;
    return 1;

}
