/*****************************************************************************/
/*                               2009 SeronLab                               */
/*                             JAVASCRIPT GENERAL                            */
/*****************************************************************************/

// VARIABLES
var general_usuario_identificado = false;
var general_usuario_nombre = '';

// PRECARGA DE IMAGENES
var preCargaImagenes = new Array();

function preCarga(rutaImagen) {
	preCargaImagenes.push(new Image());
	preCargaImagenes[preCargaImagenes.length-1].src = rutaImagen;
}

// FUNCIONES IMAGEN ROTATORIA
var img_rotatoria_act = 0;
var img_rotatoria_cantidad = 0;

function img_rotatoria_start(seccion, cantidad, contenedor) {
	img_rotatoria_act = 0;
	img_rotatoria_cantidad = cantidad;

	for(i=1; i<=img_rotatoria_cantidad; i++)
		preCarga('/img/portada/img0'+i+'.jpg');

	window.onload = img_rotatoria(seccion, contenedor);
}

function img_rotatoria(seccion, contenedor) {
	img_rotatoria_act++;
	if (img_rotatoria_act>img_rotatoria_cantidad) img_rotatoria_act = 1;
	$(contenedor).src = '/img/'+seccion+'/img'+( img_rotatoria_act < 10 ? '0' : '' )+img_rotatoria_act+'.jpg';
	setTimeout('img_rotatoria(\''+seccion+'\', \''+contenedor+'\')',5000);
}

// FUNCIONES
function redir(url){
	window.location.href = url;
}

function tiendaCantitadDisminuir(producto){
	var campo = $('pr'+producto);
	var cantidad = parseInt(campo.value);
	if (cantidad > 0) cantidad -= 1;
	campo.value = cantidad;
	tiendaCantitadSincronizar(producto, cantidad);
}

function tiendaCantitadAumentar(producto){
	var campo = $('pr'+producto);
	var cantidad = parseInt(campo.value);
	cantidad += 1;
	campo.value = cantidad;
	tiendaCantitadSincronizar(producto, cantidad);
}

function tiendaCantitadSincronizar(producto, cantidad){
	var hora = new Date().getTime();

	new Ajax.Request("/exec/ajax/producto_add.php", {
		parameters: {
			producto: producto,
			cantidad: cantidad,
			hora: hora
		},
		onSuccess: function(respuesta) {}
	});
}

var tiendaTemporizadorFicha;

function tiendaMostrarFicha(producto){
	tiendaTemporizadorFicha = setTimeout('tiendaCargarFicha('+producto+')', 300);
}

function tiendaOcultarFicha(){
	if (typeof tiendaTemporizadorFicha != 'undefined')
		clearTimeout(tiendaTemporizadorFicha);
	$('fichaProducto').hide();
}

function tiendaCargarFicha(producto){
	new Ajax.Request("/exec/ajax/producto_ficha.php", {
		parameters: {
			producto: producto
		},
		onSuccess: function(respuesta) {
			var DatosLeidos = respuesta.responseText.split('|||||');

			var imagenURL 			= DatosLeidos[0];
			var imagenAncho 		= DatosLeidos[1];
			var imagenAlto 			= DatosLeidos[2];
			var productoNombre 		= DatosLeidos[3];
			var productoDescripcion = DatosLeidos[4];

			$('fichaProductoImagen').update('<img src="/fotos_productos/'+imagenURL+'.jpg" style="width: '+imagenAncho+'px; height: '+imagenAlto+'px;">');
			$('fichaProductoNombre').update(productoNombre);
			$('fichaProductoDescripcion').update(productoDescripcion);

			var elemento = $('fila_'+producto);
			//var posTop = elemento.cumulativeOffset().top - $('fichaProducto').getHeight();
			//var posLeft = elemento.cumulativeOffset().left;
			var posTop = elemento.viewportOffset().top - $('fichaProducto').getHeight();
			var posLeft = elemento.viewportOffset().left;
			$('pruebas').update('scroll<br>top: '+elemento.cumulativeScrollOffset().top+' | left: '+elemento.cumulativeScrollOffset().left+'<br>offset<br>top: '+elemento.viewportOffset().top+' | left: '+elemento.viewportOffset().left);
			$('fichaProducto').setStyle({top: posTop+'px', left: posLeft+'px'});
			$('fichaProducto').show();
		}
	});
}

