/* *
 * Este objeto se encargará de las funciones accesibles desde todas las aplicaciones del portal así como de los
 * que las engloban.
 *
 * @Date: 2009/05/29
 * @Rev: 1.0
 */
var Portal = {
	isReady: false,
	acciones: {},
	actions: {},
	messages: {},
	responses: {},
	fields: {},
	ga_listCustomVar: {},
	msgTypes: {
		error:   4,
		warning: 3,
		correct: 2,
		message: 1
	},
	msgStyles: {
		error:   'notimooError',
		warning: 'notimooWarning',
		correct: 'notimooCorrect',
		info: 'notimooInfo'
	},
	notificationManager: null,
	init: function() {
		if(this.isReady) return;
	    //Inicialización de id desde atributo name.
		$$('form, input, textarea, select').each(function(input, index){
			if(!$chk(input.get('id'))) {
				input.set('id', input.get('name'));
			}
		});
		// Inicialización y notificación de mensajes a usuario
		this.notificationManager = new Notimoo({locationVBase :150,locationHBase :50});
		if($chk(MSG_ERROR))this.showError(MSG_ERROR);
		if($chk(MSG_AVISO))this.showWarning(MSG_AVISO);
		if($chk(MSG_CORRECTO))this.showCorrect(MSG_CORRECTO);

		//Inicialización del componente de ampliación de imágenes
		window.myZoomer = null;
		//window.myZoomer = new ByZoomer('byzoomer',{zoom:1.5});
		window.myZoomer = new ByZoomer('byzoomer');

		//todos los elementos que están ocultos por no se útiles sin javascript (class="noscript hide") se han de mostrar
		//Eliminamos el estilo oculto de todas las imágenes a tratar.
		//$$('.noscript').each(function(element){element.removeClass('hide')});

		//añadimos el target _blank a todos los enlaces externos
		$$('._blank').each(function(element){
			element.set('target','_blank');
		});

		//Inicializamos los enlaces de cambio de idioma
		$$('.idioma').each(function(link) {
			link.addEvent('click', function(event){
				Portal.cambioIdiomaDelegado(link, event);
			});
		});

		//Inicializamos los enlaces de tipo Información Estática
		$$('.infoEstatica').each(function(link) {
			link.addEvent('click', function(event){
				new Event(event).stop();
				Portal.abrirEstatica(this.get('href'));
			});
		});

		//Inclusión del script ga.js de Google
		//El resto de js implementan en su init la llamada al Portal.init lo que detiene su ejecución hasta que el ga.js
		// se ha cargado. El delay simbólico de 10ms se utiliza para continuar la ejecución permitiendo al resto de js
		// continuar ya que no han de depender de la interacción con Analytics.  
		Portal.ga_callGoogleTracking.bind(this).delay(10);

		this.isReady = true;
	},
    /* Inicio de las funciones para gestión de Google Analytics */
    ga_trackPageview: function (url) {
    	if($chk(this.ga_listCustomVar)) {
    		if($chk(this.ga_listCustomVar.tipoUsusario))
    			this.ga_pageTracker._setCustomVar(1, 'Tipo usuario', 'Empresa', 1);
    		if($chk(this.ga_listCustomVar.sexo))
    			this.ga_pageTracker._setCustomVar(2, 'Sexo', 'Masculino', 1);
    		if($chk(this.ga_listCustomVar.edad))
				this.ga_pageTracker._setCustomVar(3, 'Edad', '25-35', 1);
			if($chk(this.ga_listCustomVar.estadoUsuario))
				this.ga_pageTracker._setCustomVar(4, 'Estado usuario', 'No identificado', 2);
    	}
     	if($chk(url)) this.ga_pageTracker._trackPageview();
     	else this.ga_pageTracker._trackPageview(url);
    },

	ga_callGoogleTracking: function () {
		var gaJsUrl = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + "google-analytics.com/ga.js";
		this.loadScript(gaJsUrl, function () {
            this.ga_pageTracker = _gat._getTracker("UA-848840-1")
			this.ga_trackPageview();
			Portal.ga_notifyTrans();
			Portal.ga_virtualTracking();
			Portal.ga_virtualEvent();

			window.myZoomer.addEvent('onZoomInComplete',function(myZoomer) {
				try {
					this.ga_virtualEvent( {
						category: 'imagen',
						action: 'ampliacion',
						description: myZoomer.largeElements[myZoomer.zoomed].src
					} );
				} catch(error) {
					this.iflr_trackError(error);
				}
			}.bind(this));
		}.bind(this));
	},

	ga_addVirtualTracking: function(url) {
		if(!$chk(this.ga_listVirtualTracking)) {
			this.ga_listVirtualTracking = new Array();
		}
		this.ga_listVirtualTracking.push(url);
	},

	ga_virtualTracking: function(directUrl) {
		try {
			if($chk(directUrl)) {
				this.ga_trackPageview(directUrl);
				return true;
			}
			if(!$chk(this.ga_listVirtualTracking)) return true;
			this.ga_listVirtualTracking.each(function(url){
				this.ga_trackPageview(url);
			});
		} catch (error) {
			return false;
		}
		return true;
	},
	ga_addVirtualEvent: function(event) {
		if(!$chk(this.ga_listVirtualEvent)) {
			this.ga_listVirtualEvent = new Array();
		}
		this.ga_listVirtualEvent.push(event);
	},

	ga_virtualEvent: function(directEvent) {
		try {
			if($chk(directEvent)) {
				this.ga_pageTracker._trackEvent(directEvent.category, directEvent.action, directEvent.description, directEvent.value);
				return true;
			}
			if(!$chk(this.ga_listVirtualEvent)) return true;
			this.ga_listVirtualEvent.each(function(event){
				this.ga_pageTracker._trackEvent(event.category, event.action, event.description, event.value);
			});
		} catch (error) {
			return false;
		}
		return true;
	},
	ga_addTrans: function(trans) {
		if(!$chk(this.ga_listTrans)) {
			this.ga_listTrans = new Array();
		}
		this.ga_listTrans.push(trans);
	},
	/**
	 * Este método se encarga de notificar transacciones al módulo de comercio electronico de GA.
	 * @param directTrans. Opcional. En caso de recibirse como parámetro se notificará solo esta transacción. En caso de
	 * no recibir ningún parámetro se notificarán a GA todas las transacciones añadidas previamente con el metodo ga_addTrans.
	 * El objeto directTrans ha de cumplir el siguiente formato:
	 * (Incluyo un ejemplo de la creación del objeto a partir de un PedidoLightValue
	 *		{
	 *			orderId:	"<%=pedido.getIdOrdenWeb()%>", 							//"order-id" required
	 *			affiliate:	"<%=pedido.getOrigenVenta()%>", 						//"affiliate or store name"
	 *			total:		"<%=pedido.getImporte().toString().replace(',','.')%>", //"total"
	 *			tax:		"0", 													//"tax" No disponemos de la información
	 *			shipping:	"0", 													//"shipping" No disponemos de la información
	 *			city:		"<%=pedido.getIdCiudadDest()%>", 						//"city"
	 *			state:		"<%=pedido.getIdProvDest()%>", 							//"state"
	 *			country:	"<%=pedido.getIdPaisDestino()%>", 						//"country"
	 *			item: {
	 *				orderId:			"<%=pedido.getIdOrdenWeb()%>", 								//"order-id" required
	 *				SKU:				"<%=pedido.getIdProducto()%>", 								//"SKU"
	 *				productName:		"<%=pedido.getDescProducto().substring(pedido.getDescProducto().indexOf("-")+1,pedido.getDescProducto().length()).trim()%>", //"product name"
	 *				productCategory:	"<%=categoria != null? categoria.getDescInterna(): "-"%>", 	//"product category"
	 *				unitPrice:			"<%=pedido.getImporte().toString().replace(',','.')%>", 	//"unit price" required
	 *				quantity:			"1" 														//"quantity" required
	 *			}
	 *		}
	 *
	 * @return boolean. Retorna true siempre que no se genere un error durante la ejecución.
	 */
	ga_notifyTrans: function(directTrans) {
		try {
			var bindTrack = function(trans) {
				this.ga_pageTracker._addTrans(
					trans.orderId,
					trans.affiliate,
					trans.total,
					trans.tax,
					trans.shipping,
					trans.city,
					trans.state,
					trans.country
				);
				this.ga_pageTracker._addItem(
					trans.item.orderId,
					trans.item.SKU,
					trans.item.productName,
					trans.item.productCategory,
					trans.item.unitPrice,
					trans.item.quantity
				);
				this.ga_pageTracker._trackTrans();
			}.bind(this);

			if($chk(directTrans)) {
				bindTrack(directTrans);
				return true;
			}
			if(!$chk(this.ga_listTrans)) return true;
			this.ga_listTrans.each(function(trans){
				bindTrack(trans);
			});
		} catch (error) {
			return false;
		}
		return true;
	},
    /* Fin de las funciones para gestión de Google Analytics */

	loadScript: function(scriptUrl, fntCallback){
		var script = document.createElement("script")
		script.type = "text/javascript";

		if (script.readyState) { //IE
			script.onreadystatechange = function() {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					fntCallback();
				}
			};
		} else { //FF, Chrome, Safari
			script.onload = function() {
				fntCallback();
			};
		}
		script.src = scriptUrl;
		document.getElementsByTagName("head")[0].appendChild(script);
	},
	/*
	* Este método sobreescribe la navegación de los enlaces del cambio de idioma de forma que sean los formularios de
	* aplicación los que realicen la navegación real.
	* Para que este método sobreescriba la navegación se han de dar tres condiciones:
	*	1. Ha de existir el contenedor de aplicación 'contenedor'. Este se considera el área de representación gráfica
	*	   de las distintas páginas de la aplicación.
	*	2. Dentro del contenedor de aplilcación hemos de tener un formulario para realizar la navegación.
	*	3. El formulario ha de tener un campo para contener el valor del nuevo idioma.
	*
	* En cualquier otro caso se realiza la navegación del propio enlace que, por norma, llamará a la home de la
	* aplicación internacionalizada al nuevo idoma.
	* Nota: El destino de la navegación directa de los enlaces no depende de este script y se representa directamente en
	*       el html de cabecera.jsp
	*/
	cambioIdiomaDelegado: function (link, event) {
		if(
			$chk($('contenido')) &&
			$chk($('contenido').getChildren('form')) &&
			$chk($('contenido').getChildren('form').getChildren('#codIdioma'))
		) {
			var lang = null;
			link.get('class').split(' ').each(function(styleClass){
				if(styleClass.contains('lang\[')) {
					lang = eval(styleClass.replace('lang',''))[0];
				}
			});
			if(lang) {
				new Event(event).stop();
				var form = $('contenido').getChildren('form')[0];
				form.accion.value = Portal.acciones.CAMBIO_IDIOMA;
				form.codIdioma.value = lang;
				form.submit();
			}
		}
	},

	showMessage: function(msg, type, title, clearSticky, parent, time) {
		var defaultTitle = "";
	    var styleClass = "";
		switch(type) {
			case this.msgTypes.error:
				defaultTitle =  this.messages.errorTitle;
				styleClass = this.msgStyles.error;
				break;
			case this.msgTypes.warning:
				defaultTitle =  this.messages.warningTitle;
				styleClass = this.msgStyles.warning;
				break;
			case this.msgTypes.correct:
				defaultTitle =  this.messages.correctTitle;
				styleClass = this.msgStyles.correct;
				break;
			default:
				defaultTitle =  this.messages.infoTitle;
				styleClass = this.msgStyles.info;
		}

		if(!$chk(title)) title = defaultTitle;
        var actParent = this.notificationManager.options.parent;
        if(parent)this.notificationManager.options.parent = $(parent);
        this.notificationManager.show({
			title: title,
			message: msg,
			sticky: !clearSticky,
			styleClass: styleClass,
			sticky: !$chk(time),
			visibleTime: time
		});
		this.notificationManager.options.parent = actParent;
		/*if($chk(time)) {
			(function(){
				alert('Cerrando tras ' + time + ' milisegundos.');
			}).delay(time);
		}*/
	},

	showError: function(msg, title, parent, time) {
		this.showMessage(msg, this.msgTypes.error, title, false, parent, time);
	},
	showWarning: function(msg, title, parent, time) {
		this.showMessage(msg, this.msgTypes.warning, title, false, parent, time);
	},
	showCorrect: function(msg, title, parent, time) {
		this.showMessage(msg, this.msgTypes.correct, title, false, parent, time);
	},
	showInfo: function(msg, title, parent, time) {
		this.showMessage(msg, this.msgTypes.info, title, false, parent, time);
	},

	/**
	 * Función para la apertura de ventanas de información general
	 */
	abrirEstatica: function(urlbase, ancho, alto, posX, posY) {
		if(!ancho) ancho = "550";
		if(!alto) alto="700";
		if(!posX) posX = (screen.availWidth-ancho)/2;
		if(!posY) posY=(screen.availHeight-alto)/2;
		ancho += "px";
		alto += "px";
		var ventana = this.abrirVentana(urlbase,"ventanaPopup",ancho,alto,posX,posY);
	},

	/**
	 * Abre la url indicada en una nueva ventana con los parámeros recibidos. Antes de cerrarse llamará a la función
	 * indicada en la ventana padre.
	 * url. Url a abrir en la nueva venta.
	 * nombre. Nombre javascript de la ventana.
	 * width. Ancho de la nueva ventana.
	 * height. Alto de la nueva ventana.
	 * posX. Número de pixeles desde el margen izquierdo hasta el inicio de la ventana. En caso de null, centrado.
	 * posY. Número de pixeles desde el margen superior hasta el inicio de la ventana. En caso de null, centrado.
	 * modal. (true o false) Indica si la nueva ventana se habre en modo modal o no.
	 * funcionPadre. Función que ejecuta la ventana antes de cerrarse para notificar este evento a la ventana padre.
	 * return Objeto de tipo window con referencia a la nueva ventana para mantener el control desde la ventana padre.
	 */
	abrirVentana: function (url, nombre, width, height, posX, posY, modal, funcionPadre) {
		var ventana;
		if(!nombre) nombre = "ventanaPopup";
		if(!width) width = 400;
		if(!height) height = 400;
		if(!posX) posX = 10;
		if(!posY) posY = 10;
		if(modal) {
			ventana = showModalDialog(
				url,
				nombre,
				"width=" + width +
				",height=" + height +
				",top=" + posY +
				",left=" + posX +
				",toolbar=0" +
				",scrollbars=0|1" +
				",location=0" +
				",menubar=0" +
				",status=0" +
				",resizable=1"
			);
		} else {
			var ventana = window.open(
				url,
				nombre,
				"width=" + width +
				",height=" + height +
				",top=" + posY +
				",left=" + posX +
				",toolbar=no" +
				",scrollbars=auto" +
				",location=no" +
				",menubar=no" +
				",status=no"
			);
		}
		return ventana;
	},

	iflr_trackError: function (error) {
		try {
            if(window.console && window.console.firebug)  {
				console.error(error);
			}
		} catch (crash) {
		}
	}
}

window.addEvent('load', function(){
	Portal.init();
});
