$(function() {
	
	$(".banners").jCarouselLite( {
		btnNext: ".bannernext",
		btnPrev: ".bannerprev",
		auto: 6000,
		speed: 800,
		visible: 1
	});
	
	$("#last-news").cycle('fade');
	
	//Estilizando tabelas
	$(".malha tbody tr:even").addClass("eventr");;
	$(".malha tbody tr:odd").addClass("oddtr");;

	//mouseover e mouseout nas tabelas
	$(".malha tbody tr").hover(function() {$(this).addClass("trover");},function() {$(this).removeClass("trover");}); 
	
	// Máscaras
	if (typeof $.fn.mask != "undefined") { 
		$(".masc_telefone").mask("(99)9999-9999"); 
		$(".masc_cpf").mask("999.999.999-99"); 
		$(".masc_data").mask("99/99/9999"); 
		$(".masc_cep").mask("99999-999"); 
	}
});

$(document).ready(function() {
	$(".bt-voltar").click(function(){ history.back(); return false; }); //Botão de voltar a página anterior
	$("a[rel='colorbox-principal']").colorbox({ transition: "elastic", maxHeight: "90%", maxWidth: "90%" });
	$("a[rel='colorbox-galeria']").colorbox({ transition: "elastic", maxHeight: "90%", maxWidth: "90%" });
	$(".documento-layer").colorbox({ iframe: true, innerWidth: "90%", innerHeight: "95%" });
	$(".video").colorbox({iframe:true, innerWidth:425, innerHeight:344});
	
	// Links externos
	$("a[rel=external]").attr("target", "_blank");
	
	//Menu usuário
	//$("ul.subnav").parent().append("<span></span>");
	$("ul.topnav li p").click(function() {
		$(this).parent().find("ul.subnav").slideDown("fast").show();
		$(this).parent().hover(function() {
		}, function() {
			$(this).parent().find("ul.subnav").slideUp("400");
		});
	}).hover(function() {
		$(this).addClass("subhover");
	}, function() {
		$(this).removeClass("subhover");
	});
});

/**
  * Função limpa espaço
  * @param str String
  * @return nada
  **/
function getTrim(str) {
	if(typeof(str) !== "undefined"){
		return str.replace(/^\s+|\s+$/g, "");
	}else{
		return "";
	}
}

/**
  * Formata número
  * @param $campo int id
  * @param $event Evento
  * @return String
  **/
function formataNumero(campo, e) {
	t = typeof window.event != "undefined" ? window.event.keyCode : e.which;
	if((isNaN(String.fromCharCode(t)) || (t == 32)) && (t != 8 && t != 0)) {
		return false;
	}
}

/**
  * Função monta caixa de seleção
  * @param div DIV
  * @param id Identificador
  * @return nada
  **/
function montaCaixa(div, id, padrao) {
	$.ajax({
		type: "POST",
		url: "lib/acao-monta-caixa.php",
		data: "div=" + div + "&id=" + id + "&padrao=" + padrao,
		success: function(txt) {
			$("#" + div).html(txt);
		}
	});
}

/**
  * Função seleciona os checkbox
  * @param name Nome do input
  * @param checked Verifica se está selecionado
  * @return nada
  **/
function selecinaCampos(name,checked) {
	var elements = document.getElementsByTagName("input");
	for(i = 0; i < elements.length; i++) {
		if(elements[i].type == "checkbox" && elements[i].name.indexOf(name) != -1) {
			if (!checked) {
				elements[i].checked = "";
			} else {
				elements[i].checked = "checked";
			}
		}
	}
}

/**
  * Função que valida a data
  * @param String $value data
  * @return boolean
  **/
function validaData(campo) {
    var valor = campo.split("/");
    if(valor[0] != "" && valor[1] != "" && valor[2] != "") {
        data = new Date(valor[2], valor[1]-1, valor[0]);
        if (valor[2] != data.getFullYear() || valor[1] !=  data.getMonth()+1 || valor[0] != data.getDate() || valor[2] < 1902 || valor[2] > 2037) {
            return false;
        }
    }
    return true;
}

/**
  * Função que valida CPF
  * @param String $s CPF
  * @return boolean
  **/
function validaCpf(s) {
	if(s != "") {
		var cpf = s.replace(/\D/g, "");
		if (
			cpf == "00000000000" ||
			cpf == "11111111111" ||
			cpf == "22222222222" ||
			cpf == "33333333333" ||
			cpf == "44444444444" ||
			cpf == "55555555555" ||
			cpf == "66666666666" ||
			cpf == "77777777777" ||
			cpf == "88888888888" ||
			cpf == "99999999999" ||
			cpf.length != 11)
		{
			return false;
		}

		var soma = 0;
		for ( var i = 10 ; i > 1; i--) {
			soma += cpf.charAt(10 - i) * i;
		}
		d1 = (soma % 11 < 2) ? 0 : (11 - (soma % 11));
		if (d1 != cpf.charAt(9)) {
			return false;
		}
		soma = 0;
		for ($i=11 ; $i>1; $i--) {
			soma += cpf.charAt(11 - i) * i;
		}
		d2 = (soma % 11 < 2) ? 0 : (11 - (soma % 11) );
		if (d2 != cpf.charAt(10)) {
			return false;
		}
		return true;
	}
}

