<?php
/**
 * @file
 * A module that adds one of the ShareThis widget to your website.
 */

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function sharethis_help($path, $arg) {
  global $base_url;
  switch ($path) {
    case 'admin/config/services/sharethis':
      return '<p>' . t('Choose the widget, button family, and services for using <a href="@sharethis">ShareThis</a> to share content online.', array('@sharethis' => 'http://www.sharethis.com')) . '</p>';
      break;
    case "admin/help#sharethis":
      $return_value = "<p>" . t("This plugin places the ShareThis widget on each node.") . '</p>';
      $return_value .= "<ul><li>" . t("The Block pulls the URL from the current page and current Drupal title, the node version pulls it from the node title and url.") . '</li>';
      $return_value .= "<li>" . t("The block can be placed anywhere on a page, the node is limited to where nodes normally go") . '</li>';
      $return_value .= "<li>" . t("The block module is more likely to be compatible with other plugins that use blocks rather than nodes. (Panels works nicely with the block)") . '</li></ul>';
      $return_value .= "<p>" . t('For various configuration options please got to <a href="@sharethis">the settings page</a>.', array('@sharethis' => url('admin/config/services/sharethis'))) . '</p>';
      $return_value .= '<p>' . t('For more information, please visit <a href="@help">support.sharethis.com</a>.', array('@help' => 'http://support.sharethis.com/customer/portal/articles/446621-drupal-integration')) . '</p>';
      return $return_value;
      break;
  }
}

/**
 * Converts given value to boolean.
 *
 *
 * @param val
 *   Which value to convert to boolean
 */
function to_boolean($val) {
  if (strtolower(trim($val)) === 'false') {
    return false;
  } else {
    return (boolean)$val;
  }
}

/**
 * Implements hook_permission().
 */
function sharethis_permission() {
  return array(
    'administer sharethis' => array(
      'title' => t('Administer ShareThis'),
      'description' => t('Change the settings for how ShareThis behaves on the site.'),
    ),
  );
}

 /**
 * This is the main configuration form for the admin page.
 */
