//-------------------------------------------------------------
//  Anura Gallery v1.0
//  Created by Eric Puidokas (www.puidokas.com)
//
//  Licensed under the Creative Commons Attribution 2.5 License
//  (http://creativecommons.org/licenses/by/2.5/)
//-------------------------------------------------------------

// CONFIGURATION VARIABLES
var AnuraLoadingAni = 'loading.gif';

// GLOBALS
var AnuraImageArray = new Array;
var AnuraInterval;
var AnuraCurrent;
var AnuraCanClick;
var AnuraThumbsLoaded = 0;
var AnuraStyle;

// Extensions to the Element class from prototype.js
Object.extend(Element, {
	setHeight: function(element,height){
   		element = $(element);
    	element.style.height = height +"px";
	},
	setWidth: function(element,width){
   		element = $(element);
    	element.style.width = width +"px";
	},
	setPosition: function(element,type,top,left){
   		element = $(element);
    	element.style.position = type;
    	element.style.top = top + 'px';
    	element.style.left = left + 'px';
	},
	setBoxModel: function(element,width,height,margin,padding){
   		element = $(element);
    	element.style.width = width + 'px';
    	element.style.height = height + 'px';
		if(margin!=undefined){element.style.margin = margin;}
		if(padding!=undefined){element.style.padding = padding;}
	}
});

