// +------------------------------------------------------------------------+
// | Display Images in full screen
// +------------------------------------------------------------------------+
// | Javascript
// |
// | @author		 		Xuan Nguyen <xuxu.fr_at_gmail_dot_com>
// | @author		 		Stanislas Ormières <laruiss_atgmail_dot_com>
// | @version 				1.9
// | Last update			2007/010/10
// |
// | Licensed under the Creative Commons Attribution 3 License - http://creativecommons.org/licenses/by-sa/3.0/
// +------------------------------------------------------------------------+


function getElt(eltId) {
	var obj;
	obj = document.getElementById(eltId);
	if (!obj && document.all) {
		obj = document.all(eltId);
	}
	return obj;
}

// rel value to make it a splash image link
var relValue = 'splash';
// Top margin between viewport and top of image
var topMargin = 40;
// Right margin between viewport and right of image
var rightMargin = 40;
// Bottom margin between viewport and bottom of image
var bottomMargin = 40;
// Left margin between viewport and left of image
var leftMargin = 40;
// images groups array
var splashGroups = new Array();
// Splash links array
var splashLinks = new Array();
// Link titles array
var splashTitles = new Array();
// Delay variable
var slideTimeOut;
// Play/pause notification disappearing timeout
var slideTimeOutNotification;
// Slide delay between two pictures
var slideDelay = 4000;
// Current image group
var currentGroup;
// Current group image position
var currentPosition;
// Slide flag
var isSliding = false;
// Splash replacing ilghtbox flag
var lightboxReplace = true;
// Image background flag (set to true if image instead of color)
var setBg = false;
// Minimum elements z-index
var minZIndex = 100000;
// Objects-to-hide array (will contain <embed> and <object> elements 
var obj2Hide = new Array();
// body element
var bodyElt;

// Default messages are in english
defaultSplashImageMessages = {
	'nextImage': 'Jump to next image',
	'previousImage': 'Jump to previous image',
	'closeSplash': 'Close the splash',
	'startSlide': 'Start the slide',
	'stopSlide': 'Stop the slide',
	'slidingOrNot': 'Sliding (or not)',
	'originalImageLinkText': 'See original image',
	'handlerAttachmentError': 'Handler could not be attached'
}

// -----------------------------------------------------------------------------------
//  Displays right image in full screen
function splashImg(a) {
	// Hide <embed> and <object> elements
    toggleObjectsVisibility('hidden');
	// Initialize currentGroup (this image group if any)
	relAttr = a.rel;
	val = relAttr.replace(relValue+'|', '');
	splashId = a.className ? new String(a.className).match(new RegExp("splash[0-9]+$")) : '';
	if (val != relValue && splashGroups[val].length > 0) {
		currentGroup = val;
		currentPosition = inArray(splashGroups[val], splashId);
	} else {
		currentGroup = currentPosition = '';
	}
	if (!getElt('splash_screen')) {
		// Background creation
		splashScreenBg = document.createElement('a');
		splashScreenBg.id = 'splash_screen';
		splashScreenBg.title = splashImageMessages.closeSplash;
       	splashScreenBg.style.zIndex = minZIndex;
		pageDimensions = getPageSize();
		splashScreenBg.style.width = pageDimensions[0]+'px';
		splashScreenBg.style.height = pageDimensions[1]+'px';
		splashScreenBg.onclick = function() { quitSplash(); return false; }
		if (setBg) { splashScreenBg.className = 'bg'; }
		bodyElt.appendChild(splashScreenBg);
       	splashScreenBg.style.zIndex = minZIndex;

		// Image and loading container creation
		imgContainer = document.createElement('div');
		imgContainer.id = 'image_content';
		imgContainer.style.width = '200px';
		imgContainer.style.height = '200px';
		imgContainer.className = 'ajax-loading';
		bodyElt.appendChild(imgContainer);
       	imgContainer.style.zIndex = minZIndex+1;

		// Positionning
		pageScrollDimensions = getPageScroll();
		pageDimensions = getPageSize();
		imgContainer.style.top = pageScrollDimensions[1]+topMargin+'px';
		imgContainer.style.left = (document.body.scrollWidth || pageDimensions[0])/2-(parseInt(imgContainer.style.width)/2)+'px';
	} else {
		splashScreenBg = getElt('splash_screen');
		imgContainer = getElt('image_content');
		imgContainer.removeChild(getElt('splash_img'));
		imgContainer.className = 'ajax-loading';
	}

	// Remove the title_content
	if (getElt('title_content')) {
		imgTitleElt = getElt('title_content');
		// Remove navigation if exists
		if (getElt('splash_previous')) {
			imgTitleElt.removeChild(getElt('splash_previous'));
			imgTitleElt.removeChild(getElt('splash_next'));
			if (getElt('splash_notification')) { imgContainer.removeChild(getElt('splash_notification')); }
			what = (isSliding) ? 'pauseSplash' : 'splash_play';
			imgTitleElt.removeChild(getElt(what));
		}
		bodyElt.removeChild(imgTitleElt);
	}

	// Load image
	ini_image(a);
}

