You are here

getdirections.module in Get Directions 7.3

Fetches google map directions.

File

getdirections.module
View source
<?php

/**
 * @file
 * Fetches google map directions.
 */
define('GETDIRECTIONS_PATH', drupal_get_path('module', 'getdirections'));

/**
 * Implements hook_help().
 */
function getdirections_help($path, $arg) {
  switch ($path) {
    case 'admin/help#getdirections':
      $output = '<p>' . t('Fetches google map directions.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_init().
 */
function getdirections_init() {
  if (!module_load_include('inc', 'getdirections', 'getdirections.config')) {
    define('GETDIRECTIONS_WAYPOINTS_MAX', 8);
  }
  module_load_include('inc', 'getdirections', 'getdirections.api');
  if (module_exists('colorbox')) {
    $getdirections_colorbox = variable_get('getdirections_colorbox', array(
      'enable' => 0,
      'width' => 600,
      'height' => 600,
    ));
    $settings = array(
      'getdirections_colorbox' => $getdirections_colorbox,
    );
    drupal_add_js($settings, 'setting');
    drupal_add_js(GETDIRECTIONS_PATH . '/js/getdirections.js');
  }
}

/**
 * Implements hook_permission().
 */
function getdirections_permission() {
  return array(
    'access gmap getdirections' => array(
      'title' => t('Access Getdirections'),
      'description' => t('View and use the Getdirections module.'),
    ),
    'access user getdirections' => array(
      'title' => t('Access user Getdirections'),
      'description' => t('View users with the Getdirections module.'),
    ),
  );
}

/**
 * Implement hook_menu().
 */
function getdirections_menu() {
  $items = array();
  $items['admin/config/services/getdirections'] = array(
    'title' => 'Get directions',
    'description' => 'Configure Get directions',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'getdirections_settings_form',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'getdirections.admin.inc',
  );
  $items['getdirections'] = array(
    'title' => 'Get directions',
    'description' => 'Get directions on a map',
    'access arguments' => array(
      'access gmap getdirections',
    ),
    'page callback' => 'getdirections_direction',
    'type' => MENU_SUGGESTED_ITEM,
  );

  // location enabled
  $items['getdirections/location/%getdirections_fromto/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_node_setlocation',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/locations/%getdirections_id/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_node_setlocations',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/locations_via/%getdirections_via'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_node_setlocations_via',
    'page arguments' => array(
      2,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/location_user/%getdirections_fromto/%getdirections_uid'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_user_location',
    'page callback' => 'getdirections_user_setlocation',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/locations_user/%getdirections_uid/%getdirections_uid'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_user_location',
    'page callback' => 'getdirections_user_setlocations',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/location_n2u/%getdirections_id/%getdirections_uid'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_user_location',
    'page callback' => 'getdirections_n2u_setlocation',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/location_u2n/%getdirections_uid/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_user_location',
    'page callback' => 'getdirections_u2n_setlocation',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/locations_user_via/%getdirections_via'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_user_setlocations_via',
    'page arguments' => array(
      2,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/latlon/%getdirections_fromto/%getdirections_latlon/%'] = array(
    'title' => 'Get directions',
    'access arguments' => array(
      'access gmap getdirections',
    ),
    'page callback' => 'getdirections_latlon',
    'page arguments' => array(
      2,
      3,
      4,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/latlons/%'] = array(
    'title' => 'Get directions',
    'access arguments' => array(
      'access gmap getdirections',
    ),
    'page callback' => 'getdirections_latlons',
    'page arguments' => array(
      2,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/location_id/%getdirections_fromto/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_setlocation_id',
    'page arguments' => array(
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  if (getdirections_get_vocabularies()) {

    // taxonomy_term
    $items['getdirections/location_term/%getdirections_fromto/%getdirections_id'] = array(
      'title' => 'Get directions',
      'access callback' => 'getdirections_access_location',
      'page callback' => 'getdirections_term_setlocation',
      'page arguments' => array(
        2,
        3,
      ),
      'type' => MENU_CALLBACK,
    );
  }
  if (getdirections_check_entity_type('comment')) {

    // comment
    $items['getdirections/location_comment/%getdirections_fromto/%getdirections_id'] = array(
      'title' => 'Get directions',
      'access callback' => 'getdirections_access_location',
      'page callback' => 'getdirections_comment_setlocation',
      'page arguments' => array(
        2,
        3,
      ),
      'type' => MENU_CALLBACK,
    );
  }
  $items['getdirections/%getdirections_entity_type/%getdirections_fromto/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_entity_setlocation',
    'page arguments' => array(
      1,
      2,
      3,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections/%getdirections_entity_type/%getdirections_id/%getdirections_entity_type/%getdirections_id'] = array(
    'title' => 'Get directions',
    'access callback' => 'getdirections_access_location',
    'page callback' => 'getdirections_entity_setlocations',
    'page arguments' => array(
      1,
      2,
      3,
      4,
    ),
    'type' => MENU_CALLBACK,
  );
  $items['getdirections_box'] = array(
    'title' => 'Get directions',
    'access arguments' => array(
      'access gmap getdirections',
    ),
    'page callback' => 'getdirections_direction_box',
    'type' => MENU_CALLBACK,
  );
  if (module_exists('date_popup')) {
    $items['getdirections/getdirections_get_datestamp'] = array(
      'access arguments' => array(
        'access gmap getdirections',
      ),
      'page callback' => 'getdirections_get_datestamp',
      'type' => MENU_CALLBACK,
    );
  }
  if (module_exists('smart_ip')) {
    $items['getdirections/smart_ip'] = array(
      'page callback' => 'getdirections_smart_ip',
      'access arguments' => array(
        'access content',
      ),
      'type' => MENU_CALLBACK,
    );
  }
  if (module_exists('ip_geoloc')) {
    $items['getdirections/ip_geoloc'] = array(
      'page callback' => 'getdirections_ip_geoloc',
      'access arguments' => array(
        'access content',
      ),
      'type' => MENU_CALLBACK,
    );
  }
  return $items;
}

/**
 * menu placeholder functions
 */
function getdirections_fromto_load($arg) {
  $allowed = array(
    'from',
    'to',
  );
  return in_array($arg, $allowed) ? $arg : FALSE;
  return $arg;
}
function getdirections_id_load($arg) {
  return is_numeric($arg) && $arg > 0 ? $arg : FALSE;
}
function getdirections_uid_load($arg) {
  return is_numeric($arg) && $arg > 0 && getdirections_user_check($arg) ? $arg : FALSE;
}
function getdirections_via_load($arg) {
  if (stristr($arg, ',')) {
    $x = explode(',', $arg);
    foreach ($x as $v) {
      if (!is_numeric($v)) {
        return FALSE;
      }
    }
    return $arg;
  }
  return FALSE;
}
function getdirections_latlon_load($arg) {
  if (getdirections_latlon_check($arg)) {
    return $arg;
  }
  return FALSE;
}
function getdirections_entity_type_load($arg) {
  if (getdirections_check_entity_type($arg)) {
    return $arg;
  }
  return FALSE;
}

/**
 * menu access functions
 */
function getdirections_access_location() {
  if (user_access('access gmap getdirections')) {
    if (getdirections_get_current_supported_module()) {
      return TRUE;
    }
  }
  return FALSE;
}
function getdirections_access_user_location() {
  if (user_access('access user getdirections') && getdirections_check_entity_type('user')) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Optional. The direction the supplied input applies to
 * @param string $location
 *   Optional. The string to search with
 * @param string $country
 *   Optional. The country
 * @param string $latlon
 *   Optional. Comma delimited string containing latitude and longitude
 * @return
 *   Returns the themed map and form
 */
function getdirections_direction($direction = '', $location = '', $country = '', $latlon = '', $entity_id = 0, $entity_type = 'node', $width = '', $height = '') {
  if (!getdirections_check()) {
    return t('You need to !c first.', array(
      '!c' => l('configure Getdirections', 'admin/config/services/getdirections'),
    ));
  }
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  getdirections_setup_map($getdirections_defaults, $getdirections_misc);
  $getdirections_settings = getdirections_get_settings($getdirections_defaults, $getdirections_misc);
  $mapid = getdirections_get_key();
  drupal_add_js(array(
    'getdirections' => array(
      $mapid => $getdirections_settings,
    ),
  ), 'setting');
  if ($getdirections_misc['keep_title'] && $entity_id && $direction) {
    if ($direction == 'to') {
      $direction_translated = t('to');
    }
    elseif ($direction == 'from') {
      $direction_translated = t('from');
    }

    // entityfy this
    if ($entity_type == 'term') {
      $entity_type = 'taxonomy_term';
    }

    // is it location enabled?
    if (getdirections_check_entity_type($entity_type)) {
      $entity_get_info = entity_get_info($entity_type);
      if ($entity_get_info['fieldable']) {
        $load_hook = $entity_get_info['load hook'];
        $entity = $load_hook($entity_id);
        $entity_title = '';
        if (isset($entity_get_info['entity keys']['label'])) {
          $entity_title = $entity_get_info['entity keys']['label'];
        }
        elseif ($entity_type == 'user') {
          $entity_title = 'name';
        }
        if (isset($entity->{$entity_title})) {
          $title = $entity->{$entity_title};
          drupal_set_title(t('Get directions @d !t', array(
            '@d' => $direction_translated,
            '!t' => $title,
          )));
        }
      }
    }
  }
  if (empty($width)) {
    $width = $getdirections_defaults['width'];
  }
  if (empty($height)) {
    $height = $getdirections_defaults['height'];
  }

  // remove brackets if any
  $latlon = preg_replace("/^\\(|\\)\$/", '', $latlon);
  $raw_form = drupal_get_form('getdirections_direction_form', $mapid, $direction, $location, $country, $latlon);
  $form = render($raw_form);
  return theme('getdirections_show', array(
    'form' => $form,
    'mapid' => $mapid,
    'width' => $width,
    'height' => $height,
    'entity_id' => $entity_id,
    'entity_type' => $entity_type,
  ));
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Optional. The direction the supplied input applies to
 * @param string $location
 *   Optional. The string to search with
 * @param string $country
 *   Optional. The country
 * @param string $latlon
 *   Optional. Comma delimited string containing latitude and longitude
 * @param int $lid
 *   Optional. location identifier
 * @param $type
 *   Optional. Used to distinguish various sources
 * @return
 *   Returns the themed map and form
 */
function getdirections_direction_other($direction = '', $location = '', $country = '', $latlon = '', $lid = 0, $type = '', $width = '', $height = '') {
  if (!getdirections_check()) {
    return t('You need to !c first.', array(
      '!c' => l('configure Getdirections', 'admin/config/services/getdirections'),
    ));
  }
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  getdirections_setup_map($getdirections_defaults, $getdirections_misc);
  $getdirections_settings = getdirections_get_settings($getdirections_defaults, $getdirections_misc);
  $mapid = getdirections_get_key();
  drupal_add_js(array(
    'getdirections' => array(
      $mapid => $getdirections_settings,
    ),
  ), 'setting');
  if ($getdirections_misc['keep_title'] && $lid && $direction) {
    if ($type == 'location') {
      if ($direction == 'to') {
        $direction_translated = t('to');
      }
      elseif ($direction == 'from') {
        $direction_translated = t('from');
      }
      $t = getdirections_get_lid_title($lid);
      if ($t) {
        drupal_set_title(t('Get directions @d !t', array(
          '@d' => $direction_translated,
          '!t' => $t,
        )));
      }
    }
  }
  if (empty($width)) {
    $width = $getdirections_defaults['width'];
  }
  if (empty($height)) {
    $height = $getdirections_defaults['height'];
  }

  // remove brackets if any
  $latlon = preg_replace("/^\\(|\\)\$/", '', $latlon);
  $raw_form = drupal_get_form('getdirections_direction_form', $mapid, $direction, $location, $country, $latlon);
  $form = render($raw_form);
  return theme('getdirections_show', array(
    'form' => $form,
    'mapid' => $mapid,
    'width' => $width,
    'height' => $height,
    'entity_id' => 0,
    'entity_type' => '',
    'lid' => $lid,
    'type' => $type,
  ));
}

/**
 * Function to setup the map
 *
 * @param string $fromlocs
 *   Required. The string to display for From.
 * @param string $fromlatlon
 *   Required. The location point for From. In decimal latitude,longitude
 * @param string $tolocs
 *   Required. The string to display for To.
 * @param string $tolatlon
 *   Required. The location point for To. In decimal latitude,longitude
 * @return
 *   Returns the themed map.
 */
function getdirections_locations($fromlocs, $fromlatlon, $tolocs, $tolatlon, $width = '', $height = '') {
  if (!getdirections_check()) {
    return t('You need to !c first.', array(
      '!c' => l('configure Getdirections', 'admin/config/services/getdirections'),
    ));
  }
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  getdirections_setup_map($getdirections_defaults, $getdirections_misc);
  $getdirections_settings = getdirections_get_settings($getdirections_defaults, $getdirections_misc);

  // remove brackets if any
  $fromlatlon = preg_replace("/^\\(|\\)\$/", '', $fromlatlon);
  $getdirections_settings['fromlatlon'] = $fromlatlon;
  $tolatlon = preg_replace("/^\\(|\\)\$/", '', $tolatlon);
  $getdirections_settings['tolatlon'] = $tolatlon;
  $mapid = getdirections_get_key();
  drupal_add_js(array(
    'getdirections' => array(
      $mapid => $getdirections_settings,
    ),
  ), 'setting');
  if (empty($width)) {
    $width = $getdirections_defaults['width'];
  }
  if (empty($height)) {
    $height = $getdirections_defaults['height'];
  }
  return theme('getdirections_show_locations', array(
    'mapid' => $mapid,
    'width' => $width,
    'height' => $height,
    'fromlocs' => $fromlocs,
    'tolocs' => $tolocs,
  ));
}

/**
 * Function to setup the map
 *
 * @param array $locs
 *   Required. An array of location descriptions.
 * @param array $latlons
 *   Required. An array of decimal latitude,longitude
 * @return
 *   Returns the themed map.
 */
function getdirections_locations_via($locs, $latlons, $width = '', $height = '') {
  if (!getdirections_check()) {
    return t('You need to !c first.', array(
      '!c' => l('configure Getdirections', 'admin/config/services/getdirections'),
    ));
  }
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  getdirections_setup_map($getdirections_defaults, $getdirections_misc);
  $getdirections_settings = getdirections_get_settings($getdirections_defaults, $getdirections_misc);
  $getdirections_settings['latlons'] = implode('|', $latlons);
  $mapid = getdirections_get_key();
  drupal_add_js(array(
    'getdirections' => array(
      $mapid => $getdirections_settings,
    ),
  ), 'setting');
  if (empty($width)) {
    $width = $getdirections_defaults['width'];
  }
  if (empty($height)) {
    $height = $getdirections_defaults['height'];
  }
  return theme('getdirections_show_locations_via', array(
    'mapid' => $mapid,
    'width' => $width,
    'height' => $height,
    'locs' => $locs,
  ));
}

/**
 *
 *
 */
function getdirections_get_settings($getdirections_defaults, $getdirections_misc) {
  global $language, $is_https;
  $lla = explode(',', $getdirections_defaults['latlong']);
  $settings = array(
    'lat' => $lla[0],
    'lng' => $lla[1],
    'zoom' => $getdirections_defaults['zoom'],
    'controltype' => $getdirections_defaults['controltype'],
    'pancontrol' => $getdirections_defaults['pancontrol'],
    'mtc' => $getdirections_defaults['mtc'],
    'maptype' => $getdirections_defaults['maptype'],
    'baselayers' => $getdirections_defaults['baselayers'],
    'unitsystem' => $getdirections_defaults['unitsystem'],
    'scale' => $getdirections_defaults['scale'],
    'overview' => $getdirections_defaults['overview'],
    'overview_opened' => $getdirections_defaults['overview_opened'],
    'scrollwheel' => $getdirections_defaults['scrollwheel'],
    'draggable' => $getdirections_defaults['draggable'],
    'streetview_show' => $getdirections_defaults['streetview_show'],
    'transit_date_format' => $getdirections_defaults['transit_date_format'],
    'map_backgroundcolor' => $getdirections_defaults['map_backgroundcolor'],
    'waypoints' => intval($getdirections_defaults['waypoints']),
    'waypoints_optimise' => intval($getdirections_defaults['waypoints_optimise']),
    'waypoint_color' => $getdirections_defaults['waypoint_color'],
    'advanced_autocomplete' => $getdirections_defaults['advanced_autocomplete'],
    'advanced_autocomplete_bias' => $getdirections_defaults['advanced_autocomplete_bias'],
    'advanced_autocomplete_via' => $getdirections_defaults['advanced_autocomplete_via'],
    'panoramio_use' => $getdirections_misc['panoramio_use'],
    'panoramio_show' => $getdirections_misc['panoramio_show'],
    'panoramio_state' => $getdirections_misc['panoramio_state'],
    'bicycleinfo' => $getdirections_misc['bicycleinfo'],
    'bicycleinfo_state' => $getdirections_misc['bicycleinfo_state'],
    'transitinfo' => $getdirections_misc['transitinfo'],
    'transitinfo_state' => $getdirections_misc['transitinfo_state'],
    'trafficinfo' => $getdirections_misc['trafficinfo'],
    'trafficinfo_state' => $getdirections_misc['trafficinfo_state'],
    'geolocation_enable' => $getdirections_misc['geolocation_enable'],
    'geolocation_option' => $getdirections_misc['geolocation_option'],
    'show_distance' => $getdirections_misc['show_distance'] ? t('Total distance') : '',
    'show_duration' => $getdirections_misc['show_duration'] ? t('Total duration') : '',
    'weather_use' => $getdirections_misc['weather_use'],
    'weather_show' => $getdirections_misc['weather_show'],
    'weather_state' => $getdirections_misc['weather_state'],
    'weather_temp' => $getdirections_misc['weather_temp'],
    'weather_speed' => $getdirections_misc['weather_speed'],
    'weather_label' => $getdirections_misc['weather_label'],
    'weather_cloud' => $getdirections_misc['weather_cloud'],
    'weather_cloud_state' => $getdirections_misc['weather_cloud_state'],
    'weather_clickable' => $getdirections_misc['weather_clickable'],
    'weather_info' => $getdirections_misc['weather_info'],
    'switchfromto' => $getdirections_misc['switchfromto'],
    'use_https' => $is_https ? 1 : 0,
    'mylocale' => $language->language,
    'smartip_callback_url' => url("getdirections/smart_ip"),
    'ip_geoloc_callback_url' => url("getdirections/ip_geoloc"),
    'nokeyboard' => $getdirections_defaults['nokeyboard'],
    'nodoubleclickzoom' => $getdirections_defaults['nodoubleclickzoom'],
    'uselatlons' => $getdirections_defaults['uselatlons'],
  );
  return $settings;
}

/**
 *
 *
 */
function getdirections_get_key() {
  static $getdirections_mapid = 0;
  $getdirections_mapid++;
  return 'key_' . $getdirections_mapid;
}

/**
 * Function to setup the form
 *
 * @param string $fromto
 *   Optional. The direction the supplied input applies to
 * @param string $loc
 *   Optional. The string to search with
 * @param string $country
 *   Optional. The country
 * @param string $latlon
 *   Optional. Comma delimited string containing latitude and longitude
 * @return
 *   Returns the form
 */
function getdirections_direction_form($form, &$form_state, $mapid, $fromto = '', $loc = '', $country = '', $latlon = '') {
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  $form = array();
  $form += _getdirections_direction_form($getdirections_defaults, $getdirections_misc, $mapid, $fromto, $loc, $country, $latlon);
  return $form;
}

/**
 *
 *
 */
function _getdirections_direction_form($defaults, $misc, $mapid, $fromto = '', $loc = '', $country = '', $latlon = '') {
  $islocation = module_exists('location');
  $isgetlocations_fields = module_exists('getlocations_fields');
  if ($defaults['use_country_dropdown'] && ($islocation || $isgetlocations_fields) && !$defaults['advanced_autocomplete']) {
    $default_country = $islocation ? variable_get('location_default_country', '') : variable_get('site_default_country', '');
    $countries = array(
      '#type' => 'select',
      '#title' => t('Country'),
      '#options' => array_merge(array(
        '' => t('Please select'),
      ), $islocation ? _location_supported_countries() : getlocations_fields_get_countries_list()),
      '#default_value' => $default_country,
    );
  }

  // weights
  if ($defaults['use_advanced']) {
    $from_country_weight = 1;
    $from_weight = 2;
    $to_country_weight = 3;
    $to_weight = 4;
  }
  else {
    $from_weight = 1;
    $from_country_weight = 2;
    $to_weight = 3;
    $to_country_weight = 4;
  }
  $form = array(
    '#action' => '#',
    '#attributes' => array(
      'class' => array(
        'getdirections_form',
      ),
    ),
  );
  if ($fromto == 'from') {
    $form['from_' . $mapid] = array(
      '#type' => 'hidden',
      '#value' => $latlon,
    );
    if (empty($loc)) {
      if (empty($country)) {
        $mfrom = t('Starting point');
      }
      else {
        $mfrom = drupal_strtoupper($country);
      }
    }
    else {
      $mfrom = $loc;
      $form['from_address_' . $mapid] = array(
        '#type' => 'hidden',
        '#value' => $loc,
      );
    }
    $form['mfrom'] = array(
      '#type' => 'item',
      '#title' => t('From'),
      '#markup' => $mfrom,
    );
  }
  else {
    $from_desc = t('Enter the address, postcode and/or city and country from where you want to start your journey.');
    if ($defaults['use_advanced'] && $defaults['advanced_autocomplete']) {
      $from_desc = t('Start typing the address of your starting point, then select from the dropdown menu.');
    }
    if ($defaults['use_country_dropdown'] && ($islocation || $isgetlocations_fields) && !$defaults['advanced_autocomplete']) {
      $form['country_from_' . $mapid] = $countries;
      $form['country_from_' . $mapid]['#weight'] = $from_country_weight;
      $from_desc = t('Enter the address, postcode and/or city from where you want to start your journey.');
    }
    $form['from_' . $mapid] = array(
      '#type' => 'textfield',
      '#title' => t('Starting from'),
      '#size' => $defaults['from_width'],
      '#required' => TRUE,
      '#description' => $from_desc,
      '#weight' => $from_weight,
    );
  }
  if ($fromto == 'to') {
    $form['to_' . $mapid] = array(
      '#type' => 'hidden',
      '#value' => $latlon,
    );
    if (empty($loc)) {
      if (empty($country)) {
        $mto = t('Destination');
      }
      else {
        $mto = drupal_strtoupper($country);
      }
    }
    else {
      $mto = $loc;
      $form['to_address_' . $mapid] = array(
        '#type' => 'hidden',
        '#value' => $loc,
      );
    }
    $form['mto'] = array(
      '#type' => 'item',
      '#title' => t('To'),
      '#markup' => $mto,
    );
  }
  else {
    $to_desc = t('Enter the address, postcode and/or city and country of your journey destination.');
    if ($defaults['use_advanced'] && $defaults['advanced_autocomplete']) {
      $to_desc = t('Start typing the address of your destination, then select from the dropdown menu.');
    }
    if ($defaults['use_country_dropdown'] && ($islocation || $isgetlocations_fields) && !$defaults['advanced_autocomplete']) {
      $form['country_to_' . $mapid] = $countries;
      $form['country_to_' . $mapid]['#weight'] = $to_country_weight;
      $to_desc = t('Enter the address, postcode and/or city of your journey destination.');
    }
    $form['to_' . $mapid] = array(
      '#type' => 'textfield',
      '#title' => t('Destination'),
      '#size' => $defaults['to_width'],
      '#required' => TRUE,
      '#description' => $to_desc,
      '#weight' => $to_weight,
    );
  }
  $wt = 6;
  if ($defaults['travelmode_show']) {
    $form['travelmode_' . $mapid] = array(
      '#type' => 'select',
      '#title' => t('Travel mode'),
      '#options' => array(
        'driving' => t('Driving'),
        'walking' => t('Walking'),
        'bicycling' => t('Bicycling'),
        'transit' => t('Public transport'),
      ),
      '#default_value' => 'driving',
      '#weight' => $wt,
    );
    $wt = $wt + 2;
    if (module_exists('date_popup')) {
      $form['transit_date_select_' . $mapid] = array(
        '#type' => 'select',
        '#title' => t('Date select'),
        '#options' => array(
          'depart' => t('Departure time'),
          'arrive' => t('Arrival time'),
        ),
        '#default_value' => 'depart',
        '#prefix' => '<div id="getdirections_transit_dates_wrapper_' . $mapid . '">',
        '#weight' => $wt,
      );
      $wt = $wt + 2;
      if ($defaults['transit_date_format'] == 'int') {
        $fmt = 'j/n/Y H:i';
      }
      else {
        $fmt = 'n/j/Y H:i';
      }
      $form['transit_dates_' . $mapid] = array(
        '#type' => 'date_popup',
        '#default_value' => '',
        '#date_year_range' => '-0:+1',
        '#date_format' => $fmt,
        '#mindate' => "+0",
        '#suffix' => '</div>',
        '#weight' => $wt,
      );
      $wt = $wt + 2;
    }
  }
  if ($defaults['travelextras_show']) {
    $form['travelextras_' . $mapid] = array(
      '#type' => 'checkboxes',
      '#title' => t('Travel options'),
      '#options' => array(
        'avoidhighways' => t('Avoid Highways'),
        'avoidtolls' => t('Avoid Tolls'),
        'avoidferries' => t('Avoid Ferries'),
        'altroute' => t('Alternative routes'),
      ),
      '#weight' => $wt,
    );
    $wt = $wt + 2;
  }
  if ($defaults['use_advanced'] && $defaults['advanced_autocomplete'] && $defaults['waypoints'] > 0 && $defaults['advanced_autocomplete_via'] && !$defaults['advanced_alternate']) {
    for ($ct = 1; $ct <= $defaults['waypoints']; $ct++) {
      $form['via_autocomplete_' . $mapid . '_' . $ct] = array(
        '#type' => 'textfield',
        '#title' => t('Via !c', array(
          '!c' => $ct,
        )),
        '#size' => $defaults['advanced_autocomplete_via_width'],
        '#weight' => $wt,
      );
      $wt = $wt + 2;
    }
  }
  if ($misc['switchfromto'] && !$fromto && !$defaults['use_advanced']) {
    $form['switchfromto_' . $mapid] = array(
      '#type' => 'markup',
      '#markup' => '<input type="button" id="getdirections_togglefromto_' . $mapid . '" class="switchfromto" name="op" value="' . t('Switch From/To') . '">',
      '#weight' => $wt,
    );
    $wt = $wt + 2;
  }

  // mapid for use in theme
  $form['mapid'] = array(
    '#type' => 'value',
    '#value' => $mapid,
  );
  if ($defaults['use_advanced'] && !$defaults['advanced_autocomplete']) {
    $form['next_' . $mapid] = array(
      '#type' => 'button',
      '#value' => t('Next'),
      '#attributes' => array(
        'onclick' => 'Drupal.getdirections.nextbtn(); return false;',
      ),
      '#weight' => $wt,
    );
    $wt = $wt + 2;
  }
  $form['submit_' . $mapid] = array(
    '#type' => 'button',
    '#value' => t('Get Directions'),
    '#weight' => $wt,
  );
  return $form;
}

/**
 * Some defaults.
 */
function getdirections_defaults() {
  global $is_https;
  $defaults = array(
    'width' => '300px',
    'height' => '200px',
    'latlong' => '40,0',
    'zoom' => 3,
    'controltype' => 'small',
    'pancontrol' => 1,
    'mtc' => 'standard',
    'maptype' => 'Map',
    'baselayers' => array(
      'Map' => 1,
      'Satellite' => 1,
      'Hybrid' => 1,
      'Physical' => 1,
      'OpenStreetMap' => 0,
    ),
    'unitsystem' => 'metric',
    'scale' => 0,
    'overview' => 0,
    'overview_opened' => 0,
    'scrollwheel' => 0,
    'draggable' => 1,
    'streetview_show' => 0,
    'travelmode_show' => 0,
    'transit_dates' => 0,
    'transit_date_format' => 'int',
    'travelextras_show' => 0,
    'map_backgroundcolor' => '',
    'from_width' => 20,
    'to_width' => 20,
    'use_country_dropdown' => 1,
    'use_advanced' => 0,
    'waypoints' => 0,
    'waypoints_optimise' => 0,
    'waypoint_color' => 'white',
    'advanced_autocomplete' => 0,
    'advanced_autocomplete_bias' => 0,
    'advanced_autocomplete_via' => 0,
    'advanced_autocomplete_via_width' => 20,
    'advanced_alternate' => 0,
    'use_https' => $is_https ? 1 : 0,
    'nokeyboard' => 0,
    'nodoubleclickzoom' => 0,
    'region_bias' => variable_get('site_default_country', ''),
    'uselatlons' => 0,
  );
  $getdirections_defaults = variable_get('getdirections_default', array());

  // remove old stuff
  if (isset($getdirections_defaults['behavior'])) {
    if (isset($getdirections_defaults['behavior']['scale'])) {
      $getdirections_defaults['scale'] = $getdirections_defaults['behavior']['scale'];
    }
    if (isset($getdirections_defaults['behavior']['scrollwheel'])) {
      $getdirections_defaults['scrollwheel'] = $getdirections_defaults['behavior']['scrollwheel'];
    }
    if (isset($getdirections_defaults['behavior']['draggable'])) {
      $getdirections_defaults['draggable'] = $getdirections_defaults['behavior']['draggable'];
    }
    if (isset($getdirections_defaults['behavior']['overview'])) {
      $getdirections_defaults['overview'] = $getdirections_defaults['behavior']['overview'];
    }
    if (isset($getdirections_defaults['behavior']['overview_opened'])) {
      $getdirections_defaults['overview_opened'] = $getdirections_defaults['behavior']['overview_opened'];
    }
    unset($getdirections_defaults['behavior']);
  }
  $newdefaults = getdirections_adjust_vars($defaults, $getdirections_defaults);
  return $newdefaults;
}

/**
 *
 *
 */
function getdirections_returnlink_defaults() {
  $defaults = array(
    'node_enable' => 0,
    'node_link' => t('Return to page'),
    'user_enable' => 0,
    'user_link' => t('Return to page'),
    'taxonomy_term_enable' => 0,
    'taxonomy_term_link' => t('Return to page'),
    'comment_enable' => 0,
    'comment_link' => t('Return to page'),
  );
  $getdirections_returnlink_defaults = variable_get('getdirections_returnlink', array());
  $newdefaults = getdirections_adjust_vars($defaults, $getdirections_returnlink_defaults);
  return $newdefaults;
}

/**
 *
 *
 */
function getdirections_colorbox_defaults() {
  $defaults = array(
    'enable' => 0,
    'width' => 600,
    'height' => 600,
  );
  $getdirections_colorbox_defaults = variable_get('getdirections_colorbox', array());
  $newdefaults = getdirections_adjust_vars($defaults, $getdirections_colorbox_defaults);
  return $newdefaults;
}

/**
 *
 *
 */
function getdirections_misc_defaults() {
  $defaults = array(
    'keep_title' => 0,
    'show_distance' => 0,
    'trafficinfo' => 0,
    'trafficinfo_state' => 0,
    'bicycleinfo' => 0,
    'bicycleinfo_state' => 0,
    'switchfromto' => 0,
    'show_duration' => 0,
    'panoramio_use' => 0,
    'panoramio_show' => 0,
    'panoramio_state' => 0,
    'transitinfo' => 0,
    'transitinfo_state' => 0,
    'geolocation_enable' => 0,
    'geolocation_option' => 1,
    'geolocation_mobile_check' => 1,
    'weather_use' => 0,
    'weather_show' => 0,
    'weather_state' => 0,
    'weather_temp' => 1,
    'weather_speed' => 1,
    'weather_label' => 0,
    'weather_cloud' => 1,
    'weather_cloud_state' => 0,
    'weather_clickable' => 1,
    'weather_info' => 1,
  );
  $getdirections_misc_defaults = variable_get('getdirections_misc', array());
  $newdefaults = getdirections_adjust_vars($defaults, $getdirections_misc_defaults);
  return $newdefaults;
}

/**
 * Function to setup the map
 *
 * @param string $entity_type
 *   Required. The Entity type, eg node, user etc
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $entity_id
 *   Required. The entity identifier.
 * @return
 *   Returns the themed map
 */
function getdirections_entity_setlocation($entity_type, $direction, $entity_id, $width = '', $height = '') {
  if (is_numeric($entity_id) && $entity_id && getdirections_check_entity_type($entity_type)) {
    $location = getdirections_load_locations($entity_id, $entity_type);
    if (count($location)) {
      $country = isset($location[0]['country']) ? $location[0]['country'] : '';
      $latlon = $location[0]['latitude'] . ',' . $location[0]['longitude'];

      // sanity check
      if (!getdirections_latlon_check($latlon)) {
        watchdog('getdirections', 'Lat, Lon failed for !e id !nid', array(
          '!e' => $entity_type,
          '!nid' => $entity_id,
        ), WATCHDOG_WARNING);
        $latlon = getdirections_load_latlon_defaults();
      }

      // $locs only used for display now
      $locs = _getdirections_loadaddress($location[0]);
      $content = getdirections_direction($direction, $locs, $country, $latlon, $entity_id, $entity_type, $width, $height);
      return $content;
    }
  }
  return getdirections_direction();
}

// backwards compat
function getdirections_setlocation($direction, $nid, $width = '', $height = '') {
  return getdirections_entity_setlocation('node', $direction, $nid, $width, $height);
}

/**
 * Function to setup the map
 *
 * @param string $from_entity_type
 *   Required.  The Entity type of the starting point, eg node, user etc
 * @param int $from_entity_id
 *   Required. The identifier of the starting point.
 * @param string $from_entity_type
 *   Required.  The Entity type of the destination, eg node, user etc
 * @param int $from_entity_id
 *   Required. The identifier of the destination.
 *
 * @return
 *   Returns the themed map
 */
function getdirections_entity_setlocations($from_entity_type, $from_entity_id, $to_entity_type, $to_entity_id, $width = '', $height = '') {
  if (is_numeric($from_entity_id) && $from_entity_id && is_numeric($to_entity_id) && $to_entity_id && getdirections_check_entity_type($from_entity_type) && getdirections_check_entity_type($to_entity_type)) {

    // from
    $from_location = getdirections_load_locations($from_entity_id, $from_entity_type);
    if (count($from_location)) {
      $from_latlon = $from_location[0]['latitude'] . ',' . $from_location[0]['longitude'];

      // sanity check
      if (!getdirections_latlon_check($from_latlon)) {
        watchdog('getdirections', 'Lat, Lon failed for !e id !nid', array(
          '!e' => $from_entity_type,
          '!nid' => $from_entity_id,
        ), WATCHDOG_WARNING);
        $from_latlon = getdirections_load_latlon_defaults();
      }
      $from_locs = _getdirections_loadaddress($from_location[0]);

      // to
      $to_location = getdirections_load_locations($to_entity_id, $to_entity_type);
      if (count($to_location)) {
        $to_latlon = $to_location[0]['latitude'] . ',' . $to_location[0]['longitude'];

        // sanity check
        if (!getdirections_latlon_check($to_latlon)) {
          watchdog('getdirections', 'Lat, Lon failed for !e id !nid', array(
            '!e' => $to_entity_type,
            '!nid' => $to_entity_id,
          ), WATCHDOG_WARNING);
          $to_latlon = getdirections_load_latlon_defaults();
        }
        $to_locs = _getdirections_loadaddress($to_location[0]);
        $content = getdirections_locations($from_locs, $from_latlon, $to_locs, $to_latlon, $width, $height);
        return $content;
      }
    }
  }
  return getdirections_direction();
}

/**
 * Function to setup the map to display waypoints
 *
 * @param string $entity_ids
 *   Required. A comma delimited list of identifiers
 * @param string $from_entity_type
 *   Required.  The Entity type of the points, eg node, user etc
 * @return
 *   Returns the themed map
 */
function getdirections_entity_setlocations_via($entity_ids, $entity_type, $width = '', $height = '') {

  // $entity_ids is a comma delimeted list
  $arr_entity_ids = explode(',', $entity_ids);
  foreach ($arr_entity_ids as $key => $entity_id) {
    if ($key > GETDIRECTIONS_WAYPOINTS_MAX && $key < count($arr_entity_ids)) {
      continue;
    }
    if (!is_numeric($entity_id) || !$entity_id) {
      continue;
    }
    $locations = getdirections_load_locations($entity_id, $entity_type);
    if (!count($locations)) {
      continue;
    }
    $locs[] = _getdirections_loadaddress($locations[0]);
    $latlon = $locations[0]['latitude'] . ',' . $locations[0]['longitude'];

    // sanity check
    if (!getdirections_latlon_check($latlon)) {
      watchdog('getdirections', 'Lat, Lon failed for user id !nid', array(
        '!nid' => $entity_id,
      ), WATCHDOG_WARNING);
      continue;
    }
    $latlons[] = $latlon;
  }
  $content = getdirections_locations_via($locs, $latlons, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $uid
 *   Required. The uid of the location owner
 * @return
 *   Returns the themed map and form
 */
function getdirections_user_setlocation($direction, $uid, $width = '', $height = '') {
  $content = getdirections_entity_setlocation('user', $direction, $uid, $width, $height);
  return $content;
}

/**
 * Function to setup the map
 *
 * @param int $fromuid
 *   Required. The uid of the starting point
 * @param int $touid
 *   Required. The uid of the destination
 * @return
 *   Returns the themed map
 */
function getdirections_user_setlocations($fromuid, $touid, $width = '', $height = '') {
  $content = getdirections_entity_setlocations('user', $fromuid, 'user', $touid, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $nid
 *   Required. The nid of the location node
 * @return
 *   Returns the themed map and form
 */
function getdirections_node_setlocation($direction, $nid, $width = '', $height = '') {
  $content = getdirections_entity_setlocation('node', $direction, $nid, $width, $height);
  return $content;
}

/**
 * Function to setup the map
 *
 * @param int $fromnid
 *   Required. The nid of the starting point
 * @param int $tonid
 *   Required. The nid of the destination
 * @return
 *   Returns the themed map
 */
function getdirections_node_setlocations($fromnid, $tonid, $width = '', $height = '') {
  $content = getdirections_entity_setlocations('node', $fromnid, 'node', $tonid, $width, $height);
  return $content;
}

/**
 * Function to setup the map
 *
 * @param int $nid
 *   Required. The nid of the starting point
 * @param int $uid
 *   Required. The uid of the destination
 * @return
 *   Returns the themed map
 */
function getdirections_n2u_setlocation($nid, $uid, $width = '', $height = '') {
  $content = getdirections_entity_setlocations('node', $nid, 'user', $uid, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param int $uid
 *   Required. The uid of the starting point
 * @param int $nid
 *   Required. The nid of the destination
 * @return
 *   Returns the themed map
 */
function getdirections_u2n_setlocation($uid, $nid, $width = '', $height = '') {
  $content = getdirections_entity_setlocations('user', $uid, 'node', $nid, $width, $height);
  return $content;
}

/**
 * Function to setup the map to display waypoints
 *
 * @param $uids
 *   Required. A comma delimited list of uids
 * @return
 *   Returns the themed map
 */
function getdirections_user_setlocations_via($uids, $width = '', $height = '') {
  $content = getdirections_entity_setlocations_via($uids, 'user', $width, $height);
  return $content;
}

/**
 * Function to setup the map to display waypoints
 *
 * @param string $nids
 *   Required. A comma delimited list of nids
 * @return
 *   Returns the themed map
 */
function getdirections_node_setlocations_via($nids, $width = '', $height = '') {
  $content = getdirections_entity_setlocations_via($nids, 'node', $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $tid
 *   Required. The tid of the location enabled taxonomy term
 * @return
 *   Returns the themed map and form
 */
function getdirections_term_setlocation($direction, $tid, $width = '', $height = '') {
  $content = getdirections_entity_setlocation('taxonomy_term', $direction, $tid, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $cid
 *   Required. The cid of the location enabled comment
 * @return
 *   Returns the themed map and form
 */
function getdirections_comment_setlocation($direction, $cid, $width = '', $height = '') {
  $content = getdirections_entity_setlocation('comment', $direction, $cid, $width, $height);
  return $content;
}

/**
 * Function to setup the map
 *
 * @param string $lls
 *   Required. A pipe delimited string of latitude,longitude pairs.
 * @return
 *   Returns the themed map
 */
function getdirections_latlons($lls, $width = '', $height = '') {
  $latlons = array();
  $locs = array();
  $arrlls = explode('|', $lls);
  foreach ($arrlls as $key => $ll) {
    if ($key > GETDIRECTIONS_WAYPOINTS_MAX && $key < count($arrlls)) {
      continue;
    }
    if (!getdirections_latlon_check($ll)) {
      watchdog('getdirections', 'Lat, Lon failed for !ll', array(
        '!ll' => $ll,
      ), WATCHDOG_WARNING);
      continue;
    }
    $latlons[] = $ll;
  }
  $content = getdirections_locations_via($locs, $latlons, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param string $latlon
 *   Required. A latitude,longitude pair
 * @param string $locs
 * Optional. a description of the target.
 * @return
 *   Returns the themed map and form
 */
function getdirections_latlon($direction, $latlon, $locs = '', $width = '', $height = '') {
  $country = '';
  $id = 0;
  $type = 'other';
  if (!getdirections_latlon_check($latlon)) {
    watchdog('getdirections', 'Lat, Lon failed for user id !uid', array(
      '!uid' => $uid,
    ), WATCHDOG_WARNING);
    $latlon = getdirections_load_latlon_defaults();
  }
  $content = getdirections_direction_other($direction, $locs, $country, $latlon, $id, $type, $width, $height);
  return $content;
}

/**
 * Function to setup the map and form
 *
 * @param string $direction
 *   Required. The direction the supplied input applies to
 * @param int $lid
 *   Required. The lid of the location
 * @return
 *   Returns the themed map and form
 */
function getdirections_setlocation_id($direction, $lid, $width = '', $height = '') {
  if (is_numeric($lid) && $lid) {
    $location = getdirections_load_location($lid);
    if (is_array($location) && count($location)) {
      $country = isset($location['country']) ? $location['country'] : '';
      $latlon = $location['latitude'] . ',' . $location['longitude'];

      // sanity check
      if (!getdirections_latlon_check($latlon)) {
        watchdog('getdirections', 'Lat, Lon failed for location id !lid', array(
          '!lid' => $lid,
        ), WATCHDOG_WARNING);
        $latlon = getdirections_load_latlon_defaults();
      }

      // $locs only used for display now
      $locs = _getdirections_loadaddress($location);
      $content = getdirections_direction_other($direction, $locs, $country, $latlon, $lid, 'location', $width, $height);
      return $content;
    }
  }
  return getdirections_direction();
}

/**
 * Function to setup the map scripts
 *
 * @param $defaults
 *   Required. the current settings.
 * Sets up the call to googlemaps, css and the relevant getdirections js in html head
 */
function getdirections_setup_map($defaults, $misc_defaults) {
  global $language, $is_https;
  $getdirections_paths = getdirections_paths_get();

  // v3 googlemaps API
  $key = variable_get('getdirections_api3_key', '');
  $clientID = variable_get('getdirections_api3_clientID', '');
  $channel = variable_get('getdirections_api3_channel', '');
  $query = array();
  if (!empty($key)) {
    $query['key'] = $key;
  }
  if (!empty($clientID)) {
    $query['client'] = $clientID;
  }
  if (!empty($channel)) {
    $query['channel'] = $channel;
  }
  $query['sensor'] = 'false';
  $query['language'] = $language->language;
  if ($defaults['region_bias']) {
    $query['region'] = $defaults['region_bias'];
  }
  $libraries = array();
  if ($defaults['advanced_autocomplete']) {
    $libraries['places'] = 'places';
  }
  if ($misc_defaults['panoramio_use']) {
    $libraries['panoramio'] = 'panoramio';
  }
  if ($misc_defaults['weather_use']) {
    $libraries['weather'] = 'weather';
  }

  // more libraries here
  // compat with getlocations
  if (module_exists('getlocations')) {
    $getlocations_defaults = getlocations_defaults();
    if (function_exists('getlocations_places_check')) {
      if (getlocations_places_check()) {
        $libraries['places'] = 'places';
      }
    }
    elseif ($getlocations_defaults['places']) {
      $libraries['places'] = 'places';
    }
    if ($getlocations_defaults['panoramio_use']) {
      $libraries['panoramio'] = 'panoramio';
    }
    if ($getlocations_defaults['weather_use']) {
      $libraries['weather'] = 'weather';
    }
  }

  // load libraries if any
  if (count($libraries)) {
    $query['libraries'] = implode(',', $libraries);
  }
  $current_js = drupal_get_js();
  $scheme = $is_https ? 'https' : 'http';
  $gmapdomain = "maps.googleapis.com/maps/api/js";
  $gmaplink = url($scheme . '://' . $gmapdomain, array(
    'query' => $query,
  ));
  if (!stristr($current_js, $scheme . '://' . $gmapdomain)) {
    drupal_add_js($gmaplink, 'external');
  }
  if (isset($defaults['preview_map'])) {
    $js = $getdirections_paths['getdirections_preview_path'];
  }
  else {
    if ($defaults['use_advanced']) {
      if ($defaults['advanced_alternate']) {
        $js = $getdirections_paths['getdirections_v3b_path'];
      }
      else {
        $js = $getdirections_paths['getdirections_v3a_path'];
      }
    }
    else {
      $js = $getdirections_paths['getdirections_v3_path'];
    }
  }
  drupal_add_css(GETDIRECTIONS_PATH . '/getdirections.css');
  drupal_add_js($js);
}

/**
 * Implements hook_views_api().
 */
function getdirections_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Function to collect an address
 *
 * @param array $location
 * @param bool $addcountry
 *
 * @return
 *   Returns array.
 */
function _getdirections_loadaddress($location, $addcountry = TRUE) {

  // theme it so others can change it
  return theme('getdirections_loadaddress', array(
    'location' => $location,
    'addcountry' => $addcountry,
  ));
}

/**
 * Function to collect an address from addressfield
 *
 * @param array $address
 * @param bool $addcountry
 *
 * @return
 *   Returns array.
 */
function _getdirections_addressfield_loadaddress($address, $addcountry = TRUE) {

  // theme it so others can change it
  return theme('getdirections_addressfield_loadaddress', array(
    'address' => $address,
    'addcountry' => $addcountry,
  ));
}

/**
 * Function to check the user status and existence
 *
 * @param int $uid
 *
 * @return
 *   Returns status.
 */
function getdirections_user_check($uid) {
  $query = db_select('users', 'u')
    ->fields('u', array(
    'status',
  ))
    ->condition('u.uid', $uid);
  $row = $query
    ->execute()
    ->fetchAssoc();
  return isset($row['status']) && $row['status'] ? TRUE : FALSE;
}

/**
 * Function to get the vid from node table.
 *
 * @param int $nid
 *
 * @return
 *   Returns vid.
 */

// NOT IN USE
function getdirections_get_vid($nid) {
  if (is_numeric($nid) && $nid) {
    $query = db_select('node', 'n')
      ->fields('n', array(
      'vid',
    ))
      ->condition('n.nid', $nid);
    $row = $query
      ->execute()
      ->fetchAssoc();
    return isset($row['vid']) && $row['vid'] ? $row['vid'] : FALSE;
  }
  return FALSE;
}

/**
 * Function to get the nid from node table.
 *
 * @param int $vid
 *
 * @return
 *   Returns nid.
 */

// NOT IN USE
function getdirections_get_nid($vid) {
  if (is_numeric($vid) && $vid) {
    $query = db_select('node', 'n')
      ->fields('n', array(
      'nid',
    ))
      ->condition('n.vid', $vid);
    $row = $query
      ->execute()
      ->fetchAssoc();
    return isset($row['nid']) && $row['nid'] ? $row['nid'] : FALSE;
  }
  return FALSE;
}

/**
 * Function to get the node identifier if available
 *
 * @param int $lid
 *
 * @return
 *   Returns nid.
 */

// NOT IN USE
function getdirections_get_nid_from_lid($lid) {
  if ($lid) {
    $query = FALSE;
    if (module_exists('getlocations_fields')) {
      $nid = getlocations_get_nid_from_lid($lid);
      if ($nid) {
        return $nid;
      }
    }
    elseif (module_exists('location')) {
      $query = db_select('location_instance', 'i')
        ->fields('i', array(
        'nid',
      ))
        ->condition('i.lid', $lid);
    }
    if ($query) {
      $row = $query
        ->execute()
        ->fetchAssoc();
      return isset($row['nid']) && $row['nid'] ? $row['nid'] : FALSE;
    }
  }
  return FALSE;
}

/**
 * Function to get the term identifier if available
 *
 * @param int $lid
 *
 * @return
 *   Returns tid.
 */

// NOT IN USE
function getdirections_get_tid_from_lid($lid) {
  $tid = FALSE;
  if (module_exists('getlocations_fields')) {
    $tid = getlocations_get_tid_from_lid($lid);
  }
  if ($tid) {
    return $tid;
  }
  return FALSE;
}

/**
 * Function to get the location name if available
 *
 * @param int $lid
 *
 * @return
 *   Returns name.
 */
function getdirections_get_lid_title($lid) {
  if ($lid) {
    $query = FALSE;
    if (module_exists('getlocations_fields')) {
      $query = db_select('getlocations_fields', 'i')
        ->fields('i', array(
        'name',
      ))
        ->condition('i.glid', $lid);
    }
    elseif (module_exists('location')) {
      $query = db_select('location', 'i')
        ->fields('i', array(
        'name',
      ))
        ->condition('i.lid', $lid);
    }
    if ($query) {
      $row = $query
        ->execute()
        ->fetchAssoc();
      return isset($row['name']) && $row['name'] ? $row['name'] : FALSE;
    }
  }
  return FALSE;
}

/**
 *
 *
 */
function getdirections_load_latlon_defaults() {
  $getdirections_defaults = getdirections_defaults();
  return $getdirections_defaults['latlong'];
}

/**
 * Check if the config has been run
 *
 */
function getdirections_check() {
  $check = variable_get('getdirections_default', 'xxx');
  if ($check == 'xxx') {
    return FALSE;
  }
  return TRUE;
}

/**
 * Function to check a lat,lon string
 *
 * @param string $latlon
 *
 * @return
 *   Returns true or false
 */
function getdirections_latlon_check($latlon) {
  if (!empty($latlon) && preg_match("/[0-9.\\-],[0-9.\\-]/", $latlon)) {
    $ll = explode(',', $latlon);
    if (isset($ll[0]) && is_numeric($ll[0]) && $ll[0] != 0 && isset($ll[1]) && is_numeric($ll[1]) && $ll[1] != 0) {
      return $latlon;
    }
  }
  return FALSE;
}

/**
 * for colorbox and suchlike
 *
 */
function getdirections_direction_box() {
  $a1 = FALSE;
  $a2 = FALSE;
  $a3 = FALSE;
  $a4 = FALSE;
  if (arg(1)) {
    $a1 = arg(1);
  }
  if (arg(2)) {
    $a2 = arg(2);
  }
  if (arg(3)) {
    $a3 = arg(3);
  }
  if (arg(4)) {
    $a4 = arg(4);
  }
  if ($a1 == 'location' && ($a2 == 'from' || $a2 == 'to') && is_numeric($a3)) {
    $content = getdirections_node_setlocation($a2, $a3);
  }
  elseif ($a1 == 'locations' && is_numeric($a2) && is_numeric($a3)) {
    $content = getdirections_node_setlocations($a2, $a3);
  }
  elseif ($a1 == 'locations_via' && $a2) {
    $content = getdirections_node_setlocations_via($a2);
  }
  elseif ($a1 == 'locations_user_via' && $a2) {
    $content = getdirections_user_setlocations_via($a2);
  }
  elseif ($a1 == 'location_user' && ($a2 == 'from' || $a2 == 'to') && is_numeric($a3)) {
    $content = getdirections_user_setlocation($a2, $a3);
  }
  elseif ($a1 == 'locations_users' && is_numeric($a2) && is_numeric($a3)) {
    $content = getdirections_user_setlocations($a2, $a3);
  }
  elseif ($a1 == 'location_n2u' && is_numeric($a2) && is_numeric($a3)) {
    $content = getdirections_n2u_setlocation($a2, $a3);
  }
  elseif ($a1 == 'location_u2n' && is_numeric($a2) && is_numeric($a3)) {
    $content = getdirections_u2n_setlocation($a2, $a3);
  }
  elseif ($a1 == 'latlon' && ($a2 == 'from' || $a2 == 'to')) {
    $content = getdirections_latlon($a2, $a3, $a4);
  }
  elseif ($a1 == 'latlons' && $a2) {
    $content = getdirections_latlons($a2);
  }
  elseif ($a1 == 'location_id' && ($a2 == 'from' || $a2 == 'to')) {
    $content = getdirections_setlocation_id($a2, $a3);
  }
  elseif ($a1 == 'location_term' && ($a2 == 'from' || $a2 == 'to')) {
    $content = getdirections_term_setlocation($a2, $a3);
  }
  elseif ($a1 == 'location_comment' && ($a2 == 'from' || $a2 == 'to')) {
    $content = getdirections_comment_setlocation($a2, $a3);
  }
  elseif (getdirections_check_entity_type($a1) && ($a2 == 'from' || $a2 == 'to') && is_numeric($a3)) {
    $content = getdirections_entity_setlocation($a1, $a2, $a3);
  }
  elseif (getdirections_check_entity_type($a1) && is_numeric($a2) && getdirections_check_entity_type($a3) && is_numeric($a4)) {
    $content = getdirections_entity_setlocations($a1, $a2, $a3, $a4);
  }
  else {
    $content = getdirections_direction();
  }
  $output = theme('getdirections_box', array(
    'content' => $content,
  ));
  print $output;
  exit;
}

/**
 * Load one or more locations
 *
 * @param int $entity_id
 * @param string $entity_type
 *
 * @return array
 *
 */
function getdirections_load_locations($entity_id, $entity_type) {
  $locations = '';
  $module = getdirections_get_current_supported_module();
  if ($module == 'getlocations_fields') {
    $entity_get_info = entity_get_info($entity_type);
    $entity_key = $entity_get_info['entity keys']['id'];

    // nid, cid, uid etc
    $locations = getlocations_fields_load_locations($entity_id, $entity_key);
  }
  elseif ($module == 'location_node' || $module == 'location_cck') {
    $entity_get_info = entity_get_info($entity_type);
    $entity_key = $entity_get_info['entity keys']['id'];

    // nid, cid, uid etc
    $locations = location_load_locations($entity_id, $entity_key);
  }
  elseif ($module == 'geofield') {
    $locations = getdirections_other_load_locations($entity_id, $entity_type, 'geofield');
  }
  elseif ($module == 'geolocation') {
    $locations = getdirections_other_load_locations($entity_id, $entity_type, 'geolocation');
  }
  return $locations;
}

/**
 * Load a location
 *
 * @param int $lid
 *
 * @return array
 *
 */
function getdirections_load_location($lid) {
  $location = '';
  if (module_exists('getlocations_fields')) {
    $location = getlocations_fields_load_location($lid);
  }
  elseif (module_exists('location')) {
    $location = location_load_location($lid);
  }
  return $location;
}

/**
 * Load one or more locations
 * For Geofield and Geolocation modules
 *
 * @param int $entity_id
 * @param string $entity_type
 *
 * @return array
 *
 */
function getdirections_other_load_locations($entity_id, $entity_type, $module = '') {
  global $language;
  $locations = array();
  if (empty($module)) {
    return $locations;
  }
  $entity_get_info = entity_get_info($entity_type);
  $load_hook = $entity_get_info['load hook'];
  $obj = $load_hook($entity_id);
  $entity_title = '';
  if (isset($entity_get_info['entity keys']['label'])) {
    $entity_title = $entity_get_info['entity keys']['label'];
  }
  elseif ($entity_type == 'user') {
    $entity_title = 'name';
  }
  $entity_key = $entity_get_info['entity keys']['id'];

  // nid, cid, uid etc
  $location_name = '';
  if (isset($obj->{$entity_title})) {
    $location_name = $obj->{$entity_title};
  }

  // get the field_xxx names
  $objfields = array();
  foreach ($obj as $k => $therest) {
    if (preg_match("/^field_/", $k)) {
      $objfields[] = $k;
    }
  }
  if (empty($objfields)) {
    return $locations;
  }

  // find a geofield
  if ($module == 'geofield') {
    $type = 'geofield';
    $geofields = getdirections_get_fieldname($type, $module, $entity_type);
    if (!empty($geofields)) {
      $geofield = '';
      foreach ($objfields as $field) {
        if (in_array($field, $geofields)) {
          $geofield = $field;
        }
      }
      if (empty($geofield)) {
        return $locations;
      }

      // got one
      $geo = $obj->{$geofield};
      $geo_keys = array_keys($geo);
      foreach ($geo_keys as $lang) {
        if ($lang == $language->language || isset($obj->language) && $lang == $obj->language || $lang == 'und') {
          $ct = 0;
          foreach ($geo[$lang] as $g) {
            $locations[$ct]['latitude'] = $g['lat'];
            $locations[$ct]['longitude'] = $g['lon'];
            $locations[$ct]['entity_key'] = $entity_key;
            $locations[$ct]['entity_id'] = $entity_id;
            $locations[$ct]['entity_type'] = $entity_type;
            $locations[$ct]['name'] = $location_name;
            $ct++;
          }
        }
      }
    }
  }
  elseif ($module == 'geolocation') {
    $type = 'geolocation_latlng';
    $geolocationfields = getdirections_get_fieldname($type, $module, $entity_type);
    if (!empty($geolocationfields)) {
      $geolocationfield = '';
      foreach ($objfields as $field) {

        // test for geolocationfields
        if (in_array($field, $geolocationfields)) {
          $geolocationfield = $field;
        }
      }
      if (empty($geolocationfield)) {
        return $locations;
      }

      // got one
      $geo = $obj->{$geolocationfield};
      $geo_keys = array_keys($geo);
      foreach ($geo_keys as $lang) {
        if ($lang == $language->language || isset($obj->language) && $lang == $obj->language || $lang == 'und') {
          $ct = 0;
          foreach ($geo[$lang] as $g) {
            $locations[$ct]['latitude'] = $g['lat'];
            $locations[$ct]['longitude'] = $g['lng'];
            $locations[$ct]['entity_key'] = $entity_key;
            $locations[$ct]['entity_id'] = $entity_id;
            $locations[$ct]['entity_type'] = $entity_type;
            $locations[$ct]['name'] = $location_name;
            $ct++;
          }
        }
      }
    }
  }

  // sanity check
  if (empty($locations)) {
    return $locations;
  }

  // addressfield
  if (module_exists('addressfield')) {

    // find an addressfield
    $type = 'addressfield';
    $addressfields = getdirections_get_fieldname($type, 'addressfield', $entity_type);
    if (!empty($addressfields)) {
      $addressfield = '';
      foreach ($objfields as $field) {
        if (in_array($field, $addressfields)) {
          $addressfield = $field;
        }
      }
      if (empty($addressfield)) {
        return $locations;
      }

      // got one
      $addr = $obj->{$addressfield};
      $addr_keys = array_keys($addr);
      foreach ($addr_keys as $lang) {
        if ($lang == $language->language || isset($obj->language) && $lang == $obj->language || $lang == 'und') {
          $ct = 0;
          foreach ($addr[$lang] as $a) {
            if (isset($locations[$ct])) {
              $locations[$ct] += getdirections_addressfield_convert($a);
            }
            $ct++;
          }
        }
      }
    }
  }
  return $locations;
}

/**
 * Get field names
 *
 * @param string $type
 * @param string $module
 * @param string $entity_type
 *
 * @return array field names
 *
 */
function getdirections_get_fieldname($type, $module, $entity_type = '') {
  $query = db_select('field_config', 'fc');
  $query
    ->fields('fc', array(
    'field_name',
  ));
  $query
    ->join('field_config_instance', 'i', 'fc.id = i.field_id');
  $query
    ->condition('fc.module', $module);
  $query
    ->condition('fc.type', $type);
  $query
    ->condition('fc.active', 1);
  $query
    ->condition('fc.storage_active', 1);
  if (!empty($entity_type)) {
    $query
      ->condition('i.entity_type', $entity_type);
  }
  $rows = $query
    ->execute();
  $field_names = array();
  foreach ($rows as $row) {
    $field_names[] = $row->field_name;
  }
  return $field_names;
}

/**
 * Get the javascript paths
 *
 * @return array paths
 *
 */
function getdirections_paths_get($reset = FALSE) {
  $defaults = array(
    'getdirections_v3_path' => GETDIRECTIONS_PATH . '/js/getdirections_v3.js',
    'getdirections_v3a_path' => GETDIRECTIONS_PATH . '/js/getdirections_v3a.js',
    'getdirections_v3b_path' => GETDIRECTIONS_PATH . '/js/getdirections_v3b.js',
    'getdirections_preview_path' => GETDIRECTIONS_PATH . '/js/getdirections_preview.js',
  );
  if ($reset) {
    return $defaults;
  }
  $getdirections_paths = variable_get('getdirections_paths', $defaults);
  $newdefaults = getdirections_adjust_vars($defaults, $getdirections_paths);
  return $newdefaults;
}

/**
 * Fetch a timestamp
 *
 * @return array json
 *
 */
function getdirections_get_datestamp() {
  $d = $_GET['d'];
  $t = $_GET['t'];
  $date = $d . ' ' . $t;
  $time = strtotime($date);
  drupal_json_output(array(
    'content' => $time * 1000,
  ));
}

/**
 *
 *
 */
function getdirections_is_mobile() {
  $getdirections_misc_defaults = getdirections_misc_defaults();
  if (!$getdirections_misc_defaults['geolocation_mobile_check']) {
    return TRUE;
  }
  $getdirections_ua = getdirections_ua_get();
  $str = "/" . $getdirections_ua['ua_string'] . "/i";
  $is_mobile = FALSE;
  $ua = $_SERVER['HTTP_USER_AGENT'];
  if (preg_match($str, $ua)) {
    $is_mobile = TRUE;
  }
  return $is_mobile;
}

/**
 * @return
 *   Returns a string of mobile compatible user agents
 */
function getdirections_ua_get() {
  $default = array(
    'ua_string' => "iphone|ipad|android|blackberry|blazer|bolt|symbian|mobile safari|fennec|gobrowser|iemobile|maemo browser|profile midp|minimo|kindle|opera mini|opera mobi|skyfire|teashark|uzardweb",
  );
  $getdirections_ua = variable_get('getdirections_ua', $default);
  return $getdirections_ua;
}

/**
 * @return
 *   Returns location array
 *
 */
function getdirections_smart_ip() {
  if (module_exists('smart_ip')) {
    global $user;
    $location = FALSE;
    if ($user->uid > 0 && isset($user->data['geoip_location'])) {
      $location = $user->data['geoip_location'];
    }
    elseif (isset($_SESSION['smart_ip']['location'])) {
      $location = $_SESSION['smart_ip']['location'];
    }
    drupal_json_output($location);
  }
  exit;
}

/**
 * @return
 *   Returns location array
 *
 */
function getdirections_ip_geoloc() {
  if (module_exists('ip_geoloc')) {
    $location = FALSE;
    if (isset($_SESSION['ip_geoloc']['location'])) {
      $location = $_SESSION['ip_geoloc']['location'];
    }
    drupal_json_output($location);
  }
  exit;
}

/**
 * @return
 *   Returns an array of supported modules
 */
function getdirections_supported_modules() {
  return array(
    'getlocations_fields',
    'geofield',
    'geolocation',
    'location_node',
    'location_cck',
  );
}

/**
 *
 *
 */
function getdirections_get_current_supported_module() {
  $modules = getdirections_supported_modules();
  foreach ($modules as $module) {
    if (module_exists($module)) {
      return $module;
    }
  }
  return FALSE;
}

/**
 * Recursively merge the defaults with the current settings
 *
 * @param array $defaults
 *
 * @param array $settings
 *
 * @return array The merged settings
 *
 */
function getdirections_adjust_vars($defaults, $settings) {
  $newdefaults = array();
  foreach ($defaults as $k => $v) {
    if (isset($settings[$k])) {
      if (is_array($v)) {
        $newdefaults[$k] = getdirections_adjust_vars($v, $settings[$k]);
      }
      else {
        $newdefaults[$k] = $settings[$k];
      }
    }
    else {
      $newdefaults[$k] = $v;
    }
  }
  return $newdefaults;
}

/**
 * Default settings form
 * @return array form
 *
 */
function getdirections_default_settings($defaults, $parent = 'getdirections_default') {
  $form = array();
  $form['width'] = array(
    '#type' => 'textfield',
    '#title' => t('Default width'),
    '#default_value' => $defaults['width'],
    '#size' => 25,
    '#maxlength' => 25,
    '#description' => t('The default width of a Google map, as a CSS length or percentage. Examples: <em>50px</em>, <em>5em</em>, <em>2.5in</em>, <em>95%</em>'),
    '#required' => TRUE,
  );
  $form['height'] = array(
    '#type' => 'textfield',
    '#title' => t('Default height'),
    '#default_value' => $defaults['height'],
    '#size' => 25,
    '#maxlength' => 25,
    '#description' => t('The default height of a Google map, as a CSS length or percentage. Examples: <em>50px</em>, <em>5em</em>, <em>2.5in</em>, <em>95%</em>'),
    '#required' => TRUE,
  );
  $form['latlong'] = array(
    '#type' => 'textfield',
    '#title' => t('Map center'),
    '#default_value' => $defaults['latlong'],
    '#size' => 50,
    '#maxlength' => 255,
    '#description' => t('The default center coordinates of Google map, expressed as a decimal latitude and longitude, separated by a comma.'),
    '#required' => TRUE,
  );
  $form['zoom'] = array(
    '#type' => 'select',
    '#title' => t('Zoom'),
    '#default_value' => $defaults['zoom'],
    '#options' => drupal_map_assoc(range(0, 17)),
    '#description' => t('The default zoom level of a Google map.'),
  );

  // v3
  $opts = array(
    'none' => t('None'),
    'default' => t('Default'),
    'small' => t('Small'),
    'large' => t('Large'),
  );
  $form['controltype'] = array(
    '#type' => 'select',
    '#title' => t('Zoom Control type'),
    '#options' => $opts,
    '#default_value' => $defaults['controltype'],
  );
  $form['pancontrol'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show Pan control'),
    '#default_value' => $defaults['pancontrol'],
    '#return_value' => 1,
  );
  $opts2 = array(
    'none' => t('None'),
    'standard' => t('Horizontal bar'),
    'menu' => t('Dropdown'),
  );
  $form['mtc'] = array(
    '#type' => 'select',
    '#title' => t('Map Control Type'),
    '#options' => $opts2,
    '#default_value' => $defaults['mtc'],
  );
  $options = array();
  $layers = array(
    'Map' => t('Standard street map'),
    'Satellite' => t('Standard satellite map'),
    'Hybrid' => t('Hybrid satellite map'),
    'Physical' => t('Terrain map'),
    'OpenStreetMap' => t('OpenStreet map'),
  );
  foreach ($layers as $key => $layer) {
    if ($defaults['baselayers'][$key]) {
      $options[$key] = $layer;
    }
  }
  $form['maptype'] = array(
    '#type' => 'select',
    '#title' => t('Default map type'),
    '#default_value' => $defaults['maptype'],
    '#options' => $options,
  );
  $form['baselayers'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enable map types'),
    '#description' => t('Select which maps you want to be available.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['baselayers']['Map'] = array(
    '#type' => 'checkbox',
    '#title' => t('Standard street map'),
    '#description' => t('The standard default street map.'),
    '#default_value' => $defaults['baselayers']['Map'],
    '#return_value' => 1,
  );
  $form['baselayers']['Satellite'] = array(
    '#type' => 'checkbox',
    '#title' => t('Standard satellite map'),
    '#description' => t('Satellite view without street overlay.'),
    '#default_value' => $defaults['baselayers']['Satellite'],
    '#return_value' => 1,
  );
  $form['baselayers']['Hybrid'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hybrid satellite map'),
    '#description' => t('Satellite view with street overlay.'),
    '#default_value' => $defaults['baselayers']['Hybrid'],
    '#return_value' => 1,
  );
  $form['baselayers']['Physical'] = array(
    '#type' => 'checkbox',
    '#title' => t('Terrain map'),
    '#description' => t('Map with physical data (terrain, vegetation.)'),
    '#default_value' => $defaults['baselayers']['Physical'],
    '#return_value' => 1,
  );
  $form['baselayers']['OpenStreetMap'] = array(
    '#type' => 'checkbox',
    '#title' => t('OpenStreet map'),
    '#description' => t('Map from the OpenStreetMap Foundation.'),
    '#default_value' => $defaults['baselayers']['OpenStreetMap'],
    '#return_value' => 1,
  );
  $form['unitsystem'] = array(
    '#type' => 'select',
    '#title' => t('Default distance units'),
    '#description' => t("Units to display distances in."),
    '#default_value' => $defaults['unitsystem'],
    '#options' => array(
      'metric' => t('Metric'),
      'imperial' => t('Imperial'),
    ),
  );
  $form['scale'] = array(
    '#type' => 'checkbox',
    '#title' => t('Scale'),
    '#description' => t('Show scale'),
    '#default_value' => $defaults['scale'],
    '#return_value' => 1,
  );
  $form['overview'] = array(
    '#type' => 'checkbox',
    '#title' => t('Overview map'),
    '#description' => t('Show overview map'),
    '#default_value' => $defaults['overview'],
    '#return_value' => 1,
  );
  $form['overview_opened'] = array(
    '#type' => 'checkbox',
    '#title' => t('Overview map state'),
    '#description' => t('Show overview map as open by default'),
    '#default_value' => $defaults['overview_opened'],
    '#return_value' => 1,
  );
  $form['scrollwheel'] = array(
    '#type' => 'checkbox',
    '#title' => t('Scrollwheel'),
    '#description' => t('Enable scrollwheel zooming'),
    '#default_value' => $defaults['scrollwheel'],
    '#return_value' => 1,
  );
  $form['draggable'] = array(
    '#type' => 'checkbox',
    '#title' => t('Draggable'),
    '#description' => t('Enable dragging on the map'),
    '#default_value' => $defaults['draggable'],
    '#return_value' => 1,
  );
  $form['nokeyboard'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable keyboard shortcuts'),
    '#description' => t('Enabling this will disable keyboard shortcuts on the map.'),
    '#default_value' => $defaults['nokeyboard'],
    '#return_value' => 1,
  );
  $form['nodoubleclickzoom'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable Doubleclick zoom'),
    '#description' => t('Enabling this will disable doubleclick zooming on the map.'),
    '#default_value' => $defaults['nodoubleclickzoom'],
    '#return_value' => 1,
  );
  $form['streetview_show'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show streetview button'),
    '#default_value' => $defaults['streetview_show'],
    '#return_value' => 1,
  );
  $form['travelmode_show'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show travel mode'),
    '#description' => t('Enable travel mode selector.'),
    '#default_value' => $defaults['travelmode_show'],
    '#return_value' => 1,
  );
  if (module_exists('date_popup')) {
    $form['transit_dates'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show Public transport Dates'),
      '#description' => t('When "Public transport" has been selected as travel mode, allow user to enter a date and time.'),
      '#default_value' => $defaults['transit_dates'],
      '#return_value' => 1,
      '#prefix' => '<div id="getdirections_transit_dates_wrapper">',
    );
    $form['transit_date_format'] = array(
      '#type' => 'select',
      '#title' => t('Date format'),
      '#default_value' => $defaults['transit_date_format'],
      '#options' => array(
        'int' => t('International Format'),
        'usa' => t('American Format'),
      ),
      '#suffix' => '</div>',
    );
  }
  else {
    $form['transit_dates'] = array(
      '#type' => 'value',
      '#value' => 0,
    );
    $form['transit_date_format'] = array(
      '#type' => 'value',
      '#value' => 'int',
    );
  }
  $form['travelextras_show'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show travel extras'),
    '#description' => t('Enable travel extras checkboxes.'),
    '#default_value' => $defaults['travelextras_show'],
    '#return_value' => 1,
  );
  $form['map_backgroundcolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Map background color'),
    '#default_value' => $defaults['map_backgroundcolor'],
    '#description' => t('Can be a color name or HTML hex, eg #FF0000. Leave empty for the default color.'),
    '#size' => 10,
  );
  $form['from_width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width of From box'),
    '#default_value' => $defaults['from_width'],
    '#size' => 5,
    '#description' => t("The width of the Get directions 'From' box."),
    '#required' => TRUE,
  );
  if ($parent) {
    $form['from_width']['#parents'] = array(
      $parent,
      'from_width',
    );
  }
  $form['to_width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width of To box'),
    '#default_value' => $defaults['to_width'],
    '#size' => 5,
    '#description' => t("The width of the Get directions 'To' box."),
    '#required' => TRUE,
  );
  if ($parent) {
    $form['to_width']['#parents'] = array(
      $parent,
      'to_width',
    );
  }
  if (module_exists('location') || module_exists('getlocations_fields')) {
    $form['use_country_dropdown'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use Country dropdown'),
      '#description' => t('Use a dropdown list of countries on the form.'),
      '#default_value' => $defaults['use_country_dropdown'],
      '#return_value' => 1,
    );
  }
  else {
    $form['use_country_dropdown'] = array(
      '#type' => 'value',
      '#value' => 0,
    );
  }
  $form['use_advanced'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use advanced features'),
    '#description' => t('Advanced features include a clickable map, waypoints or draggable route.'),
    '#default_value' => $defaults['use_advanced'],
    '#return_value' => 1,
  );
  $waypoints_opts = range(0, GETDIRECTIONS_WAYPOINTS_MAX);
  $waypoints_opts[0] = t('None');
  $form['waypoints'] = array(
    '#type' => 'select',
    '#title' => t('Number of waypoints'),
    '#description' => t('The number of waypoints to display on the map.'),
    '#default_value' => $defaults['waypoints'],
    '#options' => $waypoints_opts,
    '#prefix' => '<div id="wrap-waypoints">',
  );
  $form['advanced_autocomplete_via'] = array(
    '#type' => 'checkbox',
    '#title' => t('Waypoints Autocomplete'),
    '#description' => t('Provides Autocomplete box for waypoints. Requires "Use Google Autocomplete" to be enabled.'),
    '#default_value' => $defaults['advanced_autocomplete_via'],
    '#return_value' => 1,
  );
  $form['advanced_autocomplete_via_width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width of Waypoints box'),
    '#default_value' => $defaults['advanced_autocomplete_via_width'],
    '#size' => 5,
    '#description' => t("The width of the Waypoints Autocomplete box."),
    '#required' => TRUE,
  );
  if ($parent) {
    $form['advanced_autocomplete_via_width']['#parents'] = array(
      $parent,
      'advanced_autocomplete_via_width',
    );
  }
  $form['waypoints_optimise'] = array(
    '#type' => 'checkbox',
    '#title' => t('Optimise Waypoints'),
    '#description' => t("Re-orders the waypoints to minimize overall cost of the route."),
    '#default_value' => $defaults['waypoints_optimise'],
    '#return_value' => 1,
  );
  $form['waypoint_color'] = array(
    '#type' => 'select',
    '#title' => t('Color of waypoint markers'),
    '#description' => t('The color of waypoint markers used on the map.'),
    '#default_value' => $defaults['waypoint_color'],
    '#options' => array(
      'black' => t('Black'),
      'blue' => t('Blue'),
      'brown' => t('Brown'),
      'gray' => t('Gray'),
      'green' => t('Green'),
      'orange' => t('Orange'),
      'purple' => t('Purple'),
      'red' => t('Red'),
      'white' => t('White'),
      'yellow' => t('Yellow'),
    ),
  );
  $form['advanced_alternate'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use draggable route'),
    '#description' => t('An alternative to waypoints.'),
    '#default_value' => $defaults['advanced_alternate'],
    '#return_value' => 1,
  );
  $form['advanced_autocomplete'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Google Autocomplete'),
    '#description' => t('An alternative method for collecting starting point and destination.'),
    '#default_value' => $defaults['advanced_autocomplete'],
    '#return_value' => 1,
  );
  $form['advanced_autocomplete_bias'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Viewport bias'),
    '#description' => t('Bias the Google Autocomplete results to the area on the map.'),
    '#default_value' => $defaults['advanced_autocomplete_bias'],
    '#return_value' => 1,
    '#suffix' => '</div>',
  );
  $form['region_bias'] = array(
    '#type' => 'select',
    '#title' => t('Regional bias'),
    '#description' => t('Bias the maps to a particular country'),
    '#default_value' => $defaults['region_bias'],
    '#options' => array(
      '' => t('None'),
    ) + getdirections_get_countries_list(),
  );
  $form['uselatlons'] = array(
    '#type' => 'checkbox',
    '#title' => t('Only use Coordinates in searches'),
    '#default_value' => $defaults['uselatlons'],
    '#return_value' => 1,
  );
  global $is_https;
  $form['use_https'] = array(
    '#type' => 'value',
    '#value' => $is_https ? 1 : 0,
  );
  return $form;
}

/**
 * Configure returnlinks
 *
 */
function getdirections_returnlink_settings($defaults) {
  $form = array();
  $entity_types = getdirections_get_enabled_entity_types();
  if (in_array('node', $entity_types)) {
    $form['node_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Page Return Link'),
      '#default_value' => $defaults['node_enable'],
      '#return_value' => 1,
    );
    $form['node_link'] = array(
      '#type' => 'textfield',
      '#title' => t('Text of page return link'),
      '#description' => t('Use %n to insert the page title'),
      '#default_value' => $defaults['node_link'],
      '#size' => 30,
      // need this to get validation to work
      '#parents' => array(
        'getdirections_returnlink',
        'node_link',
      ),
      '#prefix' => '<div id="wrap-node-link">',
      '#suffix' => '</div>',
    );
  }

  #  else {

  #    $form['node_enable'] = array('#type' => 'value', '#value' => 0);

  #    $form['node_link'] = array('#type' => 'value', '#value' => $defaults['node_link']);

  #  }
  if (in_array('user', $entity_types)) {
    $form['user_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable User Return Link'),
      '#default_value' => $defaults['user_enable'],
      '#return_value' => 1,
    );
    $form['user_link'] = array(
      '#type' => 'textfield',
      '#title' => t('Text of user return link'),
      '#description' => t('Use %n to insert the user name'),
      '#default_value' => $defaults['user_link'],
      '#size' => 30,
      // need this to get validation to work
      '#parents' => array(
        'getdirections_returnlink',
        'user_link',
      ),
      '#prefix' => '<div id="wrap-user-link">',
      '#suffix' => '</div>',
    );
  }

  #  else {

  #    $form['user_enable'] = array('#type' => 'value', '#value' => 0);

  #    $form['user_link'] = array('#type' => 'value', '#value' => $defaults['user_link']);

  #  }
  if (in_array('taxonomy_term', $entity_types)) {
    $form['taxonomy_term_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Term Return Link'),
      '#default_value' => $defaults['taxonomy_term_enable'],
      '#return_value' => 1,
    );
    $form['taxonomy_term_link'] = array(
      '#type' => 'textfield',
      '#title' => t('Text of Term return link'),
      '#description' => t('Use %n to insert the term name'),
      '#default_value' => $defaults['taxonomy_term_link'],
      '#size' => 30,
      // need this to get validation to work
      '#parents' => array(
        'getdirections_returnlink',
        'taxonomy_term_link',
      ),
      '#prefix' => '<div id="wrap-term-link">',
      '#suffix' => '</div>',
    );
  }

  #  else {

  #    $form['taxonomy_term_enable'] = array('#type' => 'value', '#value' => 0);

  #    $form['taxonomy_term_link'] = array('#type' => 'value', '#value' => $defaults['taxonomy_term_link']);

  #  }
  if (in_array('comment', $entity_types)) {
    $form['comment_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Comment Return Link'),
      '#default_value' => $defaults['comment_enable'],
      '#return_value' => 1,
    );
    $form['comment_link'] = array(
      '#type' => 'textfield',
      '#title' => t('Text of Comment return link'),
      '#description' => t('Use %n to insert the comment subject'),
      '#default_value' => $defaults['comment_link'],
      '#size' => 30,
      // need this to get validation to work
      '#parents' => array(
        'getdirections_returnlink',
        'comment_link',
      ),
      '#prefix' => '<div id="wrap-comment-link">',
      '#suffix' => '</div>',
    );
  }

  #  else {

  #    $form['comment_enable'] = array('#type' => 'value', '#value' => 0);

  #    $form['comment_link'] = array('#type' => 'value', '#value' => $defaults['comment_link']);

  #  }
  return $form;
}

/**
 * Colorbox settings form
 *
 */
function getdirections_colorbox_settings($defaults) {
  $form = array();
  $form['enable'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Colorbox'),
    '#default_value' => $defaults['enable'],
    '#return_value' => 1,
    '#description' => t('Show Getdirections in a Colorbox.'),
  );
  $form['width'] = array(
    '#type' => 'textfield',
    '#title' => t('Colorbox width'),
    '#default_value' => $defaults['width'],
    '#size' => 5,
    '#required' => TRUE,
    // need this to get validation to work
    '#parents' => array(
      'getdirections_colorbox',
      'width',
    ),
    '#prefix' => '<div id="wrap-getdirections-colorbox">',
  );
  $form['height'] = array(
    '#type' => 'textfield',
    '#title' => t('Colorbox height'),
    '#default_value' => $defaults['height'],
    '#size' => 5,
    '#required' => TRUE,
    // need this to get validation to work
    '#parents' => array(
      'getdirections_colorbox',
      'height',
    ),
    '#suffix' => '</div>',
  );
  return $form;
}

/**
 * Miscellaneous settings form
 *
 */
function getdirections_misc_settings($defaults, $config = TRUE, $extras = TRUE) {
  if ((module_exists('location') || module_exists('getlocations_fields')) && $config) {
    $form['keep_title'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show original title'),
      '#description' => t("Show the node title or user name when using 'to' or 'from'."),
      '#default_value' => $defaults['keep_title'],
      '#return_value' => 1,
    );
  }
  else {
    $form['getdirections_misc']['keep_title'] = array(
      '#type' => 'value',
      '#value' => 0,
    );
  }
  $form['show_distance'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show total distance'),
    '#default_value' => $defaults['show_distance'],
    '#return_value' => 1,
  );
  $form['show_duration'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show total duration'),
    '#default_value' => $defaults['show_duration'],
    '#return_value' => 1,
  );
  $form['geolocation_enable'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable geolocation options'),
    '#default_value' => $defaults['geolocation_enable'],
    '#return_value' => 1,
    '#description' => t('For use on mobile devices.'),
  );
  $form['geolocation_mobile_check'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable check for mobiles'),
    '#default_value' => $defaults['geolocation_mobile_check'],
    '#return_value' => 1,
    '#description' => t('Enable geolocation for mobile devices only.'),
    '#prefix' => '<div id="wrap-getdirections-geolocation-options">',
  );
  $geo_opts = array(
    1 => t('Browser based geocoding'),
  );
  if (module_exists('smart_ip')) {
    $geo_opts[2] = t('Smart IP based geocoding');
  }
  if (module_exists('ip_geoloc')) {
    $geo_opts[3] = t('IP Geolocation based geocoding');
  }
  $form['geolocation_option'] = array(
    '#type' => 'radios',
    '#title' => t('Geolocation option'),
    '#default_value' => $defaults['geolocation_option'],
    '#options' => $geo_opts,
    '#suffix' => '</div>',
  );
  $form['trafficinfo'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Traffic information'),
    '#default_value' => $defaults['trafficinfo'],
    '#description' => t('Google trafficinfo layer, limited availability.'),
    '#return_value' => 1,
  );
  $form['trafficinfo']['#suffix'] = '<div id="wrap-getdirections-trafficinfo">';
  $form['trafficinfo_state'] = array(
    '#type' => 'checkbox',
    '#title' => t('Activate Traffic information'),
    '#default_value' => $defaults['trafficinfo_state'],
    '#description' => t('Activate Traffic layer when map is first displayed'),
    '#return_value' => 1,
  );
  $form['trafficinfo_state']['#suffix'] = '</div>';
  $form['bicycleinfo'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Bicycling information'),
    '#default_value' => $defaults['bicycleinfo'],
    '#description' => t('Google bicycling layer, limited availability.'),
    '#return_value' => 1,
  );
  $form['bicycleinfo']['#suffix'] = '<div id="wrap-getdirections-bicycleinfo">';
  $form['bicycleinfo_state'] = array(
    '#type' => 'checkbox',
    '#title' => t('Activate Bicycling information'),
    '#default_value' => $defaults['bicycleinfo_state'],
    '#description' => t('Activate Bicycling layer when map is first displayed'),
    '#return_value' => 1,
  );
  $form['bicycleinfo_state']['#suffix'] = '</div>';
  $form['transitinfo'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Public transport information'),
    '#default_value' => $defaults['transitinfo'],
    '#description' => t('Google transit layer, limited availability.'),
    '#return_value' => 1,
  );
  $form['transitinfo']['#suffix'] = '<div id="wrap-getdirections-transitinfo">';
  $form['transitinfo_state'] = array(
    '#type' => 'checkbox',
    '#title' => t('Activate Transit information'),
    '#default_value' => $defaults['transitinfo_state'],
    '#description' => t('Activate Transit layer when map is first displayed'),
    '#return_value' => 1,
  );
  $form['transitinfo_state']['#suffix'] = '</div>';
  if ($config) {
    $form['panoramio_use'] = array(
      '#type' => 'checkbox',
      '#title' => t('Load Panoramio Library'),
      '#default_value' => $defaults['panoramio_use'],
      '#description' => t('Provide Google panoramio library to all maps.'),
      '#return_value' => 1,
    );
    $form['panoramio_use']['#suffix'] = '<div id="wrap-getdirections-panoramio-use">';
    $form['panoramio_show'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Panoramio'),
      '#default_value' => $defaults['panoramio_show'],
      '#description' => t('Google panoramio picture links.'),
      '#return_value' => 1,
    );
    $form['panoramio_show']['#suffix'] = '<div id="wrap-getdirections-panoramio">';
    $form['panoramio_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Panoramio'),
      '#default_value' => $defaults['panoramio_state'],
      '#description' => t('Activate Panoramio layer when map is first displayed'),
      '#return_value' => 1,
    );
    $form['panoramio_state']['#suffix'] = '</div></div>';
  }
  elseif ($defaults['panoramio_use']) {
    $form['panoramio_show'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Panoramio'),
      '#default_value' => $defaults['panoramio_show'],
      '#description' => t('Google panoramio picture links.'),
      '#return_value' => 1,
    );
    $form['panoramio_show']['#suffix'] = '<div id="wrap-getdirections-panoramio">';
    $form['panoramio_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Panoramio'),
      '#default_value' => $defaults['panoramio_state'],
      '#description' => t('Activate Panoramio layer when map is first displayed'),
      '#return_value' => 1,
    );
    $form['panoramio_state']['#suffix'] = '</div>';
  }
  if ($config) {

    // weather
    $form['weather_use'] = array(
      '#type' => 'checkbox',
      '#title' => t('Load Weather Library'),
      '#default_value' => $defaults['weather_use'],
      '#description' => t('Provide Google Weather library to all maps.'),
      '#return_value' => 1,
    );
    $form['weather_use']['#suffix'] = '<div id="wrap-getdirections-weather-use">';
    $form['weather_show'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Weather information'),
      '#default_value' => $defaults['weather_show'],
      '#description' => t('Google Weather information.'),
      '#return_value' => 1,
    );
    $form['weather_show']['#suffix'] = '<div id="wrap-getdirections-weather">';
    $form['weather_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Weather information'),
      '#default_value' => $defaults['weather_state'],
      '#description' => t('Activate Weather information when map is first displayed.'),
      '#return_value' => 1,
    );
    $form['weather_temp'] = array(
      '#type' => 'select',
      '#title' => t('Temperature units'),
      '#default_value' => $defaults['weather_temp'],
      '#options' => array(
        1 => t('Celsius'),
        2 => t('Fahrenheit'),
      ),
    );
    $form['weather_speed'] = array(
      '#type' => 'select',
      '#title' => t('Windspeed units'),
      '#default_value' => $defaults['weather_speed'],
      '#options' => array(
        1 => t('Kilometers per hour'),
        2 => t('Meters per second'),
        3 => t('Miles per hour'),
      ),
    );
    $form['weather_label'] = array(
      '#type' => 'select',
      '#title' => t('Label colour'),
      '#default_value' => $defaults['weather_label'],
      '#options' => array(
        0 => 'Auto',
        1 => t('Black'),
        2 => t('White'),
      ),
    );
    $form['weather_clickable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable clicking on maps'),
      '#default_value' => $defaults['weather_clickable'],
      '#return_value' => 1,
    );
    $form['weather_info'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable weather InfoWindows'),
      '#default_value' => $defaults['weather_info'],
      '#return_value' => 1,
    );
    $form['weather_info']['#suffix'] = '</div>';
    $form['weather_cloud'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Cloud Layer'),
      '#default_value' => $defaults['weather_cloud'],
      '#description' => t('Google Cloud information.'),
      '#return_value' => 1,
    );
    $form['weather_cloud']['#suffix'] = '<div id="wrap-getdirections-weather-cloud">';
    $form['weather_cloud_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Cloud Layer'),
      '#default_value' => $defaults['weather_cloud_state'],
      '#description' => t('Activate Cloud layer when map is first displayed.'),
      '#return_value' => 1,
    );
    $form['weather_cloud_state']['#suffix'] = '</div></div>';
  }
  elseif ($defaults['weather_use']) {
    $form['weather_show'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Weather information'),
      '#default_value' => $defaults['weather_show'],
      '#description' => t('Google Weather information.'),
      '#return_value' => 1,
    );
    $form['weather_show']['#suffix'] = '<div id="wrap-getdirections-weather">';
    $form['weather_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Weather information'),
      '#default_value' => $defaults['weather_state'],
      '#description' => t('Activate Weather information when map is first displayed.'),
      '#return_value' => 1,
    );
    $form['weather_state']['#suffix'] = '</div>';
    $form['weather_cloud'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Cloud Layer'),
      '#default_value' => $defaults['weather_cloud'],
      '#description' => t('Google Cloud information.'),
      '#return_value' => 1,
    );
    $form['weather_cloud']['#suffix'] = '<div id="wrap-getdirections-weather-cloud">';
    $form['weather_cloud_state'] = array(
      '#type' => 'checkbox',
      '#title' => t('Activate Cloud Layer'),
      '#default_value' => $defaults['weather_cloud_state'],
      '#description' => t('Activate Cloud layer when map is first displayed.'),
      '#return_value' => 1,
    );
    $form['weather_cloud_state']['#suffix'] = '</div>';
  }
  if ($extras) {
    if (!$defaults['use_advanced']) {
      $form['switchfromto'] = array(
        '#type' => 'checkbox',
        '#title' => t('Enable From/To Switch'),
        '#default_value' => $defaults['switchfromto'],
        '#return_value' => 1,
      );
    }
    else {
      $form['switchfromto'] = array(
        '#type' => 'value',
        '#value' => 0,
      );
    }
  }
  return $form;
}

/**
 * Convert an addressfield
 *
 */
function getdirections_addressfield_convert($address) {
  $location = theme('getdirections_addressfield_convert', array(
    'address' => $address,
  ));
  return $location;
}

/**
 * Check that an entity type is location enabled.
 *
 */
function getdirections_check_entity_type($entity_type = '', $bundle = '') {
  if ($entity_type == 'term') {
    $entity_type = 'taxonomy_term';
  }
  $module = getdirections_get_current_supported_module();
  if ($module) {
    $query = db_select('field_config', 'f');
    $query
      ->fields('f', array(
      'id',
    ));
    $query
      ->join('field_config_instance', 'i', 'f.id=i.field_id');
    $query
      ->condition('f.module', $module);
    if ($entity_type) {
      $query
        ->condition('i.entity_type', $entity_type);
    }
    if ($bundle) {
      $query
        ->condition('i.bundle', $bundle);
    }
    $query
      ->condition('f.active', 1);
    $number_of_rows = $query
      ->countQuery()
      ->execute()
      ->fetchField();
    if ($number_of_rows) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Return fieldable entities
 *
 */
function getdirections_get_fieldable_entity_types() {
  $entity_get_info = entity_get_info();
  $fieldables = array();
  foreach ($entity_get_info as $entity_type => $info) {
    if (isset($entity_get_info[$entity_type]['fieldable']) && $entity_get_info[$entity_type]['fieldable']) {
      $fieldables[] = $entity_type;
    }
  }
  return $fieldables;
}

/**
 * Return fieldable entities
 *
 */
function getdirections_get_enabled_entity_types() {
  $entity_types = array();
  $fieldables = getdirections_get_fieldable_entity_types();
  foreach ($fieldables as $entity_type) {
    if (getdirections_check_entity_type($entity_type)) {
      $entity_types[] = $entity_type;
    }
  }
  return $entity_types;
}

/**
 * Provide an array of vocabularies.
 *
 */
function getdirections_get_vocabularies() {
  if (module_exists('taxonomy')) {
    $vocabularies = taxonomy_get_vocabularies();
    $options = array();
    if (count($vocabularies)) {
      foreach ($vocabularies as $vid => $vocabulary) {
        if (getdirections_check_vocabulary($vocabulary->machine_name)) {
          $options[$vid] = $vocabulary->name;
        }
      }
      return $options;
    }
  }
  return FALSE;
}

/**
 * Check that a taxonomy type is fieldable.
 *
 */
function getdirections_check_vocabulary($machine_name) {
  if (module_exists('taxonomy')) {
    return getdirections_check_entity_type('taxonomy_term', $machine_name);
  }
  return FALSE;
}

/**
 * Fetch a list of the core Drupal list of countries.
 * from location module
 *
 * @param bool $upper Default uppercase
 *
 * @return array The countries array
 */
function getdirections_get_countries_list($upper = TRUE, $only_continents = '', $only_countries = '') {
  if (module_exists('countries')) {
    $filter = array(
      'enabled' => COUNTRIES_ENABLED,
    );
    if ($only_countries) {
      $only_countries = drupal_strtoupper($only_countries);
      $oc = explode(',', $only_countries);
      if (!empty($oc)) {
        $filter['countries'] = $oc;
      }
    }
    elseif (is_array($only_continents)) {
      $oc = array();
      foreach ($only_continents as $v) {
        $oc[] = $v;
      }
      if (!empty($oc)) {
        $filter['continents'] = $oc;
      }
    }
    $countries = countries_get_countries('name', $filter);
  }
  else {
    include_once DRUPAL_ROOT . '/includes/locale.inc';

    // Statically cache a version of the core Drupal list of countries
    $countries =& drupal_static(__FUNCTION__);
    if (!isset($countries) || empty($countries)) {
      $countries = country_get_list();
    }
  }
  if (!$upper) {
    $countries = array_change_key_case($countries, CASE_LOWER);
  }
  return $countries;
}

/**
 * Implements hook_theme().
 *
 * This lets us tell Drupal about our theme functions and their variables.
 */
function getdirections_theme() {
  return array(
    'getdirections_show' => array(
      'variables' => array(
        'form' => NULL,
        'mapid' => '',
        'width' => '',
        'height' => '',
        'entity_id' => 0,
        'entity_type' => '',
        'lid' => 0,
        'type' => '',
      ),
    ),
    'getdirections_show_locations' => array(
      'variables' => array(
        'mapid' => '',
        'width' => '',
        'height' => '',
        'fromlocs' => '',
        'tolocs' => '',
      ),
    ),
    'getdirections_show_locations_via' => array(
      'variables' => array(
        'mapid' => '',
        'width' => '',
        'height' => '',
        'locs' => NULL,
      ),
    ),
    'getdirections_direction_form' => array(
      'render element' => 'form',
    ),
    'getdirections_box' => array(
      'variables' => array(
        'content' => NULL,
      ),
      'template' => 'getdirections_box',
    ),
    'getdirections_loadaddress' => array(
      'variables' => array(
        'location' => array(),
        'addcountry' => FALSE,
      ),
    ),
    'getdirections_addressfield_loadaddress' => array(
      'variables' => array(
        'address' => array(),
        'addcountry' => FALSE,
      ),
    ),
    'getdirections_addressfield_convert' => array(
      'variables' => array(
        'address' => array(),
      ),
    ),
    'getdirections_settings_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Theme to use for when one or no locations are supplied.
 *
 */
function theme_getdirections_show($variables) {
  $form = $variables['form'];
  $width = $variables['width'];
  $height = $variables['height'];
  $entity_id = $variables['entity_id'];
  $entity_type = $variables['entity_type'];
  $mapid = $variables['mapid'];
  $lid = $variables['lid'];
  $type = $variables['type'];
  $output = '';
  $getdirections_returnlink_default = getdirections_returnlink_defaults();
  $getdirections_returnlink = variable_get('getdirections_returnlink', $getdirections_returnlink_default);
  if ($type !== 'location') {

    // entity way
    // permissions first
    if ($entity_id) {
      if (isset($getdirections_returnlink[$entity_type . '_enable']) && $getdirections_returnlink[$entity_type . '_enable']) {
        $linktext = $getdirections_returnlink[$entity_type . '_link'];
        $entity_get_info = entity_get_info($entity_type);
        $load_hook = $entity_get_info['load hook'];
        $obj = $load_hook($entity_id);
        $uri_func = $entity_get_info['uri callback'];
        $uri = $uri_func($obj);
        $entity_title = '';
        if (isset($entity_get_info['entity keys']['label'])) {
          $entity_title = $entity_get_info['entity keys']['label'];
        }
        elseif ($entity_type == 'user') {
          $entity_title = 'name';
        }
        if ($entity_title && isset($obj->{$entity_title})) {
          $linktext = preg_replace("/%n/", $obj->{$entity_title}, $linktext);
          $l = l($linktext, $uri['path']);
          $output .= '<div class="getdirections_returnlink">' . $l . '</div>';
        }
      }
    }
  }
  $output .= $form;
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  if ($getdirections_misc['show_distance']) {
    $output .= '<div id="getdirections_show_distance_' . $mapid . '"></div>';
  }
  if ($getdirections_misc['show_duration']) {
    $output .= '<div id="getdirections_show_duration_' . $mapid . '"></div>';
  }
  $help = '';
  if ($getdirections_defaults['use_advanced']) {
    if ($getdirections_defaults['waypoints'] > 0 && !$getdirections_defaults['advanced_alternate']) {
      $help = t('Drag <img src="http://labs.google.com/ridefinder/images/mm_20_!c.png"> to activate a waypoint', array(
        '!c' => $getdirections_defaults['waypoint_color'],
      ));
      if ($getdirections_defaults['advanced_autocomplete'] && $getdirections_defaults['advanced_autocomplete_via']) {
        $help .= ' ' . t('or use the Autocomplete boxes');
      }
    }
    elseif ($getdirections_defaults['advanced_alternate']) {
      $help = t('You can drag the route to change it');
    }
  }
  $output .= '<div id="getdirections_help_' . $mapid . '">' . $help . '</div>';
  $header = array();
  $rows[] = array(
    array(
      'data' => '<div id="getdirections_map_canvas_' . $mapid . '" style="width: ' . $width . '; height: ' . $height . '" ></div>',
      'valign' => 'top',
      'align' => 'center',
      'class' => array(
        'getdirections-map',
      ),
    ),
    array(
      'data' => ($getdirections_defaults['use_advanced'] && $getdirections_defaults['advanced_alternate'] ? '<button id="getdirections-undo-' . $mapid . '">' . t('Undo') . '</button>' : '') . '<div id="getdirections_directions_' . $mapid . '"></div>',
      'valign' => 'top',
      'align' => 'left',
      'class' => array(
        'getdirections-list',
      ),
    ),
  );
  $output .= '<div class="getdirections">' . theme('table', array(
    'header' => $header,
    'rows' => $rows,
  )) . '</div>';
  return $output;
}

/**
 * Theme to use for when both locations are supplied.
 *
 */
function theme_getdirections_show_locations($variables) {
  $width = $variables['width'];
  $height = $variables['height'];
  $fromlocs = $variables['fromlocs'];
  $tolocs = $variables['tolocs'];
  $mapid = $variables['mapid'];
  $output = "";
  $output .= "<div class='getdirections_display'><label>" . t('From') . ":</label> " . $fromlocs . "</div>";
  $output .= "<div class='getdirections_display'><label>" . t('To') . ":</label> " . $tolocs . "</div>";
  $getdirections_misc = getdirections_misc_defaults();
  if ($getdirections_misc['show_distance']) {
    $output .= '<div id="getdirections_show_distance_' . $mapid . '"></div>';
  }
  if ($getdirections_misc['show_duration']) {
    $output .= '<div id="getdirections_show_duration_' . $mapid . '"></div>';
  }
  $header = array();
  $rows[] = array(
    array(
      'data' => '<div id="getdirections_map_canvas_' . $mapid . '" style="width: ' . $width . '; height: ' . $height . '" ></div>',
      'valign' => 'top',
      'align' => 'center',
      'class' => array(
        'getdirections-map',
      ),
    ),
    array(
      'data' => '<div id="getdirections_directions_' . $mapid . '"></div>',
      'valign' => 'top',
      'align' => 'left',
      'class' => array(
        'getdirections-list',
      ),
    ),
  );
  $output .= '<div class="getdirections">' . theme('table', array(
    'header' => $header,
    'rows' => $rows,
  )) . '</div>';
  return $output;
}

/**
 * Theme to use for when both locations are supplied with waypoints.
 *
 */
function theme_getdirections_show_locations_via($variables) {
  $width = $variables['width'];
  $height = $variables['height'];
  $locs = $variables['locs'];
  $mapid = $variables['mapid'];
  $output = "";
  foreach ($locs as $key => $loc) {
    if ($key == 0) {
      $label = t('From');
    }
    elseif ($key == count($locs) - 1) {
      $label = t('To');
    }
    else {
      $label = t('Via');
    }
    $output .= "<div class='getdirections_display'><label>" . $label . ":</label> " . $loc . "</div>";
  }
  $getdirections_misc = getdirections_misc_defaults();
  if ($getdirections_misc['show_distance']) {
    $output .= '<div id="getdirections_show_distance_' . $mapid . '"></div>';
  }
  if ($getdirections_misc['show_duration']) {
    $output .= '<div id="getdirections_show_duration_' . $mapid . '"></div>';
  }
  $header = array();
  $rows[] = array(
    array(
      'data' => '<div id="getdirections_map_canvas_' . $mapid . '" style="width: ' . $width . '; height: ' . $height . '" ></div>',
      'valign' => 'top',
      'align' => 'center',
      'class' => array(
        'getdirections-map',
      ),
    ),
    array(
      'data' => '<div id="getdirections_directions_' . $mapid . '"></div>',
      'valign' => 'top',
      'align' => 'left',
      'class' => array(
        'getdirections-list',
      ),
    ),
  );
  $output .= '<div class="getdirections">' . theme('table', array(
    'header' => $header,
    'rows' => $rows,
  )) . '</div>';
  return $output;
}

/**
 * Themes the getdirections form.
 *
 */
function theme_getdirections_direction_form($variables) {
  $form = $variables['form'];
  $mapid = $form['mapid']['#value'];
  unset($form['mapid']);
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  if (isset($form['settings']['#value'])) {
    $settings = $form['settings']['#value'];
    $getdirections_defaults = $settings['default'];
    $getdirections_misc = $settings['misc'];
    unset($form['settings']);
  }
  $output = '';

  // if you want to do fancy things with the form, do it here ;-)
  if (isset($form['mto'])) {
    $form['mto']['#prefix'] = '<div class="container-inline getdirections_display">';
    $form['mto']['#suffix'] = '</div>';
  }
  if (isset($form['mfrom'])) {
    $form['mfrom']['#prefix'] = '<div class="container-inline getdirections_display">';
    $form['mfrom']['#suffix'] = '</div>';
  }
  if (isset($form['travelmode_' . $mapid])) {
    $form['travelmode_' . $mapid]['#prefix'] = '<div class="container-inline getdirections_display">';
    $form['travelmode_' . $mapid]['#suffix'] = '</div>';
  }
  if (isset($form['travelextras_' . $mapid])) {
    $form['travelextras_' . $mapid]['#prefix'] = '<div class="container-inline getdirections_display">';
    $form['travelextras_' . $mapid]['#suffix'] = '</div>';
  }
  if (!$getdirections_defaults['advanced_autocomplete']) {
    if ($getdirections_misc['geolocation_enable'] && getdirections_is_mobile()) {
      if ($getdirections_misc['geolocation_option'] == 1) {

        // html5 geolocation
        $geolocation_button = '<input type="button" value="' . t('Find Location') . '" title="' . t('Get the latitude and longitude for your current position from the browser') . '" id="getdirections_geolocation_button_from_' . $mapid . '" class="form-submit" />';
        $geolocation_button .= '<span id="getdirections_geolocation_status_from_' . $mapid . '" ></span>';
        $form['from_' . $mapid]['#field_suffix'] = '&nbsp;&nbsp;&nbsp;' . $geolocation_button;
      }
      elseif ($getdirections_misc['geolocation_option'] == 2 && module_exists('smart_ip')) {

        // smart ip
        $geolocation_button = '<input type="button" value="' . t('Locate by Smart IP') . '" title="' . t('Get the latitude and longitude for your current position from Smart IP') . '" id="getdirections_geolocation_button_from_' . $mapid . '" class="form-submit" />';
        $geolocation_button .= '<span id="getdirections_geolocation_status_from_' . $mapid . '" ></span>';
        $form['from_' . $mapid]['#field_suffix'] = '&nbsp;&nbsp;&nbsp;' . $geolocation_button;
      }
      elseif ($getdirections_misc['geolocation_option'] == 3 && module_exists('ip_geoloc')) {

        // ip_geoloc
        $geolocation_button = '<input type="button" value="' . t('Locate by IP Geolocation') . '" title="' . t('Get the latitude and longitude for your current position from IP Geolocation') . '" id="getdirections_geolocation_button_from_' . $mapid . '" class="form-submit" />';
        $geolocation_button .= '<span id="getdirections_geolocation_status_from_' . $mapid . '" ></span>';
        $form['from_' . $mapid]['#field_suffix'] = '&nbsp;&nbsp;&nbsp;' . $geolocation_button;
      }
    }
  }
  if ($getdirections_defaults['use_advanced']) {
    $desc = t('Fill in the form below.');
    $desc .= '<br />';
    $desc .= t('You can also click on the map and move the marker.');
    if (isset($form['country_from_' . $mapid])) {
      $desc = t('Select a country first, then type in a town.');
      $desc .= '<br />';
      $desc .= t('You can also click on the map and move the marker.');
      $form['country_from_' . $mapid]['#prefix'] = '<div id="getdirections_start_' . $mapid . '"><div class="container-inline getdirections_display">';
      $form['country_from_' . $mapid]['#suffix'] = '</div>';
    }
    if (isset($form['from_' . $mapid]) && $form['from_' . $mapid]['#type'] == 'textfield' && (module_exists('location') || module_exists('getlocations_fields')) && !$getdirections_defaults['advanced_autocomplete'] && isset($form['country_from_' . $mapid])) {
      $form['from_' . $mapid]['#suffix'] = '</div><div class="getdirections_start_info" id="getdirections_start_info_' . $mapid . '"></div>';
    }
    if (isset($form['country_to_' . $mapid])) {
      $form['country_to_' . $mapid]['#prefix'] = '<div id="getdirections_end_' . $mapid . '"><div class="container-inline getdirections_display">';
      $form['country_to_' . $mapid]['#suffix'] = '</div>';
    }
    if (isset($form['to_' . $mapid]) && $form['to_' . $mapid]['#type'] == 'textfield' && (module_exists('location') || module_exists('getlocations_fields')) && !$getdirections_defaults['advanced_autocomplete'] && isset($form['country_to_' . $mapid])) {
      $form['to_' . $mapid]['#suffix'] = '</div><div class="getdirections_end_info" id="getdirections_end_info_' . $mapid . '"></div>';
    }
    if ($getdirections_defaults['advanced_autocomplete'] && $getdirections_defaults['waypoints'] > 0 && $getdirections_defaults['advanced_autocomplete_via'] && !$getdirections_defaults['advanced_alternate']) {
      for ($ct = 1; $ct <= $getdirections_defaults['waypoints']; $ct++) {
        if ($ct == 1) {
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#prefix'] = '<div id="autocomplete_via_wrapper_' . $mapid . '"><div class="container-inline getdirections_display">';
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#suffix'] = '</div>';
        }
        elseif ($ct == $getdirections_defaults['waypoints']) {
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#prefix'] = '<div class="container-inline getdirections_display">';
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#suffix'] = '</div></div>';
        }
        else {
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#prefix'] = '<div class="container-inline getdirections_display">';
          $form['via_autocomplete_' . $mapid . '_' . $ct]['#suffix'] = '</div>';
        }
      }
    }
  }
  else {
    if (isset($form['country_from_' . $mapid])) {
      $form['country_from_' . $mapid]['#prefix'] = '<div class="container-inline getdirections_display">';
      $form['country_from_' . $mapid]['#suffix'] = '</div>';
    }
    if (isset($form['country_to_' . $mapid])) {
      $form['country_to_' . $mapid]['#prefix'] = '<div class="container-inline getdirections_display">';
      $form['country_to_' . $mapid]['#suffix'] = '</div>';
    }
    $desc = t('Fill in the form below.');
  }
  if (isset($form['switchfromto_' . $mapid])) {
    $form['switchfromto_' . $mapid]['#prefix'] = '<div id="getdirections_switchfromto_' . $mapid . '">';
    $form['switchfromto_' . $mapid]['#suffix'] = '</div>';
  }
  if (isset($form['next_' . $mapid])) {
    $form['next_' . $mapid]['#prefix'] = '<div id="getdirections_nextbtn_' . $mapid . '">';
    $form['next_' . $mapid]['#suffix'] = '</div>';
  }
  if (isset($form['submit_' . $mapid])) {
    $form['submit_' . $mapid]['#prefix'] = '<div id="getdirections_btn_' . $mapid . '">';
    $form['submit_' . $mapid]['#suffix'] = '</div>';
  }
  $output .= '<p class="description">' . $desc . '</p>';
  $output .= drupal_render_children($form);

  // buttons
  $buttons = array();
  $output_buttons = '';
  if ($getdirections_misc['trafficinfo']) {
    $buttons[] = '<input type="button" value="' . t('Traffic Info !t', array(
      '!t' => $getdirections_misc['trafficinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleTraffic_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['bicycleinfo']) {
    $buttons[] = '<input type="button" value="' . t('Bicycle Info !t', array(
      '!t' => $getdirections_misc['bicycleinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleBicycle_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['transitinfo']) {
    $buttons[] = '<input type="button" value="' . t('Transit Info !t', array(
      '!t' => $getdirections_misc['transitinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleTransit_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['panoramio_use'] && $getdirections_misc['panoramio_show']) {
    $buttons[] = '<input type="button" value="' . t('Panoramio !t', array(
      '!t' => $getdirections_misc['panoramio_state'] ? t('Off') : t('On'),
    )) . '" id="getdirections_togglePanoramio_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['weather_use']) {
    if ($getdirections_misc['weather_use'] && $getdirections_misc['weather_show']) {
      $buttons[] = '<input type="button" value="' . t('Weather !t', array(
        '!t' => $getdirections_misc['weather_state'] ? t('Off') : t('On'),
      )) . '" id="getdirections_toggleWeather_' . $mapid . '" class="form-submit" />';
    }
    if ($getdirections_misc['weather_cloud']) {
      $buttons[] = '<input type="button" value="' . t('Clouds !t', array(
        '!t' => $getdirections_misc['weather_cloud_state'] ? t('Off') : t('On'),
      )) . '" id="getdirections_toggleCloud_' . $mapid . '" class="form-submit" />';
    }
  }
  if (count($buttons)) {
    $output_buttons .= '<div class="getdirections_map_buttons container-inline">';
    $output_buttons .= implode('&nbsp;', $buttons);
    $output_buttons .= '</div>';
  }
  $output .= $output_buttons;
  return $output;
}

/**
 * For use with colorbox.
 *
 */
function template_preprocess_getdirections_box(&$variables) {
  if (module_exists('admin_menu')) {
    admin_menu_suppress();
  }
  drupal_add_js(GETDIRECTIONS_PATH . '/js/getdirections_box.js');

  // Construct page title
  if (drupal_get_title()) {
    $head_title = array(
      strip_tags(drupal_get_title()),
      variable_get('site_name', 'Drupal'),
    );
  }
  else {
    $head_title = array(
      variable_get('site_name', 'Drupal'),
    );
    if (variable_get('site_slogan', '')) {
      $head_title[] = variable_get('site_slogan', '');
    }
  }
  $variables['head_title'] = implode(' | ', $head_title);
  $variables['base_path'] = base_path();
  $variables['head'] = drupal_get_html_head();
  $variables['language'] = $GLOBALS['language'];
  $variables['language']->dir = $GLOBALS['language']->direction ? 'rtl' : 'ltr';
  $variables['css'] = drupal_add_css();
  $variables['styles'] = drupal_get_css();
  $variables['scripts'] = drupal_get_js();
  $variables['title'] = drupal_get_title();

  // Closure should be filled last.
  $variables['closure'] = theme('closure');

  // Compile a list of classes that are going to be applied to the body element.
  // This allows advanced theming based on context (home page, node of certain type, etc.).
  $body_classes = array();

  // Add a class that tells us whether we're on the front page or not.
  $body_classes[] = $variables['is_front'] ? 'front' : 'not-front';

  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $body_classes[] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
  $body_classes[] = 'no-sidebars';

  // Implode with spaces.
  $variables['body_classes'] = implode(' ', $body_classes);
}

/**
 * Manipulates the address.
 *
 */
function theme_getdirections_loadaddress($variables) {
  $location = $variables['location'];
  $addcountry = $variables['addcountry'];
  $loc = array();

  #  if (isset($location['name']) && $location['name']) {

  #    $loc[] = $location['name'];

  #  }
  if (isset($location['street']) && $location['street']) {
    $loc[] = $location['street'];
  }
  if (isset($location['additional']) && $location['additional']) {
    $loc[] = $location['additional'];
  }
  if (isset($location['city']) && $location['city']) {
    $loc[] = $location['city'];
  }
  if (isset($location['province_name']) && $location['province_name']) {
    $loc[] = $location['province_name'];
  }
  if (isset($location['postal_code']) && $location['postal_code']) {
    $loc[] = $location['postal_code'];
  }
  if ($addcountry) {
    if (isset($location['country']) && $location['country']) {
      $loc[] = drupal_strtoupper($location['country']);
    }
  }
  $output = implode(', ', $loc);
  return $output;
}

/**
 * Handles addressfield
 *
 */
function theme_getdirections_addressfield_loadaddress($variables) {
  $address = $variables['address'];
  $addcountry = $variables['addcountry'];
  $location = getdirections_addressfield_convert($address);
  return theme('getdirections_loadaddress', array(
    'location' => $location,
    'addcountry' => $addcountry,
  ));
}

/**
 * Manipulates addressfield to make it compatible with $location
 *
 */
function theme_getdirections_addressfield_convert($variables) {
  $address = $variables['address'];
  $location = array();
  if (is_array($address) && !empty($address)) {
    $name = array();
    if (isset($address['name_line']) && $address['name_line']) {
      $name[] = $address['name_line'];
    }
    if (isset($address['first_name']) && $address['first_name']) {
      if (isset($address['last_name']) && $address['last_name']) {
        $name[] = $address['first_name'] . ' ' . $address['last_name'];
      }
      else {
        $name[] = $address['first_name'];
      }
    }
    elseif (isset($address['last_name']) && $address['last_name']) {
      $name[] = $address['last_name'];
    }
    if (isset($address['organisation_name']) && $address['organisation_name']) {
      $name[] = $address['organisation_name'];
    }
    $location['name'] = count($name) ? implode(", ", $name) : '';
    $location['street'] = isset($address['thoroughfare']) ? $address['thoroughfare'] : '';
    $additional = array();
    if (isset($address['premise']) && $address['premise']) {
      $additional[] = $address['premise'];
    }
    if (isset($address['sub_premise']) && $address['sub_premise']) {
      $additional[] = $address['sub_premise'];
    }
    $location['additional'] = count($additional) ? implode(", ", $additional) : '';
    $city = array();
    if (isset($address['dependent_locality']) && $address['dependent_locality']) {
      $city[] = $address['dependent_locality'];
    }
    if (isset($address['locality']) && $address['locality']) {
      $city[] = $address['locality'];
    }
    $location['city'] = count($city) ? implode(", ", $city) : '';
    $admin_area = array();
    if (isset($address['sub_administrative_area']) && $address['sub_administrative_area']) {
      $admin_area[] = $address['sub_administrative_area'];
    }
    if (isset($address['administrative_area']) && $address['administrative_area']) {
      $admin_area[] = $address['administrative_area'];
    }
    $location['province_name'] = count($admin_area) ? implode(", ", $admin_area) : '';
    $location['postal_code'] = isset($address['postal_code']) ? drupal_strtoupper($address['postal_code']) : '';
    $location['country_name'] = isset($address['country_name']) ? $address['country_name'] : $address['country'];
    $location['country'] = $address['country'];
  }
  return $location;
}
function theme_getdirections_settings_form($variables) {
  $form = $variables['form'];
  $output = '';
  $getdirections_defaults = getdirections_defaults();
  $getdirections_misc = getdirections_misc_defaults();
  $getdirections_defaults['preview_map'] = 1;
  getdirections_setup_map($getdirections_defaults, $getdirections_misc);
  $getdirections_settings = getdirections_get_settings($getdirections_defaults, $getdirections_misc);
  $mapid = getdirections_get_key();
  drupal_add_js(array(
    'getdirections_preview' => array(
      $mapid => $getdirections_settings,
    ),
  ), 'setting');
  if (empty($width)) {
    $width = $getdirections_defaults['width'];
  }
  if (empty($height)) {
    $height = $getdirections_defaults['height'];
  }
  $preview_map = '<div id="getdirections_preview_map_canvas_' . $mapid . '" style="width:' . $width . '; height:' . $height . ';" ></div>';

  // buttons
  $buttons = array();
  $output_buttons = '';
  if ($getdirections_misc['trafficinfo']) {
    $buttons[] = '<input type="button" value="' . t('Traffic Info !t', array(
      '!t' => $getdirections_misc['trafficinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleTraffic_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['bicycleinfo']) {
    $buttons[] = '<input type="button" value="' . t('Bicycle Info !t', array(
      '!t' => $getdirections_misc['bicycleinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleBicycle_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['transitinfo']) {
    $buttons[] = '<input type="button" value="' . t('Transit Info !t', array(
      '!t' => $getdirections_misc['transitinfo_state'] ? t('Off') : t('On'),
    )) . '" title="' . t('Limited Availability') . '" id="getdirections_toggleTransit_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['panoramio_use'] && $getdirections_misc['panoramio_show']) {
    $buttons[] = '<input type="button" value="' . t('Panoramio !t', array(
      '!t' => $getdirections_misc['panoramio_state'] ? t('Off') : t('On'),
    )) . '" id="getdirections_togglePanoramio_' . $mapid . '" class="form-submit" />';
  }
  if ($getdirections_misc['weather_use']) {
    if ($getdirections_misc['weather_use'] && $getdirections_misc['weather_show']) {
      $buttons[] = '<input type="button" value="' . t('Weather !t', array(
        '!t' => $getdirections_misc['weather_state'] ? t('Off') : t('On'),
      )) . '" id="getdirections_toggleWeather_' . $mapid . '" class="form-submit" />';
    }
    if ($getdirections_misc['weather_cloud']) {
      $buttons[] = '<input type="button" value="' . t('Clouds !t', array(
        '!t' => $getdirections_misc['weather_cloud_state'] ? t('Off') : t('On'),
      )) . '" id="getdirections_toggleCloud_' . $mapid . '" class="form-submit" />';
    }
  }
  if (count($buttons)) {
    $output_buttons .= '<div class="getdirections_map_buttons container-inline">';
    $output_buttons .= implode('&nbsp;', $buttons);
    $output_buttons .= '</div>';
  }
  $preview_map .= $output_buttons;
  $form['getdirections_preview']['preview_map']['#markup'] = '<div id="getdirections_preview_map">' . $preview_map . '</div>';
  $output .= drupal_render_children($form);
  return $output;
}

Functions

Namesort descending Description
getdirections_access_location menu access functions
getdirections_access_user_location
getdirections_addressfield_convert Convert an addressfield
getdirections_adjust_vars Recursively merge the defaults with the current settings
getdirections_check Check if the config has been run
getdirections_check_entity_type Check that an entity type is location enabled.
getdirections_check_vocabulary Check that a taxonomy type is fieldable.
getdirections_colorbox_defaults
getdirections_colorbox_settings Colorbox settings form
getdirections_comment_setlocation Function to setup the map and form
getdirections_defaults Some defaults.
getdirections_default_settings Default settings form
getdirections_direction Function to setup the map and form
getdirections_direction_box for colorbox and suchlike
getdirections_direction_form Function to setup the form
getdirections_direction_other Function to setup the map and form
getdirections_entity_setlocation Function to setup the map
getdirections_entity_setlocations Function to setup the map
getdirections_entity_setlocations_via Function to setup the map to display waypoints
getdirections_entity_type_load
getdirections_fromto_load menu placeholder functions
getdirections_get_countries_list Fetch a list of the core Drupal list of countries. from location module
getdirections_get_current_supported_module
getdirections_get_datestamp Fetch a timestamp
getdirections_get_enabled_entity_types Return fieldable entities
getdirections_get_fieldable_entity_types Return fieldable entities
getdirections_get_fieldname Get field names
getdirections_get_key
getdirections_get_lid_title Function to get the location name if available
getdirections_get_nid
getdirections_get_nid_from_lid
getdirections_get_settings
getdirections_get_tid_from_lid
getdirections_get_vid
getdirections_get_vocabularies Provide an array of vocabularies.
getdirections_help Implements hook_help().
getdirections_id_load
getdirections_init Implements hook_init().
getdirections_ip_geoloc
getdirections_is_mobile
getdirections_latlon Function to setup the map and form
getdirections_latlons Function to setup the map
getdirections_latlon_check Function to check a lat,lon string
getdirections_latlon_load
getdirections_load_latlon_defaults
getdirections_load_location Load a location
getdirections_load_locations Load one or more locations
getdirections_locations Function to setup the map
getdirections_locations_via Function to setup the map
getdirections_menu Implement hook_menu().
getdirections_misc_defaults
getdirections_misc_settings Miscellaneous settings form
getdirections_n2u_setlocation Function to setup the map
getdirections_node_setlocation Function to setup the map and form
getdirections_node_setlocations Function to setup the map
getdirections_node_setlocations_via Function to setup the map to display waypoints
getdirections_other_load_locations Load one or more locations For Geofield and Geolocation modules
getdirections_paths_get Get the javascript paths
getdirections_permission Implements hook_permission().
getdirections_returnlink_defaults
getdirections_returnlink_settings Configure returnlinks
getdirections_setlocation
getdirections_setlocation_id Function to setup the map and form
getdirections_setup_map Function to setup the map scripts
getdirections_smart_ip
getdirections_supported_modules
getdirections_term_setlocation Function to setup the map and form
getdirections_theme Implements hook_theme().
getdirections_u2n_setlocation Function to setup the map and form
getdirections_ua_get
getdirections_uid_load
getdirections_user_check Function to check the user status and existence
getdirections_user_setlocation Function to setup the map and form
getdirections_user_setlocations Function to setup the map
getdirections_user_setlocations_via Function to setup the map to display waypoints
getdirections_via_load
getdirections_views_api Implements hook_views_api().
template_preprocess_getdirections_box For use with colorbox.
theme_getdirections_addressfield_convert Manipulates addressfield to make it compatible with $location
theme_getdirections_addressfield_loadaddress Handles addressfield
theme_getdirections_direction_form Themes the getdirections form.
theme_getdirections_loadaddress Manipulates the address.
theme_getdirections_settings_form
theme_getdirections_show Theme to use for when one or no locations are supplied.
theme_getdirections_show_locations Theme to use for when both locations are supplied.
theme_getdirections_show_locations_via Theme to use for when both locations are supplied with waypoints.
_getdirections_addressfield_loadaddress Function to collect an address from addressfield
_getdirections_direction_form
_getdirections_loadaddress Function to collect an address

Constants

Namesort descending Description
GETDIRECTIONS_PATH @file Fetches google map directions.