/*****************************************************************************/
/*                                2010 Shio2e                                */
/*                        JAVASCRIPT TICKER PUBLICIDAD                       */
/*****************************************************************************/

var tickerPublicidad = {
	// VARIABLES CONFIGURACION
	num_visionados_envio 	: 5,
	tiempo_reinicio			: 15,
	tiempo_vigilante		: 2,
	tiempo_cambio			: 7,
	tiempo_transicion		: 3,
	margen_inferior			: 3,

	// VARIABLES INTERNAS
	tickers 				: new Array(),
	cargado 				: false,
	visionados 				: new Array(),
	nuevos_anuncios 		: {},
	tickers_detenidos 		: 0,
	tickers_orden_enviada 	: false,

	// FUNCIONES
	nuevo : function (id_contenedor, anuncios_cantidad, anuncios, tiempo_cambio, enlace_javascript){
		tiempo_cambio = tiempo_cambio || this.tiempo_cambio;
		enlace_javascript = typeof enlace_javascript == "undefined" ? true : enlace_javascript;
		if (this.cargado) {
			tickerPublicidad.tickers.push(new tickerPublicidadClass(id_contenedor, anuncios_cantidad, this.margen_inferior, tiempo_cambio, this.tiempo_transicion, anuncios, enlace_javascript));
		} else {
			Event.observe(window, 'load', function (){
				tickerPublicidad.cargado = true;
				tickerPublicidad.tickers.push(new tickerPublicidadClass(id_contenedor, anuncios_cantidad, tickerPublicidad.margen_inferior, tiempo_cambio, tickerPublicidad.tiempo_transicion, anuncios, enlace_javascript));
			});
		}
	},

	getTickerXId : function (id_contenedor){
		for (i=0; i<this.tickers.length; i++)
			if (this.tickers[i].id_contenedor == id_contenedor)
				return this.tickers[i];
		return null;
	},

	visionadoAdd : function (id_anuncio){
		this.visionados.push(id_anuncio);
		if (this.visionados.length >= this.num_visionados_envio)
			this.visionadoSend();
	},

	visionadoSend : function (){
		var visionados = Object.toJSON(this.visionados);
		this.visionados = new Array();

		new Ajax.Request('/exec/ajax/ticker_visionado.php', {
			parameters: { visionados: visionados }
		});
	},

	recargar : function (anuncios){
		if (typeof anuncios == "undefined") {
			anuncios = this.nuevos_anuncios;
		} else {
			this.nuevos_anuncios = anuncios;
		}

		if (this.tickers_detenidos >= 4) {
			if (!this.tickers_orden_enviada) {
				this.tickers_orden_enviada = true;
				anuncios = anuncios.evalJSON();
				$('visor1').ticker.setAnuncios(anuncios.visor1);
				$('visor2').ticker.setAnuncios(anuncios.visor2);
				$('visor3').ticker.setAnuncios(anuncios.visor3);
				$('visor4').ticker.setAnuncios(anuncios.visor4);
				this.tickers_detenidos = 0;
			}
		} else {
			this.tickers_orden_enviada = false;

			for (i=0; i<this.tickers.length; i++)
				this.tickers[i].detener();

			setTimeout('tickerPublicidad.recargar()', 300);
		}
	},

	vigilar : function (){
		Event.observe(window, 'load', function (){ setTimeout('setInterval(\'tickerPublicidad.vigilante()\', tickerPublicidad.tiempo_vigilante * 1000)', tickerPublicidad.tiempo_reinicio * 1000); } );
	},

	vigilante : function (){
		var hora_actual = Math.round(parseInt(new Date().getTime()) / 1000);

		for (i=0; i<this.tickers.length; i++)
			if (this.tickers[i].ultima_transicion != 0 && this.tickers[i].ultima_transicion <= hora_actual - this.tiempo_reinicio && this.tickers[i].detenido == false)
				this.tickers[i].transicion();
	}
}

// Class: tickerPublicidadClass
var tickerPublicidadClass = Class.create();