// -----------------------------------------------------------------------------------
// Loads image
function ini_image(a) {
	// Get image dimensions
	img = document.createElement('img');
	img.src = a.href;

	if (!img.complete) { // If image is not loaded yet
		img.onload = function() {
			image_display(a);
		}
	} else { // If image has already been loaded
		image_display(a);
	}
}

// -----------------------------------------------------------------------------------
// Display image
function image_display(a) {
	imgContainer = getElt('image_content');
	splashScreenBg = getElt('splash_screen');

	// Image element creation
	imgElt = document.createElement('img');
	imgElt.id = 'splash_img';
	imgElt.onclick = function() { quitSplash(); return false; }
	imgContainer.appendChild(imgElt);
    imgElt.style.zIndex = minZIndex+2;

	// Image container resize 
	imgContainer.style.width = img.width+'px';
	imgContainer.style.height = img.height+'px';

	// Image container repositionning
	pageScrollDimensions = getPageScroll();
	pageDimensions = getPageSize();
	imgContainer.style.top = pageScrollDimensions[1]+topMargin+'px';
	imgContainer.style.left = pageDimensions[0]/2-(parseInt(img.width)/2)+'px';

	// Display Image
	imgContainer = getElt('image_content');
	imgContainer.className = '';
	imgElt.src = a.href;
	imgElt.style.display = 'block';

	// splash_close object creation
	closeElt = document.createElement('a');
	closeElt.id = 'splash_close';
	closeElt.title = splashImageMessages.closeSplash;
	closeElt.onclick = function() { quitSplash(); return false; }
	imgContainer.appendChild(closeElt);
    closeElt.style.zIndex = minZIndex+3;

	// Title container creation  
	imgTitleElt = document.createElement('div');
	imgTitleElt.id = 'title_content';
    imgTitleElt.style.zIndex = minZIndex+4;
	imgTitleElt.style.width = (isIE()) ? imgElt.offsetWidth+'px' : img.width+'px';
	imgTitleElt.style.top = pageScrollDimensions[1]+topMargin+(parseInt(imgContainer.style.height))+20+'px';
	imgTitleElt.style.left = pageDimensions[0]/2-(parseInt(imgContainer.style.width)/2)+'px';

	// Label position
	strPosition = (currentGroup != '') ? 'Image '+(currentPosition+1)+' sur '+splashGroups[currentGroup].length+' :' : '';
	textElt = document.createTextNode(strPosition);
	imgTitleElt.appendChild(textElt);

	// Description
	descriptionElt = document.createElement('div');
	descriptionElt.id = 'splash_description';
	imgTitleElt.appendChild(descriptionElt);
    descriptionElt.style.zIndex = minZIndex+5;
	splashId = a.className ? new String(a.className.match(new RegExp("splash[0-9]+$"))) : '';
	textElt = document.createTextNode(splashTitles[splashId]);
	descriptionElt.appendChild(textElt);

	// Link to original image
	descriptionElt.appendChild(document.createTextNode(' '));
	linkElt = document.createElement('a');
	linkElt.id = 'splash_link';
	linkElt.href = a.href;
	imgTitleElt.appendChild(linkElt);
    linkElt.style.zIndex = minZIndex+6;
	linkElttext = document.createTextNode(splashImageMessages.originalImageLinkText);
	linkElt.appendChild(linkElttext);
	descriptionElt.appendChild(linkElt);

	// Finally display title container (at the end to avoid the different reflows)
	bodyElt.appendChild(imgTitleElt);

	// Resize background if image is too large
	pageDimensions = getPageSize();
	total_width = leftMargin+parseInt(imgContainer.style.width)+rightMargin;
	if (total_width > pageDimensions[0]) { splashScreenBg.style.width = total_width+'px'; imgContainer.style.left = leftMargin+'px'; imgTitleElt.style.left = leftMargin+'px'; };
	total_height = topMargin+parseInt(imgContainer.style.top)+parseInt(imgElt.height)+parseInt(imgTitleElt.offsetHeight)+bottomMargin;
	if (total_height > pageDimensions[1]) { splashScreenBg.style.height = total_height+'px'; };

	// Initialize navigation if image is from a group
	initNav(a);
}

