/**
 * Librería: jQuery versión 1.3.2
 */

/**
 * Creamos un array que contiene los elementos deplegables en el indice 1 y los elementos botones (que despliegan a los otros) en el indice 0
 * los indices 2 y 3 contienen la acción que se está ejecutando en ese momento para contabilizar en las estadísticas web
 */
var objetos = new Array(3);
objetos[0] = new Array(3);
objetos[1] = new Array(3);
objetos[2] = new Array(3);
objetos[3] = new Array(3);

objetos[0][0] = "abrirRegistro";
objetos[0][1] = "#registro";
objetos[0][2] = "/html/registroForm_init";
objetos[0][3] = "/html/registroForm_close";

objetos[1][0] = "abrirRecordarP";
objetos[1][1] = "#recordarPass";
objetos[1][2] = "/html/recordarPassForm_init";
objetos[1][3] = "/html/recordarPassForm_close";
objetos[2][0] = "postear";
objetos[2][1] = "#postear";
objetos[2][2] = "/html/postCommentForm_init";
objetos[2][3] = "/html/postCommentForm_close";

objetos[3][0] = "votar";
objetos[3][1] = "#gana";
objetos[3][2] = "/html/votar_init";
objetos[3][3] = "/html/votar_close";

var captionVideoLona = "Lona Te Quiero Atleti";

$(document).ready(function(){
	$("#registro").hide();
	$("#recordarPass").hide();
	$("#mensajes").hide();
	
	$("#telefono").numeric();
		
	$("#link_condiciones_legales").live("click", function(){
		googleAnalitycs("html/click_legales");
		return popup(this.href, "Condiciones_legales", "width=1000,height=750,scrollbars=1");
	});
	$("#link_aviso_legal").live("click", function(){
		googleAnalitycs("html/click_legales");
		return popup(this.href, "Condiciones_legales", "width=1000,height=750,scrollbars=1");
	});
	$(".abrirRegistro").live("click", function(){
		return cierraLosDemas($(this));
	});
	$(".abrirRecordarP").live("click", function(){
		return cierraLosDemas($(this));
	});
	$("#logout").live("click", function(){
		return logOut();
	});
	$("#hacer_login").live("click", function(){
		return hacerLogin();
	});
	$(".postear").live("click", function(){
		return cierraLosDemas($(this));
	});
	$(".ampliarComment").live("click", function(){
		return ampliarComentario(this, "ampliar");
	});
	$(".pagination a").live("click", function(){
		var inicio = this.href.indexOf("?",0)+1;
		var fin = this.href.length;
		eval(this.href.substring(inicio,fin));
		return cargaComentarios(pagina);
	});
	$(".voto_jugador").live("click", function(){
		return votarJugador(this);
	});
	$("#formApuesta input[type='radio']").live("click", function(){
		return cierraLosDemas(this);
	});
	$("#video_corazon").live("click", function(){
		cee_show(captionVideoLona, this.href, null)
		return false;
	});
	
	controladorSubmitLogin();
	controladorSubmitNuevoComentario();
	controladorSubmitRegistro();
	controladorSubmitRecordarPass();
	controladorSubmitBajaNewsletter();
	/* ************************************************************* */
	/* EMBED FLASHES */
	var params = {
			quality: "high",
			scale: "noscale",
			allowscriptaccess: "always",
			wmode: "transparent"
		};
	var flashvars = {};
	var attributes = {};
	/* GALERÍA */
	if (!empty($("#section_album").html())){
		attributes = {id:"galeriaswf"};
		swfobject.embedSWF("swf/galeria.swf", "galeriaswf", "670", "820", "8", "swf/expressInstall.swf", flashvars, params, attributes);
	}
	/* CABECERAS */
	var cabecera = "";
	if(!empty($("#section_apuesta").html())) cabecera = "cabecera_apuesta.swf";
	if(!empty($("#section_crack").html())) cabecera = "cabecera_crack.swf";
	if(!empty($("#section_aforo").html())) cabecera = "cabecera_aforo.swf";
	if(!empty($("#section_album").html())) cabecera = "cabecera_album.swf";
	if(!empty($("#section_oferta").html())) cabecera = "cabecera_oferta.swf";
	if(!empty($("#section_ganadores").html())) cabecera = "cabecera_ganadores.swf";
	if(!empty($("#section_home").html())) cabecera = "cabecera_home.swf";
	if(!empty(cabecera)){
		attributes = {id:"branding_flash"};
		swfobject.embedSWF("swf/"+cabecera, "branding_flash", "914", "255", "8", "swf/expressInstall.swf", flashvars, params, attributes);
		$("#branding").css("background", "none");
	}
	/* BANNERS DERECHA */
	attributes = {id:"paf"};
	swfobject.embedSWF("swf/paf.swf", "paf", "237", "222", "8", "swf/expressInstall.swf", flashvars, params, attributes);
	attributes = {id:"nba"};
	var params2 = {
			quality: "high",
			scale: "noscale",
			allowscriptaccess: "always",
			bgcolor: "#FFFFFF"
		};
	swfobject.embedSWF("swf/nba.swf", "nba", "237", "200", "8", "swf/expressInstall.swf", flashvars, params2, attributes);
	attributes = {id:"outlet"};
	swfobject.embedSWF("swf/outlet.swf", "outlet", "237", "60", "8", "swf/expressInstall.swf", flashvars, params2, attributes);
	/* BANNERS HOME */ 
	if(!empty($("#section_home").html())){
		attributes = {id:"navegacion_home_item_01"};
		swfobject.embedSWF("swf/home_aforo.swf", "navegacion_home_item_01", "288", "185", "8", "swf/expressInstall.swf", flashvars, params, attributes);
		attributes = {id:"navegacion_home_item_02"};
		swfobject.embedSWF("swf/home_crack.swf", "navegacion_home_item_02", "288", "185", "8", "swf/expressInstall.swf", flashvars, params, attributes);
		attributes = {id:"navegacion_home_item_03"};
		swfobject.embedSWF("swf/home_album.swf", "navegacion_home_item_03", "288", "185", "8", "swf/expressInstall.swf", flashvars, params, attributes);
		attributes = {id:"navegacion_home_item_04"};
		swfobject.embedSWF("swf/home_apuesta.swf", "navegacion_home_item_04", "288", "185", "8", "swf/expressInstall.swf", flashvars, params, attributes);
		attributes = {id:"navegacion_home_ganadores"};
		swfobject.embedSWF("swf/home_ganadores.swf", "navegacion_home_ganadores", "636", "185", "8", "swf/expressInstall.swf", flashvars, params, attributes);
	}
	
	definirMensajesRegistro();
});

