PopupGallery = Class.create();
PopupGallery.prototype = {
	defaultImageWidth: 980,
	previous: null,
	next: null,
	items: [],

 	initialize: function(itemClass) {
		this.items = $$('li.' + itemClass);
		if (this.items.length>0) {
			this.createPopup();
			this.setImageAttributes();
		}

	},

 	createPopup: function() {
		this.closeBtn = Builder.node('a', {href:'#close', 'class':'close'}, 'Close');
		Event.observe(this.closeBtn, 'click', this.close.bindAsEventListener(this), false);

		this.popupimg = Builder.node('img', {'class':'popupimg', border:0});
		this.descriptionPanel = Builder.node('div', {'class':'description'});
		var middle = [this.popupimg, this.descriptionPanel];
		
 		this.popup = Builder.node('div', {id:'popupGal'}, [
 			
	 		Builder.node('div', {'class':'topmiddlecap'}, [this.closeBtn]),
 			Builder.node('div', {'class':'middle'}, middle)
 			
 		]);

 		document.body.appendChild(this.popup, document.body.firstChild);
 	},

 	setImageAttributes: function() {
 		for (var i=0; i<this.items.length; i++) {
 			this.items[i] = $(this.items[i]).down(0);
 			var item = this.items[i]; 

 			
			item.img = new Image();
			item.img.src = item.href;
			item.img.alt = $(item).down(0).alt;
 			this.setEvent(item, i);
 		}
	},

 	setEvent: function(item, i) {
		Event.observe(item, 'click', this.onClick.bindAsEventListener(this, item, i), false);
	},

	windowSize: function() {
		var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
		var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
		var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
		var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
		return {'width':width, 'height':height, 'x':x, 'y':y}
	},

 	onClick: function(evt, item, i) {
 		// store the small size and position for later
		this.width = (item.offsetWidth>80) ? 80 : item.offsetWidth;
		this.left = evt.pageX || evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		this.left -= this.width/2;
		this.height = item.offsetHeight;
		this.top = evt.pageY || evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
		this.top -= this.height/2;

		// stop the default event
 		Event.stop(evt);
		
 		this.popImage(evt, item, i);
 	},

 	popImage: function(evt, item, i) {
 		// reset the movie stuff
		this.popup.onclick = this.close.bindAsEventListener(this);

		// set the source for image in the popup
 		this.popupimg.src = item.img.src;
 		this.popupimg.alt = item.img.alt;
		this.descriptionPanel.innerHTML = item.img.alt;
 		// get the ratio of that image
 		var ratio = item.img.width / item.img.height;

		// default size
		var left, top = null;
		var width = this.defaultImageWidth;
		this.padleft = (this.popup.offsetWidth-width);
		var height = Math.round(width/ratio);
		this.padtop = (this.popup.offsetHeight-height);

		// re-size functions
		var smallWidth = function() {
 			//console.log('width is small'); // width is small
	 		width = Math.round(this.windowSize().width*.8);
			height = Math.round(width/ratio);
		}.bind(this)

		var smallHeight = function() {
 			//console.log('height is small'); // height is small
			height = Math.round(this.windowSize().height*.6);
	 		width = Math.round(height*ratio);
		}.bind(this)

		// figure out if we're small or big
	 	if (this.windowSize().width<width+this.padleft && this.windowSize().height<height+this.padtop) {
 			//console.log('both are small'); // both are small
	 		if (this.windowSize().width<this.windowSize().height*ratio) {
	 			smallWidth();
	 		} else {
	 			smallHeight();
	 		}
	 	} else if (this.windowSize().width<width+this.padleft) {
	 		smallWidth();
	 	} else if (this.windowSize().height<height+this.padtop) {
	 		smallHeight();
	 	}

		var after = function() {
			Element.removeClassName(this.popup, 'isanim');
			Element.addClassName(this.popup, 'popped');
		}.bind(this)

		// set the position of the image according to the height/width we just found
		if (!left) left = this.windowSize().x+(this.windowSize().width-width)/2;
		if (!top) top = this.windowSize().y+(this.windowSize().height-height)*.6;
		
		// call the effect
		this.pop(width, top, height, left, after);
	},

 	pop: function(width, top, height, left, after) {
		// prep the popup for the effect
		this.popup.style.width = this.width+'px';
		this.popup.style.height = this.height+'px';
		this.popup.style.left = this.left+'px';
		this.popup.style.top = this.top+'px';

		this.popup.style.zIndex = '999';
 		Element.setOpacity(this.popup, 0);

		// do the craziness
		new Effect.Parallel([
				new Effect.MoveBy(this.popup, top-this.top, left-this.left, { sync:true }), 
				new Effect.Scale(this.popup, (width/this.width)*100, { sync:true, scaleMode:{ originalWidth:this.width, originalHeight:this.height }, scaleY:false, scaleContent:false }),
				new Effect.Scale(this.popup, (height/this.height)*100, { sync:true, scaleMode:{ originalWidth:this.width, originalHeight:this.height }, scaleX:false, scaleContent:false }),
				new Effect.Appear(this.popup, { sync:true })
			],
			{ duration:.2, beforeStart:function() { Element.addClassName(this.popup, 'isanim'); }.bind(this), afterFinish:after }
		);
	},

 	close: function(evt) {
 		if (evt) Event.stop(evt);

		var width = (this.popupimg.offsetWidth) ? this.popupimg.offsetWidth : this.popup.offsetWidth - this.padleft;
		var left = this.popup.offsetLeft + this.padleft/2;
		var height = (this.popupimg.offsetHeight) ? this.popupimg.offsetHeight : this.popup.offsetHeight - this.padtop/2;
		var top = this.popup.offsetTop + this.padtop/2;

		new Effect.Parallel([
				new Effect.MoveBy(this.popup, this.top-top, this.left-left, { sync:true }), 
				new Effect.Scale(this.popup, (this.width/width)*100, { sync:true, scaleMode:{ originalWidth:width, originalHeight:height }, scaleY:false, scaleContent:false }),
				new Effect.Scale(this.popup, (this.height/height)*100, { sync:true, scaleMode:{ originalWidth:width, originalHeight:height }, scaleX:false, scaleContent:false }),
				new Effect.Fade(this.popup, { sync:true })
			],
			{ duration:.3, afterFinish:this.afterClose.bind(this) }
		);
	},

 	afterClose: function(evt) {
		// reset everything
		this.popup.style.width = '';
		this.popup.style.height = '';
		this.popup.style.left = '';
		this.popup.style.top = '';
		this.popup.className = '';

		this.popup.style.zIndex = '-10';
		this.popup.style.display = '';
		this.popup.style.visibility = '';
		Element.setOpacity(this.popup, '');
		
		if (Prototype.Browser.WebKit) {
			if (!this.scrollTo) this.scrollTo = 1;
			window.scroll(this.windowSize().x+this.scrollTo, this.windowSize().y+this.scrollTo);
			this.scrollTo = -this.scrollTo;
			window.scroll(this.windowSize().x+this.scrollTo, this.windowSize().y+this.scrollTo);
			this.scrollTo = -this.scrollTo;
		}
		
		this.resetVar();
 	},

 	resetVar: function(evt) {
		this.width, this.padleft, this.left, this.height, this.padtop, this.top = null;
 	}

}


