<?php

/**
 * @file
 * This module is in charge of generating the carousels based on the ouput of the views.
 */
 
/**
 * Implements hook_views_api().
 */
function views_fixed_grid_views_api() {
  return array('api' => 3.0);
}

/**
 * Preprocess function for the views_view_fixed_grid theme function
 * 
 * If random order is selected the coordinates for each value are
 * randomly generated.
 */
function template_preprocess_views_view_fixed_grid(&$vars) {
  $view = $vars['view'];
  // Get the options selected in the view.
  $opts_plugin = $view->style_plugin->options;
  // Get the maximum number of items if selected
  if (!empty($opts_plugin['maxitems']) && $opts_plugin['maxitems']) {
    $max = $opts_plugin['maxitems'];
  }
  else {
    $max = $opts_plugin['rows'] * $opts_plugin['columns'];
  }
  // If there are not enough items to fill up to the max, then the max
  // is the number of items retrieved.
  $max = $max > count($view->result) ? count($view->result) : $max;
  $coordinates = array();
  $indexes = array();
  for ($i=0; $i < $max; $i++) {
    // Generate the random coordinates if needed
    if ($opts_plugin['alignment'] == 'random') {
      $index = rand(0, ($opts_plugin['rows'] * $opts_plugin['columns']) - 1);
      while (in_array($index, $indexes)) {
        $index = rand(0, ($opts_plugin['rows'] * $opts_plugin['columns']) - 1);
      }
    }
    else {
      $index = $i;
    }
    $indexes[] = $index;
    // Go from index to 2D coordinates
    if ($opts_plugin['alignment'] == 'vertical') {
      $coordinates[$index % $opts_plugin['rows']][(int)($index / $opts_plugin['rows'])] = $i;
    }
    else {
      $coordinates[(int)($index / $opts_plugin['columns'])][$index % $opts_plugin['columns']] = $i;
    }
  }
  $vars['coordinates'] = $coordinates;
  $vars['numrows'] = $opts_plugin['rows'];
  $vars['numcols'] = $opts_plugin['columns'];
  $vars['class'] = 'views-view-fixed-grid';
  if (!empty($handler->options['summary'])) {
    $vars['attributes'] = drupal_attributes(array('summary' => $handler->options['summary']));
  }
}