// -----------------------------------------------------------------------------------
// Display navigation if image is from a group
function initNav(a) {
	clearTimeout(slideTimeOut);
	imgTitleElt = getElt('title_content');

	// Check if image is from a group
	relAttr = a.rel;
	val = relAttr.replace(relValue+'|', '');

	if (splashGroups[val] && getElt('splash_img')) {
		// splash_previous object creation
		previousElt = document.createElement('a');
		previousElt.id = 'splash_previous';
		previousElt.title = splashImageMessages.previousImage;
		previousElt.onmouseover = function() { previousElt.className = 'over'; }
		previousElt.onmouseout = function() { previousElt.className = ''; }
		previousElt.onclick = function() { splash_previous(); }
		imgTitleElt.appendChild(previousElt);
        previousElt.style.zIndex = minZIndex+6;

		// splash_next object creation 
		nextElt = document.createElement('a');
		nextElt.id = 'splash_next';
		nextElt.title = splashImageMessages.nextImage;
		nextElt.onmouseover = function() { nextElt.className = 'over'; }
		nextElt.onmouseout = function() { nextElt.className = ''; }
		nextElt.onclick = function() { splash_next(); }
		imgTitleElt.appendChild(nextElt);
        nextElt.style.zIndex = minZIndex+6;

		// slide_play object creation
		var playElt = document.createElement('a');
		if (!isSliding) {
			playElt.id = 'splash_play';
			playElt.title = splashImageMessages.startSlide;
		} else {
			playElt.id = 'pauseSplash';
			playElt.title = splashImageMessages.stopSlide;
		}
		playElt.onclick = function() { pauseSplash(); }
		playElt.onmouseover = function() { playElt.className = 'over'; }
		playElt.onmouseout = function() { playElt.className = ''; }
		imgTitleElt.appendChild(playElt);
        playElt.style.zIndex = minZIndex+6;

		//
		if (isSliding) { slideTimeOut = window.setTimeout(splash_next, slideDelay); }
	}
}

// -----------------------------------------------------------------------------------
// To previous image
function splash_previous() {
	currentPosition = (currentPosition-1 < 0) ? splashGroups[currentGroup].length-1 : currentPosition-1;
	splashImg(splashLinks[splashGroups[currentGroup][currentPosition]]);
}

// -----------------------------------------------------------------------------------
// To next image
function splash_next() {
	currentPosition = (currentPosition+1 == splashGroups[currentGroup].length) ? 0 : currentPosition+1;
	splashImg(splashLinks[splashGroups[currentGroup][currentPosition]]);
}

// -----------------------------------------------------------------------------------
// Pause the slide (ou pas)
function pauseSplash() {
	if (!isSliding) {
		isSliding = true;
		getElt('splash_play').id = 'pauseSplash';
		getElt('pauseSplash').title = splashImageMessages.stopSlide;
		currentPosition = (currentPosition == splashGroups[currentGroup].length) ? 0 : currentPosition;
		slideTimeOut = window.setTimeout(splash_next, slideDelay/4);
	} else {
		isSliding = false;
		getElt('pauseSplash').id = 'splash_play';
		getElt('splash_play').title = splashImageMessages.startSlide;
		clearTimeout(slideTimeOut);
	}
}

// -----------------------------------------------------------------------------------
// Action notification
function notification() {
	clearTimeout(slideTimeOutNotification);
	imgContainer = getElt('image_content');
	if (!getElt('splash_notification')) {
		// Little play/pause icon creation 
		slideControlElt = document.createElement('a');
		slideControlElt.id = 'splash_notification';
		slideControlElt.title = splashImageMessages.slidingOrNot;
		imgContainer.appendChild(slideControlElt);
        slideControlElt.style.zIndex = minZIndex+6;
		slideControlElt.style.top = (parseInt(imgContainer.style.height)/2)-25+'px'; // 25 for half of play/pause image height
		slideControlElt.style.left = (parseInt(imgContainer.style.width)/2)-25+'px'; // 25 for half of play/pause image width
		slideControlElt.style.width = '50px'; // 50 play/pause image width 
		slideControlElt.style.height = '50px'; // 50 play/pause image height 
	} else {
		slideControlElt = getElt('splash_notification');
	}
	if (isSliding) {
		slideControlElt.className = 'playing';
	} else {
		slideControlElt.className = 'paused';
		slideTimeOutNotification = setTimeout(quitSplashNotification, 2000);
	}
}

// -----------------------------------------------------------------------------------
// Slide notification
function quitSplashNotification() {
	if (getElt('image_content')) {
		imgContainer = getElt('image_content');
		imgContainer.removeChild(getElt('splash_notification'));
	}
	clearTimeout(slideTimeOutNotification);
}

// -----------------------------------------------------------------------------------
// Quit splash
function quitSplash() {
	clearTimeout(slideTimeOut);
	clearTimeout(slideTimeOutNotification);
	isSliding = false;
	bodyElt.removeChild(getElt('splash_screen'));
	bodyElt.removeChild(getElt('image_content'));
	if (getElt('title_content')) { bodyElt.removeChild(getElt('title_content')); }
	// Display <embed> and <object> elements again
    toggleObjectsVisibility('visible');
}

