<?php
// $Id: collapsiblock.module,v 1.1.2.5 2006/07/13 20:16:40 nedjo Exp $

/**
 * @file
 * Make blocks collapsible.
 */

/**
 * Implementation of hook_help().
 */
function collapsiblock_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Makes blocks collapsible.');
  }
}

/**
 * Implementation of hook_menu().
 */
function collapsiblock_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'collapsiblock/js',
      'title' => t('collapsiblock'),
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK,
      'callback' => 'collapsiblock_js'
     );
    $items[] = array(
      'path' => 'collapsiblock/defaults.js',
      'title' => t('collapsiblock defaults'),
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK,
      'callback' => 'collapsiblock_defaults'
     );
  }
  else {
    collapsiblock_load();
  }
  return $items;
}

/**
 * Load needed files.
 */
function collapsiblock_load() {
  $path = drupal_get_path('module', 'collapsiblock');
  module_invoke('jstools', 'add_js', array(
    $path . '/collapsiblock.js',
    (variable_get('clean_url', '0') ? '' : '?q=') . 'collapsiblock/defaults.js')
  );
  drupal_add_js($path . '/collapsiblock.js');
  drupal_set_html_head(theme_stylesheet_import(base_path() . $path .'/collapsiblock.css'));
}

function collapsiblock_form_alter($form_id, &$form) {
  if ($form_id == 'block_admin_configure') {
    $settings = variable_get('collapsiblock_settings', array());
    $form['#submit']['collapsiblock_submit'] = array();
    $form['collapsiblock'] = array(
      '#type' => 'fieldset',
      '#title' => t('Collapsible'),
      '#collapsible' => true,
      '#weight' => -5
    );
    $form['collapsiblock']['collapse_type'] = array(
      '#type' => 'radios',
      '#title' => t('Block collapse behavior'),
      '#options' => array(1 => t('None.'), 2 => t('Collapsible, expanded by default.'), 3 => t('Collapsible, collapsed by default.')),
      '#default_value' => $settings['block-' . $form['module']['#value'] . '-' . $form['delta']['#value']] ? $settings['block-' . $form['module']['#value'] . '-' . $form['delta']['#value']] : 2
    );
  }
}

function collapsiblock_submit($form_id, $edit) {
  $settings = variable_get('collapsiblock_settings', array());
  $settings['block-' . $edit['module'] . '-' . $edit['delta']] = $edit['collapse_type'];
  variable_set('collapsiblock_settings', $settings);
}

function collapsiblock_defaults() {
  $defaults = variable_get('collapsiblock_settings', array());
  drupal_set_header('Content-Type: text/javascript');
  print 'jsTools.collapsiblockDefaults = ' . drupal_to_js($defaults) . ";\n";
  exit();
}
