$(document).ready(function() {
	initCasino();
	initMDSClub();
	initJuegos();
});

var juegos_expanded = new Array();
function initCasino() {
	/*
	 * Para IE6/IE7
	 */
	corregirPosiciones();
	
	/*
	 * Activa el efecto de luz al pasar el mouse
	 * por encima de las imágenes especificadas.
	 */
	$("#carrusel img").bind('mouseenter', function(e) {
		var temp = $(this).attr('src');
		$(this).attr('src', $(this).attr('alt')).attr('alt', temp);
	});

	$("#carrusel img").bind('mouseleave', function(e) {
		var temp = $(this).attr('src');
		$(this).attr('src', $(this).attr('alt')).attr('alt', temp);
	});
	
	/*
	 * Lo mismo para la imagen de inscripción al Club MDS
	 * (usamos la función setFading() en vez de hacerlo a mano,
	 * en este caso se puede porque son links y no imágenes solas,
	 * además que nose requieren acciones adicionales).
	 */
	forceFading("#mds-club", 0.5);
	forceFading("#entrada-1click", 0.5);
	
	setFading("#imagenes_y_noticias tr td.imagenes div div#caja-imagenes", 0.5);
	setFading("#imagenes_y_noticias tr td.juegos div div#caja-juegos", 0.5);
	setFading("#imagenes_y_noticias tr td.eventos div > *", 0.5);
	
	

	var jackpotLink = $("#jackpot-ver_todos");
	
	if (!jackpotLink.length) { // Si el link "ver todos" no está habilitado en el botón de jackpot
		forceFading("#jackpot", 0.5);
	
		$("#jackpot").click(function() {
			top.location.href = "index.php?seccion=casino&subseccion=jackpot";
		}).css({ 'cursor' : 'pointer' });
	}
	
	/*
	 * Definiciones para los elementos expansibles de las categorías
	 * de juegos (sección "Juegos").
	 */
	$("#casino-juegos-categorias_de_juegos div.juego div.titulo").click(function(e) {
		var arrowArriba = "imagenes/casino/juegos/arrow-arriba.jpg";
		var arrowAbajo = "imagenes/casino/juegos/arrow-abajo.jpg";
		
		e.preventDefault();
		
		var id_padre = $(this).parent().attr('id');
		var informacion = $("#" + id_padre + " div.informacion");
		var expansion = $("#" + id_padre + " div.titulo span.expansion");
		var img = $(this).children(0);

		var i = 0, found = false;
		while(i < juegos_expanded.length && !found) {
			if (juegos_expanded[i] == id_padre) found = true;
			i++;
		}
		
		if (!found) { // Elemento cerrado. Se abre.
			juegos_expanded.push(id_padre);
			
			expansion.html("[-]");
			informacion.show('fast');
			
			if (img.attr('src') == arrowAbajo) {
				img.attr('src', arrowArriba);
			}
		}
		else { // Elemento abierto. Se cierra.
			juegos_expanded.splice(i-1, 1);
			
			expansion.html("[+]");
			informacion.hide('fast');
			
			if (img.attr('src') == arrowArriba) {
				img.attr('src', arrowAbajo);
			}
		}
	});
	
	forceFading(".jackpot-button img", 0.5);
}

function corregirPosiciones() {
	var aumento = 5; /* Píxeles que deben aumentarse en IE para valores del Jackpot */
	
	var temp, tempTop;
	if (navigator.appName == "Microsoft Internet Explorer") {
		if (getIEVersionNumber() < 8) {
			/*
			 * Fixes para IE6/IE7
			 */
			$("#eventos").css({
				'left' : $(this).offset().left - 160
			});
			
			$("#jackpot div#jackpot-mayor_pozo span").each(function() {
				corregirPosicionesAddTop($(this), aumento);
			});
			
			//corregirPosicionesAddTop($("#links-anexos"), 10);
		}
		else {
			/*
			 * Fixes exclusivos para IE8 y superiores
			 */
			//corregirPosicionesAddTop($("#links-anexos"), 5);
		}
	
		
		/*
		 * Fixes en general para Internet Explorer
		 */
		$("div.ventana div.body table").css({ 'height' : '133px' });
	}
}


function corregirPosicionesAddTop(obj, aumento) {
	var tempDir = parseInt(obj.css('top').replace('px', ''), 10);
	var newPos = parseInt(tempDir + aumento, 10) + 'px';
	
	obj.css({
		'top' : newPos
	});
}

function corregirPosicionesAddLeft(obj, aumento) {
	var tempDir = parseInt(obj.css('left').replace('px', ''), 10);
	var newPos = parseInt(tempDir + aumento, 10) + 'px';
	
	obj.css({
		'left' : newPos
	});
}


/*
 * Funciones para MDS Club
 */
