function googleAnalytics(){	
	try {
		var pageTracker = _gat._getTracker("UA-15584499-1");
		pageTracker._trackPageview();
	} catch(err) {}
}

function autocompletar(){
	var options = {
			script:"scripts/diversos/autocompletar.php?json=true&limit=8&",
			varname:"input",
			json:true,
			shownoresults:false,
			maxresults:8
		};
		var as_json = new bsn.AutoSuggest('pesquisaPalavraHome', options);
		var as_json = new bsn.AutoSuggest('pesquisaBusca', options);
}

function criaObjeto(){
    var obj;
	try{		
		// XmlHttpRequest para Firefox,	Opera, Safari e derivados.		
		obj = new XMLHttpRequest();
	}	catch (e){		
		// XmlHttpRequest para Internet Explorer.		
		try{			
		// Internet Explorer 6.0+
			obj = new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			// Internet Explorer.			
			obj = new ActiveXObject("Microsoft.XMLHTTP");		
		}	
	}	
	return obj;
}

var http = criaObjeto();
var nomeDiv;
var mensagemNova=0;

function enviaRequisicao(campo,acao,mensagem,caminho){
	campoEnviado = campo;
	acaoEnviado  = acao;
	mensagemEnviado = mensagem;
	caminhoEnviado = caminho;
	if (mensagem != undefined){
		document.getElementById(campo).innerHTML = '<table width="100%"><tr><td align=center><br/><img src="http://www.centraldodelivery.com.br/img/loading_bm.gif"><br/>' +  mensagem + '</td></tr></table>';
	}
	if (caminho != undefined){
		caminhoLocal = caminho;
	}
	nomeDiv = campo;
    http.open('get',acao,true);
    http.onreadystatechange = processaResposta;
    http.send(null);
}