function actualizarEstadoUsuario(estado, usuario){
	if (estado == 'ON') {
		general_usuario_identificado = true;
		general_usuario_nombre = usuario;
		$('menu_usuario').update('Bienvenid@ '+usuario+' - <a href="javascript:void(0);" onclick="javascript:LoginDesconectar();">Desconectar</a>');
	} else if (estado == 'OFF') {
		general_usuario_identificado = false;
		$('menu_usuario').update('<a href="javascript:void(0);" onclick="javascript:LoginMostrar();">Login</a> - <a href="javascript:void(0);" onclick="javascript:RegistroMostrar();">Registro</a>');
	} else {
		return;
	}
}

function textoTratar(texto, tipo) {
	tipo = typeof tipo == "undefined" ? 0 : tipo;

	// VALORES DE: tipo
	//  0 : JavaScript a PHP
	//  1 : URL
	//  2 : Cuadro de texto
	//  3 : Cuadro de texto a PHP
	//  4 : A cuadro de texto

	if (tipo == 0 || tipo == 1) {
		// PROTECCION CONTRA CODIGO
		texto = strReplace(texto, 'javascript:', 'codigo_no_permitido');
		texto = strReplace(texto, '$(\'', 'codigo_no_permitido');
	}

	if (tipo == 0 || tipo == 2) {
		texto = strReplace(texto, '<', '&lt;');
		texto = strReplace(texto, '>', '&gt;');
	}

	if (tipo == 2 || tipo == 3) {
		texto = strReplace(texto, '\n', '<br>');
	}

	if (tipo == 4) {
		texto = strReplace(texto, '<br>', '\n');
	}

	if (tipo == 0 || tipo == 3) {
		// CAMBIOS PARA LOS ACENTOS
		texto = strReplace(texto, ':', '::');

		texto = strReplace(texto, 'á', ':acer:'); texto = strReplace(texto, 'Á', ':Acer:');
		texto = strReplace(texto, 'é', ':ecer:'); texto = strReplace(texto, 'É', ':Ecer:');
		texto = strReplace(texto, 'í', ':icer:'); texto = strReplace(texto, 'Í', ':Icer:');
		texto = strReplace(texto, 'ó', ':ocer:'); texto = strReplace(texto, 'Ó', ':Ocer:');
		texto = strReplace(texto, 'ú', ':ucer:'); texto = strReplace(texto, 'Ú', ':Ucer:');

		texto = strReplace(texto, 'à', ':aabi:'); texto = strReplace(texto, 'À', ':Aabi:');
		texto = strReplace(texto, 'è', ':eabi:'); texto = strReplace(texto, 'È', ':Eabi:');
		texto = strReplace(texto, 'ì', ':iabi:'); texto = strReplace(texto, 'Ì', ':Iabi:');
		texto = strReplace(texto, 'ò', ':oabi:'); texto = strReplace(texto, 'Ò', ':Oabi:');
		texto = strReplace(texto, 'ù', ':uabi:'); texto = strReplace(texto, 'Ù', ':Uabi:');

		texto = strReplace(texto, 'ä', ':adie:'); texto = strReplace(texto, 'Ä', ':Adie:');
		texto = strReplace(texto, 'ë', ':edie:'); texto = strReplace(texto, 'Ë', ':Edie:');
		texto = strReplace(texto, 'ï', ':idie:'); texto = strReplace(texto, 'Ï', ':Idie:');
		texto = strReplace(texto, 'ö', ':odie:'); texto = strReplace(texto, 'Ö', ':Odie:');
		texto = strReplace(texto, 'ü', ':udie:'); texto = strReplace(texto, 'Ü', ':Udie:');

		texto = strReplace(texto, 'â', ':afle:'); texto = strReplace(texto, 'Â', ':Afle:');
		texto = strReplace(texto, 'ê', ':efle:'); texto = strReplace(texto, 'Ê', ':Efle:');
		texto = strReplace(texto, 'î', ':ifle:'); texto = strReplace(texto, 'Î', ':Ifle:');
		texto = strReplace(texto, 'ô', ':ofle:'); texto = strReplace(texto, 'Ô', ':Ofle:');
		texto = strReplace(texto, 'û', ':ufle:'); texto = strReplace(texto, 'Û', ':Ufle:');

		texto = strReplace(texto, 'ñ', ':ntil:'); texto = strReplace(texto, 'Ñ', ':Ntil:');
		texto = strReplace(texto, 'ç', ':ctre:'); texto = strReplace(texto, 'Ç', ':Ctre:');

		texto = strReplace(texto, '´', ':cer:');
		texto = strReplace(texto, '`', ':abi:');
		texto = strReplace(texto, '¨', ':die:');
		texto = strReplace(texto, '^', ':fle:');

		texto = strReplace(texto, '¿', ':inta:');
		texto = strReplace(texto, '?', ':intc:');
		texto = strReplace(texto, '¡', ':exca:');
		texto = strReplace(texto, '!', ':excc:');

		texto = strReplace(texto, '·', '&middot;');
		texto = strReplace(texto, '€', '&euro;');
	}

	return texto;
}

