
var map = null;
var geocoder = null;
var bounds= new GLatLngBounds;
var idmunicipi_ant, address_ant, cl_ant;
var limits;
var limits_autoritzats;
var actual_cantonada_SO;
var actual_cantonada_NE;
var lat_centre_actual=0.0;
var long_centre_actual=0.0;
var modo_buscar=0;		//0=tot municipi, 1=per carrer
var gicone=[];			//icones normals
var gicone1=[];			//icones empresa
var gicone2=[];			//icones escoles
//var giconep=[];			//icones petits
var gicone_carrer;
var iniciat_click=0;

var lat_inici=42.26549833;
var long_inici=3.15961833;
var zoom_inici=10;
var limit_lat_minima=41.906365;
var limit_lat_maxima=42.621833;
var limit_long_minima=2.290;
var limit_long_maxima=3.790;

var strtipus_residu=Array("","Paper","Envasos","Vidre");

function load()
{
	if (GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById("map"));

		map.enableDoubleClickZoom();		//map.enableContinuousZoom();
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl() );
		map.addControl(new GOverviewMapControl() );
		//map.setCenter(new GLatLng(lat_inici,long_inici),zoom_inici);
		//geocoder = new GClientGeocoder();
	}
	//GEvent.addListener(map, "move", function() { mou_mapa(); } );	// afegeix funcio al moure mapa
	//GEvent.addListener(map, "click", function() { retorna_limits_mapa(); } );	// afegeix funcio comprova_limits al Event 'move'
	//limits_autoritzats= new GLatLngBounds(new GLatLng(limit_lat_minima,limit_long_minima), new GLatLng(limit_lat_maxima,limit_long_maxima));     // limita a empordÃ  aprox

	gicone_carrer = new GIcon();
	gicone_carrer.image = "../Images/Mapas/cDireccio.png";
	gicone_carrer.iconAnchor = new GPoint(8, 27);
	gicone_carrer.infoWindowAnchor = new GPoint(8, 1);

	gicone[1] = new GIcon();
	gicone[1].image = "../Images/Mapas/cPaperMin1_18x18.gif";
	gicone[1].iconAnchor = new GPoint(5, 14);
	gicone[1].infoWindowAnchor = new GPoint(9, 5);
	gicone[2] = new GIcon();
	gicone[2].image = "../Images/Mapas/cEnvasosMin1_18x18.gif";
	gicone[2].iconAnchor = new GPoint(9, 16);
	gicone[2].infoWindowAnchor = new GPoint(9, 5);
	gicone[3] = new GIcon();
	gicone[3].image = "../Images/Mapas/cVidreMin1_18x18.gif";
	gicone[3].iconAnchor = new GPoint(13, 18);
	gicone[3].infoWindowAnchor = new GPoint(9, 5);

	gicone1[1] = new GIcon();
	gicone1[1].image = "../Images/Mapas/cPaperMin1_18x18_comercial.gif";
	gicone1[1].iconAnchor = new GPoint(5, 14);
	gicone1[1].infoWindowAnchor = new GPoint(9, 5);
	gicone1[2] = new GIcon();
	gicone1[2].image = "../Images/Mapas/cEnvasosMin1_18x18_comercial.gif";
	gicone1[2].iconAnchor = new GPoint(9, 16);
	gicone1[2].infoWindowAnchor = new GPoint(9, 5);
	gicone1[3] = new GIcon();
	gicone1[3].image = "../Images/Mapas/cVidreMin1_18x18_comercial.gif";
	gicone1[3].iconAnchor = new GPoint(13, 18);
	gicone1[3].infoWindowAnchor = new GPoint(9, 5);

	gicone2[1] = new GIcon();
	gicone2[1].image = "../Images/Mapas/cPaperMin1_18x18_escoles.gif";
	gicone2[1].iconAnchor = new GPoint(5, 14);
	gicone2[1].infoWindowAnchor = new GPoint(9, 5);
	gicone2[2] = new GIcon();
	gicone2[2].image = "../Images/Mapas/cEnvasosMin1_18x18_escoles.gif";
	gicone2[2].iconAnchor = new GPoint(9, 16);
	gicone2[2].infoWindowAnchor = new GPoint(9, 5);
	gicone2[3] = new GIcon();
	gicone2[3].image = "../Images/Mapas/cVidreMin1_18x18_escoles.gif";
	gicone2[3].iconAnchor = new GPoint(13, 18);
	gicone2[3].infoWindowAnchor = new GPoint(9, 5);
}