/**
  * Função chaca o valor do radio
  * @param String $radioObj
  * @return boolean
  **/
function getCheckedValue(radioObj) {
	if (!radioObj) {
		return "";
	}
	var radioLength = radioObj.length;
	if (radioLength == undefined) {
		if (radioObj.checked) {
			return radioObj.value;
		} else {
			return "";
		}
	}
	for (var i = 0; i < radioLength; i++) {
		if (radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

/**
  * Formata a número decimal máscara
  * @param obj String campo que será atualizado
  * @return void
  **/
function mascara_num(obj) {
	valida_num(obj)
	valor = obj.value.replace("-","");
	valor = valor.replace(",","");
	if (valor.length >= 3) {
		valor = poe_ponto_num(valor.substring(0,valor.length-2))+","+valor.substring(valor.length-2, valor.length);
	}
	obj.value = valor;
}

/**
  * Formata a número decimal colocando os pontos
  * @param valor String campo que será atualizado
  * @return void
  **/
function poe_ponto_num(valor) {
	valor = valor.replace(/\./g,"");
	if (valor.length > 3) {
		valores = "";
		while (valor.length > 3) {
			valores = "."+valor.substring(valor.length-3,valor.length)+""+valores;
			valor = valor.substring(0,valor.length-3);
		}
		return valor+""+valores;
	} else {
		return valor;
	}
}

/**
  * Formata a número decimal valida número
  * @param obj String campo que será atualizado
  * @return void
  **/
function valida_num(obj) {
	numeros = new RegExp("[0-9]");
	while (!obj.value.charAt(obj.value.length-1).match(numeros)) {
		if(obj.value.length == 1 && obj.value == "-") {
			return true;
		}
		if(obj.value.length >= 1) {
			obj.value = obj.value.substring(0,obj.value.length-1);
		} else {
			return false;
		}
	}
}

/**
  * Função Validar Formulário
  * @param form Identificador do form
  * @return Boolean
  **/
function validaForm(form) {
    for (var i = 0; i < document.getElementById(form).elements.length; i++) {
        var nomeObj = document.getElementById(form).elements[i].name;
        var idObj 	= document.getElementById(form).elements[i].id;
		var relObj 	= document.getElementById(form).elements[i].getAttribute("rel");
		switch (relObj) {
			case "email":
				expressao = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
				if (!expressao.test(document.getElementById(form).elements[i].value)) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			break;
			case "required":
				if ((document.getElementById(form).elements[i].value == null) || (document.getElementById(form).elements[i].value == "")) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].focus();
					return false;
				}
			break;
			case "cpf":
				if ((!validaCpf(document.getElementById(form).elements[i].value)) || (document.getElementById(form).elements[i].value == null) || (document.getElementById(form).elements[i].value == "")) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			break;
			case "data":
				if ((!validaData(document.getElementById(form).elements[i].value)) || (document.getElementById(form).elements[i].value == null) || (document.getElementById(form).elements[i].value == "")) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			break;
			case "radio":
			case "checkbox":
				if(getCheckedValue(document.getElementsByName(nomeObj))) {
				} else {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].focus();
					return false;
				}
			break;
			default:
			break;
		}
    }
    return true;
}

/**
  * Função validar depoimento
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarDepoimento(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-depoimento.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Mensagem enviada com sucesso.");
					document.getElementById(form).reset();
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar ajuda
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarAjuda(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-ajuda.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Mensagem enviada com sucesso.");
					document.getElementById(form).reset();
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar login
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarLogin(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-login.php",
			data: str,
			success: function(txt) {
				arr = txt.split("<!-- SEPARADOR -->");
				if (arr[1]) {
					window.location = "index.php?cmd=noticias";
					return false;
				}
				if (arr[0]) {
					alert(arr[0]);
					return false;
				}
			}
		});
	}
}

/**
  * Função validar usuário
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarUsuario(form) {
	if (validaForm(form)) {				
		document.getElementById("div-botao-enviar").style.display = 'none';
		document.getElementById("div-botao-aguarde").style.display = '';
		$(document).ready(function() {
            $("#" + form).ajaxForm(function(txt) {				
				arr = txt.split("<!-- SEPARADOR -->"); // Array de retorno								
				retorno = getTrim(arr[1]); // Retorno				
				mensagem = getTrim(arr[0]); // Mensagem				
				alert(mensagem); // Mostra a mensagem				
				if (retorno == "1") { // Retorno					 
					window.location = "index.php?cmd=msg-cadastro";					
					return false;
				}								
				if (retorno == "2") { // Retorno					 
					window.location = "index.php?cmd=participe";	
					return false;
				}	
				if (retorno == "0") { // Retorno					 
					document.getElementById("div-botao-enviar").style.display = '';
					document.getElementById("div-botao-aguarde").style.display = 'none';				
				}
            });
        });
	}
}

/**
  * Função validar ajuda
  * @param form arquivo do Arquivo (SWF)
  * @param form width
  * @param form height
  * @return flash
  **/
