<?php

/**
 * @file
 * Updates Drupal to use the latest version of jQuery.
 */

/**
 * Implements hook_help().
 */
function jquery_update_help($path, $arg) {
  switch ($path) {
      // Help for another path in the block module
    case 'admin/config/development/jquery_update':
      return '<p>' . t('Configure how <a href="@jquery">jQuery</a> behaves on the site. Select which jQuery version, the compression level and whether or not to use a CDN.', array(
        '@jquery' => 'http://jquery.com',
      )) . '</p>';
  }
}

/**
 * Implements hook_library().
 */
function jquery_update_library() {
  // Register libraries available in the external directory.
  $path = drupal_get_path('module', 'jquery_update') . '/ui/external';
  $libraries['qunit'] = array(
    'title' => 'QUnit',
    'js' => array(
      $path . '/qunit.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 2,
      ),
    ),
    'css' => array(
      $path . '/qunit.css' => array(),
    ),
  );
  $libraries['jquery.metadata'] = array(
    'title' => 'QUnit',
    'js' => array(
      $path . '/jquery.metadata.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 2,
      ),
    ),
    'version' => '4187',
  );
  $libraries['jquery.bgiframe'] = array(
    'title' => 'bgiframe',
    'website' => 'http://docs.jquery.com/Plugins/bgiframe',
    'js' => array(
      $path . '/jquery.bgiframe.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 2,
      ),
    ),
    'version' => '2.1.2',
  );
  return $libraries;
}

/**
 * Implementation of hook_library_alter().
 */
function jquery_update_library_alter(&$javascript, $module) {

  // We are updating just the system module. For all other cases we return.
  if ($module != 'system') {
    return;
  }

  $path = drupal_get_path('module', 'jquery_update');

  // Make sure we inject either the minified or uncompressed version as desired.
  $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
  $cdn = variable_get('jquery_update_jquery_cdn', 'none');

  // Replace jQuery with the latest version.
  $version = variable_get('jquery_update_jquery_version', '1.5');
  jquery_update_jquery_replace($javascript, $cdn, $path, $min, $version);

  // Replace jQuery UI with CDN or local files. If from a CDN include all of jQuery UI.
  jquery_update_jqueryui_replace($javascript, $cdn, $path, $min);

  // Replace the jQuery Cookie plugin.
  $javascript['cookie']['js']['misc/jquery.cookie.js']['data'] = $path . '/replace/ui/external/jquery.cookie.js';
  // Noting the version based on git commit as no version number is available.
  $javascript['cookie']['version'] = '67fb34f6a866c40d0570';

  // Replace jQuery Form plugin.
  $javascript['jquery.form']['js']['misc/jquery.form.js']['data'] = $path . '/replace/misc/jquery.form' . $min . '.js';
  $javascript['jquery.form']['version'] = '2.69';

  // Replace files for jQuery 1.7 and up
  if (version_compare($version, '1.7', '>=')) {
    $javascript['drupal.states']['js']['misc/states.js']['data'] = $path . '/replace/misc/1.7/states.js';
  }
}

/**
 * Implements hook_menu().
 */
