<?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(t('Blocks management'), '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 = $menu_default = array();

  // Integration with the Domain Access module.
  if (module_exists('domain_conf')) {
    $main = variable_get('menu_main_links_source');
    $secondary = variable_get('menu_secondary_links_source');
    if ($main) {
      $menu_default['domainaccessmenu1st-' . $main . ':0'] = t('Domains Access') . ': ' . t('Main links');
    }
    if ($secondary) {
      $menu_default['domainaccessmenu2nd-' . $secondary . ':0'] = t('Domains Access') . ': ' . t('Secondary links');
    }
  }
  $menu_default += menu_parent_options(menu_get_menus(), array('mlid' => 0));

  $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-settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Superfish settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sf-settings']['superfish_menu_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Menu'),
    '#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_default,
  );
  $form['sf-settings']['superfish_type_' . $delta] = array(
    '#type' => 'radios',
    '#title' => t('Type'),
    '#default_value' => variable_get('superfish_type_' . $delta, 'horizontal'),
    '#options' => array(
      'horizontal' => t('Horizontal (single row)') . ' <em>(' . t('Default') . ')</em>',
      'navbar' => t('Horizontal (double row)'),
      'vertical' => t('Vertical (stack)')
    ),
  );
  $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_arrow_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add arrows to parent menus'),
    '#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']['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']['sf-advanced']  = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-settings']['sf-advanced']['sf-menu']  = array(
    '#type' => 'fieldset',
    '#title' => t('Menu'),
    '#collapsible' => FALSE
  );
  $form['sf-settings']['sf-advanced']['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-settings']['sf-advanced']['sf-menu']['superfish_expanded_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Take "Expanded" option into effect.'),
    '#description' => t('By enabling this option only those parent menu items which have the <em>Expanded</em> option enabled will have their sub-menus included in this menu block.') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_expanded_' . $delta, 0),
  );
  $form['sf-settings']['sf-advanced']['sf-menu']['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-advanced']['sf-menu']['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-settings']['sf-advanced']['sf-menu']['superfish_clone_parent_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Add cloned parent links to the top of sub-menus.') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em>',
    '#default_value' => variable_get('superfish_clone_parent_' . $delta, 0),
  );
  $form['sf-settings']['sf-advanced']['sf-settings']  = array(
    '#type' => 'fieldset',
    '#title' => t('Superfish'),
    '#collapsible' => FALSE
  );
  $form['sf-settings']['sf-advanced']['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,
  );
  $form['sf-settings']['sf-advanced']['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']['sf-advanced']['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 setting <strong>only and 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']['sf-advanced']['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><br />' . t('Change this setting <strong>only and only</strong> if you are <strong>totally sure</strong> of what you are doing.'),
    '#default_value' => variable_get('superfish_pathlevels_' . $delta, 1),
    '#options' => drupal_map_assoc(range(0, 10)),
  );
  $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>' . ((!file_exists(superfish_get_path('superfish') . '/jquery.bgiframe.min.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload jquery.bgiframe.min.js to the /libraries/superfish directory.') : ''),
    '#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>' . ((!file_exists(superfish_get_path('superfish') . '/supposition.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload supposition.js to the /libraries/superfish directory.') : ''),
    '#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>' . ((!file_exists(superfish_get_path('superfish') . '/jquery.hoverIntent.minified.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload jquery.hoverIntent.minified.js to the /libraries/superfish directory.') : ''),
    '#default_value' => variable_get('superfish_hid_' . $delta, 1),
  );
  $form['sf-plugins']['superfish_amw_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Use sf-AutomaticWidth plugin for this menu.'),
    '#description' => t('Automatically adjusts the menu width to maximum possible.') . ' <em>(' . t('Default') . ': ' . t('disabled') . ')</em><br />' . t('This is limited to Horizontal and NavBar types.') . ((!file_exists(superfish_get_path('superfish') . '/sfautomaticwidth.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload sfautomaticwidth.js to the /libraries/superfish directory.') : ''),
    '#default_value' => variable_get('superfish_amw_' . $delta, 0),
  );
  $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>' . ((!file_exists(superfish_get_path('superfish') . '/sftouchscreen.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload sftouchscreen.js to the /libraries/superfish directory.') : ''),
    '#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']['superfish_touchbh_' . $delta] = array(
    '#type' => 'radios',
    '#title' => t('Select a behaviour'),
    '#description' => t('Using this plugin, the first click or tap will expand the sub-menu, here you can choose what a second click or tap should do.'),
    '#default_value' => variable_get('superfish_touchbh_' . $delta, 2),
    '#options' => array(
      0 => t('Opening the parent menu item link on the second tap.'),
      1 => t('Hiding the sub-menu on the second tap.'),
      2 => t('Hiding the sub-menu on the second tap, adding cloned parent links to the top of sub-menus as well.') . ' <sup>(' . t('Default') . ')</sup>',
    ),
  );
  $form['sf-plugins']['sf-touchscreen']['superfish_touchdh_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Also disable the <em>hover</em> (mouse over) event for all its items.'),
    '#default_value' => variable_get('superfish_touchdh_' . $delta, 0),
  );
  $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',
    '#title' => t('Breakpoint'),
    '#description' => '<em>(' . t('Default') . ': 768px)</em>',
    '#default_value' => variable_get('superfish_touchbp_' . $delta, 768),
    '#size' => 10,
    '#prefix' => '<div class="clearfix"></div><div class="sf-breakpoint" style="float:left;">',
    '#suffix' => '</div>',
  );
  $form['sf-plugins']['sf-touchscreen']['sf-touchscreen-windowwidth']['superfish_touchbpu_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Unit'),
    '#default_value' => variable_get('superfish_touchbpu_' . $delta, 'px'),
    '#options' => array(
      'px' => 'px',
      'em' => 'em',
    ),
    '#prefix' => '<div class="sf-breakpoint-unit" style="float:left;">',
    '#suffix' => '</div><div class="clearfix"></div>',
  );
  $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>' . ((!file_exists(superfish_get_path('superfish') . '/sfsmallscreen.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload sfsmallscreen.js to the /libraries/superfish directory.') : ''),
    '#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',
    '#title' => t('Breakpoint'),
    '#description' => '<em>(' . t('Default') . ': 768px)</em>',
    '#default_value' => variable_get('superfish_smallbp_' . $delta, 768),
    '#size' => 10,
    '#prefix' => '<div class="clearfix"></div><div class="sf-breakpoint" style="float:left;">',
    '#suffix' => '</div>',
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-windowwidth']['superfish_smallbpu_' . $delta] = array(
    '#type' => 'select',
    '#title' => t('Unit'),
    '#default_value' => variable_get('superfish_smallbpu_' . $delta, 'px'),
    '#options' => array(
      'px' => 'px',
      'em' => 'em',
    ),
    '#prefix' => '<div class="sf-breakpoint-unit" style="float:left;">',
    '#suffix' => '</div><div class="clearfix"></div>',
  );
  $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']['superfish_smallact_' . $delta] = array(
    '#type' => 'radios',
    '#title' => t('Select a reaction'),
    '#default_value' => variable_get('superfish_smallact_' . $delta, 1),
    '#options' => array(
      0 => t('Convert the menu to a &lt;select&gt; element.'),
      1 => t('Convert the menu to an accordion menu.') . ' <sup>(' . t('Default') . ')</sup>',
    ),
  );
  $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;.') . ' <sup><em>(' . t('Default') . ': ' . t('disabled') . ')</em></sup>',
    '#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;.') . ' <sup><em>(' . t('Default') . ': ' . t('disabled') . ')</em></sup>',
    '#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-smallscreen']['sf-smallscreen-accordion'] = array(
    '#type' => 'fieldset',
    '#title' => t('Accordion settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-accordion']['superfish_smallamt_' . $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Accordion menu title'),
    '#description' => t('By default the caption of the accordion toggle switch 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('Menu') . '</em>.',
    '#default_value' => variable_get('superfish_smallamt_' . $delta, ''),
    '#size' => 50,
    '#maxlength' => 500,
  );
  $form['sf-plugins']['sf-smallscreen']['sf-smallscreen-accordion']['superfish_smallabt_' . $delta] = array(
    '#type' => 'radios',
    '#title' => t('Accordion button type'),
    '#default_value' => variable_get('superfish_smallabt_' . $delta, 1),
    '#options' => array(
      0 => t('Use parent menu items as buttons.'),
      1 => t('Use parent menu items as buttons, add cloned parent links to sub-menus as well.') . ' <sup>(' . t('Default') . ')</sup>',
      2 => t('Create new links next to parent menu item links and use them as buttons.'),
    ),
  );
  $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.') . ((!file_exists(superfish_get_path('superfish') . '/supersubs.js')) ? '<br /><strong>' . t('Important') . ':</strong> ' . t('Cannot find the required JavaScript file, please upload supersubs.js to the /libraries/superfish directory.') : ''),
    '#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_supersubs_emm_' . $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Do not use Supersubs for multi-column sub-menus.'),
    '#default_value' => variable_get('superfish_supersubs_emm_' . $delta, 0),
  );
  $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' => 10,
  );
  $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' => 10,
  );
  $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'),
    '#description' => t('Please consider using CSS pseudo-elements :before &amp; :after before using the features below as improper use of them may break your drop down menu.'),
    '#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;LI&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_amw_' . $delta, $edit['superfish_amw_' . $delta]);
  variable_set('superfish_touch_' . $delta, $edit['superfish_touch_' . $delta]);
  variable_set('superfish_touchbh_' . $delta, $edit['superfish_touchbh_' . $delta]);
  variable_set('superfish_touchdh_' . $delta, $edit['superfish_touchdh_' . $delta]);
  variable_set('superfish_touchbp_' . $delta, $edit['superfish_touchbp_' . $delta]);
  variable_set('superfish_touchbpu_' . $delta, $edit['superfish_touchbpu_' . $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_smallact_' . $delta, $edit['superfish_smallact_' . $delta]);
  variable_set('superfish_smallbp_' . $delta, $edit['superfish_smallbp_' . $delta]);
  variable_set('superfish_smallbpu_' . $delta, $edit['superfish_smallbpu_' . $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_smallamt_' . $delta, $edit['superfish_smallamt_' . $delta]);
  variable_set('superfish_smallabt_' . $delta, $edit['superfish_smallabt_' . $delta]);
  variable_set('superfish_supersubs_' . $delta, $edit['superfish_supersubs_' . $delta]);
  variable_set('superfish_supersubs_emm_' . $delta, $edit['superfish_supersubs_emm_' . $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_clone_parent_' . $delta, $edit['superfish_clone_parent_' . $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]);
}

/**
 * Implements hook_block_view().
 */
function superfish_block_view($delta = 0) {
  global $language;
  $block_css = $block_js = $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'] = superfish_sanitize(variable_get('superfish_ulclass_' . $delta, ''), 'strict');
  $sfsettings['liclass'] = superfish_sanitize(variable_get('superfish_liclass_' . $delta, ''), 'strict');
  $sfsettings['hlclass'] = superfish_sanitize(variable_get('superfish_hlclass_' . $delta, ''), 'strict');
  $sfsettings['wrapmul'] = superfish_sanitize(variable_get('superfish_wrapmul_' . $delta, ''));
  $sfsettings['wrapul'] = superfish_sanitize(variable_get('superfish_wrapul_' . $delta, ''));
  $sfsettings['wraphl'] = superfish_sanitize(variable_get('superfish_wraphl_' . $delta, ''));
  $sfsettings['wraphlt'] = superfish_sanitize(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['clone_parent'] = variable_get('superfish_clone_parent_' . $delta, 0);
  $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'], ',')) ? superfish_array_filter(explode(',', $sfsettings['hldmenus'])) : $sfsettings['hldmenus'];
  $sfsettings['hldexclude'] = variable_get('superfish_hldexclude_' . $delta, '');
  $sfsettings['hldexclude'] = (strpos($sfsettings['hldexclude'], ',')) ? superfish_array_filter(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'], ',')) ? superfish_array_filter(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');
  if ($speed != 'normal') {
    $sfoptions['speed'] = ((is_numeric($speed)) ? (int) $speed : (($speed == ('slow' || 'normal' || 'fast')) ? $speed : ''));
  }
  $sfoptions['autoArrows'] = (variable_get('superfish_arrow_' . $delta, 1) == 0) ? FALSE : '';
  $sfoptions['dropShadows'] = (variable_get('superfish_shadow_' . $delta, 1) == 0) ? FALSE : '';

  if (variable_get('superfish_hid_' . $delta, 1) == 1 && superfish_library('javascript', 'jquery.hoverIntent.minified.js', 'check')) {
    $block_js = array_merge($block_js, superfish_library('javascript', 'hoverIntent', 'add'));
  }
  else {
    $sfoptions['disableHI'] = TRUE;
  }
  $sfoptions = superfish_array_filter($sfoptions);

  if (variable_get('superfish_amw_' . $delta, 0) == 1 && superfish_library('javascript', 'sfautomaticwidth.js', 'check')) {
    $sfplugins['automaticwidth'] = TRUE;
    $block_js = array_merge($block_js, superfish_library('javascript', 'sfautomaticwidth', 'add'));
  }

  $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'));
    $behaviour = variable_get('superfish_touchbh_' . $delta, 2);
    $sfplugins['touchscreen']['behaviour'] = ($behaviour != 2) ? $behaviour : '';
    if (variable_get('superfish_touchdh_' . $delta, 0)) {
      $sfplugins['touchscreen']['disableHover'] = TRUE;
    }
    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 : '';
        $tsbpu = variable_get('superfish_touchbpu_' . $delta, 'px');
        $sfplugins['touchscreen']['breakpointUnit'] = $tsbpu;
        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)|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';
                    if ($behaviour == 2) {
                      $sfsettings['clone_parent'] = 1;
                    }
                  }
                  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';
                    if ($behaviour == 2) {
                      $sfsettings['clone_parent'] = 1;
                    }
                  }
                  break;

              }
            }
            break;

        }
        break;
    }
  }

  // Unset hoverIntent if sfTouchscreen settings make it ineffective.
  if (isset($sfplugins['touchscreen']['disableHover']) && $sfplugins['touchscreen']['disableHover'] === TRUE && $sfplugins['touchscreen']['mode'] == 'always_active') {
    $hid = array_keys(superfish_library('javascript', 'hoverIntent', 'add'));
    if (isset($block_js[$hid[0]])) {
      unset($block_js[$hid[0]]);
    }
  }

  $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 : '';
        $ssbpu = variable_get('superfish_smallbpu_' . $delta, 'px');
        $sfplugins['smallscreen']['breakpointUnit'] = $ssbpu;
        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;
    }
    $type = variable_get('superfish_smallact_' . $delta, 1);
    switch ($type) {
      case 0:
        $asa = variable_get('superfish_smallasa_' . $delta, 0);
        $cmc = variable_get('superfish_smallcmc_' . $delta, 0);
        $chc = variable_get('superfish_smallchc_' . $delta, 0);
        $ecm = variable_get('superfish_smallecm_' . $delta, '');
        $ech = variable_get('superfish_smallech_' . $delta, '');
        $icm = variable_get('superfish_smallicm_' . $delta, '');
        $ich = variable_get('superfish_smallich_' . $delta, '');

        $sfplugins['smallscreen']['type'] = 'select';
        $sfplugins['smallscreen']['addSelected'] = ($asa == 1) ? TRUE : '';
        $sfplugins['smallscreen']['menuClasses'] = ($cmc == 1) ? TRUE : '';
        $sfplugins['smallscreen']['hyperlinkClasses'] = ($chc == 1) ? TRUE : '';
        $sfplugins['smallscreen']['excludeClass_menu'] = ($cmc == 1 && !empty($ecm)) ? $ecm : '';
        $sfplugins['smallscreen']['excludeClass_hyperlink'] = ($chc == 1 && !empty($ech)) ? $ech : '';
        $sfplugins['smallscreen']['includeClass_menu'] = (!empty($icm)) ? $icm : '';
        $sfplugins['smallscreen']['includeClass_hyperlink'] = (!empty($ich)) ? $ich : '';
        break;

      case 1:
        if (superfish_library('CSS', 'smallscreen', 'check')) {
          $block_css = array_merge($block_css, superfish_library('CSS', 'smallscreen', 'add'));
        }
        $ab = variable_get('superfish_smallabt_' . $delta, 1);
        $sfplugins['smallscreen']['accordionButton'] = ($ab != 1) ? $ab : '';
        $sfplugins['smallscreen']['expandText'] = (t('Expand') != 'Expand') ? t('Expand') : '';
        $sfplugins['smallscreen']['collapseText'] = (t('Collapse') != 'Collapse') ? t('Collapse') : '';
        break;
    }
  }

  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'));
  }

  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'));
  }

  if (variable_get('superfish_supersubs_' . $delta, 1) == 1 && superfish_library('javascript', 'supersubs.js', 'check')) {
    $block_js = array_merge($block_js, superfish_library('javascript', 'supersubs', 'add'));
    $emm = variable_get('superfish_supersubs_emm_' . $delta, 0);
    $minwidth = variable_get('superfish_minwidth_' . $delta, 12);
    $maxwidth = variable_get('superfish_maxwidth_' . $delta, 27);
    $sfplugins['supersubs']['megamenu'] = ($emm) ? FALSE : '';
    $sfplugins['supersubs']['minWidth'] = ($minwidth != 12) ? $minwidth : '';
    $sfplugins['supersubs']['maxWidth'] = ($maxwidth != 27) ? $maxwidth : '';
    if (empty($sfplugins['supersubs']['minWidth']) && empty($sfplugins['supersubs']['maxWidth']) && $sfplugins['supersubs']['megamenu'] !== FALSE) {
      $sfplugins['supersubs'] = TRUE;
    }
  }

  $menu_name = variable_get('superfish_menu_' . $delta, 'primary-links:0');
  // Integration with the Domain Access module.
  $main = variable_get('menu_main_links_source');
  $secondary = variable_get('menu_secondary_links_source');
  if ($main || $secondary) {
    if (strpos($menu_name, 'domainaccessmenu1st') !== FALSE) {
      $menu_name = $main . ':0';
    }
    elseif (strpos($menu_name, 'domainaccessmenu2nd') !== FALSE) {
      $menu_name = $secondary . ':0';
    }
  }
  $menu_name = str_replace(array('domainaccessmenu1st-', 'domainaccessmenu2nd-'), '', $menu_name);

  list($menu_name, $mlid) = explode(':', $menu_name);

  $vars = array(
    'id' => $delta,
    'menu_name' => $menu_name,
    'mlid' => $mlid,
    'sfsettings' => $sfsettings,
  );
  if ($block = theme('superfish', $vars)) {
    if (!empty($block['content'])) {
      $block['content'] = array(
        '#type' => 'markup',
        '#markup' => $block['content'],
        '#contextual_links' => array(
          'superfish' => array('admin/structure/menu/manage', array($menu_name)),
        ),
      );

      // Creating a title for the small-screen menu.
      if ($smallscreen > 0 && superfish_library('javascript', 'sfsmallscreen.js', 'check')) {
        switch ($type) {
          case 0:
            $title = variable_get('superfish_smallset_' . $delta, '');
            break;

          case 1:
            $title = variable_get('superfish_smallamt_' . $delta, '');
            break;
        }
        $sfplugins['smallscreen']['title'] = (empty($title)) ? $block['subject'] : $title;
      }
      $sfplugins = superfish_array_filter($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, superfish_styles('path', $sfsettings['style']));
      }
      $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)));
        }
      }
      $block['content']['#attached'] = array(
        'css' => $block_css,
        'js' => $block_js,
      );
    }
  }
  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;
    $allowed_speed = array('slow', 'normal', 'fast');
    $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, $allowed_speed)) {
      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 = superfish_array_filter(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>'));
      }
    }
  }
}

