<?php

// Implementation of hook_help()
function flashgallery_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      $output = t('Create Flash Photo Gallery blocks');
      break;
  }
  return $output;
}

// Implementation of hook_menu()
function flashgallery_menu($may_cache){
  if(!$may_cache){
    drupal_add_js(drupal_get_path('module','flashgallery').'/js/swfobject.js');
  }
  return array();
}

// Implementation of hook_settings()
function flashgallery_settings() {
  $form['flashgallery_number'] = array(
    '#type' => 'select', 
    '#title' => t('Number of Flash Gallery Blocks'), 
    '#description' => t('The total number of independent Flash Gallery Blocks you want.'),
    '#default_value' => variable_get('flashgallery_number', '1'),
    '#options' => drupal_map_assoc(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
  );
  $form['flashgallery_debug'] = array(
    '#type' => 'select', 
    '#title' => t('Debug'), 
    '#description' => t('Debug mode will display the raw html and javascript instead of using it to display the flash.'),
    '#default_value' => variable_get('flashgallery_debug', 'normal'),
    '#options' => drupal_map_assoc(array('normal','debug'))
  );
  return $form;
}

function _flashgallery_image_galleries(){
  $options = array();
  if(module_exist('nat')){
    $options[-1] = '[ NAT Value ]';
  }
  if ($tree = taxonomy_get_tree(_image_gallery_get_vid())) {
    foreach ($tree as $term) {
      $options[$term->tid] = _taxonomy_depth($term->depth) .' '. $term->name;
    }
  }
  return $options;
}  

// Implementation of hook_block().
function flashgallery_block($op = 'list', $delta = 1, $edit = array()) {
  global $user;

  switch ($op) {
    case 'list':
      for ($i=1;$i<=variable_get('flashgallery_number', '1');$i++) {
        $blocks[$i]['info'] = variable_get('flashgallery_name_'. $i, 'Flash Gallery ' . $i) . ' (Flash Gallery)';
      }
      return $blocks;
    break;

    case 'configure':
      $form['flashgallery_name_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Block Name'), 
        '#default_value' => variable_get('flashgallery_name_'. $delta, 'Flash Gallery ' . $delta)
      );
      $form['flashgallery_gallery_'. $delta] = array(
        '#type' => 'select', 
        '#title' => t('Image Gallery'), 
        '#description' => t('The image gallery to pull the images from.'),
        '#default_value' => variable_get('flashgallery_gallery_'. $delta, '1'),
        '#options' => _flashgallery_image_galleries()
      );
      $form['swf'] = array(
        '#type' => 'fieldset',
        '#title' => t('Flash File Information'),
        '#collapsible' => false
      );
      $form['swf']['flashgallery_swf_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Flash file (.swf) location'), 
        '#default_value' => variable_get('flashgallery_swf_'. $delta, 'gallery.swf'),
        '#description' => t('Enter the path to the flash file (example: "flash/gallery.swf").<br />Macros:<ul><li>%h (host name: http://www.example.com/)</li><li>%t (path to theme: theme/yourtheme/)</li></ul>')        
      );
      $form['swf']['flashgallery_height_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Height'), 
        '#default_value' => variable_get('flashgallery_height_'. $delta, '400'),
        '#size' => 5,
        '#description' => t('The height of the gallery in pixels, but without px')
      );
      $form['swf']['flashgallery_width_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Width'), 
        '#default_value' => variable_get('flashgallery_width_'. $delta, '400'),
        '#size' => 5,
        '#description' => t('The width of the gallery in pixels, but without px')
      );
      $form['swf']['flashgallery_bgcolor_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Background color'), 
        '#default_value' => variable_get('flashgallery_bgcolor_'. $delta, '#FFFFFF'),
        '#size' => 10,
        '#description' => t('The HTML color code for the background color of the movie (ex: #FFFFFF)')
      );
      $form['swf']['flashgallery_transparent_'. $delta] = array(
        '#type' => 'checkbox', 
        '#title' => t('Transparent'), 
        '#description' => t('Use a transparent background?'),
        '#default_value' => variable_get('flashgallery_transparent_'. $delta, false),        
      );
            
      return $form;
    break;

    case 'save':
      variable_set('flashgallery_name_'. $delta, $edit['flashgallery_name_'.$delta]);
      variable_set('flashgallery_gallery_'. $delta, $edit['flashgallery_gallery_'.$delta]);
      variable_set('flashgallery_swf_'. $delta, $edit['flashgallery_swf_'.$delta]);
      variable_set('flashgallery_height_'. $delta, $edit['flashgallery_height_'.$delta]);
      variable_set('flashgallery_width_'. $delta, $edit['flashgallery_width_'.$delta]);
      variable_set('flashgallery_bgcolor_'. $delta, $edit['flashgallery_bgcolor_'.$delta]);
      variable_set('flashgallery_transparent_'. $delta, $edit['flashgallery_transparent_'.$delta]);
    break;

    case 'view':
      if(variable_get('flashgallery_debug', 'normal') == 'debug'){
        $block['content'] = '<pre>'.htmlspecialchars(_flashgallery_block_view($delta)).'</pre>';
      }else{
        $block['content'] = _flashgallery_block_view($delta);
      }
      return $block; 
    break;
  }
}
  