function sharethis_configuration_form($form, &$form_state) {
  // First, setup variables we will need.
  // Get the path variables setup.
  $my_path = drupal_get_path('module', 'sharethis');
  // Load the css and js for our module's configuration.
  drupal_add_css($my_path . '/ShareThisForm.css');
  drupal_add_js('https://ws.sharethis.com/share5x/js/stcommon.js', 'external');  //This is ShareThis's common library - has a serviceList of all the objects that are currently supported.
  drupal_add_js($my_path . '/ShareThisForm.js');
  drupal_add_js($my_path . '/stlib_picker.js');
  drupal_add_css($my_path . '/stlib_picker.css');
  $current_options_array = sharethis_get_options_array();
  global $base_url;

  // Create the variables related to widget choice.
  $widget_type = $current_options_array['widget'];
  $widget_markup = "";
  if ($widget_type == "st_multi") {
    $widget_markup = "st_multi";
  }
  // Create the variables related to button choice.
  $button_choice = check_plain($current_options_array['buttons']);
  // Create the variables related to services chosen.
  $service_string = $current_options_array['services'];
  $service_string_markup = "";
  foreach (explode(",", $service_string) as $name => $string) {
    $key = explode(":", drupal_substr($string, 0, -1));
    $key = $key[1];
    $service_string_markup .= "\"" . $key . "\",";
  }
  $service_string_markup = drupal_substr($service_string_markup, 0, -1);

  // Create the variables for publisher keys.
  $publisher = $current_options_array['publisherID'];
  // Create the variables for teasers.

  $form = array();
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Display'),
  );
  $form['options']['sharethis_button_option'] = array(
    '#required' => TRUE,
    '#type' => 'radios',
    '#options' => array(
      'stbc_large' => t('Large Chicklets'),
      'stbc_' => t('Small Chicklets'),
      'stbc_button' => t('Classic Buttons'),
      'stbc_vcount' => t('Vertical Counters'),
      'stbc_hcount' => t('Horizontal Counters'),
      'stbc_custom' => t('Custom Buttons via CSS'),
    ),
    '#default_value' => $button_choice,
    '#title' => t("Choose a button style:"),
    '#prefix' => '<div class="st_widgetContain"><div class="st_spriteCover"><img id="stb_sprite" class="st_buttonSelectSprite ' . $button_choice . '" src="' . $base_url . '/' . $my_path . '/img/preview_sprite.png"></img></div><div class="st_widgetPic"><img class="st_buttonSelectImage" src="' . $base_url . '/' . $my_path . '/img/preview_bg.png"></img></div>',
    '#suffix' => '</div>'
  );
  $form['options']['sharethis_service_option'] = array(
    '#description' => t("<b>Add</b> a service by selecting it on the right and clicking the <i>left arrow</i>.  <b>Remove</b> it by clicking the <i>right arrow</i>.<br /><b>Change the order</b> of services under \"Selected Services\" by using the <i>up</i> and <i>down</i> arrows."),
    '#required' => TRUE,
    '#type' => 'textfield',
    '#prefix' => '<div>',
    '#suffix' => '</div><div id="myPicker"></div><script type="text/javascript">stlib_picker.setupPicker(jQuery("#myPicker"), [' . $service_string_markup . '], drupal_st.serviceCallback);</script>',
    '#title' => t("Choose Your Services."),
    '#default_value' => t($service_string),
    '#maxlength' => 1024,
  );
  $form['options']['sharethis_option_extras'] = array(
    '#title' => t('Extra services'),
    '#description' => t('Select additional services which will be available. These are not officially supported by ShareThis, but are available.'),
    '#type' => 'checkboxes',
    '#options' => array(
      'Google Plus One:plusone' => t('Google Plus One'),
      'Facebook Like:fblike' => t('Facebook Like'),
    ),
    '#default_value' => $current_options_array['option_extras'],
  );

  $form['options']['sharethis_callesi'] = array(
    '#type' => 'hidden',
    '#default_value' => $current_options_array['sharethis_callesi'],
  );

  $form['additional_settings'] = array(
    '#type' => 'vertical_tabs',
  );
  $form['context'] = array(
    '#type' => 'fieldset',
    '#title' => t('Context'),
    '#group' => 'additional_settings',
    '#description' => t('Configure where the ShareThis widget should appear.'),
  );

  $form['context']['sharethis_location'] = array(
    '#title' => t('Location'),
    '#type' => 'radios',
    '#options' => array(
      'content' => t('Node content'),
      'block' => t('Block'),
      'links' => t('Links area'),
    ),
    '#default_value' => variable_get('sharethis_location', 'content'),
  );

  // Add an information section for each location type, each dependent on the
  // currently selected location.
  foreach (array('links', 'content', 'block') as $location_type) {
    $form['context'][$location_type]['#type'] = 'container';
    $form['context'][$location_type]['#states']['visible'][':input[name="sharethis_location"]'] = array('value' => $location_type);
  }

  // Add help text for the 'content' location.
  $form['context']['content']['help'] = array(
    '#markup' => t('When using the Content location, you must place the ShareThis links in the <a href="@url">Manage Display</a> section of each content type.', array('@url' => url('admin/structure/types'))),
    '#weight' => 10,
    '#prefix' => '<em>',
    '#suffix' => '</em>',
  );
  // Add help text for the 'block' location.
  $form['context']['block']['#children'] = t('You must choose which region to display the <em>ShareThis block</em> in from the <a href="@blocksadmin">Blocks administration</a>.', array('@blocksadmin' => url('admin/structure/block')));

  // Add checkboxes for each view mode of each bundle.
  $entity_info = entity_get_info('node');
  $modes = array();
  foreach ($entity_info['view modes'] as $mode => $mode_info) {
    $modes[$mode] = $mode_info['label'];
  }
  // Get a list of content types and view modes
  $view_modes_selected = $current_options_array['view_modes'];
  foreach ($entity_info['bundles'] as $bundle => $bundle_info) {
    $form['context']['links']['sharethis_' . $bundle . '_options'] = array(
      '#title' => t('%label View Modes', array('%label' => $bundle_info['label'])),
      '#description' => t('Select which view modes the ShareThis widget should appear on for %label nodes.', array('%label' => $bundle_info['label'])),
      '#type' => 'checkboxes',
      '#options' => $modes,
      '#default_value' => $view_modes_selected[$bundle],
    );
  }

  // Allow the user to choose which content types will have ShareThis added
  // when using the 'Content' location.
  $content_types = array();
  $enabled_content_types = $current_options_array['sharethis_node_types'];
  foreach($entity_info['bundles'] as $bundle => $bundle_info) {
    $content_types[$bundle] = t($bundle_info['label']);
  }
  $form['context']['content']['sharethis_node_types'] = array(
    '#title' => t('Node Types'),
    '#description' => t('Select which node types the ShareThis widget should appear on.'),
    '#type' => 'checkboxes',
    '#options' => $content_types,
    '#default_value' => $enabled_content_types,
  );
  $form['context']['sharethis_comments'] = array(
    '#title' => t('Comments'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('sharethis_comments', FALSE),
    '#description' => t('Display ShareThis on comments.'),
    '#access' => module_exists('comment'),
  );
  $form['context']['sharethis_weight'] = array(
    '#title' => t('Weight'),
    '#description' => t('The weight of the widget determines the location on the page where it will appear.'),
    '#required' => FALSE,
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(-100, -50, -25, -10, 0, 10, 25, 50, 100)),
    '#default_value' => variable_get('sharethis_weight', 10),
  );
  $form['advanced'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced'),
    '#group' => 'additional_settings',
    '#description' => t('The advanced settings can usually be ignored if you have no need for them.'),
  );
  $form['advanced']['sharethis_publisherID'] = array(
    '#title' => t("Insert a publisher key (optional)."),
    '#description' => t("When you install the module, we create a random publisher key.  You can register the key with ShareThis by contacting customer support.  Otherwise, you can go to <a href='http://www.sharethis.com/account'>ShareThis</a> and create an account.<br />Your official publisher key can be found under 'My Account'.<br />It allows you to get detailed analytics about sharing done on your site."),
    '#type' => 'textfield',
    '#default_value' => $publisher
  );
  $form['advanced']['sharethis_late_load'] = array(
    '#title' => t('Late Load'),
    '#description' => t("You can change the order in which ShareThis widget loads on the user's browser. By default the ShareThis widget loader loads as soon as the browser encounters the JavaScript tag; typically in the tag of your page. ShareThis assets are generally loaded from a CDN closest to the user. However, if you wish to change the default setting so that the widget loads after your web-page has completed loading then you simply tick this option."),
    '#type' => 'checkbox',
    '#default_value' => variable_get('sharethis_late_load', FALSE),
  );
  $form['advanced']['sharethis_twitter_suffix'] = array(
    '#title' => t("Twitter Suffix"),
    '#description' => t("Optionally append a Twitter handle, or text, so that you get pinged when someone shares an article. Example: <em>via @YourNameHere</em>"),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharethis_twitter_suffix', ''),
  );
  $form['advanced']['sharethis_twitter_handle'] = array(
    '#title' => t('Twitter Handle'),
    '#description' => t('Twitter handle to use when sharing.'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharethis_twitter_handle', ''),
  );
  $form['advanced']['sharethis_twitter_recommends'] = array(
    '#title' => t('Twitter recommends'),
    '#description' => t('Specify a twitter handle to be recommended to the user.'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharethis_twitter_recommends', ''),
  );
  $form['advanced']['sharethis_option_onhover'] = array(
    '#type' => 'checkbox',
    '#title' => t('Display ShareThis widget on hover'),
    '#description' => t('If disabled, the ShareThis widget will be displayed on click instead of hover.'),
    '#default_value' => variable_get('sharethis_option_onhover', TRUE),
  );
  $form['advanced']['sharethis_option_neworzero'] = array(
    '#type' => 'checkbox',
    '#title' => t('Display count "0" instead of "New"'),
    '#description' => t('Display a zero (0) instead of "New" in the count for content not yet shared.'),
    '#default_value' => variable_get('sharethis_option_neworzero', FALSE),
  );
  $form['advanced']['sharethis_option_shorten'] = array(
    '#type' => 'checkbox',
    '#title' => t('Display short URL'),
    '#description' => t('Display either the full or the shortened URL.'),
    '#default_value' => variable_get('sharethis_option_shorten', TRUE),
  );
  $form['advanced']['sharethis_cns'] = array(
    '#title' => t('<b>CopyNShare </b><sup>(<a href="http://support.sharethis.com/customer/portal/articles/517332-share-widget-faqs#copynshare" target="_blank">?</a>)</sup>'),
    '#type' => 'checkboxes',
    '#prefix' => '<div id="st_cns_settings">',
    '#suffix' => '</div><div class="st_cns_container">
				<p>CopyNShare is the new ShareThis widget feature that enables you to track the shares that occur when a user copies and pastes your website\'s <u>URL</u> or <u>Content</u>. <br/>
				<u>Site URL</u> - ShareThis adds a special #hashtag at the end of your address bar URL to keep track of where your content is being shared on the web.<br/>
				<u>Site Content</u> - It enables the pasting of "See more: YourURL#SThashtag" after user copies-and-pastes text. When a user copies text within your site, a "See more: yourURL.com#SThashtag" will appear after the pasted text. <br/>
				Please refer the <a href="http://support.sharethis.com/customer/portal/articles/517332-share-widget-faqs#copynshare" target="_blank">CopyNShare FAQ</a> for more details.</p>
			</div>',
    '#options' => array(
		'donotcopy' => t('Measure copy & shares of your site\'s Content'),
		'hashaddress' => t('Measure copy & shares of your site\'s URLs'),
		),
    '#default_value' => $current_options_array['sharethis_cns'],
  );

  $form['#submit'][] = 'sharethis_configuration_form_submit';
  return system_settings_form($form);
}

/**
 * Form validation handler for sharethis_configuration_form().
 */
function sharethis_configuration_form_validate($form, &$form_state) {
  //Additional filters for the service option input

  // Sanitize the publisher ID option.  Since it's a text field, remove anything that resembles code
  $form_state['values']['sharethis_service_option'] = filter_xss($form_state['values']['sharethis_service_option'], array());

  //Additional filters for the option extras input
  $form_state['values']['sharethis_option_extras'] = (isset($form_state['values']['sharethis_option_extras'])) ? $form_state['values']['sharethis_option_extras'] : array();

  // Sanitize the publisher ID option.  Since it's a text field, remove anything that resembles code
  $form_state['values']['sharethis_publisherID'] = filter_xss($form_state['values']['sharethis_publisherID'], array());

  if($form_state['values']['sharethis_callesi'] == 1){
	unset($form_state['values']['sharethis_cns']);
  }
  unset($form_state['values']['sharethis_callesi']);

  // Ensure default value for twitter suffix
  $form_state['values']['sharethis_twitter_suffix'] = (isset($form_state['values']['sharethis_twitter_suffix'])) ? $form_state['values']['sharethis_twitter_suffix'] : '';

  // Ensure default value for twitter handle
  $form_state['values']['sharethis_twitter_handle'] = (isset($form_state['values']['sharethis_twitter_handle'])) ? $form_state['values']['sharethis_twitter_handle'] : '';

  // Ensure default value for twitter recommends
  $form_state['values']['sharethis_twitter_recommends'] = (isset($form_state['values']['sharethis_twitter_recommends'])) ? $form_state['values']['sharethis_twitter_recommends'] : '';
}

/**
 * Form submission handler for sharethis_configuration_form().
 */
function sharethis_configuration_form_submit($form, &$form_state) {
  // If the location is changing to/from 'content', clear the Field Info cache.
  $current_location = variable_get('sharethis_location', 'content');
  $new_location = $form_state['values']['sharethis_location'];
  if (($current_location == 'content' || $new_location == 'content') && $current_location != $new_location) {
    field_info_cache_clear();
  }
}

 /**
 * Implements hook_menu().
 *
 * This is the ShareThis Config Menu.
 */
function sharethis_menu() {
  $items['admin/config/services/sharethis'] = array(
    'title' => 'ShareThis',
    'description' => 'Choose the widget, button family, and services for using ShareThis to share content online.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sharethis_configuration_form'),
    'access arguments' => array('administer sharethis')
  );
  return $items;
}

 /**
 * Implements hook_node_view().
 *
 * Inserts ShareThis widget code onto each node view.
 * TODO: Want to add the option somewhere to select nodes.
 *
 * @param node
 *   The node that is being acted upon
 * @param view_mode
 *   The type of view (teaser, full, etc)
 * @param langcode
 *   Information about the language
 */
