function animacaoFrete() {
	if($('bannerFrete1').style.display == 'none') {
		$('bannerFrete1').style.display = 'block';
		$('bannerFrete2').style.display = 'none';
	} else {
		$('bannerFrete1').style.display = 'none';
		$('bannerFrete2').style.display = 'block';
	}
}

function animacaoCimo() {
	if($('bannerCimo1').style.display == 'none') {
		$('bannerCimo1').style.display = 'block';
		$('bannerCimo2').style.display = 'none';
	} else {
		$('bannerCimo1').style.display = 'none';
		$('bannerCimo2').style.display = 'block';
	}	
}

//function mostraTotalPedido(opcao) {
//	var totalPedido = parseFloat($('valorTotalPedido').value);
//	var totalProdutos = parseFloat($('valorTotalProdutos').value);
//	var descontoAVista = parseFloat($('pctDescontoAVista').value);
	//	var descontoAVista = parseFloat(0.1);
//	
//	if(opcao == 'aPrazo') {
//		$('divTotalPedido').innerHTML = 'R$ ' + floatToMoeda(totalPedido);
//		$('divValorDesconto').innerHTML = '+R$ 0,00';
//	} else {
//		$('divTotalPedido').innerHTML = 'R$ ' + floatToMoeda(totalPedido - (totalProdutos * descontoAVista));
//		$('divValorDesconto').innerHTML = '-R$ ' + floatToMoeda(totalProdutos * descontoAVista);
//	}
//}

function floatToMoeda(num) {
   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }

   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));

   ret = num + ',' + cents;

   if (x == 1) ret = ' - ' + ret;
   
   return ret;

}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    var startRow = 0;
    // workaround for Tapestry not using thead
    if (!table.getElementsByTagName("thead")[0]) {
	    startRow = 1;
    }
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    // add event handlers so rows light up and are clickable
    for (i=startRow; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            if (link.onclick) {
                call = link.getAttribute("onclick");
                if (call.indexOf("return ") == 0) {
                    call = call.substring(7);
                }
                // this will not work for links with onclick handlers that return false
                eval(call);
            } else {
                location.href = link.getAttribute("href");
            }
            this.style.cursor="wait";
            return false;
        }
    }
}

function highlightTableRowsSet(tableId,colunaLink,colInicial,colFinal) {
    var previousClass = null;
    var table = document.getElementById(tableId); 
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
		
		var corFundo;
		
        rows[i].onmouseover = function() {
			
			corFundo = this.style.backgroundColor;
			
			this.style.cursor = "pointer";
				
				for(j=colInicial; j <= colFinal; j++){
					cells = this.getElementsByTagName("td");
					if(!cells)return;
					celLink = cells[colunaLink];
					alink = celLink.getElementsByTagName("a")[0];
						
					cells[j].onclick = function(){
						//var cell = celLink;
						if (celLink.getElementsByTagName("a").length > 0) {
							
							if (alink.onclick) {
								call = alink.getAttributeValue("onclick");
								// this will not work for links with onclick handlers that return false
								eval(call);
							} else {
							  location.href = alink.getAttribute("href");
							}
							this.style.cursor="wait";
						}
					}
				}
			};

		rows[i].onmouseout = function() { this.style.backgroundColor = corFundo; };
        /*
		rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[colunaLink];
            if (cell.getElementsByTagName("a").length > 0) {
                var link = cell.getElementsByTagName("a")[0];
                if (link.onclick) {
                    call = link.getAttributeValue("onclick");
                    // this will not work for links with onclick handlers that return false
                    eval(call);
                } else {
                  location.href = link.getAttribute("href");
                }
                this.style.cursor="wait";
            }
        }
		*/
    }
}

function MM_formt(chr,src,mask, e) {
    var tecla = (window.event)?event.keyCode:e.which;
    if( ( tecla == 8 ) || ( tecla == 9 ) || ( tecla == 11 ) || ( tecla == 0 ) ) 
    	return true;
    	
	var i = src.value.length;
	var texto = mask.substring(i);
	
 	if (texto.substring(0,1) != chr) { 
 		src.value += texto.substring(0,1);
 	}
 	
 	return true; 
}	

function validaCampoFloat(e){
	var tecla=(window.event)?event.keyCode:e.which;
	var input;
	if(!e.srcElement)
		input = e.target; // firefox aceita, ie não
	else
		input = e.srcElement; // ie aceita, firefox não
	if((tecla == 44) && (input.value.indexOf(',') < 0)) // permite digitar virgula
		return true;
	else
		return SomenteNumero(e);
}
	
