
/* Mirabilia JavaScript */

var bodyClass, rootPath, visitaVirtual, _gaq;

window.addEvent('domready',	function(){
	bodyClass = $(document.body).getProperty('class');
	rootPath = ({
		inicio: '',
		historia: '../',
		'indice-monumentos': '../',
		monumento: '../../',
		itinerario: '../',
		glosario: '../',
		'informacion-interes': '../'
	})[bodyClass];
	if (bodyClass == 'inicio') addGoogleCode();
	new Menu();
	new Pagina();
	new Pie();
	$(document.body).setStyle('visibility', 'visible');
});


/* Google Code */

var addGoogleCode = function(){
	window.___gcfg = {lang: 'es'};
	_gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-19013951-1']);
	_gaq.push(['_trackPageview']);
	$$('script[src="https://apis.google.com/js/plusone.js"]')[0].async = true;
	$$('script[src="http://www.google-analytics.com/ga.js"]')[0].async = true;
};


/* Menú */

var Menu = new Class({

	initialize: function(){
		var ulMenu = new Element('ul').adopt(
			this.addItem('menu-inicio', 'Inicio', 'index.html'),
			this.addItem('menu-historia', 'Historia de Oviedo', 'historia_de_oviedo/etapa_romana.html'),
			this.addItem('menu-monumentos', 'Monumentos', 'monumentos/antecedentes_urbanos.html'),
			this.addItem('menu-itinerarios', 'Itinerarios', 'itinerarios/indice.html'),
			this.addItem('menu-glosario', 'Glosario', 'glosario/glosario_a.html'),
			this.addItem('menu-informacion-interes', 'Información de interés', 'informacion_de_interes/bibliografia.html'),
			new Element ('li', {html:
				'<form id="cse-search-box" action="http://www.google.com/cse"> \
					<input name="cx" value="006075879255089284707:igqj2-ij0ge" type="hidden"> \
					<input name="ie" value="UTF-8" type="hidden"> \
					<input id="menu-buscar-campo" type="text" name="q"> \
					<input name="siteurl" value="www.mirabiliaovetensia.com" type="hidden"> \
				</form>'
			})
		);
		$('menu').grab(ulMenu);
	},

	addItem: function(id, html, href){
		var liItem = new Element('li', {id: id});
		var aItem = new Element('a', {href: rootPath + href, html: html});
		return liItem.grab(aItem);
	}

});


/* Pagina */

var Pagina = new Class({

	initialize: function(){
		var divPage = new Element('div#pagina');
		switch (bodyClass) {
		case 'inicio':
			$$('.seccion').each(function(divSeccion, i){new Seccion(divSeccion, i);});
			$$('.g-plusone').each(function(divGPlusOne){new GooglePlusOne(divGPlusOne);});
		case 'glosario':
			$$('.termino').each(function(divTermino, i){new Termino(divTermino, i);});
		case 'monumento':	
			if ($('galeria')) new Galeria();
			if ($('visita-virtual')) visitaVirtual = new VisitaVirtual();
			if ($('vista-google-earth')) new VistaGoogleEarth();
		default:
			$$('.ilustracion').each(function(divIlustracion){new Ilustracion(divIlustracion);});
		}
		divPage.wraps($('contenido'));
		if ($('indice')) divPage.grab($('indice'), 'top');
		divPage.grab(new Element('div#borde-superior'), 'top');
		divPage.grab(new Element('div#borde-inferior'));
	}

});


/* Pie */

var Pie = new Class({

	initialize: function(){
		var ulFooter = new Element('ul').adopt(
			this.addItem('Créditos', 'informacion_de_interes/acerca_de_mirabilia_ovetensia.html', true),
			this.addItem('Contacto', 'informacion_de_interes/acerca_de_mirabilia_ovetensia.html#contacto', true),
			this.addItem('Licencia', 'informacion_de_interes/acerca_de_mirabilia_ovetensia.html#licencia')
		);
		$('pie').grab(ulFooter);
	},

	addItem: function(html, href, bar){
		var liItem = new Element('li');
		var aItem = new Element('a', {href: rootPath + href, html: html});
		liItem.grab(aItem);
		if (bar) liItem.appendText(' |');
		return liItem;
	}

});