function processaResposta(){
    if(http.readyState == 4){
        if(http.status == 200){
            var resposta = http.responseText;
            document.getElementById(nomeDiv).innerHTML = resposta;
            if(resposta.indexOf('erroIndicaSite') > 0){
            	alert('Não foi possivel enviar seu convite!');
            }
            if(resposta.indexOf('erroValidarCartao') > 0){
            	alert('Dados inválidos.');
	           	chamaFormDadosCartao();
            }
            if (resposta.indexOf('avancaDadosCartao')>0){
				inicio = resposta.indexOf('-')+1;
				fim = resposta.indexOf('--');
				caminho = resposta.substring(inicio,fim);
				mensagem = '&nbsp;<br/>&nbsp;<br/>&nbsp;<br/><img src="http://www.centraldodelivery.com.br/img/loading_bm.gif"><br/>Finalizando compra...<br/><br/>';
				document.getElementById("conexaoSegura").innerHTML = mensagem;
				newInterval = setInterval("finalizaCompraCartao(caminho)",2000);
            }
            if(resposta.indexOf('enviouIndicaSite') > 0){
            	alert('Convite enviado com sucesso!\nObrigado por indicar a Central do Delivery!');
            	document.formIndica.reset();
            	fecharIndicaSite();            	
            }
            if (resposta.indexOf('siteOffLine') >0){
           		location.href="http://www.centraldodelivery.com.br";
            }
            if (resposta.indexOf('naoPossuiSessao') >0){            	
            	inicio = resposta.indexOf('[*')+2;
				fim = resposta.indexOf('**]');
				caminho = resposta.substring(inicio,fim);
           		alert("Você passou muito tempo sem acessar o sistema.\nPor questões de segurança você será reconectado.");
           		location.href="http://www.centraldodelivery.com.br"+caminho;
            }
            if (resposta.indexOf('terminouAdicionar') >0){
           		closeAd();
            }
            if (resposta.indexOf('ativaProcessaCard') >0){
            	ativaProcessamentoCartao();
            }
            if (resposta.indexOf('excluiu') >0){
            	alert("Exclusão efetuada com sucesso.");
            }
            if (resposta.indexOf('erroEsqueceuSenha') >0){
            	alert("Email não localizado.");
            }
            if (resposta.indexOf('enviouEsqueceuSenha') >0){
            	document.getElementById('esqueceuSenha').value = '';
            	alert("Prezado cliente, a sua senha foi enviada ao email cadastrado. Obrigado.");
            }
            if (resposta.indexOf('lojaDiferente') >0){
            	alert("A compra só pode ser feita em uma mesma loja.\nPara comprar em lojas diferentes você deferá efetuar uma nova compra.");
            }
            if (resposta.indexOf('cartaoProcessado') >0){
            	clearInterval(ourInterval);
            	redirecionaPaginaFinalCartao(caminhoFinalizaCartaoAtual);
            }
            if (resposta.indexOf('testeMinhasCompras') >0){
				inicio = resposta.indexOf('-')+1;
				fim = resposta.indexOf('--');
				menuAreaUsuario('meusPedidos',resposta.substring(inicio,fim));
            	//minhasCompras(resposta.substring(inicio,fim));
            }
            if(resposta.indexOf('pratosMaisComprados') > 0){
            	inicio = resposta.indexOf('-')+1;
				fim = resposta.indexOf('--');
				menuAreaUsuario('maisPedidos',resposta.substring(inicio,fim));
            }
            if(resposta.indexOf('avaliarLojaCliente') > 0){
            	inicio = resposta.indexOf('-')+1;
				fim = resposta.indexOf('--');
				menuAreaUsuario('avaliarLoja',resposta.substring(inicio,fim));
            }            
            if (resposta.indexOf('carregaAreasAtendimento') >0){
				inicio = resposta.indexOf('*/*')+3;
				fim = resposta.indexOf('**/**');
            	enviaRequisicao('divAreasAtendimento',resposta.substring(inicio,fim),'Carregando...');
            }
            if (resposta.indexOf('voltarLoja') >0){
				inicio = resposta.indexOf('*')+1;
				fim = resposta.indexOf('**');
				id = resposta.substring(inicio,fim);
				
				inicio = resposta.indexOf('*/*')+3;
				fim = resposta.indexOf('**/**');
				
				caminho = resposta.substring(inicio,fim);
				buscaLoja(id,caminho);
            }
            if (resposta.indexOf('avancaPagamento') >0){
            	inicio = resposta.indexOf('*')+1;
				fim = resposta.indexOf('**');
				eval(resposta.substring(inicio,fim));
            }
            if (resposta.indexOf('totalRetornoEnderecos') >0){
            	inicio = resposta.indexOf('*')+1;
				fim = resposta.indexOf('**');
				if (document.getElementById('totalEnderecos')!=null){
            		document.getElementById('totalEnderecos').value = parseInt(resposta.substring(inicio,fim));
            	}
            }
            if(resposta.indexOf('clienteAvaliouLoja') > 0){
            	alert("Obrigado pela sua avaliação.");	
            }   
            if(resposta.indexOf('clienteAvaliacaoLojaFalhou') > 0){
            	alert("Sua avaliação falhou. Tente novamente mais tarde.");
            }
            if(resposta.indexOf('clienteExcluiuAvaliacao') > 0){
            	alert("Avaliação excluída com sucesso.");
            }
            if(resposta.indexOf('encartePromocaoCentral') > 0){
			    jQuery('#mycarouse1').jcarousel({
					scroll: 5,
					wrap:'last',
					animation: 1500	
				});
            }
            // redireciona para página inicial
            if(resposta.indexOf('paginaInicialCentral') > 0){
            	location.href = 'index1.php';
            }
            if(resposta.indexOf('respostaClienteEndereco') > 0){
            	alert("Não foi possível salvar o endereço.")
            }
            if( resposta.indexOf('autocompletar') > 0 ){
            	autocompletar();
            }
            googleAnalytics();
        }else{
       		if(mensagemNova==0){
				mensagemTemp = 'Ainda Carregando...';
				mensagemNova=1;
			}else{
				mensagemTemp = 'Tentando Novamente...';
				mensagemNova=0;
			}
        	document.getElementById('textoSponsor').innerHTML =mensagemTemp;
        	enviaRequisicao(campoEnviado,acaoEnviado,mensagemTemp,caminhoEnviado);
            //document.getElementById(nomeDiv).innerHTML = "Erro.";
        }
      
    }
    
}
function enviaRequisicao2(campo,acao,mensagem){
	http2 = criaObjeto();
	if (mensagem != undefined){
		document.getElementById(campo).innerHTML = '<div style="font-family:Arial, Helvetica;font-size:12px;float:left">' +  mensagem + '</div>';
	}
	nomeDiv2 = campo;
    http2.open('get',acao);
    http2.onreadystatechange = processaResposta2;
    http2.send(null);
}

function processaResposta2(){
    if(http2.readyState == 4){
        if(http2.status == 200){
            var resposta = http2.responseText;
            document.getElementById(nomeDiv2).innerHTML = resposta;
 		}else{
            document.getElementById(nomeDiv2).innerHTML = "Página não encontrada.";
        }
    }
}

//Executa a função objetoXML()
var xmlhttp = criaObjeto(); 

