/*
  script modified by lorenz textor lorenz@textor.ch
    - added automatic resizing of images if larger than browser window
    - added automatic slideshow function
*/

/*
  Slidebox (Asynchronous Javascript Lightbox Slideshow)
  by Olivier Ramonat http://olivier.ramonat.free.fr/slidebox/slidebox.js

  Add functions :
  - getXMLCaption that read an external file
  - setXMLCaption called by getXMLCaption that write caption and links
  to prev and next link
  
  
*/

/*
	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/

	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	(basically, do anything you want, just leave my name and link)
	
	Table of Contents
	-----------------
	Configuration
	
	Functions
	- getPageScroll()
	- getPageSize()
	- pause()
	- showLightbox()
	- hideLightbox()
	- initLightbox()
	- addLoadEvent()
	
	Function Calls
	- addLoadEvent(initLightbox)

*/

//
// Configuration
//

// If you would like to use a loading image, point to it in the next line
var loadingImage = 'http://www.issw.ch/SilvaPhotoGallery/loading.gif';
var next_link_image = 'http://www.issw.ch/SilvaPhotoGallery/next.gif';
var previous_link_image = 'http://www.issw.ch/SilvaPhotoGallery/previous.gif';

// If you want to allow slideshow and caption, add an xml file like this:
//   <response>
//      <source id='http://hal.ramonat.fr/projects/img/crw_0362_rj.jpg'>
//         <caption>Monsieur Chat</caption>
//      </source>
//   <response>

// So point to the xml file
var xml_url      = "http://www.issw.ch/SilvaPhotoGallery/captions.xml?url=http://www.issw.ch/fotos/index_DE";

// Global variables

var idx = 0;
var anchors;
var slide = false;
var myTimer;


// function slideshow_start()
// added by lorenz textor
function slideshow_start()
{
	slide=true;
	// hide links
	prevLink = document.getElementById('go_left');
	if ( prevLink )
		prevLink.style.visibility = 'hidden';
	nextLink = document.getElementById('go_right');
	if ( nextLink )
		nextLink.style.visibility = 'hidden';
	myTimer = setTimeout(slideshow_next, document.getElementById('timeSelect').value);
}

// function slideshow_next()
// added by lorenz textor
function slideshow_next()
{
	if ( slide ) {
		gotoLightbox('go_right');
	}
}

// function slideshow_stop()
// added by lorenz textor
function slideshow_stop()
{
	slide = false;
	clearTimeout(myTimer);
	// show links
	prevLink = document.getElementById('go_left');
	if ( prevLink )
		prevLink.style.visibility = 'visible';
	nextLink = document.getElementById('go_right');
	if ( nextLink )
		nextLink.style.visibility = 'visible';
}

//
// Set the path of the xml file to read
// Use to load caption url form external javascript 
// (usefull when multiples slideshow on one site)
//
function AJLSetFile (path)
{
   xml_url = path;
}

function getKey (e) {
  if (e == null) { // ie
    keycode = event.keyCode;
  } else { // mozilla
    keycode = e.which;
  }
  switch(keycode) {
    case 27: if(slide){slideshow_stop();}else{hideLightbox();}return false; // esc
    case 37: if(!slide){gotoLightbox('go_left');}return false; // left arrow
    case 39: if(!slide){gotoLightbox('go_right');}return false; // right arrow
  }
  key = String.fromCharCode(keycode).toLowerCase();
  switch(key) {
    case "n": if(!slide){gotoLightbox('go_right');}return false;
//    case " ": if(!slide){gotoLightbox('go_right');}return false;
    case "p": if(!slide){gotoLightbox('go_left');}return false;
//    case "x": if(slide){slideshow_stop();}else{hideLightbox();}return false;
    case "q": if(slide){slideshow_stop();}else{hideLightbox();}return false;
    case "s": if(!slide){slideshow_start();}return false;
  }
}

function listenkey () {
document.onkeyup = getKey;
}

function gotoLightbox(direction) {
   var next_link = document.getElementById(direction);
   if (next_link != null) {
      var href = next_link.getAttribute('href');
      hideOnlyLightbox();
      showLightbox(next_link);
   } else {
      hideLightbox();
   }
}

//
// Ajax Request to get an xml file
// Call setXMLCaption on complete
//
function getXMLCaption(href)
{
   var myAjax = new Ajax.Request
      (xml_url,
       {method: 'get', parameters: '', 
          onComplete: function (req) 
          {
	  setXMLCaption(req.responseXML, href)}}
       );
}

