$(document).ready(function(){
	
	//CÓDIGO PARA OS SUBMENUS FUNFAREM NO INTERNET EXPLORER //
	$(".menu-secundario li").each(function() {		
		$(this).mouseover(function(){
			$(this).addClass("over");
		}).mouseout(function(){
			$(this).removeClass("over");
		});	
	});
	
	//colore a tabela de parcelamento
	$("#parcela tr:odd").addClass("cinza");
	$("#parcela tr:even").addClass("branco");
});


// Funções genéricas
//--------------------------------------------------------------------------------------------------------------------------------
function valida_mail(valor) {
	   prim = valor.indexOf("@")
	   if(prim < 1) return false;
	   if(valor.indexOf("@",prim + 1) != -1) return false;
	   if(valor.indexOf(".") < 1) return false;
	   if(valor.indexOf("zipmeil.com") > 0) return false;
	   if(valor.indexOf("hotmeil.com") > 0) return false;
	   if(valor.indexOf(".@") > 0) return false;
	   if(valor.indexOf("@.") > 0) return false;
	   if(valor.indexOf(".com.br.") > 0) return false;
	   if(valor.indexOf("/") > 0) return false;
	   if(valor.indexOf("[") > 0) return false;
	   if(valor.indexOf("]") > 0) return false;
	   if(valor.indexOf("(") > 0) return false;
	   if(valor.indexOf(")") > 0) return false;
	   if(valor.indexOf("..") > 0) return false;
	   if(valor.indexOf(",") > 0) return false;
	   return true;
}

function validaVazio(obj, msgErro) {
    if (obj.value == "") {
	   alert(msgErro);
	   obj.focus();
	   return true;
    }
    return false;
}

function validaCpf(value) {
	
	var i;
	
	s = value.replace(".", "");
	s = s.replace(".", "");
	s = s.replace("-", "");
	s = s.replace("/", "");
	
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(10-i);
	}
	 
	if (d1 == 0) {
		return false;
	}
	 
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	
	if (dv.charAt(0) != d1)	{
		return false;
	}
	
	d1 *= 2;				 
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(11-i);
	}
	 
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	 
	if (dv.charAt(1) != d1) {
		return false;
	}
	 
	return true;
}

//função para máscara
function formata(campo, mask, evt) {

	if(document.all)
	{ // Internet Explorer
		var key = evt.keyCode;
	}
	else
	{ // Nestcape
		var key = evt.which;
	}

	var teclasPermitidas = Array(0, 8, 13);

	for (var i=0; i < teclasPermitidas.length; i++)
	{
		if (key == teclasPermitidas[i]) return true;
	}

	var string = campo.value;
	i		   = string.length;

	if (i < mask.length)
	{
		if (mask.charAt(i) == '§')
		{
			return (key > 47 && key < 58);
		}
		else
		{
			if (mask.charAt(i) == '!') return true;

			for (var c = i; c < mask.length; c++)
			{
				if (mask.charAt(c) != '§' && mask.charAt(c) != '!')
				{
					campo.value = campo.value + mask.charAt(c);
				}
				else if (mask.charAt(c) == '!')
				{
					return true;
				}
				else
				{
					return (key > 47 && key < 58);
				}
			}
		}
	} else return false;
}

function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g);
	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();
	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
	return (num + ',' + cents);
}

function controlaCarrinho(id, acao, qtde)
{
	var url = "../cadastro/controla_carrinho.php?id="+id+"&acao="+acao;
	if (qtde)
	{
		if (qtde > 0)
		{
			url += "&qtde="+qtde;
		}
		else
		{
			alert("Por favor, informe uma quantidade válida");
			return;
		}
	}
	window.location = url;
	return false;
}

function CalculaFrete(cepDestino, peso)
{
	if (cepDestino && peso)
	{
		var url = "../cadastro/CalculaFrete.php?cep="+cepDestino+"&peso="+peso;
		funcRetorno = "MostraValorFrete()";
		loadXMLDoc(url);
	}
	else if (!cepDestino)
	{
		alert("Por favor, informe o CEP");
	}
	/*else
	{
		alert("Por favor, informe o peso");
	}*/
}