function flash(arquivo, width, height) {	
	$.ajax({
		type: "POST",
		url: "lib/acao-form-flash.php",
		data: "arquivo=" + arquivo + "&width=" + width + "&height=" + height,
		success: function(txt) {
			$("#div-rodadas").html(txt);
		}
	});
}

/**
  * Função hora simulado
  * @param nada
  * @return html
  **/
function horaSimulado() {
	segundo--;
	if (segundo < 0) {
		segundo = 59;
		minuto--;
		if (minuto <= 9) {
			minuto = "0" + minuto;
		}
	}
	if (minuto == "0-1") {
		minuto = 59;
		hora--;
		if (hora <= 9) {
			hora = "0" + hora;
		}
	}
	if (segundo <= 9) {
		segundo = "0" + segundo;
	}
	if (hora == "0-1") {
		hora = "00";
		minuto = "00";
		segundo = "00";
		$("#div-hora").html(hora + ":" + minuto + ":" + segundo);
	} else {
		$("#div-hora").html(hora + ":" + minuto + ":" + segundo);
		id_simulado = setTimeout("horaSimulado();", 1000);
	}
}

/**
  * Função validar simulado
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarSimulado(form) {		
	if (validaForm(form)) {		
		document.getElementById("div-botao-simulado").style.display = 'none';
		document.getElementById("div-botao-aguarde").style.display = '';
		clearTimeout(id_simulado);
		document.getElementById(form).submit();
/*
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-simulado.php",
			data: str,
			success: function(txt) {				
				if (getTrim(txt) == "ok") {
					if ($("#fk_pergunta").val() <= 19) {
						window.location = "index.php?cmd=simulados&id=" + $("#fk_similado").val() + "&questao=" + (parseInt($("#fk_pergunta").val()) + 1);
					} else {
						window.location = "index.php?cmd=simulados&id=" + $("#fk_similado").val() + "&expirou=1";
					}
				} else {
					alert("Não foi possível votar no simulado, tente novamente.");
				}
			}
		});
*/

	}
}

/**
  * Função validar enquete
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarEnquete(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-enquete.php",
			data: str,
			success: function(txt) {				
				arr = txt.split("<!-- SEPARADOR -->"); // Array de retorno								
				retorno = getTrim(arr[1]); // Retorno				
				mensagem = getTrim(arr[0]); // Mensagem				
				if (retorno != "2") {
					alert(mensagem); // Mostra a mensagem				
				}
				if (retorno == "1") { // Retorno					 
					window.location = "index.php?cmd=participe";					
				}
				if (retorno == "2") { // Retorno					 
					window.location = "index.php?cmd=login";
				}
			}
		});
	}
}

/**
  * Função validar tópico
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarTopico(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-forum-topico.php",
			data: str,
			success: function(txt) {				
				if (getTrim(txt) == "ok") {
					alert("Tópico cadastrado com sucesso, aguarde aprovação.");
					document.getElementById(form).reset();
				} else {
					alert("Não foi possível cadastrar o tópico, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar resposta
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarResposta(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-forum-resposta.php",
			data: str,
			success: function(txt) {				
				if (getTrim(txt) == "ok") {
					alert("Mensagem cadastrada com sucesso, aguarde aprovação.");
					document.getElementById(form).reset();
				} else {
					alert("Não foi possível cadastrar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar plano
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarPlano(form) {
	if (validaForm(form)) {		
		document.getElementById(form).submit();
	}
}

/**
  * Função validar compra
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarCompra(form) {	
	var str = $("#" + form).serialize();
	$.ajax({
		type: "POST",
		url: "lib/acao-form-compra.php",
		data: str,
		success: function(txt) {							
			if (getTrim(txt) == "ok") {				
				if (document.getElementById("fk_forma").value == "1") { // Boleto bancário
					itauShopline();
					document.getElementById(form).submit();
					setTimeout("window.location = 'index.php?cmd=pagamentos';", 2000);
				} else if (document.getElementById("fk_forma").value == "2") { // PagSeguro
					document.getElementById(form).submit();
					setTimeout("window.location = 'index.php?cmd=pagamentos';", 2000);
				} else if (document.getElementById("fk_forma").value == "3") { // Cheque
					alert("O seu plano de adesão ao GEMT - Grupo de Estudos da Magistratura do Trabalho foi escolhido. Você será encaminhado à página de pagamentos.");
					window.location = 'index.php?cmd=pagamentos';
				} else {
					alert("Não foi possível efetuar o pagamento, tente novamente.");
				}
			} else {
				alert("Não foi possível efetuar o pagamento, tente novamente.");
			}
		}
	});	
}

/**
  * Função validar login
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarLembrar(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-senha.php",
			data: str,
			success: function(txt) {
				arr = txt.split("<!-- SEPARADOR -->");
				if (arr[1]) {
					alert(arr[0]);
					window.location = "index.php?cmd=login";
					return false;
				}
				if (arr[0]) {
					alert(arr[0]);
					return false;
				}
			}
		});
	}
}