/* Sección */

var Seccion = new Class({

	initialize: function(divSeccion, i){
		if (i > 0) divSeccion.grab(new Element((i == 1) ? 'div#portada-separador' : 'div.separador'), 'before');
	}

});


/* Termino */

var Termino = new Class({

	initialize: function(divTermino, i){
		var divLeft = new Element('div.ilustraciones');
		var divRight = new Element('div.descripcion');
		divLeft.adopt(divTermino.getChildren('.ilustracion'));
		divRight.adopt(divTermino.getChildren('p, ul'));
		divTermino.adopt(divLeft, divRight);
		if (i > 0) divTermino.grab(new Element('div.separador'), 'before');
	}

});


/* Galeria */

var Galeria = new Class({

	initialize: function(){
		var divInfografias = $('infografias');
		this.imageSet = new ImageSet(divInfografias);
		this.caption = new Caption(divInfografias, this.imageSet.titles[0], 'play');
		this.thumbnailSet = new ThumbnailSet($('planta'));
		this.caption.divButton.addEvent('click', this.control.bind(this));
		this.thumbnailSet.thumbnails.each(function(thumbnail, i){
			thumbnail.liButton.addEvent('click', this.change.bind(this, i));
		}, this);
		this.index = 0;
		this.playTimer = null;
	},

	show: function(toIndex){
		this.imageSet.change(this.index, toIndex);
		this.thumbnailSet.change(this.index, toIndex);
		if (this.imageSet.titles[toIndex])
			this.caption.change(this.imageSet.titles[toIndex]);
		this.index = toIndex;
	},

	next: function(){
		toIndex = this.index + 1;
		if (toIndex == this.imageSet.imgs.length) toIndex = 0;
		this.show(toIndex);
	},

	start: function(){
		this.caption.setButton('pause');
		this.playTimer = this.next.periodical(5000, this);
		this.next();
	},

	stop: function(){
		this.caption.setButton('play');
		clearInterval(this.playTimer); 
		this.playTimer = null;
	},

	change: function(toIndex){
		if (this.playTimer) this.stop();
		if (toIndex != this.index) this.show(toIndex);
	},

	control: function(){
		if (!this.playTimer) this.start(); else this.stop();
	}

});


/* Visita Virtual */

var VisitaVirtual = new Class({

	initialize: function(){
		var divPanorama = $('panorama');
		this.divVisitaVirtual = $('visita-virtual');
		this.panorama = new Panorama();
		this.tooltip = new Tooltip(divPanorama, 20);
		this.thumbnailSet = new ThumbnailSet($('planta'));
		this.caption = new Caption(divPanorama, this.thumbnailSet.thumbnails[0].title, 'play');
		this.divVisitaVirtual.addEvent('mousemove', function(event){this.tooltipMove(event);}.bind(this));
		this.caption.divButton.addEvent('click', this.control.bind(this));
		this.thumbnailSet.thumbnails.each(function(thumbnail, i){
			thumbnail.liButton.addEvent('click', this.openNext.bind(this, i));
		}, this);
		this.index = 0;
		this.rotation = false;
	},

	change: function(toIndex){
		this.thumbnailSet.change(this.index, toIndex);
		this.caption.change(this.thumbnailSet.thumbnails[toIndex].title);
		this.index = toIndex;
	},

	openNext: function(toIndex){
		if (toIndex != this.index){
			this.panorama.change(this.thumbnailSet.thumbnails[toIndex].href);
			this.change(toIndex);
		}
	},

	control: function(){
		if (this.rotation){
			this.panorama.stop();
			this.caption.setButton('play');
			this.rotation = false;
		}
		else {
			this.panorama.rotate();		
			this.caption.setButton('pause');
			this.rotation = true;
		}
	},

	tooltipMove: function(event){
		this.tooltipX = event.page.x;
		this.tooltipY = event.page.y;
		if (this.over) this.tooltip.move(this.tooltipX, this.tooltipY);
	},

	hotspotOver: function(hu){
		var index = this.thumbnailSet.hrefs().indexOf(hu);
		this.tooltip.show(this.thumbnailSet.thumbnails[index].alt, this.tooltipX, this.tooltipY);
		this.over = true;
	},

	hotspotOut: function(hu){
		this.tooltip.fadeOut();
		this.over = false;
	},

	hotspotClick: function(hu){
		var toIndex = this.thumbnailSet.hrefs().indexOf(hu);
		if (toIndex !=this.index) this.openNext(toIndex);
	}

});


