/**
 * Seguimiento (Sogecable) de plus.es
 *
 * Autor: fgarcia
 * A la llamada del script se le pasan los 3 parámetros de seguimiento con el siguiente formato #PARAM1*PARAM2*PARAM3
 *
 * <script type="text/javascript" src="/js/seguimiento.js#PARAM1*PARAM2*PARAM3" id="segplus"></script>
 *
 * Se pueden lanzar nuevos seguimientos llamando a SEGUIMIENTO.ponerMarca('SEG0*SEG1*SEG2');
 */
SEGUIMIENTO = {
	sUrlPixel : 'http://controlsgc.prisacom.com/index',
	sParamSalidaComun : '', /* Parte común del seguimiento */
	sParamSalidaPlusEs : '', /* Parte del seguimiento cuando se navega desde las páginas de plus.es (cookie PlusLogNavegacion) */
	sParamSalidaJunior : '', /* Parte del seguimiento cuando se navema desde las páginas de Junior (cookie PlusJuniorLogNavegacion) */
	inicio : function () {
		/* Almacenamos los parametros de la url del pixel en SEGUIMIENTO.sParamSalidaComun, sParamSalidaPlusEs y sParamSalidaJunior */
		/* Cookies se hace uso del plugin de cookies de http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ */
		SEGUIMIENTO.sParamSalidaPlusEs = "&cl=" + SEGUIMIENTO.transformaNotNull(SEGUIMIENTO.cookie('PlusLogNavegacion'));
		SEGUIMIENTO.sParamSalidaJunior = "&cl=" + SEGUIMIENTO.transformaNotNull(SEGUIMIENTO.cookie('PlusJuniorLogNavegacion'));
		/* Parte común */
		SEGUIMIENTO.sParamSalidaComun = "&cs=" + SEGUIMIENTO.transformaNotNull(SEGUIMIENTO.getCookieSeguimiento(SEGUIMIENTO.getAleatorio()));

		/* Página que mandad el pixel y la Referrer */
		SEGUIMIENTO.sParamSalidaComun += "&r=" + encodeURIComponent(document.location);
		SEGUIMIENTO.sParamSalidaComun += "&re=" + encodeURIComponent(document.referrer);

		/* String con los tres valores de seguimiento */
		SEGUIMIENTO.ponerMarca(SEGUIMIENTO.getSeguimientoDeSrc());
	},
	ponerMarca : function(sSeguimiento) {
		var aSeguimiento = SEGUIMIENTO.parseSeguimiento(sSeguimiento);
		var sParamSeg = "?seg0="+ aSeguimiento[0] +"&seg1="+ aSeguimiento[1] +"&seg2="+ aSeguimiento[2];
		/* Generamos los seguimientos del pixel dependiendo de si el parámetro web es de JUNIOR o de plus.es */
		sParamSalida = aSeguimiento[0]== "JUNIOR"
			? SEGUIMIENTO.sParamSalidaJunior + SEGUIMIENTO.sParamSalidaComun
			: SEGUIMIENTO.sParamSalidaPlusEs + SEGUIMIENTO.sParamSalidaComun;
		var sNoCache = "&rd=" + SEGUIMIENTO.getAleatorio(); /* Valor aleatorio para evitar caches */

		/* Precargar una imagen para dejar log en el pixel */
		var oPixel = new Image;
		oPixel.src = SEGUIMIENTO.sUrlPixel + sParamSeg + sParamSalida + sNoCache;
	},
	getAleatorio : function() {
		/* Valor aleatorio para evitar caches y posible valor de la sesion */
		var d = new Date();
		return (Math.floor(Math.random()*100000) +'.'+ d.getTime());
	},
	parseSeguimiento : function(sSeguimiento) {
		/* Transforma un seguimiento string de la forma PARAM1*PARAM2*PARAM3 en un array, es caso de problema mete SINSEG*SINSEG*SINSEG */
		aSeguimiento = sSeguimiento.split('*'); /* Extraer los tres códigos de seguimiento */

		/* Si hay algún problema se graba SINSEG, SINSEG, SINSEG */
		if (aSeguimiento[0] == null || aSeguimiento[1] == null || aSeguimiento[2] == null) {
			aSeguimiento[0] = 'SINSEG';
			aSeguimiento[1] = 'SINSEG';
			aSeguimiento[2] = 'SINSEG';
		}
		else {
			/* Sino urlencodeo el resultado para evitar conflictos con & y cosas similares */
			aSeguimiento[0] = encodeURIComponent(aSeguimiento[0]);
			aSeguimiento[1] = encodeURIComponent(aSeguimiento[1]);
			aSeguimiento[2] = encodeURIComponent(aSeguimiento[2]);
		}

		return aSeguimiento;
	},
	getSeguimientoDeSrc : function() {
		/* Extraer el código de seguimiento del <script src="...#SEG0*SEG1*SEG2"...> */
		var sSeguimientoBruto = document.getElementById("segplus").getAttribute("src");
		if (sSeguimientoBruto) {
			var re = /.*#/g; /* Elimina todo lo que va delante de la # incluida esta */
			sSeguimiento = sSeguimientoBruto.replace(re, '');
			//aSeguimiento = sSeguimiento.split('*'); /* Extraer los tres códigos de seguimiento */
		}
		else {
			sSeguimientoBruto = "SINSEG*SINSEG*SINSEG";
		}

		return sSeguimiento;
	},
	getCookieSeguimiento : function(sSemilla) {
			/* Generación de la sesion si no existe */
			if (!SEGUIMIENTO.cookie('plusSesionUsu')) {
				/* Mantenter la continuidad con la antigua cookie */
				/* determinamos si el host es una ip o un nombre de dominio */
				aHost = document.location.hostname.split('.');
				if (isNaN (parseInt (aHost[aHost.length-1])))
					/* Es un nombre de dominio */
					sDomain = '.'+aHost[aHost.length-2]+'.'+aHost[aHost.length-1]
				else
					/* Es una ip */
					sDomain = document.location.hostname;

				if (SEGUIMIENTO.cookie('plusSesion'))
					SEGUIMIENTO.cookie('plusSesionUsu', SEGUIMIENTO.cookie('plusSesion'), {expires: 7300, domain: sDomain, path: '/'})
				else
					SEGUIMIENTO.cookie('plusSesionUsu', sSemilla, {expires: 7300, domain: sDomain, path: '/'})

				SEGUIMIENTO.cookie('plusSesion', '', {expires: -1}); /* Nos despedimos de la vieja cookie */
			}

		return SEGUIMIENTO.cookie('plusSesionUsu');
	},
	transformaNotNull : function(sEntrada) {
		return (sEntrada == null ? '' : sEntrada);
	},
	trim: function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},
	cookie : function(name, value, options) {
		/* Código del plugin jCookie de Klaus Hartl/klaus.hartl@stilbuero.de*/
		if (typeof value != 'undefined') { // name and value given, set cookie
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
			}
			// CAUTION: Needed to parenthesize options.path and options.domain
			// in the following expressions, otherwise they evaluate to undefined
			// in the packed version for some reason...
			var path = options.path ? '; path=' + (options.path) : '';
			var domain = options.domain ? '; domain=' + (options.domain) : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else { // only name given, get cookie
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = SEGUIMIENTO.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						//cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						cookieValue = unescape(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	}

}

if (typeof(jQuery) != "undefined"){

	/* Plugin de jQuery para asociarlo a nodos */
	/* Ej. $("a.conSeguimiento").ponSeguimientoSogecable("UNO*DOS*TRES"); */
	/*	 $("a.conSeguimiento").ponSeguimientoSogecable("UNO*DOS*TRES", "mouseover"); */
	jQuery.fn.ponSeguimientoSogecable = function(sSeguimiento, evento){
		/* Si no viene evento al que asocial le mentemos el click */
		evento = (evento === undefined) ? "click" : evento;

		this.each( function(){
			$(this).bind(evento,
				function() {
					SEGUIMIENTO.ponerMarca(sSeguimiento);
				}
			);
			//alert(this + '['+ sSeguimiento + ']['+ evento + ']');
		});
		return (this);
	}
}
/* No es necesario que esté cargado el documento para precargar la imagen */
SEGUIMIENTO.inicio();
