var lojas = new Array();
var markers = new Array();
var map;
var geocoder;
var contador=0;
var gdir;
var markerEstouAqui;
var enderecoPartida;
var enderecoDestino;

function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    geocoder = new GClientGeocoder();

    center = new GLatLng(-23.548881, -46.63765);
	map.setCenter(center, 11);

	map.addMapType(G_PHYSICAL_MAP);
    map.addControl(new GLargeMapControl());
    map.addControl(new GHierarchicalMapTypeControl());

    gdir = new GDirections(map, document.getElementById("tracar-resultado") );

    GEvent.addListener(gdir, "error", handleErrors);
    GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);

    loadEnderecos();
  }
}

function loadEnderecos(){
    GDownloadUrl("listaEnderecos.php", function(data) {
        var xml = GXml.parse(data);
        var loja = xml.documentElement.getElementsByTagName("LOJA");
        for (var i = 0; i < loja.length; i++) {
          var lojaAtual = loja.item(i);
          var nome = GXml.value(lojaAtual.getElementsByTagName("NOME").item(0));
          var telefone = GXml.value(lojaAtual.getElementsByTagName("TELEFONE").item(0));
          var idCanal = GXml.value(lojaAtual.getElementsByTagName("ID_CANAL").item(0));
          var txtCanal = GXml.value(lojaAtual.getElementsByTagName("CANAL").item(0));
          var idCliente = GXml.value(lojaAtual.getElementsByTagName("ID_CLIENTE").item(0));
          var idFilial = GXml.value(lojaAtual.getElementsByTagName("ID_FILIAL").item(0));
          var logo = GXml.value(lojaAtual.getElementsByTagName("LOGO").item(0));
          var site = GXml.value(lojaAtual.getElementsByTagName("SITE").item(0));

          var end = lojaAtual.getElementsByTagName("ENDERECO").item(0);
          var rua = end.getAttribute("RUA");
          var numero = end.getAttribute("NUMERO");
          var bairro = end.getAttribute("BAIRRO");
          var cidade = end.getAttribute("CIDADE");
          var estado = end.getAttribute("ESTADO");
          var latitude = end.getAttribute("LATITUDE");
          var longitude = end.getAttribute("LONGITUDE");

          var endereco = new Endereco(rua, numero, bairro, cidade, estado, latitude, longitude);
          lojas[contador] = new Loja(nome , telefone , idCanal, txtCanal , idCliente , idFilial , endereco, logo, site);
          addLocation(lojas[contador++]);
        }

	    if($.getURLParam("idFilial")!=null)
	    	listaCliente($.getURLParam("idFilial"), $.getURLParam("idCliente"));
	    else if($.getURLParam("idCanal")!=null)
	    	listaCategoria($.getURLParam("idCanal"));

      });
}

function listaCategoria(idCanal){
	for(i=0;i<contador;i++){
		if(lojas[i].idCanal != idCanal && markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].hide();
		}else if(markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].show();
		}
	}
}

function listaClientes(idCliente){
	ultimoIndice=-1;
	for(i=0;i<contador;i++){
		if(lojas[i].idCliente == idCliente && markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].show();
			ultimoIndice=lojas[i].idFilial;
		}else if(markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].hide();
		}
	}

	if(ultimoIndice!=-1){
		map.setCenter(markers[ultimoIndice].getPoint());
	}
}

function listaCliente(idFilial, idCliente){
	ultimoIndice=-1;
	for(i=0;i<contador;i++){
		if(lojas[i].idFilial == idFilial && markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].show();
			ultimoIndice=lojas[i].idFilial;
		}else if(markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].hide();
		}
	}

	if(ultimoIndice!=-1){
		map.setCenter(markers[ultimoIndice].getPoint());
	}
}

function listaTodos(){
	for(i=0;i<contador;i++){
		if(markers[lojas[i].idFilial])
			markers[lojas[i].idFilial].show();
	}
}

function showLocationPoint(loja){
    point = new GLatLng( loja.endereco.latitude , loja.endereco.longitude );

    if(markers[ loja.idFilial ]==null){
    	markers[ loja.idFilial ] = createMarker( point , loja);
    	map.addOverlay( markers[loja.idFilial] );
    }
}

