<?php
// $Id$

// Atomic Ant Simplemap module
// Julian Thompson 2009
// julian@atomicant.co.uk
// www.atomicant.co.uk
// 
// Adds a new menu into blocks configuration 'Add map block' that allows the 
// addition of simple static maps with markers into a block.



define('SMNL',"\n");


/**
 * Implements hook_menu().
 */
function simplemap_menu() {
  $items['admin/build/block/add-map-block'] = array(
    'title' => 'Add map block',
    'description' => 'Add a new map block.',
    'access arguments' => array('administer blocks'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simplemap_add_block_form'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'simplemap.admin.inc',
  );
  $items['admin/build/block/delete-map-block'] = array(
    'title' => 'Delete map block',
    'access arguments' => array('administer blocks'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simplemap_delete'),
    'type' => MENU_CALLBACK,
    'file' => 'simplemap.admin.inc',
  );
  $items['admin/settings/simplemap'] = array(
    'title' => 'Simplemap',
    'description' => 'Settings for simple maps.',
    'position' => 'left',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simplemap_settings'),
    'access arguments' => array('administer site configuration'),
    'block callback' => 'simplemap_settings',
    'file' => 'simplemap.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_help().
 */

function simplemap_help($path, $arg) {
  switch ($path) {
    case 'admin/build/block/configure':
      if ($arg[4] != 'simplemap') {
        break;
      }
    case 'admin/help#simplemap':
    case 'admin/build/block':
    case 'admin/build/block/add-map-block':
      module_load_include('inc', 'simplemap', 'simplemap.pages');
      return _simplemap_help($path, $arg);
  }
}



/**
 * Implements hook_block().
 */
function simplemap_block($op = 'list', $delta = NULL, $edit = NULL) {

  $function = 'simplemap_block_' . $op;
  
  if (function_exists($function)) {
    return $function($delta, $edit);
  } else {
    module_load_include('inc', 'simplemap', 'simplemap.admin');
    if (function_exists($function)) {
      return $function($delta, $edit);
    }
  }
}


/**
 * Alters the block admin form to add delete links next to menu blocks.
 */
function simplemap_form_block_admin_display_form_alter(&$form, $form_state) {
  module_load_include('inc', 'menu_block', 'simplemap.admin');
  _simplemap_form_block_admin_display_form_alter($form, $form_state);
}


function simplemap_block_view($delta = 0) {
  return simplemap_location_map($delta);
}


function simplemap_theme() {
  return array(
    'simplemap_marker_fieldset' => array(
      'arguments' => array('element' => NULL),
    )
  );
}


function theme_simplemap_marker_fieldset($element) {
  return $element['#children'];
}


function simplemap_get_locations() {
  $locationkeys = variable_get('simplemap_block_ids', array());
  $locations = array();
  foreach($locationkeys as $delta) {
    if ($locationarray = variable_get('simplemap_block_'.$delta,false)) { 
      $locations[$delta] = $locationarray;
    }
  }
  return $locations;   
}


function simplemap_new_marker($title,$lat,$lng,$content) {
  $marker = new StdClass();
  
  $marker->title = $title;
  $marker->lat = $lat;
  $marker->lng = $lng;
  $marker->content = $content;
  
  return $marker;
}


function simplemap_get_theme_marker_image($key) {
  static $imagearray = false;
  
  if (!is_array($imagearray)) {
    $imagearray = array();
    $activetheme = variable_get('theme_default', 'garland');
    $themepath = drupal_get_path('theme', $activetheme);
    $markerconfigpath = $_SERVER['DOCUMENT_ROOT'].'/'.$themepath.'/simplemap.markers';
    if (file_exists($markerconfigpath)) {
      $imagebasepath = '/'.$themepath.'/';
      $options = parse_ini_file($markerconfigpath,true);
      foreach($options as $class=>$settings) {
        $icon = new StdClass();
        foreach($settings as $key=>$setting) {
          $tree = explode('-',$key);
          $valuekey=array_pop($tree);
          $current = $icon;
          if (!empty($tree)) {
            foreach($tree as $treeitem) {
              if (!isset($current->{$treeitem})) $current->{$treeitem} = new StdClass();
              $current = $current->{$treeitem};
            } 
          } 
          if ($valuekey=='path') $setting = $imagebasepath.$setting;
          $current->{$valuekey} = $setting;
        }
        if ($icon->image->path && (!$icon->image->width || !$icon->image->height)) {
          if ($size = simplemap_get_marker_dimensions($icon->image->path)) {
            if (!$icon->image->width) $icon->image->width = $size['width'];
            if (!$icon->image->height) $icon->image->height = $size['height'];
          }
        }
        if ($icon->shadow->path && (!$icon->shadow->width || !$icon->shadow->height)) {
          if ($size = simplemap_get_marker_dimensions($icon->shadow->path)) {
            if (!$icon->shadow->width) $icon->shadow->width = $size['width'];
            if (!$icon->shadow->height) $icon->shadow->height = $size['height'];
          }
        }
        $imagearray[$class] = $icon;
      }
    }
  }
  if (isset($imagearray[$key])) return $imagearray[$key];
  return false;
}


function simplemap_get_marker_dimensions($imagepath) {
  $imagedimensions = array();
    
  if(isset($imagedimensions[$imagepath])) {
    return $imagedimensions[$imagepath];
  } else {
    $fullpath = $_SERVER['DOCUMENT_ROOT'].'/'.$imagepath;
    if (file_exists($fullpath)) {
       if ($imagesize = getimagesize($fullpath)) {
         list($width, $height) = $imagesize;
         $sizes = array("width" => $width, "height" => $height);
         $imagedimensions[$imagepath] = $sizes;
         return $sizes;
       }    
    }
  }
  return false;
}


function simplemap_get_marker_images(&$location) {
  $default = simplemap_get_theme_marker_image('simplemap'.$location['id'].'-default');
  if (!$default) $default = simplemap_get_theme_marker_image('default');
  foreach($location['markers'] as $key=>$marker) {
    if ($markericon = simplemap_get_theme_marker_image('simplemap'.$location['id'].'-marker'.($key+1))) {
      $location['markers'][$key]->icon = $markericon;
    } elseif ($default) {
      $location['markers'][$key]->icon = $default;
    }
  }
}


function simplemap_get_location($delta) {
  if ($locationarray = variable_get('simplemap_block_'.$delta,false)) { 
    $locationarray['id'] = $delta;
    $locationarray['key'] = $delta;
    simplemap_get_marker_images($locationarray);
    return $locationarray;
  }
  return false;
}


function simplemap_get_api_key() {
  if (module_exists('gmap')) {
    $key = gmap_get_key();
    if (empty($key)) drupal_set_message('As the GMAP module is installed you must set a api key in the gmap module settings','error');
  } else {
    $key = variable_get('simplemap_googleapikey', '');
    if (empty($key)) drupal_set_message('You must set a api key in the simplemap settings','error');
  }
  return $key;
}


function simplemap_location_map($delta) {
  if ($mapsettings = simplemap_get_location($delta)) {
    $block = array();
    $block['subject'] = t($mapsettings['title']);
    $block['content'] = simplemap_embedmap($mapsettings);
    return $block;
  }
}



function simplemap_add_js_external($url) {
  static $staticurls = array();
  if (!in_array($url,$staticurls)) {
    drupal_add_js('//--><!]]>'.SMNL.'</script>'."\n".'<script type="text/javascript" src="'.$url.'" ></script>'.SMNL.'<script type="text/javascript">'.SMNL.'<!--//--><![CDATA[//><!--', 'inline');
    $staticurls[] = $url;
  }
}


function simplemap_embed($delta) {
    $block = simplemap_location_map($delta);
    if ($block) {
        return $block['content'];
    }
    return '';
}



function simplemap_embedmap($settings=array(),$edit=false) {

  $key = simplemap_get_api_key();

  if (!empty($key)) {
    $mapsurl = 'http://maps.google.com/maps?file=api&v=2&key='.simplemap_get_api_key();
    $settings['editmode'] = $edit;
  
    simplemap_add_js_external($mapsurl);
  
    drupal_add_css(drupal_get_path('module', 'simplemap') .'/css/simplemap.css'); 
  
    if ($edit) {
      drupal_add_css(drupal_get_path('module', 'simplemap') .'/css/simplemap.admin.css');  
    }
  
    $mappageid = 'simplemap'.$settings['id'];
  
    drupal_add_js(array('simplemap'=>array($mappageid=>$settings)),'setting'); 
   
    drupal_add_js(drupal_get_path('module', 'simplemap') .'/script/jquery.simplemap1.0-min.js');

    return '<div class="mapcanvas" id="'.$mappageid.'"></div>';
  }
  return '';
}


