<?php

/**
 * Implementation of hook_help().
 */
function digett_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      // This description is shown in the listing at admin/modules.
      return t('Utility module for Digett.');
  }
}

/**
 * Implementation of hook_menu().
 */
function digett_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'admin/block/delete_digett', 'title' => t('delete digett block'),
      'access' => user_access('administer blocks'),
      'callback' => 'digett_block_delete',
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/block/add_digett', 'title' => t('add digett block'),
      'access' => user_access('administer blocks'),
      'callback' => 'digett_block_add',
      'type' => MENU_LOCAL_TASK);
  }
  return $items;
}

/**
 * Menu callback; displays the block creation form.
 */
function digett_block_add() {
  $form = digett_block_form();
  $form['submit'] = array('#type' => 'submit', '#value' => t('Create block'));

  return drupal_get_form('digett_block_add', $form);
}

function digett_block_form($edit = array()) {
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
    '#default_value' => $edit['info'],
    '#maxlength' => 64,
    '#description' => t('A brief description of your block. Used on the <a href="%overview">block overview page</a>.', array('%overview' => url('admin/block'))),
    '#required' => TRUE,
    '#weight' => -19,
  );
  
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Select a block type'),
    '#default_value' => $edit['type'],
    '#required' => TRUE,
    '#options' => _digett_block_types(),
    '#weight' => -19,
  );

  return $form;
}

function digett_block_add_validate($form_id, $form_values) {
  if (empty($form_values['info']) || db_num_rows(db_query("SELECT info FROM {digett_blocks} WHERE info = '%s'", $form_values['info']))) {
    form_set_error('info', t('Please ensure that each block description is unique.'));
  }
}

function digett_block_add_submit($form_id, $form_values) {
  if (!form_get_errors()) {
    if (digett_block_save($form_values)) {
      drupal_set_message(t('The block has been created.'));
      return 'admin/block';
    }
  }
}

function _digett_block_types(){
  return array(
    'secondary_links' => 'Secondary Links',
    'random_image' => 'Random Image',
    'html_pod' => 'HTML Pod',
    'taxonomy' => 'Taxonomy List',
  );
}
    
function digett_block_save($edit, $delta = NULL) {
  if (isset($delta)) {
    foreach($edit as $key=>$value){
      if(strpos($key, 'digett_block_') === 0){
        $data[substr($key,strlen('digett_block_'))] = $value;
      }
    }
    $data_str = serialize($data);
    db_query("UPDATE {digett_blocks} SET data = '%s' WHERE delta = %d", $data_str, $delta);
  }
  else {
    db_query("INSERT INTO {digett_blocks} (info, type) VALUES  ('%s', '%s')", $edit['info'], $edit['type']);
  }
  return true;
}

function digett_block_get($delta) {
  $block = db_fetch_array(db_query('SELECT * FROM {digett_blocks} WHERE delta = %d', $delta));
  $block['data'] = unserialize($block['data']);
  return $block;
}

/**
 * Menu callback; confirm deletion of custom blocks.
 */

function digett_block_delete($delta = 0) {
  $block = digett_block_get($delta);
  $form['info'] = array('#type' => 'hidden', '#value' => $block['info']);
  $form['delta'] = array('#type' => 'hidden', '#value' => $delta);

  return confirm_form('digett_block_delete_confirm', $form, 
    t('Are you sure you want to delete the block %name?', array('%name' => 
      theme('placeholder', $block['info']))), 'admin/block', '', t('Delete'), t('Cancel'));
}

/**
 * Deletion of Custom blocks
 */

function digett_block_delete_confirm_submit($form_id, $form_values) {
  db_query('DELETE FROM {digett_blocks} WHERE delta = %d', $form_values['delta']);
  drupal_set_message(t('The digett block %name has been removed.', array('%name' => theme('placeholder', $form_values['info']))));
  cache_clear_all();
  return 'admin/block';
};



/**
 * Implementation of hook_block().
 */
function digett_block($op = 'list', $delta = 0, $edit = array()) {
  if($delta){
    $block = digett_block_get($delta);
    $name = str_replace(' ', '_', strtolower($block['type']));
    $function = '_digett_block_' . $name . '_' . $op;
    include_once(dirname(__FILE__) . '/blocks/' . $name . '.inc');
  }

  if ($op == 'list') {
    $result = db_query('SELECT * FROM {digett_blocks}');
    while($block = db_fetch_object($result)) {
      $blocks[$block->delta]['info'] = t($block->info) . ' - Digett Block';
    } 
    return $blocks;
  }
  else if ($op == 'configure') {
    return call_user_func($function, $block);
  }
  else if ($op == 'save') {
    digett_block_save($edit, $delta);
  }
  else if ($op == 'view') {
    return call_user_func($function, $block);
  }
}

function digett_block_variable_get(&$block, $key, $default){
  if(is_array($block['data']) && isset($block['data'][$key])){
    return $block['data'][$key];
  }else{
    return $default;
  }
}


function digett_form_alter($form_id, &$form) {
  if($form_id == 'block_admin_display'){
    foreach (element_children($form) as $i) {
      $block = $form[$i];
      if ($block['module']['#value'] == 'digett'){
        $form[$i]['delete'] = array('#value' => l(t('delete'), 'admin/block/delete_digett/'. $block['delta']['#value']));
      }
    }
  }
}

function _digett_block_section($mid=false){
  static $stored_mid = 'none';
  if($mid){
    $item = menu_get_item($mid);
    $stored_mid = str_replace(' ', '-', strtolower($item['title'])); 
  }
  return $stored_mid;
}
