<?php
			include '../SQL/conexion.php';

			$lvl="Superior"; //$_GET["lvl"];
			$sql	= "			SELECT 'Superior' as Level, CV_CCT as Clave, MUNICIPIO as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Superior LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";
			$sql .= "UNION SELECT 'Media' as Level, CV_CCT as Clave, MUNICIPIO as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Media LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";
						$sql .= "UNION SELECT 'Secundaria' as Level, CV_CCT as Clave, C_NOM_MUN as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Secundaria LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";
						$sql .= "UNION SELECT 'Primaria' as Level, CV_CCT as Clave, C_NOM_MUN as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Primaria LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";
						$sql .= "UNION SELECT 'Preescolar' as Level, CV_CCT as Clave, C_NOM_MUN as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Preescolar LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";
						$sql .= "UNION SELECT 'Inicial' as Level, CV_CCT as Clave, C_NOM_MUN as Municipio, NOMBRECT as Institucion, lat as Lat, lon as Lon, COUNT(respuesta.id_respuesta) AS Respuestas FROM Inicial LEFT JOIN respuesta ON CV_CCT = respuesta.clave_escuela GROUP BY CV_CCT, NOMBRECT ";

						$sql .= ";";

			$result = $conn->query($sql);


//C_NOM_MUN

?>
<!DOCTYPE html>
<html>
	<head>
	<!-- Caracteres latinos -->	
	<meta charset="UTF-8">
	<!-- Estilos -->
	<link type="text/css" rel="stylesheet" href="css/style.css?v<?php echo "2a";//rand(11111,99999); ?>">


	<!-- Estilos leaflet -->
	<link rel="stylesheet" href="css/leaflet.css" />
	<link href='css/MarkerCluster.css' rel='stylesheet' />
	<link href='css/MarkerCluster.Default.css' rel='stylesheet' />

	<!-- Scripts de leaflet -->
		<script src="js/leaflet.js"></script>
		<script src='js/MarkerCluster.js'></script>
		<script src='js/MarkerClusterGroup.js'></script>
		<script src='js/DistanceGrid.js'></script>
		<script src='js/MarkerCluster.QuickHull.js'></script>
		<script src='js/MarkerCluster.Spiderfier.js'></script>
		<script src='js/MarkerClusterGroup.Refresh.js'></script>
		<script src='js/MarkerOpacity.js'></script>
	<!-- Scripts de Charts -->
		<script src="js/Chart.js"></script>

		<script src="js/jquery-3.2.1.min.js"></script>

	<!-- Custom fonts for this template-->
	<link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

		<script>

		// Obtenemos el tiempo inicial...
		var sDate = new Date();
		var sTime = sDate.getTime().toString().substring(0, 10);
		
		// Arreglos de marcadores individuales...
		var lvlMarkers = [];
			lvlMarkers["Inicial"] = [];
			lvlMarkers["Preescolar"] = [];
			lvlMarkers["Primaria"] = [];
			lvlMarkers["Secundaria"] = [];
			lvlMarkers["Media"] = [];
			lvlMarkers["Superior"] = [];
		
		// Arreglos de capas de marcadores...	
		var lvlLayers = [];
		
		// Establecemos el zoom inicial...
		var myZoom = 8;
		// Estabecemos el centro inicial...
		var myCenter = [20.6995387,-88.9815442];

		// Mapa general...
		var map;

		// Tiempos de espera...
		var TInterval = 1000;	// Tiempo de espera entre llamadas de actualización...

		// Arreglo de marcadores (cluster)...
		var markers;
		// Marcadores iniciales...
		var bMarkers = false;
				// Contador de instituciones...
				var cInstituciones = 0;

			// Íconos de marcadores...
			var greenIcon, redIcon;

			// Inicialización del mapa...
				function initALL() {

				// Creamos mapa, centro Yuc, zoom 8...
				map = L.map('map').setView(myCenter, myZoom);
				// En cambio de xoom redibujamos clusters...
				map.on('zoomend', function(e){markers.refreshClusters();});
				// Al abrir, cargamos botones de imagen...
				//map.on('popupopen', function(e){VPage(e.popup._source._myID, -1);});

				// Mapa base de openstreet maps (simple)...
				L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
					maxZoom: 19,
					attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
				}).addTo(map);

				// Cluster de marcadores...
				markers = new L.MarkerClusterGroup({

					 iconCreateFunction: function (cluster) {

						var Childs = cluster.getAllChildMarkers();
						var childCount = cluster.getChildCount();
						var Ans = 0, Unans = 0;

						for(A=0;A<Childs.length;A++){				
							if(Childs[A].options.title.indexOf("(0)") != -1){
								Unans+=1;
							}else{
								Ans+=1;
							}
						}

						var Size =	40;
						var c = ' marker-cluster-';
						if (childCount < 10) {
							c += 'small';
							Size = 30;
						} else if (childCount < 100) {
							c += 'medium';
							Size = 40;
						} else {
							c += 'large';
							Size = 50;
						}

						var rID = getRandomNumber(1111,9999); 
						var myIcon = new L.DivIcon({ html: '<div style="white-space: nowrap;	text-shadow: -2px 0 white, 0 2px white, 2px 0 white, 0 -2px white;"><center><canvas id="myChart_'+rID+'" width="'+Size+'" height="'+Size+'" style="opacity:0.6;"></canvas><br><font style="color:#009000"><b>'+Ans+'</b></font> / <font style="color:#F00000"><b>'+Unans+'</b></font><br> (<b>'+ childCount +'</b>)</center></div>', className: 'marker-cluster' + c, iconSize: new L.Point(Size, Size) });
						setTimeout(function () { if(document.getElementById("myChart_"+rID) != undefined) var Icons = new Chart(document.getElementById("myChart_"+rID).getContext("2d")).Pie([{value: (Unans*100/childCount), color:"#FF0000", highlight: "#F00000", label: "Sin participación"}, {value: (Ans*100/childCount), color:"#00FF00", highlight: "#00F000", label: "Con Participación"}], {segmentShowStroke : true, segmentStrokeColor : "#fff", segmentStrokeWidth : 1});}, 500);

						return	myIcon;
					}

				});



				// Marcadores positivos...
				greenIcon = L.icon({
					iconUrl: 'img/marker-icon-green.png',
					shadowUrl: 'img/marker-shadow.png',
					popupAnchor: [1, -45],
					shadowSize: [41, 41],
					shadowAnchor: [13, 40],
					iconSize: [25, 41],
					iconAnchor: [13, 41]
				});

				// Marcadores negativos...
				redIcon = L.icon({
					iconUrl: 'img/marker-icon-red.png',
					shadowUrl: 'img/marker-shadow.png',
					popupAnchor: [1, -45],
					shadowSize: [41, 41],
					shadowAnchor: [13, 40],
					iconSize: [25, 41],
					iconAnchor: [13, 41]
				});


				// Obtenemos los marcadores...
				getMarkers();

			}


			// Adición de marcadores...
			function AddMarker(Level, Key, Name, Lat, Lng, Count){

				// Aumentamos el contador...
				cInstituciones = cInstituciones + 1;
				// Creamos el marcador...
				var marker = L.marker(new L.LatLng(Lat, Lng), {icon: Count==0?redIcon:greenIcon, title:Name +" ("+Count+")", alt:Key});
				marker._myID = Key;

				// Creamos el popup del mapa...
				marker.bindPopup("\
																		<div style='width:100%; height: 100%; border: 0px solid black; Margin-Left:-20px; Margin-Top:-10px; Padding:20px;'>\
																				<div style='width: 100%; height: 100%; border: 0px solid green;'><center><b> \
																				" + Name + "</b></center><hr>" + "<b>Nivel:</b> " + Level + "<br><b>Clave:</b> " + Key + "<br><b>Respuestas:</b> " + Count +
									"</div>\
								</div>", {maxWidth: 1000});	

				// Lo agregamos al arreglo correspondiente...
				lvlMarkers[Level].push(marker);

			}
			
			// Formateo de números con ceros a la izquiera....
			function pad(a,b){return(1e15+a+"").slice(-b)}

			// Generación de números ealeatorios...
			function getRandomNumber(min, max) {
				return Math.random() * (max - min) + min;
			}

			// Converidor RGB a hexadecima...
			var fullColorHex = function(r,g,b) {	 
				var red = rgbToHex(Math.round(r));
				var green = rgbToHex(Math.round(g));
				var blue = rgbToHex(Math.round(b));

				return red+green+blue;
			};

			// Convertidor decimal a hexadecimal...
			var rgbToHex = function (rgb) { 
				var hex = Number(rgb).toString(16);
				if (hex.length < 2) {
					hex = "0" + hex;
				}
	
				return hex;
			};

					
					
					function getMarkers(){
						<?php
							if (!empty($result)){
								foreach ($result as $respuesta){
									echo "AddMarker('".$respuesta["Level"]."', '".$respuesta["Clave"]."', '".$respuesta["Institucion"]."', ".$respuesta["Lat"].", ".$respuesta["Lon"].", ".$respuesta["Respuestas"].");\n";
								}
							}
						?>

						// Agrupamos marcadores...
						lvlLayers["Inicial"] = L.layerGroup(lvlMarkers["Inicial"]);
						lvlLayers["Preescolar"] = L.layerGroup(lvlMarkers["Preescolar"]);
						lvlLayers["Primaria"] = L.layerGroup(lvlMarkers["Primaria"]);
						lvlLayers["Secundaria"] = L.layerGroup(lvlMarkers["Secundaria"]);
						lvlLayers["Media"] = L.layerGroup(lvlMarkers["Media"]);
						lvlLayers["Superior"] = L.layerGroup(lvlMarkers["Superior"]);

						// Agrergamos grupos a capas...
						markers.addLayer(lvlLayers["Inicial"]);
						markers.addLayer(lvlLayers["Preescolar"]);
						markers.addLayer(lvlLayers["Primaria"]);
						markers.addLayer(lvlLayers["Secundaria"]);
						markers.addLayer(lvlLayers["Media"]);
						markers.addLayer(lvlLayers["Superior"]);

						// Agregamos clusters a mapa...
						map.addLayer(markers);
  
					}

		</script>

		</head>

	<body style="overflow: hidden" onload="initALL();">

		<div style="border: 0px solid red; position: absolute; top: 75px; left: -0px; z-index: 1;"> 

		<div class="container">
			<ul class="ks-cboxtags">
				<li><input class = "map-l-button" type="checkbox" id="cbInicial" value="Inicial" checked><label for="cbInicial">Inicial</label></li>
				<li><input class = "map-l-button" type="checkbox" id="cbPreescolar" value="Preescolar" checked><label for="cbPreescolar">Preescolar</label></li>
				<li><input class = "map-l-button" type="checkbox" id="cbPrimaria" value="Primaria" checked><label for="cbPrimaria">Primaria</label></li>
				<li><input class = "map-l-button" type="checkbox" id="cbSecundaria" value="Secundaria" checked><label for="cbSecundaria">Secundaria</label></li>
				<li><input class = "map-l-button" type="checkbox" id="cbMedia" value="Media" checked><label for="cbMedia">Media</label></li>                
				<li><input class = "map-l-button" type="checkbox" id="cbSuperior" value="Superior" checked><label for="cbSuperior">Superior</label></li>                
			</ul>
		</div>

		</div>

		<!-- Div de mapa -->
		<div id="map" style="width:100%; height:98vh;"></div>

<script>
		// Click check button...
		$(".map-l-button").on("click", function() {
			if($(this).prop('checked') == true) {
				markers.addLayer(lvlLayers[$(this).val()]);
			}else{
				markers.removeLayer(lvlLayers[$(this).val()]);			
			}
		});

</script>


	</body>

</html>

