/*

This is ArneBox, my Lightbox-ish script. I made it because i wanted to, and I think the result is pretty great.
 
To use it, include the following in your HTML:

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="js/arnebox.js"></script>
<style type="text/css">
  @import url(style/abstyle.css);
</style>

This assumes you have the javascript-files in the "js"-subfolder, and the stylesheet in the "style"-subfolder.
Change it if you want to.

The script relies on prototype.js and scriptaculous. There's also a couple of image files and a style sheet, namely 
"background.png", "progress.gif", "pref.png", "next.png", "close.png" and "abstyle.css".

LICENSE: Beerware.

*/

// These values can be customized if you want to.
var next_text = "Neste bilde";    // Alt-text and title for next image
var prev_text = "Forrige bilde";  // Ditto for previous image
var close_text = "Lukk bilde";    // Ditto for the close box
var stylefolder = "style/"        // Folder for GUI-images
// Don't touch too much beyond this point if you don't know what you're doing.

// Set up basic variables
var loaded = false;
var opening = false;
var images = [];
var totalimages = 0;
// Load GUI-images
var background = new Image();
background.src = stylefolder+"/background.png";
var animation = new Image();
animation.src = stylefolder+"progress.gif";

// Extend all img-tags with open and close-methods
Element.addMethods('img', {
  
  // Open-method
  openit: function(image) {
    // Only open image if document is loaded and another image isn't opening at the same time
    if (loaded && !opening) {
      opening = true;
      
      // Close any open images
      images.invoke('closeit');
      image.setAttribute('open', 'true');
      
      // Log message
      // console.log('openit '+image.classNames());
      
      // Get info about image
      var imgnumber = parseInt(image.getAttribute('abimagenumber'));
      var link = image.ancestors()[0];
      var href = link.getAttribute('href');
      var title = image.getAttribute('title');
      if (title == null || title == "") {
        title = link.getAttribute('title');
        if (title == null) { title = ""; }
      }
      var alt = image.getAttribute('alt');
      
      var thumbWidth = image.getWidth();
      var thumbHeight = image.getHeight();
      var thumbXpos = image.cumulativeOffset()[0];
      var thumbYpos = image.cumulativeOffset()[1];
      
      // Set up the main image file
      var imgfile = new Image();
      
      // Insert the loading-thingy on top of the thumbnail
      $$('body')[0].insert({ bottom: '<div id="loadingimage'+imgnumber+'" style="background-image:url(style/background.png);position:absolute;left:'+thumbXpos+'px;top:'+thumbYpos+'px;width:'+thumbWidth+'px;height:'+thumbHeight+'px;z-index:99998;"><img src="'+stylefolder+'progress.gif" alt="" style="position:absolute;display:block;left:'+((thumbWidth/2)-8)+'px;top:'+((thumbHeight/2)-8)+'px;"></div>'});
      
      // Do this when the main image file is loaded
      imgfile.onload = function() {
        
        // Remove the loading-thingy
        $('loadingimage'+imgnumber).remove();
        
        // Get info about dimensions of final image
        var imgwidth = imgfile.width;
        var imgheight = imgfile.height;
        var finalX = (document.viewport.getWidth()/2 - imgwidth/2)+document.viewport.getScrollOffsets()[0];
        var finalY = (document.viewport.getHeight()/2 - imgheight/2)+document.viewport.getScrollOffsets()[1];
        
        // Insert main image on top of thumbnail 
        $$('body')[0].insert({ bottom: '<div id="abimagediv'+imgnumber+'" class="abimagediv" style="position:absolute;left:'+thumbXpos+'px;top:'+thumbYpos+'px;z-index:99999;"><img id="abimage'+imgnumber+'" src="'+href+'" alt="'+alt+'" height="'+thumbHeight+'" width="'+thumbWidth+'" class="lbimage" style="cursor:pointer;-webkit-box-shadow:0.6em 0.6em 3em black;box-shadow:0.6em 0.6em 3em black;width:'+thumbWidth+';height:'+thumbHeight+';"></div>' });
        
        // Hide thumbnail
        image.setStyle({'visibility':'hidden'});
        
        // Deactivate onclick-functions for thumbnail
        link.stopObserving();
        link.observe('click', function(e) {e.stop();});
        link.setStyle({'cursor': 'default'});
        
        // Animate zooming of the main image
        new Effect.Parallel(
          [ new Effect.Morph($('abimage'+imgnumber), {style:'width:'+imgwidth+'px;height:'+imgheight+'px;'}),
            new Effect.Morph($('abimagediv'+imgnumber), {style:'top:'+finalY+'px;left:'+finalX+'px;'}) ],
          {
            duration: 0.3,
            
            // Do this when image is zoomed
            afterFinish: function() {
              // Insert image text
              $('abimagediv'+imgnumber).insert({ bottom: '<p id="abimagetext'+imgnumber+'" class="abimagetext" style="opacity:0;position:absolute;left:0;right:0;top:'+(imgheight+5)+'px;-webkit-border-radius:0.5em;">'+title+'</p>'});
              
              // Insert the close-box
              $$('body')[0].insert({ bottom: '<div id="abimageclose'+imgnumber+'" title="'+close_text+'" style="cursor:pointer;position:absolute;z-index:100000;left:'+(finalX-12)+'px;top:'+(finalY-12)+'px;opacity:0;width:24px;height:24px;background-image:url(style/close.png);">'}).observe('click', function() { image.closeit(); });
              
              // Insert prev/next-links, if needed
              if (imgnumber < totalimages) {
                $('abimagetext'+imgnumber).insert({ top: '<img id="abnextimage'+imgnumber+'" src="'+stylefolder+'next.png" alt="'+next_text+'" title="'+next_text+'" style="display:block;padding:0.2em;position:absolute;right:0.5em;float:right;cursor:pointer;">'});
                $('abnextimage'+imgnumber).observe('click', function(e) { e.stop(); image.opennext(); });
              }
              if (imgnumber > 1) {
                $('abimagetext'+imgnumber).insert({ top: '<img id="abprevimage'+imgnumber+'" src="'+stylefolder+'prev.png" alt="'+prev_text+'" title="'+prev_text+'" style="display:block;padding:0.2em;position:absolute;left:0.5em;float:left;cursor:pointer;">'});
                $('abprevimage'+imgnumber).observe('click', function(e) { e.stop(); image.openprev(); });
              }
              
              // Fade the image text and the close box in
              new Effect.Parallel(
                [ new Effect.Appear($('abimagetext'+imgnumber)),
                  new Effect.Appear($('abimageclose'+imgnumber)) ],
                  { duration: 0.2 }
              );
              
              // OK to open another image
              opening = false;
            }
          
          }
        );
        
        
      }
      
      // Load the main image file
      imgfile.src = href;
    }
  },
  
  // Function for closing an image
  closeit: function(image) {
    // Only run if images are loaded and this image is open
    if (loaded && image.getAttribute('open') == 'true') {
      image.setAttribute('open', 'false');
      
      // Get info about image
      var imgnumber = parseInt(image.getAttribute('abimagenumber'));
      var thumbWidth = image.getWidth();
      var thumbHeight = image.getHeight();
      var thumbXpos = image.cumulativeOffset()[0];
      var thumbYpos = image.cumulativeOffset()[1];
      var link = image.ancestors()[0];
      
      // Log message
      // console.log('closeit '+image.classNames());
      
      // Zoom closing of image
      new Effect.Morph($('abimagetext'+imgnumber), {style: 'opacity:0;', duration: 0.1, afterFinish: function() {
        
        new Effect.Parallel(
          [ new Effect.Morph($('abimage'+imgnumber), {style: 'width:'+thumbWidth+'px;height:'+thumbHeight+'px'}),
            new Effect.Morph($('abimagediv'+imgnumber), {style: 'left:'+thumbXpos+'px;top:'+thumbYpos+'px;'}),
            new Effect.Morph($('abimageclose'+imgnumber), {style: 'opacity:0;left:'+thumbXpos+'px;top:'+thumbYpos+'px;'}) ],
          {
            duration: 0.2,

            // Do this when image is zoomed in
            afterFinish: function() {

              // Display the thumbnail, and remove the main image
              image.setStyle({'visibility':'visible'});
              $('abimagediv'+imgnumber).remove();
              $('abimageclose'+imgnumber).remove();

              // Re-create onclick-function
              link.setStyle({'cursor':'pointer'});
              link.stopObserving();
              link.observe("click", function(s) {
                s.stop();
                image.openit();
              });
            }
          }
        );
        
      }});

      
    }
  },
  
  // Open the next image
  opennext: function(image) {
    // Only run if images are loaded and there is a next image
    if (loaded && parseInt(image.getAttribute('abimagenumber')) < totalimages) {
      // Open the image with the class ".abimage<current+1>"
      $$('.abimage' + (parseInt(image.getAttribute('abimagenumber')) + 1)).each( function(e) {e.openit()});
    }
  },
  
  // Open the previous image
  openprev: function(image) {
    // Only run if images are loaded and there is a previous image
    if (loaded && parseInt(image.getAttribute('abimagenumber')) > 1) {
      // Open the image with the class ".abimage<current-1>"
      $$('.abimage' + (parseInt(image.getAttribute('abimagenumber')) - 1)).each( function(e) {e.openit()});
    }                                                                                    
  }                                                                                      
  
});