//Função que envia o formulário
function enviarForm(url, campos, destino, mensagem, caminhoEnviado) {
	caminhoNovo = caminhoEnviado;
	//Atribui à variável 'elemento' o elemento que irá receber a página postada
	elemento = document.getElementById(destino); 
	//Se o objeto de 'xmlhttp' não estiver true
	if (!xmlhttp) {
		//Insere no 'elemento' o texto atribuído
		elemento.innerHTML = 'Impossível iniciar o objeto XMLHttpRequest.'; 
		return;
	} else { 
		if (mensagem != undefined){
			//Insere no 'elemento' o texto atribuído
			elemento.innerHTML = mensagem; 
		}
	}
	//Abre a página que receberá os campos do formulário
	xmlhttp.open('POST',url,true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	xmlhttp.send(campos); 	
	xmlhttp.onreadystatechange = processaRespostaPost;
}
function processaRespostaPost(){
	//Se a requisição estiver completada
	if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0){ 
		//Se o status da requisição estiver OK
		resposta = xmlhttp.responseText;
		elemento.innerHTML = resposta; 
		if (xmlhttp.status == 200) {
			resposta = xmlhttp.responseText;
            elemento.innerHTML = resposta; 
            if (resposta.indexOf('cadastrouCliente') >0){
	            if (resposta.indexOf('chamaCarrinho') >0){
	            	inicio = resposta.indexOf('*')+1;
					fim = resposta.indexOf('**');
					eval(resposta.substring(inicio,fim));
					document.getElementById("fundoCaixaLogin").style.backgroundImage="url('"+caminhoNovo+"img/p.gif')";
					document.getElementById("caixaLogarSistema").innerHTML='<a href="'+caminhoNovo+'scripts/menu/menu_area_usuario.php"><img src="'+caminhoNovo+'img/area_usuario_acompanhe.gif" border="0" /></a>';
					if (ie||w3){
						document.getElementById("imagemCadCliente").style.display="none";
					}else{
						document.getElementById("imagemCadCliente").style.display.visibility ="hide";
					}
	            }else{
	            	if(resposta.indexOf('lojaTemplate') > 0){	            		
	            		setTimeout("location.href='"+caminhoNovo+"lojas/index.php'",5000);
	            	}else{
	            		setTimeout("location.href='"+caminhoNovo+"index1.php'",5000);
	            	}
	            	if (document.getElementById('imagemCadCliente')!=null){
	            		document.getElementById("imagemCadCliente").innerHTML='';
	            	}
	            }
            }
            if (resposta.indexOf('avancaPagamento') >0){
            	inicio = resposta.indexOf('*')+1;
				fim = resposta.indexOf('**');
				eval(resposta.substring(inicio,fim));
            }
            if (resposta.indexOf('cadastrouEnd') >0){
            	limpaCamposEnd();
            	if (document.getElementById('totalEnderecos')!=null){
            		document.getElementById('totalEnderecos').value = document.getElementById('totalEnderecos').value+1;
            	}
            }
            if (resposta.indexOf('excluiuEnd') >0){
            	alert("Endereço excluído com sucesso.");
            	if (document.getElementById('totalEnderecos')!=null){
            		document.getElementById('totalEnderecos').value = document.getElementById('totalEnderecos').value-1;
            	}
            }
            if (resposta.indexOf('emailEnviado') >0){
            	closeAd();
            }
            if (resposta.indexOf('naoPossuiSessao') >0){
            	inicio = resposta.indexOf('[*')+2;
				fim = resposta.indexOf('**]');
				caminho = resposta.substring(inicio,fim);
           		alert("Você passou muito tempo sem acessar o sistema.\nPor questões de segurança você será reconectado.");
           		location.href="http://www.centraldodelivery.com.br"+caminho;        
            }
            
            if (resposta.indexOf('clienteLogou') >0){    	
	            if (resposta.indexOf('chamaEndereco') >0){
	            	inicio = resposta.indexOf('*')+1;
					fim = resposta.indexOf('**');
					eval(resposta.substring(inicio,fim));
					closeAd();
					document.getElementById("fundoCaixaLogin").style.backgroundImage="url('"+caminhoNovo+"img/p.gif')";
					caminhoImagemLoja = caminhoNovo;
					// Para a loja especifica
					if (resposta.indexOf('caminhoImagemLoja') >0){
		            	inicio = resposta.indexOf('#')+1;
						fim = resposta.indexOf('##');
						caminhoImagemLoja = resposta.substring(inicio,fim);
					}
					document.getElementById("caixaLogarSistema").innerHTML='<a href="'+caminhoNovo+'scripts/menu/menu_area_usuario.php"><img src="'+caminhoImagemLoja+'img/area_usuario_acompanhe.gif" border="0" /></a>';
					if (ie||w3){
						document.getElementById("imagemCadCliente").style.display="none";
					}else{
						document.getElementById("imagemCadCliente").style.display.visibility ="hide";
					}
	            }else{		   
	            	inicio = resposta.indexOf('-')+1;
					fim = resposta.indexOf('--');
					tamanho = resposta.substring(inicio,fim);   
					
					ini = resposta.indexOf('{')+1;
					fim = resposta.indexOf('}');
					tamSemAvaliacao = resposta.substring(ini,fim);
					
	       			if(tamanho > 0){	       			
	       				if(tamSemAvaliacao > 0){
	       					setTimeout("location.href='"+caminhoNovo+"index1.php?areaDoUsuarioAvaliacaoLoja'", 1000);	
	       				}else{
			        		setTimeout("location.href='"+caminhoNovo+"index1.php?areaDoUsuario'",1000);
	       				}
	       			}else{
	       				setTimeout("location.href='"+caminhoNovo+"index1.php'",1000);
	       			}
	            }
            }
            if (resposta.indexOf('erroLogando') >0){
				inicio = resposta.indexOf('-')+1;
				fim = resposta.indexOf('--');
				closeAd();
				alert(resposta.substring(inicio,fim));
            } 
            googleAnalytics();       
		} else { 
			//Insere no 'elemento' o texto atribuído
			elemento.innerHMTL = 'Página não encontrada!'; 
		}
	}
}
