/**
 * Gallery Plugin to insert gallery on current DOM model.
 *
 * @author Mariano Iglesias & Claudia Mansilla
 */
var GalleryPlugin = Class.create(AppPlugin, {
	/**
	 * Type of gallery (normal / embedded)
	 *
	 * @var string
	 */
	type: 'normal',
	
	/**
	 * Holds all images
	 *
	 * @var array
	 */
	images: [],
	
	/**
	 * Holds all DOM images
	 *
	 * @var array
	 */
	domImages: [],

	/**
	 * How many images to show per page
	 *
	 * @var int
	 */
	count: 10,

	/**
	 * Current page
	 *
	 * @var object
	 */
	page: 1,
	
	/**
	 * Total pages
	 *
	 * @var object
	 */
	pages: 1,
	
	/**
	 * Maximum width full size image can have
	 *
	 * @var int
	 */
	maximumWidth: 700,
	
	/**
	 * Current image being shown
	 *
	 * @var string
	 */
	currentImageId: null,
	
	/**
	 * Default opacity to use for thumbs when they are not hovered
	 *
	 * @var float
	 */
	thumbOpacity: 0.5,

	/**
	 * Called when the DOM object has updated (after window
	 * load or after an AJAX complete)
	 *
	 * @access public
	 */
	domUpdated: function()
	{
		var self = this;
		var holder = $('gallery-elements');
		
		if (holder)
		{
			this.clean();
			
			var settings = {count: 3, type: 'normal', maximumWidth: 744 };
			
			if (holder.readAttribute('rel'))
			{
				settings = Object.extend(settings, holder.readAttribute('rel').evalJSON());
			}
			
			this.type = settings.type;
			this.count = settings.count;
			this.maximumWidth = settings.maximumWidth;
			
			$$('#gallery-elements div.gallery-element').each(function(element) {
				self.images.push(element.readAttribute('rel').evalJSON());
			});
			
			if (this.images.length > 0)
			{
				this.pages = Math.ceil(this.images.length / this.count);
				this.show();
			}
		}
	},
	
	clean: function()
	{
		this.page = 1;
		this.currentImageId = null;
		this.images = [];
		this.domImages = [];
		
		$('gallery-thumbs').update('');
		$('gallery-navigation').update('');
		$('gallery-main').update('');
	},
	
	show: function(page)
	{
		if (!page)
		{
			page = this.page;
		}
		
		this.page = page;
		
		// Clean DOM images
		
		this.domImages = [];
		
		// Show thumbs
		
		var thumbnailsHolder = $('gallery-thumbs').update('');
		var self = this;
		var maximumHeight = null;
		
		for(var i=(this.page - 1) * this.count, limiti = (this.page * this.count <= this.images.length ? this.page * this.count : this.images.length); i < limiti; i++)
		{
			if (this.images[i].thumb.height > maximumHeight)
			{
				maximumHeight = this.images[i].thumb.height;
				
			}
		}
		
		for(var i=(this.page - 1) * this.count, limiti = (this.page * this.count <= this.images.length ? this.page * this.count : this.images.length); i < limiti; i++)
		{
			var options = { 
				'src': App.url('files/' + this.images[i].thumb.path),
				'id': 'gallery-thumb-' + this.images[i].id,
				'width': this.images[i].thumb.width,
				'height': this.images[i].thumb.height,
				'style': 'vertical-align: middle'
				/*,
				'style': 'display: none'*/
			};
			var divOptions = {};
			
			if (this.type == 'normal')
			{
				var paddingTop = 10;
				
				if (this.images[i].thumb.height < maximumHeight)
				{
					paddingTop += Math.ceil((maximumHeight - this.images[i].thumb.height) / 2);
				}
				
				divOptions = {'class': 'thumb-holder', 'style': 'float: left; display: table-cell; padding-top: ' + paddingTop + 'px; padding-bottom: ' + paddingTop + 'px; text-align: center;'};
			}
			
			var domImageHolder = thumbnailsHolder.appendChild(new Element('div', divOptions));
			
			var domImage = new Element('img', options);
			
			domImage.setOpacity(this.thumbOpacity);
			this.domImages.push(domImage);
			
			var thumbImageHolder = domImageHolder.appendChild(new Element('a', {
				'href': '#',
				'id' : 'link-thumb-' + this.images[i].id
			}));
			
			if (this.type == 'normal')
			{
				domImageHolder.appendChild(new Element('br'));
				domImageHolder.appendChild(document.createTextNode(this.images[i].name));
			}
			
			thumbImageHolder.appendChild(domImageHolder.appendChild(domImage));
			
			$('gallery-thumb-' + this.images[i].id).observe('mouseover', galleryPlugin.handleThumbHoverOn);
			$('gallery-thumb-' + this.images[i].id).observe('mouseout', galleryPlugin.handleThumbHoverOut);
			$('link-thumb-' + this.images[i].id).observe('click', galleryPlugin.handleThumbClick);
		}
		
		// Show pagination
		
		if (this.pages > 1)
		{
			var navigationHtml = '';
			
			if (this.type == 'normal')
			{
				navigationHtml += '<table class="borderless" width="100%"><tr>';
				navigationHtml += '<td width="50">';
			}
			
			navigationHtml += (this.page > 1 ? '<a href="#" onClick="galleryPlugin.show(' + (this.page - 1) + '); return false;" class="previous"></a>' : '');
			
			if (this.type == 'normal')
			{
				navigationHtml += '</td>';
				navigationHtml += '<td align="center">';
			
				for (var i=1; i <= this.pages; i++)
				{
					if (i > 1)
					{
						navigationHtml += ' - ';
					}
					
					if (i != this.page)
					{
						navigationHtml += '<a href="#" onClick="galleryPlugin.show(' + i + '); return false;">';
					}
					
					navigationHtml += i;
					
					if (i != this.page)
					{
						navigationHtml += '</a>';
					}
				}
			
				navigationHtml += '</td>';
				navigationHtml += '<td width="50">';
			}
			
			navigationHtml += (this.page < this.pages ? '<a href="#" onClick="galleryPlugin.show(' + (this.page + 1) + '); return false;" class="next"></a>' : '');
			
			if (this.type == 'normal')
			{
				navigationHtml += '</td>';
				navigationHtml += '</tr></table>';
			}
			
			$('gallery-navigation').update(navigationHtml);
		}
		
		if (this.type == 'embedded')
		{
			// Show first image in this page
			
			this.showImage(this.images[(this.page - 1) * this.count].id);
		}
	},
	
	handleThumbHoverOn: function(event)
	{
		var self = galleryPlugin;
		var currentId = event.element().readAttribute('id');
		
		if (currentId.replace('gallery-thumb-', '') == self.currentImageId)
		{
			return false;
		}
		
		Effect.Appear(currentId, {
			duration: 0.2,
			from: self.thumbOpacity,
			to: 1,
			queue: { scope: 'thumbScope', position: 'front' },
			afterFinish: function(event) {
				$(currentId).setOpacity(1);
			}
		});
	},
	
	handleThumbHoverOut: function(event)
	{
		var self = galleryPlugin;
		var currentId = event.element().readAttribute('id');
		
		if (currentId.replace('gallery-thumb-', '') == self.currentImageId)
		{
			return false;
		}
		
		Effect.Fade(currentId, {
			duration: 0.1,
			from: 1,
			to: self.thumbOpacity,
			queue: { scope: 'thumbScope', position: 'end' },
			afterFinish: function(event) {
				$(currentId).setOpacity(self.thumbOpacity);
			}
		});
	},
	
	handleThumbClick: function(event)
	{
		var self = galleryPlugin;
		
		self.showImage(event.element().readAttribute('id').replace('gallery-thumb-', ''), true);
	},
	
	showImage: function(id, clicked)
	{
		var image = null;
		var self = this;
		
		for (var i=0; image == null && i < this.images.length; i++)
		{
			if (this.images[i].id == id)
			{
				image = this.images[i];
			}
		}
		
		if (image != null)
		{
			if (this.type == 'normal')
			{
				var content = '<img src="' + App.url('files/' + image.main.path) + '" border="0" alt="" width="' + image.main.width + '" height="' + image.main.height + '" style="margin-top: 10px; margin-bottom: 10px;" /><br /><strong>' + image.name + '</strong>';
				var imageWindow = new UI.Window({
					id: 'image_' + image.id,
					width: image.main.width + 30,
					height: image.main.height + 90,
					draggable: true,
					resizable: true,
					minimize: false,
					maximize: false,
					close: 'destroy',
					theme: 'leopard',
					shadowTheme: 'drop_shadow',
					shadow: true
				}).setContent(content).center().show(true);
			}
			else
			{
				// Grey out previously colorized thumbnail
				
				if (this.currentImageId != null)
				{
					var previousImage = null;
					
					for(var i=0; previousImage == null && i < this.images.length; i++)
					{
						if (this.images[i].id == this.currentImageId)
						{
							previousImage = this.images[i];
						}
					}
					
					this.domImages.each(function(current) {
						if (current.readAttribute('id') == 'gallery-thumb-' + previousImage.id)
						{
							current.setOpacity(self.thumbOpacity);
						}
					});
				}
				
				// Colorize selected thumbnail
				
				this.currentImageId = id;
				
				$('gallery-thumb-' + this.currentImageId).setOpacity(1);
				
				// Load main picture
				
				var width = (image.main.width > this.maximumWidth ? this.maximumWidth : image.main.width);
				var height = (image.main.width > this.maximumWidth ? this.maximumWidth * (image.main.height / image.main.width) : image.main.height);
				
				$('gallery-main').update('').appendChild(new Element('img', { 
					'id': 'gallery-image-' + image.id,
					'src': App.url('files/' + image.main.path),
					'width': width,
					'height': height,
					'style': 'display: none'
				}));
				
				Effect.Appear('gallery-image-' + image.id);
			}
		}
	}
});

// Instantiate plugin

galleryPlugin = new GalleryPlugin();