/** FUNCIONES */
function popup(href, ventana, opciones){
	window.open(href, ventana, opciones);
	return false;
}

function cierraLosDemas(cualAbre){
	var haCerrado = false;
	var devolver = false;
	if (cualAbre[0]==undefined){
		var estoyAbriendo = cualAbre;
	}else{
		var estoyAbriendo = cualAbre[0];
	}
	// recorremos los objetos
	for (x in objetos){
		// buscamos el objeto que se está abriendo, buscando la coincidencia entre el classname de cualAbre y los objetos que recorremos
		if ((estoyAbriendo.className).indexOf(objetos[x][0]) >= 0) {
			// comprobamos si el objeto que abrimos es el form para postear comentarios, si es asi debemos comprobar si el usuario ha iniciado su sesión
			if ((estoyAbriendo.className).indexOf("postear") >= 0) {
				var estado = {procedencia: "postComment", datos: null};
				compruebaLogin(estado);
			}else if ((estoyAbriendo.type).indexOf("radio") >= 0) {
				var estado = {procedencia: "apuesta", datos: estoyAbriendo};
				compruebaLogin(estado);
			}else {
				// ahora haremos la acción de cerrar o abrir el modulo, pero antes controlamos la visibilidad de este
				// para mandar la estadística correspondiente
				if ($(objetos[x][1]).is(":hidden")){
					googleAnalitycs(objetos[x][2]);
				}else{
					googleAnalitycs(objetos[x][3]);
				}
				// el indice 3 es el de los input para apuesta, estos no deben ocultarse
				if(x!=3){
					$(objetos[x][1]).slideToggle("slow", "");
				}
			}
		}else{
			// este objeto no es el que manda la acción, comprobamos si está cerrado o abierto
			if (objetos[x][1] != objetos[3][1]) {
				haCerrado = compruebaYCierra(objetos[x][1]);
				if (haCerrado == true) {
					googleAnalitycs(objetos[x][3]);
				}
			}
		}
	}	
	return devolver;
}

