/*
 * Smoothbox v20070814 by Boris Popoff (http://gueschla.com)
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0 ;

var nextimg;
var previmg;
var crtimg = 0;
var bgSlider;
var elements;
var lock=false;
var stopped = true;
var timer;


// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
	$$("a.smoothbox").each(function(el){el.onclick=TB_bind});
	$$("form.smoothbox").each(function(el){el.onsubmit=TB_bind});
}

function TB_bind(event) {
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	if(this.get('tag')=="form"){
		TB_show(caption, this.action, group);
		this.onsubmit=TB_bind;
	}else{
		TB_show(caption, this.href, group);
		this.onclick=TB_bind;
	}
	
	return false;
}


// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel) {
	// create iframe, overlay and box if non-existent
	if ( !$("TB_overlay") )
	{
		new Element('iframe').setProperty('id', 'TB_HideSelect').inject(document.body);
		$('TB_HideSelect').setStyle('opacity', 0);
		new Element('div').setProperty('id', 'TB_overlay').inject(document.body);
		$('TB_overlay').setStyle('opacity', 0);
		TB_overlaySize();
		new Element('div').setProperty('id', 'TB_load').inject(document.body);
		$('TB_load').innerHTML = "<img src='/img/smoothbox/loading.gif' />";
		TB_load_position();
		new Fx.Tween('TB_overlay',{duration: 400, transition: Fx.Transitions.Sine.easeInOut}).start('opacity',0.6);
	}
	
	if ( !$("TB_load") )
	{		
		new Element('div').setProperty('id', 'TB_load').inject(document.body);
		$('TB_load').innerHTML = "<img src='loading.gif' />";
		TB_load_position();
	}
	
	if ( !$("TB_window") )
	{
		new Element('div').setProperty('id', 'TB_window').inject(document.body);
		$('TB_window').setStyle('opacity', 0);
	}
	
	$("TB_overlay").onclick=TB_remove;
	window.onscroll=TB_positionEffect;

	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// check for images
	if ( baseURL.match(imageURL) ) {
		var dummy = { caption: "", url: "", html: "" };
		
		var prev = dummy,
			next = dummy,
			imageCount = "";
			
		// if an image group is given
		if ( rel ) {
			function getInfo(image, id, label) {
				return {
					caption: image.title,
					url: image.href,
					html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
				}
			}
		
			// find the anchors that point to the group
			var imageGroup = [] ;
			$$("#container a.smoothbox").each(function(el){
				if (el.rel==rel) {imageGroup[imageGroup.length] = el ;}
			})

			var foundSelf = false;
			
			// loop through the anchors, looking for ourself, saving information about previous and next image
			for (var i = 0; i < imageGroup.length; i++) {
				var image = imageGroup[i];
				var urlTypeTemp = image.href.match(imageURL);
				
				// look for ourself
				if ( image.href == url ) {
					foundSelf = true;
					crtimg=i;
					previmg=i-1;
					nextimg=i+1;
					imageCount = galleryLanguage.image+' ' + (i + 1) + ' ' + galleryLanguage.of + ' ' + (imageGroup.length);
				} else {
					// when we found ourself, the current is the next image
					if ( foundSelf ) {
						next = getInfo(image, "next", "");
						// stop searching
						break;
					} else {
						// didn't find ourself yet, so this may be the one before ourself
						prev = getInfo(image, "prev", "");
					}
				}
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// Resizing large images
			var x = window.getWidth() - 150;
			var y = window.getHeight() - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			// TODO don't use globals
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			
			
			//ESL MODIFICATION: min-height and min-width
			if(TB_WIDTH < 621) TB_WIDTH = 621;
			if(TB_HEIGHT < 363) TB_HEIGHT = 363;
			
			//ESL MODIFICATION: keep always the next and previous
			if(prev.html==''){
				prev = getInfo(imageGroup[imageGroup.length-1], "prev", "");
				previmg = imageGroup.length-1;
			}else if (next.html==''){
				next = getInfo(imageGroup[0], "next", "");
				nextimg = 0;
			}
			
			// TODO empty window content instead
			// ESL MODIFICATION: add span msg, play and stop
			$("TB_window").innerHTML += "<a href='' id='TB_ImageOff' title='"+galleryLanguage.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div style='clear:left'></div><div id='TB_caption'><div id='TB_secondLine'>" + "<span id='msg'>"+imageCount+"</span>" + prev.html + "<span id='TB_stop'></span><span id='TB_play'></span>" + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+galleryLanguage.close+"'>"+galleryLanguage.close+"</a></div>";
			
			$("TB_closeWindowButton").onclick = TB_remove;
			
			/* ESL MODIFICATION: don't use the goPrev and goNext function
			 * use our goPrev and goNext
			 
			function buildClickHandler(image) {
				return function() {
					$("TB_window").remove();
					new Element('div').setProperty('id', 'TB_window').inject(document.body);
					TB_show(image.caption, image.url, rel);
					return false;
				};
			}
			
			goPrev = buildClickHandler(prev);
			goNext = buildClickHandler(next);*/
			
			/*------------------------------SYLVAIN TEST------------------------------*/
			var browseImg = new Element('div',{'id':'TB_thumbsContainer'});
			
			elements = imageGroup;
			
			elements.each(function(link,i){
				new Element('img',{
					'class':'thumbs',
					'alt':link.getProperty('title'),
					'src': link.getFirst().getProperty('src'),
					'events':{
						'click': function(){
							switchImg(link.getProperty('href'),i);
						}
						
					}
				}).inject(browseImg);
			});
			
			browseImg.injectAfter('TB_ImageOff');
			thumbsList = $$('img.thumbs');
			
			bgSlider = new BackgroundSlider(thumbsList,{mouseOver: false, duration: 1000, className: 'outline', padding:{top:-1,right:-1,bottom:-1,left:-1}, container: browseImg});			
			bgSlider.set(thumbsList[crtimg],true);
			
			
			var tipsTop = $('TB_prev').getCoordinates().bottom-$('TB_window').getCoordinates().top;
			
			var tipPrev = createTips('prev',galleryLanguage.previous,tipsTop);
			var tipNext = createTips('next',galleryLanguage.next,tipsTop);
			var tipPlay = createTips('play',galleryLanguage.play,tipsTop);
			var tipStop = createTips('stop',galleryLanguage.stop,tipsTop);
			
			if ( $('TB_prev') ) {
				$("TB_prev").addEvents({
					'click': function(e){
						var e = new Event(e);
						e.stop();
						goPrev();
					},
					
					'mouseover': function(){
						this.addClass('over');
						tipPrev.start('opacity',0,1);
					},
					
					'mouseout': function(){
						this.removeClass('over');
						tipPrev.start('opacity',1,0);
					}
				});
			}
			
			if ( $('TB_next') ) {		
				$("TB_next").addEvents({
					'click': function(e){
						var e = new Event(e);
						e.stop();
						goNext();
					},
					
					'mouseover': function(){
						this.addClass('over');
						tipNext.start('opacity',0,1);
					},
					
					'mouseout': function(){
						this.removeClass('over');
						tipNext.start('opacity',1,0);
					}
				});
			}
			
			$('TB_play').addEvents({
				'click': function(){
					play();
				},
				
				'mouseover': function(){
					this.addClass('over');
					tipPlay.start('opacity',0,1);
				},
					
				'mouseout': function(){
					this.removeClass('over');
					tipPlay.start('opacity',1,0);
				}
			});
			
			$('TB_stop').addEvents({
				'click': function(){
					stop();
				},
				
				'mouseover': function(){
					this.addClass('over');
					tipStop.start('opacity',0,1);
				},
					
				'mouseout': function(){
					this.removeClass('over');
					tipStop.start('opacity',1,0);
				}
			});
			/*-----------------------------------------------------------------------*/
			
			document.onkeydown = function(event) {
				var event = new Event(event);
				switch(event.code) {
				case 27:
					TB_remove();
					break;
				case 190:
					if( $('TB_next') ) {
						document.onkeydown = null;
						goNext();
					}
					break;
				case 188:
					if( $('TB_prev') ) {
						document.onkeydown = null;
						goPrev();
					}
					break;
				}
			}
			
			// TODO don't remove loader etc., just hide and show later
			$("TB_ImageOff").onclick = TB_remove;
			TB_position();
			TB_showWindow(true);
		}
		imgPreloader.src = url;
		
	} else { //code to show html pages
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery( queryString );
		
		TB_WIDTH = (params['width']*1) + 30;
		TB_HEIGHT = (params['height']*1) + 40;

		var ajaxContentW = TB_WIDTH - 30,
			ajaxContentH = TB_HEIGHT - 45;
		
		if(url.indexOf('TB_iframe') != -1){				
			urlNoQuery = url.split('TB_');
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+parent.$('sendtoafriend').rel+"'>"+parent.$('sendtoafriend').rel+"</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showWindow()'> </iframe>";
		} else {
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>";
		}
				
		$("TB_closeWindowButton").onclick = TB_remove;
		
			if(url.indexOf('TB_inline') != -1){	
				$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
				TB_position();
				TB_showWindow();
			}else if(url.indexOf('TB_iframe') != -1){
				TB_position();
				if(frames['TB_iframeContent'] == undefined){//be nice to safari
					$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
					TB_showWindow();
				}
			}else{
				var handlerFunc = function(){
					TB_position();
					TB_showWindow();
				};
				var myRequest = new Ajax(url, {method: 'get',update: $("TB_ajaxContent"),onComplete: handlerFunc}).request();
			}
	}

	window.onresize=function(){ TB_position(); TB_load_position(); TB_overlaySize();}  
	
	document.onkeyup = function(event){ 	
		var event = new Event(event);
		if(event.code == 27){ // close
			TB_remove();
		}	
	}
	
}