// This function is run when the document with all images is loaded
Event.observe(window, 'load', function() {
  
  // All images wrapped in an <a>-tag with a href ending with .png, .jpg, .jpeg, .gif, .tif, .tiff or .bmp, 
  // and without rel="noarnebox" are added to the "images"-array
  $$('img').each(function(img) {
    var parent = img.ancestors()[0];
    if (parent.tagName == 'A' && parent.getAttribute('rel') != 'noarnebox' && (parent.getAttribute('href').search(/\.png$/) >= 0 || parent.getAttribute('href').search(/\.jpg$/) >= 0 || parent.getAttribute('href').search(/\.jpeg$/) >= 0 || parent.getAttribute('href').search(/\.gif$/) >= 0 || parent.getAttribute('href').search(/\.tif$/) >= 0 || parent.getAttribute('href').search(/\.tiff$/) >= 0 || parent.getAttribute('href').search(/\.bmp$/) >= 0)) {
      images.push(img);
    }
  });
  
  // Count all images
  totalimages = images.length;
  
  // Log message
  // console.log(images);
  
  // Iterate over all images in the "images"-array
  var i = 1;
  images.each(function(image) {
    
    // Set attributes for images
    image.setAttribute('abimagenumber', i);
    image.setAttribute('open', false);
    image.addClassName('abimage'+i); 
    i++;
    
    // Add onclick-events to the images
    image.ancestors()[0].observe('click', function(evt) {
      evt.stop();
      image.openit();
    });
  });
  
  // Now everything is loaded
  loaded = true;
  
});