function sharethis_node_view($node, $view_mode, $langcode) {
  // Don't display if the user is currently searching, or in the RSS feed.
  switch ($view_mode) {
    case 'search_result':
    case 'search_index':
    case 'rss':
      return;
  }
  // First get all of the options for the sharethis widget from the database:
  $data_options = sharethis_get_options_array();

  // Get the full path to insert into the Share Buttons.
  $mPath = url('node/' . $node->nid, array('absolute' => TRUE));
  $mTitle = $node->title;

  // Check where we want to display the ShareThis widget.
  switch (variable_get('sharethis_location', 'content')) {
    case 'content':
      $enabled_types = $data_options['sharethis_node_types'];
      if (isset($enabled_types[$node->type]) && $enabled_types[$node->type] === $node->type) {
        $node->content['sharethis'] = array(
          '#tag' => 'div', // Wrap it in a div.
          '#type' => 'html_tag',
          '#attributes' => array('class' => 'sharethis-buttons'),
          '#value' => theme('sharethis', array('data_options' => $data_options, 'm_path' => $mPath, 'm_title' => $mTitle)),
          '#weight' => intval(variable_get('sharethis_weight', 10)),
        );
      }
    break;
    case 'links':
      $enabled_view_modes = variable_get('sharethis_' . $node->type . '_options', array());
      if (isset($enabled_view_modes[$view_mode]) && $enabled_view_modes[$view_mode]) {
        $links['sharethis'] = array(
          'html' => TRUE,
          'title' => theme('sharethis', array('data_options' => $data_options, 'm_path' => $mPath, 'm_title' => $mTitle)),
          'attributes' => array('class' => 'sharethis-buttons'),
        );
        $node->content['links']['sharethis'] = array(
          '#theme' => 'links',
          '#links' => $links,
          '#attributes' => array(
            'class' => array('links', 'inline'),
          ),
          '#tag' => 'div', // Wrap it in a div.
          '#type' => 'html_tag',
          '#weight' => intval(variable_get('sharethis_weight', 10)),
        );
       }
    break;
  }
}