//helper functions below

function TB_showWindow(with_anim){
	//$("TB_load").remove();
	//$("TB_window").setStyles({display:"block",opacity:'0'});
	
	if (TB_doneOnce==0) {
		TB_doneOnce = 1;
		
		/* MODIFICATION BY ESL with animation */
		if (with_anim) {
			showAnimWindow();
		}
		else var myFX = new Fx.Tween('TB_window',{duration: 250, transition: Fx.Transitions.Sine.easeInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').destroy();}} }).start('opacity',1);
		/*-------------------------------------------------------------------------------------------------------*/
		
	} else {
		$('TB_window').setStyle('opacity',1);
		if ($('TB_load')) { $('TB_load').destroy();}
	}
}

function TB_remove() {
	if($('TB_load')) $("TB_load").destroy();
 	$("TB_overlay").onclick=null;
	document.onkeyup=null;
	document.onkeydown=null;
	
	if ($('TB_imageOff')) $("TB_imageOff").onclick=null;
	if ($('TB_closeWindowButton')) $("TB_closeWindowButton").onclick=null;
	if ( $('TB_prev') ) { $("TB_prev").onclick = null; }
	if ( $('TB_next') ) { $("TB_next").onclick = null; }

	new Fx.Tween('TB_window',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_window').destroy();} }).start('opacity',0);
	new Fx.Tween('TB_overlay',{duration: 400, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_overlay').destroy();} }).start('opacity',0);

	window.onscroll=null;
	window.onresize=null;	
	
	$('TB_HideSelect').destroy();
	TB_init();
	TB_doneOnce = 0;
	stopped = true;
	return false;
}

function TB_position() {
	$("TB_window").setStyles({width: TB_WIDTH+'px', 
				 left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
				 top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_positionEffect() {
	new Fx.Morph('TB_window', {duration: 75, transition: Fx.Transitions.sineInOut}).start({
		'left':(window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
		'top':(window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
	$("TB_overlay").setStyles({"height": '0px', "width": '0px'});
	$("TB_HideSelect").setStyles({"height": '0px', "width": '0px'});
	$("TB_overlay").setStyles({"height": window.getScrollHeight()+'px', "width": window.getScrollWidth()+'px'});
	$("TB_HideSelect").setStyles({"height": window.getScrollHeight()+'px',"width": window.getScrollWidth()+'px'});
}

function TB_load_position() {
	if ($("TB_load")) { $("TB_load").setStyles({left: (window.getScrollLeft() + (window.getWidth() - 56)/2)+'px', top: (window.getScrollTop() + ((window.getHeight()-20)/2))+'px',display:"block"}); }
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}


/* ESL FUNCTIONS */
function switchImg(url, id){
	$clear(timer);
	if (!lock) {
		
		bgSlider.setStart(thumbsList[id]);
		bgSlider.move(thumbsList[id],true);
		
		showImg(url);
		
		crtimg = id;
		nextimg = (id + 1) % elements.length;
		previmg = (id - 1);
		
		if (previmg < 0) {
			previmg = elements.length - 1;
		}
		
		if($('msg')){
			$('msg').set('text', galleryLanguage.image+' '+(crtimg + 1)+' '+galleryLanguage.of+' '+elements.length);
		}
		
		if ($('title')) {
			$('title').set('text', thumbsList[id].getProperty('alt'));
		}
	}
}

function showImg(url){
	if (TB_doneOnce != 0) {
		var newImage = $('TB_Image').clone();
		newImage.setProperties({
			'src': url,
			'id': 'TB_Image_clone'
		});
		newImage.setStyles({
			'z-index': 1
		});
		newImage.injectAfter($('TB_Image'));
		var fx = new Fx.Tween($('TB_Image'), {
			duration: 1000,
			transition: Fx.Transitions.Quart.easeInOut,
			onStart: function(){
				lock = true;
			},
			onComplete: function(){
				$('TB_Image').destroy();
				newImage.setProperty('id', 'TB_Image');
				newImage.setStyle('z-index', 2);
				lock = false;
			}
		});
		fx.start('opacity', 0);
		if (!stopped) {
			goNext.delay(1100, this, true);
		}
	}
}

function goNext(wait){
	if (stopped && wait) return;
	if (!stopped && wait){
		waiting();
	}else{
		switchImg(elements[nextimg].getProperty('href'), nextimg);
	}
	
}

function goPrev(){
	switchImg(elements[previmg].getProperty('href'),previmg);
}

function play(){
	if(stopped){
		stopped = false;
		goNext();
	}
}

function stop(){
	if(!stopped){
		$clear(timer);
		stopped = true;
	}
}

function waiting(){
	timer = goNext.delay(3000,this);
}

function showAnimWindow(){
	var div = new Element('div',{'id':'animbox'}).inject(document.body);
	var coord = $('TB_window').getCoordinates();
	var init_height = div.getStyle('height').toInt();
		
	div.setStyle('top',coord.top+(TB_HEIGHT-init_height)/2);
		
	var animFX = new Fx.Morph(div,{
		duration: 500, 
		transition: Fx.Transitions.sineInOut
	}).start({
		'width':[0,TB_WIDTH],
		'left':[coord.left+TB_WIDTH/2,coord.left]
	}).chain(function(){
		this.start({
			'height':[init_height,TB_HEIGHT],
			'top':[coord.top+(TB_HEIGHT-init_height)/2,coord.top]
		});
	}).chain(function(){
		var myFX = new Fx.Tween('TB_window',{duration: 250, transition: Fx.Transitions.Sine.easeInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').destroy();} div.destroy(); } }).start('opacity',1);
	});
}


function createTips(id,content,top){
			btnCoord = $('TB_'+id+'').getCoordinates();
			var tip = new Element('span',{
				'id':'tip'+id,
				'class':'gtips'
			}).set('text', content).inject('TB_secondLine');
			
			
			tip.setStyles({
				'top':top,
				'left':btnCoord.left+(btnCoord.width-tip.offsetWidth)/2
			});
			
			return new Fx.Tween(tip,{'duration':300,wait:false}).set('opacity', 0);
}
