IncludeJavaScript("scripts/jquery.form.js"); // Forms Upload
IncludeJavaScript("scripts/jquery.facebox.js"); // Facebox
IncludeJavaScript("scripts/jquery.lightbox.js"); // Lightbox
IncludeJavaScript("scripts/jquery.cycle.js"); // Cycle
IncludeJavaScript("scripts/jquery.easing.js"); // Easing
IncludeJavaScript("scripts/jquery.em.js"); //
IncludeJavaScript("scripts/jquery.maskedinput.js"); // Máscaras para formulários 

$(function() {
	
	// if (typeof $.fn.cycle != "undefined") { $("ul.cycle").cycle({ fx: "scrollHorz", prev: ".arrow-left", next: ".arrow-right", timeout: 0 }); }
	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"); }
	
	// LINKS EXTERNOS
	$("a[rel=external]").attr('target','_blank');
	$("a[rel=external nofollow]").attr('target','_blank');
	$("input[type=submit]").css("cursor","pointer");
	$("input[type=button]").css("cursor","pointer");
	$(".bt-voltar").click(function(){ history.back(); return false; });

	// Transparencia
	$(".opac").css("opacity","0.6");
	
	// Estiliza listas
    $(".lista li:even").addClass("even");
    $(".lista li:odd").addClass("odd");
    $(".lista li:first-child").addClass("first");
    $(".lista li:last-child").addClass("last");
    $(".paginacao a:last-child").addClass("last");
	
	//Navegação dos serviços
	$('#navplus-top a.down').mouseover(function() {
		var ref = $(this).attr("href");
		$('#subnav ul ul').slideUp('fast');
		$('#'+ref).slideDown('medium');
		return false;
	});
	$('#subnav .close-sev').click(function() {
		$(this).parent().parent().slideUp('medium');
		return false;
	});

    //Slideshow Cycle Clientes > Depoimentos
    $('#depoimentos').after('<div id="nav"></div>').cycle({ 
        fx:     'scrollHorz', 
        speed:  'fast', 
        timeout: 14000, 
        pager:  '#nav'
    });

    setTimeout(function() {
       //Slideshow Cycle Banner HOME
        $('#banner').after('<div id="nav"></div>').cycle({ 
            fx:     'fade', 
            speed:  '2000', 
            timeout: 4000, 
            pager:  '#nav'
        }); 
    }, 1500);

	//Tab Clientes e Parceiros
	$('#clientes-parceiros .nav-tab').click(function() {
		var $tab = $(this).attr('href');

		$('#clientes-parceiros .nav-tab').removeClass('active');
		$('ul.lista').hide('fast');
		$(this).addClass('active');
		$($tab).show('slow');

		return false;
	});

});

/**
  * 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 para checar links dos Tweets e converter em URLs
  * @param string Tweet a ser tratado
  * @return retorno do link
  **/
function tweet2url(string){
	string = string.replace(/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
		function(url){
			var full_url = url;
			if (!full_url.match('^https?:\/\/')) {
				full_url = 'http://' + full_url;
			}
			return '<a href="' + full_url + '" target="_blank">' + url + '</a>';
		}
	);
	return string;
}

/**
  * Função para converter a data do Tweet (Ex. 4 minutos atrás)
  * @param time Data do Tweet a ser tratado
  * @return retorno do tempo
  **/
function tweetTempoConvert(time){
	var date = new Date(time),
		difer = (((new Date()).getTime() - date.getTime()) / 1000),
		dia_difer = Math.floor(difer / 86400);
 
	if ( isNaN(dia_difer) || dia_difer < 0 || dia_difer >= 31 )
		return;
 
	return dia_difer == 0 && (
		difer < 60 && "Agora" ||
		difer < 120 && "Há 1 minuto atrás" ||
		difer < 3600 && "Há " + Math.floor( difer / 60 ) + " minutos atrás" ||
		difer < 7200 && "Há 1 hora atrás" ||
		difer < 86400 && "Há " + Math.floor( difer / 3600 ) + " horas atrás") ||
		dia_difer == 1 && "Ontem" ||
		dia_difer < 7 && "Há " + dia_difer + " dias atrás" ||
		dia_difer < 31 && "Há " + Math.ceil( dia_difer / 7 ) + " Semanas atrás";
}

/**
  * 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 contato
  * @param form Identificador do form
  * @param name Sufixo do nome do arquivo que envia o form
  * @return mensagem de erro
  **/
function validarContato(form,name) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-" + name + ".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();
                    $.facebox.close();
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}


/**
  * Função validar contato
  * @param form Identificador do form
  * @param name Sufixo do nome do arquivo que envia o form
  * @return mensagem de erro
  **/
function validarTrabalheConosco(form) {
    if (validaForm(form)) {        
        var str = $("#" + form).serialize();
        $.ajax({
            type: "POST",
            url: "lib/acao-form-trabalhe-conosco.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("Curriculo enviada com sucesso.");
                    document.getElementById(form).reset();
                } else {
                    alert("Não foi possível enviar a mensagem, tente novamente.");
                }
            }
        });
    }
}



/**
  * Função validar Comentário
  * @param form Identificador do form
  * @param name Sufixo do nome do arquivo que envia o form
  * @return mensagem de erro
  **/
function validarComentario(form) {
    if (validaForm(form)) {        
        var str = $("#" + form).serialize();
        $.ajax({
            type: "POST",
            url: "lib/acao-form-comentario.php",
            data: str,
            success: function(txt) {
                if (getTrim(txt) == "0") {
                    alert("Não foi possível enviar o comentário, tente novamente.");
                } else if (getTrim(txt) == "1") {
                    alert("Comentário enviado com sucesso.\n Aguardando aprovação do Administrador.");
                    document.getElementById(form).reset();
                    $.facebox.close();
                } else {
                    alert("Não foi possível enviar o comentário tente novamente.");
                }
            }
        });
    }
}




/**
  * Função validar Trabalhe Conosco
  * @param form Identificador do form
  * @return mensagem de erro

function validarTrabalheConosco(form) {
	if (validaForm(form)) {
		var queryString = $('#' + form).formSerialize();
		 
		var options = { 
		    url:			'lib/acao-form-trabalhe-conosco.php', 
		    type:		'POST', 
		    data:		queryString, 
		    success:	function(txt) { 
		      if (getTrim(txt) == "1") {
		        alert('Curriculo enviado com sucesso!');
		        document.getElementById(form).reset();
		      }else{
		      	alert("Não foi possível enviar a mensagem, tente novamente.");
		      }
		    } 
		}; 
		 
		// passando os options para o ajaxForm 
		$('#'+form).ajaxForm(options);

	}
}
  **/
