document.documentElement.className += ' js';

(function($){
	window.addEvent('load', function(){
		document.documentElement.className += ' loaded';
		if(Shadowbox) Shadowbox.init();
		
		$$('p:empty').dispose();
		$$('input.input-date').addEvent('focus', function(){
			showCalendarControl(this);
		});
		
		$$('div#productos.despieces div.marca:nth-child(1)').addClass('first-child');
		
	});
	
	window.addEvent('domready', function(){
		// clases de compatibilidad para navegadores chungos
		$$('li:last-child').addClass('last-child');
		$$('li:first-child').addClass('first-child');
		$$('ul.anuncios li:nth-child(5n)').addClass('quinto');
		
		if($$('#productos div.marca').length) $$('#productos div.marca').getLast().addClass('last-child');		
		
		$$('#productos .caracteristicas a').each(function(el){
			el.addEvent('click', function(){
				var destino = this.get('href').split('#')[1];
				if($(destino)) {
					$(destino).highlight();								
					$(destino).getParent().getNext().highlight();					
				}
			})
		})
		
		
		// rollover para los links de idioma
		$$('#idioma a').each(function(el){
			el.addEvents({
				'mouseenter': function(){
					this.getParent('ul').getElement('strong').getParent('li').removeClass('activo');					
					this.getParent().addClass('activo');					
				},
				'mouseleave': function(){
					this.getParent('ul').getElement('strong').getParent('li').addClass('activo');					
					this.getParent().removeClass('activo');					
				}
			})
		});
		
		// rollover imgs home proudctos y home empresa
		$$('#contenido div.seccion a img').each(function(el){
			new TweenOpacity(el);			
		});
		
		
		// cuando el sidebar es mas alto que el contenido
		if($('sidebar') && $('contenido')){
			if($('sidebar').getHeight() > $('contenido').getHeight()) $('contenido').setStyles({
				'_height': $('sidebar').getHeight(),
				'min-height': $('sidebar').getHeight()
			})			
		}
		
		// inicio funciones		
		$$('#marcas li a').each(function(el){
			new FadeImgsFooter(el);			
		});
					
		$$('.galerias img, .videos img').each(function(el){
			new OverOpacity(el);			
		});
		
		$$('#navegacion-global li a').each(function(el){
			new MenuDesplegable(el);			
		});
		
		new Carrusel($('carrusel'));
				
		new CZ.Modal();	
		
		new Collapsible();
		
		$$('input.email').each(function(el){			
			new LabelOverInput(el);			
		});
		
		
		new MapaTiendas($('mapa-espana'), $$('#tiendas div.grupo'),{
			rutaImgs: document.location.protocol + '//' + document.location.host + '/wp/wp-content/themes/normark/images/' 
			//rutaImgs: 'http://kus.sites/normark/wp/wp-content/themes/normark/images/', 
			//rutaScripts: 'http://kus.sites/normark/wp/wp-content/themes/normark/js/'
		});		
		
		$$('div#productos.despieces ul.collapsible-content li a').each(function(el){
			new LoadAjax(el,{
				loaderDivID: 'desglose', // div donde se carga la respuesta
				selectorTitleLoadedContent: 'h5.h3' // selector CSS
			});			
		})
	});
	
	
var FadeImgsFooter = new Class({
	initialize: function(element){
		if(element) this.element = element;
		this.setOpacity();
		this.hoverEffect();
	},
	setOpacity: function(){
		this.element.getElement('img').setStyle('opacity', 0);
	},
	hoverEffect: function(){
		this.element.addEvents({
			'mouseenter': function(){
				this.getElement('img').tween('opacity', 1);
			},
			'mouseleave': function(){			
				this.getElement('img').tween('opacity', 0);					
			}
		})
	}
});

var TweenOpacity = new Class({
	Implements: Options,
	options: {
		opacity: .5
	},
	initialize: function(element, options){
		this.setOptions(options);
		this.element = element;
		this.setOpacity();
		this.hoverEffect();		
	},
	setOpacity: function(){
		this.element.setStyle('opacity', this.options.opacity);		
	},
	hoverEffect: function(){
		var _this = this;
		if(this.element.getParent('a')){
			this.element.getParent('a').addEvents({
				'mouseenter': function(){
					this.getElement('img').tween('opacity', 1);					
				},
				'mouseleave': function(){
					this.getElement('img').tween('opacity', _this.options.opacity);					
				}
			});
		}
		else{
			this.element.addEvents({
				'mouseenter': function(){
					this.tween('opacity', 1);					
				},
				'mouseleave': function(){
					this.tween('opacity', _this.options.opacity);					
				}
			});
		}
	}	
});
		
var MenuDesplegable = new Class({
	Implements: Options,
	options: {
		claseActivo: 'hover',
		claseFocus: 'focus',
		claseDesplegable: 'desplegable',
		titleMenuDesplegable: 'Utilice la flecha abajo del teclado para acceder al submenú',
		claseCompatibilidad: 'child' // selector de hijo
	},
	initialize: function(element, options){
		this.element = element;
		this.setOptions(options);			
		if(this.tieneSubmenu()){
			this.anadirClaseCompatibilidad();	
			this.anadirRolesAria();				
			this.manageFocus();			
			this.muestraSubmenu();							
		}
		this.esconderSubmenus();			
	},
	tieneSubmenu: function(){
		return (this.element.getParent('li').getElement('ul'));			
	},
	anadirClaseCompatibilidad: function(){
		this.element.getParent('li').addClass(this.options.claseDesplegable);			
		if(this.element.getParent().getElement('ul')) this.element.addClass(this.options.claseCompatibilidad);			
	},
	anadirRolesAria: function(){		
		this.element.getParent('div').set({
			'role': 'application', // necesario para que el AT atienda a nuestros eventos de teclado e ignore los suyos del modo cursor virtual
			'aria-labelledby': 'navegacion-global-label'
		});			
		
		this.element.getParent('ul').getElements('li.'+this.options.claseDesplegable).each(function(el,i){								
			el.getElement('ul').set({
				'aria-hidden': 'true',
				'id': 'submenu-' + i,
				'role': 'menu'
			});
			el.getElement('a').set('id','submenu-label-' + i);				
			el.getElement('ul').getElement('a').set('id', 'first-link-submenu-' + i);
			el.getElement('ul').getElements('a').set({
				'role':'menuitemradio',
				'aria-checked':'false'
			}).addEvents({
				'focus': function(){
					this.set('aria-checked','true')
				},
				'blur': function(){
					this.set('aria-checked','false')
				}
			});
			
			el.getElement('a').set({
				'role': 'menuitem',
				'aria-haspopup': 'true'
			});			
		}.bind(this));
							
	},
	manageFocus: function(){
		this.element.set('tabindex','0');	
		var opt = this.options;
		this.element.addEvent('keydown', function(ev){
			if(ev.key == 'down'){
				ev.stop();					
				this.getParent().getElement('ul').set('aria-hidden','false').setStyle('display','block');		
				this.getParent().addClass(opt.claseFocus);					
				this.getParent().getElement('ul').getElement('a').focus();										
			}
			if(ev.key == 'up'){
				ev.stop();					
				this.getParent().removeClass(opt.claseFocus);					
				this.getParent().getElement('ul').set('aria-hidden','true').setStyle('display','none');					
			}				
		});	
		
		//anadimos tooltip indicativo para usuarios de teclado "videntes"
		this.element.addEvents({
			'keyup': function(ev){
				var tooltip = new Element('span',{
					'class': 'tooltip'
					,'id': 'tooltip'
					,'text': this.options.titleMenuDesplegable
					,'role': 'presentation' // no debe mostrarse a lectores de pantalla (JAWS lo muestra :S)
					,'aria-hidden': 'true'
				}).setStyle('opacity', .5);
				if(!$('tooltip') && this.element.getParent('li').getElement('ul').get('aria-hidden') != 'false') this.element.getParent('li').grab(tooltip,'bottom');					
			}.bind(this),
			'blur': function(){		
				if($('tooltip')) this.element.getParent('li').getElement('span.tooltip').dispose();					
			}.bind(this)
		});
		
		// submenus 
		this.element.getParent('li').getElement('ul').getElements('a').each(function(el){
			el.addEvent('keydown', function(ev){
				if(ev.key == 'down'){
					ev.stop();						
					if(el.getParent().getNext()) {
						el.getParent().getNext().getElement('a').focus();						
					}
					else{
						el.getParent('ul').getElement('li').getElement('a').focus();							
					}
				}
				if(ev.key == 'up'){
					ev.stop();
					if(el.getParent().getPrevious()) {
						el.getParent().getPrevious().getElement('a').focus();						
					}			
					else{
						el.getParent('ul').getLast('li').getElement('a').focus();							
					}			
				}
			})
		});
	},	
	muestraSubmenu: function(){
		var _this = this;
		if(!this.element.getParent('li').getElement('ul')) return;
		this.element.getParent('li').addEvents({
			'mouseenter': function(){
				this.addClass(_this.options.claseActivo);					
				this.getElement('ul').set('aria-hidden','false').setStyle('display','block');					
			},
			'mouseleave': function(){
				this.removeClass(_this.options.claseActivo);					
				this.getElement('ul').set('aria-hidden','true').setStyle('display','none');					
			}
		})
	},
	esconderSubmenus: function(){
		var opt = this.options;
		this.element.addEvent('focus',function(){
			this.getParent('ul').getElements('li.' + opt.claseDesplegable).removeClass(opt.claseFocus);					
			if(this.getParent().hasClass(opt.claseDesplegable)) this.getParent().addClass(opt.claseFocus);
			
			this.getParent('ul').getElements('li.' + opt.claseDesplegable).each(function(el){
				if(!el.hasClass(opt.claseFocus)){
					el.getElement('ul').set('aria-hidden','true').setStyle('display','none');						
				}
			})
		})
	}
});
		
var Carrusel = new Class({
	Implements: Options,
	options: {
		tag: 'li', // tag por defecto
		textoEnlaceControl: 'Imagen',
		idWrapperControles: 'controles-carrusel',
		claseControlActivo: 'activo',
		autoPlay: true,
		intervalo: 5000,
		visible: 'visible'
	},
	initialize: function(element, options){
		if(!element) return;
		this.element = element;			
		this.setOptions(options);
		this.prepararHTML(); 
	},
	prepararHTML: function(){
		// evitamos que se vea el efecto de carga de las imgs
		// TODO: poner como imagen de fondo un loading
		this.element.fade('hide'); 
					
		var isLoaded = function(){
			// compruebo si el DOM esta cargado
			if(document.documentElement.className.lastIndexOf('loaded') != -1){
				this.element.fade('in').addClass(this.options.visible);						
				$clear(this.checkWindowLoad);
				this.play();					
			}
		}
		this.checkWindowLoad = isLoaded.periodical(500, this);
		
		
		var wrapperControles = new Element('div',{
			id: this.options.idWrapperControles
		});
		var wrapperList = new Element('ul');
		
		var list = [], link = [];
		this.element.getElements(this.options.tag).each(function(el, i){				
			i+= 1;
			el.set('id', 'i' + i);	
			link[i] = new Element('a',{
				href: '#',
				text: this.options.textoEnlaceControl + ' ' + i
			});
			list[i] = new Element('li',{
				'class': el.get('id')
			}).adopt(link[i]);				
			
			link[i].addEvent('click', function(ev){
				ev.stop();
				this.mostrar(el);	
				if(this.options.autoPlay) this.stop();	// si hay autoPlay desactivamos al clicar			
			}.bind(this));
		}.bind(this));		
						
		wrapperList.adopt(list);
		wrapperControles.adopt(wrapperList);
		this.element.getParent().grab(wrapperControles, 'top');			
		
		wrapperList.getElements('li')[0].addClass(this.options.claseControlActivo);	
		
		this.element.getElements(this.options.tag)[0].setAttribute('visible','true');				
		if(this.options.autoPlay && this.element.hasClass(this.options.visible)) this.play();									
	},
	mostrar: function(item){			
		item.getParent().getElements(this.options.tag).fade('out');
		item.getParent().getElements(this.options.tag).each(function(el){
			el.removeAttribute('visible','true');
		});
		item.fade('in').setAttribute('visible','true');	
		
		$(this.options.idWrapperControles).getElements('li').removeClass(this.options.claseControlActivo);			
		$(this.options.idWrapperControles).getElement('li.' + item.get('id')).addClass(this.options.claseControlActivo);			
	},
	play: function(){			
		var _this = this;	
		var mostrar = function(){
			var siguiente = _this.element.getElement('li[visible]').getNext() ? _this.element.getElement('li[visible]').getNext() : _this.element.getElements('li')[0];
			_this.mostrar(siguiente);				
		}
		this.intervalo = mostrar.periodical(_this.options.intervalo);
	},
	stop: function(){
		$clear(this.intervalo);			
	}
});
	
var OverOpacity = new Class({
	Implements: Options,
	options:{
		opacity: .5
	},
	initialize: function(element, options){
		this.setOptions(options);
		this.element = element;
		this.changeOpacity();			
	},
	changeOpacity: function(){
		var _this = this;
		this.element.setStyle('opacity', this.options.opacity);
		this.element.addEvents({
			'mouseenter': function(){
				this.setStyle('opacity', 1);					
			},
			'mouseleave': function(){
				this.setStyle('opacity', _this.options.opacity);					
			}
		})
	}
});
	
var MapaTiendas = new Class({
	Implements: Options,
	options: {
		rutaImgs: '',
		rutaScripts: document.location.protocol + '//' + document.location.host + '/wp/wp-content/themes/normark/js/' // CAMBIAR EN PRODUCCION!!
	},
	initialize: function(element,provincias,options){
		if(!element) return;
		this.element = element;			
		this.provincias = provincias;
		this.setOptions(options);			
		//this.anadirScripts();			
		this.precargarImgs(); // precarga las imagenes de cada comunidad activa			
	},
	anadirScripts: function(){
		var p = this.options.rutaScripts;			
		var scriptMapper = new Asset.javascript(p + 'mapper.js');								
	},
	precargarImgs: function(){
		var _this = this;
		var p = this.options.rutaImgs;
		var imgs = [
			p + 'andalucia.png',
			p + 'andorra.png',
			p + 'aragon.png',
			p + 'asturias.png',
			p + 'cantabria.png',
			p + 'castilla-la-mancha.png',
			p + 'castilla-y-leon.png',
			p + 'cataluna.png',
			p + 'ceuta-y-melilla.png',
			p + 'comunidad-valenciana.png',
			p + 'extremadura.png',
			p + 'galicia.png',
			p + 'islas-baleares.png',
			p + 'islas-canarias.png',
			p + 'la-rioja.png',
			p + 'madrid.png',
			p + 'murcia.png',
			p + 'navarra.png',
			p + 'pais-vasco.png'
		];
		var mapas = new Asset.images(imgs,{
			onComplete: function(){
				//alert('imgs cargadas');
				_this.clickArea();							
			}
		});			
	},
	clickArea: function(){			
		this.element.getElements('area').each(function(el){								
			el.addEvent('click', function(ev){										
				//ev.stop();										
				var provincia = el.get('href').split('#')[1];
				this.mostrar(provincia);															
			}.bind(this))
		},this)
	},
	mostrar: function(provincia){
		this.cambiarImagenMapa(provincia);			
		this.provincias.setStyle('display','none');
		$(provincia).setStyle('display','block');
	},
	cambiarImagenMapa: function(provincia){
		// peligroso: damos por hecho que solo habra un mapa de imagen...
		var imgMapa = $('gmipam_0_image');
		//var imgMapa = $$('img[usemap]')[0];			
				
		var srcOriginal = imgMapa.get('src');
		var posUltimaBarraRuta = srcOriginal.lastIndexOf('/') + 1;
		var ruta = srcOriginal.slice(0, posUltimaBarraRuta);
		
		// tambien damos por hecho el nombre y formato de archivo
		var nuevaImg = provincia.split('ca-')[1] + '.png';
		imgMapa.set('src', ruta + nuevaImg);							
	}
});
	
var Collapsible = new Class({
	Implements: Options,
	options: {
		heading: '.collapsible-heading',
		content: '.collapsible-content',
		titleMostrar: 'Mostrar',
		titleOcultar: 'Ocultar'
	},
	initialize: function(options){
		this.setOptions(options);
		this.prepareHTML();			
	},
	prepareHTML: function(){
		$$(this.options.content).each(function(el, i){
			//if(el.tagName == 'UL' && !el.getElements('li').length) el.getParent('div').dispose(); // esto se carga todos los elementos en Explorer
			
			el.set({
				'aria-hidden': 'true',
				'index': i,
				'id': 'collapsible-content-' + i,
				'role': 'group',
				'aria-expanded': 'false'
			}).setStyle('display','none');				
		});
		$$(this.options.heading).each(function(el, i){			
			var link = new Element('a',{
				'index': i,
				'href': '#',
				'role': 'button',
				'aria-expanded': 'false',
				'id': 'collapsible-heading-' + i,
				'text': el.get('html'), // parece que el.get('text) no funciona bien en Safari
				'title': this.options.titleMostrar
			});
			link.addEvent('click', this.collapse.bindWithEvent(this));	

			var linkWrapper = new Element(el.get('tag'),{
				'class': el.get('class')
			}).grab(link);			
						
			linkWrapper.replaces(el);
			
			if(link.getParent().getNext(this.options.content)) {
				link.set('aria-controls', link.getParent().getNext(this.options.content).get('id'));
				link.getParent().getNext(this.options.content).set('aria-labelledby', link.get('id'));
			}						
		}.bind(this));
	},
	collapse: function(event){
		event.stop();
		var link = event.target;
		if(!link.getParent().getNext(this.options.content)) return;
		var content = link.getParent().getNext(this.options.content);
		if(content.get('aria-hidden') == 'true'){
			content.set({
				'aria-hidden':'false',
				'aria-expanded':'true'
			}).setStyle('display','');			
			link.set('title',this.options.titleOcultar);				
			link.set({
				'title':this.options.titleOcultar,
				'aria-expanded':'true'
			}).getParent().addClass('expanded');				
		}
		else{
			content.set({
				'aria-hidden':'true',
				'aria-expanded':'false'
			}).setStyle('display','none');				
			link.set({
				'title':this.options.titleMostrar,
				'aria-expanded':'false'
			}).getParent().removeClass('expanded');
		}
	}
});

var LabelOverInput = new Class({
	Implements: [Options, Events],
	options: {
		claseFocus: 'focus'
	},
	initialize: function(element, options){
		this.setOptions(options);
		this.element = element;		
		this.addClasses();		
	},
	addClasses: function(){
		var _this = this;
		this.element.addEvents({
			'focus': function(){				
				this.getParent('form').addClass(_this.options.claseFocus)
			},
			'blur': function(){
				if(this.value == this.defaultValue || this.value.length == 0) this.getParent('form').removeClass(_this.options.claseFocus)
			}
		});
	}
});

var LoadAjax = new Class({
	Implements: Options,
	options: {
		loaderDivID: null, // div donde se carga el contenido
		callback: '?json=1',
		selectorTitleLoadedContent: 'h5',
		loadingClass: 'loading'
	},
	initialize: function(element, options){
		this.setOptions(options);
		if(!$(this.options.loaderDivID)) return;
		this.element = element;		
		this.element.addEvent('click', function(ev){
			this.ajaxCall(ev);			
		}.bind(this));		
	},
	ajaxCall: function(ev){
		ev.stop();
		var callback  = this.options.callback;			
		var url = ev.target.get('href');	
		var req = new Request.JSON({
			url: url + callback,
			onRequest: function(){
				$(this.options.loaderDivID).empty().addClass(this.options.loadingClass);				
			}.bind(this),
			onSuccess: function(data){								
				if(!data) return;
				$(this.options.loaderDivID).removeClass(this.options.loadingClass);				
				this.setLoadedHtml(data);				
			}.bind(this)
		}).get();		
	},
	setLoadedHtml: function(data){		
		var title = new Element(this.options.selectorTitleLoadedContent,{
			text: data.post.title_plain
		});
		var content = new Element('div',{
			html: data.post.content
		});
		$(this.options.loaderDivID).adopt(title, content);		
	}
});
})(document.id);

