<?php

/**
 * @file
 * Enables the use of jQuery Superfish plugin for Drupal menus.
 */

/**
 * Implements hook_menu().
 */
function superfish_menu() {
  $items['admin/config/user-interface/superfish'] = array(
    'title' => 'Superfish',
    'description' => 'Configure Superfish Menus',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('superfish_admin_settings'),
    'access arguments' => array('administer superfish'),
    'file' => 'superfish.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function superfish_permission() {
  return array(
    'administer superfish' => array(
      'title' => t('Administer Superfish'),
    ),
  );
}

/**
 * Implements hook_help().
 */
function superfish_help($path, $arg) {
  $output = '';
  switch ($path) {
    case 'admin/modules#description':
      $output .= t('jQuery Superfish plugin for your Drupal menus.');
      break;
    case 'admin/config/user-interface/superfish':
      $output .= t('<p>Block-specific Superfish settings could be found at !link</p>', array('!link' => l('admin/structure/block', 'admin/structure/block')));
      break;
  }
  return $output;
}

/**
 * Implements hook_block_info().
 */
function superfish_block_info() {
  $blocks = array();
  $number = variable_get('superfish_number', 4);
  for ($i = 1; $i <= $number; $i++) {
    $blocks[$i] = array(
      'info' => variable_get('superfish_name_' . $i, 'Superfish ' . $i) . ' (Superfish)',
      'cache' => DRUPAL_NO_CACHE,
    );
  }
  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function superfish_block_configure($delta = 0) {
  $form = array();
  $form['superfish_name_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
    '#description' => t('A brief description of your block. Used on the !link', array('!link' => l(t('Blocks administration page'), 'admin/structure/block'))),
    '#default_value' => variable_get('superfish_name_' . $delta, 'Superfish ' . $delta),
  );
  $form['sf-menu'] = array(
    '#type' => 'fieldset',
    '#title' => t('Menu'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-menu']['superfish_menu_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Menu parent'),
    '#description' => t('The menu you want to be displayed using Superfish.') . ' <em>(' . t('Default') . ': &lt;Main menu&gt;)</em>',
    '#default_value' => variable_get('superfish_menu_' . $delta, 'main-menu:0'),
    '#options' => menu_parent_options(menu_get_menus(), array('mlid' => 0)),
  );
  $form['sf-menu']['superfish_depth_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Menu depth'),
    '#description' => t('The number of child levels starting with the parent selected above. <strong>-1</strong> means all of them, <strong>0</strong> means none of them.') . ' <em>(' . t('Default') . ': -1)</em>',
    '#default_value' => variable_get('superfish_depth_' . $delta, -1),
    '#options' => drupal_map_assoc(range(-1, 50)),
  );
  $form['sf-menu']['superfish_expanded_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Take "Expanded" option into effect.'),
    '#description' => t('By enabling this option, only parent menu items with <em>Expanded</em> option enabled will have their submenus appear.') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_expanded_' . $delta, 0),
  );
  $form['sf-settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Superfish settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-settings']['superfish_type_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Menu type'),
    '#description' => '<em>(' . t('Default') . ': ' . t('Horizontal') . ')</em>',
    '#default_value' => variable_get('superfish_type_' . $delta, 'horizontal'),
    '#options' => array(
      'horizontal' => t('Horizontal'),
      'vertical' => t('Vertical'),
      'navbar' => t('NavBar'),
    ),
  );
  $form['sf-settings']['superfish_style_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Style'),
    '#description' => '<em>(' . t('Default') . ': ' . t('None') . ')</em>',
    '#default_value' => variable_get('superfish_style_' . $delta, 'none'),
    '#options' => superfish_styles(),
  );
  $form['sf-settings']['superfish_speed_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Animation speed'),
    '#description' => t('The speed of the animation either in <strong>milliseconds</strong> or pre-defined values (<strong>slow, normal, fast</strong>).') . ' <em>(' . t('Default') . ': fast)</em>',
    '#default_value' => variable_get('superfish_speed_' . $delta, 'fast'),
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['sf-settings']['superfish_delay_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Mouse delay'),
    '#description' => t('The delay in <strong>milliseconds</strong> that the mouse can remain outside a sub-menu without it closing.') . ' <em>(' . t('Default') . ': 800)</em>',
    '#default_value' => variable_get('superfish_delay_' . $delta, 800),
    '#size' => 15,
  );
  $form['sf-settings']['superfish_pathclass_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Path class'),
    '#description' =>  t('The class you have applied to list items that lead to the current page.') . ' <em>(' . t('Default') . ': active-trail)</em><br />' . t('Change this <strong>only</strong> if you are <strong>totally sure</strong> of what you are doing.'),
    '#default_value' => variable_get('superfish_pathclass_' . $delta, 'active-trail'),
    '#size' => 15,
  );
  $form['sf-settings']['superfish_pathlevels_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Path levels'),
    '#description' => t('The amount of sub-menu levels that remain open or are restored using <strong>Path class</strong>.') . ' <em>(' . t('Default') . ': 1)</em>',
    '#default_value' => variable_get('superfish_pathlevels_' . $delta, 1),
    '#options' => drupal_map_assoc(range(0, 10)),
  );
  $form['sf-settings']['superfish_slide_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Slide-in effect'),
    '#description' => '<em>(' . t('Default') . ': ' . t('Vertical') . ')</em><br />' . ((count(superfish_effects()) == 4) ? t('jQuery Easing plugin is not installed.') . '<br />' . t('The plugin provides a handful number of animation effects, they can be used by uploading the \'jquery.easing.js\' file to the libraries directory within the \'easing\' directory (for example: sites/all/libraries/easing/jquery.easing.js). Refresh this page after the plugin is uploaded, this will make more effects available in the above list.') . '<br />' : '') . '<strong>' . t('Important') . ':</strong> ' . t('Easing effects require jQuery 1.6.1 or higher. If you need to update your jQuery to version 1.6.1 or higher, please use the jQuery Update module.'),
    '#default_value' => variable_get('superfish_slide_' . $delta, 'vertical'),
    '#options' => superfish_effects(),
  );
  $form['sf-settings']['superfish_arrow_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Auto-arrows'),
    '#default_value' => variable_get('superfish_arrow_' . $delta, 1),
  );
  $form['sf-settings']['superfish_shadow_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Drop shadows'),
    '#default_value' => variable_get('superfish_shadow_' . $delta, 1),
  );
  $form['sf-settings']['sf-more']  = array(
    '#type' => 'fieldset',
    '#title' => t('More options'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-settings']['sf-more']['superfish_use_link_theme_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Use a theme function for hyperlinks.') . ' <em>(' . t('Default') . ': ' . t('enabled') . ')</em><br /><small>' . t('(Disabling this feature can result in performance improvements, depending on the number of hyperlinks in the menu.)') . '</small>',
    '#default_value' => variable_get('superfish_use_link_theme_' . $delta, 1),
  );
  $form['sf-settings']['sf-more']['superfish_use_item_theme_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Use a theme function for menu items.') . ' <em>(' . t('Default') . ': ' . t('enabled') . ')</em><br /><small>' . t('(Disabling this feature can result in performance improvements, depending on the number of items in the menu.)') . '</small>',
    '#default_value' => variable_get('superfish_use_item_theme_' . $delta, 1),
  );
  $form['sf-plugins'] = array(
    '#type' => 'fieldset',
    '#title' => t('Superfish plugins'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['superfish_bgf_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Use jQuery BgiFrame plugin for this menu.'),
    '#description' => t('Helps ease the pain when having to deal with IE z-index issues.') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_bgf_' . $delta, 0),
  );
  $form['sf-plugins']['superfish_spp_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Use jQuery Supposition plugin for this menu.') . ' <sup>(' . t('Beta') . ')</sup>',
    '#description' => t('Relocates sub-menus when they would otherwise appear outside the browser window area.') . ' <em>(' . t('Default') . ': ' . t('enabled') . ')</em>',
    '#default_value' => variable_get('superfish_spp_' . $delta, 1),
  );
  $form['sf-plugins']['superfish_hid_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable hoverIntent detection.'),
    '#description' => t('Prevents accidental firing of animations by waiting until the user\'s mouse slows down enough, hence determinig user\'s <em>intent</em>.') . ' <em>(' . t('Default') . ': ' . t('enabled') . ')</em>',
    '#default_value' => variable_get('superfish_hid_' . $delta, 1),
  );
  $form['sf-plugins']['sf-touchscreen'] = array(
    '#type' => 'fieldset',
    '#title' => t('sf-Touchscreen') . ' <sup>(' . t('Beta') . ')</sup>',
    '#description' => t('<strong>sf-Touchscreen</strong> provides touchscreen compatibility for your menus.') . ' <sup>(' . t('The first click on a parent hyperlink shows its children and the second click opens the hyperlink.') . ')</sup>',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-plugins']['sf-touchscreen']['superfish_touch_' . $delta] = array(
    '#type' => 'radios',
    '#default_value' => variable_get('superfish_touch_' . $delta, 0),
    '#options' => array(
      0 => t('Disable') . '. <sup>(' . t('Default') . ')</sup>',
      1 => t('Enable jQuery sf-Touchscreen plugin for this menu.'),
      2 => t('Enable jQuery sf-Touchscreen plugin for this menu depending on the user\'s Web browser <strong>window width</strong>.'),
      3 => t('Enable jQuery sf-Touchscreen plugin for this menu depending on the user\'s Web browser <strong>user agent</strong>.'),
    ),
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-windowwidth'] = array(
    '#type' => 'fieldset',
    '#title' => t('Window width settings'),
    '#description' => t('sf-Touchscreen will be enabled only if the width of user\'s Web browser window is smaller than the below value.') . '<br /><br />' . t('Please note that in most cases such a meta tag is necessary for this feature to work properly:') . '<br /><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;</code>',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-windowwidth']['superfish_touchbp_' . $delta] = array(
    '#type' => 'textfield',
    '#description' => t('Also known as "Breakpoint".') . ' <em>(' . t('Default') . ': 768)</em>',
    '#default_value' => variable_get('superfish_touchbp_' . $delta, 768),
    '#field_suffix' => t('pixels'),
    '#size' => 10,
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-useragent'] = array(
    '#type' => 'fieldset',
    '#title' => t('User agent settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-useragent']['superfish_touchua_' . $delta] = array(
    '#type' => 'radios',
    '#default_value' => variable_get('superfish_touchua_' . $delta, 0),
    '#options' => array(
      0 => t('Use the pre-defined list of the <strong>user agents</strong>.') . '<sup>(' . t('Default') . ') (' . t('Recommended') . ')</sup>',
      1 => t('Use the custom list of the <strong>user agents</strong>.'),
    ),
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-useragent']['superfish_touchual_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Custom list of the user agents'),
    '#description' => t('Could be partial or complete. (Asterisk separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ':<ul><li>iPhone*Android*iPad <sup>(' . t('Recommended') . ')</sup></li><li>Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.0 * Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405</li></ul>' . ((isset($_SERVER['HTTP_USER_AGENT'])) ? '<br />' . t('<strong>UA string of the current Web browser:</strong>') . ' ' . $_SERVER['HTTP_USER_AGENT'] : ''),
    '#default_value' => variable_get('superfish_touchual_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 2000,
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-useragent']['superfish_touchuam_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('<strong>User agent</strong> detection method'),
    '#description' => '<em>(' . t('Default') . ': ' . t('Client-side (JavaScript)') . ')</em>',
    '#default_value' => variable_get('superfish_touchuam_' . $delta, 0),
    '#options' => array(
      0 => t('Client-side (JavaScript)'),
      1 => t('Server-side (PHP)')
    ),
  );
  $form['sf-plugins']['sf-smallscreen'] = array(
    '#type' => 'fieldset',
    '#title' => t('sf-Smallscreen') . ' <sup>(' . t('Beta') . ')</sup>',
    '#description' => t('<strong>sf-Smallscreen</strong> provides small-screen compatibility for your menus.') . ' <sup>(' . t('Converts the dropdown into a &lt;select&gt; element.') . ')</sup>',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-plugins']['sf-smallscreen']['superfish_small_' . $delta] = array(
    '#type' => 'radios',
    '#default_value' => variable_get('superfish_small_' . $delta, 2),
    '#options' => array(
      0 => t('Disable') . '.',
      1 => t('Enable jQuery sf-Smallscreen plugin for this menu.'),
      2 => t('Enable jQuery sf-Smallscreen plugin for this menu depending on the user\'s Web browser <strong>window width</strong>.') . ' <sup>(' . t('Default') . ')</sup>',
      3 => t('Enable jQuery sf-Smallscreen plugin for this menu depending on the user\'s Web browser <strong>user agent</strong>.'),
    ),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-windowwidth'] = array(
    '#type' => 'fieldset',
    '#title' => t('Window width settings'),
    '#description' => t('sf-Smallscreen will be enabled only if the width of user\'s Web browser window is smaller than the below value.') . '<br /><br />' . t('Please note that in most cases such a meta tag is necessary for this feature to work properly:') . '<br /><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;</code>',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-windowwidth']['superfish_smallbp_' . $delta] = array(
    '#type' => 'textfield',
    '#description' => t('Also known as "Breakpoint".') . ' <em>(' . t('Default') . ': 768)</em>',
    '#default_value' => variable_get('superfish_smallbp_' . $delta, 768),
    '#field_suffix' => t('pixels'),
    '#size' => 10,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-useragent'] = array(
    '#type' => 'fieldset',
    '#title' => t('User agent settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-useragent']['superfish_smallua_' . $delta] = array(
    '#type' => 'radios',
    '#default_value' => variable_get('superfish_smallua_' . $delta, 0),
    '#options' => array(
      0 => t('Use the pre-defined list of the <strong>user agents</strong>.') . '<sup>(' . t('Default') . ') (' . t('Recommended') . ')</sup>',
      1 => t('Use the custom list of the <strong>user agents</strong>.'),
    ),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-useragent']['superfish_smallual_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Custom list of the user agents'),
    '#description' => t('Could be partial or complete. (Asterisk separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ':<ul><li>iPhone*Android*iPad <sup>(' . t('Recommended') . ')</sup></li><li>Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.0 * Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405</li></ul>' . ((isset($_SERVER['HTTP_USER_AGENT'])) ? '<br />' . t('<strong>UA string of the current Web browser:</strong>') . ' ' . $_SERVER['HTTP_USER_AGENT'] : ''),
    '#default_value' => variable_get('superfish_smallual_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 2000,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-useragent']['superfish_smalluam_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('<strong>User agent</strong> detection method:'),
    '#description' => '<em>(' . t('Default') . ': ' . t('Client-side (JavaScript)') . ')</em>',
    '#default_value' => variable_get('superfish_smalluam_' . $delta, 0),
    '#options' => array(
      0 => t('Client-side (JavaScript)'),
      1 => t('Server-side (PHP)')
    ),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select'] = array(
    '#type' => 'fieldset',
    '#title' => t('&lt;select&gt; settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['superfish_smallset_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('&lt;select&gt; title'),
    '#description' => t('By default the first item in the &lt;select&gt; element will be the name of the parent menu or the title of this block, you can change this by setting a custom title.') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': <em> - ' . t('Main Menu') . ' - </em>.',
    '#default_value' => variable_get('superfish_smallset_' . $delta, ''),
    '#size' => 50,
    '#maxlength' => 500,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['superfish_smallasa_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <em>selected</em> attribute to the &lt;option&gt; element with the class <strong>active</strong>'),
    '#description' => t('Makes pre-selected the item linked to the active page when the page loads.'),
    '#default_value' => variable_get('superfish_smallasa_' . $delta, 0),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more'] = array(
    '#type' => 'fieldset',
    '#title' => t('More'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallcmc_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Copy the main &lt;ul&gt; classes to the &lt;select&gt;.'),
    '#description' => ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_smallcmc_' . $delta, 0),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallecm_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Exclude these classes from the &lt;select&gt; element'),
    '#description' => t('Comma separated') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em>',
    '#default_value' => variable_get('superfish_smallecm_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
    '#states' => array(
      'enabled' => array(
       ':input[name="superfish_smallcmc_' . $delta . '"]' => array('checked' => TRUE),
      ),
    ),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallchc_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Copy the hyperlink classes to the &lt;option&gt; elements of the &lt;select&gt;.'),
    '#description' => ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_smallchc_' . $delta, 0),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallech_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Exclude these classes from the &lt;option&gt; elements of the &lt;select&gt;'),
    '#description' => t('Comma separated') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em>',
    '#default_value' => variable_get('superfish_smallech_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
    '#states' => array(
      'enabled' => array(
       ':input[name="superfish_smallchc_' . $delta . '"]' => array('checked' => TRUE),
      ),
    ),
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallicm_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Include these classes in the &lt;select&gt; element'),
    '#description' => t('Comma separated') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em>',
    '#default_value' => variable_get('superfish_smallicm_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-select']['sf-smallscreen-select-more']['superfish_smallich_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Include these classes in the &lt;option&gt; elements of the &lt;select&gt;'),
    '#description' => t('Comma separated') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em>',
    '#default_value' => variable_get('superfish_smallich_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-plugins']['sf-supersubs'] = array(
    '#type' => 'fieldset',
    '#title' => t('Supersubs'),
    '#description' => t('<strong>Supersubs</strong> makes it possible to define custom widths for your menus.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-plugins']['sf-supersubs']['superfish_supersubs_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Supersubs for this menu.'),
    '#default_value' => variable_get('superfish_supersubs_' . $delta, 1),
  );
  $form['sf-plugins']['sf-supersubs']['superfish_minwidth_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Minimum width'),
    '#description' => t('Minimum width for sub-menus, in <strong>em</strong> units.') . ' <em>(' . t('Default') . ': 12)</em>',
    '#default_value' => variable_get('superfish_minwidth_' . $delta, '12'),
    '#size' => 20,
    '#required' => TRUE,
  );
  $form['sf-plugins']['sf-supersubs']['superfish_maxwidth_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum width'),
    '#description' => t('Maximum width for sub-menus, in <strong>em</strong> units.') . ' <em>(' . t('Default') . ': 27)</em>',
    '#default_value' => variable_get('superfish_maxwidth_' . $delta, '27'),
    '#size' => 20,
    '#required' => TRUE,
  );
  $form['sf-megamenu'] = array(
    '#type' => 'fieldset',
    '#title' => t('Multi-column sub-menus') . ' <sup>(' . t('Beta') . ')</sup>',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-megamenu']['superfish_multicolumn_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable multi-column sub-menus.'),
    '#default_value' => variable_get('superfish_multicolumn_' . $delta, 0),
  );
  $form['sf-megamenu']['superfish_mcexclude_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Exclude below menu items'),
    '#description' => t('Enter the ID number of the parent menu item you <strong>do not</strong> want multi-column sub-menus for. (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': 5,10,20',
    '#default_value' => variable_get('superfish_mcexclude_' . $delta, ''),
    '#size' => 50,
  );
  $form['sf-megamenu']['superfish_mcdepth_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Start from depth'),
    '#description' => t('The depth of the first instance of multi-column sub-menus.') . ' <em>(' . t('Default') . ': 1)</em>',
    '#default_value' => variable_get('superfish_mcdepth_' . $delta, 1),
    '#options' => drupal_map_assoc(range(1, 10)),
  );
  $form['sf-megamenu']['superfish_mclevels_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Levels'),
    '#description' => t('The amount of sub-menu levels that will be included in the multi-column sub-menu.') . ' <em>(' . t('Default') . ': 1)</em>',
    '#default_value' => variable_get('superfish_mclevels_' . $delta, 1),
    '#options' => drupal_map_assoc(range(1, 10)),
  );
  $form['sf-advanced-html'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced HTML settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-advanced-html']['sf-hyperlinks'] = array(
    '#type' => 'fieldset',
    '#title' => t('Hyperlinks'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-html']['sf-hyperlinks']['superfish_hhldescription_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide hyperlink descriptions ("title" attribute)') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#description' => t('(Enabling this feature makes the below settings ineffective.)'),
    '#default_value' => variable_get('superfish_hhldescription_' . $delta, 0),
  );
  $form['sf-advanced-html']['sf-hyperlinks']['sf-hyperlinktexts'] = array(
    '#type' => 'fieldset',
    '#title' => t('Hyperlink texts'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-html']['sf-hyperlinks']['sf-hyperlinktexts']['superfish_hldescription_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Insert hyperlink descriptions ("title" attribute) into hyperlink texts.'),
    '#default_value' => variable_get('superfish_hldescription_' . $delta, 0),
  );
  $form['sf-advanced-html']['sf-hyperlinks']['sf-hyperlinktexts']['superfish_hldmenus_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Limit to below menu items'),
    '#description' => t('Enter menu item ID\'s. Leave empty to include all menus. (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': 5,10,20',
    '#default_value' => variable_get('superfish_hldmenus_' . $delta, ''),
    '#size' => 50,
  );
  $form['sf-advanced-html']['sf-hyperlinks']['sf-hyperlinktexts']['superfish_hldexclude_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Exclude below menu items'),
    '#description' => t('Enter the ID of the menu items you <strong>do not</strong> want to link descriptions for. (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': 5,10,20',
    '#default_value' => variable_get('superfish_hldexclude_' . $delta, ''),
    '#size' => 50,
  );
  $form['sf-advanced-html']['sf-html-wrappers'] = array(
    '#type' => 'fieldset',
    '#title' => t('HTML wrappers'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-html']['sf-html-wrappers']['superfish_wrapmul_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Around the main &lt;UL&gt;'),
    '#description' => t('Insert extra codes <strong>before</strong> and\or <strong>after</strong> the main UL. (Comma separated).') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ': <ul><li>&lt;h3&gt;Discover the universe!&lt;/h3&gt;,</li><li>&lt;h3&gt;Hello there!&lt;/h3&gt;,&lt;div style="clear:both"&gt;&lt;/div&gt;</li><li>,&lt;div style="clear:both"&gt;&lt;/div&gt;</li></ul>',
    '#default_value' => variable_get('superfish_wrapmul_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-html']['sf-html-wrappers']['superfish_wrapul_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Around the &lt;UL&gt; content'),
    '#description' => t('Insert extra codes <strong>before</strong> and\or <strong>after</strong> the ULs. (Comma separated).') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ': <ul><li>&lt;h3&gt;Discover the universe!&lt;/h3&gt;,</li><li>&lt;h3&gt;Hello there!&lt;/h3&gt;,&lt;div style="clear:both"&gt;&lt;/div&gt;</li><li>,&lt;div style="clear:both"&gt;&lt;/div&gt;</li></ul>',
    '#default_value' => variable_get('superfish_wrapul_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-html']['sf-html-wrappers']['superfish_wraphl_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Around the hyperlinks'),
    '#description' => t('Insert HTML objects <strong>before</strong> and\or <strong>after</strong> hyperlinks. (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ': <ul><li>&lt;span class="background-left"&gt;&lt;span class="background-right"&gt;,&lt;/span&gt;&lt;/span&gt;</li><li>&lt;img src="example.jpg" width="24" height="24" alt="example" title="example" /&gt;,</li><li>,&lt;span class="custom-arrow"&gt;>&lt;/span&gt;</li></ul>',
    '#default_value' => variable_get('superfish_wraphl_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-html']['sf-html-wrappers']['superfish_wraphlt_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Around the hyperlinks content'),
    '#description' => t('Insert extra codes <strong>before</strong> and\or <strong>after</strong> the text in hyperlinks. (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ': <ul><li>&lt;span class="background-left"&gt;&lt;span class="background-right"&gt;,&lt;/span&gt;&lt;/span&gt;</li><li>&lt;img src="example.jpg" width="24" height="24" alt="example" title="example" /&gt;,</li><li>,&lt;span class="custom-arrow"&gt;>&lt;/span&gt;</li></ul>',
    '#default_value' => variable_get('superfish_wraphlt_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-css'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced CSS settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-advanced-css']['sf-helper-classes'] = array(
    '#type' => 'fieldset',
    '#title' => t('Helper classes'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_firstlast_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <strong>first \ middle \ last</strong> classes.'),
    '#default_value' => variable_get('superfish_firstlast_' . $delta, 1),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_zebra_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <strong>odd \ even</strong> classes.'),
    '#default_value' => variable_get('superfish_zebra_' . $delta, 1),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_dfirstlast_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Do <strong>not</strong> add <strong>first \ middle \ last</strong> classes to single menu items.'),
    '#default_value' => variable_get('superfish_dfirstlast_' . $delta, 0),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_dzebra_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Do <strong>not</strong> add <strong>odd \ even</strong> classes to single menu items.'),
    '#default_value' => variable_get('superfish_dzebra_' . $delta, 0),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_itemcount_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <strong>item count</strong> class to menu items.') . '<em>(sf-item-1, sf-item-2, sf-item-3, ...)</em>',
    '#default_value' => variable_get('superfish_itemcount_' . $delta, 1),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_itemcounter_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <strong>children counter</strong> classes to menu items.') . '<em>(sf-total-children-7 sf-parent-children-4 sf-single-children-3, ...)</em>',
    '#default_value' => variable_get('superfish_itemcounter_' . $delta, 1),
  );
  $form['sf-advanced-css']['sf-helper-classes']['superfish_itemdepth_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add <strong>item depth</strong> class to menu items and their hyperlinks.') . '<em>(sf-depth-1, sf-depth-2, sf-depth-3, ...)</em>',
    '#default_value' => variable_get('superfish_itemdepth_' . $delta, 1),
  );
  $form['sf-advanced-css']['sf-custom-classes'] = array(
    '#type' => 'fieldset',
    '#title' => t('Custom classes'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-css']['sf-custom-classes']['superfish_ulclass_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('For the main UL'),
    '#description' => t('(Space separated, without dots)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': top-menu category-science',
    '#default_value' => variable_get('superfish_ulclass_' . $delta, ''),
    '#size' => 50,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-css']['sf-custom-classes']['superfish_liclass_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('For the list items'),
    '#description' => t('(Space separated, without dots)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': science-sub',
    '#default_value' => variable_get('superfish_liclass_' . $delta, ''),
    '#size' => 50,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-css']['sf-custom-classes']['superfish_hlclass_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('For the hyperlinks'),
    '#description' => t('(Space separated, without dots)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Example') . ': science-link',
    '#default_value' => variable_get('superfish_hlclass_' . $delta, ''),
    '#size' => 50,
    '#maxlength' => 1000,
  );
  $form['sf-advanced-css']['sf-extra-css'] = array(
    '#type' => 'fieldset',
    '#title' => t('Extra CSS'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-advanced-css']['sf-extra-css']['superfish_pathcss_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Path to CSS file(s)'),
    '#description' => t('Include extra CSS file(s). (Comma separated)') . ' <em>(' . t('Default') . ': ' . t('empty') . ')</em><br />' . t('Examples') . ': <ul><li>sites/all/files/example.css</li><li>sites/all/files/example.css,sites/all/files/example2.css</li></ul>',
    '#default_value' => variable_get('superfish_pathcss_' . $delta, ''),
    '#size' => 100,
    '#maxlength' => 1000,
  );
  return $form;
}

/**
 * Implements hook_block_save().
 */
function superfish_block_save($delta = 0, $edit = array()) {
  variable_set('superfish_name_' . $delta, $edit['superfish_name_' . $delta]);
  variable_set('superfish_menu_' . $delta, $edit['superfish_menu_' . $delta]);
  variable_set('superfish_depth_' . $delta, $edit['superfish_depth_' . $delta]);
  variable_set('superfish_type_' . $delta, $edit['superfish_type_' . $delta]);
  variable_set('superfish_style_' . $delta, $edit['superfish_style_' . $delta]);
  variable_set('superfish_speed_' . $delta, $edit['superfish_speed_' . $delta]);
  variable_set('superfish_delay_' . $delta, $edit['superfish_delay_' . $delta]);
  variable_set('superfish_pathclass_' . $delta, $edit['superfish_pathclass_' . $delta]);
  variable_set('superfish_pathlevels_' . $delta, $edit['superfish_pathlevels_' . $delta]);
  variable_set('superfish_slide_' . $delta, $edit['superfish_slide_' . $delta]);
  variable_set('superfish_shadow_' . $delta, $edit['superfish_shadow_' . $delta]);
  variable_set('superfish_arrow_' . $delta, $edit['superfish_arrow_' . $delta]);
  variable_set('superfish_expanded_' . $delta, $edit['superfish_expanded_' . $delta]);
  variable_set('superfish_bgf_' . $delta, $edit['superfish_bgf_' . $delta]);
  variable_set('superfish_spp_' . $delta, $edit['superfish_spp_' . $delta]);
  variable_set('superfish_hid_' . $delta, $edit['superfish_hid_' . $delta]);
  variable_set('superfish_touch_' . $delta, $edit['superfish_touch_' . $delta]);
  variable_set('superfish_touchbp_' . $delta, $edit['superfish_touchbp_' . $delta]);
  variable_set('superfish_touchua_' . $delta, $edit['superfish_touchua_' . $delta]);
  variable_set('superfish_touchual_' . $delta, $edit['superfish_touchual_' . $delta]);
  variable_set('superfish_touchuam_' . $delta, $edit['superfish_touchuam_' . $delta]);
  variable_set('superfish_small_' . $delta, $edit['superfish_small_' . $delta]);
  variable_set('superfish_smallbp_' . $delta, $edit['superfish_smallbp_' . $delta]);
  variable_set('superfish_smallua_' . $delta, $edit['superfish_smallua_' . $delta]);
  variable_set('superfish_smallual_' . $delta, $edit['superfish_smallual_' . $delta]);
  variable_set('superfish_smalluam_' . $delta, $edit['superfish_smalluam_' . $delta]);
  variable_set('superfish_smallset_' . $delta, $edit['superfish_smallset_' . $delta]);
  variable_set('superfish_smallasa_' . $delta, $edit['superfish_smallasa_' . $delta]);
  variable_set('superfish_smallcmc_' . $delta, $edit['superfish_smallcmc_' . $delta]);
  variable_set('superfish_smallecm_' . $delta, $edit['superfish_smallecm_' . $delta]);
  variable_set('superfish_smallchc_' . $delta, $edit['superfish_smallchc_' . $delta]);
  variable_set('superfish_smallech_' . $delta, $edit['superfish_smallech_' . $delta]);
  variable_set('superfish_smallicm_' . $delta, $edit['superfish_smallicm_' . $delta]);
  variable_set('superfish_smallich_' . $delta, $edit['superfish_smallich_' . $delta]);
  variable_set('superfish_supersubs_' . $delta, $edit['superfish_supersubs_' . $delta]);
  variable_set('superfish_minwidth_' . $delta, $edit['superfish_minwidth_' . $delta]);
  variable_set('superfish_maxwidth_' . $delta, $edit['superfish_maxwidth_' . $delta]);
  variable_set('superfish_multicolumn_' . $delta, $edit['superfish_multicolumn_' . $delta]);
  variable_set('superfish_mcexclude_' . $delta, $edit['superfish_mcexclude_' . $delta]);
  variable_set('superfish_mcdepth_' . $delta, $edit['superfish_mcdepth_' . $delta]);
  variable_set('superfish_mclevels_' . $delta, $edit['superfish_mclevels_' . $delta]);
  variable_set('superfish_firstlast_' . $delta, $edit['superfish_firstlast_' . $delta]);
  variable_set('superfish_zebra_' . $delta, $edit['superfish_zebra_' . $delta]);
  variable_set('superfish_dfirstlast_' . $delta, $edit['superfish_dfirstlast_' . $delta]);
  variable_set('superfish_dzebra_' . $delta, $edit['superfish_dzebra_' . $delta]);
  variable_set('superfish_itemcount_' . $delta, $edit['superfish_itemcount_' . $delta]);
  variable_set('superfish_itemcounter_' . $delta, $edit['superfish_itemcounter_' . $delta]);
  variable_set('superfish_itemdepth_' . $delta, $edit['superfish_itemdepth_' . $delta]);
  variable_set('superfish_use_link_theme_' . $delta, $edit['superfish_use_link_theme_' . $delta]);
  variable_set('superfish_use_item_theme_' . $delta, $edit['superfish_use_item_theme_' . $delta]);
  variable_set('superfish_hhldescription_' . $delta, $edit['superfish_hhldescription_' . $delta]);
  variable_set('superfish_hldescription_' . $delta, $edit['superfish_hldescription_' . $delta]);
  variable_set('superfish_hldmenus_' . $delta, $edit['superfish_hldmenus_' . $delta]);
  variable_set('superfish_hldexclude_' . $delta, $edit['superfish_hldexclude_' . $delta]);
  variable_set('superfish_wrapmul_' . $delta, $edit['superfish_wrapmul_' . $delta]);
  variable_set('superfish_wrapul_' . $delta, $edit['superfish_wrapul_' . $delta]);
  variable_set('superfish_wraphl_' . $delta, $edit['superfish_wraphl_' . $delta]);
  variable_set('superfish_wraphlt_' . $delta, $edit['superfish_wraphlt_' . $delta]);
  variable_set('superfish_ulclass_' . $delta, $edit['superfish_ulclass_' . $delta]);
  variable_set('superfish_liclass_' . $delta, $edit['superfish_liclass_' . $delta]);
  variable_set('superfish_hlclass_' . $delta, $edit['superfish_hlclass_' . $delta]);
  variable_set('superfish_pathcss_' . $delta, $edit['superfish_pathcss_' . $delta]);
  return;
}

/**
 * Implements hook_block_contents().
 */
function superfish_contents($delta = 0) {
  global $language;
  $block_css = $block_js = array();

  list($menu_name, $mlid) = explode(':', variable_get('superfish_menu_' . $delta, 'main-menu:0'));

  $sfsettings = $sfoptions = $sfplugins = array();
  $sfsettings['depth'] = variable_get('superfish_depth_' . $delta, '-1');
  $sfsettings['type'] = variable_get('superfish_type_' . $delta, 'horizontal');
  $sfsettings['style'] = variable_get('superfish_style_' . $delta, 'default');
  $sfsettings['expanded'] = variable_get('superfish_expanded_' . $delta, 0);
  $sfsettings['firstlast'] = variable_get('superfish_firstlast_' . $delta, 1);
  $sfsettings['zebra'] = variable_get('superfish_zebra_' . $delta, 1);
  $sfsettings['dfirstlast'] = variable_get('superfish_dfirstlast_' . $delta, 0);
  $sfsettings['dzebra'] = variable_get('superfish_dzebra_' . $delta, 0);
  $sfsettings['itemcount'] = variable_get('superfish_itemcount_' . $delta, 1);
  $sfsettings['itemcounter'] = variable_get('superfish_itemcounter_' . $delta, 1);
  $sfsettings['itemdepth'] = variable_get('superfish_itemdepth' . $delta, 1);
  $sfsettings['ulclass'] = variable_get('superfish_ulclass_' . $delta, '');
  $sfsettings['liclass'] = variable_get('superfish_liclass_' . $delta, '');
  $sfsettings['hlclass'] = variable_get('superfish_hlclass_' . $delta, '');
  $sfsettings['wrapmul'] = variable_get('superfish_wrapmul_' . $delta, '');
  $sfsettings['wrapul'] = variable_get('superfish_wrapul_' . $delta, '');
  $sfsettings['wraphl'] = variable_get('superfish_wraphl_' . $delta, '');
  $sfsettings['wraphlt'] = variable_get('superfish_wraphlt_' . $delta, '');
  $sfsettings['use_link_theme'] = variable_get('superfish_use_link_theme_' . $delta, 1);
  $sfsettings['use_item_theme'] = variable_get('superfish_use_item_theme_' . $delta, 1);
  $sfsettings['hidelinkdescription'] = variable_get('superfish_hhldescription_' . $delta, 0);
  $sfsettings['linkdescription'] = variable_get('superfish_hldescription_' . $delta, 0);
  $sfsettings['hldmenus'] = variable_get('superfish_hldmenus_' . $delta, '');
  $sfsettings['hldmenus'] = (strpos($sfsettings['hldmenus'], ',')) ? array_remove_empty(explode(',', $sfsettings['hldmenus'])) : $sfsettings['hldmenus'];
  $sfsettings['hldexclude'] = variable_get('superfish_hldexclude_' . $delta, '');
  $sfsettings['hldexclude'] = (strpos($sfsettings['hldexclude'], ',')) ? array_remove_empty(explode(',', $sfsettings['hldexclude'])) : $sfsettings['hldexclude'];
  $sfsettings['megamenu'] = variable_get('superfish_multicolumn_' . $delta, 0);
  $sfsettings['megamenu_depth'] = variable_get('superfish_mcdepth_' . $delta, 1);
  $sfsettings['megamenu_depth'] = ($sfsettings['type'] == 'navbar' && $sfsettings['megamenu_depth'] == 1) ? 2 : $sfsettings['megamenu_depth'];
  $sfsettings['megamenu_levels'] = variable_get('superfish_mclevels_' . $delta, 1) + $sfsettings['megamenu_depth'];
  $sfsettings['megamenu_exclude'] = variable_get('superfish_mcexclude_' . $delta, '');
  $sfsettings['megamenu_exclude'] = (strpos($sfsettings['megamenu_exclude'], ',')) ? array_remove_empty(explode(',', $sfsettings['megamenu_exclude'])) : $sfsettings['megamenu_exclude'];

  $sfoptions['pathClass'] = ($sfsettings['type'] == 'navbar') ? variable_get('superfish_pathclass_' . $delta, 'active-trail') : '';
  $sfoptions['pathLevels'] = (variable_get('superfish_pathlevels_' . $delta, 1) != 1) ? variable_get('superfish_pathlevels_' . $delta, 1) : '';
  $sfoptions['delay'] = (variable_get('superfish_delay_' . $delta, 800) != 800) ? variable_get('superfish_delay_' . $delta, 800) : '';
  $sfoptions['animation']['opacity'] = 'show';
  $slide = variable_get('superfish_slide_' . $delta, 'vertical');
  if (strpos($slide, '_') && superfish_library('javascript', 'jquery.easing.js', 'check')) {
    $slide = explode('_', $slide);
    switch ($slide[1]) {
      case 'vertical':
        $sfoptions['animation']['height'] = array('show', $slide[0]);
      break;
      case 'horizontal':
        $sfoptions['animation']['width'] = array('show', $slide[0]);
      break;
      case 'diagonal':
        $sfoptions['animation']['height'] = array('show', $slide[0]);
        $sfoptions['animation']['width'] = array('show', $slide[0]);
      break;
    }
    $block_js = array_merge($block_js, superfish_library('javascript', 'easing', 'add'));
  }
  else {
    switch ($slide) {
      case 'vertical':
        $sfoptions['animation']['height'] = 'show';
      break;
      case 'horizontal':
        $sfoptions['animation']['width'] = 'show';
      break;
      case 'diagonal':
        $sfoptions['animation']['height'] = 'show';
        $sfoptions['animation']['width'] = 'show';
      break;
    }
  }
  $speed = variable_get('superfish_speed_' . $delta, 'fast');
  $sfoptions['speed'] = ((is_numeric($speed)) ? (int)$speed : (($speed == ('slow' || 'normal' || 'fast')) ? '\'' . $speed . '\'': ''));
  $sfoptions['autoArrows'] = (variable_get('superfish_arrow_' . $delta, 1) == 1) ? TRUE : FALSE;
  $sfoptions['dropShadows'] = (variable_get('superfish_shadow_' . $delta, 1) == 1) ? TRUE : FALSE;
  if (variable_get('superfish_hid_' . $delta, 1) == 1 && superfish_library('javascript', 'jquery.hoverIntent.minified.js', 'check')) {
    $sfoptions['disableHI'] = FALSE;
    $block_js = array_merge($block_js, superfish_library('javascript', 'hoverIntent', 'add'));
  }
  else {
    $sfoptions['disableHI'] = FALSE;
  }
  $sfoptions = array_remove_empty($sfoptions);

  $touchscreen = variable_get('superfish_touch_' . $delta, 0);
  if ($touchscreen > 0  && superfish_library('javascript', 'sftouchscreen.js', 'check')) {
    $block_js = array_merge($block_js, superfish_library('javascript', 'sftouchscreen', 'add'));
    switch ($touchscreen) {
      case 1 :
        $sfplugins['touchscreen']['mode'] = 'always_active';
      break;
      case 2 :
        $sfplugins['touchscreen']['mode'] = 'window_width';
        $tsbp = variable_get('superfish_touchbp_' . $delta, 768);
        $sfplugins['touchscreen']['breakpoint'] = ($tsbp != 768) ? (int)$tsbp : '';
      break;
      case 3 :
        // Which method to use for UA detection.
        $tsuam = variable_get('superfish_touchuam_' . $delta, 0);
        $tsua = variable_get('superfish_touchua_' . $delta, 0);
        switch ($tsuam) {
          // Client-side.
          case 0 :
            switch ($tsua) {
              case 0 :
                $sfplugins['touchscreen']['mode'] = 'useragent_predefined';
              break;
              case 1 :
                $sfplugins['touchscreen']['mode'] = 'useragent_custom';
                $tsual = drupal_strtolower(variable_get('superfish_touchual_' . $delta, ''));
                if (strpos($tsual, '*')) {
                  $tsual = str_replace('*', '|', $tsual);
                }
                $sfplugins['touchscreen']['useragent'] = $tsual;
              break;
            }
          break;
          // Server-side.
          case 1 :
            if (isset($_SERVER['HTTP_USER_AGENT'])) {
              $hua = drupal_strtolower($_SERVER['HTTP_USER_AGENT']);
              switch ($tsua) {
                // Use the pre-defined list of mobile UA strings.
                case 0 :
                  if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $hua)) {
                    $sfplugins['touchscreen']['mode'] = 'always_active';
                  }
                break;
                // Use the custom list of UA strings.
                case 1 :
                  $tsual = drupal_strtolower(variable_get('superfish_touchual_' . $delta, ''));
                  $tsuac = array();
                  if (strpos($tsual, '*')) {
                    $tsual = explode('*', $tsual);
                    foreach ($tsual as $ua) {
                      $tsuac[] = (strpos($hua, $ua)) ? 1 : 0;
                    }
                  }
                  else {
                    $tsuac[] = (strpos($hua, $tsual)) ? 1 : 0;
                  }
                  if (in_array(1, $tsuac)) {
                    $sfplugins['touchscreen']['mode'] = 'always_active';
                  }
                break;
              }
            }
          break;
        }
      break;
    }
  }

  $smallscreen = variable_get('superfish_small_' . $delta, 2);
  if ($smallscreen > 0 && superfish_library('javascript', 'sfsmallscreen.js', 'check') == 1) {
    $block_js = array_merge($block_js, superfish_library('javascript', 'sfsmallscreen', 'add'));
    switch ($smallscreen) {
      case 1 :
        $sfplugins['smallscreen']['mode'] = 'always_active';
      break;
      case 2 :
        $sfplugins['smallscreen']['mode'] = 'window_width';
        $ssbp = variable_get('superfish_smallbp_' . $delta, 768);
        $sfplugins['smallscreen']['breakpoint'] = ($ssbp != 768) ? (int)$ssbp : '';
      break;
      case 3 :
        // Which method to use for UA detection.
        $ssuam = variable_get('superfish_smalluam_' . $delta, 0);
        $ssua = variable_get('superfish_smallua_' . $delta, 0);
        switch ($ssuam) {
          // Client-side.
          case 0 :
            switch ($ssua) {
              case 0 :
                $sfplugins['smallscreen']['mode'] = 'useragent_predefined';
              break;
              case 1 :
                $sfplugins['smallscreen']['mode'] = 'useragent_custom';
                $ssual = drupal_strtolower(variable_get('superfish_smallual_' . $delta, ''));
                if (strpos($ssual, '*')) {
                  $ssual = str_replace('*', '|', $ssual);
                }
                $sfplugins['smallscreen']['useragent'] = $ssual;
              break;
            }

          break;
          // Server-side.
          case 1 :
            if (isset($_SERVER['HTTP_USER_AGENT'])) {
              $hua = drupal_strtolower($_SERVER['HTTP_USER_AGENT']);
              switch ($ssua) {
                // Use the pre-defined list of mobile UA strings.
                case 0 :
                  if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $hua)) {
                    $sfplugins['smallscreen']['mode'] = 'always_active';
                  }
                break;
                // Use the custom list of UA strings.
                case 1 :
                  $ssual = drupal_strtolower(variable_get('superfish_smallual_' . $delta, ''));
                  $ssuac = array();
                  if (strpos($ssual, '*')) {
                    $ssual = explode('*', $ssual);
                    foreach ($ssual as $ua) {
                      $ssuac[] = (strpos($hua, $ua)) ? 1 : 0;
                    }
                  }
                  else {
                    $ssuac[] = (strpos($hua, $ssual)) ? 1 : 0;
                  }
                  if (in_array(1, $ssuac)) {
                    $sfplugins['smallscreen']['mode'] = 'always_active';
                  }
                break;
              }
            }
          break;
        }
      break;
    }
    $addselected = variable_get('superfish_smallasa_' . $delta, 0);
    $menuclasses = variable_get('superfish_smallcmc_' . $delta, 0);
    $hyperlinkclasses = variable_get('superfish_smallchc_' . $delta, 0);
    $excludeclass_menu = variable_get('superfish_smallecm_' . $delta, '');
    $excludeclass_hyperlink = variable_get('superfish_smallech_' . $delta, '');
    $includeclass_menu = variable_get('superfish_smallicm_' . $delta, '');
    $includeclass_hyperlink = variable_get('superfish_smallich_' . $delta, '');
    $sfplugins['smallscreen']['addSelected'] = ($addselected == 1) ? TRUE : FALSE;
    $sfplugins['smallscreen']['menuClasses'] = ($menuclasses == 1) ? TRUE : FALSE;
    $sfplugins['smallscreen']['hyperlinkClasses'] = ($hyperlinkclasses == 1) ? TRUE : FALSE;
    if ($menuclasses == 1 && !empty($excludeclass_menu)) {
      $sfplugins['smallscreen']['excludeClass_menu'] = $excludeclass_menu;
    }
    if ($hyperlinkclasses == 1 && !empty($excludeclass_hyperlink)) {
      $sfplugins['smallscreen']['excludeClass_hyperlink'] = $excludeclass_hyperlink;
    }
    if (!empty($includeclass_menu)) {
      $sfplugins['smallscreen']['includeClass_menu'] = $includeclass_menu;
    }
    if (!empty($includeclass_hyperlink)) {
      $sfplugins['smallscreen']['includeClass_hyperlink'] = $includeclass_hyperlink;
    }
  }

  if (variable_get('superfish_spp_' . $delta, 1) == 1 && superfish_library('javascript', 'supposition.js', 'check')) {
    $sfplugins['supposition'] = TRUE;
    $block_js = array_merge($block_js, superfish_library('javascript', 'supposition', 'add'));
  }
  else {
    $sfplugins['supposition'] = FALSE;
  }

  if (variable_get('superfish_bgf_' . $delta, 0) == 1 && superfish_library('javascript', 'jquery.bgiframe.min.js', 'check')) {
    $sfplugins['bgiframe'] = TRUE;
    $block_js = array_merge($block_js, superfish_library('javascript', 'bgiframe', 'add'));
  }
  else {
    $sfplugins['bgiframe'] = FALSE;
  }

  if (variable_get('superfish_supersubs_' . $delta, 1) == 1 && superfish_library('javascript', 'supersubs.js', 'check')) {
    $sfplugins['supersubs']['minWidth'] = variable_get('superfish_minwidth_' . $delta, '12');
    $sfplugins['supersubs']['maxWidth'] = variable_get('superfish_maxwidth_' . $delta, '27');
    $sfplugins['supersubs']['extraWidth'] = 1;
    $block_js = array_merge($block_js, superfish_library('javascript', 'supersubs', 'add'));
  }

  $vars = array(
    'id' => $delta,
    'menu_name' => $menu_name,
    'mlid' => $mlid,
    'sfsettings' => $sfsettings
  );
  if ($output = theme('superfish', $vars)) {
    if (!empty($output['content'])) {
      $output['content'] = array(
        '#type' => 'markup',
        '#markup' => filter_xss($output['content'], $allowed_tags = array('a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'map', 'mark', 'meter', 'nav', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'ul', 'var', 'video', 'wbr')),
        '#contextual_links' => array(
          'superfish' => array('admin/structure/menu/manage', array($menu_name)),
        )
      );

      // Creating a title for the <select> title.
      if ($smallscreen > 0 && superfish_library('javascript', 'sfsmallscreen.js', 'check')) {
        $smallset = variable_get('superfish_smallset_' . $delta, '');
        if (empty($smallset)) {
          $sfplugins['smallscreen']['title'] = $output['subject'];
        }
        else {
          $sfplugins['smallscreen']['title'] = $smallset;
        }
      }
      $sfplugins = array_remove_empty($sfplugins);

      // Prepare the JavaScript settings.
      $javascript['superfish'][$delta]['id'] = $delta;
      $javascript['superfish'][$delta]['sf'] = isset($sfoptions) ? $sfoptions : array();
      if (!empty($sfplugins)) {
        $javascript['superfish'][$delta]['plugins'] = $sfplugins;
      }
      // Adding required Javascript.
      if (superfish_library('javascript', 'superfish.js', 'check')) {
        $block_js = array_merge($block_js, superfish_library('javascript', 'superfish.js', 'add'));
        if (superfish_library('javascript', 'drupal_behavior', 'check')) {
          $block_js = array_merge($block_js, array(array('data' => $javascript, 'type' => 'setting')));
          $block_js = array_merge($block_js, superfish_library('javascript', 'drupal_behavior', 'add'));
        }
      }

      // Adding required CSS files
      if (superfish_library('CSS', 'superfish', 'check')) {
        $block_css = array_merge($block_css, superfish_library('CSS', 'superfish', 'add'));
      }
      if (superfish_library('CSS', $sfsettings['type'], 'check')) {
        $block_css = array_merge($block_css, superfish_library('CSS', $sfsettings['type'], 'add'));
      }
      if ($sfsettings['style'] != 'none' && superfish_styles('path', $sfsettings['style']) != '') {
        $block_css = array_merge($block_css, array(superfish_styles('path', $sfsettings['style']) => array('type' => 'file', 'weight' => 500)));
      }
      $extracss = variable_get('superfish_pathcss_' . $delta, '');
      if ($extracss) {
        if (strpos($extracss, ',')) {
          $extracss = explode(',', $extracss);
          foreach ($extracss as $c) {
            $block_css = array_merge($block_css, array($c => array('type' => 'file', 'weight' => 510)));
          }
        }
        else {
          $block_css = array_merge($block_css, array($extracss => array('type' => 'file', 'weight' => 510)));
        }
      }
      $output['content']['#attached'] = array(
        'css' => $block_css,
        'js' => $block_js,
      );
    }
  }
  return $output;
}

/**
 * Implements hook_block_view().
 */
function superfish_block_view($delta = 0) {
  $block = superfish_contents($delta);
  return $block;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function superfish_form_block_admin_configure_alter(&$form, $form_state) {
  $form['#validate'][] = 'superfish_block_validate';
}

/**
 * Validation function for the block configuration form.
 */
function superfish_block_validate($form, &$form_state) {
  if ($form_state['values']['module'] == 'superfish') {
    $supersubs_error = FALSE;
    $delta = $form_state['values']['delta'];
    $style = $form_state['values']['superfish_style_' . $delta];
    $speed = $form_state['values']['superfish_speed_' . $delta];
    $delay = $form_state['values']['superfish_delay_' . $delta];
    $pathclass = $form_state['values']['superfish_pathclass_' . $delta];
    $touch = $form_state['values']['superfish_touch_' . $delta];
    $touchbp = $form_state['values']['superfish_touchbp_' . $delta];
    $touchua = $form_state['values']['superfish_touchua_' . $delta];
    $touchual = $form_state['values']['superfish_touchual_' . $delta];
    $small = $form_state['values']['superfish_small_' . $delta];
    $smallbp = $form_state['values']['superfish_smallbp_' . $delta];
    $smallua = $form_state['values']['superfish_smallua_' . $delta];
    $smallual = $form_state['values']['superfish_smallual_' . $delta];
    $minwidth = $form_state['values']['superfish_minwidth_' . $delta];
    $maxwidth = $form_state['values']['superfish_maxwidth_' . $delta];
    $mcexclude = $form_state['values']['superfish_mcexclude_' . $delta];
    $hldmenus = $form_state['values']['superfish_hldmenus_' . $delta];
    $hldexclude = $form_state['values']['superfish_hldexclude_' . $delta];
    $extracss = $form_state['values']['superfish_pathcss_' . $delta];

    if ($style != 'none' && superfish_styles('path', $style) == '') {
      form_set_error('superfish_style_' . $delta, t('Cannot find the CSS file of the selected style.'));
    }
    elseif (!is_numeric($speed) && !in_array($speed, array('slow', 'normal', 'fast'))) {
      form_set_error('superfish_speed_' . $delta, t('<strong>Animation speed</strong>: unacceptable value entered.'));
    }
    if (!is_numeric($delay)) {
      form_set_error('superfish_delay_' . $delta, t('<strong>Mouse delay</strong>: unacceptable value entered.'));
    }
    if (is_numeric($pathclass)) {
      form_set_error('superfish_pathclass_' . $delta, t('<strong>Path class</strong>: unacceptable value entered.'));
    }
    if ($touch == 2 && $touchbp == '') {
      form_set_error('superfish_touchbp_' . $delta, t('<strong>sf-Touchscreen Breakpoint</strong>: field cannot be empty.'));
    }
    if (!is_numeric($touchbp)) {
      form_set_error('superfish_touchbp_' . $delta, t('<strong>sf-Touchscreen Breakpoint</strong>: unacceptable value entered.'));
    }
    if ($touch == 3 && $touchua == 1 && $touchual == '') {
      form_set_error('superfish_touchual_' . $delta, t('<strong>sf-Touchscreen Custom list of user agents</strong>: field cannot be empty.'));
    }
    if ($small == 2 && $smallbp == '') {
      form_set_error('superfish_smallbp_' . $delta, t('<strong>sf-Smallscreen Breakpoint</strong>: field cannot be empty.'));
    }
    if (!is_numeric($smallbp)) {
      form_set_error('superfish_smallbp_' . $delta, t('<strong>sf-Smallscreen Breakpoint</strong>: unacceptable value entered.'));
    }
    if ($small == 3 && $smallua == 1 && $smallual == '') {
      form_set_error('superfish_smallual_' . $delta, t('<strong>sf-Smallscreen Custom list of user agents</strong>: field cannot be empty.'));
    }
    if (!is_numeric($minwidth)) {
      form_set_error('superfish_minwidth_' . $delta, t('<strong>Supersubs minimum width</strong>: unacceptable value entered.'));
      $supersubs_error = TRUE;
    }
    if (!is_numeric($maxwidth)) {
      form_set_error('superfish_maxwidth_' . $delta, t('<strong>Supersubs maximum width</strong>: unacceptable value entered.'));
      $supersubs_error = TRUE;
    }
    if ($supersubs_error !== TRUE && $minwidth > $maxwidth) {
      form_set_error('superfish_maxwidth_' . $delta, t('Supersubs <strong>maximum width</strong> has to be bigger than the <strong>minimum width</strong>.'));
    }
    if (!empty($mcexclude) && (!is_numeric(str_replace(',', '', $mcexclude)) || strpos($mcexclude, ' .'))) {
      form_set_error('superfish_mcexclude_' . $delta, t('<strong>Multi-column subs-menus</strong>: unacceptable value entered.'));
    }
    if (!empty($hldmenus) && (!is_numeric(str_replace(',', '', $hldmenus)) || strpos($hldmenus, ' .'))) {
      form_set_error('superfish_hldmenus_' . $delta, t('<strong>Hyperlinks</strong>: unacceptable value entered.'));
    }
    if (!empty($hldexclude) && (!is_numeric(str_replace(',', '', $hldexclude)) || strpos($hldexclude, ' .'))) {
      form_set_error('superfish_hldexclude_' . $delta, t('<strong>Hyperlinks</strong>: unacceptable value entered.'));
    }
    if (!empty($extracss)) {
      if (strpos($extracss, ',')) {
        $error = array();
        $extracss = array_remove_empty(explode(',', $extracss));
        foreach ($extracss as $c) {
          if (!file_exists($c)) {
            $error[] = $c;
          }
        }
        if (!empty($error)) {
          form_set_error('superfish_pathcss_' . $delta, t('Cannot find the CSS file mentioned in <strong>Extra CSS</strong>'));
        }
      }
      elseif (!file_exists($extracss)) {
        form_set_error('superfish_pathcss_' . $delta, t('Cannot find the CSS file mentioned in <strong>Extra CSS</strong>'));
      }
    }
  }
}

/**
 * Get a list of CSS files that can be used for styles.
 */
function superfish_styles($display = 'list', $style = NULL) {
  $output = '';
  // Ensure the Libraries API module is installed and working.
  if (module_exists('libraries') && function_exists('libraries_get_path')) {
    $directory = libraries_get_path('superfish') . '/style';
  }
  // Otherwise use the default directory.
  else {
    $directory = 'sites/all/libraries/superfish/style';
  }
  $files = (file_exists($directory)) ? file_scan_directory($directory, '/.*\.css$/', array('key' => 'name')) : '';
  if ($display == 'list') {
    $output = array('none' => '- ' . t('None') . ' -');
    if (is_array($files)) {
      foreach ($files as $file) {
        $output[$file->name] = drupal_ucfirst($file->name);
      }
    }
    natcasesort($output);
  }
  if ($display == 'path' && $style) {
    if (isset($files[$style])) {
      $output = $files[$style]->uri;
    }
    else {
      watchdog('page not found', 'Required files for the Superfish \'%style\' style cannot be found.', array('%style' => $style), WATCHDOG_WARNING);
      $output = '';
    }
  }
  return $output;
}

/**
 * Generate a list of available slide-in effects.
 */
function superfish_effects() {
  $output = array(
    'none' => '- ' . t('None') . ' -',
    'vertical' => t('Vertical'),
    'horizontal' => t('Horizontal'),
    'diagonal' => t('Diagonal'));
  // Ensure the Libraries API module is installed and working.
  if (module_exists('libraries') && function_exists('libraries_get_path') && libraries_get_path('easing') != '') {
    $file = libraries_get_path('easing') . '/jquery.easing.js';
  }
  // Otherwise look for the file in the default location.
  else {
    $file = 'sites/all/libraries/easing/jquery.easing.js';
  }
  if (file_exists($file)) {
    $easing_types = array(
      'easeInSine_vertical' => 'easeInSine (' . t('Vertical') . ')',
      'easeInSine_horizontal' => 'easeInSine (' . t('Horizontal') . ')',
      'easeInSine_diagonal' => 'easeInSine (' . t('Diagonal') . ')',
      'easeInQuint_vertical' => 'easeInQuint (' . t('Vertical') . ')',
      'easeInQuint_horizontal' => 'easeInQuint (' . t('Horizontal') . ')',
      'easeInQuint_diagonal' => 'easeInQuint (' . t('Diagonal') . ')',
      'easeInQuart_vertical' => 'easeInQuart (' . t('Vertical') . ')',
      'easeInQuart_horizontal' => 'easeInQuart (' . t('Horizontal') . ')',
      'easeInQuart_diagonal' => 'easeInQuart (' . t('Diagonal') . ')',
      'easeInQuad_vertical' => 'easeInQuad (' . t('Vertical') . ')',
      'easeInQuad_horizontal' => 'easeInQuad (' . t('Horizontal') . ')',
      'easeInQuad_diagonal' => 'easeInQuad (' . t('Diagonal') . ')',
      'easeInExpo_vertical' => 'easeInExpo (' . t('Vertical') . ')',
      'easeInExpo_horizontal' => 'easeInExpo (' . t('Horizontal') . ')',
      'easeInExpo_diagonal' => 'easeInExpo (' . t('Diagonal') . ')',
      'easeInElastic_vertical' => 'easeInElastic (' . t('Vertical') . ')',
      'easeInElastic_horizontal' => 'easeInElastic (' . t('Horizontal') . ')',
      'easeInElastic_diagonal' => 'easeInElastic (' . t('Diagonal') . ')',
      'easeInCubic_vertical' => 'easeInCubic (' . t('Vertical') . ')',
      'easeInCubic_horizontal' => 'easeInCubic (' . t('Horizontal') . ')',
      'easeInCubic_diagonal' => 'easeInCubic (' . t('Diagonal') . ')',
      'easeInCirc_vertical' => 'easeInCirc (' . t('Vertical') . ')',
      'easeInCirc_horizontal' => 'easeInCirc (' . t('Horizontal') . ')',
      'easeInCirc_diagonal' => 'easeInCirc (' . t('Diagonal') . ')',
      'easeInBounce_vertical' => 'easeInBounce (' . t('Vertical') . ')',
      'easeInBounce_horizontal' => 'easeInBounce (' . t('Horizontal') . ')',
      'easeInBounce_diagonal' => 'easeInBounce (' . t('Diagonal') . ')',
      'easeInBack_vertical' => 'easeInBack (' . t('Vertical') . ')',
      'easeInBack_horizontal' => 'easeInBack (' . t('Horizontal') . ')',
      'easeInBack_diagonal' => 'easeInBack (' . t('Diagonal') . ')',
      'easeOutQuint_vertical' => 'easeOutQuint (' . t('Vertical') . ')',
      'easeOutQuint_horizontal' => 'easeOutQuint (' . t('Horizontal') . ')',
      'easeOutQuint_diagonal' => 'easeOutQuint (' . t('Diagonal') . ')',
      'easeOutQuart_vertical' => 'easeOutQuart (' . t('Vertical') . ')',
      'easeOutQuart_horizontal' => 'easeOutQuart (' . t('Horizontal') . ')',
      'easeOutQuart_diagonal' => 'easeOutQuart (' . t('Diagonal') . ')',
      'easeOutQuad_vertical' => 'easeOutQuad (' . t('Vertical') . ')',
      'easeOutQuad_horizontal' => 'easeOutQuad (' . t('Horizontal') . ')',
      'easeOutQuad_diagonal' => 'easeOutQuad (' . t('Diagonal') . ')',
      'easeOutExpo_vertical' => 'easeOutExpo (' . t('Vertical') . ')',
      'easeOutExpo_horizontal' => 'easeOutExpo (' . t('Horizontal') . ')',
      'easeOutExpo_diagonal' => 'easeOutExpo (' . t('Diagonal') . ')',
      'easeOutElastic_vertical' => 'easeOutElastic (' . t('Vertical') . ')',
      'easeOutElastic_horizontal' => 'easeOutElastic (' . t('Horizontal') . ')',
      'easeOutElastic_diagonal' => 'easeOutElastic (' . t('Diagonal') . ')',
      'easeOutCubic_vertical' => 'easeOutCubic (' . t('Vertical') . ')',
      'easeOutCubic_horizontal' => 'easeOutCubic (' . t('Horizontal') . ')',
      'easeOutCubic_diagonal' => 'easeOutCubic (' . t('Diagonal') . ')',
      'easeOutCirc_vertical' => 'easeOutCirc (' . t('Vertical') . ')',
      'easeOutCirc_horizontal' => 'easeOutCirc (' . t('Horizontal') . ')',
      'easeOutCirc_diagonal' => 'easeOutCirc (' . t('Diagonal') . ')',
      'easeOutBounce_vertical' => 'easeOutBounce (' . t('Vertical') . ')',
      'easeOutBounce_horizontal' => 'easeOutBounce (' . t('Horizontal') . ')',
      'easeOutBounce_diagonal' => 'easeOutBounce (' . t('Diagonal') . ')',
      'easeOutBack_vertical' => 'easeOutBack (' . t('Vertical') . ')',
      'easeOutBack_horizontal' => 'easeOutBack (' . t('Horizontal') . ')',
      'easeOutBack_diagonal' => 'easeOutBack (' . t('Diagonal') . ')',
      'easeInOutQuint_vertical' => 'easeInOutQuint (' . t('Vertical') . ')',
      'easeInOutQuint_horizontal' => 'easeInOutQuint (' . t('Horizontal') . ')',
      'easeInOutQuint_diagonal' => 'easeInOutQuint (' . t('Diagonal') . ')',
      'easeInOutQuart_vertical' => 'easeInOutQuart (' . t('Vertical') . ')',
      'easeInOutQuart_horizontal' => 'easeInOutQuart (' . t('Horizontal') . ')',
      'easeInOutQuart_diagonal' => 'easeInOutQuart (' . t('Diagonal') . ')',
      'easeInOutQuad_vertical' => 'easeInOutQuad (' . t('Vertical') . ')',
      'easeInOutQuad_horizontal' => 'easeInOutQuad (' . t('Horizontal') . ')',
      'easeInOutQuad_diagonal' => 'easeInOutQuad (' . t('Diagonal') . ')',
      'easeInOutExpo_vertical' => 'easeInOutExpo (' . t('Vertical') . ')',
      'easeInOutExpo_horizontal' => 'easeInOutExpo (' . t('Horizontal') . ')',
      'easeInOutExpo_diagonal' => 'easeInOutExpo (' . t('Diagonal') . ')',
      'easeInOutElastic_vertical' => 'easeInOutElastic (' . t('Vertical') . ')',
      'easeInOutElastic_horizontal' => 'easeInOutElastic (' . t('Horizontal') . ')',
      'easeInOutElastic_diagonal' => 'easeInOutElastic (' . t('Diagonal') . ')',
      'easeInOutCubic_vertical' => 'easeInOutCubic (' . t('Vertical') . ')',
      'easeInOutCubic_horizontal' => 'easeInOutCubic (' . t('Horizontal') . ')',
      'easeInOutCubic_diagonal' => 'easeInOutCubic (' . t('Diagonal') . ')',
      'easeInOutCirc_vertical' => 'easeInOutCirc (' . t('Vertical') . ')',
      'easeInOutCirc_horizontal' => 'easeInOutCirc (' . t('Horizontal') . ')',
      'easeInOutCirc_diagonal' => 'easeInOutCirc (' . t('Diagonal') . ')',
      'easeInOutBounce_vertical' => 'easeInOutBounce (' . t('Vertical') . ')',
      'easeInOutBounce_horizontal' => 'easeInOutBounce (' . t('Horizontal') . ')',
      'easeInOutBounce_diagonal' => 'easeInOutBounce (' . t('Diagonal') . ')',
      'easeInOutBack_vertical' => 'easeInOutBack (' . t('Vertical') . ')',
      'easeInOutBack_horizontal' => 'easeInOutBack (' . t('Horizontal') . ')',
      'easeInOutBack_diagonal' => 'easeInOutBack (' . t('Diagonal') . ')');
    $output = array_merge($output, $easing_types);
  }
  return $output;
}

/**
 * Add require JavaScript and CSS files from the Superfish library.
 */
function superfish_library($type = NULL, $name = NULL, $action = 'add') {
  // Ensure the Libraries API module is installed and working and is able to find the library.
  if (module_exists('libraries') && function_exists('libraries_get_path') && libraries_get_path('superfish') != '') {
    $directory = libraries_get_path('superfish');
    $directory_easing = libraries_get_path('easing');
  }
  // Otherwise use the default directory.
  else {
    $directory = 'sites/all/libraries/superfish';
    $directory_easing = 'sites/all/libraries/easing';
  }
  $slp_default = $directory . "/jquery.hoverIntent.minified.js\n" .
    $directory . "/jquery.bgiframe.min.js\n" .
    $directory . "/superfish.js\n" .
    $directory . "/supersubs.js\n" .
    $directory . "/supposition.js\n" .
    $directory . "/sftouchscreen.js\n" .
    $directory . "/sfsmallscreen.js";

  $sf_library = variable_get('superfish_slp', $slp_default);
  $sf_library = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", trim($sf_library));
  $sf_library = explode("\n", $sf_library);

  if ($action == 'check') {
    switch ($type) {
      case  'javascript':
        switch ($name) {
          case 'drupal_behavior':
            $name = 'superfish.js';
            $sf_library = array(drupal_get_path('module', 'superfish') . '/' . $name);
          break;
          case 'jquery.easing.js':
            $name = 'jquery.easing.js';
            $sf_library = array($directory_easing . '/' . $name);
          break;
        }
        foreach ($sf_library as $s) {
          if (strpos($s, $name) !== FALSE) {
            if (file_exists($s)) {
              return TRUE;
            }
            else {
              $file = $directory . (($type == 'CSS') ? '/css' : '') . '/' . $name;
              watchdog('page not found', '%file', array('%file' => $file), WATCHDOG_ERROR);
              return FALSE;
            }
          }
        }
      break;
      case 'CSS':
        $directory .= '/css';
        switch ($name) {
          case 'superfish':
          case 'horizontal':
            if (file_exists($directory . '/superfish.css')) {
              return TRUE;
            }
            else {
              watchdog('page not found', '%directory/superfish.css', array('%directory' => $directory), WATCHDOG_WARNING);
              return FALSE;
            }
          break;
          case 'navbar':
          case 'vertical':
            if (file_exists($directory . '/superfish-' . $name . '.css')) {
              return TRUE;
            }
            else {
              watchdog('page not found', '%directory/superfish-%name.css', array('%directory' => $directory, '%name' => $name), WATCHDOG_WARNING);
              return FALSE;
            }
          break;
        }
      break;
    }
  }
  if ($action == 'add') {
    switch ($type) {
      case 'javascript':
        switch ($name) {
          case 'easing':
            $output = array($directory_easing . '/jquery.easing.js' => array('type' => 'file', 'weight' => 490));
            return $output;
          break;
          case 'drupal_behavior':
            $output = array(drupal_get_path('module', 'superfish') . '/superfish.js' => array('type' => 'file', 'weight' => 495));
            return $output;
          break;
          default:
            if (file_exists($directory . '/superfish.js')) {
              foreach ($sf_library as $s) {
                if (strpos($s, $name) !== FALSE) {
                  switch ($name) {
                    case 'superfish':
                      $weight = 480;
                    break;
                    case 'supersubs':
                      $weight = 490;
                    break;
                    default:
                      $weight = 470;
                    break;  
                  }
                  $output = array($s => array('type' => 'file', 'weight' => $weight));
                  return $output;
                }
              }
              // If the required file did not exist in the library files list.
              if (empty($output)) {
                watchdog('page not found', '%name cannot be found.', array('%name' => $name), WATCHDOG_WARNING);
              }
            }
            else {
              watchdog('page not found', '%directory/superfish.js', array('%directory' => $directory), WATCHDOG_ERROR);
            }
          break;
        }
      break;
      case 'CSS':
        $directory .= '/css';
        switch ($name) {
          case 'superfish':
          case 'horizontal':
            $output = array($directory . '/superfish.css' => array('type' => 'file', 'weight' => 480));
            return $output;
          break;
          case 'navbar':
          case 'vertical':
            $output = array($directory . '/superfish-' . $name . '.css' => array('type' => 'file', 'weight' => 490));
            return $output;
          break;
        }
      break;
    }
  }
}

/**
 * Helper function to clean up arrays.
 */
function array_remove_empty($haystack) {
  foreach ($haystack as $key => $value) {
    if (is_array($value)) {
      $haystack[$key] = array_remove_empty($haystack[$key]);
    }
    elseif (empty($value) && is_bool($value) !== TRUE) {
      if ($haystack[$key] != '0') {
        unset($haystack[$key]);
      }
    }
  }
  return $haystack;
}

/**
 * Implements hook_theme().
 */
function superfish_theme() {
  return array(
    'superfish' => array(
      'variables' => array(
        'id' => NULL,
        'menu_name' => NULL,
        'mlid' => NULL,
        'sfsettings' => NULL
      ),
    ),
    'superfish_build' => array(
      'variables' => array(
        'id' => NULL,
        'menu' => NULL,
        'depth' => -1,
        'trail' => NULL,
        'sfsettings' => NULL
      ),
    ),
    'superfish_menu_item' => array(
      'variables' => array(
        'element' => NULL,
        'properties' => NULL,
      ),
    ),
    'superfish_menu_item_link' => array(
      'variables' => array(
        'menu_item' => NULL,
        'link_options' => NULL,
      ),
    ),
  );
}

/**
 * Builds the active trail from the page's menu data.
 */
function superfish_build_page_trail($page_menu) {
  $trail = array();
  foreach ($page_menu as $item) {
    if ($item['link']['in_active_trail'] || ($item['link']['href'] == '<front>' && drupal_is_front_page())) {
      $trail[] = $item['link']['mlid'];
    }
    if ($item['below']) {
      $trail = array_merge($trail, superfish_build_page_trail($item['below']));
    }
  }
  // Allows other modules to alter the active trail.
  drupal_alter('superfish_active_trail', $trail);
  return $trail;
}

/**
 * Theme function to allow any menu tree to be themed as a Superfish menu.
 */
function theme_superfish($variables) {
  global $user, $language;

  $id = $variables['id'];
  $menu_name = $variables['menu_name'];
  $mlid = $variables['mlid'];
  $sfsettings = $variables['sfsettings'];

  $menu = menu_tree_all_data($menu_name);

  if (function_exists('i18n_menu_localize_tree')) {
    $menu = i18n_menu_localize_tree($menu);
  }

  // For custom $menus and menus built all the way from the top-level we
  // don't need to "create" the specific sub-menu and we need to get the title
  // from the $menu_name since there is no "parent item" array.
  // Create the specific menu if we have a mlid.
  if (!empty($mlid)) {
    // Load the parent menu item.
    $item = menu_link_load($mlid);
    $title = check_plain($item['title']);
    $parent_depth = $item['depth'];
    // Narrow down the full menu to the specific sub-tree we need.
    for ($p = 1; $p < 10; $p++) {
      if ($sub_mlid = $item["p$p"]) {
        $subitem = menu_link_load($sub_mlid);
        $key = (50000 + $subitem['weight']) . ' ' . $subitem['title'] . ' ' . $subitem['mlid'];
        $menu = (isset($menu[$key]['below'])) ? $menu[$key]['below'] : $menu;
      }
    }
  }
  else {
    $result = db_query("SELECT title FROM {menu_custom} WHERE menu_name = :a", array(':a' => $menu_name))->fetchField();
    $title = check_plain($result);
  }

  $output['content'] = '';
  $output['subject'] = $title;
  if ($menu) {
    // Set the total menu depth counting from this parent if we need it.
    $depth = $sfsettings['depth'];
    $depth = ($sfsettings['depth'] > 0 && isset($parent_depth)) ? $parent_depth + $depth : $depth;

    $var = array(
      'id' => $id,
      'menu' => $menu,
      'depth' => $depth,
      'trail' => superfish_build_page_trail(menu_tree_page_data($menu_name)),
      'sfsettings' => $sfsettings
    );
    if ($menu_tree = theme('superfish_build', $var)) {
      if ($menu_tree['content']) {
        // Add custom HTML codes around the main menu.
        if ($sfsettings['wrapmul'] && strpos($sfsettings['wrapmul'], ',') !== FALSE) {
          $wmul = explode(',', $sfsettings['wrapmul']);
          // In case you just wanted to add something after the element.
          if (drupal_substr($sfsettings['wrapmul'], 0) == ',') {
            array_unshift($wmul, '');
          }
        }
        else {
          $wmul = array();
        }
        $output['content'] = isset($wmul[0]) ? $wmul[0] : '';
        $output['content'] .= '<ul id="superfish-' . $id . '"';
        $output['content'] .= ' class="menu sf-menu sf-' . $menu_name . ' sf-' . $sfsettings['type'] . ' sf-style-' . $sfsettings['style'];
        $output['content'] .= ($sfsettings['itemcounter']) ? ' sf-total-items-' . $menu_tree['total_children'] : '';
        $output['content'] .= ($sfsettings['itemcounter']) ? ' sf-parent-items-' . $menu_tree['parent_children'] : '';
        $output['content'] .= ($sfsettings['itemcounter']) ? ' sf-single-items-' . $menu_tree['single_children'] : '';
        $output['content'] .= ($sfsettings['ulclass']) ? ' ' . $sfsettings['ulclass'] : '';
        $output['content'] .= ($language->direction == 1) ? ' rtl' : '';
        $output['content'] .= '">' . $menu_tree['content'] . '</ul>';
        $output['content'] .= isset($wmul[1]) ? $wmul[1] : '';
      }
    }
  }
  return $output;
}

/**
 * Helper function that builds the nested lists of a Superfish menu.
 */
function theme_superfish_build($variables) {
  $output = array('content' => '');
  $id = $variables['id'];
  $menu = $variables['menu'];
  $depth = $variables['depth'];
  $trail = $variables['trail'];
  // Keep $sfsettings untouched as we need to pass it to the child menus.
  $settings = $sfsettings = $variables['sfsettings'];
  $megamenu = $megamenu_below = $settings['megamenu'];
  $total_children = $parent_children = $single_children = 0;
  $i = 1;

  // Reckon the total number of available menu items.
  foreach ($menu as $menu_item) {
    if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
      $total_children++;
    }
  }

  foreach ($menu as $menu_item) {

    $show_children = $megamenu_wrapper = $megamenu_column = $megamenu_content = FALSE;
    $item_class = $link_options = $link_class = array();
    $mlid = $menu_item['link']['mlid'];

    if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
      $item_class[] = ($trail && in_array($mlid, $trail)) ? 'active-trail' : '';

      // Add helper classes to the menu items and hyperlinks.
      $settings['firstlast'] = ($settings['dfirstlast'] == 1 && $total_children == 1) ? 0 : $settings['firstlast'];
      $item_class[] = ($settings['firstlast'] == 1) ? (($i == 1 && $i == $total_children) ? 'firstandlast' : (($i == 1) ? 'first' : (($i == $total_children) ? 'last' : 'middle'))) : '';
      $settings['zebra'] = ($settings['dzebra'] == 1 && $total_children == 1) ? 0 : $settings['zebra'];
      $item_class[] = ($settings['zebra'] == 1) ? (($i % 2) ? 'odd' : 'even') : '';
      $item_class[] = ($settings['itemcount'] == 1) ? 'sf-item-' . $i : '';
      $item_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
      $link_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
      $item_class[] = ($settings['liclass']) ? $settings['liclass'] : '';
      if (strpos($settings['hlclass'], ' ')) {
        $l = explode(' ', $settings['hlclass']);
        foreach ($l as $c) {
          $link_class[] = $c;
        }
      }
      else {
        $link_class[] = $settings['hlclass'];
      }
      $i++;

      // Hide hyperlink descriptions ("title" attribute).
      if ($settings['hidelinkdescription'] == 1) {
        unset($menu_item['link']['localized_options']['attributes']['title']);
      }

      // Insert hyperlink description ("title" attribute) into the text.
      $show_linkdescription = ($settings['linkdescription'] == 1 && !empty($menu_item['link']['localized_options']['attributes']['title'])) ? TRUE : FALSE;
      if ($show_linkdescription) {
        if (!empty($settings['hldmenus'])) {
          $show_linkdescription = (is_array($settings['hldmenus'])) ? ((in_array($mlid, $settings['hldmenus'])) ? TRUE : FALSE) : (($mlid == $settings['hldmenus']) ? TRUE : FALSE);
        }
        if (!empty($settings['hldexclude'])) {
          $show_linkdescription = (is_array($settings['hldexclude'])) ? ((in_array($mlid, $settings['hldexclude'])) ? FALSE : $show_linkdescription) : (($settings['hldexclude'] == $mlid) ? FALSE : $show_linkdescription);
        }
        if ($show_linkdescription) {
          $menu_item['link']['title'] .= ' <span class="sf-description">';
          $menu_item['link']['title'] .= (!empty($menu_item['link']['localized_options']['attributes']['title'])) ? $menu_item['link']['localized_options']['attributes']['title'] : array();
          $menu_item['link']['title'] .= '</span>';
          $link_options['html'] = TRUE;
        }
      }

      // Add custom HTML codes around the menu items.
      if ($sfsettings['wrapul'] && strpos($sfsettings['wrapul'], ',') !== FALSE) {
        $wul = explode(',', $sfsettings['wrapul']);
        // In case you just wanted to add something after the element.
        if (drupal_substr($sfsettings['wrapul'], 0) == ',') {
          array_unshift($wul, '');
        }
      }
      else {
        $wul = array();
      }

      // Add custom HTML codes around the hyperlinks.
      if ($settings['wraphl'] && strpos($settings['wraphl'], ',') !== FALSE) {
        $whl = explode(',', $settings['wraphl']);
        // The same as above
        if (drupal_substr($settings['wraphl'], 0) == ',') {
          array_unshift($whl, '');
        }
      }
      else {
        $whl = array();
      }

      // Add custom HTML codes around the hyperlinks text.
      if ($settings['wraphlt'] && strpos($settings['wraphlt'], ',') !== FALSE) {
        $whlt = explode(',', $settings['wraphlt']);
        // The same as above
        if (drupal_substr($settings['wraphlt'], 0) == ',') {
          array_unshift($whlt, '');
        }
        $menu_item['link']['title'] = $whlt[0] . check_plain($menu_item['link']['title']) . $whlt[1];
        $link_options['html'] = TRUE;
      }

      $expanded = ($sfsettings['expanded'] == 1) ? (($menu_item['link']['expanded'] == 1) ? TRUE : FALSE) : TRUE;

      if (!empty($menu_item['link']['has_children']) && !empty($menu_item['below']) && $depth != 0 && $expanded === TRUE) {

        // Megamenu is still beta, there is a good chance much of this will be changed.
        if (!empty($settings['megamenu_exclude'])) {
          if (is_array($settings['megamenu_exclude'])) {
            $megamenu_below = (in_array($mlid, $settings['megamenu_exclude'])) ? 0 : $megamenu;
          }
          else {
            $megamenu_below = ($settings['megamenu_exclude'] == $mlid) ? 0 : $megamenu;
          }
          // Send the result to the sub-menu.
          $sfsettings['megamenu'] = $megamenu_below;
        }
        if ($megamenu_below == 1) {
          $megamenu_wrapper = ($menu_item['link']['depth'] == $settings['megamenu_depth']) ? TRUE : FALSE;
          $megamenu_column = ($menu_item['link']['depth'] == $settings['megamenu_depth'] + 1) ? TRUE : FALSE;
          $megamenu_content = ($menu_item['link']['depth'] >= $settings['megamenu_depth'] && $menu_item['link']['depth'] <= $settings['megamenu_levels']) ? TRUE : FALSE;
        }
        // Render the sub-menu.
        $var = array(
          'id' => $id,
          'menu' => $menu_item['below'],
          'depth' => $depth,
          'trail' => $trail,
          'sfsettings' => $sfsettings
        );
        $children = theme('superfish_build', $var);
        // Check to see whether it should be displayed.
        $show_children = (($menu_item['link']['depth'] <= $depth || $depth == -1) && $children['content']) ? TRUE : FALSE;
        if ($show_children) {
          // Add item counter classes.
          if ($settings['itemcounter']) {
            $item_class[] = 'sf-total-children-' . $children['total_children'];
            $item_class[] = 'sf-parent-children-' . $children['parent_children'];
            $item_class[] = 'sf-single-children-' . $children['single_children'];
          }
          // More helper classes.
          $item_class[] = ($megamenu_column) ? 'sf-megamenu-column' : '';
          $item_class[] = $link_class[] = 'menuparent';
        }
        $parent_children++;
      }
      else {
        $item_class[] = 'sf-no-children';
        $single_children++;
      }

      $item_class = implode(' ', array_remove_empty($item_class));

      if (isset($menu_item['link']['localized_options']['attributes']['class'])) {
        $link_class_current = $menu_item['link']['localized_options']['attributes']['class'];
        $link_class = array_merge($link_class_current, array_remove_empty($link_class));
      }
      $menu_item['link']['localized_options']['attributes']['class'] = array_remove_empty($link_class);

      // The Context module uses theme_menu_link, Superfish does not, this is why we have to do this.
      if (function_exists('context_active_contexts')) {
        if ($contexts = context_active_contexts()) {
          foreach ($contexts as $context) {
            if ((isset($context->reactions['menu']))) {
              if ($menu_item['link']['href'] == $context->reactions['menu']) {
                $menu_item['link']['localized_options']['attributes']['class'][] = 'active';
              }
            }
          }
        }
      }

      $link_options += $menu_item['link']['localized_options'];

      // Render the menu item.
      // Should a theme be used for menu items?
      if ($settings['use_item_theme']) {
        $item_variables = array(
          'element' => array(
            'attributes' => array(
              'id' => 'menu-' . $mlid . '-' . $id,
              'class' => trim($item_class),
            ),
            'below' => ($show_children) ? $children['content'] : NULL,
            'item' => $menu_item,
            'localized_options' => $link_options,
          ),
          'properties' => array(
            'megamenu' => array(
              'megamenu_column' => $megamenu_column,
              'megamenu_wrapper' => $megamenu_wrapper,
              'megamenu_content' => $megamenu_content,
            ),
            'use_link_theme' => $settings['use_link_theme'],
            'wrapper' => $whl,
          ),
        );
        $output['content'] .= theme('superfish_menu_item', $item_variables);
      }
      else {
        $output['content'] .= '<li id="menu-' . $mlid . '-' . $id . '"';
        $output['content'] .= ($item_class) ? ' class="' . trim($item_class) . '">' : '>';
        $output['content'] .= ($megamenu_column) ? '<div class="sf-megamenu-column">' : '';
        $output['content'] .= isset($whl[0]) ? $whl[0] : '';
        if ($settings['use_link_theme']) {
          $link_variables = array(
            'menu_item' => $menu_item,
            'link_options' => $link_options,
          );
          $output['content'] .= theme('superfish_menu_item_link', $link_variables);
        }
        else {
          $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['href'], $link_options);
        }
        $output['content'] .= isset($whl[1]) ? $whl[1] : '';
        $output['content'] .= ($megamenu_wrapper) ? '<ul class="sf-megamenu"><li class="sf-megamenu-wrapper ' . $item_class . '">' : '';
        $output['content'] .= ($show_children) ? (isset($wul[0]) ? $wul[0] : '') : '';
        $output['content'] .= ($show_children) ? (($megamenu_content) ? '<ol>' : '<ul>') : '';
        $output['content'] .= ($show_children) ? $children['content'] : '';
        $output['content'] .= ($show_children) ? (($megamenu_content) ? '</ol>' : '</ul>') : '';
        $output['content'] .= ($show_children) ? (isset($wul[1]) ? $wul[1] : '') : '';
        $output['content'] .= ($megamenu_wrapper) ? '</li></ul>' : '';
        $output['content'] .= ($megamenu_column) ? '</div>' : '';
        $output['content'] .= '</li>';
      }
    }
  }
  $output['total_children'] = $total_children;
  $output['parent_children'] = $parent_children;
  $output['single_children'] = $single_children;
  return $output;
}
/**
 * Returns HTML for a menu item.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: Structured array data for a menu item.
 *   - properties: Various properties of a menu item.
 *
 * @ingroup themeable
 */
function theme_superfish_menu_item($variables) {
  $element = $variables['element'];
  $properties = $variables['properties'];
  $sub_menu = '';

  if ($element['below']) {
    $sub_menu .= isset($variables['wrapper']['wul'][0]) ? $variables['wrapper']['wul'][0] : '';
    $sub_menu .= ($properties['megamenu']['megamenu_content']) ? '<ol>' : '<ul>';
    $sub_menu .= $element['below'];
    $sub_menu .= ($properties['megamenu']['megamenu_content']) ? '</ol>' : '</ul>';
    $sub_menu .= isset($variables['wrapper']['wul'][1]) ? $variables['wrapper']['wul'][1] : '';
  }

  $output = '<li' . drupal_attributes($element['attributes']) . '>';
  $output .= ($properties['megamenu']['megamenu_column']) ? '<div class="sf-megamenu-column">' : '';
  $output .= isset($properties['wrapper']['whl'][0]) ? $properties['wrapper']['whl'][0] : '';
  if ($properties['use_link_theme']) {
    $link_variables = array(
      'menu_item' => $element['item'],
      'link_options' => $element['localized_options']
    );
    $output .= theme('superfish_menu_item_link', $link_variables);
  }
  else {
    $output .= l($element['item']['link']['title'], $element['item']['link']['href'], $element['localized_options']);
  }
  $output .= isset($properties['wrapper']['whl'][1]) ? $properties['wrapper']['whl'][1] : '';
  $output .= ($properties['megamenu']['megamenu_wrapper']) ? '<ul class="sf-megamenu"><li class="sf-megamenu-wrapper ' . $element['attributes']['class'] . '">' : '';
  $output .= $sub_menu;
  $output .= ($properties['megamenu']['megamenu_wrapper']) ? '</li></ul>' : '';
  $output .= ($properties['megamenu']['megamenu_column']) ? '</div>' : '';
  $output .= '</li>';

  return $output;
}
/**
 * Theme a menu item link.
 *
 * @param $variables
 *   An array of variables containing:
 *    - menu_item: The menu item array.
 *    - link_options: An array of link options.
 *
 * @ingroup themeable
 */
function theme_superfish_menu_item_link($variables) {
  $menu_item = $variables['menu_item'];
  $link_options = $variables['link_options'];
  return l($menu_item['link']['title'], $menu_item['link']['href'], $link_options);
}