function strReplace(cadena, original, cambio) {
	var cadArray = cadena.split(original);
	var tamArray = cadArray.size();
	var salida = cadArray[0];

	for (var i=1;i<tamArray;i++)
		salida = salida + cambio + cadArray[i];

	return salida;
}

function validarEmail(valor) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
		return true;
	} else {
		return false;
	}
}

function VentanaAbrir(titulo, contenido, ancho, marg_superior){
	marg_superior = typeof marg_superior == "undefined" ? 10 : marg_superior;
	var contenedor;
	var temporal = '';

	temporal += '<table border="0" cellspacing="1px" cellpadding="0" align="center" style="margin-top: '+marg_superior+'px; width: '+ancho+'px; background: #FFFFFF;">';
	temporal += '	<tr>';
	temporal += '		<td colspan="3" align="center" valign="middle">';
	temporal += '			<p style="padding: 3px; float: right; font-weight: bold; color: #FFFFFF;"><a href="javascript:void(0);" onclick="javascript:VentanaCerrar();" style="color: #FFFFFF;">X</a></p>';
	temporal += '			<p style="padding: 3px; background: #5f97b4; text-align: center; font-weight: bold; color: #FFFFFF;">';
	temporal += titulo;
	temporal += '			</p>';
	temporal += '		</td>';
	temporal += '	</tr>';
	temporal += '	<tr>';
	temporal += '		<td id="premios_visualizador" colspan="3" align="center" valign="middle"style="background: #aad7ee;">';
	temporal += contenido;
	temporal += '		</td>';
	temporal += '	</tr>';
	temporal += '</table>';

	// MOSTRAR EL CONTENIDO
	$('capa_ventana_laventana').update(temporal);
	$('capa_ventana').show();
}

function VentanaCerrar(){
	$('capa_ventana_laventana').update('');
	$('capa_ventana').hide();
}

function LoginMostrar(error, email){
	VentanaAbrir('SeronLab', '<p style="text-align: center; margin: 10px;">Cargando...</p>', 200);

	new Ajax.Request("/login", {
		parameters: {
			error: error,
			email: email
		},
		onSuccess: function(respuesta) {
			// TRATAR DATOS RECIBIDOS
			var DatosLeidos = respuesta.responseText.split('%%%2000%%%');
			var titulo 		= DatosLeidos[0];
			var contenido 	= DatosLeidos[1];

			// PROCESAR DATOS
			VentanaAbrir(titulo, contenido, 300);

			// FOCUS AL PRIMER CAMPO
			$('log_email').focus();
		}
	});
}

function LoginValidar(email, pass){
	// LECTURA DE VARIABLES DEL FORMULARIO
	email = typeof email == "undefined" ? $('log_email').value : email;
	pass = typeof pass == "undefined" ? $('log_pass').value : pass;

	// VENTANA DE PROCESANDO FORMULARIO
	VentanaAbrir('SeronLab', '<p style="text-align: center; margin: 10px;">Procesando datos...</p>', 200);

	// VALIDAR DATOS DEL FORMULARIO
	var errores_procesado = '';
	if (email == '' || pass == '')
		errores_procesado += (errores_procesado == '' ? '' : '_')+'0';
	if (!validarEmail(email))
		errores_procesado += (errores_procesado == '' ? '' : '_')+'1';

	// CONTROL DE ERRORES
	if (errores_procesado != '') {
		LoginMostrar(errores_procesado, email); return;
	}

	// PROCESAR FORMULARIO
	new Ajax.Request("/login/procesar", {
		parameters: {
			email: textoTratar(email),
			pass: textoTratar(pass)
		},
		onSuccess: function(respuesta) {
			if (respuesta.responseText.startsWith('error ')) {
				var cod_error = respuesta.responseText.sub('error ', '');
				LoginMostrar(cod_error, email); return;
			} else if (respuesta.responseText.startsWith('ok ')) {
				VentanaCerrar();
				actualizarEstadoUsuario('ON', respuesta.responseText.sub('ok ', ''));
			}
		}
	});
}

function LoginDesconectar(){
	new Ajax.Request("/login/desconectar", {
		parameters: {},
		onSuccess: function(respuesta) {
			VentanaCerrar();
			actualizarEstadoUsuario('OFF');
		}
	});
}

