/*
Java script taxi 
Programador :  Luiz Bonsaver
descrição : controle de calculo de tarifa ,e distancia 
ultima atualização:08/01/2009 Pablo Torres(escolher cidade no IE)
*/

// JavaScript Document
	var xml = carregarXml("xmltaxi/tarifastaxi.xml");
	var GB_ANIMATION;
	var map;
    var gdir;
	var geocoder = null;
    var addressMarker;
// novas varaiaveis 
    var newMarkers = [];
    var latLngs = [];
    var icons = [];
//novas varaiaveis
////////////////// guilherme Alterações///////////////////////////////////	
function onGDirectionsAddOverlay(){ 
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }

  // Loop through the markers and create draggable copies
  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
    map.addOverlay(newMarkers[i]);

    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragend", function(){
      var points = [];
      for (var i=0; i<newMarkers.length; i++){
        points[i]= newMarkers[i].getLatLng();
      }
      gdir.loadFromWaypoints(points);
    });

    //Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
  }

  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      //GEvent.trigger(oldMarker,'click');
    });
  }
}
////////////////// guilherme Alterações///////////////////////////////////
	//funcao inicial
    function load() {
		if (!GBrowserIsCompatible()) {
			alert("Desculpe, a API do GoogleMaps não é compatível com este browser");
		}
		else {
			map = new GMap2(document.getElementById("map"));
			gdir = new GDirections(map, document.getElementById("directions"));
			GEvent.addListener(gdir, "load", calcularTarifas);
			GEvent.addListener(gdir, "error", erros);
             GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay, calcularTarifas);
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			document.getElementById("txtorigem").select(erros);
			$("#box_top3").hide();
		}
    }// fim funcao load

	//carrega o arquivo xml com cidades e tarifas
	function carregarXml(url){
        if(window.XMLHttpRequest){
            var Loader = new XMLHttpRequest();
            Loader.open("GET", url ,false);
            Loader.send(null);
            return Loader.responseXML;
        }//fim if
		else if(window.ActiveXObject){
            var Loader = new ActiveXObject("Msxml2.DOMDocument.3.0");
            Loader.async = false;
            Loader.load(url);
            return Loader;
        }//fim do else
    }//fim funcao carregarXml
	
	//carrega as direcoes do google
	function direcoes() {
      var local = "pt_BR";
      var pais = "Brasil";
      var combo = document.getElementById("cmbCidade");
      var estado = combo.options[combo.selectedIndex].value;
      var cidade = combo.options[combo.selectedIndex].text;
      var origem = document.getElementById("txtorigem").value + "," + cidade + "," + estado + "," + pais;
      var destino = document.getElementById("txtdestino").value + "," + cidade + "," + estado + "," + pais;
	  gdir.load("from: " + origem + " to: " + destino,{ "locale": local });
	}// fim funcao direcoes
	
	//carrega a cidade
	function carregarCidade(){
        var Elem = xml.getElementsByTagName("tarifa");
		for(i=0;i<Elem.length;i++){
            var item = Elem[i];
            var value =  item.getElementsByTagName("estado")[0].firstChild.nodeValue;
			var text =  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;
            var combo = document.getElementById("cmbCidade");
            combo.options[i]=new Option(text,value);
        }//fim for
		lerUltimaCidade();
    }// fim funcao carregarCidade
    
	//carrega as tarifas da cidade escolhida
    function carregarTarifas() {
        var combo = document.getElementById("cmbCidade");
        var seltext = combo.options[combo.selectedIndex].text;
        var Elem = xml.getElementsByTagName("tarifa") ;

        for(var i=0;i<Elem.length;i++){
            var item = Elem[i];
            
            if(item.getElementsByTagName("cidade")[0].firstChild.nodeValue == seltext){
                this.bandeirada =  parseFloat(item.getElementsByTagName("bandeirada")[0].firstChild.nodeValue);
			    this.bandeira1 =  parseFloat(item.getElementsByTagName("bandeira1")[0].firstChild.nodeValue);
                this.bandeira2 = parseFloat(item.getElementsByTagName("bandeira2")[0].firstChild.nodeValue);
                return;
			}//fim if
        }//fim for
    }// fim funcao carregarTarifas
	
	//calculo das tarifas
	function calcularTarifas(){
		$("#box_top").fadeOut("fast");
		$("#box_top2").fadeIn("slow");
	    var result1
		var result2
	    var gdis = gdir.getDistance();
	    var tarifa = new carregarTarifas();
		var combo = document.getElementById("cmbCidade");
		var cidade = combo.options[combo.selectedIndex].text;
		
		if (cidade == "São Paulo"){
			preco1= Math.round((tarifa.bandeirada + (tarifa.bandeira1 * (gdis.meters/1000)))*100)/100;
			preco1total=(preco1*0.02)+preco1;
			document.getElementById("tar1").innerHTML = "R$ "+preco1total.toFixed(2);
			preco2= Math.round((((tarifa.bandeirada * 0.3)+ tarifa.bandeirada) + (((tarifa.bandeira1 * 0.3) + tarifa.bandeira1) * (gdis.meters/1000)))*100)/100;
			preco2total=(preco2*0.02)+preco2;
			document.getElementById("tar2").innerHTML = "R$ "+preco2total.toFixed(2);
		}
		else{
			preco1= Math.round((tarifa.bandeirada + (tarifa.bandeira1 * (gdis.meters/1000)))*100)/100;
			preco1total=(preco1*0.02)+preco1;
			document.getElementById("tar1").innerHTML = "R$ "+preco1total.toFixed(2);
			preco2= Math.round((tarifa.bandeirada + (tarifa.bandeira2 * (gdis.meters/1000)))*100)/100;
			preco2total=(preco2*0.02)+preco2;
			document.getElementById("tar2").innerHTML = "R$ "+preco2total.toFixed(2);
		}
	}// fim funcao calcularTarifas
	
	//erros possiveis
	function erros(){
		
	   if(gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
	     document.getElementById("erro").innerHTML = "Lougradouro não encontrado, verifique a ortografia e tente novamente.";
		 $("#erro").slideDown("slow");
		}
	}// fim funcao erros
	
	//enter para calcular o preco da corrida
	function enterPress(e){
		var k=e.keyCode;
		if (k == 13)
			direcoes();
	}//fim funcao enterPress
	
	//muda a url de acordo com a cidade escolhida
	/*function url(){
		var url="http://localhost/taxi_com_br_0.1/";
	    var addon=document.getElementById("cmbCidade").value;
    	location.href=url+addon;
	}//fim funcao url*/
	
	$(document).ready(function(){
			
		$("#cmbCidade").change(function(){
			$("#box_top0").fadeOut("fast");
			$("#box_top").fadeIn("slow");
			document.getElementById("cmbCidade2").selectedIndex = document.getElementById("cmbCidade").selectedIndex;
			salvarUltimaCidade();
		});
		
		$("#cmbCidade2").change(function(){
			document.getElementById("cmbCidade").selectedIndex = document.getElementById("cmbCidade2").selectedIndex;
			salvarUltimaCidade();
		});
		$("#btnvoltar").click(function(){
			$("#box_top2").fadeOut("fast");
			$("#box_top").fadeIn("slow");
			$("#erro").hide();
			$("#erro2").hide();
		});
		$("#btninfo").click(function(){
			$("#box_top2").fadeOut("fast");
			$("#box_top3").fadeIn("slow");
		});
		$("#btnvoltar2").click(function(){
			$("#box_top3").fadeOut("fast");
			$("#box_top2").fadeIn("slow");
		});
		$("#btnnovapesquisa").click(function(){
			$("#box_top").fadeOut("fast");
			$("#box_top").fadeIn("slow");
			$("#erro").hide();
			$("#erro2").hide();
			$("#form1")[0].reset();
		});	
		$("#btnnovapesquisa1").click(function(){
			$("#box_top2").fadeOut("fast");
			$("#box_top").fadeIn("slow");
			$("#erro").hide();
			$("#erro2").hide();
			$("#form1")[0].reset();
		});
		$("#btnnovapesquisa2").click(function(){
			$("#box_top3").fadeOut("fast");
			$("#box_top").fadeIn("slow");
			$("#erro").hide();
			$("#erro2").hide();
			$("#form1")[0].reset();
		});
	    lastBlock = $("#a1");
    	maxWidth = 215;
	    minWidth = 75;
		
		var GB_ANIMATION = true;
	       	$("a.greybox").click(function(){
				var t = this.title || $(this).text() || this.href;
          		GB_show(t,this.href,600,900);
          		return false;
        	});
			
		$("ul li a").hover(function(){
			$(lastBlock).animate({width: minWidth+"px"}, { queue:false, duration:400 });
			$(this).animate({width: maxWidth+"px"}, { queue:false, duration:400});
			lastBlock = this;
		});
	});
	
	function lerUltimaCidade() {
		var cidade = readCookie("ultimaCidade");
		var cmb1 = document.getElementById("cmbCidade");
		var cmb2 = document.getElementById("cmbCidade2");
		for(var i=0; i < cmb1.options.length; i++) {
			cmb2.options[i] = new Option(cmb1.options[i].text, cmb1.options[i].value);
		}
		
		if(cidade != undefined) {	
			document.getElementById("cmbCidade").selectedIndex = parseInt(cidade);
			document.getElementById("cmbCidade2").selectedIndex = parseInt(cidade);
			$("#box_top").show();
		} else {
			$("#box_top0").show();
		}
		
	}
	
	function salvarUltimaCidade() {
		createCookie("ultimaCidade", document.getElementById("cmbCidade").selectedIndex, 365);
	}
	
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}