<?php

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

// Implementation of hook_menu()
function lovegallery_menu($may_cache){
  if($may_cache){
    $items[] = array(
      'path' => 'gallery', 'title' => t('Photo Galleries'),
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK,
      'callback' => 'lovegallery_page');
  }
  return $items;
}

function lovegallery_page($tid=0){
  if($tid == 0){
    return lovegallery_listing();
  }
    
  $term = taxonomy_get_term($tid);
  if($term->vid != _image_gallery_get_vid()){
    return drupal_not_found();
  }

  if(db_num_rows(taxonomy_select_nodes(array($tid))) < 1){
    return '';
  }
  
  $swf = variable_get('lovegallery_swf', '%h%m/lovegallery.swf');
  $swf = str_replace(array('%h','%m','%t'), array(base_path(), drupal_get_path('module','lovegallery'), path_to_theme()), $swf);
  $h = variable_get('lovegallery_height', '585');
  $w = variable_get('lovegallery_width', '640');
  $bg = variable_get('lovegallery_bgcolor', '#000000');
  $ver = variable_get('lovegallery_version', '7');
  $trans = (variable_get('lovegallery_transparent',false)) ? 'transparent' : 'opaque';
  $photoPath = base_path().file_directory_path().'/';
  $random = variable_get('lovegallery_random', false) ? 'true' : 'false';
  $text = check_markup(
    variable_get('lovegallery_replacement_text','<p><a href="http://www.adobe.com">Click Here</a> to upgrade your Flash player in order to view this gallery.</p>'),
    variable_get('lovegallery_replacement_format',1), FALSE);
  $id = 'lovegallery';
  $content = <<<JS
    <div id="flash-lovegallery">{$text}</div>
    <script type="text/javascript">
      var $id = new SWFObject("$swf",
        "lovegallery","$w","$h","$ver", "$bg");
      $id.addVariable("photoPath", "$photoPath");
      $id.addVariable("myTagId", "$tid");
      $id.addVariable("myRandom", $random);
      $id.addParam("wmode","$trans");
      $id.write("flash-lovegallery");
    </script>
JS;

  drupal_set_title($term->name);
  drupal_add_js(drupal_get_path('module','lovegallery').'/js/swfobject.js');  
  return theme('lovegallery_page',$term,$content);
}

function lovegallery_listing(){
  $galleries = taxonomy_get_tree(_image_gallery_get_vid(), 0, -1, 1);
  foreach($galleries as $gallery){
    $count = taxonomy_term_count_nodes($gallery->tid, 'image');
    $items[] = l($gallery->name, 'gallery/'.$gallery->tid) . ' ('
      . format_plural($count, '1 image', '%count images') . ')'; 
  }
  return theme('item_list', $items);  
}

function theme_lovegallery_page($term, $content){
  if($term->description){
    $output .= '<div class="description">'.$term->description.'</div>';
  }
  $output .= $content;
  $output .= '<p>&laquo '.l('Back to thumbnail gallery','image/tid/'.$term->tid).'</p>';
  return $output;
}

// Implementation of hook_settings()
function lovegallery_settings() {
  $form['swf'] = array(
    '#type' => 'fieldset',
    '#title' => t('Flash File Information'),
    '#collapsible' => false
  );
  $form['swf']['lovegallery_swf'] = array(
    '#type' => 'textfield', 
    '#title' => t('Flash file (.swf) location'), 
    '#default_value' => variable_get('lovegallery_swf', '%h%m/lovegallery.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>%m (path to module: modules/lovegallery/)</li><li>%t (path to theme: theme/yourtheme/)</li></ul>')        
  );
  $form['swf']['lovegallery_height'] = array(
    '#type' => 'textfield', 
    '#title' => t('Height'), 
    '#default_value' => variable_get('lovegallery_height', '585'),
    '#size' => 5,
    '#description' => t('The height of the gallery in pixels, but without px')
  );
  $form['swf']['lovegallery_width'] = array(
    '#type' => 'textfield', 
    '#title' => t('Width'), 
    '#default_value' => variable_get('lovegallery_width', '640'),
    '#size' => 5,
    '#description' => t('The width of the gallery in pixels, but without px')
  );
  $form['swf']['lovegallery_version'] = array(
    '#type' => 'textfield', 
    '#title' => t('Version'), 
    '#default_value' => variable_get('lovegallery_version', '7'),
    '#size' => 5,
    '#description' => t('The minimum required flash version')
  );  
  $form['swf']['lovegallery_bgcolor'] = array(
    '#type' => 'textfield', 
    '#title' => t('Background color'), 
    '#default_value' => variable_get('lovegallery_bgcolor', '#000000'),
    '#size' => 10,
    '#description' => t('The HTML color code for the background color of the movie (ex: #FFFFFF)')
  );
  $form['swf']['lovegallery_transparent'] = array(
    '#type' => 'checkbox', 
    '#title' => t('Transparent'), 
    '#description' => t('Use a transparent background?'),
    '#default_value' => variable_get('lovegallery_transparent', false),        
  );
  
  $form['images'] = array(
    '#type' => 'fieldset',
    '#title' => 'imagecache presets',
  );
  $form['images']['lovegallery_thumbnail'] = array(
    '#type' => 'select',
    '#title' => t('Thumbnail Preset'),
    '#description' => t('Choose the imagecache preset to use for the thumbnail images'),
    '#default_value' => variable_get('lovegallery_thumbnail',0),
    '#options' => _imagecache_get_presets(),
  );
  $form['images']['lovegallery_fullsize'] = array(
    '#type' => 'select',
    '#title' => t('Fullsize Preset'),
    '#description' => t('Choose the imagecache preset to use for the full-size images'),
    '#default_value' => variable_get('lovegallery_fullsize',0),
    '#options' => _imagecache_get_presets(),
  );
  
  $form['replacement'] = array(
    '#type' => 'fieldset',
    '#title' => 'Replacement Text',
  );
  $form['replacement']['lovegallery_replacement_text'] = array(
    '#type' => 'textarea',
    '#default_value' => variable_get('lovegallery_replacement_text','<p><a href="http://www.adobe.com">Click Here</a> to upgrade your Flash player in order to view this gallery.</p>'),
    '#cols' => 60,
    '#rows' => 6,
    '#description' => t('Text to display if an appropriate flash plugin is not found.'),
  );
  
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => 'Options',
  );
  $form['options']['lovegallery_random'] = array(
    '#type' => 'select',
    '#title' => 'Random',
    '#description' => 'Start on a random image',
    '#options' => array(0=>'No', 1=>'Yes'),
    '#default_value' => variable_get('lovegallery_random',0),
  );

  $form['replacement']['lovegallery_replacement_format'] = filter_form(
    variable_get('lovegallery_replacement_format',1), 1, array('lovegallery_replacement_format'));
  
  return $form;
}

