$(window).load(function(){

	// Links externos
	$("a[rel=external]").attr("target", "_blank");
	$("a[rel=external nofollow]").attr("target", "_blank");
	
	// Estilizar select
	$("select#exame").selectmenu({ style: "dropdown" });
	
	// Arredondar cantos
	DD_roundies.addRule("div.curso_redondo", "15px", true);

	//Cufon nos titulo e textos
	Cufon.replace(".botao_top, .corp_light", { fontFamily: "CorporateS-Light", hover: true });
	Cufon.replace(".titulo, .corp_bold", { fontFamily: "CorporateS-Bold", hover: true });
	Cufon.replace(".corp_extrabold", { fontFamily: "CorporateS-ExtraBold", hover: true });
	Cufon.replace("a.fonte1", { fontFamily: "AvenirLTStd-Book", hover: true });
	Cufon.replace("div.interna_margim > h1, div.interna_margim > h2, .corp_demi", { fontFamily: "CorporateS-Demi", hover: true });
	Cufon.replace(".corp_regular", { fontFamily: "CorporateS-Regular", hover: true });
	
	// Adiciona class even e  odd nas lis do mural
	$("div.mural ul li:even").addClass("even");
	$("div.mural ul li:odd").addClass("odd");
	
	// Corpo Clinico para tooltip left e right
	$("div.inclui_classe1 ul > li:even").addClass("even");
	$("div.inclui_classe1 ul > li:odd").addClass("odd");
	
	$("div.inclui_classe2 ul > li:even").addClass("even");
	$("div.inclui_classe2 ul > li:odd").addClass("odd");
	
	$("div.inclui_classe3 ul > li:even").addClass("even");
	$("div.inclui_classe3 ul > li:odd").addClass("odd");
	
	
	// Ativa jquery.equalHeight para as lis
	jQuery("div.mural ul li, .equalheight li").equalHeight();	
	
	
	
	// Carrega fancybox
	$("a[rel=fancybox]").fancybox({
		"transitionIn" : "none",
		"transitionOut" : "none",
		"titlePosition" : "inside",
		"titleFormat"	: function formatTitle(title, currentArray, currentIndex, currentOpts) {
			return '<div id="tip-title"><span></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + '</div>';
		}
		
		
	});
	
    // Facebox
    $('a[rel*=facebox]').facebox();
    
	// Fancybox home
	$("a[rel=fancybox-home]").fancybox({
		"transitionIn" : "none",
		"transitionOut" : "none",
		"titlePosition" : "over",
		"titleShow"		: false
	});
	
	// fancybox para ampliar mapa
	$(".mapa_zoom").fancybox({
		"width" : 670,
		"height" : 450,
        "autoScale" : false,
        "transitionIn" : "none",
		"transitionOut" : "none",
		"type" : "iframe"
	});
	
	$('.banners-home').show();
	$('.banners-home').cycle({
		fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	});
	
	// Mascaras formularios
	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_hora").mask("99:99");
		$(".masc_cep").mask("99999-999");
	}
});

/**
  * 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 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 "";
}

/**
  * 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");
		var error = 0;
		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();
					error=error+1;
					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();
					error=error+1;
					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();
					error=error+1;
					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();
					error=error+1;
					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();
					error=error+1;
					return false;
				}
			break;
			default:
			break;
		}
    }
	if(error>0){
		return false;
	}else{
		return true;
	}
}

/**
  * 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 exame
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarExame(form) {
	if (validaForm(form)) {
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-exame.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.");
					$("#banner-principal").click();
					document.getElementById(form).reset();
					$.facebox.close();
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar currículo
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarCurriculo(form) {
	if (validaForm(form)) {
		$(document).ready(function() {
            $("#" + form).ajaxForm(function(txt) {
				if (getTrim(txt) == "1") {
					alert("Cadastro realizado com sucesso.");
					window.location = "index.php?cmd=trabalhe-conosco";
					return false;
				}
				alert(txt);
            });
        });
	}
}

/**
  * Função validar Validar Cadastrar Email
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarCadastrarEmail(form) {
    if (validaForm(form)) {
        var str = $("#" + form).serialize();
        $.ajax({
            type: "POST",
            url: "lib/acao-form-cadastro-online.php",
            data: str,
            success: function(txt) {
                if (getTrim(txt) == "0") {
                    alert("Não foi possível enviar seu cadastro, tente novamente.");
                } else if (getTrim(txt) == "1") {
                    alert("Cadastro enviada com sucesso.");
                    $.facebox.close();
                    document.getElementById(form).reset();
                } else {
                    alert("Não foi possível enviar seu cadastro, tente novamente.");
                }
            }
        });
    }
}


/**
  * Função validar Validar Esqueci Minha Senha
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarEsqueciSenha(form) {
    if (validaForm(form)) {
        var str = $("#" + form).serialize();
        $.ajax({
            type: "POST",
            url: "lib/acao-form-esqueci-senha.php",
            data: str,
            success: function(txt) {
                if (getTrim(txt) == "0") {
                    alert("Não foi possível solicitar seu senha, tente novamente.");
                } else if (getTrim(txt) == "1") {
                    alert("Solicitação de senha enviada com sucesso.");
                    $.facebox.close();
                    document.getElementById(form).reset();
                } else {
                    alert("Não foi possível solicitar seu senha, tente novamente.");
                }
            }
        });
    }
}