function load2_sense_municipi()
{
	map.setCenter(new GLatLng(lat_inici,long_inici),zoom_inici);
	geocoder = new GClientGeocoder();
}

function load2_amb_municipi_1(idresidu)
{
	busca_exclusions();
	document.getElementById("checkresidu1").checked=false;
	document.getElementById("checkresidu2").checked=false;
	document.getElementById("checkresidu3").checked=false;
	document.getElementById("checkresidu"+idresidu).checked=true;
	boto_mapa_click();
}
function load2_amb_municipi_2()
{
	map.setCenter(new GLatLng(lat_centre_actual,long_centre_actual),zoom_inici);
	geocoder = new GClientGeocoder();
}

function busca_address(address,municipi) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point)
            {
              alert ("Address no trobada");
            }
            else
            {
             // map.addControl(new GSmallMapControl());
	      map.addControl(new GMapTypeControl());
	      map.setCenter(point, 16);
              var marker_carrer = new GMarker(point,gicone_carrer);
              map.addOverlay(marker_carrer,gicone_carrer);
              marker_carrer.openInfoWindowHtml("<span class='TextoErr' style='padding-left: 0px;'><b>"+document.frm_ppal.address.value+"<br>"+municipi+"</b></span>");
            }
          }
        );
      }
}

function boto_mapa_click()
{
	var index_select_municipi=document.frm_ppal.Municipios.selectedIndex;
	var municipi=document.frm_ppal.Municipios.options[index_select_municipi].text;
	var idmunicipi=document.frm_ppal.Municipios.options[index_select_municipi].value;
	var address=document.frm_ppal.address.value;

	if (address.length>0) modo_buscar=1;
	else modo_buscar=0;

	var residus="";
	if (document.frm_ppal.tipus_residu[0].checked) residus="1";
	if (document.frm_ppal.tipus_residu[1].checked) residus=residus+"2";
	if (document.frm_ppal.tipus_residu[2].checked) residus=residus+"3";

        var cl="no";
        if (document.frm_ppal.cl[1].checked)
        { if (!document.frm_ppal.cl[0].checked) cl="nomes";
          else cl="afegir";
        }

	var refrescar_mapa="no";
	if (idmunicipi!=idmunicipi_ant || address!=address_ant || cl!=cl_ant) refrescar_mapa="si";

	var str="";

	if (index_select_municipi==0)
	{	alert("S'ha de triar un municipi de la llista");
	}
	else if (residus.length==0)
	{	alert("S'ha triar almenys un tipus de residu");
	}
	else
	{
		busca_contenidors(municipi,idmunicipi,residus,refrescar_mapa,cl);

		if (modo_buscar==0 && refrescar_mapa=="si")					// tot municipi, auto-limits, auto-zoom
		{  // res de moment
		}
		else							// s'ha buscat per carrer
		{
			if (refrescar_mapa=="si")   // si s'ha canviat municipi o adreÃ§a es calcula mapa, sino no.
			{
		  		if (address.length>0) str=address+", ";
		  		busca_address(str+municipi+", spain",municipi);
                	}
		}
		idmunicipi_ant=idmunicipi;
		address_ant=address;
		cl_ant=cl;
	}
}

