/**
 * Opciones de galeria
 */
Cubic_gallery_options = Object.extend({
	//Este variable permite cambiar el site_url, para que las llamadas ajax funcionan en un dominio distinto que el que recoge el agent.
	site_url_temp: '',  
	
    overlay_opacity: 0.5,           //La cantidad de transperencia
    animate: true,                  // Animar cambiando tamaño
    calculate_size: false,          // Calcular el tamaño de la capa de la galeria.
    fixed_width: 524,				// Si no se calcula el tamaño, poner aqui el valor fijo de ancho
    fixed_height: 396,				// Si no se calcula el tamaño, poner aqui el valor fijo de altura
    calculate_thumblayer_height: false,  // Calcular la altura de la capa thumbs
    resize_speed: 7,                // Velocidad de animación (1=mas lento and 10=mas rapido)
    change_image_speed: 0.5,        // Velocidad de animación (0.1=mas rapido and 3=mas lento)	
	thumb_size: [140,140],          // Tamaño maximo de thumbs. Primer valor es la anchura y el segundo la altura
	central_layer_size: [666,400],  // Tamaño de la capa central. El imagen visualizado se adapta a este tamaño, 
	                                // y si es mas pequeño, se muestra a 100% y centrada. 
	thumb_layer: 'left',            // top|left|center|right|bottom      Los thumbs flotan dentro la capa y jujando con los estilos se puede 
	                                // crear filas con x thumbs.
	main_images_layer: 'center',    // top|left|center|right|bottom      La capa en donde se muestran los imagenes grandes. No puede ser igual a thumb_layer
	title_layer: 'top',             // top|left|center|right|bottom      La capa en donde se escribe el titulo.
	description_layer: 'top',       // top|left|center|right|bottom      La capa en donde se escribe la descripcion (puede ser igual a lo de titulo).
	close_button_layer: 'top',		// top|left|center|right|bottom      La capa en donde se pone el boton de cerrar.
	image_navigation_layer: 'bottom',// top|left|center|right|bottom     La capa en donde se pone el texto dynamico con imagen tal de tal y los botones prev y next
	preload_images: false,          // Precargar los imagenen en la capa central cuande se abre una galeria de una carpeta. Precargar todos genera mas
	                                // trafico, pero permite pasar mas rapido por los fotos.
	force_open_first_image: true,	// Cuando esta puesto al true, siempre abre el primer imagen al abrir una galeria. Si es false, usara el id de imagen
									// que sale en el enlace, y abrira esa imagen por defecto.
    gallery_action: 'repository.getGallery/folder_id/', //La ruta para recoger una galeria. El resto se coge a traves de agent_url.    	
	text_loading: '<img src="html/images/loading.gif" alt="">',
	text_error: 'error',
	close_button: '<img src="html/images/close.png" alt="">'
	/*prev_button: '<<<',
	next_button: '>>>',
	text_image: "Imagen ",
	text_of: " de "*/	
}, window.Cubic_gallery_options || {});

/**
 * Crear la galeria
 */