AlbumGallery = Class.create();
AlbumGallery.prototype = {
 	initialize: function(container, options) {
		this.container = $(container);
		this.options   =  options || {};
		this.options.width = this.options.width || 320;
		this.options.height = this.options.height || 240;
		this.options.changeTime = this.options.changeTime || 5;
		this.options.effects 	= this.options.effects || ['Fade','BlindUp','Shrink','Shrink','Fade','Shrink'];
		
		this.fotos = $$('#'+container + ' img');
		
		this.lienzo = Builder.node('img', {id:'lienzoGallery',src:this.fotos[0].src,width:this.options.width+'px',height:this.options.height+'px',style:'position:absolute;z-index:900;'});
		
		this.marco = Builder.node('img', {id:'marcoGallery',src:this.fotos[1].src,width:this.options.width+'px',height:this.options.height+'px',style:'position:absolute;z-index:899;'});
		
		this.clavo = Builder.node('div', {id:'clavoGallery'}, [
	 		this.lienzo,this.marco
	 		]);
		
		Element.update(this.container,'');  
	    
	    this.currentIndex = 1;
		this.container.appendChild(this.clavo);
		
		this.startup();

	},
	startup: function() { 
		new PeriodicalExecuter(this.cycle.bind(this), this.options.changeTime) // change image every 5 seconds 
	}, 
	cycle: function() {    
    	var actualIndex = this.currentIndex;
    	var nextIndex = (this.fotos.length - 1 == this.currentIndex) ? 0 : this.currentIndex + 1; 
    	this.currentIndex = nextIndex;
    	var fx = this.options.effects;
    	var aleat = Math.round(Math.random() * (fx.length-1)); 
    	
    	var fun = fx[aleat];
    	var dirs = ['top-left','top-right','bottom-left','bottom-right','center'];
    	var aleat = Math.round(Math.random() * (dirs.length-1)); 
    	var dir = dirs[aleat];
    	
		new Effect[fun]('lienzoGallery', { // the id of the <DIV> containing the photos 
			duration: 1, 
			fps: 50,
			direction: dir,
			afterFinish: function() { 
				// alert(this.fotos[this.currentIndex]);
				this.lienzo.src = this.fotos[actualIndex].src;
				this.lienzo.alt = this.fotos[actualIndex].alt;
				
				this.lienzo.setStyle({display:'block'});
				
				this.marco.src = this.fotos[nextIndex].src;
				new Effect.Appear(this.marco,{duration: 1,fps: 5});
			}.bind(this)
		}) 
	} 
} 

/*
//
// Uso de las funciones de este script
//
//
Behaviour.addLoadEvent( function() {
	new PopupGallery('galleryitem');
	new AlbumGallery('albumFotos',{width:640,height:480,changeTime:3,effects:['Fade']});
});
*/