/**
 * Implements hook_field_extra_fields().
 */
function sharethis_field_extra_fields() {
  $extra = array();
  // Only add extra fields if the location is the node content.
  if (variable_get('sharethis_location', 'content') == 'content') {
    $entity_info = entity_get_info('node');
    foreach ($entity_info['bundles'] as $bundle => $bundle_info) {
      $extra['node'][$bundle]['display'] = array(
        'sharethis' => array(
          'label' => t('ShareThis'),
          'description' => t('ShareThis links'),
          'weight' => intval(variable_get('sharethis_weight', 10)),
        ),
      );
     }
   }
  return $extra;
}

/**
 * Implements hook_theme().
 */
function sharethis_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['sharethis'] = array(
    'variables' => array(
      'data_options' => NULL,
      'm_path' => NULL,
      'm_title' => NULL,
    ),
  );
  return $theme;
}

/**
* get_stLight_options() function is creating options to be passed to stLight.options
* $data_options array is the settings selected by publisher in admin panel
*/
function get_stLight_options($data_options)
{
	// Provide the publisher ID.
	$paramsStLight = array(
		'publisher' => $data_options['publisherID'],
	);
	$paramsStLight['version'] = ($data_options['widget'] == 'st_multi') ? "5x" : "4x";
	if($data_options['sharethis_callesi'] == 0){
		$paramsStLight["doNotCopy"] = !to_boolean($data_options['sharethis_cns']['donotcopy']);
		$paramsStLight["hashAddressBar"] = to_boolean($data_options['sharethis_cns']['hashaddress']);
		if(!($paramsStLight["hashAddressBar"]) && $paramsStLight["doNotCopy"]){
			$paramsStLight["doNotHash"] = true;
		}else{
			$paramsStLight["doNotHash"] = false;
		}
	}
	if (isset($data_options['onhover']) && $data_options['onhover'] == FALSE) {
	   $paramsStLight['onhover'] = FALSE;
	}
    if ($data_options['neworzero']) {
      $paramsStLight['newOrZero'] = "zero";
    }
  if (!$data_options['shorten']) {
    $paramsStLight['shorten'] = 'false';
  }
	$stlight = drupal_json_encode($paramsStLight);

	return $stlight;
}