var Cubic_gallery = Class.create();
Cubic_gallery.prototype = {
	
	initialize: function(){
		this.gallerylayers = new Hash();
		
		this.updateImageList();
		
        if (Cubic_gallery_options.resize_speed > 10) Cubic_gallery_options.resize_speed = 10;
        if (Cubic_gallery_options.resize_speed < 1)  Cubic_gallery_options.resize_speed = 1;
		if (Cubic_gallery_options.change_image_speed < 0.1)  Cubic_gallery_options.change_image_speed = 0.1;
		if (Cubic_gallery_options.change_image_speed > 3)  Cubic_gallery_options.change_image_speed = 3;

	    this.resizeDuration = Cubic_gallery_options.animate ? ((11 - Cubic_gallery_options.resize_speed) * 0.15) : 0;
	    this.overlayDuration = Cubic_gallery_options.animate ? 0.2 : 0;
		this.changeImageDuration = Cubic_gallery_options.animate ? Cubic_gallery_options.change_image_speed : 0;
		
		this.site_url = null;
		this.agent_url = null;
		this.current_repository = null;
		this.current_folder = null;
		this.current_resource = null;
		this.current_open_image = null;
		this.folder_title = null;
		
		this.gallery_images = new Hash();
		this.gallery_first_images = new Hash();
	},

	/**
	 * Actualizar los listeners a los enlaces con el rel que contiene "cubic_gallery".
	 * En su propio enlace (que tiene que ser el imagen) tiene que encontrar el repository_id y resource_id.
	 */
    updateImageList: function() {
		document.observe('click', (function(event){
            var target = event.findElement('a[rel^=cubic_gallery]') || event.findElement('area[rel^=cubic_gallery]');
			if (target) {
				//Poner por defecto que es una galeria valido.
				var valid_gallery = true;
				
				//Coger el url de agent
				//Si no se encuentra, no hay que seguir mostrando la galeria.
				var image_url = target.href.split('?');
				if (image_url.length>1) {
					//Coger los parametros desde el enlace.
					var params = target.href.toQueryParams();
					var repository_id = params.repository_id;
					var resource_id = params.resource_id;
										
					//Comprobar si hay que abrir una galeria o solo 1 unico imagen.
					//En el caso que el rel es cubic_gallery[3] se dice que es la galeria de carpeta con id 3.
					var folder_id = null;
					if ((target.rel != 'cubic_gallery')) {
						var sRegEx = new RegExp('cubic_gallery\\[(.*?)\\]');
						var res = target.rel.match(sRegEx);
						if (res) {
							var values = res[1];
							var values_array = values.split('|');
							var folder_id = values_array[0];
							var folder_title = values_array[1];
						}
					}
					
					//Recoger el agent_url
					var agent_url = image_url[0];
					
					//Y a traves de agent url, recoger el url de pagina.
					//Convertir el url en un array.
					var v_url = agent_url.split('/');
					
					//Primero, detectar si tiene el http://
					var site_url;
					if ((Cubic_gallery_options.site_url_temp === null) || (Cubic_gallery_options.site_url_temp == '')) {
						var sRegEx = new RegExp('http://');
						var res = agent_url.match(sRegEx);
						if (res) {
							site_url = v_url[0] + '//' + v_url[2] + '/';
						}
						else {
							site_url = v_url[0] + '/';
						}
						
						//Comprobar si estamos en local.
						if (site_url == 'http://localhost/') {
							var v_url = window.location.href.split('htdocs/');
							site_url = v_url[0] + 'htdocs/';
						}
					} else {
						site_url = Cubic_gallery_options.site_url_temp;
						}	
				} else {
					//Si no hay agent_url, la galeria no es valido.
					var valid_gallery = false;
				}
				
				//Si la galeria es valido, abrirlo. Sino, se abriría como un enlace normal.
				if (valid_gallery) {
					//Para el onclick de a
					event.stop();
					
					//Abrir la galeria
                	this.open(site_url, agent_url, repository_id, folder_id, resource_id, folder_title);					
				}				
            }
        }).bind(this));
    },

	/**
	 * Abrir la galeria. Si es por la primera ves, crear y cargarlo.
	 * @param {Int} folder_id
	 * @param {Int} current_image_id
	 */
	open: function(site_url, agent_url, repository_id, folder_id, resource_id, folder_title){
		//Guardar los variables
		this.site_url = site_url;
		this.agent_url = agent_url;
		this.folder_title = folder_title;
		
		//Si no hay repositorio, apuntarlo como null.
		if (Object.isUndefined(repository_id)) {
			this.current_repository = null;
		} else {
			this.current_repository = parseInt(repository_id, 10);
		}
		
		this.current_folder = parseInt(folder_id, 10);
		
		//Si no hay recurso, apuntarlo como null
		if (Object.isUndefined(resource_id) || (Cubic_gallery_options.force_open_first_image)) {
			if (!Object.isUndefined(this.gallery_first_images.get(this.current_repository + '_' + this.current_folder))) {
				this.current_resource = this.gallery_first_images.get(this.current_repository + '_' + this.current_folder);
			} else {
				this.current_resource = null;
			}
		} else {
			this.current_resource = parseInt(resource_id, 10);
		}
		
		//Cargar el html basico de galeria. Solo si no esta cargado aun.
		if (Object.isUndefined(this.gallerylayers.get('gallery'))) {
			
			//Crear la galeria (el html).
			this.create();
			
			//Mostrar la galeria.
			this.showGallery();
			
			//Despues de mostrar, calcular su ancho y altura y modificar sus estilos.
			if (Cubic_gallery_options.calculate_size) {
				this.setSize();
			}
		} else {
			//Si ya esta creada, solo mostrarlo
			this.showGallery();
		}
	},
	
	/**
	 * Crear galeria
	 */
	create : function() {
		//Crear los elementos basicos
		this.gallerylayers.set('overlay', new Element('div', {'id': 'cubic_gallery_overlay', 'class': 'cubic_gallery_overlay'}));
		this.gallerylayers.set('gallery', new Element('div', {'id': 'cubic_gallery_content', 'class': 'cubic_gallery_main'}));
		
		//Lo que inserta el update tiene que ser codigo recogido con Ajax.
		this.gallerylayers.get('gallery').update('<div id="cubic_gallery_main_block" class="cubic_gallery_main_pusher cubic_gallery_container">'
				+ '<div id="cubic_gallery_top_block" class="cubic_gallery_top">'
				+ '</div>'
				+ '<div class="cubic_gallery_container">'
				+ '<div id="cubic_gallery_left_block" class="cubic_gallery_left cubic_gallery_container">'
				+ '</div>'
				+ '<div id="cubic_gallery_center_block" class="cubic_gallery_center cubic_gallery_container">'
				+ '</div>'
				+ '<div id="cubic_gallery_desc_block" class="cubic_gallery_desc cubic_gallery_container">'
				+ '</div>'
				+ '<div id="cubic_gallery_right_block" class="cubic_gallery_right cubic_gallery_container">'
				+ '</div>'
				+ '</div>'
				+ '<div id="cubic_gallery_bottom_block" class="cubic_gallery_bottom cubic_gallery_container">'
				+ '</div>'
				+ '</div>');
				
		//Ocultarlas antes de insertar
		this.gallerylayers.get('overlay').hide();
		this.gallerylayers.get('gallery').hide();
		
		//Crear eventos sobre estos elementos
		this.gallerylayers.get('overlay').observe('click', this._closeHandler.bindAsEventListener(this, false));
		this.gallerylayers.get('gallery').observe('click', this._closeHandler.bindAsEventListener(this, true));
		
		//Insertar el html
		var objBody = $$('body')[0];
		objBody.appendChild(this.gallerylayers.get('overlay'));
		objBody.appendChild(this.gallerylayers.get('gallery'));
		
		//Buscar las capas principales de la galeria, para poder rellenarlos.
		var v_layers = ['main', 'top', 'left', 'center', 'right', 'bottom', 'desc'];
		for (var i = 0, len = v_layers.length; i < len; ++i) {
			if ($('cubic_gallery_' + v_layers[i] + '_block')) this.gallerylayers.set(v_layers[i], $('cubic_gallery_' + v_layers[i] + '_block'));
		}
		
		//Poner el tamaño a la capa central.
		this.gallerylayers.get('center').setStyle({
			'width': Cubic_gallery_options.central_layer_size[0] + 'px',
			'height': Cubic_gallery_options.central_layer_size[1] + 'px'
		});
		
		//Poner las capas left y right con la misma altura.
		if (Cubic_gallery_options.calculate_thumblayer_height) {
			this.gallerylayers.get('left').setStyle({
				'height': Cubic_gallery_options.central_layer_size[1] + 'px'
			});
		}
		this.gallerylayers.get('right').setStyle({
			'height': Cubic_gallery_options.central_layer_size[1] + 'px'
		});
		
		//Insertar el boton html que permite cerrar.
		this.gallerylayers.set('close_button', new Element('button', {
			'type': 'button',
			'class': 'cubic_gallery_close_button'
		}).update(Cubic_gallery_options.close_button));
		
		//Insertar el boton de cerrar.
		this.gallerylayers.get(Cubic_gallery_options.close_button_layer).appendChild(this.gallerylayers.get('close_button'));
		
		//Crear eventos sobre estos elementos
		this.gallerylayers.get('close_button').observe('click', this._closeHandler.bindAsEventListener(this, false));
		
		//Insertar la navegacion
		/*this.gallerylayers.set('navegation', new Element('div', {'class': 'cubic_gallery_navegation'}));
		this.gallerylayers.set('prev_button', new Element('button', {
			'type': 'button',
			'class': 'cubic_gallery_prev_button'
		}).update(Cubic_gallery_options.prev_button));
		this.gallerylayers.set('next_button', new Element('button', {
			'type': 'button',
			'class': 'cubic_gallery_next_button'
		}).update(Cubic_gallery_options.next_button));*/
	},

	/**
	 * Handler para mostrar el select de eligir modelo
	 * @param {Object} event
	 */
	_closeHandler : function(event) {
		var check_layer = arguments[1];		
		if (check_layer) {
			var element = Event.findElement(event, 'div');
			if (element.id != this.gallerylayers.get('gallery').id) {
				return false;
			}
		}
		this.close();
	},

	/**
	 * Mostrar la galleria
	 */
	showGallery: function() {
		//Cerrar capas que pueden dar problemas con el z-index
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

		//Mostrar el fondo, y actualizar el tamaño de la capa de el
		this.showOverlay(true);

		//Posicionar la galeria
		this.setPosition();
		
		//Occultar las capas de folders de la galeria antes de abrirlo
		var me = this;
		this.gallerylayers.get('gallery').select('div.cubic_gallery_central_layer_images').each(function(el) {
			var current_folder = me.gallerylayers.get('cubic_gallery_central_images_layer_' + me.current_repository + '_' + me.current_folder);
			if (!current_folder || (el.id != current_folder.id)) {
				el.hide();
			}
		});
		
		//Mostrar la galeria.
		this.gallerylayers.get('gallery').show();
		
		//Despues de mostrar el html vacio de galeria, rellenarlo con la tira de imagenes.
		//Solo si hay una id de carpeta.
		if (this.current_folder !== null) {
			//Cargar los thumbs
			this.loadThumbs(this.site_url, this.agent_url, this.current_repository, this.current_folder, this.current_resource);
		} else {
			//Si no hay carpeta, solo mostrar el imagen principal como un imagen suelta. En este caso, hay que mostrar la capa de
			//thumbs vacio.
			this.hideThumbs();
		}
	},
	
	/**
	 * Mostrar el fondo
	 * @param {Boolean} update
	 */
	showOverlay: function(update) {
		//Comprobar si hay que actualizar el fondo
		if (update) {
			this.updateOverlay();
		}
		
		//Mostrar el fondo
		new Effect.Appear(this.gallerylayers.get('overlay'), { duration: this.overlayDuration, from: 0.0, to: Cubic_gallery_options.overlay_opacity });		
	},
	
	/**
	 * Actualizar el tamaño del fondo
	 */
	updateOverlay: function() {
		//Cambiar el tamaño de overlay para que nea igual que la pagina
        var arrayPageSize = this.getPageSize();
        this.gallerylayers.get('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
	},

	/**
	 * Actualizar el tamaño de la galeria
	 */
	setSize: function() {
		var main_block_width = this.gallerylayers.get('left').getWidth() + Cubic_gallery_options.central_layer_size[0] + this.gallerylayers.get('right').getWidth();
		this.gallerylayers.get('main').setStyle({
			'width': main_block_width + 'px'
		})
	},

	/**
	 * Posicionar la galeria
	 */
	setPosition: function() {
        var offsets = document.viewport.getScrollOffsets();
        var top = offsets[1] + (document.viewport.getHeight() / 10);
        var left = offsets[0];
        this.gallerylayers.get('gallery').setStyle({ 'top': top + 'px', 'left': left + 'px' });
	},
		
	/**
	 * Cargar los thumbs.
	 * @param {String} site_url
	 * @param {String} agent_url
	 * @param {Int} repository_id
	 * @param {Int} folder_id
	 * @param {Int} resource_id
	 */
	loadThumbs: function(site_url, agent_url, repository_id, folder_id, resource_id) {
		//Si no existe, crearlo. Sino, solo abrir.
		if (Object.isUndefined(this.gallerylayers.get('thumb_layer_' + repository_id + '_' + folder_id))) {
			
			//Crear el elemento que va a contener los thumbs
			var thumb_strip = new Element('div', {
				'id': 'thumb_layer_' + repository_id + '_' + folder_id,
				'class': 'cubic_gallery_thumbs_strip'
			}).update(Cubic_gallery_options.text_loading);
			
			//Ponerlo por defecto oculto.
			thumb_strip.hide();
			
			//Ponerlo en su sitio
			this.gallerylayers.get(Cubic_gallery_options.thumb_layer).appendChild(thumb_strip);
			
			//Guardar la capa en el hash.
			this.gallerylayers.set('thumb_layer_' + repository_id + '_' + folder_id, thumb_strip);
			
			//Y cargar dynamicamente los imágenes de los thumbs.
			var ajax_thumbs_url = site_url + Cubic_gallery_options.gallery_action + folder_id;
			if (repository_id) {
				ajax_thumbs_url += '/repository_id/' + repository_id;
			}
			var me = this;
			new Ajax.Request(ajax_thumbs_url, {
				method:'get',
				onSuccess: function(transport){					
					me.loadThumbsImages(transport.responseText, agent_url, repository_id, folder_id);
				}
			});
		} else {
			//Comprobar si se han cargado los imagenes
			var image = this.gallery_images.get(repository_id + '_' + folder_id + '_' + resource_id);
			if (image) {
				//Abrir el imagen principal
				this.openImage(repository_id, folder_id, resource_id);
			}
		}
		
		//Mostrar
		this.showThumbs(repository_id, folder_id);
	},
	
	/**
	 * Antes de mostrar un serie de thumbs, ocultar todos.
	 * Despues se puede abrir la capa que se ha pedido, pero solo si es de carpeta seleccionado actualmente.
	 */	
	showThumbs: function(repository_id, folder_id) {
		//Ocultar antes 
		this.hideThumbs();
		
		//Mostrarlo
		if ((this.current_folder == folder_id) && (this.current_repository == repository_id)) {
			this.gallerylayers.get('thumb_layer_' + repository_id + '_' + folder_id).show();
		}
	},
	
	/**
	 * Ocultar los thumbs
	 */
	hideThumbs: function() {
		//Ocultar antes 
		this.gallerylayers.get('gallery').select('div.cubic_gallery_thumbs_strip').each(function(el) {
			el.hide();
		});
	},
	
	/**
	 * Comprobar el JSON y si es correcto, crear la capa de thumbs y llamar a la funcion que lo rellena con cada thumb.
	 * @param {Object} data
	 * @param {String} agent_url
	 * @param {Int} repository_id
	 * @param {Int} folder_id
	 */
	loadThumbsImages: function(data, agent_url, repository_id, folder_id) {
		var json = data.evalJSON();
		if (json) {
			var v_images = json;
			if (Object.isArray(v_images)) {
				//Coger la capa de thumbs
				this.gallerylayers.get('thumb_layer_' + repository_id + '_' + folder_id).update('');
				
				//Recorrer los imagenes
				for (var i = 0, len = v_images.length; i < len; ++i) {
					var hash_image = $H(v_images[i]);
					hash_image.set('repository_id', repository_id);
					hash_image.set('folder_id', folder_id);
					hash_image.set('agent_url', agent_url);
					
					//Guardar la información del imagen en un hash.
					this.gallery_images.set(repository_id + '_' + folder_id + '_' + hash_image.get('id'), hash_image);
					
					//Coger el id de primer imagen y apuntarlo
					if (i == 0) {
						this.gallery_first_images.set(repository_id + '_' + folder_id, hash_image.get('id'));
					}
					
					//Si no hay id de recurso actual, o en la configuracion esta puesto que hay que mostrar el primero por defecto,
					//tomar el primer id de este bucle.
					if (this.current_resource===null) {
						this.current_resource = hash_image.get('id');
					}
					
					//Si se encuentra el imagen seleccionado, cargarlo en la parte principal
					if ((repository_id == this.current_repository) && (folder_id == this.current_folder) && (hash_image.get('id') == this.current_resource)) {
						//Abrir el imagen principal
						this.openImage(repository_id, folder_id, hash_image.get('id'));
					}
					
					//Cargar el thumb
					this.loadThumbImage(hash_image);
				}
				
			} else {
				this.gallerylayers.get('thumb_layer_' + repository_id + '_' + folder_id).update(Cubic_gallery_options.text_error);
			}
		}
	},
	
	/**
	 * Cargar un thumb
	 * @param {Object} image
	 */
	loadThumbImage: function(thumb_image) {
		//Coger la informacion del imagen
		if (thumb_image.get('width')>thumb_image.get('height')) {
			var max = Cubic_gallery_options.thumb_size[0];
		} else {
			var max = Cubic_gallery_options.thumb_size[1];
		}
		
		//Crear el imagen (thumb)
		var img_thumb = new Element('img', {
			'src': this.agent_url + '?repository_id=' + thumb_image.get('repository_id') + '&resource_id=' + thumb_image.get('id') + '&max=' + max,
			'title': thumb_image.get('title')
		});
		
		//Poner el handler
		img_thumb.observe('click', this._openImageHandler.bindAsEventListener(this, thumb_image.get('repository_id'), thumb_image.get('folder_id'), thumb_image.get('id')));
		
		//Insertar el elemento
		this.gallerylayers.get('thumb_layer_' + thumb_image.get('repository_id') + '_' + thumb_image.get('folder_id')).appendChild(img_thumb);
		
		//Si precargar es true, precargar el imagen central.
		if (Cubic_gallery_options.preload_images) {
			this.loadImage(thumb_image.get('repository_id'), thumb_image.get('folder_id'), thumb_image.get('id'));
		}
		
	},
	
	/**
	 * Manejar el onclick de un thumb para abrir un imagen en la capa central
	 * @param {Object} event
	 */
	_openImageHandler: function(event) {
		var repository_id = arguments[1];
		var folder_id = arguments[2];
		var resource_id = arguments[3];
				
		//Abrir el imagen
		this.openImage(repository_id, folder_id, resource_id);
	},
	
	/**
	 * Abrir un imagen en la capa central
	 * @param {Int} repository_id
	 * @param {Int} folder_id
	 * @param {Int} resource_id
	 */
	loadImage: function(repository_id, folder_id, resource_id) {
		//Si no existe la capa en el area central, crearlo
		if (Object.isUndefined(this.gallerylayers.get('cubic_gallery_central_images_layer_' + repository_id + '_' + folder_id))) {
			var central_images_layer = new Element('div', {
				'id': 'cubic_gallery_central_images_layer_' + repository_id + '_' + folder_id,
				'class': 'cubic_gallery_central_layer_images'
			});
			
			//Ponerlo por defecto oculto.
			central_images_layer.hide();
			
			//Guardar la capa
			this.gallerylayers.set('cubic_gallery_central_images_layer_' + repository_id + '_' + folder_id, central_images_layer);
			
			//Ponerlo en su sitio
			this.gallerylayers.get(Cubic_gallery_options.main_images_layer).appendChild(central_images_layer);
		} else {
			var central_images_layer = this.gallerylayers.get('cubic_gallery_central_images_layer_' + repository_id + '_' + folder_id);
		}
		
		//Coger la informacion del imagen para insertar
		var image = this.gallery_images.get(repository_id + '_' + folder_id + '_' + resource_id);
		
		//Crear el imagen grande.
		//Primero, coger los tamaños maximos
		if (Cubic_gallery_options.calculate_size) {
			var max_width = Cubic_gallery_options.central_layer_size[0];
			var max_height = Cubic_gallery_options.central_layer_size[1];
		} else {
			var max_width = Cubic_gallery_options.fixed_width;
			var max_height = Cubic_gallery_options.fixed_height;
		}
		
		//Comprobar si el imagen tiene un tamaño mayor a la capa central.
		var img_url_suffix = '';
		var padding_top = 0;
		var padding_left = 0;
		if ((image.get('width') > max_width) || (image.get('height') > max_height)) {
		
			//Coger la forma del imagen
			if (image.get('width') >= image.get('height')) {
				var img_shape = "landscape";			
			} else {
				var img_shape = "portrait";
			}
			
			//Segun la forma, comprobar como hay que mostrarlo.
			var max;
			if (img_shape=="landscape") {
				if (image.get('width')>max_width) {
					max = 'w=' + max_width;
					var new_height = (max_width / image.get('width')) * image.get('height');
					var new_width = max_width;
				}
			} else {
				if (image.get('height')>max_height) {
					max = 'h=' + max_height;
					var new_width = (max_height / image.get('height')) * image.get('width');
					var new_height = max_height;
				}
			}
			
			//var new_height = (max_width / image.get('width')) * image.get('height');
			var padding_top = (Cubic_gallery_options.central_layer_size[1] - new_height)/2;
			//var new_width = (max_height / image.get('height')) * image.get('width');
			var padding_left = (Cubic_gallery_options.central_layer_size[0] - new_width)/2;
						
			if (img_shape=="landscape") {
				if (new_height>max_height) {
					max = 'h=' + max_height;
				}
			} else {
				if (new_width>max_width) {
					max = 'w=' + max_width;
				}
			}
				
			img_url_suffix = '&' + max;
			
		} else {
			//Si el imagen no es mayor que el bloque central, mostrarlo centrado.			
			var padding_left = (max_width - image.get('width'))/2;
			var padding_top = (max_height - image.get('height'))/2;
		}
		
		//Crear el imagen (grande)
		var img_main = new Element('img', {
			'src': image.get('agent_url') + '?repository_id=' + image.get('repository_id') + '&resource_id=' + image.get('id') + img_url_suffix,
			'id': 'cubic_gallery_img_' + image.get('repository_id') + '_' + image.get('id'),
			'title': image.get('title')
		});
		
		//Comprobar si no hay max y que si tenemos que poner los paddings al imagen.
		img_main.setStyle({
			'paddingLeft': padding_left + 'px',
			'paddingTop': padding_top + 'px'
		});
		
		//Ponerlo por defecto oculto.
		img_main.hide();
		
		//Poner el imagen el la capa
		central_images_layer.appendChild(img_main);		
	},
	
	/**
	 * Abrir un imagen en la capa principal.
	 * @param {Int} repository_id
	 * @param {Int} resource_id
	 */
	openImage: function(repository_id, folder_id, resource_id) {
		//Comprobar si el imagen ya existe en la pagina
		if (!$('cubic_gallery_img_' + repository_id + '_' + resource_id)) {
			this.loadImage(repository_id, folder_id, resource_id);
		}
		
		if (this.current_open_image != 'cubic_gallery_img_' + repository_id + '_' + resource_id) {
			//Mostrar la capa con los imagenes principales (estos capas contienen los fotos de cada carpeta)
			var folder_layer = this.gallerylayers.get('cubic_gallery_central_images_layer_' + repository_id + '_' + folder_id);
			if (!folder_layer.visible()) {
				folder_layer.show();
			}
			
			//Occultar el imagen actualmete abierto
			if ($(this.current_open_image)) {
				new Effect.Fade($(this.current_open_image), {
					duration: this.changeImageDuration
				});
			}
			
			//Cambiar el titulo y descripcion.
			if (Object.isUndefined(this.gallerylayers.get('title_block'))) {
				var title_block = new Element('div', {
					'id': 'cubic_gallery_title_block',
					'class': 'cubic_gallery_title_block'
				});
				this.gallerylayers.get(Cubic_gallery_options.title_layer).appendChild(title_block);
				this.gallerylayers.set('title_block', title_block);
			}
			this.gallerylayers.get('title_block').update(this.folder_title);	
			
			var image = this.gallery_images.get(repository_id + '_' + folder_id + '_' + resource_id);
			var title = '';
			var desc = '';
			if (image.get('title') != '' && image.get('title') != null) {
				title = '<span class="">' + image.get('title') + '</span>';
			}
			if (image.get('description') != '' && image.get('description') != null) {
				desc = '<span class="">' + image.get('description') + '</span>';
			}
			if (desc != '') {
				if (Cubic_gallery_options.title_layer == Cubic_gallery_options.description_layer) {
					title += '<br />' + desc;
				} else {
					this.gallerylayers.get(Cubic_gallery_options.description_layer).update(desc);
				}
			}
			this.gallerylayers.get('desc').update(title);
		
			//Mostrar el imagen
			this.current_open_image = 'cubic_gallery_img_' + repository_id + '_' + resource_id;
			new Effect.Appear($(this.current_open_image), {
				duration: this.changeImageDuration
			});
		}
	},
	
    /**
     * Cerrar la galeria
     */
    close: function() {
        this.gallerylayers.get('gallery').hide();
        new Effect.Fade(this.gallerylayers.get('overlay'), { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },
	
    /**
     * Coger el tamaño de la pagina
     */
    getPageSize: function() {
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			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
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				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 = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}
}

//Despues de cargar el dom, ininciar la galeria.
document.observe('dom:loaded', function () { new Cubic_gallery(); });