/* Vista Google Earth */

var VistaGoogleEarth = new Class({

	initialize: function(){
		var urlKMZ = null;
		var divGoogleEarth = $('google-earth');
		var aKMZ = $('modelo3D');
		if (aKMZ != null) urlKMZ = aKMZ.dispose().getProperty('href');
		this.thumbnailSet = new ThumbnailSet($('planta'));
		this.googleEarth = new GoogleEarth(divGoogleEarth, urlKMZ, this.thumbnailSet.thumbnails[0].href);
		this.thumbnailSet.thumbnails.each(function(thumbnail, i){
			thumbnail.liButton.addEvent('click', this.change.bind(this, i));
		}, this);
		this.index = 0;
	},

	change: function(toIndex){
		this.googleEarth.change(this.thumbnailSet.thumbnails[toIndex].href);
		this.thumbnailSet.change(this.index, toIndex);
		this.index = toIndex;
	}

});


/* Ilustracion */

var Ilustracion = new Class({

	initialize: function(elemIlustracion){
		var divIlustracion;
		if (elemIlustracion.match('div'))
			divIlustracion = elemIlustracion;
		else {
			divIlustracion = new Element('div.ilustracion').wraps(elemIlustracion);
			elemIlustracion.removeClass('ilustracion');
		}
		if (divIlustracion.getStyle('background-image') == "none") divIlustracion.addClass('sin-sombra');
		if (divIlustracion.hasClass('info'))
			this.type = 'info';
		else if (divIlustracion.hasClass('anim'))
			this.type = 'anim';
		else if (divIlustracion.hasClass('alternante'))
			this.type = 'alternant';
		else
			this.type = 'default';
		this.imageSet = new ImageSet(divIlustracion);
		if (this.imageSet.alts[0]){
			if (this.type != 'alternant' && this.imageSet.imgs.length > 1){
				var buttonType = ({'default': 'next', anim: 'play', info: 'info'})[this.type];
				this.caption = new Caption(divIlustracion, this.imageSet.alts[0], buttonType);
				this.caption.divButton.addEvent('click', this.control.bind(this));
			} else 
				this.caption = new Caption(divIlustracion, this.imageSet.alts[0], null);
		}
		if (divIlustracion.getElement('map')){
			var areas = divIlustracion.getElement('map').getChildren('area');
			if (areas[0].getProperty('title')){
				this.tooltip = new Tooltip(divIlustracion, 10);
				areas.each(function(area){
					area.addEvents({
						mouseover: this.tooltipShow.bind(this, area.getProperty('title')),
						mousemove: this.tooltipMove.bind(this),
						mouseout: this.tooltip.fadeOut.bind(this.tooltip)
					});
					area.setProperty('title', "");
				}, this);
			}
			areas.each(function(area){
				var imgIndex = this.imageSet.srcs.indexOf(area.getProperty('href'), 2);
				if (imgIndex != -1)
					area.addEvent('click', this.select.bind(this, imgIndex));
			}, this);
		}
		var divWrap = new Element('div',{
			styles: {
				position: 'absolute',
				width: divIlustracion.getStyle('width'),
				height: divIlustracion.getStyle('height')
			}
		});
		divWrap.adopt(this.imageSet.imgs);
		if (this.caption) divWrap.grab(this.caption.divCaption);
		divIlustracion.grab(divWrap);
		this.index = 0;
		if (this.type == 'alternant') this.alternate();
	},

	change: function(toIndex, transition){
		switch (transition) {
			case 'default':
				this.imageSet.change(this.index, toIndex);
				break;
			case 'overlayIn':
				this.imageSet.overlayIn(toIndex);
				break;
			case 'overlayOut':
				this.imageSet.overlayOut(toIndex);
				break;
		}
		if (this.imageSet.alts[this.index] != this.imageSet.alts[toIndex])
			this.caption.change(this.imageSet.alts[toIndex]);
		this.index = toIndex;
	},

	next: function(){
		var toIndex = (this.index == this.imageSet.imgs.length - 1) ? 0 : this.index + 1;
		this.change(toIndex, 'default')
	},

	alternate: function(){
		this.imageSet.imgs[1].set('tween', {duration: 2000});
		this.imageSet.alternate();
		this.imageSet.alternate.periodical(5000, this.imageSet)
	},

	select: function(index, event){
		this.infoSelect = true;
		event.preventDefault();
		this.change(index, 'default');
		this.caption.setButton('back');
		if (this.tooltip) this.tooltip.fadeOut();
	},

	control: function(){
		switch (this.type) {
			case 'default':
				this.next();
				break;
			case 'anim':
				if (this.playTimer) {
					clearInterval(this.playTimer);
					this.caption.setButton('play');
					this.playTimer= null;
				} else {
					this.playTimer = this.next.periodical(5000, this);
					this.next();
					this.caption.setButton('pause');
				}
				break;
			case 'info':
				var imageSetLength = this.imageSet.imgs.length;
				if (!this.infoSelect){
					if (this.index == imageSetLength - 2)
						this.caption.setButton('info_off');
					else if (this.index == imageSetLength - 1)
						this.caption.setButton('info');
					else
						this.caption.setButton('next');	
					if (this.index == 0)
						this.change(1, 'overlayIn');
					else if (this.index == 1 && imageSetLength == 2)
						this.change(0, 'overlayOut');
					else
						this.next();
				} else {
					this.change(1, 'default');
					this.caption.setButton('next');
					this.infoSelect = false;
				}
				break;
		}
	},
	
	tooltipShow: function(tooltipText, event){
		this.tooltip.show(tooltipText, event.page.x, event.page.y);
	},

	tooltipMove: function(event){
		this.tooltip.move(event.page.x, event.page.y);
	}

});


