// Copyright (c) 2008 Tels (http://bloodgate.com/js/)

// highlight the Nth image
function Gallery_Index_highlight(idx)
  {
  with (this)
    {
    if (idx < lastImage && idx >= 0)
      {
      imgs[currentImage].removeClassName('current');
      imgs[idx].addClassName('current');
      currentImage = idx;
      }
    }
  }

// highlight the next image
function Gallery_Index_next_image()
  {
  if (this.currentImage < this.lastImage)
    {
    this.highlight( this.currentImage + 1 );
    }
  }

// highlight the previous image
function Gallery_Index_prev_image()
  {
  if (this.currentImage > 0)
    {
    this.highlight( this.currentImage - 1 );
    }
  }

// handle keypresses
function Gallery_Index_handle_key(e)
  {
  var evt = (e) ? e : window.event;

  var char = (evt.charCode) ? evt.charCode : evt.keyCode;
  // <-
  if (char == 37)
    {
    gi.prevImage(); evt.returnValue = false;
    }
  // -> or SPACE
  else if (char == 39 || char == 32)
    {
    gi.nextImage(); evt.returnValue = false;
    }
  // HOME
  else if (char == 36)
    {
    // show first image
    gi.highlight(0); evt.returnValue = false;
    }
  // ENTER
  else if (char == 13)
    {
    // go to current image
    var cur = gi.links[gi.currentImage].href;
    // redirecting without timeout does'nt work in firefox
    self.setTimeout( function () { self.location.href = cur; }, 0.1);
    }
  // END
  else if (char == 35)
    {
    // show last image
    gi.highlight( gi.links.length - 1 ); evt.returnValue = false;
    }
  // ESC
  else if (char == 27 && gi.ESC != 0)
    {
    // go back to the overview page
    var cur = window.location.href;
    cur = cur.replace ( /\/index.html/,'/../index.html');
    // redirecting without timeout does'nt work in firefox
    self.setTimeout( function () { self.location.href = cur; }, 0.1);
    }
  }

// create a new Gallery_Index object
function Gallery_Index( elem_selector, img_selector, enableESC )
  {
  this.links = ( $$(elem_selector) );
  this.imgs  = ( $$(img_selector)  );
 
  // attach a unique ID to each link so we find them again
  for (var i = 0, len = this.links.length; i < len; ++i)
    {
    this.links[i].id = 'a' + i;
    //alert(this.links[i]);
    // find the image contained in this element
    //this.imgs.push ( $$( "#a" + i + " img") );
    //alert(this.imgs[i]);
    }

  this.currentImage = 0;
  this.lastImage = this.links.length;

  // allow ESC to go up one directory?
  this.ESC = enableESC || 0;

  // public methods:
  this.highlight    = Gallery_Index_highlight;
  this.handleKeys   = Gallery_Index_handle_key;
  this.nextImage    = Gallery_Index_next_image;
  this.prevImage    = Gallery_Index_prev_image;

  this.highlight(0);

  // install a keypress handler
  document.onkeydown = this.handleKeys;

  // break out of frames
  if (top.location != document.location)
    {
    top.location.href = document.location.href;
    }

  return this;
  }