function compruebaYCierra(objeto){
	// si el objeto es visible le cerramos
	if ($(objeto).is(":visible")){
		//controlamos que el objeto no sea un input para apuesta, estos no deben ocultarse
		if(objeto!=objetos[3][1]){
			$(objeto).slideToggle("slow", "");
		}
		return true;
	}else{
		return false;
	}
}

function googleAnalitycs(params){
	//alert(params);
	pageTracker._trackPageview(params);
}

function mostrarCargador(modulo, cual){
	var img, imgSrc;
	switch(cual){
		case "posts":
			imgSrc = "cargador_posts";
		break;
		case "cargador_grande_oscuro":
			imgSrc = "cargador_grande_oscuro";
		break;
		default:
			imgSrc = "cargador_modulo_form";
		break;
	}
	img = "<img class='image_cargador' src='images/"+imgSrc+".gif' alt='Cargando, espere por favor' />";
	modulo.html(img + "&nbsp;Cargando, espere por favor");
}

function isEmail(cadena){
	if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(cadena)){
		return true;
	}else{
		return false;
	}
}

function esTelefono(cadena){
	if (/^(9|8|6)\d{8}/.test(cadena)){
		return true;
	}else{
		return false;
	}
}
// El código postal debe tener 4 o 5 dígitos
function esCodigoPostal(cadena){
	if (!/\d{4}/.test(cadena)) {
		return true;
	}else{
		return false;
	}
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return {"x": scrOfX, "y": scrOfY};
}

/**
 * CONTROL DE AVISOS AL USUARIO
 */
// Variables de control para los avisos
var estoyDandoUnAviso = false; // nos indica si en ese momento se está mostrando un mensaje
var arrayMensajes = new Array(); // si se está dando un mensaje guardamos el que se manda para mostrarlo más tarde
/**
 * mostramos mensajes al usuario
 * @param {Object} mensaje
 */
function aviso(mensaje){
	if(!estoyDandoUnAviso){
		// si el mensaje procede de modulos_form no ocultamos los modulos
		if(mensaje.procedencia != "modulos_form" || mensaje.procedencia == undefined){
			cierraLosDemas($("a"));
		}
		$.scrollTo("#nav_main");
		estoyDandoUnAviso = true;
		if(mensaje.objeto != null){
			luminoso(mensaje.objeto);
		}
		$("#contenido_mensajes").html(mensaje.texto);
		$("#mensajes").slideToggle("slow");
		setTimeout("pararMensaje()", mensaje.tiempo);
		if (arrayMensajes.length >= 1) { // quitamos el primer item del array para eliminar mensajes de la cola
			arrayMensajes.shift();
		}
	}else{
		// si se está dando un mensaje guardamos el actual en el array
		arrayMensajes.push(mensaje);
	}
	
}
/**
 * Finaliza la muestra del mensaje
 */
function pararMensaje(){
	$("#mensajes").slideToggle("slow", function(){
		// callback cuando termina el efecto, cuando ya no se ve el div, eliminamos su contenido
		$("#contenido_mensajes").html("");
		estoyDandoUnAviso = false;
	});
	// si el array de mensajes tiene alguno volvemos a llamar a la función de aviso con el primer mensaje de la cola
	if (arrayMensajes.length>=1){
		setTimeout("aviso(arrayMensajes[0])", 1000);
	}
}

function luminoso(objetosAIluminar){
	// recorremos el array de objetos para comprobar cuales no tienen ningún valor
	var num_objetos = objetosAIluminar.dom.length-1;
	for(var i=0;i<=num_objetos;i++){
		var iluminar = false;
		switch(objetosAIluminar.iluminar){
			case true:
				iluminar = true;
			break;
			case "emptyOnly":
				if ($(objetosAIluminar.dom[i]).val()=="")
					iluminar = true;
			break;
		}
		if(iluminar){
			$(objetosAIluminar.dom[i]).colorBlend([{fromColor:"#171616", toColor:"#A7111F", param:"background-color", cycles:3}]);
		}
	}
}

/* FUNCIONES */
/* http://kevin.vanzonneveld.net/techblog/article/phpjs_licensing/ */
function empty (mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    
    var key;
    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        mixed_var === undefined
    ){
        return true;
    }
 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}