var olb_borderSize = 10;

// -----------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var olb_imageArray = new Array;
var olb_activeImage;

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var olb_Lightbox = Class.create();

olb_Lightbox.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateImageList and then
	// the function inserts html at the bottom of the page which is used to display the shadow 
	// overlay and the image container.
	//
	initialize: function() {	
		
		this.updateImageList();

		// Code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="overlay"></div>
		//	<div id="lightbox">
		//		<div id="outerImageContainer">
		//			<div id="imageContainer">
		//				<img id="lightboxImage">
		//				<div style="" id="hoverNav">
		//					<a href="#" id="prevLink"></a>
		//					<a href="#" id="nextLink"></a>
		//				</div>
		//				<div id="loading">
		//					<a href="#" id="loadingLink">
		//						<img src="/images/loading.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//		<div id="imageDataContainer">
		//			<div id="imageData">
		//				<div id="imageDetails">
		//					<span id="caption"></span>
		//					<span id="numberDisplay"></span>
		//				</div>
		//				<div id="bottomNav">
		//					<a href="#" id="bottomNavClose">
		//						<img src="/images/close.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//	</div>


		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','olb_overlay');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { olb_myLightbox.end(); }
		objBody.appendChild(objOverlay);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','olb_lightbox');
		objLightbox.style.display = 'none';
		objLightbox.onclick = function(e) {	// close Lightbox is user clicks shadow overlay
			if (!e) var e = window.event;
			clickObj = Event.element(e).id;
			if ( clickObj == 'olb_lightbox') {
				olb_myLightbox.end();
			}
		};
		objBody.appendChild(objLightbox);
			
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','olb_outerImageContainer');
		objLightbox.appendChild(objOuterImageContainer);

		// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
		// If animations are turned off, it will be hidden as to prevent a flicker of a
		// white 250 by 250 box.
		if(animate){
			Element.setWidth('olb_outerImageContainer', 250);
			Element.setHeight('olb_outerImageContainer', 250);			
		} else {
			Element.setWidth('olb_outerImageContainer', 1);
			Element.setHeight('olb_outerImageContainer', 1);			
		}

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','olb_imageContainer');
		objOuterImageContainer.appendChild(objImageContainer);

		var objLightboxImage = document.createElement("div");
		objLightboxImage.setAttribute('id','olb_lightboxImage');
		
   		objImageContainer.appendChild(objLightboxImage);
	
		var objHoverNav = document.createElement("div");
		objHoverNav.setAttribute('id','olb_hoverNav');
		objImageContainer.appendChild(objHoverNav);
	
		var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','olb_prevLink');
		objPrevLink.setAttribute('href','#');
		objHoverNav.appendChild(objPrevLink);
		
		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','olb_nextLink');
		objNextLink.setAttribute('href','#');
		objHoverNav.appendChild(objNextLink);
	
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','olb_loading');
		objImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','olb_loadingLink');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { olb_myLightbox.end(); return false; }
		objLoading.appendChild(objLoadingLink);
	
		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileLoadingImage);
		objLoadingLink.appendChild(objLoadingImage);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','olb_imageDataContainer');
		objLightbox.appendChild(objImageDataContainer);

		var objImageData = document.createElement("div");
		objImageData.setAttribute('id','olb_imageData');
		objImageDataContainer.appendChild(objImageData);
	
		var objImageDetails = document.createElement("div");
		objImageDetails.setAttribute('id','olb_imageDetails');
		objImageData.appendChild(objImageDetails);
	
		var objCaption = document.createElement("span");
		objCaption.setAttribute('id','olb_caption');
		objImageDetails.appendChild(objCaption);
	
		var objNumberDisplay = document.createElement("span");
		objNumberDisplay.setAttribute('id','olb_numberDisplay');
		objImageDetails.appendChild(objNumberDisplay);
	
		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id','olb_bottomNav');
		objImageData.appendChild(objBottomNav);
	},


	//
	// updateImageList()
	// Loops through anchor tags looking for 'lightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
	//
	updateImageList: function() {	
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');
		var areas = document.getElementsByTagName('area');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('olb_lightbox'))){
				anchor.onclick = function () {olb_myLightbox.start(this); return false;}
			}
		}

		// loop through all area tags
		// todo: combine anchor & area tag loops
		for (var i=0; i< areas.length; i++){
			var area = areas[i];
			
			var relAttribute = String(area.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (area.getAttribute('href') && (relAttribute.toLowerCase().match('olb_lightbox'))){
				area.onclick = function () {olb_myLightbox.start(this); return false;}
			}
		}
	},
	
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to olb_imageArray.
	//
	start: function(imageLink) {	

		hideSelectBoxes();
		hideFlash();

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('olb_overlay', arrayPageSize[0]);
		Element.setHeight('olb_overlay', arrayPageSize[1]);

		new Effect.Appear('olb_overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });

		olb_imageArray = [];
		imageNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName( imageLink.tagName);

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'olb_lightbox')){
			// add single image to olb_imageArray
			olb_imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));			
		} else {
		// if image is part of a set..

			// loop through anchors, find other images in set, and add them to olb_imageArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					olb_imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}
			olb_imageArray.removeDuplicates();
			while(olb_imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}
		
		if((imageLink.getAttribute('lightbox_textbox') == 'rejestracja')){
			document.getElementById('temporary_lightbox_x').value = "635";
			document.getElementById('temporary_lightbox_y').value = "465";
			document.getElementById('temporary_lightbox_txt').value=1;
		} else if((imageLink.getAttribute('lightbox_textbox') == 'logowanie')){
			document.getElementById('temporary_lightbox_x').value = "400";
			document.getElementById('temporary_lightbox_y').value = "225";
			document.getElementById('temporary_lightbox_txt').value=2;
		} else if((imageLink.getAttribute('lightbox_textbox') == 'feedback')){
			document.getElementById('temporary_lightbox_x').value = "450";
			document.getElementById('temporary_lightbox_y').value = "333";
				document.getElementById('temporary_lightbox_txt').value=30;
		}else if((imageLink.getAttribute('lightbox_textbox') == 'newsletter')){
			document.getElementById('temporary_lightbox_x').value = "450";
			document.getElementById('temporary_lightbox_y').value = "333";
			document.getElementById('temporary_lightbox_txt').value=3;
		} else if((imageLink.getAttribute('lightbox_textbox') == 'przypomnienie')){
			document.getElementById('temporary_lightbox_x').value="450";
			document.getElementById('temporary_lightbox_y').value="230";
			document.getElementById('temporary_lightbox_txt').value=11;
		}

		// calculate top and left offset for the lightbox 
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		Element.setTop('olb_lightbox', lightboxTop);
		Element.setLeft('olb_lightbox', lightboxLeft);
		
		Element.show('olb_lightbox');
		
		this.changeImage(imageNum);
		
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {	
		
		olb_activeImage = imageNum;	// update global var
		// hide elements during transition
		if(animate){ Element.show('olb_loading');}
		Element.hide('olb_lightboxImage');
		Element.hide('olb_hoverNav');
		Element.hide('olb_prevLink');
		Element.hide('olb_nextLink');
		Element.hide('olb_imageDataContainer');
		Element.hide('olb_numberDisplay');		
		
		imgPreloader = new Image();
		
		// once image is preloaded, resize image container
    imgPreloader.onload=function(){
			Element.setSrc('olb_lightboxImage', olb_imageArray[olb_activeImage][0]);
			olb_myLightbox.resizeImageContainer(Number(document.getElementById('temporary_lightbox_x').value), Number(document.getElementById('temporary_lightbox_y').value));
      document.getElementById('olb_lightboxImage').innerHTML = getLightboxString(Number(document.getElementById('temporary_lightbox_txt').value));
			imgPreloader.onload=function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise 
		}
		// imgPreloader.src = olb_imageArray[olb_activeImage][0];
	  imgPreloader.src = "/images/pixel_trans.gif";
  },

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get curren width and height
		this.widthCurrent = Element.getWidth('olb_outerImageContainer');
		this.heightCurrent = Element.getHeight('olb_outerImageContainer');

		// get new width and height
		var widthNew = (imgWidth  + (olb_borderSize * 2));
		var heightNew = (imgHeight  + (olb_borderSize * 2));
    
		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;

		if(!( hDiff == 0)){ new Effect.Scale('olb_outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale('olb_outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }

		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
		}

		Element.setHeight('olb_prevLink', imgHeight);
		Element.setHeight('olb_nextLink', imgHeight);
		Element.setWidth( 'olb_imageDataContainer', widthNew);

		this.showImage();
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		Element.hide('olb_loading');
		new Effect.Appear('olb_lightboxImage', { duration: resizeDuration, queue: 'end', afterFinish: function(){	olb_myLightbox.updateDetails();} });
		this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
	
		// if caption is not null
		if(olb_imageArray[olb_activeImage][1]){
			Element.show('olb_caption');
			Element.setInnerHTML( 'olb_caption', olb_imageArray[olb_activeImage][1]);
		}
		
		// if image is part of set display 'Image x of x' 
		if(olb_imageArray.length > 1){
			//Element.show('numberDisplay');
			//Element.setInnerHTML( 'numberDisplay', "Zdjêcie " + eval(olb_activeImage + 1) + " z " + olb_imageArray.length);
		}

		new Effect.Parallel(
			[ new Effect.SlideDown( 'olb_imageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }), 
			  new Effect.Appear('olb_imageDataContainer', { sync: true, duration: resizeDuration }) ], 
			{ duration: resizeDuration, afterFinish: function() {
				// update overlay size and update nav
				var arrayPageSize = getPageSize();
				Element.setHeight('olb_overlay', arrayPageSize[1]);
				olb_myLightbox.updateNav();
				}
			} 
		);
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		//Element.show('hoverNav');				

		// if not first image in set, display prev image button
		if(olb_activeImage != 0){
			Element.show('olb_prevLink');
			document.getElementById('olb_prevLink').onclick = function() {
				olb_myLightbox.changeImage(olb_activeImage - 1); return false;
			}
		}

		// if not last image in set, display next image button
		if(olb_activeImage != (olb_imageArray.length - 1)){
			Element.show('olb_nextLink');
			document.getElementById('olb_nextLink').onclick = function() {
				olb_myLightbox.changeImage(olb_activeImage + 1); return false;
			}
		}
		
		// this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	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((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){	// close lightbox
			olb_myLightbox.end();
		} else if((key == 'p') || (keycode == 37)){	// display previous image
			if(olb_activeImage != 0){
				olb_myLightbox.disableKeyboardNav();
				olb_myLightbox.changeImage(olb_activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){	// display next image
			if(olb_activeImage != (olb_imageArray.length - 1)){
				olb_myLightbox.disableKeyboardNav();
				olb_myLightbox.changeImage(olb_activeImage + 1);
			}
		}

	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((olb_imageArray.length - 1) > olb_activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = olb_imageArray[olb_activeImage + 1][0];
		}
		if(olb_activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = olb_imageArray[olb_activeImage - 1][0];
		}
	
	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		Element.hide('olb_lightbox');
		new Effect.Fade('olb_overlay', { duration: overlayDuration});
		showSelectBoxes();
		showFlash();
	}
}



function olb_initLightbox() { olb_myLightbox = new olb_Lightbox(); }
Event.observe(window, 'load', olb_initLightbox, false);