function jquery_update_menu() {
  $items['admin/config/development/jquery_update'] = array(
    'title' => 'jQuery update',
    'description' => 'Configure settings related to the jQuery upgrade, the library path and compression.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('jquery_update_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

/**
 * Implementation of hook_form_FORM_ID().
 */
function jquery_update_settings_form() {
  $form['jquery_update_jquery_version'] = array(
    '#type' => 'select',
    '#title' => t('jQuery Version'),
    '#options' => array(
      '1.5' => '1.5',
      '1.7' => '1.7',
      '1.8' => '1.8',
    ),
    '#default_value' => variable_get('jquery_update_jquery_version', '1.5'),
    '#description' => t('Select which jQuery version branch to use.'),
  );
  $form['jquery_update_compression_type'] = array(
    '#type' => 'radios',
    '#title' => t('jQuery compression level'),
    '#options' => array(
      'min' => t('Production (minified)'),
      'none' => t('Development (uncompressed)'),
    ),
    '#default_value' => variable_get('jquery_update_compression_type', 'min'),
  );
  $form['jquery_update_jquery_cdn'] = array(
    '#type' => 'select',
    '#title' => t('jQuery and jQuery UI CDN'),
    '#options' => array(
      'none' => t('None'),
      'google' => t('Google'),
      'microsoft' => t('Microsoft'),
      'jquery' => t('jQuery'),
    ),
    '#default_value' => variable_get('jquery_update_jquery_cdn', 'none'),
    '#description' => t('Use jQuery and jQuery UI from a CDN. If the CDN is not available the local version of jQuery and jQuery UI will be used.'),
  );

  return system_settings_form($form);
}

/**
 * Update jQuery to the CDN or local path.
 *
 * @param array $javascript
 *   The library definition array as seen in hook_library_alter().
 * @param string $cdn
 *   The name of the CDN option to use. Possible options are:
 *   - none
 *   - google
 *   - microsoft
 * @param string $version
 *   The version of jQuery to use.
 */
function jquery_update_jquery_replace(&$javascript, $cdn, $path, $min, $version) {
  // Make sure to use the latest version in given branch.
  $trueversion = NULL;
  switch ($version) {
    case '1.5':
      $trueversion = '1.5.2';
      break;
    case '1.7':
      $trueversion = '1.7.1';
      break;
    case '1.8':
      $trueversion = '1.8.2';
      break;
  }
  $javascript['jquery']['version'] = $trueversion;

  // Check for CDN support.
  switch($cdn) {
    case 'google':
      $javascript['jquery']['js']['misc/jquery.js']['data'] = 'https://ajax.googleapis.com/ajax/libs/jquery/'. $trueversion . '/jquery' . $min . '.js';
      $javascript['jquery']['js']['misc/jquery.js']['type'] = 'external';
      jquery_update_jquery_backup($javascript, $path, $min, $version);
      break;
    case 'microsoft':
      $javascript['jquery']['js']['misc/jquery.js']['data'] = 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-'. $trueversion . $min . '.js';
      $javascript['jquery']['js']['misc/jquery.js']['type'] = 'external';
      jquery_update_jquery_backup($javascript, $path, $min, $version);
      break;
    case 'jquery':
      $javascript['jquery']['js']['misc/jquery.js']['data'] = 'http://code.jquery.com/jquery-'. $trueversion . $min . '.js';
      $javascript['jquery']['js']['misc/jquery.js']['type'] = 'external';
      jquery_update_jquery_backup($javascript, $path, $min, $version);
      break;
    case 'none':
    default:
      $javascript['jquery']['js']['misc/jquery.js']['data'] = $path . '/replace/jquery/'. $version . '/jquery' . $min . '.js';
      break;
  }
}

/**
 * Add the local fallback in case jQuery from the CDN is unavailable.
 *
 * @param array $javascript
 *   The $libraries array as seen in hook_library_alter()
 * @param string $path
 *   The path to the module where replacements can be found.
 * @param string $min
 *   The '.min' to include in the file name if we are requesting a minified version.
 * @param string $version
 *   The verison of jQuery to use.
 */
function jquery_update_jquery_backup(&$javascript, $path, $min, $version) {
  $javascript['jquery']['js'][] = array(
    'data' => 'window.jQuery || document.write("<script src=\'' . base_path() . $path . '/replace/jquery/'. $version . '/jquery' . $min . '.js\'>\x3C/script>")',
    'type' => 'inline',
    'group' => JS_LIBRARY,
    'weight' => -19.999999999,
  );
}

/**
 * Update jQuery UI to the CDN or local path.
 *
 * @param array $javascript
 *   The library definition array as seen in hook_library_alter().
 * @param string $cdn
 *   The name of the CDN option to use. Possible options are:
 *   - none
 *   - google
 *   - microsoft
 */
function jquery_update_jqueryui_replace(&$javascript, $cdn, $path, $min) {
  // Replace all CSS files.
  $names = drupal_map_assoc(array(
    'ui.accordion', 'ui.autocomplete', 'ui.button', 'ui.datepicker',
    'ui.dialog', 'ui.progressbar', 'ui.resizable', 'ui.selectable',
    'ui.slider', 'ui.tabs',
  ));
  $names['ui'] = 'ui.core';
  $csspath = $path . '/replace/ui/themes/base/' . (($min == '.min') ? 'minified/' : '');
  foreach ($names as $name => $file) {
    $javascript[$name]['css']["misc/ui/jquery.$file.css"]['data'] = $csspath . 'jquery.' . $file . $min . '.css';
  }
  // Make sure ui.theme is replaced as well.
  $javascript['ui']['css']['misc/ui/jquery.ui.theme.css']['data'] = $csspath . 'jquery.ui.theme' . $min . '.css';

  // Replace jQuery UI's JavaScript, beginning by defining the mapping.
  $names = drupal_map_assoc(array(
    'ui.accordion', 'ui.autocomplete', 'ui.button', 'ui.datepicker',
    'ui.dialog', 'ui.draggable', 'ui.droppable', 'ui.mouse', 'ui.position',
    'ui.progressbar', 'ui.resizable', 'ui.selectable', 'ui.slider',
    'ui.sortable', 'ui.tabs', 'ui.widget', 'effects.blind', 'effects.bounce',
    'effects.clip', 'effects.drop', 'effects.explode', 'effects.fade',
    'effects.fold', 'effects.highlight', 'effects.pulsate', 'effects.scale',
    'effects.shake', 'effects.slide', 'effects.transfer',
  ));
  $names['ui'] = 'ui.core';
  $names['effects'] = 'effects.core';

  switch($cdn) {
    case 'google':
      $cdn = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui' . $min . '.js';
      jquery_update_jqueryui_cdn($cdn, $javascript, $path, $min, $names);
      jquery_update_jqueryui_backup($javascript, $path, $min);
      break;
    case 'microsoft':
      $cdn = 'http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/jquery-ui' . $min . '.js';
      jquery_update_jqueryui_cdn($cdn, $javascript, $path, $min, $names);
      jquery_update_jqueryui_backup($javascript, $path, $min);
      break;
    case 'none':
      jquery_update_jqueryui_local($javascript, $path, $min, $names);
      break;
  }
}

/**
 * Add the local fallback in case jQuery UI from the CDN is unavailable.
 *
 * @param array $javascript
 *   The $libraries array as seen in hook_library_alter()
 * @param string $path
 *   The path to the module where replacements can be found.
 * @param string $min
 *   The '.min' to include in the file name if we are requesting a minified version.
 */
function jquery_update_jqueryui_backup(&$javascript, $path, $min) {
  $js_path = ($min == '.min') ? '/replace/ui/ui/minified/jquery-ui.min.js' : '/replace/ui/ui/jquery-ui.js';
  $javascript['ui']['js'][] = array(
    'data' => 'window.jQuery.ui || document.write("<script src=\'' . base_path() . $path . $js_path . '\'>\x3C/script>")',
    'type' => 'inline',
    'group' => JS_LIBRARY,
    'weight' => -10.999999999,
  );
}

/**
 * Handle when jQuery UI is updated to the cdn version.
 *
 * @param array $javascript
 *   The $libraries array as seen in hook_library_alter()
 * @param string $path
 *   The path to the module where replacements can be found.
 * @param string $min
 *   The '.min' to include in the file name if we are requesting a minified version.
 * @param array $names
 *   An array mapping jquery ui parts to their file names.
 */
function jquery_update_jqueryui_cdn($cdn, &$javascript, $path, $min, $names) {

  // Construct the jQuery UI path and replace the JavaScript.
  $jspath = $path . '/replace/ui/ui/' . ($min == '.min' ? 'minified/' : '');
  foreach ($names as $name => $file) {
    $corefile = 'misc/ui/jquery.' . $file . '.min.js';
    // Remove the core files.
    unset($javascript[$name]['js'][$corefile]);
    $javascript[$name]['version'] = '1.8.11';
  }

  // UI is used by all of UI. Add the js cdn here.
  $javascript['ui']['js'][$cdn] = array(
    'data' => $cdn,
    'type' => 'external',
    'group' => JS_LIBRARY,
    'weight' => -11,
  );
}

/**
 * Handle when jQuery UI is updated to the local version.
 *
 * @param array $javascript
 *   The $libraries array as seen in hook_library_alter()
 * @param string $path
 *   The path to the module where replacements can be found.
 * @param string $min
 *   The '.min' to include in the file name if we are requesting a minified version.
 * @param array $names
 *   An array mapping jquery ui parts to their file names.
 */
function jquery_update_jqueryui_local(&$javascript, $path, $min, $names) {

  // Construct the jQuery UI path and replace the JavaScript.
  $jspath = $path . '/replace/ui/ui/' . ($min == '.min' ? 'minified/' : '');
  foreach ($names as $name => $file) {
    $corefile = 'misc/ui/jquery.' . $file . '.min.js';
    $javascript[$name]['js'][$corefile]['data'] = $jspath . 'jquery.' . $file . $min . '.js';
    $javascript[$name]['version'] = '1.8.11';
  }
}
