<?php
// $Id$

// Atomic Ant Simplemap module admin
// 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.

function simplemap_block_list() {
  $blocks = array();
  
  $locations = simplemap_get_locations();
  
  foreach($locations as $key=>$location) {
  
    $locationtitle = (isset($location['title']))?$location['title']:$key;
  
    $blocks[$key] = array(
      'info'       => t('Map : !index',array('!index'=>$locationtitle)),
      'weight'     => 0,
      'visibility' => 1,
      'cache' => BLOCK_NO_CACHE
    );
  }
  return $blocks;
}


function simplemap_settings_submit($form, &$form_state) {
  variable_set('simplemap_googleapikey',$form_state['values']['simplemap_googleapikey']);
}


function simplemap_block_configure($delta, $edit=array()) {
  return simplemap_map_form($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) {
  foreach (variable_get('simplemap_block_ids', array()) AS $delta) {
    $form['simplemap_' . $delta]['delete'] = array('#value' => l(t('delete'), 'admin/build/block/delete-map-block/'. $delta));
  }
}

/**
 * Deletion of menu blocks.
 */
function simplemap_delete_submit($form, &$form_state) {
  // Remove the menu block configuration variables.
  $delta = $form_state['values']['delta'];
  $block_ids = variable_get('simplemap_block_ids', array());
  unset($block_ids[array_search($delta, $block_ids)]);
  sort($block_ids);
  variable_set('simplemap_block_ids', $block_ids);
  variable_del("simplemap_block_{$delta}");

  db_query("DELETE FROM {blocks} WHERE module = 'simplemap' AND delta = %d", $delta);
  db_query("DELETE FROM {blocks_roles} WHERE module = 'simplemap' AND delta = %d", $delta);
  drupal_set_message(t('The "%name" block has been removed.', array('%name' => $form_state['values']['block_title'])));
  cache_clear_all();
  $form_state['redirect'] = 'admin/build/block';
  return;
}


function simplemap_settings() {

  // play nice with the gmap module
  if (module_exists('gmap')) {

    $form['simplemap_googleapikey'] = array(
      '#type' => 'markup',
      '#title' => t('Google Maps API Key'),
      '#value' => t('Since the GMAP module is installed Simplemap will use the Google Maps API key provided by it.  You can configure this setting under <a href="@gmapsettings">admin->settings->gmap</a>.  If the GMAP module is removed you will be able to add your api key here.  You can get a key by visiting <a href="@googlemappath">Google maps API sign up page</a>', array('@gmapsettings'=>url('admin/settings/gmap'),'@googlemappath'=>url('http://code.google.com/apis/maps/signup.html'))),
    );

  } else {

    $form['simplemap_googleapikey'] = array(
      '#type' => 'textfield',
      '#title' => t('Google Maps API Key'),
      '#description' => t('Please provide a valid google api key.  You can get a key by visiting <a href="@googlemappath">Google maps API sign up page</a>', array('@googlemappath'=>url('http://code.google.com/apis/maps/signup.html'))),
      '#default_value' => variable_get('simplemap_googleapikey', ''),
    );
    $form['#submit'][] = 'simplemap_settings_submit';
    $form['buttons']['submit'] = array('#type' => 'submit', '#value' => t('Save configuration') );

  }

  return $form;
}  


function simplemap_add_block_form(&$form_state) {
  $key = simplemap_get_api_key();
  if (empty($key)) {
    drupal_set_message('You must set a Google Maps API key in the Simplemap settings before you can add map blocks.','error');
    drupal_goto('admin/build/block');
  }
  include_once './' . drupal_get_path('module', 'block') . '/block.admin.inc';
  return block_admin_configure($form_state, 'simplemap', NULL);

}


function simplemap_add_block_form_submit($form, &$form_state) {
  // Determine the delta of the new block.
  $block_ids = variable_get('simplemap_block_ids', array());
  $delta = empty($block_ids) ? 1 : max($block_ids) + 1;

  // Save the new array of blocks IDs.
  $block_ids[] = $delta;
  
  // Save the block configuration.
  simplemap_block_save($delta, $form_state['values']);
  variable_set('simplemap_block_ids', $block_ids);

  // Run the normal new block submission (borrowed from block_add_block_form_submit).
  foreach (list_themes() as $key => $theme) {
    if ($theme->status) {
      db_query("INSERT INTO {blocks} (visibility, pages, custom, title, module, theme, status, weight, delta, cache) VALUES(%d, '%s', %d, '%s', '%s', '%s', %d, %d, %d, %d)", $form_state['values']['visibility'], trim($form_state['values']['pages']), $form_state['values']['custom'], $form_state['values']['title'], $form_state['values']['module'], $theme->name, 0, 0, $delta, BLOCK_NO_CACHE);
    }
  }

  foreach (array_filter($form_state['values']['roles']) as $rid) {
    db_query("INSERT INTO {blocks_roles} (rid, module, delta) VALUES (%d, '%s', '%s')", $rid, $form_state['values']['module'], $delta);
  }

  drupal_set_message(t('The block has been created.'));
  cache_clear_all();

  $form_state['redirect'] = 'admin/build/block';
}


function simplemap_map_form($delta,$edit=array()) {

  if (isset($delta)) {
    $mapsettings = simplemap_get_location($delta);
  } 

  if (!$mapsettings) {
    $mapsettings = array(
      'id'=>'new',
      'title'=>'',
      'zoomlevel'=>5,
      'lat'=>0,
      'lng'=>0,
      'markers'=>array(),
    );
  }

  if (!is_array($mapsettings['allowedtypes'])) $mapsettings['allowedtypes'] = array('map','satellite','hybrid');
  
  $form = array(
    '#type' => 'markup',
    '#prefix' => '<div id="simplemap-edit">',
    '#suffix' => '</div>'  
  );
  
  $form['locationtitle'] = array(
    '#type' => 'textfield',
    '#title' => t('Location Title'),
    '#description' => t('Type a name for this map. This is used only the block administration screen.'),
    '#default_value' => $mapsettings['title']
  );
  
  $mapid = 'simplemap'.$mapsettings['id'];
  $locationindex = 'location'.$index;
  $form[$mapid] = array(

    '#title' => 'Block '.$mapsettings['key'].' - '.$mapsettings['title'],
    '#description' => t('Define the location and details for block 1'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#tree' => TRUE
  );
  
  $form[$mapid]['map'] = array(
    '#title' => 'Map',
    '#description' => t('Define the location and details for block 1'),
    '#prefix' => '<div id="edit-'.$mapid.'-wrapper" style="margin-right:10px;" class="form-item"><label>Map:</label>',
    '#suffix' => '</div>',
    '#value' => simplemap_embedmap($mapsettings,true)
  );
  
  $form[$mapid]['centeraddress'] = array(
    '#type' => 'textfield',
    '#title' => t('Map Center Address'),
    '#description' => t('Type an address for the center of the map. This is only used to help you locate a position on the map'),
    '#default_value' => $settings['address'],
    '#attributes'=> array('class'=>'mapcenteraddress')
  );
  
  $form[$mapid]['markers'] = simplemap_markers_form($mapsettings);

  $form[$mapid]['advanced'] = array(
    '#type' => 'fieldset',
    '#title' => 'Advanced',
    '#description' => t('Advanced settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE
  );
   
  $form[$mapid]['advanced']['centerlat'] = array(
    '#type' => 'textfield',
    '#title' => 'Map Center Latitude',
    '#default_value' => $mapsettings['mapcenterlat'],
  );
  $form[$mapid]['advanced']['centerlng'] = array(
    '#type' => 'textfield',
    '#title' => 'Map Center Longitude',
    '#default_value' => $mapsettings['mapcenterlng'],
  );
  $form[$mapid]['advanced']['allowedtypes'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available Map Types'),
    '#description' => t('Choose the types of maps that the viewer can access. Note you can\'t remove the currently active type'),
    '#options' => array(
      'map' => t('Normal'),
      'satellite' => t('Satellite'),
      'hybrid' => t('Hybrid')
    ),        
    '#default_value' => $mapsettings['allowedtypes'],
    '#attributes'=> array('class'=>'allowedtypes')
  );
  $form[$mapid]['advanced']['zoomlevel'] = array(
    '#type' => 'hidden',
    '#title' => 'Zoomlevel',
    '#default_value' => $mapsettings['zoomlevel']
  );
  $form[$mapid]['advanced']['type'] = array(
    '#type' => 'hidden',
    '#title' => 'MapType',
    '#default_value' => $mapsettings['type']
  );

  
  return $form;
}


function simplemap_block_save($delta, $edit) {

  if (empty($edit['delta'])) {
    $mapdataindex = 'simplemapnew';
  } else {
    $mapdataindex = 'simplemap'.$delta;
  }
  
  $maptree = $edit[$mapdataindex];
  $markerindex = 'edit-'.$mapdataindex;
  $markerlist = isset($_POST[$markerindex]['markers'])?$_POST[$markerindex]['markers']:array();
  
  $markerobjlist = array();
  
  foreach($markerlist as $marker) {
    $markerobjlist[] = (object) $marker;    
  }
  
  $locationtitle = (empty($edit['locationtitle']))?('Map Block '.$delta):($edit['locationtitle']);
  
  $allowedtypes = array_keys(array_filter($maptree['advanced']['allowedtypes']));
  

  $mapsettings = array(
    'title'=>$locationtitle,
    'mapcenteraddress'=>$maptree['centeraddress'],
    'mapcenterlat'=>$maptree['advanced']['centerlat'],
    'mapcenterlng'=>$maptree['advanced']['centerlng'],
    'zoomlevel'=>$maptree['advanced']['zoomlevel'],
    'maptype'=>strtolower($maptree['advanced']['type']),
    'allowedtypes'=> $allowedtypes,
    'markers'=>$markerobjlist
    
  ); 
  
  variable_set('simplemap_block_'.$delta,$mapsettings);
}


/**
 * Menu callback: confirm deletion of map blocks.
 */
function simplemap_delete(&$form_state, $delta = 0) {
  $title = _simplemap_format_title($delta);
  $form['block_title'] = array('#type' => 'hidden', '#value' => $title);
  $form['delta'] = array('#type' => 'hidden', '#value' => $delta);

  return confirm_form($form, t('Are you sure you want to delete the "%name" block?', array('%name' => $title)), 'admin/build/block', NULL, t('Delete'), t('Cancel'));
}


function _simplemap_format_title($delta) {
  $location = simplemap_get_location($delta);
  return $location['title'];
}


function simplemap_markers_form($settings) {
  $mapid = $settings['id'];
  $description = t("Click the map to add markers. Markers may be updated by clicking them or their position changed by dragging the marker.  You can center the map on a marker by clicking on it's title in this list.  The id next to the marker gives the appropriate entry for theming markers in your THEME/simplemarkers.info file. If you are creating a new map you will need to save the map first and then edit to get the correct ids.");
  $form = array(
        '#type' => 'fieldset',
        '#prefix' => '<div id="edit-simplemap'.$mapid.'-markers-wrapper" class="form-item"><label>Markers:</label><div id="edit-simplemap'.$mapid.'-markers">',
        '#suffix' => '</div></div><div class="description">'.$description.'</div>',
        '#tree' => true,
        '#attributes' => array('class'=>'markerlist'),
        '#theme' => 'simplemap_marker_fieldset'  
  );

  if (empty($settings['markers'])) {
    $form[] = array();
  } else {
      foreach($settings['markers'] as $key=>$marker) {
        $markerfield = array();
    
        $markerfield['title'] = array(
          '#type' => 'hidden',
          '#value' => $marker->title
        );
        $markerfield['content'] = array(
          '#type' => 'hidden',
          '#value' => $marker->content
        );
        $markerfield['lat'] = array(
          '#type' => 'hidden',
          '#value' => $marker->lat
        );
        $markerfield['lng'] = array(
          '#type' => 'hidden',
          '#value' => $marker->lng
        );
        $form[$key] = $markerfield;
      }
  }

  return $form;
}


function simplemap_location_form($settings) {

  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $settings['title']
  );

  $form['#prefix'] = '<div class="simplemapaddress">';
  $form['#suffix'] = '</div>';
  
  return $form;
}
