<?php session_start();
if(isset($_REQUEST['debug'])) {ini_set('display_errors', 'On');}
require ('milfs/xajax/xajax.inc.php');
$xajax = new xajax();
//require ('json.lab.php');
require ('milfs/funciones/funciones.php');
require ("milfs/funciones/conex.php");
include ('milfs/librerias/parsedown/Parsedown.php');
//require_once ('includes/markdown.php');
//require ('funciones/convert.php');
$xajax->processRequests();
//if($_REQUEST[id2] =='') {$agregar= $_REQUEST[id];}else {$agregar = $_REQUEST[id2];}
if(isset($_REQUEST['categoria']) AND isset($_REQUEST['buscar'])) {
	$cadena_busqueda = "$_REQUEST[buscar]";
$_REQUEST['buscar'] = "$_REQUEST[categoria]:$_REQUEST[buscar]";
}
$formulario_nombre = remplacetas('form_id','id',$_REQUEST[id],'nombre',"","") ;
$formulario_descripcion = remplacetas('form_id','id',$_REQUEST[id],'descripcion',"","") ;
$descripcion_meta = preg_replace("[\n|\r|\n\r|\t]",'', strip_tags($formulario_descripcion[0]));
$agregar_nombre = remplacetas('form_id','id',$agregar,'nombre',"","") ;
$id_empresa = remplacetas('form_id','id',$_REQUEST[id],'id_empresa',"","") ;
$twitter = remplacetas('empresa','id',"$id_empresa[0]",'twitter','',"","") ;
if($twitter[0] =="") {$twitter[0] ="@tupaleCo";}
$logo = remplacetas('empresa','id',"$id_empresa[0]",'imagen','',"","") ;
$razon_social = remplacetas('empresa','id',"$id_empresa[0]",'razon_social','',"","") ;
$campos_formulario = input_campos("$_REQUEST[id]","categoria");
$uri = "$_SERVER[SERVER_NAME]/$_SERVER[REQUEST_URI]";
$background_imagen = buscar_imagen("$_REQUEST[id]","","","$id_empresa[0]");
$plantilla ="mapa";
$categorias = lista_categorias($_REQUEST['id'],'','mapa') ;
$doble_click = remplacetas('form_parametrizacion','campo',$_REQUEST['id'],'descripcion'," tabla='form_id' and  opcion = 'doble_click'") ;
if($doble_click[0]=='1'){
	$mapa_aviso="Doble click en el mapa para agregar datos.";
$map_click = "

function onMapClick(e) {
	var coordenadas =e.latlng.lat+'|'+e.latlng.lng;
	setCookie('ubicacion',coordenadas, 1);
			sidebar.close();
xajax_formulario_embebido_ajax('','$_REQUEST[id]','','');
}

map.on('dblclick', onMapClick);
";

}else{

	$map_click ="
	function onMapClick(e) {

				sidebar.close();

	}

	map.on('dblclick', onMapClick);
	map.on('click', onMapClick);

	"; $mapa_aviso="";}
$proveedor_mapa = remplacetas('form_parametrizacion','campo',$_REQUEST['id'],'descripcion'," tabla='form_id' and  opcion = 'proveedor_mapa'") ;;
if($proveedor_mapa[0] !=""){
$proveedor ="'$proveedor_mapa[0]'";
}else{
$proveedor = "'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'";

}



$buscador ="
<form action='?id='$_REQUEST[id]' method='get'>

	<input type='hidden' id='id' name='id'  value='$_REQUEST[id]' >
	$campos_formulario'
	<div id='div_campos'></div>

		<input type='text' id='buscar' name='buscar' class='form-control ' placeholder='Buscar'   >
		<br>
		<input type='submit' class='btn btn-info btn-block ' value='Buscar'>


  </form>
  <hr>
";
?>

<!DOCTYPE html>
<html lang="en">
   <head >
   <title><?php echo "$formulario_nombre[0] / $cadena_busqueda" ?> tupale.co</title>
    <meta charset="utf-8">
<!--     <meta name="viewport" content="user-scalable=no, width=device-width,  maximum-scale=1,  initial-scale=1"> -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--     <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <meta name="description" content="">
    <meta NAME="Language" CONTENT="Spanish">

<meta NAME="Revisit" CONTENT="1 days">
<meta NAME="Distribution" CONTENT="Global">
<meta NAME="Robots" CONTENT="All">
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="<?php echo $twitter[0]; ?>">
<meta name="twitter:creator" content="@qwerty_co">
<meta name="twitter:url" content="<?php echo $uri ; ?>">
<meta name="twitter:title" content="<?php echo "$formulario_nombre[0] / $cadena_busqueda" ?> tupale.co">
<meta name="twitter:description" content=" <?php echo $descripcion_meta; ?>">
<meta name="twitter:image" content="<?php echo "$_SESSION[url]images/secure/?file=full/$background_imagen"; ?>">
   <meta property="og:type"  content="article">
<meta property="og:title" content="<?php echo "$formulario_nombre[0] / $cadena_busqueda" ?> tupale.co" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo "$uri"; ?>" />
<meta property="og:image" content="<?php echo "$_SESSION[url]images/secure/?file=full/$background_imagen"; ?>" />
<meta property="og:site_name" content="<?php echo $razon_social[0]; ?>" />
<meta property="og:description" content=" <?php echo $descripcion_meta; ?>" />
   <link rel="shortcut icon" href="<?php echo "milfs/images/secure/?file=150/$logo[0]"; ?>">
     <?php $xajax->printJavascript("milfs/xajax/");  ?>
    <link rel="shortcut icon" href="favicon-152.png">
	<link rel="apple-touch-icon-precomposed" href="favicon-152.png">
	<link rel="stylesheet" href="librerias/leaflet/leaflet.css" />
	<script src="milfs/js/scripts.js"></script>
    <?php
$otro_json = remplacetas('form_parametrizacion','campo',$_REQUEST[id],'descripcion'," tabla='form_id' and  opcion = 'json'","","") ;;
//$obj = file_get_contents('https://www.kleper.net/wiki/RutaPazTerritorial.geojson');
$ids = json_decode($otro_json[0]);
	foreach ($ids as $clave => $valor) {
	if($valor !=""){


				$obj=file_get_contents("$valor[0]");
				$li .="<script>var geojsonAuxiliar_$clave = $obj ;</script>";
				$layer .= "
						var geojsonAux_$clave = L.geoJson(geojsonAuxiliar_$clave, {

			pointToLayer: function(feature, latlng) {
                var smallIcon = new L.Icon({
				     iconSize: [100, 100],
				     iconAnchor: [13, 27],
				     popupAnchor:  [1, -24],
						 className: 'mapIcon',
				    /*iconUrl: feature.properties.icon.iconUrl*/
				     iconUrl: 'https://tupale.co/milfs/images/secure/?file=150/da6d16547658ebc06c5378b30d1ee4bf.png'

					 });
                return L.marker(latlng, {icon: smallIcon});
            },

					onEachFeature: function(feature, layer) {
            	var popupText = feature.properties.description


            layer.bindPopup(popupText)

	 ; }
		});


				";
		$add_layer .= "markers.addLayer(geojsonAux_$clave);";
		$capas_nombre .="geojsonAux_$clave,";
		$capas .= "{
							'$clave': geojsonAux_$clave
							};";
		$overlays ="
		var overlays = $capas ";
	}
	}

		echo $li;

