IncludeJavaScript("scripts/cufon.js"); // Núcleo do Cufón
IncludeJavaScript("scripts/din.js");
IncludeJavaScript("scripts/din-bold.js");
IncludeJavaScript("scripts/jquery.maskedinput.js");
IncludeJavaScript("scripts/jquery.facebox.js"); // Facebox
IncludeJavaScript("scripts/jquery.flash.js"); // Flash

// Funções
$(function() {
	
	
	// Estiliza listas
	$(".lista li:even").addClass("even");
	$(".lista li:odd").addClass("odd");
	$(".lista li:first-child").addClass("first");
	$(".lista li:last-child").addClass("last");

	// Cufon
	Cufon.replace(".din", { fontFamily: "DIN Alternate", hover: true });
	Cufon.replace(".din-bold", { fontFamily: "DIN Alternate" });
	Cufon.replace(".din-gr", {
		fontFamily: "DIN Alternate",
		color: "-linear-gradient(#c0c0c0, #050505)",
		hover: true
	});
	Cufon.replace(".din-shadow", {
		fontFamily: "DIN Alternate",
		textShadow: "#7a9193 0.5px 0.5px",
		hover: true
	});
	Cufon.replace(".din-shadow-w", {
		fontFamily: "DIN Alternate",
		textShadow: "#FFF 1px 1px",
		hover: true
	});
	
	// Flash home
	$(".flash-home").flash({
	    src: "swf/topo.swf",
	    width: 940,
	    height: 340,
		wmode: "transparent",
		expressInstall: true
	});
	
	// Flash interno
	$(".flash-interno").flash({
	    src: "swf/topoInterna.swf",
	    width: 940,
	    height: 140,
		wmode: "transparent",
		expressInstall: true
	});
	
	
	// Input
	var input = document.getElementsByTagName("input");
	for (var a=input.length-1; a >= 0; a--) {
		if (input[a].type != "text") { continue; }
		input[a].mask = input[a].value;
		input[a].onfocus = function() {
			if (this.value == this.mask) { this.value = ""; }
		};
		input[a].onblur = function() {
			if (this.value == "") { this.value = this.mask; }
		};
	}

	// Lista
	$(".lista-letras li a").click(function() {
		var abrirLetra = $(this).attr("href");
		$(".lista-letras li a").removeClass("sel");
		$(this).addClass("sel");
		$(".letras").fadeOut(800);
		setTimeout(function(){ $(abrirLetra).fadeIn(); }, 800);
		return false;
	});

	// Links externos
	$("a[rel=external]").attr("target","_blank");
	$("a[rel=external nofollow]").attr("target","_blank");

	// Botao submit
	$("input[type=submit]").css("cursor","pointer");
	$("input[type=button]").css("cursor","pointer");

	// Voltar
	$(".bt-voltar").click(function(){ history.back(); return false; });

	// Transparencia
	$(".opac").css("opacity","0.5");

	// Mascaras formularios
	if (typeof $.fn.mask != "undefined") {
		$(".masc_telefone").mask("(99) 9999-9999");
		$(".masc_cpf").mask("999.999.999-99");
	}
});

/**
  * 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 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], 5, 0, 0, 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 "";
}

/**
  * 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 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 validar credenciado
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarCredenciado(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-credenciado.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível realizar o cadastro, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Cadastro realizado com sucesso.");
					document.getElementById(form).reset();
					$.facebox.close();
				} else {
					alert("Não foi possível realizar o cadastro, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar contato
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarContato(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-contato.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 corretor
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarCorretor(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-corretor.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível realizar o cadastro, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Cadastro realizado com sucesso.");
					document.getElementById(form).reset();
					$.facebox.close();
				} else {
					alert("Não foi possível realizar o cadastro, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar seja um corretor
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarSejaCorretor(form) {
	if (validaForm(form)) {
		$("#controle-corretor").attr("href", "req/seja-corretor.php?email=" + $("#sej_email").val());
		$("#controle-corretor").click();
	}
}

/**
  * Função Habilita/Desabilita Submit
  * @param form Identificador do form
  * @return 
  **/
function habilitaDesabilitaSubmit(form,parametro) {
    for (var i = 0; i < document.getElementById(form).elements.length; i++) {
        var idObj 	= document.getElementById(form).elements[i].id;
        var tipObj 	= document.getElementById(form).elements[i].type;
		switch (tipObj) {
			case "submit":
				switch(parametro){
					case 'disabled':
						if(document.getElementById(form).elements[i].disabled){
							return true;
						}else{
							return false;
						}
					break;
					default:
						document.getElementById(form).elements[i].disabled = parametro;
					break;
				}
			break;
			default:
			break;
		}
    }
}

/**
  * Função validar
  * @param nada
  * @return nada
  **/
function validarComPost(form) {
	validarComPostFacebox(form,false);
}

/**
  * Função validar
  * @param form: id do form
  * @return nada
  **/
function validarComPostFacebox(form,fechar) {
	if (validaForm(form)) {
		if (habilitaDesabilitaSubmit(form, 'disabled')) {
			//Submit está desabilitado
			alert('Aguarde o término do processo. Obrigado!');
		} else {
			//Submit está habilitado
			habilitaDesabilitaSubmit(form, true);

			var str = $("#" + form).serialize();
			$.ajax({
				type: "POST",
				url: "lib/acao-" + form + ".php",
				data: str,
				beforeSend: function(){
				},
				success: function(txt){
					habilitaDesabilitaSubmit(form,false);

					arrtxt = txt.split('<!-- SEPARADOR -->');
					cod = getTrim(arrtxt[0]);
					msg = getTrim(arrtxt[1]);
					reload = getTrim(arrtxt[2]);
					url = getTrim(arrtxt[3]);
					switch (cod) {
						case '0':
						case 'false':
							alert(msg);
						break;

						case '1':
						case 'true':
						case 'ok':
							if(msg != ''){
								alert(msg);
							}
							document.getElementById(form).reset();
							if (fechar) {
								if ($.facebox) {
									$.facebox.close();
								}
							}
							switch (reload) {
								case '1':
								case 'true':
								case 'ok':
									habilitaDesabilitaSubmit(form,true);
									if (url != '') {
										window.location.href = url;
									}
									else {
										window.location.reload();
									}
								break;

								default:
								break;
							}
						break;

						default:
							alert(txt);
						break;
					}
				},
				error: function(txt){
					habilitaDesabilitaSubmit(form,false);
					alert("Erro: " + txt);
				}
			});
		}
	}
}
