var cidadeValida = {origem: false, destino: false};

//Vari�veis para o Scroll de not�cias
var headline_count;
var headline_interval;
var current_headline = 0;
var old_headline = 0;
var inTween 	 = false;

var enviando_orcamento = false;
function EnviarOrcamento()
{	
	if (enviando_orcamento)
	{
		alert("O orçaamento está sendo enviado. Por favor aguarde.");
		return "";	
	}
	
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
    
    var msg = "";
    if (document.getElementById("nome").value.length == "")
    {
        msg += "- Nome não informado.<br/>";
    }
    if (document.getElementById("email").value.length == "")
    {
        msg += "- E-mail não informado.<br/>";
    }
    else if (!email.test(document.getElementById("email").value))
    {
        msg += "- E-mail inválido.<br/>"; 
    }        
    if (document.getElementById("ddd").value.length == "")
    {
        msg += "- DDD não informado.<br/>";
    }
    if (document.getElementById("telefone").value.length == "")
    {
        msg += "- Telefone não informado.<br/>";
    }  
    if (document.getElementById("origem").value.length == "")
    {
        msg += "- Cidade de origem não informada.<br/>";
    } 
    if (document.getElementById("destino").value.length == "")
    {
        msg += "- Cidade destino não informada.<br/>";
    }   
    else if (document.getElementById("valor").value.length == "")
    {
        msg += "- Valor não informado.<br/>";
    }  
    
	if (msg == "") 
	{
		if (!cidadeValida.origem || !cidadeValida.destino) 
		{
			msg += "<span class=\"destaque\">- Cidade de origem ou destino inválida. Por favor, digite parte do nome da cidade desejada e selecione uma opção na lista de resultados.</span>";
		}
	}
	
    if (msg == "")
    {
        $('#orcamento-inputs').hide();
        $('#orcamento-loading').fadeIn('normal');
        
        //Padding para garantir aparecer o box de not�cias
        contentLeft 	= document.getElementById('left-sidebar');
        orcamentoResult = document.getElementById('orcamento');
        contentLeft.style.paddingTop = parseInt(orcamentoResult.offsetHeight - 15)  + 'px'; 
        
		//$.getJSON(	"ds_orcamento.php",
		$.getJSON(	"tmarmotors/ds_orcamento.php",		
					{
						nome: $("#nome").val(),
						email: $("#email").val(),
						ddd: $("#ddd").val(),
						telefone: $("#telefone").val(),
						origem: $("#origem").val(),
						destino: $("#destino").val(),
						valor: $("#valor").val(),
						tamanho: $("#tamanho_veiculo").val(),
						rand: Math.random(),
						ajax: 'true'
					},
					onFimOrcamento);       
    }
    else
    {
        document.getElementById("textoErroEnvio").innerHTML =  msg;
        $('#orcamento-erro').fadeIn('normal');
    }                      
}

function onFimOrcamento(j)
{
	var resultado = "";
	$('#orcamento-loading').hide();  
	if (j.resultado == "0")
	{
		//$("#orcamento-resultado-conteudo").html("<p><span class=\"destaque\">Houve um erro no processamento do seu orçaamento. Por favor, entre em contato através do e-mail cotacoes@tmartransportes.com.br informando os mesmos dados desse formulário.</span></p>");
		resultado = "Houve um erro no processamento do seu orçaamento. Por favor, entre em contato através do e-mail cotacoes@tmartransportes.com.br informando os mesmos dados desse formulário."; 
	}
	else
	{
		var dados = "<h4>Cliente</h4>" +
		"<p>Nome  : " + $("#nome").val() +  "</p>" +
		"<p>E-mail: " +	$("#email").val() +	"</p>" +
		"<p>Telefone : (" +	$("#ddd").val() +	") " +	$("#telefone").val() +	"</p>" +
		"<h4>Dados do Transporte</h4>" +
		"<p>Origem : " + $("#origem").val() + "</p>" +
		"<p>Destino: " + $("#destino").val() +  "</p>" +
		"<p>Valor: " + 	$("#valor").val() +	" (" +	$("#tamanho_veiculo").val() + ")</p>";
		
		if (j.resultado == "2") {
			//dados += "<p><span class=\"destaque\">Seu veículo/transporte possui características especiais e não pode ser cotado automaticamente. Um de nossos atendentes entrará em contato. Obrigado!</span></p>";
			//$("#orcamento-resultado-conteudo").html(dados);
			resultado = "Seu veículo/transporte possui características especiais e não pode ser cotado automaticamente. Um de nossos atendentes entrará em contato. Obrigado!"; 
		}
		else {
			//dados += "<p class=\"destaque_valor\">O valor para transporte do seu veículo é de <span class=\"preco\"> " + j.valor + "</span>.</p><p id=\"orcamento_complementar\">Seu pedido de orçaamento foi registrado em nosso sistema. Entraremos em contato em breve!</p>";
			//$("#orcamento-resultado-conteudo").html(dados);
			resultado = "O valor para transporte do seu veículo é de <b> " + j.valor + "</b>.</p><p id=\"orcamento_complementar\">Seu pedido de orçaamento foi registrado em nosso sistema. Entraremos em contato em breve!";
		}
		
		$("#nome").attr('value', '');
		$("#email").attr('value', '');
		$("#ddd").attr('value', '');
		$("#telefone").attr('value', '');
		$("#origem").attr('value', '');
		$("#destino").attr('value', '');
		$("#valor").attr('value', '');		
	}
    $('#orcamento-resultado').show();
	
	contentLeft 	= document.getElementById('left-sidebar');
    orcamentoResult = document.getElementById('orcamento');
    contentLeft.style.paddingTop = parseInt(orcamentoResult.offsetHeight - 15)  + 'px';	
	
	location.href="resultado_orcamento.php?msg=" + URLEncode(resultado);
}