?>


    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<link href="librerias/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="librerias/leaflet/css/leaflet-sidebar.css" />
    <link rel="stylesheet" href="librerias/bootstrap/css/bootstrap.min.css"  />
<?php
$hoja_css = remplacetas('form_parametrizacion','campo',"index",'descripcion'," tabla='hoja_css' and  opcion = 'hoja_css' and id_empresa = '$id_empresa[0]'") ;
if ($hoja_css[0] ==""){ $hoja_estilo ="<link href='./milfs/css/style.css' rel='stylesheet'>";}
else{ $hoja_estilo ="<link href='$hoja_css[0]' rel='stylesheet'>";}
print $hoja_estilo;
$css_adicional = remplacetas('form_parametrizacion','campo',"index",'descripcion'," tabla='css' and  opcion = 'adicional' and id_empresa = '$id_empresa[0]'") ;
if($css_adicional[0] !="") {
$css_adicional ="<style>

$css_adicional[0]

</style>";
print $css_adicional;
}


 ?>
    <style>
        body {
            padding: 0;
            margin: 0;
        }
        html, body, #map {
            height: 100%;
        }
    </style>

</head>
<body onload="">
	<!-- modal -->
<div class='modal fade ' id='muestraInfo' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true' data-backdrop='static' data-keyboard='false'>
	<div class='modal-dialog modal-MD' style='' >
		<div class='modal-content'>
			<div class='modal-header' >
				<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>
				<h4 class='modal-title' id='myModalLabel_info'><div id='titulo_modal'></div></h4>
			</div>
			<div class='modal-body'>
		<div id='muestra_form'></div>
			</div>
			<div class='modal-footer' id='pie_modal'>
			</div>
		</div>
	</div>