//
// setXMLCaption()
// Parse XML file and add caption, previous link and next link to lightbox
//
function setXMLCaption(result, href)
{
   var objCaption   = document.getElementById('lightboxCaption');
   
   // Delete old objCaption content
   while (objCaption.hasChildNodes()) {
      objCaption.removeChild(objCaption.firstChild);
   }
   var all_source   = result.getElementsByTagName('source');

   var i = 0;

   for (i = 0; i < all_source.length; i++) {
      var node = all_source[i];
      if (node.getAttribute("id") == href) {
         /* Add this caption and create link for previous and next images */

         //  Add previous link
         if (i != 0) {
            var previous_node = all_source[i-1];
            var prev_href = previous_node.getAttribute("id");
            var prev_link = document.createElement("a");
            prev_link.setAttribute("href", prev_href);
            prev_link.setAttribute("id", "go_left");
            prev_link.onclick = function () {
               hideOnlyLightbox();
               showLightbox(this); 
               return false;
            }
            if (previous_link_image != '') {
               var text_prev_link = document.createElement("img");
               text_prev_link.setAttribute("src", previous_link_image);
            } else {
               var text_prev_link = document.createTextNode("< prev");
            }
            prev_link.appendChild(text_prev_link);
            objCaption.appendChild(prev_link);
         }
         
         //  Add next link
         if (i < (all_source.length - 1)) {
            var next_node     = all_source[i+1];
            var next_href = next_node.getAttribute("id");
            var next_link = document.createElement("a");
            next_link.setAttribute("href", next_href);
            next_link.setAttribute("id", "go_right");
            next_link.onclick = function () {
               hideOnlyLightbox();
               showLightbox(this);
               return false;
            }
            if (next_link_image != '') {
               var text_next_link = document.createElement("img");
               text_next_link.setAttribute("src", next_link_image);
            } else {
               var text_next_link = document.createTextNode("next >");
            }
            next_link.appendChild(text_next_link);
            objCaption.appendChild(next_link);
         }

         //  Add caption
         var caption_elm = node.getElementsByTagName("caption");
         var caption     = document.createTextNode
            (caption_elm[0].firstChild.nodeValue);
         objCaption.appendChild(caption);
         return;
      } 
   }
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

   var yScroll;

   if (self.pageYOffset) {
      yScroll = self.pageYOffset;
   } else if (document.documentElement && document.documentElement.scrollTop){	 
      // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
   } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
   }

   arrayPageScroll = new Array('',yScroll) 
   return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
  // prep objects
   var objOverlay      = document.getElementById('overlay');
   var objImage        = document.getElementById('lightboxImage');
   var objLoadingImage = document.getElementById('loadingImage');
   
   var arrayPageSize   = getPageSize();
   var arrayPageScroll = getPageScroll();

  // center loadingImage if it exists
   if (objLoadingImage) {
      objLoadingImage.style.top 
         = (arrayPageScroll[1] 
            + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
      objLoadingImage.style.left
         = (((arrayPageSize[0] - 40 - objLoadingImage.width) / 2) + 'px');
   }

  // set height of Overlay to take up whole page and show
   objOverlay.style.height  = (arrayPageSize[1] + 'px');
   objOverlay.style.display = 'block';

   // get xml captions
   if (xml_url != "") {
      getXMLCaption (objLink.href);
   } 

   // preload image
   imgPreload = new Image();

   imgPreload.src = objLink.href; // Load image
   waitOnComplete (imgPreload);
}

//
// Wait until image is loaded. Then display it
//
function waitOnComplete(obj) {
   if (obj.complete) {
    // A small pause between the image loading and displaying is required
    // this prevents the previous image displaying for a short burst 
    // causing flicker.
      var showImg = function () { displayLightbox (obj) };
      setTimeout (showImg, 250);
   } else {
      var loopWhenNotComplete = function () { waitOnComplete (obj);}
      setTimeout (loopWhenNotComplete, 250); 
   }
}

//
// Display image and caption
//
function displayLightbox(obj) {
   var objLightbox = document.getElementById('lightbox');
   var objCaption  = document.getElementById('lightboxCaption');
   var objImage    = document.getElementById('lightboxImage');
   
   // start resize added by lorenz textor
	// image too height
	var imageHeight = arrayPageSize[3] - 100;
	var imageWidth = imgPreload.width / imgPreload.height * imageHeight;
	// image to width
	if ( imageWidth > (arrayPageSize[2] - 50) ) {
		imageWidth = arrayPageSize[2] - 50;
		imageHeight = imgPreload.height / imgPreload.width * imageWidth;
	}
	// resize image if too large
	imageHeight = Math.floor(imageHeight);
	imageWidth = Math.floor(imageWidth);
	if ( imageHeight > imgPreload.height ) {
		imageHeight = imgPreload.height;
		imageWidth = imgPreload.width;
	}
	objImage.style.height = imageHeight + 'px';
	objImage.style.width = imageWidth + 'px';
   // end resize added by lorenz textor

   // center lightbox
   // center lightbox and make sure that the top and left values are not negative
   // and the image placed outside the viewport

//   var lightboxTop = arrayPageScroll[1] 
//      + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
   var lightboxTop = arrayPageScroll[1] 
      + ((arrayPageSize[3] - 50 - imageHeight) / 2);

//   var lightboxLeft = ((arrayPageSize[0] - 40 - imgPreload.width) / 2);
   var lightboxLeft = ((arrayPageSize[0] - 40 - imageWidth) / 2);
   
   objLightbox.style.top  = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
   objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";

   objLightbox.style.display   = 'block';
//   objLightbox.style.width = imgPreload.width + 'px';
   objLightbox.style.width = imageWidth + 'px';

   objImage.style.visibility = 'visible';
   objImage.src = obj.src;
      
   // display caption if exist
//   objCaption.style.width = imgPreload.width + 'px';
   objCaption.style.width = imageWidth + 'px';
   objCaption.style.display = 'block';
   
   // continue slideshow
   if ( slide ) {
      slideshow_start();
   }
   
   // Listen key to print previous or next image
   listenkey();
}