function MostraValorFrete()
{
	if (req.responseText != "")
	{
		
		var valFrete = req.responseText;
		var subTotal = document.frmCarrinho.valSubTotal.value;
		var Total 	 = Number(valFrete) + Number(subTotal);
		
		document.getElementById("valFrete").innerHTML = "R$ " + formatCurrency(valFrete);		
		document.getElementById("valTotal").innerHTML = formatCurrency(Total);
	}
}

function validaContato(form)
{
	if (validaVazio(form.nome, "Por favor, informe seu nome"))
		return false;

	if (validaVazio(form.email, "Por favor, informe seu email"))
		return false;

	if (!valida_mail(form.email.value))
	{
		alert("O email fornecido não parece ser válido");
		form.email.focus();
		return false;
	}

	if (validaVazio(form.setor, "Por favor, informe o setor"))
		return false;

	if (validaVazio(form.mensagem, "Por favor, informe seu a mensagem"))
		return false;
}

function validaSac(form)
{
	if (validaVazio(form.nome, "Por favor, informe seu nome"))
		return false;

	if (validaVazio(form.email, "Por favor, informe seu email"))
		return false;

	if (!valida_mail(form.email.value))
	{
		alert("O email fornecido não parece ser válido");
		form.email.focus();
		return false;
	}

	if (validaVazio(form.ddd_telefone, "Por favor, informe o DDD"))
		return false;

	if (validaVazio(form.telefone, "Por favor, informe o telefone"))
		return false;

	if (validaVazio(form.cpf, "Por favor, informe o CPF"))
		return false;

	if (validaVazio(form.notafiscal, "Por favor, informe o No da Nota Fiscal"))
		return false;

	if (validaVazio(form.dt_notafiscal, "Por favor, informe a data da Nota Fiscal"))
		return false;

	if (validaVazio(form.cod_produto, "Por favor, informe o Código do Produto"))
		return false;

	if (validaVazio(form.motivo, "Por favor, informe o Motivo"))
		return false;

}

function validaNewsletter(form)
{
	if (validaVazio(form.nome, "Por favor, informe seu nome"))
		return false;

	if (validaVazio(form.email, "Por favor, informe seu email"))
		return false;

	if (!valida_mail(form.email.value))
	{
		alert("O email fornecido não parece ser válido");
		form.email.focus();
		return false;
	}

	for (i=0; i < form.length; i++)
	{
		if (form.elements[i].type == "checkbox" && form.elements[i].name != "all")
		{
			if (form.elements[i].checked)
				return true;

		}
	}

	alert("Por favor, selecione pelo menos uma área de interesse");
	return false;
}