/* Image Set */

var ImageSet = new Class({
					
	initialize: function(divParent){
   		this.imgs = divParent.getChildren('img').setStyle('opacity', 0);
		this.imgs[0].setStyles({visibility: 'visible', opacity: 1});
   		this.alts = this.imgs.map(function(item){return item.getProperty('alt')});
   		this.srcs = this.imgs.map(function(item){return item.getProperty('src')});
   	},

    change: function(fromIndex, toIndex){
	    this.imgs[fromIndex].fade('out');
	    this.imgs[toIndex].fade('in');
    },

    overlayIn: function(index){
    	this.imgs[index].get('tween').start('opacity', 1).chain(
    		function(){this.imgs[index - 1].setStyle('opacity', 0);}.bind(this)
    	)
    },

    overlayOut: function(index){
    	this.imgs[index].setStyle('opacity', 1);
    	this.imgs[index + 1].tween('opacity', 0);
    },

    alternate: function(){
    	this.imgs[1].fade('toggle');
    }

});


/* Panorama */

var Panorama = new Class({

	initialize: function(){
		this.objPanorama = $('pano_object');
	},

	change: function(toSwfName){
		this.objPanorama.openNext('panoramas/' + toSwfName);
	},

	rotate: function(){
		this.objPanorama.setAutorotate(0.2, 1, 0.5);
	},

	stop: function(){
		this.objPanorama.setAutorotate(0, 0, 0);
	}

});


/* Google Earth */