function _flashgallery_block_view($delta = 1){
  $tid = variable_get('flashgallery_gallery_'. $delta, 1);
  // Set gallery tid to node nat tid from image_gallery vocab
  if($tid == '-1'){
    $node = node_load(arg(1));
    while($nat = array_shift($node->nat)){
      if($nat->vid = _image_gallery_get_vid()){
        $tid = $nat->tid;
        break;
      }
    }
    if($tid == '-1'){
      return '';  // no gallery found
    }
  }
  if(db_num_rows(taxonomy_select_nodes(array($tid))) < 1){
    return '';
  }
  
  $swf = variable_get('flashgallery_swf_'. $delta, 'gallery.swf');
  $swf = str_replace(array('%h', '%t'), array(base_path(), path_to_theme()), $swf);
  $h = variable_get('flashgallery_height_'. $delta, '400');
  $w = variable_get('flashgallery_width_'. $delta, '400');
  $bg = variable_get('flashgallery_bgcolor_'. $delta, '#FFFFFF');
  $trans = (variable_get('flashgallery_transparent_'.$delta,false)) ? 'transparent' : 'opaque';
  $photoPath = base_path().file_directory_path().'/';
  $id = 'flashgallery'.$delta;
  $output = <<<JS
    <div id="flash-block">
      <p>
        <a href="http://www.adobe.com">Click Here</a> to upgrade your
        Flash player in order to view this gallery.
      </p>
      <!-- flash goes here -->
    </div>
    <script type="text/javascript">
      var $id = new SWFObject("$swf",
        "flashgallery","$w","$h","7", "$bg");
      $id.addVariable("photoPath", "$photoPath");
      $id.addVariable("myTagId", "$tid");
      $id.addParam("wmode","$trans");
      $id.write("flash-block");
    </script>
JS;
  return $output;
}

/**
 * Implementation of hook_form_alter().
 */
function flashgallery_form_alter($form_id, &$form) {
  /* this is a check for module dependencies.  the only way we
    can ensure this check happening when the module is initially
    enabled is to insert the check for when the form is initially
    built, which will also be caught when the admin/module page is
    reloaded upon submission.  this means we never want to call this
    function when the form has been submitted, so make sure there's
    no $_POST. */
  if ($form_id == 'system_modules' && !$_POST) {
    _flashgallery_system_module_validate($form);
  }
}

/**
 * Validates module dependencies for the module.
 *
 * @param $form The form array passed from hook_form_alter.
 * 
 * Set the $module variable to a string which is the name of the module, minus
 * the .module extension.  Set $dependencies to an array of module names which
 * the module is dependent on--each element is a string which is the module name
 * minus the .module extension.  Note that this will not check for any dependencies
 * for the modules this module depends on--only those that are explicitly listed in
 * the $dependencies array.
 */
function _flashgallery_system_module_validate(&$form) {

  $module = 'flashgallery';
  $dependencies = array('image_gallery', 'flashxmlrpc');

  foreach ($dependencies as $dependency) {
      if (!in_array($dependency, $form['status']['#default_value'])) {
        $missing_dependency = TRUE;
        $missing_dependency_list[] = $dependency;
      }
  }

  if (in_array($module, $form['status']['#default_value']) && isset($missing_dependency)) {
    db_query("UPDATE {system} SET status = 0 WHERE type = 'module' AND name = '%s'", $module);
    $key = array_search($module, $form['status']['#default_value']);
    unset($form['status']['#default_value'][$key]);
    drupal_set_message(t('The module %module was deactivated--it requires the following disabled/non-existant modules to function properly: %dependencies', array('%module' => $module, '%dependencies' => implode(', ', $missing_dependency_list))), 'error');

  }

}
