// $Id: OverlayImage.js,v 1.4 2010/01/30 16:49:57 miruoss Exp $
OverlayImage = {};
OverlayImage.image = {};
OverlayImage.imageData = {};
OverlayImage.preloaded = {};
OverlayImage.state = {};

$('document').ready(function () {
  /* Click Handler on single images not belonging to a gallery */
  $('a.overlay-image').click(function (event) {
    /* if ctrl or shift is pressed, do the click */
    if (event.ctrlKey || event.shiftKey) {
      self.location = $(this).attr('href');
      return false;
    }

    scroll(0,0); /* important, otherwise the image might be out of view */

    /* No Overlay Gallery for IE6 */
    if ($.browser.msie && $.browser.version.substr(0,1) == '6') {
      return true;
    }

    /* load overlay background and required container divs */
    OverlayGallery.loadBG();
    $('#overlay-gallery-container').append('<div id="overlay-image-container"></div>');
    var id = $(this).attr('rel');
    $('#overlay-image-container').addClass('gallery-loading');
    $('#overlay-image-container').show();

    /* Request information about the images the user clicked on */
    $.getJSON(Drupal.settings.basePath + 'overlay_image_load/' + id, function(data) {
      OverlayImage.displayImage(data, OverlayGallery.close);
    });
    return false;
  })
});

/**
 * Initialise click handlers for the thumbnails (when gallery is loaded)
 */
OverlayImage.init = function () {
  $('a.overlay-thumb').click(OverlayImage.open);
}

/**
 * Thumbnail click candler: opens the clicked image
 */ 
OverlayImage.open = function (event) {
  scroll(0,0);
  if (OverlayImage.state != 'open') {
    OverlayImage.state = 'open';
    OverlayImage.image = $(this).attr('rel');
    OverlayImage.showImage();
  }
  return false;
}

/**
 * Loads the metadata for the given image (might be pre-loaded already).
 * @param {function} callback 
 *   Function to be called as soon as image-data is loaded.
 */
OverlayImage.loadImage = function (image, callback) {
  /* no such image? Return! */
  if (!OverlayGallery.gallery[image]) {
    return;
  };
  var id = OverlayGallery.gallery[image].id;
  var data;
  if (OverlayImage.preloaded[id]) {
    /* already loaded. Call the callback */
    if (typeof callback == 'function') {
      callback(OverlayImage.preloaded[id]);
    }
  } else {
    /* fetch the metadata using ajax, call the callback thereafter */
    $.getJSON(Drupal.settings.basePath + 'overlay_image_load/' + id, function (data) {
      OverlayImage.preloaded[id] = data;
      jQuery("<img>").attr("src", data.normal);
      if (typeof callback == 'function') {
        callback(data);
      }
    });
  }
}

/**
 * Shows the currently active image (the one in OverlayImage.image)
 * @param {Function} callback
 *   Optional: Called when the image is loaded
 */
OverlayImage.showImage = function (callback) {
  var jsonHandler;
  
  $('#overlay-gallery-header a').fadeOut('fast');
  $('#overlay-thumbs-container').fadeOut('fast', function () {
    if($('#overlay-gallery-container').size() == 0) {
      $('body').append('<div id="overlay-gallery-container"></div>');
    }

    /* If there is no image container, create it. */
    if($('#overlay-image-container').size() == 0) {
      $('#overlay-gallery-container').append('<div id="overlay-image-container"></div>');
      $('#overlay-image-container').append('<div id="oi_stop" title="'+Drupal.t('Return to Overview')+'"></div>');
      $('#overlay-image-container').append('<div id="overlay-image-panel" class="overlay-gallery-panel"></div>');
      $('#overlay-image-panel').append('<div id="oi_prev" title="'+Drupal.t('Previous Image')+'"></div>');
      $('#overlay-image-panel').append('<div id="oi_play" title="'+Drupal.t('Start Slideshow')+'"></div>');
      $('#overlay-image-panel').append('<div id="oi_pause" title="'+Drupal.t('Stop Slideshow')+'"></div>');
      $('#overlay-image-panel').append('<div id="oi_next" title="'+Drupal.t('Next Image')+'"></div>');
      $('#oi_stop').click(OverlayImage.returnToGallery);
      $('#oi_next').click(OverlayImage.showNext);
      $('#oi_prev').click(OverlayImage.showPrevious);
      $('#oi_play').click(OverlayGallery.startSlideshow);
      $('#oi_pause').click(OverlayGallery.stopSlideshow);
    }

    /* show the "loading" icon */
    $('#overlay-image-container').addClass('gallery-loading');
    $('#overlay-image-container').show();

    /* Sets the handler for the json call.
     * If there is already an image, replace it, otherwise just display the active one 
     */
    if ($('#overlay-image').size() == 0) {
      jsonHandler = OverlayImage.displayImage;
    } else {
      jsonHandler = OverlayImage.replaceImage;
    }

    /* load and display the active image */
    OverlayImage.loadImage(OverlayImage.image, function(data) {
      jsonHandler(data, OverlayImage.showNext);
      if (typeof callback == 'function') {
        callback();
      }
      
      /* preload next image */
      OverlayImage.loadImage(OverlayImage.image+1, null);
    });
  });
}