var inputCidade = "";
function updateRecords(obj)
{   
    if (obj.name == "origem") cidadeValida.origem = false;
    else cidadeValida.destino = false;
    
    var value  = obj.value;
    if (value.length > 2)
    {	
        inputCidade = obj;
        
        var params = new Object();
        params["name"] = value;

        ajaxRequest = new AjaxRequest("ds_cidade.php"     , params);
		ajaxRequest.AddOnCompleteListener("OnComplete"    , onResponseReceived);        
		ajaxRequest.MakeQuery();
    }
    else
    {
        OcultarDivsResultado();      
    }
}

function onResponseReceived(xml)
{
    var names          = xml.getElementsByTagName("name");
    var ufs            = xml.getElementsByTagName("uf");
    
    var divResultado    = (inputCidade.name == "origem" ? document.getElementById("resultado_origem") : document.getElementById("resultado_destino"));
    if (names.length > 0)
    {
        var html    = "";        
        for (var i = 0; i < names.length;  i++)
        {
            var value = names[i].childNodes[0].nodeValue + " / " + ufs[i].childNodes[0].nodeValue;
            html += "<p><a href=\"javascript:SelecionarItem('" + value + "')\"> " + value + "</a></p>";
        }
        html += "<p>&nbsp;</p>";
        divResultado.innerHTML = html;
        divResultado.style.visibility = 'visible';    
    }
    else divResultado.style.visibility = 'hidden'; 
}

function SelecionarItem(nome)
{
    if (inputCidade.name == "origem") cidadeValida.origem = true;
    else cidadeValida.destino = true;
    
    inputCidade.value = nome;
    OcultarDivsResultado();    
}  

function OcultarDivsResultado()
{
    var div    = document.getElementById("resultado_origem");
    div.style.visibility = 'hidden';
    
    div    = document.getElementById("resultado_destino");
    div.style.visibility = 'hidden';    
}

$(document).ready(function()
{	
    //Padding para garantir aparecer o box de noticias
    contentLeft                     = document.getElementById('left-sidebar');
    orcamentoResult                 = document.getElementById('orcamento');
    contentLeft.style.paddingTop    = parseInt(orcamentoResult.offsetHeight - 15) + 'px';    

    $('#orcamento-resultado').hide();
    $('#orcamento-erro').hide();
    $('#orcamento-loading').hide();
    
    $('#orcamento-erro a').click(function(){
        $('#orcamento-erro').fadeOut('normal');                 
    });
    
    
    $('#orcamento-resultado a#voltar').click(function(){
        $('#orcamento-inputs').show();
        $('#orcamento-resultado').hide();
             
        //Padding para garantir aparecer o box de not�cias
        contentLeft = document.getElementById('left-sidebar');
        orcamentoResult = document.getElementById('orcamento');
        contentLeft.style.paddingTop = parseInt(orcamentoResult.offsetHeight - 15)  + 'px';                                     
     });
	
	//### Slide de Notícias ###//		 
	headline_count = $("div.new-scroll").size();
	   $("div.new-scroll:eq(" + current_headline + ")").css('top', '0px');	   
		headline_interval = setInterval(headline_rotate,10000); //time in milliseconds
		
	   $('#noticias-wrap').hover(function() {
		 clearInterval(headline_interval);
	   }, function() {
		 headline_interval = setInterval(headline_rotate,10000); //time in milliseconds
		 //headline_rotate();
	   });
	    $('a#next-news').click(function() {
			if (inTween) return;
			headline_rotate();
			clearInterval(headline_interval);			
		});
		 $('a#prev-news').click(function() {
		 	if (inTween) return;
			prev_headline_rotate();
			clearInterval(headline_interval);			
		});
		$('a#prev-news').hide();
});

function update_buttons_rot()
{
   if (old_headline == headline_count-1) $('a#next-news').hide();
   else $('a#next-news').show();
   
   if (old_headline == 0) $('a#prev-news').hide();
   else $('a#prev-news').show();
}

function headline_rotate() { 
   current_headline = (old_headline + 1) % headline_count;
   inTween = true;
   
   //alert( parseFloat( $("div.new-scroll:eq(" + current_headline + ")").css('top') ) );   
   $("div.new-scroll:eq(" + old_headline + ")").animate({top: -275},"slow", function() {
     $(this).css('top','-280px');
	 inTween = false;
   });
   
   if (parseFloat($("div.new-scroll:eq(" + current_headline + ")").css('top')) < 0) $("div.new-scroll:eq(" + current_headline + ")").css('top','280px');
   $("div.new-scroll:eq(" + current_headline + ")").show().animate({top: 0},"slow");  
   old_headline = current_headline;
   update_buttons_rot();   
}
 
function prev_headline_rotate() {	
   current_headline = (old_headline - 1) % headline_count; 
   inTween = true;
   
   $("div.new-scroll:eq(" + old_headline + ")").animate({top: 275},"slow", function() {
     $(this).css('top','280px');
	 inTween = false;
   });
   
   $("div.new-scroll:eq(" + current_headline + ")").show().animate({top: 0},"slow");  
   old_headline = current_headline;
	update_buttons_rot();   
}

swfobject.embedSWF("anim/mapa.swf", "mapa", "103", "103", "8.0.0", "expressInstall.swf");