
var CZ = CZ || {};

CZ.Modal = new Class({
	Implements: Options,
	options: {
		linkSelector: 'a[rel^=dialog[]', // selector por defecto. De momento no implementamos imagenes
		customSelector: null,
		overlayOpacity: .5,
		overlayColor: '#000',
		loadedDiv: 'div#contenido',
		initialWidth: 100,
		initialHeight: 400,
		closeLabel: 'Cerrar'
	},
	initialize: function(options){
		this.setOptions(options);
		this.options.customSelector != null ? this.links = $$(this.options.customSelector) : this.links = $$(this.options.linkSelector);
		if(!this.links.length) return;
		this.open();									
	},
	showOverlay: function(){
		this.wrapper = new Element('div');
				
		//console.log(window.getScrollSize().y);
		
		var overlay = new Element('div',{
			'class': 'modal-overlay'				
		}).setStyles({
			'background': this.options.overlayColor,
			'opacity': this.options.overlayOpacity,
			'height': document.documentElement.scrollHeight // comprobar que esto funciona en todos los navegadores igual
		});
		
		overlay.addEvent('click', this.close.bindWithEvent(this));	
			
		// evitamos problemas de z-index en IE
		var iframe = new Element('iframe',{
			'src': 'javascript:false;'
		}).setStyles({
			'opacity': 0,
			'height': document.documentElement.scrollHeight // comprobar que esto funciona en todos los navegadores igual
		});
		
		overlay.adopt(iframe);
		
		var dialog = new Element('div',{
			'id': 'dialog',
			'role': 'dialog',
			'aria-hidden': 'false',
			'tabindex': '-1',
			'class': 'loading'
		}).setStyles({
			'width': 'auto',
			'margin-left': '-10px',
			'top': this.setTopPosition()
		});
		
		
		
		this.wrapper.adopt(overlay);
		this.wrapper.adopt(dialog);			
		// ocultamos selects y objects en IE6
		if(Browser.Engine.trident4) $$('object', 'embed', 'select').fade('hide');		
		$$('body')[0].adopt(this.wrapper);
		return this.wrapper;			
	},
	setTopPosition: function(){
		var pxToTop = window.getScroll().y;
		var visibleArea = window.getSize().y;
		return (pxToTop + (visibleArea / 2)) - 250;				
	},
	injectIntoModal: function(link, tipo, remoteHTML){		
		var content;				
		if(tipo == 'html'){
			content = remoteHTML.get('html');			
		}
		if(tipo == 'image'){
			content = new Element('img',{
				'src': remoteHTML
			});						
		}

		var d = $('dialog');
		if(tipo == 'html'){
			d.set('html', content);			
		}
		if(tipo == 'image'){
			d.grab(content);
			
		}
		var closeButton = new Element('a',{
			'href': '#',
			'class': 'dialog-close',
			'role': 'button',
			'aria-controls': 'dialog',
			'text': this.options.closeLabel
		});
		d.grab(closeButton, 'top');	
				
		d.setStyle('margin-left', '-' + d.getSize().x / 2 + 'px');
		var dialogTitle = d.getElement('h1') ? d.getElement('h1') : d.getElement('h2');
		if(dialogTitle) dialogTitle.set('id','dialog-title');
		d.set('aria-labelledby', 'dialog-title').removeClass('loading');						
		this.manageFocus(d, link);
		document.addEvent('keydown', function(ev){
			if(ev.key == 'esc') this.close(ev, link);			
		}.bind(this));

		closeButton.addEvents({
			'click': function(ev){
				ev.stop();
				this.close(ev,link);				
			}.bind(this)
		})
		
	},
	// esto no funciona muy bien en Safari
	manageFocus: function(dialog, link){
		// llevar el foco al primer elemento focalizable de forma natural
		// atrapar el foco en la modal mientras no se cierre mediante link cerrar o tecla esc
		var focusable = 'a, input, select, textarea, button, [tabindex]';		
		dialog.getElement(focusable).focus();		
		document.addEvent('focus', function(ev){ 			
			if(dialog){								
				dialog.getElement(focusable).focus();								
			}			
		});
	},
	open: function(){				
		var _this = this;
		this.links.each(function(el){			
			el.addEvent('click', function(ev){
				ev.stop();													
				_this.showOverlay();		
				new Request.HTML({
					url: el.get('href'),
					onSuccess: function(responseTree, responseElements){										
						var remoteHTML = responseElements.filter( _this.options.loadedDiv );
						(function(){							
							_this.injectIntoModal(el, 'html', remoteHTML);							
						}).delay(1000)
					}
				}).get();					
			})
		});
		return this.request;
	},
	close: function(ev, link){	
		this.wrapper.fade('out');
		var removeWrapper = function(){
			this.wrapper.dispose();		
			if(Browser.Engine.trident4) $$('object', 'embed', 'select').fade('show');					
		}
		removeWrapper.delay(200, this);									
		link.focus();			
	}
});
	