function busca_contenidors(municipi,idmunicipi,residus,refrescar_mapa,cl)
{
	bounds = new GLatLngBounds;
        frames["recarregar_dades"].location="busca_contenidors.asp?idm="+idmunicipi+"&res="+residus+"&ltmin="+limit_lat_minima+"&ltmax="+limit_lat_maxima+"&lgmin="+limit_long_minima+"&lgmax="+limit_long_maxima+"&rm="+refrescar_mapa+"&cl="+cl;
}

function captura_nou_centre(nlatitud,nlongitud)
{
	lat_centre_actual=nlatitud;
	long_centre_actual=nlongitud;
}

function retorna_limits_mapa()
{
	limits=map.getBounds();
	actual_cantonada_SO=limits.getSouthWest();
	actual_cantonada_NE=limits.getNorthEast();

	alert (actual_cantonada_SO.lat()+"/"+actual_cantonada_SO.lng()+" - "+actual_cantonada_NE.lat()+"/"+actual_cantonada_NE.lng());
}

function comprova_limits() 						// comprova limits
{
        if (limits_autoritzats.contains(map.getCenter())) 			// ok limits empordÃ
        {
          return;
        }

        // s'estÃ n desplaÃ§ant fora de l'empordÃ :

        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = limits_autoritzats.getNorthEast().lng()/2;
        var AmaxY = limits_autoritzats.getNorthEast().lat()/2;
        var AminX = limits_autoritzats.getSouthWest().lng()/2;
        var AminY = limits_autoritzats.getSouthWest().lat()/2;

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        map.setCenter(new GLatLng(Y,X));

}

function mou_mapa()
{
	limits=map.getBounds();
	actual_cantonada_SO=limits.getSouthWest();
	actual_cantonada_NE=limits.getNorthEast();

        frames["recarregar_dades"].location="move_busca_contenidors.asp?res="+residus+"&ltmin="+limit_lat_minima+"&ltmax="+limit_lat_maxima+"&lgmin="+limit_long_minima+"&lgmax="+limit_long_maxima;
}

function representa_mapa(zoom_obligat)
{
	var nivell_zoom=13;
	nivell_zoom=map.getBoundsZoomLevel(bounds);
	if (lat_centre_actual<limit_lat_minima || lat_centre_actual>limit_lat_maxima || long_centre_actual<limit_long_minima || long_centre_actual>limit_long_maxima)
	{ lat_centre_actual=lat_inici;
	  long_centre_actual=long_inici;
	  nivell_zoom=zoom_inici;
	}
	if (nivell_zoom>15) nivell_zoom=15;
	else zoom_inici=nivell_zoom;
	if (zoom_obligat>0) nivell_zoom=zoom_obligat;

	map.setCenter(new GLatLng(lat_centre_actual,long_centre_actual),nivell_zoom);
}

function crear_Marker(idcontenidor,point,html,tipus_residu,tipo_entidad)
{
        var marker;
        if (tipo_entidad==1)  marker=new GMarker(point,gicone1[tipus_residu]); 		//empreses
        else if (tipo_entidad==2)  marker=new GMarker(point,gicone2[tipus_residu]); 	//escoles
        else marker=new GMarker(point,gicone[tipus_residu]); 				//municipals

	var dades = new Array();
	dades[0]=new GInfoWindowTab ("General", html);
	dades[1]=new GInfoWindowTab ("Recollides", "<div id='tab"+idcontenidor+"' class='TextoMaps' style='text-align:center;'><br><br><b>Buscant recollides...</b><br><br>Un moment, si us plau.</div>");

        GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(dades); canvia_contingut_infowindow(idcontenidor); });
        return marker;
}