function initMDSClub() {
	var formulario_inscripcion = $("#club_mds-formulario_inscripcion");
	var preForm = "#" + formulario_inscripcion.attr('id') + " ";
	
	if (formulario_inscripcion) {
		formulario_inscripcion.bind('submit', function(e) {
			e.preventDefault(); // Evita que se envíe el formulario de la forma común
			
			var nombre = preForm + "input[name=nombre]";
			nombre = $(nombre).val();

			var apellido = preForm + "input[name=apellido]";
			apellido = $(apellido).val();
			
			var rut = preForm + "input[name=rut]";
			rut = $(rut).val();

			var fn_dia = preForm + "select[name=fecha_nacimiento-dia]";
			fn_dia = $(fn_dia).val();
			
			var fn_mes = preForm + "select[name=fecha_nacimiento-mes]";
			fn_mes = $(fn_mes).val();

			var fn_anyo = preForm + "select[name=fecha_nacimiento-anyo]";
			fn_anyo = $(fn_anyo).val();
			
			var email = preForm + "input[name=email]";
			email = $(email).correo();
			
			var telefono_contacto = preForm + "input[name=telefono_contacto]";
			telefono_contacto = $(telefono_contacto).val();

			var ocupacion = preForm + "input[name=ocupacion]";
			ocupacion = $(ocupacion).val();
			
			var direccion = preForm + "textarea[name=direccion]";
			direccion = $(direccion).val();
			
			if (!nombre.length) alert("Debe ingresar su nombre.");
			else if (!apellido.length) alert("Debe ingresar su apellido.");
			else if (!rut.length || !validacion_rut(rut)) alert("Debe ingresar su RUT correctamente.");
			else if (!checkDate(fn_dia, fn_mes, fn_anyo)) alert("Su fecha de nacimiento es incorrecta.");
			else if (!email) alert("Debe ingresar un correo electrónico correcto.");
			else if (!validarTelefono(telefono_contacto)) alert("Su teléfono de contacto no es válido.");
			else if (!ocupacion.length) alert("Debe ingresar su profesión u ocupación.");
			else if (!validarDireccion(direccion)) alert("Debe ingresar su dirección correctamente.");
			else {
				enviarMDS();
			}
		});
	}
	
	$("#club_mds-formulario_inscripcion select[name=region]").change(function() {
		cambiarComunas();
	});
	cambiarComunas();
}

function cambiarComunas() {
	var regiones = $("#club_mds-formulario_inscripcion select[name=region]");
	var comunas = $("#club_mds-formulario_inscripcion select[name=comuna]");
	
	if (regiones.length && comunas.length) {
		var url = $("#club_mds-formulario_inscripcion").attr('action');
		var data = "seleccion_region=" + regiones.val();
		
		$.get(url, data, function(respuesta) {
			comunas.html(respuesta);
		}, 'text');
	}
}

function enviarMDS() {
	/*
	 * Habilitar eventos de aviso cuando se está enviando (usabilidad).
	 */
	
	$("#mds_club-formulario_inscripcion-procesamiento").css({
		'visibility' : 'visible'
	});
	
	$("#mds_club-formulario_inscripcion-enviar").css({
		'visibility' : 'hidden'
	});
	
	/*
	 * Envío de los datos (AJAX).
	 */
	var url = $("#club_mds-formulario_inscripcion").attr('action');
	var data = $("#club_mds-formulario_inscripcion").serialize();
	data += "&ajaxSend=true";
	
	
	$.post(url, data, enviadoMDS, 'text');
}

function enviadoMDS(texto) {
	/*
	 * Avisar que la operación ha concluído (usabilidad).
	 */
	if (texto == "OK") {
	    var mensaje = "¡Gracias por Unirte a nuestro Club MDS!\n\n";
	    mensaje += "Dentro de 48 hrs. se le enviará un correo electrónico de confirmación de su inscripción,\n";
	    mensaje += "luego usted podrá retirar su tarjeta de Socio y un Voucher de cortería para 1 trago\n";
	    mensaje += "en la Barra del Casino.\n\n";
	    mensaje += "Restricciones:\n";
	    mensaje += "- Válido sólo para nuevos Socios.\n";
	    mensaje += "- Voucher de cortesía válido para 1 semana después de la inscripción.";

	    alert(mensaje);

		$("#club_mds-formulario_inscripcion").each(function() {
			this.reset();
		});
		
		$("#mds_club-formulario_inscripcion-procesamiento").css({
			'visibility' : 'hidden'
		});
		
		$("#mds_club-formulario_inscripcion-enviar").css({
			'visibility' : 'visible'
		});
	}
	else if (texto == "ERROR" || texto == "") {
		alert('Error al enviar la inscripción.\nIntenta nuevamente.');

		$("#mds_club-formulario_inscripcion-procesamiento").css({
			'visibility' : 'hidden'
		});
		
		$("#mds_club-formulario_inscripcion-enviar").css({
			'visibility' : 'visible'
		});
	}
	else if (texto == "EXISTS") {
		alert('Su correo electrónico y/o RUT ya se encuentran registrados.');

		$("#mds_club-formulario_inscripcion-procesamiento").css({
			'visibility' : 'hidden'
		});
		
		$("#mds_club-formulario_inscripcion-enviar").css({
			'visibility' : 'visible'
		});
	}
}

