/******************************************************************************
 OBJETO ERV - ERVObject.js
 Fecha de creacion: Viernes, 2 de junio de 2006
 ÚLTIMA MODIFICACIÓN: 18 de octubre de 2007
 
 NOTA LEGAL: 
 (c) 2007 ÉNOE, REALIDAD VIRTUAL - www.enoe.es - Todos los derechos reservados

 Queda estrictamente prohibido modificar los nombres y copyrights
 que acompañan el código fuente de este Software. Queda igualmente prohibido 
 (sin que esta enumeración sea limitativa) copiar, modificar, ampliar, crear una obra 
 derivada utilizando total o parcialmente el código fuente del Software, modificar,
 incluir nuevos archivos en el directorio 'elementos' del Software, 
 intentar encontrar el código fuente, vender, atribuir, sublicenciar 
 o transferir de la forma que sea todo derecho referente al Software, excepto 
 si se obra con arreglo al Artículo 8 de la Licencia de usuario final, y si 
 corresponde, debido a que contiene secretos comerciales de Énoe, Realidad Virtual,
 como, por ejemplo, la estructura, la organización y el código del Software.
 ******************************************************************************/
if (!ERV) { var ERV = new Object(); };

ERV.hasRequired 	= function(s) { 
	if (document.getElementById && document.getElementsByTagName) {
		var html = document.getElementsByTagName('html')[0];
		html.className += ((html.className == '' ) ? '' : ' ') + 'has-dom';
		return true;
		};
	return false;
	}();

ERV.onbeforeload	= function() {	if (this.hasRequired) { for (var module in this) { if (this[module].onbeforeload) 	{ this[module].onbeforeload(); };};};};

/******************************************************************************
 Modulo ERV.hasFlash
 Detector del plug-in Macromedia/Adobe Flash y su version 
 (se requiere la 8 + AS 2 para ERV y la 7 o la 8 para otros)

 ******************************************************************************/
ERV.hasFlash = {
	detectFlash : function() {
		var flashVersion = 0;
		var required = ERV.Nav.versionFlash; //El editor ahora puede introducir un valor (7 u 8)
		var m = 16; // maxima version por la que testar
		var ua = navigator.userAgent.toLowerCase();
		if (navigator.plugins && navigator.plugins.length) {
			var p = navigator.plugins['Shockwave Flash'];
			if (typeof p == 'object') {
				for (var i = m; i >= 3; i--) {
					if (p.description && p.description.indexOf(i + '.') != -1) { flashVersion = i; break; };
					};
				};
			}
		else if (window.ActiveXObject && window.print) {
			var found = false;
			for (var i = m; i >= 3 && !found; i--) {
				try {
					found = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + i + "');");
					if(found) { flashVersion = i; };
					}
				catch(e) {};
				};
			};
		if (required <= flashVersion) {
			var html = document.getElementsByTagName('html')[0];
			html.className += ((html.className == '') ? '' : ' ') + 'has-flash';
			return true;
			};
		return false;
		}
	};
	
ERV.openNewWindow 	= function(resource, w, h, sc, n){
	window.open(resource, n,'width=' + w + ',height=' + h + ',scrollbars=' + sc + ', location=no, resizable=yes, menubar=no, statusbar=no');
	};
	
	
/******************************************************************************
 Modulo ERV.Fichas
 
 Permite utilizar un sistema de visualizacion del contenido basado en fichas
 
 ******************************************************************************/