//
// hideLightbox()
//
function hideLightbox()
{
   // get objects
   var objOverlay    = document.getElementById('overlay');
   var objLightbox   = document.getElementById('lightbox');

   // hide lightbox, overlay
   objOverlay.style.display    = 'none';
   objLightbox.style.display   = 'none';
   
   document.onkeypress = '';
   
   // end slideshow
   slideshow_stop();
}

//
// hideOnlyLightbox()
// Do not hide overlay when go to next or previous link during a slideshow
//
function hideOnlyLightbox()
{
   var objLightbox   = document.getElementById('lightbox');
   objLightbox.style.display   = 'none';
}

//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
   if (!document.getElementsByTagName) { 
      return false; 
   }

   var anchors = document.getElementsByTagName("a");
   var i = 0;

   // loop through all anchor tags
   for (i = 0; i < anchors.length; i++){
      var anchor = anchors[i];

      if (anchor.getAttribute("href") 
          && (anchor.getAttribute("rel") == "lightbox")){
         anchor.onclick = function () {showLightbox(this); return false;}
      }
   }
   
   // the rest of this code inserts html at the top of the page that looks like this:
   //
   // <div id="overlay">
   //		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
   //	</div>
   // <div id="lightbox">
   //		<a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image"><img /></a>
   //		<div id="lightboxCaption"></div>
   // </div>
   
   var objBody = document.getElementsByTagName("body").item(0);
   
  // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
   var objOverlay = document.createElement("div");
   objOverlay.setAttribute('id','overlay');
   objOverlay.onclick = function () {hideLightbox(); return false;}
   objOverlay.style.display = 'none';
   objOverlay.style.position = 'absolute';
   objOverlay.style.top = '0';
   objOverlay.style.left = '0';
   objOverlay.style.zIndex = '90';
   objOverlay.style.width = '100%';
   objBody.insertBefore(objOverlay, objBody.firstChild);
   
   var arrayPageSize = getPageSize();
   var arrayPageScroll = getPageScroll();

  // preload and create loader image
   var imgPreloader = new Image();
   
  // if loader image found, create link to hide lightbox and create loadingimage
   imgPreloader.onload=function(){

      var objLoadingImageLink = document.createElement("a");
      objLoadingImageLink.setAttribute('href','#');
      objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
      objOverlay.appendChild(objLoadingImageLink);
      
      var objLoadingImage = document.createElement("img");
      objLoadingImage.src = loadingImage;
      objLoadingImage.setAttribute('id','loadingImage');
      objLoadingImage.style.position = 'absolute';
      objLoadingImage.style.zIndex = '150';
      objLoadingImageLink.appendChild(objLoadingImage);

      imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

      return false;
   }

   imgPreloader.src = loadingImage;

  // create lightbox div, same note about styles as above
   var objLightbox = document.createElement("div");
   objLightbox.setAttribute('id','lightbox');
   objLightbox.style.display  = 'none';
   objLightbox.style.position = 'absolute';
   objLightbox.style.zIndex   = '100';	
   objBody.insertBefore(objLightbox, objOverlay.nextSibling);
   
  // create link
   var objLink = document.createElement("a");
   objLink.setAttribute('id', 'closeLightbox');
   objLink.setAttribute('title', 'Click to close');
   objLink.setAttribute('href','#');
   objLink.onclick = function () {hideLightbox(); return false;}
   objLightbox.appendChild(objLink);
   
  // create image
   var objImage = document.createElement("img");
   objImage.setAttribute('id','lightboxImage');
   objImage.style.visibility = 'hidden';
   objLink.appendChild(objImage);

   // create caption
   var objCaption = document.createElement("div");
   objCaption.setAttribute('id','lightboxCaption');
   objCaption.style.display = 'none';
   objLightbox.appendChild(objCaption);
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
   var oldonload = window.onload;
   if (typeof window.onload != 'function'){
      window.onload = func;
   } else {
      window.onload = function(){
         oldonload();
         func();
      }
   }

}

addLoadEvent(initLightbox);	// run initLightbox onLoad
//addLoadEvent(listenkey);
