var ArchivoSubidoVar = false;
//var team_actual = 1;

// LOGIN
function showLogin()
{
	showBox('box');
	listenPressedKey(function(e) {
		if (e.keyCode == 13) checkLogin();
	});
}
function hideLogin()
{
	window.location.href = RUTA;
}
function checkLogin()
{
	if (!$F('LoginEmail')) {
		$('div_login_msg').innerHTML = MSG_LOGIN_COMPLETE_MAIL;
		$('LoginEmail').focus();
	} else if (!$F('LoginPassword')) {
		$('div_login_msg').innerHTML = MSG_LOGIN_COMPLETE_PASS;
		$('LoginPassword').focus();
	} else doLogin();
}
var login_sending = false;
function doLogin() 
{
	if (!login_sending) {
		var AJAX = new sack(RUTA+"app/ajax/login_post.php");
		AJAX.setVar("LoginEmail", $F('LoginEmail'));
		AJAX.setVar("LoginPassword", $F('LoginPassword'));
		AJAX.onCompletion = function() 
		{
			var v_result = AJAX.response.split("|");
			var result = v_result[0];
			if (result > 0) {
				$('div_login_msg').innerHTML = MSG_LOGIN_SUCCESS;
				setTimeout(function() {
					window.location = RUTA+"app/";
				}, 1000);
			} else {
				$('div_login_msg').innerHTML = MSG_LOGIN_FAIL;
			}
			login_sending = false;
		}
		$('div_login_msg').innerHTML = MSG_SENDING;
		login_sending = true;
		AJAX.runAJAX();
	} else {
		$('div_login_msg').innerHTML = MSG_SENDING_WAIT;
	}
}
var forgotPassw_sending = false;
function sendForgotPassword(lang) // lang : "es", "en"
{
	if ($F('LoginForgetEmail')) {
		if (!forgotPassw_sending) {
			$('div_forget_msg').update("");
			var AJAX = new sack(RUTA+"app/ajax/forgot_passw_post.php");
			AJAX.setVar("email", $F('LoginForgetEmail'));
			AJAX.onCompletion = function()
			{
				forgotPassw_sending = false;
				if (AJAX.response == "0") {
					$('div_forget_msg').update("Your password was correctly sent.");
				} else if (AJAX.response == "1") {
					$('div_forget_msg').update("An error occurs, please try again.");
				} else if (AJAX.response == "2") {
					$('div_forget_msg').update("Email is not valid.");
				}
			}
			forgotPassw_sending = true;
			AJAX.runAJAX();
		} else {
			$('div_forget_msg').update("Sending, wait please");
		}
	} else {
		$('div_forget_msg').update("Please, enter your Email.");
		$('LoginForgetEmail').focus();
	}
}

function getWindowHeight() {

	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

// LOGIN BOX:
function getWindowWidth() {

	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}
function centerBox(element){
 
 	element = $(element);

    var my_width  = getWindowWidth();
    var my_height = getWindowHeight();

    element.style.position = 'absolute';
    element.style.zIndex   = 999999999;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";

    element.style.display  = 'block';
}
function showBox(div){
	$('overlay').style.top = 0;
    $('overlay').style.height =  document.body.scrollHeight+"px";
	$('overlay').show();
    centerBox(div);
}
function hideBox(){
    $('box').hide();
    $('overlay').hide();
}

function listenPressedKey(func)
{
	var name = 'keypress';
	if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || document.detachEvent) {
	  name = 'keydown';
	}
	if (document.addEventListener) {
		if (document.keyPressedFunc) {
			document.removeEventListener(document.keyPressedFunc);
			document.keyPressedFunc = null;
		}
	    document.addEventListener(name, function(e) { func(e)}, false);
	} else if (document.attachEvent) {
		if (document.keyPressedFunc) {
			document.detachEvent(document.keyPressedFunc);
		}
	    document.attachEvent('on'+name, function(e) { func(e)});
	}
	document.keyPressedFunc = func;
}

function cambiar_idioma() {
	var idioma = $('idioma').value;
	//new Ajax.Request(RUTA+'estructura/idioma.php?team_actual='+team_actual, {
	new Ajax.Request(RUTA+'estructura/idioma.php', {
	method: 'post',
	parameters: 'idioma='+idioma,
	onComplete: function() {
		window.location.reload();
	}
	});
}

var contacto_enviando = false;

function msgContacto(msg) {
	document.getElementById('msg').style.display = "";
}

function enviar_contacto(){
	var error = false;
	$('mensaje_enviando').style.display = "none";
	$('mensaje_ok').style.display = "none";
	$('mensaje_error').style.display = "none";
		
	var nombreObj = $('nombre');
	var apellidoObj = $('apellido');
	var ciudadObj = $('ciudad');
	var paisObj = $('pais');
	var telefonoObj = $('telefono');
	var emailObj = $('email');
	var mensajeObj = $('mensaje');
	
	var texto = $('error_mensaje').innerHTML;
	
	if (nombreObj.value == "") {
		$('error_nombre').style.display = "inline";
		error = true;
	} else{
		$('error_nombre').style.display = "none";
	} 

	if (apellidoObj.value == "") {
		$('error_apellido').style.display = "inline";
		error = true;
	} else{
		$('error_apellido').style.display = "none";
	}
	
	if (telefonoObj.value == "") {
		$('error_telefono').style.display = "inline";
		error = true;
	} else{
		$('error_telefono').style.display = "none";
	}
	
	if (emailObj.value == "") {
		$('error_email').style.display = "inline";
		error = true;
	} else{
		if (!isEmail(emailObj.value)) {
			$('error_email').style.display = "none";
			$('email_invalido').style.display = "inline";
			error = true;
		}
		else{
			$('error_email').style.display = "none";
			$('email_invalido').style.display = "none";
		}
	}
	
	if (mensajeObj.value == "" || mensajeObj.value == texto) {
		mensajeObj.value = texto;
		error = true;
	} 
	
	if(!error){
		contacto_send(nombreObj.value, apellidoObj.value, ciudadObj.value, paisObj.value, telefonoObj.value, emailObj.value, mensajeObj.value);
	}
}