function mascaraData(obj, evento)
{
    var BACKSPACE   = 8;
    var DEL         = 46;
    var FRENTE      = 39;
    var TRAS        = 37;
    var TAB         = 9;
    var SHIFT       = 16;

    var tecla       = (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode);

    if(tecla == BACKSPACE || tecla == DEL || tecla == FRENTE || tecla == TRAS || tecla == TAB || tecla == SHIFT)
        return true;

    if ((tecla < 48 || tecla > 57) && (tecla < 96 || tecla > 105))
    {
        obj.value = '';
        return false;
    }

    if(obj.value.length == 2)
        obj.value = obj.value + "/";
    if(obj.value.length == 5)
        obj.value = obj.value + "/";
    if(obj.value.length == 10)
    {
        var dia = parseInt(obj.value.substring(0,2),10);
        var mes = parseInt(obj.value.substring(3,5),10);
        var ano = parseInt(obj.value.substring(6,10),10);

        if(dia <= 31 && mes <=12 && ano >= 1000)
        {
            if(obj.value.substring(0,1) == "0" && obj.value.substring(1,2) != "0" || obj.value.substring(0,1) != "0")
            {
                if(obj.value.substring(2,3) == "/")
                {
                    if(obj.value.substring(3,4) == "0" && obj.value.substring(4,5) != "0" || obj.value.substring(3,4) != "0")
                    {
                        if(obj.value.substring(5,6) == "/")
                        {
                            if(obj.value.substring(6,7) == "0" || obj.value.substring(6,7) == "" && obj.value.substring(7,8) != "0")
                            {
                                window.alert("O ano que você digitou não existe!");
                                obj.focus();
                                obj.value = "";
                                return false;
                            }
                            else
                            {
                                if(mes == 2)
                                {
                                    if((dia > 0 ) && (dia <= 29))
                                    {
                                         if(dia == 29)
                                         {
                                             if((ano % 4) == 0)
                                             {
                                                 return true;
                                             }
                                             else
                                             {
                                                 window.alert("Este dia não existe, certifique-se de que digitou corretamente!");
                                                 obj.focus();
                                                 obj.value = "";
                                                 return false;
                                             }
                                         }
                                    }
                                    else
                                    {
                                         window.alert("Este dia não existe, certifique-se de que digitou corretamente!");
                                         obj.focus();
                                         obj.value = "";
                                         return false;
                                    }
                                }
                                if((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11))
                                {
                                    if((dia > 0 ) && (dia <= 30))
                                    {
                                         return true;
                                    }
                                    else
                                    {
                                         window.alert("Este dia não existe, certifique-se de que digitou corretamente!");
                                         obj.focus();
                                         obj.value = "";
                                         return false;
                                    }
                                }
                                if((mes == 1) || (mes == 3) || (mes == 5) || (mes == 7) || (mes == 8) || (mes == 10) || (mes == 12))
                                {
                                    if((dia > 0) && (dia <= 31))
                                    {
                                         return true;
                                    }
                                    else
                                    {
                                         window.alert("Este dia não existe, certifique-se de que digitou corretamente!");
                                         obj.focus();
                                         obj.value = "";
                                         return false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            window.alert("A data foi digitada fora do padrão(dd/mm/aaaa) !");
                            obj.focus();
                            obj.value = "";
                            return false;
                        }
                    }
                    else
                    {
                        window.alert("Você digitou um mês que não existe!");
                        obj.focus();
                        obj.value = "";
                        return false;
                    }
                }
                else
                {
                    window.alert("A data foi digitada fora do padrão(dd/mm/aaaa)!");
                    obj.focus();
                    obj.value = "";
                    return false;
                }
            }
            else
            {
                window.alert("Você digitou um dia que não existe!");
                obj.focus();
                obj.value = "";
                return false;
            }
        }
        else
        {
            window.alert("O dia e/ou o mês que você digitou não existe, ou Você digitou\nfora do padrão (dd/mm/aaaa) !");
            obj.focus();
            obj.value = "";
            return false;
        }

        return true;
    }
}

function verificaFormaPagamento(form)
{
	var campos   = form.getElementsByTagName("input");
	var verifica = false;

	for (var cont = 0; cont < campos.length; cont++)
	{
		if (campos[cont].type == 'radio')
		{
			if (campos[cont].checked)
			{
				verifica = true;
				break;
			}
		}
	}

	if (!verifica)
	{
		alert('É necessário selecionar uma forma de pagamento!');
		return false;
	}
	else
	{
		return true;
	}
}

function validaVisaPagamento(form)
{
	if (validaVazio(form.titular, "Por favor, informe o nome do titular do cartão"))
		return false;

	if (validaVazio(form.num_cartao, "Por favor, informe o número do cartão"))
		return false;

	return true;
}

function validaMastercardPagamento(form)
{
	if (validaVazio(form.titular, "Por favor, informe o nome do titular do cartão"))
		return false;

	return true;
}

function validaCadastroCliente()
{
	/*var error = false;
	var inp = false;
	
	$("#form-contato input, #form-contato select").each(function(i){
		if( $(this).val() == '' ) {
			if( $(this).attr('type') != 'checkbox' && $(this).attr('type') != 'hidden' ) {
				error = true;
				inp = (inp == false) ? this : inp;
			}
		}
		else if( $(this).attr('type') == 'radio' && $("#"+$(this).attr('id')).is(':checked') == false ){
			error = true;
			inp = (inp == false) ? this : inp;
		}
		
		if( $("#CLI_DSC_SENHA").val() != $("#CLI_DSC_SENHA_CONFIRM").val() ){
			error = true;
			inp = (inp == false) ? this : inp;
			alert('Senhas não conferem');
			
			return false;
		}
	});
	
	if( error == true ) {
		alert('Todos os campos são obrigatórios');
		$(inp).focus();
	}else{
		document.cadastrocliente.submit();
	}*/
	
	if( validateForm(document.getElementById('form-contato'), 'pt') ) 
		document.cadastrocliente.submit();
		
}

function checkAll()
{
	var campos = document.getElementsByTagName("input");

	for (var cont = 0; cont < campos.length; cont++)
	{
		if (campos[cont].type == 'checkbox')
		{
			if (campos[cont].checked)
			{
				campos[cont].checked = false;
			}
			else
			{
				campos[cont].checked = true;
			}
		}
	}
}

function mascaraCep(obj, evento)
{
	var BACKSPACE   = 8;
	var DEL         = 46;
	var FRENTE      = 39;
	var TRAS        = 37;
	var TAB         = 9;
	var SHIFT       = 16;

	var tecla       = (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode);

	if (tecla == BACKSPACE || tecla == DEL || tecla == FRENTE || tecla == TRAS || tecla == TAB || tecla == SHIFT)
		return true;

	if ((tecla < 48 || tecla > 57) && (tecla < 96 || tecla > 105))
	{
		obj.value = obj.value.substring(0, obj.value.length - 1);
		evento.returnValue = false;
		return false;
	}

	if (obj.value.length == 5)
		obj.value = obj.value + '-';
}

function checkRepet()
{
	if (document.getElementById('repetir').checked == true)
	{
		document.getElementById('END_DSC_RUA_ENTREGA').value   = document.getElementById('END_DSC_RUA').value;
		document.getElementById('END_DSC_NUMER_ENTREGA').value = document.getElementById('END_DSC_NUMER').value;
		document.getElementById('END_DSC_COMPL_ENTREGA').value = document.getElementById('END_DSC_COMPL').value;
		document.getElementById('END_DSC_CEP_ENTREGA').value   = document.getElementById('END_DSC_CEP').value;
		document.getElementById('END_DSC_BAIRR_ENTREGA').value = document.getElementById('END_DSC_BAIRR').value;
		document.getElementById('END_DSC_CIDAD_ENTREGA').value = document.getElementById('END_DSC_CIDAD').value;
		document.getElementById('END_DSC_UF_ENTREGA').value    = document.getElementById('END_DSC_UF').value;
	}
	else
	{
		document.getElementById('END_DSC_RUA_ENTREGA').value   = '';
		document.getElementById('END_DSC_NUMER_ENTREGA').value = '';
		document.getElementById('END_DSC_COMPL_ENTREGA').value = '';
		document.getElementById('END_DSC_CEP_ENTREGA').value   = '';
		document.getElementById('END_DSC_BAIRR_ENTREGA').value = '';
		document.getElementById('END_DSC_CIDAD_ENTREGA').value = '';
		document.getElementById('END_DSC_UF_ENTREGA').value    = '';
	}
}

var posBanner = 1;
function navegaBanners()
{

	var banner 	   = document.getElementById("img-banner");
	var linkBanner = document.getElementById("link-banner");

	banner.src 	    = "../imgdb/banners/"+arrBanners[posBanner][0];
	linkBanner.href = arrBanners[posBanner][1];

	posBanner++;

	if (Number(posBanner) > Number(totalBanner)-1) posBanner = 0;
}


window.onload = function()
{
	if (totalBanner > 1)
		setInterval("navegaBanners()", 5000);
}

function enviaSenha(form)
{
	if (validaVazio(form.email, "Por favor, informe seu email"))
		return false;

	var url = "../cadastro/envia_senha.php?email="+form.email.value;
	funcRetorno = "resultadoSenha()";
	loadXMLDoc(url);

}

function resultadoSenha()
{
	if (req.responseText)
	{
		alert(req.responseText);
	}
}

function validaAviseme(form)
{
	if (validaVazio(form.nome, "Por favor, informe seu nome!"))
		return false;
	
	if (validaVazio(form.email, "Por favor, informe seu email!"))
		return false;
		
	if (!valida_mail(form.email.value))
	{
		alert("Email inválido");
		form.email.focus();
		return false;
	}
		
	if (validaVazio(form.telefone, "Por favor, informe seu telefone!"))
		return false;
		
	return true;
}

function addAviseMe(id_prod)
{
	if (id_prod)
	{
		var url = "../produtos/grava_item_aviseme.php?id_prod="+id_prod;
		funcRetorno = "retornoAviseme()";
		loadXMLDoc(url);
	}
}

function retornoAviseme()
{
	var texto = req.responseText;
	if (texto.length > 0)
	{
		if (texto.indexOf("off") == 0)
		{
			var arrTemp = texto.split("#");
			location.href = "../produtos/aviseme.php?"+arrTemp[1];
		}
		else
		{
			alert(texto);
		}
	}
}