function showAddress(endereco) {
    geocoder.getLocations(endereco, function addAddressToMap(response) {

        if (!response || response.Status.code != 200){
        }else{
        	var place = response.Placemark[0];

        	var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

        	if(markerEstouAqui==null){
        		estouAquiIcon = new GIcon();
        		estouAquiIcon.image = "images/icon/estouAquiIcon.png";
        		estouAquiIcon.shadow = "images/icon/estouAquiIconShadow.png";
        		estouAquiIcon.iconSize = new GSize(11, 24);
        		estouAquiIcon.shadowSize = new GSize(22, 28);
        		estouAquiIcon.iconAnchor = new GPoint(6, 24);
        		estouAquiIcon.infoWindowAnchor = new GPoint(6, 1);

        		markerOptions = {icon:estouAquiIcon, draggable:true};

        		markerEstouAqui = new GMarker(point, markerOptions);
        		map.addOverlay(markerEstouAqui);

                html = "Estou Aqui!";
                markerEstouAqui.openInfoWindowHtml(html);

                GEvent.addListener(markerEstouAqui, "click", function() {
              	  markerEstouAqui.openInfoWindowHtml(html);
                });

        		GEvent.addListener(markerEstouAqui, "dragstart", function() {
        			map.closeInfoWindow();
        		});

                GEvent.addListener(markerEstouAqui, "dragend", function() {
              	  if(gdir!=null){
              		if(gdir.getPolyline()){
        				map.removeOverlay(gdir.getPolyline());
        	        }
              		gdir.load( ("from:  @" + markerEstouAqui.getPoint().toUrlValue() + " to:" + enderecoDestino + " @" + gdir.getMarker(1).getPoint().toUrlValue())  , { "locale": "pt-br" , "getPolyline":true} );
              	  }

              	  markerEstouAqui.openInfoWindowHtml(html);
                });

        	}else{
        		map.closeInfoWindow();
        		markerEstouAqui.setPoint(point);

	        	  if(gdir!=null){
	        		if(gdir.getPolyline()){
	    				map.removeOverlay(gdir.getPolyline());
	    	        }
	          		gdir.load( ("from:  @" + markerEstouAqui.getPoint().toUrlValue() + " to:" + enderecoDestino + " @" + gdir.getMarker(1).getPoint().toUrlValue())  , { "locale": "pt-br" , "getPolyline":true} );
	        	  }
        	}
        }
      });
 }

function addLocation(loja) {
	if(loja!=undefined && loja!=null && loja.endereco.latitude!=""){
		showLocationPoint( loja );
	}
}

function validaPosicaoAtual(){
	enderecoPartida = $("#txtDe").attr("value");
	showAddress($("#txtDe").attr("value"));
}

function buscaLojas(){
	q = $("#txtBuscar").attr("value");
	i=0;
	for(i=0;i<contador;i++){
		if(!lojas[i].search(q) && markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].hide();
		}else if(markers[lojas[i].idFilial]){
			markers[lojas[i].idFilial].show();
			i++;
		}
	}

}

function maisZoom(){
	map.setZoom(map.getZoom()+1);
}

function tracarRota(idMarker, endereco){
	enderecoDestino = endereco;
    if(enderecoPartida!=null && gdir!=null){
    	gdir.load( ("from: @" + markerEstouAqui.getPoint().toUrlValue() + " to: " + enderecoDestino + " @" + markers[idMarker].getPoint())  , { "locale": "pt-br" , "getPolyline":true} );
    }else if(enderecoPartida==null){
    	escreveMensagem("Indique a sua posição no campo(Onde estou?) !");
    }
}

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	  escreveMensagem("Endereço não encontrado!");
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	  escreveMensagem("Ocorreu um problema ao fazer sua solicitação!");
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	  escreveMensagem("Ocorreu um problema ao fazer sua solicitação!");
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	  escreveMensagem("Ocorreu um problema ao fazer sua solicitação!");
  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	  escreveMensagem("Ocorreu um problema ao fazer sua solicitação!");
  else escreveMensagem("Ocorreu um problema ao fazer sua solicitação!");
}

function escreveMensagem(mensagem){
	alert(mensagem);
}

function onGDirectionsAddOverlay(){
	// Loop through the markers and create draggable copies
	gdir.getMarker(0).hide();
	gdir.getMarker(1).hide();
	//$("#directions").html($("#directions").html().replace("http://maps.google.com/intl/pt-BR_ALL/mapfiles/icon_greenA.png", ""));

	divOn();
	var cont=0;
      	$(".tracar-resultado img").each(function(){
	  if(cont==0){
		  $(this).hide();
		  $(this).parent().append("<img src=\"\">");
      	  }else{
      		  $(this).hide();
      		  $(this).parent().append("<img src=\"\">");
	  }
	  cont=1;
    });
}

function createMarker(point, loja){

	lojaIcon = new GIcon();
	lojaIcon.image = "images/icon/mixsp_maps.png";
	lojaIcon.shadow = "images/icon/mixsp_maps_shadow.png";
	lojaIcon.iconSize = new GSize(61, 27);
	lojaIcon.shadowSize = new GSize(61, 27);
	lojaIcon.iconAnchor = new GPoint(30, 27);
	lojaIcon.infoWindowAnchor = new GPoint(30, 1);

    markerOptions = {icon:lojaIcon};
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(loja.getHtml());
    });

    return marker;
}