/**
 * Dependencias
 * 		Prototype 1.6.1 (no testeado en versiones anteriores).
 * 		Script.aculo.us		Effect
 * 
 * BUGS
 * 		- [FIXED] Al hacer scroll con la ventana en autocenter, parpadea.
 *		- >=IE6 - Los campos input se ven por encima de la ventana y del fondo.
 *		- [FIXED]En la configuración, no funcionan las subclases. Habrá que hacerlo a mano.
 *		- Problema en webkit con el posicionamiento de las capas interiores.
 */

// Miramos la versión de IE:
if(Prototype.Browser.IE){
	if(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6) Prototype.BrowserFeatures['IEVersion']=6;
	else if(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))) Prototype.BrowserFeatures['IEVersion']=7;
	else Prototype.BrowserFeatures['IEVersion']=8;
}

/*
 * Buscamos los enlaces con clase ProtoWinLink para hacer que carguen en un ProtoWin. 
 */
document.observe('dom:loaded',function(){
	$$('a.protoWinLink').each(function(a){
		a.observe('click',function(e){
			e.stop();
			new ProtoWin(e.currentTarget.href);
		});
	});
});


var ProtoWin = Class.create({
	
	options_layout: {
		id: null,				// Id que se le pondrá al objeto ventana
		innerId:null,			// Id de la capa contenedora.
		url: false,				// Indica si el contenido es una url
		autoCenter: false,		// Autocentra la pantalla cuando se recarga el contenido. NO IMPLEMENTADO
		autoScale: true,		// Dimensiona la ventana automaticamente cuando se recarga el contenido. NO IMPLEMENTADO
		backBlock: true,			// Indica si se bloquea el fondo de la pantalla
		position: {				// Posición en la que se crea la ventana. NO IMPLEMENTADO
			x: null,
			y: null
		},
		classes: {
			window: 'ProtoWin',
			container: 'container',
			header: 'header',
			bottomBar: 'bottomBar',
			closeButton: 'closeButton',
			outerContainer: 'outer-container',
			backScreen: 'backScreen'
		},
		texts: {
			closeButton: '[Cerrar]',
			ajaxError: '<span class="alert">Error al conectar con el servidor</span>'
		}
	},
	
	window: null,		// Elemento de la ventana principal
	container: null,	// Elemento contenedor de la ventana
	screen: null,		// Pantalla de bloqueo de fondo
	
	/**
	 * Recibe un contenido y lo muestra en una ventana emergente
	 * @param {mixed} content: El contenido a mostrar.
	 * @param {object} options: Objeto de opciones.
	 */
	
	initialize: function(content,options){
		// Cargamos las opciones.
		this.options = Object.clone(this.options_layout);
		Object.extend(this.options.texts,options.texts); delete(options.texts);
		Object.extend(this.options.classes,options.classes); delete(options.classes);
		Object.extend(this.options,options);
		
		// Creamos la ventana
		this.window = new Element('div',{'id':this.options.id}).addClassName(this.options.classes.window)
			.insert(new Element('a').addClassName(this.options.classes.closeButton).observe('click',this.close.bind(this)).insert(this.options.texts.closeButton))
			.insert(this.outerContainer = new Element('div',{'id':this.options.innerId}).addClassName(this.options.classes.outerContainer)
				.insert(this.container = new Element('div').addClassName(this.options.classes.container)));
		
		// Si es una url, la cargamos en el contenedor
		if(/^https?:\/\//.test(content) || this.options.url){
			new Ajax.Request(content,{
				onSuccess: function(r){this.reload(r.responseText);}.bind(this),
				onFailure: function(r){this.reload(this.options.texts.ajaxError);}.bind(this)
			});
			content = new Element('div').addClassName('loading');
		}
		// Rellenamos la ventana
		this.container.insert(content);
		
		// Creamos el fondo
		if (this.options.backBlock) {
			this.screen = new Element('div').addClassName(this.options.classes.backScreen).observe('click',this.close.bind(this));
			$$('body')[0].insert(this.screen); // Insertamos en el documento		
			this.screen.setStyle({ // Le damos las medidas
				left: 0 + 'px',
				top: 0 + 'px',
				width: $$('body')[0].getWidth()+'px',
				height: $$('body')[0].getHeight()+'px',
				opacity: 0
			});
			new Effect.Opacity(this.screen, {// Lo mostramos con efecto
				to: 0.5,
				duration: 0.5
			});
		}
		
		// Posicionamos la ventana
		this.window.setOpacity(0);
		$$('body')[0].insert(this.window);
		new Effect.Opacity(this.window,{from:0,to:1,duration:0.5});
		this.window.setStyle({
			position:'fixed'//,
			//left:this.options.position.x+'px',
			//top:this.options.position.y+'px'
		});
		if(Prototype.Browser.IE && Prototype.BrowserFeatures.IEVersion<=6) this.window.setStyle({position:'absolute'}); // Fix IE6
		this.center();
		return this;
	},
	
	reload: function(content){
		var actualSize = this.window.getDimensions(); // Guardamos el tamaño actual del elemento.
		this.container.update(content); // Rellenamos el container con el nuevo contenido.
		var newSize = this.window.getDimensions(); // Guardamos el tamaño del container con el neuvo contenido.
		
		this.window.setStyle({ // Volvemos a dar al container el tamaño del principio.
			width: actualSize.width+'px',
			height: actualSize.height+'px'
		});
		// Preparamos el objeto de las nuevas características del container
		var newStyle = {};
		newStyle.width = newSize.width + 'px';
		newStyle.height = newSize.height + 'px';
		newStyle.left = document.viewport.getWidth() / 2 - newSize.width / 2+'px';/* if(newStyle.left<0) newStyle.left =0; newStyle.left+='px';*/
		newStyle.top = document.viewport.getHeight() / 2 - newSize.height / 2+'px';/* if(newStyle.top<0) newStyle.top =0; newStyle.top+='px';*/
		// Fix IE 6
		if(Prototype.Browser.IE && Prototype.BrowserFeatures.IEVersion<=6){
			newStyle.left = (document.viewport.getScrollOffsets()[0] + document.viewport.getWidth() / 2 - newSize.width / 2) + 'px';
			newStyle.top = (document.viewport.getScrollOffsets()[1] + document.viewport.getHeight() / 2 - newSize.height / 2) + 'px';
		}
		// Aplicamos la transformación desde el primer estado al estado actual
		this.container.hide(); // Escondemos
		this.window.morph('error',{
			style: newStyle,
			duration: 0.5,
			afterFinish: function(){
				this.container.setOpacity(0);
				this.container.show();
				new Effect.Opacity(this.container,{from:0,to:1,duration:0.5});
			}.bind(this)
		});
	},
	
	center: function(){
		var left = document.viewport.getWidth()/2-this.window.getWidth()/2;
		var top = document.viewport.getHeight()/2-this.window.getHeight()/2;
		// Fix IE6
		if(Prototype.Browser.IE && Prototype.BrowserFeatures.IEVersion<=6){
			var left = document.viewport.getScrollOffsets()[0]+document.viewport.getWidth()/2-this.window.getWidth()/2;
			var top = document.viewport.getScrollOffsets()[1]+document.viewport.getHeight()/2-this.window.getHeight()/2;
		}
		if(!this.window.getOpacity()) this.window.setStyle({left: left+'px',top: top+'px'});
		else new Effect.Move(this.window,{
			x:left, y:top,
			mode:'absolute',
			duration:0.5
		});
	},
	
	close: function(){
		new Effect.Opacity(this.window,{to: 0,duration: 0.3,afterFinish: function(){this.window.remove()}.bind(this)}); // Eliminamos la ventana	
		if($$('div.'+this.options.classes.backScreen).size()>0){new Effect.Opacity(this.screen,{to:0,duration:0.3,afterFinish:function(){this.screen.remove()}.bind(this)});} // Eliminamos el bloqueo de fondo
	}
});