function contacto_send(A,B,C,D,E,F,G){
	if (!contacto_enviando) {
		var AJAX = new sack(RUTA+"mails/enviar_contacto.php");
		AJAX.setVar("nombre", A);
		AJAX.setVar("apellido", B);
		AJAX.setVar("ciudad", C);
		AJAX.setVar("pais", D);
		AJAX.setVar("telefono", E);
		AJAX.setVar("email", F);
		AJAX.setVar("mensaje", G);
		AJAX.onCompletion = function() {
			var v_result = AJAX.response.split("|");
			var result = v_result[0];
			if (result) {
				$('mensaje_enviando').style.display = "none";
				$('mensaje_error').style.display = "none";
				$('mensaje_ok').style.display = "inline";
				borrar_formulario();
			} else {
				$('mensaje_error').style.display = "inline";
			}
			contacto_enviando = false;
		}
		$('mensaje_enviando').style.display = "inline";
		contacto_enviando = true;
		AJAX.runAJAX();
	} else {
		$('mensaje_enviando').style.display = "inline";
	}
}

function borrar_formulario(){
	$('nombre').value = "";
	$('apellido').value = "";
	$('ciudad').value = "";
	$('pais').value = "";
	$('telefono').value = "";
	$('email').value = "";
	$('mensaje').value = "";
}

function isEmail(str)
{
	var filtro = /^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z0-9_.-]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (filtro.test(str))
		return true;
	else
		return false;
}

// Validate decimal numbers between 0 and 100, with 2 decimal places.
function isValidNumber(num)
{
	var filtro = /^100$|^[0-9]{1,2}$|^[0-9]{1,2}\.[0-9]{1,2}$/;
	if (filtro.test(num))
		return true;
	else
		return false;
}

// Retorna un entero con la edad,  o false en caso de que la fecha sea incorrecta o mayor que el dia actual.
function getAge(anio, mes, dia)
{
    //calculo la fecha de hoy
    var hoy = new Date();
    // Compruebo que los anio, mes, dia son correctos
    if (isNaN(anio) || isNaN(mes) || isNaN(dia)) {
		return false;
	}
	anio = parseInt(anio);
	mes = parseInt(mes);
	dia = parseInt(dia);
    // Resto los años de las dos fechas
    var edad = hoy.getFullYear() - anio - 1; // -1 porque no se si ha cumplido años ya este año
    //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido
    if (hoy.getMonth() + 1 - mes < 0) { // + 1 porque los meses empiezan en 0
       return edad;
	}
    if (hoy.getMonth() + 1 - mes > 0) {
       return edad + 1;
	}
    // Entonces es que eran iguales. miro los dias
    // Si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido
    if ((hoy.getUTCDate() - dia) >= 0) {
       return edad + 1;
	}
    return edad;
}

function is_date(date_string)
{
	// matches DD/MM/Y or DD/MM/YYYY or D/M/Y or DD/M/YYYY Leap years treated.
	reg_expr = /^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$/;
	if (!reg_expr.test(date_string)) {
		return false;
	}
	return true;
}

var curriculum_enviando = false;
function enviar_curriculum(){
	var error = false;
	var nombreObj = $('nombreCurriculum');
	if(nombreObj.value == ""){
		$('error_nombreCurriculum').style.display = "inline";
		error = true;
	}
	else{
		$('error_nombreCurriculum').style.display = "none";
	}
	if(!ArchivoSubidoVar){
		$('error_archivo').style.display = "inline";
		error = true;
	}
	else{
		$('error_archivo').style.display = "none";
	}
	if(!error){
		$('forCurriculum').submit();
	}
}
function ArchivoSubido() {
	
	ArchivoSubidoVar = true;
}

function resultadoSend(estado) {
	switch(estado){
		//Formato de archivo invalido
		case -1: if($('curriculum_ok')) $('curriculum_ok').style.display = "none";
				 if($('curriculum_enviando')) $('curriculum_enviando').style.display = "none";
				 if($('curriculum_error')) $('curriculum_error').style.display = "none";
				 if($('curriculum_archivo')) $('curriculum_archivo').style.display = "inline";
				 break;
		
		//No se envio el mail
		case 0 : if($('curriculum_archivo')) $('curriculum_archivo').style.display = "none";
				 if($('curriculum_enviando')) $('curriculum_enviando').style.display = "none";
				 if($('curriculum_ok')) $('curriculum_ok').style.display = "none";
				 if($('curriculum_error')) $('curriculum_error').style.display = "inline";
				 break;
				 
		//El curriculum se mando OK
		case 1 : if($('curriculum_error')) $('curriculum_error').style.display = "none";
				 if($('curriculum_enviando')) $('curriculum_enviando').style.display = "none";
				 if($('curriculum_archivo')) $('curriculum_archivo').style.display = "none";
				 if($('curriculum_ok')) $('curriculum_ok').style.display = "inline";
				 break;
				 
		//Se está enviando		 
		case 2 : if($('curriculum_ok')) $('curriculum_ok').style.display = "none";
				 if($('curriculum_error')) $('curriculum_error').style.display = "none";
				 if($('curriculum_archivo')) $('curriculum_archivo').style.display = "none";
				 if($('curriculum_enviando')) $('curriculum_enviando').style.display = "inline";
				 break;
	}
}