(function( $ ) {
	'use strict';
	var map = null;
	var contents_polygon = null;
    var map_center = null;
    var geojson_layer = null;
    var markers = null;
    var hidden_categories = null;
    var list_container = null;
    
    function _GET(param) {
		var vars = {};
		window.location.href.replace( location.hash, '' ).replace( 
			/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
			function( m, key, value ) { // callback
				vars[key] = value !== undefined ? value : '';
			}
		);

		if ( param ) {
			return vars[param] ? vars[param] : null;	
		}
		return vars;
	}

	function update_partner_list() {
		//TODO : store id and state in categories instead of hidden_categories
		//It could avoid to make a part of code below
		$('.wospml_cat_choice').each(function(i,e){
			var state = $(e).data('state') || 'on';
			var catid = $(e).data('catid');
			if (state == 'off') {
				$('.wosmpl_categ[data-catid="'+catid+'"]').hide();
			} else {
				$('.wosmpl_categ[data-catid="'+catid+'"]').show();
			}
		});
	}

	function wosmpl_get_hidden_cats(callback){
		
		var cats = [];
		$('.wospml_cat_choice').each(function(i,e){
			var state = $(e).data('state') || 'on';
			if (state == 'off') {
				cats.push($(e).data('catid'));
			}
		});
		callback(cats);
	}

	

	function filter_category(){
		//.wosmpl_map_cat_filter .wospml_cat_choice img {filter: grayscale(100%);}
		var clicked = $(this);
		var state = clicked.data('state') || 'on';
		var catid = clicked.data('catid');
		if (catid != 0){
			clicked.siblings('div').data('state','off');
			clicked.siblings('div').css('filter','grayscale(100%)');
		} 
		
		if (state == 'off') {
			clicked.data('state','on');
			clicked.css('filter','grayscale(0%)');
			if (catid == 0) {
				clicked.siblings('div').data('state','on');
				clicked.siblings('div').css('filter','grayscale(0%)');
			}
		}
		fill_map();

	}

    function onEachFeature(feature, layer) {
	    // does this feature have a property named popupContent?
	    if (feature.properties && feature.properties.popupContent) {
	        layer.bindPopup(feature.properties.popupContent);
	    }
    }

    function get_cat_icon_url(cat) {
    	return  cat_icon_path + cat_icon_name_prefix + cat + '.png';
    }
	
	function wosmpl_is_feature_to_be_shown(feature) {
		var answer = true;
		var fcat = feature.properties.cat || '';
		if (hidden_categories && hidden_categories.length > 0) {
			for (var i=0;i<hidden_categories.length;i++) {
				if (hidden_categories[i] == fcat) {
					answer = false;
				}
			}
		}
		return answer;
	}
	function wosmpl_point_to_layer(feature, latlng) {
		//console.log(get_icon_url(feature))
		
		if (wosmpl_is_feature_to_be_shown(feature) == true) {
	    	var icon = L.icon({ 
					        iconSize: [50, 50],
					        iconAnchor: [50,25],
					        className: 'wosmpl-icon',
					        iconUrl : get_cat_icon_url(feature.properties.cat || '')
				    	});
	    	
	        return L.marker(latlng, {icon: icon});
    	}
	}

	function fill_layer(hidden_cats) {
		hidden_categories = hidden_cats;
		geojson_layer = L.geoJSON(top.contents_to_show, {
		    pointToLayer: wosmpl_point_to_layer,
		    onEachFeature: onEachFeature
		});
		markers = L.markerClusterGroup({maxClusterRadius: 1});
		// geojson_layer.addTo(map);
		markers.addLayer(geojson_layer);
		map.addLayer(markers);
		set_contents_polygon(function(){
			map.fitBounds(contents_polygon.getBounds());
		});
		update_partner_list();
	}

	function fill_map() {
		if (markers) {
			map.removeLayer(markers);
		}
		wosmpl_get_hidden_cats(fill_layer);
		
	} 
	
	function set_contents_polygon(callback) {
		var points = []; 
		
		$.each(top.contents_to_show, function(i,e) {
			if (e.geometry) {
				if(wosmpl_is_feature_to_be_shown(e)) {
					var lnglat = e.geometry.coordinates;
					points.push([lnglat[1], lnglat[0]]);
				}
			
			}
			
			
		});

		if (points.length > 0) {
			contents_polygon = L.polygon(points);
			map_center = contents_polygon.getBounds().getCenter();
		}

		if (callback)
			callback();
	}

	function init_map() {
		var center = map_center || [43.611379, 3.875849];

		map = L.map('wosmpl-map').setView(center, 13);

		map.scrollWheelZoom.disable();
		// create the tile layer with correct attribution
	    var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
	    var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
	    var osm = new L.TileLayer(osmUrl, {minZoom: 9, maxZoom: 19, attribution: osmAttrib});
	    map.addLayer(osm);
	    var southWest = L.latLng(43.2022, 2.5887),
		    northEast = L.latLng(43.9562, 4.2586);
		var bounds = L.latLngBounds(southWest, northEast);
		map.setMaxBounds(bounds);

	    fill_map();
	    
	}

	$( window ).load(function() {
	 	if (top.contents_to_show) {

	 		// As shorcode doesn't produce div with a map id, we need do choose the first one to be the unique map div
	 		var map_divs = $('div.wosmpl-box.map');
	 		if (map_divs.length > 0) {
	 			var map_content_div = map_divs.first();
	 			map_content_div.attr('id','wosmpl-map');
	 			if(map_size_ref) {
	 				var width = $(map_size_ref).css('max-width') 
	 						   || $(map_size_ref).css('width');
	 				var num_width = width.replace('px','').replace('%','');

	 				if(isNaN(num_width)){
	 					num_width = $(map_size_ref).innerWidth();
	 					if (!isNaN(num_width)) {
	 						width = num_width + 'px';

	 					}
	 				} 
	 				if (num_width / 640 < 0.8) {
	 					map_content_div.css('height', width);
	 				}
	 			
	 				map_content_div.css('width', width);
	 			}
	 			init_map();
	 			list_container = $('div.wosmpl-box.partner_list');
	 			$('.wospml_cat_choice').click(filter_category);
	 		}

	 		
	 	} 
	});
})( jQuery );