/**
 * sharethisGetOptionArray is a helper function for DB access.
 *
 * Returns options that have been stored in the database.
 *
 * @TODO: Switch from this function to just straight variable_get() calls.
 */
function sharethis_get_options_array() {
  $default_sharethis_nodetypes = array("article"=>"article", "page"=>"page");
  $view_modes = array();
  foreach (array_keys(node_type_get_types()) as $type) {
    $view_modes[$type] = variable_get('sharethis_' . $type . '_options', $default_sharethis_nodetypes);
  }
  return array(
    'buttons' => variable_get('sharethis_button_option', 'stbc_button'),
    'publisherID' => variable_get('sharethis_publisherID', ''),
    'services' => variable_get('sharethis_service_option', '"Facebook:facebook","Tweet:twitter","LinkedIn:linkedin","Email:email","ShareThis:sharethis","Pinterest:pinterest"'),
    'option_extras' => variable_get('sharethis_option_extras', array("Google Plus One:plusone"=>"Google Plus One:plusone", "Facebook Like:fblike"=>"Facebook Like:fblike")),
    'widget' => variable_get('sharethis_widget_option', 'st_multi'),
    'onhover' => variable_get('sharethis_option_onhover', TRUE),
    'neworzero' => variable_get('sharethis_option_neworzero', FALSE),
    'twitter_suffix' => variable_get('sharethis_twitter_suffix', ''),
    'twitter_handle' => variable_get('sharethis_twitter_handle', ''),
    'twitter_recommends' => variable_get('sharethis_twitter_recommends', ''),
    'late_load' => variable_get('sharethis_late_load', FALSE),
    'view_modes' => $view_modes,
    'sharethis_cns' => variable_get('sharethis_cns',array('donotcopy'=>'0','hashaddress'=>'0')),
	'sharethis_callesi' => (NULL == variable_get('sharethis_cns'))?1:0,
	'sharethis_node_types' => variable_get('sharethis_node_types', $default_sharethis_nodetypes),
    'shorten' => variable_get('sharethis_option_shorten', TRUE),
  );
}