ERV.Fichas = {
	className 		: 'tabs',
	container		: 'div',
	onbeforeload		: function() {
		var elems	= document.getElementsByTagName(this.container);
		for (var i = 0; i < elems.length; i++) {
			var e = elems[i];
			if (e.className == this.className) {
				var tabs = e.getElementsByTagName('a');
								
				for (var j = 0; j < tabs.length; j++) {
					var lnk		= tabs[j];
					lnk.tabs	= tabs;
					lnk.tab		= document.getElementById(lnk.href.replace(/^([^#]*#)/,''));
					// Oculta los vinculos
					if (lnk.className != 'active') { lnk.tab.style.display = 'none'; };
					
					lnk.onclick = function() {
						// Desactiva todos los vinculos
						for (var i = 0; i < this.tabs.length; i++) {
							var lnk = this.tabs[i];
							lnk.className = '';
							lnk.parentNode.className = '';
							lnk.tab.style.display = 'none';
							};
						this.className = 'active';
						this.parentNode.className = 'active';
						this.tab.style.display = 'block';
						this.blur();
						ERV.Clear.init();
						return false;
						};
					};
				};
			};
		}
	};


/******************************************************************************
 Modulo ERV.Tipografia
 Aumenta/Disminuye la tipografia de la interfaz de cursos
 v. 1.1 : Se ha simplificado el codigo.
 ******************************************************************************/
ERV.Tipografia = {
	onbeforeload	: function() {
		var e 	= document.getElementById('texto-seccion');
		var g 	= document.getElementById('mas');
		var p 	= document.getElementById('menos');
		var tipografia = 12;
		
		g.onclick = function() {
			tipografia++;
			e.style.fontSize = tipografia + "px";
			e.style.lineHeight = (tipografia + 5) + "pt";
			};
		p.onclick = function() {
			tipografia--;
			e.style.fontSize = tipografia + "px";
			e.style.lineHeight = (tipografia + 5) + "px";
			};
		}
	};
	

/******************************************************************************
 Modulo ERV.InnerWindow
 
 Crea, destruye e inserta contenido en una falsa ventana draggable y resizable
 dentro del navegador
 ******************************************************************************/
ERV.InnerWindow = {
	create				: function(w, h) {
		//ERV.SmoothScroll.start();
		var fadeIn 		= new Fx.Styles($('resize'));
		var slideIn 	= new Fx.Styles($('resize'));
			slideIn.start(
			{
				'top' 			: (ERV.Screen.getPageScroll()[1] + (ERV.Screen.getPageSize()[3] / 2) + (h / 2) - h),
				'left'			: [-1000, (ERV.Screen.getPageSize()[2] / 2) + (w / 2) - w],
				'width' 		: w,
				'height' 		: h,
				'opacity'		: [0, 1]
				});
		$('resize').makeDraggable({ handle: $('dragger'), 
			onStart: function(){
				fadeIn.start( {'opacity': 0.8} );
     			}.bind(this),
			onComplete: function(){
				fadeIn.start( {'opacity': 1.0} );
				fadeIn.custom(.5,1);
     			}.bind(this) 
				});
		
		$('resize').makeResizable({ handle: $('resize-handler') });
		
		//Ocultamos los flash en seccion para que no entorpezcan la vision de la nueva ventana interna
		if($('flash')) $('flash').style.visibility = "hidden";
		
		$('btn-close-resize').addEvent('click', function() {
			ERV.InnerWindow.destroy();
			});
		},
		
	destroy			: function() {		
		ERV.Interactions.tooltip = "";
		$('scroll').innerHTML = '';
		
		if($('flash')) $('flash').style.visibility = "visible";
		
		if($('resize').style.marginLeft != '550px') {
			var slideIn 	= new Fx.Styles($('resize'));
			slideIn.start({
				'left': [(ERV.Screen.getPageSize()[2] / 2) + (w / 2) - w, -1000],
				'opacity': [1, 0]
			});
		}
		//this.open = false;
		},
	insert 			: function(recurso, windowTitle, mediaType, w, h) {
		$('scroll').innerHTML = '';
		var contenido = "";
		var iniTable = '<table width="100%" height="100%"><tr><td style="vertical-align: middle; text-align: center; padding-top: 20px;"><div class="flash" style="width:auto; position: relative;">';
		var endTable = '</div></td></tr></table>';
		w = w * 100;
		h = h * 100;
		
		if(mediaType == "video" || mediaType == "audio") {
			w = 500;
			var fv  = "file=" + recurso;
			if(mediaType == "audio") fv += "&amp;image=../../elementos/img/comun/preview-audio.jpg&amp;showeq=true";
			if(mediaType == "video") fv += "&amp;image=../../elementos/img/comun/preview-video.jpg";
			fv += "&amp;overstretch=none&amp;showfsbutton=false&amp;title=" + titulo + " ";
			if(curso.cliente) fv += "&amp;lightcolor=0x" + ERV.Nav.color01 + "&amp;frontcolor=0x" + ERV.Nav.color02;
			if(mediaType == "audio") fv += "&amp;displayheight=100&amp;shuffle=false";
			if(mediaType == "video") fv += "&amp;width=500";
			contenido += iniTable + ERV.insertFlash(rutaSwf + reproductor8, fv, w, h, 'reproductor') + endTable;		
		} else if(mediaType == 'flash') {
			contenido += iniTable + ERV.insertFlash(recurso, null, w, h, 'animacion') + endTable;
		} else if(mediaType == 'text') {
			contenido = recurso;
		} else {
			contenido += iniTable + ERV.insertFlash(mediaType, ('datos=' + recurso), w, h, 'muras') + endTable;
			};
		
		ERV.InnerWindow.create((w + 120), (h + 40));

		$('dragger').innerHTML 		 = '<p>' + windowTitle + '</p>';
		$('scroll').innerHTML 		 = contenido;
		$('scroll').style.visibility = 'visible';
		$('resize').style.visibility = 'visible';
		}
	};
	
/******************************************************************************
 Modulo ERV.SmoothScroll

 ******************************************************************************/
ERV.SmoothScroll = {
	button		: null,
	x			: null,
	y			: null,
	timer		: null,
	interval	: 25,
	start		: function() {
		this.timer = window.setTimeout("ERV.SmoothScroll.animate()",500);
		},
	onbeforeload	: function() {
		var self = this;
		if(document.getElementById("backtotop2")) {
			this.button02 = document.getElementById("backtotop2").getElementsByTagName("a")[0];

			this.button02.onclick = function() {
				clearTimeout(self.timer);
				this.blur();
				self.animate();
				return false;
				};
			};
		},
	animate		: function() {
		var x1 = x2 = x3 = 0;
		var y1 = y2 = y3 = 0;

		if (document.documentElement) {
			x1 = document.documentElement.scrollLeft || 0;
			y1 = document.documentElement.scrollTop || 0;
			};
		if (document.body) {
			x2 = document.body.scrollLeft || 0;
			y2 = document.body.scrollTop || 0;
			};

		x3 = window.scrollX || 0;
		y3 = window.scrollY || 0;

		var x = Math.max(x1, Math.max(x2, x3));
		var y = Math.max(y1, Math.max(y2, y3));

		window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));

		if (x > 0 || y > 0) {
			this.timer = window.setTimeout("ERV.SmoothScroll.animate()",this.interval);
		} else {
			clearTimeout(this.timer);
			};
		}
	};	

/******************************************************************************
 Modulo ERV.Clear

 ******************************************************************************/
ERV.Clear = {
	id01		: 'z-derecha',
	id02		: 'texto-seccion',
	onbeforeload: function() {
		this.init();
		},
	init		: function() {
		if($(this.id01)) {
			var h2 = $(this.id02).offsetHeight;
			var h1 = $(this.id01).offsetHeight;
			if(h2 < h1) {
				$(this.id02).setStyle('height', h1 + 'px'); 
				}
			}
		}	
	};
	
/******************************************************************************
 Modulo ERV.VentanasModales
 
 Abre una imagen, una secuencia de imagenes o texto HTML en un div interno
 sobre un overlay
 ******************************************************************************/
 ERV.VentanasModales = {
	type: 'image',
	onbeforeload: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,
			initialWidth: 250,
			initialHeight: 250,
			animateCaption: true,
			showCounter: true
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^vmodal/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		this.overlay 		  = new Element('div', {'id': 'overlay'}).injectInside(document.body);
		this.center 		  = new Element('div', {'id': 'center', 'class' : 'cab', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).injectInside(document.body);
		this.contents 		  = new Element('div', {'id': 'image', 'class': 'content-vmodal'}).injectInside(this.center);
		this.container 		  = new Element('div', {'id': 'container'}).injectInside(this.contents);
		this.closeBtn		  = new Element('a', {'id': 'bottomNavClose', 'href': '#','title': '' }).injectInside(this.center).onclick = this.overlay.onclick = this.close.bind(this);
		this.prevLink 		  = new Element('a', {'id': 'prevLink', 'href': '#', 'title': '', 'styles': {'display': 'none'}}).injectInside(this.center);
		this.nextLink 		  = new Element('a', {'id': 'nextLink', 'href': '#', 'title': '', 'styles': {'display': 'none'}}).injectInside(this.center);
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.bottomContainer = new Element('div', {'id': 'bottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
		this.bottom 		 = new Element('div', {'id': 'bottom'}).injectInside(this.bottomContainer);
		this.caption 		 = new Element('div', {'id': 'caption'}).injectInside(this.bottom);
		//this.number 		 = new Element('div', {'id': 'number'}).injectInside(this.bottom);
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.contents.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
			};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
		},
	params: new Object(),
	parseQuery : function(query) {
	   if (!query) return this.params; 
	   var Pairs = query.split(/[;&]/);
	   for ( var i = 0; i < Pairs.length; i++ ) {
		  var KeyVal = Pairs[i].split('=');
		  if ( ! KeyVal || KeyVal.length != 2 ) continue;
		  var key = unescape( KeyVal[0] );
		  var val = unescape( KeyVal[1] );
		  val = val.replace(/\+/g, ' ');
		  val = Number(val) * 100;
		  this.params[key] = val;
		  }   
	   	  return this.params;
		},	
	click: function(link) {
		if(link.rel.length == 6)  {
			this.type = 'image';
			return this.show(link.href, link.title);
			}
		else if (link.rel.indexOf('?') != -1) {
			this.params = this.parseQuery(link.rel.substr(7,999)); //Parametros para que la ventana tenga un ancho y alto concreto...
			this.type = 'other';
			return this.getType(link.href, link.title); //this.show(link.href, link.title);
			}
		else {
			this.type = 'image';
			var j, imageNum, images = [];
			this.anchors.each(function(el){
				if (el.rel == link.rel){
					for (j = 0; j < images.length; j++) if(images[j][0] == el.href) break;
					if (j == images.length){
						images.push([el.href, el.title]);
						if (el.href == link.href) imageNum = j;
						}
					}
				}, this);
			return this.open(images, imageNum);
			}
		},
	show: function(url, title){
		return this.open([[url, title]], 0);
		},
	open: function(images, imageNum){
		this.images = images;
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
		},
	getType : function(href, title) {
		//Si es un contenido incustrado
		if(href.indexOf("#") != -1) {
			this.innerDiv = href.substr(href.indexOf("#") + 1,1000);
			this.innerDiv = $(this.innerDiv).innerHTML;
		}
		return this.show(this.innerDiv, title);
		},
	position: function(){
		this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
		},
	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
		},
	keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
			case 37: case 80: this.previous(); break;	
			case 39: case 78: this.next();
			}
		},
	previous: function(){
		return this.changeImage(this.activeImage-1);
		},
	next: function(){
		return this.changeImage(this.activeImage+1);
		},
	changeImage: function(imageNum){
		this.contents.innerHTML = '';
		this.contents.style.backgroundImage = 'none';
		this.contents.style.overflow = 'hidden';

		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'loading';
		
		this.preload = new Image();
		this.preload.src = this.images[imageNum][0];
		
		if(this.type == 'image') this.preload.onload = this.nextEffect.bind(this);
		else this.nextEffect();
		return false;
		},
	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			if(this.type == 'image') {
				this.contents.style.backgroundImage = 'url(' + this.images[this.activeImage][0] + ')';
				this.contents.style.width = this.bottom.style.width = this.preload.width + 'px';
				this.contents.style.height = this.prevLink.style.height = this.nextLink.style.height = this.preload.height + 'px';
			}
			else  {
				this.contents.innerHTML = this.innerDiv;
				this.contents.style.width = this.bottom.style.width = this.params.w + 'px';
				this.contents.style.height = this.params.h + 'px';
				}
			
			this.caption.setHTML(this.images[this.activeImage][1] || '');
			//this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : '' + ' ' + (this.activeImage + 1) + ' ' + '' + ' ' + this.images.length);

			if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
			if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
			if (this.center.clientHeight != this.contents.offsetHeight){
				this.fx.resize.start({height: this.contents.offsetHeight + 40}); //El valor '40' compensa la altura de la cabecera 
				break;
				}
				this.step++;
		case 2:
			if (this.center.clientWidth != this.contents.offsetWidth){
				this.fx.resize.start({width: this.contents.offsetWidth, marginLeft: -this.contents.offsetWidth/2});
				break;
				}
				this.step++;
		case 3:
			this.bottomContainer.setStyles({top: this.top + this.center.clientHeight, height: 0, marginLeft: this.center.style.marginLeft, display: ''});
			this.fx.image.start(1);
			this.contents.style.overflow = 'auto';
			break;
		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);
				break;
				}
				this.bottomContainer.style.height = '';
		case 5:
			if (this.activeImage) this.prevLink.style.display = '';
			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';

			this.step = 0;
			}
		},
	close: function(){
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
			}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
		}
	};