<?php
// $Id: jstools.module,v 1.1.2.3 2006/07/13 20:16:41 nedjo Exp $

/**
 * @file
 * Provide common methods used by jstools package modules.
 */

/**
 * Implementation of hook_help().
 */
function jstools_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Provides common methods used by Javascript Tools (jstools) modules. Enable if you are using any jstools module.');
  }
}

/**
 * Implementation of hook_menu().
 */
function jstools_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'jstools/settings.js',
      'title' => t('jstools'),
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK,
      'callback' => 'jstools_variables'
     );
  }
  return $items;
}

/**
 * Implementation of hook_form_alter().
 *
 * Register available forms into an array variable.
 */
function jstools_form_alter($form_id, &$form) {
  // If this form_id is not already registered, register it.
  $options = variable_get('jstools_forms_options', array());
  if (!array_key_exists($form_id, $options)) {
    $options[$form_id] = $_GET['q'];
    variable_set('jstools_forms_options', $options);
  }
}

/**
 * Implementation of hook_settings().
 */
function jstools_settings() {
  $form['jstools_debug_level'] = array(
    '#type' => 'select',
    '#title' => t('Debugging level'),
    '#description' => t('Set a debugging level to have jstools print debugging data to the screen.'),
    '#options' => array(0 => t('No debugging')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 10, 20)),
    '#default_value' => variable_get('jstools_debug_level', 0)
  );
  return $form;
}

/**
 * Add a JavaScript file to the output.
 *
 * The first time this function is invoked per page request,
 * it adds jstools files to the output. Other jstools scripts
 * depend on the methods and settings in them.
 */
function jstools_add_js($files) {
  static $core_sent;
  if (!$core_sent) {
    $path = drupal_get_path('module', 'jstools');
    drupal_add_js($path . '/jstools.js');
    drupal_set_html_head(theme_stylesheet_import(base_path() . $path . '/jstools.css'));
    drupal_add_js((variable_get('clean_url', '0') ? '' : '?q=') . 'jstools/settings.js');
  }
  foreach ($files as $file) {
    drupal_add_js($file);
  }
}

/**
 * Menu callback: generate a Javascript file containing variable data.
 */
function jstools_variables() {
  global $base_url;
  drupal_set_header('Content-Type: text/javascript');
  print 'jsTools.basePath = '. drupal_to_js(base_path()) .";\n";
  print 'jsTools.query = '. drupal_to_js(variable_get('clean_url', '0') ? '' : '?q=') .";\n";
  if ($debug_level = variable_get('jstools_debug_level', 0)) {
    print 'jsTools.debugLevel = '. $debug_level .";\n";
  }
  exit();
}