tickerPublicidadClass.prototype = {
	// VARIABLES CONFIGURACION

	// VARIABLES INTERNAS
	id_contenedor 		: '',
	id_contenido 		: '_contenido',

	tiempo_cambio		: 0, // s
	tiempo_transicion	: 0, // s
	tramo_margen		: 0, // px
	tramo_transicion	: 0, // px
	temporizador		: null,

	anuncios_cantidad	: 0,
	anuncios_actual		: 0,

	primer_anuncio 		: true,
	movimiento 			: true,
	detenido 			: false,
	transicionar		: false,
	transicionando		: false,

	ultima_transicion	: 0,

	anuncios			: null,

	enlace_javascript			: true,

	// FUNCIONES
	initialize : function (id_contenedor, anuncios_cantidad, margen_inferior, tiempo_cambio, tiempo_transicion, anuncios, enlace_javascript) {
		this.id_contenedor 		= id_contenedor;
		this.id_contenido 		= id_contenedor+this.id_contenido;

		this.margen_inferior 	= margen_inferior;
		this.tiempo_cambio 		= tiempo_cambio;
		this.tiempo_transicion 	= tiempo_transicion;
		this.tramo_margen 		= margen_inferior;
		this.tramo_transicion 	= $(id_contenedor).getHeight() + margen_inferior;

		this.anuncios_cantidad 	= anuncios_cantidad;

		this.enlace_javascript 	= enlace_javascript;

		$(id_contenedor).ticker = this;

		Event.observe($(this.id_contenedor), 'mouseover', this.mouseOver.bind(this));
		Event.observe($(this.id_contenedor), 'mouseout', this.mouseOut.bind(this));

		this.setAnuncios(anuncios);
	},

	detener : function () {
		if (!this.detenido) {
			clearTimeout(this.temporizador);
			this.movimiento = false;
			this.transicionar = false;
			if (this.transicionando) {
				setTimeout(this.detener.bind(this), 300);
			} else {
				this.detenido = true;
				tickerPublicidad.tickers_detenidos++;
			}
		}
	},

	iniciarTemporizador : function () {
		if (this.anuncios_actual >= this.anuncios_cantidad) {
			this.anuncios_actual = 0;
			$(this.id_contenedor).scrollTo(0, { duration: 0, transition: 'full' });
		}
		this.visionado(this.anuncios[this.anuncios_actual].id_anuncio);
		this.temporizador = setTimeout('$(\''+this.id_contenedor+'\').ticker.transicion()', this.tiempo_cambio * 1000);
	},

	transicion : function () {
		this.primer_anuncio = false;
		if (!this.movimiento) {
			this.transicionar = true;
		} else {
			var hora_actual = Math.round(parseInt(new Date().getTime()) / 1000);

			// VIGILAR QUE NO HAYA 2 TIMEOUTS AFECTANDO AL TICKER
			if (this.ultima_transicion > hora_actual - (this.tiempo_cambio + this.tiempo_transicion) / 2)
				return;

			// REALIZAR LA TRANSICION
			this.ultima_transicion = hora_actual;
			this.transicionando = true;
			this.transicionar = false;
			this.anuncios_actual++;
			$(this.id_contenedor).scrollTo(this.tramo_transicion * this.anuncios_actual, {
				duration: this.tiempo_transicion,
				transition: 'bounce',
				//position: 'end',
				after: this.transicionFin.bind(this)
			});
		}
	},

	transicionFin : function () {
		this.transicionando = false;
		if (this.movimiento)
			this.iniciarTemporizador();
	},

	mouseOver : function (event) {
		this.movimiento = false;
	},

	mouseOut : function (event) {
		this.movimiento = true;
		if (this.transicionar)
			this.transicion();
	},

	setAnuncios : function (anuncios) {
		anuncios_escribir = typeof anuncios_escribir == "undefined" ? true : anuncios_escribir;

		this.anuncios = new Array();

		// ELIMINAR ANUNCIOS ANTERIORES SI PROCEDE
		$(this.id_contenido).update('');

		// INSERTAR LOS ANUNCIOS NUEVOS
		var anuncio;
		var anuncios_cantidad = 0;
		while(anuncios[anuncios_cantidad]) {
			anuncio = new buscadorAnuncioClass(anuncios[anuncios_cantidad]);
			this.anuncios.push(anuncio);
			if (anuncios_escribir)
				this.escribirAnuncio(anuncio);
			anuncios_cantidad++;
		}

		// REPETIR EL PRIMER ANUNCIO PARA TENER CONTINUIDAD
		if (anuncios_cantidad > 0)
			this.escribirAnuncio(this.anuncios[0]);

		// RESETEAR VALORES INICIALES
		$(this.id_contenedor).scrollTo(0, { duration: 0, transition: 'full' });
		this.anuncios_cantidad	= anuncios_cantidad;
		this.anuncios_actual	= 0;
		this.primer_anuncio 	= true;
		this.movimiento 		= true;
		this.detenido			= false;
		this.transicionar		= false;
		this.ultima_transicion	= 0;

		// INICIAR TEMPORIZADOR
		this.iniciarTemporizador();
	},

	escribirAnuncio : function (anuncio) {
		if (this.enlace_javascript) {
			$(this.id_contenido).update($(this.id_contenido).innerHTML+'<a href="javascript:void(0);" onclick="javascript:buscador.abrir(\'carteleria\', {id_contenedor: \''+this.id_contenedor+'\', id_anuncio: '+anuncio.id_anuncio+'});"><img id="anuncio.'+anuncio.id_anuncio+'" src="http://img.shio2e.com/n/buscador-anuncio_banner-'+anuncio.id_anuncio+'.png"></a>');
		} else {
			$(this.id_contenido).update($(this.id_contenido).innerHTML+'<a href="'+anuncio.extra.url_oferta+'"><img id="anuncio.'+anuncio.id_anuncio+'" src="http://img.shio2e.com/n/buscador-anuncio_banner-'+anuncio.id_anuncio+'.png"></a>');
		}
	},

	abrir : function (id_anuncio) {
		var anuncio = this.getAnuncio(id_anuncio);
		this.clic(id_anuncio);
		buscador.anuncios.abrir(anuncio);
	},

	clic : function (id_anuncio) {
		new Ajax.Request('/exec/ajax/ticker_clic.php', {
			parameters: { id_anuncio: id_anuncio }
		});
	},

	visionado : function (id_anuncio) {
		tickerPublicidad.visionadoAdd(id_anuncio);
	},

	getAnuncio : function (id_anuncio) {
		for (i=0; i<this.anuncios.length; i++)
			if (this.anuncios[i].id_anuncio == id_anuncio)
				return this.anuncios[i];
		return false;
	}
}