/**
 * Theme function for ShareThis code based on settings.
 */
function theme_sharethis($variables) {
  $data_options = $variables['data_options'];
  $m_path = $variables['m_path'];
  $m_title = $variables['m_title'];

  // Inject the extra services.
  foreach ($data_options['option_extras'] as $service) {
    $data_options['services'] .= ',"' . $service . '"';
  }

  // The share buttons are simply spans of the form class='st_SERVICE_BUTTONTYPE' -- "st" stands for ShareThis.
  $type = drupal_substr($data_options['buttons'], 4);
  $type = $type == "_" ? "" : check_plain($type);
  $service_array = explode(",", $data_options['services']);
  $st_spans = "";
  foreach ($service_array as $service_full) {
    // Strip the quotes from the element in the array (They are there for javascript)
    $service = explode(":", $service_full);

    // Service names are expected to be parsed by Name:machine_name. If only one
    // element in the array is given, it's an invalid service.
    if (count($service) < 2) {
      continue;
    }

    // Find the service code name.
    $serviceCodeName = drupal_substr($service[1], 0, -1);

    // Switch the title on a per-service basis if required.
    $title = $m_title;
    switch ($serviceCodeName) {
      case 'twitter':
        $title = empty($data_options['twitter_suffix']) ? $title : check_plain($title) . ' ' . check_plain($data_options['twitter_suffix']);
        break;
    }

    // Sanitize the service code for display.
    $display = check_plain($serviceCodeName);

    // Put together the span attributes.
    $attributes = array(
      'st_url' => $m_path,
      'st_title' => $title,
      'class' => 'st_' . $display . $type,
    );
    if ($serviceCodeName == 'twitter') {
      if (!empty($data_options['twitter_handle'])) {
        $attributes['st_via'] = $data_options['twitter_handle'];
        $attributes['st_username'] = $data_options['twitter_recommends'];
      }
    }
    // Only show the display text if the type is set.
    if (!empty($type)) {
      $attributes['displayText'] = check_plain($display);
    }
    // Render the span tag.
    $st_spans .= theme('html_tag', array(
      'element' => array(
        '#tag' => 'span',
        '#attributes' => $attributes,
        '#value' => '', // It's an empty span tag.
      ),
    ));
  }


  // Output the embedded JavaScript.
  sharethis_include_js();
  return '<div class="sharethis-wrapper">' . $st_spans . '</div>';
}