var GoogleEarth = new Class({

	initialize: function(divGoogleEarth, urlKMZ, lookAtSettings){		
       	google.earth.createInstance(
       		divGoogleEarth,
       		function initCallback(pluginInstance){
	        	this.pluginInstance = pluginInstance;
	        	pluginInstance.getWindow().setVisibility(true);
	        	pluginInstance.getNavigationControl().setVisibility(pluginInstance.VISIBILITY_AUTO);
	        	pluginInstance.getLayerRoot().enableLayerById(pluginInstance.LAYER_TERRAIN, true);
	        	this.lookAt = pluginInstance.createLookAt('');
	        	this.change(lookAtSettings);
	        	if (urlKMZ != null){ // !=null
					google.earth.fetchKml(
					  	pluginInstance,
					  	urlKMZ,
					  	function(object){pluginInstance.getFeatures().appendChild(object);}
					);
	        	}
	        	else
	        		pluginInstance.getLayerRoot().enableLayerById(pluginInstance.LAYER_BUILDINGS, true);
	        }.bind(this),
       		function failureCallback(errorCode){}
       	);
	},
	
	change: function(lookAtSettings){
		eval("var lookAtSettings = " + lookAtSettings);
		this.lookAt.set(
	   		lookAtSettings['long'],
	   		lookAtSettings['lat'],
	   		lookAtSettings['alt'],
	   		this.pluginInstance.ALTITUDE_RELATIVE_TO_GROUND,
	   		lookAtSettings['heading'],
	   		lookAtSettings['tilt'],
	   		lookAtSettings['range']
		);
		this.pluginInstance.getView().setAbstractView(this.lookAt);
	}

});


/* Caption */

var Caption = new Class({
					
	initialize: function(divParent, text, buttonShape){
		this.bgPosition = [0, 0];
		this.divCaption = new Element('div.caption', {tween: {property: 'height'}});
		var divBack = new Element('div.caption-background', {styles: {opacity: 0.5}});
  		this.divText = new Element('div.caption-text', {html: text});
   		if (buttonShape) {
  			this.imgButton = new Element('img', {src: rootPath + 'css/elementos/botones_control.png'});
  			this.divButton = new Element('div.caption-button', {
	  			events: {
					mouseover: this.highlightButton.bind(this, 'on'),
					mouseout: this.highlightButton.bind(this, 'off')
				}
  			}).grab(this.imgButton);
  			this.setButton(buttonShape);  			
  		}
		divParent.grab(this.divCaption.adopt(divBack, this.divButton, this.divText));
		this.vMargin = this.divCaption.getSize().y - this.divText.getSize().y;
		this.divText.setStyle('width', divParent.getStyle('width').toInt() - 53);
	},
		
	change: function(toText){
		var tween = this.divCaption.get('tween');
		tween.start(0).chain(function(){
			this.divText.setProperty('html', toText);
			tween.start(this.divText.getSize().y + this.vMargin);
		}.bind(this));
	},
		
	setButton: function(type){
		var marginLeft = ({next: 0, play: 1, pause: 2, info: 3, info_off: 4, back: 5})[type];
		var altText = ({
			next: "Pasar a las iguiente imagen",
			play: "Iniciar la reproducción automática",
			pause: "Detener la reproducción automática",
			info: "Mostrar información adicional",
			info_off: "Ocultar la información adicional",
			back: "Volver a mostrar la imagen anterior"
		})[type];
		this.imgButton.setStyle('margin-left', (marginLeft * -25) + 'px');
		this.imgButton.setProperties({alt: altText, title: ""});
	},
	
	highlightButton: function(mode){
		this.imgButton.setStyle('margin-top', ({on: -25, off: 0})[mode] + 'px');
	}

});


/* Thumbnail Set */