</div>
<!-- modal -->

    <!-- optionally define the sidebar content via HTML markup -->
    <div id="sidebar" class="leaflet-sidebar collapsed">

        <!-- nav tabs -->
        <div class="leaflet-sidebar-tabs" >
            <!-- top aligned tabs -->
            <ul role="tablist">
                <li><a href="#home" onclick="sidebar.open();" role="tab"><i class="fa fa-bars active"></i></a></li>
                <li><a href="#search" onclick="sidebar.open();" role="tab"><i class="fa fa-search active"></i></a></li>

            </ul>

            <!-- bottom aligned tabs -->

            <ul role="tablist">
                <li><a href="https://tupale.co"><img title='Powered by Tupale.co' alt='http://tupale.co' class='img img-responsive' src='https://tupale.co/images/icons/icon-152x152.png'></a></li>
            </ul>
        </div>

        <!-- panel content -->
        <div class="leaflet-sidebar-content">
            <div class="leaflet-sidebar-pane" id="home">
                <h1 class="leaflet-sidebar-header">
                    <span id='formulario_titulo_mapa'><?php echo $formulario_nombre[0] ?></span>
                    <span class="leaflet-sidebar-close"><i class="fa fa-caret-left"></i></span>
                </h1>
                <hr>
                <label id='formulario_descripcion_mapa'><?php echo "$formulario_descripcion[0]"; ?></label>
                <center>
                <span class="label label-warning"><?php echo $mapa_aviso; ?></span>
                </center>
                <hr>
								<div id='div_categorias'>
									<?php echo $categorias; ?>
								</div>
             </div>
             <div class="leaflet-sidebar-pane" id="search">
				 <label><h1>Buscar en el Mapa</label>
				 <?php echo $buscador; ?>
			 </div>
        </div>
    </div>
		<div id="map"  title='<?php echo $mapa_aviso; ?>'></div>
    <script src="librerias/leaflet/leaflet.js" crossorigin=""></script>
    <script src="librerias/leaflet/leaflet-providers.js"></script>
    <script src="librerias/leaflet/js/leaflet-sidebar.js"></script>
    <link rel="stylesheet" href="librerias/leaflet/dist/MarkerCluster.css" />
		<link rel="stylesheet" href="librerias/leaflet/dist/MarkerCluster.Default.css" />
		<script src="librerias/leaflet/dist/leaflet.markercluster-src.js"></script>
		<script src="https://code.jquery.com/jquery-3.3.1.js" ></script>
		<script src="./librerias/bootstrap/js/bootstrap.min.js" ></script>

	<!-- <script src="librerias/jquery/jquery-2.1.4.min.js"></script> -->
	<?php
	if(isset($_REQUEST['buscar'])){
	$cadena_busqueda = urlencode($_REQUEST['buscar']);
}else{$cadena_busqueda="";}
/*
if (!copy($geojson_original, $nuevo_fichero)) {
    echo "Error al copiar $geojson_original ...\n";
}
*/
$geojson_generado = "cache/geojson_$_REQUEST[id].json";
if (is_readable($geojson_generado) && $cadena_busqueda=="") {
	 $geojson= "$geojson_generado";
} else {

	if(isset($_REQUEST['nocache'])){
		$geojson = "milfs/geojson.js.php?id=$_REQUEST[id]&buscar=$cadena_busqueda&item=$_REQUEST[item]";
	}else{
		$nombre_geojson = "cache/".md5($_SERVER[QUERY_STRING]).".json";
		$cachetime = 1800;

		//	if (is_readable($nombre_geojson) && time() - $cachetime < filemtime($nombre_geojson) ) {
			if (is_readable($nombre_geojson) ) {
			 $geojson= "$nombre_geojson";
			}else{
		//		if(isset($_REQUEST[generar])){
	include("milfs/includes/datos.php");
		ob_start();
		include ("$site"."milfs/geojson.js.php?id=$_REQUEST[id]&buscar=$cadena_busqueda&item=$_REQUEST[item]");
		$cache = ob_get_contents();
		ob_end_clean();
	$nuevo_fichero = "cache/".md5($_SERVER[QUERY_STRING]).".json";
	$fp = fopen("$nuevo_fichero", 'w');
	fwrite($fp, "$cache");
	fclose($fp);
	$geojson =$nuevo_fichero;
//}else{
	//$geojson = "milfs/geojson.js.php?id=$_REQUEST[id]&buscar=$cadena_busqueda&item=$_REQUEST[item]";
//}
}
//	$geojson = "milfs/geojson.js.php?id=$_REQUEST[id]&buscar=$cadena_busqueda&item=$_REQUEST[item]";
}
}
/*	}else{
		$nombre_geojson = "cache/geojson_$_REQUEST[id].json";
		if (is_readable($nombre_geojson)) {
		   $geojson= "$nombre_geojson";
		} else {
		   $geojson= "milfs/geojson.js.php?id=$_REQUEST[id]";
		}
			//$geojson ="geojsoncaen.js.php";
	}
*/
	 ?>
