$(document).ready(function(){

//inicializacao dos elementos
var animationEasing = "easeOutSine";






/* -------------------------------------------------------------------------------------- */
/* -- USER DATA ------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

// if the user is logged in fills the form with the current data
function registerFormHandler(userData){
    if (userData==null){
        return;
    }
    
    $("#fldName").attr("value",userData.nome);
    $("#fldNickname").attr("value",userData.nickname);
    $("#fldEmail").attr("value",userData.email);
    $("#fldTelefone").attr("value",userData.telefone);
    $("#fldMorada").attr("value",userData.morada);
    $("#fldCodPostal4").attr("value",userData.codigoPostal1);
    $("#fldCodPostal3").attr("value",userData.codigoPostal2);
    $("#fldLocalidade").attr("value",userData.localidade);

    if (userData.newsletter=='0'){
        $("#fldNewsletter").attr("checked","");
    }else{
        $("#fldNewsletter").attr("checked","checked");
    }

    if (userData.autorizacao=='0'){
        $("#fldUtilizacao").attr("checked","");
    }else{
        $("#fldUtilizacao").attr("checked","checked");
    }
    
    if (userData.sexo=='M'){
        $("#fldSexoMasculino").attr("checked","checked");
    }

    if (userData.sexo=='F'){
        $("#fldSexoFeminino").attr("checked","checked");
    }
    
    // prefered tea
    var idx;
    var favTea = [];
    $("#fldConfChaPreferido option").each( function(i,item) {
        favTea[i] = $(item).text();
    });
    idx = $.inArray(userData.chaPreferido, favTea);
    if (idx>=0) {
        $("#fldConfChaPreferido")[0].selectedIndex = idx;
    }
    
    // birth date
    var bYear = [];
    var yIdx, mIdx, dIdx;
    if (userData.dataAAAA!=null){
        $("#fldAno option").each( function(i,item) {
            bYear[i] = $(item).text();
        });
        yIdx = $.inArray(userData.dataAAAA, bYear);
        if (yIdx >= 0){
            mIdx = parseInt(userData.dataMM, 10);
            if ( mIdx > 0 ){
                dIdx = parseInt(userData.dataDD, 10);
                if ( dIdx > 0 ){
                    $("#fldAno")[0].selectedIndex = yIdx;
                    $("#fldMes")[0].selectedIndex = mIdx;
                    $("#fldDia")[0].selectedIndex = dIdx;
                }
            }
        }
    }
    
    // user photo
    var imgBasePath = "../images/utilizador/";
    if (userData.foto.length==0){
        switch (userData.sexo){
            case "F":
                $(".containment img").attr("src", imgBasePath + "register_user_girl.gif");
            break;
            case "M":
                $(".containment img").attr("src", imgBasePath + "register_user_boy.gif");
            break;
            default:
                $(".containment img").attr("src", imgBasePath + "register_user_no_sex.gif");
            break;
        }
    }else{
        $(".containment img").attr("src", userData.foto);
    }

}

parent.$.getUserData(registerFormHandler);











/* -------------------------------------------------------------------------------------- */
/* -- CONTROLA O ACORDEON DO REGISTO ---------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

$(".registerPanelStep:not(.active) .container .content").fadeTo("fast", 0);
var containterWidth = 841;
var containerStepsLength = $(".registerPanelStep").length * 117;
var containerWrapFinal = containterWidth+containerStepsLength+2;
$(".registerPanelStep").each(function(i){
	$(this).find(".controlSteps").click(function(event){
		event.preventDefault();	
		($(this).is(".back")) ? n=i-1 : n=i+1;	
		$(".registerPanelStep:eq("+i+")").find(".container .content").fadeTo("slow", 0, function(){
			$(this).css({'display':'none'}).parent().animate({width:'1'}, "slow", animationEasing, function (){
				$(this).hide();
			});
			$(".registerPanelContent").animate({width: containerWrapFinal}, "slow", animationEasing);
			$(".registerPanelStep:eq("+n+")").find(".container").show().animate({width: containterWidth}, "slow", animationEasing, function(){
				$(".registerPanelStep:eq("+n+")").find(".number").removeClass("off inactive");
				$(".registerPanelStep:lt("+n+")").find(".number").addClass("inactive");
				$(".registerPanelStep:gt("+n+")").find(".number").addClass("off");
				$(this).find(".content").css({'display':'block'}).fadeTo("slow", 1);
			});
		});
	});
});

/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */






/* -------------------------------------------------------------------------------------- */
/* -- MANIPULACAO DA IMAGEM ------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

//Image Config
var elmImg = $(".userPhtResize .pht img");
var elmMask = $(".userPhtResize .pht");
var elmImgWidth = elmImg.width();
var elmImgHeight = elmImg.height();

function updateElem(){
	elmImg = $(".userPhtResize .pht img");
	elmMask = $(".userPhtResize .pht");
	elmImgWidth = elmImg.width();
	elmImgHeight = elmImg.height();
}

function updateContainment(){
	//Update da largura e altura do containment
	$(".containment").css({
		width: elmImg.width()*2-elmMask.width(),
		height: elmImg.height()*2-elmMask.height(),
		left: -elmImg.width()+elmMask.width(),
		top: -elmImg.height()+elmMask.height()
	});
	//Update do center da imagem
	elmImg.css({
		top: $(".containment").height()/2-elmImg.height()/2,
		left: $(".containment").width()/2-elmImg.width()/2
	});
}

//Activa o Slider do Zoom
$(".size .slider").slider({
	range: "min",
	value: 100,
	min: 50,
	max: 150,
	slide: function(event, ui) {
		$(".sizeResult").html(ui.value + '%');
		$(".userPhtResize .pht img").width(elmImgWidth*ui.value/100);
		$(".userPhtResize .pht img").height(elmImgHeight*ui.value/100);
		updateContainment();
	}
});


/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */







/* -------------------------------------------------------------------------------------- */
// -- CONTROLA O TIPO DE IMAGEM DO USER # UPLOAD DA PHOTO ------------------------------- */
/* -------------------------------------------------------------------------------------- */

var imgType = "";
if($(".formContainer [name='fldImageType']").val() != ""){
	imgType = $(".formContainer [name='fldImageType']").val();
}else{
	imgType = "nosex";
}

var userPicNoSex = "<img src='../images/utilizador/register_user_no_sex.gif' width='108' height='112' alt='' />";
var userPicBoy = "<img src='../images/utilizador/register_user_boy.gif' width='108' height='112' alt='' />";
var userPicGirl = "<img src='../images/utilizador/register_user_girl.gif' width='108' height='112' alt='' />";
//var userPicCustom =	"<img src='../images/utilizador/_original_user_pht.jpg' width='580' height='435' alt='' />";

$("#fldSexoMasculino").click(function(){
	lastImgType = "boy";
	if(imgType != "custom"){		
		imgType = "boy";
		$(".containment img").replaceWith(userPicBoy);
		updateElem();
		updateContainment();
	}
});
$("#fldSexoFeminino").click(function(){
	lastImgType = "girl";
	if(imgType != "custom"){		
		imgType = "girl";
		$(".containment img").replaceWith(userPicGirl);
		updateElem();
		updateContainment();
	}
});

function refreshPhotoConfig(){
	lastImgType = imgType;
	imgType = "custom";
	//$(".containment img").replaceWith(userPicCustom);
	updateElem();
	updateContainment();
	elmImg.draggable({cursor: 'move', containment: '.containment'});
	$(".size .slider").slider('value' , 100);
	$(".sizeResult").html('100%');
	$(".controlLabel, .controlSlider, .removePhoto").fadeIn("slow");
}



/* UPLOAD PHOTO */
new Ajax_upload('#uploadPhoto', {
	action: '../services/users/PhotoUpload.aspx',
	responseType:'json',
	data : {
		'key1' : "This data won't",
		'key2' : "be send because",
		'key3' : "we will overwrite it"
	},
	onSubmit : function(file , ext){
		//if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
		if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
			/* Setting data */
			this.setData({
				'key': 'This string will be send with the file'
			});
			$(".userPhtResize .loading").fadeIn("slow");
			//$('#example2 .text').text('Uploading ' + file);	
		} else {
			// extension is not allowed
			alert("Erro: só é permitido o upload de imagens");
			//$('#example2 .text').text('Error: only images are allowed');
			// cancel upload
			return false;				
		}
	},
	onComplete : function(file, data){
		if(data && data.status.success){
        	$(".formContainer [name='fldImageUrl']").val(data.bodydata.src);
			$(".containment img").attr({src: data.bodydata.src, width: data.bodydata.width, height: data.bodydata.height}).load(function(){
				refreshPhotoConfig();
			});
		} else {
			//ERROS DE SERVIDOR
			alert("Ocorreu uma anomalia, por favor tente de novo.");
		}
		$(".userPhtResize .loading").fadeOut("slow");
	}		
});


$(".controlConfig .removePhoto").click(function(){
	switch(lastImgType){
		case 'boy':
			imgType = "boy";
			$(".containment img").replaceWith(userPicBoy);
			break;
		case 'girl':
			imgType = "girl";
			$(".containment img").replaceWith(userPicGirl);
			break;
		default:
			imgType = "nosex";
			$(".containment img").replaceWith(userPicNoSex);
	}
	updateElem();
	updateContainment();
	$(".controlLabel, .controlSlider, .removePhoto").fadeOut("slow");
});


/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */






/* -------------------------------------------------------------------------------------- */
/* -- CONSTRUCAO DA CONFIRMACAO DO FORMULARIO ------------------------------------------- */
/* -------------------------------------------------------------------------------------- */

function constructConfirmation(){
	$(".confirmContainer .data").each(function(){
		switch($(this).attr("title")){
			case 'fldSexo':
				$(this).html($(".formContainer [name="+$(this).attr('title')+"]:checked").val());
				break;
			case 'fldNewsletter':
			case 'fldUtilizacao':
				($(".formContainer [name="+$(this).attr('title')+"]").is(":checked")) ? $(this).html($(".formContainer [name="+$(this).attr('title')+"]").val()) : $(this).html("N&atilde;o");
				break;
			default:
				$(this).html($(".formContainer [name="+$(this).attr('title')+"]").val());
		}
	});
	
	//Valores para o crop da imagem
	$(".formContainer [name='fldImageType']").val(imgType);
	$(".formContainer [name='fldImageTop']").val(Math.abs(Math.round($(".containment").position().top + elmImg.position().top)));
	$(".formContainer [name='fldImageLeft']").val(Math.abs(Math.round($(".containment").position().left + elmImg.position().left))); 
	$(".formContainer [name='fldImageHeight']").val(elmImg.height());
	$(".formContainer [name='fldImageWidth']").val(elmImg.width());
	$(".formContainer [name='fldImageCropWidth']").val(elmMask.width());
	$(".formContainer [name='fldImageCropHeight']").val(elmMask.height());
		
		
	//Clone da imagem para a confirmacao
	$(".confirmPht .containment").replaceWith($(".pht .containment").clone());
	
	//alert($("form").serialize());
}

/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */






/* -------------------------------------------------------------------------------------- */
/* -- VALIDAÇÃO DO FORMULARIO DE REGISTO ------------------------------------------------ */
/* -------------------------------------------------------------------------------------- */

//Controla o show e o hidde das labes q estao em cima dos inputs
$(".formContainer input:text, .formContainer input:password").each(function(){
	if($(this).val() != ""){$(this).prev("label").hide();}
});
$(".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

$(".dataNascimento select").change(function(){
	$("#fldDataNascimento").val($("#fldDia").val() + $("#fldMes").val() + $("#fldAno").val());
});

$("#form1").validate({
	focusInvalid: false,
	highlight: false,
	onkeyup: false,
	errorPlacement: function(error, element) {
		error.appendTo( element.prev("label") );
	},
	errorElement: "span",
	errorClass: "alert",
	rules: {
		fldName: {required: true},
		fldNickname: {required: true},
		fldEmail: {required: true, email: true},
		fldPassword: {required: true, minlength: 6},
		fldConfPassword: {required: true, equalTo: "#fldPassword"},
		fldDataNascimento: {minlength: 9},
		fldCodPostal4: {digits: true, minlength: 4},
		fldCodPostal3: {digits: true, minlength: 3}, 
		fldTelefone: {digits: true, minlength: 9}
	},
	messages: {
		fldName: {required: "(obrigat&oacute;rio)"},
		fldNickname: {required: "(obrigat&oacute;rio)"},
		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");}},
		fldConfPassword: {required: "(obrigat&oacute;rio)",	equalTo: function(){alert("As passwords não coincidem");}},
		fldDataNascimento: {minlength: function(){alert("A data de nascimento está incompleta");}},
		fldCodPostal4: {digits: function(){alert("Usar digitos no primeiro campo do código postal");}, minlength: function(){alert("O primeiro campo do código postal tem que ter 4 digitos");}},
		fldCodPostal3: {digits: function(){alert("Usar digitos no segundo campo do código postal");}, minlength: function(){alert("O segundo campo do código postal tem que ter 3 digitos");}},
		fldTelefone: {digits: function(){alert("Usar digitos no telefone");}, minlength: function(){alert("Numero de telefone inválido");}}
	},
	submitHandler: function(form){
		$.post("../services/users/Register.aspx", $(form).serialize(), function(data, textStatus){
			$(".confirmLoading").fadeIn("slow");
			$(".confirmContainer").fadeTo("slow", 0.11, function(){
				if(data.status.success){
				    if (data.bodydata!=null)
				    {
				        parent.$.setUserData(data.bodydata); // defined in script_user_login.js
				    }
				
				 	$(".formConfirm .next").click();
				} else {
					$(".confirmLoading").fadeOut("slow");
					
					var errorCode = data.status.id;
					$(".confirmContainer").fadeTo("slow", 1, function(){
					    switch(errorCode)
					    {
					    case 3:
						    alert("Já existe um utilizador com este E-Mail.");
						    break;
					    case 11:
						    alert("Problemas com a fotografia.");
						    break;
						default:
						    alert("Ocorreu uma anomalia, por favor tente de novo.");
						    break;
                        }						
					});
				}
			});
		}, "json");
	}
});

$(".formFill a.submit").click(function(event){
	event.preventDefault();
	$("#form1").validate();
	if($("#form1").valid()){
		constructConfirmation();
		$(".formFill .next").click();
	}
});

$(".formConfirm a.submit").click(function(event){
	event.preventDefault();
	$("#form1").submit();
});
/* -------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------- */















});