var ThumbnailSet = new Class({
	
	initialize: function(divPlanta){
		divPlanta.addEvents({
			mouseenter: this.setAutoScroll.bind(this, false),
			mouseleave: this.setAutoScroll.bind(this, true)
		});
		
		this.divLeft = new Element('div.thumbnails-next', {
			events: {click: this.scroll.bind(this, -1)}
		});
		this.divRight = new Element('div.thumbnails-prev', {
			events: {click: this.scroll.bind(this, 1)}
		});
		var divThumbnails = new Element('div.thumbnails');
		this.ulButtons = new Element('ul');
		this.thumbnails = new Array();
		this.tooltip = new Tooltip(divPlanta);
		var imgMaps = divPlanta.getChildren('img[usemap]').dispose();		
		imgMaps.each(function(imgMap){
			var areas = $(imgMap.getProperty('usemap').substr(1)).getChildren('area');
			areas.each(function(area){
				var thumbnail = new Thumbnail(imgMap, area, this)
				this.thumbnails.push(thumbnail);
				this.ulButtons.grab(thumbnail.liButton);
			}, this);	
		}, this);
		divPlanta.getChildren('map').dispose();
		this.at = 0;
		this.autoScroll = true;
		this.change(0, 0);
		this.scroll(0);
		divPlanta.adopt(divThumbnails.grab(this.ulButtons), this.divLeft, this.divRight);
	},

	hrefs: function(){
		return this.thumbnails.map(
			function(thumbnail){
				return thumbnail.href;
			}
		);
	},

	change: function(fromIndex, toIndex){
		if (this.autoScroll) {
			if (toIndex < this.at) this.scroll(toIndex - this.at);
			if (toIndex > this.at + 2) this.scroll(toIndex - this.at - 2);
		}
		this.thumbnails[fromIndex].divArea.setStyles({
			opacity: 0.25,
			'background-color': 'gray',
			border: 'solid 1px black'
		});
		this.thumbnails[toIndex].divArea.setStyles({
			opacity: 0.4,
			'background-color': 'yellow',
			border: 'solid 2px gold'
		});
	},

	setAutoScroll: function(enable){
		this.autoScroll = enable;
	},

	scroll: function(dir){
		this.at = this.at + dir;
		this.divLeft.setStyle('visibility', (this.at == 0) ? 'hidden' : 'visible'); 
		this.divRight.setStyle('visibility', (this.at == this.thumbnails.length - 3) ? 'hidden' : 'visible');
		this.ulButtons.tween('margin-left', -118 * this.at);
	}

});


/* Thumbnail */

var Thumbnail = new Class({

	initialize: function(imgMap, area, thumbnailSet){
		this.liButton = new Element('li', {
			styles: {'background-image': "url('" + imgMap.get('src') + "')" },
			events: {
				mouseenter: this.enter.bind(this, thumbnailSet),
				mouseleave: this.leave.bind(this, thumbnailSet)
			}
		});
		var coords = area.getProperty('coords').split(',');
		this.divArea = new Element('div.thumbnail-area', {
			styles: {
				top: coords[0].toInt(),
				left: coords[1].toInt(),
				width: coords[2].toInt(),
				height: coords[3].toInt(),
				opacity: 0.25
			}
		});
		this.liButton.grab(this.divArea);
		this.title = area.getProperty('title');
		this.alt = area.getProperty('alt');
		this.href = area.getProperty('href');
	},

	enter: function(thumbnailSet){
		thumbnailSet.tooltip.show(this.alt, this.liButton.getPosition().x + 58, this.liButton.getPosition().y);
	},

	leave: function(thumbnailSet){
		thumbnailSet.tooltip.fadeOut();
	}

});


/* Google +1 */

var GooglePlusOne = new Class({

	initialize: function(divGPlusOne){
		divGPlusOne.setProperties({'data-size': 'medium'});
		new Element ('div.google-plus-one').wraps(divGPlusOne);
	}

});


/* Tooltip */

var Tooltip = new Class({

	initialize: function(divParent, extraOffset){
		this.divParent = divParent;
		this.extraOffset = 28 + (extraOffset || 0);
		this.divTooltip = new Element('div.tooltip', {tween: {property: 'opacity', link: 'cancel'}});
		var divLeft = new Element('div.tooltip-left');
		this.divText = new Element('div.tooltip-text');
		var divRight = new Element('div.tooltip-right');
		this.divPeak = new Element('div.tooltip-peak');
		this.divTooltip.adopt(divLeft, this.divText, divRight, this.divPeak);
		this.divTooltip.inject(divParent);
		this.xOffset = 0;
		this.yOffset = 0;
	},

	show: function(newText, x, y){
		this.divText.setProperty('text', newText);
		var xSize2 = Math.floor((this.divText.getSize().x + 22) / 2);
		this.xOffset = this.divParent.getPosition().x + xSize2;
		this.yOffset = this.divParent.getPosition().y + this.extraOffset;
		this.move(x, y);
		this.divTooltip.tween(1, 1);
		this.on = true;
	},

	move: function(x, y){
		this.divTooltip.setPosition({x: x - this.xOffset, y: y - this.yOffset});
	},

	fadeOut: function(){
		if (!Browser.ie) this.divTooltip.tween(0); else this.divTooltip.tween(0.5, 0);
		this.on = false;
	}

});