<!-- debug -->
	<script type="text/javascript" src="<?php echo $geojson; ?>"></script>
	<script src="https://unpkg.com/leaflet-responsive-popup@0.6.4/leaflet.responsive.popup.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-responsive-popup@0.6.4/leaflet.responsive.popup.css" />

    <script>
        // standard leaflet map setup ??
        var map = L.map('map');
      //  map.setView([51.2, 7], 9);

      //  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			//L.tileLayer.provider('Stamen.Watercolor').addTo(map);
        L.tileLayer(<?php echo $proveedor; ?>, {
            minZoom: 3,
          	maxZoom: 19,
            attribution: "Map data &copy; OpenStreetMap contributors <a href='https://tupale.co'>Powered by Tupale.co</a>"
        }).addTo(map);


		var geojson = L.geoJson(geojsonSample, {

			pointToLayer: function(feature, latlng) {
                var smallIcon = new L.Icon({
				     iconSize: [70, 70],
				     iconAnchor: [13, 27],
				     popupAnchor:  [1, -24],
				     autoPanPadding: [30,30],
						 className: 'mapIcon',

				     iconUrl: feature.properties.icon.iconUrl


					 });
                return L.marker(latlng, {icon: smallIcon });
            },

		onEachFeature: function(feature, layer) {
			layer._leaflet_id = feature.properties.control;

            var popupText = L.responsivePopup().setContent(feature.properties.description );
				layer.bindPopup(popupText, {
											  maxWidth: 200
											}

										);

				layer.bindTooltip(feature.properties.title).openTooltip();
				}
				});

		<?php echo $layer; ?>

	//	markers.addLayer(geojsonAux);

var markers = L.markerClusterGroup({
                        spiderfyOnMaxZoom: true,
                        showCoverageOnHover: false,
                        zoomToBoundsOnClick: true,
                        maxClusterRadius: 25,
                        chunkedLoading: true
                });


//		var markers = L.markerClusterGroup();
	//	var markers = L.layerGroup();


		markers.addLayer(geojson).addTo(map);

		<?php echo $add_layer; ?>
		map.fitBounds(geojson.getBounds().pad(Math.sqrt(2) /4));

        // create the sidebar instance and add it to the map
        var sidebar = L.control.sidebar({ container: 'sidebar', autopan: true    })
            .addTo(map)
            .open('home');

function openMarkerPopup(e){
    const markerID = e.id;
    const marker = markers.getLayer(markerID);
    marker.openPopup();

}

<?php echo $map_click; ?>
        // add panels dynamically to the sidebar



        sidebar.on('content', function (ev) {
            switch (ev.id) {

                case 'autopan':
                sidebar.options.autopan = true;
                break;
                default:sidebar.options.autopan = true;

            }
        });





    </script>
    <script language="JavaScript">
		if (screen.width<1024)
		//codigo resolución pequeña
		sidebar.close();
		else

		sidebar.open();
	</script>

<!-- Matomo -->
<script type="text/javascript">
var _paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.tupale.co"]);
_paq.push(["setDomains", ["*.tupale.co","*.firmesconlareserva.org","*.nuestrared.org","*.redhuerteros.org","*.vivirenlafinca.org"]]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.tupale.co/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//stats.tupale.co/matomo.php?idsite=1&amp;rec=1" style="border:0;" alt="" /></p></noscript>
<!-- End Matomo Code -->

</body>
</html>
