$(document).ready(function(){

//inicializacao dos elementos
var animationEasing = "easeInOutSine";



/* -------------------------------------------------------------------------------------- */
/* -- USER DATA ------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

// This var will hold user data, after login
$.userData = null;

$.getUserData = function(handler){
	if ($.userData==null){
    $.get("services/users/GetUserData.aspx", "" , function(data, textStatus){
	    if (data.status.success){
	        $.userData = data.bodydata;
	        handler($.userData);
	    }else{
	        handler(null);
	    }
    }, "json");
	}else{
	    handler($.userData);
	}
}

$.setUserData = function(userData){
    $.userData = userData;
}

// change the page to show loogedin status
function loggedinHandler(userData){
    if (userData!=null){
        // update register panel
        $(".userLogInContent .name").text(userData.nickname);
		$(".userLogOutContent").fadeOut("slow");
		$(".userLogInContent").fadeIn("slow");
		$(".userRegisterCall .register").fadeOut("slow");
		$(".userRegisterCall .change").fadeIn("slow");
		
		//esconde os botoes invisiveis e fecha os paineis
		$(".hiddenRegisterConfig, .hiddenLoginConfig").hide();
		$(".hiddenChangeConfig").show();
		$(".userRegisterCall").animate({top: "0"}, animationEasing);
		if($(".userPanelAlign").height() > 175){
			$(".userPanelAlign").animate({height: $(".userPanelAlign").height() - 95}, animationEasing);
		}
		
		// check if it is the first time the user logs in
		if (userData.ultimoAcessoData==null){
		   	$("#formsFRM").attr("src", "utilizador/registo_bem_vindo.html");
			$(".formsFRMContainer").animate({height: 320}, "slow", animationEasing, function(){
				$("#formsFRM").fadeIn("slow");
			});
		}
		
        // say something to etea if it's loaded					
	    var iframedoc = ($("#contentFRM").contents())[0];
        var flashETea = iframedoc.getElementById("layoutBgImage");
        if (flashETea && typeof(flashETea.userCall) == "function") {
            flashETea.userCall();
        }
		
    }
}

$.getUserData(loggedinHandler);



// error to complete the link validation from the email
$.linkValidationError = function(){
	$("#formsFRM").attr("src", "utilizador/registo_ups.html");
	$(".formsFRMContainer").animate({height: 320}, "slow", animationEasing, function(){
		$("#formsFRM").fadeIn("slow");
	});
}











/* -------------------------------------------------------------------------------------- */
/* -- CONTROLA A ANIMACAO DOS PAINEIS ---------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */
function openPainelLogin(){
	$.updateHeightLoginStop();
	$(".hiddenRegisterConfig, .hiddenLoginConfig").hide();
	$(".userRegisterCall").animate({top: "150"}, animationEasing);
	$(".userPanelAlign").animate({height: $(".userPanelAlign").height() + 95}, animationEasing);
};
$.closePainelLogin = function(){
	$(".hiddenRegisterConfig, .hiddenLoginConfig").show();
	$(".userRegisterCall").animate({top: "0"}, animationEasing);
	if($(".userPanelAlign").height() > 175){
		$(".userPanelAlign").animate({height: $(".userPanelAlign").height() - 95}, animationEasing);
	}
};
function closePainelLoggedIn(){
	$.closePainelLogin();
	$(".hiddenLoginConfig").hide();
};

$(".hiddenBtRegister").hover(
	function(){$(".userRegisterCall .config").addClass("on");},
	function(){$(".userRegisterCall .config").removeClass("on");}
);
$(".hiddenBtRegister").click(function(event){
	event.preventDefault();
	//openPainelLogin();
});


$(".hiddenBtLogin").hover(
	function(){$(".userLogOutContent .title a").addClass("on");},
	function(){$(".userLogOutContent .title a").removeClass("on");}
);
$(".hiddenBtLogin").click(function(event){
	event.preventDefault();
	openPainelLogin();
});
$(".userLogOutContent .title a").click(function(event){
	event.preventDefault();
	$.closePainelLogin();
});


/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */





/* -------------------------------------------------------------------------------------- */
/* -- VALIDAÇÃO DO FORMULARIO DE LOGIN -------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

//Controla o show e o hidde das labes q estao em cima dos inputs
$(".formContainer input:text, .formContainer input:password").focus(function(){
	$(this).prev("label").hide();
});
$(".formContainer input:text, .formContainer input:password").blur(function(){
	if(!$(this).val()) $(this).prev("label").show();
});



// Validacao dos inputs obrigadtorios e submit do form
$("#formLogIn").validate({
	focusInvalid: false,
	highlight: false,
	onkeyup: false,
	errorPlacement: function(error, element) {
		error.appendTo( element.prev("label") );
	},
	errorElement: "span",
	errorClass: "alert",
	rules: {
		fldEmail: {required: true, email: true},
		fldPassword: {required: true, minlength: 6}
	},
	messages: {
		fldEmail: {required: "(obrigat&oacute;rio)", email: function(rule, element){$(element).prev("label").show().find("span.alert").html("(email inv&aacute;lido)");}},
		fldPassword: {required: "(obrigat&oacute;rio)",	minlength: function(){alert("A password tem que ter no mínimo 6 caracteres");}}
	},
	submitHandler: function(form){
		$.post("services/users/Login.aspx", $(form).serialize(), function(data, textStatus){
			$(".loading").fadeIn("slow");
			$(".userLogOutContent").fadeTo("slow", 0.11, function(){
				if(data.status.success){
				    $.userData = data.bodydata; // defined in script_user_login.js
					$(".loading").fadeOut("slow", function(){
					    $(".userLogInContent .name").text($.userData.nickname);
					    $(".userLogOutContent").fadeOut("slow");
						$(".userLogInContent").fadeIn("slow");
						$(".userRegisterCall .register").fadeOut("slow");
						$(".userRegisterCall .change").fadeIn("slow");
						$(".hiddenRegisterConfig, .hiddenLoginConfig").hide();
						$(".hiddenChangeConfig").show();
						$(".userRegisterCall").animate({top: "0"}, animationEasing);
						if($(".userPanelAlign").height() > 175){
							$(".userPanelAlign").animate({height: $(".userPanelAlign").height() - 95}, animationEasing);
						}
					});

                    // say something to etea if it's loaded					
				    var iframedoc = ($("#contentFRM").contents())[0];
                    var flashETea = iframedoc.getElementById("layoutBgImage");
                    if (flashETea && typeof(flashETea.userCall) == "function") {
                        flashETea.userCall();
                    }
					
				} else {
					$(".loading").fadeOut("slow", function(){
						$(".userLogOutContent").fadeOut("slow");
						$(".userErrorContent").fadeIn("slow");
					});
				}
			});
		}, "json");
	}
});

$(".formContainer a.submit").click(function(event){
	event.preventDefault();
	$("#formLogIn").validate();
	if($("#formLogIn").valid()){
		$("#formLogIn").submit();
	}
});


$(".userErrorContent a.tryagain").click(function(event){
	event.preventDefault();
	$(".userLogOutContent").fadeTo("fast", 1, function(){
		$(".userErrorContent").fadeOut("slow");
		$(".userLogOutContent").fadeIn("slow");
	});
});

$(".userErrorContent a.panelLink").click(function(event){
	event.preventDefault();
	$(".userLogOutContent").fadeTo("fast", 1, function(){
		$(".userErrorContent").hide();
		$(".userLogOutContent").show();
	});
});


/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */















});