// verifica se é um numero, backspace ou tab e retorna true
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58))
    	return true;
    else{
	    if( ( tecla == 8 ) || ( tecla == 9 ) || ( tecla == 11 ) || ( tecla == 0 ) ) 
	    	return true;
	    else 
	    	return false;
	}
}

// Funcao JS que abre popUp com tamanho exato da imagem
function abrePopUp(imagem, caminho){
	var popup = open("about:blank","janela","no");
	popup.document.open;
	popup.document.write("<head>");
	popup.document.write("<title> - Foto </title>");
	popup.document.write("</head>");
	popup.document.write("<body topmargin='0' leftmargin='0' >");
	var temp = "<img src='"+caminho+imagem+"' name='foto' />";
	popup.document.write(temp);
	popup.document.write("</body>");
	popup.document.close;
	var largura = popup.document.foto.width;
	var altura = popup.document.foto.height;
	popup.resizeTo(largura,altura+85);
}

function abrirFaleConosco(){
	displayPopIn('atendimento','none');
	displayPopIn('emailFaleConosco','block'); 
}

function displayPopIn(id,state){
	var popIn = $(id);
	if(popIn){
		popIn.style.display = state;
		$('fundoPreto').style.display = state;
		
		
		var selects = $$('DIV.content SELECT',
						 '#envoltorio SELECT');
		for(var i = 0; i < selects.length;i++){
			var select = selects[i];
			if(state == 'block') {
				$(select.id).style.visibility = 'hidden';
			} else {
				$(select.id).style.visibility = 'visible';
			}
		}	
	}	
}
function abrirRecuperacaoSenha(){
	if( $('enviar_RecuperacaoSenha_email'))
		$('enviar_RecuperacaoSenha_email').value = $F('login');
	
	$('enviar_RecuperacaoSenha_tipoUser').value = $F('tipoUser');
	
	displayPopIn('recuperacaoSenha','block');
}
function Trim(str){
		str = str.replace(/^\s+|\s+$/g,"");
		return str;
}	

var popupAtendimento;
var intervalAtendimento;
var popinAtendimento;
function abrirAtendimentoOnline(){
	if(!popupAtendimento || popupAtendimento == null){
		if(getCookie("mmmCanal") == 30){
			
			displayPopIn('atendimento', 'none');
			displayPopIn('atendimentoPopin', 'block');
			
			var container = $('atendimentoPopinFrameContainer');
			var iframe  = document.createElement('IFRAME');
			iframe.id = 'iframe_atendimento';
			iframe.src = 'login_Atendimento.html';
			iframe.style.display = 'block';
			iframe.style.width = '100%';
			iframe.style.height = '340px';//'650px';
			iframe.style.border = 'none';
			//iframe.style.float = 'left';
			//iframe.style.clear = 'both';
			iframe.style.marginTop= '50px';
			
			container.appendChild(iframe);
			
			popinAtendimento = true;
		}else{
			popupAtendimento = window.open('login_Atendimento.html','atendimento','width=450 , height=300, scrollbars=yes, resizable=no , menubar=no, status=no, directories=no');displayPopIn('atendimento','none');
		}
	}	
	intervalAtendimento = window.setInterval('verificarPopupAtendimento()',3000);
}
function verificarPopupAtendimento(){
	if(popinAtendimento && $('atendimentoPopin').style.display == 'none'){
		desativarAtendimento();
	}
	if(!popinAtendimento &&popupAtendimento != null && popupAtendimento.closed){
		desativarAtendimento();
	}
}


