<?php

/**
 * @file
 * wysiwyg_map.module
 */

/**
 * Implements hook_wysiwyg_include_directory().
 */
function wysiwyg_map_wysiwyg_include_directory($type) {
  switch ($type) {
    case 'plugins':
      return 'wysiwyg_plugins';
      break;

  }
}

/**
 * Implements hook_menu().
 */
function wysiwyg_map_menu() {
  $items = array();

  $items['wysiwyg-map/token-builder'] = array(
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wysiwyg_map_tokenbuilder_form'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Form builder for the google map field token builder.
 */
function wysiwyg_map_tokenbuilder_form($form, &$form_state) {
  drupal_set_title(t('WYSIWYG Map Token Builder'));

  $form = array();
  $form['token_builder']['map'] = array(
    '#markup' => theme('wysiwyg_map_selector'),
    '#prefix' => '<div class="wysiwyg-map-tokenbuilder clearfix"><div class="wysiwyg-map-tokenbuilder-map">',
    '#suffix' => '</div>',
  );
  $form['token_builder']['width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width'),
    '#size' => 15,
    '#default_value' => '300',
    '#attributes' => array('onkeyup' => 'return wysiwyg_map_buildToken();'),
    '#prefix' => '<div class="wysiwyg-map-tokenbuilder-fields">',
  );
  $form['token_builder']['height'] = array(
    '#type' => 'textfield',
    '#title' => t('Height'),
    '#size' => 15,
    '#default_value' => '250',
    '#attributes' => array('onkeyup' => 'return wysiwyg_map_buildToken();'),
  );
  $form['token_builder']['css_class'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS Class'),
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('onkeyup' => 'return wysiwyg_map_buildToken();'),
  );
  $form['token_builder']['map_type'] = array(
    '#type' => 'hidden',
    '#attributes' => array('id' => 'edit-map-type'),
    '#default_value' => 'roadmap',
  );
  $form['token_builder']['zoom'] = array(
    '#type' => 'hidden',
    '#default_value' => '9',
    '#attributes' => array('id' => 'edit-zoom'),
    '#suffix' => '</div></div>',
  );
  $form['token_builder']['token'] = array(
    '#type' => 'hidden',
    '#attributes' => array('id' => 'edit-token'),
    '#default_value' => 'lat=51.0,lon=0.12,width=300,height=250,zoom=9,map_type=roadmap',
  );
  $form['token_builder']['center_on'] = array(
    '#type' => 'textfield',
    '#title' => t('Center On'),
    '#description' => t('To center the map on an approximate location, enter the location in the box above, e.g. "London, UK" or "1 Southwark Street, London, UK" and click \'center\''),
  );
  $form['token_builder']['do_center'] = array(
    '#type' => 'button',
    '#value' => t('center'),
    '#attributes' => array('onclick' => 'return wysiwyg_map_doCenterPopup();'),
  );

  return $form;
}

/**
 * Implements hook_form_alter().
 */
function wysiwyg_map_form_alter(&$form, &$form_state, $form_id) {
  if ((isset($form['#node_edit_form']) && $form['#node_edit_form']) || $form_id == 'block_add_block_form') {
    drupal_add_css(drupal_get_path('module', 'wysiwyg_map') . '/wysiwyg_plugins/wysiwyg_map_tokenbuilder/wysiwyg_map_tokenbuilder.css');
    drupal_add_js('//maps.googleapis.com/maps/api/js?sensor=false', 'external');
    drupal_add_js(drupal_get_path('module', 'wysiwyg_map') . '/js/wysiwyg_map_edit_form.js', 'file');
    drupal_add_library('system', 'ui.dialog');
    drupal_add_library('system', 'ui.draggable');
  }
}

/**
 * Implements hook_theme().
 */
function wysiwyg_map_theme($existing, $type, $theme, $path) {
  if ($type == 'module') {
    return array(
      'wysiwyg_map_selector' => array(
        'render_element' => 'element',
      ),
      'wysiwyg_map_picker' => array(
        'render_element' => 'element',
      ),
      'wysiwyg_map_token' => array(
        'render_element' => 'element',
        'variables' => array(
          'delta' => NULL,
          'width' => NULL,
          'height' => NULL,
          'css_class' => NULL,
        ),
      ),
    );
  }
  return array();
}

/**
 * Theme function to return map selector div on token builder overlay.
 */
function theme_wysiwyg_map_selector($variables) {
  return '<div id="wysiwyg_map_selector"></div>';
}

/**
 * Theme function to return map div for tokenised maps.
 */
function theme_wysiwyg_map_token($variables) {
  if ($variables['css_class'] != '') {
    return '
      <div id="wysiwyg_map_' . $variables['delta'] . '" class="' . $variables['css_class'] . ' wysiwyg-map" style="width: ' . $variables['width'] . 'px; height: ' . $variables['height'] . 'px;"></div>
    ';
  }
  else {
    return '
      <div id="wysiwyg_map_' . $variables['delta'] . '" class="wysiwyg-map" style="width: ' . $variables['width'] . 'px; height: ' . $variables['height'] . 'px;"></div>
    ';
  }
}

/**
 * Implements hook_filter_info().
 */
function wysiwyg_map_filter_info() {
  $filters['wysiwyg_map_token'] = array(
    'title' => t('WYSIWYG Map'),
    'description' => t('Use tokens to insert Google Map directly into content.'),
    'process callback' => 'wysiwyg_map_filter_process',
    'cache' => FALSE,
    'weight' => 50,
  );
  return $filters;
}

/**
 * Process callback for hook_filter_info().
 */
function wysiwyg_map_filter_process($text, $filter, $format) {

  // we don't want to load the map apis for admin pages so return
  // the test as-is.
  if (path_is_admin(current_path())) { return $text; }

  drupal_add_js('//maps.googleapis.com/maps/api/js?sensor=false', 'external');

  $out = $text;
  $matches = array();
  preg_match_all('/lat\=(.*?)\;/', $out, $matches);
  $i = 0;
  $guid = uniqid();

  $maps = array();
  while (isset($matches[1][$i])) {
    $match = str_replace(';', '', $matches[0][$i]);
    $settings = explode('~', $match);
    $map_settings = array();
    $map_settings['container_id'] = $guid;
    foreach ($settings as $setting) {
      $offset = strpos($setting, '=');
      if ($offset !== FALSE) {
        $key = trim(substr($setting, 0, $offset));
        $val = trim(substr($setting, $offset + 1));
        $map_settings[$key] = $val;
      }
    }
    $maps[$i] = $map_settings;
    $replace = $matches[0][$i];
    $settings = array(
      'delta' => $guid,
      'width' => $map_settings['map_width'],
      'height' => $map_settings['map_height'],
      'css_class' => isset($map_settings['css_class']) ? $map_settings['css_class'] : '',
    );
    $replacement = theme('wysiwyg_map_token', $settings);
    $out = preg_replace('/' . $matches[0][$i] . '/', $replacement, $out, 1);
    $guid = uniqid();
    $i++;
  }
  $map_collection = array(
    'wysiwyg_map_maps' => $maps,
  );
  drupal_add_js(drupal_get_path('module', 'wysiwyg_map') . '/js/wysiwyg_map_token_maps.js');
  drupal_add_js($map_collection, 'setting');

  return $out;
}
