var timeout = 300;
var closetimer = 0;
var ddmenuitem = 0;

function menu_open() {  
	menu_canceltimer();
	menu_close();
	ddmenuitem = $(".submenu").css('visibility', 'visible');
}

function menu_close() {  
	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function menu_timer() {  
	closetimer = window.setTimeout(menu_close, timeout);
}

function menu_canceltimer() {
	if (closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}	
}

$(window).load(function(){
	
	// Links externos
	$("a[rel=external]").attr('target','_blank');
	//$("a[rel=external nofollow]").attr('target','_blank');
	
	// Botoes
	$("input[type=submit]").css("cursor","pointer");
	$("input[type=button]").css("cursor","pointer");
	$(".bt-voltar").click(function(){ history.back(); return false; });
	$('.bt-imprimir').click(function(){ print(); return false; });
	
	// Transparencia
	$(".opac").css("opacity","0.5");
	
	// Cufon
	//Cufon.replace('.Helv77', { fontFamily: 'Helvetica Neue LT Pro', hover: true });
	
	// Estiliza listas
    $(".lista li:even a").addClass("even");
    $(".lista li:odd a").addClass("odd");
    $(".lista li:first-child a").addClass("first");
    $(".lista li:last-child a").addClass("last");
    $(".paginacao a:last-child").addClass("last");
	
	// Função pra tirar o value do input e botar devolta
	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; }
		};
	}

	// 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");
	}
	
	// Banner home
	$('#destaque').cycle({
		fx: 'fade', // tipo de efeito de transição
		speed: 'fast', // velocidade do efeito de transição
		timeout: 5000, // velocidade da transição de uma imagem a outro
		prev: ".bt-prev",
		next: ".bt-next",
		pager:  '#destaque-nav', // elemento que contera a navegação da galeria
		pagerEvent: 'mouseover', // joga o mouseover na paginação
		pause: true,
		pagerAnchorBuilder: function(idx, slide) { 
			return '#destaque-nav li:eq(' + idx + ') a'; // retorna a string seletora para ancoras ja existentes
		},
		cleartype: !$.support.opacity,
		cleartypeNoBg: true
	});
	
	$('#menu-lojas a').click(function(){
		if(!$(this).hasClass('bt-qualimais')) {
			var pegaId = $(this).attr('href');
			var animaVelocidade = 600;
			var efeito = "easeOutBounce";

			$('#menu-lojas a').animate({ opacity: 0.5 });
			$(this).animate({ opacity: 1 });
		
			if($(pegaId).hasClass('ativado')) {
				$(pegaId).animate({height: "hide"}, animaVelocidade, efeito, function(){}).removeClass('ativado');
				$('#menu-lojas a').animate({ opacity: 1 });
			} else {
				$('.menus').animate({height: "hide"}, animaVelocidade, efeito, function(){}).removeClass('ativado');
				setTimeout(function(){
					$(pegaId).animate({height: "show"}, animaVelocidade, efeito, function(){}).addClass('ativado');
				}, 600); 
			}
			return false;
		}
	});
	
	// Cycle
	$(".box-holder ul").cycle({
		fx: "scrollHorz",
		easeIn: "easeInOutBack",
		easeOut: "easeInOutBack",
		prev: ".bt-prev",
		next: ".bt-next",
		timeout: 0
	});
	
	// Cycle banner bottom
	$(".box-banner").cycle({
		fx: 'fade', // tipo de efeito de transição
		speed: 'slow', // velocidade do efeito de transição
		timeout: 3000 // velocidade da transição de uma imagem a outro
	});
		
	// Acoes Sociais
	$('.box-acoes .acoes-box').click(function(){
		if ($(this).hasClass('acoes-active')) {
			$('.box-acoes .acoes-box').removeClass('acoes-active');
			$('#'+$(this).attr('href')).slideUp(250);
		} else {
			$('.box-acoes .acoes-box').removeClass('acoes-active');
			$(this).addClass('acoes-active');
			$('.acoes-desc').slideUp(250);
			$('#'+$(this).attr('href')).slideDown(500);
		}
		return false;
	});
	
	// Maquinas e Ferramentas - Qualimais
	$('.box-maquinas-marcas a').click(function(){
		if ($('.box-maquinas-marcas a').hasClass("sel")) {
			$('.box-maquinas-marcas a').removeClass("sel");
			$(this).addClass("sel");
		} else {
			$(this).addClass("sel");
		}

		var agaref = $(this).attr("href");
		
		if($(agaref).hasClass('maquina-aberto')){
			
		} else {
			$('.box-escolhe').removeClass('maquina-aberto');
			$(agaref).addClass('maquina-aberto');
			$('.box-escolhe').slideUp('500');
			$(agaref).slideDown('500');
			
		}
		return false;
	});
	
	//Menu over, Menu out
	$('.opensub').bind('mouseover', menu_open);
	$('.opensub').bind('mouseout',  menu_timer);
	
	$('.submenu').bind('mouseover', menu_open);
	$('.submenu').bind('mouseout',  menu_timer);
	
	
});

/**
  * 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 trocar imagem
  * @param media Imagem média
  * @param grande Imagem grande
  * @param legenda Legenda da imagem
  * @return mensagem de erro
  **/
function imagem(media, grande, legenda) {
	document.getElementById("a-imagem").href = grande;
	document.getElementById("a-imagem").title = legenda;
	document.getElementById("img-imagem").src = media;
	document.getElementById("img-imagem").alt = legenda;
	document.getElementById("img-legenda").innerHTML = legenda;
}

/**
  * 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
  * @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 newsletter
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarNewsletter(form) {
	if (validaForm(form)) {		
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-newsletter.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("E-mail já cadastrado.");
				} else if (getTrim(txt) == "1") {
					alert("Estamos felizes em tê-lo como cliente. Obrigado pelo cadastro!");
					document.getElementById(form).reset();
					$.facebox.close();
				} else {
					alert("Não foi possível cadastrar o e-mail, 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) {
				if (getTrim(txt) == "0") {
					alert("Usuário inválido!");
				} else if (getTrim(txt) == "1") {
					//alert("Estamos felizes em tê-lo como cliente. Obrigado pelo cadastro!");
					//document.getElementById(form).reset();
					$.facebox.close();
					window.location.href = "index.php?cmd=colaborador";
				} else {
					alert("Não foi possível acessar, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função carregar url por option input
  * @param pUrl URL de redirecionamento
  * @param selObj Identificador do Objeto do select
  * @param restoure Reseta select
  * @return mensagem de erro
  **/
function jumpCateg(pUrl,selObj,restore){
	if(selObj.options[selObj.selectedIndex].value == ""){
		var perUrl = pUrl.split("&");
		eval("location.href='"+perUrl[0]+selObj.options[selObj.selectedIndex].value+"'");
	}else{
		eval("location.href='"+pUrl+selObj.options[selObj.selectedIndex].value+"'");
	}
	if (restore) selObj.selectedIndex=0;
}

/**
  * Função carregar busca
  * @param page Pagina de redirecionamento
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function buscar(page,form) {
	var keyword = "";
	keyword = document.getElementById(form).elements[0].value;
	/* Debug se está buscando os valores
	alert(page);
	alert(form);
	alert(keyword);*/
	window.location.href = "index.php?cmd=" + page + "&tipo=busca&q="+keyword;
}

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

function validarEmprego(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);				
            });
        });
	}
}








