jQuery(document).ready(function(){

	var vLayer = '';
	var featureRestare = {};

	jQuery('.wp_osm').each(function(){

		/*var map = new OpenLayers.Map({
		      div: jQuery(this).get(0),
		      projection: new OpenLayers.Projection('EPSG:900913'),
		      'displayProjection': new OpenLayers.Projection('EPSG:4326')
		});
		map.addLayer(new OpenLayers.Layer.OSM("New Layer"));

		var lonLat = new OpenLayers.LonLat( jQuery(this).attr('data-lon'), jQuery(this).attr('data-lat') );
		          
	    zoom = jQuery(this).attr('data-zoom');

	    var layerStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);

    	var pointLayer = new OpenLayers.Layer.Vector("Layer Name", {style: layerStyle});

    	map.addLayer(pointLayer);*/

    	var map = new ol.Map({
	        target:  jQuery(this).get(0),
	        layers: [
	          new ol.layer.Tile({
	            source: new ol.source.OSM()
	          })
	        ],
	        view: new ol.View({
	        	projection: 'EPSG:3857',
	          	center: [  jQuery(this).attr('data-lat'), jQuery(this).attr('data-lon')],
	          	zoom: jQuery(this).attr('data-zoom')
	        })
	    });

    	//marker styles
	    /*var markerStyle = OpenLayers.Util.extend({}, layerStyle);	    
	    markerStyle.pointRadius = 18;
	    markerStyle.fil/*lOpacity = 1;

	    map.setCenter (lonLat, zoom);*/

	    var popup_div = jQuery(this).find('.ol-popup').get(0);

	    var popup_overlay = new ol.Overlay({
		  element: popup_div,
		  autoPan: true,
		  autoPanAnimation: {
		    duration: 250,
		  },
		});
		map.addOverlay(popup_overlay);

		jQuery(this).find('.ol-popup .ol-popup-closer').click(function () {
		  popup_overlay.setPosition(undefined);
		  //closer.blur();
		  return false;
		});

	    var points = [], current_line = [];
	    var markerFeatures =[];

	    jQuery(this).find('.marker').each(function(){

	    	//on ajoute le marker avec l'icone
	    	/*var lon = jQuery(this).attr('data-lon');
	    	var lat = jQuery(this).attr('data-lat');
			var myPoint = new OpenLayers.Geometry.Point(lon, lat);

			var icon_url = jQuery(this).attr('data-icon');
			var currentmarkerStyle = OpenLayers.Util.extend({}, markerStyle);	  
		    currentmarkerStyle.externalGraphic = icon_url;
			var myPointFeature = new OpenLayers.Feature.Vector(myPoint, null, currentmarkerStyle);

			myPointFeature.attributes = {
				name: jQuery(this).attr('data-name'),
				description: jQuery(this).attr('data-description'),
				wikiPage: "http://www.windsorpubliclibrary.com/?page_id=45"
			};
			pointLayer.addFeatures( [ myPointFeature ] );*/

			//on ajoute le marker avec l'icone
	    	var lon = jQuery(this).attr('data-lon');
	    	var lat = jQuery(this).attr('data-lat');
			//var myPoint = new OpenLayers.Geometry.Point(lon, lat);

			var icon_url = jQuery(this).attr('data-icon');

			var iconFeature = new ol.Feature({
			  geometry: new ol.geom.Point([lon,lat]),
			  name: jQuery(this).attr('data-name'),
			  class: jQuery(this).attr('data-class'),
			  description:  jQuery(this).attr('data-description'),
			  img:  jQuery(this).attr('data-img'),
			  link:  jQuery(this).attr('data-link'),
			  periodo:  jQuery(this).attr('data-periodo'),
			  org:  jQuery(this).attr('data-org'),
			  pais:  jQuery(this).attr('data-pais'),
			});

			var icon_img = new Image();
			icon_img.src = icon_url;

			var icon = new ol.style.Icon({
			    anchor: [0.5, 0],
			    anchorOrigin: 'bottom-left',
			    anchorXUnits: 'fraction',
			    anchorYUnits: 'pixels',
			    src: icon_url,
			    // scale: 1,
				// width: 100,
				// height: 100,
			    // img: icon_img,
			    // imgSize: [50, 50]
			});

			var iconStyle = new ol.style.Style({
			  image: icon,
			});

			icon_img.onload = function() {
				icon.setScale(28/icon_img.width);
				iconFeature.changed();
			}

			iconFeature.setStyle(iconStyle);

			markerFeatures.push(iconFeature);

	    });

		// console.log(markerFeatures);

	    var vectorSource = new ol.source.Vector({
		  features: markerFeatures,
		});

		// console.log(vectorSource);

		var vectorLayer = new ol.layer.Vector({
		  source: vectorSource,
		  zIndex: 2,
		});

		map.addLayer(vectorLayer);

		vLayer = vectorLayer;

		map.on('click', function (evt) {
			var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
			    return feature;
			});
			// console.log(feature);
		  	if (feature) {
				// console.log(feature);
			    var description = feature.get('description');
				var name 		= feature.get('name');
				var img 		= feature.get('img');
				var link 		= feature.get('link');
				
				var pais 		= feature.get('pais');
				var org 		= feature.get('org');
				var periodo 	= feature.get('periodo');
			    // if(description != '')
			    // {
				    var coordinate = evt.coordinate;
					// coordinate[0] = coordinate[0] * 100;
					// coordinate[1] = coordinate[1] * 2;
					console.log(coordinate);
					// jQuery(popup_div).find('.popup-content').html(description);
					$('.card-img-top').attr('src', img);
					$('.modal-title').html(name);
					$('.title-map').html(name);
					$('.card-text').html(description);
					$('.pais-map').html(pais);
					$('.org-map').html(org);
					$('.periodo-map').html(periodo);
					if(link != '') {
						$('.card-link').attr('href', link);
						$('.card-link').show();
					} else {
						$('.card-link').hide();
					}

					$('.ol-popup').removeClass('d-none');
					popup_overlay.setPosition(coordinate);
				// }

				// var myModal = new bootstrap.Modal(document.getElementById('exampleModal'), options);
				// myModal.show();
			}

		});

		map.on('pointermove', function (evt) {

		  var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
		    return feature;
		  });

		  if (feature){
		  	//hover marker
		  	jQuery(map.getTargetElement()).find('canvas').css('cursor', 'pointer');

		  }else {
		  	//not hover marker
		  	jQuery(map.getTargetElement()).find('canvas').css('cursor', 'default');
		  }
		});

	    /*selectControl = new OpenLayers.Control.SelectFeature( pointLayer );
		map.addControl(selectControl);
		selectControl.activate();

	    pointLayer.events.on({
		    'featureselected': onFeatureSelect,
		    'featureunselected': onFeatureUnselect
		});

		function onFeatureSelect(clickInfo) {
		    clickedFeature = clickInfo.feature;
		    popup = new OpenLayers.Popup.FramedCloud(
		        "featurePopup",
		        clickedFeature.geometry.getBounds().getCenterLonLat(),
		        new OpenLayers.Size(120,250),
		        clickedFeature.attributes.description,
		        null,
		        true,
		        onPopupClose
		    );
		    clickedFeature.popup = popup;
		    popup.feature = clickedFeature;
		    map.addPopup(popup);
		}
		function onFeatureUnselect(clickInfo) {
		    feature = clickInfo.feature;
		    if (feature.popup) {
		        popup.feature = null;
		        map.removePopup(feature.popup);
		        feature.popup.destroy();
		        feature.popup = null;
		    }
		}
		function hoverFeatureCallback(clickInfo) {

		}
		function onPopupClose(closeInfo) {
		    selectControl.unselect(this.feature);
		}*/

	});

	$('.chk-filter-map').click(function() {
		var emptyImgStyle = new ol.style.Style({ image: '' });
		var arrfeatures = vLayer.getSource().getFeatures();
		
		var arr = [];
		$('.chk-filter-map').each(function(e){
		    var chk = $(this).is(":checked");
		    var id = $(this).attr("id");
		    if (chk) arr.push(id);
		});
		
		console.log(featureRestare);
		
		for( [k, v] of Object.entries(featureRestare) ){
		    arrfeatures[k].setStyle(v);
		}
		featureRestare = {};
		
// 		console.log(arrfeatures);
		
		for( var i = 0; i < arrfeatures.length; i++ ) {
			var classFeature = arrfeatures[i].get('class').split(";;");
			
			var isOk = false;
			for( var j = 0; j < classFeature.length; j++ ) {
			    if(!isOk && arr.includes(classFeature[j])) isOk = true;
			}
			
			if (!isOk) {
			    featureRestare[i] = arrfeatures[i].getStyle();
			    arrfeatures[i].setStyle(emptyImgStyle);
			}
			
			
// 			if(classFeature.includes(id)){
// 				if( featureRestare[i] === undefined )
// 				    featureRestare[i] = arrfeatures[i].getStyle();
// 				arrfeatures[i].setStyle(emptyImgStyle);
// 			}
		}
		
// 		var checked = $(this).is(":checked");
// 		var id = $(this).attr('id');
// 		if(!checked) {
// 			for( var i = 0; i < arrfeatures.length; i++ ) {
// 				var classFeature = arrfeatures[i].get('class').split(";;");
// 				if(classFeature.includes(id)){
// 					if( featureRestare[i] === undefined )
// 					    featureRestare[i] = arrfeatures[i].getStyle();
// 					arrfeatures[i].setStyle(emptyImgStyle);
// 				}
// 			}
// 		} else {
// 		    for( var i = 0; i < arrfeatures.length; i++ ) {
// 				var classFeature = arrfeatures[i].get('class').split(";;");
// 				if(classFeature.includes(id)){
// 					arrfeatures[i].setStyle(featureRestare[i]);
// 				}
// 			}
// 		}
	});

	$('.list-filter-map').click();
});