function RegistroMostrar(error, email, nombre, apellidos, fn_dia, fn_mes, fn_ano, pais, provincia, poblacion, cpostal, direccion, telefono, notificar){
	VentanaAbrir('SeronLab', '<p style="text-align: center; margin: 10px;">Cargando...</p>', 200);

	new Ajax.Request("/registro", {
		parameters: {
			error: error,
			email: textoTratar(typeof email == "undefined" ? '' : email),
			nombre: textoTratar(typeof nombre == "undefined" ? '' : nombre),
			apellidos: textoTratar(typeof apellidos == "undefined" ? '' : apellidos),
			fn_dia: fn_dia,
			fn_mes: fn_mes,
			fn_ano: fn_ano,
			pais: pais,
			provincia: textoTratar(typeof provincia == "undefined" ? '' : provincia),
			poblacion: textoTratar(typeof poblacion == "undefined" ? '' : poblacion),
			cpostal: cpostal,
			direccion: textoTratar(typeof direccion == "undefined" ? '' : direccion),
			telefono: telefono,
			notificar: notificar
		},
		onSuccess: function(respuesta) {
			// TRATAR DATOS RECIBIDOS
			var DatosLeidos = respuesta.responseText.split('%%%2000%%%');
			var titulo 		= DatosLeidos[0];
			var contenido 	= DatosLeidos[1];

			// PROCESAR DATOS
			VentanaAbrir(titulo, contenido, 390);

			// FOCUS AL PRIMER CAMPO
			$('reg_email').focus();
		}
	});
}

function RegistroValidar(){
	// LECTURA DE VARIABLES DEL FORMULARIO
	var email 		= $('reg_email').value;
	var pass1 		= $('reg_pass1').value;
	var pass2 		= $('reg_pass2').value;

	var nombre 		= $('reg_nombre').value;
	var apellidos 	= $('reg_apellidos').value;
	var fn_dia 		= $('reg_fecha_nacimiento_dia').value;
	var fn_mes 		= $('reg_fecha_nacimiento_mes').value;
	var fn_ano 		= $('reg_fecha_nacimiento_ano').value;

	var pais 		= $('reg_pais').value;
	var provincia 	= $('reg_provincia').value;
	var poblacion 	= $('reg_poblacion').value;
	var cpostal 	= $('reg_cpostal').value;
	var direccion 	= $('reg_direccion').value;
	var telefono 	= $('reg_telefono').value;

	var codigo 		= $('reg_codigo').value;

	var normas 		= $('reg_normas').checked;
	var notificar 	= $('reg_notificar').checked ? 1 : 0;

	// VENTANA DE PROCESANDO FORMULARIO
	VentanaAbrir('SeronLab', '<p style="text-align: center; margin: 10px;">Procesando datos...</p>', 200);

	// VALIDAR DATOS DEL FORMULARIO
	var errores_procesado = '';
	if (email == '' || pass1 == '' || pass2 == '' || nombre == '' || apellidos == '' || fn_dia == '' || normas == '' || codigo == '')
		errores_procesado += (errores_procesado == '' ? '' : '_')+'0';
	if (!validarEmail(email))
		errores_procesado += (errores_procesado == '' ? '' : '_')+'1';
	if (pass1 != pass2)
		errores_procesado += (errores_procesado == '' ? '' : '_')+'3';
	if (!normas)
		errores_procesado += (errores_procesado == '' ? '' : '_')+'4';

	// CONTROL DE ERRORES
	if (errores_procesado != '') {
		RegistroMostrar(errores_procesado, email, nombre, apellidos, fn_dia, fn_mes, fn_ano, pais, provincia, poblacion, cpostal, direccion, telefono, notificar); return;
	}

	// PROCESAR FORMULARIO
	new Ajax.Request("/registro/procesar", {
		parameters: {
			email: textoTratar(email),
			pass1: textoTratar(pass1),
			pass2: textoTratar(pass2),
			nombre: textoTratar(nombre),
			apellidos: textoTratar(apellidos),
			fn_dia: fn_dia,
			fn_mes: fn_mes,
			fn_ano: fn_ano,
			pais: pais,
			provincia: textoTratar(provincia),
			poblacion: textoTratar(poblacion),
			cpostal: cpostal,
			direccion: textoTratar(direccion),
			telefono: telefono,
			codigo: codigo,
			normas: normas ? 1 : 0,
			notificar: notificar
		},
		onSuccess: function(respuesta) {
			if (respuesta.responseText.startsWith('error ')) {
				var cod_error = respuesta.responseText.sub('error ', '');
				RegistroMostrar(cod_error, email, nombre, apellidos, fn_dia, fn_mes, fn_ano, pais, provincia, poblacion, cpostal, direccion, telefono, notificar); return;
			} else {
				VentanaAbrir('SeronLab', '<p style="text-align: center; margin: 10px;">Registro completado con éxito.</p>', 200);
			}
		}
	});
}