/**
 * Include st js scripts.
 */
function sharethis_include_js() {
  $has_run = &drupal_static(__FUNCTION__, FALSE);
  if (!$has_run) {
    // These are the ShareThis scripts:
    $data_options = sharethis_get_options_array();
    $st_js_options = array();
    $st_js_options['switchTo5x'] = $data_options['widget'] == 'st_multi' ? TRUE : FALSE;
    if ($data_options['late_load']) {
      $st_js_options['__st_loadLate'] = TRUE;
    }
    $st_js = "";
    foreach ($st_js_options as $name => $value) {
      $st_js .= 'var ' . $name . ' = ' . drupal_json_encode($value) . ';';
    }
    drupal_add_js($st_js, 'inline');
    
	if((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) {
		$external = "https://ws.sharethis.com/button/buttons.js";
	} else {
		$external = "http://w.sharethis.com/button/buttons.js";
	}

    drupal_add_js($external, 'external');
    
    $stlight = get_stLight_options($data_options);
    $st_js = "if (stLight !== undefined) { stLight.options($stlight); }";
    drupal_add_js($st_js, 'inline');
    
    $has_run = TRUE;
  }
  return $has_run;
}
/**
 * Implements hook_block_info().
 */
function sharethis_block_info() {
  $blocks['sharethis_block'] = array(
    'info' => t('ShareThis'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

/**
 * Implements of hook_block_view().
 */
function sharethis_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'sharethis_block':
      $block['content'] = sharethis_block_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function sharethis_block_contents() {
  if (variable_get('sharethis_location', 'content') == 'block') {
    // First get all of the options for the sharethis widget from the database:
    $data_options = sharethis_get_options_array();
    $path = isset($_GET['q']) ? $_GET['q'] : '<front>';
    if ($path == variable_get('site_frontpage')) {
      $path = "<front>";
    }
    $mPath = url($path, array('absolute' => TRUE));
    $mTitle = decode_entities(drupal_get_title());

    return theme('sharethis', array('data_options' => $data_options, 'm_path' => $mPath, 'm_title' => $mTitle));
  }
}

/**
 * Implements hook_comment_view().
 */
function sharethis_comment_view($comment, $view_mode, $langcode) {
  if (variable_get('sharethis_comments', FALSE)) {
    $data_options = sharethis_get_options_array();
    $path = isset($_GET['q']) ? $_GET['q'] : '<front>';
    $mPath = url($_GET['q'], array(
      'absolute' => TRUE,
      'fragment' => 'comment-' . $comment->cid,
    ));
    $mTitle = decode_entities(drupal_get_title());
    $html = theme('sharethis', array('data_options' => $data_options, 'm_path' => $mPath, 'm_title' => $mTitle));
    $comment->content['sharethis'] = array(
      '#type' => 'html_tag',
      '#value' => $html,
      '#tag' => 'div',
      '#attributes' => array('class' => 'sharethis-comment'),
      '#weight' => intval(variable_get('sharethis_weight', 10)),
    );
  }
}

/**
 * Implements hook_contextual_links_view_alter().
 */
function sharethis_contextual_links_view_alter(&$element, $items) {
  // Add the configuration link for the ShareThis settings on the block itself.
  if (isset($element['#element']['#block']->module) && $element['#element']['#block']->module == 'sharethis' && $element['#element']['#block']->delta == 'sharethis_block' && user_access('access administration pages')) {
    $element['#links']['sharethis-configure'] = array(
      'title' => t('Configure ShareThis'),
      'href' => 'admin/config/services/sharethis',
    );
  }
}

/**
 * Implements hook_views_api().
 */
function sharethis_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'sharethis') . '/views',
  );
}

/**
 * Implements of hook_ctools_plugin_directory
 */
function sharethis_ctools_plugin_directory($module, $plugin) {
  if ($module == 'panels' || $module == 'ctools') {
    return 'plugins/' . $plugin;
  }
}