/**
 * Helper function to get library paths.
 */
function superfish_get_path($library = 'superfish') {
  $directory = '';
  // Ensure the Libraries API module is installed.
  if (module_exists('libraries') && function_exists('libraries_get_path')) {
    $directory = libraries_get_path($library);
  }
  // Otherwise use the default directory.
  elseif (file_exists('profiles/' . drupal_get_profile() . '/libraries/' . $library)) {
    $directory = 'profiles/' . drupal_get_profile() . '/libraries/' . $library;
  }
  if (empty($directory)) {
    $directory = 'sites/all/libraries/' . $library;
  }
  return $directory;
}

/**
 * Get a list of CSS files that can be used for styles.
 */
function superfish_styles($display = 'list', $style = NULL) {
  $output = '';
  $directory = superfish_get_path('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 = array($files[$style]->uri => array('type' => 'file', 'weight' => 500));
    }
    else {
      watchdog('page not found', 'Cannot find the required files for the Superfish \'%style\' style.', 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'));

  if (file_exists(superfish_get_path('easing') . '/jquery.easing.js')) {
    $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') {
  $directory = superfish_get_path('superfish');
  $directory_easing = superfish_get_path('easing');
  $sf_library = $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\n" .
    $directory . "/sfautomaticwidth.js";

  $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;
        }
        $in_library = FALSE;
        foreach ($sf_library as $s) {
          if (strpos($s, $name) !== FALSE) {
            $in_library = TRUE;
            if (file_exists($s)) {
              return TRUE;
            }
            else {
              watchdog('page not found', '%file', array('%file' => $directory . '/' . $name), WATCHDOG_ERROR);
              return FALSE;
            }
          }
        }
        if (!$in_library) {
          watchdog('page not found', '%path missing from Superfish library configuration, please add it immediately.', array('%path' => $directory . '/' . $name), WATCHDOG_WARNING, l(t('Superfish library configuration'), 'admin/config/user-interface/superfish'));
          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':
          case 'smallscreen':
            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;

          case 'drupal_behavior':
            $output = array(
              drupal_get_path('module', 'superfish') . '/superfish.js' =>
              array('type' => 'file', 'weight' => 495),
            );
            return $output;

          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;
                  }
                  $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;

      case 'CSS':
        $directory .= '/css';
        switch ($name) {
          case 'superfish':
          case 'horizontal':
            $output = array($directory . '/superfish.css' => array('type' => 'file', 'weight' => 480));
            return $output;

          case 'navbar':
          case 'vertical':
          case 'smallscreen':
            $output = array($directory . '/superfish-' . $name . '.css' => array('type' => 'file', 'weight' => 490));
            return $output;

        }
        break;
    }
  }
}