// -----------------------------------------------------------------------------------
// Check la touche clavier enfoncé
function keyCheck(e) {
	if (getElt('splash_img')) {
		clearTimeout(slideTimeOut);
		what = (e == null) ? event.keyCode : e.which;
		if (inArray(new Array(27, 38, 46, 88), what) >= 0) { // Esc, Del, up arrow, x
			quitSplash();
			return false;
		}
		if (splashGroups[currentGroup]) {
			if (inArray(new Array(13, 32, 40), what) >= 0) { // Return, Space, down arrow
				pauseSplash();
				notification();
				return false;
			} else if (inArray(new Array(33, 37, 109), what) >= 0) { // Page Up , left arrow, -
				splash_previous();
				return false;
			} else if (inArray(new Array(34, 39, 107), what) >= 0) { // Page Down, right arrow, +
				splash_next();
				return false;
			}
		}
	}
}

// -----------------------------------------------------------------------------------
// Hide or show <embed> and <object> elements
function toggleObjectsVisibility(visibilityValue){
	for (i=0; i<obj2Hide.length; i++) { obj2Hide[i].style.visibility = visibilityValue; }
}

// -----------------------------------------------------------------------------------
// Attach event to every <a> element that are meant to have splash event
function initSplashImgs() {
	// Load the 'messages' 
	if (!splashImageMessages) {
		splashImageMessages = defaultSplashImageMessages;
	}

    // Get body
	bodyElt = document.getElementsByTagName('body').item(0);

    // Get the elements to make invisible (<object> and <embed>)
	objs = document.getElementsByTagName('object');
	for (i=0; i<objs.length; i++) {
	    if (objs[i].style.visibility == 'visible' || objs[i].style.visibility == '') { obj2Hide[obj2Hide.length] = objs[i]; }
    }
	objs = document.getElementsByTagName('embed');
	for (i=0; i<objs.length; i++) {
	    if (objs[i].style.visibility == 'visible' || objs[i].style.visibility == '') { obj2Hide[obj2Hide.length] = objs[i]; }
    }

	splashGroups = new Array();
	splashLinks = new Array();
	splashTitles = new Array();
	as = document.getElementsByTagName('a');
	for (i=0; i<as.length; i++) {
		a = as[i];
		relAttr = a.rel;
		if (relAttr.match('splash.image')) { relAttr = relAttr.replace('splash.image', 'splash'); a.rel = relAttr; }
		if (lightboxReplace && relAttr.match('lightbox')) {
            relAttr = relAttr.replace('lightbox', 'splash');
            relAttr = relAttr.replace('splash[', 'splash|');
            relAttr = relAttr.replace(/]$/, '');
            a.rel = relAttr;
        }
		relAttr = a.rel;
		if (relAttr.match('splash')) {
			splashId = 'splash'+i;
			klass = a.className ? a.className + ' ' + splashId : splashId;
			a.className = klass;
			a.onclick = function () { splashImg(this); return false; }
			val = relAttr.replace(relValue+'|', '');
			if (val != relValue) {
				array = (!splashGroups[val] || typeof splashGroups[val] != 'object') ? new Array() : splashGroups[val];
				array[array.length] = splashId;
				splashGroups[val] = array;
				splashLinks[splashId] = a;
			}
			splashTitles[splashId] = a.title ? a.title : 'Image '+i;
		}
	}
	// -----------------------------------------------------------------------------------
	// Check pressed key
	document.onkeydown = keyCheck;
}

// -----------------------------------------------------------------------------------
//
// Other functions
//
// -----------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
// Code by Lokesh Dhakar
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
// Code by Lokesh Dhakar
// Edit for Firefox by pHaez
//
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;
	}
	// arrayPageSize = new Array(xScroll,yScroll,windowWidth,windowHeight)
	// for small pages with total height smaller than viewport height
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	// for small pages with total width smaller than viewport width 
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------
// Cross browser attach event method
// Core code from - quirksmode.org
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener) { // DOM compliant
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){ // MS IE
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
}

// -----------------------------------------------------------------------------------
// Check if a value is present in an array
// Last update 2007-04-03
// Code by Xuan NGUYEN
function inArray (ar, val) {
	if (ar.length == 0) { return -1; }
	for (i=0; i<ar.length; i++) { if (ar[i] == val) { return i; } }
	return -1;
}

// +------------------------------------------------------------------------+
// + isIE()
// +------------------------------------------------------------------------+
function isIE() {
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var regEx = new RegExp('MSIE [0-9]*.[0-9]*', 'gi');
		var str = new String(navigator.appVersion);
		var result = new String(str.match(regEx));
		var versionArray = result.split(' ');
		var version = versionArray[1];
		return version;
	} else {
		return false;
	}
}

// Initialize splash when window is loaded
addEvent(window, 'load', initSplashImgs);

