$(document).ready( function() {
	criarLinkExterno();
	$("#fCurriculo").change(function(){
		$(".fake").val($("#fCurriculo").val());
	});
});

/* Habilita os links externos para abrirem em uma nova janela */

function criarLinkExterno() {
	$("a[rel='external']").click(function() {
		$(this).attr("target", "_blank");
	});
}

/* Manipula a exibição dos widgets */

function manipularWidgets( idLista, objSeta ) {
	$("#" + idLista).slideToggle('fast');

	$(objSeta).toggleClass('abre');
	$(objSeta).toggleClass('fecha');

	var title = $(objSeta).hasClass("abre") ? "Expandir" : "Recolher";
	$(objSeta).attr("title", title);

	return false;
}

function obterURLArquivos(mes, isURLLimpa, urlSite) {
	var campoAno = '#ano_arquivo';
	var ano = parseInt($(campoAno).text());
	var url = urlSite + '/';
	var idAno = 'ano_arquivo';

	mes =  parseInt(mes);
	if ( mes < 10 ) {
		mes = '0' + mes;
	}

	if ( isURLLimpa )  {
		url += ano + '/' + mes;
	} else {
		url += '?m=' + ano + mes;
	}

	location.href = url;
}

function incrementaDecrementaAno(sinal) {
	var campoAno = '#ano_arquivo';

	if ( sinal == '-' ) {
		$(campoAno).text( parseInt($(campoAno).text()) - 1 );
	} else {
		$(campoAno).text( parseInt($(campoAno).text()) + 1 );
	}
}

function compartilhe_enviar(post) {
	var form = document.compartilhe_form;
	var nome = form.nome;
	var email = form.email;
	var destinatarios = form.destinatarios;
	var msg = '';

	if ( nome.value == '' || nome.value == 'Seu nome' ) {
		msg += "- O nome é obrigatório \n";
		nome.focus();
	}

	if ( email.value == '' || email.value == 'Seu e-mail' ) {
		msg += "- O e-mail é obrigatório \n";
		email.focus();

	} else if ( !isEmail(email.value) ) {
		msg += "- O e-mail é inválido \n";
		email.focus();
	}

	if ( destinatarios.value == 'Destinatário(s)                 separe os e-mails de destinatário com vírgula' ) {
		msg += "- A mensagem é obrigatória \n";
	}

	if ( msg != '' ) {
		mostrarMensagem('<span style="color:#FF86B2">' + msg + '</span>');
		return false;
	}

	
	$.post(
		form.action, 
		{'nome': nome.value, 'email': email.value, 'destinatarios': destinatarios.value, 'acao': 'compartilhar', 'post': post},
		function(data) {
			var dados = eval('(' + data + ')');
			if ( typeof(dados) == 'object'  ) {
				var cor = dados.sucesso ? '#00FF40' : '#FF86B2';
				var mensagem = '<span style="color:' + cor + '">' + dados.mensagem + '</span>';
				mostrarMensagem(mensagem);

				if ( dados.sucesso ) {
					nome.value = 'Seu nome';
					email.value = 'Seu e-mail';
					destinatarios.value = 'Destinatário(s)                 separe os e-mails de destinatário com vírgula';
				}

			} else {
				mostrarMensagem('Não foi possível enviar o e-mail!');
			}
		}		
	);
}

function validarFormularioComentario(form) {
	var msg = '';
	var nome = form.author;
	var email = form.email;
	var comentario = form.comment;


	if ( nome.value == '' )  {
		msg += '- O nome é obrigatório \n';
	}

	if ( email.value == '' || !isEmail(email.value) ) {
		msg += '- O e-mail é inválido \n';
	}

	if ( comentario.value == "" ) {
		msg += '- comentário é obrigatório \n';
	} else if ( comentario.value.length > 500 ) {
		msg += '- O campo comentário não pode ultrapassar 500 caracteres \n';
	}

	if ( msg != '' ) {
		msg = '<span style="color:#FF86B2">' + msg + '</span>';
		mostrarMensagem(msg);
		return false;
	}

	return true;
}

function mostrarMensagem(mensagem) {
	var msg = "<div style='position: relative'>" + mensagem + "</div>";
	msg += '<div style="position: absolute; top: 3px; right: 3px;"><a href="#" onclick="jQuery.unblockUI(); return false;" style="font:weight: bold; color: white; font-family: verdana; font-size: 14px">X</a></div>';

	jQuery.blockUI(
		{	message: msg.replace(/\n/g, '<br />'),
			css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: 'black', 
				opacity: '0.8', 
				color: '#fff',
				cursor: 'pointer',
				'font-weight': 'bold',
				'font-size': '14px'
			},
			overlayCSS: {opacity: '0.3'},
			fadeOut: '200'
		}
	);

	//jQuery("body").mousemove( function(){setTimeout(jQuery.unblockUI, 2000)} );
	jQuery("body").keypress( jQuery.unblockUI );
	jQuery('.blockOverlay').attr('title','Fechar').click(jQuery.unblockUI);
	//setTimeout(jQuery.unblockUI, 10000);
}


function isEmail(email) {
	var expr = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   	
    if(email.search(expr) == -1)
	{
		return false;
	}
	return true;    
}


/**
  * Verifica o valor padrÃ£o dos campos 
  */
function controlarValorPadrao(padrao, tag) {
	var elemento = $(tag);
	var valor = ( elemento.val() == padrao ) ? "" : ( elemento.val() == "" ) ? padrao : elemento.val();

	elemento.val(valor);
}

/* Adiciona a página ao sistema de bookmark escolhido */
function bookmark(tipo) {
	if ( tipo == "rec6") { window.open("http://rec6.via6.com/link.php?url=" + encodeURIComponent(location.href) + "&titulo=" + encodeURIComponent(document.title)); }
	if ( tipo == "delicious") { window.open("http://del.icio.us/post?url=" + encodeURIComponent(location.href) + "&title=" +encodeURIComponent(document.title)); }
	if ( tipo == "stumble") { window.open("http://www.stumbleupon.com/refer.php?url=" + encodeURIComponent(location.href) + "&title=" + encodeURIComponent(document.title)); }
	if ( tipo == "digg") { window.open("http://digg.com/submit?phase=2&url=" + encodeURIComponent(location.href) + "&title=" + encodeURIComponent(document.title)); }

	return false;
}

/* Monitora a quantidade de caracteres digitados */
function contarCaracteres(textarea, contador) {
	var quantidade = 500;
	var texto = "";

	if ( textarea.value.length <= quantidade ) {
		texto = "Restam " + (quantidade - textarea.value.length) + " caracteres";
	} else {
		texto = "Ultrapassou " + quantidade + " caracteres";
	}
	
	$("#" + contador).text(texto);
}

function validarFormularioTrabalheConosco( form ) {
	$(form).find(".obrigatorio").each(function (){
		if ( $(this).val() == "" ) {
			$(this).addClass("realce");
		}
		else {
			$(this).removeClass("realce");
		}
	});

	if ( $(form).find(".realce").length > 0 ) {
		$(".painel-erro").html("<p>Os campos marcados em vermelho s&atilde;o de preenchimento obrigat&oacute;rio</p>");
		$(".painel-erro").show();

		window.scrollTo(0,0);

		return false;
	}
}