/**
 * Sanitization function.
 *
 * @param string The input.
 * @param mode Sanitization type.
 *
 * @return string
 */
function superfish_sanitize($string, $type = '') {
  if ($type == 'strict') {
    $allowed_tags = array();
  } else {
    $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', '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', 'section',
      'select', 'small', 'source', 'span', 'strong', 'sub', 'summary',
      'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead',
      'time', 'tr', 'track', 'tt', 'ul', 'var', 'video', 'wbr');
  }
  return filter_xss($string, $allowed_tags);
}

/**
 * Helper function to clean up arrays.
 */
function superfish_array_filter($haystack) {
  foreach ($haystack as $key => $value) {
    if (is_array($value)) {
      $haystack[$key] = superfish_array_filter($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,
        'clone_parent' => 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)),
      'clone_parent' => FALSE,
      '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();
        }
        $classes = 'menu sf-menu sf-' . $menu_name . ' sf-' . $sfsettings['type'] . ' sf-style-' . $sfsettings['style'];
        $classes .= ($sfsettings['itemcounter']) ? ' sf-total-items-' . $menu_tree['total_children'] : '';
        $classes .= ($sfsettings['itemcounter']) ? ' sf-parent-items-' . $menu_tree['parent_children'] : '';
        $classes .= ($sfsettings['itemcounter']) ? ' sf-single-items-' . $menu_tree['single_children'] : '';
        $classes .= ($sfsettings['ulclass']) ? ' ' . trim($sfsettings['ulclass']) : '';
        $classes .= ($language->direction == 1) ? ' rtl' : '';
        $output['content'] = isset($wmul[0]) ? $wmul[0] : '';
        $output['content'] .= '<ul ' . drupal_attributes(array('id' => 'superfish-' . $id, 'class' => $classes)) . '>';
        $output['content'] .= $menu_tree['content'];
        $output['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'];
  $clone_parent = $variables['clone_parent'];
  // 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++;
    }
  }

  // sfTouchscreen.
  // Adding cloned parent to the sub-menu.
  if ($clone_parent !== FALSE) {
    array_unshift($menu, $clone_parent);
  }

  foreach ($menu as $menu_item) {

    $show_children = $megamenu_wrapper = $megamenu_column = $megamenu_content = FALSE;
    $item_class = $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']) ? trim($settings['liclass']) : '';
      $item_class[] = ($clone_parent !== FALSE) ? 'sf-clone-parent' : '';
      if (strpos($settings['hlclass'], ' ')) {
        $l = explode(' ', $settings['hlclass']);
        foreach ($l as $c) {
          $link_class[] = trim($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>';
          $menu_item['link']['localized_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] . $menu_item['link']['title'] . $whlt[1];
        $menu_item['link']['localized_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 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;
        }

        // sfTouchscreen.
        // Preparing the cloned parent links to be added to the sub-menus.
        $below_visible = array();
        foreach ($menu_item['below'] as $below) {
          if (!isset($below['link']['hidden']) || $below['link']['hidden'] == 0) {
            $below_visible[] = 1;
          }
        }
        if ($settings['clone_parent'] == 1 && in_array(1, $below_visible)) {
          $clone_parent = $menu_item;
          unset($clone_parent['below']);
          unset($clone_parent['has_children']);
        }
        else {
          $clone_parent = FALSE;
        }

        // Render the sub-menu.
        $var = array(
          'id' => $id,
          'menu' => $menu_item['below'],
          'depth' => $depth,
          'trail' => $trail,
          'clone_parent' => $clone_parent,
          '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 = trim(implode(' ', superfish_array_filter($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, superfish_array_filter($link_class));
      }
      $menu_item['link']['localized_options']['attributes']['class'] = superfish_array_filter($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';
              }
            }
          }
        }
      }

      // 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,
          ),
          'properties' => array(
            'megamenu' => array(
              'megamenu_column' => $megamenu_column,
              'megamenu_wrapper' => $megamenu_wrapper,
              'megamenu_content' => $megamenu_content,
            ),
            'use_link_theme' => $settings['use_link_theme'],
            'wrapper' => array(
              'wul' => $wul,
              'whl' => $whl,
            ),
          ),
          'sfsettings' => $sfsettings,
        );
        $output['content'] .= theme('superfish_menu_item', $item_variables);
      }
      else {
        $output['content'] .= '<li' . drupal_attributes(array('id' => 'menu-' . $mlid . '-' . $id, 'class' => $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' => $menu_item['link']['localized_options'],
          );
          $output['content'] .= theme('superfish_menu_item_link', $link_variables);
        }
        else {
          $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['href'], $menu_item['link']['localized_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 array $variables
 *   An associative array containing:
 *   - element: Structured array data for a menu item.
 *   - properties: Various properties of a menu item.
 *
 * @return string
 *   HTML string
 *
 * @ingroup themeable
 */
function theme_superfish_menu_item($variables) {
  $element = $variables['element'];
  $properties = $variables['properties'];
  $sub_menu = '';

  if ($element['below']) {
    $sub_menu .= isset($properties['wrapper']['wul'][0]) ? $properties['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($properties['wrapper']['wul'][1]) ? $properties['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['item']['link']['localized_options'],
    );
    $output .= theme('superfish_menu_item_link', $link_variables);
  }
  else {
    $output .= l($element['item']['link']['title'], $element['item']['link']['href'], $element['item']['link']['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 array $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);
}
