var lightboxScroll = true;
/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var ie6 = false;
var bHeight;
/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
	
	ie6 = checkIt('msie 6');
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,
	callback : null,
	slideshow : null,
	slideArray : null,

	initialize: function(ctrl)
	{
	    if(ctrl)
	    {
			this.content = ctrl.href;
			Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
			ctrl.onclick = function(){return false;};
		}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function()
	{
			this.prepareIE('100%', 'hidden');
			this.hideSelects('hidden');
		if (browser == 'Internet Explorer' && !lightboxScroll){
			this.getScroll();
			this.setScroll(0,0);
		}
		this.displayLightbox("block");
		this.enableKeyboardNav();
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		if(!lightboxScroll)
		{
		    bod.style.overflow = overflow;
		}
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		if(!lightboxScroll)
		{
		    htm.style.overflow = overflow; 
		}
		
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	displayLightbox: function(display){
		$('overlay').style.display = display; 
		$('lightbox').style.display = display;
		$('lightboxFixed').style.display = display;
		if(display != 'none') this.loadInfo();
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	
	loadInfo: function() {
		if (this.content)
		{
			var myAjax = new Ajax.Request(
	        this.content,
	        {method: 'post',  evalScripts: true, parameters: "ajax=1", onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}		
	},
	
	// Display Ajax response
	processInfo: function(response){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";	
		this.actions();		
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		//lbActions = document.getElementsByClassName('lbAction');
		lbActions = $('lbContent').getElementsByTagName('a');

		for(i = 0; i < lbActions.length; i++) {
			if(lbActions[i].rel == 'insert' || lbActions[i].rel == 'deactivate' || lbActions[i].rel == 'prevSlide' || lbActions[i].rel == 'nextSlide' || lbActions[i].rel == 'toggleAutoSlideShow')
			{
				Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
				lbActions[i].onclick = function(){return false;};
			}
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
		link = Event.element(e).parentNode;
		if(document.getElementById('lbContent'))
		{
			$('lbOutputs').appendChild($('lbContent').childNodes[0]);
			Element.remove($('lbContent'));
		}
		
	 
		var myAjax = new Ajax.Request(
			link.href,
			{method: 'post', evalScripts: true, parameters: "ajax=1", onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		autoSlideShow = false;
		if(document.getElementById('lbContent'))
		{
			$('lbOutputs').appendChild($('lbContent').childNodes[0]);
			Element.remove($('lbContent'));
		}		
		this.prepareIE("auto", "auto");
		this.hideSelects("visible");
		if (browser == "Internet Explorer" && !lightboxScroll){
			this.setScroll(0,this.yPos);
		}
		
		var autoSlideShow = false;
        var autoSlideShowEnq = false;
        var slideKeyNav = false;
		this.displayLightbox("none");
		this.disableKeyboardNav();
	},
	
	alert:function(content)
	{
		this.activate();
		info = "<div id='lbContent'>" + content + "</div>";
		new Insertion.Before($('lbLoadMessage'), info);
		$('lightbox').className = "done";
		this.actions();
	},
	
	displayDiv:function(id)
	{
		this.activate();
		info = document.createElement('div');
		info.id='lbContent';
		info.appendChild($(id));
		//new Insertion.Before($('lbLoadMessage'), info.innerHTML);
		$('lightbox').insertBefore(info, $('lbLoadMessage'));
		$('lightbox').className = "done";
		this.actions();
	},

	startSlideShow:function(albumId, photoId)
	{
		this.slideshow = new Array();
		this.slideshow['albumId'] = albumId;
		this.slideshow['firstPhotoId'] = photoId;
		this.slideshow['baseUrl'] = siteurl + 'userfiles/gallery/' + albumId + '/';
		this.activate();
		// show preloader
		lb = $('lightbox');
		lb.className = 'loading';
		lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<p>Proszę czekać</p>' +
						  '</div>';
		// let's load file list
		url = siteurl + 'gallery/album/ajaxSlideList/id/' + albumId;
		new Ajax.Request(url,{onComplete: this.loadSlideShow.bindAsEventListener(this), onFailure: this.deactivate});
	},
	loadSlideShow:function(response)
	{
		eval("var tmp = ("+response.responseText+")");
		this.slideArray = tmp;
		
		this.slideIndex = new Array();
		// create enumeration index
		for(var id in tmp)
		{
			this.slideIndex.push(id);
			if(id == this.slideshow['firstPhotoId'])
			{
				this.slideshow['indexPos'] = this.slideIndex.length - 1;
			}
		}
		this.createSlideShowMarkup();
		this.actions();
		this.setSlide(this.slideshow['firstPhotoId']);
	},
	changeSlide:function(step)
	{
		if(step == null) { step = 1; }
		this.slideshow['indexPos'] = this.slideshow['indexPos'] + step;
		if(this.slideshow['indexPos'] < 0)
		{
			//this.slideshow['indexPos'] = 0;
			this.slideshow['indexPos'] = this.slideIndex.length - 1; // loop around
		}
		else if(this.slideshow['indexPos'] > this.slideIndex.length - 1)
		{
			//this.slideshow['indexPos'] = this.slideIndex.length - 1;			
			this.slideshow['indexPos'] = 0; // loop around
		}
		i = this.slideshow['indexPos'];
		nextPhotoId = this.slideIndex[i]; 
		this.setSlide(nextPhotoId);
	},
	prevSlide:function()
	{
		this.changeSlide(-1);
	},
	nextSlide:function()
	{
		this.changeSlide(1);
	},
	toggleAutoSlideShow:function()
	{
		if(autoSlideShow == true)
		{
			autoSlideShow = false;
			$('slideshowStart').className = '';
		}
		else
		{
			autoSlideShow = true;
			$('slideshowStart').className = 'running';
			autoSlideShowEnq = false;
			this.initAutoSlideChange();
		}
	},
	initAutoSlideChange:function()
	{
		if(autoSlideShow == true && autoSlideShowEnq == false)
		{
			autoSlideShowEnq = true;
			setTimeout(function() {autoSlideShowEnq = false;if(autoSlideShow == true) {slideBox.nextSlide();} }, 4000);
		}
	},
	createSlideShowMarkup:function()
	{
		$('lbOutputs').innerHTML = '';
	
		outerDiv = document.createElement('div');
		outerDiv.className = 'outerContainer';

		// ain't beautiful, but it works!
		outerDiv.innerHTML = '<table cellpadding="0" cellspacing="0" id="imgTab"><tbody>'
							+'<tr><td colspan="3"><img id="currentSlide" src="' + document.location.href + '" title="" /></td></tr>'
							+'<tr><td id="imageDesc">&nbsp;</td>'
							+'<td class="imageOptions">'
								+'<img src="/i/ico-wait.gif" alt="" id="slidePreloader" />'
								+'<a href="#" rel="prevSlide" id="prevImg" title="'+ _('Poprzednie zdjęcie') +'">Poprzednie zdjęcie</a>'		
								+'<a href="#" rel="toggleAutoSlideShow" id="slideshowStart" title="'+ _('Slideshow') +'">Slideshow</a>'
								+'<a href="#" rel="nextSlide" id="nextImg" title="'+ _('Następne zdjęcie') +'">Następne zdjęcie</a>'	
								+'<a href="#" rel="deactivate" id="deactivate" title="'+ _('Zamknij (ESC)') +'">Zamknij</a>'
							+'</td></tr></tbody></table>';
							
		lbContent = document.createElement('div');
		lbContent.id='lbContent';
		lbContent.appendChild(outerDiv);	
		$('lightbox').appendChild(lbContent);
	},
	setSlide:function(id)
	{
		$('slidePreloader').style.visibility = 'visible';
		this.slideshow['currentSlideId'] = id;
		img = $('currentSlide');
		
		imgPreloader = new Image();
		// once image is preloaded, reset image container
		imgPreloader.onload = function()
		{
		    lbIw = this.width;
		    lbIh = this.height;
			if(img.src.length > 0 && img.src != document.location.href)
			{
				new Effect.Fade($('currentSlide'), {to: 0.2, duration: 0.2});
				setTimeout(function(){
					$('currentSlide').src = slideBox.slideshow['baseUrl'] + 'x1024_' + slideBox.slideArray[id]['filename'];
					$('currentSlide').title = slideBox.slideArray[id]['title'];
					$('currentSlide').style.width = lbIw;
					$('currentSlide').style.height = lbIh;
					//$('imageDesc').innerHTML = slideBox.slideArray[id]['title'];
					slideBox.setTitle(id);
					
					new Effect.Appear($('currentSlide'), {to: 1, duration: 0.2});
					}, 200);
				setTimeout(function(){
					var tested = 120 + $('currentSlide').height;

					$('lightboxFixed').style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
					if(ie6)
					{
					    document.getElementsByTagName('html')[0].style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
					}
					}, 420);
			}
			else
			{
				// clear the loading message
				$('lightbox').className = 'done imageZoom';
		
				$('currentSlide').src = slideBox.slideshow['baseUrl'] + 'x1024_' + slideBox.slideArray[id]['filename'];
				$('currentSlide').title = slideBox.slideArray[id]['title'];
				$('currentSlide').style.width = lbIw;
				$('currentSlide').style.height = lbIh;
				slideBox.setTitle(id);
				setTimeout(function(){
					var tested = 120 + $('currentSlide').height;
					$('lightboxFixed').style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
					if(ie6)
					{
					    document.getElementsByTagName('html')[0].style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
					}
					}, 420);
					
					/*var tested = 120 + $('currentSlide').height;
					var bHeight = (document.height ? document.height : document.body.offsetHeight) + 90;
			    $('lightboxFixed').style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
			    if(browser == 'Internet Explorer')
				{
				    document.getElementsByTagName('html')[0].style.height = (bHeight > tested) ? ((bHeight) + 'px') : (tested + 'px');
				}*/
				//$('imageDesc').innerHTML = slideBox.slideArray[id]['title'];
			}
			$('slidePreloader').style.visibility = 'hidden';
			imgPreloader.onload=function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise
			if(autoSlideShow == true)
			{
				slideBox.initAutoSlideChange();
			}
			
		}
		imgPreloader.src = this.slideshow['baseUrl'] + 'x1024_' + this.slideArray[id]['filename']; 
	},
	setTitle:function(id)
	{
		i = slideBox.slideshow.indexPos + 1;
		count = slideBox.slideIndex.length;
		url = siteurl + slideBox.slideArray[id]['url'];
		url.replace('//', '/');		// fix double slashes
		$('imageDesc').innerHTML = '<span class="slideNo">' + i + '/' + count +'</span> '
								+'<a href="'+url+'" title="'+_('Przejdź do tego zdjęcia')+'">'
								+ slideBox.slideArray[id]['title'] + '</a>';
	},
	keyboardAction: function(e)
	{
		if (e == null) { // ie
			keycode = event.keyCode;
			escapeKey = 27;
		} else { // mozilla
			keycode = e.keyCode;
			escapeKey = e.DOM_VK_ESCAPE;
		}
		key = String.fromCharCode(keycode).toLowerCase();
		
		if(keycode == escapeKey)
		{	// close lightbox
			this.deactivate();
		} else if(slideKeyNav)
		{
			if((key == 'p') || (keycode == 37)){	// display previous image
				this.prevSlide();
			} else if((key == 'n') || (keycode == 39)){	// display next image
				this.nextSlide();
			}
		}
	},
	enableKeyboardNav: function()
	{
		//document.onkeydown = this.keyboardAction;
		Event.observe(document, 'keydown', this.keyboardAction.bindAsEventListener(this), false); 
	},
	disableKeyboardNav: function()
	{
		document.onkeydown = '';
		slideKeyNav = false;
	}	
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize()
{
	addLightboxMarkup();
	bHeight = (document.height ? document.height : document.body.offsetHeight) + 90;
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
bod = document.getElementsByTagName('body')[0];
lightboxFixed = document.createElement('div');
lightboxFixed.id = 'lightboxFixed';
overlay = document.createElement('div');
overlay.id = 'overlay';
lb = document.createElement('div');
lb.id = 'lightbox';
lb.className = 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<p>Proszę czekać</p>' +
						  '</div>';

bod.appendChild(lightboxFixed);
lightboxFixed.appendChild(overlay);
lightboxFixed.appendChild(lb);


}

function showLightbox(id)
{
	alertBox = new lightbox();
	alertBox.displayDiv(id);
	return false;
}

function zoomImage(link, albumId, pictureId)
{
	if(link && link.href && albumId && pictureId)
	{
	    slideBox = new lightbox();
		slideKeyNav = true;
		slideBox.startSlideShow(albumId, pictureId);
		return false;
	}
	return true;
}

var alertBox;
var autoSlideShow = false;
var autoSlideShowEnq = false;
var slideKeyNav = false;
var lbIw;
var lbIh;