// Anura Class
var Anura = Class.create();
Anura.prototype = {
	
	// initialize()
	initialize: function(){
		
		// Create HTML for overlay cover
		// this iframe allows the overlay to cover select boxes and activex objects in IE
		var overlayCover = '<iframe id="AnuraOverlayCover" style="filter:alpha(opacity=0);-moz-opacity:0;opacity:0;position:absolute;top:0;left:0;width:100%;display:none;" frameborder="0"></iframe>';
		document.body.innerHTML += overlayCover;
		
		// Create HTML for overlay
		// this is the color that fades out the content behind
		var overlay = document.createElement("div");
		overlay.setAttribute('id','AnuraOverlay');
		overlay.style.background='#000';
		Element.setPosition(overlay,'absolute',0,0);
		overlay.style.width = '100%';
		overlay.style.display = 'none';
		document.body.appendChild(overlay);
		
		// Create HTML for gallery
		// This contains all of the images and controls for the Anura Gallery
		var gallery = document.createElement("div");
		gallery.setAttribute('id','AnuraGallery');
		Element.setPosition(gallery,'fixed',0,0);
		gallery.style.display = 'none';
		gallery.style.textAlign = 'center';
		gallery.innerHTML = '<div id="AnuraLoading"><img src="' + AnuraLoadingAni + '"/> Loading...</div>';
		gallery.innerHTML += '<div id="AnuraThumbs"></div>';
		gallery.innerHTML += '<div id="AnuraFullsize"></div>';
		gallery.innerHTML += '<a href="#" onclick="event.returnValue=false;return false;" id="AnuraPrev" style="display:none;"><span>previous</span></a>';
		gallery.innerHTML += '<a href="#" onclick="event.returnValue=false;return false;" id="AnuraNext" style="display:none;"><span>next</span></a>';
		gallery.innerHTML += '<a href="#" onclick="myAnura.close();event.returnValue=false;return false;" id="AnuraClose"><span>close[x]</span></a>';
		gallery.innerHTML += '<a href="http://www.puidokas.com/" id="AnuraVersion">Anura Gallery v1.0</a>';
		document.body.appendChild(gallery);
	},
	
	// getImages()
	getImages: function(url){		
	
		// clear out previous content since this might not be the first time the gallery has loaded
		$('AnuraThumbs').innerHTML='';
		$('AnuraFullsize').innerHTML='';
		
		// make sure content containers and close link are visible
		$('AnuraThumbs').style.display = 'block';
		$('AnuraFullsize').style.display = 'block';
		$('AnuraClose').style.display = 'block';
		
		// set globals to their defaults
		AnuraCurrent = false;
		AnuraCanClick = true;
		AnuraThumbsLoaded = 0;
	
		// if the browser is IE5 or IE6
		if(navigator.userAgent.toLowerCase().indexOf('msie 6')+1 || navigator.userAgent.toLowerCase().indexOf('msie 5')+1){
			//use absolute positioning to place the gallery
			Element.setPosition('AnuraGallery','absolute',myAnura.getPageScroll()[1],0);
		}
	
		// set the overlay's height to the page's height and then fade it in
		// after the overlay has appeared, begin loadThumbs()
		var arrayPageSize = myAnura.getPageSize();
		Element.setHeight('AnuraOverlayCover', arrayPageSize[1]);
		Element.setHeight('AnuraOverlay', arrayPageSize[1]);
		Element.show('AnuraOverlayCover');
		new Effect.Appear('AnuraOverlay', { duration: 0.4, from: 0.0, to: 0.8, afterFinish:function(){myAnura.loadThumbs();} });
		
		var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get',
				onComplete: myAnura.evalResponse
			});
	},
	
	// evalResponse()
	evalResponse: function(originalRequest)
	{
		eval(originalRequest.responseText);
	},
	
	// loadGallery()
	loadGallery: function(galleryArray, galleryOptions){
		
		// set to style of animation
		if(galleryOptions[0]=='fade'){
			AnuraStyle = 'fade';
		}else{
			AnuraStyle = 'morph';
		}
		
		// copy array passed to the global array
		// galleryArray must not be a global variable since javascript doesn't copy an array, it makes a reference to it
		AnuraImageArray=galleryArray;
		
		//add filler at each end of the array so the thumbnails are spaced correctly at the beginning and end
		AnuraImageArray.unshift(AnuraImageArray[0]);
		AnuraImageArray.unshift(AnuraImageArray[0]);
		AnuraImageArray.push(AnuraImageArray[AnuraImageArray.length-1]);
		AnuraImageArray.push(AnuraImageArray[AnuraImageArray.length-1]);
	
	},
	
	//loadThumbs()
	loadThumbs: function(){
	
		// display loading message and Anura Gallery container
		$('AnuraLoading').style.display = 'block';
		$('AnuraGallery').style.display = 'block';
		
		// create first two blank spaces for the thumbnails
		for(i=0;i<2;i++){
			$('AnuraThumbs').innerHTML += '<img src="' + AnuraImageArray[i][0] + '" id="AnuraThumb' + i + '" onload="myAnura.thumbLoaded();" style="height:1px;width:0;opacity:0.0;filter:alpha(opacity=0);" />';
		}
		
		// create the thumbnails
		// each thumbnail runs thumbLoaded() after it's loaded.  Once all thumb have been loaded, loadImage(2) is run which begins loading the first large image
		for(i=2;i<AnuraImageArray.length-2;i++){
			$('AnuraThumbs').innerHTML += '<img src="' + AnuraImageArray[i][0] + '" id="AnuraThumb' + i + '" onload="myAnura.thumbLoaded();" onclick="myAnura.loadImage(' + i + ');" class="AnuraThumb" style="height:' + AnuraImageArray[i][2] + 'px;width:0;" />';
		}
		
		// create last two blank spaces for the thumbnails
		for(i=AnuraImageArray.length-2;i<AnuraImageArray.length;i++){
			$('AnuraThumbs').innerHTML += '<img src="' + AnuraImageArray[i][0] + '" id="AnuraThumb' + i + '" onload="myAnura.thumbLoaded();" style="height:1px;width:0;opacity:0.0;filter:alpha(opacity=0);" />';
		}
	},	
	
	// thumbLoaded()
	thumbLoaded: function(){
		
		// this is a counter for how many thumbnails have been loaded
		AnuraThumbsLoaded++;
		
		// Once all the thumbs have been loaded, display them and begin loading large images
		if(AnuraThumbsLoaded==AnuraImageArray.length){
		
			//hide first thumbnails
			$('AnuraThumb2').style.display = 'none';
			$('AnuraThumb3').style.display = 'none';
			$('AnuraThumb4').style.display = 'none';
			
			// set size on first thumbnails
			Element.setBoxModel('AnuraThumb0',AnuraImageArray[0][1]/4,AnuraImageArray[0][2],'0 '+(AnuraImageArray[0][1]/40)+'px');
			Element.setBoxModel('AnuraThumb1',AnuraImageArray[1][1]*2/3,AnuraImageArray[1][2],'0 '+(AnuraImageArray[1][1]/20)+'px');
			Element.setBoxModel('AnuraThumb2',AnuraImageArray[2][1],AnuraImageArray[2][2],'0 '+(AnuraImageArray[2][1]/10)+'px');
			Element.setBoxModel('AnuraThumb3',AnuraImageArray[3][1]*2/3,AnuraImageArray[3][2],'0 '+(AnuraImageArray[3][1]/20)+'px');
			Element.setBoxModel('AnuraThumb4',AnuraImageArray[4][1]/4,AnuraImageArray[4][2],'0 '+(AnuraImageArray[4][1]/40)+'px');
			
			//fade in first thumbnails
			new Effect.Appear('AnuraThumb2',{duration:0.3});
			new Effect.Appear('AnuraThumb3',{duration:0.3});
			new Effect.Appear('AnuraThumb4',{duration:0.3});
			
			// begin loading large images
			myAnura.loadImage(2);
		}
	},
	
	// loadImage()
	loadImage: function(imageNum){
		
		// clear the interval that is checking if the image has been preloaded
		AnuraInterval = window.clearInterval(AnuraInterval);
		
		// don't do anything if there is an image currently fading out
		if(AnuraCanClick){
		
			// update previous and next links
			myAnura.toggleNav(imageNum);
		
			// scroll to the thumbnail
			myAnura.goToImage(imageNum);
		
			// if there is currently an image displayed
			if(AnuraCurrent){
			
				// if the imageNum is already the current image, don't do anything
				if(AnuraCurrent!='AnuraFull'+imageNum){
				
					// you can't click a new image until the current one has faded out
					AnuraCanClick = false;
					
					//make sure all captions are hidden
					for(var i=0;i<AnuraImageArray.length;i++){
						try{$('AnuraCaption'+i).style.display='none';}catch(err){}
					}
					
					// Which animation style should I use?
					if(AnuraStyle=='fade'){// Use Fade effect
						
						// Fade out old image
						new Effect.Fade(AnuraCurrent, {duration: 0.5, afterFinish: function(){AnuraCanClick=true;myAnura.showImage(imageNum);}});
					
					}else{// Use morph effect
						
						// Morph out old image
						new Effect.Morph(AnuraCurrent,{style:'width:' + AnuraImageArray[imageNum][1] + 'px;height:0;',duration: 0.3,afterFinish: function(){AnuraCanClick=true;myAnura.showImage(imageNum);}});
					}
				}	
			}else{ //there is no image currently displayed
				myAnura.showImage(imageNum);
			}
		}
	},

	// showImage()
	showImage: function(imageNum){
		
		// if there is a curret image, hide it
		try{Element.hide(AnuraCurrent);}catch(err){}
		AnuraCurrent = false;
		
		if(AnuraImageArray[imageNum][8]){
			// set this image to the current image
			AnuraCurrent = 'AnuraFull' + imageNum;
		
			// hide the loading message
			$('AnuraLoading').style.display = 'none';
			
			// Which animation style should I use?
			if(AnuraStyle=='fade'){// Use Fade effect
				
				//Make sure image is set to it's full size
				Element.setWidth(AnuraCurrent,AnuraImageArray[imageNum][4]);
				Element.setHeight(AnuraCurrent,AnuraImageArray[imageNum][5]);
				
				// Fade in image
				new Effect.Appear('AnuraFull' + imageNum, {duration: 0.5});
				
			}else{// Use morph effect
				
				//make sure image is at correct size for morph effect
				var newImage = $('AnuraFull' + imageNum);
				Element.setWidth(newImage,AnuraImageArray[imageNum][1]);
				Element.setHeight(newImage,0);
				Element.show(newImage);
				
				// morph in image
				new Effect.Morph(newImage,{style:'width:'+AnuraImageArray[imageNum][4]+'px;height:'+AnuraImageArray[imageNum][5]+'px;',duration: 0.5});
			}
			// fade in caption
			new Effect.Appear('AnuraCaption' + imageNum, {duration: 0.5});
		}else{// if the image hasn't preloaded yet
			
			// begin preloading image
			myAnura.preloadImage(imageNum);
			
			// interval to check if image has been loaded every .5 seconds
			AnuraInterval = window.setInterval("myAnura.loadImage(" + imageNum + ");", 500);
			
			// display loading message
			$('AnuraLoading').style.display = 'block';
		}
	},
	
	// preloadImage()
	preloadImage: function(imageNum){
		
		// make sure that this image exists in the image array
		if((imageNum) < AnuraImageArray.length){
			
			// if the image hasnt already been preloaded
			if($('AnuraFull'+imageNum)==undefined){
				
				// create fullsize <IMG>
				// when this image is downloaded, it calls preloadImage() to start loading the next image
				var fullImage = document.createElement("img");
				fullImage.setAttribute('id','AnuraFull' + imageNum);
				fullImage.style.display = 'none';
				fullImage.style.width = '75px';
				fullImage.style.height = '0';
				fullImage.onload = function(){
					AnuraImageArray[imageNum][8] = true;
					myAnura.preloadImage(imageNum + 1);
				};
				fullImage.src = AnuraImageArray[imageNum][3];
				$('AnuraFullsize').appendChild(fullImage);
				
				var caption = document.createElement("div");
				caption.setAttribute('id','AnuraCaption' + imageNum);
				caption.style.display = 'none';
				caption.innerHTML = '<div class="AnuraCredit">'+AnuraImageArray[imageNum][6]+'</div><div class="AnuraCaption">'+AnuraImageArray[imageNum][7]+'</div>';
				$('AnuraFullsize').appendChild(caption);
				
			}else{ // if the image has already been loaded
				// preload the next image
				myAnura.preloadImage(imageNum + 1);
			}
		}
	},
	
	// toggleNav()
	toggleNav: function(imageNum){
	
		// If they are on the first image
		if(imageNum<3){
			//hide the previous link
			Element.hide('AnuraPrev');
		}else{
			//make the previous link visible and update the onclick for it
			Element.show('AnuraPrev');
			$('AnuraPrev').onclick = function(){myAnura.loadImage(imageNum-1);try{event.returnValue=false;}catch(err){}return false;};
		}
		
		// If they are on the last image
		if(imageNum>(AnuraImageArray.length-4)){
			//hide the next link
			Element.hide('AnuraNext');
		}else{
			//make the next link visible and update the onclick for it
			Element.show('AnuraNext');
			$('AnuraNext').onclick = function(){myAnura.loadImage(imageNum+1);try{event.returnValue=false;}catch(err){}return false;};
		}
	},
	
	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org | Edit for Firefox by pHaez
	getPageSize: function(){
		
		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;
	},
	
	// getPageScroll()
	// Returns array with x,y page scroll values.
	// Core code from - quirksmode.org
	getPageScroll: function(){

		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 IE's
			yScroll = document.body.scrollTop;
		}

		arrayPageScroll = new Array('',yScroll) 
		return arrayPageScroll;
	},
	
	// goToImage()
	goToImage: function( imageNum ){
		$('AnuraThumb'+ (imageNum - 2)).morph('width:'+(AnuraImageArray[imageNum-2][1]/4)+'px; margin: 0 '+(AnuraImageArray[imageNum-2][1]/40)+'px;');
		$('AnuraThumb'+ (imageNum - 1)).morph('width:'+(AnuraImageArray[imageNum-1][1]*2/3)+'px; margin: 0 '+(AnuraImageArray[imageNum-1][1]/20)+'px;');
		$('AnuraThumb'+ (imageNum)).morph('width:'+AnuraImageArray[imageNum][1]+'px; margin: 0 '+(AnuraImageArray[imageNum][1]/10)+'px;');
		$('AnuraThumb'+ (imageNum + 1)).morph('width:'+(AnuraImageArray[imageNum+1][1]*2/3)+'px; margin: 0 '+(AnuraImageArray[imageNum+1][1]/20)+'px;');
		$('AnuraThumb'+ (imageNum + 2)).morph('width:'+(AnuraImageArray[imageNum+2][1]/4)+'px; margin: 0 '+(AnuraImageArray[imageNum+2][1]/40)+'px;');
		for(var i=0;i<imageNum-2; i++){
			$('AnuraThumb'+ i).morph('width:0px; margin: 0;');
		}
		for(var i=imageNum+3; i<AnuraImageArray.length; i++){
			$('AnuraThumb'+ i).morph('width:0px; margin: 0;');
		}
	},
	
	// close()
	close: function(){
		// clear interval if it's checking for a new image
		AnuraInterval = window.clearInterval(AnuraInterval);
		
		// hide close, next, and prev controls
		Element.hide('AnuraClose');
		Element.hide('AnuraNext');
		Element.hide('AnuraPrev');
	
		// fade out overlay
		// when finished, hide the overlay cover as well
		new Effect.Fade('AnuraOverlay',{duration:0.5,afterFinish:function(){Element.hide('AnuraOverlayCover');}});
		
		// fade out thumbnails
		new Effect.Fade('AnuraThumbs',{duration:0.5});
		
		// fade out the full size image
		// when finished, hide the Anura Gallery container as well
		new Effect.Fade('AnuraFullsize',{duration:0.5,afterFinish:function(){Element.hide('AnuraGallery');}});
	}
}

// Once the page has loaded, start Anura Gallery
function initAnura(){ myAnura = new Anura(); }
Event.observe(window, 'load', initAnura, false);