// Implementaion of hook_xmlrpc()
function lovegallery_xmlrpc() {
  return array(
    'lovegallery.getImages' => 'lovegallery_xmlrpc_getImages',
    'lovegallery.countImages' => 'lovegallery_xmlrpc_countImages');
}

function lovegallery_xmlrpc_countImages($tid){
  $sql = "SELECT n.nid FROM {term_node} t "
         . "INNER JOIN {node} n ON t.nid=n.nid "
         . "WHERE n.status=1 AND n.type='image' AND t.tid={$tid} "
         . "ORDER BY n.sticky DESC, n.created DESC";

  return db_num_rows(db_query($sql));
}  

function lovegallery_xmlrpc_getImages($tid=0,$limit=false,$start=0){
  $sql = "SELECT n.nid FROM {term_node} t "
         . "INNER JOIN {node} n ON t.nid=n.nid "
         . "WHERE n.status=1 AND n.type='image' AND t.tid={$tid} "
         . "ORDER BY n.sticky DESC, n.created ASC";

  $start = is_numeric($start) ? $start : 0;

  if($limit){
    $result = db_query_range(db_rewrite_sql($sql), $start, $limit);
  }else{
    $result = db_query(db_rewrite_sql($sql));
  }
  
  $presets = _imagecache_get_presets();
  $thumbnail = $presets[variable_get('lovegallery_thumbnail',0)];
  $gallery = $presets[variable_get('lovegallery_fullsize',0)];
  while($row = db_fetch_object($result)) {
    $temp = node_load(array('nid'=>$row->nid));
    $nodes[] = array(
      'nid' => $temp->nid,
      'title' => $temp->title,
      'body' => $temp->body,
      'thumbnail' => check_url('imagecache/'.$thumbnail.'/'.$temp->images['_original']),
      'gallery' => check_url('imagecache/'.$gallery.'/'.$temp->images['_original']),
      'fullsize' => $temp->images['_original'],
    );
  }
  
  return $nodes;
}


function _lovegallery_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 lovegallery_block($op = 'list', $delta = 1, $edit = array()) {
  global $user;

  switch ($op) {
    case 'list':
      for ($i=1;$i<=variable_get('lovegallery_number', '1');$i++) {
        $blocks[$i]['info'] = variable_get('lovegallery_name_'. $i, 'LoveGallery ' . $i);
      }
      return $blocks;
    break;

    case 'configure':
      $form['lovegallery_name_'. $delta] = array(
        '#type' => 'textfield', 
        '#title' => t('Block Name'), 
        '#default_value' => variable_get('lovegallery_name_'. $delta, 'Flash Gallery ' . $delta)
      );
      $form['lovegallery_gallery_'. $delta] = array(
        '#type' => 'select', 
        '#title' => t('Image Gallery'), 
        '#description' => t('The image gallery to pull the images from.'),
        '#default_value' => variable_get('lovegallery_gallery_'. $delta, '1'),
        '#options' => _lovegallery_image_galleries()
      );
      return $form;
    break;

    case 'save':
      variable_set('lovegallery_name_'. $delta, $edit['lovegallery_name_'.$delta]);
      variable_set('lovegallery_gallery_'. $delta, $edit['lovegallery_gallery_'.$delta]);
    break;

    case 'view':
      $block['content'] = lovegallery_page(variable_get('lovegallery_gallery_'.$delta,0));
      return $block; 
    break;
  }
}