function desativarAtendimento(){
	intervalAtendimento = clearInterval(intervalAtendimento);
	popupAtendimento = null;
	if(popinAtendimento){
		displayPopIn('atendimentoPopin', 'none');
		jQuery("#atendimentoPopinFrameContainer").html('');
		popinAtendimento = false;
	}
	jQuery.ajax({
		url: "fechaAtendimento_Atendimento.html",
		success: function(data){
		}
	});
}
function escapeCamposNewsletter(){
	var lng = document.getElementById('request_locale').value;
	$('clienteNewsLetter.nome').value = escape($F('clienteNewsLetter.nome'));
	if(lng == "en" || lng == "es"){
		$('clienteNewsLetter.endereco.cidade').value = escape($F('clienteNewsLetter.endereco.cidade'));
		$('clienteNewsLetter.funcao').value = escape($F('clienteNewsLetter.funcao'));
		$('clienteNewsLetter.endereco.nome').value = escape($F('clienteNewsLetter.endereco.nome'));
		$('clienteNewsLetter.endereco.logradouro').value = escape($F('clienteNewsLetter.endereco.logradouro'));
		$('clienteNewsLetter.atividadePrincipal').value = escape($F('clienteNewsLetter.atividadePrincipal'));
	} else {
		$('clienteNewsLetter.cidade').value = escape($F('clienteNewsLetter.cidade'));
	}
	return true;
}
function validacaoNewsLetter(src) {
	/*maskEmail = /^[\w_-]+(\.[\w_-]+)*@(([\w-]{1,}\.)+[A-Za-z]{2,})$/;*/
	$('submitnewsletter').disabled = 'disabled';
	var lng = document.getElementById('request_locale').value;
	if(lng == "en" || lng == "es") {
		var nome = document.getElementById('clienteNewsLetter.nome').value;
		var email = Trim(document.getElementById('clienteNewsLetter.email').value);
		var funcao = Trim(document.getElementById('clienteNewsLetter.funcao').value);
		var ativPrincipal = Trim(document.getElementById('clienteNewsLetter.atividadePrincipal').value);
		var cia =  Trim(document.getElementById('clienteNewsLetter.endereco.nome').value);
		var endereco = Trim(document.getElementById('clienteNewsLetter.endereco.logradouro').value);
		var nro = Trim(document.getElementById('clienteNewsLetter.endereco.numero').value);
		var cidade = Trim(document.getElementById('clienteNewsLetter.endereco.cidade').value);
		var cep = Trim(document.getElementById('clienteNewsLetter.endereco.cep').value);
		var tel = Trim(document.getElementById('clienteNewsLetter.endereco.telefone').value);
		var paises = document.getElementById('clienteNewsLetter.endereco.pais');
		var pais = paises ? paises.options[paises.selectedIndex].value : "";
		if(lng == "en") {
			if (nome == "Complete Name*" || nome == "" || email == "Email*" || email == "" || funcao == "Position*" || funcao == ""  ||
					cia == "Company/Shop*" || cia == "" || ativPrincipal == "Main Activity*" || ativPrincipal == "" ||
					endereco == "Address*" || endereco == "" || nro == "Number*" || nro == "" || cidade == "City*" || cidade == "" ||
					pais == "" || cep == "Zip Code*" || cep == "" || tel == "Phone*" || tel == "")  {
				alert("Please, fill in the compulsory fields.");
				return false;
			}
			
		} else {
			if (nome == "Nombre Completo*" || nome == "" || email == "Email*" || email == "" || funcao == "Función*" || funcao == ""  ||
					cia == "Compañia/Tienda*" || cia == "" || ativPrincipal == "Actividad Principal*" || ativPrincipal == "" ||
					endereco == "Dirección*" || endereco == "" || nro == "Número*" || nro == "" || cidade == "Ciudad*" || cidade == "" ||
					pais == "" || cep == "Código Postal*" || cep == "" || tel == "Teléfono*" || tel == "")  {
				alert("Por favor, rellene los campos obligatorios.");
				return false;
			}
		}
		
	} else {
		var nome = document.getElementById('clienteNewsLetter.nome').value;
		var email = Trim(document.getElementById('clienteNewsLetter.email').value);
		var sexo = document.getElementsByName('clienteNewsLetter.sexo');
		var cidade = Trim(document.getElementById('clienteNewsLetter.cidade').value);
		var estados = document.getElementById('clienteNewsLetter.estado');
		var estado = estados ? estados.options[estados.selectedIndex].value : "";
		var paises = document.getElementById('clienteNewsLetter.pais');
		var pais = "BR";
		
		var check = false;
		for(var i = 0; i < sexo.length; i++ ) {
			if(sexo[i].checked) check = true;
		}
		
		if(nome == "Nome" || nome == "" || email == "E-mail" || email == "" || check == false || cidade == "Cidade" || cidade == "" || estado == "") {
			alert("Preencha corretamente todos os campos");	
			return false;	
		}
		/*if(!maskEmail.test(email)) {
			alert("E-mail inválido");
			return false;
		} else {
			document.getElementById('clienteNewsLetter.email').value = email;
		}*/
	}
	if(src) {
		$('clienteNewsLetterForm').onsubmit = function() {return true;}
		$('submitnl').click();
		/*$('submitnl').disabled = "disabled";*/
	}
	return true;
}
function validaBusca(erro) {
	if($('campo_busca').value.length >= 3 && $('campo_busca').value != 'Busca' && $('campo_busca').value != 'Search' && $('campo_busca').value != 'B\u00FAsqueda') {
		//$('submitBusca').click();
		return true;
	} else {
		alert(erro);
		//alert('Digite pelo menos 3 caracteres');
		return false;
	}
}
function Esconde(){
	$('floating_banner').hide();
}
function validaEmailForm() { 
	
		var remetente = $('remetente').value;
		remetente = Trim(remetente);
		var email = $('email').value;
		email = Trim(email);
		var mensagem = $('mensagem').value;
		mensagem = Trim(mensagem);
		
		if(remetente == '' || email == '' || mensagem == '' )
			alert('H\u00E1 campos obrigat\u00F3rios n\u00E3o preenchidos.');
		else {
			$('submitEmail').click();
			
			$('remetente').value = "";
			$('email').value = "";
			$('mensagem').value = "";
		}
		return false;
	}
	function escondeDivEmail() {
		document.getElementById('form').style.display = "none";
		document.getElementById('msgEmail').style.display = "block";
		document.getElementById('emailFaleConosco').style.top = "55%";
		document.getElementById('emailFaleConosco').style.left = "50%";
	}
	function restauraDivEmail() {
		document.getElementById('form').style.display = "block";
		document.getElementById('msgEmail').style.display = "none";
		document.getElementById('emailFaleConosco').style.top = "35%";
		document.getElementById('emailFaleConosco').style.left = "47%";
	}
	function validaNotificacaoForm() {
		var email = document.getElementById('notificacao_email').value;
		var maskEmail = /^([0-9a-zA-Z._-]+([_.-]?([0-9a-zA-Z][_.-])+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]*)$/;
		if (Trim(email) == "" ) {
			alert("Digite o e-mail");
		} else if( !maskEmail.test(email) ) {
			alert("Digite um e-mail v\u00E1lido");
		} else {
			document.getElementById('submitNotificacao').click();
		}
	}
	function submitenter(idButton, e) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
	
		if (keycode == 13){
		   if(document.getElementById(idButton).onclick) 	
			   document.getElementById(idButton).onclick();
		   else
			   document.getElementById(idButton).click()
		   return false;
		}else
		   return true;
	}
	function verificaFim(e,obj,idButton){
		if( SomenteNumero(e) ){
			var cep = obj;
		    var tecla=(window.event)?event.keyCode:e.which;
		    if( cep.value.length == 8 && tecla > 47 && tecla < 58 ){
				cep.value = cep.value+String.fromCharCode(tecla);
				document.getElementById(idButton).click();
			}
			return true;
		}
		return false;
	}
	function escapeBusca() {
		$('campo_busca').value = escape($('campo_busca').value);
	}
	function formatarMonetario(num) {
		var x = 0;
		if(num < 0) {
			num = Math.abs(num);
			x = 1;
		}
		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));
		}
		ret = num + ',' + cents;
		if (x == 1) {
			ret = ' - ' + ret;
		}
		return ret;
	}
	function verificaFimCarrinho(e){
		if( SomenteNumero(e) ){
			var cep = document.getElementById('carrinho_cep');
		    var tecla=(window.event)?event.keyCode:e.which;
		    if( cep.value.length == 8 && tecla > 47 && tecla < 58 ){
				cep.value = cep.value+String.fromCharCode(tecla);
				document.getElementById('submit_carrinho').click();
			}
			return true;
		}
		return false;
	}
	var t; 
	var intime=false;
	/*A funcao seguinte eh utilizada no carrinho.jsp e no pedido.jsp*/
	function VerificaNumeroCarrinho(e, src, idsubmit) {
	    var tecla=(window.event)?event.keyCode:e.which;
		if((tecla > 47 && tecla < 58)) {
	    	if(intime == false){
	    		intime = true;
	    	} else {
	    		clearTimeout(t);
	    	}
	    	t = setTimeout("$('"+idsubmit+"').click();intime=false;", 1500);
	    	return true;
	    } else{
	    	if( ( tecla == 8 ) || ( tecla == 9 ) || ( tecla == 11 ) || ( tecla == 0 ) ) 
	    		return true;
	    	else
	    		return false;
		}
	}