function posa_punt(idcontenidor,idselectiva,latitud,longitud,via,tipus_residu,tipo_entidad,tenir_en_compte_per_zoom,fecha_alta)
{
      var latitud_format,longitud_format;
      var point = new GLatLng(latitud,longitud);
      var contingut_marker="<table border='0' width='240'><tr valign='top'><td>";

      contingut_marker+="<img src='";
      if (tipo_entidad==1)  contingut_marker+=gicone1[tipus_residu].image 		//empreses
      else if (tipo_entidad==2)  contingut_marker+=gicone2[tipus_residu].image 	//escoles
      else contingut_marker+=gicone[tipus_residu].image				//municipals
      contingut_marker+="' border='0'>";
      contingut_marker+="</td><td class='TextoMaps'>";

      contingut_marker+="Refer&egrave;ncia: <b>"+idselectiva+"</b>";
      contingut_marker+="<br>Tipus residu: <b>"+strtipus_residu[tipus_residu]+"</b>";
      contingut_marker+="<br>Via: <b>"+via+"</b>";
      contingut_marker+="<br>Data alta: <b>"+fecha_alta+"</b>";
      contingut_marker+="<br><span id='darrera"+idcontenidor+"'>Buscant recollides...<br>&nbsp;</span>";
      contingut_marker+="<br>&nbsp;";

      contingut_marker+="<br><a href=\"javascript:plana_incidencia("+idcontenidor+","+tipus_residu+",'"+idselectiva+"','"+via+"');\">Indicar incid&egrave;ncia >></a>";
      contingut_marker+="<br>&nbsp;";

      contingut_marker+="</td></tr></table>";

      if (tenir_en_compte_per_zoom==1) bounds.extend(point);	// per calcular nivell de zoom
      var marker = crear_Marker(idcontenidor,point,contingut_marker,tipus_residu,tipo_entidad);
      map.addOverlay(marker,gicone[tipus_residu]);
}

function plana_incidencia(idcontenidor,tipus_residu,idselectiva,via)
{
	document.getElementById("frm_inci_LMunicipios").value=document.frm_ppal.Municipios.options[document.frm_ppal.Municipios.selectedIndex].value;
	document.getElementById("frm_inci_Contenedor").value=tipus_residu;
	document.getElementById("frm_inci_Via").value=via;
	document.getElementById("frm_inci_Referencia").value=idselectiva;
	document.getElementById("frm_inci_IDContenedor").value=idcontenidor;
	document.getElementById("frm_incidencies").submit();
}

function escriu_quant_trobats(npaper,nenvasos,nvidre,nfora_limits)
{
	var str="Total trobats: <b>" + (npaper+nenvasos+nvidre) + "</b>";
	if (nfora_limits>0)
	{
	  str+="&nbsp;&nbsp;<span class='TextoErr' style='padding-left: 0px;'><b>(-" + nfora_limits + ")</b></span>";
	}
      	document.getElementById("trobats_paper").innerHTML = "paper<br>("+npaper+")";
      	document.getElementById("trobats_envasos").innerHTML =  "envasos<br>("+nenvasos+")"
      	document.getElementById("trobats_vidre").innerHTML = "vidre<br>("+nvidre+")"
      	document.getElementById("totals").innerHTML = str;
}

function canvia_contingut_infowindow(idcontenidor)
{
        frames["recarregar_dades"].location="busca_recollides.asp?idc="+idcontenidor;
}

function activa_plana_recollides(idcontenidor,inici,fi,total)
{
	var cont=0;
	var objecte;
	for (cont=0; cont<total; cont++)
	{
		objecte=document.getElementById("tr"+idcontenidor+"_"+cont);
		if (objecte!=null)
		{
			if (cont>=inici && cont<fi) objecte.style.display = "";
			else objecte.style.display = "none";
		}
	}
	if (inici==0) document.getElementById("seg"+idcontenidor).innerHTML = "<a href='javascript:activa_plana_recollides("+idcontenidor+",6,12,"+total+")'><i>plana 2&nbsp;>></i></a>";
	else document.getElementById("seg"+idcontenidor).innerHTML = "<a href='javascript:activa_plana_recollides("+idcontenidor+",0,6,"+total+")'><i><<&nbsp;plana 1</i></a>";
}


