<?php
/*
 * @file:
 * yui_datatable Module for Drupal 6.x
 *
 * This module allows Drupal to replace tables with YUI datatables.
 */

/*
 * Implementation of hook_menu()
 */
function yui_datatable_menu() {
  $items['admin/settings/yui_datatable'] = array(
    'title' => t('YUI datatable settings'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('yui_datatable_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer site configuration'),
    'description' => t("View/Modify YUI datatable settings"),
  );

  return $items;
}

/*
 * implementation of hook_perm().
 */
function yui_datatable_perm() {
  $array = array('Access YUI datatable');

  return $array;
}

/*
 *The settings page.
 */
function yui_datatable_settings_form() {
  $form = array();
  $form['yui_datatable_theme_all'] = array(
    '#type' => 'checkbox',
    '#title' => t('Theme ALL tables with the YUI DataTable'),
    '#default_value' => variable_get('yui_datatable_theme_all', 0),
    '#description' => t('This will force all Drupal generated tables to be themed as YUI DataTables.'));

  return system_settings_form($form);
}

function theme_yui_datatable_view($view, $options, $records, $title) {
  if (function_exists('template_preprocess_views_view_table')) {
    $vars = array();
    $vars['view'] = $view;
    $vars['rows'] = $records;

    template_preprocess_views_view_table($vars);

    $header = $vars['header'];
    $rows = $vars['rows'];

    return theme('yui_datatable', $header, $rows, $attributes = array(), $title);
  }
}

function theme_yui_datatable_table_user($header, $rows, $attributes = array(), $caption = NULL) {
    return theme('table', $header, $rows, $attributes, $caption, TRUE);
}

function theme_yui_datatable_table($header, $rows, $attributes = array(), $caption = NULL, $user_generated = FALSE) {
  if (! user_access('Access YUI datatable')) {
    return theme_table($header, $rows, $attributes, $caption);  
  }
  if ((! variable_get('yui_datatable_theme_all', 0) and ! $user_generated)) {
    return theme_table($header, $rows, $attributes, $caption);
  }

  static $tableID;
  $tableID++;
  $thisTableID = 'table-' . $tableID;
  $thisMarkupID = 'markup-' . $tableID;
  
  render_datatable();
  $attributes['id'] = $thisTableID;
  $sort = '';
  foreach ($header as $row) {
    if (is_array($row)) {
      if ($row['data'] == NULL) {
        $row['data'] = ' ';
      }
      if (isset($row['sort'])) {
        $sort = ", { sortedBy : { key: '" . str_replace(' ', '', $row['data']) . "', dir : '" . $row['sort'] . "' } } ";
      }
      $rowJS .= "{ className : '" . $row['class'] . "', key : '" . str_replace(' ', '', $row['data']) . "', label : '" . $row['data'] . "', sortable : " . (isset($row['field']) ? 'true' : 'false') . " },";
    }
    else {
      $rowJS .= "{ key : '$row', label : '$row' },";
    }  
  }
  foreach ($rows as $index => $row) {
    while (sizeof($rows[$index]) < sizeof($header)) {
      $rows[$index][] = array('data' => '&nbsp;');
    }
  }

  drupal_add_js("
    YAHOO.util.Event.addListener(window, 'load', function() {
      YAHOO.example.EnhanceFromMarkup = new function() {
        var myColumnDefs = [ $rowJS ];

        this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get('$thisTableID'));
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
        this.myDataSource.responseSchema = { fields: [ $rowJS ] };

        this.myDataTable = new YAHOO.widget.DataTable('$thisMarkupID', myColumnDefs, this.myDataSource$sort);
        $('form table:has(th div.select-all):not(.tableSelect-processed)').each(Drupal.yui_datatable_select);
      };
    });", "inline", "footer");

  return '<div id="' . $thisMarkupID . '">' . theme_table($header, $rows, $attributes, $caption) . '</div>';
}

function yui_datatable_theme() {
  return array(
    'table' => array(
      'function' => 'theme_yui_datatable_table',
      'arguments' => array('header' => array(), 'rows' => array(), 'attributes' => array(), 'caption' => NULL)
    ),
    'yui_datatable' => array(
      'function' => 'theme_yui_datatable_table_user',
      'arguments' => array('header' => array(), 'rows' => array(), 'attributes' => array(), 'caption' => NULL, 'user_generated' => TRUE)
    ),
  );
}

/*
 * Add the javascript/CSS needed to render the datatable
 */
function render_datatable() {
  $yui_source = 'http://yui.yahooapis.com/2.5.2'; //variable_get('yui_source','http://yui.yahooapis.com/2.5.2');
  yui_add_css('datatable', $yui_source, '/build/fonts/fonts-min.css');
  yui_add_css('datatable', $yui_source, '/build/datatable/assets/skins/sam/datatable.css');
  yui_add_js('datatable', $yui_source, '/build/yahoo-dom-event/yahoo-dom-event.js');
  yui_add_js('datatable', $yui_source, '/build/element/element-beta-min.js');
  yui_add_js('datatable', $yui_source, '/build/datasource/datasource-beta-min.js');
  yui_add_js('datatable', $yui_source, '/build/datatable/datatable-beta-min.js');
  drupal_add_js(drupal_get_path("module", "yui_datatable")."/yui_datatable_select.js");
}

function yui_datatable_views_plugins() {
  return array(
    'module' => 'views', // This just tells our themes are elsewhere.
    'style' => array(
      'yui_datatable' => array(
        'title' => t('YUI DataTable'),
        'help' => t('Displays rows in a YUI DataTable.'),
        'handler' => 'views_plugin_style_table',
        'theme' => 'yui_datatable_view',
        'uses row plugin' => FALSE,
        'uses fields' => TRUE,
        'uses options' => TRUE,
        'type' => 'normal',
      ),
    ),
  );
}