function verificar_forma_rut(rut) {
	var caracteres = "0123456789Kk.-";
	
	var rutLength = rut.length;
	var i = 0;
	while(i < rutLength) {
		if (caracteres.indexOf(rut.toLowerCase().charAt(i)) == -1) return false;
		i++;
	}

	return true;
}

function validacion_rut(rut) {
	if (!verificar_forma_rut(rut)) return false;
	
	var datos = rut.split('-');
	if (datos.length != 2) return false;
	
    datos[0]=datos[0].split('.').join('');
	datos[1]=datos[1].split('-').join('');
	
	var texto = datos[0];
	var letra = datos[1];
	
	letra = letra.toUpperCase();
	
	if (texto != "") {
		if (texto.length < 4){
		    texto = "";
			letra = "";
			return false;
		} 
		else if (!Val_Rut(texto, letra)){
			texto.value = "";
			letra.value = "";
			return false;
		}
		else return true;
	}
	return false;
}


function Val_Rut(texto, letra){
	var l, i, k, c, suma = 0, str = "", rut;

	rut = texto + "-" + letra;
	
	if ((rut.length < 8) || (rut.length > 10)) return false;

	if (texto < 500000) return false;
	
	if (texto == "") return true;

	c = "32765432765432";
	
	for (i = 0; i <= texto.length; i++) {
		if (texto.charAt(i) != "." || texto.charAt(i) != "") str = str + texto.charAt(i);
	}

	texto = str;
	
	for (j = texto.length; j > 0; j--) {
        i = texto.substring(j-1, j);
        p = c.substring(c.length - 1, c.length);
        suma = suma + (p*i);
        c = c.substring(0, c.length - 1);
	}

	i = 0;
	suma = 11 - (suma%11);
	if (suma == 10) ch = "K";
	else {
		if (suma==11) suma = 0;
		
		ch = suma;
	}

	if (ch == letra.toUpperCase()) return true;
	
	return false;
}

function validarTelefono(telefono) {
	while (telefono.indexOf(" ") != -1) telefono = telefono.replace(" ", "");
	
	var tempFono = parseInt(telefono, 10);
	if (tempFono != telefono) return false;
	
	var numeros = "0123456789", caracter;
	
	if (telefono.length < 7) return false;
	
	var numLength = telefono.length, i = 0;
	while(i < numLength) {
		caracter = telefono.charAt(i);
		
		if (numeros.indexOf(caracter) == -1) return false;
		
		i++;
	}
	
	return true;
}

function validarDireccion(direccion) {
	if (!direccion.length) return false;
	
	var tempDireccion = direccion;
	while (tempDireccion.indexOf(".") != -1) tempDireccion = tempDireccion.replace(".", "");
	while (tempDireccion.indexOf(",") != -1) tempDireccion = tempDireccion.replace(",", "");
	while (tempDireccion.indexOf("-") != -1) tempDireccion = tempDireccion.replace("-", "");
	while (tempDireccion.indexOf("/") != -1) tempDireccion = tempDireccion.replace("/", "");
	while (tempDireccion.indexOf(" ") != -1) tempDireccion = tempDireccion.replace(" ", "");
	while (tempDireccion.indexOf("\n") != -1) tempDireccion = tempDireccion.replace("\n", "");
	while (tempDireccion.indexOf("\b") != -1) tempDireccion = tempDireccion.replace("\b", "");
	while (tempDireccion.indexOf("\t") != -1) tempDireccion = tempDireccion.replace("\t", "");
	
	if (tempDireccion.length < 5) return false;
	
	return true;
}


/*
 * Funciones para el selector de términos en Juegos
 */
function initJuegos() {
	var obj = $("#glosario_de_terminos tr td.descripciones div.descripcion_termino");
	var lista = $("#glosario_de_terminos tr td.seleccion select#glosario_de_terminos-seleccion");
	var html = "";
	
	var i = 1;
	
	obj.each(function() {
		if (i == 1) {
			$(this).show(0);
		}
		
		$(this).attr('id', 'glosario_de_terminos-termino_' + i);
		
		if (i == 1) html += "<option value=\"" + $(this).attr('id') + "\" selected>" + $(this).children(0).html() + "</option>";
		else html += "<option value=\"" + $(this).attr('id') + "\">" + $(this).children(0).html() + "</option>"; 

		i++;
	});
	
	lista.html(html);
	
	lista.change(function() {
		var id = $(this).val();
		
		obj.each(function() {
			$(this).hide(0);
		});
		
		$("#" + id).show('slow');
	});
}