var gallery_full_image_src = '';

function gallery_mouseover(event)
{
  var element = Event.element(event);
  
  var newsrc = element.src.replace('thumbs/', '');
  if (gallery_full_image_src != newsrc)
  {
    var fulldiv = $('fullsize');
    var largeimg;
    if (largeimg = fulldiv.down('img'))
    {
      fulldiv.removeChild(largeimg);
    }
    
    gallery_full_image_src = newsrc;
    largeimg = new Element('img');
    fulldiv.appendChild(largeimg);
    var state = { thumb: element }
    largeimg.observe('load', gallery_reveal.bindAsEventListener(state));
    largeimg.src = newsrc;
  }
  else
  {
    var largeimg = $('fullsize').down('img');
    if (largeimg)
    {
      $('fullsize').show();
    }
  }
  
  Event.stop(event);
}

function gallery_reveal(event)
{
  var state = this;
  var fulldiv = $('fullsize');
  var image = Event.element(event);
  var thumbpos = state.thumb.cumulativeOffset();
  
  var top = 0;
  var left = 0;
  
  // Must show the DIV here or IE can't tell us the image dimensions.
  fulldiv.show();
  
  // Is the image wider or taller?
  if (image.width > image.height)
  {
    // Landscape orientation: position overlay below the thumbnail.
    top = thumbpos['top'] + state.thumb.height + 10;
    left = (document.viewport.getWidth() - image.width) / 2;
    if (left < 0)
    {
      left = 30;
    }
  }
  else
  {
    // Portrait orientation: position overlay to the side of the thumbnail.
    if (thumbpos['left'] >= image.width + 14)
    {
      // There is room for the image to the left of the thumbnail.
      left = thumbpos['left'] - image.width - 14;
    }
    else
    {
      left = thumbpos['left'] + state.thumb.width + 10;
    }
    top = (document.viewport.getHeight() - image.height) / 2;
    if (top < 0)
    {
      top = 30;
    }
  }
  
  fulldiv.setStyle({ position: 'absolute', top: top + 'px', left: left + 'px' });
  
  Event.stop(event);
}

function gallery_mouseout(event)
{
  $('fullsize').hide();
}

function gallery_attach_events(img)
{
  img.observe('mouseover', gallery_mouseover);
  img.observe('mouseout', gallery_mouseout);
}

$$('#thumbs img').each(function(e) { gallery_attach_events(e); });
