<?php
// $Id: prev_next_views.module,v 1.1.2.2 2010/05/17 16:54:07 jcnventura Exp $

/**
 * Implementation of hook_prev_next_nid().
 */
function prev_next_views_prev_next_nid($nid, $op = 'next') {
  if (isset($_SESSION['prev_next_views'])) {
    // There's a prev_next views list stored for this session
    $index = array_search($nid, $_SESSION['prev_next_views']);
    if ($index !== FALSE) {
      // This node is part of the prev_next list, so return the appropriate node
      $ret = $index;
      if ($op == 'prev') {
        $ret--;
      }
      elseif ($op == 'next') {
        $ret++;
      }

      if (($ret >= 0) && ($ret < count($_SESSION['prev_next_views']))) {
        return $_SESSION['prev_next_views'][$ret];
      }
      else {
        // First or last element of the view
        return 0;
      }
    }
  }
  return FALSE;
}


/**
 * Implementation of hook_perm().
 */
function prev_next_views_perm() {
  return array('administer prev_next_views');
}


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

  $items['admin/settings/prev_next/views'] = array(
    'title' => 'Views',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('prev_next_views_settings'),
    'access arguments'  => array('administer prev_next_views'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'file' => 'prev_next_views.admin.inc',
  );

  return $items;
}


/**
 * Implementation of hook_nodeapi().
 */
function prev_next_views_nodeapi(&$node, $op) {
  if (isset($_SESSION['prev_next_views']) && (array_search($node->nid, $_SESSION['prev_next_views']) === FALSE)) {
    // The current node is no longer part of the views results, so forget about it
    unset($_SESSION['prev_next_views']);
  }
}


/**
 * Implementation of hook_views_api().
 */
function prev_next_views_views_api() {
  return array(
    'api' => 2,
  );
}


/**
 * Implementation of hook_views_pre_execute().
 */
function prev_next_views_views_pre_execute(&$view) {
  if (in_array($view->name, variable_get('prev_next_views_enabled', array()))) {
    $query = db_rewrite_sql($view->build_info['query'], $view->base_table, $view->base_field, array('view' => &$view));
    $args = $view->build_info['query_args'];

    $result = db_query($query, $args);
    $nids = array();
    while ($item = db_fetch_array($result)) {
      $nids[] = $item['nid'];
    }

    $_SESSION['prev_next_views'] = $nids;
  }
}