/**
 * Displays the given image. This function creates all the dom elements (divs, img)
 * needed to show the image.
 * 
 * @param {Object} data
 *   The data of the image to display.
 * @param {Object} clickHandler
 *   The Handler for the click on the image
 */
OverlayImage.displayImage = function (data, clickHandler) {
  var img = $('<img>');
  var img_link = $('<a>');
  var img_definition = $('<span>');
  img_definition.css('display', 'none');
  OverlayImage.imageData = data;

  /* Loading icon is shown until the image is downloaded */
  img.load(function () {
    $('#overlay-image-container').removeClass('gallery-loading');
    $('#overlay-image-def').fadeIn();
  }).attr({
    'src': data.normal,
    'id': 'overlay-image'
  });
  img_link.attr({
    'href': Drupal.settings.basePath+'node/'+data.id,
    'id': 'overlay-image-link'
  }).append(img);
  img_link.click(clickHandler);
  img_definition.attr('id', 'overlay-image-def').append(img_link);
  img_definition.append('<div id="overlay-image-meta">'+data.caption+'</div>');
  $('#overlay-image-container').append(img_definition);

  /* add comments */
  if (data.comments) {
    OverlayComment.init(data);
  }

  OverlayImage.adjustSize();
  OverlayImage.invokeLoaded();
}

/**
 * Similar to displayImage but replaces an existing image. No need to create all
 * the dom elements anymore.
 * @param {Object} data
 *   The data of the image to be displayed
 * @param {Object} notused
 *   The click handler is already set so this variable will be ignored.
 */
OverlayImage.replaceImage = function(data, notused) {
  OverlayImage.imageData = data;
  $('#overlay-image-def').fadeOut('normal', function () {
    OverlayImage.adjustSize();

    /* Loading icon is shown until the image is downloaded */
    $('#overlay-image').load(function () {
      $('#overlay-image-container').removeClass('gallery-loading');
      $('#overlay-image-def').fadeIn();
    }).attr('src', data.normal);

    $('#overlay-image-link').attr('href', Drupal.settings.basePath+'node/'+data.id);
    $('#overlay-image').removeAttr('height');
    $('#overlay-image-meta').html(data.caption);
    OverlayComment.setComments(data);
    OverlayImage.invokeLoaded();

    /* preload next image */
    OverlayImage.loadImage(OverlayImage.image+1, null);
  });
}

/**
 * Click handler for for "next"-button and image
 */
OverlayImage.showNext = function (event) {
  $('#overlay-image-container').addClass('gallery-loading');
  OverlayImage.image++;
  if (OverlayGallery.gallery[OverlayImage.image]) {
    OverlayImage.loadImage(OverlayImage.image, OverlayImage.replaceImage);
  } else {
    OverlayImage.returnToGallery();
  }
  return false;
}

/**
 * Click handler for for "previous"-button and image
 */
OverlayImage.showPrevious = function (event) {
  $('#overlay-image-container').addClass('gallery-loading');
  OverlayImage.image--;
  if (OverlayGallery.gallery[OverlayImage.image]) {
    var id = OverlayGallery.gallery[OverlayImage.image].id;
    $.getJSON(Drupal.settings.basePath + 'overlay_image_load/' + id, OverlayImage.replaceImage);
  } else {
    OverlayImage.returnToGallery();
  }
  return false;
}
/**
 * Click handler for for "return"-button and image
 */
OverlayImage.returnToGallery = function () {
  OverlayImage.state = 'closed';
  $('#overlay-image-container').fadeOut('normal', function () {
    $('#overlay-image-def').hide();
    $('#overlay-thumbs-container').fadeIn();
    $('#overlay-gallery-header a').fadeIn();
    OverlayGallery.stopSlideshow();
  })
}

/**
 * The sized of the displayed image is always adjusted to the window size
 */
OverlayImage.adjustSize = function () {
  var maxHeight = $(window).height() * 0.7;
  var imageHeight = OverlayImage.imageData.height;
  if(imageHeight > maxHeight) {
    $('#overlay-image').attr('height', maxHeight);
  }
}

/**
 * invode the js function overlayImageLoaded() if it exists.
 * This function can be implemented by other modules.
 */
OverlayImage.invokeLoaded = function () {
  if (typeof Drupal.overlayImageLoaded == 'function') {
    Drupal.overlayImageLoaded();
  }
}
