<repo_name>ICGCat/Instamaps<file_sep>/geocatweb/js/instamaps.wms-1.0.0.js
/**
 * 
 */
;(function(global, $){
	var InstamapsWms = function(options){
		return new InstamapsWms.init(options);
	};
	
	var _options = {
		proxyUrl: "http://www.instamaps.cat/share/jsp/ows2json.jsp?"	
	};
	
	InstamapsWms.prototype = {
		initUi: function(){
			var self = this;
			self._div = self.container;
			self._botons = self.botons;
			if (self.loadTemplateParam==undefined) self.loadTemplate();
			return self;
		},
		
		loadTemplate: function(){
			var self = this;
			$.get("templates/wmsTemplate.html",function(data){
				self._div.html(data);
				self._uiloaded = true;
				$(".layers-wms").hide();
				
				$(".url-wms").focus(function() {
					self.clear();
					//jQuery('#txt_URLWMS').val('');
				});
					
				$(".btn-conn-wms").on('click', function(e) {
					
					var input = $(e.target).closest('.txt_ext').find('.url-wms');					
				    var url = $.trim(input.val());
					
					if (url === "") {
						alert(window.lang.translate("Has d'introduïr una URL del servidor"));
					} else if (!isValidURL(url)) {
						alert(window.lang.translate("La URL introduïda no sembla correcte"));
					} else {
						self.getCapabilities({url:url});
					}
				});
				
			});
			return self;
		}, 
		
		clear: function(){
			var self = this;
			$('.layers-wms').html('');
			$(".layers-wms").hide();
			self._botons.empty();
			return self;
		},
		
		show: function(){
			var self = this;
			$(".layers-wms").show();
			return self;
		},
		
		getLayers: function(options){
			var self = this;
			$(".url-wms").val(options.url);
			self.url = options.url;
			self.name = options.name;			
			options.capa ? self.capa=options.capa : self.capa=null;			
			self.getCapabilities();
			return self;
		}, 
		
		getWMSLayers: function(data){
			var self = this;
			return jQuery.ajax({
				url: self.proxyUrl,
				data: data,
				async: true,
				method: 'post',
				dataType: 'jsonp',
				timeout: 12000 //timeout WMS
			}).promise();
		},
		
		getCapabilities: function(options){
			var self = this,
				ActiuWMS = {};
			
			self = $.extend(self, options);
			var data = {url: self.url, capa:self.capa};
			
			self.getWMSLayers(data).then(function(results) {
				var bbox, servidor, WMS_BBOX,
				souce_capabilities_template = $("#capabilities-template").html(),
				capabilities_template = Handlebars.compile(souce_capabilities_template);
				
				Handlebars.registerPartial( "list-template", $( "#list-template" ).html() );
				Handlebars.registerHelper('layer', function(context, options) {
				  var ret = "";
				  if (!Handlebars.Utils.isArray(context)){
					  context = [context];
				  }
				  for(var i=0, j=context.length; i<j; i++) {
					  if (!Handlebars.Utils.isArray(context[i])){
						  ret = ret + options.fn(context[i]);
					  }else{
						  for(var k=0, l=context.length; k<l; k++) {
							  ret = ret + options.fn(context[i][k]);
						  }
					  }
				  }
				  return ret;
				});
				Handlebars.registerHelper("debug", function(optionalValue) {
				  console.log("Current Context");
				  console.log("====================");
				  console.log(this);
				 
				  if (optionalValue) {
				    console.log("Value");
				    console.log("====================");
				    console.log(optionalValue);
				  }
				});
				
				self.clear().show();

				if (servidor == null) {
					servidor = results.Service.Title;
				}
				
				
				try{
					if(results.Capability.Layer.Layer.LatLonBoundingBox){
						bbox = results.Capability.Layer.Layer.LatLonBoundingBox;
						WMS_BBOX=[[bbox["@miny"], bbox["@minx"]],[bbox["@maxy"], bbox["@maxx"]]];
					}else if(results.Capability.Layer.LatLonBoundingBox){
						bbox = results.Capability.Layer.LatLonBoundingBox;
						WMS_BBOX=[[bbox["@miny"], bbox["@minx"]],[bbox["@maxy"], bbox["@maxx"]]];
					}else{
						WMS_BBOX=null;
					}	
				} catch (err) {
					WMS_BBOX=null;
				}
				
				try {
					var matriuEPSG = results.Capability.Layer.CRS,
					epsg = [],
					html = "";
					
					if($.isArray(results.Capability.Layer)){
						html = capabilities_template({Layer: results.Capability.Layer});
					}else{
						html = capabilities_template({Layer: [results.Capability.Layer]});
					}
					
					ActiuWMS.servidor = self.name || servidor || results.Capability.Layer.Title;
					ActiuWMS.url = self.url;
					
					
					
					if (!matriuEPSG) {
						matriuEPSG = results.Capability.Layer.SRS;
						if (!matriuEPSG) {
							matriuEPSG = results.Capability.Layer[0].CRS;
							
							if (!matriuEPSG) {
								matriuEPSG = results.Capability.Layer[0].SRS;
							}
						}
					}
					if ($.isArray(matriuEPSG)){
						$.each(matriuEPSG, function(index, value) {
							epsg.push(value);
						});
					}else{
						epsg.push(matriuEPSG);
					}
			
					if ($.inArray('EPSG:3857', epsg) != -1) {
						ActiuWMS.epsg = L.CRS.EPSG3857;
						ActiuWMS.epsgtxt = 'EPSG:3857';
					} else if ($.inArray('EPSG:900913', epsg) != -1) {
						ActiuWMS.epsg = L.CRS.EPSG3857;
						ActiuWMS.epsgtxt = 'EPSG:3857';
					} else if ($.inArray('EPSG:4326', epsg) != -1) {
						ActiuWMS.epsg = L.CRS.EPSG4326;
						ActiuWMS.epsgtxt = '4326';
					} else if ($.inArray('CRS:84', epsg) != -1) {
						ActiuWMS.epsg = L.CRS.EPSG4326;
						ActiuWMS.epsgtxt = '4326';
					} else if ($.inArray('EPSG:4258', epsg) != -1) {
						ActiuWMS.epsg = L.CRS.EPSG4326;
						ActiuWMS.epsgtxt = '4326';	
					} else {
						alert(window.lang.translate("No s'ha pogut visualitzar aquest servei: Instamaps només carrega serveis WMS globals en EPSG:3857 i EPSG:4326"));
						return;
					}
					
					self.ActiuWMS = ActiuWMS;
					
					$('.layers-wms').empty().append(html);
					self.addTreeEvents();
					self._botons.empty();
					self._botons.html(
						'<div style="float:right"><button lang="ca" class="btn btn-success btn-add-wms" >' +
						window.lang.translate("Afegir capes") + '</button></div>');
					
					//if(self.capa){
					if(self.hasOwnProperty('capa')){
						var ls;
						var hits=0;
						//para las capas con nombres de números y que solo son dos capas
						//en el excel puede variar el formato y poner 5.5 en lugar de 5.1
						if(self.capa == null){
							self.capa="null";
						}
						
						self.capa = self.capa.replace(/(\d)\.(\d)/,"$1,$2");
						
						if(self.capa.indexOf(",")!=-1){								//hi ha més una capa
							ls=self.capa.split(",");
							for(i=0; i < ls.length;i++){
								hits=hits + self._ckechLayerWMS(ls[i]);
							}							
						}else{
							
							ls=self.capa;
							hits=hits + self._ckechLayerWMS(ls);
						}	
						
						
						if(hits > 0){
							self.addExternalWMS(false);						
						}else{
							jQuery("#div_controlWMS_OFICIALS").show();
							jQuery("#div_emptyWMS_OFICIALS").show();								
						}						
					}else{
						jQuery("#div_controlWMS_OFICIALS").show();
						jQuery("#div_emptyWMS_OFICIALS").show();
					}
					//ckbox_layer					
					$(".btn-add-wms").on('click', function(e) {
					    self.addExternalWMS(false);
					});
					
				} catch (err) {
					console.debug(err);
					$('.layers-wms').html('<hr lang="ca">'+window.lang.translate("Error en interpretar capabilities")+': ' + err + '</hr>');
				}
			},function(data,status,error){
				status.indexOf('parser')!=-1?alert(window.lang.translate("Error en interpretar capabilities")):alert(window.lang.translate("Error: No s'ha pogut executar l'operació"));
				
				});
			
			return self;
		},
		
		_ckechLayerWMS: function(layerName){
			var self = this;
			var hit=0;
			jQuery(".ckbox_layer").each(function() {		
				if(this.value==layerName){				
				jQuery(this).prop('checked',true);
				hit=hit +1;				
				}				
			});			
			return hit;			
		},	
		
		_getChekedLayers:function(){
			var ch=0;
			$(".ckbox_layer").each(function() {
				if(jQuery(this).prop('checked')){
					ch=ch + 1;
				}
				return ch;					
			});	
		},	
		
		addExternalWMS: function(){
			var self = this,
			_dateFormat = false;
						
			var cc = $('.layers-wms input:checked').map(function(){
				var name = this.value.replace(/:/g,"\\\:");
				try{
					if($('#geoservicetime_'+name).length > 0){
						_dateFormat = true;
					}
				}catch(e){
					
				}
				return this.value;
			});
			
			cc = jQuery.makeArray(cc);
			cc = cc.join(',');
						
			var _nomCapesWMS=[];
			var cc1 = $('.layers-wms input:checked').map(function(){			
				return this.id;
			});
			
			cc1 = jQuery.makeArray(cc1);	
			
			//TODO esto lo debemos activar para la pestaña de WMS y no para las de 
			//dades oficials
			if(cc1.length==1){
				//self.ActiuWMS.servidor=cc1.join(" ");
			}
			
			self.ActiuWMS.wmstime = _dateFormat;
			
			if(cc.length === 0){
				alert(window.lang.translate("Has de seleccionar almenys una capa"));
			}else{
				self.ActiuWMS.layers = cc;
				if(self.callback){
					self.callback(self.ActiuWMS);
				}
			}
			return self;
		},
		
		addTreeEvents: function(){
			var self = this;
			
			$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
		    $('.tree li.parent_li > span').on('click', function (e) {
		        var children = $(this).parent('li.parent_li').find(' > ul > li');
		        if (children.is(":visible")) {
		            children.hide('fast');
		            $(this).attr('title', 'Expand this branch').find(' > i').addClass('glyphicon-folder-close').removeClass('glyphicon-folder-open');
		        } else {
		            children.show('fast');
		            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('glyphicon-folder-open').removeClass('glyphicon-folder-close');
		        }
		        e.stopPropagation();
		    });
		    
		    $('.tree li > span.leaf').on('click', function (e) {
		    	$(this).children('.ckbox_layer').click();
		    });
		    
		    $('.ckbox_layer').on('click', function (e) {
		    	e.stopPropagation();
		    });
		    
		    $('.btn-all').on('click',function(){
		    	$(this).parent('li.parent_li').find('input:checkbox').prop('checked', true);
			});
			
			$('.btn-none').on('click',function(){
				$(this).parent('li.parent_li').find('input:checkbox').prop('checked', false);
			});

			$('.btn-invert').on('click',function(){
				var ul = $(this).parent("li.parent_li").find(".sublayers_list");
				ul.children().each(function(i,li){ul.prepend(li)});
			});
			
			return self;
		}
		
	};
	
	InstamapsWms.init = function(options){
		var self = this;
		self = $.extend(self, _options, options);
		self.initUi();
	};
	
	InstamapsWms.init.prototype = InstamapsWms.prototype;
	
	global.InstamapsWms = InstamapsWms;
	
}(window, jQuery));
<file_sep>/geocatweb/js/leaflet/L.IM_ControlLayerManager.js
L.Control.OrderLayers = L.Control.Layers.extend({
	options : {
		collapsed : true,
		position : 'topright',
		title : 'Title',
		autoZIndex : true,
		autoUpdate: true
	},

	initialize : function(baseLayers, groupedOverlays, options) {
		var i, j;
		
		L.Util.setOptions(this, options);
		
		this._layers = {};
		this._lastZIndex = 0;
		this._handlingClick = false;
		this._groupList = [];
		this._domGroups = [];
		this._socInstamapsVell="_socVisorVellInstamaps_";
		this._mapConfig = options.mapConfig;
		
		for (i in baseLayers) {
			for ( var j in baseLayers[i].layers) {
				this._addLayer(baseLayers[i].layers[j], j,
					baseLayers[i], false);
			}
		}

		for (i in groupedOverlays) {
			for ( var j in groupedOverlays[i].layers) {
				this._addLayer(groupedOverlays[i].layers[j], j, true,
					null, groupedOverlays[i]);
			}
		}
	},

	onAdd : function(map) {
		this._initLayout();
		this._update();
		map.on('layeradd', this._onLayerChange, this).on('layerremove', this._onLayerChange, this);
		return this._container;
	},

	onRemove : function(map) {
		map.off('layeradd', this._onLayerChange).off('layerremove', this._onLayerChange);
	},

	addBaseLayer : function(layer, name, group) {
		this._addLayer(layer, name, group, false);
		this._update();
		return this;
	},

	addOverlay : function(layer, name, overlay, groupLeafletId) {
		this._addLayer(layer, name, overlay, groupLeafletId);
		this._update();
		return this;
	},
	
	removeLayer : function(obj) {
		var id = L.stamp(obj.layer);
		if (!obj.sublayer) {
			delete this._layers[id];
		} else {
			delete this._layers[obj.layerIdParent]._layers[id];
		}

		var _thereIs = false;
		for (layer in this._layers) {
			if (this._layers[layer].layer.options.tipus && this._layers[layer].layer.options.tipus.indexOf(t_wms) != -1) {
				if (this._layers[layer].layer.options.wmstime == true) {
					_thereIs = true;
				}
			}
		}

		showTimeControl(_thereIs);

		this._update();
		if(estatMapa3D){mapaVista3D.actualitzaVistaOverlays(obj.layer.options,"remove",true);}
		return this;
	},

	getCountLayers:function(){
		var i=0;
		for (layer in this._layers) {
			i=i+1;
			for (sublayer in this._layers[layer]._layers) {
				i=i+1;
			}
		}
		return i;
	},
	
	getLayersFromGroupId : function(groupId, groupName) {
		var resp_Layer = [];
		for (layer in this._layers) {
			if (this._layers[layer].layer.options.group.groupName == groupName
				&& this._layers[layer].layer.options.group.id == groupId) {
				resp_Layer.push(this._layers[layer]);
			}
		}
		return resp_Layer;
	},

	updateTreeGroupLayers : function(groupId, groupName, businessId, z_order, expanded) {
		var dfd = $.Deferred();
		try{
			this._groupList[groupId].groupName = groupName;
			this._groupList[groupId].name = groupName;
			this._groupList[groupId].id = groupId;
			this._groupList[groupId].expanded = expanded;
	
			for (layer in this._layers) {
				if (this._layers[layer].layer.options.group
					&& this._layers[layer].layer.options.businessId == businessId) {
					this._layers[layer].layer.options.group.name = groupName;
					this._layers[layer].layer.options.group.groupName = groupName;
					this._layers[layer].layer.options.group.id = groupId;
					this._layers[layer].layer.options.group.z_order = z_order;
					this._layers[layer].layer.options.group.expanded = expanded;
					this._layers[layer].layer.options.zIndex = z_order;
					this._layers[layer].layer.setZIndex(parseInt(z_order)+1);
					map.eachLayer(function(layer) {
						if (layer.options
							&& layer.options.businessId == businessId) {
							try {
								layer.bringToFront();
							} catch (Err) {
							}
						}
					});
					dfd.resolve(this._layers[layer].layer);
				}
			}
		}catch(Err){
			dfd.reject(Err);
			console.debug(Err);
		}
		return dfd.promise();
	},

	updateGroupName : function(oldName, newName, groupId) {
		var resp_Layer = [];
		for (group in this._groupList) {
			if (this._groupList[group].groupName == oldName
				&& this._groupList[group].id == groupId) {
				this._groupList[group].groupName = newName;
				this._groupList[group].name = newName;

				for (layer in this._layers) {
					if (this._layers[layer].layer.options.group
						&& this._layers[layer].layer.options.group.name == oldName
						&& this._layers[layer].layer.options.group.id == groupId) {
						this._layers[layer].layer.options.group.name = newName;
						this._layers[layer].layer.options.group.groupName = newName;
						resp_Layer.push(this._layers[layer].layer);
					}
				}
			}
		}
		this._update();
		return resp_Layer;
	},

	removeGroup : function(groupName, groupId) {
		if (groupName) {
			for (group in this._groupList) {
				if (this._groupList[group].groupName == groupName
						&& this._groupList[group].id == groupId) {
					for (layer in this._layers) {
						if (this._layers[layer].layer.options.group
							&& this._layers[layer].layer.options.group.groupName == groupName
							&& this._layers[layer].layer.options.group.id == groupId) {
							delete this._layers[layer];
						}
					}
					delete this._groupList[group];
					this._update();
					break;
				}
			}
		}
	},

	_initLayout : function() {
		var modeMapa = ($(location).attr('href').indexOf('/mapa.html') != -1);
		var className = 'leaflet-control-layers', 
		container = this._container = L.DomUtil.create('div', className);

		// Makes this work on IE10 Touch devices by stopping it from
		// firing a mouseout event when the touch is released
		container.setAttribute('aria-haspopup', true);

		if (!L.Browser.touch) {
			L.DomEvent.disableClickPropagation(container);
			L.DomEvent.on(container, 'wheel', L.DomEvent.stopPropagation);
		} else {
			L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
		}
		var section = document.createElement('section');
		section.className = 'ac-container ' + className + '-list';
		
		var spiner = this._spiner = L.DomUtil.create('div', className + '-spiner');
		
		spiner.innerHTML = "<i class='fa fa-refresh fa-spin fa-fw margin-bottom'></i>"+
		"<span lang='ca'>Carregant, esperi si us plau...</span>";
		
		section.appendChild(spiner);
		
		var form = this._form = L.DomUtil.create('div', className + '-list');

		if (this.options.title) {
			var title = L.DomUtil.create('h3', className + '-title editable');
			title.innerHTML = this.options.title;
			title.id = 'nomAplicacio';
			form.appendChild(title);
		}

		section.appendChild(form);

		if (this.options.collapsed) {
			if (!L.Browser.android) {
				L.DomEvent.on(container, 'mouseover', this._expand,
					this).on(container, 'mouseout', this._collapse,
					this);
			}
			var link = this._layersLink = L.DomUtil.create('a',
				className + '-toggle', container);
			link.href = '#';
			link.title = 'Layers';

			if (L.Browser.touch) {
				L.DomEvent.on(link, 'click', L.DomEvent.stop).on(link,
					'click', this._expand, this);
			} else {
				L.DomEvent.on(link, 'focus', this._expand, this);
			}

			this._map.on('click', this._collapse, this);
			// TODO keyboard accessibility

		} else {
			this._expand();
		}

		var strLayersList = 'layers-list';
		this._baseLayersList = L.DomUtil.create('div', className + '-base', form);

		this._overlaysList = L.DomUtil.create('ol', className + '-overlays', form);

		if (getModeMapa()) {
			this._addButton = L.DomUtil.create('div', 'addVerd', form);
			L.DomEvent.on(this._addButton, 'click',
				this._addGroupFromScratch, this);

			$(this._addButton).tooltip({
				placement : 'left',
				container : 'body',
				title : window.lang.translate("Nou grup")
			});
		}

		container.appendChild(section);

		// process options of ac-container css class - to
		// options.container_width and options.container_maxHeight
		for (var c = 0; c < (containers = container
		  .getElementsByClassName('ac-container')).length; c++) {
			if (this.options.container_width) {
				containers[c].style.width = this.options.container_width;
			}

			// set the max-height of control to y value of map object
			this._default_maxHeight = this.options.container_maxHeight ? this.options.container_maxHeight
				: (this._map._size.y - 70);
		}
		window.onresize = this._on_resize_window.bind(this);
	},

	_on_resize_window : function() {

	},

	// remove the px from a css value and convert to a int
	_removePxToInt : function(value) {
		if (typeof (value) == "number") {
			return value;
		} else {
			return parseInt(value.replace("px", ""));
		}
	},

	_socVisorInstamaps:function(){
		var self = this;
		var hoSoc=false;
		if (self._mapConfig===undefined) self._mapConfig=mapConfig;
		if(self._mapConfig.tipusAplicacioId==1 && !getModeMapa()){
			hoSoc=true;
		}
		return hoSoc;
	},
	
	_createGroupFromScratch : function(position) {
		var pos = this._groupList.length;
		var posTXT;
		var genericName=window.lang.translate('Capes');
		var genericPos="";

		pos==0?genericPos="":genericPos=pos;

		this._socVisorInstamaps()?genericName=this._socInstamapsVell:genericName=genericName;

		if (position == 1 && pos > 0) { // estic afegint una
			// capa però ja existeix
			// un grup
			return this.getActiveGroup();
		} else {
			var group = {
				"groupName" : genericName+" "+ genericPos,
				"name" : genericName+" "+ genericPos,
				"id" : pos,
				"expanded" : true
			};
			this._groupList.push(group);
			return group;
		}
	},

	getActiveGroup : function() {
		var groupLast = this._groupList[this._groupList.length - 1];
		var notExpanded = false;
		if (groupLast.expanded==true || groupLast.expanded=="true") {
			return groupLast;
		} else {
			for (j=0; j < this._groupList.length;j++ ){
				var _gr=this._groupList[j];
				if (_gr.expanded==true || _gr.expanded=="true") {
					notExpanded = true;
					return _gr;
				}
			}
		}
		if (!notExpanded) {
			return groupLast;
		}
	},

	getGroupWhereIBelong : function() {
		var pos = this._groupList.length;
		if (pos > 0) { // estic afegint una capa però ja existeix un
			// grup
			return this._groupList[this._groupList.length - 1];
		} else {
			return null;
		}
	},

	_addGroupFromScratch : function() {
		var container = this._overlaysList;
		var obj = {};
		var group = this._createGroupFromScratch(0);

		obj.group = group;
		this._addGroup(container, obj, null);
		if (getModeMapa()) {
			updateEditableElements();
			refreshSortablesElements();
		}
	},

	_addGroupFromObject : function(group) {
		if (group) {
			var container = this._overlaysList;
			var obj = {};
			obj.group = group;
			var trobat = false;
			for (g in this._groupList) {
				if (this._groupList[g].id == group.id) {
					trobat = true;
					break;
				}
			}
			if (!trobat) {
				this._groupList.push(obj.group);
			}
			this._addGroup(container, obj, null);
		}
	},

	_addGroup : function(container, _obj, _menu_item_checkbox) {
		var _id;
		var obj;
		if (_obj.group) {
			_id = _obj.group.id;
			obj = _obj;
		} else if (_obj.layer) {
			obj = _obj.layer.options;
			try{
			_id = _obj.layer.options.group.id;
			}catch(Err){

			_id= this._domGroups.length -1;
			}
		} else {
			_id = null;
		}
		if (_id >= 0) {
			var groupContainer = this._domGroups[_id];
			if (!groupContainer) {
				groupContainer = document.createElement('div');
				groupContainer.id = 'leaflet-control-accordion-layers-'+ _id;
				groupContainer.className = 'leaflet-control-accordion-layers';
				// verify if group is expanded
				var s_expanded = obj.group.expanded ? ' checked = "true" ': '';
				// verify if type is exclusive
				var s_type_exclusive = this.options.exclusive ? ' type="radio" '
					: ' type="checkbox" ';
				inputElement = '<input id="ac' + _id
					+ '" name="accordion-' + _id
					+ '" class="menu expanded_input" ' + s_expanded
					+ s_type_exclusive + '/>';
				inputLabel = document.createElement('label');
				var _for = document.createAttribute('for');
				_for.value = "ac" + _id;
				inputLabel.setAttributeNode(_for);

				var spanGroup = document.createElement('span');
				spanGroup.innerHTML = obj.group.name;
				var classExpanded = 'glyphicon glyphicon-triangle-bottom label_gl';
				if (!obj.group.expanded) {
					classExpanded = 'glyphicon glyphicon-triangle-right label_gl';
				}
				inputLabel.id = 'lbl_ac_' + _id;

				if(obj.group.name.indexOf(this._socInstamapsVell)==-1){
					inputLabel.className = 'label_ac';
				}else{
					inputLabel.className = 'label_ac_novisible';
				}

				var _i = document.createElement('i');
				_i.id = '_i_' + _id;
				_i.className = classExpanded
				inputLabel.appendChild(_i);
					L.DomEvent.on(inputLabel, 'click', this._onExpandGroup,this);
				spanGroup.className = 'span_ac editable';
				spanGroup.id = 'ac' + _id;
				spanGroup.groupId = _id;
				spanGroup.groupName = obj.group.name;
				inputLabel.appendChild(spanGroup);

				if (getModeMapa()) {
					var col = L.DomUtil.create('span', 
						'tema_verd glyphicon glyphicon-remove group-conf');
					col.id = 'mv-' + _id;
					col.groupId = _id;
					col.groupName = obj.group.name;
					L.DomEvent.on(col, 'click', this._onRemoveGroup,this);
					inputLabel.appendChild(col);

					$(col).tooltip({
						placement : 'left',
						container : 'body',
						title : window.lang.translate("Esborrar grup")
					});

					var col = L.DomUtil.create('span',
						'tema_verd_move glyphicon glyphicon-move group-conf');
					col.id = 'rv-' + _id;
					col.groupName = obj.group.name;
					col.groupId = _id;
					inputLabel.appendChild(col);
					$(col).tooltip({
						placement : 'left',
						container : 'body',
						title : window.lang.translate("Moure grup")
					});
				}

				article = document.createElement('ol');
				article.className = 'ac-large';
				if (_menu_item_checkbox) {
					article.appendChild(_menu_item_checkbox);
				}

				// process options of ac-large css class - to
				// options.group_maxHeight property
				if (this.options.group_maxHeight) {
					article.style.maxHeight = this.options.group_maxHeight;
				}

				groupContainer.innerHTML = inputElement;
				groupContainer.appendChild(inputLabel);
				groupContainer.appendChild(article);

				var supraLI = document.createElement('li');
				supraLI.appendChild(groupContainer);

				container.appendChild(supraLI);

				this._domGroups[_id] = groupContainer;
			} else {
				if (_menu_item_checkbox) {
					groupContainer.lastElementChild.appendChild(_menu_item_checkbox);
				}
			}
		}
	},

	_addLayer : function(layer, name, overlay, groupLeafletId) {
		var id = L.Util.stamp(layer);
		if (groupLeafletId) {
			this._layers[groupLeafletId]._layers[id] = {
				layer : layer,
				name : name,
				overlay : overlay,
				sublayer : true,
				layerIdParent : groupLeafletId
			};
		} else {
			this._layers[id] = {
				layer : layer,
				name : name,
				overlay : overlay,
				sublayer : false,
				_layers : {}
			};
		}
		var group = layer.options.group;
		var _heCreat = false;
		var _heCreatFromScratch=false;
		if (!group) {
			group = this._createGroupFromScratch(1);
			_heCreat = true;
			_heCreatFromScratch=true;
		}
		var groupId;
		if (group) {
			//var groupId = this._groupList.indexOf(group);
			if (undefined !=group.id) {
				groupId = group.id;
				var trobat = false;
				for (g in this._groupList) {
					if (this._groupList[g].id == group.id) {
						trobat = true;
						break;
					}
				}
				if (!trobat) {
					this._groupList.push(group);
				}

			}
			// if not find the group search for the name
			/*if (groupId === -1) {
				for (g in this._groupList) {
					if (this._groupList[g].groupName == group.groupName) {
						groupId = g;
						break;
					}
				}
			}*/

			if (groupId === -1) {
				groupId = this._groupList.push(group) - 1;
			}

			
			if (this._layers[id]) {
				this._layers[id].layer.options.group = {
					name : group.groupName,
					groupName : group.groupName,
					id : groupId,
					z_order : this._layers[id].layer.options.zIndex,
					expanded : group.expanded
				};

				if (_heCreat) {
					if (getModeMapa()) {
						if(_heCreatFromScratch){
							var data = {
								mapBusinessId: url('?businessid'),
								businessId : this._layers[id].layer.options.businessId, // url('?businessid')
								uid : Cookies.get('uid'),
								options : JSON.stringify(this._layers[id].layer.options.group)
							};
							// Ara desactivat
							updateGroupsLayerGroup(data, null);
						}
					}
				}
			}
		}
		if (this.options.autoZIndex && layer.setZIndex) {
			this._lastZIndex++;
			layer.setZIndex(this._lastZIndex);
		}
	},

	_update : function(makeUpdate) {
		var self = this;
		var redraw = makeUpdate || self.options.autoUpdate;
		if(redraw){
			if (!self._container) {
				return;
			}

			self._domGroupsTMP = self._groupList;
			self._groupList = [];
			self._baseLayersList.innerHTML = '';
			self._overlaysList.innerHTML = '';
			self._domGroups.length = 0;

			self._domGroupsTMP = sortByKey(self._domGroupsTMP, "id");
			self._groupList = sortByKey(self._groupList, "id");			
			
			self._domGroupsTMP.forEach(function(item, index, array) {
				self._addGroupFromObject(item);
			});

			var baseLayersPresent = false, overlaysPresent = false, i, obj;
			var layerArray=[];
			for (i in self._layers) {
				layerArray.push(self._layers[i]);
			}
			layerArray = sortByKeyPath(layerArray, "zIndex");
			
			for (i in layerArray) {
				obj = layerArray[i];
				self._addItem(obj);
				overlaysPresent = overlaysPresent || obj.overlay;
				baseLayersPresent = baseLayersPresent || !obj.overlay;
			}
			
			self._hideSpiner();
			
			map.fire('onRedrawLegend', self._mapConfig);
			$.publish('onRedrawLegend', self._mapConfig);
		}
	},
	
	forceUpdate: function(autoUpdate){
		if(autoUpdate){
			this.options.autoUpdate = true;
		}
		this._update(true);
	},

	_diferences : function(a1, a2) {
		var a = [], diff = [];
		for (var i = 0; i < a1.length; i++)
			a[a1[i]] = true;
		for (var i = 0; i < a2.length; i++)
			if (a[a2[i]])
				delete a[a2[i]];
			else
				a[a2[i]] = true;
		for ( var k in a)
			diff.push(parseInt(k));
		return diff;
	},

	_onLayerChange : function(e) {
		var obj = this._layers[L.Util.stamp(e.layer)];
		if (!obj) {
			return;
		}
		if (!this._handlingClick) {
			this._update();
		}
		//parece que esta parte de código no se usa.
		var type = obj.overlay ? (e.type === 'layeradd' ? 'overlayadd'
			: 'overlayremove')
			: (e.type === 'layeradd' ? 'baselayerchange' : null);
		if (type) {
			this._map.fire(type, obj);					
		}
	},

	_createRadioElement : function(name, checked) {
		var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="'
			+ name + '"';
		if (checked) {
			radioHtml += ' checked="checked"';
		}
		radioHtml += '/>';
		var radioFragment = document.createElement('div');
		radioFragment.innerHTML = radioHtml;
		return radioFragment.firstChild;
	},

	_addItem : function(obj) {
		var _menu_item_checkbox = document.createElement('li'), 
		input, checked = this._map.hasLayer(obj.layer), 
		container;	
		
		var _leaflet_input = document.createElement('div');
		if (obj.overlay) {
			_menu_item_checkbox.className = "leaflet-row";
			_menu_item_checkbox.id = 'LI-'+ obj.layer.options.businessId;

			input = document.createElement('input');
			input.id = 'input-' + obj.layer.options.businessId;
			input.type = 'checkbox';
			input.className = 'checkbox_styled hide leaflet-control-layers-selector';
			
			if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_wms) != -1) {
				if (obj.layer.options.wmstime == true) {
					input.className = 'checkbox_time hide leaflet-control-layers-selector';
				}
			}
			input.defaultChecked = checked;
		} else {
			input = this._createRadioElement('leaflet-base-layers', checked);
		}

		_leaflet_input.className = "leaflet-input";
		input.layerId = L.Util.stamp(obj.layer);
		L.DomEvent.on(input, 'click', this._onInputClick, this);
		var label_for = document.createElement('label');
		var _for = document.createAttribute('for');
		_for.value = 'input-' + obj.layer.options.businessId;
		label_for.setAttributeNode(_for);
		_leaflet_input.appendChild(input);
		_leaflet_input.appendChild(label_for);

		var _leaflet_name = document.createElement('div');
		_leaflet_name.className = 'leaflet-name';
		var _label_buit = document.createElement('label');
		var nomCapa = document.createElement('span');

		
		var layerName=obj.name;			
    	(layerName.length > 71)?layerName=layerName.substring(0,71)+"...":layerName;		
 
		nomCapa.innerHTML = ' ' + layerName;
		//nomCapa.innerHTML = ' ' + obj.name;
		nomCapa.className = 'editable';
		nomCapa.id = input.layerId;

		if(obj.layer.error){
			_label_buit.className = 'error';
		}
		
		_label_buit.appendChild(nomCapa);

		if (obj.layer.options.tipus == t_visualitzacio
				|| obj.layer.options.tipus == t_tematic
				|| obj.layer.options.tipus == t_dades_obertes
				|| obj.layer.options.tipus == t_json
				|| obj.layer.options.tipus == t_url_file) {
			var count = document.createElement('span');
			count.className = 'layer-count';
			count.id = 'count-' + obj.layer.options.businessId;
			count.innerHTML = ' (' + obj.layer.getLayers().length + ')';
			_label_buit.appendChild(count);
		}

		_leaflet_name.appendChild(_label_buit);
		_menu_item_checkbox.appendChild(_leaflet_input);
		_menu_item_checkbox.appendChild(_leaflet_name);

		var container;
		var modeMapa = ($(location).attr('href').indexOf('/mapa.html') != -1);

		var col;

		if (obj.overlay) {
			// Icona conf Sempre
			col = L.DomUtil.create('div', 'leaflet-conf glyphicon glyphicon-cog opcio-conf');
			L.DomEvent.on(col, 'click', this._showOptions, this);
			col.layerId = input.layerId;
			_menu_item_checkbox.appendChild(col);

			// Icona remove només Edicio
			if (getModeMapa()) {
				col = L.DomUtil.create('div',
					'conf-'+ obj.layer.options.businessId+ ' leaflet-remove glyphicon glyphicon-remove subopcio-conf');
				col.layerId = input.layerId;
				L.DomEvent.on(col, 'click', this._onRemoveClick, this);
				_menu_item_checkbox.appendChild(col);
			}
			// Icona Taula de Dades Sempre
			if ((obj.layer.options.source || obj.layer.options.geometryType=="marker" ||  obj.layer.options.geometryType=="polyline" 
				||  obj.layer.options.geometryType=="polygon") && !obj.layer.options.dinamic ) {
				col = L.DomUtil.create('div',
					'data-table-'+ obj.layer.options.businessId+ ' leaflet-data-table glyphicon glyphicon-list-alt');
				col.layerId = input.layerId;
				L.DomEvent.on(col, 'click', this._onOpenDataTable, this);
				_menu_item_checkbox.appendChild(col);
			}
			// Icona Descàrrega sempre
			//Issue #467: S'ha de respectar el que es selecciona al publicar sobre si una capa és descarregable o no.
			if (getModeMapa()) {
				if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_wms) == -1
					&& obj.layer.options.tipus.indexOf(t_geojsonvt) == -1) {
					col = L.DomUtil.create('div',
						'conf-'+ obj.layer.options.businessId+ ' leaflet-download glyphicon glyphicon-save subopcio-conf');
							col.layerId = input.layerId;
							L.DomEvent.on(col, 'click', this._onDownloadClick, this);
							_menu_item_checkbox.appendChild(col);
				}
			}else{
				if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_wms) == -1
					&& obj.layer.options.tipus.indexOf(t_geojsonvt) == -1) {
					if(downloadableData[obj.layer.options.businessId]){
	    				if(downloadableData[obj.layer.options.businessId][0].chck) {
							col = L.DomUtil
									.create(
											'div',
											'conf-'
													+ obj.layer.options.businessId
													+ ' leaflet-download glyphicon glyphicon-save subopcio-conf');
							col.layerId = input.layerId;
							L.DomEvent
									.on(col, 'click', this._onDownloadClick, this);
							_menu_item_checkbox.appendChild(col);
	    				}
					}
				}

			}
			// Icona Transparència
			if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_wms) != -1) {
				col = L.DomUtil.create('div',
					'conf-'+ obj.layer.options.businessId+ ' leaflet-trans glyphicon glyphicon-adjust subopcio-conf');
				col.layerId = input.layerId;
				L.DomEvent.on(col, 'click', this._onTransparenciaClick,this);
				_menu_item_checkbox.appendChild(col);
				$(col).tooltip({
					placement : 'bottom',
					container : 'body',
					title : window.lang.translate("Transparència")
				});
			}

			// Icona Moure només Edicio
			if (getModeMapa()) {
				col = L.DomUtil.create('div',
					'conf-'+ obj.layer.options.businessId+ ' leaflet-move glyphicon glyphicon-move subopcio-conf');
				col.layerId = input.layerId;
				_menu_item_checkbox.appendChild(col);
				$(col).tooltip({
					placement : 'bottom',
					container : 'body',
					title : window.lang.translate("Moure")
				});
			}

			col = L.DomUtil.create('div',
				'conf-'+ obj.layer.options.businessId+ ' leaflet-zoom glyphicon glyphicon-search subopcio-conf');
				col.layerId = input.layerId;
				L.DomEvent.on(col, 'click', this._onZoomClick,this);
				_menu_item_checkbox.appendChild(col);

				$(col).tooltip({
					placement : 'bottom',
					container : 'body',
					title : window.lang.translate("Zoom a la capa")
				});
			
			if (getModeMapa()) {
				if ((obj.layer.options.tipus == t_visualitzacio
						|| obj.layer.options.tipus == t_url_file
						|| obj.layer.options.tipus == t_json) && !obj.layer.options.dinamic) {
					col = L.DomUtil
							.create(
									'div',
									'conf-'
											+ obj.layer.options.businessId
											+ ' leaflet-zoom glyphicon glyphicon-font subopcio-conf');
					col.layerId = input.layerId;
					// L.DomEvent.on(col, 'click', this._onDownClick, this);
					L.DomEvent.on(col, 'click', this._onEtiquetaClick,
							this);
					_menu_item_checkbox.appendChild(col);

					$(col).tooltip({
						placement : 'bottom',
						container : 'body',
						title : window.lang.translate("Etiquetes de la capa")
					});
				}
			}
			
			container = this._overlaysList;
		} else {
			container = this._baseLayersList;
		}

		var sublayers = obj._layers;
		for (j in sublayers) {
			var row_sublayer = this._createSubItem(sublayers[j], input.layerId, modeMapa);
			_menu_item_checkbox.appendChild(row_sublayer);
		}

		this._addGroup(container, obj, _menu_item_checkbox);

		// Afegim tooltips
		$(".data-table-" + obj.layer.options.businessId
			+ ".leaflet-data-table").tooltip({
			placement : 'bottom',
			container : 'body',
			title : window.lang.translate("dades")
		});

		$(".opcio-conf").tooltip({
			placement : 'bottom',
			container : 'body',
			title : window.lang.translate("opcions")
		});

		if (getModeMapa()){
			try{
				updateEditableElements();
				refreshSortablesElements();
				map.fireEvent('addItemFinish');
				
				
				if(estatMapa3D){mapaVista3D.actualitzaVistaOverlays(obj.layer.options,"add",true);}	
				
				//generallegendaMapaEdicio();
				
			}catch(Err){
				updateEditableElements();
			}
		}
		return _menu_item_checkbox;
	},
	
	_createSubItem : function(sublayer, layerIdParent, modeMapa) {
		var row_sublayer = L.DomUtil.create('div',
				'leaflet-row leaflet-subrow');

		var label_sublayer, 
			input_sublayer, checked = this._map.hasLayer(sublayer.layer);

		if(sublayer.layer.error){
			label_sublayer = L.DomUtil.create('label', 'error');
		}else{
			label_sublayer = L.DomUtil.create('label', '');
		}
		label_sublayer.id =  'lblsub-'+ sublayer.layer.options.businessId;		
				
		input_sublayer = L.DomUtil.create('input');
		input_sublayer.id = 'input-'
				+ sublayer.layer.options.businessId;
		input_sublayer.type = 'checkbox';
		input_sublayer.className = 'checkbox_eye hide leaflet-control-layers-selector';
		input_sublayer.defaultChecked = checked;

		input_sublayer.layerId = L.stamp(sublayer.layer);
		input_sublayer.layerIdParent = layerIdParent; // input.layerId;

		L.DomEvent.on(input_sublayer, 'click', this._onInputClick, this);

		var name_sublayer = document.createElement('span');
		name_sublayer.className = 'editable';
		name_sublayer.idParent = layerIdParent;
		name_sublayer.id = L.stamp(sublayer.layer);
		var layerName=sublayer.name;			
    	(layerName.length > 71)?layerName=layerName.substring(0,71)+"...":layerName;			
 
		name_sublayer.innerHTML = ' ' + layerName;

		var col_sublayer = L.DomUtil.create('div', 'leaflet-input');
		var label_for = document.createElement('label');
		var _for = document.createAttribute('for');
		_for.value = 'input-' + sublayer.layer.options.businessId;
		label_for.setAttributeNode(_for);
		col_sublayer.appendChild(input_sublayer);
		col_sublayer.appendChild(label_for);

		row_sublayer.appendChild(col_sublayer);
		col_sublayer = L.DomUtil.create('div', 'leaflet-name');
		col_sublayer.appendChild(label_sublayer);
		row_sublayer.appendChild(col_sublayer);
		label_sublayer.appendChild(name_sublayer);

		if (modeMapa) {
			col_sublayer = L.DomUtil.create('span','leaflet-remove glyphicon glyphicon-remove opcio-conf');
			L.DomEvent.on(col_sublayer, 'click', this._onRemoveClick, this);
			col_sublayer.layerId = input_sublayer.layerId;
			col_sublayer.layerIdParent = layerIdParent;
			row_sublayer.appendChild(col_sublayer);
				
			if(estatMapa3D){mapaVista3D.actualitzaVistaOverlays(sublayer.layer.options,"add",true);}	
		}
		return row_sublayer;
	},

	getCountActiveLayers:function(){
		var i, input, obj, 
		inputs = this._form.getElementsByTagName('input'), 
		inputsLen = inputs.length;
		var j=0;
		for (i = 0; i < inputsLen; i++) {
			input = inputs[i];
			if (!input.layerId) {
				continue;
			} else{
				
				if (input.checked){
					j=j+1;
					obj=input.id.replace("input-", "");
				}	
					
			}
		
		}
		return {total:j, lastActive:obj};
	},	
	
	_onInputClick : function(event) {
		var i, input, obj, 
		inputs = this._form.getElementsByTagName('input'), 
		inputsLen = inputs.length;

		this._handlingClick = true;
		var checkHeat = false;
		var id, parentId;

		var currentbid = arguments[0].currentTarget.id.replace("input-", "");
		
		// tractament en cas heatmap
		if (arguments[0].currentTarget.layerIdParent) {
			id = arguments[0].currentTarget.layerId;
			parentId = arguments[0].currentTarget.layerIdParent;
			checkHeat = isHeat(controlCapes._layers[parentId]._layers[id])
					&& arguments[0].currentTarget.value == "on";
		}

		var _timeLayers = [];
		var isLegendLoad=false;
		
		for (i = 0; i < inputsLen; i++) {
			input = inputs[i];
			if (!input.layerId) {
				continue;
			} else if (!input.layerIdParent) {
				obj = this._layers[input.layerId];
			} else {
				obj = this._layers[input.layerIdParent]._layers[input.layerId];
			}

			// Si la capa clickada es  heatmap i s'ha d'activar, i la que
			// estem tractant tb, no s'ha de mostrar
			if (isHeat(obj) && checkHeat && obj.layer._leaflet_id != id) {
				input.checked = false;
			}
			// valida tipus CapaTime
			if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_wms) != -1) {
				if (obj.layer.options.wmstime == true) {
					_timeLayers.push(input);
				}
			}

			if(currentbid === obj.layer.options.businessId){
				
					//$.publish('activaLegendTab',{id: currentbid, activo: input.checked});
					this._map.fire('activaLegendTab',{id: currentbid, activo: input.checked});
				
				
				}
			
			
			// Afegir
			var canSpiderify = (obj.layer.options.tipusRang == tem_clasic || 
				obj.layer.options.tipusRang == tem_simple || 
				obj.layer.options.tipusRang == tem_origen);
			if (input.checked && !this._map.hasLayer(obj.layer)) {
				
				
				this._map.addLayer(obj.layer);

				if(this._map.hasOwnProperty("oms") && obj.layer._layers ){
					
				
					//Add the markers to Spiderify
					var keys = Object.keys(obj.layer._layers);
					var num = this._map.oms.markers.length;
					for(var j=0; j<keys.length; ++j)
					{

						var aux = obj.layer._layers[keys[j]];
						if(canSpiderify)
							this._map.oms.addMarker(aux);

					}

					if(num != this._map.oms.markers.length)
						this._map.oms.unspiderfy();

				}

				//Mostrem els labels
				if (obj.layer.options.opcionsVisEtiqueta!=undefined && (obj.layer.options.opcionsVisEtiqueta=="nomesetiqueta" ||
					obj.layer.options.opcionsVisEtiqueta=="etiquetageom")){
					jQuery.each(obj.layer._layers, function(i, lay){	
						var zoomInicial = "2";
				 		if (obj.layer.options.zoomInicial) zoomInicial=obj.layer.options.zoomInicial;
				 		var zoomFinal = "19";
				 		if (obj.layer.options.zoomFinal) zoomFinal = obj.layer.options.zoomFinal;
				 		
				 		if ( map.getZoom()>=zoomInicial &&  map.getZoom() <= zoomFinal) {//mostrem labels
							jQuery.each(obj.layer._layers, function(i, lay){
								if (lay.label!=undefined) {
									if(lay.label){
										lay.label.setOpacity(1);
									}
									if(lay._showLabel){
				                        lay._showLabel({latlng: lay.label._latlng});
									}
								}
							});											
				 		 }
				 		 else {//amaguem labels
							jQuery.each(obj.layer._layers, function(i, lay){
								if(lay.label){
									lay.label.setOpacity(0);
								}
							});										
						 }						
					});
				}
				
				if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_vis_wms) != -1) {
					var optionsUtfGrid = {
						layers : obj.layer.options.businessId,
						crs : L.CRS.EPSG4326,
						srs : "EPSG:4326",
						transparent : true,
						format : 'utfgrid',
						nom : obj.layer.options.nom + " utfgrid",
						tipus : obj.layer.options.tipus,
						businessId : obj.layer.options.businessId
					};
					var utfGrid = createUtfGridLayer(obj.layer._url, optionsUtfGrid);
					this._map.addLayer(utfGrid);
					obj.layer.options.utfGridLeafletId = utfGrid._leaflet_id;
				}
				// Si hem activat capa de tipus tematic categories,
				// mostrem la seva llegenda
				if (currentbid == obj.layer.options.businessId
						&& obj.layer.options.tipusRang
						&& (obj.layer.options.tipusRang == tem_clasic || obj.layer.options.tipusRang == tem_size)) {
					//thisLoadMapLegendEdicio(obj.layer);
					isLegendLoad=true;
				}
				else if (obj.layer.options.tipus=="wms"){//per WMS tb s'ha d'omplir
					//thisLoadMapLegendEdicio(obj.layer);
					isLegendLoad=true;
				}					
				else if (!isLegendLoad){
					//thisEmptyMapLegendEdicio(obj.layer,true);
				}
				
				
				
				
				if (obj.layer.options.dinamic && (obj.layer.options.tem == tem_clasic || obj.layer.options.tem == tem_size)) {
					//thisLoadMapLegendEdicioDinamic(obj.layer);
					isLegendLoad=true;
				}
				else if(!isLegendLoad){

				//thisEmptyMapLegendEdicio(obj.layer,true);
				}
				//mirem vista 3D
				if(estatMapa3D){mapaVista3D.actualitzaVistaOverlays(obj.layer.options,'display',true);}
			
			
				
			
			} else if (!input.checked && this._map.hasLayer(obj.layer)) {
				//Amaguem els labels
				if (obj.layer.options.opcionsVisEtiqueta!=undefined && (obj.layer.options.opcionsVisEtiqueta=="nomesetiqueta" ||
					obj.layer.options.opcionsVisEtiqueta=="etiquetageom")){
					jQuery.each(obj.layer._layers, function(i, lay){
						if(lay.label){
							lay.label.setOpacity(0);
						}
					});	
				}
				// Si es vis_wms, hem d'eliminar tb la capa utfgrid
				if (obj.layer.options.tipus && obj.layer.options.tipus.indexOf(t_vis_wms) != -1) {
					var utfGridLayer = this._map._layers[obj.layer.options.utfGridLeafletId];
					this._map.removeLayer(utfGridLayer);
				}

				this._map.removeLayer(obj.layer);

				if(this._map.hasOwnProperty("oms") && obj.layer._layers ){
				
					//Remove the markers from Spiderify
					var keys = Object.keys(obj.layer._layers);
					var num = this._map.oms.markers.length;
					for(var j=0; j<keys.length; ++j)
					{

						var aux = obj.layer._layers[keys[j]];
						if(canSpiderify)
							this._map.oms.removeMarker(aux);

					}

					if(num != this._map.oms.markers.length)
						this._map.oms.unspiderfy();

				}

				// Si hem desactivat capa de tipus tematic categories,
				// mostrem la seva llegenda
				if (currentbid == obj.layer.options.businessId
						&& obj.layer.options.tipusRang
						&& (obj.layer.options.tipusRang == tem_clasic|| obj.layer.options.tipusRang == tem_size)) {
					thisEmptyMapLegendEdicio(obj.layer);
				}
				
				if (currentbid == obj.layer.options.businessId && obj.layer.options.dinamic && 
						(obj.layer.options.tem == tem_clasic || obj.layer.options.tem == tem_size)) {
					thisEmptyMapLegendEdicio(obj.layer);
				}
				if (obj.layer.options.tipus=="wms"){
					thisEmptyMapLegendEdicio(obj.layer);
				}
						
				if(estatMapa3D){mapaVista3D.actualitzaVistaOverlays(obj.layer.options,'display',false);}
			}
		}
		this._validateWmsTime(_timeLayers);
		this._handlingClick = false;
		this._refocusOnMap();
	},

	_validateWmsTime : function(_timeLayers) {
		var _thereIs = false;
		for (j = 0; j < _timeLayers.length; j++) {
			if (_timeLayers[j].checked) {
				_thereIs = true;
			}
		}
		showTimeControl(_thereIs);
	},

	_onUpClick : function(e) {
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var inputs = this._form.getElementsByTagName('input');
		var obj = this._layers[layerId];

		if (!obj.overlay) {
			return;
		}

		var replaceLayer = null;
		for (var i = 0; i < inputs.length; i++) {
			if (!inputs[i].layerIdParent) {
				var auxLayer = this._layers[inputs[i].layerId];
				if (auxLayer.overlay
						&& ((obj.layer.options.zIndex - 1) === auxLayer.layer.options.zIndex)) {
					replaceLayer = auxLayer;
					break;
				}
			}
		}

		var newZIndex = obj.layer.options.zIndex - 1;
		if (replaceLayer) {

			if (typeof url('?businessid') == "string") {
				var data = {
					uid : Cookies.get('uid'),
					businessId : url('?businessid'),
					servidorWMSbusinessId : obj.layer.options.businessId
							+ ','
							+ replaceLayer.layer.options.businessId,
					order : newZIndex + ',' + (newZIndex + 1)
				};

				updateServersOrderToMap(data).then(function(results) {
					if (results.status != 'OK')
						return;// SI no ha anat be el canvi a BD. que
					// no es faci tampoc a client, i es
					// mostri un error
				}, function(results) {
					return;// SI no ha anat be el canvi a BD. que no es
					// faci tampoc a client, i es mostri un
					// error
				});
			}

			obj.layer.options.zIndex = newZIndex;
			replaceLayer.layer.options.zIndex = newZIndex + 1;

			this._map.fire('changeorder', obj, this);
		}
	},

	_onDownClick : function(e) {
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var inputs = this._form.getElementsByTagName('input');
		var obj = this._layers[layerId];

		if (!obj.overlay) {
			return;
		}

		var replaceLayer = null;
		for (var i = 0; i < inputs.length; i++) {
			if (!inputs[i].layerIdParent) {
				var auxLayer = this._layers[inputs[i].layerId];
				if (auxLayer.overlay
						&& ((obj.layer.options.zIndex + 1) === auxLayer.layer.options.zIndex)) {
					replaceLayer = auxLayer;
					break;
				}
			}
		}

		var newZIndex = obj.layer.options.zIndex + 1;
		if (replaceLayer) {
			if (typeof url('?businessid') == "string") {
				var data = {
					uid : Cookies.get('uid'),
					businessId : url('?businessid'),
					servidorWMSbusinessId : obj.layer.options.businessId
							+ ','
							+ replaceLayer.layer.options.businessId,
					order : newZIndex + ',' + (newZIndex - 1)
				};

				updateServersOrderToMap(data).then(function(results) {
					if (results.status != 'OK')
						return;// SI no ha anat be el canvi a BD. que
					// no es faci tampoc a client, i es
					// mostri un error
				}, function(results) {
					return;// SI no ha anat be el canvi a BD. que no es
					// faci tampoc a client, i es mostri un
					// error
				});
			}

			obj.layer.options.zIndex = newZIndex;
			replaceLayer.layer.options.zIndex = newZIndex - 1;

			this._map.fire('changeorder', obj, this);
		}
	},

	_onExpandGroup : function(e) {
		var cl=e.explicitOriginalTarget;
		if(!cl){
			cl=e.srcElement;
		}
		var cls=jQuery(cl).attr('class');
		if(getModeMapa()){
			if(cls && cls.indexOf('label')!=-1){
				var _id = e.currentTarget.id;
				_id = _id.replace('lbl_ac_', '_i_');
				if ($('#' + _id).hasClass('glyphicon-triangle-bottom')) {
					$('#' + _id).removeClass('glyphicon-triangle-bottom');
					$('#' + _id).addClass('glyphicon-triangle-right');

				} else if ($('#' + _id).hasClass('glyphicon-triangle-right')) {
					$('#' + _id).removeClass('glyphicon-triangle-right');
					$('#' + _id).addClass('glyphicon-triangle-bottom');

				}
			}
		}else{
			var _id = e.currentTarget.id;
			_id = _id.replace('lbl_ac_', '_i_');
			if ($('#' + _id).hasClass('glyphicon-triangle-bottom')) {
				$('#' + _id).removeClass('glyphicon-triangle-bottom');
				$('#' + _id).addClass('glyphicon-triangle-right');
	
			} else if ($('#' + _id).hasClass('glyphicon-triangle-right')) {
				$('#' + _id).removeClass('glyphicon-triangle-right');
				$('#' + _id).addClass('glyphicon-triangle-bottom');
	
			}
		}
		if (getModeMapa()) {
			reOrderGroupsAndLayers(false);
		}
	},

	_onRemoveGroup : function(e) {
		$('.tooltip').hide();
		e.stopImmediatePropagation();

		$('#dialog_delete_group').modal('show');
		$('#dialog_delete_group #nom_group_delete').text(e.currentTarget.groupName);
		$('#dialog_delete_group .btn-danger').data("group",e.currentTarget);
	},

	_onRemoveClick : function(e) {
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var layerIdParent = e.currentTarget.layerIdParent;
		var lbusinessId = [];
		if (!layerIdParent) {
			var obj = this._layers[layerId];
			lbusinessId.push(obj.layer.options.businessId);
			for (i in obj._layers) {
				lbusinessId.push(obj._layers[i].layer.options.businessId);
			}
		} else {
			var objParent = this._layers[layerIdParent];
			var obj = objParent._layers[layerId];
			lbusinessId.push(obj.layer.options.businessId);
		}

		if (!obj.overlay) {
			return;
		}

		if (typeof url('?businessid') == "string") {
			var data = {
				businessId : url('?businessid'),
				uid : Cookies.get('uid'),
				servidorWMSbusinessId : lbusinessId.toString()
			};
			$('#dialog_delete_capa').modal('show');
			$('#dialog_delete_capa #nom_capa_delete').text(obj.layer.options.nom);
			$('#dialog_delete_capa .btn-danger').data("data", data);
			$('#dialog_delete_capa .btn-danger').data("obj", obj);
		}
	},

	_onDeleteClick : function(obj) {
		var node = obj.target.parentElement.childNodes[0];
		n_obj = this._layers[node.layerId];

		// verify if obj is a basemap and checked to not remove
		if (!n_obj.overlay && node.checked) {
			return false;
		}

		if (this._map.hasLayer(n_obj.layer)) {
			this._map.removeLayer(n_obj.layer);
		}
		this.removeLayer(n_obj.layer);
		obj.target.parentNode.remove();

		return false;
	},
	
	_onEditNameClick : function(e) {
		var layerId = e.currentTarget.layerId;
		var obj = this._layers[layerId];
		if (!obj.overlay) {
			return;
		}
	},
	
	_onOpenDataTable : function(e) {
		$('.tooltip').hide();

		$('#modal_data_table').modal('show');
		console.debug($('#modal_data_table'));
		var layerId = e.currentTarget.layerId;
		var obj = this._layers[layerId];
		download_layer = obj;
		fillModalDataTable(obj);
	},

	_onTransparenciaClick : function(e) {
		var layerId = e.currentTarget.layerId;
		var obj = this._layers[layerId];
		var op = obj.layer.options.opacity;

		op ? op = obj.layer.options.opacity
				: op = obj.layer.options.fillOpacity;

		if (!op) {
			op = 1;
			obj.layer.options.fillOpacity = 1;
		} else {
			if (op == 0) {
				op = 1
			} else {
				op = (parseFloat(op) - 0.25)
			}
		}

		try {
			obj.layer.setOpacity(op);
			if(estatMapa3D){mapaVista3D.canviaOpacity(obj.layer.options.businessId,op);}
		} catch (err) {
			obj.layer.options.fillOpacity = op;
			obj.layer.options.opacity = op;
		}

		if (getModeMapa()) {
			var data = {
				businessId : obj.layer.options.businessId, // url('?businessid')
				uid : Cookies.get('uid'),
				opacity : op
			};
			updateServidorWMSOpacity(data).then(function(results) {
				if (results.status === 'OK') {
					// console.debug(results);
				}
			});
		}
	},

	_onDownloadClick : function(e) {
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var obj = this._layers[layerId];
		download_layer = obj;

		if (obj.layer.options.tipusRang
				&& (obj.layer.options.tipusRang == tem_cluster || obj.layer.options.tipusRang == tem_heatmap)) {
			$('#modal-body-download-not-available').show();
			$('#modal-body-download-error').hide();
			$('#modal-body-download').hide();
			$('#modal_download_layer .modal-footer').show();
			$('#bt_download_tancar').show();
			$('#bt_download_accept').hide();
			$('#modal_download_layer').modal('show');
		} else {
			$('#modal-body-download-not-available').hide();
			$('#modal-body-download-error').hide();
			$('#modal-body-download').show();
			$('#modal_download_layer .modal-footer').show();
			$('#bt_download_tancar').hide();
			$('#bt_download_accept').show();
			$('#modal_download_layer').modal('show');
		}
	},
	
	_onZoomClick: function(e){
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var obj = this._layers[layerId];
		if (obj.layer._wmsVersion==undefined){
			var bounds = obj.layer.getBounds();
			!estatMapa3D?map.fitBounds(bounds):mapaVista3D._goToBounds(bounds);
		}
		else{
			var instamapsWms = InstamapsWms({
				loadTemplateParam :false});
			var dataWMS = {url: obj.layer._url};
			instamapsWms.getWMSLayers(dataWMS).then(function(results) {
				try{
					if(results.Capability.Layer.Layer.LatLonBoundingBox){
						var bbox = results.Capability.Layer.Layer.LatLonBoundingBox;
						WMS_BBOX=[[bbox["@miny"], bbox["@minx"]],[bbox["@maxy"], bbox["@maxx"]]];
					}else if(results.Capability.Layer.LatLonBoundingBox){
						
						var bbox = results.Capability.Layer.LatLonBoundingBox;
						WMS_BBOX=[[bbox["@miny"], bbox["@minx"]],[bbox["@maxy"], bbox["@maxx"]]];
					}else{
						WMS_BBOX=null;
					}	
				} catch (err) {
					WMS_BBOX=null;
				}
				if (WMS_BBOX !=null) map.fitBounds(WMS_BBOX);
			});
		}
	},
	
	_hideSpiner: function(){
		$(this._spiner).hide();
	},
	
	_showSpiner: function(){
		$(this._spiner).show();
	},
	
	_onEtiquetaClick : function(e) {
		$('.tooltip').hide();
		var layerId = e.currentTarget.layerId;
		var layerIdParent = e.currentTarget.layerIdParent;
		var lbusinessId = [];
		if (!layerIdParent) {
			var obj = this._layers[layerId];
			lbusinessId.push(obj.layer.options.businessId);
			for (i in obj._layers) {
				lbusinessId
						.push(obj._layers[i].layer.options.businessId);
			}
		} else {
			var objParent = this._layers[layerIdParent];
			var obj = objParent._layers[layerId];
			lbusinessId.push(obj.layer.options.businessId);
		}

		if (!obj.overlay) {
			return;
		}

		if (typeof url('?businessid') == "string") {
			var data = obj.layer.options;
			if (data!=undefined){
				var dataNames = [];
				var fields = {};
				fields[window.lang.translate('Escull el camp')] = '---';
								
				if (data.propName!=undefined && data.propName!='null' && data.propName!='') {
					var propName = data.propName;
					if(typeof (propName)=="string"){	
						try {
							dataNames = JSON.parse(propName);
						}
						catch (err) {
							dataNames = propName;		
						}
					}else{			
						dataNames = propName;	
					}					
					if (typeof (dataNames)=="string"){
						 var dataNamesSplit=dataNames.split(",");
						 jQuery.each(dataNamesSplit, function( index, value ) {
								if (value!='') 	fields[value] = value;
						});
					}
					else{
						jQuery.each(dataNames, function( index, value ) {
							if (value!='') 	fields[value] = value;
						});
					}
				}
				else{
					fields['nom']='nom';
					fields['text']='text';
				}
				//creamos el select con los campos
				var source1 = jQuery("#etiquetes-layers-fields").html();
				var template1 = Handlebars.compile(source1);
				var html1 = template1({fields:fields});
				jQuery('#dataFieldEtiqueta').html(html1);
				$('#dialog_etiquetes_capa').modal('show');
				//console.debug(obj.layer.options);
				$('#dialog_etiquetes_capa #nom_capa_etiqueta').text(obj.layer.options.nom);
				//console.debug(obj.layer);
				$('#dialog_etiquetes_capa #businessIdCapaEtiqueta').val(obj.layer.options.businessId);
				$('#dialog_etiquetes_capa #leafletIdCapaEtiqueta').val(obj.layer._leaflet_id);
				$('#dialog_etiquetes_capa #leafletIdCapaEtiquetaControl').val(layerId);
				//Si tenim al camp options informació de les etiquetes ho marquem en el formulari
				if (obj.layer.options.campEtiqueta!=undefined)	$('#dataFieldEtiqueta option[value='+obj.layer.options.campEtiqueta+']').attr('selected','selected');
				else $('#dataFieldEtiqueta option[value=---]').attr('selected','selected');
				if (obj.layer.options.fontFamily!=undefined)	$('#font-family option[value='+obj.layer.options.fontFamily+']').attr('selected','selected');
				else $('#font-family option[value='+obj.layer.options.fontFamily+']').attr('selected','selected');
				if (obj.layer.options.fontSize!=undefined)	$('#font-size option[value='+obj.layer.options.fontSize+']').attr('selected','selected');
				else $('#font-size option[value=Arial]').attr('selected','selected');
				if (obj.layer.options.fontStyle!=undefined)	$('#font-style option[value='+obj.layer.options.fontStyle+']').attr('selected','selected');
				else $('#font-style option[value=10px]').attr('selected','selected');
				if (obj.layer.options.fontColor!=undefined)	$('#dv_color_etiqueta').css('background-color',obj.layer.options.fontColor);
				else 	$('#dv_color_etiqueta').css('background-color','#000000');
				if (obj.layer.options.caixaColor!=undefined)	$('#dv_color_caixa_etiqueta').css('background-color',obj.layer.options.caixaColor);
				else 	$('#dv_color_caixa_etiqueta').css('background-color','#000000');
				if (obj.layer.options.opcionsVisEtiqueta!=undefined) $('input:radio[name=etiqueta][value='+obj.layer.options.opcionsVisEtiqueta+']').attr('checked', true);
				else $('input:radio[name=etiqueta][value=etiquetageom]').attr('checked', true);
				var zoomInicial = "2";
		 		if (obj.layer.options.zoomInicial) zoomInicial=obj.layer.options.zoomInicial;
		 		var zoomFinal = "19";
		 		if (obj.layer.options.zoomFinal) zoomFinal = obj.layer.options.zoomFinal;
		 		//Omplim els camps amb el que hi ha guardat a la BBDD
		 		 var tooltip = function(sliderObj, ui){
		 			 	
		                val1            = '<div id="slider_tooltip" style="font-size:10px;">'+ zoomInicial +'</div>';
		                val2            = '<div id="slider_tooltip" style="font-size:10px;">'+ zoomFinal +'</div>';
		                if (ui.values[0]==zoomInicial)  sliderObj.children('.ui-slider-handle').first().html(val1);
		                else  sliderObj.children('.ui-slider-handle').first().html('');
		                if (ui.values[1]==zoomFinal)   sliderObj.children('.ui-slider-handle').last().html(val2);
		                else  sliderObj.children('.ui-slider-handle').last().html('');
		            };
				$( "#slider" ).slider({
					range:true,
			        min: 2,
			        max: 19,			 
			        values: [parseInt(zoomInicial),parseInt(zoomFinal)],
			        change:function(event,ui){
		            	//tooltip($(this),ui);  
		            },
			        start: function( event, ui ) {
			        	$('#slider .ui-slider-handle').first().tooltip('destroy');			        
			        	$('#slider .ui-slider-handle').last().tooltip('destroy');
			        	
			        },
			        stop: function( event, ui ) {
			        	$('#slider .ui-slider-handle').first().html('');
			        	$('#slider .ui-slider-handle').last().html('');	
			            //alert(  ui.values[ 0 ] + " - " + ui.values[ 1 ] );
			             $('#slider .ui-slider-handle').first().tooltip({title: ui.values[0], trigger: 'manual', placement: 'bottom'}).tooltip("show");
			            $('#slider .ui-slider-handle').last().tooltip({title: ui.values[1], trigger: 'manual', placement: 'bottom'}).tooltip("show");
			         }    
			       }
				);
				
				
				$('#dialog_etiquetes_capa .btn-success').on('click', function (e) {
					e.preventDefault();
					e.stopImmediatePropagation();
					if (jQuery('#dataFieldEtiqueta').val()!=undefined && jQuery('#dataFieldEtiqueta').val()=="---"){
						alert("Cal escollir un camp per etiquetar");
					}
					else {
						var capaLeafletId = $('#dialog_etiquetes_capa #leafletIdCapaEtiqueta').val();
						var capaLeafletIdControl = $('#dialog_etiquetes_capa #leafletIdCapaEtiquetaControl').val();
						var color = rgb2hex($('#dv_color_etiqueta').css('background-color'));
						var caixaColor  = rgb2hex($('#dv_color_caixa_etiqueta').css('background-color'));
						var sliderVals =$("#slider").slider("values");
						var options = {
								campEtiqueta:jQuery('#dataFieldEtiqueta').val(),
								fontFamily:jQuery('#font-family').val(),
								fontSize:jQuery('#font-size').val(),
								fontStyle:jQuery('#font-style').val(),
								fontColor:color,
								opcionsVis:$("input[name=etiqueta]:checked").val(),
								caixaColor: caixaColor,
								contorn:$("input[name=contorn]:checked").val(),
								caixa:$("input[name=caixeti]:checked").val(),
								zoomInicial:sliderVals[0],
								zoomFinal:sliderVals[1]
						}
						var layerMap=map._layers[capaLeafletId];
						var optionsMap;
						if (layerMap==undefined) {
							layerMap = controlCapes._layers[capaLeafletId];
							optionsMap=layerMap.layer.options;
						}
						else optionsMap=layerMap.options;
						
						var data={
								businessId: $('#dialog_etiquetes_capa #businessIdCapaEtiqueta').val(),
								uid: Cookies.get('uid'),
								options:  JSON.stringify(options),
								nom:optionsMap.nom,
								tipus:optionsMap.tipusRang,
								geometryType:optionsMap.geometryType
						};
						updateVisualitzacioLayer(data).then(function(results){
							$('#dialog_etiquetes_capa').modal('hide');
							reloadVisualitzacioLayer(layerMap, results.visualitzacio, results.layer, map).then(function(results) {
								//refresh zoom etiquetes
								refrescarZoomEtiquetes(results);
							});
						});
					}
				});
				
			}
		}
	},
	
	_onRefreshClick : function(e) {
		$('.tooltip').hide();
		console.debug(e.currentTarget);
		var layerId = e.currentTarget.layerId;
		var layerIdParent = e.currentTarget.layerIdParent;
		console.debug(this._layers);
		var obj = this._layers[layerIdParent]._layers[layerId];
		//Refrescar els temàtics: eliminem sublayer del mapa, i recarreguem
		map.removeLayer(obj.layer);
		loadVisualitzacioLayer(obj.layer);
	},

	_showOptions : function(e) {
		var layerId = e.currentTarget.layerId;
		var inputs = this._form.getElementsByTagName('input');
		var obj = this._layers[layerId];
		showConfOptions(obj.layer.options.businessId);
	},

	_expand : function() {
		L.DomUtil.addClass(this._container,
				'leaflet-control-layers-expanded');
	},

	_collapse : function() {
		this._container.className = this._container.className.replace(
				' leaflet-control-layers-expanded', '');
	}
});
						
L.control.orderlayers = function(baseLayers, overlays, options) {
	return new L.Control.OrderLayers(baseLayers, overlays, options);
};

function isHeat(obj) {
	return (obj.layer.options.tipusRang && obj.layer.options.tipusRang
			.indexOf('heatmap') != -1);
}

function showConfOptions(businessId) {
	jQuery(".conf-" + businessId + "").toggle("fast");
	addTooltipsConfOptions(businessId);
}

function updateCheckStyle() {
	$('.leaflet-input input').iCheck({
		checkboxClass : 'icheckbox_flat-blue',
		radioClass : 'iradio_flat-blue'
	});
}

function thisFillModalDataTable(obj) {
	fillModalDataTable(obj);
}

function thisLoadMapLegendEdicio(obj) {
	if (getModeMapa()){
		loadMapLegendEdicio(obj);
	}
}

function thisLoadMapLegendEdicioDinamic(obj) {
	if (getModeMapa()){
		loadMapLegendEdicioDinamics(obj);
	}
}

function thisEmptyMapLegendEdicio(obj,isOrigen) {
	if (getModeMapa()){
		emptyMapLegendEdicio(obj,isOrigen);
	}
}
<file_sep>/deploy.sh
#!/bin/bash

# In case that something fails, stops execution
set -e

cd /usr/local/nginx/html/
su nginx
git fetch origin production
git fetch --tags
git pull origin production
chown -R nginx:nginx *
chmod 777 -Rf maps
chmod 777 -Rf mapcache
<file_sep>/geocatweb/js/geocat.ajax-1.0.0.js
runningActions = [];

function actionCompleted(jqXHR, status) {
	//Remove the completed action from the running actions
	var index = runningActions.indexOf(jqXHR);
	runningActions.splice(index, 1);
}

function loadPublicGaleria(params){
	var xhr = jQuery.ajax({
		url: paramUrl.getAllPublicsMaps,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function loadNumGaleria(){
	var xhr = jQuery.ajax({
		url: paramUrl.getNumGaleria,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}


function searchGaleriaMaps(params){
	var xhr = jQuery.ajax({
		url: paramUrl.searchGaleriaMaps,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function searchGaleriaMapsByUser(params){
	var xhr = jQuery.ajax({
		url: paramUrl.searchGaleriaMapsByUser,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteMap,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* registre.html */

function registerUser(url, dataUrl){
	var xhr = jQuery.ajax({
		url: url,
		data: dataUrl,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();		
}

function checkUsername(username){
	  var xhr = jQuery.ajax({
			url: paramUrl.validateUsername,
			data: {uid:username},
			method: 'post',
			dataType: 'jsonp',
			complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function checkEmail(user_email){
	  var xhr = jQuery.ajax({
			url: paramUrl.validateEmail,
			data: {email: user_email},
			method: 'post',
			dataType: 'jsonp',
			complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* galeria.html */

//solo galeria privada de geolocal para obtener las aplicaciones
function getUserData(username){
	var xhr = jQuery.ajax({
		url: paramUrl.getUserSimple,
		data: {uid : username},
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* comuns */
function doLogout(){
	var xhr = jQuery.ajax({
		url: paramUrl.logoutUser,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* sessio.html */

function doLogin(data){
	var xhr = jQuery.ajax({
		url: paramUrl.loginUser,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function doLoginIcgc(data){
	var xhr = jQuery.ajax({
		url: paramUrl.loginUserIcgc,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function loginToken(data){
	var xhr = jQuery.ajax({
		url: paramUrl.loginToken,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* map */
function createTematicLayerFeature(data){
	var xhr = $.ajax({
		url: paramUrl.createTematicLayerFeature,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function addFeatureToTematic(data){
	var xhr = $.ajax({
		url: paramUrl.addFeatureToTematic,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getTematicLayerByBusinessId(data){
	var xhr = $.ajax({
		url: paramUrl.getTematicLayerByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getCacheVisualitzacioLayerByBusinessId(data){
	var xhr = $.ajax({
		url: paramUrl.getCacheVisualitzacioLayerByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createFeature(data){
	var xhr = $.ajax({
		url: paramUrl.createFeature,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createData(data){
	var xhr = $.ajax({
		url: paramUrl.createData,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createRang(data){
	var xhr = $.ajax({
		url: paramUrl.createRang,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getLListaDadesObertes(){
	var xhr = jQuery.ajax({
		url: paramUrl.dadesObertes,
		data: {metode:'getDatasets'},
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getMapByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getMapByBusinessId,
		//url: paramUrl.getMapById,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getCacheMapByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getCacheMapByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/*//Local
function updateMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}*/

function updateMap(data){
	var xhr = jQuery.ajax({
//		url: paramUrl.proxy + "?url=" + paramUrl.updateMap + "&uid="+data.uid,
		url: paramUrl.updateMap,
		data: data,
		method: 'POST',
//		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getAllServidorsWMSByUser(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getAllServidorsWMSByUser,
		data: data,
		method: 'POST',
//		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function addServerToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.addServerToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getAllTematicLayerByUid(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getAllTematicLayerByUid,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteTematicLayerAll(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteTematicLayerAll,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function doUpdateMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateServersOrderToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServersOrderToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}


function updateServerOrderToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServerOrderToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateMapName(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateMapName,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getTwitterLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getTwitterLayer,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function removeServerToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.removeServerToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteServerRemoved(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteServerRemoved,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateServidorWMSName(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServidorWMSName,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}


function updateServidorWMSOptions(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServidorWMSOptions,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateServidorWMSGroup(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServidorWMSGroup,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateServidorWMSOpacity(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServidorWMSOpacity,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}



function addServerToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.addServerToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createServidorInMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createServidorInMap,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getWikipediaLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getWikipediaLayer,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function shortUrl(url){
    var xhr = jQuery.ajax({
    	url: paramUrl.shortUrl,
        contentType: "application/json; charset=utf-8",
        method: 'POST',
        data: JSON.stringify({longUrl: url}),
        dataType: 'json',
    	complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function doReadFile(data){
	var xhr = jQuery.ajax({
		url: paramUrl.readFile,
		data: data,
		//async: false,
		//method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function doUploadFile(data){
	var xhr = jQuery.ajax({
		url: paramUrl.uploadFile,
		data: data,
		//async: false,
		//method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getDownloadLayer(data){
	var xhr = jQuery.ajax({
		//url: paramUrl.proxy_download,
		url: paramUrl.download_layer,
		data: data,
		type: "POST",
//		dataType: 'html'
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteServidorWMS(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteServidorWMS,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createTematicLayerEmpty(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createTematicLayerEmpty,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function moveFeatureToTematic(data){
	var xhr = jQuery.ajax({
		url: paramUrl.moveFeatureToTematic,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteFeature(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteFeature,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateFeature(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateFeature,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateTematicRangs(data){
    var xhr = jQuery.ajax({
    	//url: paramUrl.proxy + "?url=" + paramUrl.updateTematicRangs + "&uid="+data.uid,
        url: paramUrl.updateTematicRangs,
        data: data,
        method: 'post',
    	complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createRandomUser(){
	var xhr = jQuery.ajax({
		url: paramUrl.createRandomUser,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteRandomUser(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteRandomUser,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getJSONPServei(url){
	var xhr = jQuery.ajax({
		url: paramUrl.json2jsonp,
		data: {url:url},
		async: false,
		method: 'post',
		dataType: 'jsonp',
	});
	runningActions.push(xhr);
	return xhr.promise()
	.fail(function(msg,err) {
		console.info(err);
	});
}

function updateServidorWMS(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateServidorWMS,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function duplicateTematicLayer(data){
	var xhr = jQuery.ajax({
		//url: paramUrl.proxy + "?url=" + paramUrl.duplicateTematicLayer + "&uid="+data.uid,
		url: paramUrl.duplicateTematicLayer,
		data: data,
		method: 'post',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function reminderMail(data){
	var xhr = jQuery.ajax({
		url: paramUrl.reminderMail,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function renewPassword(data){
	var xhr = jQuery.ajax({
		url: paramUrl.renewPassword,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getNumEntitatsActives(){
	var xhr = jQuery.ajax({
		url: paramUrl.getNumEntitatsActives,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getNumMapes(){
	var xhr = jQuery.ajax({
		url: paramUrl.getNumMapes,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getNumCapes(){
	var xhr = jQuery.ajax({
		url: paramUrl.getNumCapes,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function publicarCapesMapa(data){
	var xhr = jQuery.ajax({
		url: paramUrl.publicarCapesMapa,
		data: data,
		method: 'post',
		//dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function publicarMapConfig(data){
	var xhr = jQuery.ajax({
		url: paramUrl.publicarMapConfig,
		data: data,
		method: 'post',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getUrlFile(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlFile,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteUser(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteUser,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getUrlFileProves(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlFileProves,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getUrlFileNoDin(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlFileNoDin,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getUrlFileDin(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlFileDin,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getUserSimple(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getUserSimple,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function uploadImageBase64(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urluploadBase64,		
		data: data,		
		contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		method: 'POST',
		dataType: 'json',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}	


function createGeoPdfMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlgetMapImage,
		data: data,	
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		method: 'POST',
		dataType: 'json',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}	



function createMapToWMS(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlMapToWMS,
		data: data,	
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		method: 'POST',
		dataType: 'json',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}	



//esborra imatge galeria

function deleteImageGaleria(data){
	var xhr = jQuery.ajax({
		url: paramUrl.urlgetMapImage,
		data:data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}





function updatePasswordIcgc(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updatePasswordIcgc,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}


/*FUNCIONS NOU MODEL*/
function createVisualitzacioLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createVisualitzacioLayer,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function addGeometriaToVisualitzacio(data){
	var xhr = jQuery.ajax({
		url: paramUrl.addGeometriaToVisualitzacio,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function moveGeometriaToVisualitzacio(data){
	var xhr = jQuery.ajax({
		url: paramUrl.moveGeometriaToVisualitzacio,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateGeometria(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateGeometria,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function modificarEstiloGeometria(data){
	var xhr = jQuery.ajax({
		url: paramUrl.modificarEstiloGeometria,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function removeGeometriaFromVisualitzacio(data){
	var xhr = jQuery.ajax({
		url: paramUrl.removeGeometriaFromVisualitzacio,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateNameVisualitzacioLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateNameVisualitzacioLayer,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteVisualitzacioLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteVisualitzacioLayer,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getVisualitzacioByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getVisualitzacioByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createVisualitzacioSimple(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createVisualitzacioSimple,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createVisualitzacioTematica(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createVisualitzacioTematica,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createVisualitzacioHeatCluster(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createVisualitzacioHeatCluster,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getGeometriesColleccioByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getGeometriesColleccioByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/*Data Table*/

function getGeometriesPropertiesLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getGeometriesPropertiesLayer,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function removeGeometriaFromProperties(data){
	var xhr = jQuery.ajax({
		url: paramUrl.removeGeometriaFromProperties,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function updateGeometriaProperties(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateGeometriaProperties,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

/* galeria.html */
function updateMapVisibility(data){
	var xhr = jQuery.ajax({
		url: paramUrl.updateMapVisibility,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function sendMail(data){
	var xhr = jQuery.ajax({
		url: paramUrl.sendMail,
		data: data,
		method: 'post',
        dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function loadMapsColaboracio(params){
	var xhr = jQuery.ajax({
		url: paramUrl.getEntitatsAplicacioRolByUidColaborador,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function getEntitatsColaboradorsByAplicacio(params){
	var xhr = jQuery.ajax({
		url: paramUrl.getEntitatsColaboradorsByAplicacio,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function getConvidatsByBusinessId(params){
	var xhr = jQuery.ajax({
		url: paramUrl.getConvidatsByBusinessId,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function deleteConvidatByBusinessId(params){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteConvidatByBusinessId,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function deleteUser(params){
	var xhr = jQuery.ajax({
		url: paramUrl.deleteUser,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
/*
function updateRankAplicacio(params){
	var xhr = jQuery.ajax({
		url: paramUrl.updateRankAplicacio,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
});
runningActions.push(xhr);
return xhr.promise();
}
*/
function buffer(params){
	var xhr = jQuery.ajax({
		url: paramUrl.buffer,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function centroid(params){
	var xhr = jQuery.ajax({
		url: paramUrl.centroid,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function intersection(params){
	var xhr = jQuery.ajax({
		url: paramUrl.intersection,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function union(params){
	var xhr = jQuery.ajax({
		url: paramUrl.union,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function tag(params){
	var xhr = jQuery.ajax({
		url: paramUrl.tag,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function getVisualitzacioSimpleByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getVisualitzacioSimpleByBusinessId,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function filterVisualitzacio(data){
	var xhr = jQuery.ajax({
		url: paramUrl.filterVisualitzacio,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function registreInstamaper(data){
	var xhr = jQuery.ajax({
		url: paramUrl.signinInstamaper,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function crearFitxerPolling(params){
	var xhr = jQuery.ajax({
		url: paramUrl.crearFitxerPolling,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function resetClauMapa(data){
	var xhr = jQuery.ajax({
		url: paramUrl.resetClauMapa,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function loadPrivateMapByBusinessId(data){
	var xhr = jQuery.ajax({
		url: paramUrl.loadPrivateMapByBusinessId,
		method: 'post',
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function filter(params){
	var xhr = jQuery.ajax({
		url: paramUrl.filter,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function callActions(data){
	var xhr = jQuery.ajax({
		url: paramUrl.callActions,
		data: data,
		async: false,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function loadAplicacionsUser(){
	/*
	var xhr = jQuery.ajax({
		url: paramUrl.loadAplicacionsUser,
		method: 'get',
		dataType: 'json'
		complete: actionCompleted
});
runningActions.push(xhr);
return xhr.promise();
	*/
	var defer = jQuery.Deferred();
	defer.resolve(perfilConfig);
	return defer.promise();
}

function getUser(username){
	var xhr = jQuery.ajax({
		url: paramUrl.getUser,
		data: {uid : username},
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getConfiguradesUser(data){
	var xhr = jQuery.ajax({
		url: paramUrl.getConfiguradesUser,
		data: data,
		crossDomain: true,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function deleteAplicacionsGeolocal(url){
	var xhr = jQuery.ajax({
		url: url,
		crossDomain: true,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function createToken(data){
	var xhr = jQuery.ajax({
		url: paramUrl.createToken,
		data: data,
		method: 'post',
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function getValuesFromKeysProperty(params){
	var xhr = jQuery.ajax({
		url: paramUrl.getValuesFromKeysProperty,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function columnJoin(params){
	var xhr = jQuery.ajax({
		url: paramUrl.columnJoin,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function spatialJoin(params){
	var xhr = jQuery.ajax({
		url: paramUrl.spatialJoin,
  		data: params,
  		method: 'post',
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function searchCapesPubliques(params){
	var xhr = jQuery.ajax({
		url: paramUrl.searchCapesPubliques,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function addServerDuplicateToMap(data){
	var xhr = jQuery.ajax({
		url: paramUrl.addServerDuplicateToMap,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function duplicateVisualitzacioLayer(data){
	var xhr = jQuery.ajax({
		url: paramUrl.duplicateVisualitzacioLayer,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function searchCatalegIdec(params){
	var xhr = jQuery.ajax({
		url: paramUrl.searchCatalegIdec,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function addGeometriaToVisualitzacioTematic(params){
	var xhr = jQuery.ajax({
		url: paramUrl.addGeometriaToVisualitzacioTematic,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function updateVisualitzacioLayer(params){
	var xhr = jQuery.ajax({
		url: paramUrl.updateVisualitzacioLayer,
		data: params,
  		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function searchCatalogInspire(params){
	var xhr = jQuery.ajax({
			url: paramUrl.urlgetInspireCatalog,
			data: params,
			traditional:true,
			dataType: 'jsonp',
			jsonp: 'json.wrf',
			complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function desbloquejarMapa(data){
	var xhr = jQuery.ajax({
		url: paramUrl.desbloquejarMapa,
		data: data,
		dataType: 'jsonp',
		complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}
function crearFitxerSocrata(data){
	var xhr = jQuery.ajax({
			url: paramUrl.crearFitxerSocrata,
			data: data,
			method: 'post',
			dataType: 'jsonp',			
			complete: actionCompleted
	});
	runningActions.push(xhr);
	return xhr.promise();
}

function generateTokenRemember(data){
	var xhr = jQuery.ajax({
		url: paramUrl.generateTokenRemember,
		data: data,
		method: 'post',
		dataType: 'jsonp',			
		complete: actionCompleted
});
runningActions.push(xhr);
return xhr.promise();
}
<file_sep>/geocatweb/js/instamaps.geolocal.widgets.mascara.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetMascara = {
					
		init: function() {
			
			
			this.url = "/geotimeservices/aoc?";
			this.layerFiltreCom='filtre_comarca';
			this.layerFiltreMuni='filtre_municipi'
			this.layerWMS=null;
			this.itemActive=null;
			this.containerId = '.drawWidgets';
			this.cache();
        	this.subscriptions();
        	//this.bindEvents();			
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	this.container = $(this.containerId);
        },
        
        getWidget: function(){
        	return this;
        },
                
        drawButton: function(container){
			
			var selMask = $('<input/>')
        	.addClass('chk_mascara')
        	.prop('type', "checkbox")
			
			.prop('id', "id_chk_mascara")
        	.on('click',function(){
        		$.publish('changeMask',$(this).prop('checked'));
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_Mascara']});
        	});
			
			var selMaskdiv = $('<div/>').addClass('checkbox');
			selMask.appendTo(selMaskdiv);
			
			var selLabelMask=$('<label />')
			.prop('for', "id_chk_mascara")
			.text( "Aplicar màscara");
			selLabelMask.appendTo(selMaskdiv);
			container.append( selMaskdiv);
			
			
			this.bindEvents();	
			
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	$(this.containerId).empty();
        },
        getActiveItem:function(){
		
			return this.itemActive;
		
		},	
		
		setActiveItem:function(data){
			 this.itemActive=data;
			
		},	
		draw:function(data,input){
			
			var that = this;
				
			if(this.layerWMS !=null && map.hasLayer(this.layerWMS)){map.removeLayer(this.layerWMS);}	
			
			if(input){

			var layerFiltre=that.layerFiltreMuni;

				this.itemActive.tipusMunicipi?layerFiltre=that.layerFiltreMuni:layerFiltre=that.layerFiltreCom;
					
					this.layerWMS= L.tileLayer.betterWms(that.url, {
					layers : layerFiltre,
					//crs : '3857',
					
					transparent : true,
					CODIENS : this.itemActive.municipiMunicat,
					exceptions:'application/vnd.ogc.se_blank',
					//exceptions:checkExceptionsType(wms.url),
					format : 'image/png',
					wmstime:false,
					tileSize:512
				}).addTo(map).bringToFront();
			
			}
			
			
		
		},
		
        
                
        /**********Events**************/
        bindEvents: function(){
			var _that =this;
			map.on('layeradd',function(e){
				
				if(_that.layerWMS !=null && map.hasLayer(_that.layerWMS)){_that.layerWMS.bringToFront()}	
				
			});	
			
			
        },
        
        subscriptions: function() {
        	var _that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
				
				_that.setActiveItem(data);
				
        		if(data && $('#id_chk_mascara').prop('checked')){
     
				_that.draw(data, true);	
					
					
        		}
        	});
			
			
			
			$.subscribe('changeMask',function(e, input){
				
				
			
				var data=_that.getActiveItem();
								
        		if(input && data ){					
					
					_that.draw(data, true);	

        		}else{
				
				_that.draw(null, false);	
				
				}	
        	});
			
			
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetMascara.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetMascara = WidgetMascara.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/instamaps.google-analytics.js
/**
 * Se encargar de agregar el ga y controlar los eventos
 * 
 * require jQuery.cookie
 * require geocat.utils
 */
var _gaq = _gaq || [];
 
(function() {
	$.subscribe('loadConfig', function(e, data){
		var _mapConfig = data,
			perfil = Cookies.get('perfil');
		//Diferenciem entre usuari Geolocal i Instamaps
		if (isGeolocalUser() || $(location).attr('href').indexOf('geolocal.html') != -1 || perfil === 'geolocal') {	  
			_gaq.push(['_setAccount', 'UA-46332195-6']);
		}else if (_mapConfig && _mapConfig.tipusAplicacioId == TIPUS_APLIACIO_GEOLOCAL || _mapConfig.tipusAplicacioId == TIPUS_APLIACIO_AOC){
			_gaq.push(['_setAccount', 'UA-46332195-6']);
		}else{ 
			_gaq.push(['_setAccount', 'UA-46332195-3']);
		}
	  	_gaq.push(['_trackPageview']);

		//TODO poner el subscriber
		$.publish('loadGaEvents');
	});
	
	$.subscribe('trackEvent', function(e, data){
		checkIfAnalyticsLoaded(data);
	});
	
	$.subscribe('trackPageview', function(e, data){
		_gaq.push(['_trackPageview']);
	});
})();

function checkIfAnalyticsLoaded(data) {
	if($.isArray(_gaq)){
		setTimeout(function(){
			checkIfAnalyticsLoaded(data);
		}, 500);
	}else{
		_gaq.push(data.event);
	}
}
 
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
<file_sep>/geocatweb/js/geocat.oblidat-1.0.0.js
var trackEventFrom = '';

jQuery(document).ready(function() {
	jQuery(document).keypress(function(e) {
	    if(e.which == 13) {
	    	jQuery("#login_button").click();
	    }
	});
	
	$.publish('loadConfig', null);
	
});//Fi document ready

jQuery("#login_button").click(function(){

	_gaq.push(['_trackEvent',trackEventFrom,'remember password', 'retention']);
	
	if(!$('#login_user').val()){
		$('#login_user').addClass("invalid");
		$( ".text_error" ).removeClass('hide').show();
	}else{
		$('#login_user').removeClass("invalid");
		$( ".text_error" ).hide();
		
		var dataUrl = {
			email: $('#login_user').val(),
			lang: window.lang.currentLang
		}
		
		reminderMail(dataUrl).always(function(results){
			if (results.status=="OK") {
				if (results.results =="reminderMail") {
					$('#modal_send_mail').modal('toggle');
				}
				else {
					var providers = results.results;
					var html = providers;					
					$('#profiler').html(html);
					$('#modal_provider_noticgc').modal('toggle');
				}
			}
			else if (results.status=="ERROR") {
				if (results.results=="EntitatNotFoundException"){
					$('#modal_user_not_exists').modal('toggle');
				}
				else if (results.results=="EntitatNotActiveException"){
					$('#modal_user_not_active').modal('toggle');
				}
				else if (results.results=="unregistered_user"){
					$('#modal_user_not_active').modal('toggle');
				}
			}
		});
	}
});<file_sep>/geocatweb/js/geocat.mapa.legend.js
/*************** LLEGENDA ********************/

function addLegend(){
	legend = L.control({position: 'bottomright'});
	legend.onAdd = function (map) {
	    var div = L.DomUtil.create('div', 'info legend visor-legend mCustomScrollbar');
	    div.id = "mapLegend";
	    jQuery.each(mapLegend, function(i, row){
	    	for (var i = 0; i < row.length; i++) {
	    		if(row[i].chck){
	    			//console.debug(row[i]);
	    			if (row[i].symbol.indexOf("circle")>-1){
	    				var padding_left="0px";
	    				var midaStr = row[i].symbol.substring(row[i].symbol.indexOf("r="),row[i].symbol.indexOf("style"));
	    				midaStr=midaStr.substring(midaStr.indexOf("=")+2,midaStr.length-2);
	    				var mida=parseFloat(midaStr);
	    				if (mida>0 && mida<=6) padding_left="15px";
	    				else if (mida>6 && mida<=14) padding_left="10px";
	    				else if (mida>14 && mida<=22) padding_left="5px";
	    				div.innerHTML +='<div class="visor-legend-row">'+
		    				'<div class="visor-legend-symbol col-md-4 col-xs-4" style="padding-left:'+padding_left+'">'+row[i].symbol+'</div>'+
		    				'<div class="visor-legend-name col-md-8 col-xs-8" style="float:right;width:40%">'+row[i].name+'</div>'+
		    				'</div>'+
		    				'<div class="visor-separate-legend-row"></div>';	
	    			}
	    			else{
	    			div.innerHTML +='<div class="visor-legend-row">'+
						'<div class="visor-legend-symbol col-md-4 col-xs-4">'+row[i].symbol+'</div>'+
						'<div class="visor-legend-name col-md-8 col-xs-8" style="float:right;">'+row[i].name+'</div>'+
	    				'</div>'+
	    				'<div class="visor-separate-legend-row"></div>';	    			
	    			}	    			
	    		}
	    	}
	    });
	    return div;
	};
	
	ctr_legend = L.control({
		position : 'bottomright'
	});
	ctr_legend.onAdd = function(map) {
		this._div = L.DomUtil.create('div', 'div_barrabotons btn-group-vertical');
		var btllista = L.DomUtil.create('div', 'leaflet-bar btn btn-default btn-sm bt_legend');
		this._div.appendChild(btllista);
		btllista.innerHTML = '<span class="fa fa-list-alt greenfort"></span>';
		return this._div;
	};
	ctr_legend.addTo(map);	
	legend.addTo(map);
}

/*Control llegenda buida o be, q hagi publicat el mapa amb llegenda, 
pero cap opcio de la llegenda marcada*/
function checkEmptyMapLegend(){
	var trobat = false;
	if(typeof mapLegend == "string" ) mapLegend = [mapLegend]
	jQuery.each(mapLegend, function(i, row){
    	for (var i = 0; i < row.length && !trobat; i++) {
    		if(row[i].chck){
    			trobat = true;
    		}
    	}		
	});
	if(trobat){
		addLegend();
		$("#mapLegend").mCustomScrollbar();
	}
}

function createModalConfigLegend(){
	//Obrim modal llegenda
	var html = '<span lang="ca" id="llegenda-title-text"  style="width:20%;font-size: 18px;">'+window.lang.translate('Llegenda')+'</span><span>&nbsp;&nbsp;&nbsp;&nbsp;'+window.lang.translate('Marca els símbols que vols que es visualitzin')+'</span>';
	html += '<div class="separate-legend-row-all"></div>';
	html += '<div class="legend-row">'+
				'<div class="legend-subrow-all">'+
				'<input id="legend-chck-all" class="col-md-1 legend-chck" type="checkbox">'+
				'<div class="col-md-11 legend-name-all">'+
					window.lang.translate('Tots')+
				'</div>'+
			'</div>';
	var count = 0;
	var layersHtml = {order:[], notorder:[]};
	html += '<div class="sortable">';
	
	
	
	jQuery.each(controlCapes._layers, function(i, item){
		controlLegendPoint = [];
		controlLegendMarker = [];
		controlLegendLine = [];
		controlLegendPol = [];
		//console.debug(item);
		layersHtml = addLayerToLegend(item.layer, count,layersHtml);
		count++;
		jQuery.each(item._layers, function(i, sublayer){
			if (sublayer._layers!=undefined && sublayer._layer.length>0){
				jQuery.each(sublayer._layers, function(i, sublayer2){
					layersHtml = addLayerToLegend(sublayer2.layer, count, layersHtml, sublayer2.layerIdParent );
					count++;
				});
			}
			else {
				layersHtml = addLayerToLegend(sublayer.layer, count, layersHtml, sublayer.layerIdParent );
				count++;
			}
		});
	});
	
	jQuery.each(layersHtml.order, function(i, item){
		if(isValidValue(item)){
			html += item;
		}
	});
	jQuery.each(layersHtml.notorder, function(i, item){
		if(isValidValue(item)){
			html += item;
		}
	});
	html += '</div>';
	$('#dialgo_publicar .modal-body .modal-legend').html(html);
	$('#dialgo_publicar .modal-body .modal-legend').show();
	$('.legend-subrow input, .legend-subrow-all input').iCheck({
	    checkboxClass: 'icheckbox_flat-blue',
	    radioClass: 'iradio_flat-blue'
	});	
		
	
	$('.legend-subrow-all input').on('ifChecked', function(event){
		  $('.legend-subrow input').iCheck('check');
	});
	
	$('.legend-subrow-all input').on('ifUnchecked', function(event){
		  $('.legend-subrow input').iCheck('uncheck');
	});	
	
	$('.sortable').sortable();
	
	return html;
}



function generallegendaMapaEdicio(){
		
	var arbreHTML=createModalConfigLegend();	
	var mapLegendTMP = {};
		
	$(arbreHTML).find(".legend-subrow").each(function(index,element){
	
	var businessId = $(element).attr('data-businessId');
		var html=$(element).children(".legend-symbol").html();
		if(html.indexOf('GetLegendGraphic')!= -1){
			html=html.replace(/width:26px;/g,'');
			html=html.replace('png8','png');
		}
		var obj = {
			chck : true,
			symbol : html,
			name : $(element).children(".legend-name").children("input").val(),
			order: index
		};
		if(!mapLegendTMP[businessId]){
			mapLegendTMP[businessId] = [];
		}
		mapLegendTMP[businessId].push(obj);
	
	});
	
	/*
	$.each(arbreHTML.order,function(index,element){
		
	});
*/
			
	return mapLegendTMP;

}	


function obteLListatCapesEditor(idLayer){	
	var layerType={};

		jQuery.each(controlCapes._layers, function(i, item){
				if(item.layer.options.businessId==idLayer){					
					layerType.serverName=item.layer.options.nom.replace('##1','');
					layerType.capesOrdre=""+i+"";					
				}	
				
		jQuery.each(item._layers, function(j, item2){
				if(item2.layer.options.businessId==idLayer){					
					layerType.serverName=item2.layer.options.nom.replace('##1','');
					layerType.capesOrdre="sublayer";					
				}			
			});		
			
		});
		return layerType;		
}	





function addLayerToLegend(layer, count, layersHtml, layerIdParent){
	var html = "";
	html += '<div class="legend-row">';
	html+='<div class="separate-legend-row"></div>';
	var layerName = layer.options.nom;
	
	
	var checked = "";
	if(undefined != mapLegend[layer.options.businessId]){
		layerName = mapLegend[layer.options.businessId][0].name;
		if(mapLegend[layer.options.businessId][0].chck) checked = 'checked="checked"';
	}
	if (layerIdParent!=undefined){
		 layerName = layer.options.nom;
	}
	html += '<div class="legend-row" style="padding-left:15px">'+layerName+'</div>'; 
	//Cluster
	if(layer.options.tipusRang && layer.options.tipusRang == tem_cluster){
		html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
		html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
		html += '<div class="col-md-2 legend-symbol">'+
					'<img src="img/clustering.png" class="btn-paleta" style=""/>'+
				'</div>'+
				'<div class="col-md-9 legend-name">'+
					'<input type="text" class="form-control my-border" value="'+layerName+'">'+
				'</div>';
		html+='</div>';
	//Heatmap
	}else if(layer.options.tipusRang && layer.options.tipusRang == tem_heatmap){
		html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
		html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';	
		html += '<div class="col-md-2 legend-symbol">'+
					'<img src="img/heatmap.png" class="btn-paleta" style=""/>'+
				'</div>'+
				'<div class="col-md-9 legend-name">'+
					'<input type="text" class="form-control my-border" value="'+layerName+'">'+
				'</div>';		
		html+='</div>';
	//WMS
	}else if(layer.options.tipus == t_wms){
		
		try{
		var legend_layer = layer.getLegendGraphic();
		html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
		html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';	
		html += '<div class="col-md-2 legend-symbol">';
			if(!jQuery.isArray(legend_layer)){
				html += '<img src="'+layer.getLegendGraphic()+'" class="btn-paleta img-legend" style="width:26px;max-width:150px !important"/>';
			}else{
				jQuery.each(legend_layer, function(i, lay){
					html += '<img src="'+lay+'" class="btn-paleta img-legend" style="width:26px;max-width:150px !important"/>';
				});
			}
		html +=	'</div>'+
			'<div class="col-md-9 legend-name">'+
				'<input type="text" class="form-control my-border" value="'+layerName+'">'+
			'</div>';		
		html+='</div>';	
		
		}catch(exception){
            
        }

	//Dades obertes y JSON
	}else if(layer.options.tipus == t_dades_obertes || layer.options.tipus == t_json){//es un punt
		var estil_do = layer.options.estil_do;
		if(layer.options.options && layer.options.options.estil_do) estil_do = layer.options.options.estil_do;//Si es JSON
		else if(estil_do.options) estil_do = estil_do.options;
		if(estil_do.isCanvas || estil_do.markerColor.indexOf("punt_r")!=-1){
			var size="";
			if(estil_do.iconSize){
				size = 'width: '+estil_do.iconSize.x+'px; height: '+estil_do.iconSize.y+'px;';
			}else{
				var mida = getMidaFromRadius(estil_do.radius);
				if (layer.options.tem == tem_size) mida = estil_do.iconSize;
				size = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';
			}
			var icon = "";
			var colorIcon=""; 
			var auxColor="";
			if(estil_do.divColor){
				auxColor = hexToRgb(estil_do.divColor);
				colorIcon = 'color: rgb('+auxColor.r+', '+auxColor.g+', '+auxColor.b+');';
			} 
			if(estil_do.fillColor){
				auxColor = hexToRgb(estil_do.fillColor);
			} 
			if(estil_do.icon){
				icon = "fa fa-"+estil_do.icon;
			}
			html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
			html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
			if (layer.options.tem != tem_size){
			html +=	'<div class="col-md-2 legend-symbol">'+
						'<div class="awesome-marker-web awesome-marker-icon-punt_r '+icon+' legend-symbol" '+
							'style="background-color: rgb('+auxColor.r+', '+auxColor.g+', '+auxColor.b+'); '+
							' '+size+'">'+
						'</div>'+
					'</div>'+
					'<div class="col-md-9 legend-name">'+
						'<input type="text" class="form-control my-border" value="'+layerName+'">'+
					'</div>';
			}else{
				if(mida>=60) mida=60;
				var height=mida*2.8;
				var padding_left="0px";
				if (mida>0 && mida<=6) padding_left="28px";
				else if (mida>6 && mida<=14) padding_left="22px";
				else if (mida>14 && mida<=22) padding_left="16px";
				else if (mida>22 && mida<=34) padding_left="10px";
				else if (mida>34 && mida<=40) padding_left="5px";

				var color = hexToRgb(estil_do.fillColor);
				html +=	'<div class="col-md-2 legend-symbol" style="padding-left:'+padding_left+'">'+
						'<svg height="'+height+'">'+
							'<circle cx="'+mida+'" cy="'+mida+'" r="'+mida+'" '+
							'style="stroke:white; fill:rgb('+color.r+', '+color.g+', '+color.b+');"></circle>'+
							'</svg>';
						'</div>'+
						'<div class="col-md-9 legend-name" style="padding-left:45px">'+
							'<input type="text" class="form-control my-border" value="'+layerName+'">'+
						'</div>';
			}
			html+='</div>';
		}else{
			var color = hexToRgb(estil_do.iconColor);
			html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
			html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';	
			html += '<div class="col-md-2 legend-symbol">'+
						'<div class="awesome-marker-web awesome-marker-icon-'+estil_do.markerColor+
							' fa fa-'+estil_do.icon+'" style="width: 28px; height: 42px; font-size: 14px;'+ 
							'background-color: transparent; color: rgb('+color.r+', '+color.g+', '+color.b+');">'+
						'</div>'+
					'</div>'+
					'<div class="col-md-9 legend-name">'+
						'<input type="text" class="form-control my-border" value="'+layerName+'">'+
					'</div>';
			html+='</div>';
		}
	//URL FILE
	}else if(layer.options.tipus == t_url_file){
		var type = "";
		var geometrytype = "";
		jQuery.each(layer._layers, function(i, lay){
			geometrytype = lay.feature.geometry.type.toLowerCase(); 
			return (geometrytype=="");
		});		
		geometrytype = transformTipusGeometry(geometrytype);
		
		if(layer.options.tem && (layer.options.tem == tem_clasic || layer.options.tem == tem_size)){
			var i = 0;
			var controlColorCategoria = [];//per controlar que aquell color no esta afegit ja a la llegenda
			var estils = layer.options.estil_do.estils;
			var label = layer.options.estil_do.dataField;
			if(geometrytype == t_marker){
					var map={};
					jQuery.each(layer._layers, function(i, lay){
						if (layer.options.tem=='sizeTematic'){
							var radius=lay.options.radius;
							if (radius!=undefined){
								if (map[radius]==undefined) map[radius]=1;
								else {
									var i=map[radius];
									map[radius]=i+1;
								}
							}
						}
						else{
							var color = lay.options.fillColor;
							if (color!=undefined){
								if (map[color]==undefined) map[color]=1;
								else {
									var i=map[color];
									map[color]=i+1;
								}
							}
						}
					});
					jQuery.each(estils, function(i, estilRang){
						
						var mida = getMidaFromRadius(estilRang.estil.simbolSize);
						if (layer.options.tem == tem_size) mida = estilRang.estil.simbolSize; 
						var iconSize = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';						
						var color = hexToRgb(estilRang.estil.color);
						if(mida>=60) mida=60;
						var height=mida*2.8;
						var padding_left="0px";
						if (mida>0 && mida<=6) padding_left="28px";
						else if (mida>6 && mida<=14) padding_left="22px";
						else if (mida>14 && mida<=22) padding_left="16px";
						else if (mida>22 && mida<=34) padding_left="10px";
						else if (mida>34 && mida<=40) padding_left="5px";
						
						
						
						var stringStyle =	'<svg height="'+height+'">'+
											'<circle cx="'+mida+'" cy="'+mida+'" r="'+mida+'" '+
												'style="stroke:white; fill:rgb('+color.r+', '+color.g+', '+color.b+');"></circle>'+
											'</svg>';
						if (layer.options.tem!=tem_size){
							stringStyle ='<div class="awesome-marker-web awesome-marker-icon-punt_r legend-symbol" '+
											'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+
											' '+iconSize+'">'+
										'</div>';
						}
						
						var labelNomCategoria = "";
						checked = "";
						var index=-1;
						if (undefined!=mapLegend[layer.options.businessId]) {
							index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
						}
						
						if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
							labelNomCategoria = mapLegend[layer.options.businessId][index].name;
							if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
						}else{
							if(estilRang.valueMax == estilRang.valueMin){
								labelNomCategoria = estilRang.valueMax;
							}else{
								labelNomCategoria = estilRang.valueMin +" - "+ estilRang.valueMax;
							}
							
							if(labelNomCategoria == "Altres"){
								labelNomCategoria = window.lang.translate("Altres");
							}
							
						}						
						if (layer.options.tem=='sizeTematic'){
							if (labelNomCategoria.indexOf('('+map[estilRang.estil.simbolSize]+')')==-1){
								labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.simbolSize]+')';
							}
							
						}
						else{
							if (labelNomCategoria.indexOf('('+map[estilRang.estil.color]+')')==-1){
								labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.color]+')';
							}
							
						}
						
						html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
						html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
						if (layer.options.tem == tem_size){
							html +=	'<div class="col-md-2 legend-symbol" style="padding-left:'+padding_left+'">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name" style="padding-left:45px">'+
										'<input type="text" class="form-control my-border" value="'+labelNomCategoria+ '">'+
									'</div>';
						}
						else{
							html +=	'<div class="col-md-2 legend-symbol">'+
											stringStyle+
										'</div>'+
										'<div class="col-md-9 legend-name">'+
											'<input type="text" class="form-control my-border" value="'+labelNomCategoria+'">'+
										'</div>';
						}
						html+='</div>';	
						
					});

				}else if(geometrytype == t_polyline){
					var map={};
					jQuery.each(layer._layers, function(i, lay){
						var color = lay.options.color;
						if (color!=undefined){
							if (map[color]==undefined) map[color]=1;
							else {
								var i=map[color];
								map[color]=i+1;
							}
						}
					});
					jQuery.each(estils, function(i, estilRang){
						
						var color = hexToRgb(estilRang.estil.color);
						var lineWidth = estilRang.estil.lineWidth;
						var stringStyle =	'<svg height="20" width="20">'+
												'<line x1="0" y1="20" x2="20" y2="0" '+
													'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
											'</svg>';	
						
						var labelNomCategoria = "";
						checked = "";
						
						var index=-1;
						if (undefined!=mapLegend[layer.options.businessId]) {
							index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
						}
						if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
							labelNomCategoria = mapLegend[layer.options.businessId][index].name;
							if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
						}else{
							if(estilRang.valueMax == estilRang.valueMin){
								labelNomCategoria = estilRang.valueMax;
							}else{
								labelNomCategoria = estilRang.valueMin +" - "+ estilRang.valueMax;
							}
							
							if(labelNomCategoria == "Altres"){
								labelNomCategoria = window.lang.translate("Altres");
							}
						}						
						
						if (labelNomCategoria.indexOf("("+map[estilRang.estil.color]+")")==-1){
							labelNomCategoria = labelNomCategoria+ " ("+map[estilRang.estil.color]+")";
						}
						
						html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
						html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
						html +=	'<div class="col-md-2 legend-symbol">'+
											stringStyle+
										'</div>'+
										'<div class="col-md-9 legend-name">'+
											'<input type="text" class="form-control my-border" value="'+labelNomCategoria+'">'+
										'</div>';				
						html+='</div>';	
					});					
				}else if(geometrytype == t_polygon){
					var map={};
					jQuery.each(layer._layers, function(i, lay){
						if (lay.options!=undefined){
							if (lay.options.fillColor!=undefined) {
								var color = lay.options.fillColor;
								if (color!=undefined){
									if (map[color]==undefined) map[color]=1;
									else {
										var i=map[color];
										map[color]=i+1;
									}
								}
							}				
						}
						else {
							if (lay.getLayers()[0].options!=undefined){
								if (lay.getLayers()[0].options.fillColor!=undefined) {
									var color = lay.getLayers()[0].options.fillColor;
									if (color!=undefined){
										if (map[color]==undefined) map[color]=1;
										else {
											var i=map[color];
											map[color]=i+1;
										}
									}
								}				
							}
						}
					});
					jQuery.each(estils, function(i, estilRang){
				
						var color = "";
						if (estilRang.estil.color) color=hexToRgb(estilRang.estil.color);
						else color=hexToRgb(estilRang.estil.borderColor);
						var borderColor = hexToRgb(estilRang.estil.borderColor);
						var opacity = estilRang.estil.opacity/100;
						var borderWidth = estilRang.estil.borderWidth;		
						if (borderWidth==0) borderWidth=1;
						var stringStyle =	'<svg height="30" width="30">'+
												'<polygon points="5 5, 5 25, 25 25, 25 5" stroke-linejoin="round" '+
													'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
											'</svg>';						
						
						
						var labelNomCategoria = "";
						checked = "";
						
						var index=-1;
						if (undefined!=mapLegend[layer.options.businessId]) {
							index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
						}
						if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
							labelNomCategoria = mapLegend[layer.options.businessId][index].name;
							if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
						}else{
							if(estilRang.valueMax == estilRang.valueMin){
								labelNomCategoria = estilRang.valueMax;
							}else{
								labelNomCategoria = estilRang.valueMin +" - "+ estilRang.valueMax;
							}
							
							if(labelNomCategoria == "Altres"){
								labelNomCategoria = window.lang.translate("Altres");
							}
						}						
						if (labelNomCategoria.indexOf("("+map[estilRang.estil.color]+")")==-1){
							labelNomCategoria = labelNomCategoria+ " ("+map[estilRang.estil.color]+")";
						}
						html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
						html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
						html +=	'<div class="col-md-2 legend-symbol">'+
											stringStyle+
										'</div>'+
										'<div class="col-md-9 legend-name">'+
											'<input type="text" class="form-control my-border" value="'+labelNomCategoria+ '">'+
										'</div>';				
						html+='</div>';	
						
					});						
					
				}
			 
		 }else{
			 	var estil_do = layer.options.estil_do;
			 	if (layer.options.dinamic) estil_do = layer.options.style;
			
				if(geometrytype == t_marker){
					var mida = getMidaFromRadius(estil_do.radius);
					if (layer.options.tem == tem_size) mida = estil_do.simbolSize;
					size = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';			
					var color = hexToRgb(estil_do.fillColor);
					
					if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
						layerName=layerName+' ('+layer.getLayers().length+')';
					}
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
					html +=	'<div class="col-md-2 legend-symbol">'+
								'<div class="awesome-marker-web awesome-marker-icon-punt_r legend-symbol" '+
									'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+
									' '+size+'">'+
								'</div>'+
							'</div>'+
							'<div class="col-md-9 legend-name">'+
								'<input type="text" class="form-control my-border" value="'+layerName+'">'+
							'</div>';
					html+='</div>';
					
				}else if(geometrytype == t_polygon){
					var color = "";
					if (estil_do.fillColor) color=hexToRgb(estil_do.fillColor);
					else color=hexToRgb(estil_do.color);
					var borderColor = hexToRgb(estil_do.color);
					var opacity = estil_do.fillOpacity;
					var borderWidth = estil_do.weight;		
					if (borderWidth==0) borderWidth=1;
					var polStyle =	'<svg height="30" width="30">'+
											'<polygon points="5 5, 5 25, 25 25, 25 5" '+
												'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
										'</svg>';
					
					if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
						layerName=layerName+' ('+layer.getLayers().length+')';
					}
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';					
					html += '<div class="col-md-2 legend-symbol">'+
								polStyle+
							'</div>'+
							'<div class="col-md-9 legend-name">'+
								'<input type="text" class="form-control my-border" value="'+layerName+'">'+
							'</div>';					
					
					html+='</div>';			
					
				}else if(geometrytype == t_polyline){
					var color;
					if (layer.options.dinamic) color = hexToRgb(estil_do.color);
					else color = hexToRgb(estil_do.fillColor);
					var lineWidth = estil_do.weight;
					var lineStyle =	'<svg height="20" width="20">'+
											'<line  x1="0" y1="20" x2="20" y2="0" '+ 
												'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
										'</svg>';	
					
					if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
						layerName=layerName+' ('+layer.getLayers().length+')';
					}
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';	
					html += '<div class="col-md-2 legend-symbol">'+
								lineStyle +
							'</div>'+
							'<div class="col-md-9 legend-name">'+
								'<input type="text" class="form-control my-border" value="'+layerName+'">'+
							'</div>';					
					html+='</div>';				
				}			 
		 }
	//XARXES SOCIALS
	}else if(layer.options.tipus == t_xarxes_socials){
		html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
		html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
		if(layer.options.hashtag){
			html += '<div class="col-md-2 legend-symbol">'+
						'<div class="awesome-marker-web awesome-marker-icon-blue fa fa-twitter" style="width: 28px; height: 42px; font-size: 14px; background-color: transparent;"></div>'+
					'</div>'+
					'<div class="col-md-9 legend-name">'+
						'<input type="text" class="form-control my-border" value="'+layerName+'">'+
					'</div>';			
		}else if(layer.options.maxLoad){
			
			html += '<div class="col-md-2 legend-symbol">'+
						'<img src="http://mw2.google.com/mw-panoramio/photos/small/43954089.jpg" class="leaflet-marker-icon photo-panoramio leaflet-zoom-animated leaflet-clickable" style="" tabindex="0"/>'+
					'</div>'+
					'<div class="col-md-9 legend-name">'+
						'<input type="text" class="form-control my-border" value="'+layerName+'">'+
					'</div>';				
		}else{
			html += '<div class="col-md-2 legend-symbol">'+
						'<div class="awesome-marker-web awesome-marker-icon-gray fa fa-book" style="width: 28px; height: 42px; font-size: 14px; background-color: transparent;"></div>'+
					'</div>'+
					'<div class="col-md-9 legend-name">'+
						'<input type="text" class="form-control my-border" value="'+layerName+'">'+
					'</div>';				
		}
		html+='</div>';
	
	//VISUALITZACIO
	}else if(layer.options.tipus == t_visualitzacio){
		var rangs = getRangsFromLayerLegend(layer);
		var size = rangs.length;
		//Classic tematic
		if(layer.options.tipusRang && layer.options.tipusRang==tem_clasic){
			var geometryType = transformTipusGeometry(layer.options.geometryType);
			var i = 0;
			var controlColorCategoria = [];//per controlar que aquell color no esta afegit ja a la llegenda
			
			var estilsRangs = layer.options.estilsRangs;
			var rangsEstilsLegend = layer.options.rangsEstilsLegend;
			var arrRangsEstilsLegend = sortObject(rangsEstilsLegend);
			if(!layer.options.hasOwnProperty("trafficLightKey"))
				arrRangsEstilsLegend.sort(sortByValueMax);
			else
			{

				//Si és un semafòric no reordenem els valors de la llegenda, ja ens venen ben assignats i el sortByValueMax se'l carrega

			}
			if(geometryType == t_marker){
				
				jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
					var indexEstil = 0;
					while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
						indexEstil++;
					}
					var mida = getMidaFromRadius(layer.options.estil[indexEstil].simbolSize);
					if (layer.options.tem == tem_size) mida = layer.options.estil[indexEstil].simbolSize;
					var iconSize = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';						
					var color = hexToRgb(layer.options.estil[indexEstil].color);
					var stringStyle ='<div class="awesome-marker-web awesome-marker-icon-punt_r legend-symbol" '+
										'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+
										' '+iconSize+'">'+
									'</div>';
					
					var labelNomCategoria = "";
					checked = "";						
					
					var index=-1;
					if (undefined!=mapLegend[layer.options.businessId]) {
						index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
					}
					labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);					
					if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && 
						-1!=index && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
					html +=	'<div class="col-md-2 legend-symbol">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name">'+
										'<input type="text" class="form-control my-border" value="'+labelNomCategoria +'">'+
									'</div>';				
					html+='</div>';	
				});
			}else if(geometryType == t_polyline){
				
				jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
					var indexEstil = 0;
					while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
						indexEstil++;
					}
					
					var color = hexToRgb(layer.options.estil[indexEstil].color);
					var lineWidth = layer.options.estil[indexEstil].lineWidth;
					var stringStyle =	'<svg height="20" width="20">'+
											'<line x1="0" y1="20" x2="20" y2="0" '+
												'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
										'</svg>';	
					
					var labelNomCategoria = "";
					checked = "";						
					
					var index=-1;
					if (undefined!=mapLegend[layer.options.businessId]) {
						index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
					}
					
					labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
					if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && 
						-1!=index && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
					html +=	'<div class="col-md-2 legend-symbol">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name">'+
										'<input type="text" class="form-control my-border" value="'+labelNomCategoria+'">'+
									'</div>';				
					html+='</div>';	
				});				
				
			}else{
				
				jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
					var indexEstil = 0;
					while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
						indexEstil++;
					}
					var color = "";
					if (layer.options.estil[indexEstil].color) color=hexToRgb(layer.options.estil[indexEstil].color);
					else color = hexToRgb(layer.options.estil[indexEstil].borderColor);
					var borderColor = hexToRgb(layer.options.estil[indexEstil].borderColor);
					
					var opacity = layer.options.estil[indexEstil].opacity/100;
					var borderWidth = layer.options.estil[indexEstil].borderWidth;			
					if (borderWidth==0) borderWidth=1;
					var stringStyle =	'<svg height="30" width="30">'+
					
											'<polygon points="5 5, 5 25, 25 25, 25 5" stroke-linejoin="round" '+
												'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
										'</svg>';	
					
					var labelNomCategoria = "";
					checked = "";						
					
					var index=-1;
					if (undefined!=mapLegend[layer.options.businessId]) {
						index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
					}
					
					labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
					if(mapLegend!=undefined && mapLegend[layer.options.businessId]!=undefined && 
						-1!=index && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
					html +=	'<div class="col-md-2 legend-symbol">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name">'+
										'<input type="text" class="form-control my-border" value="'+labelNomCategoria+'">'+
									'</div>';				
					html+='</div>';	
				});					
				
			}

		}else if(layer.options.tipusRang && layer.options.tipusRang==tem_size){
			
			var geometryType = transformTipusGeometry(layer.options.geometryType);
			var i = 0;
			var controlColorCategoria = [];//per controlar que aquell color no esta afegit ja a la llegenda
			
			var estilsRangs = layer.options.estilsRangs;
			var rangsEstilsLegend = layer.options.rangsEstilsLegend;
			
			var arrRangsEstilsLegend = sortObject(rangsEstilsLegend);
			arrRangsEstilsLegend.sort(sortByValueMax);
			
			if(geometryType == t_marker){

				jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
					var indexEstil = 0;
					while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
						indexEstil++;
					}
					var mida = getMidaFromRadius(layer.options.estil[indexEstil].simbolSize);
					if (layer.options.tipusRang == tem_size) mida =layer.options.estil[indexEstil].simbolSize;
					var color = hexToRgb(layer.options.estil[indexEstil].color);
					if (mida>60) mida=60;
					var height=mida*2.8;
					var padding_left="0px";
					if (mida>0 && mida<=6) padding_left="28px";
					else if (mida>6 && mida<=14) padding_left="22px";
					else if (mida>14 && mida<=22) padding_left="16px";
					else if (mida>22 && mida<=34) padding_left="10px";
					else if (mida>34 && mida<=40) padding_left="5px";
					 
					
					
					var stringStyle =	'<svg height="'+height+'">'+
										'<circle cx="'+mida+'" cy="'+mida+'" r="'+mida+'" '+
											'style="stroke:white; fill:rgb('+color.r+', '+color.g+', '+color.b+');"></circle>'+
										'</svg>';
					
					var labelNomCategoria = "";
					checked = "";						
					
					var index=-1;
					if (undefined!=mapLegend[layer.options.businessId]) {
						index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
					}
					labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
					var map={};
					jQuery.each(layer._layers, function(i, lay){
							var radius=lay.options.radius;
							if (radius!=undefined){
								if (map[radius]==undefined) map[radius]=1;
								else {
									var i=map[radius];
									map[radius]=i+1;
								}
							}
					});
					if (map[layer.options.estil[indexEstil].simbolSize]!=undefined && labelNomCategoria.indexOf('('+map[layer.options.estil[indexEstil].simbolSize]+')')==-1){
						labelNomCategoria = labelNomCategoria +' ('+map[layer.options.estil[indexEstil].simbolSize]+')';
					}
					if(undefined!=mapLegend[layer.options.businessId] && mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
					
					html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
					html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';
					html +=	'<div class="col-md-2 legend-symbol" style="padding-left:'+padding_left+'">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name" style="padding-left:45px">'+
										'<input type="text" class="form-control my-border" value="'+labelNomCategoria+'">'+
									'</div>';				
					html+='</div>';	
				});
			}
		}
		else{
			
			//Si es simpleTematic, amb el primer element de rang ja tenim prou, no ens cal recorrer tots el rangs 
			//pq seran tots iguals
			if(layer.options.tipusRang && layer.options.tipusRang==tem_simple){
				if(size > 0) size = 1;//Control rangs no buit
			}
			
			var geometryType = transformTipusGeometry(layer.options.geometryType);
			if(geometryType == t_marker){
				for(var i=0;i<size;i++){
					//Si es un punt
					if(rangs[i].isCanvas || rangs[i].marker.indexOf("punt_r")!=-1){
						var iconSize="";
						if(rangs[i].iconSize){
							var mides = rangs[i].iconSize.split("#");
							iconSize = 'width: '+mides[0]+'px; height: '+mides[1]+'px;';
						}else{
							var mida = getMidaFromRadius(rangs[i].simbolSize);
							if (layer.options.tem == tem_size) mida = rangs[i].simbolSize;
							iconSize = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';
						}
						var color = hexToRgb(rangs[i].color);
						var icon = "";
						var colorIcon=""; 
						if(rangs[i].simbolColor){
							var auxColor = hexToRgb(rangs[i].simbolColor);
							colorIcon = 'color: rgb('+auxColor.r+', '+auxColor.g+', '+auxColor.b+');';
						} 
						
						if(rangs[i].simbol){
							icon = "fa fa-"+rangs[i].simbol;
						}
						var obj = {iconSize: iconSize, color: color, icon:icon, colorIcon: colorIcon};
						var existeix = checkPointStyle(obj);
						
						if(!existeix){
							controlLegendPoint.push(obj);
							
							var stringStyle =	'<div class="awesome-marker-web awesome-marker-icon-punt_r '+icon+' legend-symbol" '+
													'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+colorIcon+
													' '+iconSize+'">'+
												'</div>';

							//Reinicialitzem
							layerName = layer.options.nom;
							checked = "";						
							var index=-1;
							if (undefined!=mapLegend[layer.options.businessId]) {
								index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
							}
							if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
								layerName = mapLegend[layer.options.businessId][index].name;
								if(mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
							}		
							
							if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
								layerName=layerName+' ('+layer.getLayers().length+')';
							}
							
							html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
							html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';					
							html +=	'<div class="col-md-2 legend-symbol">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name">'+
										'<input type="text" class="form-control my-border" value="'+layerName+'">'+
									'</div></div>';								
						}
					}else{//Si es un pintxo
						var color = hexToRgb(rangs[i].simbolColor);
						
						var obj = {color: color, marker: rangs[i].marker, simbol: rangs[i].simbol};
						var existeix = checkMarkerStyle(obj);
						
						if(!existeix){
							controlLegendMarker.push(obj);
							
							var stringStyle =	'<div class="awesome-marker-web awesome-marker-icon-'+rangs[i].marker+
													' fa fa-'+rangs[i].simbol+'" style="width: 28px; height: 42px; font-size: 14px;'+ 
													'background-color: transparent; color: rgb('+color.r+', '+color.g+', '+color.b+');">'+
												'</div>';
	
							//Reinicialitzem
							layerName = layer.options.nom;
							checked = "";						
							var index=-1;
							if (undefined!=mapLegend[layer.options.businessId]) {
								index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
							}
							if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
								layerName = mapLegend[layer.options.businessId][index].name;
								if(mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
							}		
							
							if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
								layerName=layerName+' ('+layer.getLayers().length+')';
							}
							
							html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
							html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';						
							html += '<div class="col-md-2 legend-symbol">'+
										stringStyle+
									'</div>'+
									'<div class="col-md-9 legend-name">'+
										'<input type="text" class="form-control my-border" value="'+layerName+'">'+
									'</div></div>';							
						}
					}
				}				
			}else if(geometryType == t_polyline){
				
				for(var i=0;i<size;i++){
					
					var color = hexToRgb(rangs[i].color);
					var lineWidth = rangs[i].lineWidth;
	
					var obj = {color: color, lineWidth: lineWidth};
					var existeix = checkLineStyle(obj);
					
					if(!existeix){
						controlLegendLine.push(obj);
						
						var stringStyle =	'<svg height="20" width="20">'+
												'<line x1="0" y1="20" x2="20" y2="0" '+
													'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
											'</svg>';
						//Reinicialitzem
						layerName = layer.options.nom;
						checked = "";						
						var index=-1;
						if (undefined!=mapLegend[layer.options.businessId]) {
							index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
						}
						if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
							layerName = mapLegend[layer.options.businessId][index].name;
							if(mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
						}					
						if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
							layerName=layerName+' ('+layer.getLayers().length+')';
						}
						html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
						html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';	
						html += '<div class="col-md-2 legend-symbol">'+
											stringStyle +
								'</div>'+
								'<div class="col-md-9 legend-name">'+
									'<input type="text" class="form-control my-border" value="'+layerName+'">'+
								'</div>';					
						
						html+='</div>';						
					}
				}				
			}else if(geometryType == t_polygon){
				
				for(var i=0;i<size;i++){
				
					var color = "";
					if (rangs[i].color) color=hexToRgb(rangs[i].color);
					else color=hexToRgb(rangs[i].borderColor);
					var borderColor = hexToRgb(rangs[i].borderColor);
					var opacity = rangs[i].opacity/100;
					var borderWidth = rangs[i].borderWidth;
					if (borderWidth==0) borderWidth=1;
					var obj = {color: color, borderColor: borderColor, opacity:opacity, borderWidth:borderWidth};
					var existeix = checkPolStyle(obj);					
					
					if(!existeix){
						controlLegendPol.push(obj);					
					
						var stringStyle =	'<svg height="30" width="30">'+
												'<polygon points="5 5, 5 25, 25 25, 25 5" '+
													'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
											'</svg>';
						
						//Reinicialitzem
						layerName = layer.options.nom;
						checked = "";						
						var index=-1;
						if (undefined!=mapLegend[layer.options.businessId]) {
							index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
						}
						if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
							layerName = mapLegend[layer.options.businessId][index].name;
							if(mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
						}						
						if (layerName.indexOf('('+layer.getLayers().length+')')==-1){
							layerName=layerName+' ('+layer.getLayers().length+')';
						}
						html += '<div class="legend-subrow" data-businessid="'+layer.options.businessId+'">';
						html += '<input class="col-md-1 legend-chck" type="checkbox" '+checked+' >';					
						html += '<div class="col-md-2 legend-symbol">'+
										stringStyle+
								'</div>'+
								'<div class="col-md-9 legend-name">'+
									'<input type="text" class="form-control my-border" value="'+layerName+'">'+
								'</div>';					
						
						html+='</div>';
					}
					
				}
			}
		}		
	//TEMATIC
	}

	html+='</div>';
	if(undefined!=mapLegend[layer.options.businessId]){
		if (mapLegend[layer.options.businessId][0].order >= 0){
			layersHtml.order[mapLegend[layer.options.businessId][0].order] = html;
		}else{
			layersHtml.notorder.push(html);
		}
	}else{
		layersHtml.notorder.push(html);
	}
	
	
	return layersHtml;
}

function checkLineStyle(obj){
	var existeix = false;
	for(var i=0; i<controlLegendLine.length && !existeix;i++){
		var item = controlLegendLine[i];
		if(item.lineWidth == obj.lineWidth && 
				item.color.r == obj.color.r && 
				item.color.g == obj.color.g && 
				item.color.b == obj.color.b) existeix = true;
	}
	return existeix;
}

function checkPolStyle(obj){
	var existeix = false;
	for(var i=0; i<controlLegendPol.length && !existeix;i++){
		var item = controlLegendPol[i];
		if(item.opacity == obj.opacity && 
				item.borderWidth == obj.borderWidth &&
				item.borderColor.r == obj.borderColor.r && 
				item.borderColor.g == obj.borderColor.g && 
				item.borderColor.b == obj.borderColor.b	&&			
				item.color.r == obj.color.r && 
				item.color.g == obj.color.g && 
				item.color.b == obj.color.b) existeix = true;
	}
	return existeix;
}

function checkPointStyle(obj){
	var existeix = false;
	for(var i=0; i<controlLegendPoint.length && !existeix;i++){
		var item = controlLegendPoint[i];
		if(item.iconSize == obj.iconSize && 
				item.icon == obj.icon &&
				item.colorIcon.r == obj.colorIcon.r && 
				item.colorIcon.g == obj.colorIcon.g && 
				item.colorIcon.b == obj.colorIcon.b	&&			
				item.color.r == obj.color.r && 
				item.color.g == obj.color.g && 
				item.color.b == obj.color.b) existeix = true;
	}
	return existeix;
}

function checkMarkerStyle(obj){
	var existeix = false;
	for(var i=0; i<controlLegendMarker.length && !existeix;i++){
		var item = controlLegendMarker[i];
		if(item.marker == obj.marker && 
				item.simbol == obj.simbol &&
				item.color.r == obj.color.r && 
				item.color.g == obj.color.g && 
				item.color.b == obj.color.b) existeix = true;
	}
	return existeix;
}

function getRangsFromLayerLegend(layer){
	var styles = jQuery.map(layer.getLayers(), function(val, i){
		//Si la layer es multipoligon ha d'agafa l'estil de les seves layers de dins
		if(val.options.tipus && val.options.tipus.indexOf(t_multipolygon)!= -1){
			return {key: val.properties.businessId, style: val.getLayers()[0]};
		}else{
			return {key: val.properties.businessId, style: val};
		}
	});
	
	var tematic = layer.options;
	tematic.tipusRang = tematic.tipusRang ? tematic.tipusRang : tem_origen;
	tematic.businessid = tematic.businessId; 
	tematic.leafletid = layer._leaflet_id;
	tematic.geometrytype = tematic.geometryType;
	tematic.from = tematic.tipusRang;
	
	var rangs = getRangsFromStyles(tematic, styles);
    //rangs = JSON.stringify({rangs:rangs});	
	
    return rangs;
}

function findLabelCategoria(rang, rangsField){
	if(rang.valorMin){
		return rangsField +": "+rang.valorMin +" - "+ rang.valorMax;
	}else{
		return rang.valorMax;
	}
}

//This will sort your array
function sortByValorMax(a, b){
	var aName = a.valorMax.toLowerCase();
	var bName = b.valorMax.toLowerCase(); 
	return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
//	if (a.valorMax < b.valorMax) return -1;
//	if (a.valorMax > b.valorMax) return 1;
//	return 0;	
}



function sortObject(obj) {
    var arr = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            arr.push({
                'key': prop,
                'value': obj[prop]
            });
        }
    }
    return arr;
}

function updateMapLegendData(){
	mapLegend = {};
	$(".legend-subrow").each(function(index,element){
		var businessId = $(element).attr('data-businessId');
		var html=$(element).children(".legend-symbol").html();
		if(html.indexOf('GetLegendGraphic')!= -1){
			html=html.replace(/width:26px;/g,'');
			html=html.replace('png8','png');
		}
		var obj = {
			chck : $(element).children(".icheckbox_flat-blue").hasClass("checked"),
			symbol : html,
			name : $(element).children(".legend-name").children("input").val(),
			order: index
		};
		if(!mapLegend[businessId]){
			mapLegend[businessId] = [];
		}
		mapLegend[businessId].push(obj);
	});
	
	
}

function findStyleInLegend(legend,stringStyle){
	var index = -1;
	for(var i=0; i<legend.length;i++){
		if(legend[i].symbol.trim() == stringStyle.trim()){
			index = i;
			break;
		}		
	}
	return index;
}

function checkColorAdded(controlColorCategoria, color){
	var existeix = false;
	for(var i=0; i<controlColorCategoria.length && !existeix;i++){	
		if (controlColorCategoria[i].r == color.r &&
				controlColorCategoria[i].g == color.g &&
				controlColorCategoria[i].b == color.b) existeix = true;
	}
	return existeix;
}

function addHtmlModalLegend(){
	
	jQuery('#mapa_modals').append(
	'<!-- Modal Llegenda -->'+
	'		<div id="dialog_llegenda" class="modal fade">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content">'+
	'				<div class="modal-header">'+
	'					<button type="button" class="close" data-dismiss="modal"'+
	'						aria-hidden="true">&times;</button>'+
	'					<h4 lang="ca" class="modal-title">Llegenda</h4>'+
	'				</div>'+
	'				<div class="modal-body">'+
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<button lang="ca" type="button" class="btn btn-default"'+
	'						data-dismiss="modal">Cancel·lar</button>'+
	'					<button lang="ca" type="button" class="btn btn-primary">Preview</button>'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- Fi Modal Llegenda -->'		
	);
}

/*************** FI:LLEGENDA ********************/


/**** LLEGENDA TEMATICA MODE EDICIO ****/

function addLegendEdicio(){
	
	
	
	
	try{

			ctr_legend = L.control.legend({
				title: window.lang.translate('Llegenda'),
				tipusllegenda: "dinamica",  //"dinamica"
				llegendaOpt: true      //true
			});
			ctr_legend.addTo(map);
	
	}catch(Err){
		

	
		
	
	}	
	
	
	/*
	legend = L.control({position: 'bottomright'});
	legend.onAdd = function (map) {
	    var div = L.DomUtil.create('div', 'info legend visor-legend mCustomScrollbar');
	    div.id = "mapLegendEdicio";
	    return div;
	};
	ctr_legend = L.control({
		position : 'bottomright'
	});
	ctr_legend.onAdd = function(map) {
		this._div = L.DomUtil.create('div', 'div_barrabotons btn-group-vertical');
		var btllista = L.DomUtil.create('div', 'leaflet-bar btn btn-default btn-sm bt_legend');
		this._div.appendChild(btllista);
		btllista.innerHTML = '<span class="fa fa-list-alt greenfort"></span>';
		return this._div;
	};
	ctr_legend.addTo(map);	
	legend.addTo(map);
	$("#mapLegendEdicio").mCustomScrollbar();
	$(".bt_legend").hide();
	activaLlegenda(false);
	
*/	
}

function emptyMapLegendEdicio(layer,isOrigen){
	if($("#mapLegendEdicio").data("businessid") == layer.options.businessId ){
		$("#mapLegendEdicio").html("");
		activaLlegenda(false);
		$(".bt_legend").hide();
	}
	else if (isOrigen){
		$("#mapLegendEdicio").html("");
		activaLlegenda(false);
		$(".bt_legend").hide();
	}
}

function loadMapLegendEdicio(layer){
		
	//Eliminem de la lleganda tematització anterior
	$("#mapLegendEdicio").html("");
	$("#mapLegendEdicio").data("businessid",layer.options.businessId);
	
	var html="";
	if(layer.options.tipus == t_wms){
		html = '<div class="titol-legend col-md-12 col-xs-12">'+layer.options.nom+'</div><div class="titol-separate-legend-row"></div>';
	}
	else{
		html = '<div class="titol-legend col-md-12 col-xs-12">'+layer.options.nom+' ('+layer.getLayers().length+')</div><div class="titol-separate-legend-row"></div>';
			
	}
	var geometryType = transformTipusGeometry(layer.options.geometryType);
	var i = 0;
//	var controlColorCategoria = [];//per controlar que aquell color no esta afegit ja a la llegenda
	if(layer.options.tipus == t_wms){	
		var legend_layer = layer.getLegendGraphic();
		html += '<div class="visor-legend-row ">';
		
		if(!jQuery.isArray(legend_layer)){
			html += '<img src="'+layer.getLegendGraphic()+'" class="btn-paleta img-legend"/>';
		}else{
			jQuery.each(legend_layer, function(i, lay){
				html += '<img src="'+lay+'" class="btn-paleta img-legend"/>';
			});
		}
		html+='</div><div class="visor-separate-legend-row"></div>';
	}
	else{
	var estilsRangs = layer.options.estilsRangs;
	var rangsEstilsLegend = layer.options.rangsEstilsLegend;
//	rangsEstilsLegend.sort(sortByValorMax);
	
	var arrRangsEstilsLegend = sortObject(rangsEstilsLegend);
	arrRangsEstilsLegend.sort(sortByValueMax);
	
	var totalLayers=0;
	
	if(geometryType == t_marker){

		jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
			var indexEstil = 0;
			while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
				indexEstil++;
				
			}
			totalLayers = totalLayers+layer.options.estil[indexEstil].geometria.features.length;
			//console.debug(layer.options.estil[indexEstil].geometria.features.length);
			var mida = getMidaFromRadius(layer.options.estil[indexEstil].simbolSize);
			if (layer.options.tipusRang == tem_size) mida = layer.options.estil[indexEstil].simbolSize;
			var iconSize = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';						
			var color = hexToRgb(layer.options.estil[indexEstil].color);
			if(mida>=60) mida=60;
			var height=mida*2.8;
			var padding_left="0px";
			if (mida>0 && mida<=6) padding_left="15px";
			else if (mida>6 && mida<=14) padding_left="10px";
			else if (mida>14 && mida<=22) padding_left="5px";
			
			
			
			var stringStyle =	'<svg height="'+height+'">'+
								'<circle cx="'+mida+'" cy="'+mida+'" r="'+mida+'" '+
									'style="stroke:white; fill:rgb('+color.r+', '+color.g+', '+color.b+');"></circle>'+
								'</svg>';
			if (layer.options.tipusRang!=tem_size){
				stringStyle ='<div class="awesome-marker-web awesome-marker-icon-punt_r legend-symbol" '+
								'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+
								' '+iconSize+'">'+
							'</div>';
			}
			
			var labelNomCategoria = "";
//			checked = "";						
			var index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
			labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
			
			html += '<div class="visor-legend-row ">';
			if (layer.options.tipusRang == tem_size){
				html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4" style="padding-left:'+padding_left+'">'+
						stringStyle+
						'</div>'+
						'<div class="visor-legend-name col-md-8 col-xs-8" style="float:right;width:40%">'+labelNomCategoria+'</div>';	
			}
			else{
						html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';				
			}
			html+='</div><div class="visor-separate-legend-row"></div>';	
		});
	}else if(geometryType == t_polyline){
		
		jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
			var indexEstil = 0;
			while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
				indexEstil++;
			}
			totalLayers = totalLayers+layer.options.estil[indexEstil].geometria.features.length;
			var color = hexToRgb(layer.options.estil[indexEstil].color);
			var lineWidth = layer.options.estil[indexEstil].lineWidth;
			var stringStyle =	'<svg height="20" width="20">'+
									'<line x1="0" y1="20" x2="20" y2="0" '+
										'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
								'</svg>';	
			
			var labelNomCategoria = "";
			checked = "";						
			
			var index=-1;
			if (undefined!=mapLegend[layer.options.businessId]) {
				index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
			}
			labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
			
			html += '<div class="visor-legend-row ">';
			html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';				
//			
			html+='</div><div class="visor-separate-legend-row"></div>';
		});				
		
	}else{
		
		jQuery.each(arrRangsEstilsLegend, function(i, estilRang){
			var indexEstil = 0;
			while(indexEstil<layer.options.estil.length && estilRang.key!=layer.options.estil[indexEstil].businessId){
				indexEstil++;
			}
			totalLayers = totalLayers+layer.options.estil[indexEstil].geometria.features.length;
			var color = "";
			if (layer.options.estil[indexEstil].color) color=hexToRgb(layer.options.estil[indexEstil].color);
			else color=hexToRgb(layer.options.estil[indexEstil].borderColor);
			var borderColor = hexToRgb(layer.options.estil[indexEstil].borderColor);
			var opacity = layer.options.estil[indexEstil].opacity/100;
			var borderWidth = layer.options.estil[indexEstil].borderWidth;		
			if (borderWidth==0) borderWidth=1;
			var stringStyle =	'<svg height="30" width="30">'+
									'<polygon points="5 5, 5 25, 25 25, 25 5" stroke-linejoin="round" '+
										'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
								'</svg>';	
			
			var labelNomCategoria = "";
			checked = "";						
			
			var index=-1;
			if (undefined!=mapLegend[layer.options.businessId]) {
				index = mapLegend[layer.options.businessId]?findStyleInLegend(mapLegend[layer.options.businessId],stringStyle):-1;
			}
			labelNomCategoria = getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil);	
			
			html += '<div class="visor-legend-row ">';
			html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';				
//			
			html+='</div><div class="visor-separate-legend-row"></div>';
		});					
		
	}	}
	html= html.replace("totalLayers",totalLayers);
	$("#mapLegendEdicio").html(html);
	//Afegim de nou les classes i l'scroll
	$("#mapLegendEdicio").addClass("info");
	$("#mapLegendEdicio").addClass("legend");
	$("#mapLegendEdicio").addClass("visor-legend");
	$("#mapLegendEdicio").addClass("mCustomScrollbar");
	$("#mapLegendEdicio").mCustomScrollbar();
	
	$(".bt_legend").show();
	activaLlegenda(true);
	
}


function loadMapLegendEdicioDinamics(layer){
	
	//Eliminem de la lleganda tematització anterior
	$("#mapLegendEdicio").html("");
	$("#mapLegendEdicio").data("businessid",layer.options.businessId);
	
	var html = '<div class="titol-legend col-md-12 col-xs-12">'+layer.options.nom+' ('+layer.getLayers().length+')</div><div class="titol-separate-legend-row"></div>';
	
	var geometryType = transformTipusGeometry(layer.options.geometryType);

	var rangsEstilsLegend = layer.options.estil_do.estils;
	
		if(geometryType == t_marker){
			var map={};
			jQuery.each(layer._layers, function(i, lay){
				if (layer.options.tem=='sizeTematic'){
					var radius=lay.options.radius;
					if (radius!=undefined){
						if (map[radius]==undefined) map[radius]=1;
						else {
							var i=map[radius];
							map[radius]=i+1;
						}
					}
				}
				else{
					var color = lay.options.fillColor;
					if (color!=undefined){
						if (map[color]==undefined) map[color]=1;
						else {
							var i=map[color];
							map[color]=i+1;
						}
					}
				}
			});
		jQuery.each(rangsEstilsLegend, function(i, estilRang){
			var mida = getMidaFromRadius(estilRang.estil.simbolSize);
			if (layer.options.tem == tem_size) mida = estilRang.estil.simbolSize;
			var padding_left="0px";
			if (mida>0 && mida<=6) padding_left="15px";
			else if (mida>6 && mida<=14) padding_left="10px";
			else if (mida>14 && mida<=22) padding_left="5px";
			var color = hexToRgb(estilRang.estil.color);
			var height=mida*2.8;
			var iconSize = 'width: '+mida+'px; height: '+mida+'px; font-size: 8px;';						
			
			var stringStyle =	'<svg height="'+height+'">'+
								'<circle cx="'+mida+'" cy="'+mida+'" r="'+mida+'" '+
									'style="stroke:white; fill:rgb('+color.r+', '+color.g+', '+color.b+');"></circle>'+
								'</svg>';	

			if (layer.options.tem != tem_size) {
				stringStyle ='<div class="awesome-marker-web awesome-marker-icon-punt_r legend-symbol" '+
				'style="background-color: rgb('+color.r+', '+color.g+', '+color.b+'); '+
				' '+iconSize+'">'+
				'</div>';
			}	
			var labelNomCategoria = "";
//			checked = "";						
			
			if (estilRang.valueMax == estilRang.valueMin){
				labelNomCategoria = estilRang.valueMax;
			}
			else {
				labelNomCategoria = estilRang.valueMin+"-"+ estilRang.valueMax;
			}
			
			if (layer.options.tem=='sizeTematic'){
				if (labelNomCategoria.indexOf('('+map[estilRang.estil.simbolSize]+')')==-1){
					labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.simbolSize]+')';
				}
			}
			else{
				if (labelNomCategoria.indexOf('('+map[estilRang.estil.color]+')')==-1){
					labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.color]+')';
				}
			}
			
			html += '<div class="visor-legend-row ">';
			if (layer.options.tem == tem_size) {
				html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4" style="margin-top:4px;padding-left:'+padding_left+'">'+
						stringStyle+
						'</div>'+
						'<div class="visor-legend-name col-md-8 col-xs-8" style="padding-left:50px;">'+labelNomCategoria+'</div>';	
					}
			else {
				html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';
			}
//			
			html+='</div><div class="visor-separate-legend-row"></div>';	
			
		});
	}else if(geometryType == t_polyline){
		var map={};
		jQuery.each(layer._layers, function(i, lay){
			var color = lay.options.color;
			if (color!=undefined){
				if (map[color]==undefined) map[color]=1;
				else {
					var i=map[color];
					map[color]=i+1;
				}
			}
		});
		jQuery.each(rangsEstilsLegend, function(i, estilRang){
		
			
			var color = hexToRgb(estilRang.estil.color);
			var lineWidth = estilRang.estil.lineWidth;
			var stringStyle =	'<svg height="20" width="20">'+
									'<line x1="0" y1="20" x2="20" y2="0" '+
										'style="stroke:rgb('+color.r+', '+color.g+', '+color.b+'); stroke-width:'+lineWidth+';"></line>'+
								'</svg>';	
			
			var labelNomCategoria = "";
								
			if (estilRang.valueMax == estilRang.valueMin){
				labelNomCategoria = estilRang.valueMax;
			}
			else {
				labelNomCategoria = estilRang.valueMin+"-"+ estilRang.valueMax;
			}	
			
			if (labelNomCategoria.indexOf('('+map[estilRang.estil.color]+')')==-1){
				labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.color]+')';
			}
			
			html += '<div class="visor-legend-row ">';
			html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';			
//			
			html+='</div><div class="visor-separate-legend-row"></div>';
		});				
		
	}else{
		var map={};
		jQuery.each(layer._layers, function(i, lay){
			if (lay.options!=undefined){
				if (lay.options.fillColor!=undefined) {
					var color = lay.options.fillColor;
					if (color!=undefined){
						if (map[color]==undefined) map[color]=1;
						else {
							var i=map[color];
							map[color]=i+1;
						}
					}
				}				
			}
			else {
				if (lay.getLayers()[0].options!=undefined){
					if (lay.getLayers()[0].options.fillColor!=undefined) {
						var color = lay.getLayers()[0].options.fillColor;
						if (color!=undefined){
							if (map[color]==undefined) map[color]=1;
							else {
								var i=map[color];
								map[color]=i+1;
							}
						}
					}				
				}
			}
		});
		jQuery.each(rangsEstilsLegend, function(i, estilRang){
			
			
			var color = "";
			if (estilRang.estil.color) color=hexToRgb(estilRang.estil.color);
			else color=hexToRgb(estilRang.estil.borderColor);
			var borderColor = hexToRgb(estilRang.estil.borderColor);
			var opacity = estilRang.estil.opacity/100;
			var borderWidth = estilRang.estil.borderWidth;
			if (borderWidth==0) borderWidth=1;
			var stringStyle =	'<svg height="30" width="30">'+
									'<polygon points="5 5, 5 25, 25 25, 25 5" stroke-linejoin="round" '+
										'style=" fill:rgb('+color.r+', '+color.g+', '+color.b+'); stroke:rgb('+borderColor.r+', '+borderColor.g+', '+borderColor.b+'); stroke-width:'+borderWidth+'; fill-rule:evenodd; fill-opacity:'+opacity+';"></polygon>'+
								'</svg>';	
			
			var labelNomCategoria = "";
			
			if (estilRang.valueMax == estilRang.valueMin){
				labelNomCategoria = estilRang.valueMax;
			}
			else {
				labelNomCategoria = estilRang.valueMin+"-"+ estilRang.valueMax;
			}	
			
			if (labelNomCategoria.indexOf('('+map[estilRang.estil.color]+')')==-1){
				labelNomCategoria = labelNomCategoria+' ('+map[estilRang.estil.color]+')';
			}
			
			html += '<div class="visor-legend-row ">';
			html +=	'<div class="visor-legend-symbol col-md-4 col-xs-4">'+
								stringStyle+
							'</div>'+
							'<div class="visor-legend-name col-md-8 col-xs-8">'+labelNomCategoria+'</div>';
//			
			html+='</div><div class="visor-separate-legend-row"></div>';
		});					
		
	}	
	
	$("#mapLegendEdicio").html(html);
	//Afegim de nou les classes i l'scroll
	$("#mapLegendEdicio").addClass("info");
	$("#mapLegendEdicio").addClass("legend");
	$("#mapLegendEdicio").addClass("visor-legend");
	$("#mapLegendEdicio").addClass("mCustomScrollbar");
	$("#mapLegendEdicio").mCustomScrollbar();
	
	$(".bt_legend").show();
	activaLlegenda(true);
	
}

function getLabelNomCategoria(layer,rangsEstilsLegend,index,indexEstil){
	var labelNomCategoria="";
	if(index != -1){//Si l'ha trobat, fica el seu check i el seu name
		labelNomCategoria = mapLegend[layer.options.businessId][index].name;
		if (labelNomCategoria.indexOf(rangsEstilsLegend[""+layer.options.estil[indexEstil].businessId+""])==-1) {
			labelNomCategoria=rangsEstilsLegend[""+layer.options.estil[indexEstil].businessId+""];
		}
		if(mapLegend[layer.options.businessId][index].chck == true) checked = 'checked="checked"';
	}else{
		labelNomCategoria = rangsEstilsLegend[""+layer.options.estil[indexEstil].businessId+""];
		
		if(labelNomCategoria == "Altres"){
			labelNomCategoria = window.lang.translate("Altres");
		}
	}						
	
	if (labelNomCategoria.indexOf('('+layer.options.estil[indexEstil].geometria.features.length+')')==-1){
		labelNomCategoria = labelNomCategoria +' ('+layer.options.estil[indexEstil].geometria.features.length+')';
	}
	return labelNomCategoria;
	
}

/**** fi/LLEGENDA TEMATICA MODE EDICIO ****/


function activaLlegenda(obre) {
	var dfd = $.Deferred();
	var cl = jQuery('.bt_legend span').attr('class');
	var funcioObrir = (obre!=undefined ? obre : cl.indexOf('grisfort') != -1);
	if (funcioObrir) {
		jQuery('.bt_legend span').removeClass('grisfort');
		jQuery('.bt_legend span').addClass('greenfort');
		$(".bt_legend").transition({ x: '0px', y: '0px',easing: 'in', duration: 500 });
		$(".visor-legend").transition({ x: '0px', y: '0px',easing: 'in', opacity: 1,duration: 500 });
	} else {
		jQuery('.bt_legend span').removeClass('greenfort');
		jQuery('.bt_legend span').addClass('grisfort');
		var height = $(".visor-legend").height();
		var y1 = $(".visor-legend").height() - 20;
		var y2 = $(".visor-legend").height() +50;
		$(".bt_legend").transition({ x: '225px', y: y1+'px',duration: 500 });
		$(".visor-legend").transition({ x: '250px', y: y2+'px',  opacity: 0.1,duration: 500 });		
	}	
	dfd.resolve();
	return dfd.promise();
}<file_sep>/geocatweb/js/geocat.visor.fons.js
/**
 * TODO Cambiar a la carpeta de leaflet
 */
L.IM_ControlFons = L.Control.extend({
	options: {
		collapsed: true,
        position: 'bottomleft',
        title: 'Escollir el mapa de fons',
        langTitle: 'Escollir el mapa de fons',
        tooltip: 'right'
    },
    
    onAdd: function (map) {
    	this._initLayout();
    	
    	this._div = this._container;
    	
    	return this._container;
    },
    
    _initLayout: function(){
    	var self = this,
		options = self.options,
		className = 'control-btn-fons',
	    container = this._container = L.DomUtil.create('div', className);
    	
    	// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
		container.setAttribute('aria-haspopup', true);
		
		container.title = options.title;
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;

        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var version = 11;
        if (msie > 0) version = parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
		
        if (!L.Browser.touch) {
			L.DomEvent
				.disableClickPropagation(container)
				.disableScrollPropagation(container);
		} else {
			L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
		}
    	
	
		if (this.options.collapsed){
			//#499: Amb IE10 no es carreguen els visors
			if (msie==0){
				if (!L.Browser.android) {
						L.DomEvent.on(container, {
							mouseenter: this._expand,
							mouseleave: this._collapse
						}, this);
					}
			}
			
    		
    		
    		L.DomEvent.on(container, 'click', this._expand, this);
    		
    		this._map.on('click', this._collapse, this);
    	}else{
    		this._expand();
    	}
    	    	
    	var btllista = L.DomUtil.create('div','leaflet-bar btn btn-default btn-sm');
    	
    	if (this._map.getActiveMap() == "ortoMap"){
    		L.DomUtil.addClass(btllista, 'bt_topo');
    	}else{
    		L.DomUtil.addClass(btllista, 'bt_orto');
    	}
    	
		container.appendChild(btllista);
		this._btllista = btllista;
		btllista.innerHTML = '<small id="sm_tipus" lang="ca">Fons</small>';
				
		var llistaFons = L.DomUtil.create('div','leaflet-bar btn btn-default llista-fons');
		
		this._addLayers(llistaFons);
	
		container.appendChild(llistaFons);
						
		return container;
    },
    
    hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
    
    _update: function(){
    	
    },
    
    _expand: function(){
    	L.DomUtil.addClass(this._container, 'control-btn-fons-expanded');	
    },
    
    _collapse: function(){
    	L.DomUtil.removeClass(this._container, 'control-btn-fons-expanded');
    },
    
    _addLayers: function(container){
		

		
    	 this._addItem(container,{id:'topoMap',className:'div_fons_1',title:'Topogràfic'});
    	 this._addItem(container,{id:'topoMapGeo',className:'div_fons_12',title:'Simple'});
    	 this._addItem(container,{id:'hibridMap',className:'div_fons_13',title:'Mapa híbrid'});
    	 this._addItem(container,{id:'ortoMap',className:'div_fons_3',title:'Imatge'});    	
    	 this._addItem(container,{id:'terrainMap',className:'div_fons_4',title:'Terreny'});
    	 this._addItem(container,{id:'alcadaMap',className:'div_fons_15',title:'Model d\'elevacions'});
    	 this._addItem(container,{id:'historicOrtoMap',className:'div_fons_11',title:'Ortofoto històrica Catalunya 1956-57'});
    	 this._addItem(container,{id:'historicOrtoMap46',className:'div_fons_14',title:'Ortofoto històrica Catalunya 1946'});
    	 this._addItem(container,{id:'historicMap',className:'div_fons_10',title:'Mapa històric Catalunya 1936'});     	
    	 this._addItem(container,{id:'topoGrisMap',className:'div_fons_2',title:'Topogràfic gris'});
    	 this._addItem(container,{id:'nit',className:'div_fons_6',title:'Nit'});
    	 this._addItem(container,{id:'sepia',className:'div_fons_7',title:'Sèpia'});
    	 this._addItem(container,{id:'zombie',className:'div_fons_8',title:'Coure'});
    	 this._addItem(container,{id:'orquidea',className:'div_fons_9',title:'BluePrint'});
    	 this._addItem(container,{id:'naturalMap',className:'div_fons_16',title:'Natural'});
    	 this._addItem(container,{id:'divadminMap',className:'div_fons_17',title:'Divisions administratives'});		 
		 this._addItem(container,{id:'hibridTerrainMap',className:'div_fons_18',title:'Terreny híbrid'});		
		 this._addItem(container,{id:'colorBlankMapwhite',className:'div_fons_blank',title:'Fons neutre blanc'});
		 this._addItem(container,{id:'colorBlankMaplightgray',className:'div_fons_gris',title:'Fons neutre gris'} );
		 this._addItem(container,{id:'colorBlankMapgray',className:'div_fons_gris_fort',title:'Fons neutre gris fort'});
		 
		 
    },
    
    _addItem: function(container, properties){
		
	
    	var item = document.createElement('div');
    	item.id = properties.id;
    	item.className = properties.className;
    	item.setAttribute("data-toggle","tooltip");
    	item.setAttribute("data-lang-title",properties.title);
    	item.title = properties.title;
    	
    	L.DomEvent.on(item, 'click', L.DomEvent.stopPropagation);
    	L.DomEvent.on(item, 'click', this._onItemClick, this);
    	container.appendChild(item);
    	$(item).tooltip({placement : 'bottom',container : 'body'});
    },
    
    _onItemClick: function(evt){
    	var that = this;
    	var _this = evt.target;
    	var fons = $(_this).attr('id');
		
		
		_gaq.push(['_trackEvent', 'visor', tipus_user+'fons', fons, 1]);
		if (fons == 'topoMap'){
			this._map.topoMap();
		}else if (fons == 'topoMapGeo') {
			this._map.topoMapGeo();
		}else if (fons == 'ortoMap') {
			this._map.ortoMap();
		}else if (fons == 'terrainMap') {
			this._map.terrainMap();
		}else if (fons == 'topoGrisMap') {
			this._map.topoGrisMap();
		}else if (fons == 'historicOrtoMap') {
			this._map.historicOrtoMap();
		}else if (fons == 'historicMap') {
			this._map.historicMap();
		}else if (fons == 'hibridMap'){
			this._map.hibridMap();
		}else if (fons == 'historicOrtoMap46'){
			this._map.historicOrtoMap46();
		}else if (fons == 'alcadaMap'){
			this._map.alcadaMap();
			
		}else if (fons == 'naturalMap') {
			this._map.naturalMap();
			
		}else if (fons == 'divadminMap') {
			this._map.divadminMap();
		

		}else if (fons == 'hibridTerrainMap') {
			this._map.hibridTerrainMap();	
			
		}else if (fons.indexOf('colorBlankMap')!=-1) {
						
				
			this._map.colorBlankMap(fons);
			
		}else{
			this._map.colorMap(fons);			
		}
		if (fons == 'ortoMap'){
			L.DomUtil.removeClass(this._btllista, 'bt_orto');
			L.DomUtil.addClass(this._btllista, 'bt_topo');
		}else{
			L.DomUtil.removeClass(this._btllista, 'bt_topo');
			L.DomUtil.addClass(this._btllista, 'bt_orto');
		}
		this._collapse();
    }
});

L.IM_controlFons = function (options) {
    return new L.IM_ControlFons(options);
};

/*
//Control mapa orto/topo
	var ctr_llistaCapes = L.control({
        position : 'bottomright'
	});
	ctr_llistaCapes.onAdd = function (map) {

		
	};
	ctr_llistaCapes.addTo(map);
	
	jQuery('.div_barrabotons').on('click', function () {
		if (jQuery('div', this).hasClass('bt_orto')) {
	        map.ortoMap();
	        canvasTiles.bringToFront();
	        jQuery('#sm_tipus').text('Mapa');
	        jQuery('div', this).addClass('bt_topo');
	        jQuery('div', this).removeClass('bt_orto');
		}else{
	        map.topoMapGeo();
	        canvasTiles.bringToFront();
	        jQuery('#sm_tipus').text('Ortofoto');
	        jQuery('div', this).addClass('bt_orto');
	        jQuery('div', this).removeClass('bt_topo');
		}
	});
	
*/	<file_sep>/geocatweb/js/leaflet/L.IM_MinimapControl.js
/**
 * L.Control.Minimapa igual que el L.Control.MiniMap
 * 
 * require L.Control.MiniMap
 */
L.Control.Minimapa = L.Control.MiniMap.extend({
	onAdd: function(map) {
		var self = this;
		var container = L.Control.MiniMap.prototype.onAdd.call(self, map);
		self._div = container;
		return container;
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	}
});

L.control.minimapa = function(layer, options){
	return new L.Control.Minimapa(layer, options);
};
<file_sep>/geocatweb/js/instamaps.geolocal.widgets.rpuc.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetRPUC = {
					
		init: function() {
			this.url = "http://ptop.gencat.cat/rpucportal/AppJava/cercaExpedient.do?reqCode=cerca&municipiSel=widget_id_municipi";;
        	this.containerId = '.drawWidgets';
			this.cache();
        	this.subscriptions();
        	this.bindEvents();
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	this.container = $(this.containerId);
        },
        
        getWidget: function(){
        	return this;
        },
                
        drawButton: function(container){
        	var that = this;
        	$('<div/>').addClass('widget-button').addClass('widget-rpuc')
        	.on('click',function(){
        		$.publish('widgetActivated',{'target':this,'widget':that});
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_Rpuc']});
        	})
        	.appendTo(container);
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	$(this.containerId).empty();
        },
        
        draw: function(data){	
		
	
        	var that = this;
        	if(that.active  && data.tipusMunicipi){
				
			
				
        		$(that.containerId).empty();
        		var codi = data.municipiCodi.substring(0,5);
        		var url = that.url.replace("widget_id_municipi", codi);
    			this.windowObjectReference = window.open(url,"PromoteFirefoxWindowName", "resizable=yes,scrollbars=yes,status=yes");  
    			this.windowObjectReference.focus();
    			
    			$('<p></p>').addClass('text').html('Municipi de <b>' + data.municipi + '</b>').appendTo($(that.containerId));
    			$('<div></div>').addClass('list').append(
	    			$('<a></a>', {
						'href' : url,
						'target' : '_blank'
					}).html(data.municipi + " al registre de planejament urbanístic de Catalunya")).append(
					$('<span></span>',{'class':'glyphicon glyphicon-new-window'})).appendTo($(that.containerId));
        	}
        },
                
        /**********Events**************/
        bindEvents: function(){
        },
        
        subscriptions: function() {
        	var that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
        		if(data){
        			that.draw(data);
        		}
        	});
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetRPUC.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetRPUC = WidgetRPUC.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/leaflet/L.IM_MapExportControl.js
/**
 * 
 */
L.Control.MapExport = L.Control
		.extend({
			options : {
				position : 'topright',
				id : 'dv_bt_mapExport',
				className : 'leaflet-bar btn btn-default btn-sm bt_exportfile grisfort',
				title : 'Exportar i imprimir mapa',
				langTitle : 'Exportar i imprimir mapa',
				html : '<span class="glyphicon glyphicon-paste"></span>',
				tooltip : 'bottom'
			},

			onAdd : function(map) {
				var self = this, options = self.options, stop = L.DomEvent.stopPropagation, container = L.DomUtil
						.create('div', options.className);

				container.id = options.id;
				container.innerHTML = options.html;
				container.title = options.title;

				container.dataset.toggle = 'tooltip';
				container.dataset.placement = window.lang.translate(options.tooltip);
				container.dataset.langTitle = window.lang.translate(options.langTitle);

				self._div = container;

				var _scope = 'visor';
				var tipus_user = "";
				getModeMapa() ? _scope = 'mapa' : _scope = 'visor';

				if (_scope == 'mapa') {
					tipus_user = defineTipusUser();
				}

				this._div_H_Export = L.DomUtil.create('div',
						'div_barraexport div_gr40');

				var btcamera = jQuery(
						"<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_captura\" title=\"Capturar la vista del mapa\" data-lang-title=\"Capturar la vista del mapa\"><span class='glyphicon glyphicon-camera grisfort'></span></div>")
						.on(
								'click',
								function(event) {
									aturaClick(event);
									_gaq.push([ '_trackEvent', _scope,
											tipus_user + 'captura pantalla',
											'label captura', 1 ]);
									capturaPantalla(CAPTURA_MAPA);
									self.hide()
								});

				this._div_H_Export.appendChild(btcamera[0]);

				var btprint = jQuery(
						"<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_print\" title=\"Imprimir la vista del mapa\" data-lang-title=\"Imprimir la vista del mapa\"><span class='glyphicon glyphicon-print grisfort'></span></div>")
						.on(
								'click',
								function(event) {

									aturaClick(event);
									_gaq.push([ '_trackEvent', _scope,
											tipus_user + 'print',
											'label print', 1 ]);
									capturaPantalla(CAPTURA_INFORME);
									self.hide();
								});
				this._div_H_Export.appendChild(btprint[0]);

				var btgeopdf = jQuery(
						"<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_geopdf\" title=\"Descarrega mapa en format GeoPDF\" data-lang-title=\"Descarrega mapa en format GeoPDF\"><span class='fa fa-file-pdf-o geopdf'></span></div>")
						.on(
								'click',
								function(event) {

									aturaClick(event);
									_gaq.push([ '_trackEvent', _scope,
											tipus_user + 'geopdf',
											'label geopdf', 1 ]);
									capturaPantalla(CAPTURA_GEOPDF);
									self.hide();
								});
				this._div_H_Export.appendChild(btgeopdf[0]);

				var btgeotiff = jQuery(
						"<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_geotiff\" title=\"Descarrega mapa en format GeoTiff\" data-lang-title=\"Descarrega mapa en format GeoTiff\"><span class='fa fa-file-image-o grisfort'></span></div>")
						.on(
								'click',
								function(event) {
									aturaClick(event);

									_gaq.push([ '_trackEvent', _scope,
											tipus_user + 'geotiff',
											'label geotiff', 1 ]);

									capturaPantalla(CAPTURA_MAPA_GEOTIFF);
									self.hide();

								});
				this._div_H_Export.appendChild(btgeotiff[0]);

				var btgeopkg = jQuery(
						"<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_geopkg\" title=\"Descarrega vectors en format GeoPackage\" data-lang-title=\"Descarrega vectors en format GeoPackage\"><span class='fa fa-database grisfort'></span></div>")
						.on('click',
								function(event) {
									
									aturaClick(event);
									_gaq.push([ '_trackEvent', _scope,
											tipus_user + 'geopkg',
											'label geopkg', 1 ]);
									
									
									capturaPantalla(CAPTURA_MAPA_GEOPACKAGE);
									self.hide()
								});

				this._div_H_Export.appendChild(btgeopkg[0]);

				jQuery('body').append(this._div_H_Export);

				L.DomEvent.on(container, 'click', stop).on(container,
						'mousedown', stop).on(container, 'dblclick', stop).on(
						container, 'click', L.DomEvent.preventDefault).on(
						container, 'click', self._toggle, self);

				return container;
			},

			hideBtn : function() {
				var self = this;
				$(self._div).hide();
			},

			showBtn : function() {
				var self = this;
				$(self._div).show();
			},

			hide : function() {
				L.DomUtil.removeClass(this._div, 'greenfort');
				L.DomUtil.addClass(this._div, 'grisfort');
				$('.div_barraexport').hide();
			},

			show : function(e) {

				L.DomUtil.removeClass(this._div, 'grisfort');
				L.DomUtil.addClass(this._div, 'greenfort');
				var leftO = ($(this._div_H_Export).width() + parseInt(10));
				var offset = $(this._div).offset();
				$('.div_barraexport').css('top', (offset.top - 10) + 'px');
				$('.div_barraexport').css('left', (offset.left - leftO) + 'px');
				$('.div_barraexport').show();
				jQuery('.leaflet-control-layers').hide();
			},

			_toggle : function(e) {
				var collapsed = L.DomUtil.hasClass(this._div, 'grisfort');
				this[collapsed ? 'show' : 'hide']();
			},

		});

L.control.mapExport = function(options) {
	return new L.Control.MapExport(options);
};<file_sep>/geocatweb/js/geocat.mapa.dades-obertes.js
/**
 * Gestió de la creació i carrega de capes de Dades obertes
 */

var _htmlDadesObertes = [];
function generaLListaDadesObertes() {
	getLListaDadesObertes().then(function(results) {
		_htmlDadesObertes.push('<div class="panel-danger"><ul class="bs-dadesO llista-do panel-heading">');
		$.each(results.dadesObertes, function(key, dataset) {
			_htmlDadesObertes.push('<li><a class="label-explora" lang="ca" title="Afegir capa" href="#" id="'
				+ dataset.dataset
				+ '">'
				+ dataset.text
				+ '</a>'
				+ '<a target="_blank" lang="ca" title="Informació de les dades" href="'+dataset.urn+'"><span class="glyphicon glyphicon-info-sign info-explora"></span></a>'							
				+'</li>');
		});
		_htmlDadesObertes.push('</ul><div id="div_do_message"></div></div>');
	});
}

function addCapaDadesObertes(dataset,nom_dataset) {

	_gaq.push(['_trackEvent', 'mapa', tipus_user+'dades obertes', nom_dataset, 1]);

	
	var param_url = paramUrl.dadesObertes + "dataset=" + dataset;
	var estil_do = retornaEstilaDO(dataset);
	
	var capaDadaOberta = new L.GeoJSON.AJAX(param_url, {
		onEachFeature : createPopupWindowDadesObertes,
		nom : dataset,
		tipus : t_dades_obertes,
		dataset: dataset,
		estil_do: estil_do,
		businessId : '-1',
		geometryType:t_marker,
		pointToLayer : function(feature, latlng) {
			if(dataset.indexOf('meteo')!=-1){
				return L.marker(latlng, {icon:L.icon({					
					    iconUrl: feature.style.iconUrl,
					    iconSize:     [44, 44], 
					    iconAnchor:   [22, 22], 				   
					    popupAnchor:  [-3, -3] 
				})});
			}else if(dataset.indexOf('incidencies')!=-1){
				var inci=feature.properties.descripcio_tipus;
				var arr = ["Obres", "Retenció", "Cons", "Meterologia" ];
				var arrIM = ["st_obre.png", "st_rete.png", "st_cons.png", "st_mete.png" ];
				var imgInci="/geocatweb/img/"+arrIM[jQuery.inArray( inci, arr )];
				return L.marker(latlng, {icon:L.icon({					
				    iconUrl: imgInci,
				    iconSize:     [30, 26], 
				    iconAnchor:   [15, 13], 				   
				    popupAnchor:  [-3, -3] 
			})});
			}else if(dataset.indexOf('cameres')!=-1){
				return L.marker(latlng, {icon:L.icon({					
				    iconUrl: "/geocatweb/img/st_came.png",
				    iconSize:     [30, 26], 
				    iconAnchor:   [15, 13], 				   
				    popupAnchor:  [-3, -3] 
			})});
			}else{
			return L.circleMarker(latlng, estil_do);
			}
		},
		middleware:function(data){
            
            if(data.status && data.status.indexOf("ERROR")!=-1){
        		if(data.results.indexOf("CONVERT ERROR")!= -1){
    			var txt_error = window.lang.translate("Error en el tractament de les dades");
    			jQuery("#div_do_message").html('<div class="alert alert-danger">'+txt_error+'</div>');
	    		}
	    		else{
	    			var txt_error = window.lang.translate("Impossible accedir a la font de dades");
	    			jQuery("#div_do_message").html('<div class="alert alert-danger">'+txt_error+'</div>');
	    		}            	
            }else{
            	if (data!=null && data.features!="undefined"){
            		jQuery("#div_do_message").html("");
	            	capaDadaOberta.addData(data);
	            	
	            	if(typeof url('?businessid') == "string"){
	    				var data = {
	    					uid:Cookies.get('uid'),
	    					mapBusinessId: url('?businessid'),
	    					serverName: nom_dataset,
	    					serverType: t_dades_obertes,
	    					calentas: false,
	    		            activas: true,
	    		            visibilitats: true,
	    		            order: controlCapes._lastZIndex+1,
	    		            epsg: '4326',
	    		            transparency: true,
	    		            visibilitat: visibilitat_open,
	    					options: '{"dataset":"'+dataset+'","estil_do":{"radius":"'+estil_do.radius+'","fillColor":"'+estil_do.fillColor+'","color":"'+estil_do.color+'","weight":"'+estil_do.weight+'","opacity":"'+estil_do.opacity+'","fillOpacity":"'+estil_do.fillOpacity+'","isCanvas":"'+estil_do.isCanvas+'"}}'			
	    				};
	    				
	    				createServidorInMap(data).then(function(results){
	    					if (results.status == "OK"){
	    						capaDadaOberta.nom = nom_dataset;// +" ("+datasetLength+")";
	    						
	    						capaDadaOberta.options={"dataset":dataset,
	    								"estil_do":{"radius":estil_do.radius,
	    									"fillColor":estil_do.fillColor,
	    									"color":estil_do.color,
	    									"weight":estil_do.weight,
	    									"opacity":estil_do.opacity,
	    									"fillOpacity":estil_do.fillOpacity,
	    									"isCanvas":estil_do.isCanvas}};
	    						
	    						capaDadaOberta.options.businessId = results.results.businessId;
	    						
	    						capaDadaOberta.options.zIndex = controlCapes._lastZIndex+1;
	    						capaDadaOberta.options.tipus= t_dades_obertes;
	    						capaDadaOberta.options.nom = nom_dataset;
	    						capaDadaOberta.addTo(map)
	    						
	    						
	    						controlCapes.addOverlay(capaDadaOberta, nom_dataset, true);
	    						controlCapes._lastZIndex++;
	    						activaPanelCapes(true);
	    						
	    					}
	    				});
	    			}else{
	    				capaDadaOberta.nom = nom_dataset;// +" ("+datasetLength+")";
	    				capaDadaOberta.addTo(map);
	    				capaDadaOberta.options.zIndex = controlCapes._lastZIndex+1;
	    				controlCapes.addOverlay(capaDadaOberta, nom_dataset, true);
	    				controlCapes._lastZIndex++;
	    				activaPanelCapes(true);
	    			}	
            	}
            }
        }
	});
}

function loadDadesObertesLayer(layer){
	
	var defer = $.Deferred();
	
	var options = jQuery.parseJSON( layer.options );
	if(options.tem == null || options.tem == tem_simple){
		var url_param = paramUrl.dadesObertes + "dataset=" + options.dataset;
		var estil_do = options.estil_do;
		
		if (options.tem == tem_simple){
			estil_do = createFeatureMarkerStyle(options.style);
		}
		var capaDadaOberta = new L.GeoJSON.AJAX(url_param, {
			onEachFeature : createPopupWindowDadesObertes,
			nom : layer.serverName,
			tipus : layer.serverType,
			dataset: options.dataset,
			businessId : layer.businessId,
			dataType : "jsonp",
			estil_do : estil_do, //per la llegenda
			pointToLayer : function(feature, latlng) {
				if(options.dataset.indexOf('meteo')!=-1){
					return L.marker(latlng, {icon:L.icon({					
						    iconUrl: feature.style.iconUrl,
						    iconSize:     [44, 44], 
						    iconAnchor:   [22, 22], 				   
						    popupAnchor:  [-3, -3] 
					})});
				}else if(options.dataset.indexOf('incidencies')!=-1){
					var inci=feature.properties.descripcio_tipus;
					var arr = ["Obres", "Retenció", "Cons", "Meterologia" ];
					var arrIM = ["st_obre.png", "st_rete.png", "st_cons.png", "st_mete.png" ];
					var imgInci="/geocatweb/img/"+arrIM[jQuery.inArray( inci, arr )];
					return L.marker(latlng, {icon:L.icon({					
					    iconUrl: imgInci,
					    iconSize:     [30, 26], 
					    iconAnchor:   [15, 13], 				   
					    popupAnchor:  [-3, -3] 
					})});
				}else if(options.dataset.indexOf('cameres')!=-1){
					return L.marker(latlng, {icon:L.icon({					
					    iconUrl: "/geocatweb/img/st_came.png",
					    iconSize:     [30, 26], 
					    iconAnchor:   [15, 13], 				   
					    popupAnchor:  [-3, -3] 
					})});
				}else{
					if (estil_do.isCanvas){
						return L.circleMarker(latlng, estil_do);
					}else{
						return L.marker(latlng, {icon:estil_do,isCanvas:false, tipus: t_marker});
					}
				}
			}
		});	
		
		
		//afegim group
		if (options.group){
			capaDadaOberta.options.group=options.group;
		}
		
		
		if (layer.capesActiva== null || layer.capesActiva == 'null' || layer.capesActiva == true || layer.capesActiva == "true"){
			capaDadaOberta.addTo(map);
		}
				
		if (!layer.capesOrdre || layer.capesOrdre == null || layer.capesOrdre == 'null'){
			capaDadaOberta.options.zIndex = controlCapes._lastZIndex + 1;
		}else{
			capaDadaOberta.options.zIndex = parseInt(layer.capesOrdre);
		}		
		
		if(!options.origen){
			//Fins que no estigui carregada del tot no afegim al controlcapes (per tenir be el comptador de features)
			capaDadaOberta.on('data:loaded', function(e){
				controlCapes.addOverlay(capaDadaOberta, layer.serverName, true);
				controlCapes._lastZIndex++;
				defer.resolve();
			});
		}else{//Si te origen es una sublayer
			var origen = getLeafletIdFromBusinessId(options.origen);
			capaDadaOberta.options.zIndex = capesOrdre_sublayer;
			controlCapes.addOverlay(capaDadaOberta, layer.serverName, true, origen);
			defer.resolve();
		}		
		
	}else if(options.tem == tem_cluster){
		loadDadesObertesClusterLayer(layer,defer);
	}else if(options.tem == tem_heatmap){
		loadDOHeatmapLayer(layer,defer);
	}
	return defer.promise();
}

function createPopupWindowDadesObertes(player,l){
	//console.debug("createPopupWindowData");
	var html='';
	var out = [];
	if (player.properties.nom && !isBusinessId(player.properties.nom)){
		html+='<h4>'+player.properties.nom+'</h4>';
	}else if(player.properties.name && !isBusinessId(player.properties.name)){
		html+='<h4>'+player.properties.name+'</h4>';
	}else if(player.properties.Name && !isBusinessId(player.properties.Name)){
		html+='<h4>'+player.properties.Name+'</h4>';
	}
	if (player.properties.description){
		if (!$.isNumeric(player.properties.description) && !validateWkt(player.properties.description)) html+='<div>'+parseUrlTextPopUp(player.properties.description)+'</div>';
		else html+='<div>'+player.properties.description+'</div>';
	}
	html+='<div class="div_popup_visor"><div class="popup_pres">';
	var pp = player.properties;

	$.each( pp, function( key, value ) {
		if(isValidValue(value) && !validateWkt(value)){
			if (key != 'name' && key != 'Name' && key != 'description' && key != 'id' && key != 'businessId' && key != 'slotd50'){
				html+='<div class="popup_data_row">';
				var txt = value;
				if (!$.isNumeric(txt)) {
					txt = parseUrlTextPopUp(value,key);				
				
					if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
						html+='<div class="popup_data_key">'+key+'</div>';
						html+='<div class="popup_data_value">'+txt+'</div>';
					}else{
						html+='<div class="popup_data_img_iframe">'+txt+'</div>';
					}
				}
				else {
					html+='<div class="popup_data_key">'+key+'</div>';
					html+='<div class="popup_data_value">'+txt+'</div>';
				}
				html+= '</div>';
			}
		}
	});	
	
	html+='</div></div>';
	l.bindPopup(html,{'offset':[0,-25]});
}<file_sep>/geocatweb/js/geocat.mapa.heat.js

function createHeatMap(capa,tipus){
	
	_gaq.push(['_trackEvent', 'mapa', tipus_user+'estils', 'heatmap', 1]);
//	_kmq.push(['record', 'estils', {'from':'mapa', 'tipus user':tipus_user, 'tipus tematic':'heatmap'}]);
	
	var nom = window.lang.translate("Concentració");
	//Heatmap
	if (tipus == t_vis_wms){
		var instamapsWms = InstamapsWms({
			loadTemplateParam :false});
		var dataWMS = {url: capa.layer._url};
		instamapsWms.getWMSLayers(dataWMS).then(function(results) {
			var layers = [];
			layers=results.Capability.Layer.Layer;
			for (var i=0;i<layers.length;i++){
				var layer = layers[i];
				if (layers[i].Name.indexOf("heatmap")>-1) {
					var data = {
							businessId: capa.layer.options.businessId,//businessId id de la visualización de origen
							uid: Cookies.get('uid'),//uid id de usuario
				            mapBusinessId: url('?businessid'),//mapBusinessId id del mapa donde se agrega la visualización	           
				            nom: layers[i].Name,//nom nombre de la nueva visualizacion
				            activas: true,
				            order: capesOrdre_sublayer,//order (optional) orden de la capa en el mapa
							tem: tem_heatmap,
							serverType: tem_heatmap_wms,//tem_heatmap
							url: capa.layer._url
//				            estils: JSON.stringify(rangs[0])
					};
					createVisualitzacioHeatCluster(data).then(function(results){
						if(results.status == 'OK'){
							loadVisualitzacioWmsLayerSenseUtfGrid(results.layer);			
							$('#input-'+results.layer.businessId).trigger( "click" );
							$('#input-'+results.layer.businessId).prop( "checked", true );
							activaPanelCapes(true);
							$('#input-'+results.layer.businessId).trigger( "click" );
							$('#input-'+results.layer.businessId).prop( "checked", false );
							$('#input-'+results.layer.businessId).trigger( "click" );
							$('#input-'+results.layer.businessId).prop( "checked", true );
							activaPanelCapes(true);	
							//Desactivem la capa mare
							if ($( "#input-"+capaMare.options.businessId).attr("checked")!=undefined) $( "#input-"+capa.layer.options.businessId).click();
						}else{
							//TODO error
							console.debug("createVisualitzacioHeat ERROR");					
						}
					},function(results){
						//TODO error
						console.debug("createVisualitzacioHeat ERROR");
					});
					
				}
			}
		});
	}
	else {
			var arrP=[];
			
			capa.layer.eachLayer(function(layer){
				var d =[layer.getLatLng().lat,layer.getLatLng().lng,1];	
				arrP.push(d);			
			});
			
			var heatLayerActiu = L.heatLayer(arrP,{radius:20,blur:15,max:1,
				gradient: {			
					0.35: "#070751",
					0.40: "#0095DE",
					0.45: "#02D5FF",
					0.50: "#02E0B9",
					0.55: "#00B43F",
					0.60: "#97ED0E",
					0.61: "#FFF800",
					0.65: "#FF9700",
					0.70: "#FF0101",
					1: "#720404"
					}	
			});
			
			if(typeof url('?businessid') == "string"){
				//Si capa origen dades obertes, creem nova capa
				if(capa.layer.options.tipus == t_dades_obertes){
					data = {
							uid:Cookies.get('uid'),
							mapBusinessId: url('?businessid'),
							serverName: capa.layer.options.nom+" "+nom,
							serverType: t_dades_obertes,
							calentas: false,
				            activas: true,
				            order: capesOrdre_sublayer,
				            visibilitats: true,
				            epsg: '4326',
				            imgFormat: 'image/png',
				            infFormat: 'text/html',
				            tiles: true,	            
				            transparency: true,
				            opacity: 1,
				            visibilitat: 'O',
				            options: '{"dataset":"'+capa.layer.options.dataset+'","tem":"'+tem_heatmap+'","origen":"'+capa.layer.options.businessId+'"}'
					};	
					
					createServidorInMap(data).then(function(results){
						if (results.status == "OK"){
							
							heatLayerActiu.options.businessId = results.results.businessId;
							
							heatLayerActiu.options.nom = capa.layer.options.nom+" "+nom;
							heatLayerActiu.options.tipus = t_dades_obertes;
							heatLayerActiu.options.tipusRang = tem_heatmap;
							
							map.addLayer(heatLayerActiu);
							heatLayerActiu.options.zIndex = capesOrdre_sublayer; //controlCapes._lastZIndex+1;
							controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, capa.layer._leaflet_id);
		//					controlCapes._lastZIndex++;
							activaPanelCapes(true);
							if ($( "#input-"+capa.layer.options.businessId).attr("checked")!=undefined) $( "#input-"+capa.layer.options.businessId).click();
						}else{
							console.debug('error create server in map');					
						}
					});				
				
				//tipus json 
				}else if(capa.layer.options.tipus == t_json){
					
					var data = {
						uid:Cookies.get('uid'),
						mapBusinessId: url('?businessid'),
						serverName: capa.layer.options.nom+" "+nom,
						serverType: t_json,
						calentas: false,
					    activas: true,
					    visibilitats: true,
					    order: capesOrdre_sublayer,
					    epsg: '4326',
					    imgFormat: 'image/png',
					    infFormat: 'text/html',
					    tiles: true,	            
					    transparency: true,
					    opacity: 1,
					    visibilitat: 'O',
					    url: capa.layer.options.url,
					    calentas: false,
					    activas: true,
					    visibilitats: true,
					    options: '{"x":"'+capa.layer.options.options.x+'", "y":"'+capa.layer.options.options.y+'","tem":"'+tem_heatmap+'","origen":"'+capa.layer.options.businessId+'"}'
		//			    options: '{"x":"'+cmd_json_x+'", "y":"'+cmd_json_y+'","titol":"'+cmd_json_titol+'","descripcio":"'+cmd_json_desc+'", "imatge":"'+cmd_json_img+'","vincle":"'+cmd_json_vin+'","estil_do":{"radius":"'+estil_do.radius+'","fillColor":"'+estil_do.fillColor+'","color":"'+estil_do.color+'","weight":"'+estil_do.weight+'","opacity":"'+estil_do.opacity+'","fillOpacity":"'+estil_do.fillOpacity+'","isCanvas":"'+estil_do.isCanvas+'"}}'
					};			
					
					createServidorInMap(data).then(function(results){
						if (results.status == "OK"){
							heatLayerActiu.options.businessId = results.results.businessId;
							
							heatLayerActiu.options.nom = capa.layer.options.nom+" "+nom;
							heatLayerActiu.options.tipus = t_json;
							heatLayerActiu.options.tipusRang = tem_heatmap;
							
							map.addLayer(heatLayerActiu);
							heatLayerActiu.options.zIndex = capesOrdre_sublayer; //controlCapes._lastZIndex+1;
							controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, capa.layer._leaflet_id);
		//					controlCapes._lastZIndex++;
							activaPanelCapes(true);
							//Desactivem la capa mare
							if ($( "#input-"+capa.layer.options.businessId).attr("checked")!=undefined)	$( "#input-"+capa.layer.options.businessId).click();
		//					$(".layers-list").mCustomScrollbar({
		//						   advanced:{
		//						     autoScrollOnFocus: false,
		//						     updateOnContentResize: true
		//						   }           
		//					});	
						}else{
							console.debug("Error add heatmap JSON");
						}
					});
				}else if(capa.layer.options.tipus == t_url_file){
					
					
					var options = {
							url: capa.layer.options.url,//capaMare.options.url,
							tem: tem_heatmap,
							origen: capa.layer.options.businessId,
							tipus : t_url_file,
		//					businessId : '-1',
							tipusFile: capa.layer.options.tipusFile,
		//					estil_do: estil_do,
							epsgIN: capa.layer.options.epsgIN,
							geometryType: capa.layer.options.geometryType,
							colX: capa.layer.options.colX,
							colY: capa.layer.options.colY,
							dinamic: capa.layer.options.dinamic
						};
					
		//				console.debug(options);			
					
					var data = {
							uid:Cookies.get('uid'),
							mapBusinessId: url('?businessid'),
							serverName: capa.layer.options.nom+" "+nom,
		//					serverName: capa.layer.options.nom+" "+window.lang.translate("Bàsic"),
							serverType: capa.layer.options.tipus,
							calentas: false,
				            activas: true,
				            visibilitats: true,
				            order: capesOrdre_sublayer,				
				            epsg: capa.layer.options.epsgIN,
				            imgFormat: 'image/png',
				            infFormat: 'text/html',
		//		            tiles: true,	            
				            transparency: true,
				            opacity: 1,
				            visibilitat: 'O',
				            url: capa.layer.options.url,//capaMare.options.url,
							options: JSON.stringify(options)
						};
					
					
					createServidorInMap(data).then(function(results){
						if (results.status == "OK"){
							heatLayerActiu.options.businessId = results.results.businessId;
		
							heatLayerActiu.options.nom = capa.layer.options.nom+" "+nom;
							heatLayerActiu.options.tipus = t_url_file;
							heatLayerActiu.options.tipusRang = tem_heatmap;
							
							map.addLayer(heatLayerActiu);
							heatLayerActiu.options.zIndex = capesOrdre_sublayer; //controlCapes._lastZIndex+1;
							controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, capa.layer._leaflet_id);
		//					controlCapes._lastZIndex++;
							activaPanelCapes(true);
							//Desactivem la capa mare
							if ($( "#input-"+capa.layer.options.businessId).attr("checked")!=undefined) $( "#input-"+capa.layer.options.businessId).click();
		
						}else{
							console.debug("Error add heatmap URL FILE");
						}
					});
					
				}else if (capa.layer.options.tipus == t_visualitzacio){
					var data = {
							businessId: capa.layer.options.businessId,//businessId id de la visualización de origen
							uid: Cookies.get('uid'),//uid id de usuario
				            mapBusinessId: url('?businessid'),//mapBusinessId id del mapa donde se agrega la visualización	           
				            nom: capa.layer.options.nom+" "+nom,//nom nombre de la nueva visualizacion
				            activas: true,
				            order: capesOrdre_sublayer,//order (optional) orden de la capa en el mapa
							tem: tem_heatmap//tem_heatmap
		//		            estils: JSON.stringify(rangs[0])
						};	
						
						createVisualitzacioHeatCluster(data).then(function(results){
							if(results.status == 'OK'){
								
								heatLayerActiu.options.businessId = results.layer.businessId;
								heatLayerActiu.options.nom = capa.layer.options.nom+" "+nom;
								heatLayerActiu.options.tipus = capa.layer.options.tipus;
								heatLayerActiu.options.tipusRang = tem_heatmap;
		
		//						map.addLayer(heatLayerActiu);Comentat per control de un heatmap actiu alhora
								heatLayerActiu.options.zIndex = capesOrdre_sublayer; //controlCapes._lastZIndex+1;
								controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, capa.layer._leaflet_id);
		//						controlCapes._lastZIndex++;
								activaPanelCapes(true);
								//Desactivem la capa mare
								$('#input-'+results.layer.businessId).click();
								if ($( "#input-"+capa.layer.options.businessId).attr("checked")!=undefined) $( "#input-"+capa.layer.options.businessId).click();
								
							}else{
								//TODO error
								console.debug("createVisualitzacioHeat ERROR");					
							}
						},function(results){
							//TODO error
							console.debug("createVisualitzacioHeat ERROR");
						});
				}
		
			}else{
				heatLayerActiu.options.businessId = -1;
				heatLayerActiu.options.nom = capa.layer.options.nom+" "+nom;
				heatLayerActiu.options.tipus = capa.layer.options.tipus;
				heatLayerActiu.options.tipusRang = tem_heatmap;
				
				map.addLayer(heatLayerActiu);
				heatLayerActiu.options.zIndex = capesOrdre_sublayer; //controlCapes._lastZIndex+1;
				controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, capa.layer._leaflet_id);
		//		controlCapes._lastZIndex++;
				activaPanelCapes(true);
			}	
	}
	
}

function loadDOHeatmapLayer(layer, dfd){
	//console.debug(layer);
	var options = jQuery.parseJSON( layer.options );
	var estil_do = retornaEstilaDO(options.dataset);
	var url_param = paramUrl.dadesObertes + "dataset=" + options.dataset;	
	
	var capaDadaOberta = new L.GeoJSON.AJAX(url_param, {
		onEachFeature : popUp,
		nom : layer.serverName,
		tipus : layer.serverType,
		dataset: options.dataset,
		businessId : layer.businessId,
		dataType : "jsonp",
		zIndex: parseInt(layer.capesOrdre),
		pointToLayer : function(feature, latlng) {
			return L.circleMarker(latlng, estil_do);
		}	
	});
	
	capaDadaOberta.on('data:loaded', function(e){
		//console.debug("data:loaded");
		
		var arrP=[];
		capaDadaOberta.eachLayer(function(layer){
			var d =[layer.getLatLng().lat,layer.getLatLng().lng,1];	
			arrP.push(d);			
		});
		
		var heatLayerActiu = L.heatLayer(arrP,{radius:20,blur:15,max:1,
			gradient: {			
				0.35: "#070751",
				0.40: "#0095DE",
				0.45: "#02D5FF",
				0.50: "#02E0B9",
				0.55: "#00B43F",
				0.60: "#97ED0E",
				0.61: "#FFF800",
				0.65: "#FF9700",
				0.70: "#FF0101",
				1: "#720404"
				}	
		});
		
		heatLayerActiu.options.businessId = layer.businessId;
		heatLayerActiu.options.nom = layer.serverName;
		heatLayerActiu.options.zIndex = parseInt(layer.capesOrdre);
		heatLayerActiu.options.tipus = layer.serverType;
		heatLayerActiu.options.tipusRang = tem_heatmap;
		
		if (layer.capesActiva == true || layer.capesActiva == "true"){
			map.addLayer(heatLayerActiu);
		}
		
		var origen = getLeafletIdFromBusinessId(options.origen);
		controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, origen);
//		controlCapes._lastZIndex++;
		activaPanelCapes(true);
		
		if(dfd){
			try{
				dfd.resolve();
			}catch(e){
				
			}
		}
	});
}

function loadJsonHeatmapLayer(layer){
	console.debug("loadJsonHeatmapLayer");
	
	var options = jQuery.parseJSON( layer.options );

	var v_respotaJSON;
	getJSONPServei(layer.url).then(function(results) {
		var op = [];
		if (jQuery.isArray(results)) {
			v_respotaJSON = results;
		} else {
			for (key in results) {
				if (jQuery.isArray(results[key])) {
					v_respotaJSON = results[key];
				}
			}
		}

		if (!jQuery.isArray(v_respotaJSON)) {
			alert(window.lang.translate("No s'ha interpretat bé l'estructura del JSON"));
			return;
		}
		var arrP=[];
		
		for (key in v_respotaJSON) {
			var lat = v_respotaJSON[key][options.y];
			var lon = v_respotaJSON[key][options.x];
			var d =[parseFloat(lat),parseFloat(lon),1];	
			arrP.push(d);
		}
		
		var heatLayerActiu = L.heatLayer(arrP,{radius:20,blur:15,max:1,
			gradient: {			
				0.35: "#070751",
				0.40: "#0095DE",
				0.45: "#02D5FF",
				0.50: "#02E0B9",
				0.55: "#00B43F",
				0.60: "#97ED0E",
				0.61: "#FFF800",
				0.65: "#FF9700",
				0.70: "#FF0101",
				1: "#720404"
				}	
		});
		
		heatLayerActiu.options.businessId = layer.businessId;
		heatLayerActiu.options.nom = layer.serverName;
		heatLayerActiu.options.zIndex = layer.capesOrdre;
		heatLayerActiu.options.tipus = layer.serverType;
		heatLayerActiu.options.tipusRang = tem_heatmap;
		
		if (layer.capesActiva == true || layer.capesActiva == "true"){
			map.addLayer(heatLayerActiu);
		}
		var origen = getLeafletIdFromBusinessId(options.origen);
		controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, origen);
		activaPanelCapes(true);
		console.debug("FI loadJsonHeatmapLayer");
	});
}


function loadTematicHeatmap(layer, zIndex, layerOptions, capesActiva){
	
	var options = jQuery.parseJSON(layerOptions);
	
	var arrP=[];
	$.each(layer.geometries.features.features, function(i, feature) {
		console.debug(feature.geometry);
		var d =[feature.geometry.coordinates[1],feature.geometry.coordinates[0],1];	
		arrP.push(d);			
	});
	
	var heatLayerActiu = L.heatLayer(arrP,{radius:20,blur:15,max:1,
		gradient: {			
			0.35: "#070751",
			0.40: "#0095DE",
			0.45: "#02D5FF",
			0.50: "#02E0B9",
			0.55: "#00B43F",
			0.60: "#97ED0E",
			0.61: "#FFF800",
			0.65: "#FF9700",
			0.70: "#FF0101",
			1: "#720404"
			}	
	});	
	
	heatLayerActiu.options.businessId = layer.businessId;
	heatLayerActiu.options.nom = layer.nom;
	heatLayerActiu.options.zIndex = parseInt(zIndex);
	heatLayerActiu.options.tipus = t_tematic;
	heatLayerActiu.options.tipusRang = tem_heatmap;
	
//	if (layer.capesActiva == true || layer.capesActiva == "true"){
//		map.addLayer(heatLayerActiu);
//	}
	
	if (capesActiva.indexOf("false")==-1){
		map.addLayer(heatLayerActiu);
	}
	
	var origen = getLeafletIdFromBusinessId(options.origen);
	controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, origen);
//	controlCapes._lastZIndex++;
	activaPanelCapes(true);		
	
}

function loadVisualitzacioHeatmap(layer, zIndex, layerOptions, capesActiva, dfd){
	
	//var options = jQuery.parseJSON(layerOptions);
	
	var options; 
	if(typeof (layerOptions)=="string"){	
		try {
			options = JSON.parse(layerOptions);
		}
		catch (err) {
			options = layerOptions;		
		}
	}else{			
		options = layerOptions;	
	}
	
	
	var businessId;
	if (layer.geometriesBusinessId){
		businessId=layer.geometriesBusinessId
	}
	else businessId=options.origen;
	var data = {
			businessId: businessId,//businessId id de la visualización de origen
			uid: Cookies.get('uid')//uid id de usuario
		};	
	
	//Carrego llistat geometries
	getGeometriesColleccioByBusinessId(data).then(function(results){
		if(results.status == 'OK'){
			
			var arrP=[];
			$.each(results.geometries.geometria.features, function(i, feature) {
				if (feature.geometry.type=="MultiPoint"){
					$.each(feature.geometry.coordinates, function(j, coord) {	
						var d =[coord[1],coord[0],1];	
						arrP.push(d);	
					});
					
				}
				else {
					var d =[feature.geometry.coordinates[1],feature.geometry.coordinates[0],1];	
					arrP.push(d);				
				}
			});
			//console.debug(arrP);
			var heatLayerActiu = L.heatLayer(arrP,{radius:20,blur:15,max:1,
				gradient: {			
					0.35: "#070751",
					0.40: "#0095DE",
					0.45: "#02D5FF",
					0.50: "#02E0B9",
					0.55: "#00B43F",
					0.60: "#97ED0E",
					0.61: "#FFF800",
					0.65: "#FF9700",
					0.70: "#FF0101",
					1: "#720404"
					}	
			});	
			
			heatLayerActiu.options.businessId = layer.businessId;
			heatLayerActiu.options.nom = layer.nom;
			heatLayerActiu.options.zIndex = parseInt(zIndex);
			heatLayerActiu.options.tipus = t_visualitzacio;
			heatLayerActiu.options.tipusRang = tem_heatmap;
			
//			if (layer.capesActiva == true || layer.capesActiva == "true"){
//				map.addLayer(heatLayerActiu);
//			}
			
			if (capesActiva!=undefined && capesActiva.indexOf("false")==-1){
				map.addLayer(heatLayerActiu);
			}
			else if (capesActiva==undefined) map.addLayer(heatLayerActiu);
			
			var origen = getLeafletIdFromBusinessId(options.origen);
			controlCapes.addOverlay(heatLayerActiu,	heatLayerActiu.options.nom, true, origen);
//			controlCapes._lastZIndex++;
			activaPanelCapes(true);
			
			if(dfd){
				try{
					dfd.resolve();
				}catch(e){
					
				}
			}
			
		}else{
			console.debug("getGeometriesColleccioByBusinessId ERROR");					
		}
	},function(results){
		//TODO error
		console.debug("getGeometriesColleccioByBusinessId ERROR");
	});	
}

<file_sep>/geocatweb/js/geocat.mapa.xarxes-socials.js
/**
 * Gestió de la creació i carrega de capes de tipus social:
 * - L.Panoramio.custom.js
 * - L.Wikipedia.custom.js
 * - L.Twitter.custom.js
 */

function addPanoramioLayer(){
	
	_gaq.push(['_trackEvent', 'mapa', tipus_user+'panoramio', 'label panoramio', 1]);
	//_kmq.push(['record', 'panoramio', {'from':'mapa', 'tipus user':tipus_user}]);
	
	var panoramio = new L.Panoramio.custom({
		maxLoad: 10, 
		maxTotal: 250, 
		nom : 'panoramio',
		businessId: '-1',
		tipus: t_xarxes_socials
	});
	
	if(typeof url('?businessid') == "string"){
		var data = {
			uid:Cookies.get('uid'),
			mapBusinessId: url('?businessid'),
			serverName: 'panoramio',
			serverType: t_xarxes_socials,
			calentas: false,
            activas: true,
            visibilitats: true,
            order: controlCapes._lastZIndex+1,
            epsg: '4326',
            transparency: true,
            visibilitat: visibilitat_open,
			options: '{"xarxa_social": "panoramio"}'
		};
		
		createServidorInMap(data).then(function(results){
			if (results.status == "OK"){
				panoramio.options.businessId = results.results.businessId;
				panoramio.options.xarxa_social="panoramio";
				panoramio.addTo(map);
				panoramio.options.zIndex = controlCapes._lastZIndex+1;
				controlCapes.addOverlay(panoramio, 'panoramio', true);
				controlCapes._lastZIndex++;
				activaPanelCapes(true);
			}else{
				console.debug('error create server in map');
			}
		});	
	}else{
		panoramio.addTo(map);
		panoramio.options.zIndex = controlCapes._lastZIndex+1;
		controlCapes.addOverlay(panoramio, 'panoramio', true);
		controlCapes._lastZIndex++;
		activaPanelCapes(true);
	}	
}

function loadPanoramioLayer(layer){	
	
	
	
	var panoramio = new L.Panoramio.custom({
		maxLoad: 10, 
		maxTotal: 250, 
		zIndex: parseInt(layer.capesOrdre),
		nom : layer.serverName,
		tipus : layer.serverType,
		businessId: layer.businessId,
		options: '{"xarxa_social": "panoramio"}'
	});	
	
	var options = jQuery.parseJSON( layer.options );
	if (options.group){
		panoramio.options.group=options.group;
		panoramio.options.xarxa_social="panoramio";
	}
	
	if (layer.capesActiva == true || layer.capesActiva == "true"){
		panoramio.addTo(map);
	}
	controlCapes.addOverlay(panoramio, layer.serverName, true);
	controlCapes._lastZIndex++;
}

function addTwitterLayer(){
	
	_gaq.push(['_trackEvent', 'mapa', tipus_user+'twitter', hashtag, 1]);	
	//_kmq.push(['record', 'twitter', {'from':'mapa', 'tipus user':tipus_user, 'hashtag':hashtag}]);
	
	var hashtag = $('#twitter-collapse .input-group #hashtag_twitter_layer').val();
	//Control no afegit #
	if(hashtag.indexOf("#") == 0) hashtag = hashtag.substr(1);
	
	if(hashtag == null || hashtag == "") return;
	
	$('#twitter-collapse .input-group #hashtag_twitter_layer').val("");
	var twitter = new L.Twitter({
		hashtag: hashtag,
		nom: 'twitter #'+ hashtag,
		businessId: '-1',
		tipus: t_xarxes_socials
	});

	//Si el mapa existeix a BD
	if(typeof url('?businessid') == "string"){	
		var data = {
				uid:Cookies.get('uid'),
				mapBusinessId: url('?businessid'),
				serverName: 'twitter #'+ hashtag,
				serverType: t_xarxes_socials,
				calentas: false,
	            activas: true,
	            visibilitats: true,
	            order: controlCapes._lastZIndex+1,
	            epsg: '4326',
	            transparency: true,
	            visibilitat: visibilitat_open,
				options: '{"xarxa_social": "twitter", "hashtag": "'+hashtag+'"}'
		};
		
		createServidorInMap(data).then(function(results){
			if (results.status == "OK"){
				twitter.options.businessId = results.results.businessId;
				twitter.options.xarxa_social="twitter";
				twitter.options.hashtag=hashtag;
				twitter.addTo(map);
				twitter.options.zIndex = controlCapes._lastZIndex+1;
				controlCapes.addOverlay(twitter, 'twitter #'+ hashtag, true);
				controlCapes._lastZIndex++;
				activaPanelCapes(true);
			}else{
				console.debug('error create server in map');
			}
		});	
	}else{
		twitter.addTo(map);
		twitter.options.zIndex = controlCapes._lastZIndex+1;
		controlCapes.addOverlay(twitter, 'twitter #'+ hashtag, true);
		controlCapes._lastZIndex++;
		activaPanelCapes(true);
	}	
	//Tanquem input twitter
	$('#twitter-collapse').hide();
} 

function loadTwitterLayer(layer, hashtag){
	var twitter = new L.Twitter({
		hashtag: hashtag,
		nom: layer.serverName,
		tipus : layer.serverType,
		zIndex: parseInt(layer.capesOrdre), 
		businessId: layer.businessId
	});	
	
	
	var options = jQuery.parseJSON( layer.options );
	if (options.group){
		twitter.options.group=options.group;
	}
	
	
	if (layer.capesActiva == true || layer.capesActiva == "true"){
		twitter.addTo(map);
	}
	controlCapes.addOverlay(twitter, layer.serverName, true);
	controlCapes._lastZIndex++;
}





function addWikipediaLayer(){	
	
	_gaq.push(['_trackEvent', 'mapa', tipus_user+'wikipedia', 'label wikipedia', 1]);
	//_kmq.push(['record', 'wikipedia', {'from':'mapa', 'tipus user':tipus_user}]);
	
	var keyName = $('#wikipedia-collapse .input-group #name_wikipedia_layer').val();	
	
	var wikipedia = new L.Wikipedia({
		nom : 'wikipedia',
		businessId: '-1',
		tipus: t_xarxes_socials,
		key: keyName
	});
	
	if(typeof url('?businessid') == "string"){
		
		var data = {
			uid:Cookies.get('uid'),
			mapBusinessId: url('?businessid'),
			serverName: 'wikipedia',
			serverType: t_xarxes_socials,
			calentas: false,
            activas: true,
            visibilitats: true,
            order: controlCapes._lastZIndex+1,
            epsg: '4326',
            transparency: true,
            visibilitat: visibilitat_open,
			options: '{"xarxa_social": "wikipedia", "key": "'+keyName+'"}'
		};
		
		
		
		createServidorInMap(data).then(function(results){
			if (results.status == "OK"){
				wikipedia.options.businessId = results.results.businessId;			
				wikipedia.options.xarxa_social = "wikipedia";				
				wikipedia.options.key = keyName;								
				wikipedia.addTo(map);
				wikipedia.options.zIndex = controlCapes._lastZIndex+1;
				controlCapes.addOverlay(wikipedia, 'wikipedia', true);
				controlCapes._lastZIndex++;
				activaPanelCapes(true);
			}else{
				console.debug('error create server in map');
			}
		});
	}else{
		
		
		
		
		wikipedia.addTo(map);
		wikipedia.options.zIndex = controlCapes._lastZIndex+1;
		controlCapes.addOverlay(wikipedia, 'wikipedia', true);
		controlCapes._lastZIndex++;
		activaPanelCapes(true);
	}	
}

function loadWikipediaLayer(layer){
	
	var wikipedia = new L.Wikipedia({
		zIndex: parseInt(layer.capesOrdre),
		nom : layer.serverName,
		tipus : layer.serverType,
		businessId: layer.businessId
	});	
	
	var options = jQuery.parseJSON( layer.options );
	if (options.group){
		wikipedia.options.group=options.group;
	}
	
	
	if (layer.capesActiva == true || layer.capesActiva == "true"){
		wikipedia.addTo(map);
	}
	controlCapes.addOverlay(wikipedia, layer.serverName, true);
	controlCapes._lastZIndex++;
}
<file_sep>/geocatweb/js/geocat.mapa.carrega-fitxers.js
var drgFromMapa = null;
var drgFromBoto = null;
var midaFitxer = 500000000;//en bytes
var midaFitxerRandom = 10000000;//en bytes

var busy = false; //per controlar si ja estem pujant un fitxer

var envioArxiu={isDrag:false,
	tipusAcc:'gdal', //gdal,adreca,coordenades,codis
	colX:null,
	colY:null,
	colWKT:null,
	tipusCSV:null,
	srid:'EPSG:4326',
	bid:null,
	codi:null,
	codiType:null,
	geomType:null,
	type:null,
	camps:null,
	ext:null,
	uid : null,
	mapBusinessId : null,
	markerStyle: null,
	lineStyle: null,
	polygonStyle: null,
	midaFitxer: null,
	serverName: null,
	format : ""
};

var drOpcionsMapa = {
	url : paramUrl.upload_gdal_2015,
	paramName : "file", 
	maxFilesize : 500, // MB
	method : 'post',
	accept : function(file, done) {
	}
};

function creaAreesDragDropFiles() {
	// dropzone
	var opcionsBoto = drOpcionsMapa;
	opcionsBoto.clickable=false;
	
	if (drgFromMapa == null) {
		var divMapa="div#map";	
		estatMapa3D?divMapa="div#map3D":divMapa="div#map";	
		
		drgFromMapa = new window.Dropzone(divMapa, drOpcionsMapa);

		drgFromMapa.on("addedfile", function(file) {
			if(!busy){
				envioArxiu.isDrag=true;
				busy = true;
				accionaCarrega(file,envioArxiu.isDrag);
			}else{
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està processant un arxiu. Si us plau, espereu que aquest acabi."));
				$('#dialog_info_upload').modal('show');
				drgFromMapa.removeAllFiles(true);
			}
		});
				
		drgFromMapa.on("processing ", function(file) {
			
		});
		
		drgFromMapa.on("sending", function(file, xhr, formData) {
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades drag&drop', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
			
			if( envioArxiu.ext == "tif" || (envioArxiu.ext=="sid") || (envioArxiu.ext=="jpg") || (envioArxiu.ext=="ecw") 
					|| envioArxiu.format == "tif" || (envioArxiu.format =="sid") || (envioArxiu.format =="jpg") ){	
				$('#dialog_carrega_dades').modal('hide');
				formData.append("srs", envioArxiu.srid.toLowerCase());
				formData.append("format", (envioArxiu.ext== "zip" ? envioArxiu.format : envioArxiu.ext));
				formData.append("name", envioArxiu.serverName);
				jQuery("#div_uploading_txt").html('<div id="div_upload_step1" class="status_current" lang="ca">'+window.lang.translate('Processant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</span></div>');
				jQuery('#info_uploadFile').show();
			}else{
				formData.append("nomArxiu", file.name); 
				formData.append("tipusAcc", envioArxiu.tipusAcc); //gdal,coordenades,codis,adreca
				formData.append("colX", envioArxiu.colX);	
				formData.append("colY", envioArxiu.colY);
				formData.append("colWKT", envioArxiu.colWKT);
				formData.append("tipusCSV", envioArxiu.tipusCSV);
				formData.append("srid", envioArxiu.srid);
				formData.append("bid", envioArxiu.bid);
				formData.append("codiCAMP", envioArxiu.codi);//Nom de la columna de l'excel on esta el codi
				formData.append("codiType", envioArxiu.codiType);//ine,municat,cadastre...
				formData.append("geomType", envioArxiu.geomType);//comarques/municipis
				formData.append("type", envioArxiu.type);//codis, coordenades
				formData.append("camps", envioArxiu.camps);
				formData.append("campUnic", envioArxiu.campUnic);
				formData.append("ext", envioArxiu.ext);
				formData.append("uid", Cookies.get('uid'));
				formData.append("mapBusinessId", url('?businessid'));
				formData.append("midaFitxer", envioArxiu.midaFitxer);
				var file = file.name.split(".");
				formData.append("serverName", file[0]);
				formData.append("markerStyle", envioArxiu.markerStyle);	
				formData.append("lineStyle", envioArxiu.lineStyle);	
				formData.append("polygonStyle", envioArxiu.polygonStyle);			
				formData.append("uploadFile", paramUrl.uploadFile);
				formData.append("createMapFile", paramUrl.createMapFile);
				var codiUnic = getCodiUnic();
				formData.append("codiUnic", codiUnic);
				
				$('#dialog_carrega_dades').modal('hide');

				jQuery("#div_uploading_txt").html("");
				jQuery("#div_uploading_txt").html(
					'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Pujant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</span></div>'+
					'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Analitzant fitxer')+'</div>'+
					'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Creant geometries')+'</div>'+
					'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
				);				
				jQuery('#info_uploadFile').show();			
				jQuery('#info_uploadFile').show();
				
				//Definim interval de polling en funcio de la mida del fitxer
				var pollTime = getPollTime(envioArxiu.midaFitxer);
				
				//Fem polling
				(function(){							
					poll = function(){
						$.ajax({
							url: paramUrl.polling +"pollingFileName="+ codiUnic + url('?businessid')+".json",
							dataType: 'json',
							type: 'get',
							success: function(data){
								if(data.status.indexOf("PAS2")!=-1){
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Analitzant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
										'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Creant geometries')+'</div>'+
										'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
									);									
								}else if(data.status.indexOf("PAS3")!=-1){
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Fitxer analitzat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
										'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
									);									
								}else if(data.status.indexOf("OK")!=-1){
									clearInterval(pollInterval);
									
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Fitxer analitzat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step3" class="status_check" lang="ca">3. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step4" class="status_current" lang="ca">4. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
									);									
									
									$.get(HOST_APP+tmpdirPolling +codiUnic + url('?businessid')+"_response.json", function(data) { 
										if(data.status.indexOf("OK")!=-1){											
												addDropFileToMap(data);
										 }							
									});
									_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades ok', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
								}else if(data.status.indexOf("KO")!=-1){
									console.error("Error al carregar fitxer:");
									console.error(data);
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									var msg = "[08]: " + window.lang.translate("Error durant el processament de la informació del fitxer. Comprovi que el fitxer és correcte.");
									msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
									$('#dialog_error_upload_txt').html(msg);
									$('#dialog_error_upload').modal('show');
									_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error sense codi', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
									
								}else if(data.status.indexOf("ERROR")!=-1){
									console.error("Error al carregar fitxer:");
									console.error(data);
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									$('#dialog_error_upload_txt').html("");
									
									if(data.codi){
										_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error '+data.codi, envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
										if(data.codi.indexOf("01")!=-1){//cas 01: Exception durant el tractament del fitxer
											var msg = "[01]: " + window.lang.translate("Ha ocorregut un error inesperat durant la càrrega del fitxer.");
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("02")!=-1){//cas 02: Error durant les conversions de format del fitxer
											var msg = "[02]: " + window.lang.translate("Error durant el procés de conversió de format del fitxer. Comprovi que el fitxer és correcte.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("03")!=-1){//cas 03: OGRInfo ha donat resposta fallida
											var msg = "[03]: " + window.lang.translate("Error durant l'anàlisi de la informació del fitxer. Comprovi que el fitxer és correcte.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";										
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("04")!=-1){//cas 04: OGRInfo ha donat una excepció
											var msg = "[04]: " + window.lang.translate("Ha ocorregut un error inesperat durant l'anàlisi de la informació del fitxer.");
												$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("05")!=-1){//cas 05: OGRInfo ha tornat resposta buida
											var msg = "[05]: " + window.lang.translate("L'anàlisi de la informació del fitxer no ha tornat resultats. Comprovi el fitxer i torni a intentar-ho.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";										
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("06")!=-1){//cas 06: Accedeix a fileDefault_Error, no li ha arribat be el nom del fitxer
											var msg = "[06]: " + window.lang.translate("Problema de comunicació amb el servidor. Si us plau, torni a intentar-ho.");
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("07")!=-1){//cas 07: EnviaFileReady a myUtils.jsp ha donat una excepcio
											var msg = "[07]: " + window.lang.translate("Ha ocorregut un error inesperat durant la comunicació amb el servidor. Si us plau, torni a intentar-ho.");
											$('#dialog_error_upload_txt').html(msg);
										}
									}else{
										_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error sense codi', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
										var msg = window.lang.translate("Error en la càrrega de l'arxiu");
										msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";										
										$('#dialog_error_upload_txt').html(msg);
									}
									
									$('#dialog_error_upload').modal('show');
								}
							}
						});
					};
					
					pollInterval = setInterval(function(){
						poll();
					},pollTime);
					
				})();				
			}
		});
		
		drgFromMapa.on('success', function(file, resposta) {
			drgFromMapa.removeAllFiles(true);
			busy = false;
			if(resposta.map){
				ActiuWMS.url = "http://betaserver.icgc.cat/geoservice/"+resposta.map;
				ActiuWMS.servidor = envioArxiu.serverName;
				ActiuWMS.layers = envioArxiu.serverName;
				ActiuWMS.epsg = undefined;
				addExternalWMS(true).then(function(success){
					jQuery('#info_uploadFile').hide();
					if(!success){
						var msg = window.lang.translate("Error en la càrrega de l'arxiu");
						$('#dialog_error_upload_txt').html(msg);
					}
				},function(error){
					jQuery('#info_uploadFile').hide();
				});
			}
		});
		
		drgFromMapa.on('error', function(file, errorMessage) {
			drgFromMapa.removeAllFiles(true);
			busy = false;
		});
	}
}

function addHtmlModals(){
	var dfd = $.Deferred();
	$.when( addHtmlModalCarregarFitxers(), addHtmlModalErrorUpload(), addHtmlModalInfoUpload() ).done(function ( v1, v2 ) {
		dfd.resolve();
	});
	return dfd.promise();
}

function addFuncioCarregaFitxers(){
	addHtmlInterficieCarregarFitxers();
	addHtmlModals().then(function(){
		// zona 1
		jQuery('#div_carrega_dades').on("click", function(e) {
			carregarModalFitxer();
		});	
	
		//Botons per enviar arxius
		jQuery("#bt_esborra_ff").on('click', function() {
			if(envioArxiu.isDrag){
				drgFromMapa.removeAllFiles(true);	
			}else{
				if (drgFromBoto != null) drgFromBoto.removeAllFiles(true); 
			}
			jQuery("#file_name").text("");
			jQuery('#dv_optCapa').hide();
			jQuery('#dv_optSRS').hide();
			jQuery("#bt_esborra_ff").hide();
			jQuery('#prg_bar').css('width',"0%");
		});	
	
		jQuery("#load_TXT_coord").on('click', function() {// fitxer TXT
			var isOK=false;
			var colX = jQuery("#cmd_upload_colX").val();
			var colY = jQuery("#cmd_upload_colY").val();
			var colWKT=jQuery("#cmd_upload_wkt").val();
			var srid = jQuery("#select-upload-epsg").val();
			var tipusCSV=jQuery('input:radio[name="opt_csv_field"]:checked').val();
			
			if ((colX == "null" || colY == "null" ||srid == "null")  && tipusCSV=='coords') {
				isOK = false;
				alert(window.lang.translate("Cal indicar els camps de les coordenades i el sistema de referència"));		
			}else if ((srid == "null" || colWKT=="null") && tipusCSV=='wkt') {	
				isOK = false;
				alert(window.lang.translate("Cal indicar el camp geomètric i el sistema de referència"));		
			}else{
				isOK = true;
				
				if(envioArxiu.ext=="csv"){
					envioArxiu.tipusAcc='gdal'; 
				}else if(envioArxiu.ext=="txt"){
					envioArxiu.tipusAcc='gdal'; 	
				}else{
					envioArxiu.tipusAcc='coordenades';	
				}
				
				 //gdal,adreca,coordenades,codis
				envioArxiu.colX=colX;
				envioArxiu.colY=colY;
				envioArxiu.colWKT=colWKT;
				envioArxiu.srid=srid;
				envioArxiu.tipusCSV=tipusCSV;			
				enviarArxiu();
			}	
		});	
	
		jQuery('input:radio[name="opt_csv_field"]').on('click', function() {
			var ori=this.id;
			
			if(ori.indexOf('coords')!=-1){
				jQuery('#ul_coords').show();
				jQuery('#ul_geom').hide();				
			}else if(ori.indexOf('geom')!=-1){
				jQuery('#ul_coords').hide();
				jQuery('#ul_geom').show();	
			}else{		
				jQuery('#ul_coords').toggle();
				jQuery('#ul_geom').toggle();
			}		
		});	
		
		jQuery("#cmd_upload_topo").change(function(){
			if (jQuery(this).val()==="topo"){
				jQuery("#upload_num_txt").attr("style","display:block;");
				jQuery("#upload_num").attr("style","display:block;");
			}
			else {
				jQuery("#upload_num_txt").attr("style","display:none;");
				jQuery("#upload_num").attr("style","display:none;");
			}
			
		});						
		
		jQuery("#load_TXT_adre").on('click', function() {// fitxer TXT	
			var cc=$('input:radio[name="opt_adreca_field"]:checked').val();
			
			var isOK=true; //mientras adaptamos el nuevo geocodificador
			envioArxiu.tipusAcc='adreca'; 
			if(cc == 'parts'){
				var artVia=jQuery("#cmd_upload_artVia").val();
				var tipVia=jQuery("#cmd_upload_tipVia").val();
				var nomVia=jQuery("#cmd_upload_nomVia").val();
				var portal=jQuery("#cmd_upload_portal").val();
				var municipi=jQuery("#cmd_upload_municipi").val();
				var carretera=jQuery("#cmd_upload_carretera").val();
				var pk=jQuery("#cmd_upload_pk").val();
				var caixaUnica=jQuery("#cmd_caixaUnica").val();
				var topo=jQuery("#cmd_upload_topo").val();
				var toponum=jQuery("#cmd_upload_topo_num").val();
				
		       if (nomVia!="null" || municipi!="null" ||  topo!="null" || carretera!="null"){
		    	   isOK=true; 
		    	   envioArxiu.tipusAcc='adreca'; 
		    	   envioArxiu.camps= artVia+","+tipVia+","+nomVia+","+portal+","+municipi+","+carretera+","+pk+","+topo+","+toponum;
		    	   envioArxiu.campUnic='';
		    	   console.debug(envioArxiu.camps);
		       }else{
		    	   isOK=false;
		    	   alert(window.lang.translate("Cal indicar algun camp per cerca l'adreça"));
		    	  
		       };	      
		    }else if(cc == 'unica'){	    	
		    	var adrecaUnica=jQuery("#cmd_upload_caixaUnica").val();
		    	
		    	if((adrecaUnica!='null')){ 
		    		 isOK=true; 
		    		 envioArxiu.tipusAcc='adreca';
		    		 envioArxiu.campUnic=adrecaUnica;    
		    		 envioArxiu.camps='';
		    	}else{
		    		 isOK=false;
			    	 alert(window.lang.translate("Cal indicar els camps que contenen l'adreça"));
		    	}
		    }/*else if(cc == '2'){	    	
		    	var nc=jQuery("#cmd_upload_adre_21").val();
		    	var numc=jQuery("#cmd_upload_adre_22").val();
		    	var mun=jQuery("#cmd_upload_adre_23").val();
		    	
		    	if((nc!='null') && (numc!='null') && (mun!='null') ){ 
		    		 isOK=true; 
		    		 envioArxiu.tipusAcc='adreca';
		    		 envioArxiu.camps=nc+","+numc+","+mun;    		
		    	}else{
		    		 isOK=false;
			    	 alert(window.lang.translate("Cal indicar els camps que contenen l'adreça"));
		    	}
		    }*/	
			if(isOK){enviarArxiu();}
		});

		jQuery("#load_TXT_codi").on('click', function() {// fitxer codi
			 var isOK = true;
			 if (jQuery('#cmd_upload_codi').val()!="null"){
				isOK=true; 
			  	envioArxiu.tipusAcc='codis'; 
			  	envioArxiu.codi=jQuery('#cmd_upload_codi').val();
				   
			  	envioArxiu.geomType=jQuery('#cmd_codiType_Capa').val();
				envioArxiu.codiType=jQuery('#cmd_codiType').val();
			}else{
		  	   	isOK=false;
		  	   	alert(window.lang.translate("Cal indicar el camp que conté el codi"));
			 };
				
			 if(isOK){enviarArxiu();}
		});

		jQuery("#load_FF_SRS_coord").on('click', function() {
			 var isOK = true;	
			 if (jQuery('#select-upload-ff-epsg').val()!="null"){
		  	   isOK=true; 
		  	   envioArxiu.tipusAcc='gdal'; 
		  	   envioArxiu.srid=jQuery('#select-upload-ff-epsg').val();
		     }else{
		  	   isOK=false;
		  	   alert(window.lang.translate("Cal indicar el sistema de referència"));
		  	  
		     };
		     if(isOK){enviarArxiu();}
		});

		jQuery('#cmd_codiType_Capa').on('change',function(e) {
			var html = "";
			if (jQuery(this).val() == "municipis") {
				html = "<option value='ine'>INE (5 digits)</option><option value='idescat'>IDESCAT (6 digits)</option><option value='municat'>MUNICAT (10 digits)</option><option value='cadastre'>CADASTRE (5 digits)</option>";
			} else {
				html = "<option value='ine'>NUM_COMARCA (2 digits)</option><option value='municat'>MUNICAT (10 digits)</option>";
			}
			jQuery('#cmd_codiType').html(html);
		});

		$('input:radio[name="radio_adre"]').change(function(){
			var cc=$(this).val(); 
			if(cc == '0'){
		       jQuery('#cmd_upload_adre_0').attr('disabled',false);
		       jQuery("[id*='cmd_upload_adre_1']").attr('disabled',true);
		       jQuery("[id*='cmd_upload_adre_2']").attr('disabled',true);
		    }else if(cc == '1'){
		    	jQuery("[id*='cmd_upload_adre_1']").attr('disabled',false);
		    	jQuery('#cmd_upload_adre_0').attr('disabled',true);
		    	jQuery("[id*='cmd_upload_adre_2']").attr('disabled',true);
		    }else if(cc == '2'){
		    	jQuery("[id*='cmd_upload_adre_2']").attr('disabled',false);
		    	jQuery('#cmd_upload_adre_0').attr('disabled',true);
		    	jQuery("[id*='cmd_upload_adre_1']").attr('disabled',true);
		    	
		    }	
		});
		
		jQuery('input:radio[name="opt_adreca_field"]').on('click', function() {
			var ori=this.id;
			console.debug(ori);
			if(ori.indexOf('unica')!=-1){
				jQuery('#ul_adreca_unica').show();
				jQuery('#ul_adreca_parts').hide();				
			}else if(ori.indexOf('parts')!=-1){
				jQuery('#ul_adreca_unica').hide();
				jQuery('#ul_adreca_parts').show();	
			}else{		
				jQuery('#ul_adreca_unica').toggle();
				jQuery('#ul_adreca_parts').toggle();
			}		
		});	
	});
}

function getPollTime(midaFitxer){
	if(midaFitxer > 0 && midaFitxer <= 50000) return 3000;
	else if (midaFitxer > 50000 && midaFitxer <= 500000) return 5000;
	else if (midaFitxer > 500000 && midaFitxer <= 5000000) return 7000;
	else if (midaFitxer > 5000000 && midaFitxer <= 10000000) return 10000;
	else if (midaFitxer > 10000000 && midaFitxer <= 25000000) return 20000;
	else return 30000;	
}

function getCategoriaMidaFitxer(midaFitxer){
	if(midaFitxer <= 1000) return "<=1MB";
	else if (midaFitxer > 1000 && midaFitxer <= 5000) return "1-5MB";
	else if (midaFitxer > 5000 && midaFitxer <= 10000) return "5-10MB";
	else if (midaFitxer > 10000 && midaFitxer <= 25000) return "10-25MB";
	else if (midaFitxer > 25000 && midaFitxer <= 50000) return "25-50MB";
	else return ">50MB";	
}

function enviarArxiu(){
	ldpercent=0;
	if(envioArxiu.isDrag){
		drgFromMapa.uploadFile(drgFromMapa.files[0]);	
	}else{
		drgFromBoto.uploadFile(drgFromBoto.files[0]);;
	}
	if(envioArxiu.tipusAcc=="codis"){
		map.divadminMap();
	}
}

function obreModalCarregaDades(isDrag) {

	$('#dialog_carrega_dades').modal('show');
	
	if(isDrag){
		$('#upload_file').attr('disabled',true);
	}else{
		$('#upload_file').attr('disabled',false);
	}
	
	jQuery('#dv_optCapa').hide();
	jQuery('#dv_optSRS').hide();
	$('#url').val(paramUrl.dragFile);
	jQuery('#prg_bar').css('width',"0%");
	jQuery("#bt_esborra_ff").hide();
	jQuery("#file_name").text("");
}

function accionaCarrega(file,isDrag) {
	if(isDrag){
		drgFromMapa.options.url = paramUrl.upload_gdal_2015;
		drgFromMapa.options.paramName = "file";
	}else if(drgFromBoto != null){
		drgFromBoto.options.url = paramUrl.upload_gdal_2015;
		drgFromBoto.options.paramName = "file";
	}
	
	var obroModal = false;
	
	miraFitxer(file).then(function(res){
		var ff = res;
		if (ff.isValid) {
			//Careguem estils seleccionats per enviar amb el fitxer
			loadDefaultStyles();
			
			if ( isDrag) {obreModalCarregaDades(true);}
			jQuery("#file_name").text(file.name);
			jQuery("#bt_esborra_ff").show();
			
			if ((ff.ext == "csv") || (ff.ext == "txt")) {
				obteCampsCSV(file);
				obroModal = true;
				
			} else if (ff.ext == "xlsx") {
				obteCampsXLSX(file);
				obroModal = true;
				
			} else if (ff.ext == "xls") {
				obteCampsXLSX(file);
				obroModal = true;
				
			} else if( (ff.ext == "tif")  || (ff.ext=="sid") || (ff.ext=="jpg") || (ff.ext=="ecw") || (ff.ext=="zip" && !ff.isShape)) {
				if(isDrag){
					drgFromMapa.options.url = "/cloudifier/";
					drgFromMapa.options.paramName = "clientfile";
				}else{
					console.info("is from BOTO!");
					drgFromBoto.options.url = "/cloudifier/";
					drgFromBoto.options.paramName = "clientfile";
				}
				var name = file.name.split(".");
				envioArxiu.serverName = name[0];
				jQuery('#dv_optCapa').hide();
				jQuery('#dv_optSRS').show();
				obroModal = true;
				
			}else if ((ff.ext == "dgn") || (ff.ext == "dxf") || (ff.ext == "geojson") || (ff.ext == "json") || (ff.ext=="zip" && ff.isShape)) {
				jQuery('#dv_optCapa').hide();
				jQuery('#dv_optSRS').show();
				obroModal = true;
				
			}else{
				envioArxiu.tipusAcc='gdal'; 
				enviarArxiu();
				obroModal = false;
			}

		}else{ // novalid
			$('#dialog_info_upload_txt').html(window.lang.translate(ff.msg));
			$('#dialog_info_upload').modal('show');		
			obroModal = false;
			busy = false;
			if(isDrag){
				drgFromMapa.removeAllFiles(true);		
			}else if (drgFromBoto != null){
				drgFromBoto.removeAllFiles(true); 								
			}
		}
	},function(res){
		
	});
}

function analitzaMatriu(matriu) {
	var op = [];
	jQuery('#dv_optCapa').show();
	jQuery('#dv_optSRS').hide();

	$('#nav_pill a[href="#opt_codi"]').attr("data-toggle","tab");
	$('#nav_pill a[href="#opt_adreca"]').attr("data-toggle","tab");
	
	$.each(matriu, function(index, value) {
		if (!jQuery.isNumeric(value)){
		op.push("<option value=\"" + value + "\">" + value.toUpperCase()
				+ "</option>");
		}
		else {
			op.push("<option value=\"" + value + "\">" + value
					+ "</option>");	
		}
	});

	jQuery('#cmd_upload_colX').html("<option value='null'>" + window.lang.translate('Selecciona un camp')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_colY').html("<option value='null'>" + window.lang.translate('Selecciona un camp')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_wkt').html("<option value='null'>" + window.lang.translate('Selecciona un camp')+ "</option>"+op.join(" "));
	
	jQuery('#cmd_upload_artVia').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_tipVia').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_nomVia').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_portal').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_municipi').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_carretera').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_pk').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_topo').html("<option value='null'>" + window.lang.translate('Selecciona un camp si en conté')+ "</option>"+op.join(" "));
	jQuery('#cmd_upload_caixaUnica').html("<option value='null'>" + window.lang.translate('Selecciona un camp')+ "</option>"+op.join(" "));
		
	jQuery('#cmd_upload_codi').html("<option value='null'>" + window.lang.translate('Selecciona un camp amb el codi')+ "</option>"+op.join(" "));

	var fieldType = "";
	for (var x = 0; x < matriu.length; x++) {
		if (!jQuery.isNumeric(matriu[x]) && (matriu[x].toUpperCase() == "X" || matriu[x].toUpperCase() == "LON"
				|| matriu[x].toUpperCase() == "LONGITUD")) {
			fieldType = "colX";
			$('#cmd_upload_colX option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_coord"]').tab('show');

		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "Y"
				|| matriu[x].toUpperCase() == "LAT"
				|| matriu[x].toUpperCase() == "LATITUD")) {

			fieldType = "colY";
			$('#cmd_upload_colY option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_coord"]').tab('show');

		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "POLIGONO"
				|| matriu[x].toUpperCase() == "POLYGON"
				|| matriu[x].toUpperCase() == "POINT"
				|| matriu[x].toUpperCase() == "GEOM"
				|| matriu[x].toUpperCase() == "LINESTRING")) {

			fieldType = "wkt";
			$('#cmd_upload_wkt option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_coord"]').tab('show');	
			jQuery("#opt_csv_geom").click();
			
		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "CARRER"
				|| matriu[x].toUpperCase() == "ADRECA")) {
			fieldType = "adre";
			$('#cmd_upload_adre option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_adreca"]').tab('show');
		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "MUNICIPI"
				|| matriu[x].toUpperCase() == "MUNI"
				|| matriu[x].toUpperCase() == "POPBLA"
				|| matriu[x].toUpperCase() == "COMARC")) {
			fieldType = "adre";
			$('#cmd_upload_mun option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_adreca"]').tab('show');
		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "ID"
				|| matriu[x].toUpperCase() == "BID"
				|| matriu[x].toUpperCase() == "CODI")) {
			fieldType = "bid";
		} else if (!jQuery.isNumeric(matriu[x]) &&  (matriu[x].toUpperCase() == "CODI_INE"
				|| matriu[x].toUpperCase() == "CODI INE"
				|| matriu[x].toUpperCase() == "INE"
				|| matriu[x].toUpperCase() == "CODI_MUNICAT"
				|| matriu[x].toUpperCase() == "MUNICAT"
				|| matriu[x].toUpperCase() == "IDESCAT"
				|| matriu[x].toUpperCase() == "CADASTRE")) {
			fieldType = "codi";
			$('#cmd_upload_codi option:contains("' + matriu[x] + '")').prop(
					'selected', true);
			$('#nav_pill a[href="#opt_codi"]').tab('show');
		}
	}
}

function obteCampsCSV(file) {
	var matriuActiva = [];
	var reader = new FileReader();
	reader.onload = function(e) {
		var csvval = e.target.result.split("\n");
		var separador = ";";
		if (csvval[0].indexOf(";") != -1) {
			separador = ";";
		} else if (csvval[0].indexOf(",") != -1) {
			separador = ",";
		} else if(csvval[0].indexOf(",") != -1) {
			separador = " ";
		}
		var csvvalue = csvval[0].split(separador);
		for ( var i = 0; i < csvvalue.length; i++) {
			matriuActiva.push(csvvalue[i].replace("\r", ""));
		}
		analitzaMatriu(matriuActiva);
	};
	reader.readAsText(file);
}

var X = XLSX;
var XW = {
	/* worker message */
	msg: 'xlsx',
	/* worker scripts */
	rABS: '/llibreries/js/formats/xlsxworker2.js',
	norABS: '/llibreries/js/formats/xlsxworker1.js',
	noxfer: '/llibreries/js/formats/xlsxworker.js'
};

function fixdata(data) {
	var o = "", l = 0, w = 10240;
	for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
	o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
	return o;
}

function ab2str(data) {
	var o = "", l = 0, w = 10240;
	for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint16Array(data.slice(l*w,l*w+w)));
	o+=String.fromCharCode.apply(null, new Uint16Array(data.slice(l*w)));
	return o;
}

function s2ab(s) {
	var b = new ArrayBuffer(s.length*2), v = new Uint16Array(b);
	for (var i=0; i != s.length; ++i) v[i] = s.charCodeAt(i);
	return [v, b];
}

function xw_noxfer(data, cb, rABS) {
	var worker = new Worker(XW.noxfer);
	worker.onmessage = function(e) {
		switch(e.data.t) {
			case 'ready': break;
			case 'e': console.error(e.data.d); break;
			case XW.msg: cb(JSON.parse(e.data.d)); break;
		}
	};
	var arr = rABS ? data : btoa(fixdata(data));
	worker.postMessage({d:arr,b:rABS});
}

function xw_xfer(data, cb, rABS) {
	var worker = new Worker(rABS ? XW.rABS : XW.norABS);
	worker.onmessage = function(e) {
		switch(e.data.t) {
			case 'ready': break;
			case 'e': console.error(e.data.d); break;
			default: xx=ab2str(e.data).replace(/\n/g,"\\n").replace(/\r/g,"\\r"); console.log("done"); cb(JSON.parse(xx)); break;
		}
	};
	if(rABS) {
		var val = s2ab(data);
		worker.postMessage(val[1], [val[1]]);
	} else {
		worker.postMessage(data, [data]);
	}
}

function xw(data, cb, rABS) {
	var transferable = typeof Worker !== 'undefined';
	if(transferable) xw_xfer(data, cb, rABS);
	else xw_noxfer(data, cb, rABS);
}

function obteCampsXLSX(f) {
	var rABS = typeof FileReader !== 'undefined'
		&& typeof FileReader.prototype !== 'undefined'
		&& typeof FileReader.prototype.readAsBinaryString !== 'undefined';	
	var matriuActiva = [];
	var reader = new FileReader();
	var name = f.name;
	reader.onload = function(e) {
		var data = e.target.result;
		function doit() {
			try {
				var useworker = typeof Worker !== 'undefined';
				if(useworker) {
					xw(data, llegirTitolXLSX, rABS);
				} else {
					var wb;
					if(rABS) {
						wb = X.read(data, {type: 'binary'});
					} else {
						var arr = fixdata(data);
						wb = X.read(btoa(arr), {type: 'base64'});
					}
					llegirTitolXLSX(wb, 'XLSX');
				}
			} catch (e) {
				$('#dialog_carrega_dades').modal('hide');
				busy = false;
				$('#dialog_error_upload_txt').html("");
				var msg = window.lang.translate("No es pot llegir l'arxiu");
				$('#dialog_error_upload_txt').html(msg);
			}
		}

		//Comprovem  mida fitxer i si usuari loginat
		if (isRandomUser(Cookies.get('uid'))){
			if((e.target.result.length && e.target.result.length < midaFitxerRandom) ||
				(e.target.result.byteLength && e.target.result.byteLength < midaFitxerRandom)) {
				doit();
			}else{
				$('#dialog_info_upload_txt').html(window.lang.translate("La mida del fitxer supera el límit preestablert per usuaris que no han iniciat sessió (10MB)."));
				$('#dialog_info_upload').modal('show');
				drgFromMapa.removeAllFiles(true);
				busy = false;
			}
		}else if((e.target.result.length && e.target.result.length < midaFitxerRandom) ||
				(e.target.result.byteLength && e.target.result.byteLength < midaFitxerRandom))
		{
			doit();
		}else{
			$('#dialog_info_upload_txt').html(window.lang.translate("La mida del fitxer supera el límit preestablert (500MB)."));
			$('#dialog_info_upload').modal('show');
			drgFromMapa.removeAllFiles(true);
			busy = false;
		}
	};
	if (rABS)
		reader.readAsBinaryString(f);
	else
		reader.readAsArrayBuffer(f);
}

function llegirTitolXLSX(wb, type, sheetidx) {
	var matriuActiva = [];
	var sheet = wb.SheetNames[sheetidx || 0];
	if (undefined != type && type.toLowerCase() == 'xls' && wb.SSF)
		XLS.SSF.load_table(wb.SSF);
	matriuActiva = get_columns(wb.Sheets[sheet], type);
	analitzaMatriu(matriuActiva);
	return matriuActiva;
}

function get_columns(sheet, type) {
	var val, rowObject, range, columnHeaders, emptyRow, C;
	range = XLS.utils.decode_range(sheet["!ref"]);
	columnHeaders = [];
	for (C = range.s.c; C <= range.e.c; ++C) {
		val = sheet[XLS.utils.encode_cell({
			c : C,
			r : range.s.r
		})];
		if (!val)
			continue;
		columnHeaders[C] = (undefined != type && type.toLowerCase() == 'xls') ? XLS.utils
				.format_cell(val) : val.v;
	}
	return columnHeaders;
}

function checkFileRaster(file){
	var dfd = $.Deferred();
	var res = {
		formatInvalid : false,
		isShape : false
	};
	var reader = new FileReader();
	//Closure to capture the file information.
	reader.onload = (function(theFile) {
	  return function(e) {
		  var zip = new JSZip(e.target.result);
		  // that, or a good ol' for(var entryName in zip.files)
		  var extArray= [];
		  $.each(zip.files, function (index, zipEntry) {
			var ext = zipEntry.name.split('.').pop().toLowerCase();
			extArray.push(ext);
		  });
			formatInvalid = true;
			if(jQuery.inArray("shp", extArray)!=-1){
				res.isShape = true;
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("dgn", extArray)!=-1){
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("dxf", extArray)!=-1){
				envioArxiu.format = "dxf";
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("sid", extArray)!=-1){
				envioArxiu.format = "sid";
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("jpg", extArray)!=-1){
				envioArxiu.format = "jpg";
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("tif", extArray)!=-1){
				envioArxiu.format = "tif";
				res.formatInvalid = res.formatInvalid && false;
			}else if(jQuery.inArray("ecw", extArray)!=-1){
				envioArxiu.format = "ecw";
				res.formatInvalid = res.formatInvalid && false;
			}

			if (!res.formatInvalid) { // hi hso
				console.debug("Hi ha alguna extensio valida...");
				if(jQuery.inArray("tif", extArray)!=-1 || jQuery.inArray("sid", extArray)!=-1 || jQuery.inArray("jpg", extArray)!=-1){
					res.formatInvalid = (jQuery.inArray("sdw", extArray)==-1) && (jQuery.inArray("tfw", extArray)==-1) && (jQuery.inArray("jpw", extArray)==-1) && (jQuery.inArray("jgw", extArray)==-1);
					console.debug("es geotiif o mrsid o geo-jpg");
				}
				dfd.resolve(res);
			}else{
				dfd.resolve(res);
			}
	  }

	})(file);
	// read the file !
	reader.readAsArrayBuffer(file);

    return dfd.promise();
}

function miraFitxer(fitxer) {
	var dfd = $.Deferred();
	
	var obj = {}
	obj.isShape = false;
	obj.ext = fitxer.name.split('.').pop().toLowerCase();

	var arr = [ 'shp', 'xls', 'xlsx', 'dgn', 'dxf', 'zip', 'geojson', 'kml',
				'kmz', 'gml', 'xml', 'gpx', 'txt', 'csv', 'json', 'jpg', 'tif', 'sid', 'ecw' ];
	
	if (jQuery.inArray(obj.ext, arr) != -1) { // hi hso
		
		console.debug("Extensio:"+ obj.ext);
		
		if(obj.ext=="shp"){
			obj.isValid = false;
			obj.msg =  window.lang.translate("El fitxer SHP ha d'anar dins d'un ZIP juntament amb els fitxers SHX i DBF.");	
			dfd.resolve(obj);
		}else{
			//Comprovem  mida fitxer i si usuari loginat
			var randomUser = isRandomUser(Cookies.get('uid'));
			if( (randomUser && fitxer.size<midaFitxerRandom) || (!randomUser && fitxer.size < midaFitxer) ){
				
				if(obj.ext=="zip"){
					//TODO
					checkFileRaster(fitxer).then(function(res){
						obj.isValid = !res.formatInvalid;
						if(res.formatInvalid){
							obj.msg =  window.lang.translate("Els fitxers TIF, SID i JPG han d'anar dins d'un ZIP juntament amb els seus TFW, SDW, JPW/JGW corresponents.");
						}
						obj.isShape = res.isShape;
						dfd.resolve(obj);
					},function(res){
						obj.isValid = false;
						dfd.resolve(obj);
					});
				}else{
					obj.isValid = true;
					dfd.resolve(obj);
				}
				
			}else{
				obj.isValid = false;
				if(randomUser) obj.msg =  window.lang.translate("La mida del fitxer supera el límit preestablert per usuaris que no han iniciat sessió (10MB).");
				else obj.msg = window.lang.translate("La mida del fitxer supera el límit preestablert (500MB).");
				busy = false;
				dfd.resolve(obj);
			}
		}
	}else{
		obj.isValid = false;
		obj.msg = window.lang.translate("Tipus de fitxer no acceptat");
		dfd.resolve(obj);
	}
	
	envioArxiu.ext=obj.ext;
	envioArxiu.midaFitxer=fitxer.size;
	//Categoria segons mida fitxer per GA
	envioArxiu.categoriaMidaFitxer = getCategoriaMidaFitxer(fitxer.size/1000);
	
	return dfd.promise();
}

function addDropFileToMap(results) {
	if(results.layer && results.layer.serverType.indexOf(t_vis_wms_noedit)!=-1){
		loadVisualitzacioWmsLayer(results.layer);
		jQuery('#info_uploadFile').hide();
	}else{
		//Si geometries tipus marker
		if(results.layerMarker){
			
			//LIMIT GEOMETRIES: Comprovem si es vis_wms o normal
			if(results.layerMarker.serverType.indexOf(t_vis_wms)!=-1){
				loadVisualitzacioWmsLayer(results.layerMarker);
				jQuery('#info_uploadFile').hide();
			}else{
				var defer = $.Deferred();
				loadVisualitzacioLayer(results.layerMarker).then(function(results1){
					if(results1 && !jQuery.isEmptyObject(results1._layers)){
						map.fitBounds(results1.getBounds());
					}								
					jQuery('#info_uploadFile').hide();
				});					
			}
		}					
		//Si geometries tipus línies
		if(results.layerLine){
			if(results.layerLine.serverType.indexOf(t_vis_wms)!=-1){
				loadVisualitzacioWmsLayer(results.layerLine);
				jQuery('#info_uploadFile').hide();
			}else{
				var defer = $.Deferred();
				loadVisualitzacioLayer(results.layerLine).then(function(results1){
					if(results1 && !jQuery.isEmptyObject(results1._layers)){
						map.fitBounds(results1.getBounds());
					}
					jQuery('#info_uploadFile').hide();
					
				});					
			}
		}
		//Si geometries tipus polygon
		if(results.layerPolygon){
			if(results.layerPolygon.serverType.indexOf(t_vis_wms)!=-1){
				loadVisualitzacioWmsLayer(results.layerPolygon);
				jQuery('#info_uploadFile').hide();
			}else{
				var defer = $.Deferred();
				loadVisualitzacioLayer(results.layerPolygon).then(function(results1){
					if(results1 && !jQuery.isEmptyObject(results1._layers)){
						map.fitBounds(results1.getBounds());
					}
					jQuery('#info_uploadFile').hide();
					
				});					
			}
		}				
	}
	
	//En cas que no hagi retornat cap geometria com a resultat, amaguem finestra carregant
	if(!results.layer && !results.layerPolygon && !results.layerLine && !results.layerMarker){
		jQuery('#info_uploadFile').hide();
	}
	var dataPopover ={
		iduser:_UsrID
	};
	refrescaPopOverMevasDades(dataPopover);
	busy = false;
	map.spin(false);
}

function loadDefaultStyles(){
	envioArxiu.markerStyle = JSON.stringify(getMarkerRangFromStyle(defaultPunt));
	envioArxiu.lineStyle = JSON.stringify(getLineRangFromStyle(canvas_linia));
	envioArxiu.polygonStyle = JSON.stringify(getPolygonRangFromStyle(canvas_pol));
}

function addHtmlModalCarregarFitxers(){
	var dfd = $.Deferred();
	$.get("templates/modalCarregarFitxers.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);
		
		$('#dialog_carrega_dades').on('hide.bs.modal', function (event) {
			busy = false;
			if(envioArxiu.isDrag){
				drgFromMapa.removeAllFiles(true);
			}else{
				if (drgFromBoto != null) drgFromBoto.removeAllFiles(true);
			}
		});
		
		jQuery('#dialog_carrega_dades #bt_upload_cancel').on("click", function(e) {
			$('#dialog_carrega_dades').modal('hide');
			if(envioArxiu.isDrag){
				drgFromMapa.uploadFile(drgFromMapa.files[0]);	
			}else{
				drgFromBoto.uploadFile(drgFromBoto.files[0]);;
			}
		});	
		dfd.resolve();
	});
	return dfd.promise();
}

function addHtmlModalErrorUpload(){
	var dfd = $.Deferred();
	$.get("templates/modalErrorUpload.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);
		dfd.resolve();
	});
	return dfd.promise();
}

function addHtmlModalInfoUpload(){
	var dfd = $.Deferred();
	$.get("templates/modalInfoUpload.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);
		dfd.resolve();
	});
	return dfd.promise();
}

function addHtmlInterficieCarregarFitxers(){
	jQuery("#funcio_carregar_fitxers").append(
			'<div lang="ca" id="div_carrega_dades" class="div_carrega_dades" data-toggle="tooltip" title="Arrossega les teves dades sobre el mapa o fes clic aquí" data-lang-title="Arrossega les teves dades sobre el mapa o fes clic aquí"></div>'		
	);
	
	$('.div_carrega_dades').tooltip({
		placement : 'bottom',
		container : 'body'
	});	
}

function carregarModalFitxer(refrescar,businessId,name,servertype,capaEdicio){
	obreModalCarregaDades(false);
	var opcionsBoto = drOpcionsMapa;
	opcionsBoto.clickable = true;
	
		
	if (drgFromBoto == null) {
		drgFromBoto = new window.Dropzone("button#upload_file", opcionsBoto);

		drgFromBoto.on("addedfile", function(file) {
			if(!busy){
				envioArxiu.isDrag=false;
				busy = true;
				accionaCarrega(file, envioArxiu.isDrag);	
			}else{
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està processant un arxiu. Si us plau, espereu que aquest acabi."));
				$('#dialog_info_upload').modal('show');
				drgFromMapa.removeAllFiles(true);
			}
		});

		drgFromBoto.on("sending", function(file, xhr, formData) {
			console.debug("sending");
			/*if (refrescar){
				console.debug("refrescar");
				//1. Dupliquem capa
				var data = {
						uid: Cookies.get('uid'),
						mapBusinessId: url('?businessid'),
						businessId:  businessId,
						nom: name +"_duplicat",
						markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
						lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
						polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol))
				};	
				duplicateVisualitzacioLayer(data).then(function(results){
					if(results.status==='OK'){
						var value = results.results;
						
						if (value.epsg == "4326"){
							value.epsg = L.CRS.EPSG4326;
						}else if (value.epsg == "25831"){
							value.epsg = L.CRS.EPSG25831;
						}else if (value.epsg == "23031"){
							value.epsg = L.CRS.EPSG23031;
						}else{
							value.epsg = map.crs;
						}							
						if(servertype == t_wms){
							loadWmsLayer(value);
						}else if((servertype == t_dades_obertes)){
							loadDadesObertesLayer(value);
						}else if(servertype == t_xarxes_socials){
							
							var options = jQuery.parseJSON( value.options );
							if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
							else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
							else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
							
						}else if(servertype == t_tematic){
							loadTematicLayer(value);
						}else if(servertype == t_visualitzacio){
							loadVisualitzacioLayer(value);
						}							
						activaPanelCapes(true);
					}
				});
			}*/
			
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades menu', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);				
			
			if( envioArxiu.ext == "tif" || (envioArxiu.ext=="sid") || (envioArxiu.ext=="jpg") || (envioArxiu.ext=="ecw") 
					|| envioArxiu.format == "tif" || (envioArxiu.format =="sid") || (envioArxiu.format =="jpg") ){	
				
				$('#dialog_carrega_dades').modal('hide');
				formData.append("srs", envioArxiu.srid.toLowerCase());
				formData.append("format", (envioArxiu.ext== "zip" ? envioArxiu.format : envioArxiu.ext));
				formData.append("name", envioArxiu.serverName);
				jQuery("#div_uploading_txt").html('<div id="div_upload_step1" class="status_current" lang="ca">'+window.lang.translate('Processant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</span></div>');
				jQuery('#info_uploadFile').show();
				
			}else{
				formData.append("nomArxiu", file.name); 
				formData.append("tipusAcc", envioArxiu.tipusAcc); 
				formData.append("colX", envioArxiu.colX);	
				formData.append("colY", envioArxiu.colY);
				formData.append("colWKT", envioArxiu.colWKT);
				formData.append("tipusCSV", envioArxiu.tipusCSV);
				formData.append("srid", envioArxiu.srid);
				formData.append("bid", envioArxiu.bid);
				formData.append("codiCAMP", envioArxiu.codi);
				formData.append("codiType", envioArxiu.codiType);
				formData.append("geomType", envioArxiu.geomType);
				formData.append("type", envioArxiu.type);
				formData.append("camps", envioArxiu.camps);
				formData.append("campUnic", envioArxiu.campUnic);
				formData.append("ext", envioArxiu.ext);
				formData.append("markerStyle", envioArxiu.markerStyle);	
				formData.append("lineStyle", envioArxiu.lineStyle);	
				formData.append("polygonStyle", envioArxiu.polygonStyle);	
				formData.append("uid", Cookies.get('uid'));
				formData.append("mapBusinessId", url('?businessid'));
				formData.append("midaFitxer", envioArxiu.midaFitxer);
				var file = file.name.split(".");
				formData.append("serverName", file[0]);
				formData.append("uploadFile", paramUrl.uploadFile);
				formData.append("createMapFile", paramUrl.createMapFile);
				var codiUnic = getCodiUnic();
				formData.append("codiUnic", codiUnic);
				if (refrescar) formData.append("businessIdVis",businessId); 
				
				//Comencem polling...
				$('#dialog_carrega_dades').modal('hide');

				jQuery("#div_uploading_txt").html("");
				jQuery("#div_uploading_txt").html(
					'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Pujant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</span></div>'+
					'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Analitzant fitxer')+'</div>'+
					'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Creant geometries')+'</div>'+
					'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
				);					
				jQuery('#info_uploadFile').show();
				
				//Definim interval de polling en funcio de la mida del fitxer
				var pollTime = getPollTime(envioArxiu.midaFitxer);
				
				//Fem polling
				(function(){							
					poll = function(){
						$.ajax({
							url: paramUrl.polling +"pollingFileName="+ codiUnic + url('?businessid')+".json",
							dataType: 'json',
							type: 'get',
							success: function(data){
								if(data.status.indexOf("PAS2")!=-1){
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Analitzant fitxer')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
										'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Creant geometries')+'</div>'+
										'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
									);									
								}else if(data.status.indexOf("PAS3")!=-1){
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Fitxer analitzat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
										'<div id="div_upload_step4" class="status_uncheck" lang="ca">4. '+window.lang.translate('Processant la resposta')+'</div>'//+	
									);									
								}else if(data.status.indexOf("OK")!=-1){
									clearInterval(pollInterval);
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
										'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Fitxer pujat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></span></div>'+
										'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Fitxer analitzat')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step3" class="status_check" lang="ca">3. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
										'<div id="div_upload_step4" class="status_current" lang="ca">4. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
									);									
									
									//addDropFileToMap(data);					
									$.get(HOST_APP+tmpdirPolling +codiUnic + url('?businessid')+"_response.json", function(data) { 
										if(data.status.indexOf("OK")!=-1){		
											//eliminem sublayer del mapa, i recarreguem
											if (capaEdicio!=undefined){
												var layerEd=capaEdicio.layer;
												map.removeLayer(capaEdicio.layer);
												controlCapes.removeLayer(capaEdicio);	
											}
											addDropFileToMap(data,refrescar);									
										}								
									});
									
									_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades ok', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
								
								}else if(data.status.indexOf("KO")!=-1){
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									$('#dialog_error_upload_txt').html("");
									
									$.get(HOST_APP+tmpdirPolling +codiUnic + url('?businessid')+"_response.json", function(data) { 
										var msg = "[08]: " + window.lang.translate("Error durant el processament de la informació del fitxer. Comprovi que el fitxer és correcte.");
										msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
										$('#dialog_error_upload_txt').html(msg);
										$('#dialog_error_upload').modal('show');
									});
									
									_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error sense codi', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
								}else if(data.status.indexOf("ERROR")!=-1){
									console.error("Error al carregar fitxer:");
									console.error(data);
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									$('#dialog_error_upload_txt').html("");
									
									if(data.codi){
										_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error '+data.codi, envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
										
										if(data.codi.indexOf("01")!=-1){//cas 01: Exception durant el tractament del fitxer
											var msg = "[01]: " + window.lang.translate("Ha ocorregut un error inesperat durant la càrrega del fitxer.");
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("02")!=-1){//cas 02: Error durant les conversions de format del fitxer
											var msg = "[02]: " + window.lang.translate("Error durant el procés de conversió de format del fitxer. Comprovi que el fitxer és correcte.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("03")!=-1){//cas 03: OGRInfo ha donat resposta fallida
											var msg = "[03]: " + window.lang.translate("Error durant l'anàlisi de la informació del fitxer. Comprovi que el fitxer és correcte.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("04")!=-1){//cas 04: OGRInfo ha donat una excepció
											var msg = "[04]: " + window.lang.translate("Ha ocorregut un error inesperat durant l'anàlisi de la informació del fitxer.");
												$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("05")!=-1){//cas 05: OGRInfo ha tornat resposta buida
											var msg = "[05]: " + window.lang.translate("L'anàlisi de la informació del fitxer no ha tornat resultats. Comprovi el fitxer i torni a intentar-ho.");
											msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("06")!=-1){//cas 06: Accedeix a fileDefault_Error, no li ha arribat be el nom del fitxer
											var msg = "[06]: " + window.lang.translate("Problema de comunicació amb el servidor. Si us plau, torni a intentar-ho.");
											$('#dialog_error_upload_txt').html(msg);
										}else if(data.codi.indexOf("07")!=-1){//cas 07: EnviaFileReady a myUtils.jsp ha donat una excepcio
											var msg = "[07]: " + window.lang.translate("Ha ocorregut un error inesperat durant la comunicació amb el servidor. Si us plau, torni a intentar-ho.");
											$('#dialog_error_upload_txt').html(msg);
										}
									}else{
										_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades error sense codi', envioArxiu.ext+"#"+envioArxiu.categoriaMidaFitxer, 1]);
										var msg =window.lang.translate("Error en la càrrega de l'arxiu");
										msg += "<br/><br/><span style='font-weight:normal'>"+window.lang.translate("Per a més informació consultar")+": </span><a href='http://betaportal.icgc.cat/wordpress/errors_carregar_arxius/' target='_blank'>"+window.lang.translate("Errors freqüents en carregar arxius a Instamaps")+"</a>";
										$('#dialog_error_upload_txt').html(msg);
									}
									
									$('#dialog_error_upload').modal('show');
								}
							}
						});
					};
					
					pollInterval = setInterval(function(){
						poll();
					},pollTime);
					
				})();
			}
		});
		
		drgFromBoto.on('success', function(file, resposta) {
			drgFromBoto.removeAllFiles(true);
			busy = false;
			if(resposta.map){
				ActiuWMS.url = "http://betaserver.icgc.cat/geoservice/"+resposta.map;
				ActiuWMS.servidor = envioArxiu.serverName;
				ActiuWMS.layers = envioArxiu.serverName;
				ActiuWMS.epsg = undefined;
				addExternalWMS(true).then(function(success){
					jQuery('#info_uploadFile').hide();
					if(!success){
						var msg = window.lang.translate("Error en la càrrega de l'arxiu");
						$('#dialog_error_upload_txt').html(msg);
					}
				},function(error){
					jQuery('#info_uploadFile').hide();
				});
			}
		});
		
		drgFromBoto.on('error', function(file, errorMessage) {
			drgFromBoto.removeAllFiles(true);
			busy = false;
		});
	}
}
<file_sep>/geocatweb/js/geocat.mapa.url_file_omnivore.js
/**
 * 
 */

function createURLfileLayer(urlFile, tipusFile){
	
	var nomCapa = window.lang.translate("Capa URL fitxer ");
	nomCapa += tipusFile;
	var estil_do = retornaEstilaDO(t_url_file);
	
	if(typeof url('?businessid') == "string"){
		var data = {
			uid:Cookies.get('uid'),
			mapBusinessId: url('?businessid'),
			serverName: nomCapa,//+' '+ (parseInt(controlCapes._lastZIndex) + 1),
			serverType: t_url_file,
			calentas: false,
            activas: true,
            visibilitats: true,
            order: controlCapes._lastZIndex+1,
            epsg: '4326',
            imgFormat: 'image/png',
            infFormat: 'text/html',
            tiles: true,	            
            transparency: true,
            opacity: 1,
            visibilitat: 'O',
            url: urlFile,//Provar jQuery("#txt_URLJSON")
            calentas: false,
            activas: true,
            visibilitats: true,
            options: '{"tipusFile":"'+tipusFile+'","estil_do":{"radius":"'+estil_do.radius+'","fillColor":"'+estil_do.fillColor+'","color":"'+estil_do.color+'","weight":"'+estil_do.weight+'","opacity":"'+estil_do.opacity+'","fillOpacity":"'+estil_do.fillOpacity+'","isCanvas":"'+estil_do.isCanvas+'"}}'
		};
		tipusFile = t_file_topojson;
		createServidorInMap(data).then(function(results){
			if (results.status == "OK"){
//				urlFile = 'image_locations.geojson';
				if(tipusFile == t_file_geojson){
					var capaURLfile = omnivore.geojson(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer2(this, estil_do, nomCapa, results.results.businessId, urlFile, tipusFile);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    });
//				    .addTo(map);					
				}else if(tipusFile == t_file_topojson){
					var capaURLfile = omnivore.topojson(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}else if(tipusFile == t_file_wkt){
					var capaURLfile = omnivore.wkt(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}else if(tipusFile == t_file_wkt){
					var capaURLfile = omnivore.wkt(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}else if(tipusFile == t_file_kml){
					var capaURLfile = omnivore.kml(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}else if(tipusFile == t_file_gpx){
					var capaURLfile = omnivore.gpx(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}else if(tipusFile == t_file_csv){
					var capaURLfile = omnivore.csv(urlFile, null, L.FeatureGroup())
				    .on('ready', function() {
				    	constructLayer(this, estil_do);
				    })
				    .on('error', function() {
				    	console.debug("Error omnivore");
				    })
				    .addTo(map);					
				}
				
//				L.Proj.GeoJSON(capaURLfile.toGeoJSON()).addTo(map);
				
//				jQuery('#dialog_dades_ex').modal('toggle');					
//				capaURLfile.options.businessId = results.results.businessId;
//				capaURLfile.options.nom = nomCapa;
//				capaURLfile.options.tipus = t_url_file;
//				capaURLfile.options.url = urlFile;
//				capaURLfile.options.options = jQuery.parseJSON('{"tipusFile":"'+tipusFile+'"}');
//				capaURLfile.options.options.estil_do = estil_do;
//				capaURLfile.options.zIndex = controlCapes._lastZIndex+1; 
//				controlCapes.addOverlay(capaURLfile, nomCapa, true);
//				controlCapes._lastZIndex++;
//				activaPanelCapes(true);	
				
//				 map.fitBounds(capaURLfile.getBounds());
				
			}else{
				console.debug("Error omnivore llegint");
			}
		});
	}else{
		//usuari no logat, no entra mai
	}
}

function constructLayer2(capaURLfile, estil_do, nomCapa, businessId, urlFile, tipusFile){
	
	var geojsonLayer = capaURLfile.toGeoJSON();
	geojsonLayer.crs = capaURLfile.options;	
//	geojsonLayer.crs = {
//			type: 'name',
//		    properties: {
//		        'name': 'urn:ogc:def:crs:EPSG::25831'
//		      }				    			
//	};
	
	var layer = L.Proj.geoJson(geojsonLayer, {
		  'pointToLayer': function(feature, latlng) {
			  
				var geometryType = transformTipusGeometry(feature.geometry.type);
				if(geometryType == t_marker){
					var geom = L.circleMarker(latlng, estil_do);
				}else if(geometryType == t_polyline){
					var geom = L.polyline(latlng, {color: estil_do.fillColor, weight: "3", opacity: "1"});
				}else if(geometryType == t_polygon){
					var geom = L.polygon(latlng, {color: estil_do.color, fillColor: estil_do.fillColor, fillOpacity: estil_do.fillOpacity, weight: estil_do.weight});
				}
		    	    	
		    	var pp = feature.properties;
		    	var html ='<div class="div_popup_visor"><div class="popup_pres">';
		    	$.each( pp, function( key, value ) {
		    		if(isValidValue(value) && !validateWkt(value)){
		    			if (key != 'name' && key != 'Name' && key != 'description' && key != 'id' && key != 'businessId' && key != 'slotd50'){
		    				html+='<div class="popup_data_row">';
		    				var txt = value;
		    				if (!$.isNumeric(txt)) {
			    				txt = parseUrlTextPopUp(value,key);
			    				if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
			    					html+='<div class="popup_data_key">'+key+'</div>';
			    					html+='<div class="popup_data_value">'+txt+'</div>';
			    				}else{
			    					html+='<div class="popup_data_img_iframe">'+txt+'</div>';
			    				}
		    				}
		    				else {
		    					html+='<div class="popup_data_key">'+key+'</div>';
		    					html+='<div class="popup_data_value">'+txt+'</div>';
		    				}
		    				html+= '</div>';
		    			}
		    		}
		    	});	
		    	html+='</div></div>';    	
//		    					    			  
//			  
			  	feature.geometry.coordinates[0]=latlng.lat;
			  	feature.geometry.coordinates[1]=latlng.lng;
    		    return geom.bindPopup(html);
    		  }
    		}).addTo(map);	
		
		jQuery('#dialog_dades_ex').modal('toggle');					
		layer.options.businessId = businessId;
		layer.options.nom = nomCapa;
		layer.options.tipus = t_url_file;
		layer.options.url = urlFile;
		layer.options.options = jQuery.parseJSON('{"tipusFile":"'+tipusFile+'"}');
		layer.options.options.estil_do = estil_do;
		layer.options.zIndex = controlCapes._lastZIndex+1; 
		controlCapes.addOverlay(layer, nomCapa, true);
		controlCapes._lastZIndex++;
		activaPanelCapes(true);	
//		$(".layers-list").mCustomScrollbar({
//			   advanced:{
//			     autoScrollOnFocus: false,
//			     updateOnContentResize: true
//			   }           
//		});	
//		 map.fitBounds(capaURLfile.getBounds());		
		
	
}

function constructLayer(layer, estil_do){
	layer.eachLayer(function(marker) {
		
		var geometryType = transformTipusGeometry(marker.feature.geometry.type);
		if(geometryType == t_marker){
			var geom = L.circleMarker(marker._latlng, estil_do);
		}else if(geometryType == t_polyline){
			var geom = L.polyline(marker._latlngs, {color: estil_do.fillColor, weight: "3", opacity: "1"});
		}else if(geometryType == t_polygon){
			var geom = L.polygon(marker._latlngs, {color: estil_do.color, fillColor: estil_do.fillColor, fillOpacity: estil_do.fillOpacity, weight: estil_do.weight});
		}
    	    	
    	var pp = marker.toGeoJSON().properties;
    	var html ='<div class="div_popup_visor"><div class="popup_pres">';
    	$.each( pp, function( key, value ) {
    		if(isValidValue(value) && !validateWkt(value)){
    			if (key != 'name' && key != 'Name' && key != 'description' && key != 'id' && key != 'businessId' && key != 'slotd50'){
    				html+='<div class="popup_data_row">';
    				var txt=value;

    				if (!$.isNumeric(txt)) {
	    				 txt = parseUrlTextPopUp(value,key);
	    				if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
	    					html+='<div class="popup_data_key">'+key+'</div>';
	    					html+='<div class="popup_data_value">'+txt+'</div>';
	    				}else{
	    					html+='<div class="popup_data_img_iframe">'+txt+'</div>';
	    				}
    				}
    				else {
    					html+='<div class="popup_data_key">'+key+'</div>';
    					html+='<div class="popup_data_value">'+txt+'</div>';
    				}
    				html+= '</div>';
    			}
    		}
    	});	
    	html+='</div></div>';    	
    	geom.bindPopup(html);
    	layer.removeLayer(marker);
    	layer.addLayer(geom);
    	
    });
}

function loadURLfileLayer(layer) {

	var defer = $.Deferred();
	var options = jQuery.parseJSON( layer.options );
	var tipusFile = options.tipusFile;
	var estil_do = options.estil_do;
	var urlFile = layer.url;
	
	if(tipusFile == t_file_geojson){
		var capaURLfile = omnivore.geojson(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_topojson){
		var capaURLfile = omnivore.topojson(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_wkt){
		var capaURLfile = omnivore.wkt(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_wkt){
		var capaURLfile = omnivore.wkt(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_kml){
		var capaURLfile = omnivore.kml(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_gpx){
		var capaURLfile = omnivore.gpx(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}else if(tipusFile == t_file_csv){
		var capaURLfile = omnivore.csv(urlFile, null, L.FeatureGroup())
	    .on('ready', function() {
	    	constructLayer(this, estil_do);
	    })
	    .on('error', function() {
	    	console.debug("Error omnivore");
	    })
	    .addTo(map);					
	}
					
	capaURLfile.options.businessId = layer.businessId;
	capaURLfile.options.nom = layer.serverName;
	capaURLfile.options.tipus = t_url_file;
	capaURLfile.options.url = urlFile;
	capaURLfile.options.options = jQuery.parseJSON('{"tipusFile":"'+tipusFile+'"}');
	capaURLfile.options.options.estil_do = estil_do;
	capaURLfile.options.zIndex = controlCapes._lastZIndex+1; 
	controlCapes.addOverlay(capaURLfile, layer.serverName, true);
	controlCapes._lastZIndex++;
	activaPanelCapes(true);	
	return defer.promise();
}
<file_sep>/geocatweb/js/leaflet/L.IM_LegendControl.js
/**
 * L.Control.Legend control que crea el boton de la legenda y agrega la legenda al mapa
 * 
 * require /geocatweb/js/leaflet/L.IM_LegendDivControl.js
 * require /geocatonline/llibreries/js/jquery/plugins/jquery.transit.js
 */
L.Control.Legend = L.Control.extend({
	options: {
		position: 'bottomright',
		idBtn: 'dv_bt_legend',
		classNameBtn: 'leaflet-bar btn btn-default btn-sm bt_legend grisfort',
		title: 'Llegenda',
		html: '<span class="fa fa-list-alt"></span>',
		id: 'mapLegend',
		className: 'info legend visor-legend ',
		tipusllegenda: 'dinamica',
		llegendaOpt: 'tancada',
		transition: true
	},
	
	initialize: function(options){
		L.setOptions(this, options);
	
		var self = this,
		options = self.options;
		
		self.button = L.control.legenbtn({
			position: options.position,
			id: options.idBtn,
			className: options.classNameBtn,
			html: options.html,
			title: options.title,
			control: self
		}).addTo(map);
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			stop = L.DomEvent.stopPropagation,
			container = L.DomUtil.create('div', options.className);
		
		container.id = options.id;
		
		self._div = container;
		
		map.on('loadconfig', self._updateLegend, self);
		map.on('visorconfig', self._updateLegend, self);				
		map.on('activaLegendTab', self._updateTabLegend, self);
		map.on('onRedrawLegend', self._redraw, self);
			
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', L.DomEvent.preventDefault);
		
		self.hide();
		
		return container;
	},
	
	onRemove: function (map) {
		var self = this;
		map.off('loadconfig', self._updateLegend, self);
		map.off('visorconfig', self._updateLegend, self);				
		map.off('activaLegendTab', self._updateTabLegend, self);
		map.off('onRedrawLegend', self._redraw, self);
	},
	
	hideBtn: function(){
		var self = this;
		self.button.hideBtn();
	},
	
	showBtn: function(){
		var self = this;
		self.button.showBtn();
	},
	
	hide: function() {
		var _$this = $(this._div),
		y2 = _$this.height() +50;
		if(this.options.transition){
			//_$this.fadeOut({duration: 'fast'});
			_$this.hide();
		}else{
			_$this.hide();
		}
		this._redrawTabs();
	},
	
	show: function(e){
		var self = this;
		var _$this = $(self._div);
		_$this.show();
		if(self.options.transition){
			_$this.fadeIn({duration: 'fast'});
		}
		self._redrawTabs();
		
	},
	
	_updateLegend: function(config){
		var self = this;
		self.servidorsWMS=config.servidorsWMS;		
		self.legend = (config.legend? $.parseJSON( config.legend):"");		
		
		self._draw();
		$('#nav_legend').tabdrop({offsetTop: -5},'layout');
	},
		
	_redraw: function(config){
		var self = this;
		//this.servidorsWMS=config.servidorsWMS;						
		if(self.options && self.options.origenllegenda=="mapa"){
			self.legend=generallegendaMapaEdicio();
		}else{
			self.legend = (config.legend? $.parseJSON( config.legend):"");			
		}				
		$(self._div).html('');	
		self._draw();
		$('#nav_legend').tabdrop({offsetTop: -5},'layout');
	},
	
	_redrawTabs: function(){
		var self = this;
		if(!$('#nav_legend li:first-child').hasClass('dropdown') || $("#nav_legend li").length > 1){
			$('#nav_legend').tabdrop({offsetTop: -5},'layout');
		}
	},
	
	_updateTabLegend:function(obje){
		
		var self = this;
		self.fromLayer = true;
		if(obje.activo){
			$('#nav_legend a[href="#tab'+obje.id+'"]').tab('show');	
		}else{			
			var lastActive=controlCapes.getCountActiveLayers();	
			lastActive.total >0?$('#nav_legend a[href="#tab'+lastActive.lastActive+'"]').tab('show'):$('#nav_legend a[href="#tab'+obje.id+'"]').tab('show');										
		}
	},	
	
	_getLastActived:function(){	
		var self = this,
		mapLegend = self.legend;
		var lastPos={indexPos:0};
		var indexPos=0;			
		var k=0;
		
		try{
		jQuery.each(self.servidorsWMS, function(j, row){
			
			
			if (self.servidorsWMS[j].capesActiva=="true"){
				k=0;
				jQuery.each(mapLegend, function(index, row){
					k++;
					for (var i = 0; i < row.length; i++) {							
			    		if(row[i].chck){
			    			if (self.servidorsWMS[j].businessId==index){				    				
			    				lastPos.indexPos=k-1;
			    			}
			    		}
			    	}
				});
			}			
		});				
		
		if(lastPos.indexPos==-1){lastPos.indexPos=0}
			return lastPos;		
		}catch(Err){
			return lastPos;
		}	
		
	},
	
	_draw: function(){
		var self = this,
		mapLegend = self.legend,
		div = self._div;
		if (self._checkEmptyMapLegend()){
			var legendhtml = [];
			if (self.options.tipusllegenda && self.options.tipusllegenda=="estatica"){
				jQuery.each(mapLegend, function(i, row){
					var layerType=self._getNameLayer(i);
					var serverName="";
					for (var k = 0; k < row.length; k++) {
						if (row[k].chck) {
							serverName=layerType.serverName;
						}
					}
					if (row.length>=1 && undefined!=serverName && ""!=serverName){
						legendhtml.push($('<div class="visor-legend-row">'+
			    			'<div class="visor-legend-name">'+layerType.serverName+'</div>'+
			    			'</div>'+
			    			'<div class="visor-separate-legend-row"></div>'));
					}
					else if (row.length>=1 && ""!=row[0].name) {
						var name=row[0].name;
							
						legendhtml.push($('<div class="visor-legend-row">'+
				    			'<div class="visor-legend-name">'+name.substring(0,name.indexOf("("))+'</div>'+
				    			'</div>'+
				    			'<div class="visor-separate-legend-row"></div>'));
					}
					for (var i = 0; i < row.length; i++) {
			    		if(row[i].chck){
			    			if (row[i].symbol.indexOf("circle")>-1){
			    				var padding_left="0px";
			    				var midaStr = row[i].symbol.substring(row[i].symbol.indexOf("r="),row[i].symbol.indexOf("style"));
			    				midaStr=midaStr.substring(midaStr.indexOf("=")+2,midaStr.length-2);
			    				var mida=parseFloat(midaStr);
			    				if (mida>0 && mida<=6) padding_left="15px";
			    				else if (mida>6 && mida<=14) padding_left="10px";
			    				else if (mida>14 && mida<=22) padding_left="5px";
			    				legendhtml.push($('<div class="visor-legend-row">'+
					    			'<div class="visor-legend-symbol col-md-4 col-xs-4" style="padding-left:'+padding_left+'">'+row[i].symbol+'</div>'+
					    			'<div class="visor-legend-name col-md-8 col-xs-8" style="float:right;width:40%">'+row[i].name+'</div>'+
					    			'</div>'+
					    			'<div class="visor-separate-legend-row"></div>'));
			    			} else{
			    				legendhtml.push($('<div class="visor-legend-row">'+
					    			'<div class="visor-legend-symbol col-md-4 col-xs-4">'+row[i].symbol+'</div>'+
					    			'<div class="visor-legend-name col-md-8 col-xs-8" style="float:right;">'+row[i].name+'</div>'+
									'</div>'+
									'<div class="visor-separate-legend-row"></div>'));
			    			}	    			
			    		}
			    	}
			    });
				$(div).append(legendhtml);
				$(div).mCustomScrollbar();
			}
			else {
				var legendTab=[];
				var legendCont=[];
				var legendTabContent=[];
				
				
				
				legendCont.push('<div id="legend_cont">');
				legendTab.push('<div id="legend_cont"><ul id="nav_legend" class="nav nav-tabs">');
				legendTabContent.push('<div class="legendTabCont tab-content">');
				
				var index=0;
				
				var lastPos=self._getLastActived();
				
				jQuery.each(mapLegend, function(j, row){
				var layerType=self._getNameLayer(j);
				index==lastPos.indexPos?active=' active':active="";
								
				if(layerType.capesOrdre && layerType.capesOrdre.indexOf('sublayer') ==-1){
					legendTabContent.push('<div style="padding-top:10px;" class="dv_lleg tab-pane'+active+'" id="tab'+j+'">');
				}
				
				var serverName="";
				var posServerName=-1;
				for (var i = 0; i < row.length; i++) {
					if(row[i].chck || self.options.origenllegenda=='mapa'){
						if ((undefined==serverName && ""==serverName) || (undefined!=layerType.serverName && layerType.serverName!=serverName)) {
							posServerName=i;
							serverName=layerType.serverName;							
						}
						else {
							posServerName=i;
							var name=row[i].name;
							serverName=name.substring(0,name.indexOf("("));
						}
						var padding_left="";
						var textalg='left';
						if (row[i].symbol.indexOf("circle")>-1){
							padding_left="padding-left:0px";
							textalg='center';
				    		var midaStr = row[i].symbol.substring(row[i].symbol.indexOf("r="),row[i].symbol.indexOf("style"));
				    		midaStr=midaStr.substring(midaStr.indexOf("=")+2,midaStr.length-2);
				    		var mida=parseFloat(midaStr);
				    		if (mida>0 && mida<=6) padding_left="padding-left:15px";
				    		else if (mida>6 && mida<=14) padding_left="padding-left:10px";
				    		else if (mida>14 && mida<=22) padding_left="padding-left:5px";
						}
						var isWMS=false;
						if (row[i].symbol.indexOf("GetLegendGraphic")>-1){
							isWMS=true;
						}
						
						index==lastPos.indexPos?active=' active':active="";
						index==lastPos.indexPos?self.options.currentTab=j:null;	
										
						if(i==posServerName){legendTab.push('<li class="'+active+'"><a href="#tab'+j+'" data-toggle="tab">'+shortString(serverName,25)+'</a></li>');}
						
						/*if(layerType.capesOrdre && layerType.capesOrdre.indexOf('sublayer') ==-1){
							legendTabContent.push(row[i].symbol);
							legendTabContent.push('<br/>');
						}else{*/
							if(i==posServerName){legendTabContent.push('<div  class="dv_lleg tab-pane'+active+'" id="tab'+j+'">');}
							legendTabContent.push('<div class="visor-legend-row">'+
						    	'<div class="visor-legend-symbol col-md-4 col-xs-4" style="padding-top:1px;'+padding_left+'">'+row[i].symbol+'</div>');
							if (isWMS){
								legendTabContent.push('</div><div class="visor-separate-legend-row"></div>');	
							}
							else {
								legendTabContent.push('<div class="visor-legend-name col-md-8 col-xs-8" style="text-align:'+textalg+' ;padding-top:5px;">'+row[i].name+'</div>'+
						    	'</div><div class="visor-separate-legend-row"></div>');	
							}
										
							if(i==row.length-1){legendTabContent.push('</div>');}			
						//}
					}
				}
				index=index+1;
				if(layerType.capesOrdre && layerType.capesOrdre.indexOf('sublayer') ==-1){
					legendTabContent.push('</div>');
				}
			    });
				
				legendTab.push('</ul>');
				legendTabContent.push('</div></div>');
				
				$(div).append(legendTab.join(""));
				$(div).append(legendTabContent.join(""));
				$('#nav_legend').tabdrop({offsetTop: -5},'layout');
			
				$("#nav_legend").on('click', function(event){ //enables click event
					$("#nav_legend .dropdown-menu").toggle();			
				});
				$("#nav_legend .dropdown-menu a").on('click', function(event){
					var href = $(location).attr('href');
					href=href.substring(0,href.indexOf("#"));
				    var objecthref=event.target.href;
				    objecthref= objecthref.replace(href+'#tab',"");
				    $('#nav_legend a[href="#tab'+objecthref+'"]').tab('show');
				});
				
				$(div).on('click', function(e){			
					changeWMSQueryable(false);
				});	
				 
				$(div).on('mouseout', function(e){				
					changeWMSQueryable(true);
				});	
								
				$('.dv_lleg').on('click', function(e){			
					aturaClick(e);
				});	
								
				$('.legendTabCont').on('click', function(e){			
					aturaClick(e);
				});	
								
				$('.legendTabCont').on('mousedown', function(e){			
					aturaClick(e);
				});	
			
				$(' #nav_legend a[data-toggle="tab"]').on('shown.bs.tab', self._activaCapaTab.bind(self));
			}
		}
	},
	
	_activaCapaTab: function(e){
		var self = this;
		self._redrawTabs();
		if(!self.fromLayer){
			var idLayer=$(e.target).attr('href').replace('#tab','');
			$( "#input-"+idLayer).attr("checked")==undefined ? $("#input-"+idLayer).click():null;
		}else{
			self.fromLayer = false;
		}
	},
	
	_getNameLayer:function(idLayer){		
		var self = this;
		servidorsWMS = self.servidorsWMS;
		var layerType={};
		if(typeof servidorsWMS === "string" ){servidorsWMS = [servidorsWMS]};
		$.each(servidorsWMS, function(i, row){			
				if(row.businessId==idLayer){
					layerType.serverName=row.serverName.replace('##1','');
					layerType.capesOrdre=row.capesOrdre;

				}						
		});	

	if(!layerType.serverName && getModeMapa()){
		
		layerType=obteLListatCapesEditor(idLayer);
	}	
		
		
		return layerType;		
	},	

	_checkEmptyMapLegend: function(){
		var trobat = false,
		self = this,
		mapLegend = self.legend;
		if(typeof mapLegend === "string" ){mapLegend = [mapLegend]};
		$.each(mapLegend, function(i, row){
	    	for (var i = 0; i < row.length && !trobat; i++) {
	    		if(row[i].chck){
	    			trobat = true;
	    		}
	    	}
		});
		return trobat;
	},
});

L.control.legend = function(options){
	return new L.Control.Legend(options);
};<file_sep>/geocatweb/js/geocat.galeria-2.0.0.js
/**
 * require Jquery
 * require Handelbars
 */
;(function(global, $){
	
	var Galeria = function(options){
		return new Galeria.init(options);
	}
	
	var pageGaleria = 0;
	var	userList;
	var loading = false;
	var searchString;
	var businessIds = [];
	var mapsGalery = [];
	var codiUsuari;
	var tipusEntitat;
	var busy=false;
	
	//TODO definir los templates dentro del modulo
	var source = $("#galeria-template").html();
	var template = Handlebars.compile(source);
	
	var sourcePublic = $("#galeriaPublic-template").html();
	var templatePublic = Handlebars.compile(sourcePublic);

	var sourceAdmin = $("#galeriaAdmin-template").html();
	var templateAdmin = Handlebars.compile(sourceAdmin);
	
	var sourceAplicacions = $("#aplicacions-template").html();
	var templateAplicacions = Handlebars.compile(sourceAplicacions);
	
	var sourceConfigurades = $("#configurades-template").html();
	var templateConfigurades = Handlebars.compile(sourceConfigurades);
	
	Handlebars.registerHelper('if_eq', function(a, b, opts) {
	    if(a == b) // Or === depending on your needs
	        return opts.fn(this);
	    else
	        return opts.inverse(this);
	});
	
	var galeriaOptions = { //default instamaps
		tipusApp: 1,
		isGeolocal: false,
		publica: true
	};
	
	Galeria.prototype = {
		
		getNumMaps: function(){
			var self = this;
			var data = {
				tipusApp: self.options.tipusApp	
			}
			return $.ajax({
				url: paramUrl.getNumGaleria,
				dataType: 'jsonp',
				data: data
			}).promise();	
		}, 
		
		showTabs: function(){
			var self = this;
			$('#tabs_links').removeClass('hide');
		},
		
		hideTabs: function(){
			var self = this;
			$('#tabs_links').addClass('hide');
		},
		
		drawGaleria: function(data){
			var self = this;
			if(self.options.publica){
				self.drawPublic();
			}else{
				self.drawPrivate(data);
				if(self.options.isGeolocal){
					self.drawGeoLocal();
				}
			}
		},
		
		updateTotal: function(){
			var self = this;
			if ($('.new_map').is(':visible')){
				self.escriuResultats(userList.visibleItems.length-1);
			}else{
				self.escriuResultats(userList.visibleItems.length);
			}
		},
		
		escriuResultats: function(total){
			$('.sp_rs_maps').html(total);
			$('.sp_total_maps').hide();
			$('.sp_rs_maps').show();
			if(total === 0){
				$('.msg_no_result').removeClass('hide').show();
			}else{
				$('.msg_no_result').hide();
			}
		},
		
		escriuTotal: function(){
			$('.sp_total_maps').show();
			$('.sp_rs_maps').hide();
		},
		
		updateResultats: function(){
			var total=(parseInt($('.sp_rs_maps').html()) -1);
			$('.sp_rs_maps').html(total);
			$('.sp_total_maps').hide();
			$('.sp_rs_maps').show();
		}, 

		privateSortFunction: function(a, b, options)
		{

			var aName = a.values()['nomAplicacioSort'];
			var bName = b.values()['nomAplicacioSort'];
			var ret = 0;
			if("" == aName && "" != bName)
				ret = -1;
			else if("" != aName && "" == bName)
				ret = 1;
			else
			{
			
				options.desc = options.order == "desc" ? true : false;
				ret = userList.helpers.naturalSort(a.values()[options.valueName], b.values()[options.valueName], options);
			}

			return ret;

		},

		shouldShowNoViewerModal: function(hasOptions, name)
		{

			if(!hasOptions)
			{
				
				$('#dialog_noViewer').modal('show');
				$('#dialog_noViewer .nom_mapa').text(name);

			}

			return !hasOptions;

		},

		privateClicked: function(event, caller)
		{

			event.preventDefault();
			event.stopImmediatePropagation();
			var $this = caller;
			if(!this.shouldShowNoViewerModal($this.parent().data("hasoptions"), $this.parent().data("nom")))
			{

				var appbusinessid = $this.parent().data("businessid");
				var urlMap = paramUrl.visorPage+"?businessid="+appbusinessid;
				if ($.trim($this.parent().data("idusr")) != ""){
					urlMap += "&id="+$this.parent().data("idusr");
				}
				_gaq.push(['_trackEvent', 'galeria privada', tipus_user+'veure mapa']);
				window.open(urlMap);

			}

		},
		
		drawPrivate: function(results){
			var self = this;
			$('#loadingGaleria').hide();
			
			$('#galeriaSort #obtenirUrlPublica').show();
			
			results.results = jQuery.map( results.results, function( val, i ) {
				///val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";
			
				try{
					
					var data;
					val.dataActualitzacio?data=val.dataActualitzacio:data=val.dataPublicacio;
					
					var d1=new Date(data);
					var d = new Date();
					d.setFullYear(2016, 11, 22);				
					if(d1 > d){
						val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".png";					
					}else{					
						val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";
					}
									
				}catch(err){	
					
					
					val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";				
				}
			
			
				
				if (val.options){
					val.options = $.parseJSON(val.options);	
				}
				val.uid=Cookies.get('uid');
				val.convidats=val.convidats;	
				val.data =  new Date(val.dataPublicacio).toLocaleDateString();
				return val;
			});
			var html = template(results);
			$('#galeriaSort .list').append(html);	
			//Search function
			var optionsSearch = {
				valueNames: [ 'nomAplicacioSort','dataPublicacio', 'rankSort' ],
				page:1000,
				sortFunction: self.privateSortFunction
			};
			$('#sortbyuser').attr("style","display:none;");
			userList = new List('galeriaSort', optionsSearch);
					
			$('input.search.form-control').on('keyup', function(event){
				self.updateTotal();
			});					
			
			$('.new_map').on('click', function(event){
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'fer mapa'/*, 'acquisition'*/]);
				window.location.href = paramUrl.mapaPage;
			});
			
			if(Cookies.get('tipusEntitat') == TIPUS_AOC){
				$('.btn-danger').hide();
			}
			
			$('#galeriaRow').on('click', '.btn.btn-danger', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				$('#dialgo_delete').modal('show');
				$('#dialgo_delete .nom_mapa').text($this.data("nom"));
				$('#dialgo_delete .btn-danger').data("businessid", $this.data("businessid"));
				$('#dialgo_delete .btn-danger').data("idusr", $this.data("idusr"));
			});

			$('#galeriaRow').on('click', '.descAplicacio', function(event){
				self.privateClicked(event, $(this));
			});
			
			
			$('#dialgo_delete .btn-danger').on('click', function(event){
				var $this = $(this);
				var data = {
					businessId: $this.data("businessid"),
					uid: Cookies.get('uid')
				};
				deleteMap(data).then(function(results){
					if (results.status == "OK"){
						$('#'+$this.data("businessid")).remove();
						$('#dialgo_delete').modal('hide');
						_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'esborrar mapa'/*, 'acquisition'*/]);
						self.updateResultats();
						
						var data2 = {
							businessId: $this.data("businessid"),
							metode: "rmGaleria"
						};
						deleteImageGaleria(data2).then(function(results){
							
						});
						
						if($this.data("idusr")){
							var data3 = {
								businessId: $this.data("businessid"),
								entitatUid: $this.data("idusr"),
								metode: "deleteWMSfromMap"
							};
							
							createMapToWMS(data3).then(function(results){});
						}
					}
				});
			});
						
			$('#galeriaRow').on('click', '.btn.btn-warning', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				var urlMap = paramUrl.mapaPage+"?businessid="+$this.data("businessid");
				if ($this.data("colaboracio")) {
					urlMap = urlMap +"&mapacolaboratiu=si";
					_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'editar mapa','col.laboratiu']);
				}	
				else _gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'editar mapa','no col.laboratiu']);
				window.location.href = urlMap;
			});
			
			$('#galeriaRow').on('click', '.btn.btn-success', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);

				$('#dialgo_colaborate').data('businessid', $this.data("businessid")).modal('show');
				
				if ($this.data("title")!=undefined) {
					var idConvidats="#convidats_"+$this.data("businessid");
					var data1 = {
						businessId: $this.data("businessid"),
						uid: Cookies.get('uid')
					}
					getConvidatsByBusinessId(data1).then(function(results){
						for (var j=1;j<11;j++){ //Netejem els camps dels convidats
							$('#convidats'+j).val("");
							$('#convidats'+j).prop('disabled',false);
							$('#convidats'+j).attr("style","margin-bottom:3px;width:88%;");
							$('#convidats'+j+"_remove").attr("style","display:none;");
							$('#convidats'+j+"_remove").on('click', function(event){
								event.preventDefault();
								event.stopImmediatePropagation();
								var id=event.target.attributes.id.value;
								var idC=id.toString().substring(0,10);
								var data = {
									convidatEsborrar: $('#'+idC).val(),
									businessId: $('#dialgo_colaborate').data('businessid'),
									uid: Cookies.get('uid')
								}
								deleteConvidatByBusinessId(data).then(function(results2){
									if (results2.status=="OK"){
										alert( window.lang.window.lang.translate("Col·laborador ")+$('#'+idC).val()+window.lang.translate(" esborrat"));
										$('#'+idC).val("");
										$('#'+idC).prop('disabled',false);
										$('#'+idC).attr("style","margin-bottom:3px;width:88%;");
										$('#'+idC+"_remove").attr("style","display:none;");										
									}				
								});
							});
						}
						if (results.results!=null) {
							var convidatsJson=$.parseJSON(results.results);
							var jsonObj = [];
							jQuery.map( convidatsJson, function( val, i ) {
								var conv='#convidats'+(i+1);
								var convR='#convidats'+(i+1)+"_remove";	
								if (val.validat=="S") {
									$(conv).val(val.email);
									$(conv).prop('disabled', true);
									var item = {};
							        item ["email"] = val.email;
							        jsonObj.push(item);
							        $(convR).attr("style","display:none;");
								}
								else {
									$(conv).val(val.email);
									$(conv).prop('disabled', true);
									$(conv).attr("style","background-color:#d9534f;opacity:0.85;margin-bottom:3px;width:88%;");
									var item = {};
							        item ["email"] = val.email;
							        jsonObj.push(item);
							        $(convR).attr("style","display:block;");
								}					
							});		
						}
					});
					
					$('#businessIdConvidar').val($this.data("businessid"));
				}
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'preconvidar']);
			});
			
			$('#galeriaRow').on('click', '.btn.btn-primary', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				if(!self.shouldShowNoViewerModal($this.parent().parent().data("hasoptions"), $this.parent().parent().data("nom")))
				{
				
					var urlMap = 'http://'+DOMINI+paramUrl.visorPage+'?businessid='+$this.data("businessid");
					if ($.trim($this.data("idusr")) != ""){
						urlMap += "&id="+$this.data("idusr");
					}
					shortUrl(urlMap).then(function(results){
						$('#urlMap').val(results.id);
					});
					$('#urlVisor').attr("href", urlMap);
					$('#iframeMap').val('<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+urlMap+'&embed=1" ></iframe>');
					$('#dialgo_url_iframe').modal('show');
					_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'enllaça mapa', 'referral', 1]);

				}

			});
			
			$('#galeriaRow').on('click', '.caption.descAplicacio', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				var appbusinessid = appbusinessid = $this.parent().data("businessid");
				var urlMap = paramUrl.visorPage+"?businessid="+appbusinessid;
				if ($.trim($this.data("idusr")) != ""){
					urlMap += "&id="+$this.data("idusr");
				}
				_gaq.push(['_trackEvent', 'galeria privada', tipus_user+'veure mapa']);
				window.open(urlMap);
			});
			
			//Change visibility
			$('#galeriaRow').on('click', '.btn.btn-visibility', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				
				var visibilitatAntiga="P";
				var idPriv="#privacitat_"+$this.data("businessid");
				
				if ($(idPriv).attr("class") == "glyphicon glyphicon-eye-open" ) visibilitatAntiga="O";				
				
				var visibilitatNova="";
				var textVisibilitatNova="";
				if (visibilitatAntiga=="P") {
					visibilitatNova="O";
					textVisibilitatNova="public";
				}
				else {
					visibilitatNova="P";
					textVisibilitatNova="privat";
				}
				
				var data1 = {
						businessId: $this.data("businessid"),
						uid: Cookies.get('uid'),
						visibilitat: visibilitatNova
				};
				updateMapVisibility(data1).then(function(results){
					if (results.status=="OK") {
						if (visibilitatAntiga=="P") {
							$(idPriv).attr("class", "glyphicon glyphicon-eye-open");
							$this.data("title", window.lang.translate("El mapa és visible a la galeria pública"));
							//$this.attr('title', window.lang.translate("El mapa és visible a la galeria pública")).tooltip('fixTitle').tooltip('show');
						}
						else {
							$(idPriv).attr("class", "glyphicon glyphicon-eye-close");
							$this.data("title",window.lang.translate("El mapa només és visible a la teva galeria privada"));
							//$this.attr('title', window.lang.translate("El mapa només és visible a la teva galeria privada")).tooltip('fixTitle').tooltip('show');
							
						}
					}
					else alert(window.lang.translate("No ha sigut possible canviar la visibilitat del mapa"));
				});
				
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'visibilitat',textVisibilitatNova]);
				
			});			

			$('.thumbnail').hover(function(){
				var descAplicacio = $(this).find(".descAplicacio");
				descAplicacio.fadeIn(500);
				if (descAplicacio.find(".starwarsbody").text().length > 160){
					descAplicacio.find(".starwarsmain").addClass('starwars');
					descAplicacio.find(".starwarsbody").addClass('starwarscontent');
				}
				return false;	
			}, function(){
				$(this).find(".descAplicacio").fadeOut();
				return false;	
			});
			
			$('#dialgo_colaborate #convidar').on('click', function(event){
				var businessId= $('#dialgo_colaborate').data('businessid');
				var urlMap = HOST_APP+paramUrl.visorPage+'?businessid='+businessId;
				var contingut= window.lang.translate("Et convido a col&#183;laborar en el mapa ")+"<span style='font-weight:bold'>"+$('#nomAplicacioSort_'+businessId).val()+"</span>"+ window.lang.translate(" d'Instamaps (creat per ")+$('#userAplicacio_'+businessId).val()+window.lang.translate(" ). Clica a l'enllaç per accedir-hi. Hauràs de registrar-te si no ho has fet encara.")+"<br/>";
				contingut=htmlentities(contingut)+urlMap;
				var to = "";
				var idConv="#convidats_"+businessId;
				var convidats=$(idConv).val();
				var totalConv=0;
				for (var i=1;i<11;i++){
					if ($('#convidats'+i) && $('#convidats'+i).val()!="" ) {
						var convidat=$('#convidats'+i).val();
						if (convidats.indexOf(convidat)!=-1) {
							if ($('#convidats'+i).prop("disabled")!=true) alert("Aquest mail "+convidat+" ja el tens afegit com a col·laborador");
						}
						else {
							if ($('#convidats'+i).prop("disabled")!=true)
							{
								if (to!="")	to=to+","+$('#convidats'+i).val();
								else to=to+$('#convidats'+i).val();
							}

							totalConv++;
							var data = {
								uid: Cookies.get('uid'),
								to:to,
								subject:window.lang.translate('Mapa col&#183;laboratiu a Instamaps. Invitaci&oacute;'),
								content: contingut,
								esColaboratiu: 'S',
								businessId: businessId
							};
							sendMail(data).then(function(results){
								if (results.status=="OK") {
									$('#dialgo_colaborate').modal('hide');
								}
								else alert(window.lang.translate("Hi ha hagut algun problema amb la tramesa dels correus electrònics"));
							});
						}
					}
				}
				
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'convidar',totalConv]);
				
			});
			
			$('#galeriaSort #obtenirUrlPublica').on('click', function(event){
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'obtenir URL galeria pública']);
				var urlGaleriaUsuari = "http://www.instamaps.cat/"+paramUrl.galeriaPage.substring(1,paramUrl.galeriaPage.length)+"?user="+Cookies.get('uid');
				
				$('#urlPublicaLlarga').val(urlGaleriaUsuari);
				shortUrl(urlGaleriaUsuari).then(function(results){
					$('#urlPublicaCurta').val(results.id);
				});
				$('#dialog_public_url').modal('show');
			});
			
			$('#typesTabs a[href="#galeriaTab"]').on('click',function(){
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'accés galeria de mapes']);
			});
			
			$('#typesTabs a[href="#aplicacionsTab"]').on('click',function(){
				_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'accés aplicacions']);
			});
			
			//Duplicate mapa
			$('#galeriaRow').on('click', '.btn#btn-duplicate', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				$('#dialgo_duplicar_mapa').data('businessid', $this.data("businessid"));
				$('#dialgo_duplicar_mapa #nomMapaDuplicar').val($this.data("nomaplicacio")+"_duplicat");
				busy=true;
				$('#infoDuplicar').attr("style","display:none;");
				$('#dialgo_duplicar_mapa #cancelarBoto').html("Cancel·lar");
				$('#dialgo_duplicar_mapa #cancelarBoto').attr("class","btn btn-default");
				$('#dialgo_duplicar_mapa #cancelarBoto').removeAttr("disabled");
				$('#dialgo_duplicar_mapa #duplicarBoto').attr("style","display:inline");	
				$('#infoText').attr("style","display:none;");
				$('#loadingGaleria_duplicate').attr("style","display:none");
				$('#dialgo_duplicar_mapa').modal('show');
			});
			
			$('#dialgo_duplicar_mapa #duplicarBoto').on('click', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				self.duplicateMap();
						
			});
		},
		
		drawPublic: function(){
			var self = this;
			$('#galeriaSort #obtenirUrlPublica').hide();
			
			$('.cleansort').on('click', function(){
				userList.sort('rankSort', { order: "desc" });
			});
			
			var data = {};
			data.tipusApp = self.options.tipusApp;
			if(typeof Cookies.get('uid') !== "undefined"){
				data = {uid: Cookies.get('uid')};
			}
				
			var delay = (function(){
				  var timer = 0;
				  return function(callback, ms){
				    clearTimeout (timer);
				    timer = setTimeout(callback, ms);
				  };
			})();
			
			$('input.search.form-control').on('keyup', function(event){
				var q = $(this).val();
				q = $.trim(q);
				if(q != "" && q.length >= 3 && (typeof url('?user')== "undefined")){
					if (userList.size() < $('.sp_total_maps').text()){
						delay(function(){
							loading = true;
							$('#loadingGaleria').show();
							if (userList && userList.searched){
				    			searchString = userList.searchString;
				    			searchString = $.trim(searchString);
				    			//userList.search();
				    		}
							var searchdata = {q: q.toLowerCase()};
							searchdata.tipusApp = self.options.tipusApp;
							searchGaleriaMaps(searchdata).then(function(results){
								self.pintaGaleria(results);
								loading = false;
								if (searchString && searchString != ""){
									userList.search(searchString);
									searchString = null;
								}
							});
							
					    }, 400 );
					}	
				}else if ((typeof url('?user') == "string")){
					delay(function(){
						loading = true;
						$('#loadingGaleria').show();
						if (userList && userList.searched){
			    			searchString = userList.searchString;
			    			searchString = $.trim(searchString);
			    			//userList.search();
			    		}
						var searchString2 = $.trim(q.toLowerCase());
						var searchdata = {user: url('?user'),q: searchString2};
						searchdata.tipusApp = self.options.tipusApp;
						searchGaleriaMapsByUser(searchdata).then(function(results){
							if(searchString2 && searchString2 != ""){
								self.pintaGaleriaMapsByUser(results, searchString);
							}else{
								self.pintaGaleriaMapsByUser(results, null);
							}
						});
					 }, 400 );
				}
				else if (q == ""){
					self.escriuTotal();
				}
			});
			
			$('#geoRss').on('click', function(event){
				_gaq.push(['_trackEvent', 'galeria publica', tipus_user+'rss']);
			});
			
			$('#galeriaSort > button.sort').on('click',function(event){
				if (userList && !userList.searched){
					var that = $(this);
					data.field = that.data('sort');
					data.ordre = 'asc';
					if(that.hasClass('asc')){
						data.ordre = 'desc';
					}
					loading = true;
					data.tipusApp = self.options.tipusApp;
					loadPublicGaleria(data).then(function(results){
						var sort = self.getOrderGaleria();
						$('#loadingGaleria').show();
						self.pintaGaleria(results);
						loading = false;
						self.reorderGaleria(sort);
					});
				}
			});
			
			//cargar mapas
			if(typeof url('?q') == "string"){
				var searchString = url('?q');
				searchString = $.trim(searchString);
				if(searchString != "" && searchString.length >= 3){
					$('#galeriaSort>div>input').val(searchString);
					var searchdata = {q: searchString.toLowerCase(), page: pageGaleria};
					searchdata.tipusApp = self.options.tipusApp;
					searchGaleriaMaps(searchdata).then(function(results){
						if(results.results.length > 0){
							self.pintaGaleria(results);	
						}
						loading = false;
						if (searchString && searchString != "" && userList){
							userList.search(searchString);
						}
						data.tipusApp = self.options.tipusApp;
						loadPublicGaleria(data).then(function(results){
							self.pintaGaleria(results);
							if (searchString && searchString != ""){
								userList.search(searchString);
								searchString = null;
							}
						});
					});
				}else{
					data.tipusApp = self.options.tipusApp;
					loadPublicGaleria(data).then(function(results){
						self.pintaGaleria(results);
					});
				}
			}else if(typeof url('?user') == "string"){
				var searchString = url('?user');
				searchString = $.trim(searchString);
				var searchString2 = url('?q');
				searchString2 = $.trim(searchString2);
				$('#galeriaSort>div>input').val(searchString);
				var searchdata = {user: searchString, q:searchString2.toLowerCase(), page: pageGaleria};
				searchdata.tipusApp = self.options.tipusApp;
				searchGaleriaMapsByUser(searchdata).then(function(results){
					if(searchString2 && searchString2 != ""){
						self.pintaGaleriaMapsByUser(results, searchString2);
					}else{
						self.pintaGaleriaMapsByUser(results, null);
					}
				});			
			}else{
				data.tipusApp = self.options.tipusApp;
				loadPublicGaleria(data).then(function(results){
					self.pintaGaleria(results);
				});
			}
			
			$(window).scroll(function(){
			    if ($(window).scrollTop() == $(document).height() - $(window).height()){
			    	if (!loading){
			    		if(userList && !userList.searched){
				    		if (userList.size() < $('.sp_total_maps').text()){
				    			loading = true;
				    			pageGaleria++;
				    			var sort = self.getOrderGaleria();
				    			$('#loadingGaleria').show();
			    				var data = {};
								if(typeof Cookies.get('uid') !== "undefined"){
									data = {uid: Cookies.get('uid')};
								}
								data.page = pageGaleria;
								data.ordre = sort.order;
								data.field = sort.sortField;
								data.tipusApp = self.options.tipusApp;
								loadPublicGaleria(data).then(function(results){
									self.pintaGaleria(results);
									loading = false;
									self.reorderGaleria(sort);
								});
			    			
				    		}
			    		}
			    	}
				}
			});
		},
		
		drawGeoLocal: function(){
			var self = this;
			self.showTabs();
			
			//cambiar el footer
			$('footer div.container span').text("InstaMaps.Geolocal");
			
			getUserData(Cookies.get('uid')).then(function(results){
				loadAplicacionsUser().then(function(results1){
					codiUsuari = Cookies.get('uid');
					tipusEntitat = Cookies.get('tipusEntitat');
					self.pintaGaleriaAplicacions(results1, tipusEntitat);
					getConfiguradesUser({codiUsuari: codiUsuari}).then(function(results){
						self.pintaGaleriaConfigurades(results);
					});
				});
			});
		}, 
		
		pintaGaleriaAplicacions: function(results, tipusEntitat){
			var self = this;
			var html = templateAplicacions({results: results[tipusEntitat]});
			$('#AplicacionsRow .list').append(html);
			$('#AplicacionsRow').on('click', '.btn.btn-warning' ,function(event){
				var urlMap = $(this).data('url');
				if (!urlMap){
					var editor = $(this).data('editor');
					if(editor){
						editor = editor.split("|");
						urlMap = paramAplications[editor[0]].editor + editor[1]
					}
				}			
				//usar el cookie token	
				urlMap += Cookies.get('uid')+"&token="+Cookies.get('token');
				if(urlMap.indexOf("EdCarrerer") != -1){
					urlMap += "&muniIne="+Cookies.get('uid').substring(1); 
				}
				window.open(urlMap);	
			});
		}, 
		
		pintaGaleriaConfigurades: function(results){
			var self = this;
			var configurades = $.map(results,function(val, i){
				if (val.tipusAplicacio.businessId == "at" || 
					val.tipusAplicacio.businessId == "par" ||
					val.tipusAplicacio.businessId == "ics"){
					return val;
				}
			});
			var html = templateConfigurades({results: configurades});
			$('#AplicacionsRow .list').append(html);
			
			$('#AplicacionsRow').on('click', '.btn.btn-success' ,function(event){
				var urlMap = $(this).data('url');
				window.open(urlMap);
			});
			
			$('#AplicacionsRow').on('click', '.btn.btn-danger', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				$('#dialgo_delete_aplicacio').modal('show');
				$('#dialgo_delete_aplicacio .nom_mapa').text($this.data("nom"));
				$('#dialgo_delete_aplicacio .btn-danger').data("businessid", $this.data("businessid"));
				$('#dialgo_delete_aplicacio .btn-danger').data("idusr", $this.data("idusr"));
				var eliminar = $(this).data('eliminar');
				eliminar = eliminar.split("|");
				var urlMap = "";
				switch (eliminar[0]){
					case 'ics': 
						urlMap = paramAplications.incasol.eliminar;
						break;
					case 'at':
						urlMap = paramAplications.atles.eliminar;
						break;
					case 'par':
						urlMap = paramAplications.infoparcela.eliminar;
						break;
				}
				//usar el cookie token
				urlMap += eliminar[1] + "&token="+Cookies.get('token');
				$('#dialgo_delete_aplicacio .btn-danger').data("url", urlMap);
			});
			
			$('#dialgo_delete_aplicacio .btn-danger').on('click', function(event){
				var $this = $(this);
				deleteAplicacionsGeolocal($this.data("url")).then(function(results){
					if (results.status == "OK"){
						$('#'+$this.data("businessid")).remove();
						$('#dialgo_delete_aplicacio').modal('hide');
						_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'esborrar aplicacio']);
					}
				});
			});
			
		}, 
		
		reorderGaleria: function(sort){
			var self = this;
			if (sort.order == "asc"){
				userList.sort(sort.sortField, { order: "asc" });
			}else if(sort.order == "desc"){
				userList.sort(sort.sortField, { order: "desc" });
			}
		}, 
		
		getOrderGaleria: function(){
			var selft = this;
			var asc = $('#galeriaSort > button.sort.asc');
			var desc = $('#galeriaSort > button.sort.desc');
			var sort = {};
			if (asc.length > 0){
				var btn = asc[0];
				var sortField = $(btn).data('sort');
				sort.sortField = sortField;
				sort.order = "asc";
			}else if(desc.length > 0){
				var btn = desc[0];
				var sortField = $(btn).data('sort');
				sort.sortField = sortField;
				sort.order = "desc";
			}
			return sort;
		}, 
		
		pintaGaleria: function(results){
			var self = this;
			$('#loadingGaleria').hide();
			results.results = jQuery.map( results.results, function( val, i ) {
				if($.inArray(val.businessId, businessIds) == -1){
					businessIds.push(val.businessId);
					//val.thumbnail = paramUrl.urlgetMapImage+ "&request=getGaleria&update=false&businessid=" + val.businessId;
					val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";
					
					
					try{
						
						var data;
						val.dataActualitzacio?data=val.dataActualitzacio:data=val.dataPublicacio;
						
						var d1=new Date(data);
						var d = new Date();
						d.setFullYear(2016, 11, 22);				
						if(d1 > d){
							val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".png";					
						}else{					
							val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";
						}
										
					}catch(err){	
						
						
						val.thumbnail = HOST_APP+"galeria/"+ val.businessId+".jpeg";				
					}
					
					
					if (val.options){
						val.options = $.parseJSON(val.options);	
					}
					if (isDefaultMapTitle(val.nomAplicacio)){
						val.rank = -1;
					}
					var autor = val.entitatUid;
					val.entitatUid = autor.split("@")[0];
					val.data =  new Date(val.dataPublicacio).toLocaleDateString();
					var urlMap = HOST_APP+paramUrl.visorPage+"?businessid="+val.businessId;		
					var nomApp=val.nomAplicacio;
					if (undefined!=nomApp){
						var nomIndexacio=nomApp;			
			        	(nomIndexacio.length > 100)?nomIndexacio=nomIndexacio.substring(0,100):nomIndexacio;			
			        	nomIndexacio= encodeURI(nomIndexacio);
						urlMap += "&title="+nomIndexacio;
					}
					val.generatedScript=generarScriptMarkupGoogle(urlMap,val.nomAplicacio,val.thumbnail,autor,val.dataPublicacio,val.description);
					mapsGalery.push(val);
					return val;
				}else{
					return null;
				}
			});
			
			results.results = mapsGalery;
			
			results.results.sort(function(a,b) { 
	            return parseFloat(a.rank) < parseFloat(b.rank) 
			});
			
			if (results.admin == "OK"){
				var html = templateAdmin(results);
			}else{
				var html = templatePublic(results);
			}
			
			
				
			$('#galeriaSort .list').html(html);						
			
			$('#galeriaRow').on('click', '.btn.btn-success', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				event.stopImmediatePropagation();
				var $this = $(this);
				var appbusinessid = $this.data("businessid");
				var nomApp=$this.data("nomapp");
				if (!appbusinessid){
					appbusinessid = $this.parent().data("businessid");
				}
				var urlMap = paramUrl.visorPage+"?businessid="+appbusinessid;
				if ($.trim($this.data("idusr")) != ""){
					urlMap += "&id="+$this.data("idusr");
					
				}
				if (undefined!=nomApp){
					var nomIndexacio=nomApp;			
		        	(nomIndexacio.length > 100)?nomIndexacio=nomIndexacio.substring(0,100):nomIndexacio;			
		        	nomIndexacio= encodeURI(nomIndexacio);
					urlMap += "&title="+nomIndexacio;
				}
				
				_gaq.push(['_trackEvent', 'galeria publica', tipus_user+'veure mapa']);
				//_kmq.push(['record', 'veure mapa', {'from':'galeria publica', 'tipus user':tipus_user}]);
				window.open(urlMap);
			});
			
			$('#galeriaRow').on('click', '.btn-acctions .btn.btn-primary', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				var urlMap = 'http://'+DOMINI+paramUrl.visorPage+'?businessid='+$this.data("businessid");
				if ($.trim($this.data("idusr")) != ""){
					urlMap += "&id="+$this.data("idusr");
				}
				//$('#urlMap').val(urlMap);
				shortUrl(urlMap).then(function(results){
					$('#urlMap').val(results.id);
				});
				$('#urlVisor').attr("href", urlMap);
				$('#iframeMap').val('<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+urlMap+'&embed=1" ></iframe>');
				$('#dialgo_url_iframe').modal('show');
				_gaq.push(['_trackEvent', 'galeria publica', tipus_user+'enllaça mapa', 'referral', 1]);
				//_kmq.push(['record', 'enllaça mapa', {'from':'galeria publica', 'tipus user':tipus_user}]);
			});
			
			$('#galeriaRow').on('click', '.btn.btn-warning', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				$('#dialgo_rank').modal('show');
				$('#dialgo_rank .rank_mapa').val($this.data("rank"));
				$('#dialgo_rank .btn-primary').data("businessid", $this.data("businessid"));
			});
			
			$('#galeriaRow').on('click', '#dialgo_rank .btn-primary', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				var businessid =  $this.data("businessid");
				var params = {
					businessId: businessid,
					rank: $('#dialgo_rank .rank_mapa').val(),
					uid: Cookies.get('uid')
				};
				updateRankAplicacio(params).then(function(results){
					if (results.status == "OK"){
						$('#'+businessid + ' .rank').text(results.results);
						$('#'+businessid + ' .rankSort').text(results.results);
						userList.sort('rankSort', { order: "desc" });
					}
					$('#dialgo_rank').modal('hide');
				});
			});
			
			$('.tab-content').on('mouseenter', '.thumbnail', function(){
				var descAplicacio = $(this).find(".descAplicacio");
				descAplicacio.fadeIn(500);
				if (descAplicacio.find(".starwarsbody").text().length > 160){
					descAplicacio.find(".starwarsmain").addClass('starwars');
					descAplicacio.find(".starwarsbody").addClass('starwarscontent');
				}
				return false;	
			});
			
			$('.tab-content').on('mouseleave', '.thumbnail', function(){
				$(this).find(".descAplicacio").fadeOut();
				return false;	
			});
			
			$('#galeriaRow').on('click', '.caption.descAplicacio', function(event){
				event.preventDefault();
				event.stopImmediatePropagation();
				var $this = $(this);
				var appbusinessid = appbusinessid = $this.parent().data("businessid");
				var urlMap = paramUrl.visorPage+"?businessid="+appbusinessid;
				if ($.trim($this.data("idusr")) != ""){
					urlMap += "&id="+$this.data("idusr");
				}
				var nomApp=$this.parent().data("nomapp");
				if (undefined!=nomApp){
					var nomIndexacio=nomApp;			
					(nomIndexacio.length > 100)?nomIndexacio=nomIndexacio.substring(0,100):nomIndexacio;			
					 nomIndexacio= encodeURI(nomIndexacio);
					 urlMap += "&title="+nomIndexacio;
				}
				_gaq.push(['_trackEvent', 'galeria privada', tipus_user+'veure mapa']);
				window.open(urlMap);
			});
			
			if (userList){
				userList.reIndex();
			}else{
				//Search function
				var optionsSearch = {
					valueNames: [ 'nomAplicacioSort', 'byuser', 'dataPublicacio', 'rankSort' ],
					page: 10000
				};
				
				userList = new List('galeriaSort', optionsSearch);
				
				userList.on('searchComplete',function(){
					self.escriuResultats(userList.visibleItems.length);
				});
			}
			
			if(userList && userList.searched){
				self.escriuResultats(userList.visibleItems.length);
			}else{
				self.escriuTotal();
			}
		}, 
		
		onMessage: function(e){
			var self = this;
			if (e.origin == "http://www.geolocal.cat"){
				switch(e.data){
					case 'reload':
						self.reload();
						break;
				}
			}
		}, 
		
		reload: function(){
			var self = this;
			if( isGeolocalUser() ){
				$("#AplicacionsRow .configurades").remove();
				getConfiguradesUser({codiUsuari: codiUsuari}).then(function(results){
					self.pintaGaleriaConfigurades(results);
				});
			}
		},
		
		refresh: function(){
			var self = this;
			self.loadGaleria();
		},
		
		pintaGaleriaMapsByUser: function(results, searchString){
			var self = this;
			if (results.results!=undefined && results.results.length>0){
				self.pintaGaleria(results);
				loading = false;
				if (searchString && searchString != ""){
					userList.search(searchString);
				}
				self.updateTotal();
			}
			else {
				loading = false;
				self.updateTotal();
				$('#loadingGaleria').hide();
				/*
				if(userList.visibleItems.length === 0){
					//antes se redireccionaba
					//var redirect=paramUrl.galeriaPage;
					//window.location.href=redirect;
				}
				*/
			}
		}, 
		
		loadGaleria: function(){
			var self = this;
			self._loadGaleria({uid: self.options.uid}).then(function(results){
				self.drawGaleria(results);
				self.escriuResultats(results.results.length);
			});
		},
		
		_loadGaleria: function(params){
			return jQuery.ajax({
				url: paramUrl.getAllMapsByUser,
		  		data: params,
		  		method: 'post',
		  		dataType: 'jsonp'
			}).promise();
		},
		
		duplicateMap: function(){
			var self = this;	
			var data1 = {
					uid: Cookies.get('uid'),
					businessId1: $('#dialgo_duplicar_mapa').data('businessid')
			}
			//Polling
			crearFitxerPolling(data1).then(function(results) {
				var tmpFile="";
				if (results.status=="OK"){
					tmpFile = results.tmpFilePath;
					//Definim interval de polling en funcio de la mida del fitxer
					var pollTime =1000;
					//Fem polling
					(function(){							
						pollBuffer = function(){
							$.ajax({
								url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
								dataType: 'json',
								type: 'get',
								success: function(data){
									//console.debug(data);
									//$('#dialgo_duplicar_mapa').modal('hide');
									$('#infoDuplicar').attr("style","display:block;padding:5px;");
									$('#loadingGaleria_duplicate').attr("style","display:block");
									$('#dialgo_duplicar_mapa #cancelarBoto').html("Acceptar");
									$('#dialgo_duplicar_mapa #cancelarBoto').attr("class","btn btn-success btn-default");
									$('#dialgo_duplicar_mapa #cancelarBoto').attr("disabled", true);
									$('#dialgo_duplicar_mapa #duplicarBoto').attr("style","display:none");		
										
									if(data.status.indexOf("PAS")!=-1 && busy){
									
									}else if(data.status.indexOf("OK")!=-1 && busy){
										busy=false;
										clearInterval(pollInterval);
										$('#infoDuplicar').attr("style","display:none");
										var urlMapaDuplicat = 'http://www.instamaps.cat/geocatweb/mapa.html?businessid='+data.results.businessId;
										var spanText = '<span lang="ca" class="status_check">Procés finalitzat correctament</span>';
										spanText += ' <div id="urlMapDuplicat"><a target="_blank" href="'+urlMapaDuplicat+'">'+
													' <span lang="ca">Anar al mapa</span><span class="glyphicon glyphicon-share-alt"></span>'+
													' </a></div>';	
										$('#infoText').html(spanText);
										$('#infoText').attr("style","display:block");
										$('#loadingGaleria_duplicate').attr("style","display:none");
										$('#dialgo_duplicar_mapa #cancelarBoto').removeAttr("disabled");
										userList.clear();
										self.refresh();		
										var sort = self.getOrderGaleria();
										self.reorderGaleria(sort);
									}else if(data.status.indexOf("ERROR")!=-1 && busy){
										console.error("Error calculant l'operació");
										console.error(data);
										busy = false;										
										clearInterval(pollInterval);
										clearInterval(pollInterval);
										$('#infoDuplicar').attr("style","display:none");
										var spanText = '<span lang="ca" class="status_check">Error al duplicar el mapa</span>';
										$('#infoText').html(spanText);
										$('#infoText').attr("style","display:block");
										$('#loadingGaleria_duplicate').attr("style","display:none");
										$('#dialgo_duplicar_mapa #cancelarBoto').removeAttr("disabled");
										//error
									}
									else if (!busy){
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
									}
								},
								error:  function(data){
									busy=false;
									$('#loadingGaleria_duplicate').attr("style","display:none");
								}
							});
						};
						
						pollInterval = setInterval(function(){
							pollBuffer();
						},pollTime);
						
					})();
					
					var data ={
						uid:self.options.uid,
						duplicate: 'si',
						urlDuplicar: paramUrl.duplicateMap,
						businessId:$('#dialgo_duplicar_mapa').data('businessid'),
						nom: $('#dialgo_duplicar_mapa #nomMapaDuplicar').val(),
						tmpFilePath: tmpFile
					};
								
					callActions(data);
					/*self._duplicateMap(data).then(function(results){
					if (results.status == "OK"){
						self._hideLoading();
						self.refresh();
						$('#dialgo_duplicar_mapa').modal('hide');
						_gaq.push(['_trackEvent', 'galeria privada', t_user_loginat+'duplicar aplicacio']);
					}
					});*/	
				
				}
				else {
					busy=false;
				}
				

				
			 });
			
			
				
		},
		
		_duplicateMap: function(params){
			return jQuery.ajax({
				url: paramUrl.duplicateMap,
				data: params,
		  		dataType: 'jsonp'
			}).promise();
		},
		
		_showLoading: function(){
			$('#loadingGaleria_duplicate').show();
		},
		
		_hideLoading: function(){
			$('#loadingGaleria_duplicate').hide();
		}


	};
	
	Galeria.init = function(options){
		var self = this;
		self.options = $.extend({}, galeriaOptions, options);
		$.publish('loadConfig',null);
	}
	
	Galeria.init.prototype = Galeria.prototype;
	
	global.Galeria = Galeria; 
	
}(window, jQuery));

<file_sep>/geocatweb/js/leaflet/L.IM_LayersBtnControl.js
/**
 * L.Control.LayersBtn control que agrega el control de capas
 * 
 * require /geocatonline/geocatweb/js/leaflet/L.IM_ControlLayerManager.js
 * require /geocatonline/llibreries/js/jquery/plugins/jquery.transit.js
 */
L.Control.LayersBtn = L.Control.extend({
	options: {
		position: 'topright',
		id: 'dv_bt_layers',
		className: 'leaflet-bar btn btn-default btn-sm grisfort',
		title: 'Llista de capes',
		langTitle: 'Llista de capes',
		html: '<span class="glyphicon glyphicon-th-list"></span>',
		transition: true,
		button: true,
		tooltip: 'left'
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			container,
			stop = L.DomEvent.stopPropagation;
		
		if(options.button){
			container = L.DomUtil.create('div', options.className);
			container.id = options.id;
			container.innerHTML = options.html;
			container.title = options.title;
			container.dataset.toggle = 'tooltip';
			container.dataset.placement = options.tooltip;
			container.dataset.langTitle = options.langTitle;
		}else{
			container = L.DomUtil.create('div', '');
		}
		
		self._div = container;
		
		map.on('loadconfig', self._updateMapConfig, self);
		map.on('visorconfig', self._updateMapConfig, self);
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', L.DomEvent.preventDefault)
			.on(container, 'click', self._toggle, self);
		
		self.control = L.control.orderlayers(null, null, {
			collapsed : false,
			id : 'div_capes',
			editMode: false,
			autoUpdate: false,
			mapConfig: self.options.mapConfig
		}).addTo(map);
		
		controlCapes = self.control;

		map.on('addItemFinish',function(){
			$(".layers-list").mCustomScrollbar("destroy");
			$(".layers-list").mCustomScrollbar({
			   advanced:{
			     autoScrollOnFocus: false,
			     updateOnContentResize: true
			   }
			});
		});
		
		self.hide();
		
		return container;
	},
	
	onRemove: function (map) {
		var self = this;
		map.off('loadconfig', self._updateMapConfig, self);
		map.off('visorconfig', self._updateMapConfig, self);
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
		var div = self.control.getContainer();
		$(div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
		if(!self.control.options.collapsed){
			var div = self.control.getContainer();
			$(div).show();
		}
	},
	
	hide: function() {
		var self = this;
		L.DomUtil.removeClass(self._div, 'greenfort');
		L.DomUtil.addClass(self._div, 'grisfort');
		var div = self.control.getContainer();
		self.control.options.collapsed = true;
		if(self.options.transition){
			$(div).fadeOut({duration: 'fast'});
		}else{
			$(div).hide();
		}
	},
	
	show: function(e){
		var self = this;
		L.DomUtil.removeClass(self._div, 'grisfort');
		L.DomUtil.addClass(self._div, 'greenfort');
		var div = self.control.getContainer();
		self.control.options.collapsed = false;
		if(self.options.transition){
			$(div).fadeIn({duration: 'fast'});
		}else{
			$(div).show();
		}
	},
	
	_toggle: function(e){
		var self = this;
		var collapsed = L.DomUtil.hasClass(self._div, 'grisfort');
		this[collapsed ? 'show' : 'hide']();
	},
	
	_updateMapConfig: function(config){
		this.options.mapConfig = config;
	}
});

L.control.layersBtn = function(options){
	return new L.Control.LayersBtn(options);
};<file_sep>/geocatweb/js/geocat.mapa.dades-usuari.js
var delay = (function(){
	  var timer = 0;
	  return function(callback, ms){
	    clearTimeout (timer);
	    timer = setTimeout(callback, ms);
	  };
})();

var serverType="";
var primerCop="";
var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Encara no has creat cap capa de dades')+"<strong>  <span class='fa fa-warning sign'></span></div>";

$(function() {
	$(document).on("keyup", 'input.search.form-control', function() {
		var q = $(this).val();
		q = $.trim(q);
		var data = {};
		if(q !== "" && q.length >= 3 ){
			jQuery("#id_sw").empty();
			
			data = {
				uid: Cookies.get('uid'),
				serverName: q,
				serverType: serverType,
				iduser:_UsrID
			};
			delay(function(){
				primerCop="false";
				refrescaPopOverMevasDades(data).then(function(results){
						actualitzarMevesDades(results);
						$('input.search.form-control').val(q);
				});
			}, 400 );
		}
		else if (q===""){
			jQuery("#id_sw").empty();
			
			data = {
				uid: Cookies.get('uid'),
				serverType: serverType,
				iduser:_UsrID
			};
			primerCop="false";
			refrescaPopOverMevasDades(data).then(function(results){
					actualitzarMevesDades(results);
			});
		}
	});
	
	$(document).on("click",'#bt_cercaTevesDades', function() {
		var q = $('input.search.form-control').val();
		q = $.trim(q);
		var data = {};
		if(q !== "" && q.length >= 3 ){
			jQuery("#id_sw").empty();
			
			data ={
				uid: Cookies.get('uid'),
				serverName: q,
				serverType: serverType,
				iduser:_UsrID
			};
			delay(function(){
				primerCop="false";
				refrescaPopOverMevasDades(data).then(function(results){
						actualitzarMevesDades(results);
						$('input.search.form-control').val(q);
				});
			}, 400 );
		}
		else if (q === ""){
			jQuery("#id_sw").empty();
			
			data ={
				uid: Cookies.get('uid'),
				serverType: serverType,
				iduser:_UsrID
			};
			primerCop="false";
			refrescaPopOverMevasDades(data).then(function(results){
					actualitzarMevesDades(results);
			});
		}
	});
	
	$(document).on("ifChecked",'#checkbox-filtres input',function () {
		if (primerCop=="false") {
			 var sThisVal =  $(this).val() ;
			 if (serverType.indexOf(sThisVal)==-1) {
				 if (serverType === "") serverType += sThisVal;
				 else serverType += ","+sThisVal;
			 }
		     $('#listnav-teves-dades > .'+sThisVal).each(function(){
		    	  $(this).removeClass("display-none");
	   		      $(this).addClass("display-block");  		      
		     });
		}		
	 });
	
	$(document).on("ifUnchecked",'#checkbox-filtres input',function () {
		 var sThisVal =  $(this).val() ;
		 if (serverType.indexOf(sThisVal)>-1) {
			 serverType = serverType.replace(","+sThisVal,"");			 
		 }
		 $('#listnav-teves-dades > .'+sThisVal).each(function(){
	    	  $(this).removeClass("display-block");
  		      $(this).addClass("display-none");   	
	     });
	   });
});

function carregaDadesUsuari(){
	//console.debug("carregaDadesUsuari");
	addHtmlInterficieDadesUsuari();
	addHtmlModalDadesUsuari();
	addHtmlModalErrorMsg();
	primerCop="true";
	var data = {uid: Cookies.get('uid')};
	creaPopOverMevasDades();

}


function creaPopOverMevasDades(){
	jQuery(".div_dades_usr").on('click', function() {
		//console.debug("creaPopOverMevasDades");
		jQuery('.modal').modal('hide');
		$('#cercaTevesDades').attr("style","width:98%");
		$('#dialog_teves_dades').modal('show');
				
		//Per tenir actualitzar canvis: remove layers, add layers, etc
		serverType="";
		jQuery("#id_sw").empty();
		var data = {uid: Cookies.get('uid'),iduser:_UsrID};
		refrescaPopOverMevasDades(data).then(function(results){
			actualitzarMevesDades(results);
		});
	});
}

function actualitzarMevesDades(results){
	initMevesDades = true;
	if(results.results.length === 0){
		jQuery('#id_sw').html(warninMSG);		
	}else{
		var source1 = jQuery("#meus-wms-template").html();
		var template1 = Handlebars.compile(source1);

		var html1 = template1(results);				
		jQuery("#id_sw").append(html1);
		
		$('#listnav-teves-dades > li.wms').each(function(){
			var txt = $(this).find('a').text();
			$(this).find('a').text(txt + " (WMS)");
		});
		
		$('#checkbox-filtres input').iCheck({
    	    checkboxClass: 'icheckbox_flat-blue',
    	    radioClass: 'iradio_flat-blue'
    	});
		
		$('#checkbox-filtres input').each(function(){
			if (serverType === ""){
				 var sThisVal =  $(this).val() ;
				$(this).iCheck('check');
				 if (serverType === "") serverType += sThisVal;
				 else serverType += ","+sThisVal;
			}
			else {
				if (serverType.indexOf($(this).val())>-1) {
					$(this).iCheck('check');
				}
				else {
					$(this).iCheck('uncheck');
				}
			}
	     });
		
		$('#id_sw>input').attr("placeholder", window.lang.translate("Cerca"));
		
		$("#listnav-teves-dades").listnav({					
		    initLetter: '',				    
		    allText: window.lang.translate('Tots'),
		    noMatchText: window.lang.translate('No hi ha entrades coincidents'),
		    onClick: function(letter){
		    	if (jQuery("#error-message").length>0) $('#dialog_error_teves_dades').modal('hide');
		     } 
		});
		
		jQuery("ul.llista-teves-dades").on('click', '.usr_wms_layer', function(event) {
			event.preventDefault();
			var _this = jQuery(this);
		
			var data = {
					uid: Cookies.get('uid'),
					businessId: mapConfig.businessId,
					servidorWMSbusinessId: _this.data("businessid"),
					layers: _this.data("layers"),
					calentas:false,
					activas:true,
					visibilitats:true,
					order: controlCapes._lastZIndex+ 1
			};						
			
			addServerToMap(data).then(function(results){
				if(results.status==='OK'){
					
					var value = results.results;
					_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar meves dades', value.serverType, 1]);
//							_kmq.push(['record', 'carregar meves dades', {'from':'mapa', 'tipus user':tipus_user, 'tipus layer':value.serverType}]);
					
					if (value.epsg == "4326"){
						value.epsg = L.CRS.EPSG4326;
					}else if (value.epsg == "25831"){
						value.epsg = L.CRS.EPSG25831;
					}else if (value.epsg == "23031"){
						value.epsg = L.CRS.EPSG23031;
					}else{
						value.epsg = map.crs;
					}							
					
					if(_this.data("servertype") == t_wms){
						loadWmsLayer(value);
					}else if((_this.data("servertype") == t_dades_obertes)){
						loadDadesObertesLayer(value);
					}else if(_this.data("servertype") == t_xarxes_socials){
						
						var options = jQuery.parseJSON( value.options );
						if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
						else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
						else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
						
					}else if(_this.data("servertype") == t_tematic){
						loadTematicLayer(value);
					}else if(_this.data("servertype") == t_visualitzacio){
						loadVisualitzacioLayer(value);
					}							
					$('#dialog_teves_dades').modal('hide');
					activaPanelCapes(true);
				}		
			});							
		});					
				
		//Eliminem servidors
		jQuery("ul.llista-teves-dades").on('click', 'span.glyphicon-remove', function(event) {
			event.preventDefault();
			event.stopPropagation();
			var _this = jQuery(this);
			var data = {
				uid: Cookies.get('uid'),
				businessId: _this.data("businessid")
			};
			
			var firstLetter = _this.data("servername").charAt(0).toLowerCase();
			if($.isNumeric(firstLetter)) firstLetter = "_";
			
			var parent = _this.parent();
			var parentul = parent.parent();
			//_this.parent().remove();
			if (jQuery.trim(jQuery("#id_sw").text()) === ""){
				jQuery('#id_sw').html(warninMSG);
			}
			jQuery("#error-message").remove();
			if(_this.data("servertype") == t_tematic){
				deleteTematicLayerAll(data).then(function(results){
					if (results.status == "ERROR"){
						//parentul.append(parent);
						if (results.results){
							if (results.results.indexOf("DataIntegrityViolationException")!=-1){
							var aplicacions=results.results.split("__");
							var visors="";
							for (var i=0;i<aplicacions.length;i++){
								var businessIdNom=aplicacions[i].split("#");
								var businessId=businessIdNom[0];
								if (businessId.indexOf("DataIntegrityViolationException")!=-1) businessId=businessId.replace("DataIntegrityViolationException_","");
								var nom=businessIdNom[1];
								if (visors !== "") visors = visors +'<br/>'+ '<a target="_blank" class="deleteCapa" href="http://'+DOMINI+paramUrl.mapaPage+'?businessid='+businessId+
								'">'+nom+"</a>";
								else visors = '<br/>'+visors +'<a target="_blank" class="deleteCapa" href="http://'+DOMINI+paramUrl.mapaPage+'?businessid='+businessId+
								'">'+nom+"</a>";
							}
							var errorMSG="<div id='error-message' class='alert alert-danger'>" +
							 "<span class='fa fa-warning sign'></span><strong>"+window.lang.translate('La capa ')+_this.data("servername")+
							 window.lang.translate(' no es pot esborrar perquè actualment és en ús: ')+visors+"<strong>  " +
						     "</div>";
							
							$('#dialog_error_teves_dades').modal('show');
							jQuery('#dialog_error_teves_dades #id_sw').append(errorMSG);
						}}
					}else{
						_this.parent().remove();
						$('#dialog_error_teves_dades').modal('hide');
						globalCounts[''+firstLetter +'']--;
					}					
				});
			}else{
				deleteServidorWMS(data).then(function(results){
					if (results.status == "ERROR"){
						//parentul.append(parent);
						if (results.results) {
							if ( results.results.indexOf("DataIntegrityViolationException")!=-1){
						
							var aplicacions=results.results.split("__");
							var visors="";
							for (var i=0;i<aplicacions.length;i++){
								var businessIdNom=aplicacions[i].split("#");
								var businessId=businessIdNom[0];
								if (businessId.indexOf("DataIntegrityViolationException")!=-1) businessId=businessId.replace("DataIntegrityViolationException_","");
								var nom=businessIdNom[1];
								if (visors !== "") visors = visors +'<br/>'+ '<a target="_blank" class="deleteCapa" href="http://'+DOMINI+paramUrl.mapaPage+'?businessid='+businessId+
								'">'+nom+"</a>";
								else visors = '<br/>'+visors +'<a target="_blank" class="deleteCapa" href="http://'+DOMINI+paramUrl.mapaPage+'?businessid='+businessId+
								'">'+nom+"</a>";
							}
							var errorMSG="<div  id='error-message' class='alert alert-danger'>" +
							 "<span class='fa fa-warning sign'></span><strong>"+window.lang.translate('La capa ')+_this.data("servername")+
							 window.lang.translate(' no es pot esborrar perquè actualment és en ús: ')+visors+"<strong>  " +
						     "</div>";
							$('#dialog_error_teves_dades').modal('show');
							jQuery('#dialog_error_teves_dades #id_sw').append(errorMSG);
							}}														
							
					}else{
						_this.parent().remove();
						$('#dialog_error_teves_dades').modal('hide');
						globalCounts[''+firstLetter +'']--;
						var data2 = {
								uid: Cookies.get('uid'),
								businessId: _this.data("businessid")
						};
						deleteVisualitzacioLayer(data2).then(function(results){
							
						});

						//Esborra GeoJson creat per el servei WMS						
						var data3 = {
							businessId:  _this.data("businessid"),
							//entitatUid:  Cookies.get('uid'),										
							entitatUid: _UsrID,
							metode: "deleteGeoJSONfromMap"
						};
						
						createMapToWMS(data3).then(function(results){});
					}
				});						
			}
		});		
	}
}

function refrescaPopOverMevasDades(data){
	var dfd = jQuery.Deferred();
	
	getAllServidorsWMSByUser(data).then(function(results){
		
		var serverOrigen = [];
		if (results.results.length>0){
			dades1=results;
			if (results.status=="OK"){
				jQuery.each(results.results, function(i, item){
					if (item.serverType == t_tematic || item.serverType == t_visualitzacio){
						if (item.options === null){
							serverOrigen.push(item);
						}else{
							var options = jQuery.parseJSON( item.options );
							
							if (options.tem == tem_origen || options.tipus == tem_origen || options.tipus ==t_visualitzacio ||  options.tipus ==t_tematic){
								serverOrigen.push(item);
							}
						}
					}else if(item.serverType == t_wms || item.serverType == t_url_file){
						serverOrigen.push(item);
					}
				});
			}
			dades1.results = serverOrigen;
			dfd.resolve(dades1);
		}
		else {//No es troben resultats
			
			if (!isRandomUser(Cookies.get('uid'))){
				var data ={
					uid: Cookies.get('uid'),
					iduser:_UsrID
				};
				getAllServidorsWMSByUser(data).then(function(results){
					var serverOrigen = [];
					if (results.results.length>0){
						dades1=results;
						jQuery.each(results.results, function(i, item){
							if (item.serverType == t_tematic || item.serverType == t_visualitzacio){
								if (item.options === null){
									serverOrigen.push(item);
								}else{
									var options = jQuery.parseJSON( item.options );
									
									if (options.tem == tem_origen || options.tipus == tem_origen || options.tipus ==t_visualitzacio ||  options.tipus ==t_tematic){
										serverOrigen.push(item);
									}
								}
							}else if(item.serverType == t_wms || item.serverType == t_url_file){
								serverOrigen.push(item);
							}
						});
						dades1.results = serverOrigen;
						dfd.resolve(dades1);
					}
				},function(results){
					gestioCookie('refrescaPopOverMevasDades');
				});
			}
		}
		
	},function(results){
		gestioCookie('refrescaPopOverMevasDades');
	});
	return dfd.promise();
}

function addHtmlInterficieDadesUsuari(){	
	jQuery("#carregar_dades .div_gr2").append(
		'<div lang="ca" id="div_dades_usr" class="div_dades_usr" data-toggle="tooltip" title="Accedeix a les teves dades" data-lang-title="Accedeix a les teves dades">'+
		'	<script id="meus-wms-template" type="text/x-handlebars-template">'+
		'	<div class="panel-body">'+
		'		<div >'+
		'			<button id="bt_cercaTevesDades" class="btn btn-tevesDades" type="button"><span class="glyphicon glyphicon-search"></span></button>'+
		'			<input type="text" class="search form-control input-tevesDades" id="cercaTevesDades" placeholder="Cercar a les teves dades"><br/>'+
		'		</div>'+
		'		<!--div style="margin-bottom:3px;" id="checkbox-filtres">'+
		'           Filtre per: '+
		'				<input type="checkbox" id="filtre" style="position: absolute; opacity: 0;" name="tipusCapa" value="visualitzacio">'+
		'			Capes Vector'+
		'				<input type="checkbox" id="filtre" style="position: absolute; opacity: 0;" name="tipusCapa" value="wms">'+
		'			Capes WMS'+
		'				<input type="checkbox" id="filtre" style="position: absolute; opacity: 0;" name="tipusCapa" value="url_file">'+
		'			Capes de fitxers'+
		'		</div-->'+
		'		<div id="list-teves-dades" >'+
		'		<ul id="listnav-teves-dades" class="llista-teves-dades">'+
		'		{{#each results}}'+				    
		'			<li  class="{{serverType}}"><a href="#" data-businessid="{{businessId}}" data-layers="{{layers}}" data-servertype="{{serverType}}" data-options="{{options}}" class="usr_wms_layer label-teves-dades">{{serverName}}</a>'+
		'			<span data-businessid="{{businessId}}" data-servername="{{serverName}}" data-servertype="{{serverType}}" class="glyphicon glyphicon-remove info-teves-dades"></span>'+
		'			</li>'+
		'		{{/each}}'+
		'		</ul>'+
		'		</div>'+
		'	</div>'+
		'	</script>'+
		'</div>'		
	);
	$('#div_dades_usr').tooltip({
		placement : 'bottom',
		container : 'body'
	});
}

function addHtmlModalDadesUsuari(){
	jQuery('#mapa_modals').append(
	'	<!-- Modal les teves dades -->'+
	'		<div class="modal fade" id="dialog_teves_dades">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content panel-primary">'+
	'				<div class="modal-header panel-heading">'+
	'					<button type="button" class="close" data-dismiss="modal"'+
	'						aria-hidden="true">&times;</button>'+
	'					<h4 id="modal-title-teves-dades" class="modal-title"><span lang="ca">Accedeix a les teves dades</span><span><a class="faqs_link" href="http://betaportal.icgc.cat/wordpress/faq-dinstamaps/#accedeix" target="_blank"><i class="fa fa-question-circle-o fa-lg fa-fw"></i></a></span></h4>'+
	'				</div>'+
	'				<div id="id_sw" class="modal-body">'+
	'					<!-- <ul class="nav nav-tabs etiqueta">'+
	'						<li><a href="#id_sv" lang="ca" data-toggle="tab">Serveis Vector</a></li>'+
	'						<li><a href="#id_sw" lang="ca" data-toggle="tab">Serveis WMS</a></li>'+
	'					</ul>'+
	'					<div class="tab-content tab-content-margin5px">'+
	'						<div class="tab-pane fade" id="id_sv"></div>'+
	'						<div class="tab-pane fade" id="id_sw"></div>'+
	'					</div> -->'+
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<!-- <button type="button" class="btn btn-default" data-dismiss="modal">Tancar</button>'+
	'         <button type="button" class="btn btn-success">Canviar</button> -->'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- fi Modal les teves dades -->'	
	);
}

function addHtmlModalErrorMsg(){
	jQuery('#mapa_modals').append(
	'	<!-- Modal error les teves dades -->'+
	'		<div class="modal fade" id="dialog_error_teves_dades">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content panel-primary">'+
	'				<div id="id_sw" class="modal-body">'+								
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<button type="button" class="btn btn-default" data-dismiss="modal">Tancar</button>'+
	'        <!-- <button type="button" class="btn btn-success">Canviar</button> -->'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- fi Modal les teves dades -->'	
	);
}
<file_sep>/geocatweb/js/leaflet/L.IM_RoutingControl.js
/**
 * L.Control.RoutingControl control de routing basado en el leaflet-routing-machine
 */

L.Control.RoutingControl = L.Control.extend({
	includes: L.Mixin.Events,
	
	options: {
		position: 'topleft',
		lang: 'ca',
		id: 'dv_bt_Routing',
		className: 'leaflet-bar btn btn-default btn-sm grisfort',
		title: 'Routing',
		langTitle: 'Routing',
		html: '<span id="span_bt_Routing" class="t" style="font-size:16px; margin-top:-2px;">'+
		'<i class="t-square-rounded" style="-webkit-transform:scale(1.25) scale(0.65) rotate(45deg);-moz-transform:scale(1.25) scale(0.65) rotate(45deg);transform:scale(1.25) scale(0.65) rotate(45deg)"></i>'+
		'<i class="t-turn-90-l t-c-white" style="-webkit-transform:scale(-1.3, 1.3);-moz-transform:scale(-1.3, 1.3);transform:scale(-1.3, 1.3)"></i>'+
		'</span>',
		tooltip: 'right',
		marker_style_origen: {
			icon : '',
			markerColor : 'green',
			divColor:'transparent',
			iconAnchor : new L.Point(14, 42),
			iconSize : new L.Point(28, 42),
			iconColor : '#000000',
			prefix : 'fa',
			isCanvas:false,
			radius:6,
			opacity:1,
			weight : 2,
			fillOpacity : 0.9,
			color : "#ffffff",
			fillColor :"transparent"
		},
		marker_style_desti: {
			icon : '',
			markerColor : 'red',
			divColor:'transparent',
			iconAnchor : new L.Point(14, 42),
			iconSize : new L.Point(28, 42),
			iconColor : '#000000',
			prefix : 'fa',
			isCanvas:false,
			radius:6,
			opacity:1,
			weight : 2,
			fillOpacity : 0.9,
			color : "#ffffff",
			fillColor :"transparent"
		},
		marker_style_intermig: {
			icon : '',
			markerColor : 'orange',
			divColor:'transparent',
			iconAnchor : new L.Point(14, 42),
			iconSize : new L.Point(28, 42),
			iconColor : '#000000',
			prefix : 'fa',
			isCanvas:false,
			radius:6,
			opacity:1,
			weight : 2,
			fillOpacity : 0.9,
			color : "#ffffff",
			fillColor :"transparent"
		},
		originTexts: {
			title: "Càlcul de rutes",
			btnStart: "Defineix com a origen",
			btnEnd: "Defineix com a destí",
			btnReverse: "Ruta inversa",
			btnAdd: "Afegir punts",
			start: "Inici",
			end: "Destí"
		},
		texts: {
			title: "Càlcul de rutes",
			btnStart: "Defineix com a origen",
			btnEnd: "Defineix com a destí",
			btnReverse: "Ruta inversa",
			btnAdd: "Afegir punts",
			start: "Inici",
			end: "Destí"
		}
	},
	
	//TODO ver el tema del lang para poder cambiar el idioma del control
	
	initialize: function(options) {
		L.setOptions(this, options);
		
		var self = this,
			options = this.options,
			lang = options.lang,
			puntIntermig = L.AwesomeMarkers.icon(options.marker_style_intermig),
			puntDesti = L.AwesomeMarkers.icon(options.marker_style_desti),
			puntOrigen = L.AwesomeMarkers.icon(options.marker_style_origen);
		
		this._reversablePlan = L.Routing.Plan.extend({
		    createGeocoders: function() {
		        var container = L.Routing.Plan.prototype.createGeocoders.call(this),
		        title = (window.lang) ? window.lang.translate(options.originTexts.btnReverse) : options.texts.btnReverse,
		        reverseButton = self._createButton('<span class="glyphicon glyphicon-sort" style="font-size:14px;"></span>', container, title, lang);
		        L.DomEvent.on(reverseButton, 'click', function() {
		            var waypoints = this.getWaypoints();
		            this.setWaypoints(waypoints.reverse());
		        }, this);
		        return container;
		    }
		});
		
		var createMarker = function(i, wp) {
        	var numWp = this._route.getWaypoints().length;
        	if(i == 0){
        		return L.marker(wp.latLng, {
    				draggable: true,
    				icon: puntOrigen
    			});
        	}
        	else if (i === (numWp - 1)){
        		return L.marker(wp.latLng, {
    				draggable: true,
    				icon: puntDesti
    			});
        	}
        	else {
        		return L.marker(wp.latLng, {
    				draggable: true,
    				icon: puntIntermig
    			});
        	}
        };
		
		this._plan = new this._reversablePlan([], {
	        geocoder: L.Control.Geocoder.icgc(),
	        routeWhileDragging: true,
	        language: lang,
	        createMarker: createMarker.bind(self)
	    });
		
		//console.debug(lang);
		
		this._route = L.Routing.control({
			router: L.Routing.mapzen('mapzen-aMHsmLA', {
				language: lang,
				    costing:'auto',
				    directions_options: {
				        language: lang
				      }
				    }),
			 formatter: new L.Routing.mapzenFormatter(),
	         routeWhileDragging: true,
	         plan: this._plan,
	         position: 'topleft',
	         language: lang,
		     showAlternatives: true,
		     lineOptions: {
	            styles: [
	              {color: '#00B3FD', opacity: 1, weight: 4},
	            ]
	           },
	         altLineOptions:{
	        	styles: [
	     	      {color: 'black', opacity: 1, weight: 2},
	     	    ]
	         }
		});
		
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			stop = L.DomEvent.stopPropagation,
			container = L.DomUtil.create('div', options.className);
		
		container.id = options.id;
		container.innerHTML = options.html;
		container.title = options.title;
		
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		self._map = map;
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', L.DomEvent.preventDefault)
			.on(container, 'click', self._toggle, self);
		
		return container;
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
	
	show: function() {
		L.DomUtil.removeClass(this._div, 'grisfort');
		L.DomUtil.addClass(this._div, 'greenfort');
		var _map = this._map,
			options = this.options,
			_texts = options.texts,
			_route = this._route;
		
		_map.fire('showRouting'); //to track ga events
		
		_map.on('click', this._routingPopup, this);
		_route.addTo(_map);
		
		if(window.lang){
			_texts.title = window.lang.translate(options.originTexts.title);
			_texts.btnReverse = window.lang.translate(options.originTexts.btnReverse);
			_texts.btnAdd = window.lang.translate(options.originTexts.btnAdd);
			_texts.start = window.lang.translate(options.originTexts.start);
			_texts.end = window.lang.translate(options.originTexts.end);
		}
		
		$('.leaflet-routing-geocoders').before( '<div class="div-routing-title"><span lang="ca" class="routing-title">'+_texts.title+'</span>&nbsp;<a href="http://www.liedman.net/leaflet-routing-machine/" target="_blank" class="div-routing-title" style="display:inline;"><span class="glyphicon glyphicon-info-sign white" style="font-size:14px;"></a></div>' );
		$('.leaflet-routing-add-waypoint').attr('title',_texts.btnAdd);
		$('.leaflet-routing-add-waypoint').attr('lang',options.lang);
		$('.leaflet-routing-geocoder').first().find('input').attr('placeholder',_texts.start);
		$('.leaflet-routing-geocoder').last().find('input').attr('placeholder',_texts.end);
		
		var offset = $(this._div).offset();
		
		jQuery('.leaflet-routing-container').css('top', (offset.top-60)+'px');
		jQuery('.leaflet-routing-container').css('left', (offset.left + 35)+'px');
		jQuery('.leaflet-routing-container').css('position','absolute');
		jQuery('.leaflet-routing-container').css('z-index','100');
		
	},

	hide: function() {
		var self = this,
		_map = self._map,
		_route = self._route;
		
		
		L.DomUtil.removeClass(self._div, 'greenfort');
		L.DomUtil.addClass(self._div, 'grisfort');
		console.debug("AQUI");
		try{
			_route.removeFrom.call(_route,_map);
		}catch(e){
			console.debug(e);
		}finally{
			_map.off('click',self._routingPopup, self);
		}
		
	},
	
	_toggle: function(e){
		var collapsed = L.DomUtil.hasClass(this._div, 'grisfort');
		this[collapsed ? 'show' : 'hide']();
	}, 
	
	_routingPopup: function(e) {
		console.debug("routing");
		var options = this.options,
		_texts = options.texts;
		
		if(window.lang){
			_texts.title = window.lang.translate(options.originTexts.title);
			_texts.btnStart = window.lang.translate(options.originTexts.btnStart);
			_texts.btnEnd = window.lang.translate(options.originTexts.btnEnd);
		}
		
		var container ='<div id="contentRoutingPopup" class="contentRoutingPopup">';
		container +='<h4 style="border-bottom:0px;" lang="ca">'+_texts.title+'</h4>';
		container +='<button class="btn startBtn" lang="ca" type="button" id="startBtn">'+_texts.btnStart+'</button>'+
		  	'<span class="awesome-marker-icon-green awesome-marker leaflet-zoom-hide leaflet-clickable leaflet-marker-draggable icona icona-origen" id="icona-origen"></span>'+
		   	'<button class="btn endBtn" lang="ca" type="button" id="destBtn">'+_texts.btnEnd+'</button>'+
		   	'<span class="awesome-marker-icon-red awesome-marker leaflet-zoom-hide leaflet-clickable leaflet-marker-draggable icona icona-desti" id="icona-desti"></span>';
		container += "</div>";
		
		var _map = this._map,
			_route = this._route;
		
		L.popup().setContent(container).setLatLng(e.latlng).openOn(_map);

		jQuery(".leaflet-popup-content").css('width','184px');
		jQuery(".leaflet-popup-content").css('margin','5px 15px');

	    jQuery('#startBtn').on('click', function() {
	    	_route.spliceWaypoints(0, 1, e.latlng);
	    	_map.closePopup();
	    });

	    jQuery('#destBtn').on('click', function() {
	    	_route.spliceWaypoints(_route.getWaypoints().length - 1, 1, e.latlng);
	        _map.closePopup();
	    });

	    jQuery('#icona-origen').on('click', function() {
	    	_route.spliceWaypoints(0, 1, e.latlng);
	    	_map.closePopup();
	    });

	    jQuery('#icona-desti').on('click', function() {
	    	_route.spliceWaypoints(_route.getWaypoints().length - 1, 1, e.latlng);
	        _map.closePopup();
	    });

	}, 
	
	_createButton: function(label, container, title, lang) {
	    var btn = L.DomUtil.create('button', '', container);
	    btn.setAttribute('type', 'button');
	    btn.setAttribute('lang', lang);
	    btn.setAttribute('title', title);
	    btn.innerHTML = label;
	    return btn;
	},

	_createSpan: function(label, container) {
	    var span = L.DomUtil.create('span', '', container);
	    span.innerHTML = label;
	    return span;
	}
});

L.control.routingControl = function(options){
	return new L.Control.RoutingControl(options);
};<file_sep>/README.md
# Instamaps

Eina de lInstitut Cartogrąfic i Geolņgic de Catalunya (ICGC) posa a la teva disposició per tal que puguis explorar la geoinformació de Catalunya i el món, crear els teus mapes de manera rąpida i fącil, visualitzar-los en qualsevol dispositiu i compartir-los amb les xarxes socials.

##FAQs
http://betaportal.icgc.cat/wordpress/category/instamaps/
<file_sep>/geocatweb/js/instamaps.geolocal.widgets.idescat.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetIdescat = {
					
		init: function() {
			this.url = "http://api.idescat.cat/emex.ifr?bc=333333&lc=0000cc&c=000000&t=0&e=f&enc=utf-8&tc=ffffff&id=widget_id_municipi&i=f261,f321,f187,f188,f184,f91,f242,f122,f133,f134,f141,f144,f215,f219,f19&lang=cat";
			this.containerId = '.drawWidgets';
			this.cache();
        	this.subscriptions();
        	this.bindEvents();
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	this.container = $(this.containerId);
        },
        
        getWidget: function(){
        	return this;
        },
                
        drawButton: function(container){
        	var that = this;
        	$('<div/>').addClass('widget-button').addClass('widget-idescat')
        	.on('click',function(){
        		$.publish('widgetActivated',{'target':this,'widget':that});
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_Idescat']});
        	})
        	.appendTo(container);
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	this.iframe = false;
        	$(this.containerId).empty();
        },
        
        draw: function(data){
        	var that = this;
        	if(that.active   && data.tipusMunicipi){
        		var codi = data.municipiCodi;
        		if (codi){
            		var url = that.url.replace("widget_id_municipi", codi);
            		if (that.iframe){
            			$(that.containerId).find('iframe').prop('src',url);
                	}else{
                		$('<iframe/>').prop('src',url)
                		.attr('seamless','seamless').attr('scrolling','no')
                		.appendTo($(that.containerId));
                		that.iframe = true;
                	}
            	}else{
            		$(that.containerId).empty();
            	}
        	}
        },
                
        /**********Events**************/
        bindEvents: function(){
        },
        
        subscriptions: function() {
        	var that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
        		if(data){
        			that.draw(data);
        		}
        	});
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetIdescat.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetIdescat = WidgetIdescat.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/instamaps.geolocal.widgets.cadastre.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetCadastre = {
					
		init: function() {
			this.rutaUrbanaCadastre = "http://www.catastro.minhap.es/INSPIRE/CadastralParcels/_provincia_/_codi_-_nom_/A.ES.SDGC.CP.U._codi_.zip";
			this.rutaRuralCadastre = "http://www.catastro.minhap.es/INSPIRE/CadastralParcels/_provincia_/_codi_-_nom_/A.ES.SDGC.CP.R._codi_.zip";
			this.containerId = '.drawWidgets';
			this.m_SGDC = "Els arxius es descarregaran en el format GML 3.2. Si tens problemes per visualitzar-los consulta la <a href='http://www.geoportal.cat/geoportal/cat/documentacio/manuals/index.jsp' target='_blank' class='alert-link'>Guia IDEC de visualització GML</a> <br><br><i>Font dades:<a href='http://www.catastro.minhap.es/INSPIRE/CadastralParcels/ES.SDGC.CP.Atom.xml' target='_blank' class='alert-link'>Servei INSPIRE-ATOM SDGC</a></i>";
			this.cache();
        	this.subscriptions();
        	this.bindEvents();
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	var that = this;
        	that.container = $(that.containerId);
        },
        
        getWidget: function(){
        	return this;
        },
        
        drawButton: function(container){
        	var that = this;
        	$('<div/>').addClass('widget-button').addClass('widget-cadastre')
        	.on('click',function(){
        		$.publish('widgetActivated',{'target':this,'widget':that});
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_Cadastre']});
        	})
        	.appendTo(container);
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	$(this.containerId).empty();
        },
        
        draw: function(data){
        	var that = this;
        	if(that.active   && data.tipusMunicipi){
        		$(that.containerId).empty();
        		var codi = data.codiCadastre;
        		var urlUrbana = that.rutaUrbanaCadastre.replace('_nom_',data.municipiCadastre);
        		urlUrbana = urlUrbana.replace('_provincia_',data.provinciaCodi);
        		urlUrbana = urlUrbana.replace(/_codi_/g,data.codiCadastre);
        		
        		var urlRural = that.rutaRuralCadastre.replace('_nom_',data.municipiCadastre);
        		urlRural = urlRural.replace('_provincia_',data.provinciaCodi);
        		urlRural = urlRural.replace(/_codi_/g,data.codiCadastre);
        		
        		if (codi){
        			$('<p></p>').addClass('text').html('Municipi de <b>' + data.municipi + '</b>').appendTo($(that.containerId));
        			$('<div></div>').addClass('list').append(
        			$('<a></a>', {
    					'href' : urlUrbana,
    					'class' : 'zip',
    					'target' : '_blank'
    				}).html(data.municipiCadastre + " urbana.zip")).append(
    					$('<span></span>',{'class':'glyphicon glyphicon-compressed'})).appendTo($(that.containerId));
        			
        			$('<div></div>').addClass('list').append($('<a></a>', {
    					'href' : urlRural,
    					'class' : 'zip',
    					'target' : '_blank'
    				}).html(data.municipiCadastre + " rústega.zip")).append(
        					$('<span></span>',{'class':'glyphicon glyphicon-compressed'})).appendTo($(that.containerId));
        			
        			$('<p></p>').appendTo($(that.containerId));
        			$('<div></div>').addClass('alert alert-info').html(that.m_SGDC).appendTo($(that.containerId));
        		}else{
            		$(that.containerId).empty();
            	}
        	}
        },
                
        /**********Events**************/
        bindEvents: function(){
        },
        
        subscriptions: function() {
        	var that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
        		if(data){
        			that.draw(data);
        		}
        	});
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetCadastre.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetCadastre = WidgetCadastre.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/geocat.mapa-1.0.0.js
var lockController,timeoutBloqueig;
jQuery(document).ready(function() {

	if(typeof url('?uid') == "string"){
		gestioCookie();
		Cookies.remove('uid');
		Cookies.set('uid', url('?uid'));
		checkUserLogin();
	}

	defineTipusUser();

	if (!Modernizr.canvas  || !Modernizr.sandbox){
		//jQuery("#mapaFond").show();

	}else{
		if (tipus_user == t_user_loginat){
			var data = {
					uid: Cookies.get('uid'),
					businessId: url('?businessid'),
					mapacolaboratiu: url('?mapacolaboratiu')
				};
				getUserSimple(data).then(function(results){
					$('#userId').val(results.results.id);
					_UsrID=results.results.id;
					loadApp();
				});
		}else{
			loadApp();
		}
	}

}); // Final document ready


function loadApp(){

	var v_url = window.location.href;
	if (!url('?id')){
		v_url += "&id="+jQuery('#userId').val();
	}
	if(true){//if(v_url.contains('localhost')){
		v_url = v_url.replace('localhost',DOMINI);
	}
	v_url = v_url.replace('mapa','visor');

	if(typeof url('?businessid') == "string"){
		map = new L.IM_Map('map', {
			zoomAnimation:false,
			dragging: true,
			touchZoom: true,
			scrollWheelZoom: true,
			doubleClickZoom: true,
			boxzoom: true,
			typeMap : 'topoMapGeo',
			minZoom: 2,
			maxZoom : 19,
			timeDimension: true,
		    timeDimensionControl: true,
		    timeDimensionControlOptions:{
		    	speedSlider:false
		    }
			//drawControl: true
		}).setView([ 41.431, 1.8580 ], 8);

		/*L.control.mousePosition({
			position : 'bottomright',
			'emptystring':'',
			'numDigits': 6,
			'prefix': 'WGS84',
			'separator': ' '
		}).addTo(map);*/

		L.control.coordinates({
			position : 'bottomright',
			'emptystring':' ',
			'numDigits': 2,
			'numDigits2': 6,
			'prefix': 'ETRS89 UTM 31N',
			'prefix2': 'WGS84',
			'separator': ' ',
			'showETRS89':true,
			'lngFirst':true
		}).addTo(map);


		L.control.scale({position : 'bottomright', 'metric':true,'imperial':false}).addTo(map);

		var _minTopo=new L.TileLayer(URL_MQ, {minZoom: 0, maxZoom: 19, subdomains:subDomains});

		var miniMap = new L.Control.MiniMap(_minTopo, {
			toggleDisplay: true,
			autoToggleDisplay: true,
			mapOptions: {trackResize: false}
		}).addTo(map);

		gestioCookie('loadApp');

		var data = {
			businessId: url('?businessid'),
			uid: Cookies.get('uid'),
			mapacolaboratiu: url('?mapacolaboratiu')
		};

		getUserSimple(data).then(function(results){
			$('#userId').val(results.results.id);
			_UsrID=results.results.id;
		});

		getMapByBusinessId(data).then(function(results){
			if (results.status == "ERROR"){
				gestioCookie('getMapByBusinessId');
			}
			else if (results.status == "KO"){
				var uidBloq = results.results;
				var txt = window.lang.translate("Mapa bloquejat per l'usuari:")+uidBloq+".\n";
				txt += window.lang.translate("Quan aquest usuari surti de la sessió d'edició podràs treballar amb aquest mapa.");
				alert(txt);
				gestioCookie('getMapByBusinessId2');
			}
			else{
				if (Cookies.get('collaboratebid')) Cookies.remove('collaboratebid');
				if (Cookies.get('collaborateuid')) Cookies.remove('collaborateuid');
				try{
					mapConfig = results.results;
					if (typeof mapConfig.bloquejat == "string" && mapConfig.bloquejat.indexOf("bloquejat")>-1 && mapConfig.bloquejat.indexOf("null")==-1) {
						var bloquejatJson=$.parseJSON(mapConfig.bloquejat);
						jQuery.map( bloquejatJson, function( val, i ) {
								if (val.bloquejat==="S") {
									gestioCookie('mapaBloquejat');
									controlarBloqueigMapa();
								}
						});
					}
					//if (true) { //CANVIAR
					gestioCookie('diferentUser');
					var nomAp = mapConfig.nomAplicacio;
					$('meta[property="og:title"]').attr('content', "InstaMaps: "+nomAp.replaceAll("'","\'"));

					if(typeof (mapConfig.options)=="string"){
						mapConfig.options = $.parseJSON( mapConfig.options );
					}

					if (mapConfig.options){
						var desc = mapConfig.options.description;
						if (desc!=undefined) desc=desc.replaceAll("'","\'");
						$('meta[name="description"]').attr('content', desc);

						$('meta[property="og:description"]').attr('content', desc);

						var urlThumbnail = GEOCAT02 + paramUrl.urlgetMapImage+ "&request=getGaleria&update=false&businessid=" + url('?businessid');
						$('meta[property="og:image"]').attr('content', urlThumbnail);
					}

					mapLegend = (mapConfig.legend? $.parseJSON( mapConfig.legend):[]);

					downloadableData = (mapConfig.options && mapConfig.options.downloadable?
											mapConfig.options.downloadable:[]);

					mapConfig.newMap = false;

					//Afegim barres d'eines i control de capes
					addControlsInici();
					//addLegendEdicio();

					//afegim llegenda

					ctr_legend = L.control.legend({
						title: window.lang.translate('Llegenda'),
						tipusllegenda: "dinamica",  //"dinamica"
						llegendaOpt: true, //true
						origenllegenda:'mapa'
					});
					ctr_legend.addTo(map);


					map.fire('loadconfig', mapConfig);
					$.publish('loadConfig', mapConfig);
					/*
					$.subscribe('loadGaEvents', function(e, data){
						loadEventsGa();
					});
					*/

					loadMapConfig(mapConfig).then(function(){

						$('#nomAplicacio').html(mapConfig.nomAplicacio);
						//llegim configuracio de funcionalitats del mapa, si no te, per defecte

						var configuracio = "";
						loadConfiguracio(mapConfig.configuracio).then(function(results){
							//iniciem els controls basics
							initControls();
							//careguem funcionalitats:
							loadControls(results);
							//Actualitzar idiomes
							updateLangText();
							//Add tooltips
							addToolTipsInici();

							//Actulitza idioma dels tooltips
							$("body").on("change-lang", function(event, lang){
								addDrawTooltips();//Actualitzem tootltips funcionalitat draw
								window.lang.change(lang);
								//window.lang.run(lang);
								updateLangTooltips();
								updateLangText();
							});
							canviaIdioma(web_determinaIdioma());
							document.title = "InstaMaps: "+mapConfig.nomAplicacio;
							addInfoBloqueigMapa(mapConfig);
						});

						//carreguem WMS en cas que s'hagi passat parametre
						if(typeof url('?urlwms') == "string"){
							ActiuWMS.url = url('?urlwms');
							var layername = url('?layername');

							ActiuWMS.servidor = layername;
							ActiuWMS.layers = layername;
							ActiuWMS.epsg = undefined;

							addExternalWMS(true);
						}


					});
					//}
					//else {
					//	alert("Aquest mapa està bloquejat per un altre usuari");
					//	window.location.href = paramUrl.galeriaPage;
					//}
				}catch(err){
					console.debug(err);

					gestioCookie('loadMapConfig');
				}
			}
		},function(results){
			gestioCookie('getMapByBusinessIdError');
		});
		addLeaveModal();

	}else{
		if (!Cookies.get('uid')){
			createRandomUser().then(function(results){
				if (results.status==='OK'){
					var user_login = results.results.uid;
					var pass_login = "<PASSWORD>1234";
					var dataUrl = {user:user_login, password:<PASSWORD>};
					doLogin(dataUrl).then(function(results){
						if(results.status==='OK'){
							Cookies.set('uid', user_login);
							createNewMap();
						}
					});
				}
			});
		}else{
			mapConfig.newMap = true;
			createNewMap();
		}
	}

	/********Events*************/

	$.subscribe('reloadMapConfig',function(e, namespace){
		if (namespace){
			$.publish(namespace+'loadMapConfig', mapConfig);
		}else{
			$.publish('loadMapConfig', mapConfig);
		}
	});

	$.subscribe('getMap',function(e, namespace){
		if (namespace){
			$.publish(namespace+'setMap', map);
		}else{
			$.publish('setMap', map);
		}
	});

	$.subscribe('updateMapConfig',function(e, data){
		mapConfig = data;
	});
}

function initControls(){

	addClicksInici();
//	tradueixMenusToolbar();
	redimensioMapa();
	addHtmlModalOldBrowser();

	addHtmlModalExpire();
	addHtmlModalMessages();

	//carrega font de dades
	generaLListaDadesObertes();
	generaLlistaServeisWMS();

	//Afegir modul3D
	addModul3D(mapConfig);
}

function addClicksInici() {

/*
	jQuery('.bt_legend').on('click', function(event) {
		aturaClick(event);
		activaLlegenda();
	});
*/
	jQuery('.bt_llista').on('click', function(event) {
		aturaClick(event);
		activaPanelCapes();
	});
	
	jQuery('.bt_geotiff').on('click', function(event) {
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'geotiff', 'label geotiff', 1]);
		
	});	

	jQuery('#dv_bt_mapExport').on('click', function(event) {
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'exportmap', 'label exportmap', 1]);
		
	});	
	
	jQuery('.bt_captura').on('click', function(event) {
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'captura pantalla', 'label captura', 1]);
	});

	jQuery('.bt_print').on('click', function(event) {
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'print', 'label print', 1]);
	});

	jQuery('.bt_geopdf').on('click', function(event) {		
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'geopdf', 'label geopdf', 1]);

	});

	jQuery('.bt_geopkg').on('click', function(event) {		
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'geotiff', 'label geopkg', 1]);	
	});

	
	
	
	
	jQuery(document).on('click', function(e) {
        if(e!=undefined && e.target!=undefined && e.target.id!=undefined && e.target.id.indexOf("popovercloseid" )!=-1)
        {
       	 var pop=e.target.id.split("#");
       	 var ddv="#"+pop[1];
       	 jQuery(ddv).popover('hide');
        }
    });
}

function addControlsInici(){

	var sidebar = L.control.sidebar('sidebar', {
		position : 'left',
		closeButton : false
	});

	map.addControl(sidebar);
	setTimeout(function() {
		sidebar.show();
	}, 500);

	controlCapes = L.control.orderlayers(null, null, {
		collapsed : false,
		id : 'div_capes',
		editMode: true,
		autoUpdate: false
	}).addTo(map);

	map.on('addItemFinish',function(){
		$(".layers-list").mCustomScrollbar("destroy");
		$(".layers-list").mCustomScrollbar({
			   advanced:{
			     autoScrollOnFocus: false,
			     updateOnContentResize: true
			   }
		});
	});

	var ctr_llistaCapes = L.control({
		position : 'topright'
	});
	ctr_llistaCapes.onAdd = function(map) {

		this._div = L.DomUtil.create('div', 'div_barrabotons btn-group-vertical');
		//this._div_H_Export= L.DomUtil.create('div', 'div_barraexport div_gr40');

		var btllista = jQuery("<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_llista\" title=\"Llista de capes\" data-lang-title=\"Llista de capes\"><span class='glyphicon glyphicon-th-list grisfort'></span></div>");
		this._div.appendChild(btllista[0]);



			var bt3D_2D = jQuery("<div data-toggle=\"tooltip\" class=\"leaflet-bar btn btn-default btn-sm bt_3D_2D\" title=\"Canviar vista\" data-lang-title=\"Canviar vista\"><span class='text3D'>3D</span></div>");
			this._div.appendChild(bt3D_2D[0]);




		return this._div;
	};
	ctr_llistaCapes.addTo(map);

	ctr_exportMap = L.control.mapExport({
				title: window.lang.translate('Exportar i imprimir mapa')
			});
	ctr_exportMap.addTo(map);

	jQuery('.div_barrabotons .leaflet-bar').tooltip({
		placement : 'left',
		container : 'body'
	});

	 ctr_vistaInicial = L.control({
		position : 'topleft'
	});

	ctr_vistaInicial.onAdd = function(map) {

		this._div = L.DomUtil.create('div', 'leaflet-bar bt_house');
		this._div.id='dv_bt_vistaInicial';
		this._div.title=window.lang.translate('Vista inicial');
		this._div.innerHTML = '<span id="span_bt_vistaInicial" class="fa fa-home grisfort"></span>';
		return this._div;
	};
	ctr_vistaInicial.addTo(map);
}


function addToolTipsInici() {

}

function updateLangTooltips(){
	jQuery('body').on('show.bs.tooltip','[data-toggle="tooltip"]',function(){
		jQuery(this).attr('data-original-title', window.lang.translate(jQuery(this).data('lang-title')));
	});

	jQuery("#dv_bt_vistaInicial").on('click',function(e){
		if (mapConfig.options && mapConfig.options.bbox){
			var bbox = mapConfig.options.bbox.split(",");
			var southWest = L.latLng(bbox[1], bbox[0]);
		    var northEast = L.latLng(bbox[3], bbox[2]);
		    var bounds = L.latLngBounds(southWest, northEast);
			map.fitBounds( bounds );
		}
		else if (mapConfig.options && mapConfig.options.center){
			var opcenter = mapConfig.options.center.split(",");
			map.setView(L.latLng(opcenter[0], opcenter[1]), mapConfig.options.zoom);
		}else{


			map.setView([ 41.4324, 1.1453 ], 8);
		}
		aturaClick(e);
	});
}

function updateLangText(){

	//Add tooltip caixa cerca
	jQuery(".leaflet-control-search .search-button, .glyphicon-search").attr('title',window.lang.translate('Cercar llocs o coordenades ...'));
	jQuery(".leaflet-control-search .search-input").attr('placeholder',window.lang.translate('Cercar llocs o coordenades ...'));

	$('#funcio_draw #funcio_draw_titol_1').html(window.lang.translate("Situar un punt"));
	$('#funcio_draw #funcio_draw_titol_2').html(window.lang.translate("Dibuixar una línia o un polígon"));
	$('#funcio_tematics>h5').html(window.lang.translate("Triar l'estil de la capa"));
	$('#funcio_fonsMapes>h5').html(window.lang.translate("Escollir el mapa de fons"));
	var txtBoto="";
	if (mapConfig.bloquejat!=undefined  && mapConfig.bloquejat!='' && mapConfig.bloquejat!='[{}]' && mapConfig.bloquejat!='N'
		&& mapConfig.bloquejat!='[{"bloquejat":"N"}]' && mapConfig.bloquejat!='[{"uid":null,"bloquejat":null}]'){
		txtBoto="Desar / Desbloquejar";
	}
	else{
		txtBoto="Desar / Publicar el mapa";
	}
	$('.bt_publicar>span').html(window.lang.translate(txtBoto));
	$('#socialShare>h5').html(window.lang.translate("Compartir"));

	//Traducció dels textos del modal de publicar
	$('#titlePublicar').text(window.lang.translate('Publicar el mapa'));
	$('#id_info_tab').text(window.lang.translate('Informació'));
	$('#id_privacitat_tab').text(window.lang.translate('Privacitat'));
	$('#id_llegenda_tab').text(window.lang.translate('Llegenda'));
	$('#id_reuse_tab').text(window.lang.translate('Reutilització'));


	$('#nomAplicacioPub').attr("placeholder", window.lang.translate("Nom"));
    $('#optDescripcio').attr("placeholder", window.lang.translate("Descripció"));
    $('#optTags').attr("placeholder", window.lang.translate("Etiquetes"));
	$('#publish-warn-text').text(window.lang.translate('El mapa es publicarà amb la vista actual: àrea geogràfica, nivell de zoom i capes visibles'));


    $('#llegendaTitle').text(window.lang.translate('Llegenda'));
    $('#textLegend').text(window.lang.translate('Escull si vols o no generar la llegenda associada al mapa'));

    $('#checkObert').text(window.lang.translate('Obert'));
    $('#checkRestringit').text(window.lang.translate('Restringit'));
    $('#txtPublic').text(window.lang.translate("Tothom amb l'enllaç pot accedir al mapa"));
    $('#txtPrivat').text(window.lang.translate("L'accés al mapa es protegit amb clau"));
    $('#checkPublic').text(window.lang.translate('Públic'));
    $('#checkPrivat').text(window.lang.translate('Privat'));
    $('#txtVisible').text(window.lang.translate('El mapa és visible a la galeria pública'));
    $('#txtNoVisible').text(window.lang.translate('El mapa només és visible a la teva galeria privada'));
    $('#resetClau').text(window.lang.translate('Reiniciar'));

    $('#cancelPublicar').text(window.lang.translate('Cancel·lar'));
    $('#okPublicar').text(window.lang.translate('Publicar'));

}

function loadMapConfig(mapConfig){
	//console.debug(mapConfig);
	var dfd = jQuery.Deferred();
	var instamapsLayers = InstamapsLayers({map: map, edit: true});
	if (!jQuery.isEmptyObject( mapConfig )){
		jQuery('#businessId').val(mapConfig.businessId);
		//TODO ver los errores de leaflet al cambiar el mapa de fondo
		//cambiar el mapa de fondo a orto y gris
		if (mapConfig.options != null){
			if (mapConfig.options.fons){
				var fons = mapConfig.options.fons;
				if (fons == 'topoMap'){
					map.topoMap();
				}else if (fons == 'topoMapGeo') {
					map.topoMapGeo();
				}else if (fons == 'ortoMap') {
					map.ortoMap();
				}else if (fons == 'terrainMap') {
					map.terrainMap();
				}else if (fons == 'topoGrisMap') {
					map.topoGrisMap();
				}else if (fons == 'historicOrtoMap') {
					map.historicOrtoMap();
				}else if (fons == 'historicMap') {
					map.historicMap();
				}else if (fons == 'hibridMap'){
					map.hibridMap();
				}else if (fons == 'historicOrtoMap46'){
					map.historicOrtoMap46();
				}else if (fons == 'alcadaMap'){
					map.alcadaMap();
				}else if (fons == 'naturalMap') {
					map.naturalMap();
				}else if (fons == 'divadminMap') {
					map.divadminMap();
				}else if (fons == 'hibridTerrainMap') {
					map.hibridTerrainMap();
				}else if (fons.indexOf('colorBlankMap')!=-1) {
					map.colorBlankMap(fons);
				}else if (fons == 'colorMap') {
					map.colorMap(mapConfig.options.fonsColor);
				}
				map.setActiveMap(mapConfig.options.fons);
				map.setMapColor(mapConfig.options.fonsColor);
				//map.gestionaFons();
			}
			if (mapConfig.options.center){
				var opcenter = mapConfig.options.center.split(",");
				map.setView(L.latLng(opcenter[0], opcenter[1]), mapConfig.options.zoom);
			}else if (mapConfig.options.bbox){
				var bbox = mapConfig.options.bbox.split(",");
				var southWest = L.latLng(bbox[1], bbox[0]);
			    var northEast = L.latLng(bbox[3], bbox[2]);
			    var bounds = L.latLngBounds(southWest, northEast);
				map.fitBounds( bounds );
			}
		}

		instamapsLayers._loadAllLayers(mapConfig, controlCapes).then(function(){
			//self._updateLayerControl();
			controlCapes.forceUpdate(true);
		});



		/*
		//carga las capas en el mapa
		loadOrigenWMS().then(function(results){
			var num_origen = 0;
			jQuery.each(results.origen, function(index, value){
				loadLayer(value).then(function(){
					num_origen++;
					if (num_origen == results.origen.length){
						jQuery.each(results.sublayers, function(index, value){
							loadLayer(value);
						});
					}
				});
			});
		});
		*/

		map.on('zoomend', function (e) {
			jQuery.each(controlCapes._layers, function(i, obj){
				refrescarZoomEtiquetes(obj.layer);
			 });
		});

		jQuery('#div_loading').hide();
		//console.warn("Capes afegides")
	}

	dfd.resolve();
	return dfd.promise();
}

function loadOrigenWMS(){
	var dfd = $.Deferred();
	var layer_map = {origen:[],sublayers:[]};
	jQuery.each(mapConfig.servidorsWMS, function(index, value){
		//TODO parsear las options y el group y dejarlo en json.
		//TODO quitar el parse de cada tipo de capa.
		if(value.options && value.capesGroup){
			var options;

			if(typeof (value.options)=="string"){
				try {
					options = JSON.parse(value.options);
				}
				catch (err) {
					options = value.options;
				}

			}else{

				options = value.options;
			}

			var group ;

			if(typeof (value.capesGroup)=="string"){
				try {
					group = JSON.parse(value.capesGroup);
				}
				catch (err) {
					group =value.capesGroup;
				}

			}else{

				group = value.capesGroup;
			}


			options.group = group;
			value.options = JSON.stringify(options);
		}

		if(value.capesOrdre == capesOrdre_sublayer){
			layer_map.sublayers.push(value);
			lsublayers.push(value);
		}else{
			layer_map.origen.push(value);
		}
	});
	//NOu
	/*
	jQuery.each(layer_map.origen, function(index, value){
		var options=JSON.parse(value.options);
		controlCapes._addGroupFromObject(options.group);
	});
	*/

jQuery.each(layer_map.origen, function(index, value){
		var jsonOptions;
		if(typeof (value.options)=="string"){
			try {
				jsonOptions = JSON.parse(value.options);
			}
			catch (err) {
				jsonOptions = value.options;
			}

		}else{

			jsonOptions = value.options;
		}

		if(jsonOptions && jsonOptions.group){
			controlCapes._addGroupFromObject(jsonOptions.group);
		}

	});

	dfd.resolve(layer_map);
	return dfd.promise();
}

function loadLayer(value){

	//console.info("loadLayer");
	//console.info(value);
	var defer = $.Deferred();

	if (value.epsg == "4326"){
		value.epsg = L.CRS.EPSG4326;
	}else if (value.epsg == "25831"){
		value.epsg = L.CRS.EPSG25831;
	}else if (value.epsg == "23031"){
		value.epsg = L.CRS.EPSG23031;
	}else{
		value.epsg = map.crs;
	}

	//Si la capa es de tipus wms
	if(value.serverType == t_wms){
		loadWmsLayer(value);
		defer.resolve();
	//Si la capa es de tipus json
	}else if(value.serverType == t_json){
		loadCapaFromJSON(value).then(function(){
			defer.resolve();
		});
		//Si la capa es de tipus url file
	}else if(value.serverType == t_url_file){
		loadURLfileLayer(value).then(function(){
			defer.resolve();
		});
	//Si la capa es de tipus geojsonVT
	}else if(value.serverType == t_geojsonvt){
		loadGeojsonvtLayer(value);
		defer.resolve();
	//Si la capa es de tipus geojsonVT
	}else if(value.serverType == t_geojsonvt){
		loadGeojsonvtLayer(value);
		defer.resolve();
	//Si la capa es de tipus dades obertes
	}else if(value.serverType == t_dades_obertes){
		loadDadesObertesLayer(value).then(function(){
			defer.resolve();
		});
	//Si la capa es de tipus xarxes socials
	}else if(value.serverType == t_xarxes_socials){
		var options = jQuery.parseJSON( value.options );

		if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
		else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
		else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
		defer.resolve();
	}else if(value.serverType == t_tematic){
		loadTematicLayer(value).then(function(){
			defer.resolve();
		});
	}else if(value.serverType == t_visualitzacio){
		loadVisualitzacioLayer(value).then(function(){
			defer.resolve();
		});
	//Si la capa es de tipus vis_wms
	}else if(value.serverType == t_vis_wms || value.serverType == t_vis_wms_noedit){
		loadVisualitzacioWmsLayer(value);
		defer.resolve();
	}
	else if(value.serverType == tem_heatmap_wms || value.serverType == tem_cluster_wms){
		loadVisualitzacioWmsLayerSenseUtfGrid(value);
		defer.resolve();
	}
	return defer.promise();
}


function createNewMap(){
	//console.debug("createNewMap");
	var tipusApp = 'vis';

	if(isGeolocalUser() || (typeof url('?tipus') == "string" && url('?tipus')=="geolocal") ){
		tipusApp = 'geolo'; //para visores geolocal

	}

	var data = {
		nom: getTimeStamp(),
		uid: Cookies.get('uid'),
		visibilitat: visibilitat_privat,
		tipusApp: tipusApp,
	};

	createMap(data).then(function(results){
		if (results.status == "ERROR"){
			//TODO Mensaje de error
			gestioCookie('createMapError');
		}else{
			try{
				mapConfig = results.results;
				mapConfig.options = jQuery.parseJSON( mapConfig.options );
				jQuery('#businessId').val(mapConfig.businessId);
				mapConfig.newMap = false;

				//Si hi ha parametre enllac servei wms, etc
				var param = "";
				if(typeof url('?urlwms') == "string"){
					param = "&urlwms="+url('?urlwms')+"&layername="+url('?layername');
				}
//				console.debug(param);
				if (tipusApp=="geolo") window.location = paramUrl.mapaPage+"?businessid="+mapConfig.businessId+param+"&tipus=geolocal";
				else window.location = paramUrl.mapaPage+"?businessid="+mapConfig.businessId+param;

			}catch(err){
				gestioCookie('createMap');
			}
		}
	});
}

/**
 * Obtener los businessId de las capas para crear los json
 */
function getBusinessIdOrigenLayers(){
    var lBusinessId = "";
    jQuery.each(controlCapes._layers, function(i, item){
          lBusinessId += item.layer.options.businessId +",";
          jQuery.each(item._layers, function(j, subitem){
        	  if( subitem.layer.options.tipusRang == tem_simple || subitem.layer.options.tipusRang == tem_clasic){
            	  lBusinessId += subitem.layer.options.businessId +",";
              }
          });
    });
    lBusinessId = lBusinessId.substring(0, lBusinessId.length - 1);
    return lBusinessId;

}

function getTrafficLightKeys()
{

	var lBusinessId = "";
	jQuery.each(controlCapes._layers, function(i, item){
		lBusinessId += ",";
		jQuery.each(item._layers, function(j, subitem){
			if( subitem.layer.options.tipusRang == tem_simple || subitem.layer.options.tipusRang == tem_clasic)
			{

				if(subitem.layer.options.hasOwnProperty("trafficLightValue"))
					lBusinessId += subitem.layer.options.trafficLightValue +",";
				else
					lBusinessId += ",";

			}
		});
    });
    lBusinessId = lBusinessId.substring(0, lBusinessId.length - 1);
    return lBusinessId;

}

function loadControls(configuracio){
	//funcionalitats a carregar nomes si esta loginat
	if (Cookies.get('uid')){
		jQuery.each(configuracio.funcionalitatsLoginat, function(i, funcionalitatLoginat){
			eval(funcionalitatLoginat);
		});
	}
	jQuery.each(configuracio.funcionalitats, function(i, funcionalitat){
		eval(funcionalitat);
	});
}

function loadConfiguracio(configuracio){
	var dfd = new jQuery.Deferred();
	if(configuracio){
		configuracio = $.parseJSON(mapConfig.configuracio);
		dfd.resolve(configuracio);
	}else{
		jQuery.get('../../default_config_mapa_0.4.txt', function(data) {
			   configuracio = $.parseJSON(data);
			   dfd.resolve(configuracio);
		});
	}
	return dfd.promise();
}

function addLeaveModal(){
	addHtmlModalLeave();

	if (isRandomUser(Cookies.get('uid'))){
		jQuery('#hl_sessio1').attr('href', paramUrl.loginPage+"?from=mapa");

		jQuery('.navbar-form .bt-sessio').on('click',function(){
			jQuery(window).off('beforeunload');
			jQuery(window).off('unload');
			window.location = paramUrl.loginPage+"?from=mapa";
		});

		jQuery('#dialgo_leave').modal('show');
		jQuery('#dialgo_leave .bt-sessio').on('click',function(){
			jQuery(window).off('beforeunload');
			jQuery(window).off('unload');
			window.location = paramUrl.loginPage+"?from=mapa";
		});

		jQuery('#dialgo_leave .bt_orange').on('click',function(){
			jQuery(window).off('beforeunload');
			jQuery(window).off('unload');
			window.location = paramUrl.registrePage+"?from=mapa";
		});

		jQuery('#dialgo_leave').on('hide.bs.modal', function (e) {

		});

		jQuery(window).on('unload',function(event){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'sortir', 'label sortir', 1]);
			deleteRandomUser({uid: Cookies.get('uid')});
			Cookies.remove('uid');
		});
	}else{
		jQuery('#dialgo_leave .btn-primary').on('click',function(){
			leaveMapa();
		});
	}

	$('.leaflet-remove').click(function() {
		alert( "Handler for .click() called." );
	});

	//boton de comentaris
	jQuery('#feedback_btn').on('click',function(e){
		window.open(paramUrl.comentarisPage);
	});
	//Missatge error de carrega de dades
	jQuery("#div_carrega_dades_message").hide();
	jQuery('#dialog_carrega_dades').on('hidden.bs.modal', function (e) {
		jQuery("#div_carrega_dades_message").hide();
	});

}

function nobackbutton(){
	window.location.hash="no-back-button";
    window.location.hash="Again-No-back-button" //chrome
    window.onhashchange=function(){window.location.hash="no-back-button";}
}

function refrescarZoomEtiquetes(obj){
	if (obj.options.opcionsVisEtiqueta!=undefined && (obj.options.opcionsVisEtiqueta=="nomesetiqueta" ||
			obj.options.opcionsVisEtiqueta=="etiquetageom")){
	 		var zoomInicial = "2";
	 		if (obj.options.zoomInicial) zoomInicial=obj.options.zoomInicial;
	 		var zoomFinal = "19";
	 		if (obj.options.zoomFinal) zoomFinal = obj.options.zoomFinal;

	 		if ( map.getZoom()>=zoomInicial &&  map.getZoom() <= zoomFinal) {//mostrem labels
				jQuery.each(obj._layers, function(i, lay){
					if (lay.label!=undefined) {
						if(lay.label){
							lay.label.setOpacity(1);
						}
						if(lay._showLabel){
	                        lay._showLabel({latlng: lay.label._latlng});
						}
					}
				});
	 		 }
	 		 else {//amaguem labels
				jQuery.each(obj._layers, function(i, lay){
					if(lay.label){
						lay.label.setOpacity(0);
					}
				});
			 }
	}
}

function addHtmlModalBloqueigMapa(){
	$.get("templates/modalBloqueigMapa.html",function(data){
		$('#mapa_modals').append(data);
		//Desbloquejar el mapa
		$('#dialog_bloqueig_mapa .btn-danger').on('click', function(event){
			window.clearTimeout(timeoutBloqueig);
			$('#dialog_bloqueig_mapa').modal('hide');
			treureBloqueigMapa();
		});
		//Continuar treballant amb el mapa
		$('#dialog_bloqueig_mapa .btn-default').on('click', function(event){
			window.clearTimeout(timeoutBloqueig);
			$('#dialog_bloqueig_mapa').modal('hide');
			//Reinicialitzar el temps del controlador!
			lockController.start();
		});
	});
}

function addHtmlModalInfoBloqueigMapa(){
	$.get("templates/modalInfoBloqueigMapa.html",function(data){
		$('#mapa_modals').append(data);
		$('#dialog_info_bloqueig_mapa .btn-default').on('click', function(event){
			$('#dialog_info_bloqueig_mapa').modal('hide');
		});

	});
}

function addInfoBloqueigMapa(mapConfig){
	addHtmlModalInfoBloqueigMapa();
	//Si és un mapa col·laboratiu mostrem la finestra de informació de bloqueig
	if (typeof mapConfig.bloquejat == "string" && mapConfig.bloquejat.indexOf("bloquejat")>-1  && mapConfig.bloquejat.indexOf("null")==-1) {
		setTimeout(function() {
			$('#dialog_info_bloqueig_mapa').modal('show');
		}, 1000);
	}
}

/*TODO estas funciones estaban pensadas para prevenir al usaurio al abandonar
la pagína sin publicar el mapa. La idea era que al entrar en un mapa nuevo
se creara el mapa en la BD y que el si el usuario abandona la página sin publicar se
mostrara el mensaje de advertencia y se borrara el mapa.
*/
/*
function avisDesarMapa(){
	//console.debug(mapConfig.newMap);
	if (mapConfig.newMap){
		jQuery(window).on('beforeunload',function(event){
			//$('#dialgo_leave').modal('show');
			//event.stopPropagation();
			//event.preventDefault();
			//console.debug("antes de ir e");
			//return "Mensaje de aviso que no se muestra en Firefox";
		});
	}else{
		jQuery(window).off('beforeunload',function(){
			return true;
		});
	}
}

function leaveMapa(){
	console.debug("borrar el mapa e ir a la galeria");
}
*/
<file_sep>/moduls/psolar/js/L.TileLayer.BetterWMS.PSolar.js
L.TileLayer.BetterWMS = L.TileLayer.WMS.extend({
		onAdd : function (map) {
			// Triggered when the layer is added to a map.
			// Register a click listener, then do all the upstream WMS things
			
			this.options.maxZoom = 19;
			L.TileLayer.WMS.prototype.onAdd.call(this, map);
			map.on('click', this.getFeatureInfo, this);
			addBarraPSolar();
			activaPanelCapes(true);			
			addControLSolarLL();
			var params = this.getLegendGraphic();
			updateLLegendaPSolar(params,this.wmsParams.layers,true);
			
		},
		onRemove : function (map) {
			// Triggered when the layer is removed from a map.
			// Unregister a click listener, then do all the upstream WMS things
			L.TileLayer.WMS.prototype.onRemove.call(this, map);
			map.off('click', this.getFeatureInfo, this);
			esborraCapes();
			jQuery('#psolar_info_dv').hide();
			//if (this.wmsParams.layers.indexOf('irradiacio_global_calculada') != -1) {
			//jQuery('#psolar_info_dvLL').hide();
			//}
			var params = this.getLegendGraphic();
			//console.info(this.wmsParams.layers);
			updateLLegendaPSolar(params,this.wmsParams.layers,false);
			
		},
		getFeature : function (feature) {

		var that=this;
		
			var newFeature = feature[0];
			var coords = "";
			for (var z = 0; z < newFeature.length; z++) {

				coords = coords + newFeature[z][0] + "," + newFeature[z][1] + "%20";

			}

			var obj = jQuery.trim(coords);
			var params = this.getFeatureUrl();

			var urlApp = document.location.href;
			if ((urlApp.indexOf('localhost') != -1) || (urlApp.indexOf('.local') != -1) || (urlApp.indexOf('192.168.127.12') != -1)) {
				params = params.replace('betaserver.icgc.cat', '172.16.31.10');
				params = params.replace('www.instamaps.cat', '192.168.127.12');
				
				//params = params.replace('192.168.127.12', 'localhost');
			}
			//params=params.replace('betaserver.icgc.cat','172.16.17.32');


			var paramsWFS = this.wfsFyer(params, this.wmsParams.layers, map.getZoom(), obj, 'area');

			if (paramsWFS.capa != null) {
				if (map.hasLayer(capaGeoJSON_SOLAR)) {
					map.removeLayer(capaGeoJSON_SOLAR);
					
					map.on('click',function(e){ 
						that.getFeatureInfo(e);
						});
					
				}
			
				if((params.indexOf('instamaps.cat')!=-1) || (params.indexOf('instaweb') != -1) || (params.indexOf('192.168.127.12') != -1)){
										
									jQuery.ajax({
										url : paramsWFS.url,
										
										always : function (data, status, xhr) {
											map.spin(false);

										},
										success : function (geojson, status, xhr) {
											map.spin(false);

											if (geojson.features) {
												iniciaInfoPSolar(paramsWFS.capa, geojson);

											}

										},
										error : function (xhr, status, error) {
											map.spin(false);
										}

									});	
										
										
										
									}else{
				
				
				
				jQuery.ajax({
					url : paramUrl.proxy_betterWMS,
					data : {
						url : paramsWFS.url
					},
					always : function (data, status, xhr) {
						map.spin(false);

					},
					success : function (geojson, status, xhr) {
						map.spin(false);

						if (geojson.features) {
							iniciaInfoPSolar(paramsWFS.capa, geojson);

						}

					},
					error : function (xhr, status, error) {
						map.spin(false);
					}

				});
				
									}
				
				
				
				

			}// Fi If

			setTimeout(function () {
				heFetUnClick = true
			}, 3000);
			//heFetUnClick=true;

		},
		getFeatureUrl : function () {

			params = {
				request : 'GetFeature',
				service : 'WFS',
				srs : 'EPSG:4326',
				version : '1.0.0',
				//format: this.wmsParams.format,
				//filter: filter,
				//typename:capa;
				outputformat : 'geojson'
			};

			return this._url + L.Util.getParamString(params, this._url, true);

			return params;

		},
		getFeatureInfo : function (evt) {

		var that=this;
		
		
			if (heFetUnClick) {
				tancaFinestra();				
				var params = this.getFeatureUrl();			
				aturaClick(evt);

				var urlApp = document.location.href;
				if ((urlApp.indexOf('localhost') != -1) || (urlApp.indexOf('.local') != -1) || (urlApp.indexOf('192.168.127.12') != -1)) {
					params = params.replace('betaserver.icgc.cat', '172.16.31.10');
					params = params.replace('www.instamaps.cat', '192.168.127.12');
					
					//params = params.replace( '192.168.127.12','localhost');
				}
				
				
				var paramsWFS = this.wfsFyer(params, this.wmsParams.layers, map.getZoom(), evt.latlng, 'click');

				if (paramsWFS.capa != null) {
					if (map.hasLayer(capaGeoJSON_SOLAR)) {
						//map.clearLayers(capaGeoJSON_SOLAR);
						
						map.removeLayer(capaGeoJSON_SOLAR);	
						
						map.on('click',function(e){ 
						that.getFeatureInfo(e);
						});
						
					}
					

									if((params.indexOf('instamaps.cat')!=-1) || (params.indexOf('instaweb') != -1)|| (params.indexOf('192.168.127.12') != -1)){
										
									jQuery.ajax({
										url : paramsWFS.url,
										
										always : function (data, status, xhr) {
											map.spin(false);

										},
										success : function (geojson, status, xhr) {
											map.spin(false);

											if (geojson.features) {
												iniciaInfoPSolar(paramsWFS.capa, geojson);

											}

										},
										error : function (xhr, status, error) {
											map.spin(false);
										}

									});	
										
										
										
									}else{
									jQuery.ajax({
										url : paramUrl.proxy_betterWMS,
										data : {url : paramsWFS.url},
										always : function (data, status, xhr) {
											map.spin(false);

										},
										success : function (geojson, status, xhr) {
											map.spin(false);

											if (geojson.features) {
												iniciaInfoPSolar(paramsWFS.capa, geojson);

											}

										},
										error : function (xhr, status, error) {
											map.spin(false);
										}

									});

									}//fi else
				
				
				
				
				
				}//fi if
			}

			
			
		},

		getLegendGraphic : function () {

			params = {
				request : 'GetLegendGraphic',
				service : 'WMS',
				version : this.wmsParams.version,
				format : this.wmsParams.format,
				layer : this.wmsParams.layers

			};

			return this._url + L.Util.getParamString(params, this._url, true);

			return params;

		},

		getFeatureInfoUrl : function (latlng) {
			var bounds = this._map.getBounds();
			var SRS = this.wmsParams.srs;
			var BBOX = bounds.toBBoxString();
			if (SRS.indexOf('3857') != -1) {
				var NW = L.CRS.EPSG3857.project(bounds.getNorthWest());
				var SE = L.CRS.EPSG3857.project(bounds.getSouthEast());

				BBOX = NW.x + "," + SE.y + "," + SE.x + "," + NW.y;

			}

			// Construct a GetFeatureInfo request URL given a point
			var point = this._map.latLngToContainerPoint(latlng, this._map.getZoom()),
			size = this._map.getSize(),
			params = {
				request : 'GetFeatureInfo',
				service : 'WMS',
				srs : SRS,
				styles : this.wmsParams.styles,
				transparent : this.wmsParams.transparent,
				version : this.wmsParams.version,
				format : this.wmsParams.format,
				bbox : BBOX,
				//bbox: ""+bounds.getSouth()+","+bounds.getWest()+","+bounds.getNorth()+","+bounds.getEast()+"",
				height : size.y,
				width : size.x,
				layers : this.wmsParams.layers,
				query_layers : this.wmsParams.layers,
				info_format : 'text/html'
			};
			params[params.version === '1.3.0' ? 'i' : 'x'] = point.x;
			params[params.version === '1.3.0' ? 'j' : 'y'] = point.y;
			return this._url + L.Util.getParamString(params, this._url, true);

			return params;
		},
		showGetFeatureInfo : function (err, latlng, content) {
			if (err) {
				console.log(err);
				return;
			} // do nothing if there's an error
			// Otherwise show the content in a popup, or something.
			L.popup({
				maxWidth : 800
			})
			.setLatLng(latlng)
			.setContent(content)
			.openOn(this._map);
		},

		wfsFyer : function (params, capa, zoom, latlng, tipus) {

			if (zoom >= 18) {

				if (capa.indexOf('_fotovoltaic') != -1) {
					capa = T_FV;
				} else if (capa.indexOf('_termosolar') != -1) {
					capa = T_TS;
				} else {
					capa = null;
				}
				//fotovoltaic
				//termosolar

			} else {

				if (capa.indexOf('_fotovoltaic') != -1) {
					capa = E_FV;
				} else if (capa.indexOf('_termosolar') != -1) {
					capa = E_TS;
				} else {
					capa = null;
				}

			}

			var filter = "";
			if (tipus == 'click') {
				/*

				filter="FILTER=<Filter><Intersects><PropertyName>Geometry</PropertyName><gml:Point>"+
				"<gml:coordinates>"+latlng.lng+","+latlng.lat+"</gml:coordinates></gml:Point><Distance units='m'>1</Distance>"+
				"</Intersects></Filter>";
				 */

				filter = "FILTER=<Filter>" +
					"<BBOX><PropertyName>NAME</PropertyName><Box%20srsName='EPSG:4326'>" +
					"<coordinates>" + latlng.lng + "," + latlng.lat + "%20" + parseFloat(latlng.lng + 0.00001) + "," + parseFloat(latlng.lat + 0.00001) + "</coordinates></Box></BBOX>" +
					"</Filter>";

			} else {

				//filter="FILTER=<Filter><Intersects><PropertyName>Geometry</PropertyName><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>"+latlng+"</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></Intersects></Filter>";

				filter = "FILTER=<Filter><Within><PropertyName>Geometry</PropertyName><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>" + latlng + "</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></Within></Filter>";

			}

			params = params.replace("REQUEST=GetFeatureInfo", "REQUEST=GetFeature");
			params = params.replace("SERVICE=WMS", "SERVICE=WFS");
			// params=params.replace("LAYERS=","TYPENAME=");
			params = params.replace("VERSION=1.1.1", "VERSION=1.1.0");
			params = params + "&OUTPUTFORMAT=geojson&MAXFEATURES=300&TYPENAME=" + capa + "&" + filter;

			var wfs = {
				url : params,
				capa : capa
			};

			return wfs;

		}

	});

L.tileLayer.betterWms = function (url, options) {
	return new L.TileLayer.BetterWMS(url, options);
};
<file_sep>/geocatweb/js/leaflet/L.IM_HomeControl.js
/**
 * L.Control.Home control que permite volver a la vista inicial del mapa
 */
L.Control.Home = L.Control.extend({
	options: {
		position: 'topleft',
		id: 'dv_bt_vistaInicial',
		className: 'leaflet-bar  btn btn-default btn-sm',
		title: 'Vista inicial',
		langTitle: 'Vista inicial',
		html: '<span id="span_bt_vistaInicial" class="fa fa-home grisfort"></span>',
		tooltip: 'right'
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			stop = L.DomEvent.stopPropagation,
			container = L.DomUtil.create('div', options.className);
		
		container.id = options.id;
		container.innerHTML = options.html;
		container.title = options.title;
		
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		
		map.on('loadconfig', self._updateMapConfig, self);
		map.on('visorconfig', self._updateMapConfig, self);
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', self._goHome, self);
		return container;
	},
	
	onRemove: function (map) {
		map.off('loadconfig', this._updateMapConfig, this);
		map.off('visorconfig', this._updateMapConfig, this);
	},
	
	_goHome: function(e){
		var _mapConfig = this.options.mapConfig,
			_map = this._map;
		
		if(_mapConfig){
			if (_mapConfig.options.bbox){
				var bbox = _mapConfig.options.bbox.split(",");
				var southWest = L.latLng(bbox[1], bbox[0]);
			    var northEast = L.latLng(bbox[3], bbox[2]);
			    var bounds = L.latLngBounds(southWest, northEast);
			    _map.fitBounds( bounds );
			}
			else if (_mapConfig.options.center){
				var opcenter = _mapConfig.options.center.split(",");
				_map.setView(L.latLng(opcenter[0], opcenter[1]), _mapConfig.options.zoom);
			}
		}
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
	
	_updateMapConfig: function(config){
		this.options.mapConfig = config;
	}
});

L.control.home = function(options){
	return new L.Control.Home(options);
};<file_sep>/geocatweb/js/leaflet/L.IM_SearchControl.js
/**
 * L.Control.SearchControl control que permite hacer busquedas con caja única 
 */
L.Control.SearchControl = L.Control.extend({
	options: {
		position: 'topleft',
		id: 'dv_bt_Find',
		className: 'leaflet-bar btn btn-default btn-sm grisfort',
		title: 'Cercar',
		langTitle: 'Cercar',
		html: '<span id="span_bt_Find" class="fa fa-search"></span>',
		idInputText: 'ctr_cerca',
		inputplaceholderText: 'Cercar llocs al món o coordenades  ...',
		tooltip: 'right'
	},
	
	initialize: function(options){
		L.setOptions(this, options);
		
		var self = this,
		options = this.options,
		inputText = L.DomUtil.create('div', options.idInputText);
		
		inputText.id = options.idInputText;
		jQuery('#searchBar').addClass("input-group").append(inputText);
	},
	
	onAdd: function(map){
		var self = this,
		options = self.options,
		stop = L.DomEvent.stopPropagation,
		container = L.DomUtil.create('div', options.className);
		
		//agregar el boton
		container.id = options.id;
		container.innerHTML = options.html;
		container.title = options.title;
		
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', L.DomEvent.preventDefault)
			.on(container, 'click', self._toggle, self);
		
		//agregar el control
		//TODO extender el control de origen en lugar de modificarlo
		self.control = new L.Control.Search({url: options.searchUrl,
			position:'topcenter',
			filterJSON: self._filterJSON,
			animateLocation: false,
			markerLocation: false,
			zoom: 12,
			minLength: 3,
			autoType: false,
			text:options.inputplaceholderText,
			idInputText : '#'+options.idInputText,
			zoom : 14,
			textSize : 22,
			autoCollapseTime: 3200
		}).addTo(map);
		
		return container;
	},
	
	_filterJSON: function(rawjson){
		var self = this,
		jsonData = JSON.parse(rawjson.resposta),
		json = {},
		key, 
		loc, 
		disp = [];
		
		if (jsonData.resultats.length>1){
			for (var i = 0; i < jsonData.resultats.length; i++) {
			    var resultat = jsonData.resultats[i];
			    var coordsSplit = resultat.coordenades.split(",");
			    json[ resultat.nom ] = L.latLng(coordsSplit[0], coordsSplit[1]);
			}
		}
		else {
			if (jsonData.resultats.length>0){
				var coords= jsonData.resultats[0].coordenades;
				var nom = jsonData.resultats[0].nom;
				var coordsSplit = [];
				if (coords) {
					coordsSplit = coords.split(",");
					loc = L.latLng(coordsSplit[0], coordsSplit[1] );
					console.debug(self);
					self.showLocation(loc,coords,nom); 
				}
			}
			else self.showAlert(self.control.options.textErr);
		}
		return json;
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
	
	hide: function() {
		L.DomUtil.removeClass(this._div, 'greenfort');
		L.DomUtil.addClass(this._div, 'grisfort');
		$('#searchBar').hide();
	},
	
	show: function(e){
		L.DomUtil.removeClass(this._div, 'grisfort');
		L.DomUtil.addClass(this._div, 'greenfort');
		var offset = $(this._div).offset();
		$('#searchBar').css('top', (offset.top - 15) +'px');
		$('#searchBar').css('left', (offset.left + 35) +'px');
		$('#searchBar').show();
	}, 
	
	_toggle: function(e){
		var collapsed = L.DomUtil.hasClass(this._div, 'grisfort');
		this[collapsed ? 'show' : 'hide']();
	},
});

L.control.searchControl = function(options){
	return new L.Control.SearchControl(options);
};<file_sep>/llibreries/js/leaflet/plugin/leaflet.utfgridWMS.js
/*
 Copyright (c) 2012, Smartrak, <NAME>
 Leaflet.utfgrid is an open-source JavaScript library that provides utfgrid interaction on leaflet powered maps.
 https://github.com/danzel/Leaflet.utfgrid
*/
(function (window, undefined) {

L.Util.ajaxGrid = function (url, cb) {
	// the following is from JavaScript: The Definitive Guide
	// and https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
	if (window.XMLHttpRequest === undefined) {
		window.XMLHttpRequest = function () {
			/*global ActiveXObject:true */
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch  (e) {
				throw new Error("XMLHttpRequest is not supported");
			}
		};
	}
	var response, request = new XMLHttpRequest();
	request.open("GET", url);
	request.onreadystatechange = function () {
		/*jshint evil: true */
		if (request.readyState === 4 && request.status === 200) {
			if (window.JSON) {
				if(request.responseText.toLowerCase().indexOf("error")!=-1){
					console.debug("ResponseText WMS error:"+request.responseText);
				}
				else if (request.responseText.toLowerCase().indexOf("mapserver message")!=-1){
					console.debug("MapServer Message:"+request.responseText);
				}
				else response = JSON.parse(request.responseText);
			} else {
				response = eval("(" + request.responseText + ")");
			}
			cb(response);
		}
	};
	request.send();
};


L.UtfGrid = L.Class.extend({
	includes: L.Mixin.Events,
	options: {
		subdomains: 'abc',

		minZoom: 0,
		maxZoom: 18,
		tileSize: 256,

		resolution: 4,

		useJsonP: false,
		pointerCursor: true
	},
	defaultWmsParams: {
		service: 'WMS',
		request: 'GetMap',
		version: '1.1.1',
		layers: '',
		styles: '',
		format: 'utfgrid',
		transparent: false
	},

	//The thing the mouse is currently on
	_mouseOn: null,

	initialize: function (url, options) {
		
		this._url = url;
		this._cache = {};

		//Find a unique id in window we can use for our callbacks
		//Required for jsonP
		var i = 0;
		while (window['lu' + i]) {
			i++;
		}
		this._windowKey = 'lu' + i;
		window[this._windowKey] = {};

		var subdomains = this.options.subdomains;
		if (typeof this.options.subdomains === 'string') {
			this.options.subdomains = subdomains.split('');
		}
		var wmsParams = L.Util.extend({}, this.defaultWmsParams);
		wmsParams.width = wmsParams.height = this.options.tileSize;

		for (var i in options) {
			// all keys that are not TileLayer options go to WMS params
			if (!this.options.hasOwnProperty(i)) {
				wmsParams[i] = options[i];
			}
		}

		this.wmsParams = wmsParams;

		L.Util.setOptions(this, options);
	},

	onAdd: function (map) {
		this._map = map;
		this._container = this._map._container;

		this._update();

		var zoom = this._map.getZoom();

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		map.on('click', this._click, this);
		map.on('mousemove', this._move, this);
		map.on('moveend', this._update, this);
	},

	onRemove: function () {
		var map = this._map;
		map.off('click', this._click, this);
		map.off('mousemove', this._move, this);
		map.off('moveend', this._update, this);
		if (this.options.pointerCursor) {
			this._container.style.cursor = '';
		}
	},

	_click: function (e) {
		this.fire('click', this._objectForEvent(e));
	},
	_move: function (e) {
		var on = this._objectForEvent(e);

		if (on.data !== this._mouseOn) {
			if (this._mouseOn) {
				this.fire('mouseout', { latlng: e.latlng, data: this._mouseOn });
				if (this.options.pointerCursor) {
					this._container.style.cursor = '';
				}
			}
			if (on.data) {
				this.fire('mouseover', on);
				if (this.options.pointerCursor) {
					this._container.style.cursor = 'pointer';
				}
			}

			this._mouseOn = on.data;
		} else if (on.data) {
			this.fire('mousemove', on);
		}
	},

	_objectForEvent: function (e) {
		var map = this._map,
		    point = map.project(e.latlng),
		    tileSize = this.options.tileSize,
		    resolution = this.options.resolution,
		    x = Math.floor(point.x / tileSize),
		    y = Math.floor(point.y / tileSize),
		    gridX = Math.floor((point.x - (x * tileSize)) / resolution),
		    gridY = Math.floor((point.y - (y * tileSize)) / resolution),
			max = map.options.crs.scale(map.getZoom()) / tileSize;

		x = (x + max) % max;
		y = (y + max) % max;
		
		var data = this._cache[map.getZoom() + '_' + x + '_' + y];
		if (!data) {
			return { latlng: e.latlng, data: null };
		}

		var idx = this._utfDecode(data.grid[gridY].charCodeAt(gridX)),
		    key = data.keys[idx],
		    result = data.data[key];

		if (!data.data.hasOwnProperty(key)) {
			result = null;
		}

		return { latlng: e.latlng, data: result};
	},

	//Load up all required json grid files
	//TODO: Load from center etc
	_update: function () {
		var bounds = this._map.getPixelBounds(),
		    zoom = this._map.getZoom(),
		    tileSize = this.options.tileSize;

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		var nwTilePoint = new L.Point(
				Math.floor(bounds.min.x / tileSize),
				Math.floor(bounds.min.y / tileSize)),
			seTilePoint = new L.Point(
				Math.floor(bounds.max.x / tileSize),
				Math.floor(bounds.max.y / tileSize)),
				max = this._map.options.crs.scale(zoom) / tileSize;

		//Load all required ones
		for (var x = nwTilePoint.x; x <= seTilePoint.x; x++) {
			for (var y = nwTilePoint.y; y <= seTilePoint.y; y++) {

				var xw = (x + max) % max, yw = (y + max) % max;
				var key = zoom + '_' + xw + '_' + yw;

				if (!this._cache.hasOwnProperty(key)) {
					this._cache[key] = null;

					if (this.options.useJsonP) {
						this._loadTileP(zoom, xw, yw);
					} else {
						this._loadTile(zoom, xw, yw);
					}
				}
			}
		}
	},

	_loadTileP: function (zoom, x, y) {
		var head = document.getElementsByTagName('head')[0],
		    key = <KEY>,
		    functionName = 'lu_' + key,
		    wk = this._windowKey,
		    self = this;

		var url = L.Util.template(this._url, L.Util.extend({
			s: L.TileLayer.prototype._getSubdomain.call(this, { x: x, y: y }),
			z: zoom,
			x: x,
			y: y,
			cb: wk + '.' + functionName
		}, this.options));

		
		/*var map = this._map,
		crs = map.options.crs,

		tileSize = this.options.tileSize,

	
		
		bounds = this._map.getBounds();
		var SRS="EPSG:4326";
		var bbox=bounds.toBBoxString();
		if(SRS.indexOf('3857')!=-1){
				var NW = L.CRS.EPSG3857.project(bounds.getNorthWest());
				var SE = L.CRS.EPSG3857.project(bounds.getSouthEast());
				  
				 bbox=NW.x+","+SE.y+","+SE.x+","+NW.y;
			
			}
		*/
		var tilePoint = new L.Point(x,y);
				
		  var map = this._map,
	          crs = map.options.crs,
	          tileSize = this.options.tileSize,
		  nwPoint = tilePoint.multiplyBy(tileSize),
		  sePoint = nwPoint.add([tileSize, tileSize]),

		  //nw = crs.project(map.unproject(nwPoint, zoom)),
		  //se = crs.project(map.unproject(sePoint, zoom)),

		  bbox = [nwPoint.x, sePoint.y, sePoint.x, nwPoint.y].join(','),
			
		url = url + (L.Util.getParamString(this.wmsParams)).replace("?","") + "&bbox=" + bbox;
		
				
		var script = document.createElement('script');
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url);

		window[wk][functionName] = function (data) {
			self._cache[key] = data;
			delete window[wk][functionName];
			//head.removeChild(script);
		};

		head.appendChild(script);
	},

	_loadTile: function (zoom, x, y) {
		var url = L.Util.template(this._url, L.Util.extend({
			s: L.TileLayer.prototype._getSubdomain.call(this, { x: x, y: y }),
			z: zoom,
			x: x,
			y: y
		}, this.options));
		
		
		/*bounds = this._map.getBounds();
		var SRS="EPSG:4326";
		var bbox=bounds.toBBoxString();
		if(SRS.indexOf('3857')!=-1){
				var NW = L.CRS.EPSG3857.project(bounds.getNorthWest());
				var SE = L.CRS.EPSG3857.project(bounds.getSouthEast());
				  
				 bbox=NW.x+","+SE.y+","+SE.x+","+NW.y;
			
			}
		*/


		  
		  
		  var tilePoint = new L.Point(x,y);
		  var tileSize = this.options.tileSize,
          nwPoint = tilePoint.multiplyBy(tileSize),
          sePoint = nwPoint.add([tileSize, tileSize]),
          nw = this._map.unproject(nwPoint),
          se = this._map.unproject(sePoint);
		  
		  var my_crs = this._map.options.crs; // get the CRS
		  var my_proj = my_crs.projection; // get the projection
		  // transform the lat lon Point to a utm point
		  var nw_utm = my_proj.project(nw); 
		  var se_utm = my_proj.project(se); 
          bbox = [nw.lng, se.lat, se.lng, nw.lat].join(','),
			
		url = url + (L.Util.getParamString(this.wmsParams)).replace("?","") + "&bbox=" + bbox;

		
		var key = <KEY>;
		var self = this;
		L.Util.ajaxGrid(url, function (data) {
			self._cache[key] = data;
		});
	},

	_utfDecode: function (c) {
		if (c >= 93) {
			c--;
		}
		if (c >= 35) {
			c--;
		}
		return c - 32;
	},
	openPopUp: function(data){
		
//		jQuery('#bt_info_geojsonvt_close').on('click', function (e) {
////			jQuery('#info_geojsonvt .div_popup_visor').html('');
//			jQuery('#info_geojsonvt').hide();
//		});
		
		var html ='';
		html+='<div class="popup_pres">';
		$.each( data, function( key, value ) {
			if(value!=undefined && value!=null && value != " "){
				html+='<div class="popup_data_row">';
				
				
					
					if(key.indexOf("ANY_ANTIC")!=-1) key = "ANY CONSTRUCCI&Oacute; LOCAL PRINCIPAL";
					else if(key.indexOf("TIPOLOGIA4")!=-1) key = "TIPOLOGIA";
					
					
					html+='<div class="popup_data_key">'+key+'</div>';
					html+='<div class="popup_data_value">'+value+'</div>';
				html+= '</div>';
			}
		});
		
		html+= '</div>';
		
		jQuery('#info_utfgrid .div_popup').html(html);
		jQuery('#info_utfgrid').css("border", "none");
		jQuery('#info_utfgrid').show();		
		
	}
	
});


L.utfGrid = function (url, options) {
	return new L.UtfGrid(url, options);
};


}(this));
<file_sep>/geocatweb/js/geocat.google-analytics.js
/**
 * 
 */
var _gaq = _gaq || [];

(function() {

	$.subscribe('loadConfig', function(e, data) {

		var _mapConfig = data;

		var perfil = Cookies.get('perfil');

		try {
			// Diferenciem entre usuari Geolocal i Instamaps
			if (isGeolocalUser()
					|| $(location).attr('href').indexOf('geolocal.html') != -1
					|| perfil === 'geolocal') {
				_gaq.push([ '_setAccount', 'UA-46332195-6' ]);

			} else if (_mapConfig
					&& _mapConfig.tipusAplicacioId == TIPUS_APLIACIO_GEOLOCAL) {
				_gaq.push([ '_setAccount', 'UA-46332195-6' ]);

			} else if (_mapConfig
					&& _mapConfig.tipusAplicacioId == TIPUS_APLIACIO_AOC) {
				_gaq.push([ '_setAccount', 'UA-46332195-6' ]);

			} else {

				_gaq.push([ '_setAccount', 'UA-46332195-3' ]);

			}

			_gaq.push([ '_trackPageview' ]);

			// TODO poner el subscriber
			$.publish('loadGaEvents');

		} catch (err) {

			console.info(err);
		}

	});

})();

(function() {
	var ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl'
			: 'http://www')
			+ '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(ga, s);
})();
<file_sep>/geocatweb/js/geocat.mapa.tematics.js

/**
 * Funcions tematics generals*
 * */


function initButtonsTematic(){
	
	addHtmlInterficieTematics();
	addHtmlModalLayersTematic();
	addHtmlModalCategories();
	addHtmlModalBubbles();
	
	//botons tematic
	jQuery('#st_Color').on('click',function(){
		showTematicLayersModal(tem_simple,jQuery(this).attr('class'));
	});
	
	jQuery('#st_Tema').on('click',function(){
		showTematicLayersModal(tem_clasic,jQuery(this).attr('class'));
	});

	jQuery('#st_Size').on('click',function(){
		showTematicLayersModal(tem_size,jQuery(this).attr('class'));
	});
	
	jQuery('#st_Heat').on('click',function(e) {
		showTematicLayersModal(tem_heatmap,jQuery(this).attr('class'));
		
	});	

	jQuery('#st_Clust').on('click',function(e) {		
		showTematicLayersModal(tem_cluster,jQuery(this).attr('class'));
		
	});	
}

function showTematicLayersModal(tipus,className){
//	console.debug("showTematicLayersModal");
	var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Aquest estil no es pot aplicar a cap capa de les que tens en el mapa')+"<strong>  <span class='fa fa-warning sign'></span></div>";
	var warninMSG3D="<div class='alert alert-danger'><strong>"+window.lang.translate('Aquest estil no es pot aplicar amb modus 3D')+"<strong>  <span class='fa fa-warning sign'></span></div>";
	
	
	jQuery('.modal').modal('hide');
	
	jQuery('#dialog_layers_tematic').modal('show');
	
	jQuery('#stActiu').removeClass();
	jQuery('#stActiu').addClass(className);
	
	var basicHTML ='<span lang="ca">L\'estil bàsic genera una visualització dels elements d\'una capa uniformement per al conjunt.</span>'+
					'<br><br>'+
					'<div class="imagePeu">'+
					'	<img class="img1" src="css/images/original.jpg">'+
					'	<span class="peu" lang="ca">Capa d\'origen</span>'+
					'	<img src="css/images/basic.jpg">'+
					'	<span class="peu2" lang="ca">Visualització</span>'
					'</div>' ;
	var categoriesHTML ='<span lang="ca">L\'estil categories genera una visualització dels elements d\'una capa a partir d\'un camp, numèric o de text, de les dades.</span>'+
						'<br><br>'+
						'<div class="imagePeu">'+
						'	<img class="img1" src="css/images/original.jpg">'+
						'	<span class="peu" lang="ca">Capa d\'origen</span>'+
						'	<img src="css/images/categories.jpg">'+
						'	<span class="peu2" lang="ca">Visualització</span>'
						'</div>' ;
	var midesHTML ='<span lang="ca">L\'estil mides genera una visualització dels elements d\'una capa a partir d\'un camp numèric de les dades. Permet escollir entre interval graduat o proporcional al valor.</span>'+
					'<br><br>'+
					'<div class="imagePeu">'+
					'	<img class="img1" src="css/images/original.jpg">'+
					'	<span class="peu" lang="ca">Capa d\'origen</span>'+
					'	<img src="css/images/mides.jpg">'+
					'	<span class="peu2" lang="ca">Visualització</span>'
					'</div>' ;
	var heatMapHTML='<span lang="ca">L\'estil concentració genera una visualització dels elements d\'una capa a partir de la densitat de les dades en forma de mapa de calor (heatmap).</span>'+
					'<br><br>'+
					'<div class="imagePeu">'+
					'	<img class="img1" src="css/images/original.jpg">'+
					'	<span class="peu" lang="ca">Capa d\'origen</span>'+
					'	<img src="css/images/concentracio.jpg">'+
					'	<span class="peu2" lang="ca">Visualització</span>'
					'</div>' ;
	var clusterHTML ='<span lang="ca">L\'estil agrupació genera una visualització dels elements d\'una capa a partir de la densitat de les dades agrupats en grups de proximitat (clusters).</span>'+
					'<br><br>'+
					'<div class="imagePeu">'+
					'	<img class="img1" src="css/images/original.jpg">'+
					'	<span class="peu" lang="ca">Capa d\'origen</span>'+
					'	<img src="css/images/agrupacio.jpg">'+
					'	<span class="peu2" lang="ca">Visualització</span>'
					'</div>' ;
	
	if(tipus==tem_simple) jQuery('#txtTematic').html(basicHTML);
	else if (tipus==tem_clasic) jQuery('#txtTematic').html(categoriesHTML);
	else if (tipus==tem_size) jQuery('#txtTematic').html(midesHTML);
	else if (tipus==tem_heatmap)  jQuery('#txtTematic').html(heatMapHTML);
	else if (tipus==tem_cluster) jQuery('#txtTematic').html(clusterHTML); 
	
	var layers = [];
	jQuery.each( controlCapes._layers, function( key, value ) {
		var layerOptions = this.layer.options;
		
		var tipusCapa = layerOptions.tipus;
		//Si la capa no es multigeometrias
		if (layerOptions.geometryType != t_multiple){
			//Si la capa no esta tematitzada
			if(!layerOptions.tipusRang || layerOptions.tipusRang == tem_origen){
				if(tipus==tem_simple) {
					if (tipusCapa == t_tematic || tipusCapa == t_json || tipusCapa == t_visualitzacio || tipusCapa == t_url_file){ //tematic
						layers.push(this);
					}else if(tipusCapa == t_dades_obertes){ //dades obertes
						var dataset = layerOptions.dataset;
						if (dataset != "incidencies" &&
							dataset != "cameres" &&
							dataset != "meteo_comarca" &&
							dataset != "meteo_costa"){
							layers.push(this);
						}
					}
				}else if (tipus==tem_clasic){
					if (tipusCapa == t_tematic || tipusCapa == t_visualitzacio || tipusCapa == t_url_file){ //tematic
						if (this.layer.options.dades){
							layers.push(this);
						}else{
							layers.push(this);
						}
					}
				}else if (tipus==tem_cluster || tipus==tem_heatmap) {	
					if(estatMapa3D){
						$('#list_tematic_layers').html(warninMSG3D);
					}else{
						var ftype = transformTipusGeometry(layerOptions.geometryType);
						//var ftype = layerOptions.geometryType;
						if(tipusCapa == t_dades_obertes || tipusCapa == t_json ||
							(tipusCapa == t_tematic && ftype == t_marker) ||
							(tipusCapa == t_url_file && ftype == t_marker) ||
							(tipusCapa == t_visualitzacio && ftype == t_marker) ||
							(tipusCapa == t_vis_wms)){
							layers.push(this);
						}
					}
				}else if (tipus==tem_size) {
					var ftype = transformTipusGeometry(layerOptions.geometryType);
					if ((tipusCapa == t_tematic || tipusCapa == t_visualitzacio || tipusCapa == t_url_file) && ftype == t_marker){ //tematic
						if (this.layer.options.dades){
							layers.push(this);
						}else{
							layers.push(this);
						}
					}
				}else{		
					$('#list_tematic_layers').html(warninMSG);
					return;
				}
			}
		}
	});// fi each
	if(layers.length ==0){
		
		if(estatMapa3D){
						$('#list_tematic_layers').html(warninMSG3D);
					return;
		}else{
		$('#list_tematic_layers').html(warninMSG);		
		return;
		}
	}
	layers = {layers: layers};

	var source = jQuery("#tematic-layers-template").html();
	var template = Handlebars.compile(source);
	var html = template(layers);
	$('#list_tematic_layers').html(html);
	
	$('.usr_wms_layer').on('click',function(e){
		var _this = jQuery(this);
		var data = _this.data();
		data.from = tipus;
		//Revisar majus minus del "geometryType"!
		var ftype = "";
		if(data.geometrytype) ftype = transformTipusGeometry(data.geometrytype);
		else ftype = transformTipusGeometry(data.geometrType);
		
		if (tipus == tem_simple){
			if (ftype == t_marker  || data.tipus == t_dades_obertes || data.tipus == t_json ){
				if (busy){
					$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
					$('#dialog_info_upload').modal('show');
				}
				else obrirMenuModal('#dialog_estils_punts','toggle',data);
			}else if (ftype == t_polyline){
				if (busy){
					$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
					$('#dialog_info_upload').modal('show');
				}
				else obrirMenuModal('#dialog_estils_linies','toggle',data);
			}else if (ftype == t_polygon){
				if (busy){
					$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
					$('#dialog_info_upload').modal('show');
				}
				else obrirMenuModal('#dialog_estils_arees','toggle',data);
			}
		}else if(tipus == tem_clasic){
			if (busy){
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
				$('#dialog_info_upload').modal('show');
			}
			else showModalTematicCategories(data);
		}else if(tipus == tem_heatmap){
			createHeatMap(controlCapes._layers[data.leafletid]);
			jQuery('#dialog_layers_tematic').modal('hide');
		}else if(tipus == tem_cluster){
			creaClusterMap(controlCapes._layers[data.leafletid]);
			jQuery('#dialog_layers_tematic').modal('hide');
		}else if(tipus == tem_size){
			if (busy){
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
				$('#dialog_info_upload').modal('show');
			}
			else showModalTematicBubbles(data);
		}
	});
}

function loadCacheTematicLayer(layer){
	var defer = $.Deferred();
	var data={
		businessId: layer.businessId,
		uid: layer.entitatUid
	};
	
	var layerWms = layer;
	getCacheTematicLayerByBusinessId(data).then(function(results){
		results.results = jQuery.parseJSON( results.results );
		readTematic(defer, results, layerWms, layer);
	},function(results){
		//console.debug('getTematicLayerByBusinessId ERROR');
		defer.reject();
	});
	return defer.promise();
}

function loadTematicLayer(layer){
	try {map.spin(true);} catch (Err) {}
	var defer = $.Deferred();
	var data={
		businessId: layer.businessId
	};
	
	var layerWms = layer;
	
	//console.time("loadTematicLayer " + layerWms.serverName);
	getTematicLayerByBusinessId(data).then(function(results){
		try {map.spin(false);} catch (Err) {}
		readTematic(defer, results, layerWms, layer);
	},function(results){
		//console.debug('getTematicLayerByBusinessId ERROR');
		try {map.spin(false);} catch (Err) {}
		defer.reject();
	});
	return defer.promise();
}

function createPopupWindowData(player,type, editable, origen, capa){
//	console.debug("createPopupWindowData");
//	console.debug(player);
	var html='';
	if (player.properties.data.nom && !isBusinessId(player.properties.data.nom)){
		html+='<h4 class="my-text-center">'+player.properties.data.nom+'</h4>';
	}else if (player.properties.data.Nom && !isBusinessId(player.properties.data.Nom)){
		html+='<h4 class="my-text-center">'+player.properties.data.Nom+'</h4>';
	}else if (player.properties.data.NOM && !isBusinessId(player.properties.data.NOM)){
		html+='<h4 class="my-text-center">'+player.properties.data.NOM+'</h4>';
	}else if(player.properties.name && !isBusinessId(player.properties.name)){
		html+='<h4 class="my-text-center">'+player.properties.name+'</h4>';
	}else if(player.properties.data.name && !isBusinessId(player.properties.data.name)){
		html+='<h4 class="my-text-center">'+player.properties.data.name+'</h4>';
	}else if(player.properties.data.Name && !isBusinessId(player.properties.data.Name)){
		html+='<h4 class="my-text-center">'+player.properties.data.Name+'</h4>';
	}else if(player.properties.data.NAME && !isBusinessId(player.properties.data.NAME)){
		html+='<h4 class="my-text-center">'+player.properties.data.NAME+'</h4>';
	}else if(player.properties.nom && !isBusinessId(player.properties.nom)){
		html+='<h4 class="my-text-center">'+player.properties.nom+'</h4>';
	}else if(player.properties.nombre && !isBusinessId(player.properties.nombre)){
		html+='<h4 class="my-text-center">'+player.properties.nombre+'</h4>';
	}else if(player.properties.data.nombre && !isBusinessId(player.properties.data.nombre)){
		html+='<h4 class="my-text-center">'+player.properties.data.nombre+'</h4>';
	}else if(player.properties.data.nombre && !isBusinessId(player.properties.data.nombre)){
		html+='<h4 class="my-text-center">'+player.properties.data.nombre+'</h4>';
	}else if(player.properties.data.NOMBRE && !isBusinessId(player.properties.data.NOMBRE)){
		html+='<h4 class="my-text-center">'+player.properties.data.NOMBRE+'</h4>';
	}
	
	
	var isADrawarker=false;
	html+='<div class="div_popup_visor"><div class="popup_pres">';
	var esVisor = ($(location).attr('href').indexOf('mapa')==-1);
	$.each( player.properties.data, function( key, value ) {
		if (key.toLowerCase()!="geomorigen"){
			if(isValidValue(key) && isValidValue(value) && !validateWkt(value)){
				if (key != 'id' && key != 'businessId' && key != 'slotd50' && 
						key != 'NOM' && key != 'Nom' && key != 'nom' && 
						key != 'name' && key != 'Name' && key != 'NAME' &&
						key != 'nombre' && key != 'Nombre' && key != 'NOMBRE'){
					html+='<div class="popup_data_row">';
					var txt=value;
					if (!$.isNumeric(txt)) {
						txt = parseUrlTextPopUp(value, key);
						if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
							html+='<div class="popup_data_key">'+key+'</div>';
							html+='<div class="popup_data_value">'+
							(isBlank(txt)?window.lang.translate("Sense valor"):txt)+
							'</div>';
							html += '<div class="traffic-light-icon-empty"></div>';
						}else{
							html+='<div class="popup_data_img_iframe">'+txt+'</div>';
						}
					}
					else {
						html+='<div class="popup_data_key">'+key+'</div>';
						html+='<div class="popup_data_value">'+txt+'</div>';
	
						if(undefined != capa.isPropertyNumeric && capa.isPropertyNumeric[key] && 
							(esVisor && visor.colorscalecontrol && ("" == origen)) || (!esVisor && ("" == origen)) || ("" != origen && (key == capa.options.trafficLightKey)))
						{
	
							var leafletid = (("undefined" !== typeof player.properties.capaLeafletId) ? player.properties.capaLeafletId : (capa.hasOwnProperty("layer") ? capa.layer._leaflet_id : ""));
							//Només ensenyem la icona del semafòric si és una capa no temàtica o bé si ho és però és semafòrica sense semàfor fixe (sempre que el camp sigui numèric)
							html+='<div class="traffic-light-icon" data-leafletid="' + leafletid + '" data-origen="' + origen + '" title="'+window.lang.translate('Temàtic per escala de color')+'"></div>';
							
						}
						else
						{
	
							html += '<div class="traffic-light-icon-empty"></div>';
	
						}
					}
					html+= '</div>';
					if (key=='text' || key=='TEXT') isADrawarker=true;
					else isADrawarker=false;
				}
			}
		}
	});	
	if (isADrawarker && type=="marker") {
		var auxLat = player._latlng.lat;
		auxLat = auxLat.toFixed(5);
		var auxLon = player._latlng.lng;
		auxLon = auxLon.toFixed(5);
		html+='<div class="popup_data_row">';
		html+='<div class="popup_data_key">Latitud</div>';
		html+='<div class="popup_data_value">'+auxLat+'</div>';
		html+= '</div>';
		
		html+='<div class="popup_data_row">';
		html+='<div class="popup_data_key">Longitud</div>';
		html+='<div class="popup_data_value">'+auxLon+'</div>';
		html+= '</div>';
	}
	
	if(editable){
		html+= '<div id="footer_edit"  class="modal-footer">'
			+'<ul class="bs-popup">'
				+'<li class="edicio-popup"><a id="feature_edit##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-map-marker verd" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Estils')+'"></span></a>   </li>'
				+'<li class="edicio-popup"><a id="feature_move##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-move magenta" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Editar')+'"></span></a>   </li>'
				+'<li class="edicio-popup"><a id="feature_remove##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-trash vermell" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Esborrar')+'"></span></a>   </li>'
				+'<li class="edicio-popup"><a id="feature_data_table##'+player._leaflet_id+'##'+type+'##'+player.properties.capaLeafletId+'" lang="ca" href="#"><span class="glyphicon glyphicon-list-alt blau" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Dades')+'"></span></a>   </li>'
				+'<li class="edicio-popup"><a class="faqs_link" href="http://betaportal.icgc.cat/wordpress/faq-dinstamaps/#mapestematics" target="_blank"><i class="fa fa-question-circle-o fa-lg fa-fw"></i></a></span></li>'
			+'</ul>'														
			+'</div>';	
	}else{
		var capaLeafletId = player.properties.capaLeafletId;
		if(isValidValue(origen)) {
			capaLeafletId = origen; 
		}
		html+= '<div id="footer_edit"  class="modal-footer">'
			+'<ul class="bs-popup">'						
				+'<li class="consulta-popup"><a id="feature_data_table##'+player._leaflet_id+'##'+type+'##'+capaLeafletId+'" lang="ca" href="#"><span class="glyphicon glyphicon-list-alt blau-left" data-toggle="tooltip" data-placement="right" title="'+window.lang.translate('Obrir la taula de dades')+'"></span></a>   </li>'
			+'</ul>'														
		+'</div>';			
	}

	if(type == t_polyline && player.properties.mida){
		html+='<div id="mida_pres"><b>'+window.lang.translate('Longitud')+':</b> '+player.properties.mida+'</div>';	
	}else if(type == t_polygon && player.properties.mida){
		if (player.properties.mida.indexOf("NaN")==-1)	html+='<div id="mida_pres"><b>'+window.lang.translate('Àrea')+':</b> '+player.properties.mida+'</div>';
		else html+='<div id="mida_pres"><b>'+window.lang.translate('Àrea')+':</b> '+L.GeometryUtil.readableArea(L.GeometryUtil.geodesicArea(player.getLatLngs()),true)+'</div>';
	}
	html+='</div>';
	//he quitado el openPopup() ya que si la capa no està activa no se ha cargado en el mapa y da error.
	player.bindPopup(html,{'offset':[0,-25]});

	//Afegim els events de clicks per al semafòric
	jQuery(document).on('click', ".traffic-light-icon", function(e) {

		e.stopImmediatePropagation();
		var layerId = $(this).data("leafletid");
		var parentId = $(this).data("origen");
		var key = $(this).prev().prev().text();
		var value = parseFloat($(this).prev().text());
		var layer = null;
		var control = null;
		if("" == parentId)
		{

			//És una capa no temàtica, hem de crear la de previsualització
			layer = controlCapes._layers[layerId].layer;
			control = Semaforic(self.isEditing);

		}
		else
		{

			//És una capa temàtica, mirem si és una capa semafòrica de previsualització
			layer = controlCapes._layers[parentId].layer;
			if(layer.hasOwnProperty("semaforics") && "undefined" !== typeof layer.semaforics[layerId])
				control = layer.semaforics[layerId];
			else
			{

				//Si hem arribat aquí és que és una capa semafòrica, utilitzem la capa actual
				control = Semaforic();
				var businessId = controlCapes._layers[parentId]._layers[layerId].layer.options.businessId;
				var options = JSON.parse(controlCapes._visLayers[businessId].options);
				var paletaEstils = [controlCapes._visLayers[businessId].estil[0].color,
					controlCapes._visLayers[businessId].estil[1].color,
					controlCapes._visLayers[businessId].estil[2].color
					]
				control.setVisualization(controlCapes._layers[parentId]._layers[layerId]);
				control.setLayer(controlCapes._visLayers[businessId]);
				control.setLayerOptions(controlCapes._options[businessId]);
				control.setPalette(paletaEstils, options.reverse);

			}

		}

		control.render($.Deferred(), key, value, layer).then(function(data) {
			if(!layer.hasOwnProperty("semaforics"))
				layer.semaforics = {};
		
			layer.semaforics[data] = control;
			//Canviem el valor de referència de la capa al control de capes si el conté
			var name = Semaforic.getUpdatedLayerName($("#" + layerId + ".editable").text(), value);
			if(self.isEditing)
				$("#" + layerId + ".editable").editable("setValue", name, true);
			else
				$("#" + layerId + ".editable").text(name);

		});

	});
	
	//Afegim events/accions al popUp
	jQuery(document).on('click', ".bs-popup li a", function(e) {
		e.stopImmediatePropagation();
		var accio;
		if(undefined != jQuery(this).attr('id') && jQuery(this).attr('id').indexOf('##')!=-1){	
			accio=jQuery(this).attr('id').split("##");				
		}
		
		if (accio!=undefined && accio[1]!=undefined) objEdicio.featureID=accio[1];
		
		if(undefined != accio[0] && accio[0].indexOf("feature_edit")!=-1){

			//Update modal estils, amb estil de la feature seleccionada
			var obj = map._layers[accio[1]];
			//console.debug(obj);
			if(obj.options.icon /*|| obj.options.icon.options.markerColor.indexOf("punt_r")!=-1*/){
				var icon = obj.options.icon.options;	
			}else if(obj._options){
				var icon = obj._options;
			}else{
				var icon = obj.options;
			}
			updateDialogStyleSelected(icon);
			
			if(accio[2].indexOf("marker")!=-1){
				obrirMenuModal('#dialog_estils_punts','toggle',from_creaPopup);
			}else if(accio[2].indexOf("polygon")!=-1){
				obrirMenuModal('#dialog_estils_arees','toggle',from_creaPopup);
			}else{
				obrirMenuModal('#dialog_estils_linies','toggle',from_creaPopup);
			}
		}else if(undefined != accio[0] && accio[0].indexOf("feature_data_table")!=-1){
	
			$('#modal_data_table').modal('show');
			var featureId=objEdicio.featureID;
			if (featureId==undefined) featureId=accio[2];
			if (map._layers[featureId]==undefined) {
				try{
					if (accio[6]!=undefined) featureId=accio[6];
					var props=map._layers[featureId].properties;
					if (props==undefined) props=map._layers[featureId].options;
					if (accio[3]==undefined)  fillModalDataTable(controlCapes._layers[accio[2]],props.businessId);
					else fillModalDataTable(controlCapes._layers[accio[3]],props.businessId);
				}
				catch(err){
					console.debug(err);
				}
			}
			else fillModalDataTable(controlCapes._layers[accio[3]],map._layers[featureId].properties.businessId);
		
		}else if(undefined != accio[0] && accio[0].indexOf("feature_remove")!=-1){
			map.closePopup();
			var data = {
	            businessId: map._layers[objEdicio.featureID].properties.businessId,
	            uid: Cookies.get('uid')
	        };
		
			var features = {
				type:"Feature",
				id: 3124,
				businessId: map._layers[objEdicio.featureID].properties.businessId,
				properties: map._layers[objEdicio.featureID].properties.data,
				estil: map._layers[objEdicio.featureID].properties.estil,
				geometry: map._layers[objEdicio.featureID].properties.feature.geometry
			};				
			
			features = JSON.stringify(features);
			
			var data = {
				businessId: map._layers[objEdicio.featureID].properties.capaBusinessId,//bID de la visualitzacio-capa
				uid: Cookies.get('uid'),
				features: features
			};
			var businessIdCapaOrigen=map._layers[objEdicio.featureID].properties.capaBusinessId;
			removeGeometriaFromVisualitzacio(data).then(function(results){
				if(results.status == 'OK'){
					/*var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;
					var layer = map._layers[objEdicio.featureID];
					if(map._layers[capaLeafletId]!= undefined) map._layers[capaLeafletId].removeLayer(map._layers[objEdicio.featureID]);					
					if(map._layers[objEdicio.featureID]!= null) map.removeLayer(map._layers[objEdicio.featureID]);	
					var layerMap=map._layers[capaLeafletId];
					var layerMare = controlCapes._layers[capaLeafletId];
					//recarrego les sublayers de la capa modificada	
					actualitzacioTematic(layerMare,businessIdCapaOrigen,null,null,null,"baixa");  
					*/
					
					var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;
					var capaBusinessId = map._layers[objEdicio.featureID].properties.capaBusinessId;
					if(map._layers[capaLeafletId]!= undefined) map._layers[capaLeafletId].removeLayer(map._layers[objEdicio.featureID]);					
					if(map._layers[objEdicio.featureID]!= null) map.removeLayer(map._layers[objEdicio.featureID]);	
					if(map._layers[capaLeafletId]!= undefined) {
						updateFeatureCount(map._layers[capaLeafletId].options.businessId, null);
					}
					else {						
						updateFeatureCount(capaBusinessId, null);		
					}		
					 var layer = controlCapes._layers[capaLeafletId];
					//recarrego les sublayers de la capa modificada	
					actualitzacioTematic(layer,businessIdCapaOrigen,null,null,null,"baixa");
					
				}else{
					console.debug("ERROR deleteFeature");
				}
			},function(results){
				console.debug("ERROR deleteFeature");
			});					
		}else if(undefined != accio[0] && accio[0].indexOf("feature_text")!=-1){
			modeEditText();
		}else if(undefined != accio[0] && accio[0].indexOf("feature_move")!=-1){
			objEdicio.esticEnEdicio=true;
			var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;	
			objEdicio.capaEdicioLeafletId = capaLeafletId;//Ho guarda per despres poder actualitzar vis filles
			//Actualitzem capa activa
			if (capaUsrActiva){
				capaUsrActiva.removeEventListener('layeradd');
			}
			capaUsrActiva = map._layers[capaLeafletId];
			
			var capaEdicio = new L.FeatureGroup();
			capaEdicio.addLayer(map._layers[objEdicio.featureID]);
			capaUsrActiva.removeLayer(map._layers[objEdicio.featureID]);
			map.addLayer(capaEdicio);
			
			var opcionsSel={
					color: '#FF1EE5',
					"weight": 7,
					opacity: 0.6,
					dashArray: '1, 1',
					fill: true,
					fillColor: '#fe57a1',
					fillOpacity: 0.1
				};
			
			/*crt_Editing=new L.EditToolbar.SnapEdit(map, {
				featureGroup: capaEdicio,
				selectedPathOptions: opcionsSel,
				snapOptions: {
					guideLayer: guideLayers
				}
			});*/
			crt_Editing=new L.EditToolbar.Edit(map, {
				featureGroup: capaEdicio,
				selectedPathOptions: opcionsSel
			});
			crt_Editing.enable();
			
			//crt_Editing.enable();
			
			/*if(map._layers[objEdicio.featureID].properties.tipusFeature=="marker" && map._layers[objEdicio.featureID].options.isCanvas){
				crt_Editing=new L.EditToolbar.Edit(map, {
					featureGroup: capaEdicio,
					selectedPathOptions: opcionsSel
				});
				crt_Editing.enable();
			}
			else {
				crt_Editing=new L.EditToolbar.SnapEdit(map, {
					featureGroup: capaEdicio,
					selectedPathOptions: opcionsSel,
					snapOptions: {
						guideLayer: guideLayers
					}
				});
				crt_Editing.enable();
				//activarSnapping(capaEdicio);
			}*/
			
			//activarSnapping(capaEdicio);			
			
			map.closePopup();
			
		}else if(undefined != accio[0] && accio[0].indexOf("feature_no")!=-1){
			jQuery('.popup_pres').show();
			jQuery('.popup_edit').hide();
			
		}else if(undefined != accio[0] && accio[0].indexOf("feature_ok")!=-1){
			if(objEdicio.edicioPopup=='textFeature'){
				var txtTitol=jQuery('#titol_edit').val();
				var txtDesc=jQuery('#des_edit').val();
				if (txtDesc.indexOf("'")>-1) txtDesc = txtDesc.replaceAll("'",'"');
				updateFeatureNameDescr(map._layers[objEdicio.featureID],txtTitol,txtDesc);

			}else if(objEdicio.edicioPopup=='textCapa'){
				if(jQuery('#capa_edit').val()!=""){
					jQuery('#cmbCapesUsr option:selected').text(jQuery('#capa_edit').val());	
					jQuery('.popup_pres').show();
					jQuery('.popup_edit').hide();
				}else{
					alert(window.lang.translate('Has de posar un nom de capa'));	
				}
			}else if(objEdicio.edicioPopup=='nouCapa'){
				if(jQuery('#capa_edit').val()!=""){
					generaNovaCapaUsuari(map._layers[objEdicio.featureID],jQuery('#capa_edit').val());
				}else{
					alert(window.lang.translate('Has de posar un nom de capa'));	
				}
			}
		}else{
		//accio tanca
			map.closePopup();
		}
	});	

	player.on('popupopen', function(e){
		//console.debug(e);
		if(objEdicio.esticEnEdicio){//Si s'esta editant no es pot editar altre element
			map.closePopup();
		}
	});

	return html;
}

/*****************************/


/** Funcions que actualitzen l'estil per defecte, al seleccionat al dialeg d'estils
 * 	per punts, línies, i polígons. 
 * */

function changeDefaultLineStyle(canvas_linia){
	var estilTMP = default_line_style;
	estilTMP.color=canvas_linia.strokeStyle;
	estilTMP.weight=canvas_linia.lineWidth;
	estilTMP.tipus=t_polyline;
	
	
	
	if(objEdicio.obroModalFrom==from_creaCapa){
		 drawControl.options.polyline.shapeOptions= estilTMP;
	}
	return estilTMP;
}

function changeDefaultAreaStyle(canvas_pol){
	var estilTMP= default_area_style;
	estilTMP.fillColor=canvas_pol.fillStyle;
	estilTMP.fillOpacity=canvas_pol.opacity;
	estilTMP.weight=canvas_pol.lineWidth;
	estilTMP.color=canvas_pol.strokeStyle;
	estilTMP.tipus=t_polygon;
	
	if(objEdicio.obroModalFrom==from_creaCapa){
		drawControl.options.polygon.shapeOptions= estilTMP;
	}
	return estilTMP;
}

function changeDefaultPointStyle(estilP) {
	//console.debug("changeDefaultPointStyle");
	var puntTMP= new L.AwesomeMarkers.icon(default_marker_style);
	var _iconFons=estilP.iconFons.replace('awesome-marker-web awesome-marker-icon-','');
	var _iconGlif=estilP.iconGlif;	
	var cssText="";
	
	if(_iconGlif.indexOf("fa fa-")!=-1){
		_iconGlif=estilP.iconGlif.replace('fa fa-','');
	};
	
	if (_iconGlif.indexOf("font")!=-1){
		_iconGlif = _iconGlif.substring(0,_iconGlif.indexOf(" ")) ;
	}
//	console.debug(_iconFons);
	
	var _colorGlif=estilP.colorGlif;
	
	if(_iconFons.indexOf("_r")!=-1){ //sóc rodó		
		var num=estilP.size;
		puntTMP.options.shadowSize = new L.Point(1, 1);
		var tt=estilP.fontsize;
		puntTMP.options.divColor=estilP.divColor;
		if(tt=="9px" || tt=="8px"){
			cssText="font9";			
		}else if(tt=="11px" || tt=="10.5px"){
			cssText="font11";
		}else if(tt=="12px"){
			cssText="font12";
		}else if(tt=="15px"){
			cssText="font15";
		}else if(tt=="17px"){
			cssText="font17";		
		}
				
		puntTMP.options.fillColor =estilP.divColor;
		if(_iconGlif=="" || _iconGlif=="undefined" || _iconGlif==null){//no tin glif soc Canvas
			puntTMP.options.icon="";
			puntTMP.options.radius = parseInt(estilP.size/2.4);
			puntTMP.options.isCanvas=true;
		}else{
			puntTMP.options.iconAnchor= new L.Point(parseInt(num/2), parseInt(num/2));
			puntTMP.options.iconSize = new L.Point(num, num);
			console.debug(puntTMP.options.icon);
			puntTMP.options.icon=_iconGlif + " "+cssText;
			console.debug(puntTMP.options.icon);
			puntTMP.options.isCanvas=false;
		}
	}else{ // sóc pinxo
		puntTMP.options.iconAnchor= new L.Point(14, 42);
		puntTMP.options.iconSize = new L.Point(28, 42);
		puntTMP.options.shadowSize = new L.Point(36, 16);
		puntTMP.options.divColor='transparent';
		if(_iconGlif=="" || _iconGlif=="undefined" || _iconGlif==null){
			puntTMP.options.icon="";
		}else{
			puntTMP.options.icon=_iconGlif + " "+cssText;			
		}
		puntTMP.options.isCanvas=false;
	}
	puntTMP.options.markerColor=_iconFons;
	if(puntTMP.options.icon==""){
		puntTMP.options.iconColor="#000000";
	}else{
		puntTMP.options.iconColor=_colorGlif;
	}
	
	if(objEdicio.obroModalFrom==from_creaCapa){
		defaultPunt=puntTMP;
	}
	return puntTMP;
}
/*****************************/

/**Funcions per crear un objecte de tipus estil, amb les característiques que li passes
 * per punt, línia, poligon */

function createFeatureLineStyle(style){
	var estilTMP = default_line_style;
	estilTMP.color=style.color;
	estilTMP.weight=style.lineWidth;
	estilTMP.tipus=t_polyline;
	return estilTMP;
}

function createFeatureAreaStyle(style){
	var estilTMP= default_area_style;
	estilTMP.fillColor=style.color;
	estilTMP.fillOpacity=style.opacity/100;
	estilTMP.weight=style.borderWidth;
	estilTMP.color=style.borderColor;
	estilTMP.tipus=t_polygon;
	return estilTMP;
}

function createFeatureMarkerStyle(style, num_geometries){
	//console.debug("createFeatureMarkerStyle");
	if (!num_geometries){
		num_geometries = num_max_pintxos - 1;
	}
	if (style.marker && num_geometries <= num_max_pintxos){
		//Especifiques per cercle amb glyphon
		if(style.marker == 'punt_r'){
			var puntTMP = new L.AwesomeMarkers.icon(default_circuloglyphon_style);
			puntTMP.options.iconColor = style.simbolColor;
			puntTMP.options.icon = style.simbol;
			puntTMP.options.markerColor = style.marker;
			puntTMP.options.isCanvas=false;
			puntTMP.options.divColor= style.color;
			puntTMP.options.shadowSize = new L.Point(1, 1);
			puntTMP.options.radius = style.radius;
			var anchor = style.iconAnchor.split("#");
			var size = style.iconSize.split("#");
			puntTMP.options.iconAnchor.x = parseInt(anchor[0]);
			puntTMP.options.iconAnchor.y = parseInt(anchor[1]);
			puntTMP.options.iconSize.x = size[0];
			puntTMP.options.iconSize.y = size[1];
		}else{
			var puntTMP = new L.AwesomeMarkers.icon(default_marker_style);
			puntTMP.options.iconColor = style.simbolColor;
			puntTMP.options.icon = style.simbol;
			puntTMP.options.markerColor = style.marker;
			puntTMP.options.isCanvas=false;
			puntTMP.options.iconAnchor.x = 14;
			puntTMP.options.iconAnchor.y = 42;
			puntTMP.options.iconSize.x = 28;
			puntTMP.options.iconSize.y = 42;
		}
	}else{ //solo circulo
		var puntTMP = { 
			radius: style.simbolSize, 
			isCanvas: true,
			fillColor: style.color,
			color:  style.borderColor,
			weight:  style.borderWidth,
			fillOpacity: style.opacity/100,
			opacity: 1,
			tipus: t_marker
		};
	}
	return puntTMP;
}

function createRangStyle(ftype, style, num_geometries){
	var rangStyle;
	if (style){
		if (ftype === t_marker){
			rangStyle = createFeatureMarkerStyle(style, num_geometries);
		}else if (ftype === t_multipoint){
			rangStyle = createFeatureMarkerStyle(style, num_geometries);
		}else if (ftype === t_polyline){
			rangStyle = createFeatureLineStyle(style);
		}else if (ftype === t_multilinestring){
			rangStyle = createFeatureLineStyle(style);
		}else if (ftype === t_polygon){
			rangStyle = createFeatureAreaStyle(style);
		}else if (ftype === t_multipolygon){
			rangStyle = createFeatureAreaStyle(style);
		}
	}else{
		if (ftype === t_marker){
			rangStyle = L.AwesomeMarkers.icon(default_marker_style);
		}else if (ftype === t_multipoint){
			rangStyle = L.AwesomeMarkers.icon(default_marker_style);
		}else if (ftype === t_polyline){
			rangStyle = default_line_style;
		}else if (ftype === t_multilinestring){
			rangStyle = default_line_style;
		}else if (ftype === t_polygon){
			rangStyle = default_area_style;
		}else if (ftype === t_multipolygon){
			rangStyle = default_area_style;
		}
	}
	return rangStyle;
}
/*************************************************/

/**Funcio que actualitza els rangs de la capa quan: 
 * - Es canvia l'estil d'una feature
 * - Es mou una feature d'una capa a un altre
 * - Cada cop que es carrega un fitxer (dragdrop urlfile) i es vol centrar al mapa als features*/	
function getRangsFromLayer(layer){
	//console.debug("getRangsFromLayer");
	if (layer.options.tipus == t_tematic){
		var styles = jQuery.map(layer.getLayers(), function(val, i){
			return {key: val.properties.businessId, style: val};
		});
		
		var tematic = layer.options;
		tematic.tipusRang = tematic.tipusRang ? tematic.tipusRang : tem_origen;
		tematic.businessid = tematic.businessId; 
		tematic.leafletid = layer._leaflet_id;
		tematic.geometrytype = tematic.geometryType;
		tematic.from = tematic.tipusRang;
		
		var rangs = getRangsFromStyles(tematic, styles);
        rangs = JSON.stringify({rangs:rangs});
        
        var data = {
          businessId: tematic.businessid,
          uid: Cookies.get('uid'),
          tipusRang: tematic.from,
          rangs: rangs
        };
              
        updateTematicRangs(data).then(function(results){
        	//console.debug(results);
        },function(results){
			//TODO error
			console.debug("getRangsFromLayer ERROR");
		});
	}
}


function getMarkerRangFromStyle(styles){
	
	if (styles.options.isCanvas){
		var rang = {
			isCanvas: true,	
			simbolSize : styles.options.radius, 
			color :  jQuery.Color(styles.options.fillColor).toHexString(),
			borderColor :  styles.options.color,
			borderWidth :  styles.options.weight,
			opacity: (styles.options.fillOpacity * 100),
			label : false,
			labelSize : 10,
			labelFont : 'arial',
			labelColor : '#000000',					
		};
	}else{
		//CAL??
		if(jQuery.type(styles.options.icon) === "object"){
			var auxOptions = styles.options.icon.options;
		}else{
			var auxOptions = styles.options;
		}
		
		var rang = {
			isCanvas: false,
			color : auxOptions.divColor,//auxOptions.fillColor,//Color principal
			marker: auxOptions.markerColor,//Si es de tipus punt_r o el color del marker
			simbolColor: auxOptions.iconColor,//Glyphon
			radius : auxOptions.radius,//Radius
			iconSize : auxOptions.iconSize.x+"#"+auxOptions.iconSize.y,//Size del cercle
			iconAnchor : auxOptions.iconAnchor.x+"#"+auxOptions.iconAnchor.y,//Anchor del cercle
			simbol : $.trim(auxOptions.icon),//tipus glyph
			opacity : (auxOptions.opacity * 100),
			label : false,
			labelSize : 10,
			labelFont : 'arial',
			labelColor : '#000000',
		};
	}
	return rang;
}

function getLineRangFromStyle(styles){
	var rang = {
		color: styles.strokeStyle,//styles.color,
		lineWidth: styles.lineWidth,//styles.weight,
		lineStyle : 'solid',
		borderWidth : 2,
		borderColor : styles.strokeStyle,				
		//opacity: (styles.opacity * 100),
		opacity: 100,
		label : false,
		labelSize : 10,
		labelFont : 'arial',
		labelColor : '#000000'
	};	
	return rang;
}

function getPolygonRangFromStyle(styles){
	styles.fillColor = jQuery.Color(styles.fillColor).toHexString();

	var rang = {
		borderWidth: styles.lineWidth,//styles.weight,
		borderColor: styles.strokeStyle,//styles.color,
		color: rgb2hex(styles.fillStyle),//styles.fillColor,
		opacity: (styles.opacity * 100),//(styles.fillOpacity * 100),
		lineStyle : 'solid',
		label : false,
		labelSize : 10,
		labelFont : 'arial',
		labelColor : '#000000',
		weight: styles.lineWidth
	};	
	
	return rang;
}

function getRangsFromStyles(tematic, styles){
	//console.debug("getRangsFromStyles");
	if (tematic.tipus == t_dades_obertes){
		tematic.geometrytype = t_marker;
	}
	
//	var ftype_vell = transformTipusGeometry(tematic.geometrytype);
//	var ftype = transformTipusGeometry(tematic.geometryType);
	
	//Revisar majus minus del "geometryType"!
	var ftype = "";
	if(tematic.geometrytype) ftype = transformTipusGeometry(tematic.geometrytype);
	else if(tematic.geometryType) ftype = transformTipusGeometry(tematic.geometryType);
	else ftype = transformTipusGeometry(tematic.geometrType);
	
	/*Control cas multiple
	if(ftype == t_multiple && styles.options){
		 ftype = transformTipusGeometry(styles.options.tipus);
	}*/
	
	var rangs = [];
	if (jQuery.isArray(styles)){
		jQuery.each(styles, function(i, val){
			var rang = getRangsFromStyles(tematic, val.style);
			if(rang[0]){
				rang[0].featureLeafletId = val.style._leaflet_id;
				rang = rang[0];
				rang.valorMax = val.key;
				rangs.push(rang);			
			}

		});
	}else{
		if (ftype == t_marker){
			
			if (styles.options.isCanvas){
				var rang = {
					isCanvas: true,	
					simbolSize : styles.options.radius, 
					color :  jQuery.Color(styles.options.fillColor).toHexString(),
					borderColor :  styles.options.color,
					borderWidth :  styles.options.weight,
					opacity: (styles.options.fillOpacity * 100),
					label : false,
					labelSize : 10,
					labelFont : 'arial',
					labelColor : '#000000',					
				};
			}else{
				
//				var auxOptions = styles.options;
//				while(jQuery.type(styles.options.icon) === "object"){
//					//if(jQuery.trim(styles.options.icon) != "" && jQuery.isPlainObject(styles.options.icon)){
//					styles.options = styles.options.icon.options;
//				}
				
				
				if(jQuery.type(styles.options.icon) === "object"){
					var auxOptions = styles.options.icon.options;
				}else{
					var auxOptions = styles.options;
				}
				
				var rang = {
					isCanvas: false,
					//legenda : 'TODO ficar llegenda',//TODO ficar nom de la feature del popup de victor
//					valorMax : "feature" + fId,
					//Canviat a divColor, si es marker, sera sempre 'transparent'
					color : auxOptions.divColor,//auxOptions.fillColor,//Color principal
					marker: auxOptions.markerColor,//Si es de tipus punt_r o el color del marker
					simbolColor: auxOptions.iconColor,//Glyphon
					radius : auxOptions.radius,//Radius
					iconSize : auxOptions.iconSize.x+"#"+auxOptions.iconSize.y,//Size del cercle
					iconAnchor : auxOptions.iconAnchor.x+"#"+auxOptions.iconAnchor.y,//Anchor del cercle
					simbol : $.trim(auxOptions.icon),//tipus glyph
					opacity : (auxOptions.opacity * 100),
					label : false,
					labelSize : 10,
					labelFont : 'arial',
					labelColor : '#000000',
				};
			}
		}else if (ftype == t_polyline){
			
			if (styles._options){
				styles.options = styles._options;
			}else if(!styles.options) styles.options = styles;
			
			var rang = {
				color: styles.options.color,
				lineWidth: styles.options.weight,
				lineStyle : 'solid',
				borderWidth : 2,
				borderColor : styles.options.color,				
				opacity: (styles.options.opacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000'
			};
		}else if (ftype == t_polygon){
			if (styles._options){
				styles = styles._options;
			}else if(styles.options){
				styles = styles.options;
			}
			styles.fillColor = jQuery.Color(styles.fillColor).toHexString();
			var rang = {
				borderWidth: styles.weight,
				borderColor: styles.color,
				color: styles.fillColor,
				opacity: (styles.fillOpacity * 100),
				lineStyle : 'solid',
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000'					
			};
		}
//		rang.businessId = styles.properties.businessId;
//		rang.featureLeafletId = styles._leaflet_id;
		rangs.push(rang);
	}
	return rangs;
}

/*******************************************************************/

function canviaStyleSinglePoint(cvStyle,feature,capaMare,openPopup){
	var isCanvas=false;
	if(feature._ctx){isCanvas=true;}
	var featureID=feature._leaflet_id
	
	var noCanvi=(isCanvas==cvStyle.options.isCanvas);

	if(noCanvi && !isCanvas){//pinxo i/o glifons
		map._layers[featureID].setIcon(cvStyle);		
	}else if (noCanvi && isCanvas){//Nomes punt
		map._layers[featureID].setStyle(cvStyle.options);
		map._layers[featureID].setRadius(cvStyle.options.radius);
	}else if (!noCanvi ){
		capaMare.removeLayer(map._layers[featureID]);
		var layerTMP;
		if(isCanvas){//hi ha canvi de punt a pinxo i/o glifon
			layerTMP=L.marker([feature.getLatLng().lat,feature.getLatLng().lng],
					{icon: cvStyle,isCanvas:cvStyle.options.isCanvas,
					 tipus: t_marker});
		}else{//hi ha canvia de pinxo a punt canvas
			layerTMP= L.circleMarker([feature.getLatLng().lat,feature.getLatLng().lng],
				{ radius : cvStyle.options.radius, 
				  isCanvas:cvStyle.options.isCanvas,
				  fillColor : cvStyle.options.fillColor,
				  color :  cvStyle.options.color,
				  weight :  cvStyle.options.weight,
				  opacity :  cvStyle.options.opacity,
				  fillOpacity : cvStyle.options.fillOpacity,
				  tipus: t_marker}	
			);
		}
		layerTMP.properties=feature.properties;	
		layerTMP.addTo(capaMare);
		if (capaMare.options.tipus == t_dades_obertes){
			//popUp(feature, capaMare);
		}else{
			createPopupWindow(layerTMP,layerTMP.options.tipus);	
			if(!openPopup){
				//map.closePopup();
			}
		}
	}
	map.closePopup();	
}

function addHtmlInterficieTematics(){
	jQuery("#funcio_tematics").append(
			'<h5 lang="ca">Triar l\'estil de la capa</h5>'+
			'<div class="div_gr3_estils">'+
			'	<div id="st_Color" lang="ca" class="div_estil_1" data-toggle="tooltip" data-lang-title="Bàsic" title="Bàsic"></div>'+
			'	<div id="st_Tema" lang="ca" class="div_estil_2" data-toggle="tooltip" data-lang-title="Categories" title="Categories"></div>'+
			'	<div id="st_Size" lang="ca" class="div_estil_3" data-toggle="tooltip" data-lang-title="Mides" title="Mides"></div>'+
			'	<div id="st_Heat" lang="ca" class="div_estil_4" data-toggle="tooltip" data-lang-title="Concentració" title="Concentració"></div>'+
			'	<div id="st_Clust" lang="ca" class="div_estil_5" data-toggle="tooltip" data-lang-title="Agrupació" title="Agrupació"></div>'+
			'</div>'			
	);
	
	jQuery('.div_gr3_estils [data-toggle="tooltip"]').tooltip({container : 'body', placement: 'bottom'});
		
	/*
	$('#st_Color').tooltip({placement : 'bottom',container : 'body',title : window.lang.translate("Bàsic")});
	$('#st_Tema').tooltip({placement : 'bottom',container : 'body',title : window.lang.translate("Categories")});
	$('#st_Size').tooltip({placement : 'bottom',container : 'body',title : window.lang.translate("Mides")});	
	$('#st_Heat').tooltip({placement : 'bottom',container : 'body',title : window.lang.translate("Concentració")});
	$('#st_Clust').tooltip({placement : 'bottom',container : 'body',title : window.lang.translate("Agrupació")});
	*/
}

function addHtmlModalLayersTematic(){
	
	jQuery('#mapa_modals').append(
	'	<!-- Modal Tematics Layers -->'+
	'		<div class="modal fade" id="dialog_layers_tematic">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content panel-primary">'+
	'				<div class="modal-header panel-heading">'+
	'					<button type="button" class="close" data-dismiss="modal"'+
	'						aria-hidden="true">&times;</button>'+
	'					<h4 class="modal-title"><span lang="ca">Triar una capa per aplicar-hi l\'estil</span><span><a class="faqs_link" href="http://betaportal.icgc.cat/wordpress/faq-dinstamaps/#mapestematics" target="_blank"><i class="fa fa-question-circle-o fa-lg fa-fw"></i></a></span></h4>'+
	'				</div>'+
	'				<div class="modal-body">'+
	'					<div class="alert alert-success" id="txtTematic">'+
	'					</div>'+
	'					<script id="tematic-layers-template" type="text/x-handlebars-template">'+
	'					<div class="panel-warning">'+					
	'					<ul class="bs-dadesO_USR panel-heading">'+
	'						{{#each layers}}'+
	'						<li><a class="usr_wms_layer lable-usr" data-leafletid="{{layer._leaflet_id}}" data-businessId="{{layer.options.businessId}}" data-geometryType="{{layer.options.geometryType}}" data-tipus="{{layer.options.tipus}}" data-propName="{{layer.options.propName}}">{{name}}</a></li>'+
	'						{{/each}}'+
	'					</ul>'+	
	'					</div>'+
	'					</script>'+
	'					<div id="list_tematic_layers"></div>'+
	'			</div>'+
	'				<div class="modal-footer">'+
	'				<div style="float:right;line-height: 40px;"><span lang="ca">Estil actiu</span>:  <div style="float: right;width:42px;height:42px" id="stActiu"></div></div>'+
	'					<!-- <button type="button" class="btn btn-default" data-dismiss="modal">Tancar</button>'+
	'        <button type="button" class="btn btn-success">Canviar</button> -->'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- fi Modal Tematics Layers -->'		
	);
	
}

function addHtmlModalCategories(){
	
	jQuery('#mapa_modals').append(
	'	<!-- Modal Tematics Rangs -->'+
	'		<div class="modal fade" id="dialog_tematic_rangs">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content panel-primary">'+
	'				<div class="modal-header panel-heading">'+
	'					<button type="button" class="close" data-dismiss="modal"'+
	'						aria-hidden="true">&times;</button>'+
	'					<h4 class="modal-title" lang="ca">Defineix les categories</h4>'+
	'				</div>'+
	'				<div class="modal-body">'+
	'					<div class="labels_fields">'+
	'						<span>1.</span><span lang="ca">Escull el camp per simbolitzar</span>:'+
	'						<select name="dataField" id="dataField">'+
	'						</select>'+
	'					</div>'+
	'					<script id="tematic-layers-fields" type="text/x-handlebars-template">'+
	'						<option value="---" lang="ca">Escull el camp</option>'+
	'						{{#each fields}}'+
	'						<option value="{{this}}">{{@key}}</option>'+
	'						{{/each}}'+
	'					</script>'+
	'					<br/>'+										
	'					<div id="tipus_agrupacio_grp" class="labels_fields">'+
	'						<span>2.</span><span lang="ca">Escull l\'interval</span>:'+
	'						<span class="rd_separator"></span>'+
	'						<input type="radio" id="rd_tipus_unic" name="rd_tipus_agrupacio" value="U">'+
	'						<label for="rd_tipus_unic" lang="ca">'+window.lang.translate("únic")+'</label>'+
	'						<span class="rd_separator"></span>'+
	'						<input type="radio" id="rd_tipus_semaforic" name="rd_tipus_agrupacio" value="S">'+
	'						<label for="rd_tipus_semaforic" lang="ca">Escala de color</label>'+
	'						<input type="radio" id="rd_tipus_rang" name="rd_tipus_agrupacio" value="R">'+
	'						<label for="rd_tipus_rang" lang="ca">per intervals</label>'+
	'<!-- 						<select id="cmb_tipus_agrupacio"> -->'+
	'<!-- 							<option lang="ca" value="U">Únic</option> -->'+
	'<!-- 							<option lang="ca" value="R">Rang</option> -->'+
	'<!-- 						</select> -->'+
	'					</div>'+			
	'					<div id="num_rangs_grp" class="labels_fields" >'+
	'						<select id="cmb_num_rangs">'+
	'							<option value="---" selected >Intervals</option>'+
	'							<option value="2">2</option>'+
	'							<option value="3">3</option>'+
	'							<option value="4">4</option>'+
	'							<option value="5">5</option>'+
	'							<option value="6">6</option>'+
	'							<option value="7">7</option>'+
	'							<option value="8">8</option>'+
	'							<option value="9">9</option>'+
	'						</select>'+
	'					</div>'+
	'					<script id="tematic-values-unic-punt-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						{{#each values}}'+
	'						<tr><td>{{v}}</td><td>'+
	'							{{#if style.isCanvas}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
	'									style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: {{style.fillColor}};"> </div>'+
	'							{{else}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-{{style.markerColor}} fa'+
	'									{{#if style.icon}}'+
	'										fa-{{style.icon}}"></div>'+	
	'									{{else}}'+
	'										"></div>'+
	'									{{/if}}'+
	'							{{/if}}'+
	'						</td></tr>'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-unic-polyline-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						{{#each values}}'+
	'						<tr><td>{{v}}</td><td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-unic-polygon-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						{{#each values}}'+
	'						<tr><td>{{v}}</td><td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-rangs-punt-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<thead>'+
	'						<tr>'+
	'     						<th lang="ca">Valor min</th>'+
	'     						<th lang="ca">Valor max</th>'+
	'  						</tr>'+
	' 						</thead>'+
	'						<tbody>'+
	'						{{#each values}}'+
	'                       {{#if v.nodata}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min" disabled></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max" disabled></td>'+
	'							<td>'+
	'							{{#if style.isCanvas}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
	'									style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: {{style.fillColor}};"> </div>'+
	'							{{else}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-{{style.markerColor}} fa'+
	'									{{#if style.icon}}'+
	'										fa-{{style.icon}}"></div>'+	
	'									{{else}}'+
	'										"></div>'+
	'									{{/if}}'+
	'							{{/if}}'+
	'						</td></tr>'+
	'                       {{else}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min"></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max"></td>'+
	'							<td>'+
	'							{{#if style.isCanvas}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
	'									style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: {{style.fillColor}};"> </div>'+
	'							{{else}}'+
	'								<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-{{style.markerColor}} fa'+
	'									{{#if style.icon}}'+
	'										fa-{{style.icon}}"></div>'+	
	'									{{else}}'+
	'										"></div>'+
	'									{{/if}}'+
	'							{{/if}}'+
	'						</td></tr>'+
	'                       {{/if}}'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-rangs-polyline-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						{{#each values}}'+
	'                       {{#if v.nodata}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min" disabled></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max" disabled></td>'+
	'							<td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'                       {{else}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min"></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max"></td>'+
	'							<td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'                       {{/if}}'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-rangs-polygon-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						{{#each values}}'+
	'                       {{#if v.nodata}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min" disabled></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max" disabled></td>'+
	'							<td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'                       {{else}}'+
	'						<tr><td><input type="text" value="{{v.min}}" name="min"></td>'+
	'							<td><input type="text" value="{{v.max}}" name="max"></td>'+
	'							<td>'+
	'							<canvas id="cv_pol{{index}}" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'                       {{/if}}'+
	'						{{/each}}'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-semaforic-punt-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						<tr><td colspan="2"><span lang="ca">Valors menors que el de referència</span></td>'+
	'							<td>'+
	'							<div id="div_punt0" class="awesome-marker-web awesome-marker-icon-punt_r fa fa-dropdown-toggle" data-toggle="dropdown"'+ 
	'								style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: ;"> </div>'+
	'						</td></tr>'+
	'						<tr><td><span lang="ca">Valor de referència</span></td>'+
	'							<td><input id="refValue" type="text" value="{{value}}" name="ref"></td>'+
	'							<td>'+
	'							<div id="div_punt1" class="awesome-marker-web awesome-marker-icon-punt_r fa fa-dropdown-toggle" data-toggle="dropdown"'+ 
	'								style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: ;"> </div>'+
	'						</td></tr>'+
	'						<tr><td colspan="2"><span lang="ca">Valors majors que el de referència</span></td>'+
	'							<td>'+
	'							<div id="div_punt2" class="awesome-marker-web awesome-marker-icon-punt_r fa fa-dropdown-toggle" data-toggle="dropdown"'+ 
	'								style="font-size: 8px; width: 16px; height: 16px; color: rgb(51, 51, 51); background-color: ;"> </div>'+
	'						</td></tr>'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-semaforic-polyline-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						<tr><td colspan="2"><span lang="ca">Valors menors que el de referència</span></td>'+
	'							<td>'+
	'							<canvas id="cv_pol0" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						<tr><td><span lang="ca">Valor de referència</span></td>'+
	'							<td><input id="refValue" type="text" value="{{value}}" name="ref"></td>'+
	'							<td>'+
	'							<canvas id="cv_pol1" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						<tr><td colspan="2"><span lang="ca">Valors majors que el de referència</span></td>'+
	'							<td>'+
	'							<canvas id="cv_pol2" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<script id="tematic-values-semaforic-polygon-template" type="text/x-handlebars-template">'+
	'					<table class="table">'+
	'						<tbody>'+
	'						<tr><td colspan="2"><span lang="ca">Valors menors que el de referència</span></td>'+
	'							<td>'+
	'							<canvas id="cv_pol0" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						<tr><td><span lang="ca">Valor de referència</span></td>'+
	'							<td><input id="refValue" type="text" value="{{value}}" name="ref"></td>'+
	'							<td>'+
	'							<canvas id="cv_pol1" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						<tr><td colspan="2"><span lang="ca">Valors majors que el de referència</span></td>'+
	'							<td>'+
	'							<canvas id="cv_pol2" height="30" width="30" class="shadow dropdown-toggle" data-toggle="dropdown"></canvas>'+
	'						</td></tr>'+
	'						</tbody>'+
	'					</table>'+	
	'					</script>'+
	'					<div id="palet_warning" class="alert alert-warning"><span class="glyphicon glyphicon-info-sign"></span>'+
	'					<span lang="ca">Per facilitar la llegibilitat del mapa hem limitat el número màxim de colors per a aquest estil a 9. La resta de categories es simbolitzaran amb color gris</span></div>'+
	'					<div id="list_tematic_values"></div>'+

	'					<div id="paletes_colors">'+
	'						<div><span lang="ca">Tria la paleta de colors</span><span class="glyphicon glyphicon-arrow-down btn-reverse-palete"></span><span lang="ca" class="btn-reverse-palete">Inverteix paleta</span></div>'+
	'<div class="ramp BuGn"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(237,248,251)"/><rect y="15" height="15" width="15" fill="rgb(178,226,226)"/><rect y="30" height="15" width="15" fill="rgb(102,194,164)"/><rect y="45" height="15" width="15" fill="rgb(44,162,95)"/><rect y="60" height="15" width="15" fill="rgb(0,109,44)"/></svg></div>'+
	'<div class="ramp BuPu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(237,248,251)"/><rect y="15" height="15" width="15" fill="rgb(179,205,227)"/><rect y="30" height="15" width="15" fill="rgb(140,150,198)"/><rect y="45" height="15" width="15" fill="rgb(136,86,167)"/><rect y="60" height="15" width="15" fill="rgb(129,15,124)"/></svg></div>'+
	'<div class="ramp GnBu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(240,249,232)"/><rect y="15" height="15" width="15" fill="rgb(186,228,188)"/><rect y="30" height="15" width="15" fill="rgb(123,204,196)"/><rect y="45" height="15" width="15" fill="rgb(67,162,202)"/><rect y="60" height="15" width="15" fill="rgb(8,104,172)"/></svg></div>'+
	'<div class="ramp OrRd"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(254,240,217)"/><rect y="15" height="15" width="15" fill="rgb(253,204,138)"/><rect y="30" height="15" width="15" fill="rgb(252,141,89)"/><rect y="45" height="15" width="15" fill="rgb(227,74,51)"/><rect y="60" height="15" width="15" fill="rgb(179,0,0)"/></svg></div>'+
	'<div class="ramp PuBu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(241,238,246)"/><rect y="15" height="15" width="15" fill="rgb(189,201,225)"/><rect y="30" height="15" width="15" fill="rgb(116,169,207)"/><rect y="45" height="15" width="15" fill="rgb(43,140,190)"/><rect y="60" height="15" width="15" fill="rgb(4,90,141)"/></svg></div>'+
	'<div class="ramp PuBuGn"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(246,239,247)"/><rect y="15" height="15" width="15" fill="rgb(189,201,225)"/><rect y="30" height="15" width="15" fill="rgb(103,169,207)"/><rect y="45" height="15" width="15" fill="rgb(28,144,153)"/><rect y="60" height="15" width="15" fill="rgb(1,108,89)"/></svg></div>'+
	
	'<div class="ramp PuRd"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(241,238,246)"/><rect y="15" height="15" width="15" fill="rgb(215,181,216)"/><rect y="30" height="15" width="15" fill="rgb(223,101,176)"/><rect y="45" height="15" width="15" fill="rgb(221,28,119)"/><rect y="60" height="15" width="15" fill="rgb(152,0,67)"/></svg></div>'+
	'<div class="ramp RdPu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(254,235,226)"/><rect y="15" height="15" width="15" fill="rgb(251,180,185)"/><rect y="30" height="15" width="15" fill="rgb(247,104,161)"/><rect y="45" height="15" width="15" fill="rgb(197,27,138)"/><rect y="60" height="15" width="15" fill="rgb(122,1,119)"/></svg></div>'+
	'<div class="ramp YlGn"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(255,255,204)"/><rect y="15" height="15" width="15" fill="rgb(194,230,153)"/><rect y="30" height="15" width="15" fill="rgb(120,198,121)"/><rect y="45" height="15" width="15" fill="rgb(49,163,84)"/><rect y="60" height="15" width="15" fill="rgb(0,104,55)"/></svg></div>'+
	'<div class="ramp YlGnBu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(255,255,204)"/><rect y="15" height="15" width="15" fill="rgb(161,218,180)"/><rect y="30" height="15" width="15" fill="rgb(65,182,196)"/><rect y="45" height="15" width="15" fill="rgb(44,127,184)"/><rect y="60" height="15" width="15" fill="rgb(37,52,148)"/></svg></div>'+
	'<div class="ramp YlOrBr"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(255,255,212)"/><rect y="15" height="15" width="15" fill="rgb(254,217,142)"/><rect y="30" height="15" width="15" fill="rgb(254,153,41)"/><rect y="45" height="15" width="15" fill="rgb(217,95,14)"/><rect y="60" height="15" width="15" fill="rgb(153,52,4)"/></svg></div>'+
	'<div class="ramp YlOrRd"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(255,255,178)"/><rect y="15" height="15" width="15" fill="rgb(254,204,92)"/><rect y="30" height="15" width="15" fill="rgb(253,141,60)"/><rect y="45" height="15" width="15" fill="rgb(240,59,32)"/><rect y="60" height="15" width="15" fill="rgb(189,0,38)"/></svg></div>'+
	
	'<div class="ramp BrBG"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(166,97,26)"/><rect y="15" height="15" width="15" fill="rgb(223,194,125)"/><rect y="30" height="15" width="15" fill="rgb(245,245,245)"/><rect y="45" height="15" width="15" fill="rgb(128,205,193)"/><rect y="60" height="15" width="15" fill="rgb(1,133,113)"/></svg></div>'+
	'<div class="ramp PRGn"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(123,50,148)"/><rect y="15" height="15" width="15" fill="rgb(194,165,207)"/><rect y="30" height="15" width="15" fill="rgb(247,247,247)"/><rect y="45" height="15" width="15" fill="rgb(166,219,160)"/><rect y="60" height="15" width="15" fill="rgb(0,136,55)"/></svg></div>'+
	'<div class="ramp PuOr"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(230,97,1)"/><rect y="15" height="15" width="15" fill="rgb(253,184,99)"/><rect y="30" height="15" width="15" fill="rgb(247,247,247)"/><rect y="45" height="15" width="15" fill="rgb(178,171,210)"/><rect y="60" height="15" width="15" fill="rgb(94,60,153)"/></svg></div>'+
	'<div class="ramp RdGy"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(202,0,32)"/><rect y="15" height="15" width="15" fill="rgb(244,165,130)"/><rect y="30" height="15" width="15" fill="rgb(255,255,255)"/><rect y="45" height="15" width="15" fill="rgb(186,186,186)"/><rect y="60" height="15" width="15" fill="rgb(64,64,64)"/></svg></div>'+
	'<div class="ramp RdYlBu"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(215,25,28)"/><rect y="15" height="15" width="15" fill="rgb(253,174,97)"/><rect y="30" height="15" width="15" fill="rgb(255,255,191)"/><rect y="45" height="15" width="15" fill="rgb(171,217,233)"/><rect y="60" height="15" width="15" fill="rgb(44,123,182)"/></svg></div>'+
	'<div class="ramp RdYlGn"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(215,25,28)"/><rect y="15" height="15" width="15" fill="rgb(253,174,97)"/><rect y="30" height="15" width="15" fill="rgb(255,255,191)"/><rect y="45" height="15" width="15" fill="rgb(166,217,106)"/><rect y="60" height="15" width="15" fill="rgb(26,150,65)"/></svg></div>'+
	'<div class="ramp Spectral"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(215,25,28)"/><rect y="15" height="15" width="15" fill="rgb(253,174,97)"/><rect y="30" height="15" width="15" fill="rgb(255,255,191)"/><rect y="45" height="15" width="15" fill="rgb(171,221,164)"/><rect y="60" height="15" width="15" fill="rgb(43,131,186)"/></svg></div>'+
	
	'<div class="ramp Paired"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(166,206,227)"/><rect y="15" height="15" width="15" fill="rgb(31,120,180)"/><rect y="30" height="15" width="15" fill="rgb(178,223,138)"/><rect y="45" height="15" width="15" fill="rgb(51,160,44)"/><rect y="60" height="15" width="15" fill="rgb(251,154,153)"/></svg></div>'+
	'<div class="ramp Set3"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(141,211,199)"/><rect y="15" height="15" width="15" fill="rgb(255,255,179)"/><rect y="30" height="15" width="15" fill="rgb(190,186,218)"/><rect y="45" height="15" width="15" fill="rgb(251,128,114)"/><rect y="60" height="15" width="15" fill="rgb(128,177,211)"/></svg></div>'+
	'<div class="ramp Set1"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(228,26,28)"/><rect y="15" height="15" width="15" fill="rgb(55,126,184)"/><rect y="30" height="15" width="15" fill="rgb(77,175,74)"/><rect y="45" height="15" width="15" fill="rgb(152,78,163)"/><rect y="60" height="15" width="15" fill="rgb(255,127,0)"/></svg></div>'+
	'<div class="ramp Dark2"><svg height="75" width="15"><rect y="0" height="15" width="15" fill="rgb(27,158,119)"/><rect y="15" height="15" width="15" fill="rgb(217,95,2)"/><rect y="30" height="15" width="15" fill="rgb(117,112,179)"/><rect y="45" height="15" width="15" fill="rgb(231,41,138)"/><rect y="60" height="15" width="15" fill="rgb(102,166,30)"/></svg></div>'+
	
//	'						<img id="paletaPaired" src="img/paleta2.png" class="btn-paleta" lang="ca" title="Paired">'+
//	'						<img id="paletaPastel" src="img/paleta1.png" class="btn-paleta" lang="ca" title="Pastel">'+
//	'						<img id="paletaDivergent" src="img/paleta_divergent.png" class="btn-paleta" lang="ca" title="Divergent">'+
//	'						<img id="paletaSecuencial" src="img/paleta_sequencial.png" class="btn-paleta" lang="ca" title="Sequencial">'+
	'					</div>'+
	
	
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<button type="button" class="btn btn-default" data-dismiss="modal" lang="ca">Tancar</button>'+
	'         			<button type="button" class="btn btn-success" lang="ca">Canviar</button>'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- fi Modal Tematics Rangs -->'		
	);
}


function addHtmlModalBubbles(){
	jQuery('#mapa_modals').append(
			'<!-- Modal Tematics Bubble -->'+
			'<div class="modal fade" id="dialog_tematic_bubble">'+
			'	<div class="modal-dialog">'+
			'		<div class="modal-content panel-primary">'+
			'			<div class="modal-header panel-heading">'+
			'				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'+
			'				<h4 class="modal-title" lang="ca">Defineix les categories</h4>'+
			'			</div>'+
			'			<div class="modal-body">'+
			'				<div class="labels_fields">'+
			'					<span lang="ca">Escull el camp per simbolitzar</span>:'+
			'					<select name="dataFieldBubble" id="dataFieldBubble">'+
			'					</select>'+
			'				</div>'+
			'                <script id="tematic-layers-fields-bubble" type="text/x-handlebars-template">'+
			'						<option value="---" lang="ca">Escull el camp</option>'+
			'						{{#each fields}}'+
			'						<option value="{{this}}">{{@key}}</option>'+
			'						{{/each}}'+
			'					</script>'+
			'				<br/>'+										
			'				<div id="tipus_agrupacio_grp_bubble" class="labels_fields">'+
			"					<span lang='ca'>Escull l'interval</span>:"+
			'					<input type="radio" id="rd_tipus_graduado" name="rd_tipus_agrupacio_bubble" value="G">'+
			'					<label for="rd_tipus_graduado" lang="ca">graduat</label>'+
			'					<span class="rd_separator"></span>'+
			'                   <input type="radio" id="rd_tipus_proporcional" name="rd_tipus_agrupacio_bubble" value="P">'+
			'					<label for="rd_tipus_proporcional" lang="ca">proporcional</label>'+
			'				</div>'+			
			'				<div id="num_rangs_grp_bubble" class="labels_fields" >'+
			'					<select id="cmb_num_rangs_bubble">'+
			'						<option value="---" selected >Intervals</option>'+
			'						<option value="3">3</option>'+
			'						<option value="4">4</option>'+
			'						<option value="5">5</option>'+
			'						<option value="6">6</option>'+
			'						<option value="7">7</option>'+
			'					</select>'+
			'				</div>'+
			'				<script id="tematic-values-rangs-punt-template-bubble" type="text/x-handlebars-template">'+
			'				<table class="table">'+
			'					<thead>'+
			'					<tr>'+
		    ' 						<th lang="ca">Valor min.</th>'+
		    ' 						<th lang="ca">Valor max.</th>'+
			'						<th lang="ca">Mida</th>'+
			'						<th lang="ca"></th>'+
		  	'					</tr>'+
		 	'					</thead>'+
			'					<tbody>'+
			'					{{#each values}}'+
			'                   {{#if v.nodata}}'+
			'					<tr><td class="td_15"><input type="text" value="{{v.min}}" name="min" disabled></td>'+
			'						<td class="td_15"><input type="text" value="{{v.max}}" name="max" disabled></td>'+
			'						<td class="td_15"><input type="number" value="{{style.size}}" name="mida" class="mida nodata"></td>'+
			'						<td class="">'+
			'						<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
			'								style="font-size: 10.5px; width: {{style.size}}px; height: {{style.size}}px; color: rgb(51, 51, 51); background-color: {{style.fillColor}}; border-radius:{{style.radius}}px"> </div>'+
			'					</td></tr>'+
			'                   {{else}}'+
			'					<tr><td class="td_15"><input type="text" value="{{v.min}}" name="min"></td>'+
			'						<td class="td_15"><input type="text" value="{{v.max}}" name="max"></td>'+
			'						<td class="td_15"><input type="number" value="{{style.size}}" name="mida" class="mida"></td>'+
			'						<td class="">'+
			'						<div id="div_punt{{index}}" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
			'								style="font-size: 10.5px; width: {{style.size}}px; height: {{style.size}}px; color: rgb(51, 51, 51); background-color: {{style.fillColor}}; border-radius:{{style.radius}}px"> </div>'+
			'					</td></tr>'+
			'                   {{/if}}'+
			'					{{/each}}'+
			'					</tbody>'+
			'				</table>	'+
			'				</script>'+
			'				<script id="tematic-values-proportional-punt-template-bubble" type="text/x-handlebars-template">'+
			'				<table class="table text-center buble_table">'+
			'					<tbody>'+
			'					{{#each values}}'+
			'                   {{#if v.nodata}}'+
			'                   <tr><td colspan="2">'+
			'                     <div class="buble_prop">'+
			'                       <div><label lang="ca">Sense valor</label>&nbsp;{{v.min}}<input type="hidden" value="{{v.min}}" name="min"></div>'+
			'                       <div><label lang="ca">mida</label>&nbsp;<input type="number" value="{{style.size}}" name="mida" class="mida nodata"></div>'+
			'						<div id="div_punt_nodata" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
			'								style="font-size: 10.5px; width: {{style.size}}px; height: {{style.size}}px; color: rgb(51, 51, 51); background-color: {{style.fillColor}}; border-radius:{{style.radius}}px"> </div>'+
			'                     </div></td>'+
			'                   </td></tr>'+
			'                   {{else}}'+
			'					<tr><td>'+
			'                     <div class="buble_prop">'+
			'                       <div><label lang="ca">Valor min.</label>&nbsp;{{v.min}}<input type="hidden" value="{{v.min}}" name="min"></div>'+
			'                       <div><label lang="ca">mida</label>&nbsp;<input type="number" value="{{style.size}}" name="mida" class="mida"></div>'+
			'						<div id="div_punt_min" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
			'								style="font-size: 10.5px; width: {{style.size}}px; height: {{style.size}}px; color: rgb(51, 51, 51); background-color: {{style.fillColor}}; border-radius:{{style.radius}}px"> </div>'+
			'                     </div></td>'+
			'						<td><div class="buble_prop">'+
			'                        <div><label lang="ca">Valor max.</label>&nbsp;{{v.max}}<input type="hidden" value="{{v.max}}" name="max"></div>'+
			'                       <div><label lang="ca">mida</label>&nbsp;<input type="number" value="{{style.sizeMax}}" name="mida_max" class="mida"></div>'+
			'						<div id="div_punt_max" class="awesome-marker-web awesome-marker-icon-punt_r fa fa- dropdown-toggle" data-toggle="dropdown"'+ 
			'								style="font-size: 10.5px; width: {{style.sizeMax}}px; height: {{style.sizeMax}}px; color: rgb(51, 51, 51); background-color: {{style.fillColor}}; border-radius:{{style.radiusMax}}px"> </div>'+
			'					</td></tr>'+
			'                   {{/if}}'+
			'					{{/each}}'+
			'					</tbody>'+
			'				</table>	'+
			'				</script>'+
			'				<div id="list_tematic_values_bubble"></div>'+
			'				<div id="size_warning_bubble_grad" class="alert alert-warning"><span class="glyphicon glyphicon-info-sign"></span>'+
			'				<span lang="ca">Les mides han de ser creixents</span></div>'+
			'				<div id="size_warning_bubble_prop" class="alert alert-warning"><span class="glyphicon glyphicon-info-sign"></span>'+
			'				<span lang="ca">La mida mínima ha de ser inferior a la màxima</span></div>'+
			'				<div id="palet_warning_bubble" class="alert alert-warning"><span class="glyphicon glyphicon-info-sign"></span>'+
			'				<span lang="ca">Has de seleccionar un camp amb valors numèrics</span></div>'+
			'			</div>'+
			'			<div class="modal-footer">'+
			'				<div id="paletes_colors">'+
			'					<div lang="ca">Tria el color</div>'+
			'					<div class="btn-group">'+
			'						<a class="btn btn-mini dropdown-toggle" data-toggle="dropdown">'+
			'							<div id="dv_fill_color_punt_bubble" class="fill_color_punt"></div>'+
			'						</a>'+
			'						<ul class="dropdown-menu">'+
			'							<li><div id="colorpalette_punt_bubble"></div></li>'+
			'						</ul>'+
			'					</div>'+
			'				</div>'+
			'				<button type="button" class="btn btn-default" data-dismiss="modal" lang="ca">Tancar</button>'+
		    '     			<button type="button" class="btn btn-success" lang="ca">Canviar</button>'+
			'			</div>'+
			'		</div>'+
			'		<!-- /.modal-content -->'+
			'	</div>'+
			'	<!-- /.modal-dialog -->'+
			'</div>'+
			'<!-- /.modal -->'+
			'<!-- fi Modal Tematics Bubble -->'
	);
}


/*NOU MODEL VISUALITZACIO*/
function loadVisualitzacioLayer(layer,removed){
	var businessId;
	if (layer.businessId!=undefined){
		businessId=layer.businessId;
	}else if (layer.options.businessId!=undefined){
		businessId = layer.options.businessId;
	}
	
	var defer = $.Deferred();
	var data={
		uid : Cookies.get('uid'),
		businessId: businessId
	};
	
	getVisualitzacioByBusinessId(data).then(function(results){
		if(results.status == "OK" ){
			if (removed){
				var data ={
					businessId: businessId,
					uid:Cookies.get('uid')
				};
				var resultats = results.results;
				getGeometriesPropertiesLayer(data).then(function(results2){
					 readVisualitzacio(defer, resultats, results2.layer);
				});
			}
			else 
			{

				if(!controlCapes.hasOwnProperty("_visLayers"))
				{
				
					controlCapes._visLayers = {};
					controlCapes._options = {};
				}
				controlCapes._visLayers[businessId] = results.results;
				controlCapes._options[businessId] = layer;
				readVisualitzacio(defer, results.results, layer);
			}
		}else{
			console.debug('getVisualitzacioByBusinessId ERROR');
			defer.reject();
		}
	},function(results){
		console.debug('getVisualitzacioByBusinessId ERROR');
		defer.reject();
	});
	return defer.promise();
}

function reloadVisualitzacioLayer(capaVisualitzacio, visualitzacio, layer, map){
	var defer = $.Deferred();
	//update del options de la capa
	var optionsVis = getOptions(visualitzacio);
	capaVisualitzacio.options = $.extend(capaVisualitzacio.options, optionsVis);
	if(capaVisualitzacio.options.propName && jQuery.type( capaVisualitzacio.options.propName ) === "string"){
		capaVisualitzacio.options.propName = capaVisualitzacio.options.propName.split(",");
	}
		
	//limpiar las geometrias	
	try{
		capaVisualitzacio.clearLayers();
	}catch(err){
		if (capaVisualitzacio.layer!=undefined) capaVisualitzacio.layer.clearLayers();
	}
	//cargar las geometrias a la capa
	var layOptions = getOptions(layer);
	var origen = getOrigenLayer(layer);
	var hasSource = (optionsVis && optionsVis.source!=undefined) 
	|| (optionsVis.options && undefined != optionsVis.options.source)
	|| (layOptions && layOptions.source!=undefined );
	try{
		capaVisualitzacio.off('layeradd',objecteUserAdded);//Deixem desactivat event layeradd, per la capa activa
	}catch(err){
		if (capaVisualitzacio.layer!=undefined) capaVisualitzacio.layer.off('layeradd',objecteUserAdded);//Deixem desactivat event layeradd, per la capa activa
	}
	loadGeometriesToLayer(capaVisualitzacio, visualitzacio, optionsVis, origen, map, hasSource);
	
	try{
		capaVisualitzacio.on('layeradd',objecteUserAdded);//Deixem activat event layeradd, per la capa activa
	}catch(err){
		if (capaVisualitzacio.layer!=undefined) 	capaVisualitzacio.layer.on('layeradd',objecteUserAdded);//Deixem activat event layeradd, per la capa activa
	}
	
	defer.resolve(capaVisualitzacio);
	
	return defer.promise();
}

function getOptions(visualitzacio){
	var visOptions = visualitzacio.options;
	if(typeof (visOptions)=="string"){	
		try {
			optionsVis = JSON.parse(visOptions);
		}
		catch (err) {
			optionsVis = visOptions;		
		}
	}else{			
		optionsVis = visOptions;	
	}
	return optionsVis;
}

function getOrigenLayer(layer){
	var origen = "",
	options;
	if (layer.options){
		options = getOptions(layer);
		if(options.origen){//Si es una sublayer
			origen = getLeafletIdFromBusinessId(options.origen);
		}
	}
	return origen;
}

function readVisualitzacio(defer, visualitzacio, layer, geometries){
	var layOptions; 
	if(typeof (layer.options)=="string"){	
		try {
			layOptions = JSON.parse(layer.options);
		}
		catch (err) {
			layOptions = layer.options;		
		}
	}else{			
		layOptions = layer.options;	
	}
	var hasSource = (visualitzacio.options && (visualitzacio.options.indexOf("source")!=-1) ) 
		|| (layOptions && (layOptions.toString().indexOf("source")!=-1) );
	if(visualitzacio.tipus == tem_heatmap){
		loadVisualitzacioHeatmap(visualitzacio, layer.capesOrdre, layer.options, layer.capesActiva, defer);
	}else if(visualitzacio.tipus == tem_cluster){
		loadVisualitzacioCluster(visualitzacio, layer.capesOrdre, layer.options, layer.capesActiva, defer);
	}else{
		var capaVisualitzacio = new L.FeatureGroup();
		if(layOptions && layOptions.group){
			capaVisualitzacio.options = {
				businessId : layer.businessId,
				nom : layer.serverName,
				tipus : layer.serverType,
				tipusRang: visualitzacio.tipus, 
				geometryType: visualitzacio.geometryType,
				estil: visualitzacio.estil,
				group: layOptions.group
			};
		}else{
			capaVisualitzacio.options = {
				businessId : layer.businessId,
				nom : layer.serverName,
				tipus : layer.serverType,
				tipusRang: visualitzacio.tipus, 
				geometryType: visualitzacio.geometryType,
				estil: visualitzacio.estil
			};
		}
		
		var visOptions = visualitzacio.options;
		var optionsVis = getOptions(visualitzacio);
		
		if(hasSource) {
			capaVisualitzacio.options.source = optionsVis.source;
		}
		
		//Pel cas de del tematic categories, tenir els rangs d'estils
		if(visOptions && visOptions.indexOf("estilsRangs")!=-1) {
			capaVisualitzacio.options.estilsRangs = optionsVis.estilsRangs;
		}

		//Pel cas de del tematic categories, tenir els rangs d'estils
		if(visOptions && visOptions.indexOf("rangsEstilsLegend")!=-1) {
			capaVisualitzacio.options.rangsEstilsLegend = optionsVis.rangsEstilsLegend;
		}	
		
		//Pel cas de del tematic categories, tenir la paleta
		if(visOptions && visOptions.indexOf("paleta")!=-1) {
			capaVisualitzacio.options.paleta = optionsVis.paleta;
		}
		
		//Pel cas de del tematic categories, tenir la propietat reverse
		if(visOptions && visOptions.indexOf("reverse")!=-1) {
			capaVisualitzacio.options.reverse = optionsVis.reverse;
		}
		
		//Pel cas de del tematic categories, tenir la propietat dataField
		if(visOptions && visOptions.indexOf("dataField")!=-1) {
			capaVisualitzacio.options.dataField = optionsVis.dataField;
		}
		
		//Pel cas de del tematic categories, tenir la propietat labelField
		if(visOptions && visOptions.indexOf("labelField")!=-1) {
			capaVisualitzacio.options.labelField = optionsVis.labelField;
		}
		
		//Pel cas de del tematic categories, tenir la propietat tipusClasicTematic
		if(visOptions && visOptions.indexOf("tipusClasicTematic")!=-1) {
			capaVisualitzacio.options.tipusClasicTematic = optionsVis.tipusClasicTematic;
		}

		//Pel cas de del tematic semafòric, tenir la propietat de l'atribut fixat
		if(optionsVis && optionsVis.hasOwnProperty("trafficLightKey")) {
			capaVisualitzacio.options.trafficLightKey = optionsVis.trafficLightKey;
		}
		
		//Per les etiquetes
		var isCapaAmbEtiquetes=false;
		if(optionsVis && optionsVis.campEtiqueta!=undefined) {
			isCapaAmbEtiquetes=true;
			capaVisualitzacio.options.campEtiqueta = optionsVis.campEtiqueta;
			if(optionsVis && optionsVis.fontFamily!=undefined) capaVisualitzacio.options.fontFamily = optionsVis.fontFamily;
			if(optionsVis && optionsVis.fontSize!=undefined) capaVisualitzacio.options.fontSize = optionsVis.fontSize;
			if(optionsVis && optionsVis.fontColor!=undefined) capaVisualitzacio.options.fontColor = optionsVis.fontColor;
			if(optionsVis && optionsVis.fontStyle!=undefined) capaVisualitzacio.options.fontFamily = optionsVis.fontStyle;
			if(optionsVis && optionsVis.opcionsVis!=undefined) capaVisualitzacio.options.opcionsVisEtiqueta = optionsVis.opcionsVis;
			if(optionsVis && optionsVis.zoomInicial!=undefined) capaVisualitzacio.options.zoomInicial = optionsVis.zoomInicial;
			if(optionsVis && optionsVis.zoomFinal!=undefined) capaVisualitzacio.options.zoomFinal = optionsVis.zoomFinal;
			//Noves opcions de contorn i caixa
			if(optionsVis && optionsVis.contorn!=undefined) capaVisualitzacio.options.contorn = optionsVis.contorn;
			if(optionsVis && optionsVis.caixa!=undefined) capaVisualitzacio.options.caixa = optionsVis.caixa;
			if(optionsVis && optionsVis.caixaColor!=undefined) capaVisualitzacio.options.caixaColor = optionsVis.caixaColor;
		}
		
		var origen = getOrigenLayer(layer);
		
		//ordenar los estilos de mayor a menor para los bubbles
		if (visualitzacio.tipus == tem_size){
			var estilDesc = visualitzacio.estil.sort(sordDesc("simbolSize"));
			visualitzacio.estil = estilDesc;
		}
		
		var isCapaActiva=false;
		if (!layer.capesActiva || layer.capesActiva == true || layer.capesActiva == "true"){
			
			//Afegim geometries a la capa
			capaVisualitzacio.addTo(map);
			$.publish("addMapLayer");
			loadGeometriesToLayer(capaVisualitzacio, visualitzacio, optionsVis, origen, map, hasSource);
			
			
		}	
		else {
			//Afegim geometries a la capa pero no la capa al mapa
			loadGeometriesToLayer(capaVisualitzacio, visualitzacio, optionsVis, origen, map, hasSource);
			if (isCapaAmbEtiquetes){
				jQuery.each(capaVisualitzacio._layers, function(i, lay){
					if(lay.label){
						lay.label.setOpacity(0);
					}
				});	
			}
		}
		
		//Afegim num d'elements al nom de la capa, si és un fitxer
		if(layer.dragdrop || layer.urlFile){
			capaVisualitzacio.options.nom = capaVisualitzacio.options.nom;// + " ("+capaTematic.getLayers().length+")";
			var data = {
			 	businessId: capaVisualitzacio.options.businessId, //url('?businessid') 
			 	uid: Cookies.get('uid'),
			 	serverName: capaVisualitzacio.options.nom
			 };
				
			updateServidorWMSName(data).then(function(results){
			
			});					
		}
			
		if (layer.options){
			var options2;
			if(typeof (layer.options)=="string"){		
				try {
					options2 = JSON.parse(layer.options);
				}
				catch (err) {
					options2 = layer.options;
				}						
			}else{				
				options2 = layer.options;	
			}
			if (options2.propName != undefined) {
				capaVisualitzacio.options.propName = options2.propName;
			}
			else if (visualitzacio.options){
				var options2;
				if(typeof (visualitzacio.options)=="string"){	
					try {
						options2 = JSON.parse(visualitzacio.options);
					}
					catch (err) {
						options2 = visualitzacio.options;
					}
									
				}else{				
					options2 = visualitzacio.options;	
				}		
				if (options2.propName != undefined) {
					var dataNames = options2.propName.split(',');
					capaVisualitzacio.options.propName = dataNames;
				}		
				else if (geometries!=undefined){
					if (  geometries.options){
						var dataNames = geometries.options.split(',');
						//console.debug(dataNames);
						capaVisualitzacio.options.propName = dataNames;
					}
				}
			}			
		}else{
			if (geometries!=undefined){
				if (  geometries.options){
					var dataNames = geometries.options.split(',');
					capaVisualitzacio.options.propName = dataNames;
				}
			}
		}
		
		if (capaVisualitzacio.options.propName== undefined) {
			if (visualitzacio.estil!=undefined && visualitzacio.estil[0]!=undefined){
				if ( visualitzacio.estil[0].geometria!=undefined &&  visualitzacio.estil[0].geometria.features!=undefined &&
						visualitzacio.estil[0].geometria.features.length>0){
					//var props = console.debug(visualitzacio.estil[0].geometria.features[0].properties);
					
					var props;
					if(typeof (visualitzacio.estil[0].geometria.features[0].properties)=="string"){		
						try {
							props = JSON.parse(visualitzacio.estil[0].geometria.features[0].properties);
						}
						catch (err) {
							props = visualitzacio.estil[0].geometria.features[0].properties;
						}						
					}else{				
						props = visualitzacio.estil[0].geometria.features[0].properties;	
					}
					
					var dataNames ="";
					jQuery.each(props, function( index, value ) {
						dataNames+=index+",";						
					});
					capaVisualitzacio.options.propName = dataNames.substring(0,dataNames.length-1);
				}
			}			
		}
		if (capaVisualitzacio.options.propName== undefined) {
			var dataNames=[];
			dataNames[0]="nom";
			dataNames[1]="text";
			capaVisualitzacio.options.propName = dataNames;
		}

		if(layer.options && origen !== ""){//Si es una sublayer
			controlCapes.addOverlay(capaVisualitzacio, capaVisualitzacio.options.nom, true, origen);
		}else {
			if (!layer.capesOrdre){
				capaVisualitzacio.options.zIndex = controlCapes._lastZIndex + 1;
			}else{
				capaVisualitzacio.options.zIndex = parseInt(layer.capesOrdre);
			}
			controlCapes.addOverlay(capaVisualitzacio, capaVisualitzacio.options.nom, true);
			controlCapes._lastZIndex++;
		}
		
		//Si la capa es tematic categories, afegir llegenda al mode edicio
		if ((visualitzacio.tipus == tem_clasic || visualitzacio.tipus == tem_size) && $(location).attr('href').indexOf('/mapa.html')!=-1){
			loadMapLegendEdicio(capaVisualitzacio);
		}
		
		defer.resolve(capaVisualitzacio);
	}		
	return defer.promise();
}

function loadGeometriesToLayer(capaVisualitzacio, visualitzacio, optionsVis, origen, map, hasSource){
	if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined){
		var style = "font-family:"+optionsVis.fontFamily+";font-size:"+optionsVis.fontSize+";color:"+optionsVis.fontColor;
		if (optionsVis.contorn!=undefined && optionsVis.contorn=="si") {
			style+=";text-shadow:1px 1px #ffffff";
		}
		else 	style+=";text-shadow:0px 0px #ffffff";
		if (optionsVis.fontStyle!=undefined){
			if (optionsVis.fontStyle=="normal" || optionsVis.fontStyle=="bold") style+= ";font-weight:"+optionsVis.fontStyle;
			else if (optionsVis.fontStyle=="italic") style+= ";font-style:"+optionsVis.fontStyle;
		}
		if (optionsVis.caixa!=undefined && optionsVis.caixa=="si"){
			style += ";background-color:"+optionsVis.caixaColor;
		}
		else style += ";background-color:transparent";
		createClass('.etiqueta_style_'+visualitzacio.businessId,style);
	}
	
	var zoomInicialEtiqueta = "2";
	if (optionsVis!=undefined && optionsVis.zoomInicial!=undefined) zoomInicialEtiqueta=optionsVis.zoomInicial;
	var zoomFinalEtiqueta = "19";
	if (optionsVis!=undefined && optionsVis.zoomFinal!=undefined)  zoomFinalEtiqueta=optionsVis.zoomFinal;

	var canSpiderify = (visualitzacio.tipus == tem_clasic || visualitzacio.tipus == tem_simple || visualitzacio.tipus == tem_origen);
	if(visualitzacio.businessId && optionsVis && optionsVis.hasOwnProperty("trafficLightKey") && optionsVis.hasOwnProperty("trafficLightValue"))
	{

		//Canviem la visualització perquè pot ser que la del servidor no estigui bé (passa quan un cop creada la capa es publica el mapa
		//havent canviat el valor pivot de la visualització. En el servidor només s'actualitza el valor i no la geometria associada als estils)
		var sorted = Semaforic.sortGeometry(visualitzacio.estil, optionsVis.trafficLightKey, optionsVis.trafficLightValue);

		//Actualitzem la geometria dels estils a partir de les geometries ordenades i els colors que té el semafòric
		visualitzacio.estil[0].color = optionsVis.trafficLightLowerColor;
		visualitzacio.estil[1].color = optionsVis.trafficLightEqualColor;
		visualitzacio.estil[2].color = optionsVis.trafficLightHigherColor;
		visualitzacio.estil[0].geometria.features = sorted.lowerGeom;
		visualitzacio.estil[1].geometria.features = sorted.equalGeom;
		visualitzacio.estil[2].geometria.features = sorted.higherGeom;

		//Actualitzem el nom de la capa
		visualitzacio.nom = Semaforic.getUpdatedLayerName(visualitzacio.nom, optionsVis.trafficLightValue);
		capaVisualitzacio.options.nom = visualitzacio.nom;

	}
	
	var props = [];
	var checkNumericProperties = false;
	var veientMapa = ($(location).attr('href').indexOf('mapa')!=-1);
	if("undefined" !== typeof optionsVis && optionsVis.hasOwnProperty("propName") && !capaVisualitzacio.hasOwnProperty("isPropertyNumeric"))
	{
	
		props = optionsVis.propName.split(',');
		capaVisualitzacio.isPropertyNumeric = new Array(props.length);
		$.each(props, function(index, prop) {
			capaVisualitzacio.isPropertyNumeric[prop] = true;
		});
		checkNumericProperties = true;

	}
	
	//per cada estil de la visualitzacio
	jQuery.each(visualitzacio.estil, function(index, estil){
		var geomTypeVis = visualitzacio.geometryType;
		var geomStyle;
		
		if (geomTypeVis === t_marker){
			geomStyle = createMarkerStyle(estil, estil.geometria.features.length);
		}else if (geomTypeVis === t_multipoint){
			geomStyle = createMarkerStyle(estil, estil.geometria.features.length);
		}else if (geomTypeVis === t_polyline){
			geomStyle = createLineStyle(estil);
		}else if (geomTypeVis === t_multilinestring){
			geomStyle = createLineStyle(estil);
		}else if (geomTypeVis === t_polygon){
			geomStyle = createAreaStyle(estil);
		}else if (geomTypeVis === t_multipolygon){
			geomStyle = createAreaStyle(estil);
		}
		
		//per cada geometria d'aquell estil
		jQuery.each(estil.geometria.features, function(indexGeom, geom){				
			var featureTem = [];
			if (undefined != geom.geometry){
			var geomType = (geom.geometry.type?geom.geometry.type.toLowerCase():geomTypeVis);

			//Actualitzem el vector de propietats de tipus numèrics de la visualització
			//Els que són falsos en algun feature ja no cal repassar-los, els eliminem del 
			//vector de propietats a comprovar
			
			if(checkNumericProperties)
			{

				//Actualitzem el vector de propietats de tipus numèrics de la visualització
				//Els que són falsos en algun feature ja no cal repassar-los, els eliminem del 
				//vector de propietats a comprovar
				var toRemove = [];
				$.each(props, function(index, prop) {
					capaVisualitzacio.isPropertyNumeric[prop] = capaVisualitzacio.isPropertyNumeric[prop] && $.isNumeric(geom.properties[prop]);
					if(!capaVisualitzacio.isPropertyNumeric[prop])
						toRemove.push(index);
				});
				for(var i=toRemove.length-1; i>=0; i--)
					props.splice(toRemove[i], 1);

			}

			//MultyPoint
			if (geomTypeVis === t_marker && geomType === t_multipoint){
				//TODO revisar que funcione
				var coords=geom.geometry.coordinates;
				for (var i = 0; i < coords.length; i++){
					var c=coords[i];
					if(!geomStyle.isCanvas){
						featureTem.push(new L.marker([c[1], c[0]],
							{icon: geomStyle, isCanvas:false, tipus: t_marker}));
					}else{
						featureTem.push(new L.circleMarker([c[1], c[0]],geomStyle));
					}
				}
			//Punt
			}else if (geomTypeVis === t_marker || geomType === "point"){
				var coords=geom.geometry.coordinates;
				if(!geomStyle.isCanvas){
					var marker=new L.marker([coords[1],coords[0]],{icon: geomStyle, isCanvas:false,tipus: t_marker});
					if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && optionsVis.opcionsVis=="nomesetiqueta" && origen==""){
						marker.setOpacity(0);
					}			
					if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined) {
						if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && 
								(optionsVis.opcionsVis=="nomesetiqueta" || optionsVis.opcionsVis=="etiquetageom") && origen==""){
								marker.bindLabel(geom.properties[optionsVis.campEtiqueta],
								{opacity:1, noHide: true, clickable:true, direction: 'center',className: "etiqueta_style_"+visualitzacio.businessId,offset: [0, 0]});							
						}
						if ((zoomInicialEtiqueta!=undefined && map.getZoom()<zoomInicialEtiqueta) ||
								(zoomFinalEtiqueta!=undefined && map.getZoom() > zoomFinalEtiqueta)) {//ocultem labels
							if (marker.label!=undefined) marker.label.setOpacity(0);
							else marker.hideLabel();
						}
					}
					featureTem.push(marker);
				}else{
					var markerCircle=new L.circleMarker([coords[1],coords[0]],geomStyle);
					if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && optionsVis.opcionsVis=="nomesetiqueta" && origen==""){
						geomStyle = createMarkerStyle(estil, estil.geometria.features.length,0);
						markerCircle=new L.circleMarker([coords[1],coords[0]],geomStyle);
					}
					if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined) {
						if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && 
								(optionsVis.opcionsVis=="nomesetiqueta" || optionsVis.opcionsVis=="etiquetageom") && origen==""){
							markerCircle.bindLabel(geom.properties[optionsVis.campEtiqueta],
								{opacity:1, noHide: true,clickable:true,  direction: 'altre',className: "etiqueta_style_"+visualitzacio.businessId,offset: [0, 0]});						
						}
						if ((zoomInicialEtiqueta!=undefined && map.getZoom()<zoomInicialEtiqueta) ||
								(zoomFinalEtiqueta!=undefined && map.getZoom() > zoomFinalEtiqueta)) {//ocultem labels
								try{
									if (markerCircle.label!=undefined) markerCircle.label.setOpacity(0);
									else markerCircle.hideLabel();
								}catch(err){
									
								}
						}
					}
					featureTem.push(markerCircle);
				}
			//MultiPoint
			}else if (geomTypeVis === t_polyline && geomType === t_multilinestring){
				var coords=geom.geometry.coordinates;
				var llistaLines=[];
				var llistaLines2=[];
				
				for (var i = 0; i < coords.length; i++){
					var lines=coords[i];
					var llistaPunts=[];
					var myPolyline = new L.polyline(llistaPunts,geomStyle);
					
					for (var k = 0; k < lines.length; k++){
						var c=lines[k];
						var punt=new L.LatLng(c[1], c[0]);
						myPolyline.addLatLng(punt);
					}
					featureTem.push(myPolyline);
				}

			//multiLine
			}else if (geomTypeVis === t_polyline){
				var coords=geom.geometry.coordinates;
				var llistaPunts=[];
				for (var i = 0; i < coords.length; i++){
					var c=coords[i];
					var punt=new L.LatLng(c[1], c[0]);
					llistaPunts.push(punt);
				}
				var polyline= (new L.polyline(llistaPunts, geomStyle));
				if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && optionsVis.opcionsVis=="nomesetiqueta" && origen==""){
					geomStyle = createLineStyle(estil,0);
					polyline= (new L.polyline(llistaPunts, geomStyle));
				}
				if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined) {
					if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined) {
							if ((optionsVis.opcionsVis=="nomesetiqueta" || optionsVis.opcionsVis=="etiquetageom")  && origen==""){
								polyline.bindLabelEx(map,geom.properties[optionsVis.campEtiqueta], 
										{ noHide: true, direction: 'center',clickable:true, className: "etiqueta_style_"+visualitzacio.businessId ,offset: [0, 0]});
							}	
							if (optionsVis.opcionsVis=="geometries"){
								polyline.hideLabel();
							}
							if ((zoomInicialEtiqueta!=undefined && map.getZoom()<zoomInicialEtiqueta) ||
									(zoomFinalEtiqueta!=undefined && map.getZoom() > zoomFinalEtiqueta)) {//ocultem labels
								polyline.hideLabel();
							}
					}
				}
				featureTem.push(polyline);
			//multiPolygon
			}else if(geomTypeVis === t_polygon && geomType === t_multipolygon){
				var coords=geom.geometry.coordinates;
				var llistaPoligons=[];
				for (var p = 0; p < coords.length; p++){
					var poligons=coords[p];
					var llistaLines=[];
					for (var i = 0; i < poligons.length; i++){
						var lines=poligons[i];
						var llistaPunts=[];
						for (var k = 0; k < lines.length; k++){
							var c=lines[k];
							var punt=new L.LatLng(c[1], c[0]);
							llistaPunts.push(punt);
						}
						llistaLines.push(llistaPunts);
					}
					llistaPoligons.push(llistaLines);
				}
				var multipolygon = new L.multiPolygon(llistaPoligons, geomStyle);
				multipolygon._options = jQuery.extend({}, multipolygon._options);
				if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && optionsVis.opcionsVis=="nomesetiqueta" && origen==""){
					geomStyle = createAreaStyle(estil,0);
					multipolygon = new L.multiPolygon(llistaLines, geomStyle);
				}
				if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined) {
					if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined) {
							if ((optionsVis.opcionsVis=="nomesetiqueta" || optionsVis.opcionsVis=="etiquetageom")  && origen==""){
								multipolygon.bindLabelExPolygon(map,geom.properties[optionsVis.campEtiqueta], 
									{ noHide: true, direction: 'center',clickable:true, className: "etiqueta_style_"+visualitzacio.businessId,offset: [0, 0] });
							}	
							if (optionsVis.opcionsVis=="geometries"){
								multipolygon.hideLabel();
							}
							if ((zoomInicialEtiqueta!=undefined && map.getZoom()<zoomInicialEtiqueta) ||
									(zoomFinalEtiqueta!=undefined && map.getZoom() > zoomFinalEtiqueta)) {//ocultem labels
								multipolygon.hideLabel();
							}
					}
				}
				featureTem.push(multipolygon);
			//polygon
			}else if (geomTypeVis === t_polygon){
				var coords=geom.geometry.coordinates;
				var llistaLines=[];
				for (var i = 0; i < coords.length; i++){
					var lines=coords[i];
					var llistaPunts=[];
					for (var k = 0; k < lines.length; k++){
						var c=lines[k];
						var punt=new L.LatLng(c[1], c[0]);
						llistaPunts.push(punt);
					}
					llistaLines.push(llistaPunts);
				}
				var polygon = new L.Polygon(llistaLines, geomStyle);
				if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined && optionsVis.opcionsVis=="nomesetiqueta" && origen==""){
					geomStyle = createAreaStyle(estil,0);
					polygon = new L.Polygon(llistaLines, geomStyle);
				}
				if (optionsVis!=undefined && optionsVis.campEtiqueta!=undefined) {
					if (optionsVis!=undefined && optionsVis.opcionsVis!=undefined) {
							if ((optionsVis.opcionsVis=="nomesetiqueta" || optionsVis.opcionsVis=="etiquetageom")  && origen==""){
								polygon.bindLabelExPolygon(map,geom.properties[optionsVis.campEtiqueta], 
									{ noHide: true, direction: 'center',clickable:true, className: "etiqueta_style_"+visualitzacio.businessId,offset: [0, 0] });
							}	
							if (optionsVis.opcionsVis=="geometries"){
								polygon.hideLabel();
							}
							if ((zoomInicialEtiqueta!=undefined && map.getZoom()<zoomInicialEtiqueta) ||
									(zoomFinalEtiqueta!=undefined && map.getZoom() > zoomFinalEtiqueta)) {//ocultem labels
								polygon.hideLabel();
							}
					}
				}
				featureTem.push(polygon);
			}
			jQuery.each(featureTem, function(index, feat){
				feat.properties = {};
				feat.properties.businessId = geom.businessId;
				feat.properties.data = geom.properties;
				feat.properties.estil = estil;
				feat.properties.capaLeafletId = capaVisualitzacio._leaflet_id;
				feat.properties.capaNom = capaVisualitzacio.options.nom;
				feat.properties.capaBusinessId = capaVisualitzacio.options.businessId;
				feat.properties.tipusFeature = geomTypeVis;
				//Cal??
				if (feat.options){
					feat.options.tipus = geomTypeVis;
				}else{
					feat.options = {tipus: geomTypeVis};
				}
				
				feat.properties.feature = {};
				feat.properties.feature.geometry = geom.geometry;
				try{
					capaVisualitzacio.addLayer(feat);
				}catch(err){
					if (capaVisualitzacio.layer!=undefined) capaVisualitzacio.layer.addLayer(feat);
				}
			
				if(geomTypeVis == t_polygon){
					feat.properties.mida = calculateArea(feat);
				}else if(geomTypeVis == t_polyline){
					feat.properties.mida = calculateDistance(feat.getLatLngs());
				}
				else if(geomTypeVis == t_marker && map.hasOwnProperty("oms") && canSpiderify ) {
					map.oms.addMarker(feat);
				}
			
				if(!geom.hasOwnProperty("popupData"))
				{
				
					//Si la capa no ve de fitxer
					var html;
					if(!hasSource){
						//"no te source, no ve de fitxer");
						if(veientMapa && ((capaVisualitzacio.options.tipusRang == tem_origen) || !capaVisualitzacio.options.tipusRang) ){
							html = createPopupWindow(feat,geomTypeVis);
						}else{
							//"Estem mode vis i no es tem origen:"
							html = createPopupWindowData(feat,geomTypeVis, false, origen, capaVisualitzacio);
						}								
					}else{
						//"Te source, ve de fitxer";
						if(veientMapa && capaVisualitzacio.options.tipusRang == tem_origen){
							//"Estem mode mapa i es tem origen"
							html = createPopupWindowData(feat,geomTypeVis, true, origen, capaVisualitzacio);
						}else{
							//"Estem mode vis i no es tem origen:"
							html = createPopupWindowData(feat,geomTypeVis, false, origen, capaVisualitzacio);
						}
					}

					geom.popupData = html;

				}
				else
				{

					feat.bindPopup(geom.popupData, {'offset':[0,-25]});

				}
				/*try{
					if (geomTypeVis===t_marker || geomTypeVis===t_multipoint){
						feat.snapediting = new L.Handler.MarkerSnap(map, feat,{snapDistance:10});
						feat.dragging.disable(); 
					}
					else {
						feat.snapediting = new L.Handler.PolylineSnap(map, feat,{snapDistance:10});
					}
					guideLayers.push(feat);
				}catch(err){
					
				}*/
				map.closePopup();					
			});
			}
		});
	});	
	//FIN EACH
}

/**Funcions per crear un objecte de tipus estil, amb les característiques que li passes
 * per punt, línia, poligon */

function createMarkerStyle(style, num_geometries,opacity){
	//console.debug("createFeatureMarkerStyle");
	if (!num_geometries){
		num_geometries = num_max_pintxos - 1;
	}
	if (style.marker && num_geometries <= num_max_pintxos){
		//Especifiques per cercle amb glyphon
		if(style.marker == 'punt_r'){
			var puntTMP = new L.AwesomeMarkers.icon(default_circuloglyphon_style);
			puntTMP.options.iconColor = style.simbolColor;
			puntTMP.options.icon = style.simbol;
			puntTMP.options.markerColor = style.marker;
			puntTMP.options.isCanvas=false;
			puntTMP.options.divColor= style.color;
			puntTMP.options.shadowSize = new L.Point(1, 1);
			puntTMP.options.radius = style.radius;
			var anchor = style.iconAnchor.split("#");
			var size = style.iconSize.split("#");
			puntTMP.options.iconAnchor.x = parseInt(anchor[0]);
			puntTMP.options.iconAnchor.y = parseInt(anchor[1]);
			puntTMP.options.iconSize.x = size[0];
			puntTMP.options.iconSize.y = size[1];
		}else{
			var puntTMP = new L.AwesomeMarkers.icon(default_marker_style);
			puntTMP.options.iconColor = style.simbolColor;
			puntTMP.options.icon = style.simbol;
			puntTMP.options.markerColor = style.marker;
			puntTMP.options.isCanvas=false;
			puntTMP.options.iconAnchor.x = 14;
			puntTMP.options.iconAnchor.y = 42;
			puntTMP.options.iconSize.x = 28;
			puntTMP.options.iconSize.y = 42;
		}
	}else{ //solo circulo
		var fillOpacity=style.opacity/100;
		var opacitat=1;
		if (opacity!=undefined) {
			fillOpacity=opacity;
			opacitat=0;
		}
		
		var puntTMP = { 
			radius: style.simbolSize, 
			isCanvas: true,
			fillColor: style.color,
			color:  style.borderColor,
			weight:  style.borderWidth,
			fillOpacity: fillOpacity,
			opacity: opacitat,
			tipus: t_marker
		};
	}
	return puntTMP;
}

function createLineStyle(style,opacity){
	var estilTMP = default_line_style;
	estilTMP.color=style.color;
	estilTMP.weight=style.lineWidth;
	estilTMP.tipus=t_polyline;
	if (opacity!=undefined) {
		estilTMP.fillOpacity=opacity;
		estilTMP.opacity=opacity;
	}
	return estilTMP;
}

function createAreaStyle(style,opacity){
	
	var estilTMP= default_area_style;
	var opacitat=style.opacity/100;
	if (opacity!=undefined) {
		opacitat=opacity;
		estilTMP.opacity=opacity;
	}
	estilTMP.fillColor=style.color;
	estilTMP.fillOpacity=opacitat;
	estilTMP.weight=style.borderWidth;
	estilTMP.color=style.borderColor;
	estilTMP.tipus=t_polygon;
	return estilTMP;
}

function loadCacheVisualitzacioLayer(layer){
	var defer = $.Deferred();
	var data={
		businessId: layer.businessId,
		uid: layer.entitatUid
	};
	
	if(!controlCapes.hasOwnProperty("_visLayers"))
	{
	
		controlCapes._visLayers = {};
		controlCapes._options = {};
	}

	$.get(HOST_APP+'capesuser/'+data.uid+'/'+data.businessId+'.json', function(results) { 
		if(results){
			controlCapes._visLayers[data.businessId] = results.results;
			controlCapes._options[data.businessId] = layer;
			readVisualitzacio(defer, results.results, layer);			
		}else{				
			getCacheVisualitzacioLayerByBusinessId(data).then(function(results){
				if(results.status == "OK" ){
					controlCapes._visLayers[data.businessId] = results.results;
					controlCapes._options[data.businessId] = layer;
					readVisualitzacio(defer, results.results, layer);			
				}else{
					console.debug('getVisualitzacioByBusinessId ERROR');
					defer.reject();	
				}	
			});
		}		
	}).fail(function() {
	   getCacheVisualitzacioLayerByBusinessId(data).then(function(results){
			if(results.status == "OK" ){
				controlCapes._visLayers[data.businessId] = results.results;
				controlCapes._options[data.businessId] = layer;
				readVisualitzacio(defer, results.results, layer);
			}else{
				console.debug('getVisualitzacioByBusinessId ERROR');
				defer.reject();	
			}	
		});
	  });
	return defer.promise();
}

function sordDesc(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        var result = (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}
function escapeSpecialChars(jsonString) {
	var myJSONString = JSON.stringify(jsonString);
	var myEscapedJSONString = myJSONString.replace(/\n/g, "\\n");
	//console.debug(myEscapedJSONString);
	return myEscapedJSONString;
  }

function actualitzacioTematic(layerMare,businessIdCapaMare,fId,feature,features,tipusModificacio) {
	//console.debug(layerMare);
	var isClasicTematic=false;
	if (layerMare!=undefined) {
		jQuery.each(layerMare._layers, function(i, sublayer){
			//console.debug(sublayer);
			if(jQuery.type(sublayer.layer.options)== "string"){
					sublayer.layer.options = $.parseJSON(sublayer.layer.options);
			}	            	  
			//Sublayer visualitzacio, carrego la capa
			if(sublayer.layer.options.tipus.indexOf(t_visualitzacio)!=-1){
				//if (sublayer.layer.options.tipusRang=="simpleTematic"){		
					if (tipusModificacio=="alta" || tipusModificacio=="modificacio"){
						if (sublayer.layer.options.tipusRang!="clusterTematic" && sublayer.layer.options.tipusRang!="heatmapTematic"){
							if (sublayer.layer.options.tipusRang=="clasicTematic"){
								var dataRemove = {
										businessId: url('?businessid'),
										uid: Cookies.get('uid'),
										servidorWMSbusinessId:sublayer.layer.options.businessId.toString()
								};
								
								removeLayerFromMap(dataRemove,sublayer);
					
								var props;
								if (layerMare.layer.options.propName!=undefined) props = layerMare.layer.options.propName.toString();
								else props='["nom","text"]';
								var data = {
										businessid: businessIdCapaMare,
										from:"clasicTematic",
										geometrytype:layerMare.layer.options.geometryType,
										leafletid:layerMare.layer._leaflet_id,
										propname:props,
										tipus:layerMare.layer.options.tipus
								};
								jQuery('#info_uploadFile').show();
								busy=true;
								jQuery("#div_uploading_txt").html("");
								jQuery("#div_uploading_txt").html(
									'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
									'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'
								);
								createTematicCategoriesActualitzat(data,sublayer,businessIdCapaMare,layerMare);
							}
							else {	
								//Eliminem la capa de controlCapes
								controlCapes.removeLayer(sublayer);
								
								
								var rangsJSON2 = getFeatureStyle2(sublayer.layer.options.estil[0],sublayer.layer.options.geometryType);
								if (features==null){
									features = {
											type:feature.layer.options.tipus,
											id:fId,
											properties: feature.properties.data,
											estil: rangsJSON2,
											geometry: feature.geometry
									};
									features = JSON.stringify(features);
								}
								var data = {
										businessId: sublayer.layer.options.businessId,//f.layer.properties.capaBusinessId,//Bid de la visualitzacio
										uid: Cookies.get('uid'),
										features: features,
										estilBusinessId: sublayer.layer.options.estil[0].businessId
								};
								addGeometriaToVisualitzacioTematic(data).then(function(results) {
										if(results.status === 'OK'){
											sublayer.layer.serverName = sublayer.layer.options.nom;
											sublayer.layer.serverType = sublayer.layer.options.tipus;
											sublayer.layer.capesActiva = "true";
											sublayer.layer.options.origen = businessIdCapaMare;	
											sublayer.layer.businessId = sublayer.layer.options.businessId;//Si no, no ho trobarà després
												
											//eliminem sublayer del mapa, i recarreguem
											map.removeLayer(sublayer.layer);
											loadVisualitzacioLayer(sublayer.layer);
																			
										}else{
											console.debug('addGeometriaToVisualitzacio ERROR');
										}
								});
							}
						}
						else {
							sublayer.layer.serverName = sublayer.layer.options.nom;
							sublayer.layer.serverType = sublayer.layer.options.tipus;
							sublayer.layer.capesActiva = "true";
							sublayer.layer.options.origen = businessIdCapaMare;	
							sublayer.layer.businessId = sublayer.layer.options.businessId;//Si no, no ho trobarà després
							//eliminem sublayer del mapa, i recarreguem
							map.removeLayer(sublayer.layer);
							loadVisualitzacioLayer(sublayer.layer);
						}
					}
					else if (tipusModificacio=="baixa"){
						  sublayer.layer.serverName = sublayer.layer.options.nom;
				  		  sublayer.layer.serverType = sublayer.layer.options.tipus;
				  		  sublayer.layer.capesActiva = "true";
				  		  sublayer.layer.options.origen =businessIdCapaMare;//layer.properties.capaBusinessId;//BusinessIdCapaorigen
				  		  //tipusRang
				  		  sublayer.layer.businessId = sublayer.layer.options.businessId;//Si no, no ho trobarà després
				  		  //console.debug(sublayer);
				  		  //eliminem sublayer del mapa, i recarreguem
				  		  map.closePopup();
				  		  map.removeLayer(sublayer.layer);
				  		  controlCapes.removeLayer(sublayer);
				  		  loadVisualitzacioLayer(sublayer.layer);
				  		  
				  		  
					}
					else if (tipusModificacio=="modificacioInfo"){
						//Modificació informació d'una geometria - cal refer el temàtic.
						var dataRemove = {
								businessId: url('?businessid'),
								uid: Cookies.get('uid'),
								servidorWMSbusinessId:lbusinessId.toString()
							};
						removeLayerFromMap(dataRemove,sublayer);
						if (sublayer.layer.options.tipusRang=="clasicTematic"){
							var props;
							if (layerMare.layer.options.propName!=undefined) props = layerMare.layer.options.propName.toString();
							else props='["nom","text"]';
							var data = {
									businessid: businessIdCapaMare,
									from:"clasicTematic",
									geometrytype:layerMare.layer.options.geometryType,
									leafletid:layerMare.layer._leaflet_id,
									propname:props,
									tipus:layerMare.layer.options.tipus
							};
							jQuery('#info_uploadFile').show();
							busy=true;
							jQuery("#div_uploading_txt").html("");
							jQuery("#div_uploading_txt").html(
								'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
								'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'
							);
							createTematicCategoriesActualitzat(data,sublayer,businessIdCapaMare,layerMare);
						}
					}
				//}
			}
		 });
	}
	
}

function removeLayerFromMap(data,obj){
	removeServerToMap(data).then(function(results){
		if(results.status==='OK'){


			map.removeLayer(obj.layer);
			//Eliminem la capa de controlCapes
			controlCapes.removeLayer(obj);
			//Esborrem la llegenda de la capa eliminada
			emptyMapLegendEdicio(obj.layer);
			//actualitzem valors zindex de la resta si no es sublayer
			if(!obj.sublayer){
				var removeZIndex = obj.layer.options.zIndex;
				controlCapes._lastZIndex--;
				var aux = controlCapes._layers;
				for (var i in aux) {
					if (aux[i].layer.options.zIndex > removeZIndex) aux[i].layer.options.zIndex--;
				}
				//Eliminem les seves sublayers en cas que tingui
				for(indexSublayer in obj._layers){
					map.removeLayer(map._layers[indexSublayer]);
				}
			}

			//Actualitzem capaUsrActiva
			if(capaUsrActiva!=null && capaUsrActiva.options.businessId == obj.layer.options.businessId){
				capaUsrActiva.removeEventListener('layeradd');
				capaUsrActiva = null;
			}

			deleteServerRemoved(data).then(function(results){
				//se borran del listado de servidores
			});

			


		}else{
			return;//SI no ha anat be el canvi a BD. que no es faci tampoc a client, i es mostri un error
		}
	});
}


<file_sep>/geocatweb/js/geocat.mapa.sig.js
function addHtmlInterficieFuncionsSIG(){
	$.get("templates/funcionsSIG.html",function(data){
		//TODO ver como pasar el modal container
		$('#funcio_SIG').append(data);
		
		$('.div_gr3_sig [data-toggle="tooltip"]').tooltip({placement : 'bottom',container : 'body'});
		
		jQuery("#union").on('click',function(e){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'union', 1]);
			openUnionModal();
			jQuery("#fons_sig").popover('hide');
		});
				
		jQuery("#filtre").on('click',function(e){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'filter', 1]);
			openFilterModal();
			jQuery("#fons_sig").popover('hide');
		});
		
		jQuery("#columnJoin").on('click',function(e){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'columnJoin', 1]);
			openColumnJoinModal();
			jQuery("#fons_sig").popover('hide');
		});
		
		jQuery("#spatialJoin").on('click',function(e){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'spatialJoin', 1]);
			openSpatialJoinModal();
			jQuery("#fons_sig").popover('hide');
		});
		
		jQuery("#fons_sig").on('click',function(e){
			gestionaPopOver(this);
		});
		
		addHtmlModalBuffer();
		addHtmlModalIntersection();
		addHtmlModalTag();
		addHtmlModalCentroid();
		addHtmlModalLayersFilter();
		addHtmlModalFieldsFilter();
		addHtmlModalFieldsFilterAvancat();
		addHtmlModalColumnJoin();
		addHtmlModalSpatialJoin();
		addHtmlModalUnion();
		
		creaPopOverMesFuncionsGIS();
	});
}

function creaPopOverMesFuncionsGIS() {
	var html = '<div id="div_menusig" class="div_gr3_fons">'
		+ '<div id="buffer" lang="ca" class="div_sig_1" data-toggle="tooltip" data-lang-title="Àrea d\'influència" title="Àrea d\'influència"></div>'
		+  '<div id="interseccio" lang="ca" class="div_sig_2" data-toggle="tooltip" data-lang-title="Intersecar" title="Intersecar"></div>'
		+  '<div id="tag" lang="ca" class="div_sig_3" data-toggle="tooltip" data-lang-title="Transmissió (tag)" title="Transmissió (tag)"></div>'
		+  '<div id="centroide" lang="ca" class="div_sig_4" data-toggle="tooltip" data-lang-title="Centre geomètric" title="Centre geomètric"></div>'
		+ '</div>';
	
	jQuery("#fons_sig").popover({
		content : html,
		container : 'body',
		html : true,
		trigger : 'manual',
		selector: '[rel="popover"]'
	});
	
	jQuery("#fons_sig").on('show.bs.popover',function(){
		jQuery(this).attr('data-original-title','');
	});
	
	// please note, that IE11 now returns undefined again for window.chrome
	var isChromium = window.chrome,
	    vendorName = window.navigator.vendor;
	
	jQuery("#fons_sig").on('click',function(e){
		jQuery('#div_menusig [data-toggle="tooltip"]').tooltip({
			placement : 'bottom',
			container : 'body'
		});
		
		$('.popover:not(.in)').hide().detach();
		
		if(isChromium !== null && isChromium !== undefined && vendorName === "Google Inc.") {
		   // is Google chrome
		  jQuery(".popover").css('height','60px');
		  jQuery(".popover").css('width','190px');
		} else { 
			 jQuery(".popover").css('height','60px');
			 jQuery(".popover").css('width','190px');
		}
				
		jQuery(".popover").css('background-color','rgba(60, 62, 54, 0.9)');
		jQuery(".popover").css('z-index','1');
	});
	
	jQuery(document).on('click', "#div_menusig div", function(e) {
		jQuery('#div_menusig [data-toggle="tooltip"]').tooltip('hide');
		var funcioSIG = jQuery(this).attr('id');
		
		if (funcioSIG == "buffer") {
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'buffer', 1]);
			openBufferModal();
			jQuery("#fons_sig").popover('hide');
		}				
		if (funcioSIG == "interseccio") {
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'interseccio', 1]);
			openIntersectionModal();
			jQuery("#fons_sig").popover('hide');
		}
		if (funcioSIG == "tag"){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'tag', 1]);
			openTagModal();
			jQuery("#fons_sig").popover('hide');
		}
		if (funcioSIG == "centroide"){
			_gaq.push(['_trackEvent', 'mapa', tipus_user+'gis', 'centroide', 1]);
			openCentroideModal();
			jQuery("#fons_sig").popover('hide');
		}
		
		jQuery("#div_menusig  div").each(function( index ) {
			jQuery(this).css('opacity','0.7');
			jQuery(this).css('border','0px solid #FFC500');
		});
		jQuery(this).css('opacity','1');		
		jQuery("#colorMap").css('opacity','1');
		jQuery(this).css('border','1px solid #FFC500');
		
	});
}

function openFilterModal(){
	showFilterLayersModal();
	jQuery('#list_filter_values').html("");
	$('#dialog_layers_filter').modal('show');
}


function openBufferModal(){
	//addHtmlModalBuffer();
	createModalConfigLayersBuffer();
	$('#dialog_buffer').modal('show');
	jQuery('#dialog_buffer .btn-primary').on('click',function(event){
		if(busy){
			jQuery('#dialog_buffer').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
			event.stopImmediatePropagation();
			//Cridar funció buffer
			if (!$("input[name='buffer-chck']:checked").val()) {
				alert('Cal seleccionar una capa');
				return false;
			}else {
				var businessId = $("input[name='buffer-chck']:checked").parent().attr('data-businessId');
				var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollBuffer = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										jQuery('#dialog_buffer').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("ABANS BUFFER")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("DESPRES")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("OK")!=-1 && busy){
											clearInterval(pollInterval);
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
											);		
											if (data.midaFitxer==0){
												jQuery('#info_uploadFile').hide();		
												busy=false;
												$('#dialog_error_upload_txt').html("");					
												$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));					
												$('#dialog_error_upload').modal('show');
											}else {
												var data2 = {
													uid: Cookies.get('uid'),
													mapBusinessId: url('?businessid'),
													serverName:data.nomCapaOrigen+" "+window.lang.translate("Àrea d'influència"),
													path:data.path,
													tmpFilePath:data.tmpFilePath,
													midaFitxer:data.midaFitxer,
													sourceExtension:'geojson',
													markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
													lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
													polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
													propertiesList: data.propertiesList,
													geomType: data.geomType
												};
												doUploadFile(data2).then(function(results){
													if (results.status="OK") {
														addDropFileToMap(results);
														$('#dialog_buffer').modal('hide');
														busy=false;
														jQuery('#info_uploadFile').hide();
													}else{
														jQuery('#info_uploadFile').hide();		
														busy=false;
														$('#dialog_error_upload_txt').html("");					
														$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
														$('#dialog_error_upload').modal('show');
													}
												});
											}
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											busy = false;
											
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");										
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));							
											$('#dialog_error_upload').modal('show');
										}else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
							pollInterval = setInterval(function(){
								pollBuffer();
							},pollTime);
						})();
						var data = {
							uid: Cookies.get('uid'),
							urlSIG: paramUrl.buffer,
							tipusSIG: "buffer",
							businessId1: businessId,
							nom:window.lang.translate("Àrea d'influència"),
							text:window.lang.translate("Àrea d'influència"),
							tmpFilePath: tmpFile,
							radi: $('#distancia').val()
						};
						callActions(data);
					}else {
						jQuery('#info_uploadFile').hide();		
						busy=false;
					}
				});		
			}
		}
	});
}

function openIntersectionModal(){
	createModalConfigLayers2("intersection");
	$('#dialog_intersection').modal('show');
	jQuery('#dialog_intersection .btn-primary').on('click',function(event){
		if(busy){
			jQuery('#dialog_intersection').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
			event.stopImmediatePropagation();
			if (!$("input[name='intersect-chck']:checked").val() || !$("input[name='intersect-chck2']:checked").val()) {
				alert('Cal seleccionar dues capes');
				busy=false;
				return false;
			}else {
				//Cridar funció intersecció
				var businessId1 = $("input[name='intersect-chck']:checked").parent().attr('data-businessId');
				var businessId2 = $("input[name='intersect-chck2']:checked").parent().attr('data-businessId');
				var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId1,
					businessId2: businessId2
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollIntersect = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										jQuery('#dialog_intersection').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("ABANS INTERSECTION")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("DESPRES")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("OK")!=-1 && busy){
											clearInterval(pollInterval);
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
											);									
											if (data.midaFitxer==0){
												jQuery('#info_uploadFile').hide();		
												busy=false;
												$('#dialog_error_upload_txt').html("");					
												$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
												$('#dialog_error_upload').modal('show');
											}else {
												var name1 = $("input[name='intersect-chck']:checked").parent().attr('data-layername');
												var name2 = $("input[name='intersect-chck2']:checked").parent().attr('data-layername');
												var data2 = {
													uid: Cookies.get('uid'),
													mapBusinessId: url('?businessid'),
													serverName:window.lang.translate("Intersecció")+" "+name1 +" "+name2,
													path:data.path,
													tmpFilePath:data.tmpFilePath,
													midaFitxer:data.midaFitxer,
													sourceExtension:'geojson',
													markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
													lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
													polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
													propertiesList: data.propertiesList,
													geomType: data.geomType
												};
												doUploadFile(data2).then(function(results){
													if (results.status="OK") {
														addDropFileToMap(results);
														$('#dialog_intersection').modal('hide');
														busy=false;
														jQuery('#info_uploadFile').hide();
													}else {
														jQuery('#info_uploadFile').hide();		
														busy=false;
														$('#dialog_error_upload_txt').html("");					
														$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
														$('#dialog_error_upload').modal('show');
													}
												});
											}
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											busy = false;										
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");										
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));
											$('#dialog_error_upload').modal('show');
										}else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
							pollInterval = setInterval(function(){
								pollIntersect();
							},pollTime);
						})();
						var data = {
							uid: Cookies.get('uid'),
							urlSIG: paramUrl.intersection,
							tipusSIG: "intersection",
							businessId1: businessId1,
							businessId2: businessId2,
							nom:window.lang.translate("Intersecció"),
							text:window.lang.translate("Intersecció"),
							tmpFilePath: tmpFile
						};
						callActions(data);
					}else {
						jQuery('#info_uploadFile').hide();		
						busy=false;					
					}
				});		
			}
		}
	});
}

function openTagModal(){
	createModalConfigLayers2("tag");
	$('#dialog_tag').modal('show');
	jQuery('#dialog_tag .btn-primary').on('click',function(event){
		event.stopImmediatePropagation();
		if(busy){
			jQuery('#dialog_tag').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
			if (!$("input[name='tag-chck']:checked").val() || !$("input[name='tag-chck2']:checked").val()) {
				alert('Cal seleccionar dues capes');
				busy=false;
				return false;
			}else {
				//Cridar funció tag
				var businessId1 = $("input[name='tag-chck']:checked").parent().attr('data-businessId');
				var businessId2 = $("input[name='tag-chck2']:checked").parent().attr('data-businessId');
				var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId1,
					businessId2: businessId2
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollTag = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										jQuery('#dialog_tag').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("ABANS TAG")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("DESPRES")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("OK")!=-1 && busy){
											clearInterval(pollInterval);
											
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
											);									
											if (data.midaFitxer==0){
												jQuery('#info_uploadFile').hide();		
												busy=false;
												$('#dialog_error_upload_txt').html("");					
												$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
												$('#dialog_error_upload').modal('show');
											}else {
												var data2 = {
													uid: Cookies.get('uid'),
													mapBusinessId: url('?businessid'),
													serverName:window.lang.translate("Transmissió (tag)")+" "+data.nomCapaOrigen1+" "+data.nomCapaOrigen2,
													path:data.path,
													tmpFilePath:data.tmpFilePath,
													midaFitxer:data.midaFitxer,
													sourceExtension:'geojson',
													markerStyle:data.markerEstil,
													propertiesList: data.propertiesList,
													geomType: data.geomType
												};
												doUploadFile(data2).then(function(results){
													if (results.status="OK") {
														addDropFileToMap(results);
														 $('#dialog_tag').modal('hide');
														 jQuery('#info_uploadFile').hide();
														 busy=false;
													}else {
														jQuery('#info_uploadFile').hide();		
														busy=false;
														$('#dialog_error_upload_txt').html("");					
														$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
														$('#dialog_error_upload').modal('show');
													}
												});
											}
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											busy = false;										
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");										
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));					
											$('#dialog_error_upload').modal('show');
										}else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
							
							pollInterval = setInterval(function(){
								pollTag();
							},pollTime);
							
						})();
						
						var data = {
							uid: Cookies.get('uid'),
							urlSIG: paramUrl.tag,
							tipusSIG: "tag",
							businessId1: businessId1,
							businessId2: businessId2,
							nom:window.lang.translate("Transmissió (tag)"),
							text:window.lang.translate("Transmissió (tag)"),
							tmpFilePath: tmpFile
						};
						
						callActions(data);
					}else {
						jQuery('#info_uploadFile').hide();		
						busy=false;
					}
				});		
			}
		}
	});
}

function openCentroideModal(){
	//addHtmlModalCentroid();
	createModalConfigLayersCentroide();
	$('#dialog_centroid').modal('show');
	jQuery('#dialog_centroid .btn-primary').on('click',function(event){
		event.stopImmediatePropagation();
		if(busy){
			jQuery('#dialog_centroid').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
			if (!$("input[name='centroide-chck']:checked").val()) {
				alert('Cal seleccionar una capa');
				busy=false;
		        return false;
			}else {
				var businessId1 = $("input[name='centroide-chck']:checked").parent().attr('data-businessId');
				var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId1
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollCentroid = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										jQuery('#dialog_centroid').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("ABANS CENTROIDE")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("DESPRES")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
											);									
										}else if(data.status.indexOf("OK")!=-1 && busy){

											clearInterval(pollInterval);
										
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Creant geometries')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
											);									
											if (data.midaFitxer==0){
												jQuery('#info_uploadFile').hide();		
												busy=false;
												$('#dialog_error_upload_txt').html("");					
												$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
												$('#dialog_error_upload').modal('show');
											}else {
												var data2 = {
													uid: Cookies.get('uid'),
													mapBusinessId: url('?businessid'),
													serverName:data.nomCapaOrigen+" "+window.lang.translate("Centre geomètric"),
													path:data.path,
													//tmpFilePath:'E://usuaris//m.ortega//temp//tmp2.geojson',
													tmpFilePath:data.tmpFilePath,
													midaFitxer:data.midaFitxer,
													sourceExtension:'geojson',
													markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
													lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
													polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
													propertiesList: data.propertiesList,
													geomType: data.geomType
												};
												doUploadFile(data2).then(function(results){
													if (results.status="OK") {
														addDropFileToMap(results);
														$('#dialog_centroid').modal('hide');
														 jQuery('#info_uploadFile').hide();
														 busy=false;
													}
													else {
														jQuery('#info_uploadFile').hide();		
														busy=false;
														$('#dialog_error_upload_txt').html("");					
														$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
														$('#dialog_error_upload').modal('show');
													}
												});
											}
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											busy = false;										
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");										
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));										
											$('#dialog_error_upload').modal('show');
										}else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
						
							pollInterval = setInterval(function(){
								pollCentroid();
							},pollTime);
						})();
					
						var data = {
							uid: Cookies.get('uid'),
							urlSIG: paramUrl.centroid,
							tipusSIG: "centroide",
							businessId1: businessId1,
							nom:window.lang.translate("Centre geomètric"),
							text:window.lang.translate("Centre geomètric"),
							tmpFilePath: tmpFile
						};
					
						callActions(data);
					
					}else {
						jQuery('#info_uploadFile').hide();		
						busy=false;
					}
				});		
			}
		}
	});
}

function addHtmlModalBuffer(){	
	$.get("templates/modalBuffer.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function createModalConfigLayersBuffer(){
	var warningMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	var count = 0;
	var html = '<label class="control-label" lang="ca">'+
		window.lang.translate('Capes disponibles:')+
		'</label>';
	
	jQuery.each(controlCapes._layers, function(i, item){
		var layer = item.layer;
		var layerName = layer.options.nom;
		var checked = "";
		
		var tipusLayer = "";
		if(layer.options.tipus) tipusLayer = layer.options.tipus;
		//Si és visualització o visualització-wms
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ){
			html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'">'+
				'<div class="col-md-9 downloadable-name">'+ layerName +'</div>';
				if (count==0){
					html +=	'<input id="buffer-chck" name="buffer-chck" class="col-md-1 downloadable-chck" type="radio" checked >';
				}
				else {
					html +=	'<input id="buffer-chck" name="buffer-chck" class="col-md-1 downloadable-chck" type="radio"  >';
				}
			html += '</div>';		
			html += '<div class="separate-downloadable-row"></div>';			
			count++;
		}
	});	
	
	html+='';
	if (count==0){
		$('#dialog_buffer .modal-body #buffer_layers').html(warningMSG);
		$('#dialog_buffer .modal-footer').attr("style","display:none;");
	}
	else {
		$('#dialog_buffer .modal-body .modal-layers-sig').html(html);
		$('#dialog_buffer .modal-footer').attr("style","display:block;");
	}
}

function createModalConfigLayersCentroide(){
	var warningMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	var count = 0;
	var html = '<label class="control-label" lang="ca">'+
		window.lang.translate('Capes disponibles:')+
		'</label>';
	
	jQuery.each(controlCapes._layers, function(i, item){
		var layer = item.layer;
		var layerName = layer.options.nom;
		var checked = "";
		var tipusLayer = "";
		if(layer.options.tipus) tipusLayer = layer.options.tipus;
		
		//Si és visualització o visualització-wms
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ){
			if (layer.options.geometryType=="polygon"){	
				html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'">'+
					'<div class="col-md-9 downloadable-name">'+
					layerName+
					'</div>';
				if (count==0){
					html += '<input id="centroide-chck" name="centroide-chck" class="col-md-1 downloadable-chck" type="radio" checked >';
				}	
				else{
					html += '<input id="centroide-chck" name="centroide-chck" class="col-md-1 downloadable-chck" type="radio"  >';
				}
				html += '</div>';		
				html+='<div class="separate-downloadable-row"></div>';			
				count++;
			}
		}
	});	
	
	html+='';
	if (count==0){
		$('#dialog_centroid .modal-body .modal-layers-sig').html(warningMSG);
		$('#dialog_centroid .modal-footer').attr("style","display:none;");
	}
	else {
		$('#dialog_centroid .modal-body .modal-layers-sig').html(html);
		$('#dialog_centroid .modal-footer').attr("style","display:block;");
	}
}

function addHtmlModalIntersection(){
	$.get("templates/modalIntersection.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function createModalConfigLayers2(tipus){
	var warningMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	var count = 0;
	var count2 = 0;
	var countI = 0;
	var countI2= 0;
	var html = '<label class="control-label" lang="ca">'+
		window.lang.translate('Capes disponibles')+":"+
	'</label>';
	if (tipus=="tag" || tipus=="spatialJoin") {
		html = '<label class="control-label" lang="ca">'+
			window.lang.translate('Capes de polígons disponibles')+":"+
			'</label>';
	}
	else if (tipus=="intersection"){
		$('#dialog_intersection .modal-body .modal-layers-sig').html('');
	}
	jQuery.each(controlCapes._layers, function(i, item){		
		var layer = item.layer;
		var layerName = layer.options.nom;
		var checked = "";
		var tipusLayer = "";
		if(layer.options.tipus) tipusLayer = layer.options.tipus;
		//Si és visualització o visualització-wms
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms  ){
			if (tipus=="tag" || tipus=="spatialJoin") {
				if (layer.options.geometryType=="polygon"){
					html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'">'+
						'<div class="col-md-9 downloadable-name">'+
						layerName+
						'</div>';
					if (count==0) {
						html += '<input id="tag-chck" name="tag-chck" class="col-md-1 downloadable-chck" type="radio" checked>';
					}
					else {
						html += '<input id="tag-chck" name="tag-chck" class="col-md-1 downloadable-chck" type="radio"  >';
					}
				   html+='</div>';		
				   html+='<div class="separate-downloadable-row"></div>';
				   count++;
				}
			}	
			else {
				if (layer.options.geometryType=="polygon"){
					html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'" data-layername="'+layerName+'">'+
						'<div class="col-md-9 downloadable-name">'+
						layerName+
						'</div>';
					html+='<input id="intersect-chck" name="intersect-chck" class="col-md-1 downloadable-chck" type="radio"  >';
					html+='</div>';		
					html+='<div class="separate-downloadable-row"></div>';
					countI++;
				}
			}	
		}
	});	
	
	html+='';
	if (tipus=="intersection") {
		html += '<label class="control-label" lang="ca">'+
			window.lang.translate('Capes per fer intersecció')+":"+
			'</label>';
	}
	if (tipus=="union"){
		html += '<label class="control-label" lang="ca">'+
			window.lang.translate('Capes per fer unió')+":"+
			'</label>';
	}
	if (tipus=="tag" || tipus=="spatialJoin") {
		html += '<label class="control-label" lang="ca">'+
			window.lang.translate('Capes de punts disponibles')+":"+
			'</label>';
	}
	
	jQuery.each(controlCapes._layers, function(i, item){	
		var layer = item.layer;
		var layerName = layer.options.nom;
		var checked = "";
		var tipusLayer = "";
		if(layer.options.tipus) tipusLayer = layer.options.tipus;
		
		//Si és visualització o visualització-wms
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ){
			if (tipus=="tag" || tipus=="spatialJoin") {
				if (layer.options.geometryType=="marker"){
					html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'">'+
						'<div class="col-md-9 downloadable-name">'+
						layerName+
						'</div>';
					if (count2==0){
						html += '<input id="tag-chck2" name="tag-chck2" class="col-md-1 downloadable-chck" type="radio" checked>';
					}
					else {
						html += '<input id="tag-chck2" name="tag-chck2" class="col-md-1 downloadable-chck" type="radio"  >';
					}
					html += '</div>';		
					html+='<div class="separate-downloadable-row"></div>';
					count2++;
				}
			}else {
				if (layer.options.geometryType=="polygon"){	
					html += '<div class="downloadable-subrow" data-businessid="'+layer.options.businessId+'" data-layername="'+layerName+'">'+
						'<div class="col-md-9 downloadable-name">'+
						layerName+
						'</div>'+
						'<input id="intersect-chck2" name="intersect-chck2" class="col-md-1 downloadable-chck" type="radio"  >'+
						'</div>';		
					html+='<div class="separate-downloadable-row"></div>';
					countI2++;
				}
			}
			
		}
	});	
	
	html+='';
	
	if (tipus=="intersection") {
		if (countI==0 || countI2==0){
			$('#dialog_intersection .modal-body .modal-layers-sig').html(warningMSG);
			$('#dialog_intersection .modal-footer').attr("style","display:none;");
		}
		else {
			$('#dialog_intersection .modal-body .modal-layers-sig').html(html);
			$('#dialog_intersection .modal-footer').attr("style","display:block;");
		}
	}
	if (tipus=="tag") {
		if (count==0 || count2==0){
			$('#dialog_tag .modal-body .modal-layers-sig').html(warningMSG);
			$('#dialog_tag .modal-footer').attr("style","display:none;");
		}
		else {
			$('#dialog_tag .modal-body .modal-layers-sig').html(html);
			$('#dialog_tag .modal-footer').attr("style","display:block;");
		}
	}
	if (tipus=="spatialJoin") {
		if (count==0 || count2==0){
			$('#dialog_spatial_join .modal-body .modal-layers-sig').html(warningMSG);
			$('#dialog_spatial_join .modal-footer').attr("style","display:none;");
		}
		else {
			$('#dialog_spatial_join .modal-body .modal-layers-sig').html(html);
			$('#dialog_spatial_join .modal-footer').attr("style","display:block;");
		}
	}
}

function addHtmlModalTag(){	
	$.get("templates/modalTag.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}


function addHtmlModalUnion(){
	$.get("templates/modalUnion.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function addHtmlModalCentroid(){
	$.get("templates/modalCentroid.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function addHtmlModalLayersFilter(){
	$.get("templates/modalLayersFilter.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function showFilterLayersModal(){
	//console.debug("showTematicLayersModal");
	var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	jQuery('.modal').modal('hide');
	
	jQuery('#dialog_layers_filter').modal('show');
	var layers = [];
	jQuery.each( controlCapes._layers, function( key, value ) {
		var layerOptions = this.layer.options;
		var tipusLayer = "";
		if(this.layer.options.tipus) tipusLayer = this.layer.options.tipus;
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ) layers.push(this);		
	});
	// fi each
	if(layers.length ==0){
		$('#list_filter_layers').html(warninMSG);		
		return;
	}
	
	layers = {layers:layers};
	
	var source = jQuery("#filter-layers-template").html();
	var template = Handlebars.compile(source);
	var html = template(layers);
	
	$('#list_filter_layers').html(html);
	
	$('.usr_filter_layer').on('click',function(e){
		var _this = jQuery(this);
		var data = _this.data();
		showModalFilterFieldsAvancat(data);
	});
}


function showModalFilterFieldsAvancat(data){
	jQuery('.modal').modal('hide');
	jQuery('#dialog_filter_rangs_avancat').modal('show');
	jQuery("#dialog_filter_rangs_avancat").data("capamare", data);
	jQuery("#filtre_avancat").val("");
	jQuery("#select_filter").val("");
	jQuery('#dataField_filter_avancat2').html('');
	
	var dataTem={
		businessId: data.businessid,
		uid: Cookies.get('uid')
	};
	$('#visFilter').val(data.businessid);
	
	visFilter = data.businessid;
	
	if(data.tipus == t_url_file){
		var urlFileLayer = controlCapes._layers[data.leafletid].layer;
		jQuery("#dialog_filter_rangs_avancat").data("visualitzacio", urlFileLayer.options);
		var fields = {};
		//Recollim propName de les geometries de la capa
		var dataNames = urlFileLayer.options.propName.split(',');
		jQuery.each(dataNames, function( index, value ) {
			fields[value] = value;			
		});
		//creamos el select con los campos
		var source2 = jQuery("#tematic-layers-fields-avancat").html();
		var template2 = Handlebars.compile(source2);
		var html2 = template2({fields:fields});
				
		jQuery('#dataField_filter_avancat').html(html2);
		jQuery('#valors_unics').on('click',function(e){
			e.stopImmediatePropagation();
			var this_ = jQuery('#dataField_filter_avancat');
			readDataUrlFileLayer(urlFileLayer, this_.val()).then(function(results){
				if (results.length == 0){
					var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Aquest camp no te valors')+"<strong>  <span class='fa fa-warning sign'></span></div>";
				}else{
					var fields = {};	
					results.sort(sortByValueMax);
					jQuery.grep(results, function( n, i ) {
						fields[n] =n;
						var source2 = jQuery("#tematic-layers-fields-values-avancat").html();
						var template2 = Handlebars.compile(source2);
						var html2 = template2({fields:fields});
						jQuery('#dataField_filter_avancat2').html(html2);
					});
		
				}
			});
		});	
	}
	else{//Si es una visualitzacio
		var fields = {};
		var dataNames=data.propname.split(',');
		jQuery.each(dataNames, function( index, value ) {
			fields[value] = value;
		});
				
		//creamos el select con los campos
		var source1 = jQuery("#tematic-layers-fields-avancat").html();
		var template1 = Handlebars.compile(source1);
		var html1 = template1({fields:fields});
					
		jQuery('#dataField_filter_avancat').html(html1);
				
				
		jQuery('#valors_unics').on('click',function(e){
			e.stopImmediatePropagation();
			var this_ = jQuery('#dataField_filter_avancat');
			var dataVis={
				businessId1: data.businessid,
				key: this_.val(),
				uid: Cookies.get('uid')
			};
			getValuesFromKeysProperty(dataVis).then(function(results){
				var valors = results.valors;
				var fields = {};
				valors = valors.sort(sortByValueMax);
				jQuery.grep(valors, function( n, i ) {
					fields[n] = n;									
					var source2 = jQuery("#tematic-layers-fields-values-avancat").html();
					var template2 = Handlebars.compile(source2);
					var html2 = template2({fields:fields});
					jQuery('#dataField_filter_avancat2').html(html2);
				});
			});
		});		
				
		jQuery('#nomes_10_valors').on('click',function(e){
			e.stopImmediatePropagation();
			var this_ = jQuery('#dataField_filter_avancat');
			var dataVis={
				businessId1: data.businessid,
				key: this_.val(),
				uid: Cookies.get('uid')
			};
			getValuesFromKeysProperty(dataVis).then(function(results){
				var valors = results.valors;
				var fields = {};
				valors = valors.sort(sortByValueMax);
				var valors10 = valors.slice(0,10);
				jQuery.grep(valors10, function( n, i ) {
					fields[n] = n;									
					var source2 = jQuery("#tematic-layers-fields-values-avancat").html();
					var template2 = Handlebars.compile(source2);
					var html2 = template2({fields:fields});
					jQuery('#dataField_filter_avancat2').html(html2);
				});
			});
		});	
	}

	$('#dataField_filter_avancat').on('dblclick', function(e) {
		e.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " "+this_.val();
		if (keys=="") {keys+=this_.val();}
		else {keys+=","+this_.val();}
		jQuery("#select_filter").val(html);	
	}); 
	 	
	 $('#dataField_filter_avancat').on('change', function(e) {
		 e.stopImmediatePropagation();
		 var source2 = jQuery("#tematic-layers-fields-values-avancat").html();
		 var template2 = Handlebars.compile(source2);
		 var html2 = template2({});
		 jQuery('#dataField_filter_avancat2').html(html2);
	 });
	 
	 
	 $('#dataField_filter_avancat2').on('dblclick', function(e) {
		 e.stopImmediatePropagation();
		 var this_ = jQuery(this);
		 var html = jQuery("#select_filter").val() ;
		 html += " "+this_.val();
		 if (valors=="") valors+=this_.val();
		 else valors+=","+this_.val();
		 jQuery("#select_filter").val(html);				 
	 }); 

	 var keys="";
	 var operands="";
	 var valors="";
	 jQuery('#edicio_filtre').on('click',function(event){
		 event.stopImmediatePropagation();
		 var this_ = jQuery(this);
		 if (!$("input[id='edicio_filtre']:checked").val()) {
			 $('#select_filter').attr('readonly', true);
		}else {
			$('#select_filter').attr('readonly', false);
		}
	});	
	
	jQuery('#equals').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " = ";
		if (operands==""){operands+="=";}
		else {operands+=",=";}
		jQuery("#select_filter").val(html);				
	});	
	
	jQuery('#notequals').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " <> ";
		if (operands==""){operands+="<>";}
		else{operands+=",<>";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#like').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " like ";
		if (operands==""){operands+="like";}
		else{operands+=",like";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#major').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " > ";
		if (operands==""){operands+=">";}
		else{operands+=",>";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#majorequals').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " >= ";
		if (operands==""){operands+=">=";}
		else{operands+=",>=";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#and').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " and ";
		keys+=","+" ";
		valors+=","+" ";
		if (operands==""){operands+="and";}
		else{operands+=",and";}
		jQuery("#select_filter").val(html);				
	});
	jQuery('#menor').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " < ";
		if (operands==""){operands+="<";}
		else{operands+=",<";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#menorequals').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " <= ";
		if (operands==""){operands+="<=";}
		else{operands+=",<=";}
		jQuery("#select_filter").val(html);				
	});
	jQuery('#or').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " or ";
		if (keys==""){keys+=" ";}
		else{keys+=","+" ";}
		if (valors==""){valors+=" ";} 
		else{valors+=","+" ";}
		if (operands==""){operands+="or";}
		else{operands+=",or";}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#not').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " not like ";
		if (operands==""){operands+="not like";}
		else{operands+=",not like";}
		jQuery("#select_filter").val(html);				
	});
	jQuery('#parentobrir').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " (";
		if (operands==""){operands+="(";}
		else{operands+=",(";}
		jQuery("#select_filter").val(html);				
	});
	jQuery('#parenttancar').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += " )";
		if (operands==""){operands+=")";}
		else{operands+=",)";}
		jQuery("#select_filter").val(html);				
	});
	jQuery('#valorFiltre').on('click',function(event){
		event.stopImmediatePropagation();
		var this_ = jQuery(this);
		var html = jQuery("#select_filter").val() ;
		html += jQuery('#filtre_avancat').val();
		if (valors==""){valors+=jQuery('#filtre_avancat').val();} 
		else{valors+=","+jQuery('#filtre_avancat').val();}
		jQuery("#select_filter").val(html);				
	});	
	jQuery('#resetFiltre').on('click',function(event){
		event.stopImmediatePropagation();
		keys="";
		operands="";
		valors="";
		jQuery('#filtre_avancat').val('');
		jQuery("#select_filter").val('');				
	});	
	jQuery('#filtrarBtn').on('click',function(event){
		if(busy){
		 	jQuery('#dialog_filter_rangs_avancat').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
			event.stopImmediatePropagation();
			var data1 = {
				uid: Cookies.get('uid'),
				businessId1: visFilter
			};
			crearFitxerPolling(data1).then(function(results) {
				var tmpFile="";
				if (results.status=="OK"){
					tmpFile = results.tmpFilePath;
					//Definim interval de polling en funcio de la mida del fitxer
					var pollTime =3000;
					//Fem polling
					(function(){							
						pollIntersect = function(){
							$.ajax({
								url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
								dataType: 'json',
								type: 'get',
								success: function(data){
									//console.debug(data);
									jQuery('#dialog_filter_rangs_avancat').hide();
									jQuery('#info_uploadFile').show();
									if(data.status.indexOf("ABANS FILTRE")!=-1 && busy){
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
										);									
									}else if(data.status.indexOf("DESPRES")!=-1 && busy){
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'//+	
										);									
									}else if(data.status.indexOf("OK")!=-1 && busy){

										clearInterval(pollInterval);
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Operació calculada')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Geometries creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'//+	
										);									
										var defer = $.Deferred();
										jQuery('#dialog_filter_rangs_avancat').modal('hide');
										
										addDropFileToMap(data.results);
										jQuery('#info_uploadFile').hide();		
										busy=false;
										activaPanelCapes(true);
										keys="";
										operands="";
										valors="";
										
									}else if(data.status.indexOf("ERROR")!=-1 && busy){
										busy = false;										
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
										
										$('#dialog_error_upload_txt').html("");										
										$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));	
										$('#dialog_error_upload').modal('show');
										
										keys="";
										operands="";
										valors="";
									}
									else if (data.status.indexOf("KO")!=-1 && busy){
										var defer = $.Deferred();
										jQuery('#dialog_filter_rangs_avancat').modal('hide');
										jQuery('#info_uploadFile').hide();	
										$('#dialog_error_upload_txt').html("");					
										$('#dialog_error_upload_txt').html(window.lang.translate("No hi ha resultats per el filtre"));					
										$('#dialog_error_upload').modal('show');
										busy=false;
										keys="";
										operands="";
										valors="";
									}
									else if (!busy){
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
									}
								}
							});
						};
						
						pollInterval = setInterval(function(){
							pollIntersect();
						},pollTime);
						
					})();
					
					var data = {
						uid: Cookies.get('uid'),
						urlSIG: paramUrl.filter,
						tipusSIG: "filter",
						businessId1: visFilter,
						mapBusinessId:url('?businessid'),
						key: keys,
						operand: operands,
						filter: valors,
						markerStyle : JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
						lineStyle : JSON.stringify(getLineRangFromStyle(canvas_linia)),
						polygonStyle : JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
						tmpFilePath: tmpFile
					};
					
					callActions(data);
				}else {
					jQuery('#info_uploadFile').hide();		
					busy=false;					
				}
			});
		}
	});
}

function addHtmlModalFieldsFilter(){
	$.get("templates/modalFieldsFilter.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function addHtmlModalFieldsFilterAvancat(){
	$.get("templates/modalFieldsFilterAvancat.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function getTipusValuesVisualitzacioFilter(results){
	//console.debug("getTipusValuesVisualitzacio");
	if (results.length == 0){
		var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Aquest camp no te valors')+"<strong>  <span class='fa fa-warning sign'></span></div>";
		jQuery('#list_filter_values').html(warninMSG);
		jQuery('#dialog_filter_rangs .btn-success').hide();
	}else{
		var arr = jQuery.grep(results, function( n, i ) {
			return !jQuery.isNumeric(n);
		});
		var checkboxes = "";
		jQuery.grep(results, function( n, i ) {
			var check =  "<input type='checkbox' name='filterValue' value='"+escape(n)+"' id='filter_"+i+"' class='col-md-1 download'/>"+n;
			checkboxes += check +"<br/>" ;
		});
		var html = "2. "+window.lang.translate('Escull els valors pels que vols filtrar')+":<br/>";
		html += checkboxes;
		var filtres="";
		var i=0;
		jQuery('#list_filter_values').html(html);
		jQuery('#dialog_filter_rangs .btn-success').show();
		jQuery('#dialog_filter_rangs .btn-success').on('click',function(e){
			e.stopImmediatePropagation();
			filtres="";
			$('input[name="filterValue"]:checked').each(function() {
			   filtres=filtres+this.value+",";
			   i++;
			});	
			if(busy){
				jQuery('#dialog_filter_rangs').hide();
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
				$('#dialog_info_upload').modal('show');
			}else{
				busy=true; 
				var data1 = {
					uid: Cookies.get('uid'),
					businessId1: $('#visFilter').val()
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollFiltre = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										jQuery('#dialog_filter_rangs').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("ABANS FILTRE")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'
											);									
										}else if(data.status.indexOf("DESPRES")!=-1 && busy){
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
												'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'	
											);									
										}else if(data.status.indexOf("OK")!=-1 && busy){
											clearInterval(pollInterval);
										
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
												'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Creant geometries')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
												'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'	
											);									
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											busy = false;
											
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");
											
											$('#dialog_error_upload_txt').html(window.lang.translate("Error generant filtre"));
											
											
											$('#dialog_error_upload').modal('show');
										}else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
						
							pollInterval = setInterval(function(){
								pollFiltre();
							},pollTime);
						
						})();
					}else {
						jQuery('#info_uploadFile').hide();		
						busy=false;
					}
					var data = {
						mapBusinessId: url('?businessid'),
						uid: Cookies.get('uid'),
						businessId: $('#visFilter').val(),
						campFiltre: $('#dataField_filter option:selected' ).val(),
						valorsFiltre: filtres,
						tmpFilePath: tmpFile
					};
					filterVisualitzacio(data).then(function(results2){
						if (results2.status=="OK"){					
							var defer = $.Deferred();
							readVisualitzacio(defer, results2.visualitzacio, results2.layer);
							jQuery('#info_uploadFile').hide();		
							busy=false;
							activaPanelCapes(true);
						}else {
							jQuery('#info_uploadFile').hide();		
							busy=false;
							$('#dialog_error_upload_txt').html("");					
							$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
							$('#dialog_error_upload').modal('show');
							
						}
					});
				});
			}
		});
	}
}

function addHtmlModalColumnJoin(){
	$.get("templates/modalColumnJoin.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function openColumnJoinModal(){
	
	var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	jQuery('.modal').modal('hide');
	
	$('#dataField_capa1').empty();
	$('#dataField_capa2').empty();

	$('#dataField_camps_capa1').empty();
	$('#dataField_camps_capa2').empty();
	
	$('#list_join_fields').html('');
	$('#list_join_fields2').html('');
	
	jQuery('#dialog_column_join').modal('show');
	var layers = [];
	jQuery.each( controlCapes._layers, function( key, value ) {
		var layerOptions = this.layer.options;
		var tipusLayer = "";
		if(this.layer.options.tipus){tipusLayer = this.layer.options.tipus;}
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ){layers.push(this);}
	});
		
	if(layers.length ==0){
		$('#warning-spatial').html(warninMSG);
		$('#list-layers-join1').attr("style","display:none;");
		$('#list-fields-join2').attr("style","display:none;");
		$('#list-fields-join3').attr("style","display:none;");
		$('#joinBtn').attr("disabled", true);
		return;
	}
	else {
		$('#warning-spatial').html('');
		$('#list-layers-join1').attr("style","display:block;");
		$('#list-fields-join2').attr("style","display:block;");
		$('#list-fields-join3').attr("style","display:block;");
		$('#joinBtn').removeAttr("disabled");
	}
	layers = {layers: layers};
	
	var source = jQuery("#tematic-layers1").html();
	var template = Handlebars.compile(source);
	var html = template(layers);
	$('#dataField_capa1').html('<option value="null">Escull la capa</option>');
	var htmlCapa1=$('#dataField_capa1').html();		
	$('#dataField_capa1').html(htmlCapa1 + html);
	
	var source2 = jQuery("#tematic-layers2").html();
	var template = Handlebars.compile(source2);
	var html2 = template(layers);
	$('#dataField_capa2').html('<option value="null">Escull la capa</option>');
	var htmlCapa2=$('#dataField_capa2').html();
	$('#dataField_capa2').html(htmlCapa2 + html);
	
	jQuery('#dialog_column_join #dataField_capa1').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_camps_capa1').empty();
			$('#list_join_fields').html('');
		}else {
			var fields = {};
			var fields2 = {};	
			var props = event.target.value.split('___');
			var businessId = props[0];
			var propName=props[1];
			var dataNames=propName.split(',');
			fields[window.lang.translate('Escull el camp')] = '---';
			jQuery.each(dataNames, function( index, value ) {
					fields[value] = value;		
					fields2[value]=value;
			});
		
			var source1 = jQuery("#tematic-camp-layers1").html();
			var template1 = Handlebars.compile(source1);
			var html1 = template1({fields:fields});
			jQuery('#dataField_camps_capa1').html(html1);

			var source2 = jQuery("#join-fields-template").html();
			var template2 = Handlebars.compile(source2);
			var html2 = template2({fields:fields2});
			jQuery('#list_join_fields').html(html2);
			
			var nomCapa="Unió taules: ";
			if ($('#dataField_capa1 option:selected').text()!="Escull la capa"){
				if (nomCapa=="Unió taules: ") nomCapa += $('#dataField_capa1 option:selected').text();
				else nomCapa += ","+$('#dataField_capa1 option:selected').text();
			}
			if ($('#dataField_capa2 option:selected').text()!="Escull la capa"){
				if (nomCapa=="Unió taules: ")  nomCapa += $('#dataField_capa2 option:selected').text();
				else nomCapa +=","+$('#dataField_capa2 option:selected').text();
			}
			$('#input-join-name').val(nomCapa);
		}
	});
		
	jQuery('#dialog_column_join #dataField_capa2').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_camps_capa2').empty();
			
			$('#list_join_fields2').html('');
		}else {
			var fields = {};
			var fields2 = {};
			var props = event.target.value.split('___');
			var businessId = props[0];
			var propName=props[1];
			var dataNames=propName.split(',');
			fields[window.lang.translate('Escull el camp')] = '---';
			jQuery.each(dataNames, function( index, value ) {
					fields[value] = value;		
					fields2[value]=value;
			});
						
			var source1 = jQuery("#tematic-camp-layers2").html();
			var template1 = Handlebars.compile(source1);
			var html1 = template1({fields:fields});
			jQuery('#dataField_camps_capa2').html(html1);
			
			var source2 = jQuery("#join-fields-template2").html();
			var template2 = Handlebars.compile(source2);
			var html2 = template2({fields:fields2});
			jQuery('#list_join_fields2').html(html2);
			
			var nomCapa="Unió taules: ";
			if ($('#dataField_capa1 option:selected').text()!="Escull la capa"){
				if (nomCapa=="Unió taules: ") nomCapa += $('#dataField_capa1 option:selected').text();
				else nomCapa += ","+$('#dataField_capa1 option:selected').text();
			}
			if ($('#dataField_capa2 option:selected').text()!="Escull la capa"){
				if (nomCapa=="Unió taules: ")  nomCapa += $('#dataField_capa2 option:selected').text();
				else nomCapa +=","+$('#dataField_capa2 option:selected').text();
			}
			$('#input-join-name').val(nomCapa);
		}
	});
		
	jQuery('#joinBtn').on('click',function(event){
		if(busy){
			jQuery('#dialog_column_join').hide();
			$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
			$('#dialog_info_upload').modal('show');
		}else{
			busy=true; 
			event.stopImmediatePropagation();
			var listCols1="";
			var listCols2="";
			if ($('input[name=geom_capa]:checked').val()=="capa1_geom") listCols1 = "geometry_id,";
			if ($('input[name=geom_capa]:checked').val()=="capa2_geom") listCols2 = "geometry_id,";
			$('input[name="listCol1"]:checked').each(function() {
				listCols1=listCols1+this.value+",";				  
			});
			$('input[name="listCol2"]:checked').each(function() {
				listCols2=listCols2+this.value+",";				  
			});
			var businessId1_props=$('#dataField_capa1').val();
			var businessId1=businessId1_props.split('___');
			
			var businessId2_props=$('#dataField_capa2').val();
			var businessId2=businessId2_props.split('___');
			var data1 = {
				uid: Cookies.get('uid'),
				businessId1: businessId1[0],
				businessId2: businessId2[0]
			};
			crearFitxerPolling(data1).then(function(results) {
				var tmpFile="";
				if (results.status=="OK"){
					tmpFile = results.tmpFilePath;
					//Definim interval de polling en funcio de la mida del fitxer
					var pollTime =3000;
					//Fem polling
					(function(){							
						pollFiltre = function(){
							$.ajax({
								url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
								dataType: 'json',
								type: 'get',
								success: function(data){
									jQuery('#dialog_column_join').hide();
									jQuery('#info_uploadFile').show();
									if(data.status.indexOf("ABANS FILTRE")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'
										);									
									}else if(data.status.indexOf("DESPRES")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'	
										);									
									}else if(data.status.indexOf("OK")!=-1 && busy){
										clearInterval(pollInterval);
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Creant geometries')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'	
										);									
										jQuery('#dialog_column_join').modal('hide');
										
										addDropFileToMap(data.results);
										jQuery('#info_uploadFile').hide();		
										busy=false;
										activaPanelCapes(true);
									}else if(data.status.indexOf("ERROR")!=-1 && busy){
										busy = false;
										jQuery('#dialog_column_join').hide();
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
										
										$('#dialog_error_upload_txt').html("");											
										$('#dialog_error_upload_txt').html(window.lang.translate("Error unint taules per columnes"));		
										$('#dialog_error_upload').modal('show');
									}
									else if (!busy){
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
									}
								}
							});
						};
						
						pollInterval = setInterval(function(){
							pollFiltre();
						},pollTime);
						
					})();
				}
				else {
					jQuery('#info_uploadFile').hide();		
					busy=false;
				}
			
				var data = {
					uid: Cookies.get('uid'),
					urlSIG: paramUrl.columnJoin,
					tipusSIG: "columnJoin",
					mapBusinessId: url('?businessid'),
					businessId1: businessId1[0],
					businessId2: businessId2[0],
					nom: $('#input-join-name').val(),
					column1:$('#dataField_camps_capa1').val(),
					column2:$('#dataField_camps_capa2').val(),
					listColumns1: listCols1,
					listColumns2:listCols2,
					markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
					lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
					polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
					tmpFilePath: tmpFile
				};
				callActions(data);
				
			});
		}
	});
}

function addHtmlModalSpatialJoin(){
	$.get("templates/modalSpatialJoin.html",function(data){
		//TODO ver como pasar el modal container
		$('#mapa_modals').append(data);       		
	});
}

function openSpatialJoinModal(){
	var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	jQuery('.modal').modal('hide');
	
	jQuery('#dialog_spatial_join').modal('show');
	
	$('#dataField_spatial_capa1').empty();
	$('#dataField_spatial_capa2').empty();

	$('#list_spatial_join_fields').html('');
	$('#list_spatial_join_fields2').html('');
	
	 var layersMarkers = [];
	 var layersPolygons = [];
	 	
	jQuery.each( controlCapes._layers, function( key, value ) {
		var layerOptions = this.layer.options;
		var tipusLayer = "";
		//console.debug(this.layer);
		if(this.layer.options.tipus) tipusLayer = this.layer.options.tipus;
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ) {
			
			if (this.layer.options.geometryType=="marker"){
				layersMarkers.push(this);
			}
			if (this.layer.options.geometryType=="polygon"){
				layersPolygons.push(this);
			}
			
		}

	});
		
	if(layersMarkers.length ==0 || layersPolygons.length==0){
		$('#warning-spatial').html(warninMSG);
		$('#list-layers-spatial-join1').attr("style","display:none;");
		$('#list-fields-spatial-join2').attr("style","display:none;");
		$('#spatialjoinBtn').attr("disabled", true);
		return;
	}
	else {
		$('#warning-spatial').html('');
		$('#list-layers-spatial-join1').attr("style","display:block;");
		$('#list-fields-spatial-join2').attr("style","display:block;");
		$('#spatialjoinBtn').removeAttr("disabled");
	}
		
	layersMarkers = {layers: layersMarkers};
	layersPolygons = {layers: layersPolygons};

	
	var source = jQuery("#tematic-spatial-layers1").html();
	var template = Handlebars.compile(source);
	var html = template(layersMarkers);
	$('#dataField_spatial_capa1').html('<option value="null">Escull la capa</option>');
	var htmlCapa1=$('#dataField_spatial_capa1').html();
	$('#dataField_spatial_capa1').html(htmlCapa1 + html);
	
	var source2 = jQuery("#tematic-spatial-layers2").html();
	var template = Handlebars.compile(source2);
	var html2 = template(layersPolygons);
	$('#dataField_spatial_capa2').html('<option value="null">Escull la capa</option>');
	var htmlCapa2=$('#dataField_spatial_capa2').html();
	$('#dataField_spatial_capa2').html(htmlCapa2 + html2);
	 
		
	jQuery('#dialog_spatial_join #dataField_spatial_capa1').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_spatial_capa1').empty();				
			$('#list_spatial_join_fields').html('');
		}
		else {
			var fields = {};
			var props = event.target.value.split('___');
			var businessId = props[0];
			var propName=props[1];
			var dataNames=propName.split(',');
			jQuery.each(dataNames, function( index, value ) {
					fields[value] = value;						
			});


			var source = jQuery("#join-spatial-fields-template").html();
			var template = Handlebars.compile(source);
			var html = template({fields:fields});
			jQuery('#list_spatial_join_fields').html(html);
			
			var nomCapa="Punts dins polígons: ";
			if ($('#dataField_spatial_capa1 option:selected').text()!="Escull la capa"){
				nomCapa += $('#dataField_spatial_capa1 option:selected').text()+",";
			}
			if ($('#dataField_spatial_capa2 option:selected').text()!="Escull la capa"){
				nomCapa += $('#dataField_spatial_capa2 option:selected').text()+",";
			}
			$('#input-spatial-join-name').val(nomCapa);
		}
	});
		
	jQuery('#dialog_spatial_join #dataField_spatial_capa2').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_spatial_capa2').empty();				
			$('#list_spatial_join_fields2').html('');
		}
		else {
			var fields = {};
			var props = event.target.value.split('___');
			var businessId = props[0];
			var propName=props[1];
			var dataNames=propName.split(',');
			jQuery.each(dataNames, function( index, value ) {
					fields[value] = value;						
			});


			var source = jQuery("#join-spatial-fields-template2").html();
			var template = Handlebars.compile(source);
			var html = template({fields:fields});
			jQuery('#list_spatial_join_fields2').html(html);
			
			var nomCapa="Punts dins polígons: ";
			if ($('#dataField_spatial_capa1 option:selected').text()!="Escull la capa"){
				nomCapa += $('#dataField_spatial_capa1 option:selected').text()+",";
			}
			if ($('#dataField_spatial_capa2 option:selected').text()!="Escull la capa"){
				nomCapa += $('#dataField_spatial_capa2 option:selected').text()+",";
			}
			$('#input-spatial-join-name').val(nomCapa);
		}
	});
		
		
	jQuery('#spatialjoinBtn').on('click',function(event){
		event.stopImmediatePropagation();
		 if(busy){
			 	jQuery('#dialog_spatial_join').hide();
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
				$('#dialog_info_upload').modal('show');
		}else{
		 busy=true;
		 	var listCols1="";
			var listCols2="";
			$('input[name="listCol1_spatial"]:checked').each(function() {
				listCols1=listCols1+this.value+",";				  
			});
			$('input[name="listCol2_spatial"]:checked').each(function() {
				listCols2=listCols2+this.value+",";				  
			});
			var businessId1_props=$('#dataField_spatial_capa1').val();
			var businessId1=businessId1_props.split('___');
			
			var businessId2_props=$('#dataField_spatial_capa2').val();
			var businessId2=businessId2_props.split('___');
			
			var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId1[0],
					businessId2: businessId2[0]
			}
			crearFitxerPolling(data1).then(function(results) {
				var tmpFile="";
				if (results.status=="OK"){
					tmpFile = results.tmpFilePath;
					//Definim interval de polling en funcio de la mida del fitxer
					var pollTime =3000;
					//Fem polling
					(function(){							
						pollFiltre = function(){
							$.ajax({
								url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
								dataType: 'json',
								type: 'get',
								success: function(data){
									jQuery('#dialog_spatial_join').hide();
									jQuery('#info_uploadFile').show();
									if(data.status.indexOf("ABANS SPATIAL JOIN")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'
										);									
										
									}else if(data.status.indexOf("DESPRES")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'	
										);									
									}else if(data.status.indexOf("OK")!=-1 && busy){
										clearInterval(pollInterval);
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Creant geometries')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'	
										);									
										jQuery('#dialog_spatial_join').modal('hide');
										if (data.midaFitxer==0){
											jQuery('#info_uploadFile').hide();		
											busy=false;
											$('#dialog_error_upload_txt').html("");					
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
											$('#dialog_error_upload').modal('show');
										}
										else {
											var data2 = {
												uid: Cookies.get('uid'),
												mapBusinessId: url('?businessid'),
												serverName:window.lang.translate("Punts dins de polígons:")+" "+data.nomCapaOrigen1+" "+data.nomCapaOrigen2,
												path:data.path,
												tmpFilePath:data.tmpFilePath,
												midaFitxer:data.midaFitxer,
												sourceExtension:'geojson',
												markerStyle:data.markerEstil,
												propertiesList: data.propertiesList,
												geomType: data.geomType
											}
											doUploadFile(data2).then(function(results){
												if (results.status="OK") {
													addDropFileToMap(results);
													 $('#dialog_spatial_join').modal('hide');
													 jQuery('#info_uploadFile').hide();
													 busy=false;
												}
												else {
													jQuery('#info_uploadFile').hide();		
													busy=false;
													$('#dialog_error_upload_txt').html("");					
													$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
													$('#dialog_error_upload').modal('show');
												}
											});
										}
									}else if(data.status.indexOf("ERROR")!=-1 && busy){
										busy = false;
										
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
										
										$('#dialog_error_upload_txt').html("");											
										$('#dialog_error_upload_txt').html(window.lang.translate("Error unint taules per columnes"));		
										$('#dialog_error_upload').modal('show');
									}
									else if (!busy){
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
									}
								}
							});
						};
						
						pollInterval = setInterval(function(){
							pollFiltre();
						},pollTime);
						
					})();
				}
				else {
					jQuery('#info_uploadFile').hide();		
					busy=false;
				}
			
				var data = {
					uid: Cookies.get('uid'),
					urlSIG: paramUrl.spatialJoin,
					tipusSIG: "spatialJoin",
					mapBusinessId: url('?businessid'),
					businessId1: businessId1[0],
					businessId2: businessId2[0],
					nom:$('#input-spatial-join-name').val(),
					listColumns1: listCols1,
					listColumns2:listCols2,
					markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
					lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
					polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
					tmpFilePath:tmpFile
				};
				callActions(data);
			});
		}
	});
}

function openUnionModal(){
	var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Cap de les capes carregades permet aquesta operació')+
	"<strong>  <span class='fa fa-warning sign'></span></div>";
	jQuery('.modal').modal('hide');
	
	$('#dialog_union #input-join-name').val('');
	jQuery('#dialog_union').modal('show');
	
	$('#dataField_spatial_capa1').empty();
	$('#dataField_spatial_capa2').empty();

	$('#list_spatial_join_fields').html('');
	$('#list_spatial_join_fields2').html('');
	
	var layers = [];
	jQuery.each( controlCapes._layers, function( key, value ) {
		var layerOptions = this.layer.options;
		var tipusLayer = "";
		if(this.layer.options.tipus){tipusLayer = this.layer.options.tipus;}
		if(tipusLayer == t_visualitzacio ||  tipusLayer == t_vis_wms ){layers.push(this);}
	});
		
	if(layers.length ==0){
		$('#warning-union').html(warninMSG);
		$('#list-layers-union1').attr("style","display:none;");
		$('#list-fields-union2').attr("style","display:none;");
		$('#unionBtn').attr("disabled", true);
		return;
	}
	else {
		$('#warning-union').html('');	
		$('#list-layers-union1').attr("style","display:block;");
		$('#list-fields-union2').attr("style","display:block;");
		$('#unionBtn').removeAttr("disabled");
	}
	layers = {layers: layers};
	
	var source = jQuery("#tematic-union-layers1").html();
	var template = Handlebars.compile(source);
	var html = template(layers);
	$('#dataField_union_capa1').html('<option value="null">Escull la capa</option>');
	var htmlCapa1=$('#dataField_union_capa1').html();		
	$('#dataField_union_capa1').html(htmlCapa1 + html);
	
	var source2 = jQuery("#tematic-union-layers2").html();
	var template = Handlebars.compile(source2);
	var html2 = template(layers);
	$('#dataField_union_capa2').html('<option value="null">Escull la capa</option>');
	var htmlCapa2=$('#dataField_union_capa2').html();
	$('#dataField_union_capa2').html(htmlCapa2 + html);
	
	jQuery('#dialog_union #dataField_union_capa1').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_union_capa1').empty();		
		}
		else {
			var geomType1="",geomType2="";	
			var nomCapa="Unió de capes: ";
			if ($('#dataField_union_capa1 option:selected').text()!="Escull la capa"){
				var props =$('#dataField_union_capa1 option:selected').val();
				props =  props.split('___');
				var businessId = props[0];
				geomType1=props[1];
				nomCapa += $('#dataField_union_capa1 option:selected').text()+",";
			}
			if ($('#dataField_union_capa2 option:selected').text()!="Escull la capa"){
				var props =$('#dataField_union_capa2 option:selected').val();
				props =  props.split('___');
				var businessId = props[0];
				geomType2=props[1];
				nomCapa += $('#dataField_union_capa2 option:selected').text()+",";
			}
			if (geomType1!="" && geomType2!="" && geomType1!=geomType2){
				$('#dataField_union_capa1').val('null');
				$('#dataField_union_capa2').val('null');
				$('#dialog_union #input-join-name').val('');
				alert("Les capes han de ser del mateix tipus");
				
			}
			else $('#dialog_union #input-join-name').val(nomCapa);
		}
	});
	
	jQuery('#dialog_union #dataField_union_capa2').on('change',function(event){
		if (event.target.value=="null"){
			$('#dataField_union_capa2').empty();		
		}
		else {
			var geomType1="",geomType2="";	
			var nomCapa="Unió de capes: ";
			if ($('#dataField_union_capa1 option:selected').text()!="Escull la capa"){
				var props =$('#dataField_union_capa1 option:selected').val();
				props =  props.split('___');
				var businessId = props[0];
				geomType1=props[1];
				nomCapa += $('#dataField_union_capa1 option:selected').text()+",";
			}
			if ($('#dataField_union_capa2 option:selected').text()!="Escull la capa"){
				var props =$('#dataField_union_capa2 option:selected').val();
				props =  props.split('___');
				var businessId = props[0];
				geomType2=props[1];
				nomCapa += $('#dataField_union_capa2 option:selected').text()+",";
			}
			if (geomType1!="" && geomType2!="" && geomType1!=geomType2){				
				$('#dataField_union_capa1').val('null');
				$('#dataField_union_capa2').val('null');
				$('#dialog_union #input-join-name').val('');
				alert("Les capes han de ser del mateix tipus");
			}
			else $('#dialog_union #input-join-name').val(nomCapa);
		}
	});
	
	jQuery('#unionBtn').on('click',function(event){
		event.stopImmediatePropagation();
		 if(busy){
			 	jQuery('#dialog_union').hide();
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està executant una operació. Si us plau, espereu que aquesta acabi."));
				$('#dialog_info_upload').modal('show');
		}else{
			busy=true;
		 	
			var businessId1_props=$('#dataField_union_capa1').val();
			var businessId1=businessId1_props.split('___');
			
			var businessId2_props=$('#dataField_union_capa2').val();
			var businessId2=businessId2_props.split('___');
			
			var data1 = {
					uid: Cookies.get('uid'),
					businessId1: businessId1[0],
					businessId2: businessId2[0]
			}
			crearFitxerPolling(data1).then(function(results) {
				var tmpFile="";
				if (results.status=="OK"){
					tmpFile = results.tmpFilePath;
					//Definim interval de polling en funcio de la mida del fitxer
					var pollTime =3000;
					//Fem polling
					(function(){							
						pollFiltre = function(){
							$.ajax({
								url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
								dataType: 'json',
								type: 'get',
								success: function(data){
									jQuery('#dialog_union').hide();
									jQuery('#info_uploadFile').show();
									if(data.status.indexOf("ABANS")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Calculant operació')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Creant geometries')+'</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'
										);									
										
									}else if(data.status.indexOf("DESPRES")!=-1 && busy){
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Creant geometries')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step3" class="status_uncheck" lang="ca">3. '+window.lang.translate('Processant la resposta')+'</div>'	
										);									
									}else if(data.status.indexOf("OK")!=-1 && busy){
										clearInterval(pollInterval);
										
										jQuery("#div_uploading_txt").html("");
										jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Calculant operació')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Creant geometries')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step3" class="status_current" lang="ca">3. '+window.lang.translate('Processant la resposta')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'	
										);									
										jQuery('#dialog_union').modal('hide');
										if (data.midaFitxer==0){  
											jQuery('#info_uploadFile').hide();		
											busy=false;
											$('#dialog_error_upload_txt').html("");					
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
											$('#dialog_error_upload').modal('show');
										}
										else {
											var data2 = {
												uid: Cookies.get('uid'),
												mapBusinessId: url('?businessid'),
												serverName:data.serverName,
												path:data.path,
												tmpFilePath:data.tmpFilePath,
												midaFitxer:data.midaFitxer,
												sourceExtension:'geojson',
												markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
												lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
												polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol)),
												propertiesList: data.propertiesList,
												geomType: data.geomType
											}
											doUploadFile(data2).then(function(results){
												if (results.status="OK") {
													addDropFileToMap(results);
													 $('#dialog_spatial_join').modal('hide');
													 jQuery('#info_uploadFile').hide();
													 busy=false;
												}
												else {
													jQuery('#info_uploadFile').hide();		
													busy=false;
													$('#dialog_error_upload_txt').html("");					
													$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l\'operació"));					
													$('#dialog_error_upload').modal('show');
												}
											});
										}
									}else if(data.status.indexOf("ERROR")!=-1 && busy){
										busy = false;
										
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
										
										$('#dialog_error_upload_txt').html("");											
										$('#dialog_error_upload_txt').html(window.lang.translate("Error unint taules per columnes"));		
										$('#dialog_error_upload').modal('show');
									}
									else if (!busy){
										clearInterval(pollInterval);
										jQuery('#info_uploadFile').hide();
									}
								}
							});
						};
						
						pollInterval = setInterval(function(){
							pollFiltre();
						},pollTime);
						
					})();
				}
				else {
					jQuery('#info_uploadFile').hide();		
					busy=false;
				}
			
				var data = {
					uid: Cookies.get('uid'),
					urlSIG: paramUrl.unionLayers,
					tipusSIG: "unionLayers",
					mapBusinessId: url('?businessid'),
					businessId1: businessId1[0],
					businessId2: businessId2[0],
					nom:$('#dialog_union #input-join-name').val(),					
					tmpFilePath:tmpFile
				};
				callActions(data);
			});
		}
	});
}<file_sep>/geocatweb/js/instamaps.visor.geolocal.js
/**
 * 
 * require: WidgetsGeolocal, 
 */
;(function(global, $){

	var VisorGeolocal = function(options){
		return new VisorGeolocal.init(options);
	};
	
	var visorOptions = {
		controls: {},
	};
	
	VisorGeolocal.prototype = {
			
		addWidgetsControl: function(){
			var self = this,
			ctr_widgets,
			visor = self.visor,
			_map = visor.map;
			
			ctr_widgets = L.control.widgets({
				title: window.lang.translate('Ginys')
			});
			ctr_widgets.addTo(_map);
			
			self.controls.widgetsControl = ctr_widgets;
			
			return self;
		},
		
		resizeMap: function(){
			var self = this,
			visor = self.visor,
			map = visor.visor,
			optionsBtn = {},
			factorH = 0,
			factorW = 0,
			_window = $( window ),
			widthW = _window.width(),
			heightW = _window.height(),
			_mapDiv = $('#map'),
			cl = jQuery('.bt_llista span').attr('class');
			if(self.embed){//Pel cas visor, embeded
				factorH = 0;
			}else{
				factorH = $('.navbar').css('height').replace(/[^-\d\.]/g, '');
			}
			_mapDiv.css('top', factorH + 'px');
			_mapDiv.height(heightW - factorH);
			_mapDiv.width(widthW - factorW);
			
			if(widthW<500 || heightW<=350){
				optionsBtn = {
					widgets: false
				};
			}else{
				optionsBtn = {
					widgets: true
				};
			}
			self._redrawButtons(optionsBtn);
			return self;
		},
		
		_redrawButtons: function(options){
			var self = this;
			
			if(options.widgets && self.controls.widgetsControl){
				self.controls.widgetsControl.showBtn();
			}else if(self.controls.widgetsControl){
				self.controls.widgetsControl.hideBtn();
			}
		},
		
		_loadPublicMap: function(_mapConfig){
			var self = this,
			visor = self.visor,
			map = visor.map,
			nomUser = _mapConfig.entitatUid.split("@"),
			nomEntitat = _mapConfig.nomEntitat,
			infoHtml = '';
			
			//TODO  ver si podemos usar un objeto usuario para almacenar este tipo de cosas.
			//cambiamos la cookie del perfil
			Cookies.set('perfil', 'geolocal');
			checkUserLogin();
			
			//cambiamos la cuenta de google
			_gaq.push(['_setAccount', 'UA-46332195-6']);
			
			//cambiamos el info
			infoHtml += '<div style="color:#ffffff">';
			if (nomEntitat!=undefined) infoHtml +='<p>'+nomEntitat+'</p>';
			infoHtml += '</div>';
			
			//destruir el creado en el visor
			$('#infoMap').popover('destroy');
			$('#infoMap').popover({
				placement : 'bottom',
				html: true,
				content: infoHtml
			});
			$('#infoMap').on('show.bs.popover', function () {
				$(this).attr('data-original-title', window.lang.translate($(this).data('lang-title')));		
			});
			
			$('.brand-txt').hide();//#496: Traiem "Instamaps" dels visors de Geolocal
			$('.img-circle2-icon').hide();

			if (_mapConfig.options.barColor){
				$('#navbar-visor').css('background-color', _mapConfig.options.barColor);
			}

			if (_mapConfig.options.textColor){
				$('#navbar-visor').css('color', _mapConfig.options.textColor).css('border-color', '#ffffff');
				$('.navbar-brand').css('color', _mapConfig.options.textColor);
				$('#mapTitle').css('color', _mapConfig.options.textColor);
				$('#mapTitle h3').css('color', '#ffffff');
				$('.navbar-inverse .navbar-nav > li > a').css('color', _mapConfig.options.textColor);
				$('#menu_user > a > span').removeClass('green').css('color', _mapConfig.options.textColor);
				$('.navbar-form').css('border-color', 'transparent');
				$('.bt-sessio').css('border-color', '#ffffff');
			}

			if (_mapConfig.options.fontType){
				$('#navbar-visor').css('font-family', _mapConfig.options.fontType);
			}

			$('.escut').show();
			if (_mapConfig.logo){
				$('.escut img').prop('src', '/logos/'+_mapConfig.logo);
			}
			
			return self;
		},
		
		drawEmbed: function(){
			var self = this;
			
			self.widgetscontrol = true;
			
			return self;
		},
		
		draw: function(){
			var self = this,
			visor = self.visor,
			map = visor.map,
			_mapConfig = visor._mapConfig;
			
			$(window).resize(_.debounce(function(){
				self.resizeMap();
			},150));
			
			self._listenEvents();
			
			if(visor.embed){
				self.drawEmbed();
			}
			
			if(!visor.rtoolbar){
				if(!self.widgetscontrol){
					self.addWidgetsControl();
				}
			}
			
			self._addLogosGeolocal();
			
			self._loadPublicMap(_mapConfig);
			
			return self;
		},
		
		_addLogosGeolocal: function(){
			var self = this,
			visor = self.visor,
			map = visor.map;
			
			visor.addLogoInstamap();
	   		
	   		$.get("templates/logosGeolocal.html",function(data){
	   			visor.controls.controlLogos.addLogoHtml(data);
			});
			
	   		return self;
		},
		
		_showwigetsEvent: function(){
			$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widgets']});
		},
		
		_listenEvents: function(){
			var self = this,
			visor = self.visor,
			_map = visor.map;
			if(_map){
				_map.on('showwigets', self._showwigetsEvent, self);
			}
		}
		
	};
	
	VisorGeolocal.init = function(options){
		var self = this;
		self = $.extend(self, visorOptions, options);
	};
	
	VisorGeolocal.init.prototype = VisorGeolocal.prototype;
	
	global.VisorGeolocal = VisorGeolocal;
	
}(window, jQuery));<file_sep>/geocatweb/js/leaflet/L.IM_WidgetsControl.js
/**
 * 
 */
L.Control.Widgets = L.Control.extend({
	options: {
		position: 'topright',
		id: 'dv_bt_widgets',
		className: 'leaflet-bar btn btn-default btn-sm bt_widgets',
		title: 'Ginys',
		langTitle: 'Ginys',
		html: '<span class="fa fa-cogs widgets"></span>',
		modalContainer: '#mapa_modals',
		tooltip: 'left'
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			stop = L.DomEvent.stopPropagation,
			container = L.DomUtil.create('div', options.className);
		
		container.id = options.id;
		container.innerHTML = options.html;
		container.title = options.title;
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', self._showWidgets, self);
		
		self.widgets = {};
		self.subscriptions();
		self._addModalWidgets();
		
		//iniciar la lista de municipios
		$.publish('mapMoveend', map);
		
		return container;
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
	
	onRemove: function (map) {
		map.off('mapprint', this._map, this);
		
		//remove dialog
		$('.dialgo_widgets').remove();
		
	},
	
	_showWidgets: function(e){
		var _map = this._map;
		
		$('.dialgo_widgets').modal('show');
		//TODO crear los eventos
		_map.fire('showwigets'); //to track ga events
		//TODO crear el modulo de captura
		//capturaPantalla(CAPTURA_INFORME);  //geocat.mapa.canvas
	}, 
	
	_addModalWidgets: function(){
		
		
    	var that = this;
    	$.get("templates/modalWidgets.html",function(data){
			//TODO ver como pasar el modal container
    		$(that.options.modalContainer).append(data);
    		var modalbody = $('.dialgo_widgets div.widgets-list');
    		var selectdiv = $('.dialgo_widgets div.selectMunicipi');
    		var listdiv = $('.dialgo_widgets div.listMunicipis');			
    		that._addSelectMunicipis(selectdiv);
    		that._addListViewMunicipis(listdiv);
    		that._addIdescatWidget(modalbody);
    		that._addRPUCWidget(modalbody);
    		that._addCartotecaWidget(modalbody);
    		that._addMeteoWidget(modalbody);
        	that._addCadastreWidget(modalbody);
        	that._addInfoParcelaWidget(modalbody);
			that._addMascaraWidget(selectdiv);
        });
    },
    
    _addSelectMunicipis: function(container){
    	var select = SelectMunicipis.createSelect();
    	container.append(select);
    	$(select).addClass("selectpicker").selectpicker({liveSearch:true});
		
    },
    
    _addListViewMunicipis: function(container){
    	var _map = this._map;
    	ListViewMunicipis.createList(container);
    	_map.on('moveend',function(e){
      		$.publish('mapMoveend', this);
      	});
    },
    
	
    _addMeteoWidget: function(container){
    	this.widgets.meteo = WidgetMeteo.getWidget();
    	WidgetMeteo.drawButton(container);
    },
    
    _addIdescatWidget: function(container){
    	this.widgets.idescat = WidgetIdescat.getWidget();
    	WidgetIdescat.drawButton(container);
    	WidgetIdescat.activate();
    	$('.widgets-list .widget-idescat').addClass("widget-button-active");
    },
    
    _addCadastreWidget: function(container){
    	this.widgets.cadastre = WidgetCadastre.getWidget();
    	WidgetCadastre.drawButton(container);
    },
    
    _addRPUCWidget: function(container){
    	this.widgets.rpuc = WidgetRPUC.getWidget();
    	WidgetRPUC.drawButton(container);
    },
    
    _addInfoParcelaWidget: function(container){
    	this.widgets.rpuc = WidgetInfoparcela.getWidget();
    	WidgetInfoparcela.drawButton(container);
    },
	
	
	 _addMascaraWidget: function(container){
    	WidgetMascara.getWidget();
    	WidgetMascara.drawButton(container);
    },
	
	
	
	
    
    _addCartotecaWidget: function(container){
    	this.widgets.cartoteca = WidgetCartoteca.getWidget();
    	WidgetCartoteca.drawButton(container);
    },
    
    deactivateWidgets: function(){
    	var that = this;
    	for(var widget in that.widgets){
    		that.widgets[widget].deactivate();
    	}
    	$('.widgets-list .widget-button').removeClass("widget-button-active");
    },
    
    getWidgets: function(){
    	var that = this;
    	return that.widgets;
    },
    
    subscriptions: function() {
    	var that = this,
    		_map = this._map;
    	
    	$.subscribe('changeSelectMunicipis',function(e, data){
			
		
			
    		that.activeMunicipi = data;
    		//zoom al municipio
    		if(data && _map){
    			var bbox = data.bbox.split(",");
    			var southWest = L.latLng(bbox[1], bbox[0]),
    		    northEast = L.latLng(bbox[3], bbox[2]),
    		    bounds = L.latLngBounds(southWest, northEast);
    			_map.fitBounds(bounds)
    		}
    	});
    	
    	$.subscribe('widgetActivated',function(e, data){
    		that.deactivateWidgets();
    		var classWidget = $(data.target).attr('class').split(" ")[1];
    		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widgets', classWidget, 1]});
    		$(data.target).addClass("widget-button-active");
    		data.widget.activate();
    		if(that.activeMunicipi){
				console.info(that.activeMunicipi);
    			data.widget.draw(that.activeMunicipi);
    		}
    	});
    	
    }
});

L.control.widgets = function(options){
	return new L.Control.Widgets(options);
};<file_sep>/geocatweb/js/geocat.mapa.draw.js
/**
 * Funcionalitats d'afegir features al mapa (punts, línies poligons) i
 * edició de les seves característiques: estils, coordenades, 
 * dades, capa on pertanyen...
 * */

var drawControl;
var featureActive,crt_Editing,crt_Remove;
var defaultPunt;
var canvas_linia={"id":"cv_linia","strokeStyle":"#FFC500","lineWidth":"3","tipus":"linia","opacity":"100"};
var canvas_pol={"id":"cv_pol","strokeStyle":"#FFC500","opacity":"0.5","fillStyle":"rgba(255, 197, 0,0.5)","lineWidth":"3","tipus":"pol"};
var canvas_obj_l,cv_ctx_l;
var canvas_obj_p,cv_ctx_p;
var objEdicio={'esticEnEdicio':false,'obroModalFrom':'creaCapa','featureID':null,'esticSobre':false,'edicioPopup':'textFeature'};

var drawnItems = new L.FeatureGroup();

function changeRandomDefaults(){

	var randomColorInit=getRamdomColorFromArray();
	canvas_linia.strokeStyle=randomColorInit;
	canvas_pol.strokeStyle=randomColorInit;
	canvas_pol.fillStyle="rgba("+hexToRgb(randomColorInit).r+", "+hexToRgb(randomColorInit).g+", "+hexToRgb(randomColorInit).b+",0.5)";
	var colorText=getClassFromColor(randomColorInit)	
	default_marker_style.markerColor = colorText,
	default_line_style.color=randomColorInit;
	default_area_style.color=randomColorInit;
	default_area_style.borderColor=randomColorInit;
	default_area_style.fillColor="rgb("+hexToRgb(randomColorInit).r+", "+hexToRgb(randomColorInit).g+", "+hexToRgb(randomColorInit).b+")";	
	estilP.colorGlif="#000000";
	estilP.iconFons="awesome-marker-web awesome-marker-icon-"+colorText;

}

function addRandomStyleInit(){

	jQuery('#div_punt').removeClass();
	jQuery('#div_punt').addClass('awesome-marker-web awesome-marker-icon-'+default_marker_style.markerColor+' fa fa-');	
	jQuery('#div_punt').css({"font-size":"14px", "width": "28px", "height": "42px", "color": "rgb(0, 0, 0)", "background-color": "transparent"});	
	changeDefaultLineStyle(canvas_linia);
	changeDefaultPointStyle(estilP);
	changeDefaultAreaStyle(canvas_pol);

}

function addDialegEstilsDraw() {
	
	changeRandomDefaults();
	addHtmlInterficieDraw();
	
	jQuery('#div_mes_punts').on("click", function(e) {	
		obrirMenuModal('#dialog_estils_punts','toggle',from_creaCapa);
	});

	jQuery('#div_mes_linies').on("click", function(e) {			
		obrirMenuModal('#dialog_estils_linies','toggle',from_creaCapa);
	});
	
	jQuery('#div_mes_arees').on("click", function(e) {	
		obrirMenuModal('#dialog_estils_arees','toggle',from_creaCapa);
	});

	

}

/**
 * Funcio que obre el menu dialeg d'estils per punts, linies i poligons
 * */
function obrirMenuModal(_menuClass,estat,_from){
	objEdicio.obroModalFrom=_from;
	//console.debug(_menuClass+","+estat+","+_from);
	//Udate dialog estils a mostrar
	if(_from == from_creaCapa){
		
		if(_menuClass.indexOf("arees")!=-1){
			var defPol = document.getElementById("cv_pol").getContext("2d");
			var fillColor = defPol.fillStyle;
			if(fillColor.indexOf("rgb")!=-1) fillColor = rgb2hex(defPol.fillStyle);
			var icon = {color: defPol.strokeStyle,
						fillOpacity : getRgbAlpha(defPol.fillStyle),
						fillColor: fillColor,//rgb2hex(defPol.fillStyle),
						weight: defPol.lineWidth,
						tipus: t_polygon
					};
			updateDialogStyleSelected(icon);
			
		}else if(_menuClass.indexOf("linies")!=-1){
			var defLine = document.getElementById("cv_linia").getContext("2d");
			var icon = {color: defLine.strokeStyle,
						weight: defLine.lineWidth,
						tipus: t_polyline
					};
			updateDialogStyleSelected(icon);			
		
		}else{//es t_marker

			 var styleProps = $("#div_punt").css(["width","height","color","background-color","font-size"]);
			 var punt_class = $("#div_punt").attr("class");
			 
			 console.info(punt_class);
			 var lclass = punt_class.split(" ");
			 //console.debug(punt_class);
			 //Si es punt inicial per defecte
			 if(punt_class == "dibuix_punt"){
					var icon = {icon: "",//glyph
						 	iconColor: "#000000",
						 	isCanvas: false,
						 	className: "awesome-marker",
						 	markerColor: 'orange',
						 	tipus: t_marker
				};
				
				console.info(icon);
				updateDialogStyleSelected(icon);				 
			 }else if (punt_class.indexOf("punt_r")!=-1){
				 	

				 	//Es punt sense glyphon, CANVAS
				 	if(!lclass[3] || lclass[3] === "fa-"){
						var icon = {icon: "",//glyph
								 	iconColor: rgb2hex(styleProps.color),
								 	fillColor: rgb2hex(styleProps["background-color"]),
								 	radius: getRadiusFromMida(styleProps.width),
								 	isCanvas: true,
								 	tipus: t_marker
						};
						updateDialogStyleSelected(icon);
						
				 	}else{//Es punt amb glyphon
					 	var iconGlyph = "";
					 	if(lclass[3]) iconGlyph = lclass[3];
					 	
					 	var font = " font"+styleProps["font-size"].substring(0,2);
						var icon = {icon: iconGlyph.substring(3) + font,//glyph
								 	iconColor: rgb2hex(styleProps.color),
								 	divColor: rgb2hex(styleProps["background-color"]),
								 	isCanvas: false,
								 	markerColor: punt_class,
								 	tipus: t_marker
						};
						updateDialogStyleSelected(icon);					 	
				 	}
			 }else{//Pintxo
				var markerColor = (lclass[1].split("-"))[3];
			 	var iconGlyph = "";
			 	if(lclass[3]) iconGlyph = lclass[3];
			 	
				var icon = {icon: iconGlyph.substring(3),//glyph
						 	iconColor: rgb2hex(styleProps.color),
						 	isCanvas: false,
						 	className: "awesome-marker",
						 	markerColor: markerColor,
						 	tipus: t_marker
				};
				updateDialogStyleSelected(icon);
			 }
		}
	}	
	
    if (jQuery.isPlainObject( _from )){
    	if (_from.from == tem_clasic){
    		//TODO
    		/*
    		jQuery('.fila-awesome-markers').hide();
            activaPuntZ();
            jQuery('#dialog_tematic_rangs').modal('hide');
            jQuery(_menuClass).modal(estat);
            */
    	}else{
    		

    		
    		var layers_from = controlCapes._layers[_from.leafletid].layer.getLayers();
        	if( layers_from.length > num_max_pintxos || _from.tipus == t_url_file){
                jQuery('.fila-awesome-markers').hide();
                jQuery('#filaM').hide();
                estilP.iconGlif = "fa fa-";
                activaPuntZ();
        	}else{
        		jQuery('#filaM').show();
                jQuery('.fila-awesome-markers').show();
               
        	}
        	jQuery('.modal').modal('hide');     
            jQuery(_menuClass).modal(estat);
    	}
    }else{
    	jQuery('.fila-awesome-markers').show();
    	jQuery('#filaM').show();
    	jQuery('.modal').modal('hide');     
        jQuery(_menuClass).modal(estat);
    }
    
}

function initCanvas(){
	addGeometryInitP(document.getElementById(canvas_pol.id),"inicial");
	addGeometryInitP(document.getElementById(canvas_pol.id+"0"));
	addGeometryInitL(document.getElementById(canvas_linia.id),"inicial");	
	addGeometryInitL(document.getElementById(canvas_linia.id+"0"));
	
    $('#colorpalette_pf').colorPalette().on('selectColor', function(e) {   	
    	$('.fill_color_pol').css('background-color',e.color);
        $('.fill_color_pol').css('color',e.color);
        canvas_pol.opacity=jQuery('#cmb_trans').val();//Forcem el valor de opacity pq en Chrome no anava bé
        canvas_pol.fillStyle="rgba("+hexToRgb(e.color).r+", "+hexToRgb(e.color).g+", "+hexToRgb(e.color).b+","+jQuery('#cmb_trans').val()+")";
    	addGeometryInitP(document.getElementById("cv_pol0"));
    });	
    
    $('#colorpalette_pl').colorPalette().on('selectColor', function(e) {    	
    	var color=rgb2hex($('.fill_color_pol').css('background-color'));
    	$('.border_color_pol').css('border-color',e.color);
    	canvas_pol.opacity=jQuery('#cmb_trans').val();//Forcem el valor de opacity pq en Chrome no anava bé
    	canvas_pol.strokeStyle=e.color;
    	canvas_pol.fillStyle="rgba("+hexToRgb(color).r+", "+hexToRgb(color).g+", "+hexToRgb(color).b+","+jQuery('#cmb_trans').val()+")";
    	addGeometryInitP(document.getElementById("cv_pol0"));  
    });
	
	$('#colorpalette_ll').colorPalette().on('selectColor', function(e) {   	
    $('.border_color_linia').css('background-color',e.color);
		canvas_linia.strokeStyle=e.color;
		addGeometryInitL(document.getElementById("cv_linia0"));
	});
 
	$('#colorpalette_icon').colorPalette().on('selectColor', function(e) {  
		 $('.fill_color_icon').css('background-color',e.color);
			estilP.colorGlif=e.color;			
			jQuery('.bs-glyphicons li').css('color',estilP.colorGlif);
			if(e.color=="#FFFFFF"){
				jQuery('.bs-glyphicons li').css('background-color','#aaaaaa');	
			}else{
				jQuery('.bs-glyphicons li').css('background-color','#FFFFFF');	
			}
			jQuery('#div_punt0').css('color',estilP.colorGlif);
			jQuery(this).addClass("estil_selected");
	});
	


	$('#colorpalette_punt').colorPalette().on('selectColor', function(e) {  
		 $('.fill_color_punt').css('background-color',e.color);			
		 if(!jQuery('#div_puntZ').hasClass("estil_selected")){
				activaPuntZ();				
		 }else{		 
			estilP.divColor=e.color;				
			jQuery('#div_punt0').css('background-color',estilP.divColor);
		 }
		    jQuery('#div_punt9').css('background-color',e.color);		
		});
	
	var options = {
			colors:[['#ffc500', '#ff7f0b', '#ff4b3a', '#ae59b9', '#00afb5', '#7cbd00', '#90a6a9', '#ebf0f1']]
	};
	
	$('#colorpalette_marker').colorPalette(options).on('selectColor', function(e) {  
		 $('.fill_color_marker').css('background-color',e.color);	
		 activaPuntM(e.color);
	});	

	jQuery("#cmb_trans").on('change', function(e) { 
    	var color=rgb2hex($('.fill_color_pol').css('background-color'));
    	canvas_pol.opacity=jQuery(this).val();
    	canvas_pol.fillStyle="rgba("+hexToRgb(color).r+", "+hexToRgb(color).g+", "+hexToRgb(color).b+","+jQuery('#cmb_trans').val()+")";
    	addGeometryInitP(document.getElementById("cv_pol0"));
    });
    
    jQuery("#cmb_gruix").on('change', function(e) { 
    	canvas_pol.lineWidth=jQuery(this).val();
    	var color=rgb2hex($('.fill_color_pol').css('background-color'));
    	canvas_pol.opacity=jQuery('#cmb_trans').val();
    	canvas_pol.fillStyle="rgba("+hexToRgb(color).r+", "+hexToRgb(color).g+", "+hexToRgb(color).b+","+jQuery('#cmb_trans').val()+")";
    	addGeometryInitP(document.getElementById("cv_pol0"));
    });
    
    jQuery("#cmb_gruix_l").on('change', function(e) { 
    	canvas_linia.lineWidth=jQuery(this).val();
    	var color=rgb2hex($('.fill_color_pol').css('background-color'));
    	canvas_pol.opacity=jQuery('#cmb_trans').val();
    	canvas_pol.fillStyle="rgba("+hexToRgb(color).r+", "+hexToRgb(color).g+", "+hexToRgb(color).b+","+jQuery('#cmb_trans').val()+")";
    	addGeometryInitL(document.getElementById("cv_linia0"));
    });
}

function addGeometryInitL(canvas,inicial){
	var	cv_ctx_l=canvas.getContext("2d");
	cv_ctx_l.clearRect(0, 0, canvas.width, canvas.height);
	cv_ctx_l.moveTo(0.7,39.42);
	cv_ctx_l.lineTo(2.05,34.43);
	cv_ctx_l.lineTo(3.62,31.00);
	cv_ctx_l.lineTo(5.95,27.72);
	cv_ctx_l.lineTo(8.17,25.61);
	cv_ctx_l.lineTo(10.72,23.84);
	cv_ctx_l.lineTo(13.059,22.73);
	cv_ctx_l.lineTo(15.32,22.28);
	cv_ctx_l.lineTo(17.76,22.08);
	cv_ctx_l.lineTo(20.30,21.47);
	cv_ctx_l.lineTo(23.28,20.51);
	cv_ctx_l.lineTo(25.88,18.90);
	cv_ctx_l.lineTo(28.265,16.83);
	cv_ctx_l.lineTo(29.9,14.71);
	cv_ctx_l.lineTo(31.89,12.195);
	cv_ctx_l.lineTo(33.62,9.42);
	cv_ctx_l.lineTo(34.81,6.64);
	cv_ctx_l.lineTo(35.46,3.92);
	cv_ctx_l.lineTo(35.52,0.54);
	cv_ctx_l.strokeStyle=canvas_linia.strokeStyle;
	cv_ctx_l.lineWidth=canvas_linia.lineWidth;
	var idLinia = canvas.id;
	if ((inicial==null || inicial==undefined) && idLinia=='cv_linia0'){
		cv_ctx_l.shadowColor = '#999999';
		cv_ctx_l.shadowBlur = 20;
		cv_ctx_l.shadowOffsetX = 15;
		cv_ctx_l.shadowOffsetY = 15;
		cv_ctx_l.stroke(); 	
		cv_ctx_l.shadowOffsetX = -15;
		cv_ctx_l.stroke(); 	
		cv_ctx_l.shadowOffsetY = -15;
		cv_ctx_l.stroke(); 
		cv_ctx_l.shadowOffsetX = 15;
	}
	cv_ctx_l.stroke(); 	
}

function addGeometryInitP(canvas,inicial){
	var	cv_ctx_p=canvas.getContext("2d");
	cv_ctx_p.clearRect(0, 0, canvas.width, canvas.height);
	cv_ctx_p.moveTo(5.13,15.82);
	cv_ctx_p.lineTo(25.49,5.13);
	cv_ctx_p.lineTo(37.08,13.16);
	cv_ctx_p.lineTo(20.66,38.01);
	cv_ctx_p.lineTo(2.06,33.67);
	cv_ctx_p.closePath();
	cv_ctx_p.strokeStyle=canvas_pol.strokeStyle;
//	console.debug(canvas_pol);
	if(canvas_pol.fillStyle.indexOf("rgb")!= -1) cv_ctx_p.fillStyle = canvas_pol.fillStyle;
	else cv_ctx_p.fillStyle=hexToRgba(canvas_pol.fillStyle,canvas_pol.opacity );
	
//	cv_ctx_p.fillStyle=canvas_pol.fillStyle;
	cv_ctx_p.lineWidth=canvas_pol.lineWidth;
//	cv_ctx_p.opacity=canvas_pol.opacity;
	var idPol = canvas.id;
	if ((inicial==null || inicial==undefined) && idPol=='cv_pol0'){
		cv_ctx_p.shadowColor = '#999999';
		cv_ctx_p.shadowBlur = 20;
		cv_ctx_p.shadowOffsetX = 15;
		cv_ctx_p.shadowOffsetY = 18;	
		cv_ctx_p.fill();
		cv_ctx_p.stroke(); 
		cv_ctx_p.shadowOffsetX = -15;
		cv_ctx_p.fill();
		cv_ctx_p.stroke(); 	
		cv_ctx_p.shadowOffsetY = -18;
		cv_ctx_p.fill();
		cv_ctx_p.stroke(); 
		cv_ctx_p.shadowOffsetX = 15;
	}
		cv_ctx_p.fill();
		cv_ctx_p.stroke(); 
}

//Funcio inicialitzar i afegir drawControl
function addDrawToolbar() {
	initCanvas();
	
	var ptbl = L.Icon.extend({
		options : {
			shadowUrl : null,
			iconAnchor : new L.Point(14, 40),
			iconSize : new L.Point(28, 40)
		}
	});

	defaultPunt= L.AwesomeMarkers.icon(default_marker_style);
	map.addLayer(drawnItems);
	
	var options = {
		draw : false,
		polyline : {
			guidelineDistance : 2,
			repeatMode:false,
			shapeOptions : {
				color : '#FFC400',
				weight : 3,
				opacity : 1,
				tipus: t_polyline
			},
			guideLayers: guideLayers
		},
		polygon : {
			allowIntersection : true, // Restricts shapes
			repeatMode:false,
			guidelineDistance : 2,			
			shapeOptions : {
				color : '#FFC400',
				fillColor: '#FFC400',
				weight : 3,
				fillOpacity : 0.5,
				tipus: t_polygon
			},
			snapDistance: 10,
			guideLayers: guideLayers
		},
		marker:{repeatMode:false,
			icon:L.icon({iconUrl:'/geocatweb/css/images/blank.gif'}),		
			snapDistance: 10,
			snapVertices: false,
			guideLayers: guideLayers
		},
		edit :{
		    featureGroup: drawnItems, //REQUIRED!!
		    remove: false,
		    edit:false
		    }
	};
	drawControl = new L.Control.Draw(options);
	
	map.addControl(drawControl);
	addDrawTooltips();
	addRandomStyleInit();
}

//function showEditText(accio){
//	jQuery('.search-edit').animate({
//		height :accio
//	});
//}

function activaEdicioUsuari() {
	jQuery('#div_punt').on('click', function() {
		if(featureActive){featureActive.disable();}
		featureActive = new L.Draw.Marker(map, drawControl.options.marker);		 
		featureActive.enable();
	});

	jQuery('#div_linia').on('click', function() {
		if(featureActive){featureActive.disable();}
		featureActive = new L.Draw.Polyline(map, drawControl.options.polyline);
		featureActive.enable();
	});

	jQuery('#div_area').on('click', function() {
		if(featureActive){featureActive.disable();}
		featureActive = new L.Draw.Polygon(map, drawControl.options.polygon);
		featureActive.enable();
	});

	map.on('draw:drawstart',function(e){
		map.off('click',L.TileLayer.BetterWMS.getFeatureInfo);		
	});
	
	//Edicio de feature existent
	map.on('click',function(e){
		for(var i = 0;i < guideLayers.length; i++) {			
				
					if (guideLayers[i].snapediting!=undefined)  guideLayers[i].snapediting.disable();
					if (guideLayers[i].editing!=undefined) guideLayers[i].editing.disable();
				try{
					if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.disable();
				}catch(exc){
					
				}
		}
		
		if(objEdicio.esticEnEdicio){			
			try{
				updateFeatureMove(objEdicio.featureID, crt_Editing._featureGroup._leaflet_id, objEdicio.capaEdicioLeafletId);
			}catch(exc){
				
			}
			if(crt_Editing){
				try{
					crt_Editing.disable();
				}catch(exc){
					
				}
			}
//			updateFeatureMove(objEdicio.featureID, objEdicio.capaEdicioLeafletId);		
		}
		if(crt_Editing){
			try{
				crt_Editing.disable();
			}catch(exc){
				
			}
		}
	});
	
	//Controlem que si hi ha un click en un altre lloc del mapa l'edició de features es desactiva
	$('body').click(function(event) {		
		if(objEdicio.esticEnEdicio){
			 var target = $(event.target);
			 for(var i = 0;i < guideLayers.length; i++) {			
				 	
						if (guideLayers[i].snapediting!=undefined)  guideLayers[i].snapediting.disable();
						if (guideLayers[i].editing!=undefined) guideLayers[i].editing.disable();
					try{
						if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.disable();
				 	}catch(exc){
				 		
				 	}
			}
			 if(objEdicio.esticEnEdicio){			
					try{
						updateFeatureMove(objEdicio.featureID, crt_Editing._featureGroup._leaflet_id, objEdicio.capaEdicioLeafletId);
					}catch(exc){
						
					}
					if(crt_Editing){
						try{
							crt_Editing.disable();
						}catch(exc){
							
						}
					}
//					updateFeatureMove(objEdicio.featureID, objEdicio.capaEdicioLeafletId);		
				}
		
			if(crt_Editing){
				try{
					crt_Editing.disable();
				}catch(exc){
					
				}
			}
			target.click();
		}
	});
	
	map.on('preclick',function(e){
		if(crt_Editing){
			crt_Editing.disable();
		}
	});
	
	//Afegir features: point, lines and polygons
	map.on('draw:created', function(e) {
		var type = e.layerType, layer = e.layer;
		var totalFeature;
		var tipusCat,tipusCatDes;
		_gaq.push(['_trackEvent', 'mapa', tipus_user+'dibuixar geometria', type, 1]);
		//_kmq.push(['record', 'dibuixar geometria', {'from':'mapa', 'tipus user':tipus_user, 'type':type}]);
		 drawnItems.addLayer(layer);
		if (type === t_marker) {
			tipusCat=window.lang.translate('Títol Punt');
			tipusCatDes=window.lang.translate('Descripció Punt');
			var nomDefecteCapa = window.lang.translate('Capa Punt');
			
			//Mira si és icona
			if(!defaultPunt.options.isCanvas){
				 var divIcon = L.divIcon({ 
					  html: "<span style='color:blue;'>textToDisplay</span>"
					});
								
				
				layer=L.marker([layer.getLatLng().lat,layer.getLatLng().lng],
					{icon: defaultPunt,isCanvas:defaultPunt.options.isCanvas,
					 tipus: t_marker}).addTo(map);//.bindLabel('Look revealing label!', { noHide: true , direction: 'center',className: "my-label", offset: [0, 0]}).addTo(map);
			}else{
				//Si és cercle sense glifon
				layer= L.circleMarker([layer.getLatLng().lat,layer.getLatLng().lng],
						{ radius : defaultPunt.options.radius, 
						  isCanvas:defaultPunt.options.isCanvas,
						  fillColor : defaultPunt.options.fillColor,
						  color :  defaultPunt.options.color,
						  weight :  defaultPunt.options.weight,
						  opacity :  defaultPunt.options.opacity,
						  fillOpacity : defaultPunt.options.fillOpacity,
						  tipus: t_marker}
						
				).addTo(map);//.bindLabel('Look revealing label!', { noHide: true, direction: 'center',className: "my-label", offset: [0, 0] }).addTo(map);
			}
			
			if(capaUsrActiva != null && capaUsrActiva.options.geometryType != t_marker){
				capaUsrActiva.removeEventListener('layeradd');
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+ index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_marker
				};				
				map.addLayer(capaUsrActiva);
				capaUsrActiva.on('layeradd',objecteUserAdded);
				
			}else if(capaUsrActiva == null){
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_marker
				};
				map.addLayer(capaUsrActiva);
				capaUsrActiva.on('layeradd',objecteUserAdded);
			}
			
			layer.properties={
					'capaNom':capaUsrActiva.options.nom,//TODO desactualitzat quan es canvii nom capa!
					'capaBusinessId':capaUsrActiva.options.businessId,
					'capaLeafletId': capaUsrActiva._leaflet_id,
					'tipusFeature':t_marker};	
			
			layer.properties.data={
					'nom':tipusCat+' '+capaUsrActiva.getLayers().length,
					'text':tipusCatDes+' '+capaUsrActiva.getLayers().length,
			};
			/*try{
				//Active snapping
				//layer.snapediting = new L.Handler.MarkerSnap(map, layer,{snapDistance:10});
				for(var i = 0;i < guideLayers.length; i++) {
				        // Add every already drawn layer to snap list
				        layer.snapediting.addGuideLayer(guideLayers[i]);
				        // Add the currently drawn layer to the snap list of the already drawn layers
				        guideLayers[i].snapediting.addGuideLayer(layer);
				        guideLayers[i].snapediting.disable();
				        if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable(); 
				 }
			}catch(exc){
				
			}*/
			
			  // Add to drawnItems
			 drawnItems.addLayer(layer);
			 // Add newly drawn feature to list of snappable features
			  guideLayers.push(layer);
		    
			capaUsrActiva.addLayer(layer);
			
		} else if (type === t_polyline) {
			tipusCat=window.lang.translate('Títol Línia');
			tipusCatDes=window.lang.translate('Descripció Línia');
			var nomDefecteCapa = window.lang.translate('Capa Línia');
			
			if(capaUsrActiva != null && capaUsrActiva.options.geometryType != t_polyline){
				capaUsrActiva.removeEventListener('layeradd');
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_polyline

				};
				map.addLayer(capaUsrActiva);
				capaUsrActiva.on('layeradd',objecteUserAdded);
			}else if(capaUsrActiva == null){
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_polyline
				};
				map.addLayer(capaUsrActiva);
				capaUsrActiva.on('layeradd',objecteUserAdded);
			}
			
			layer.properties={
					'capaNom':capaUsrActiva.options.nom,//TODO desactualitzat quan es canvii nom capa!
					'capaBusinessId':capaUsrActiva.options.businessId,
					'capaLeafletId': capaUsrActiva._leaflet_id,
					'tipusFeature':t_polyline,
					'mida': calculateDistance(layer.getLatLngs()) };	
			
			layer.properties.data={
					'nom':tipusCat+' '+capaUsrActiva.getLayers().length,
					'text':tipusCatDes+' '+capaUsrActiva.getLayers().length,
			};	
			//Activate snapping
			/*layer.snapediting = new L.Handler.PolylineSnap(map, layer,{snapDistance:10});
			for(var i = 0;i < guideLayers.length; i++) {
		        // Add every already drawn layer to snap list
		        layer.snapediting.addGuideLayer(guideLayers[i]);
		        // Add the currently drawn layer to the snap list of the already drawn layers
		        guideLayers[i].snapediting.addGuideLayer(layer);
		        guideLayers[i].snapediting.disable();
		        if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable(); 
			 }*/
			 
			 // Add to drawnItems
			 drawnItems.addLayer(layer);
			 // Add newly drawn feature to list of snappable features
			  guideLayers.push(layer);
		   
			createClass('.polyline-style',"font-family:Verdana;font-size:20px;color:red;");
			capaUsrActiva.addLayer(layer);
			
		} else if (type === t_polygon) {
			tipusCat=window.lang.translate('Títol Polígon');
			tipusCatDes=window.lang.translate('Descripció Polígon');	
			var nomDefecteCapa = window.lang.translate('Capa Polígon');
			var mida = L.GeometryUtil.geodesicArea(layer.getLatLngs());
			mida = L.GeometryUtil.readableArea(mida,true);
			
			if(capaUsrActiva != null && capaUsrActiva.options.geometryType != t_polygon){
				capaUsrActiva.removeEventListener('layeradd');
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_polygon
				};
				map.addLayer(capaUsrActiva);				
				capaUsrActiva.on('layeradd',objecteUserAdded);
			}else if(capaUsrActiva == null){
				capaUsrActiva = new L.FeatureGroup();
				var index = parseInt(controlCapes._lastZIndex)+1;
				capaUsrActiva.options = {
					businessId : '-1',
					nom : nomDefecteCapa+' '+index,
					zIndex :  -1,
//					tipus : t_tematic,
					tipus : t_visualitzacio,
					geometryType: t_polygon
				};
				map.addLayer(capaUsrActiva);
				capaUsrActiva.on('layeradd',objecteUserAdded);
			}
			layer.properties={
					'capaNom':capaUsrActiva.options.nom,//TODO desactualitzat quan es canvii nom capa!
					'capaBusinessId':capaUsrActiva.options.businessId,
					'capaLeafletId': capaUsrActiva._leaflet_id,
					'tipusFeature':t_polygon,
					'mida': calculateArea(layer)};
			
			layer.properties.data={
					'nom':tipusCat+' '+capaUsrActiva.getLayers().length,
					'text':tipusCatDes+' '+capaUsrActiva.getLayers().length,
			};		
			//Activate snapping
			/*layer.snapediting = new L.Handler.PolylineSnap(map, layer,{snapDistance:10});
			for(var i = 0;i < guideLayers.length; i++) {
		        // Add every already drawn layer to snap list
		        layer.snapediting.addGuideLayer(guideLayers[i]);
		        // Add the currently drawn layer to the snap list of the already drawn layers
		        guideLayers[i].snapediting.addGuideLayer(layer);
		        guideLayers[i].snapediting.disable();
		        if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable(); 
			 }
			*/
	
			  // Add to drawnItems
			 drawnItems.addLayer(layer);
			 // Add newly drawn feature to list of snappable features
			guideLayers.push(layer);
			capaUsrActiva.addLayer(layer);			
		}
	});
	
}

//Funcio que crea Pop up de la feature quan te opcio d'edicio
function createPopupWindow(layer,type){
//	console.debug('createPopupWindow');
	var html = createPopUpContent(layer,type);
	layer.bindPopup(html,{'offset':[0,-25]});
	
	//eventos del popup
	jQuery(document).on('click', "#titol_pres", function(e) {
		modeEditText();
	});
	
	jQuery(document).on('click', "#des_pres", function(e) {
		modeEditText();
	});

	jQuery(document).on('click', ".bs-ncapa li a", function(e) {
		e.preventDefault();
		var accio;
		if(jQuery(this).attr('id').indexOf('#')!=-1){			
			accio=jQuery(this).attr('id').split("#");				
		}
		
		objEdicio.featureID=accio[1];
		if(accio[0].indexOf("layer_edit")!=-1){
			objEdicio.edicioPopup='textCapa';
			jQuery('#layer_accio').text(window.lang.translate('Canviar el nom de la capa'))
			jQuery('#capa_edit').val(jQuery('#cmbCapesUsr').val());
			modeLayerTextEdit();

		}else if(accio[0].indexOf("layer_add")!=-1){
			objEdicio.edicioPopup='nouCapa';
			jQuery('#layer_accio').text(window.lang.translate('Nom nova capa'))
			jQuery('#capa_edit').val("").attr('placeholder',window.lang.translate('Nova capa'));
			modeLayerTextEdit();
		}else{
			
		}
	});
	
	 jQuery(document).on('focus', ".bs-ncapa li select", function(e) {
		 $(this).data('cmbCapesUsr_old',$(this).val());
	 });	 
	 
	 jQuery(document).on('change', ".bs-ncapa li select", function(e) {
		    e.stopImmediatePropagation();
		    
			e.preventDefault();
			e.stopPropagation();		    
//		    console.debug('on change select cmbusrcapa');
			var accio;
			if(jQuery(this).attr('id').indexOf('-')!=-1){			
				accio=jQuery(this).attr('id').split("-");				
			}
			objEdicio.featureID=accio[1];
						
			var toBusinessId = jQuery(this).val().split("#");
			var fromBusinessId = $(this).data('cmbCapesUsr_old').split("#");
			//Actualitzem valor antic
			$(this).data('cmbCapesUsr_old',$(this).val());
			
			objEdicio.featureID=accio[1];
			var obj = map._layers[objEdicio.featureID];
			
			
			/*NOU MODEL*/
			var features = {
					type: obj.properties.tipusFeature,
					id:3124,
					businessId: obj.properties.businessId,//Bid de la geometria q estas afegint
					properties: obj.properties.data,
					estil: obj.properties.estil,
					geometry: obj.properties.feature.geometry
				};
			
			features = JSON.stringify(features);
			
			data= {
				toBusinessId: toBusinessId[0],//bID de la visualitzacio-capa
				fromBusinessId: fromBusinessId[0],//bID de la visualitzacio-capa
				uid: Cookies.get('uid'),
				features: features
			}	
			
			moveGeometriaToVisualitzacio(data).then(function(resultsMove) {
//				console.debug("moveGeometriaToVisualitzacio:"+ resultsMove.status);
				if(resultsMove.status === 'OK'){
					var toLayer = controlCapes._layers[''+toBusinessId[1]+''].layer;//map._layers[''+toBusinessId[1]+''];
					var fromLayer = map._layers[''+fromBusinessId[1]+''];
					fromLayer.removeLayer(obj);
					//Actualitzem capa activa
					//Primer desactivo l'event, per si la capaActiva coincideix amb la capa toLayer
					if(toLayer) toLayer.removeEventListener('layeradd');
					
					toLayer.addLayer(obj);
					//Refresh de la capa
					controlCapes._map.removeLayer(toLayer);
					controlCapes._map.addLayer(toLayer);					
					capaUsrActiva = toLayer;
					capaUsrActiva.on('layeradd',objecteUserAdded);			
					
					obj.properties.capaBusinessId = capaUsrActiva.options.businessId;
					obj.properties.capaNom = capaUsrActiva.options.nom;
					obj.properties.capaLeafletId = capaUsrActiva._leaflet_id;
					obj.properties.estil.businessId = resultsMove.estilBid;
					//Actualitzem popup del marker
					//var html = createPopUpContent(obj,obj.options.tipus);
					//obj.setPopupContent(html);
					
					var nom=resultsMove.results.properties.nom;
					var props=resultsMove.results.properties;
					var html = refrescarPopUp(nom,props,obj._leaflet_id,obj.properties.tipusFeature,obj.properties.capaLeafletId);
					map.closePopup();
					obj.closePopup();
					console.debug(obj);
					obj.bindPopup(html,{'offset':[0,-25]});					
					obj.openPopup();
					var toLayer1 = controlCapes._layers[''+toBusinessId[1]+''];
					
					actualitzacioTematic(toLayer1,toLayer.options.businessId,"3124",obj,features,"modificacio");
			
					//Actualitzem l'enllaç d'obrir la finestra de dades
					var htmlDataTable =jQuery("#feature_data_table_"+accio[1]).html();
					if (undefined != htmlDataTable){
						var stringsDataTableA = htmlDataTable.split("##");
						jQuery("#feature_data_table_"+accio[1]).html(stringsDataTableA[0]+"##"+stringsDataTableA[1]+"##"+stringsDataTableA[2]+"##"+toLayer._leaflet_id+"##"+stringsDataTableA[4]);
					}
					//NO CAL: com cridem addLayer, de controlCapes, ja s'actualitzen els comptadors de les capes
					//updateFeatureCount(fromBusinessId, toBusinessId);			
					
				}else{
					console.debug("moveGeometriaToVisualitzacio ERROR");
				}
			},function(results){
				console.debug("moveGeometriaToVisualitzacio ERROR");
			});					
	 });
	 
	jQuery(document).on('click', ".bs-popup li a", function(e) {
		e.stopImmediatePropagation();
		var accio;
		if(jQuery(this).attr('id').indexOf('#')!=-1){			
			if (jQuery(this).attr('id').indexOf('##')>-1) accio=jQuery(this).attr('id').split("##");			
			else accio=jQuery(this).attr('id').split("#");				
		}
		objEdicio.featureID=accio[1];
		
		if(accio[0].indexOf("feature_edit")!=-1){

			//Update modal estils, amb estil de la feature seleccionada
			var obj = map._layers[accio[1]];
			if(obj.options.icon /*|| obj.options.icon.options.markerColor.indexOf("punt_r")!=-1*/){
				var icon = obj.options.icon.options;	
			}else if(obj._options){
				var icon = obj._options;
			}else{
				var icon = obj.options;
			}
			
		
			updateDialogStyleSelected(icon);

			
			if(accio[2].indexOf("marker")!=-1){
				obrirMenuModal('#dialog_estils_punts','toggle',from_creaPopup);
			}else if(accio[2].indexOf("polygon")!=-1){
				obrirMenuModal('#dialog_estils_arees','toggle',from_creaPopup);
			}else{
				obrirMenuModal('#dialog_estils_linies','toggle',from_creaPopup);
			}
		}else if(accio[0].indexOf("feature_remove")!=-1){
			map.closePopup();
			var data = {
	            businessId: map._layers[objEdicio.featureID].properties.businessId,
	            uid: Cookies.get('uid')
	        };
			
			var features = {
					type:"Feature",
					id: 3124,
					businessId: map._layers[objEdicio.featureID].properties.businessId,
					properties: map._layers[objEdicio.featureID].properties.data,
					estil: map._layers[objEdicio.featureID].properties.estil,
					geometry: map._layers[objEdicio.featureID].properties.feature.geometry
				};				
			
			features = JSON.stringify(features);
			
			var data = {
				businessId: map._layers[objEdicio.featureID].properties.capaBusinessId,//bID de la visualitzacio-capa
				uid: Cookies.get('uid'),
				features: features
			};
			var businessIdCapaOrigen=map._layers[objEdicio.featureID].properties.capaBusinessId;
			removeGeometriaFromVisualitzacio(data).then(function(results){
				if(results.status == 'OK'){
					/*var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;
					var capaBusinessId = map._layers[objEdicio.featureID].properties.capaBusinessId;
					if(map._layers[capaLeafletId]!= undefined) map._layers[capaLeafletId].removeLayer(map._layers[objEdicio.featureID]);					
					if(map._layers[objEdicio.featureID]!= null) map.removeLayer(map._layers[objEdicio.featureID]);					
					//Actualitzem comptador de la capa
					if(map._layers[capaLeafletId]!= undefined) updateFeatureCount(map._layers[capaLeafletId].options.businessId, null);
					else {						
						updateFeatureCount(capaBusinessId, null);		
					}*/
					
					var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;
					var capaBusinessId = map._layers[objEdicio.featureID].properties.capaBusinessId;
					if(map._layers[capaLeafletId]!= undefined) map._layers[capaLeafletId].removeLayer(map._layers[objEdicio.featureID]);					
					if(map._layers[objEdicio.featureID]!= null) map.removeLayer(map._layers[objEdicio.featureID]);	
					if(map._layers[capaLeafletId]!= undefined) {
						updateFeatureCount(map._layers[capaLeafletId].options.businessId, null);
					}
					else {						
						updateFeatureCount(capaBusinessId, null);		
					}		
					 var layer = controlCapes._layers[capaLeafletId];
					//recarrego les sublayers de la capa modificada	
					actualitzacioTematic(layer,businessIdCapaOrigen,null,null,null,"baixa");
					
					
				}else{
					console.debug("ERROR deleteFeature");
				}
			},function(results){
				console.debug("ERROR deleteFeature");
			});		
			
		}else if(accio[0].indexOf("feature_text")!=-1){
			modeEditText();
		}else if(accio[0].indexOf("feature_move")!=-1){
			objEdicio.esticEnEdicio=true;
			var capaLeafletId = map._layers[objEdicio.featureID].properties.capaLeafletId;
			if (capaLeafletId==undefined) capaLeafletId =  map._layers[objEdicio.featureID]._leaflet_id;
			objEdicio.capaEdicioLeafletId = capaLeafletId;
			//Actualitzem capa activa
			if (capaUsrActiva){
				capaUsrActiva.removeEventListener('layeradd');
			}
			capaUsrActiva = map._layers[capaLeafletId];
			var capaEdicio = new L.FeatureGroup();
			capaEdicio.addLayer(map._layers[objEdicio.featureID]);
			
			try{
				capaUsrActiva.removeLayer(map._layers[objEdicio.featureID]);
			}
			catch(ex){
				
			}
			map.addLayer(capaEdicio);
			
			var opcionsSel={
					color: '#FF1EE5',
					"weight": 7,
					opacity: 0.6,
					dashArray: '1, 1',
					fill: true,
					fillColor: '#fe57a1',
					fillOpacity: 0.1
				};
			
			crt_Editing=new L.EditToolbar.Edit(map, {
				featureGroup: capaEdicio,
				selectedPathOptions: opcionsSel
			});
			crt_Editing.enable();
		
		
		/*	if(map._layers[objEdicio.featureID].properties.tipusFeature=="marker" && map._layers[objEdicio.featureID].options.isCanvas){
				crt_Editing=new L.EditToolbar.Edit(map, {
					featureGroup: capaEdicio,
					selectedPathOptions: opcionsSel
				});
				crt_Editing.enable();
			}
			else {
				crt_Editing=new L.EditToolbar.SnapEdit(map, {
					featureGroup: capaEdicio,
					selectedPathOptions: opcionsSel,
					snapOptions: {
						guideLayer: guideLayers
					}
				});
				crt_Editing.enable();
				//activarSnapping(capaEdicio);
			}
			
			
			*/
			
			
			map.closePopup();
			
			
		}else if(accio[0].indexOf("feature_no")!=-1){
			jQuery('.popup_pres').show();
			jQuery('.popup_edit').hide();
			
		}else if(accio[0].indexOf("feature_ok")!=-1){
			if(objEdicio.edicioPopup=='textFeature'){
				var txtTitol=jQuery('#titol_edit').val();
				var txtDesc=jQuery('#des_edit').val();
				if (txtDesc.indexOf("'")>-1) txtDesc = txtDesc.replaceAll("'",'"');
				updateFeatureNameDescr(map._layers[objEdicio.featureID],txtTitol,txtDesc);

			}else if(objEdicio.edicioPopup=='textCapa'){
				if(jQuery('#capa_edit').val()!=""){
					jQuery('#cmbCapesUsr option:selected').text(jQuery('#capa_edit').val());	
					jQuery('.popup_pres').show();
					jQuery('.popup_edit').hide();
				}else{
					alert(window.lang.translate('Has de posar un nom de capa'));	
				}
			}else if(objEdicio.edicioPopup=='nouCapa'){
				if(jQuery('#capa_edit').val()!=""){
					generaNovaCapaUsuari(map._layers[objEdicio.featureID],jQuery('#capa_edit').val());
				}else{
					alert(window.lang.translate('Has de posar un nom de capa'));	
				}
			}
		}else if(accio[0].indexOf("feature_data_table")!=-1){
			$('#modal_data_table').modal('show');
			var featureId=objEdicio.featureID;
			if (featureId==undefined) featureId=accio[2];
			//console.debug(featureId);
			console.debug(accio);
			console.debug(map._layers);
			console.debug(controlCapes._layers);
			if (map._layers[featureId]==undefined) {
				try{
					if (accio[6]!=undefined) featureId=accio[6];
					var props=map._layers[featureId].properties;
					if (props==undefined) props=map._layers[featureId].options;
					if (accio[3]==undefined)  fillModalDataTable(controlCapes._layers[accio[2]],props.businessId);
					else fillModalDataTable(controlCapes._layers[accio[3]],props.businessId);
				}
				catch(err){
					console.debug(err);
				}
			}
			else fillModalDataTable(controlCapes._layers[accio[3]],map._layers[featureId].properties.businessId);
		
		
		}else{
		//accio tanca
			map.closePopup();
		}
	});	

	layer.on('popupopen', function(e){
		if(objEdicio.esticEnEdicio){//Si s'esta editant no es pot editar altre element
			map.closePopup();
		}else{
			//actualitzem popup
			jQuery('#cmbCapesUsr-'+layer._leaflet_id+'-'+layer.options.tipus+'').html(reFillCmbCapesUsr(layer.options.tipus, layer.properties.capaBusinessId));
			if (layer.properties.data.nom){
				jQuery('#titol_pres').text(layer.properties.data.nom).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
			}
			if (layer.properties.data.text){
				var txt = layer.properties.data.text;
				
				if (!$.isNumeric(txt) && !validateWkt(txt)) {
					txt = parseUrlTextPopUp(txt,"");
					if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
						jQuery('#des_pres').html('');
						jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+layer.properties.data.text+'</span>');
						jQuery('#des_pres').append(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
					}else{
						jQuery('#des_pres').html('');
						jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+layer.properties.data.text+'</span>');
						jQuery('#des_pres').append(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
					}
				}
				else {
					jQuery('#des_pres').html('');
					jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+layer.properties.data.text+'</span>');
					jQuery('#des_pres').text(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
				}
				
			}

			if(layer.properties.mida)	
			{

				var text = window.lang.translate("Longitud");
				if(layer.properties.tipusFeature == t_polygon)
				{

					text = window.lang.translate("Àrea");

				}

				$("#mida_pres").html("<b>" + text + ":</b> " + layer.properties.mida);

			}
		}
	});

	return html;
}

function reFillCmbCapesUsr(type, businessIdCapa){
	var html = "";
	$.each( controlCapes._layers, function(i,val) {
		var layer = val.layer.options;
		if(layer.tipus==t_tematic && layer.geometryType==type ){
	        html += "<option value=\"";
	        html += layer.businessId +"#"+val.layer._leaflet_id+"\"";
	        if(businessIdCapa == layer.businessId) html += " selected";
	        html += ">"+ layer.nom + "</option>";            		
		}else if(layer.tipus==t_visualitzacio && layer.geometryType==type ){
	        html += "<option value=\"";
	        html += layer.businessId +"#"+val.layer._leaflet_id+"\"";
	        if(businessIdCapa == layer.businessId) html += " selected";
	        html += ">"+ layer.nom + "</option>";            		
		}
	});		
	return html;
}


function objecteUserAdded(f){
	
	var fId = this.toGeoJSON().features.length;
	
	var feature = f.layer.toGeoJSON();
	
//	//Invertim lng,lat perque es recuperi be desde el servidor despres
//    if(f.layer.options.tipus == t_marker){
//          var lng = feature.geometry.coordinates[0]
//          feature.geometry.coordinates[0] = feature.geometry.coordinates[1];
//          feature.geometry.coordinates[1] = lng;         
//    }else if(f.layer.options.tipus==t_polyline){
//          for(var i=0;i<feature.geometry.coordinates.length;i++){
//                var lng = feature.geometry.coordinates[i][0]
//                feature.geometry.coordinates[i][0] = feature.geometry.coordinates[i][1];
//                feature.geometry.coordinates[i][1] = lng;
//          }
//    }else if(f.layer.options.tipus==t_polygon){
//          var lcoordinates = [];
//          $.each( feature.geometry.coordinates[0], function(i,val) {
//                lcoordinates.push([val[1], val[0]]);
//          }); 
//          feature.geometry.coordinates[0] = lcoordinates;                  
//    }       

	feature.properties.data = f.layer.properties.data;    	

	var features = JSON.stringify(feature);

	var rangsJSON = getFeatureStyle(f,fId);
	var rangs = JSON.stringify(rangsJSON);
	
	if (fId == 1) {
		
		var _this = this;
		
		/*NOU MODEL: Crear nova visualització*/
		var data ={
				uid: Cookies.get('uid'),
				nom: f.layer.properties.capaNom,
				mapBusinessId: url('?businessid'),
				geometryType: f.layer.options.tipus,
//					tipus : tem_origen,//no cal, per defecte li posa origen a servidor
//					calentas: false,
//					order: controlCapes._lastZIndex+1,
				activas: true,
				visibilitats: true,				
				publica : true
		};		
		
		createVisualitzacioLayer(data).then(function(results) {
			
			if(results.status === 'OK'){
				
				_this.options.businessId = results.results.businessId;
				f.layer.properties.capaBusinessId = results.results.businessId;
				//Ara afegim nova geometria
				var features = {
						type:f.layer.options.tipus,
						id:fId,
						properties: feature.properties.data,
						estil: rangsJSON,
						geometry: feature.geometry
					};
				
				features = JSON.stringify(features);				
				
				data = {
						businessId: f.layer.properties.capaBusinessId,//Bid de la visualitzacio
						uid: Cookies.get('uid'),
						features: features,
						geometryType: f.layer.options.tipus,
						options: "text,nom"
//							geometriaBusinessId: '4c216bc1cdd8b3a69440b45b2713b014'//Bid de la geometria q estas afegint						
				};
				
				addGeometriaToVisualitzacio(data).then(function(results) {
					if(results.status === 'OK'){
					
//							_this.options.businessId = results.results.businessId;
//							f.layer.properties.capaBusinessId = results.results.businessId;
						f.layer.properties.businessId = results.feature.businessId;
						f.layer.properties.estil = results.results.estil[0];
						f.layer.properties.feature = results.feature;	
						finishAddFeatureToTematic(f.layer);			
					
						
					}else{
						console.debug('addGeometriaToVisualitzacio ERROR');
					}
				},function(results){
					console.debug('addGeometriaToVisualitzacio ERROR');
				});
				
			}else{//ERROR: control Error
				console.debug('createVisualitzacioLayer ERROR');
			}
		},function(results){//ERROR: control Error
			console.debug('createVisualitzacioLayer ERROR');
		});			

	} else if (this.getLayers().length > 1) {
	
		var features = {
				type:f.layer.options.tipus,
				id:fId,
				properties: feature.properties.data,
				estil: rangsJSON,
				geometry: feature.geometry
			};
		features = JSON.stringify(features);				
		
		data = {
				businessId: this.options.businessId,//f.layer.properties.capaBusinessId,//Bid de la visualitzacio
				uid: Cookies.get('uid'),
				features: features
//					geometriaBusinessId: '4c216bc1cdd8b3a69440b45b2713b014'//Bid de la geometria q estas afegint						
		};		
		var businessIdCapaOrigen = data.businessId;
		addGeometriaToVisualitzacio(data).then(function(results) {
			if(results.status === 'OK'){
				
//					_this.options.businessId = results.results.businessId;
//					f.layer.properties.capaBusinessId = results.results.businessId;
				f.layer.properties.businessId = results.feature.businessId;
				f.layer.properties.estil = results.results.estil[0];
				f.layer.properties.feature = results.feature;
				finishAddFeatureToTematic(f.layer);		
				
				var capaEdicio = controlCapes._layers[capaUsrActiva._leaflet_id];
				if (capaEdicio!=undefined) {
					//recarrego les sublayers de la capa modificada	
					actualitzacioTematic(capaEdicio,businessIdCapaOrigen,fId,f,features,"alta");
				}
			}else{
				console.debug('addGeometriaToVisualitzacio ERROR');
			}
		},function(results){
			console.debug('addGeometriaToVisualitzacio ERROR');
		});			
	}
}

function getFeatureStyle(f, fId){
	var rangs = {};
	//ESTIL MARKER
	if(f.layer.options.tipus == t_marker){
		if (!f.layer._ctx && f.layer.options.icon!= undefined){
			rangs = {
				color : f.layer.options.icon.options.fillColor,//Color principal
				marker: f.layer.options.icon.options.markerColor,//Si es de tipus punt_r o el color del marker
				simbolColor: f.layer.options.icon.options.iconColor,//Glyphon
				radius : f.layer.options.icon.options.radius,//Radius
				iconSize : f.layer.options.icon.options.iconSize.x+"#"+f.layer.options.icon.options.iconSize.y,//Size del cercle
				iconAnchor : f.layer.options.icon.options.iconAnchor.x+"#"+f.layer.options.icon.options.iconAnchor.y,//Anchor del cercle
				simbol : jQuery.trim(f.layer.options.icon.options.icon),//tipus glyph
				simbolSize : f.layer.options.icon.options.simbolSize,//mida glyphon
//				puntTMP.options.symbolSize = style.symbolSize;//mida glyphon
				opacity : (f.layer.options.opacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000',
			};
		}else{
			rangs = {
				color : f.layer.options.fillColor,
				simbolSize : f.layer.options.radius,
				opacity : (f.layer.options.fillOpacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000',
				borderWidth : f.layer.options.weight,
				borderColor : f.layer.options.color,
			};
		}
	//ESTIL LINE
	}else if(f.layer.options.tipus == t_polyline){
		rangs = {
			color : f.layer.options.color,
			lineWidth : f.layer.options.weight,
			lineStyle : 'solid',
			borderWidth : 2,
			borderColor : f.layer.options.color,
			opacity : (f.layer.options.opacity * 100),
			label : false,
			labelSize : 10,
			labelFont : 'arial',
			labelColor : '#000000',
		};	
	//ESTIL POLIGON		
	}else{
		var fillColor = f.layer.options.color;
		if(f.layer.options.fillColor) fillColor = rgb2hex(f.layer.options.fillColor);	
		var fillOpacity = f.layer.options.fillOpacity;
		rangs = {
				color : fillColor,
				fillColor: fillColor,
				fillOpacity: fillOpacity,
				lineWidth : f.layer.options.dashArray,
				lineStyle : 'solid',
				borderWidth : f.layer.options.dashArray,
				borderColor : f.layer.options.color,
				opacity : (f.layer.options.fillOpacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000'
			};				
	}
	return rangs;
}


function getFeatureStyle2(estil,tipus){
	var rangs = {};
	//ESTIL MARKER
	if( tipus == t_marker){
		if (estil.icon!= undefined){
			rangs = {
				color : estil.icon.options.fillColor,//Color principal
				marker:estil.icon.options.markerColor,//Si es de tipus punt_r o el color del marker
				simbolColor:estil.icon.options.iconColor,//Glyphon
				radius :estil.icon.options.radius,//Radius
				iconSize :estil.icon.options.iconSize.x+"#"+estil.icon.options.iconSize.y,//Size del cercle
				iconAnchor :estil.icon.options.iconAnchor.x+"#"+estil.icon.options.iconAnchor.y,//Anchor del cercle
				simbol : jQuery.trim(estil.icon.options.icon),//tipus glyph
				simbolSize : estil.icon.options.simbolSize,//mida glyphon
//				puntTMP.options.symbolSize = style.symbolSize;//mida glyphon
				opacity : (estil.opacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000',
				businessId: estil.businessId
			};
		}else{
			rangs = {
				color : estil.fillColor,
				simbolSize : estil.radius,
				opacity : (estil.fillOpacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000',
				borderWidth : estil.weight,
				borderColor : estil.color,
				businessId: estil.businessId
			};
		}
	//ESTIL LINE
	}else if(tipus == t_polyline){
		rangs = {
			color : estil.color,
			lineWidth : estil.weight,
			lineStyle : 'solid',
			borderWidth : 2,
			borderColor : estil.color,
			opacity : (estil.opacity * 100),
			label : false,
			labelSize : 10,
			labelFont : 'arial',
			labelColor : '#000000',
			businessId: estil.businessId
		};	
	//ESTIL POLIGON		
	}else{
		var fillColor = estil.color;
		if(estil.fillColor) fillColor = rgb2hex(estil.fillColor);	
		var fillOpacity = estil.fillOpacity;
		rangs = {
				color : fillColor,
				fillColor: fillColor,
				fillOpacity: fillOpacity,
				lineWidth : estil.dashArray,
				lineStyle : 'solid',
				borderWidth : estil.dashArray,
				borderColor : estil.color,
				opacity : (estil.fillOpacity * 100),
				label : false,
				labelSize : 10,
				labelFont : 'arial',
				labelColor : '#000000',
				businessId: estil.businessId
			};				
	}
	return rangs;
}

function finishAddFeatureToTematic(layer){
	
	var type = layer.options.tipus;
	//Afegir capa edicio a control de capes en cas que sigui nova
	if (capaUsrActiva.toGeoJSON().features.length == 1 ) {
		//Actualitzem zIndex abans d'afegir al control de capes
		capaUsrActiva.options.zIndex = controlCapes._lastZIndex+1; 								
		controlCapes.addOverlay(capaUsrActiva,	capaUsrActiva.options.nom, true);
		controlCapes._lastZIndex++;
		activaPanelCapes(true);
	}else{
			//Actualitzem comptador de la capa
			updateFeatureCount(null, capaUsrActiva.options.businessId);
	}
		
	createPopupWindow(layer,type);
	layer.openPopup();
	map.eachLayer(function(layer) {
		if (layer.options
				&& layer.options.tipus == "wms") {
			map.on('click',layer.getFeatureInfo,layer);
		}

	});
}

function updateFeatureNameDescr(layer, titol, descr){
	
	layer.properties.data.nom=titol;
	layer.properties.data.text=descr;
	
//	//VELL!!
//	if(!nou_model){
//		if (layer.properties.feature.properties){
//			layer.properties.feature.properties.nom = titol;
//			layer.properties.feature.properties.text = descr;
//		}
//			
//		var feature = layer.toGeoJSON();
//		feature.geometry = layer.properties.feature.geometry;
//		//CAL???
//		if (layer.properties.feature.properties){	
//			feature.properties = layer.properties.feature.properties;
//		}else{
//			//Obsolet a nou model
//			feature.properties = layer.properties;
//			//
//		}		
//	}

	var features = {
			type: layer.properties.tipusFeature,
			id:3124,
			businessId: layer.properties.businessId,//Bid de la geometria q estas afegint
			properties: layer.properties.data,
			estil: layer.properties.estil,
			geometry: layer.properties.feature.geometry
		};
	
	features = JSON.stringify(features);
	
    var data = {
            uid : Cookies.get('uid'),
            features : features,
            businessId: layer.properties.businessId
        };      	
	
    
    updateGeometria(data).then(function(results){
	    if(results.status == 'OK'){
			jQuery('#titol_pres').text(titol).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
			var txt = descr;			
			if (!$.isNumeric(txt) && !validateWkt(txt)) {
				txt = parseUrlTextPopUp(txt,"");
				if(txt.indexOf("iframe")==-1 && txt.indexOf("img")==-1){
					jQuery('#des_pres').html('');
					jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+descr+'</span>');
					jQuery('#des_pres').append(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
				}else{
					jQuery('#des_pres').html('');
					jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+descr+'</span>');
					jQuery('#des_pres').append(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
				}
			}
			else {
				jQuery('#des_pres').html('');
				jQuery('#des_pres').append('<span id="descrText" style="display:none;">'+descr+'</span>');
				jQuery('#des_pres').text(txt).append(' <i class="glyphicon glyphicon-pencil blau"></i>');
			}
			
			jQuery('.popup_pres').show();
			jQuery('.popup_edit').hide();   
						
			//recarrego les sublayers de la capa modificada
			var capaEdicio = controlCapes._layers[layer.properties.capaLeafletId];
			actualitzacioTematic(capaEdicio,layer.properties.capaBusinessId,"3124",null,features,"modificacioInfo");
	    }else{
	        console.debug("updateGeometria ERROR");
	    }
	}, function(results){
		  console.debug("updateGeometria ERROR");
	}); 		
        
}

function updateFeatureMove(featureID, capaEdicioID, capaEdicioLeafletId){
	
    var layer = map._layers[featureID];
    
    var feature = layer.toGeoJSON();
    
    feature.geometry = layer.properties.feature.geometry;      
        
    if(layer.properties.tipusFeature == t_marker){
        var newLatLng = layer.getLatLng();
        feature.geometry.coordinates[1] = newLatLng.lat;
        feature.geometry.coordinates[0] = newLatLng.lng;           
    }else{
	    var lcoordinates = [];
	    $.each(layer._latlngs, function(i,val) {
	    	lcoordinates.push([val.lng, val.lat]);
	    });              
	    if(layer.properties.tipusFeature == t_polyline){
	    	feature.geometry.coordinates = lcoordinates;
	    	layer.properties.mida = calculateDistance(layer.getLatLngs());
	    }else{
	    	lcoordinates.push(lcoordinates[0]);
	    	feature.geometry.coordinates[0] = lcoordinates;
	    	layer.properties.mida = calculateArea(layer);
	    }
    }
	
	var features = {
			type: layer.properties.tipusFeature,
			id:3124,
			businessId: layer.properties.businessId,//Bid de la geometria q estas afegint
			properties: layer.properties.data,
			estil: layer.properties.estil,
			geometry: feature.geometry
		};
	features = JSON.stringify(features);
	
    var data = {
            uid : Cookies.get('uid'),
            features : features,
            businessId: layer.properties.businessId
        };      	
	
    updateGeometria(data).then(function(results){
	    if(results.status == 'OK'){
	    	if (layer.properties.tipusFeature=="marker" && layer.properties.data.nom &&  layer.properties.data.text) createPopupWindow(layer,"marker");
	    	jQuery('.popup_pres').show();
	    	//Actualitzem visualitzacions de la capa on estava la geometria modificada
	    	var capaEdicio = controlCapes._layers[capaEdicioLeafletId];
	    	//recarrego les sublayers de la capa modificada	
	    	actualitzacioTematic(capaEdicio,layer.properties.capaBusinessId,null,null,null,"baixa");
			/*jQuery.each(capaEdicio._layers, function(i, sublayer){
            	if(jQuery.type(sublayer.layer.options)== "string"){
					sublayer.layer.options = $.parseJSON(sublayer.layer.options);
				}	            	  
				//Sublayer visualitzacio, carrego la capa
				if(sublayer.layer.options.tipus.indexOf(t_visualitzacio)!=-1){
            		  
            		  sublayer.layer.serverName = sublayer.layer.options.nom;
            		  sublayer.layer.serverType = sublayer.layer.options.tipus;
            		  sublayer.layer.capesActiva = "true";
            		  sublayer.layer.options.origen = layer.properties.capaBusinessId;//BusinessIdCapaorigen
            		  //tipusRang
            		  sublayer.layer.businessId = sublayer.layer.options.businessId;//Si no, no ho trobarà després
            		  sublayer.layer.options = JSON.stringify(sublayer.layer.options);
            		  loadVisualitzacioLayer(sublayer.layer).then(function(results){
            			//console.debug("LoadVisualitzacio despres de update Geometria"); 
						map.closePopup();
						map.removeLayer(sublayer.layer);
						//Eliminem la capa de controlCapes
						controlCapes.removeLayer(sublayer);
            		  });
            	  }
            	
              });*/
	    
	    	
	    }else{
	        console.debug("updateFeature ERROR");
	    }
	}, function(results){
		  console.debug("updateFeature ERROR");
	});      	
  
    //Retornem la geometria a la seva capa original
    capaUsrActiva.addLayer(layer);
    capaUsrActiva.on('layeradd',objecteUserAdded);//Deixem activat event layeradd, per la capa activa
    map._layers[capaEdicioID].removeLayer(layer);
    //Refresh de la capa
    controlCapes._map.removeLayer(capaUsrActiva);
	controlCapes._map.addLayer(capaUsrActiva);
	map.removeLayer(map._layers[capaEdicioID]);
    
    //Fi edicio
    objEdicio.esticEnEdicio=false;
}

function fillCmbCapesUsr(type){
	var html = "";
	$.each( controlCapes._layers, function(i,val) {
		var layer = val.layer.options;
		if(layer.tipus==t_tematic && layer.geometryType==type ){
	        html += "<option value=\"";
	        html += layer.businessId +"#"+val.layer._leaflet_id+"\"";
	        if(capaUsrActiva && (capaUsrActiva.options.businessId == layer.businessId)) html += " selected";
	        html += ">"+ layer.nom + "</option>";
	    //nou model    
		}else if(layer.tipus==t_visualitzacio && layer.geometryType==type /*&& !layer.source*/){
	        html += "<option value=\"";
	        html += layer.businessId +"#"+val.layer._leaflet_id+"\"";
	        if(capaUsrActiva && (capaUsrActiva.options.businessId == layer.businessId)) html += " selected";
	        html += ">"+ layer.nom + "</option>";
		}
	});		
	return html;
}

function createPopUpContent(player,type){
	
	var auxNom = window.lang.translate('Nom');
	var auxText = window.lang.translate('Descripció');
	var auxLon,auxLat;
	if(player.properties.data.nom) auxNom = player.properties.data.nom;
	if(player.properties.data.text) auxText = player.properties.data.text;
	if (player.options.tipus=="marker" && player._latlng) {
		auxLat = player._latlng.lat;
		auxLat= auxLat.toFixed(5);
		auxLon = player._latlng.lng;
		auxLon= auxLon.toFixed(5);
	}
	var html='<div class="div_popup">' 
	+'<div class="popup_pres">'							
	+'<div id="titol_pres">'+auxNom+' <i class="glyphicon glyphicon-pencil blau"></i></div>'	
	+'<div id="des_pres">'+auxText+' <i class="glyphicon glyphicon-pencil blau"></i></div>';
	
	if (player.options.tipus=="marker" && auxLat!=undefined && auxLon!=undefined) {
		html+='<div id="auxLat">'+auxLat+'</div>'
		+'<div id="auxLon">'+auxLon+'</div>';
	}

	
	if(type == t_polyline && player.properties.mida){
		html+='<div id="mida_pres"><b>'+window.lang.translate('Longitud')+':</b> '+player.properties.mida+'</div>';	
	}else if(type == t_polygon && player.properties.mida){
		if (player.properties.mida.indexOf("NaN")==-1)	html+='<div id="mida_pres"><b>'+window.lang.translate('Àrea')+':</b> '+player.properties.mida+'</div>';
		else html+='<div id="mida_pres"><b>'+window.lang.translate('Àrea')+':</b> '+L.GeometryUtil.readableArea(L.GeometryUtil.geodesicArea(player.getLatLngs()),true)+'</div>';
	}
	
	//+'<div id="capa_pres">'
	html+='<ul class="bs-ncapa">'
		+'<li><span lang="ca" class="small">'+window.lang.translate('Capa actual:')+'</span>'
			+'<select id="cmbCapesUsr-'+player._leaflet_id+'-'+type+'" data-leaflet_id='+player._leaflet_id+'>';
			html+= fillCmbCapesUsr(type);
			html+= '</select></li>'
		//+'<li><a id="layer_edit#'+player._leaflet_id+'#'+type+'" lang="ca" title="Canviar el nom de la capa" href="#"><span class="glyphicon glyphicon-pencil blau12"></span></a></li>'
	+'<li><a id="layer_add#'+player._leaflet_id+'#'+type+'" lang="ca" title="Crear una nova capa" href="#"><span class="glyphicon glyphicon-plus verd12"></span></a></li>'
	+'</ul>'	
	//'</div>'	
	+'<div id="footer_edit"  class="modal-footer">'
		+'<ul class="bs-popup">'						
		+'<li class="edicio-popup"><a id="feature_edit##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-map-marker verd" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Estils')+'"></span></a>   </li>'
		+'<li class="edicio-popup"><a id="feature_move##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-move magenta" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Editar')+'"></span></a>   </li>'
		+'<li class="edicio-popup"><a id="feature_remove##'+player._leaflet_id+'##'+type+'" lang="ca" href="#"><span class="glyphicon glyphicon-trash vermell" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Esborrar')+'"></span></a>   </li>';
	
	if (player.properties.estil) {
		html+='<li class="edicio-popup" id="feature_data_table_'+player._leaflet_id+'"><a id="feature_data_table##'+player._leaflet_id+'##'+type+'##'+player.properties.capaLeafletId+'##" lang="ca" href="#"><span class="glyphicon glyphicon-list-alt blau" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Dades')+'"></span></a>   </li>';					
	}
	else {
		html+='<li class="edicio-popup"><span class="glyphicon glyphicon-list-alt blau" data-toggle="tooltip" data-placement="bottom" title="'+window.lang.translate('Dades')+'"></span>  </li>';					
	}
	
	html+='<li class="edicio-popup"><a class="faqs_link" href="http://betaportal.icgc.cat/wordpress/faq-dinstamaps/#finestrapunt" target="_blank"><i class="fa fa-question-circle-o fa-lg fa-fw"></i></a></span></li>';
	
	html+='</ul>'														
	+'</div>'
	
	+'</div>'	
	+'<div class="popup_edit">'
	+'<div style="display:block" id="feature_txt">'
	+'<input class="form-control" id="titol_edit" type="text" value="'+auxNom+'" placeholder="">'
	+'<textarea id="des_edit" class="form-control" rows="2">'+auxText+'</textarea>'	;
	if (player.options.tipus=="marker" && auxLat!=undefined && auxLon!=undefined) {
		html+='<input class="form-control" id="lat" type="text" value="'+auxLat+'" placeholder="" disabled>'
		+'<input class="form-control" id="lon" type="text" value="'+auxLon+'" placeholder="" disabled>';
	}
	html+='</div>'	
	+'<div  style="display:block" id="capa_txt">'
	+'<div id="layer_accio"></div>'
	+'<input class="form-control" id="capa_edit" type="text" value="'+player.properties.capaGrup+'" placeholder="">'
	+'</div>'
	+'<div class="modal-footer">'
	+'<ul class="bs-popup">'
	+'<li><a id="feature_no##'+player._leaflet_id+'##'+type+'"  class="btn btn-default btn-xs">'+window.lang.translate('Cancel·lar')+'</a></li>'			
	+'<li><a id="feature_ok##'+player._leaflet_id+'##'+type+'"  class="btn btn-success btn-xs">'+window.lang.translate('Acceptar')+'</a></li>'								
	+'</ul>'														
	+'</div>'								
	+'</div>'								
	+'</div>';
	return html;
}

function generaNovaCapaUsuari(feature,nomNovaCapa){
	
	/*NOU MODEL: Crear nova visualització*/
	var data ={
			uid: Cookies.get('uid'),
			nom: nomNovaCapa,
			mapBusinessId: url('?businessid'),
			geometryType: feature.properties.tipusFeature,
//				tipus : tem_origen,//no cal, per defecte li posa origen a servidor
//				calentas: false,
//				order: controlCapes._lastZIndex+1,
			activas: true,
			visibilitats: true,				
			publica : true				
	};		
	
	createVisualitzacioLayer(data).then(function(results){
//			
		if(results.status === 'OK'){
			
			capaUsrActiva2= new L.FeatureGroup();
			capaUsrActiva2.options = {
				businessId : results.results.businessId,
				nom : nomNovaCapa,
//				tipus: t_tematic,
				tipus: t_visualitzacio,
				geometryType : feature.properties.tipusFeature
//					zIndex : controlCapes._lastZIndex//+1		
			};
			//Afegim nova capa al combo
			jQuery('#cmbCapesUsr-'+feature._leaflet_id+'-'+feature.properties.tipusFeature+'').append("<option selected value=\""+results.results.businessId+"\">"+nomNovaCapa+"</option>");	
			jQuery('.popup_pres').show();
			jQuery('.popup_edit').hide();
			
			map.addLayer(capaUsrActiva2);
			capaUsrActiva2.options.zIndex = controlCapes._lastZIndex+1;
			controlCapes.addOverlay(capaUsrActiva2,	capaUsrActiva2.options.nom, true);
			controlCapes._lastZIndex++;
			activaPanelCapes(true);			
			
			var features = {
					type: feature.properties.tipusFeature,
					id:3124,
					businessId: feature.properties.businessId,//Bid de la geometria q estas afegint
					properties: feature.properties.data,
					estil: feature.properties.estil,
					geometry: feature.properties.feature.geometry
				};
			
			features = JSON.stringify(features);
			
			data= {
				toBusinessId: results.results.businessId,//'4c216bc1cdd8b3a69440b45b2713b000',//bID de la visualitzacio-capa
				fromBusinessId: feature.properties.capaBusinessId,//'4c216bc1cdd8b3a69440b45b2713b001',//bID de la visualitzacio-capa
				uid: Cookies.get('uid'),
				features: features
			}	
			
			moveGeometriaToVisualitzacio(data).then(function(resultsMove) {
				console.debug("moveGeometriaToVisualitzacio:"+ resultsMove.status);
				if(resultsMove.status === 'OK'){
					var layer=feature._leaflet_id;
					if(capaUsrActiva) capaUsrActiva.removeLayer(feature);
					capaUsrActiva2.addLayer(feature);//.on('layeradd', objecteUserAdded);
					//feature.openPopup();
					//Actualitzem capa activa
					if(capaUsrActiva) capaUsrActiva.removeEventListener('layeradd');
					capaUsrActiva = capaUsrActiva2;//map._layers[capaUsrActiva2._leaflet_id];;
					capaUsrActiva.on('layeradd',objecteUserAdded);	
					//Actualitzem properties de la layer
					feature.properties.capaBusinessId = capaUsrActiva.options.businessId;
					feature.properties.capaNom = capaUsrActiva.options.nom;	
					feature.properties.capaLeafletId = capaUsrActiva._leaflet_id;
					feature.properties.estil.businessId = resultsMove.estilBid;
					//Actualitzem popup del marker
//						var html = createPopUpContent(feature,feature.options.tipus);
					//feature.setPopupContent(html);
					map.closePopup();
					feature.openPopup();
					
					//update rangs
				    //getRangsFromLayer(capaUsrActiva);
				    
					//Actualitzem comptador de la capa
				    updateFeatureCount(data.fromBusinessId, data.toBusinessId);		
				    
				    //actualitzacioTematic(toLayer1,toLayer.options.businessId,"3124",obj,features,"modificacio");
				  //Actualitzem l'enllaç d'obrir la finestra de dades
				    console.debug(layer);
				   var htmlDataTable =jQuery("#feature_data_table_"+layer).html();
					var stringsDataTableA = htmlDataTable.split("##");
					jQuery("#feature_data_table_"+layer).html(stringsDataTableA[0]+"##"+stringsDataTableA[1]+"##"+stringsDataTableA[2]+"##"+capaUsrActiva._leaflet_id+"##"+stringsDataTableA[4]);

					
				}else{
					console.debug("moveGeometriaToVisualitzacio ERROR");
				}
			},function(results){
				console.debug("moveGeometriaToVisualitzacio ERROR");
			});
			
		}else{
			console.debug("createVisualitzacioLayer ERROR");
		}
	});		

}

function moveFeatureToLayer(feature_businessId,layer_fromBusinessId,layer_toBusinessId){

	/*NOU MODEL*/
	var features = {
			type: feature.options.tipus,
			id:3124,
			businessId: feature.properties.businessId,//Bid de la geometria q estas afegint
			properties: feature.properties.feature.properties,
			estil: feature.properties.estil,
			geometry: feature.properties.feature.geometry
		};
	
	features = JSON.stringify(features);
	
	data= {
		toBusinessId: results.results.businessId,//'4<KEY>000',//bID de la visualitzacio-capa
		fromBusinessId: feature.properties.capaBusinessId,//'4c216bc1cdd8b3a69440b45b2713b001',//bID de la visualitzacio-capa
		uid: Cookies.get('uid'),
		features: features
	}	
	
	moveGeometriaToVisualitzacio(data).then(function(resultsMove) {
		console.debug("moveGeometriaToVisualitzacio:"+ resultsMove.status);
		if(resultsMove.status === 'OK'){
			
			if(capaUsrActiva) capaUsrActiva.removeLayer(feature);
			capaUsrActiva2.addLayer(feature);//.on('layeradd', objecteUserAdded);
			//feature.openPopup();
			//Actualitzem capa activa
			if(capaUsrActiva) capaUsrActiva.removeEventListener('layeradd');
			capaUsrActiva = capaUsrActiva2;//map._layers[capaUsrActiva2._leaflet_id];;
			capaUsrActiva.on('layeradd',objecteUserAdded);	
			//Actualitzem properties de la layer
			feature.properties.capaBusinessId = capaUsrActiva.options.businessId;
			feature.properties.capaNom = capaUsrActiva.options.nom;	
			feature.properties.capaLeafletId = capaUsrActiva._leaflet_id;
			//Actualitzem popup del marker
//			var html = createPopUpContent(feature,feature.options.tipus);
			//feature.setPopupContent(html);
			map.closePopup();
			feature.openPopup();
			
			//update rangs
		    //getRangsFromLayer(capaUsrActiva);
		    
			var capaEdicio = controlCapes._layers[capaUsrActiva._leaflet_id];
			//recarrego les sublayers de la capa modificada	
			actualitzacioTematic(capaEdicio,layer.properties.capaBusinessId,"3124",feature,features,"modificacio");
			
			//Actualitzem comptador de la capa
		    updateFeatureCount(data.fromBusinessId, data.toBusinessId);					
			
		}else{
			console.debug("moveGeometriaToVisualitzacio ERROR");
		}
	},function(results){
		console.debug("moveGeometriaToVisualitzacio ERROR");
	});		

}

function modeLayerTextEdit(){
	jQuery('#capa_txt').show();
	jQuery('#feature_txt').hide();
	jQuery('.popup_pres').hide();
	jQuery('.popup_edit').show();	
}

function modeEditText(){
	objEdicio.edicioPopup='textFeature';
	jQuery('#capa_txt').hide();
	jQuery('#feature_txt').show();
	var txtTitol=jQuery('#titol_pres').text();
	var txtDesc=jQuery('#descrText').html();
	jQuery('#titol_edit').val(txtTitol);	
	jQuery('#des_edit').val(txtDesc);
	jQuery('.popup_pres').hide();
	jQuery('.popup_edit').show();	
}

/*funcio que actulitza l'estil seleccionat al dialeg d'estils, 
 * amb el de la feature que es col editar 
 * */
function updateDialogStyleSelected(icon){
  
	if(icon.tipus == t_polyline){
		
		canvas_linia.lineWidth = icon.weight;
		canvas_linia.strokeStyle = icon.color;
		
		$("#cmb_gruix_l option[value='"+icon.weight+"']").prop("selected", "selected");
		$('.border_color_linia').css('background-color',icon.color);
		addGeometryInitL(document.getElementById("cv_linia0"));			
		
	}else if(icon.tipus == t_polygon){
		
		canvas_pol.strokeStyle = icon.color;
		canvas_pol.opacity = icon.fillOpacity;
		canvas_pol.fillStyle = icon.fillColor; //rgb2hex(icon.fillColor);
		canvas_pol.lineWidth = icon.weight;
		
		$('.border_color_pol').css('border-color',icon.color);
		$('.fill_color_pol').css('color',icon.fillColor);
		$('.fill_color_pol').css('background-color',icon.fillColor);
		$("#cmb_gruix option[value='"+icon.weight+"']").prop("selected", "selected");
		$("#cmb_trans option[value='"+icon.fillOpacity+"']").prop("selected", "selected");
		
	    addGeometryInitP(document.getElementById("cv_pol0"));
	    
	}else{//es t_marker
		
		//Deselecciono estil al modal 
		jQuery("#div_puntM").removeClass("estil_selected");
		jQuery("#div_puntZ").removeClass("estil_selected");
		jQuery(".bs-glyphicons li").removeClass("estil_selected");		
		
		
		if(icon.isCanvas){//Si es un punt
			
			var midaPunt = getMidaFromRadius(icon.radius);
			
			estilP.iconFons = 'awesome-marker-web awesome-marker-icon-punt_r';
			estilP.iconGlif = 'fa fa-'+icon.icon;
			estilP.colorGlif = icon.iconColor;
			estilP.divColor = icon.fillColor;
			estilP.width = midaPunt+'px';
			estilP.height = midaPunt+'px';

			
			
			
			
			jQuery("#div_puntZ").addClass("estil_selected");
			jQuery("#div_punt9").css("background-color",icon.fillColor);
			$('#cmb_mida_Punt option[value="'+midaPunt+'"]').prop("selected", "selected");
			jQuery("#dv_fill_color_punt").css("background-color",icon.fillColor);
			jQuery("#dv_fill_color_icon").css("background-color",icon.iconColor);
//			
		}else if(icon.markerColor.indexOf("punt_r")!=-1){
			
			var licon = icon.icon.split(" ");
			midaPunt = getMidaFromFont(licon[1]);
			
			estilP.iconFons = 'awesome-marker-web awesome-marker-icon-punt_r';
			estilP.iconGlif = 'fa fa-'+icon.icon;
			estilP.colorGlif =icon.iconColor;
			estilP.fontsize = licon[1];	
			estilP.width = midaPunt+'px';
			estilP.height = midaPunt+'px';
			estilP.divColor = icon.divColor;
			
		
			jQuery("#div_puntZ").addClass("estil_selected");
			jQuery("#div_punt9").css("background-color",icon.divColor);
			$('#cmb_mida_Punt option[value="'+midaPunt+'"]').prop("selected", "selected");
			
			jQuery("#dv_fill_color_punt").css("background-color",icon.divColor);
			jQuery("#dv_fill_color_icon").css("background-color",icon.iconColor);				
			
			jQuery(".bs-glyphicons li .fa-"+licon[0]).parent('li').addClass("estil_selected");
			jQuery("#dv_fill_color_icon").css("background-color",estilP.colorGlif);	
			jQuery('.bs-glyphicons li').css('color',estilP.colorGlif);
			if(estilP.colorGlif=="#FFFFFF"){
				jQuery('.bs-glyphicons li').css('background-color','#aaaaaa');	
			}else{
				jQuery('.bs-glyphicons li').css('background-color','#FFFFFF');	
			}			
			
			
		}else{//Si es marker
			
			
			
			estilP.iconFons = icon.className+'-web awesome-marker-icon-'+icon.markerColor;
			estilP.iconGlif = 'fa fa-'+icon.icon;
			estilP.colorGlif = icon.iconColor;
			estilP.fontsize = '14px';
			estilP.divColor = 'transparent';
			estilP.width = '28px';
			estilP.height = '42px';
			
			
			
			jQuery("#div_puntM").addClass("estil_selected");
			jQuery("#dv_fill_color_marker").css("background-color",getColorFromClass(icon.markerColor));
			jQuery('#div_punt_1').removeClass().addClass('awesome-marker-web awesome-marker-icon-'+icon.markerColor);
			
			jQuery(".bs-glyphicons li .fa-"+icon.icon).parent('li').addClass("estil_selected");
			jQuery("#dv_fill_color_icon").css("background-color",estilP.colorGlif);
			jQuery('.bs-glyphicons li').css('color',estilP.colorGlif);
			if(estilP.colorGlif=="#FFFFFF"){
				jQuery('.bs-glyphicons li').css('background-color','#aaaaaa');	
			}else{
				jQuery('.bs-glyphicons li').css('background-color','#FFFFFF');	
			}			
		}
		
		jQuery('#div_punt0').removeClass();
		jQuery('#div_punt0').addClass(estilP.iconFons+" "+estilP.iconGlif);
		jQuery('#div_punt0').css('width',estilP.width);
		jQuery('#div_punt0').css('height',estilP.height);	
		jQuery('#div_punt0').css('font-size',estilP.fontsize);
		jQuery('#div_punt0').css('background-color',estilP.divColor);
		jQuery('#div_punt0').css('color',estilP.colorGlif);			
	}
}

function getColorFromClass(classe){
	switch (classe)
	{
		case 'orange':
		  return '#ffc500';
		case 'darkorangeb':
		  return '#ff7f0b';
		case 'red':
		  return '#ff4b3a';
		case 'purple':
		  return '#ae59b9';	
		case 'blue':
		  return '#00afb5';
		case 'green':
		  return '#7cbd00';
		case 'darkgray':
		  return '#90a6a9';
		case 'gray':
		  return '#ebf0f1';		  
		 default:
			 return '#ffc500';
	} 		
}

function updateFeatureCount(fromBusinessId, toBusinessId){
	
	//Actualitzem comptador de la capa
	if(fromBusinessId){
		var sFromCount = $("#count-"+fromBusinessId).html();
		if (sFromCount!=undefined){
			sFromCount = sFromCount.replace("(", " ");
			sFromCount = sFromCount.replace(")", " ");	
			var fromCount = parseInt(sFromCount.trim());
			fromCount=fromCount-1;
			$("#count-"+fromBusinessId).html(' ('+fromCount+')');
		}
	}

	if(toBusinessId){
		var sToCount = $("#count-"+toBusinessId).html();
		if (sToCount!=undefined){
			sToCount = sToCount.replace("(", " ");
			sToCount = sToCount.replace(")", " ");	
			var toCount = parseInt(sToCount.trim());
			toCount=toCount+1;
			$("#count-"+toBusinessId).html(' ('+toCount+')');		
		}
	}
//	console.debug("Fi updateFeatureCount");
}

function addDrawTooltips() {
	L.drawLocal = {
		draw : {
			handlers : {
				marker : {
					
					tooltip : {
						start : window.lang.translate('Fes clic al mapa per posar un punt')
					}
				},
				polygon : {
					tooltip : {
						start : window.lang.translate('Clica per començar a dibuixar una àrea'),
						cont : window.lang.translate('Clica per continuar dibuixant una àrea'),
						end : window.lang.translate('Clica el primer punt per tancar aquesta àrea')
					}
				},
				polyline : {
					error : '<strong>Error:</strong> àrees no es poden creuar!',
					
					tooltip : {
						start : window.lang.translate('Clica per començar a dibuixar una línia'),
						cont : window.lang.translate('Clica per continuar dibuixant una línia'),
						end : window.lang.translate('Clica el darrer punt per acabar la línia')
					}
				}
			}
		},
		edit : {
			handlers : {
				edit : {
					
					tooltip : {
						text : window.lang.translate("Arrossega els vèrtex o el punt per editar l'objecte"),
						subtext : window.lang.translate('Fes clic sobre el mapa per finalitzar')
					}
				}
			}
		}
	};
	return L.drawLocal;
}

function addHtmlInterficieDraw(){
	jQuery("#funcio_draw").append(
		'<h5 lang="ca" id="funcio_draw_titol_1">Situar un punt</h5>'+
		'	<div class="add_costat_r" style="margin-right: 33%;">'+
		'	<div lang="ca" id="div_mes_punts" class="icon-add taronja" data-toggle="tooltip" data-lang-title="Més tipus de punts" title="Més tipus de punts"></div>'+
		'</div>'+
		'<div style="height:50px ">'+
		'	<div id="div_punt" class="dibuix_punt" data-toggle="tooltip" data-lang-title="Clica per situar un punt" title="Clica per situar un punt">'+
		'	</div>'+
		'</div>'+
		'<h5 lang="ca" id="funcio_draw_titol_2">Dibuixar una línia o un polígon</h5>'+
		'<div class="div_auto">'+
		'	<div id="div_linia" class="dibuix_linia" data-toggle="tooltip" data-lang-title="Clica per començar a dibuixar una línia" title="Clica per començar a dibuixar una línia">'+
		'	<canvas id="cv_linia" width="40" height="40"></canvas>'+
		'	</div>'+
		'	<div class="add_costat">'+
		'		<div lang="ca" id="div_mes_linies" class="icon-add taronja" data-toggle="tooltip" data-lang-title="Més estils de línia" title="Més estils de línia"></div>'+
		'	</div>'+
		'</div>'+
		'<div class="div_auto">'+
		'	<div id="div_area" class="dibuix_poligon" data-toggle="tooltip" data-lang-title="Clica per començar a dibuixar una àrea" title="Clica per començar a dibuixar una àrea">'+
		'	<canvas id="cv_pol" width="40" height="40"></canvas>'+
		'	</div>'+
		'	<div class="add_costat">'+
		'		<div lang="ca" id="div_mes_arees" class="icon-add taronja" data-toggle="tooltip" data-lang-title="Més estils d\'àrees" title="Més estils d\'àrees"></div>'+
		'	</div>'+
		'</div>'
	);
	
	$('#div_punt').tooltip({placement : 'bottom',container : 'body'});
	$('#div_linia').tooltip({placement : 'bottom',container : 'body'});
	$('#div_area').tooltip({placement : 'bottom',container : 'body'});	
	
	$('#div_mes_punts').tooltip({placement : 'right',container : 'body'});
	$('#div_mes_linies').tooltip({placement : 'right',container : 'body'});
	$('#div_mes_arees').tooltip({placement : 'right',container : 'body'});	
}

function activarSnapping(capaEdicio){
	if (capaEdicio.getLayers()[0].snapediting==undefined){
		//Activate snapping
		if (capaEdicio.getLayers()[0].properties.tipusFeature != undefined && capaEdicio.getLayers()[0].properties.tipusFeature=="marker"){
			try{
				capaEdicio.getLayers()[0].editing = new L.Handler.MarkerSnap(map, capaEdicio.getLayers()[0],{snapDistance:10});
				capaEdicio.getLayers()[0].snapediting = new L.Handler.MarkerSnap(map, capaEdicio.getLayers()[0],{snapDistance:10});
			}catch(exc){
				
			}
		}
		else{					
			capaEdicio.getLayers()[0].editing = new L.Handler.PolylineSnap(map, capaEdicio.getLayers()[0],{snapDistance:10});
			capaEdicio.getLayers()[0].snapediting = new L.Handler.PolylineSnap(map, capaEdicio.getLayers()[0],{snapDistance:10});
		}
	}
		for(var i = 0;i < guideLayers.length; i++) {
			 // Add every already drawn layer to snap list
			capaEdicio.getLayers()[0].snapediting.addGuideLayer(guideLayers[i]);
	        // Add the currently drawn layer to the snap list of the already drawn layers
			if ( guideLayers[i].snapediting!=undefined){
				guideLayers[i].snapediting.addGuideLayer(capaEdicio.getLayers()[0]);
				guideLayers[i].snapediting.enable();
				if (guideLayers[i].editing!=undefined) guideLayers[i].editing.disable();
				if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable(); 
			}
			else {
				if (guideLayers[i].properties.tipusFeature != undefined && guideLayers[i].properties.tipusFeature=="marker"){
					try{
						guideLayers[i].snapediting = new L.Handler.MarkerSnap(map, layer,{snapDistance:10});
					}catch(exc){
						
					}
				}
				else{
					guideLayers[i].snapediting = new L.Handler.PolylineSnap(map, capaEdicio.getLayers()[0],{snapDistance:10});
				}
				if (guideLayers[i].snapediting!=undefined) {
					guideLayers[i].snapediting.addGuideLayer(capaEdicio.getLayers()[0]);
					guideLayers[i].snapediting.enable();
				}
				if (guideLayers[i].editing!=undefined)  guideLayers[i].editing.disable();
				if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable(); 
			}
			if (capaEdicio.getLayers()[0].properties.tipusFeature != undefined && capaEdicio.getLayers()[0].properties.tipusFeature=="marker"){
				try{
					if (guideLayers[i].editing!=undefined)  guideLayers[i].editing.disable();
					if (guideLayers[i].dragging!=undefined) guideLayers[i].dragging.enable();
				}catch(exc){
					
				}
			}
		 }
		try{
			capaEdicio.getLayers()[0].snapediting.enable();
		}
		catch(exc){
			
		}
		// capaEdicio.getLayers()[0].editing.enable();
		  // Add to drawnItems
		 drawnItems.addLayer(capaEdicio.getLayers()[0]);
		 // Add newly drawn feature to list of snappable features
		guideLayers.push(capaEdicio.getLayers()[0]);
}



<file_sep>/geocatweb/js/geocat.constants.js
//Global vars
var map, controlCapes, hashControl;
var mapConfig = {};

var factorH = 50;
var factorW = 0;

var capaUsrPunt, capaUsrLine, capaUsrPol,capaUsrActiva;

var initMevesDades = false;
var download_layer;
var lsublayers = [];
var tipus_user;

//Arrays control elements repetits a la llegenda
var controlLegendPoint = [];//Boles
var controlLegendMarker = [];//Pintxos
var controlLegendLine = [];
var controlLegendPol = [];
var mapLegend = {};
var downloadableData = {};
var _UsrID;

var dades1;


//Contants del mapa 3D
var estatMapa3D=false;

//Evitem error javascript a les pagines html que no carreguen la llibreria de leaflet
if((urlApp.indexOf('mapa')!=-1)||(urlApp.indexOf('visor')!=-1)){
//default geometries style
var estilP={
		icon : '',
		iconFons:'awesome-marker-web awesome-marker-icon-orange',
		iconGlif:'fa fa-',
		colorGlif:'#333333',
		fontsize:'14px',
		size:'28'
	};

var default_line_style = {
	    weight: 3,
	    color: '#FFC400',
	    opacity:1,
	    dashArray: '3',
	    lineCap:'round',
	    lineJoin:'round'
	};

var default_area_style = {
	    weight: 3,
	    opacity: 1,
	    color: '#FFC400',
	    dashArray: '3',
	    fillColor: "rgb(255,196,0)",//hexToRgb('#FFC400'),
	    borderColor: '#FFC400',
	    borderWidth: '3',
	    fillOpacity: 0.5
	};

var default_marker_style = {
		icon : '',
		markerColor : 'orange',
		divColor:'transparent',
		iconAnchor : new L.Point(14, 42),
		iconSize : new L.Point(28, 42),
		iconColor : '#000000',
		prefix : 'fa',
		isCanvas:false,
		radius:6,
		opacity:1,
		weight : 2,
		fillOpacity : 0.9,
		color : "#ffffff",
		fillColor :"transparent"
	};

var default_circulo_style = {
		isCanvas:true,
		simbolSize: 6,
		borderWidth: 2,
		opacity: 90,
		borderColor : "#ffffff",
		color :"#FFC500",
		lineWidth: 3,
	};

var default_circuloglyphon_style = {
		icon : '',
		markerColor: 'punt_r',
		prefix : 'fa',
		divColor:'transparent',
		iconAnchor : new L.Point(15, 15),
		iconSize : new L.Point(30, 30),
		iconColor : '#000000',
		isCanvas:false,
		radius:6,
		opacity:1,
		weight : 2,
		fillOpacity : 0.9,
		color : "#ffffff",
		fillColor :"#FFC500"
	};

var default_onsoc_style = {
		icon : '',
		markerColor : 'red',
		divColor:'transparent',
		iconAnchor : new L.Point(14, 42),
		iconSize : new L.Point(28, 42),
		iconColor : '#000000',
		prefix : 'fa',
		isCanvas:false,
		radius:6,
		opacity:1,
		weight : 2,
		fillOpacity : 0.9,
		color : "#ffffff",
		fillColor :"transparent"
	};
}

//constants
var t_geojsonvt = "geojsonvt";
var t_dades_obertes = "dades obertes";
var t_wms = "wms";
var t_json = "json";
var t_xarxes_socials = "xarxes socials";
var t_tematic = "tematic";
var t_visualitzacio = "visualitzacio";
var t_url_file = "url_file";
var t_vis_wms = "vis_wms";
var t_vis_wms_noedit = "vis_wms_noeditable";

/**tipus estandar instamaps**/
var t_polyline = "polyline";
var t_polygon = "polygon";
var t_marker = "marker";
/************************/

var t_multiple = "multiple";
var t_point = "point";
var t_multipoint = "multipoint";
var t_linestring = "linestring";
var t_multilinestring = "multilinestring";
var t_multipolygon = "multipolygon";
var t_heatmap = "heatmap";
var t_cluster = "cluster";
var t_size = "size";
var tem_origen = "origenTematic";
var tem_simple = "simpleTematic";
var tem_clasic = "clasicTematic";
var tem_size = "sizeTematic";
var tem_heatmap = "heatmapTematic";
var tem_cluster = "clusterTematic";
var tem_heatmap_wms = "heatmapTematic_wms";
var tem_cluster_wms = "clusterTematic_wms";
var from_creaPopup = "creaPopup";
var from_creaCapa = "creaCapa";
var visibilitat_open = 'O';
var visibilitat_privat = 'P';

var t_file_csv = ".csv";
var t_file_txt = ".txt";
var t_file_gpx = ".gpx";
var t_file_kml = ".kml";
var t_file_gml = ".gml";
var t_file_wkt = ".wkt";
var t_file_json = ".json";
var t_file_geojson = ".geojson";
var t_file_topojson = ".topojson";
var t_file_shp = ".shp";
var t_file_dxf = ".dxf";
var t_file_dgn = ".dgn";
var t_file_xls = ".xls";
var t_file_xlsx = ".xlsx";

var t_user_loginat = '1#';
var t_user_random = '0#';

var num_max_pintxos = 250;
var capesOrdre_sublayer = "sublayer";//10000;

var msg_noguarda = "Per publicar o compartir el mapa has d'iniciar sessió";

var CAPTURA_MAPA = "captura_mapa";
var CAPTURA_GALERIA = "captura_galeria";
var CAPTURA_INFORME = "captura_informe";
var CAPTURA_FONS = "captura_fons";
var CAPTURA_GEOPDF = "captura_geopdf";
var CAPTURA_MAPA_GEOTIFF="captura_mapa_geotiff";
var CAPTURA_MAPA_GEOPACKAGE="captura_mapa_geopackage";
var NODATA_VALUE = "nodata";
var NODATA_COLOR = "#CCCCCC";
var NODATA_MIDA = 10;

var TIPUS_APLIACIO_INSTAMAPS = 1;
var TIPUS_APLIACIO_GEOLOCAL = 2;
var TIPUS_APLIACIO_AOC = 3;

//VAR per nou model de dades
var nou_model = true;

var instamaps_email = "<EMAIL>";
//var curs_instamaps = "1er curs InstaMaps";
//var curs_instamaps = "2n curs InstaMaps";
//var curs_instamaps = "3r curs InstaMaps";
//var curs_instamaps = "4rt curs InstaMaps";
var curs_instamaps = "5e curs InstaMaps";


//Llistat exemples de dades externes
var llista_dadesExternes = {
		"dadesExternes" : [

				{
	                "titol" : "Actes president.cat",
	                "ORGANITZAC" : "president.cat",
	                "urlOrganitzacio" : "http://www.president.cat",
	                "urlDadesExternes" : "http://www.president.cat/pres_gov/dades/president/actes-territori-ca.json?"
				},
   				{
	                "titol" : "Plaques Tectòniques",
	                "ORGANITZAC" : "earthquake.usgs.gov",
	                "urlOrganitzacio" : "http://earthquake.usgs.gov",
	                "urlDadesExternes" : "http://earthquake.usgs.gov/learn/plate-boundaries.kmz",
					"formatDadesExternes": t_file_kml,
					"epsgDadesExternes":"EPSG:4326"
				},


				{
					"titol" : "Ciutats del món",
					"ORGANITZAC" : "Wikipedia",
					"urlOrganitzacio" : "http://en.wikipedia.org/wiki/List_of_cities_by_longitude",
					"urlDadesExternes" : "https://raw.githubusercontent.com/mahemoff/geodata/master/cities.geojson",
					"formatDadesExternes": t_file_geojson,
					"epsgDadesExternes":"EPSG:4326"
				},
				{
					"titol" : "<NAME>",
					"ORGANITZAC" : "Wikimedia Foundation",
					"urlOrganitzacio" : "https://github.com/wikimedia",
					"urlDadesExternes" : "https://raw.githubusercontent.com/wikimedia/limn-data/master/geo/maps/world-countries.json",
					"formatDadesExternes": t_file_geojson,
					"epsgDadesExternes":"EPSG:4326"
				},
				{
					"titol" : "Huracans a l'Atlàntic al 2004",
					"ORGANITZAC" : "Unisys weather",
					"urlOrganitzacio" : "http://weather.unisys.com/hurricane/atlantic/2004H/index.html",
					"urlDadesExternes" : "https://raw.githubusercontent.com/colemanm/hurricanes/master/fl_2004_hurricanes.geojson",
					"formatDadesExternes": t_file_geojson,
					"epsgDadesExternes":"EPSG:4326"
				},

				{//https://github.com/FCC/lpfmpoints
					"titol" : "U.S. Low Power FM station",
					"ORGANITZAC" : "LPFM",
					"urlOrganitzacio" : "http://www.fcc.gov/encyclopedia/low-power-fm-broadcast-radio-stations-lpfm",
					"urlDadesExternes" : "https://raw.githubusercontent.com/FCC/lpfmpoints/gh-pages/data/lpfm_points.geojson",
					"formatDadesExternes": t_file_geojson,
					"epsgDadesExternes":"EPSG:4326"
				},

				{
					"titol" : "<NAME>",
					"ORGANITZAC" : "Gencat",
					"urlOrganitzacio" : "http://www.gencat.cat/",
					"urlDadesExternes" : "http://www.gencat.cat/opendata/recursos/rutes/cami_de_sant_jaume.kml",
					"formatDadesExternes": t_file_kml,
					"epsgDadesExternes":"EPSG:4326"
				}
		]
};

var TIPUS_ENTITATS_GEOLOCAL = [2,3,4,5,6,7,8,9];
var TIPUS_ADMIN = 0;
var TIPUS_INSTAMAPS = 1;
var TIPUS_AOC = 10;

var guideLayers = new Array();
<file_sep>/geocatweb/js/instamaps.visor.app-1.0.0.js
/**
 * require geocat.web-1.0.0
 * require url https://github.com/websanova/js-url
 * require geocat.google-analytics.js
 * requier geocat.utils
 */
var visorOptions = {
	uid: url('?uid') || null,
	urlwms: url('?urlwms') || null,
	layername: url('?layername') || null,
	type: url('?type') || null,
	url: url('?url') || null,
	q: url('?q') || null,
	businessid: url('?businessid') || null,
	mapacolaboratiu: url('?mapacolaboratiu') || null,
	embed: url('?embed') || null,
	llegenda: url('?llegenda') || null,
	mouseposition: url('?mouseposition') || null,
	layerscontrol: url('?layerscontrol') || null,
	printcontrol: url('?printcontrol') || null,
	minimapcontrol: url('?minimapcontrol') || null,
	snapshotcontrol: url('?snapshotcontrol') || null,
	geopdfcontrol: url('?geopdfcontrol') || null,
	widgetscontrol: url('?widgetscontrol') || null,
	fonscontrol: url('?fonscontrol') || null,
	sharecontrol: url('?sharecontrol') || null,
	likecontrol: url('?likecontrol') || null,
	searchcontrol: url('?searchcontrol') || null,
	routingcontrol: url('?routingcontrol') || null,
	openinstamaps: url('?openinstamaps') || null,
	scalecontrol: url('?scalecontrol') || null,
	control3d: url('?control3d') || null,
	view3d: url('?3d') || null,
	homecontrol: url('?homecontrol') || null,
	locationcontrol: url('?locationcontrol') || null,
	zoomcontrol: url('?zoomcontrol') || null,
	staticmap: url('?staticmap') || null,
	navbar: url('?navbar') || null,
	rtoolbar: url('?rtoolbar') || null,
	ltoolbar: url('?ltoolbar') || null,
	appmodul: url('?appmodul') || null,
	lat : url("?lat") || null,
	lon : url("?lon") || null,
	zoom : url("?zoom") || null,
	text: url("?text") || null,
	link: url("?link") || null,
	appname: url("?appname") || null,
	fons: url("?fons") || null,
	INE10: url("?INE10") || null, 
	random: url("?random") || null
};

var visor; 

jQuery(document).ready(function() {
	//TODO ver si esto es mejor ponerlo cuando ya esté cargado todo el visor para cojer bien el titulo, etc.
	//$.publish('trackPageview', null);
	
	var tipus_user = defineTipusUser();  //geocat.web-1.0.0
	
	visorOptions.tipusUser = tipus_user;
		
	visor = Visor(visorOptions).draw();
	
}); // Final document ready

<file_sep>/geocatweb/js/geocat.mapa.json.js
//var _htmlServeisJSON = [];
//
//_htmlServeisJSON.push('<div class="panel-success"><div panel-heading">');
//
//_htmlServeisJSON.push('<div class="input-group txt_ext"><input type="text" lang="ca" id="txt_URLJSON" style="height:33px" placeholder="Entrar URL servei JSON" value="" class="form-control">');
//_htmlServeisJSON.push('<span class="input-group-btn"><button class="btn btn-success" id="bt_connJSON"  type="button"><span class="glyphicon glyphicon-play"></span></button></span>');
//
////_htmlServeisJSON.push('<div class="small"
//
////http://www.president.cat/pres_gov/dades/president/actes-territori-ca.json?
//
//_htmlServeisJSON.push('</div>');
//_htmlServeisJSON.push('</div>');
//_htmlServeisJSON.push('<div style="height:230px;overflow:auto" id="div_layersJSON"  class="tbl"></div>');
//_htmlServeisJSON.push('<div id="div_emptyJSON" style="height: 35px;margin-top: 2px"></div>');

var respostaJSON;
var urlJSON;
function getServeiJSONP(purlJson) {
	urlJSON = purlJson;
	jQuery("#txt_URLJSON");
	var _htmlJSONFields = [];



		getJSONPServei(purlJson).then(function(results) {
							var op = [];
							if (jQuery.isArray(results)) {
								respostaJSON = results;
							} else {
								for (key in results) {
									if (jQuery.isArray(results[key])) {
										respostaJSON = results[key];
									}
								}
							}

							if(purlJson.indexOf(paramUrl.presidentJSON)!= -1){
							
							creaCapaFromJSON(1);
							
							}else{
							
							if (!jQuery.isArray(respostaJSON)) {
								alert(window.lang.translate("No s'ha interpretar l'estructura del JSON"));
								return;
							}
							op.push("<option value='null'>"
									+ window.lang.translate('Selecciona un camp')
									+ "</option>");
							for (key in respostaJSON[0]) {
								op.push("<option value=" + key + ">" + key
										+ "</option>");
							}

							//jQuery('#div_layersJSON').removeClass('waiting_animation');
							jQuery('#div_layersJSON').empty();
							jQuery('#div_emptyJSON').empty();

							_htmlJSONFields.push('<ul class="bs-dadesO_JSON">');

							_htmlJSONFields.push("<li><label>"
									+ window.lang.translate('Camps necessaris')
									+ "</label></li>");
							_htmlJSONFields
									.push("<li><label>"
											+ window.lang
													.convert('Selecciona el camp corresponent')
											+ "</label></li>");

							_htmlJSONFields
									.push("<li>"
											+ window.lang.translate('Coordenada X o Longitud')
											+ "</li>");
							_htmlJSONFields
									.push("<li><select  id='cmd_json_x'>"
											+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push("<li>"
									+ window.lang.translate('Coordenada Y o Latitud') + "</li>");
							_htmlJSONFields.push("<li><select id='cmd_json_y'>"
									+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push("<li><label>"
									+ window.lang.translate('Opcionals')
									+ "</label></li>");
							_htmlJSONFields.push("<li></li>");

							_htmlJSONFields.push("<li>"
									+ window.lang.translate('Títol') + "</li>");
							_htmlJSONFields
									.push("<li><select  id='cmd_json_titol'>"
											+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push("<li>"
									+ window.lang.translate('Descripció')
									+ "</li>");
							_htmlJSONFields
									.push("<li><select  id='cmd_json_desc'>"
											+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push("<li>"
									+ window.lang.translate('Imatge') + "</li>");
							_htmlJSONFields
									.push("<li><select  id='cmd_json_img'>"
											+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push("<li>"
									+ window.lang.translate('Vincle') + "</li>");
							_htmlJSONFields
									.push("<li><select id='cmd_json_vin'>"
											+ op.join(" ") + "</select></li>");

							_htmlJSONFields.push('</ul>');

							jQuery('#div_layersJSON').html(
									_htmlJSONFields.join(" "));
							jQuery('#div_emptyJSON')
									.html(
											'<div style="float:right"><button lang="ca" id="bt_addJSON" class="btn btn-success" >'
													+ window.lang
															.convert("Mapificar")
													+ '</button></div>');

							$('#cmd_json_x option:contains("long")').prop(
									'selected', true);
							$('#cmd_json_x option:contains("lng")').prop(
									'selected', true);

							$('#cmd_json_y option:contains("latitu")').prop(
									'selected', true);
							$('#cmd_json_y option:contains("lat")').prop(
									'selected', true);

							
							
							}
									
						});
		
		jQuery(document).on('click', "#bt_addJSON", function(e) {
			creaCapaFromJSON(0);
		});		
		

//	} else {
//
//		alert(window.lang.translate("La URL no sembla vàlida"));
//		return;
//	}
}



function creaCapaFromJSON(directe) {

	_gaq.push(['_trackEvent', 'mapa', tipus_user+'dades externes', urlJSON, 1]);
//	_kmq.push(['record', 'dades externes', {'from':'mapa', 'tipus user':tipus_user, 'tipus':'json', 'url':urlJSON}]);
	
	
	var cmd_json_x = "longitude";
			var cmd_json_y = "latitude";
			var cmd_json_titol ="titular";
			var cmd_json_desc = "municipio";
			var cmd_json_img = "imagen";
			var cmd_json_vin = "url";
	
	
	if(directe!=1){
		cmd_json_x = jQuery('#cmd_json_x').val();
		cmd_json_y = jQuery('#cmd_json_y').val();
		cmd_json_titol = jQuery('#cmd_json_titol').val();
		cmd_json_desc = jQuery('#cmd_json_desc').val();
		cmd_json_img = jQuery('#cmd_json_img').val();
		cmd_json_vin = jQuery('#cmd_json_vin').val();	
	}
	
	if ((cmd_json_x == "null") || (cmd_json_y == "null")) {

		alert(window.lang.translate("Els camps de coordenades no poden estar buits"));
		return;

	} else {

		//nom per defecte agafat de la url del json a mostrar
		var paraules = urlJSON.split("/");
		var paraula = paraules[paraules.length-1].split(".");
		var nomCapaJson = paraula[0];
		if(!nomCapaJson) nomCapaJson = 'Capa JSON';
		
		var capaJSON = new L.FeatureGroup();
		capaJSON.options = {
			businessId : -1,
			nom : nomCapaJson,//+' '+ (parseInt(controlCapes._lastZIndex) + 1),
			tipus:t_json,
			url: urlJSON
//			zIndex : controlCapes._lastZIndex// + 1
		};
		
		var param_estil = 'json';
		if(urlJSON.indexOf("president")!=-1) param_estil = 'json_president';
		var estil_do = retornaEstilaDO(param_estil);
		
		if(typeof url('?businessid') == "string"){
			var data = {
				uid:Cookies.get('uid'),
				mapBusinessId: url('?businessid'),
				serverName: nomCapaJson,//+' '+ (parseInt(controlCapes._lastZIndex) + 1),
				serverType: t_json,
				calentas: false,
	            activas: true,
	            visibilitats: true,
	            order: controlCapes._lastZIndex+1,
	            epsg: '4326',
	            imgFormat: 'image/png',
	            infFormat: 'text/html',
	            tiles: true,	            
	            transparency: true,
	            opacity: 1,
	            visibilitat: 'O',
	            url: urlJSON,//Provar jQuery("#txt_URLJSON")
	            calentas: false,
	            activas: true,
	            visibilitats: true,
	            options: '{"x":"'+cmd_json_x+'", "y":"'+cmd_json_y+'","titol":"'+cmd_json_titol+'","descripcio":"'+cmd_json_desc+'", "imatge":"'+cmd_json_img+'","vincle":"'+cmd_json_vin+'","estil_do":{"radius":"'+estil_do.radius+'","fillColor":"'+estil_do.fillColor+'","color":"'+estil_do.color+'","weight":"'+estil_do.weight+'","opacity":"'+estil_do.opacity+'","fillOpacity":"'+estil_do.fillOpacity+'","isCanvas":"'+estil_do.isCanvas+'"}}'
			};
			
			createServidorInMap(data).then(function(results){
				if (results.status == "OK"){
					
					for (key in respostaJSON) {
						var lat = respostaJSON[key][cmd_json_y];
						var lon = respostaJSON[key][cmd_json_x];
						pp = L.circleMarker([ lat, lon ], estil_do)

						pp.properties = {};
						var empty = true;
						
						if (cmd_json_titol == "null") {
							pp.properties.nom = ""
								
						} else {
							pp.properties.nom = respostaJSON[key][cmd_json_titol];
							empty = empty && false;
						}
						if (cmd_json_desc == "null") {
							pp.properties.text = ""
						} else {
							pp.properties.text = respostaJSON[key][cmd_json_desc];
							empty = empty && false;
						}
						if (cmd_json_img == "null") {
							pp.properties.img = ""
						} else {
							pp.properties.img = '<img width="250px" src="'
									+ respostaJSON[key][cmd_json_img] + '">';
							empty = empty && false;
						}
						if (cmd_json_vin == "null") {
							pp.properties.vincle = ""
						} else {
							pp.properties.vincle = '<a href="'
									+ respostaJSON[key][cmd_json_vin]
									+ '" target="_blank">'
									+ respostaJSON[key][cmd_json_vin] + '</a>';
							empty = empty && false;
						}

						if(!empty){
							pp.bindPopup("<div id='nom-popup-json'>" + pp.properties.nom + "</div><div>"
									+ pp.properties.text + "</div><div id='image-popup-json'>"
									+ pp.properties.img + "</div><div>" + pp.properties.vincle
									+ "</div>");
						}
						pp.addTo(capaJSON);
					}

//					jQuery('#dialog_dades_ex').modal('toggle');
					jQuery('#dialog_dades_ex').modal('hide');	
					capaJSON.options.businessId = results.results.businessId;
					capaJSON.options.options = jQuery.parseJSON('{"x":"'+cmd_json_x+'", "y":"'+cmd_json_y+'","titol":"'+cmd_json_titol+'","descripcio":"'+cmd_json_desc+'", "imatge":"'+cmd_json_img+'","vincle":"'+cmd_json_vin+'"}');
					capaJSON.options.options.estil_do = estil_do;
					capaJSON.addTo(map);
					capaJSON.options.zIndex = controlCapes._lastZIndex+1; 
					controlCapes.addOverlay(capaJSON, capaJSON.options.nom, true);
					controlCapes._lastZIndex++;
					activaPanelCapes(true);
//					$(".layers-list").mCustomScrollbar({
//						   advanced:{
//						     autoScrollOnFocus: false,
//						     updateOnContentResize: true
//						   }           
//					});	
				}
			});
			
		}else{
			capaJSON.addTo(map)
			capaJSON.options.zIndex = controlCapes._lastZIndex+1; 
			capaJSON.options.options = jQuery.parseJSON('{"x":"'+cmd_json_x+'", "y":"'+cmd_json_y+'","titol":"'+cmd_json_titol+'","descripcio":"'+cmd_json_desc+'", "imatge":"'+cmd_json_img+'","vincle":"'+cmd_json_vin+'"}');
			capaJSON.options.options.estil_do = estil_do;
			controlCapes.addOverlay(capaJSON, capaJSON.options.nom, true);
			controlCapes._lastZIndex++;
			activaPanelCapes(true);
//			$(".layers-list").mCustomScrollbar({
//				   advanced:{
//				     autoScrollOnFocus: false,
//				     updateOnContentResize: true
//				   }           
//			});	
		}		
	}
	
	//Buidem dialeg creacio capa JSON
//	jQuery('#div_layersJSON').empty();
//	jQuery('#txt_URLJSON').val('');	
	jQuery('#div_url_file').empty();
	jQuery('#txt_URLfile').val('');		
}

function loadCapaFromJSON(layer) {

	var defer = $.Deferred();
	
	var options = jQuery.parseJSON( layer.options );
	
	if(options.tem == tem_heatmap){
		loadJsonHeatmapLayer(layer);
		return defer.resolve();
	}else if(options.tem == tem_cluster){
		loadJsonClusterLayer(layer);
		return defer.resolve();
	}else{	
		var v_respotaJSON;
		getJSONPServei(layer.url).then(function(results) {
			var op = [];
			if (jQuery.isArray(results)) {
				v_respotaJSON = results;
			} else {
				for (key in results) {
					if (jQuery.isArray(results[key])) {
						v_respotaJSON = results[key];
					}
				}
			}
	
			if (!jQuery.isArray(v_respotaJSON)) {
				alert(window.lang.translate("No s'ha interpretar l'estructura del JSON"));
				return;
			}
			
			var capaJSON = new L.FeatureGroup();
			capaJSON.options = {
				businessId : layer.businessId,
				nom : layer.serverName,
				tipus:layer.serverType,
				zIndex : layer.capesOrdre,
				url: layer.url,
				options: options
			};		
			
			if (options.group){
				capaJSON.options.group=options.group;
			}
			
//			var options = jQuery.parseJSON( layer.options );
	//		var estil_do = retornaEstilaDO('json');
			var estil_do = options.estil_do;
			
			for (key in v_respotaJSON) {
				var lat = v_respotaJSON[key][options.y];
				var lon = v_respotaJSON[key][options.x];
				var pp = L.circleMarker([ lat, lon ], estil_do)
	
				pp.properties = {};
				var empty = true;
				
				if (options.titol == "null") {
					pp.properties.nom = ""
				} else {
					pp.properties.nom = v_respotaJSON[key][options.titol];
					empty = empty && false;
				}
				if (options.descripcio == "null") {
					pp.properties.text = ""
				} else {
					pp.properties.text = v_respotaJSON[key][options.descripcio];
					empty = empty && false;
				}
				if (options.imatge == "null") {
					pp.properties.img = ""
				} else {
					pp.properties.img = '<img width="250px" src="'
							+ v_respotaJSON[key][options.imatge] + '">';
					empty = empty && false;
				}
				if (options.vincle == "null") {
					pp.properties.vincle = ""
				} else {
					pp.properties.vincle = '<a href="'
							+ v_respotaJSON[key][options.vincle]
							+ '" target="_blank">'
							+ v_respotaJSON[key][options.vincle] + '</a>';
					empty = empty && false;
				}
	
				if(!empty){
					pp.bindPopup("<div id='nom-popup-json'>" + pp.properties.nom + "</div><div id='text-popup-json'>"
							+ pp.properties.text + "</div><div id='image-popup-json'>"
							+ pp.properties.img + "</div><div>" + pp.properties.vincle
							+ "</div>");
				}
				pp.addTo(capaJSON);
			}
	
			capaJSON.options.businessId = layer.businessId;
			
			if (layer.capesActiva== null || layer.capesActiva == 'null' || layer.capesActiva == true || layer.capesActiva == "true"){
				capaJSON.addTo(map)
			}		
			
			if (!layer.capesOrdre || layer.capesOrdre == null || layer.capesOrdre == 'null'){
				capaJSON.options.zIndex = controlCapes._lastZIndex + 1;
			}else{
				capaJSON.options.zIndex = parseInt(layer.capesOrdre);
			}			
				
//			controlCapes.addOverlay(capaDadaOberta, layer.serverName, true);	
//			controlCapes._lastZIndex++;
			
			if(!options.origen){
				controlCapes.addOverlay(capaJSON, capaJSON.options.nom, true);
				controlCapes._lastZIndex++;
			}else{//Si te origen es una sublayer
				var origen = getLeafletIdFromBusinessId(options.origen);
				capaJSON.options.zIndex = capesOrdre_sublayer;
				controlCapes.addOverlay(capaJSON, capaJSON.options.nom, true, origen);
			}			
			
			activaPanelCapes(true);	
			return defer.resolve();
		},function(results){
			alert(window.lang.translate("No s'ha interpretar l'estructura del JSON"));
			return defer.reject();		
		});
	}
	return defer.promise();
}
<file_sep>/geocatweb/js/geocat.mapa.edit-data-table.js
//var per controlar si hi ha hagut edicio dels elements de la capa, i si cal fer refresh
var editat = false;
var geomBusinessId = '-1';
var geomRowIndex = 0;
var numRows = 0;


function addFuncioEditDataTable(){
	
	addHtmlModalDataTable();
	addHtmlModalDeleteDataTableRow();
	
	$('#dialog_delete_row .btn-danger').on('click', function(event){
		var button = $(event.relatedTarget); // Button that triggered the modal
		var recipient = button.data('whatever');
		
    	var geometryid = $('#dialog_delete_row .btn-danger').data("geometryid");
    	var geometriesBusinessId = $('#dialog_delete_row .btn-danger').data("geometriesBusinessId");
    	var businessId = $('#dialog_delete_row .btn-danger').data("businessId");		
		
    	removeGeometryDB(geometryid,businessId,geometriesBusinessId);
	});
	
	$('#modal_data_table').on('hidden.bs.modal', function (e) {
		
//		console.debug(controlCapes);
		
		//si hem editat dades recarreguem la capa per visualitzar els canvis
		if(editat){
//			console.debug("Tanquem modal data table");
			  
	    	//Actualitzem visualitzacions de la capa on estava la geometria modificada
			var capaEdicio = $('#modal_data_table').data("capaEdicio");//controlCapes._layers[capaEdicioLeafletId];
//			console.debug("capaEdicio:");
//			console.debug(capaEdicio);
			var layerServidor = $('#modal_data_table').data("layerServidor");
			
			layerServidor.capesOrdre = capaEdicio.layer.options.zIndex.toString();
			
//			console.debug("layerServidor:");
//			console.debug(layerServidor);	
			
			//Eliminem la capa de controlCapes i mapa
			map.closePopup();
			map.removeLayer(capaEdicio.layer);
			controlCapes.removeLayer(capaEdicio);			
			
			//Recarrego la capa origen
			loadVisualitzacioLayer(layerServidor).then(function(results){
				//recarrego les sublayers si les te
				jQuery.each(capaEdicio._layers, function(i, sublayer){
					
					if(jQuery.type(capaEdicio.layer.options)== "string"){
						capaEdicio.layer.options = $.parseJSON(capaEdicio.layer.options);
					}	            	  
					//Sublayer visualitzacio, carrego la capa
					if(sublayer.layer.options.tipus.indexOf(t_visualitzacio)!=-1){
				  		  sublayer.layer.serverName = sublayer.layer.options.nom;
				  		  sublayer.layer.serverType = sublayer.layer.options.tipus;
				  		  sublayer.layer.capesActiva = "true";
				  		  sublayer.layer.options.origen = capaEdicio.layer.options.businessId;//layer.properties.capaBusinessId;//BusinessIdCapaorigen
				  		  //tipusRang
				  		  sublayer.layer.businessId = sublayer.layer.options.businessId;//Si no, no ho trobarà després
				  		  sublayer.layer.options = JSON.stringify(sublayer.layer.options);
				  		  
				  		  //eliminem sublayer del mapa, i recarreguem
				  		  map.closePopup();
				  		  map.removeLayer(sublayer.layer);
				  		  
				  		  loadVisualitzacioLayer(sublayer.layer);
			  	  	}
				});	
			});		
		}
		editat = false;
		geomBusinessId = '-1';
		geomRowIndex = 0;
		numRows = 0;
		$('#modal_data_table').off('post-body.bs.table');
		$('#modal_data_table_body #layer-data-table').bootstrapTable('destroy');
	});	
	
}

function fillModalDataTable(obj, geomBid){
	
	var columNames = [];
	var geometriesBusinessId = "";
	var modeMapa = ($(location).attr('href').indexOf('/mapa.html')!=-1);
	
	if(isValidValue(geomBid)){
		geomBusinessId = geomBid;
		
		$('#modal_data_table').on('post-body.bs.table	', function(event, name, row, 	oldValue, param) {
			event.preventDefault();
			event.stopImmediatePropagation();
			
//			var scroll = ($('div.fixed-table-body #layer-data-table tbody')[0].scrollHeight * (geomRowIndex+1)) / numRows;
//			console.debug("scroll:");
//			console.debug(scroll);
			
			 var parentDiv =  $('div.fixed-table-body');
			 var innerListItem = $('div.fixed-table-body #layer-data-table tbody tr.success');
			 if(!editat) parentDiv.scrollTo(innerListItem);
			 
		});
	}
	
	$('#modal_data_table').data("capaEdicio", obj);
	
	//obj.layer.serverName	
	//$('#modal_data_table_title').html(obj.name.toUpperCase());
	$('#modal_data_table_title').text(obj.name.toUpperCase());	
	
	var options = obj.layer.options;
	if (obj.layer.options!=undefined && obj.layer.options.estil!=undefined){
		//Primer trobem column names
		jQuery.each(obj.layer.options.estil, function(indexEstil, estil){
			
			jQuery.each(estil.geometria.features, function(indexFeature, feature){
				//console.debug(feature);
				//Geometry Id
				var objGeomId = {
						field: 'geometryid',
						title: 'ID',
						visible: false
				}
				columNames.push(objGeomId);	
	
				//Geometry Bid 
				var objGeomBid = {
						field: 'geometrybid',
						title: 'BID',
						visible: false
				}
				columNames.push(objGeomBid);			
				
				//geometryBBOX
				var objGeomBBOX = {
						field: 'geometryBBOX',
						title: 'BBOX',
						visible: false 
				}
				columNames.push(objGeomBBOX);			
				
				//console.debug(options);
				if(modeMapa){
					var isADrawMarker=false;
					//properties headers
					//console.debug(feature);
					var propName;
					if(typeof (options.propName)=="string"){	
						try {
							propName = JSON.parse(options.propName);
						}
						catch (err) {
							propName = options.propName;		
						}
					}else{			
						propName = options.propName;	
					}
					if (propName!=undefined && propName.toString().indexOf("nom,text")==-1) {
						
						for(var x in propName){	
							if (propName[x].toLowerCase()!="geomorigen") {
								//console.debug(propName[x]);
								var obj = {
									title: propName[x].toUpperCase(),
									field: propName[x].toLowerCase(),
									sortable: true,
									editable: {
										emptytext : '-'
									}
								}
								if (options.propName[x]=='text' || options.propName[x]=='TEXT') isADrawMarker=true;
								else isADrawMarker=false;
								columNames.push(obj);
							}
						}		
					}
					else {
						for(var x in feature.properties){
							if (x.toLowerCase()!="geomorigen"){
								var obj = {
									title: x.toUpperCase(),
									field: x.toLowerCase(),
									sortable: true,
									editable: {
										emptytext : '-'
									}
								}
								if (x=='text' || x=='TEXT') isADrawMarker=true;
								else isADrawMarker=false;
								columNames.push(obj);
							}
						}
					}
					if (isADrawMarker && feature.geometry.type=="Point"){ //Nomes pintem longitud/latitud quan és un punt
						var obj = {
								title: "latitud".toUpperCase(),
								field: "latitud".toLowerCase(),
								sortable: true
							}
						columNames.push(obj);
						 obj = {
									title: "longitud".toUpperCase(),
									field: "longitud".toLowerCase(),
									sortable: true
								}
						 columNames.push(obj);
					}
					
					//Actions
					var objActions = {
							title: window.lang.translate("ACCIONS"),
							field: 'Accions',
							formatter: 'actionFormatter',
							events: 'actionEvents'
					}	
					columNames.push(objActions);
					
				}else{
					//Taula no editable pel visor
					//properties headers
					var isADrawMarker=false;
					if (options.propName!=undefined && options.propName.toString().indexOf("nom,text")==-1) {
						
							for(var x in options.propName){
								if (options.propName[x].toLowerCase()!="geomorigen") {
									var obj = {
										title: options.propName[x].toUpperCase(),
										field: options.propName[x].toLowerCase(),
										sortable: true
									}
									if (options.propName[x]=='text' || options.propName[x]=='TEXT') isADrawMarker=true;
									else isADrawMarker=false;
									columNames.push(obj);
								}
							}
					}
					else {
						for(var x in feature.properties){
							if (x.toLowerCase()!="geomorigen"){
								var obj = {
									title: x.toUpperCase(),
									field: x.toLowerCase(),
									sortable: true								
								}
								if (x=='text' || x=='TEXT') isADrawMarker=true;
								else isADrawMarker=false;
								columNames.push(obj);
							}
						}
					}	
					if (isADrawMarker){
						var obj = {
								title: "latitud".toUpperCase(),
								field: "latitud".toLowerCase(),
								sortable: true
							}
						columNames.push(obj);
						 obj = {
									title: "longitud".toUpperCase(),
									field: "longitud".toLowerCase(),
									sortable: true
								}
						 columNames.push(obj);
					}
					
					//Actions
					var objActions = {
							title: window.lang.translate("ACCIONS"),
							field: 'Accions',
							formatter: 'actionFormatterVisor',
							events: 'actionEvents'
					}	
					columNames.push(objActions);
				}
				return false;
			});
			
			//return false;
		});	
	}
	else {//Primer cop que dibuixem una geometria
		//Geometry Id
		var objGeomId = {
				field: 'geometryid',
				title: 'ID',
				visible: false
		}
		columNames.push(objGeomId);	

		//Geometry Bid 
		var objGeomBid = {
				field: 'geometrybid',
				title: 'BID',
				visible: false
		}
		columNames.push(objGeomBid);			
		
		//geometryBBOX
		var objGeomBBOX = {
				field: 'geometryBBOX',
				title: 'BBOX',
				visible: false 
		}
		columNames.push(objGeomBBOX);		
		//console.debug(options);
		if(modeMapa){
			var isADrawMarker=true;
			//properties headers
			//console.debug(feature);
		
			var obj2 = {
					title: "nom".toUpperCase(),
					field: "nom".toLowerCase(),
					sortable: true,
					editable: {
						emptytext : '-'
					}
				}
				
			columNames.push(obj2);
			obj2 = {
					title: "text".toUpperCase(),
					field: "text".toLowerCase(),
					sortable: true,
					editable: {
						emptytext : '-'
					}
				}
				
			columNames.push(obj2);
			
			if (isADrawMarker && options.geometryType=="marker"){ //Nomes pintem longitud/latitud quan és un punt
				var obj2 = {
						title: "latitud".toUpperCase(),
						field: "latitud".toLowerCase(),
						sortable: true
					}
				columNames.push(obj2);
				 obj2 = {
							title: "longitud".toUpperCase(),
							field: "longitud".toLowerCase(),
							sortable: true
						}
				 columNames.push(obj2);
			}
			
			//Actions
			var objActions = {
					title: window.lang.translate("ACCIONS"),
					field: 'Accions',
					formatter: 'actionFormatter',
					events: 'actionEvents'
			}	
			columNames.push(objActions);
			
		}
		
	}
	
	window.actionEvents = {
		    'click .remove': function (e, value, row, index) {
		    	//Afegim parametres al button del dialog, per despres poder fer crida al remove
		    	$('#dialog_delete_row .btn-danger').data("geometryid", row.geometryid);
		    	$('#dialog_delete_row .btn-danger').data("geometriesBusinessId", geometriesBusinessId);
		    	$('#dialog_delete_row .btn-danger').data("businessId", obj.layer.options.businessId);
		    	
		    	$('#dialog_delete_row').modal('show');
		    },
	        'click .zoomTo': function (e, value, row, index) {
	        	$('#modal_data_table').modal('hide');
	        	var coords = row.geometryBBOX.split("#"); 
				var bbox = L.latLngBounds(L.latLng(coords[1], coords[0]), L.latLng(coords[3], coords[2]));
				map.fitBounds(bbox);
	        }
		};	

	//Portem properties del servidor
	var data ={
			businessId: obj.layer.options.businessId,
			uid:Cookies.get('uid')
		};
	
	
	getGeometriesPropertiesLayer(data).then(function(results){
			
			if (results.status == "OK"){
				
				geometriesBusinessId = results.geometriesBusinessId;
				$('#modal_data_table').data("layerServidor", results.layer);
				var resultats = results.results;
				var coords = resultats.split("#");  
				var lon = parseFloat(coords[2]);
				var lat = parseFloat(coords[1]);
				//resultats = resultats.replace("}]",",\"longitud\":\""+lon.toFixed(5)+"\",\"latitud\":\""+lat.toFixed(5)+"\"}]");
				var resultats2 = $.parseJSON(resultats);
				var resultatsMod = [];
				var resultI=0;
				var haveGeomOrigen=false;
				jQuery.each(resultats2, function(i, result){
					var coords = result.geometryBBOX.split("#");  
					var lon = parseFloat(coords[2]);
					var lat = parseFloat(coords[1]);
					if (result.longitud==undefined)  result.longitud=lon.toFixed(5);
					if (result.latitud==undefined)  result.latitud=lat.toFixed(5);					
					$.each( result, function( key, value ) {
						if (key.toLowerCase()!="geomorigen"){
							var valorStr=value.toString();
							if (valorStr.indexOf("src")>-1){
								value=valorStr.replaceAll('"',"'");//Issue #560
								//console.debug(value);
								result[key]=value;
							}
							else result[key]=value;
						}
						else {
							result[key] = null;
							delete result[key];
						}
					});
					resultatsMod[resultI]=result;
					
					resultI++;
					//console.debug(result);
					
				});
				var showRefresh=false;
				if (mapConfig.tipusAplicacioId == TIPUS_APLIACIO_AOC) showRefresh=true;
				$('#modal_data_table_body #layer-data-table').bootstrapTable({
					search: true,
					striped: true,
					height: '600',
					idField: 'geometryid',
//					clickToSelect: true,
//					checkboxHeader: true,
//					showColumns: true,
//					 showHeader: true,
					rowStyle: 'rowStyle',
				    columns: columNames,
				    showExport: true,			
				    showRefresh: showRefresh,
				    exportTypes: ['json', 'csv', 'txt', 'excel'],
				    ignoreColumn: [columNames.length-4],
				    data: resultatsMod,
				    icons: {
				       refresh: 'glyphicon-refresh'
				    }
				});	
				

				$('#modal_data_table').on('editable-save.bs.table', function(event, name, row, 	oldValue, param) {
					event.preventDefault();
					event.stopImmediatePropagation();					
					
					if(isValidValue(name)){
						
						var dataUpdate ={
								uid:Cookies.get('uid'),
								geometryid: row["geometryid"],
								key:  name,
								newValue: row[name]
							};
//						console.debug(dataUpdate);
						updateGeometriaProperties(dataUpdate).then(function(results){
							if (results.status == "OK"){
//								console.debug(results);
								editat = true;
							}else{
								console.debug('error updateGeometriaProperties');
							}
						},function(results){
							console.debug('error updateGeometriaProperties');
						});							
					}
				});	
				
				$('[name="refresh"]').on('click',function(){
					var capaEdicio = $('#modal_data_table').data("capaEdicio");
					$('#modal_data_table').modal('hide');
					carregarModalFitxer(true,obj.layer.options.businessId,obj.name,this.dataset.servertype,capaEdicio);
					
					//Tornem a carregar les dades de la visualització
					/*updateGeometries(data).then(function(results){
						if (results.status == "OK"){
							editat = true;
						}else{
							console.debug('error updateGeometries');
						}
						},function(results){
							console.debug('error updateGeometries');
						});							
					}*/
				});
				
				
				
			}else{
				console.debug('error getGeometriesPropertiesLayer');
			}
		},function(results){
			console.debug('error getGeometriesPropertiesLayer');
		});
	
}

function rowStyle(row, index) {
	
	numRows = numRows + 1;
	if (row.geometrybid == geomBusinessId) {
//    	console.debug("rowStyle:");
   
//    	console.debug(index);
    	geomRowIndex = index;
        return {
            classes: 'success'//classes[index / 2]
        };
    }
    return {};
	
//    var classes = ['active', 'success', 'info', 'warning', 'danger'];
//    
//    if (index % 2 === 0 && index / 2 < classes.length) {
//    	console.debug("rowStyle:");
//    	console.debug(row);
//        return {
//            classes: classes[index / 2]
//        };
//    }
//    return {};
}

function actionFormatter(value, row, index) {
    return [
        '<a class="zoomTo" href="javascript:void(0)" title="ZoomTo">',
        '<i class="glyphicon glyphicon-zoom-in data-table-icon-zoom"></i>',            
        '<a class="remove ml10" href="javascript:void(0)" title="Remove">',
        '<i class="glyphicon glyphicon-trash data-table-icon-remove"></i>',
        '</a>'
    ].join('');
}

function actionFormatterVisor(value, row, index) {
    return [
        '<a class="zoomTo" href="javascript:void(0)" title="ZoomTo">',
        '<i class="glyphicon glyphicon-zoom-in data-table-icon-zoom"></i>',            
        '</a>'
    ].join('');
}

function removeGeometryDB(geometryid, businessId, geometriesBusinessId){
	
	var data ={
			businessId: businessId,
			uid:Cookies.get('uid'),
			geometryid: geometryid,
			geometriesBusinessId: geometriesBusinessId
		};
	
	removeGeometriaFromProperties(data).then(function(results){
		
		if(results.status == "OK"){
			editat = true;
		    $('#modal_data_table_body #layer-data-table').bootstrapTable('remove', {
	            field: 'geometryid',
	            values: [geometryid]
	        }); 
		}else{
			console.debug("ERROR removeGeometriaFromProperties");
		}
		
	},function(results){
		console.debug("ERROR removeGeometriaFromProperties");
	});
	
}

function addHtmlModalDataTable(){
	
	jQuery('#mapa_modals').append(
	'<!-- Modal Data Table -->'+
	'		<div id="modal_data_table" class="modal fade">'+
	'		<div class="modal-dialog modal-lg">'+
	'			<div class="modal-content panel-primary">'+
	'				<div class="modal-header panel-heading">'+
	'					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'+
	'					<h4 lang="ca" id="modal_data_table_title"  class="modal-title"></h4>'+
	'				</div>'+
	'				<div id="modal_data_table_body" class="modal-body">'+
//	'					<div id="div-table">'+
//	'						<div class="cell-left">'+
	'							<div id="layer-data-table"></div>'+
//	'						</div>'+
//	'						<div class="cell-right"></div>'+
//	'						<div class="clearfix"></div>'+
//	'					</div>'+
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<button type="button" class="btn btn-default" data-dismiss="modal" lang="ca">Tancar</button>'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'<!-- fi Data Table -->'		
	);
}

function addHtmlModalDeleteDataTableRow(){
	
	jQuery('#mapa_modals').append(
	'<!-- Modal delete data table row -->'+
	'		<div id="dialog_delete_row" class="modal fade">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content">'+
	'				<div class="modal-body">'+
	'					<h4><span lang="ca">Vols esborrar la fila?</span></h4>'+
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<button lang="ca" type="button" class="btn btn-default"'+
	'						data-dismiss="modal">Cancel·lar</button>'+
	'					<button lang="ca" type="button" class="btn btn-danger"'+
	'						data-dismiss="modal">Esborrar</button>'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- Fi Modal delete -->	'		
	);
}

<file_sep>/geocatweb/js/geocat.mapa.altres-fonts-dades.js
/**
 * 
 */
function cercaCapes(e){
		var code = e.which; // recommended to use e.which, it's normalized across browsers
	    if(code==13) {//enter
	    	var data = {
	        	searchInput: jQuery("#txt_capesInstamaps").val()
	    	};
	    	valorCampText=jQuery("#txt_capesInstamaps").val();
	    	searchCapesPubliques(data).then(function(results){
	    		if(results.status == 'OK'){
	    			var lDadesInstamaps = '<ul class="bs-dadesO panel-heading llista-dadesInstamaps">';
	    			var apBusinessIds = results.apBusinessIds;

	    			jQuery.each(results.results, function(i, item) {
	    				//console.debug(item);
	    				lDadesInstamaps += '<li><a class="label-dadesInstamaps" href="#" data-url="'+item[0]+'" data-servertype="'+item[2]+'" data-nom="'+item[1]+'">'
	    						+ item[1]
	    						+ '</a>'
	    						+'&nbsp;&nbsp;<a href="http://www.instamaps.cat/geocatweb/visor.html?businessid='+apBusinessIds[item[0]]+'" target="_blank"><span class="glyphicon glyphicon-eye-open" title="Veure al corresponent mapa">'
	    						+'</span></a>'
	    						+ '</li>';
	    			});				
	    		
	    			lDadesInstamaps += '</ul>';
	    			jQuery("#id_capes_instamaps").html(
	    					'<div class="panel-dadesInstamaps">'+									
	    					'<div class="input-group txt_capes">'+
	    						'<input type="text" lang="ca" class="form-control" value="'+data.searchInput+'" placeholder="Entra el nom de la capa que vols buscar" style="height:33px" id="txt_capesInstamaps" onkeyup="cercaCapes(event);">'+ 
	    						'<span class="input-group-btn">'+
	    							'<button type="button" id="bt_capesInstamaps" class="btn btn-success" onclick="cercaCapesBtn();">'+
	    								'<span class="glyphicon glyphicon-play"></span>'+
	    							'</button>'+
	    						'</span>'+
	    					'</div>'+
	    					lDadesInstamaps +
	    				'</div>'
	    			);
	    			jQuery("#id_capes_instamaps a.label-dadesInstamaps").on('click', function(e) {
	    				var data = {
	    						uid: Cookies.get('uid'),
	    						mapBusinessId: url('?businessid'),
	    						businessId: this.dataset.url,
	    						nom: this.dataset.nom +"_duplicat",
	    						markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
	    						lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
	    						polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol))
	    				};	
	    				var servertype = this.dataset.servertype;
	    				duplicateVisualitzacioLayer(data).then(function(results){
	    					if(results.status==='OK'){
	    						
	    						var value = results.results;
	    						
	    						_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades instamaps', servertype, 1]);

	    						
	    						if (value.epsg == "4326"){
	    							value.epsg = L.CRS.EPSG4326;
	    						}else if (value.epsg == "25831"){
	    							value.epsg = L.CRS.EPSG25831;
	    						}else if (value.epsg == "23031"){
	    							value.epsg = L.CRS.EPSG23031;
	    						}else{
	    							value.epsg = map.crs;
	    						}							
	    						if(servertype == t_wms){
	    							loadWmsLayer(value);
	    						}else if((servertype == t_dades_obertes)){
	    							loadDadesObertesLayer(value);
	    						}else if(servertype == t_xarxes_socials){
	    							
	    							var options = jQuery.parseJSON( value.options );
	    							if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
	    							else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
	    							else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
	    							
	    						}else if(servertype == t_tematic){
	    							loadTematicLayer(value);
	    						}else if(servertype == t_visualitzacio){
	    							loadVisualitzacioLayer(value);
	    						}							
	    						$('#dialog_dades_ex').modal('hide');
	    						activaPanelCapes(true);
	    					}
	    				});								
	    				
	    			});
	    			
	    		}
	    	});
	    }
	
}

function cercaCapesBtn(){
		var data = {
	    		searchInput: jQuery("#txt_capesInstamaps").val()
		};
		valorCampText=jQuery("#txt_capesInstamaps").val();
		searchCapesPubliques(data).then(function(results){
			if(results.status == 'OK'){
				
				
				var lDadesInstamaps = '<ul class="bs-dadesO panel-heading llista-dadesInstamaps">';
				var apBusinessIds = results.apBusinessIds;
				
				jQuery.each(results.results, function(i, item) {
					//console.debug(item);
					lDadesInstamaps += '<li><a class="label-dadesInstamaps" href="#" data-url="'+item[0]+'" data-servertype="'+item[2]+'" data-nom="'+item[1]+'">'
							+ item[1]
							+ '</a>'
							+'&nbsp;&nbsp;<a href="http://www.instamaps.cat/geocatweb/visor.html?businessid='+apBusinessIds[item[0]]+'" target="_blank"><span class="glyphicon glyphicon-eye-open" title="Veure al corresponent mapa"></span></a>'
							+ '</li>';
				});				
			
				lDadesInstamaps += '</ul>';
				jQuery("#id_capes_instamaps").html(
						'<div class="panel-dadesInstamaps">'+									
						'<div class="input-group txt_capes">'+
							'<input type="text" lang="ca" class="form-control" value="'+data.searchInput+'" placeholder="Entra el nom de la capa que vols buscar" style="height:33px" id="txt_capesInstamaps" onkeyup="cercaCapes(event);">'+ 
							'<span class="input-group-btn">'+
								'<button type="button" id="bt_capesInstamaps" class="btn btn-success" onclick="cercaCapesBtn();">'+
									'<span class="glyphicon glyphicon-play"></span>'+
								'</button>'+
							'</span>'+
						'</div>'+
						lDadesInstamaps +
					'</div>'
				);
				jQuery("#id_capes_instamaps a.label-dadesInstamaps").on('click', function(e) {
					var data = {
							uid: Cookies.get('uid'),
							mapBusinessId: url('?businessid'),
							businessId: this.dataset.url,
							nom: this.dataset.nom +"_duplicat",
							markerStyle:JSON.stringify(getMarkerRangFromStyle(defaultPunt)),
							lineStyle:JSON.stringify(getLineRangFromStyle(canvas_linia)),
							polygonStyle:JSON.stringify(getPolygonRangFromStyle(canvas_pol))
					};	
					var servertype = this.dataset.servertype;
					duplicateVisualitzacioLayer(data).then(function(results){
						if(results.status==='OK'){
							
							var value = results.results;
							
							_gaq.push(['_trackEvent', 'mapa', tipus_user+'carregar dades instamaps', servertype, 1]);

							
							if (value.epsg == "4326"){
								value.epsg = L.CRS.EPSG4326;
							}else if (value.epsg == "25831"){
								value.epsg = L.CRS.EPSG25831;
							}else if (value.epsg == "23031"){
								value.epsg = L.CRS.EPSG23031;
							}else{
								value.epsg = map.crs;
							}							
							if(servertype == t_wms){
								loadWmsLayer(value);
							}else if((servertype == t_dades_obertes)){
								loadDadesObertesLayer(value);
							}else if(servertype == t_xarxes_socials){
								
								var options = jQuery.parseJSON( value.options );
								if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
								else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
								else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
								
							}else if(servertype == t_tematic){
								loadTematicLayer(value);
							}else if(servertype == t_visualitzacio){
								loadVisualitzacioLayer(value);
							}							
							$('#dialog_dades_ex').modal('hide');
							activaPanelCapes(true);
						}
					});								
					
				});
			
			}
		});

}

function addControlAltresFontsDades() {
	
	addHtmlInterficieDadesExt();
	addHtmlModalDadesExt();
	var _DadesOficials=new IM_DadesOficials();
	jQuery(".div_dades_ext").on('click', function() {
		//gestionaPopOver(this);
		jQuery('.modal').modal('hide');
		$('#dialog_dades_ex').modal('show');
		$('a[href^="#id_do').click();
		jQuery('#id_do').html(_htmlDadesObertes.join(' ')+'<span class="label label-font">Font: <a target="_blank" href="http://www20.gencat.cat/portal/site/dadesobertes">Dades obertes Gencat</a></span>');

		jQuery("#id_do a.label-explora").on('click', function(e) {
			if(e.target.id !="id_do"){
				addCapaDadesObertes(e.target.id,jQuery(e.target).text());
			}
		});
		jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
			var tbA = e.target.attributes.href.value;

			if (tbA == "#id_do") {
				jQuery(tbA).empty();
				jQuery(tbA).html(_htmlDadesObertes.join(' ')+'<span class="label label-font">Font: <a target="_blank" href="http://www20.gencat.cat/portal/site/dadesobertes">Dades obertes Gencat</a></span>');

				jQuery(tbA+" a.label-explora").on('click', function(e) {
					if(e.target.id !="id_do"){
						addCapaDadesObertes(e.target.id,jQuery(e.target).text());
					}
				});
			}else if (tbA=='#id_ofi'){

				jQuery(tbA).empty();
				jQuery(tbA).html(_DadesOficials.generaOpcionsHTMLDadesOficials());							
				jQuery(tbA+" a.label-dof").on('click', function(e) {
						_DadesOficials.addOpcionsHTMLTipusDadesOficials(this);
						
					});
							
			
			}else if(tbA == "#id_srvw"){
				jQuery(tbA).empty();
				jQuery(tbA).html(_htmlServeisWMS.join(' ')+'<span class="label label-font">Font: <a target="_blank" href="http://catalegidec.icc.cat">Cat&agrave;leg IDEC</a></span>');
				var instamapsWms = InstamapsWms({container:$('#div_controlWMS'), botons: $('#div_emptyWMS'),proxyUrl: paramUrl.ows2json, callback: addWmsToMap});
				jQuery(tbA+" a.label-wms").on('click', function(e) {
					
					
					
					if(e.target.id !="id_srvw"){
						instamapsWms.getLayers({url: e.target.id, name: $(e.target).text()})
						/*
						$("#txt_URLWMS").val(e.target.id);
						jQuery("#div_layersWMS").empty();
						jQuery("#div_layersWMS").hide();
						jQuery('#div_emptyWMS').empty();
						getCapabilitiesWMS(e.target.id,jQuery(e.target).text());
						*/
					}
				});
//			}else if(tbA == "#id_srvj"){
//				jQuery(tbA).empty();
//				jQuery(tbA).html(_htmlServeisJSON.join(' '));
//				jQuery("#bt_connJSON").on('click', function(e) {
//					if(e.target.id !="#id_srvj"){
//						getServeiJSONP(jQuery("#txt_URLJSON").val());
//					}
//				});		
			}else if(tbA == "#id_xs"){//Xarxes socials
				
				
				/*
				jQuery(tbA).html(
						'<div class="panel-info">'+
						'<ul class="bs-dadesO_XS panel-heading">'+
						
						'<li><a id="add_twitter_layer" href="javascript:toggleCollapseDiv(\'#twitter-collapse\')" class="label-xs">Twitter <i class="fa fa-twitter"></i></a></li>'+
						'<li><a id="add_panoramio_layer" href="javascript:addPanoramioLayer();" class="label-xs">Panoramio <i class="fa fa-picture-o"></i></a></li>'+
						'<li><a id="add_wikipedia_layer" href="javascript:addWikipediaLayer();" class="label-xs">Wikipedia <i class="fa fa-book"></i></a></li>'+
						
						'</ul>'+
						'<div class="panel-body"><span class="label-xarxes" lang="ca">'+window.lang.translate(label_xarxes)+'</span></div>'+
						'<div id="twitter-collapse">'+
							'<div class="input-group">'+
			      				'<span class="input-group-addon">Hashtag #</span>'+
			      				'<input id="hashtag_twitter_layer" type="text" class="form-control">'+
			      				'<span class="input-group-btn">'+
			      					'<button id="btn-add-twitter-layer" class="btn btn-primary editable-submit" type="button"><i class="glyphicon glyphicon-ok"></i></button>'+
			      				'</span>'+
				      		'</div>'+
				      		'</div>'+
			      		'</div>'+
						'<div id="wikipedia-collapse">'+
							'<div class="input-group">'+
			      				'<span class="input-group-addon">Paraula clau #</span>'+
			      				'<input id="name_wikipedia_layer" type="text" class="form-control">'+
			      				'<span class="input-group-btn">'+
			      					'<button id="btn-add-wikipedia-layer" class="btn btn-primary editable-submit" type="button"><i class="glyphicon glyphicon-ok"></i></button>'+
			      				'</span>'+
				      		'</div>'+
				      		'</div>'+
			      		'</div>'			      		
				);
				$('#twitter-collapse').hide();
				$('#twitter-collapse .input-group .input-group-btn #btn-add-twitter-layer').click(function(){
					addTwitterLayer();
				});

				$('#wikipedia-collapse').hide();
				$('#wikipedia-collapse .input-group .input-group-btn #btn-add-wikipedia-layer').click(function(){
					addWikipediaLayer();
				});				
				*/
			}else if(tbA == "#id_capes_instamaps"){
				jQuery(tbA).empty();
				jQuery(tbA).html('<div class="input-group txt_capes"><input type="text" lang="ca" class="form-control" placeholder="Entrar el nom de la capa que es vol buscar" style="height:33px" id="txt_capesInstamaps" onkeyup="cercaCapes(event);" >'+ 
						'<span class="input-group-btn"><button type="button" id="bt_capesInstamaps" class="btn btn-success" onclick="cercaCapesBtn();"><span class="glyphicon glyphicon-play"></span></button></span> </div>');				
				
			}
			else if(tbA == "#id_url_file"){
				jQuery(tbA).empty();
var label_xarxes = "La informació de les xarxes socials es mostra en funció de l'àrea geogràfica visualitzada."
				//Carreguem exemples de dades externes 

				var lDadesExternes = '<ul class="bs-dadesO panel-heading llista-dadesExternes">';
				jQuery.each(llista_dadesExternes.dadesExternes, function(key, dadesExternes) {
						lDadesExternes += '<li><a class="label-dadesExternes" href="#" data-url="'
							+ dadesExternes.urlDadesExternes
							+ '" data-format="'
							+ dadesExternes.formatDadesExternes
							+ '" data-epsg="'
							+ dadesExternes.epsgDadesExternes
							+ '">'
							+ window.lang.translate(dadesExternes.titol)
							+ '</a>'
							+ '<a target="_blank" lang="ca" title="Informació" href="'
							+ dadesExternes.urlOrganitzacio
							+ '"><span class="glyphicon glyphicon-info-sign info-dadesExternes"></span></a>'
							+ '</li>';
				});		

			//lDadesExternes +='<li><a id="add_panoramio_layer" href="#" data-url="panoramio" class="label-dadesExternes">Panoramio <span class="fa fa-picture-o"></span></a></li>';
			lDadesExternes +='<li><a id="add_wikipedia_layer" href="#" data-url="wikipedia" class="label-dadesExternes">Wikipedia <span class="fa fa-wikipedia-w"></span></a></li>';
			
			lDadesExternes +='<li><a id="add_twitter_layer" href="#" data-url="twitter" class="label-dadesExternes">Twitter <span class="fa fa-twitter"></span></a>'+
				'<div id="twitter-collapse">'+
							'<div class="input-group">'+
			      				'<span class="input-group-addon">Hashtag #</span>'+
			      				'<input id="hashtag_twitter_layer" type="text" class="form-control">'+
			      				'<span class="input-group-btn">'+
			      					'<button id="btn-add-twitter-layer" class="btn btn-primary editable-submit" type="button"><i class="glyphicon glyphicon-ok"></i></button>'+
			      				'</span>'+
				      		'</div>'+
				      		'</div>'+
					'</li>';
			
						


				
				lDadesExternes += '</ul>';
				
				jQuery(tbA).html(
						'<div class="panel-dadesExternes">'+
							lDadesExternes +
							//TODO agregar mensaje
							//'<div>'+window.lang.translate("Entrar URL de dades externes")+' <a lang="ca href="" title="Informació" target="_blank"><span class="glyphicon glyphicon-info-sign"></span></a></div>'+
							'<div class="input-group txt_ext">'+
								'<input type="text" lang="ca" class="form-control" value="" placeholder="'+window.lang.translate("Entrar URL de dades externes")+'" style="height:33px" id="txt_URLfile">'+ 
								'<span class="input-group-btn">'+
									'<button type="button" id="bt_URLfitxer" class="btn btn-success">'+
										'<span class="glyphicon glyphicon-play"></span>'+
									'</button>'+
								'</span>'+
							'</div>'+
						'</div>'+
						'<div id="div_url_file"  class="tbl_url_file"></div>'
//						+'<div id="div_emptyJSON" style="height: 35px;margin-top: 2px"></div>'
						//'<span class="label label-font" lang="ca">'+label_xarxes+'</span>'
				);
				
				jQuery("#div_url_file").hide();
				$('#twitter-collapse').hide();
				$('#twitter-collapse .input-group .input-group-btn #btn-add-twitter-layer').click(function(){
					addTwitterLayer();
					$('#dialog_dades_ex').modal('hide');
				});
				jQuery(".label-dadesExternes").on('click', function(e) {
					
					
					//URL PRESIDENT JSON
					if(this.dataset.url.indexOf(paramUrl.presidentJSON)!= -1){
						/*
						jQuery("#div_url_file").show();
						jQuery("#div_url_file").html(
								'<div style="height:230px;overflow:auto" id="div_layersJSON"  class="tbl"></div>'+
								'<div id="div_emptyJSON" style="height: 35px;margin-top: 2px"></div>'
						);
						*/
						getServeiJSONP(this.dataset.url);						
					}else if (this.dataset.url=="panoramio"){
						addPanoramioLayer();
						$('#dialog_dades_ex').modal('hide');
					}else if (this.dataset.url=="wikipedia"){
						addWikipediaLayer();	
						$('#dialog_dades_ex').modal('hide');						
					}else if (this.dataset.url=="twitter"){
						toggleCollapseDiv('#twitter-collapse');					
					}else{//LA RESTA
						if(!busy){
							//console.debug("No esta busy.. faig la carrega!");
							busy = true;
							createURLfileLayer(this.dataset.url, this.dataset.format, this.dataset.epsg, false, this.text);
						}else{
							//console.debug("Esta busy, no puc carregar");
							$('#dialog_dades_ex').modal('hide');
							$('#dialog_info_upload_txt').html(window.lang.translate("S'està processant un arxiu. Si us plau, espereu que aquest acabi."));
							$('#dialog_info_upload').modal('show');
							//drgFromMapa.removeAllFiles(true);							
						}
					}
				});
				
				jQuery("#bt_URLfitxer").on('click', function(e) {
					jQuery('#bt_URLfitxer').prop("disabled", true);
					jQuery("#div_url_file").show();
					var urlFile = $.trim(jQuery("#txt_URLfile").val());
					if(isValidURL(urlFile)){
						
						//URL PRESIDENT JSON
						if(urlFile.indexOf(paramUrl.presidentJSON)!= -1){
							/*
							jQuery("#div_url_file").html(
									'<div style="height:230px;overflow:auto" id="div_layersJSON"  class="tbl"></div>'+
									'<div id="div_emptyJSON" style="height: 35px;margin-top: 2px"></div>'
							);
							*/
							getServeiJSONP(urlFile);
						}
						else if(urlFile.indexOf("socrata")!= -1){
							jQuery("#div_url_file").html(
									'<br>'+
									'<div class="input-group input-group-sm">'+
										'<span lang="ca" class="input-group-addon">'+window.lang.translate("Nom capa")+'</span>'+
										'<input type="text" id="input-url-file-name" class="form-control">'+
									'</div>'+	
									'<br>'+
									'<div>'+														
										'<input id="dinamic_chck" type="checkbox" checked="checked">'+
										'&nbsp;'+window.lang.translate("Dinàmica")+
										'<br><small lang="ca" class="label label-success" id="label-dinamic">'+
											window.lang.translate("Dinàmic: S'accedirà a la font de dades cada cop que es carregui la capa")+
										'</small>'+
									'</div>&nbsp;'+
									'<div style="float:right">'+
										'<button id="bt_URLfitxer_go" class="btn btn-success btn-add-wms" lang="ca">Afegir capa</button>'+
									'</div>'+
									'<div id="div_url_file_message" class="alert alert-danger"></div>'
							);

							jQuery("#div_url_file_message").hide();
							activarEventAfegirCapa("-1");
						}else{//LA RESTA
							jQuery("#div_url_file").html(
									'<br>'+
									'<div class="input-group input-group-sm">'+
										'<span lang="ca" class="input-group-addon">'+window.lang.translate("Nom capa")+'</span>'+
										'<input type="text" id="input-url-file-name" class="form-control">'+
									'</div>'+	
									'<br>'+
									'<div>'+
									window.lang.translate("Format")+
									':&nbsp;'+
										'<select id="select-url-file-format" class="form-download-format">'+
										  '<option value=".geojson">GeoJSON</option>'+
										  '<option value=".shp">ESRI Shapefile</option>'+
										  '<option value=".dxf">DXF</option>'+
										  '<option value=".dgn">DGN</option>'+
										  '<option value=".kml">KML</option>'+
										  '<option value=".gpx">GPX</option>'+
										  '<option value=".gml">GML</option>'+
										  '<option value=".kmz">KMZ</option>'+
										  '<option value=".csv">CSV</option>'+
										  '<option value=".txt">TXT</option>'+
										  '<option value=".xls">XLS</option>'+
										  '<option value=".xlsx">XLSX</option>'+
										  '<option value=".zip">Zip File</option>'+
										  '<option value="-1">'+window.lang.translate("Selecciona el Format")+'</option>'+
										'</select>'+
										'<br><br>'+
										'<div id="input-excel-url-file">'+
										'	<div class="panel-body">'+
										'	   <ul class="nav nav-pills nav-pills-urlfile" id="nav_pill">'+
										'	      <li id="coordenades" class="active"><a lang="ca" data-toggle="tab" href="#opt_urlfile_coord" aria-expanded="true">'+window.lang.translate("Per coordenades")+'</a></li>'+
										'	      <li id="adreca"  class=""><a lang="ca" data-toggle="tab" href="#opt_urlfile_adreca" aria-expanded="false">'+window.lang.translate("Per adreces")+'</a></li>'+
										'	      <li id="codis"  class=""><a lang="ca" data-toggle="tab" href="#opt_urlfile_codi" aria-expanded="false">'+window.lang.translate("Per codis")+'</a></li>'+
										'	   </ul>'+
										'	   <!-- Tab panes -->		'+					
										'	   <div class="tab-content-urlfile tab-content" id="div_opt_urlfile">'+
										'	      <div id="opt_urlfile_coord" class="tab-pane active">'+
										'	         <ul class="pane-excel-urlfile">'+
														'<label lang="ca">'+window.lang.translate("On són les coordenades?")+'</label>'+
														'<br>'+
														'<div class="input-group input-group-sm">'+
															'<span lang="ca" class="input-group-addon">'+window.lang.translate("Coordenada X o LON")+'</span>'+
															'<input type="text" id="input-coord-x" class="form-control">'+
														'</div>'+	
														'<br>'+	
														'<div class="input-group input-group-sm">'+
															'<span lang="ca" class="input-group-addon">'+window.lang.translate("Coordenada Y o LAT ")+'</span>'+
															'<input type="text" id="input-coord-y" class="form-control">'+
														'</div>'+
										'	         </ul>'+
										'	      </div>'+
										'	      <div id="opt_urlfile_adreca" class="tab-pane">'+
										'	         <ul class="pane-excel-urlfile">'+
										'					<span lang="ca">Per codificar per adreces utilitza aquest</span>'+ 
										'					<a class="alert-link" lang="ca"	href="dades/exemple_geocod_adreces.xlsx">arxiu tipus</a>'+ 
										'					<span lang="ca">amb les teves dades.</span>'+
										'					<br/>'+
										'					<span lang="ca">Els camps Nom_via, Portal i Municipi són obligatoris.</span>'+
										'	         </ul>'+
										'	      </div>'+
										'	      <div id="opt_urlfile_codi" class="tab-pane tab-pane-urlfile">'+
										'	         <ul class="pane-excel-urlfile">'+
										'	            <li><label lang="ca">'+window.lang.translate("Els teus codis són de")+'</label>:</li>'+
										'	            <li>'+
										'	               <select id="cmd_codiType_Capa_de">'+
										'	                  <option lang="ca" value="municipis" selected="">'+window.lang.translate("Municipis")+'</option>'+
										'	                  <option lang="ca" value="comarques">'+window.lang.translate("Comarques")+'</option>'+
										'	               </select>'+
										'	            </li>'+
										'	            <li><label lang="ca">'+window.lang.translate("Tipus codi")+'</label></li>'+
										'	            <li>'+
										'	               <select name="select_codiType" id="cmd_codiType_de">'+
										'	                  <option value="ine">INE (5 digits)</option>'+
										'	                  <option value="idescat">IDESCAT (6 digits)</option>'+
										'	                  <option value="municat">MUNICAT (10 digits)</option>'+
										'	                  <option value="cadastre">CADASTRE (5 digits)</option>'+
										'	               </select>'+
										'	            </li>'+
										'	            <li><label lang="ca">'+window.lang.translate("Camp que conté el codi")+'</label></li>'+
										'	            <li>'+
															'<div class="input-group input-group-sm">'+
																'<input type="text" id="input-camp-codi-urlfile" class="form-control" placeholder="'+window.lang.translate("Entrar camp")+'">'+
															'</div>'+
										'	            </li>'+
										'	         </ul>'+
										'	      </div>'+
										'	   </div>'+
										'	</div>'+											
										'</div>'+
										'<br>'+
									'EPSG:&nbsp;'+
										'<select id="select-url-file-epsg" class="form-download-epsg">'+
											'<option value="EPSG:4326">EPSG:4326 (WGS84 geogràfiques (lat, lon) - G.G)</option>'+
					              			'<option value="EPSG:23031"><b>EPSG:23031</b> (ED50-UTM 31N Easting,Northing o X,Y)</option>'+
					              			'<option value="EPSG:25831">EPSG:25831 (ETRS89-UTM 31N Easting,Northing o X,Y)</option>'+
					              			'<option value="EPSG:4258">EPSG:4258 INSPIRE(ETRS89 geogràfiques (lat, lon) - G.G)</option>'+
					              			'<option value="EPSG:4230">EPSG:4230 (ED50 geogràfiques (lat, lon) - G.G)</option>'+
					              			'<option value="EPSG:32631">EPSG:32631 (WGS84 31N Easting,Northing o X,Y)</option>'+
					              			'<option value="EPSG:3857">EPSG:3857 (WGS84 Pseudo-Mercator Easting,Northing o X,Y)</option>'+
					              			'<option value="-1">'+window.lang.translate("Selecciona el EPSG")+'</option>'+
										'</select>'+
										'<br><br>'+								
										'<input id="dinamic_chck" type="checkbox" checked="checked">'+
										'&nbsp;'+window.lang.translate("Dinàmica")+
										'<br><small lang="ca" class="label label-success" id="label-dinamic">'+
											window.lang.translate("Dinàmic: S'accedirà a la font de dades cada cop que es carregui la capa")+
										'</small>'+
									'</div>&nbsp;'+
									'<div style="float:right">'+
										'<button id="bt_URLfitxer_go" class="btn btn-success btn-add-wms" lang="ca">Afegir capa</button>'+
									'</div>'+
									'<div id="div_url_file_message" class="alert alert-danger"></div>'
							);
							
							$('#opt_urlfile_codi').on('click',function(){
								//console.debug("click opt_urlfile_codi");
							});
							
							jQuery("#div_url_file_message").hide();
							jQuery("#input-excel-url-file").hide();
							
							//Comprovem tipus del file
							var type = "-1";
							if(urlFile.indexOf(t_file_kml)!=-1) type = t_file_kml;
							else if(urlFile.indexOf(t_file_gpx)!=-1) type = t_file_gpx;
							else if(urlFile.indexOf(t_file_shp)!=-1) type = t_file_shp;
							else if(urlFile.indexOf(t_file_dxf)!=-1) type = t_file_dxf;
							else if(urlFile.indexOf(t_file_xlsx)!=-1) type = t_file_xlsx;
							else if(urlFile.indexOf(t_file_xls)!=-1) type = t_file_xls;
							else if(urlFile.indexOf(t_file_topojson)!=-1) type = t_file_geojson;
							else if(urlFile.indexOf(t_file_geojson)!=-1) type = t_file_geojson;
							else if(urlFile.indexOf(t_file_json)!=-1) type = t_file_geojson;
							else if(urlFile.indexOf(t_file_csv)!=-1) type = t_file_csv;
							else if(urlFile.indexOf(t_file_txt)!=-1) type = t_file_txt;
							else if(urlFile.indexOf(t_file_dgn)!=-1) type = t_file_dgn;
							else if(urlFile.indexOf(t_file_gml)!=-1) type = t_file_gml;
							
							$('#select-url-file-format option[value="'+type+'"]').prop("selected", "selected");
							
							if (type==".kml" ||type==".gpx" || type==".gml"){
								$('#select-url-file-epsg option[value="EPSG:4326"]').prop("selected", "selected");
								jQuery("#select-url-file-epsg").attr('disabled',true);
							}else if(type==".xls" || type==".xlsx" || type==".csv" || type==".txt"){
								jQuery("#input-excel-url-file").show();
								$('#input-excel-url-file .nav-pills-urlfile li#codis').removeClass("disabled");
								$('#input-excel-url-file .nav-pills-urlfile li a[href="#opt_urlfile_codi"]').attr("data-toggle","tab");
							}else{
								$('#select-url-file-epsg option[value="-1"]').prop("selected", "selected");
								jQuery("#select-url-file-epsg").attr('disabled',false);
							}
							
							activarEventAfegirCapa(type);
							
							jQuery('#cmd_codiType_Capa_de').on('change',function(e) {
								var html = "";
								if (jQuery(this).val() == "municipis") {
									html = "<option value='ine'>INE (5 digits)</option><option value='idescat'>IDESCAT (6 digits)</option><option value='municat'>MUNICAT (10 digits)</option><option value='cadastre'>CADASTRE (5 digits)</option>";
								} else {
									html = "<option value='ine'>NUM_COMARCA (2 digits)</option><option value='municat'>MUNICAT (10 digits)</option>";
								}
								jQuery('#cmd_codiType_de').html(html);
							});
							
							jQuery('.nav-pills-urlfile #codis').on('click', function(){
								jQuery("#select-url-file-epsg").attr('disabled',true);
							});
							
							jQuery('.nav-pills-urlfile #coordenades').on('click', function(){
								jQuery("#select-url-file-epsg").attr('disabled',false);
							});
							
							jQuery('.nav-pills-urlfile #adreca').on('click', function(){
								jQuery("#select-url-file-epsg").attr('disabled',true);
							});
							
							jQuery("#input-coord-x").focus(function() {
								jQuery(this).removeClass("class_error");
							});	
							
							jQuery("#input-coord-y").focus(function() {
								jQuery(this).removeClass("class_error");
							});
							
							jQuery("#input-camp-codi-urlfile").focus(function() {
								jQuery(this).removeClass("class_error");
							});
							
							jQuery("#select-url-file-epsg").change(function(){
								jQuery(this).removeClass("class_error");
								jQuery("#div_url_file_message").empty();
								jQuery("#div_url_file_message").hide();
							});						
							
							jQuery('#select-url-file-format').change(function() {
								jQuery(this).removeClass("class_error");
								jQuery("#div_url_file_message").empty();
								jQuery("#div_url_file_message").hide();
								jQuery("#input-excel-url-file").hide();
								
								var ext = jQuery(this).val();
								if ((ext==".kml")||(ext==".gpx") ||(ext==".gml")){
									$('#select-url-file-epsg option[value="EPSG:4326"]').prop("selected", "selected");
									jQuery("#select-url-file-epsg").attr('disabled',true);
//									jQuery("#input-excel-url-file").hide();
								}else if((ext==".xls")||(ext==".xlsx") || (ext==".csv") || (ext==".txt") ){
									jQuery("#input-excel-url-file").show();
									$('#input-excel-url-file .nav-pills-urlfile li#codis').removeClass("disabled");
									$('#input-excel-url-file .nav-pills-urlfile li a[href="#opt_urlfile_codi"]').attr("data-toggle","tab");
								}else{
									jQuery("#select-url-file-epsg").attr('disabled',false);
//									jQuery("#input-excel-url-file").hide();
								}
							});								
						}
						
					}else{
						jQuery("#div_url_file").html(
								'<div id="txt_URLfile_error" class="alert alert-danger">'+
									'<span class="glyphicon glyphicon-warning-sign"> </span> '+
   									 window.lang.translate("Introdueix una URL vàlida")+
								'</div>'
						);
					}
				});
				
				$("#txt_URLfile").focus(function() {
					jQuery("#div_url_file").empty();
					jQuery("#div_url_file").hide();
					jQuery('#bt_URLfitxer').prop("disabled", false);
				});				
			}		
		});
	})
}


function addHtmlModalDadesExt(){
	
	jQuery('#mapa_modals').append(
	'	<!-- Modal Dades Externes -->'+
	'		<div class="modal fade" id="dialog_dades_ex" style="width:105%">'+
	'		<div class="modal-dialog">'+
	'			<div class="modal-content panel-primary">'+
	'				<div class="modal-header panel-heading">'+
	'					<button type="button" class="close" data-dismiss="modal"'+
	'						aria-hidden="true">&times;</button>'+
	'					<h4 class="modal-title"><span lang="ca">Explora altres fonts de dades</span><span><a class="faqs_link" href="http://betaportal.icgc.cat/wordpress/faq-dinstamaps/#explorafonts" target="_blank"><i class="fa fa-question-circle-o fa-lg fa-fw"></i></a></span></h4>'+
	'				</div>'+
	'				<div class="modal-body">'+
	'					<ul class="nav nav-tabs etiqueta">'+
	'						<li><a href="#id_ofi" lang="ca" data-toggle="tab">Dades oficials</a></li>'+
	'						<li><a href="#id_do" lang="ca" data-toggle="tab">Dades obertes</a></li>'+
	//'						<li><a href="#id_xs" lang="ca" data-toggle="tab">Xarxes socials</a></li>'+
	'						<li><a href="#id_srvw" lang="ca" data-toggle="tab">Serveis WMS</a></li>'+
	'						<li><a href="#id_capes_instamaps" lang="ca" data-toggle="tab">Capes reutilitzables</a></li>'+
	'						<li><a href="#id_url_file" data-toggle="tab"><span lang="ca">Dades externes</span></a></li>'+
	'					</ul>'+
	'					<div class="tab-content tab-content-margin5px">'+
	'						<div class="tab-pane fade" id="id_ofi"></div>'+
	'						<div class="tab-pane fade" id="id_do"></div>'+
	//'						<div class="tab-pane fade" id="id_xs"></div>'+
	'						<div class="tab-pane fade" id="id_srvw"></div>'+
	'						<div class="tab-pane fade" id="id_capes_instamaps"></div>'+
	'						<div class="tab-pane fade" id="id_url_file"></div>'+
	'					</div>'+
	'				</div>'+
	'				<div class="modal-footer">'+
	'					<!-- <button type="button" class="btn btn-default" data-dismiss="modal">Tancar</button>'+
	'         			<button type="button" class="btn btn-success">Canviar</button> -->'+
	'				</div>'+
	'			</div>'+
	'			<!-- /.modal-content -->'+
	'		</div>'+
	'		<!-- /.modal-dialog -->'+
	'	</div>'+
	'	<!-- /.modal -->'+
	'	<!-- fi Modal Dades Externes -->'		
	);
	
}

function addHtmlInterficieDadesExt(){
	jQuery("#carregar_dades .div_gr2").append(
			'<div lang="ca" id="div_dades_ext" class="div_dades_ext" data-toggle="tooltip" title="Explora altres fonts de dades" data-lang-title="Explora altres fonts de dades"></div>'		
	);
	$('#div_dades_ext').tooltip({
		placement : 'bottom',
		container : 'body'
	});
}

function activarEventAfegirCapa(type){
	var nom_capa = window.lang.translate("Capa de fitxer");
	if(type!=undefined && type!="-1") nom_capa+=type;
	jQuery("#input-url-file-name").val(nom_capa);
	
	jQuery("#bt_URLfitxer_go").on('click', function(e) {
		e.stopImmediatePropagation();
		jQuery("#div_url_file_message").empty();
		jQuery("#div_url_file_message").hide();
		
		var urlFile = $.trim(jQuery("#txt_URLfile").val());
		var type = jQuery("#select-url-file-format").val();
		var epsg = jQuery("#select-url-file-epsg").val();
		var opcio = jQuery('.nav-pills-urlfile .active').attr('id');
		var coordX = jQuery("#input-coord-x").val();
		var coordY = jQuery("#input-coord-y").val();
		//console.debug(opcio);
		
		if(type!=undefined && type.indexOf("-1")!= -1 || epsg!=undefined && epsg.indexOf("-1")!= -1 && opcio!=undefined && opcio!="codis" && opcio!="adreca"){
			if(type.indexOf("-1")!= -1) jQuery("#select-url-file-format").addClass("class_error");
			if(epsg.indexOf("-1")!= -1) jQuery("#select-url-file-epsg").addClass("class_error");
			
		}else if( type!=undefined && (type==".xls" || type==".xlsx" || type==".csv" || type==".txt") 
					&&  opcio == "coordenades" && (!isValidValue(coordX) || !isValidValue(coordY) ) ){
			
			if(!isValidValue(coordX)) jQuery("#input-coord-x").addClass("class_error");
			if(!isValidValue(coordY)) jQuery("#input-coord-y").addClass("class_error");
		
		}else if( type!=undefined && (type==".xls" || type==".xlsx" || type==".csv" || type==".txt") 
					&&  opcio == "codis" && (!isValidValue(jQuery("#input-camp-codi-urlfile").val())) ){
			
			jQuery("#input-camp-codi-urlfile").addClass("class_error");
		
		}else{
			if(!busy){
				busy = true;
				createURLfileLayer(urlFile, type, epsg, $("#dinamic_chck").is(':checked'),jQuery("#input-url-file-name").val(), 
						   jQuery("#input-coord-x").val(),jQuery("#input-coord-y").val(),
						   jQuery('.nav-pills-urlfile .active').attr('id'),//per coordenades o codis o adreces
						   jQuery('#cmd_codiType_Capa_de').val(), jQuery('#cmd_codiType_de').val(), jQuery("#input-camp-codi-urlfile").val());
			}else{
				$('#dialog_dades_ex').modal('hide');
				$('#dialog_info_upload_txt').html(window.lang.translate("S'està processant un arxiu. Si us plau, espereu que aquest acabi."));
				$('#dialog_info_upload').modal('show');										
			}
		}
	});
}



<file_sep>/geocatweb/js/geocat.sessio-1.0.0.js
var trackEventFrom = '';

jQuery(document).ready(function() {
	jQuery(document).keypress(function(e) {
		if(e.which == 13) {
			jQuery("#login_button").click();
		}
	});
	
	if(url('?from')){
		trackEventFrom = url('?from');
	}
	
	if(url('?token')){
		loginToken({token:url('?token')}).then(function(results){
			if(results.status==='OK'){
				if (results.uid){
					Cookies.set('uid', results.uid);
					Cookies.set('tipusEntitat', results.tipusEntitat);
					Cookies.set('token', results.token);
				}
				redirectLogin(results, trackEventFrom);
			}else if(results.results === 'cannot_authenticate'){
				$('#modal_wrong_user').modal('toggle');						
			}
		});
	}
	
	$.publish('loadConfig', null);
	
});//Fi document ready

jQuery("#login_button").click(function(){

	_gaq.push(['_trackEvent',trackEventFrom,'inici sessio', 'retention']);
	
	checkValidityLogin("");
	
	if(! $("span").hasClass( "text_error" )){
		$("#modal-message").remove();
		var user_login =jQuery("#login_user").val();
		var pass_login = jQuery("#login_pass").val();
		var dataUrl = {user:user_login, password:<PASSWORD>};
		if (isRandomUser(Cookies.get('uid'))){
			dataUrl.randomuid = Cookies.get('uid');
		}
		
		doLogin(dataUrl).then(function(results){
			if(results.status==='OK'){
				if (results.uid){
					Cookies.set('uid', results.uid);
					Cookies.set('tipusEntitat', results.tipusEntitat);
					Cookies.set('token', results.token);
				}else{
					Cookies.set('uid', user_login);
					Cookies.set('token', results.token);
				}
				if(results.login_icgc){
					$('#modal_login_new_icgc').modal('toggle');
					jQuery('#modal_login_new_icgc').on('hide.bs.modal', function (e) {
						redirectLogin(results, trackEventFrom);
					});
				}else{
					redirectLogin(results, trackEventFrom);
				}
			}else if(results.results === 'cannot_authenticate'){
				$('#modal_wrong_user').modal('toggle');						
			}else if(results.results === 'account_locked'){
				$('#modal_account_block').modal('toggle');						
			}else if(results.results === 'unregistered_user'){
				$('#modal_login_ko_donat_baixa').modal('toggle');
				if (Cookies.get('collaboratebid')) Cookies.remove('collaboratebid');
				if (Cookies.get('collaborateuid')) Cookies.remove('collaborateuid');	
			}else if (results.status === 'MAIL'){
				window.location = results.url;
			}else{
				$('#modal_login_ko').modal('toggle');				
			}				
		},function(results){
			$('#modal_login_ko').modal('toggle');					
		});
	}
});


//Recordar/modificar contrasenya
jQuery("#btn_remember_pssw").click(function(){
	window.location.href = paramUrl.oblidatPage;
	
});

jQuery("#perfil_button_remember").click(function(){
var contingut= "Tal i com ens has sol·licitat hem procedit a assignar-te una nova contrasenya per l'accés als serveis de la nostra web. Les noves dades d'accés són:";
var data = {
		to:$('#perfil_email').val(),
		subject:window.lang.translate('Instamaps.Recordatori contrasenya'),
		esRecordatoriContrasenya: 'S',
		content: contingut
};
sendMail(data).then(function(results){
	//console.debug(results);							
});
});

jQuery("#demo_button").click(function(){
	window.location.href = paramUrl.mapaPage+"?tipus=geolocal";	
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio demo geolocal','retention']);
});

function loginUserIcgc(){
	checkValidityLogin("_icgc");
	
	if(! $("span").hasClass( "text_error" )){
		$("#modal-message").remove();
		var user_login_icgc =jQuery("#login_user_icgc").val();
		var pass_login_icgc = jQuery("#login_pass_icgc").val();
		var dataUrl = {user:user_login_icgc, password:<PASSWORD>};
		if (isRandomUser(Cookies.get('uid'))){
			dataUrl.randomuid = Cookies.get('uid');
		}
		doLoginIcgc(dataUrl).then(function(results){
			if(results.status==='OK'){
				Cookies.set('uid', results.uid);
				Cookies.set('tipusEntitat', results.tipusEntitat);
				Cookies.set('token', results.token);
				redirectLogin(results, trackEventFrom);
			}else if (results.status === 'MAIL'){
				window.location = results.url;
			}else if(results.results === 'cannot_authenticate'){
				$('#dialog_session_icgc').modal('toggle');
				$('#modal_wrong_user').modal('toggle');						
			}else if(results.results === 'account_locked'){
				$('#dialog_session_icgc').modal('toggle');
				$('#modal_account_block').modal('toggle');						
			}else{
				$('#dialog_session_icgc').modal('toggle');
				$('#modal_login_ko').modal('toggle');				
			}				
		},function(results){
			$('#dialog_session_icgc').modal('toggle');
			$('#modal_login_ko').modal('toggle');
		});
	}
}

function checkValidityLogin(tipus){
	$('#login_user'+tipus).removeClass("invalid");
	$('#login_pass'+tipus).removeClass("invalid");
	$( ".text_error" ).remove();
	
	if(isBlank($('#login_user'+tipus).val())){
		$('#login_user'+tipus).addClass("invalid");
		$('#login_user'+tipus).after("<span class=\"text_error\" lang=\"ca\">El camp no pot estar buit</span>");
	}
	var pass_length = 0;
	if(tipus == "") pass_length = 4;
	
	if(isBlank($('#login_pass'+tipus).val())){
		$('#login_pass'+tipus).addClass("invalid");
		$('#login_pass'+tipus).after("<span class=\"text_error\" lang=\"ca\">El camp no pot estar buit</span>");
	}else if($('#login_pass'+tipus).val().length < pass_length){
		$('#login_pass'+tipus).addClass("invalid");
		$('#login_pass'+tipus).after("<span class=\"text_error\" lang=\"ca\">La contrasenya ha de tenir com a mínim 4 caràcters.</span>");
	}
}
  
$('#signin_twitter').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio twitter','retention']);
	window.location = paramUrl.socialAuth+"id=twitter";
});

$('#signin_facebook').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio facebook','retention']);
	window.location = paramUrl.socialAuth+"id=facebook";
});

$('#signin_linkedin').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio linkedin','retention']);
	window.location = paramUrl.socialAuth+"id=linkedin";
});

$('#signin_google').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio google','retention']);
	window.location = paramUrl.socialAuth+"id=googleplus";
});

$('#signin_icc').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio icc','retention']);
	$('#dialog_session_icgc').modal('show');
});

$('#signin_eacat').click(function() {
	_gaq.push(['_trackEvent',trackEventFrom, 'inici sessio eacat','retention']);
	window.location = paramUrl.eacat;
});

function fesRegistre(){
	//TODO REVISAR; AQUEST CAL???? NO ES PAS INTERMIG???
	if(trackEventFrom==null || trackEventFrom=="") trackEventFrom = "inici sessio";
	_gaq.push(['_trackEvent', trackEventFrom,'registre', 'pre-activation']);
	window.location = "registre.html?from="+trackEventFrom;
}

function redirectLogin(results, from){
	if(results.results === 'login_map'){
		if (results.mapBusinessId){
			window.location=GEOCAT02+paramUrl.mapaPage+"?businessid="+results.mapBusinessId;
		}else{
			window.location=GEOCAT02+paramUrl.mapaPage;
		}
	}else if(isGeolocalUser() && from != '' && from in paramAplications){
		var token = Cookies.get('token');
		window.open(paramAplications[from].url+results.uid+"&token="+token);
		window.location=GEOCAT02+paramUrl.galeriaPage+"?private=1&aplicacions=1";
	}else{
		if (Cookies.get('collaboratebid')) {
			if (Cookies.get('collaborateuid')){
				if (Cookies.get('collaborateuid')!=Cookies.get('uid')) {
					alert("No pots donar d'alta el mapa col·laboratiu perquè els usuaris no són iguals")
					window.location=GEOCAT02+paramUrl.galeriaPage+"?private=1";
					Cookies.remove('collaboratebid');
					Cookies.remove('collaborateuid');
				}
				else {
					window.location=GEOCAT02+paramUrl.visorPage+'?businessid='+Cookies.get('collaboratebid')+'&uid='+Cookies.get('uid')+'&mapacolaboratiu=alta';
				}
			}
			else {
				window.location=GEOCAT02+paramUrl.visorPage+'?businessid='+Cookies.get('collaboratebid')+'&uid='+Cookies.get('uid')+'&mapacolaboratiu=alta';
				Cookies.remove('collaboratebid');
				Cookies.remove('collaborateuid');
			}
		}
		else window.location=GEOCAT02+paramUrl.galeriaPage+"?private=1";
	}
}<file_sep>/geocatweb/js/geocat.compartir.js
/**
 * Funcionalitat compartir en xarxes socials
 */

function addCompartirMapa(){
	
	addHtmlInterficieCompartirMapa();
	
	var v_url = window.location.href;
	if (!url('?id')){
		v_url += "&id="+jQuery('#userId').val();
	}
	v_url = v_url.replace('localhost',DOMINI);
	v_url = v_url.replace('mapa','visor');	
	
	if (v_url.indexOf("mapacolaboratiu=si")>-1) v_url=v_url.replace("&mapacolaboratiu=si","");
	
	
	//Compartir en xarxes socials
	if (isRandomUser(Cookies.get('uid'))){
	
		jQuery(window).on('beforeunload',function(event){
			return 'Are you sure you want to leave?';
		});							
	
		jQuery('#socialShare').share({
			networks: ['email','facebook','googleplus','twitter','linkedin','pinterest'],
			theme: 'square'
		});
		
		jQuery('#socialShare .pop-social').off('click').on('click', function(event){
			event.preventDefault();
			jQuery('.modal').modal('hide');
			$('#dialgo_messages').modal('show');
			$('#dialgo_messages .modal-body').html(window.lang.translate(msg_noguarda));
		});
	}else{
		shortUrl(v_url).then(function(results){
			jQuery('#socialShare').share({
				networks: ['email','facebook','googleplus','twitter','linkedin','pinterest'],
				theme: 'square',
				urlToShare: results.id
			});
			
			jQuery('#socialShare .pop-social').on('click', function(event){
//				console.debug("social share click, publiquem!");
				publicarMapa(true);
			});				
		});
	}	
}

function addCompartirVisor(){
	var v_url = window.location.href;
	if(v_url.indexOf('localhost')!=-1){
		v_url = v_url.replace('localhost',DOMINI);
	}
	if (v_url.indexOf("mapacolaboratiu=si")>-1) v_url=v_url.replace("&mapacolaboratiu=si","");
	
	shortUrl(v_url).then(function(results){
		jQuery('#socialShare_visor').share({
			networks: ['email','facebook','googleplus','twitter','linkedin','pinterest'],
			//orientation: 'vertical',
			//affix: 'left center',
			theme: 'square',
			urlToShare: results.id
		});
	});	
	
	jQuery('.share-square a').attr('target','_blank');
	
	/*
	 * se declara el evento en el control 
	jQuery("#dv_bt_Share").on('click',function(e){
		posaClassActiu('#span_bt_Share');
		jQuery('#socialShare_visor').css('top', (e.clientY - 30) +'px');
		jQuery('#socialShare_visor').css('left', (e.clientX + 20) +'px');
		jQuery('#socialShare_visor').toggle();
		aturaClick(e);
	});
	*/
}

function posaClassActiu(_element){
	var cl = jQuery(_element).attr('class');
	if (cl.indexOf('grisfort') != -1) {
		jQuery(_element).removeClass('grisfort');
		jQuery(_element).addClass('greenfort');
	} else {
		jQuery(_element).removeClass('greenfort');
		jQuery(_element).addClass('grisfort');
	}
}

function addHtmlInterficieCompartirMapa(){
	jQuery("#funcio_compartir").append(
			'<div id="socialShare" class="div_gr5_social">'+
				'<h5 lang="ca">Compartir</h5>'+
			'</div>'
	);
}<file_sep>/geocatweb/js/geocat.mapa.categories.js
/**
 * Gestio del temàtic de tipus Categories 
 */

function showModalTematicCategories(data){
	//console.debug("showModalTematicCategories");
	jQuery('.modal').modal('hide');
	jQuery('#dialog_tematic_rangs').modal('show');
	
	//se ponen los off para evitar el doble evento
	//TODO hay que revisar como evitar el doble evento.
	jQuery('#dialog_tematic_rangs .btn-success').off('click');
	jQuery('#dialog_tematic_rangs .btn-success').on('click',function(e){
		jQuery('#dialog_tematic_rangs').hide();
		jQuery('#info_uploadFile').show();
		busy=true;
		jQuery("#div_uploading_txt").html("");
		jQuery("#div_uploading_txt").html(
			'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
			'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'
		);	
		createTematicLayerCategories(e);
	});	
	
	jQuery('#palet_warning').hide();
	
	jQuery(".ramp").off('click');
	jQuery(".ramp").on('click',function(evt){
		var _this = jQuery(this);
		var brewerClass = _this.attr('class').replace("ramp ","");
		jQuery("#dialog_tematic_rangs").data("paleta", brewerClass);
		if (jQuery('#list_tematic_values').html() !== ""){
			updatePaletaRangs();
		}
	});
	
	jQuery("#dialog_tematic_rangs").data("capamare", data);
	
	jQuery('#tipus_agrupacio_grp').hide();
	jQuery('#num_rangs_grp').hide();
	jQuery('#list_tematic_values').html("");
	jQuery('#dialog_tematic_rangs .btn-success').hide();
	
	jQuery('.btn-reverse-palete').off('click');
	jQuery('.btn-reverse-palete').on('click',function(evt){
		var glyp = jQuery('.btn-reverse-palete.glyphicon');
		var reverse = false;
		if(glyp.hasClass('glyphicon-arrow-down')){
			reverse = true;
			glyp.removeClass('glyphicon-arrow-down').addClass('glyphicon-arrow-up');
		}else{
			reverse = false;
			glyp.removeClass('glyphicon-arrow-up').addClass('glyphicon-arrow-down');
		}
		jQuery("#dialog_tematic_rangs").data("reverse",reverse);
		//console.debug(jQuery("#dialog_tematic_rangs").data("reverse"));
		if (jQuery('#list_tematic_values').html() !== ""){
			updatePaletaRangs();
		}
	});
	
	var dataTem={
		businessId: data.businessid,
		uid: Cookies.get('uid')
	};
	
	if(data.tipus == t_url_file){
		var urlFileLayer = controlCapes._layers[data.leafletid].layer;
		jQuery("#dialog_tematic_rangs").data("visualitzacio", urlFileLayer.options);
		var fields = {};
		//fields[window.lang.translate('Escull el camp')] = '---';
		//Recollim propName de les geometries de la capa
		var dataNames = urlFileLayer.options.propName.split(',');
		jQuery.each(dataNames, function( index, value ) {
			fields[value] = value;
		});
		//creamos el select con los campos
		var source1 = jQuery("#tematic-layers-fields").html();
		var template1 = Handlebars.compile(source1);
		var html1 = template1({fields:fields});
		jQuery('#dataField').html(html1);
		
		jQuery('#dataField').off('change');
		jQuery('#dataField').on('change',function(e){
			var this_ = jQuery(this);
			if (this_.val() == "---"){
				jQuery('#tipus_agrupacio_grp').hide();
				jQuery('#num_rangs_grp').hide();
				jQuery('#list_tematic_values').html("");
				jQuery('#dialog_tematic_rangs .btn-success').hide();
			}else{				
				readDataUrlFileLayer(urlFileLayer, this_.val()).then(function(results){
					jQuery("#dialog_tematic_rangs").data("values", results);
					getTipusValuesVisualitzacio(results,data.geometrytype);
				});			
			}
		});			
		
	}else{
		var dataNames = [];
		var fields = {};
		//fields[window.lang.translate('Escull el camp')] = '---';
		dataNames = data.propname.split(',');
		jQuery.each(dataNames, function( index, value ) {
			if (value!='') 	fields[value] = value;
		});
		if(data.propname=='null' || data.propname==''){
			fields['nom']='nom';
			fields['text']='text';
		}
		
		//creamos el select con los campos
		var source1 = jQuery("#tematic-layers-fields").html();
		var template1 = Handlebars.compile(source1);
		
		console.debug(fields);
		var html1 = template1({fields:fields});
		jQuery('#dataField').html(html1);
		
		jQuery('#dataField').off('change');
		jQuery('#dataField').on('change',function(e){
			var this_ = jQuery(this);
			if (this_.val() == "---"){
				jQuery('#tipus_agrupacio_grp').hide();
				jQuery('#num_rangs_grp').hide();
				jQuery('#list_tematic_values').html("");
				jQuery('#dialog_tematic_rangs .btn-success').hide();
			}else{
				var dataVis={
						businessId1: data.businessid,
						key: this_.val(),
						uid: Cookies.get('uid')
				};
				getValuesFromKeysProperty(dataVis).then(function(results){
					jQuery("#dialog_tematic_rangs").data("values", results);
					getTipusValuesVisualitzacio(results);					
				});
			}
		});	
		
		//Si es una visualitzacio
		/*getVisualitzacioByBusinessId(dataTem).then(function(results){
			if (results.status == "OK"){
				var visualitzacio = results.results;
				jQuery("#dialog_tematic_rangs").data("visualitzacio", visualitzacio);
				var fields = {};
				fields[window.lang.translate('Escull el camp')] = '---';
				var dataNames = [];
				if (visualitzacio.options){
					//var options = JSON.parse(visualitzacio.options);
					var options;
					if(typeof (visualitzacio.options)=="string"){
						try {
							options = JSON.parse(visualitzacio.options);
						}
						catch (err) {
							options = visualitzacio.options;	
						}
						
					}else{
						
						options = visualitzacio.options;	
					}
					
					if(options.propName){
						dataNames = options.propName.split(',');
						jQuery.each(dataNames, function( index, value ) {
							fields[value] = value;
						});
					}else{
						if (results.geometries && results.geometries.options){
							dataNames = results.geometries.options.split(',');
							jQuery.each(dataNames, function( index, value ) {
								fields[value] = value;
							});
						}
					}
				}else{
					if (results.geometries && results.geometries.options){
						dataNames = results.geometries.options.split(',');
						jQuery.each(dataNames, function( index, value ) {
							fields[value] = value;
						});
					}
				}
				
				//creamos el select con los campos
				var source1 = jQuery("#tematic-layers-fields").html();
				var template1 = Handlebars.compile(source1);
				var html1 = template1({fields:fields});
				jQuery('#dataField').html(html1);
				
				jQuery('#dataField').off('change');
				jQuery('#dataField').on('change',function(e){
					var this_ = jQuery(this);
					if (this_.val() == "---"){
						jQuery('#tipus_agrupacio_grp').hide();
						jQuery('#num_rangs_grp').hide();
						jQuery('#list_tematic_values').html("");
						jQuery('#dialog_tematic_rangs .btn-success').hide();
					}else{
						readDataVisualitzacio(visualitzacio, this_.val()).then(function(results){
							jQuery("#dialog_tematic_rangs").data("values", results);
							getTipusValuesVisualitzacio(results);
						});

					}
				});				
			}else{
				//TODO error
				console.debug("getVisualitzacioByBusinessId ERROR");				
			}
		},function(results){
			//TODO error
			console.debug("getVisualitzacioByBusinessId ERROR");
		});	*/
	}
				
}

function getTipusValuesVisualitzacio(results,geomType){
	//console.debug("getTipusValuesVisualitzacio");
	var resultats;
	if (results.valors!=undefined) resultats=results.valors;
	else resultats=results;
	
	var geometryType;
	if (results.geomType!=undefined) geometryType=results.geomType;
	else geometryType=geomType;

	
	if (resultats.length === 0){
		var warninMSG="<div class='alert alert-danger'><strong>"+window.lang.translate('Aquest camp no te valors')+"<strong>  <span class='fa fa-warning sign'></span></div>";
		jQuery('#list_tematic_values').html(warninMSG);
		jQuery('#dialog_tematic_rangs .btn-success').hide();
	}else{
		var nodata = [];
		var esText = false;
		var arr = jQuery.grep(resultats, function( n, i ) {
			var isText = false;
			if (!jQuery.isNumeric(n)){
				if (n == "Sense valor" || n == "Sin valor" || n == "Empty value" || n == NODATA_VALUE){
					nodata.push(n);
				}else{
					isText = true;
				}
			}
			return isText;
		});
		if (nodata.length !== 0){
			jQuery("#dialog_tematic_rangs").data("nodata",true);
		}
		if (arr.length === 0){ //rangos o semafòric
			jQuery('#tipus_agrupacio_grp').show();
			jQuery('#num_rangs_grp').show();
			jQuery('#list_tematic_values').html("");
			
			jQuery( "input:radio[name=rd_tipus_agrupacio]").on('change',function(e){
				var this_ = jQuery(this);
				if (this_.val() == "U"){
					jQuery('#num_rangs_grp').hide();
					showVisualitzacioDataUnic(resultats,geometryType).then(function(results1){
						loadTematicValueTemplate(results1,'unic');
					});
				}else if(this_.val() == "S") {
					jQuery('#num_rangs_grp').hide();
					createSemaforicValues(geometryType);
				}
				else {
					jQuery('#list_tematic_values').html("");
					jQuery('#dialog_tematic_rangs .btn-success').hide();
					jQuery('#num_rangs_grp').show();
					jQuery('#cmb_num_rangs').val("---");
					jQuery('#list_tematic_values').html("");
					jQuery('#dialog_tematic_rangs .btn-success').hide();
				}
			});
			
			jQuery('#cmb_num_rangs').on('change',function(e){
				var this_ = jQuery(this);
				if (this_.val() == "---"){
					jQuery('#list_tematic_values').html("");
					jQuery('#dialog_tematic_rangs .btn-success').hide();
				}else{
					createRangsValues(this_.val(),geometryType);
				}
			});
			
			jQuery('#rd_tipus_rang').click().change();		
		}else{ //unicos
			jQuery('#tipus_agrupacio_grp').hide();
			jQuery('#num_rangs_grp').hide();
			showVisualitzacioDataUnic(resultats,geometryType).then(function(results1){
				loadTematicValueTemplate(results1,'unic');
			});
		}
	}
}

function showVisualitzacioDataUnic(values,geomType){
	var defer = jQuery.Deferred();
	//var visualitzacio = jQuery("#dialog_tematic_rangs").data("visualitzacio");
	var paleta = jQuery("#dialog_tematic_rangs").data("paleta");
	var reverse = jQuery("#dialog_tematic_rangs").data("reverse");
	jQuery("#dialog_tematic_rangs").data("tipusrang","unic");
	//Ordenar valores
	values.sort(sortByValueMax);
	//console.debug(paleta);
	paleta = paleta ? paleta : 'Paired';
	//console.debug(values.length);
	var scale = createScale(paleta, values.length, reverse);	
	var ftype = transformTipusGeometry(geomType);	
	var valuesStyle = jQuery.map( values, function( a, i) {
		//console.debug(createIntervalStyle(i,ftype,scale));
		return {v: a, style: createIntervalStyle(i,ftype,scale), index: i};
	});
	defer.resolve(valuesStyle);
	return defer.promise();
}

function createIntervalStyle(index, geometryType, paleta, nodata){
	//console.debug("createIntervalStyle");
	var defStyle;
	var ftype = transformTipusGeometry(geometryType);
		
	if (ftype == t_marker){
		defStyle = jQuery.extend({}, default_circulo_style);
		defStyle.fillColor = paleta(index).hex();
		if(nodata){
			defStyle.fillColor = NODATA_COLOR;
		}
		defStyle.isCanvas = true;		
	}else if (ftype == t_polyline){
		defStyle = jQuery.extend({}, default_line_style);
		defStyle.color = paleta(index).hex();
		if(nodata){
			defStyle.color = NODATA_COLOR;
		}
	}else if (ftype == t_polygon){
		defStyle = jQuery.extend({}, default_area_style);
		defStyle.color = paleta(index).hex();
		if(nodata){
			defStyle.color = NODATA_COLOR;
		}
	}
	defStyle.geometryType = ftype;
	return defStyle;
}

function showTematicRangs(geomType){
	//TODO cambiar nombre a la funcion
	//console.debug("showTematicRangs");
	var values = jQuery("#dialog_tematic_rangs").data("rangs");
	//var visualitzacio = jQuery("#dialog_tematic_rangs").data("visualitzacio");
	var paleta = jQuery("#dialog_tematic_rangs").data("paleta");
	var reverse = jQuery("#dialog_tematic_rangs").data("reverse");
	jQuery("#dialog_tematic_rangs").data("tipusrang","rangs");
	paleta = paleta ? paleta : 'Paired';
	var scale = createScale(paleta, values.length, reverse);
			
	var defer = jQuery.Deferred();
	var valuesStyle = [];
	var ftype = transformTipusGeometry(geomType);
	valuesStyle = jQuery.map( values, function( a, i ) {
		if (a.nodata){
			return {v: a, style: createIntervalStyle(i,ftype,scale,true), index: i};
		}else{
			return {v: a, style: createIntervalStyle(i,ftype,scale,false), index: i};
		}
	});
	defer.resolve(valuesStyle);
	return defer.promise();
}

function div2RangStyle(tematic, tdElem){
	//console.debug("div2RangStyle");
	var rangStyle;
	
	var ftype = transformTipusGeometry(tematic.geometrytype);
	var divElement;	
	if (ftype == t_marker){
		divElement = tdElem.find('div');
		rangStyle = {
			borderColor :  "#ffffff",
			borderWidth :  2,
			simbolSize: parseInt(parseInt(divElement.css('height'))/2.4),
			color: jQuery.Color(divElement.css('background-color')).toHexString(),
			opacity: 90
		};
	}else if (ftype == t_polyline){
		divElement = tdElem.find('canvas')[0].getContext("2d");
		rangStyle = {
			lineWidth :  divElement.lineWidth,
			color: divElement.strokeStyle,
		};
	}else if (ftype == t_polygon){
		divElement = tdElem.find('canvas')[0].getContext("2d");
		rangStyle = {
			borderColor :  divElement.strokeStyle,
			borderWidth :  divElement.lineWidth,
			color: jQuery.Color(divElement.fillStyle).toHexString(),
			opacity: Math.round(jQuery.Color(divElement.fillStyle).alpha()*100)		
		};
	}
	return rangStyle;
}

function createTematicLayerCategories(event, extraOptions, extraData, deferred){
//	console.debug("createTematicLayerCategories"); //al guardar
	_gaq.push(['_trackEvent', 'mapa', tipus_user+'estils', 'categories', 1]);
	
	var tematic = jQuery("#dialog_tematic_rangs").data("tematic");
	var tipusRang = $("input:radio[name=rd_tipus_agrupacio]:checked").val();
//	var visualitzacio = jQuery("#dialog_tematic_rangs").data("visualitzacio");
//	console.debug(visualitzacio);
	var tematicFrom = jQuery("#dialog_tematic_rangs").data("capamare");
	var capaMare = controlCapes._layers[tematicFrom.leafletid].layer;
	var rangsTr = jQuery('#list_tematic_values tbody tr');

	var rangs = [];
	var layerName = capaMare.options.nom+" "+window.lang.translate("Categories");
	
	if("S" != tipusRang)
	{

		jQuery.each(rangsTr, function( index, value ) {
			var _this = jQuery(value);
			var tdRang, tdMin, tdMax;
			var tdVal;
			var rang = {};
			var rangEstil;
			if (_this.children().length == 2){
				tdRang = _this.find('td:eq(0)');
				//console.debug(tdRang);
				tdVal = _this.find('td:eq(1)');
				//console.debug(tdVal);
				rangEstil = div2RangStyle(tematicFrom, tdVal);
				rang.estil = rangEstil;
				rang.valueMax = tdRang.text();
				rang.valueMin = tdRang.text();
				rangs.push(rang);
			}else{
				tdMin = _this.find('td:eq(0)');
				tdMax = _this.find('td:eq(1)');
				tdVal = _this.find('td:eq(2)');
				//console.debug(tdMin);
				//console.debug(tdMax);
				//console.debug(tdVal);
				rangEstil = div2RangStyle(tematicFrom, tdVal);
				rang.estil = rangEstil; 
				rang.valueMin = tdMin.find('input').val();
				rang.valueMax = tdMax.find('input').val();
				rangs.push(rang);
			}
		});

	}
	else
	{

		var auxRangs = $("#dialog_tematic_rangs").data("rangs");
		$.each(auxRangs, function(index, value)
		{

			var rang = {};
			rang.estil = div2RangStyle(tematicFrom, $(rangsTr[index]).find("td:last"));
			rang.valueMin = value.min;
			rang.valueMax = value.max;
			rangs.push(rang);

		});

		var key = $("#dataField").val();
		layerName = key + " " + window.lang.translate("Escala de color") + " " + window.lang.translate("(Valor de ref: ") + auxRangs[1].min + ")";
		extraData = {trafficLightKey: key, trafficLightValue: auxRangs[1].min, trafficLightLowerColor: rangs[0].estil.color, 
			trafficLightEqualColor: rangs[1].estil.color, trafficLightHigherColor: rangs[2].estil.color};

	}
	//console.debug(rangs);
	var estils = {
		estils: rangs,
		dataField: jQuery('#dataField').val().toLowerCase(),
		labelField: jQuery('#dataField').val().toLowerCase()
	};
	var data1 = {};
	if(capaMare.tipus == t_url_file || tematicFrom.tipus==t_url_file){
		data1 = {
			uid: Cookies.get('uid'),
			businessId1: capaMare.options.businessId
		};
		crearFitxerPolling(data1).then(function(results) {
			var tmpFile="";
			if (results.status=="OK"){
				tmpFile = results.tmpFilePath;
				//Definim interval de polling en funcio de la mida del fitxer
				var pollTime =3000;
				//Fem polling
				(function(){							
					pollBuffer = function(){
						$.ajax({
							url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
							dataType: 'json',
							type: 'get',
							success: function(data){
								//console.debug(data);
								jQuery('#dialog_tematic_rangs').hide();
								jQuery('#info_uploadFile').show();
								if(data.status.indexOf("PAS 1")!=-1 && busy){
									
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
									);									
									
								}else if((data.status.indexOf("PAS 2") || data.status.indexOf("PAS 3"))!=-1 && busy){
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
									);										
								}else if(data.status.indexOf("OK")!=-1 && busy){
									//console.debug(data);
									clearInterval(pollInterval);
									
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Processant la resposta')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'
									);									
									
									loadURLfileLayer(data.results).then(function(results){
										activaPanelCapes(true);
										//Desactivem la capa mare
										if ($( "#input-"+capaMare.options.businessId).attr("checked")!=undefined) $( "#input-"+capaMare.options.businessId).click();
										//L'afegim a les dades guardades
										if(!controlCapes.hasOwnProperty("_visLayers"))
										{
										
											controlCapes._visLayers = {};
											controlCapes._options = {};
										}
										controlCapes._visLayers[data.layer.businessId] = data.visualitzacio;
										controlCapes._options[data.layer.businessId] = data.layer;
										if(undefined !== deferred)
											deferred.resolve(results._leaflet_id);
									});
									busy=false;					
									jQuery('#info_uploadFile').hide();
									
								}else if(data.status.indexOf("ERROR")!=-1 && busy){
									console.error("Error calculant l'operació");
									console.error(data);
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									$('#dialog_error_upload_txt').html("");
									
									$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));										
									
									$('#dialog_error_upload').modal('show');
								}
								else if (!busy){
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
								}
							}
						});
					};
					
					pollInterval = setInterval(function(){
						pollBuffer();
					},pollTime);
					
				})();
				
				var options = {
						url: capaMare.options.url,
						tem: tem_clasic,
						style: estils,
						origen: capaMare.options.businessId,
						tipus : t_url_file,
						tipusFile: capaMare.options.tipusFile,
						tipusAcc: capaMare.options.tipusAcc,
						tipusCodi: capaMare.options.tipusCodi,
						tipusFont: capaMare.options.tipusFont,
						nomCampCodi: capaMare.options.nomCampCodi,
						estil_do: estils,
						epsgIN: capaMare.options.epsgIN,
						geometryType: capaMare.options.geometryType,
						colX: capaMare.options.colX,
						colY: capaMare.options.colY,
						dinamic: capaMare.options.dinamic						
					};
					$.extend(options, extraOptions);
			
					var data = {
						uid:Cookies.get('uid'),
						mapBusinessId: url('?businessid'),
						serverName: layerName,
						serverType: capaMare.options.tipus,
						calentas: false,
				        activas: true,
				        visibilitats: true,
				        order: capesOrdre_sublayer,				
				        epsg: capaMare.options.epsgIN,
				        transparency: true,
				        opacity: 1,
				        visibilitat: 'O',
				        url: capaMare.options.url,
						options: JSON.stringify(options),
						tmpFilePath: tmpFile,
						tipusTematic:"t_url_file",
						urlTematic:paramUrl.createServidorInMap,
						paleta: jQuery("#dialog_tematic_rangs").data("paleta"),
						reverse: jQuery("#dialog_tematic_rangs").data("reverse")
					};
					$.extend(data, extraData);
					callActions(data);
					/*createServidorInMap(data);/*.then(function(results){
						busy=false;					
						jQuery('#info_uploadFile').hide();
						loadURLfileLayer(results.results).then(function(results){
							
							activaPanelCapes(true);
						});
					});*/
			}
			else {
				jQuery('#info_uploadFile').hide();		
				busy=false;
			}
					
		 });
	}else{
		data1 = {
			uid: Cookies.get('uid'),
			businessId1: capaMare.options.businessId
		};
		crearFitxerPolling(data1).then(function(results) {
			var tmpFile="";
			if (results.status=="OK"){
				tmpFile = results.tmpFilePath;
				//Definim interval de polling en funcio de la mida del fitxer
				var pollTime =3000;
				//Fem polling
				(function(){							
					pollBuffer = function(){
						$.ajax({
							url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
							dataType: 'json',
							type: 'get',
							success: function(data){
								//console.debug(data);
								jQuery('#dialog_tematic_rangs').hide();
								jQuery('#info_uploadFile').show();
								if(data.status.indexOf("PAS 1")!=-1 && busy){
									
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
									);									
									
								}else if((data.status.indexOf("PAS 2")!=-1 || data.status.indexOf("PAS 3")!=-1) && busy){
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
											'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
									);										
								}else if(data.status.indexOf("OK")!=-1 && busy){
									clearInterval(pollInterval);
									
									jQuery("#div_uploading_txt").html("");
									jQuery("#div_uploading_txt").html(
											'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
											'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Processant la resposta')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'
									);									
									var defer = $.Deferred();
									readVisualitzacio(defer, data.visualitzacio, data.layer).then(function(results){
										activaPanelCapes(true);
										//Desactivem la capa mare
										if ($( "#input-"+capaMare.options.businessId).attr("checked")!=undefined) $( "#input-"+capaMare.options.businessId).click();
										//L'afegim a les dades guardades
										if(!controlCapes.hasOwnProperty("_visLayers"))
										{
										
											controlCapes._visLayers = {};
											controlCapes._options = {};
										}
										controlCapes._visLayers[data.layer.businessId] = data.visualitzacio;
										controlCapes._options[data.layer.businessId] = data.layer;
										if(undefined !== deferred)
											deferred.resolve(results._leaflet_id);
									});
									jQuery('#info_uploadFile').hide();		
									busy=false;
								}else if(data.status.indexOf("ERROR")!=-1 && busy){
									console.error("Error calculant l'operació");
									console.error(data);
									busy = false;
									
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
									
									$('#dialog_error_upload_txt').html("");
									
									$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));
									
									$('#dialog_error_upload').modal('show');
								}
								else if (!busy){
									clearInterval(pollInterval);
									jQuery('#info_uploadFile').hide();
								}
							}
						});
					};
					
					pollInterval = setInterval(function(){
						pollBuffer();
					},pollTime);
					
				})();

				var data = {
						businessId: tematicFrom.businessid,//businessId id de la visualización de origen
						uid: Cookies.get('uid'),//uid id de usuario
				        mapBusinessId: url('?businessid'),//mapBusinessId id del mapa donde se agrega la visualización	           
				        nom: layerName,
				        activas: true,
				        order: capesOrdre_sublayer,//order (optional) orden de la capa en el mapa
				        dataField: jQuery('#dataField').val(),//¿?¿?¿?¿?
						tem: tem_clasic,//visualitzacio.from,//tem_simple
						estils: JSON.stringify(estils),
						tmpFilePath: tmpFile,
						tipusTematic:"t_visualitzacio_categories",
						urlTematic:paramUrl.createVisualitzacioTematica,
						paleta: jQuery("#dialog_tematic_rangs").data("paleta"),
						reverse: jQuery("#dialog_tematic_rangs").data("reverse")
					};
					$.extend(data, extraData);
					callActions(data);
				//	createVisualitzacioTematica(data);
			}
			else {
				jQuery('#info_uploadFile').hide();		
				busy=false;
			}
		
			
			
			/*createVisualitzacioTematica(data);/*.then(function(results){
				jQuery('#info_uploadFile').hide();		
				busy=false;
				if(results.status == 'OK'){
					var defer = $.Deferred();
					readVisualitzacio(defer, results.visualitzacio, results.layer).then(function(results){
						activaPanelCapes(true);
					});				
				}
			});		*/
		});				
	}
	
	event.preventDefault();
	event.stopImmediatePropagation();

	if("undefined" !== typeof deferred)
		return deferred.promise();
	
}

function updatePaletaRangs(softColors){
	
	var softColorsUsed = (undefined !== softColors && softColors);
	var paleta = jQuery("#dialog_tematic_rangs").data("paleta");
	var tematicFrom = jQuery("#dialog_tematic_rangs").data("capamare");
	
	//console.debug( jQuery("#dialog_tematic_rangs").data("values-norepetits"));
	var values = jQuery("#dialog_tematic_rangs").data("values-norepetits");
	//values = values;
	var rangs = jQuery("#dialog_tematic_rangs").data("rangs");
	
	var tipusrang = jQuery("#dialog_tematic_rangs").data("tipusrang");
	var reverse = jQuery("#dialog_tematic_rangs").data("reverse");
	

	
	var val_leng = 0;
	if (tipusrang == 'rangs'){
		val_leng = rangs.length;
	}else{
		val_leng = values.length;
	}

	//If soft colors are used instead of getting the [0, val_leng] and the rest evenly distributed
	//we use the half values of each interval
	//Example: 3 colors from [0, 3]
	//Non soft colors gets the colors on the [0, 1.5, 3] points
	//Soft colors gets the colors on the [0.75, 1.5, 2.25] points
	
	var ftype = transformTipusGeometry(tematicFrom.geometrytype);
	paleta = paleta ? paleta : 'Paired';

	var scale = createScale(paleta, val_leng, reverse);
	
	if (ftype == t_marker){
		var elems = $("#list_tematic_values tbody td div");
		var length = (softColors ? elems.length + 1 : elems.length - 1);
		var factor = val_leng/length;
		var start = (softColors ? factor : 0);
		elems.each(function(i, elm){
			var color = scale(start + i*factor).hex();
			jQuery(elm).css('background-color', color);
		});
	}else if (ftype == t_polyline){
		var elems = $("#list_tematic_values canvas");
		var length = (softColors ? elems.length + 1 : elems.length - 1);
		var factor = val_leng/length;
		var start = (softColors ? factor : 0);
		elems.each(function(i, elm){
			var color = scale(start + i*factor).hex();
			addGeometryInitLRang(elm, {style:{color: color}});
		});
	}else if (ftype == t_polygon){
		var elems = $("#list_tematic_values canvas");
		var length = (softColors ? elems.length + 1 : elems.length - 1);
		var factor = val_leng/length;
		var start = (softColors ? factor : 0);
		elems.each(function(i, elm){
			var color = scale(start + i*factor).hex();
			addGeometryInitPRang(elm, {style:{color: color}});
		});
	}
}

function createSemaforicValues(geomType)
{

	var values = jQuery("#dialog_tematic_rangs").data("values");
	if (values.valors!=undefined) values = values.valors;
	var nodata = jQuery("#dialog_tematic_rangs").data("nodata");
	values = jQuery.grep(values, function( n, i ) {
		return (n != NODATA_VALUE && jQuery.isNumeric(parseFloat(n)));
	});
	values.sort(function(a,b){return a-b;});
	var min = parseFloat(values[0]);
	var max = parseFloat(values[values.length-1]);
	var half = (max + min)/2;

	//Creem un vector amb els següents rangs:
	// [valor mínim, valor anterior al valor mig)
	// [valor anterior al valor mig, valor següent al valor mig)
	// [valor següent al valor mig, valor màxim]
	var newRangs = [{min: min, max: max}];
	var i = 0;
	while (values[i] <= half)
		i++;
	
	newRangs[0].max = parseFloat(values[i-1]);
	newRangs.push({min: parseFloat(values[i-1]), max: parseFloat(values[i])});
	newRangs.push({min: parseFloat(values[i]), max: max});

	if (nodata){
		newRangs.push({min: NODATA_VALUE, max: NODATA_VALUE, nodata:true});
	}
	
	jQuery("#dialog_tematic_rangs").data("rangs", newRangs);
	showTematicRangs(geomType).then(function(results){
		loadTematicValueTemplate(results,'semaforic');
		updatePaletaRangs();
	});

}

function createRangsValues(rangs,geomType){
	//console.debug("createRangsValues");
	var values = jQuery("#dialog_tematic_rangs").data("values");
	if (values.valors!=undefined) values = values.valors;
	var tematic = jQuery("#dialog_tematic_rangs").data("tematic");
	//var visualitzacio = jQuery("#dialog_tematic_rangs").data("visualitzacio");
	var nodata = jQuery("#dialog_tematic_rangs").data("nodata");
	var reverse = jQuery("#dialog_tematic_rangs").data("reverse");
	values = jQuery.grep(values, function( n, i ) {
		return (n != NODATA_VALUE && jQuery.isNumeric(parseFloat(n)));
	});
	values.sort(function(a,b){return a-b;});
	var min = parseFloat(values[0]);
	var max = parseFloat(values[values.length-1]);
	var deltaR = (max - min)/rangs;
	deltaR = parseFloat(deltaR.toFixed(2));
	var newRangs = [];
	var i = 0;
	while (min < max && i < rangs){
		if (i == (rangs-1)){
			newRangs.push({min: min, max: max});
		}else{
			var tmpmax = parseFloat((min+deltaR).toFixed(2));
			newRangs.push({min: min, max: tmpmax});
			min = tmpmax;
		}
		i++;
	}
	if (nodata){
		newRangs.push({min: NODATA_VALUE, max: NODATA_VALUE, nodata:true});
	}
	
	jQuery("#dialog_tematic_rangs").data("rangs", newRangs);
	showTematicRangs(geomType).then(function(results){
		loadTematicValueTemplate(results,'rangs');
	});
}

function loadTematicValueTemplate(results, rtype){

	var source1;
	var geometryType = results[0].style.geometryType;
	if (!geometryType){
		geometryType = results[0].style.tipus;
	}
	var ftype = transformTipusGeometry(geometryType);
	if (ftype == t_marker){
		if (rtype == 'rangs'){
			source1 = jQuery("#tematic-values-rangs-punt-template").html();
		}else if(rtype == "unic"){
			source1 = jQuery("#tematic-values-unic-punt-template").html();
		}
		else
		{
			source1 = jQuery("#tematic-values-semaforic-punt-template").html();
		}
		
	}else if (ftype == t_polyline){
		if (rtype == 'rangs'){
			source1 = jQuery("#tematic-values-rangs-polyline-template").html();
		}else if(rtype == "unic"){
			source1 = jQuery("#tematic-values-unic-polyline-template").html();
		}
		else
		{
			source1 = jQuery("#tematic-values-semaforic-polyline-template").html();
		}
		
	}else if (ftype == t_polygon){
		if (rtype == 'rangs'){
			source1 = jQuery("#tematic-values-rangs-polygon-template").html();
		}else if(rtype == "unic"){
			source1 = jQuery("#tematic-values-unic-polygon-template").html();
		}
		else
		{
			source1 = jQuery("#tematic-values-semaforic-polyline-template").html();
		}
	}
	
	var resultsNoRepetits=[];
	if (rtype=='unic'){	
		var data = {};		
		jQuery.grep(results,  function( n, i ) {
				var value = n.v;
				if(isBlank(value)) value = "nodata";
				if(!data[value]){
					data[value] = value;
					resultsNoRepetits.push(n);
				}
		});
		//match ints and floats/decimals
		var floatRegex = new RegExp('(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}');
		var resultsFloat = [];
		var i=0;
		var j=0;
		jQuery.grep(resultsNoRepetits, function( n, i ) {
			//console.debug(n.v);
			//console.debug(floatRegex.test(n.v));			
			if (floatRegex.test(n.v)) {
				//console.debug(n.v);
				resultsFloat[j]=n;
				j++;
			}
				
		});
		var template1 = Handlebars.compile(source1);
		var html1 = "";
		if (resultsFloat.length>0 && resultsNoRepetits.length == resultsFloat.length) {
			//resultsFloat.sort(function(a,b){return a.v-b.v;});
			resultsFloat.sort(sortByValueMax);
			html1 = template1({values:resultsFloat});
		}
		else {
			resultsNoRepetits.sort(sortByValueMax);
			html1 = template1({values:resultsNoRepetits});
		}
		jQuery("#dialog_tematic_rangs").data("values-norepetits",resultsNoRepetits);
	}
	else {
		
		//match ints and floats/decimals
		var floatRegex = new RegExp('(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}');
		var resultsFloat = [];
		var i=0;
		jQuery.grep(results, function( n, i ) {
			if (floatRegex.test(n.v)) {
				resultsFloat[i]=n;
				i++;
			}
				
		});
		
		var template1 = Handlebars.compile(source1);
		var html1 = "";
		if (resultsFloat.length>0) {
			resultsFloat.sort(function(a,b){return a.v-b.v;});
			html1 = template1({values:resultsFloat});
		}
		else if("semaforic" == rtype)
		{

			html1 = template1({value:results[1].v.min});

		}
		else {
			results.sort();
			html1 = template1({values:results});
		}
	}
	
	
	jQuery('#list_tematic_values').html(html1);
	jQuery('#dialog_tematic_rangs .btn-success').show();
	if (ftype == t_marker){
		jQuery('#list_tematic_values div.awesome-marker-web').on('click',function(e){
			var _this = this;
			var _$this = $(this);
			
			$("#temp_color_pallete").remove();
			
			_$this.after('<div id="temp_color_pallete" class="dropdown-menu"></div>');
			
			$("#temp_color_pallete").css({'top':_$this.position().top,'left':_$this.position().left+25}).colorPalette().on('selectColor', function(e) {
				_$this.css('background-color',e.color);
				$("#temp_color_pallete").remove();
			});
		});
		
	}else if (ftype == t_polyline){
		jQuery('#list_tematic_values canvas').each(function(i, val){
			addGeometryInitLRang(val, results[i]);
		});
		
		jQuery('#list_tematic_values canvas').on('click',function(e){
			var _this = this;
			var _$this = $(this);
			
			$("#temp_color_pallete").remove();
			
			_$this.after('<div id="temp_color_pallete" class="dropdown-menu"></div>');
			
			$("#temp_color_pallete").css({'top':_$this.position().top,'left':_$this.position().left+25}).colorPalette().on('selectColor', function(e) {
				var canvas = _this;
				var style = {style:{}};
				style.style.color = e.color;
				addGeometryInitLRang(canvas, style);
				$("#temp_color_pallete").remove();
			});
			
		});
		
	}else if (ftype == t_polygon){
		
		jQuery('#list_tematic_values canvas').each(function(i, val){
			addGeometryInitPRang(val, results[i]);
		});
		
		jQuery('#list_tematic_values canvas').on('click',function(e){
			var _this = this;
			var _$this = $(this);
			
			$("#temp_color_pallete").remove();
			
			_$this.after('<div id="temp_color_pallete" class="dropdown-menu"></div>');
			
			$("#temp_color_pallete").css({'top':_$this.position().top,'left':_$this.position().left+25}).colorPalette().on('selectColor', function(e) {
				var canvas = _this;
				var style = {style:{}};
				style.style.color = e.color;
				addGeometryInitPRang(canvas, style);
				$("#temp_color_pallete").remove();
			});
			
		});
	}
}

function addGeometryInitLRang(canvas, style){
	var	cv_ctx_l=canvas.getContext("2d");
	var scale = 0.7;
	
	cv_ctx_l.clearRect(0, 0, canvas.width, canvas.height);
		
	cv_ctx_l.shadowColor = '#999';
	cv_ctx_l.shadowBlur = 4;
	cv_ctx_l.shadowOffsetX = 2;
	cv_ctx_l.shadowOffsetY = 2;
	
	cv_ctx_l.moveTo(0.7*scale,39.42*scale);
	cv_ctx_l.lineTo(2.05*scale,34.43*scale);
	cv_ctx_l.lineTo(3.62*scale,31.00*scale);
	cv_ctx_l.lineTo(5.95*scale,27.72*scale);
	cv_ctx_l.lineTo(8.17*scale,25.61*scale);
	cv_ctx_l.lineTo(10.72*scale,23.84*scale);
	cv_ctx_l.lineTo(13.059*scale,22.73*scale);
	cv_ctx_l.lineTo(15.32*scale,22.28*scale);
	cv_ctx_l.lineTo(17.76*scale,22.08*scale);
	cv_ctx_l.lineTo(20.30*scale,21.47*scale);
	cv_ctx_l.lineTo(23.28*scale,20.51*scale);
	cv_ctx_l.lineTo(25.88*scale,18.90*scale);
	cv_ctx_l.lineTo(28.265*scale,16.83*scale);
	cv_ctx_l.lineTo(29.9*scale,14.71*scale);
	cv_ctx_l.lineTo(31.89*scale,12.195*scale);
	cv_ctx_l.lineTo(33.62*scale,9.42*scale);
	cv_ctx_l.lineTo(34.81*scale,6.64*scale);
	cv_ctx_l.lineTo(35.46*scale,3.92*scale);
	cv_ctx_l.lineTo(35.52*scale,0.54*scale);
	cv_ctx_l.strokeStyle=style.style.color;
	cv_ctx_l.lineWidth=3;
	cv_ctx_l.stroke(); 	
}

function addGeometryInitPRang(canvas, style){
	var	cv_ctx_p=canvas.getContext("2d");
	var scale = 0.7;
	
	cv_ctx_p.clearRect(0, 0, canvas.width, canvas.height);
		
	cv_ctx_p.shadowColor = '#999';
	cv_ctx_p.shadowBlur = 4;
	cv_ctx_p.shadowOffsetX = 2;
	cv_ctx_p.shadowOffsetY = 2;
	
	cv_ctx_p.moveTo(5.13*scale,15.82*scale);
	cv_ctx_p.lineTo(25.49*scale,5.13*scale);
	cv_ctx_p.lineTo(37.08*scale,13.16*scale);
	cv_ctx_p.lineTo(20.66*scale,38.01*scale);
	cv_ctx_p.lineTo(2.06*scale,33.67*scale);
	cv_ctx_p.closePath();
	cv_ctx_p.strokeStyle="#ffffff"; //hex
	cv_ctx_p.fillStyle=jQuery.Color(style.style.color).alpha(0.75).toRgbaString(); //rgba
	cv_ctx_p.lineWidth=1;
	cv_ctx_p.fill();
	cv_ctx_p.stroke();
}

function readDataUrlFileLayer(urlFileLayer, key){
	
	var defer = jQuery.Deferred();
	var data = {};
	var dataValues = [];	
	
	jQuery.each( urlFileLayer._layers, function(i,feature) {
		//var value = feature.properties[key.toLowerCase()];
		var value = feature.feature.properties[key];
		if(!data[value]){
			data[value] = value;
			dataValues.push(value);
		}
	});
	
	defer.resolve(dataValues);
	return defer.promise();
}

function readDataVisualitzacio(visualitzacio, key){
	//console.debug("readDataVisualitzacio");
	var defer = jQuery.Deferred();
	var data = {};
	var dataValues = [];
	jQuery.each(visualitzacio.estil, function(index, item){
		jQuery.each( item.geometria.features, function(i,feature) {
			//var value = feature.properties[key.toLowerCase()];
			var value = feature.properties[key];
			//Si es blanc assignem categoria "Sense valor" com una més
			//if(isBlank(value)) value = window.lang.translate("Sense valor");
			if(isBlank(value)) value = "nodata";
			if(!data[value]){
				data[value] = value;
				dataValues.push(value);
			}
		});
	});
	defer.resolve(dataValues);
	return defer.promise();
}

function createScale(paleta, length, reverse){
	var scale = ColorScales.createScale(paleta, length, reverse);
	return scale;
}



function createTematicCategoriesActualitzat(data,sublayer,businessIdCapaMare,layerMare){
	var paleta,reverse,dataField,labelField,tipusClasicTematic;
	if (sublayer.layer.options.paleta!=undefined) paleta = sublayer.layer.options.paleta;
	if (sublayer.layer.options.reverse!=undefined) reverse = sublayer.layer.options.reverse;
	if (sublayer.layer.options.dataField!=undefined) dataField = sublayer.layer.options.dataField;
	if (sublayer.layer.options.labelField!=undefined) labelField = sublayer.layer.options.labelField;
	if (sublayer.layer.options.tipusClasicTematic!=undefined) tipusClasicTematic = sublayer.layer.options.tipusClasicTematic;
	
	var tematic = jQuery("#dialog_tematic_rangs").data("tematic");
//	var visualitzacio = jQuery("#dialog_tematic_rangs").data("visualitzacio");
	var capaMare = controlCapes._layers[layerMare.layer._leaflet_id].layer;
//	console.debug(paleta);
	paleta = paleta ? paleta : 'Paired';
	var sToCount = $("#count-"+businessIdCapaMare).html();
	sToCount = sToCount.replace("(", " ");
	sToCount = sToCount.replace(")", " ");	
	var toCount = parseInt(sToCount.trim());
	var scale = createScale(paleta, toCount, reverse);	
	var ftype = transformTipusGeometry(layerMare.layer.options.geometryType);	
	var dataVis={
			businessId1: businessIdCapaMare,
			key: dataField,
			uid: Cookies.get('uid')
	};
	var rangsEstils=[];
	getValuesFromKeysProperty(dataVis).then(function(results){
		var valors = results.valors;
		var resultatsFinals=[];
						
		if (tipusClasicTematic==undefined || tipusClasicTematic=="unic"){
			var resultsNoRepetits=[];
			var data = {};		
			jQuery.grep(valors,  function( n, i ) {
						var value = n;
						if(isBlank(value)) value = "nodata";
							if(!data[value]){
								data[value] = value;
								resultsNoRepetits.push(n);
							}
			});
			//match ints and floats/decimals
			var floatRegex = new RegExp('(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}');
			var resultsFloat = [];
			var i=0;
			jQuery.grep(resultsNoRepetits, function( n, i ) {
				if (floatRegex.test(n.v)) {
					resultsFloat[i]=n;
					i++;
				}
					
			});
			if (resultsFloat.length>0) resultatsFinals=resultsFloat;
			else resultatsFinals=resultsNoRepetits;
		}
		else {
			//match ints and floats/decimals
			var floatRegex = new RegExp('(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}');
			var resultsFloat = [];
			var i=0;
			jQuery.grep(valors, function( n, i ) {
				if (floatRegex.test(n.v)) {
					resultsFloat[i]=n;
					i++;
				}
					
			});
			if (resultsFloat.length>0) resultatsFinals=resultsFloat;
			else resultatsFinals=valors;
		}
		var valuesStyle = jQuery.map( resultatsFinals, function( a, i) {
			rangsEstils[i]={v: a, style: createIntervalStyle(i,ftype,scale)};							
		});
		loadRangValues(rangsEstils,tipusClasicTematic,layerMare.layer.options.geometryType,sublayer.layer.options.estilsRangs,sublayer.layer.options.estil).then(function(rangs){
			var data1 = {
					uid: Cookies.get('uid'),
					businessId1: capaMare.options.businessId
				};
				crearFitxerPolling(data1).then(function(results) {
					var tmpFile="";
					if (results.status=="OK"){
						tmpFile = results.tmpFilePath;
						//Definim interval de polling en funcio de la mida del fitxer
						var pollTime =3000;
						//Fem polling
						(function(){							
							pollBuffer = function(){
								$.ajax({
									url: paramUrl.polling +"pollingFileName="+ results.tmpFileName,
									dataType: 'json',
									type: 'get',
									success: function(data){
										
										jQuery('#dialog_tematic_rangs').hide();
										jQuery('#info_uploadFile').show();
										if(data.status.indexOf("PAS 1")!=-1 && busy){
											
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
													'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
													'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
											);									
											
										}else if((data.status.indexOf("PAS 2")!=-1 || data.status.indexOf("PAS 3")!=-1) && busy){
											jQuery("#div_uploading_txt").html(
													'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
													'<div id="div_upload_step2" class="status_current" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'	
											);										
										}else if(data.status.indexOf("OK")!=-1 && busy){
											clearInterval(pollInterval);
											jQuery("#div_uploading_txt").html("");
											jQuery("#div_uploading_txt").html(
													'<div id="div_upload_step1" class="status_check" lang="ca">1. '+window.lang.translate('Categories creades')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'+
													'<div id="div_upload_step2" class="status_check" lang="ca">2. '+window.lang.translate('Processant la resposta')+' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></div>'
											);									
											var defer = $.Deferred();
											readVisualitzacio(defer, data.visualitzacio, data.layer).then(function(results){
												activaPanelCapes(true);
												//Desactivem la capa mare
												if ($( "#input-"+businessIdCapaMare).attr("checked")!=undefined) $( "#input-"+businessIdCapaMare).click();
											});
											jQuery('#info_uploadFile').hide();		
											busy=false;
										}else if(data.status.indexOf("ERROR")!=-1 && busy){
											console.error("Error calculant l'operació");
											console.error(data);
											busy = false;
											
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
											
											$('#dialog_error_upload_txt').html("");
											
											$('#dialog_error_upload_txt').html(window.lang.translate("Error calculant l'operació"));										
											
											$('#dialog_error_upload').modal('show');
										}
										else if (!busy){
											clearInterval(pollInterval);
											jQuery('#info_uploadFile').hide();
										}
									}
								});
							};
							
							pollInterval = setInterval(function(){
								pollBuffer();
							},pollTime);
							
						})();
							var estils = {
								estils: rangs,
								dataField: dataField,
								labelField: dataField
							};
							var options = {
								url: capaMare.options.url,
								tem: tem_clasic,
								style: estils,
								origen: capaMare.options.businessId,
								tipus : t_url_file,
								tipusFile: capaMare.options.tipusFile,
								estil_do: estils,
								epsgIN: capaMare.options.epsgIN,
								geometryType: capaMare.options.geometryType,
								colX: capaMare.options.colX,
								colY: capaMare.options.colY,
								dinamic: capaMare.options.dinamic
							};
							var data = {
								businessId: businessIdCapaMare,//businessId id de la visualización de origen
								uid: Cookies.get('uid'),//uid id de usuario
								mapBusinessId: url('?businessid'),//mapBusinessId id del mapa donde se agrega la visualización	           
								nom:  sublayer.layer.options.nom,
								activas: true,
								order: capesOrdre_sublayer,//order (optional) orden de la capa en el mapa
								dataField: jQuery('#dataField').val(),//¿?¿?¿?¿?
								tem: tem_clasic,//visualitzacio.from,//tem_simple
								estils: JSON.stringify(estils),
								tipusTematic:"t_visualitzacio_categories",
								urlTematic:paramUrl.createVisualitzacioTematica,
								tmpFilePath: tmpFile,
								paleta: jQuery("#dialog_tematic_rangs").data("paleta"),
								reverse: jQuery("#dialog_tematic_rangs").data("reverse")
							};
							//console.debug("callActions");
							callActions(data);
							/*createVisualitzacioTematica(data).then(function(results){
									var defer = jQuery.Deferred();
									readVisualitzacio (defer,results.visualitzacio,results.layer).then(function(results2){
										activaPanelCapes(true);
										//Desactivem la capa mare
										if ($( "#input-"+capaMare.options.businessId).attr("checked")!=undefined) $( "#input-"+capaMare.options.businessId).click();
									});
							});*/
					}
					else {
						jQuery('#info_uploadFile').hide();		
						busy=false;
					}
				
					
				});	
				
			});
						
		});
}

function loadRangValues(rangsEstils,tipusClasicTematic,geometrytype,estilsRangs,estilLayer){
	var defer = jQuery.Deferred();
	var rangs=[];
	var rangsGuardats=[];
	if (tipusClasicTematic=="rangs"){
		jQuery.each(estilsRangs, function( index, value ) {
			var values =[];
			values=index.split(" - ");
        	var indexEstil = 0;
        	while(indexEstil<estilLayer.length && value!=estilLayer[indexEstil].businessId){
        			indexEstil++;
			}
			var estil = estilLayer[indexEstil];			
			var tdRang, tdMin, tdMax;
			var tdVal;
			var rang = {};
			rang.estil = transformStyle(estil,geometrytype);
			rang.valueMax = values[1];
			rang.valueMin = values[0];
			rangs.push(rang);
		});
	}
	if (tipusClasicTematic==undefined || tipusClasicTematic=="unic"){
		jQuery.each(rangsEstils, function( index, value ) {
			var tdRang, tdMin, tdMax;
			var tdVal;
			var rang = {};
			rang.estil = transformStyle(value.style,geometrytype);
			rang.valueMax = value.v;
			rang.valueMin = value.v;
			rangs.push(rang);
			
		});	
	}
	console.debug(rangs);
	defer.resolve(rangs);
	return defer.promise();
}

function transformStyle(style,geometrytype){
	var rangStyle;
	var ftype = transformTipusGeometry(geometrytype);
	if (ftype == t_marker){
		//divElement = tdElem.find('div');
		var color;
		if (style.fillColor!=undefined) color=style.fillColor;
		else if (style.color!=undefined) color=style.color;
		rangStyle = {
			borderColor :  "#ffffff",
			borderWidth :  2,
			simbolSize: style.simbolSize,
			color: color,
			opacity: 90
		};
	}else if (ftype == t_polyline){
		//divElement = tdElem.find('canvas')[0].getContext("2d");
		var lineWidth;
		if (style.dashArray!=undefined) lineWidth=style.dashArray;
		else if (style.lineWidth) lineWidth=style.lineWidth;
		rangStyle = {
			lineWidth :  style.dashArray,
			color: style.color,
		};
	}else if (ftype == t_polygon){
		
		//divElement = tdElem.find('canvas')[0].getContext("2d");
		rangStyle = {
			borderColor : '#FFFFFF',
			borderWidth :  '1',
			color: style.color,
			fillColor: style.color,
			fillOpacity: style.opacity,
			opacity: '75'		//75!
		};
		//console.debug(rangStyle);
	}
	return rangStyle;
}
	


<file_sep>/geocatweb/js/geocat.mapa.search.js
var ctr_cerca; 


function filterJSON(rawjson) {
	var jsonData = JSON.parse(rawjson.resposta);
	var json = {},
	key, loc, disp = [];
	//console.debug(jsonData);
	
	if (jsonData.resultats.length>1){
		for (var i = 0; i < jsonData.resultats.length; i++) {
		    var resultat = jsonData.resultats[i];
		    var coordsSplit = resultat.coordenades.split(",");
		    json[ resultat.nom ] = L.latLng(coordsSplit[0], coordsSplit[1]);
		}
	}
	else {
		if (jsonData.resultats.length>0){
			var coords= jsonData.resultats[0].coordenades;
			var nom = jsonData.resultats[0].nom;
			console.debug(jsonData);
			var coordsSplit = [];
			if (coords) {
				coordsSplit = coords.split(",");
				loc = L.latLng(coordsSplit[0], coordsSplit[1] );
				ctr_cerca.showLocation(loc,coords,nom); 
			}
		}
		else ctr_cerca.showAlert(ctr_cerca.options.textErr);
	}
	return json;
}


function addControlCercaEdit(){
	
	addHtmlInterficieCerca();

	ctr_cerca=new L.Control.Search({url: paramUrl.searchAction+"searchInput={s}",
		position:'topcenter',
		filterJSON: filterJSON,
		animateLocation: false,
		markerLocation: false,
		zoom: 12,
		minLength: 3,
		autoType: false,
		text: window.lang.translate('Cercar llocs al món o coordenades  ...'),
		idInputText : '#ctr_cerca',
		zoom : 14,
		textSize : 22,
		autoCollapseTime: 3200,
		textEdit:'<a id="act_end" href="#" >Finaltzar Edicio <span class="glyphicon glyphicon-check"></span></a>'
		
	}).addTo(map);
	
	/*var ctr_cercaNomen = new L.Control.Search({
		url: jsonpurl,
		jsonpParam: jsonpName,
		filterJSON: filterJSONCall,
		animateLocation: false,
		markerLocation: false, //true,
		autoType: true, //false		
		position : 'topcenter',
		propertyName : 'nom',
		markerLocation : false,
		rectangleLocation:false,
		autoCollapse : false,
		botoCerca : true,
		idInputText : '#ctr_cercaNomen',
		zoom : 14,
		initial:false,
		textSize : 22,
		minLength : 1,
		text : window.lang.translate('Cercar llocs mudialment...'),
	});*/
	
//	ctr_cercaNomen.on('search_locationfound', function(e) {
//
//		e.layer.setStyle({fillColor: '#3f0', color: '#0f0'});
//
//		}).on('search_collapsed', function(e) {
//
//		featuresLayer.eachLayer(function(layer) {	//restore feature color
//		featuresLayer.resetStyle(layer);
//		});	
//		});

	//map.addControl(ctr_cercaNomen ); 
	
	jQuery('.search-edit a').on("click", function(e) {	
		var id=jQuery(this).attr('id');
		if(id=="act_move"){

		}else if(id=="act_remove"){
					
		}else if(id=="act_end"){
			
			objEdicio.esticEnEdicio=false;
			featureActive.disable();
			if(crt_Editing){
			crt_Editing.disable();
			}
			jQuery('.search-edit').animate({
				height :'hide'
			});			
		}
	});
	
}


function addHtmlInterficieCerca(){
	
	jQuery('#searchBar').addClass("input-group");
	
	jQuery('#searchBar').append(
	   		   '<div id="ctr_cerca"></div>'			
	);
}
<file_sep>/geocatweb/js/instamaps.geolocal.widgets.infoparcela.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetInfoparcela = {
					
		init: function() {
			this.url = "http://www.geolocal.cat/geoLocal/infoParcela/?bbox=widget_bbox_municipi&title=widget_nom_municipi";;
			this.containerId = '.drawWidgets';
			this.cache();
        	this.subscriptions();
        	this.bindEvents();
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	this.container = $(this.containerId);
        },
        
        getWidget: function(){
        	return this;
        },
                
        drawButton: function(container){
        	var that = this;
        	$('<div/>').addClass('widget-button').addClass('widget-infoparcela')
        	.on('click',function(){
        		$.publish('widgetActivated',{'target':this,'widget':that});
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_InfoParcela']});
        	})
        	.appendTo(container);
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	$(this.containerId).empty();
        },
        
        draw: function(data){	
        	var that = this;
        	
        	if(that.active && data.tipusMunicipi){
        		$(that.containerId).empty();
        		//var codi = data.municipiCodi.substring(0,5);
        		var url = that.url.replace("widget_nom_municipi", data.municipi);
        		url = url.replace("widget_bbox_municipi", data.bbox);
    			this.windowObjectReference = window.open(url,"PromoteFirefoxWindowName", "resizable=yes,scrollbars=yes,status=yes");  
    			this.windowObjectReference.focus();
    			
    			$('<p></p>').addClass('text').html('Municipi de <b>' + data.municipi + '</b>').appendTo($(that.containerId));
    			$('<div></div>').addClass('list').append(
	    			$('<a></a>', {
						'href' : url,
						'target' : '_blank'
					}).html(data.municipi + " a InfoParcel·la")).append(
					$('<span></span>',{'class':'glyphicon glyphicon-new-window'})).appendTo($(that.containerId));
        	}
        },
                
        /**********Events**************/
        bindEvents: function(){
        },
        
        subscriptions: function() {
        	var that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
        		if(data){
        			that.draw(data);
        		}
        	});
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetInfoparcela.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetInfoparcela = WidgetInfoparcela.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/geocat.renovar-1.0.0.js
var trackEventFrom = '';

$(document).ready(function() {
	$(document).keypress(function(e) {
	    if(e.which == 13) {
	    	$("#login_button").click();
	    }
	});
	
	if(!url('?token')){
		window.location=paramUrl.mainPage;
	}
	
	if (url('?email')){
		console.debug(url('?email'));
		$('#login_user').val(url('?email'));
	}
	
	
});//Fi document ready

$("#perfil_button_pass").click(function(){

	_gaq.push(['_trackEvent',trackEventFrom,'remember password', 'retention']);
	
	checkValidityPassword();
	
	if(!$("span").hasClass("text_error")){
		var dataUrl = {
			email: $('#login_user').val(),
			token: url('?token'),
			newPassword: $('#<PASSWORD>').val()
		}
		
		renewPassword(dataUrl).then(function(results){
			if(results.status==='OK'){
				$('#modal_registre_ok').modal('toggle');
				$('#button-alta-ok').on('click',function(){
					window.location=paramUrl.loginPage;
				});
			}else{
				if (results.results=="unregistered_user") $('#modal_registre_ko_unregistered_user').modal('toggle');
				else $('#modal_registre_ko').modal('toggle');
			}
		});
	}
});

function checkValidityPassword(){
	$('#login_user').removeClass("invalid");
	$('#perfil_pass').removeClass("invalid");
	$('#perfil_confirm_pass').removeClass("invalid");
	$( ".text_error" ).remove();
	
	if(!($('#login_user').val())){
		$('#login_user').addClass("invalid");
		$('#login_user').after("<span class=\"text_error\" lang=\"ca\">El camp no pot estar buit</span>");
	}else if(!($('#perfil_pass').val())){
		$('#perfil_pass').addClass("invalid");
		$('#perfil_pass').after("<span class=\"text_error\" lang=\"ca\">El camp no pot estar buit</span>");
	}else if($('#perfil_pass').val().length < 4){
		$('#perfil_pass').addClass("invalid");
		$('#perfil_pass').after("<span class=\"text_error\" lang=\"ca\">La contrasenya ha de tenir un mínim de 4 caràcters.</span>");
	}else if(!($('#perfil_confirm_pass').val())){
		$('#perfil_confirm_pass').addClass("invalid");
		$('#perfil_confirm_pass').after("<span class=\"text_error\" lang=\"ca\">El camp no pot estar buit</span>");
	}else if($('#perfil_pass').val() != $('#perfil_confirm_pass').val()){
		$('#perfil_confirm_pass').addClass("invalid");
		$('#perfil_confirm_pass').after("<span class=\"text_error\" lang=\"ca\">Les contrasenyes han de coincidir.</span>");
	}
}<file_sep>/geocatweb/js/geocat.index-1.0.0.js
jQuery(document).ready(function() {

	weball_tornarInici();	
	
//	$(".title-white", this).hover(swapImageIn, swapImageOut);
//  $(".img-hover", this).hover(swapImageIn, swapImageOut);

	$("#div_E").hover(function(){
		console.info("entro");
		$("#img_E").attr('src','share/img/Explora_pujat.jpg');
	},function(){
		$("#img_E").attr('src','share/img/Explora_.jpg');
		console.info("surt");	
	});
	
	jQuery("#hl_contact").on('click', function() {
		jQuery(this).attr('href','mailto:<EMAIL>');
		
	});
}

//function swapImageIn(e) {
//this.src = this.src.replace("_", "_pujat");
//}
//function swapImageOut (e) {
//this.src = this.src.replace("_pujat", "_");
//}

function web_roundCircles(){
	jQuery('#div_E').on('click', function() {
		document.location.href = "#row_E";
	});
	jQuery('#div_C').on('click', function() {
		document.location.href = "#row_C";
	});
	jQuery('#div_V').on('click', function() {
		document.location.href = "#row_V";
	});
	jQuery('#div_C1').on('click', function() {
		document.location.href = "#row_C1";
	});
}

function weball_tornarInici(){
	
	jQuery("#back-top").hide();
	jQuery('#fes-mapa-inici').hide();
		
		jQuery(function () {
			jQuery(window).scroll(function () {
				if (jQuery(this).scrollTop() > 150) {
					jQuery('#back-top').fadeIn();
					jQuery('#fes-mapa-inici').fadeIn();
				} else {
					jQuery('#back-top').fadeOut();
					jQuery('#fes-mapa-inici').fadeOut();
				}
			});

			jQuery('#back-top button').click(function () {
				jQuery('body,html').animate({
					scrollTop: 0
				}, 800);
				return false;
			});
			jQuery('#fes-mapa-inici').click(function () {
				window.open("../geocatweb/mapa.html","_self");
			});
		});
	}
<file_sep>/geocatweb/js/leaflet/L.IM_LocationControl.js
/**
 * L.Control.LocationControl control que hace lo mismo que el L.Control.Gps
 * 
 * require L.Control.Gps
 */
L.Control.LocationControl = L.Control.Gps.extend({
	
	options: {
		position: 'topleft',
		id: 'dv_bt_Location',
		title: 'Centrar mapa a la seva ubicació',
		langTitle: 'Centrar mapa a la seva ubicació',
		tooltip: 'right'
	},
	
	initialize: function(options){
		var self = this,
		_options = self.options;
		
		if(options){
			options = L.Util.extend({}, _options, options);
		}
		L.Util.setOptions(self, options);
		L.Control.Gps.prototype.initialize.call(self, options);
	},
	
	onAdd: function(map) {
		var self = this,
		options = self.options;
		var container = L.Control.Gps.prototype.onAdd.call(self, map);
		
		container.title = options.title;
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		return container;
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
});

L.control.locationControl = function(options){
	return new L.Control.LocationControl(options);
};<file_sep>/geocatweb/js/geocat.mapa.semaforic.js
;(function(global, $){
	
	var Semaforic = function(isEditing){
		return new Semaforic._init(isEditing);
	}
	
	Semaforic.prototype = {
		_createPaletteSelector: function() 
		{

			var self = this;
			var html = 
			'	<div id="interactivePalette">' +
			'		<div id="paletteBackground"></div>' +
			'		<div id="innerPalette">' +
			'			<div lang="ca" class="paletteTitle">Temàtic per escala de color</div>' + 
			'			<div lang="ca" style="font-size: 12px;">Tria la paleta de colors</div>' +
			'			<div>' +
			'				<div class="paletteLabels">' +
			'					<div style="height: 20px;" lang="ca">Valors menors</div>' +
			'					<div style="height: 20px;" lang="ca">Valors iguals</div>' +
			'					<div style="height: 20px;" lang="ca">Valors majors</div>' +
			'				</div>' +
			'				<div class="palettes" style="display: inline-block;">';
			
			var palettes = $("#paletes_colors > .ramp");
			palettes.splice(0, 0, "carto");
			if(1 == palettes.length)
				palettes = ["carto", "BuGn", "BuPu", "GnBu", "OrRd", "PuBu", "PuBuGn", "PuRd", "RdPu", "YlGn", "YlGnBu", "YlOrBr", "YlOrRd", 
					"BrBG", "PRGn", "PuOr", "RdGy", "RdYlBu", "RdYlGn", "Spectral", "Paired", "Set3", "Set1", "Dark2"];
			$.each(palettes, function(index, palette) {
				var palName;
				if($(palette).hasClass("ramp"))
					palName = $(palette).attr("class").replace("ramp ", "");
				else
					palName = palette;
				var scale = self._createScaleAux(palName, 3, false);
				html += '					<div class="ramp border ' + palName + '">' +
				'					<svg height="60" width="15">' + 
				'						<rect y="0" height="20" width="15" fill="' + scale(self._paletteColorSteps[0]).hex() + '"/>' + 
				'						<rect y="20" height="20" width="15" fill="' + scale(self._paletteColorSteps[1]).hex() + '"/>' +
				'						<rect y="40" height="20" width="15" fill="' + scale(self._paletteColorSteps[2]).hex() + '"/>' +
				'					</svg>' +
				'				</div>';
			});

			html += '				</div>' + 
			'				<div class="paletteButtons">'+
			'					<div style="display: inline-block; float:left;">'+
			'						<input id="cbSoftColors" type="checkbox"><span style="padding-left: 10px;" lang="ca">' + window.lang.translate('Colors suaus') + '</span>' +
			'					</div>'+
			'					<div class="innerPaletteButtons">'+
			'						<button type="button" class="btn btn-invert-palette"><span lang="ca">Inverteix paleta</span><span id="invert-palette-arrow" class="glyphicon glyphicon-arrow-down" style="padding-left: 5px;"></span></button>'+
			'						<button type="button" class="btn btn-default" lang="ca">Cancel·lar</button>'+
			'						<button type="button" class="btn btn-success" lang="ca">Acceptar</button>'+
			'					</div>'+
			'				</div>'+
			'			</div>' +
			'		</div>' + 
			'	</div>' +
			'	<div id="dismissPaletteDialog" class="modal fade">' + 
			'		<div class="modal-dialog">'+
			'			<div class="modal-content panel-primary">'+
			'				<div id="id_sw" class="modal-body">'+
			'					<h4><span lang="ca">Vols sortir sense guardar aquesta escala de color?</span></h4>' +
			'				</div>'+
			'				<div class="modal-footer">'+
			'					<button type="button" class="btn btn-default" data-dismiss="modal" lang="ca">Cancel·lar</button>'+
			'			        <button type="button" class="btn btn-danger" data-dismiss="modal" lang="ca">Esborrar</button>'+
			'				</div>'+
			'			</div>'+
			'		</div>'+
			'	</div>';
			$("#mapa_modals").append(html);

			$('#cbSoftColors').iCheck({
				checkboxClass: 'icheckbox_flat-blue',
				radioClass: 'iradio_flat-blue'
			});

			self._isPaletteDialogCreated = true;

		},

		_bindPaletteButtons: function()
		{

			var self = this;
			var aux = $("#interactivePalette .ramp");
			aux.off('click');
			aux.on('click',function(evt){
				var _this = $(this);
				$("#interactivePalette .ramp.active").removeClass("active");
				var brewerClass = _this.attr('class').replace("ramp border ","").replace(" active", "");
				self._palette = brewerClass;
				_this.addClass("active");

				//If we are editing, update the values of the category popup
				if(self._isEditing)
				{

					if("carto" == brewerClass)
					{

						brewerClass = ["#1a9850","#ffffbf","#d73027"];

					}

					$("#dialog_tematic_rangs").data("paleta", brewerClass);
					updatePaletaRangs(self._useSoftColors);

				}

				if(null != self._previsualizationLayer)
				{

					//Update the previsualization layer
					self._updateFakeLayer();

				}

			});

			aux = $("#interactivePalette .btn-invert-palette");
			aux.off('click');
			aux.on('click',function(evt){
				self._isPaletteReversed = !self._isPaletteReversed;

				if(self._isPaletteReversed)
				{
				
					$("#invert-palette-arrow").removeClass("glyphicon-arrow-down").addClass("glyphicon-arrow-up");

				}
				else
				{

					$("#invert-palette-arrow").removeClass("glyphicon-arrow-up").addClass("glyphicon-arrow-down");

				}

				if(self._isEditing)
				{

					$("#dialog_tematic_rangs").data("reverse",self._isPaletteReversed);
					updatePaletaRangs(self._useSoftColors);

				}

				var palettes = $("#interactivePalette .ramp");
				$.each(palettes, function(index, palette) {
					var svg = $(palette).children();
					var rects = $(svg).children();
					var startColor = $(rects[0]).attr("fill");
					var endColor = $(rects[2]).attr("fill");
					$(rects[0]).attr("fill", endColor);
					$(rects[2]).attr("fill", startColor);
				});

				if(null != self._previsualizationLayer)
				{

					//Update the previsualization layer
					self._updateFakeLayer();

				}

			});

			aux = $('#interactivePalette .btn-success');
			aux.off('click');
			aux.on('click',function(e){

				$('#interactivePalette').hide();

				if(self._isEditing)
				{

					$('#info_uploadFile').show();
					busy=true;
					$("#div_uploading_txt").html("");
					$("#div_uploading_txt").html(
						'<div id="div_upload_step1" class="status_current" lang="ca">1. '+window.lang.translate('Creant categories')+'<span class="one">.</span><span class="two">.</span><span class="three">.</div>'+
						'<div id="div_upload_step2" class="status_uncheck" lang="ca">2. '+window.lang.translate('Processant la resposta')+'</div>'
					);

					var key = $("#dialog_tematic_rangs #dataField").val();
					var rangs = $("#dialog_tematic_rangs").data("rangs");
					var value = rangs[1].min;
					var data = {nom: key + " " + window.lang.translate("Escala de color") + " " + window.lang.translate("(Valor de ref: ") + value + ")", 
						trafficLightKey: key, trafficLightValue: value, trafficLightLowerColor: self._previsualizationLayer.estil[0].color,
						trafficLightEqualColor: self._previsualizationLayer.estil[1].color, trafficLightHigherColor: self._previsualizationLayer.estil[2].color};
					createTematicLayerCategories(e, {}, data, $.Deferred()).then(function(layerId) {
						//Update the map legend
						var arrRangsEstilsLegend = sortObject(controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.rangsEstilsLegend);
						arrRangsEstilsLegend.sort(sortByValueMax);
						//Change the businessId from the styles and ranges to sort them correctly
						//(When geocat.mapa.legend.js addLayerToLegend is called, the ranges are sorted by its businessId so they are not guaranteed to 
						//mantain the lower-equal-bigger legend)
						var estils = controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.estil;
						var nousEstils = [];
						for(var i=0; i<estils.length; ++i)
						{

							if(arrRangsEstilsLegend[0].key == estils[i].businessId)
							{	//Lower style

								nousEstils[0] = estils[i];
								nousEstils[0].businessId = 0;

							}
							else if(arrRangsEstilsLegend[1].key == estils[i].businessId)
							{	//Equal style

								nousEstils[1] = estils[i];
								nousEstils[1].businessId = 1;

							}
							else if(arrRangsEstilsLegend[2].key == estils[i].businessId)
							{	//Bigger style

								nousEstils[2] = estils[i];
								nousEstils[2].businessId = 2;

							}

						}

						controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.estil = nousEstils;
						controlCapes._visLayers[controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.businessId].estil = nousEstils;
						arrRangsEstilsLegend[0].value = key + window.lang.translate(" menor de ") + value;
						arrRangsEstilsLegend[0].key = 0;
						arrRangsEstilsLegend[1].value = key + window.lang.translate(" igual a ") + value;
						arrRangsEstilsLegend[1].key = 1;
						arrRangsEstilsLegend[2].value = key + window.lang.translate(" major de ") + value;
						arrRangsEstilsLegend[2].key = 2;
						controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.rangsEstilsLegend = [];
						controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.rangsEstilsLegend[arrRangsEstilsLegend[0].key] = arrRangsEstilsLegend[0].value;
						controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.rangsEstilsLegend[arrRangsEstilsLegend[1].key] = arrRangsEstilsLegend[1].value;
						controlCapes._layers[self._previsualizationLayer.parentid]._layers[layerId].layer.options.rangsEstilsLegend[arrRangsEstilsLegend[2].key] = arrRangsEstilsLegend[2].value;
						//Remove the previsualization layer from the layer control
						map.removeLayer(self._capaVisualitzacio);
						controlCapes.removeLayer(controlCapes._layers[self._previsualizationLayer.parentid]._layers[self._capaVisualitzacio._leaflet_id]);
						self._previsualizationLayer = null;

					});

				}

			});

			aux = $('#interactivePalette .btn-default');
			aux.off('click');
			aux.on('click',function(e){
				//Activate the parent layer
				$( "#input-" + self._previsualizationLayer.geometriesBusinessId).click();
				self._closePalette();
			});

			aux = $("#paletteBackground");
			aux.off("click");
			aux.on("click", function(e) {
				$("#dismissPaletteDialog").modal("show");
			});

			aux = $("#dismissPaletteDialog .btn-danger");
			aux.off("click");
			aux.on("click", function(e) {
				self._closePalette();
			});

			$("#cbSoftColors").on("ifToggled", function(e) {
				self._softColorsCheckboxChanged();

				if(self._isEditing)
				{

					updatePaletaRangs(self._useSoftColors);

				}

				var palettes = $("#interactivePalette .ramp");
				$.each(palettes, function(index, palette) {
					var svg = $(palette).children();
					var rects = $(svg).children();
					var paletteName = $(palette).attr("class").replace("ramp border ", "").replace(" active", "");
					var scale = self._createScaleAux(paletteName, 3, self._isPaletteReversed);
					$(rects[0]).attr("fill", scale(self._paletteColorSteps[0]).hex());
					$(rects[1]).attr("fill", scale(self._paletteColorSteps[1]).hex());
					$(rects[2]).attr("fill", scale(self._paletteColorSteps[2]).hex());
				});

				if(null != self._previsualizationLayer)
				{

					//Update the previsualization layer
					self._updateFakeLayer();

				}

			});

		},

		_softColorsCheckboxChanged: function()
		{

			var self = this;
			self._useSoftColors = !self._useSoftColors;

			if(self._useSoftColors)
				self._paletteColorSteps = [0.75, 1.5, 2.25];
			else
				self._paletteColorSteps = [0, 1.5, 3];

		},

		_closePalette: function() 
		{

			var self = this;
			$('#interactivePalette').hide();
			map.removeLayer(self._capaVisualitzacio);
			controlCapes.removeLayer(controlCapes._layers[self._previsualizationLayer.parentid]._layers[self._capaVisualitzacio._leaflet_id]);
			controlCapes.forceUpdate(false);
			self._previsualizationLayer = null;

		},

		_showPaletteSelector: function()
		{

			var self = this;
			if(!self._isPaletteDialogCreated)
				self._createPaletteSelector();

			self._bindPaletteButtons();
			$("#interactivePalette").show();

		},

		_createTrafficLightStyle: function(color, bId, features)
		{

			return {
				businessId : bId,
				borderColor: "#ffffff",
				borderWidth: 1,
				color: color,
				opacity: 75,
				label: false,
				labelHaloWidth: 0,
				labelSize: 0,
				lineWidth: 0,
				radius: 0,
				simbolSize: 6,
				geometria: {
					features: features
				}
			};

		},

		_randomStringAux: function(length, chars)
		{

			var result = '';
			for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
			return result;

		},

		_randomString: function(length)
		{

			var self = this;
			return self._randomStringAux(length, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

		},

		_createTempTrafficLightLayer: function(key, value, baseLayer, layerOptions)
		{

			var self = this;
			var newLayer = {};
			var id = randomString(32);
			var newOptions = {businessId: id,
				capesActiva: "true",
				capesCalenta: null,
				capesGroup: "",
				capesOrdre: "sublayer",
				capesVisibilitat: null,
				entitatUid: null, //<----
				epsg: {},
				id: null, //<----
				imgFormat: "",
				infFormat: "",
				layers: null,
				legend: "",
				opacity: 1,
				options: JSON.stringify({
					tem: "clasicTematic",
					id: null,  //<----
					businessId: id,
					nom: key + " " + window.lang.translate("Escala de color"),
					origen: baseLayer.businessId,
					geometryType: baseLayer.geometryType,
					tipus: "clasicTematic",
					options: {
						source: baseLayer.source,
						propName: baseLayer.propName.join(),
					},
					geometriesColleccio: {
						id: baseLayer.id,
						businessId: baseLayer.businessId,
						nom: baseLayer.nom, 
						options: baseLayer.propName.join(),
						geometryType: baseLayer.geometryType
					},
					entitat: null,  //<----
					group: {
						name: baseLayer.group.name, 
						groupName: baseLayer.group.groupName,
						id: baseLayer.group.id,
						z_order: baseLayer.group.z_order,
						expanded: baseLayer.group.expanded
					},
					trafficLightKey : key,
					trafficLightValue: value,
					propName: baseLayer.propName.join()
				}),
				query:null,
				serverName: key + " " + window.lang.translate("Escala de color") + " " + window.lang.translate("(Valor de ref: ") + value + ")",
				serverType: baseLayer.tipus,
				tiles:"",
				titles:null,
				transparency:"",
				url:"",
				version:"",
				visibilitat:"O"
			};

			newLayer.options = newOptions.options;
			newLayer.businessId = null; //<----
			newLayer.geometriesBusinessId = baseLayer.businessId;
			newLayer.geometryType = baseLayer.geometryType;
			newLayer.id = null; //<----
			newLayer.nom = newOptions.options.serverName;
			newLayer.tipus = "clasicTematic";
			newLayer.uid = null;//<----

			//Set the parentid property. If the baseLayer doesn't have it, look for it on 
			//the layer control
			if(baseLayer.hasOwnProperty("leafletid"))
				newLayer.parentid = baseLayer.leafletid;
			else
			{

				var keys = Object.keys(controlCapes._layers);
				var trobat = false;
				var key;
				for(var i=0; i<keys.length && !trobat; ++i)
				{

					key = keys[i];
					trobat = (controlCapes._layers[keys[i]].layer.options.businessId == baseLayer.businessId);

				}

				newLayer.parentid = key;

			}

			$.extend(layerOptions, newOptions);

			return newLayer;

		},

		_setupTematicLayerDialog: function(layer, key, pivot, min, highestLowerValue, lowestHigherValue, max)
		{

			var self = this;
			if(self._isEditing)
			{

				//Set the category popup values to use its own click and do the
				//same process done on a 3 interval category
				$("#dialog_tematic_rangs").data("capamare", {
					businessid: layer.options.businessId,
					from: layer.options.from,
					geometrytype: layer.options.geometryType,
					leafletid: layer.options.leafletid,
					propname: layer.options.propName.join(),
					tipus: layer.options.tipus
				});

				var src;
				if (layer.options.geometryType == t_marker)
				{

					src = $("#tematic-values-semaforic-punt-template").html();

				}
				else if (layer.options.geometryType == t_polyline)
				{

					src = $("#tematic-values-semaforic-polyline-template").html();
					
				}
				else if (layer.options.geometryType == t_polygon)
				{

					src = $("#tematic-values-semaforic-polygon-template").html();

				}

				var template = Handlebars.compile(src);
				$("#rd_tipus_semaforic").prop("checked", true);
				$("#list_tematic_values").html(template({values: [{index:0, v: {min: min, max: highestLowerValue}}, {index:1, v: {min: pivot, max: pivot}}, {index:2, v:{min: lowestHigherValue, max: max}}]}));

				$("#dialog_tematic_rangs").data("rangs", [{min: min, max: highestLowerValue}, {min: pivot, max: pivot}, {min: lowestHigherValue, max: max}]);
				showTematicRangs(layer.options.geometryType);
				$("#dataField").html("<option value=\"" + key + "\">" + key + "</option>");
				$("#dataField").val(key);
				$("#cmb_num_rangs").val(3);

			}

			self._showPaletteSelector();

		},

		_createScaleAux: function(paleta, rang, reversed)
		{

			var self = this;
			var auxPaleta = paleta;
			if("carto" == auxPaleta)
			{

				auxPaleta = self._cartoPaletteColors;

			}

			return createScale(auxPaleta, rang, reversed);

		},

		sortGeometry: function(inStyles, key, pivot)
		{

			var styles = inStyles;
			var equalGeom = [];
			var lowerGeom = []; 
			var higherGeom = [];
			var highestLowerValue = Number.MIN_SAFE_INTEGER;
			var lowestHigherValue = Number.MAX_SAFE_INTEGER;
			var min = Number.MAX_SAFE_INTEGER;
			var max = Number.MIN_SAFE_INTEGER;

			$.each(inStyles, function(i, estil) {
				$.each(estil.geometria.features, function(j, feature) {

					var aux = feature;
					var val = parseFloat(aux.properties[key]);
					min = (min > val ? val : min);
					max = (max < val ? val : max);
					if(val == pivot)
					{

						//Equal color
						equalGeom.push(feature);

					}
					else if(val < pivot)
					{

						//Less than color
						lowerGeom.push(feature);
						if(val >= highestLowerValue)
							highestLowerValue = val;

					}
					else 
					{

						//Greater than color
						higherGeom.push(feature);
						if(val < lowestHigherValue)
							lowestHigherValue = val;

					}

				});
			});

			return {
				lowerGeom: lowerGeom,
				equalGeom: equalGeom,
				higherGeom: higherGeom,
				highestLowerValue: highestLowerValue,
				lowestHigherValue: lowestHigherValue,
				min: min, 
				max: max
			};

		},

		_renderFakeLayer: function(defer)
		{

			var self = this;
			readVisualitzacio($.Deferred(), self._previsualizationLayer, self._previsualizationLayerOptions).then(function(data) {
				//Desactivem la capa mare
				if ($( "#input-" + self._previsualizationLayer.geometriesBusinessId).attr("checked")!=undefined) $( "#input-" + self._previsualizationLayer.geometriesBusinessId).click();
				self._capaVisualitzacio = data;
				defer.resolve(data._leaflet_id);
				$("#interactivePalette .ramp.carto").click();
			});
			controlCapes.forceUpdate(false);

		},

		_renderLayer: function(defer)
		{

			var self = this;
			reloadVisualitzacioLayer(self._capaVisualitzacio, self._previsualizationLayer, self._previsualizationLayerOptions, map);
			defer.resolve(self._capaVisualitzacio._leaflet_id);
			controlCapes.forceUpdate(false);

		},

		render: function(defer, key, pivot, inLayer)
		{			

			var self = this;
			//Create each style and sort the geometry on each bucket
			var rangColors = self._createScaleAux(self._palette, 3, self._isPaletteReversed);
			var estilActual = [
				rangColors(self._paletteColorSteps[0]).hex(), 
				rangColors(self._paletteColorSteps[1]).hex(), 
				rangColors(self._paletteColorSteps[2]).hex()
			];
			
			var layerOptions = {};
			var layer = (null != self._previsualizationLayer ? self._previsualizationLayer : inLayer);

			var sorted = self.sortGeometry(inLayer.options.estil, key, pivot);
			var lowerStyle = self._createTrafficLightStyle(estilActual[0], 0, sorted.lowerGeom);
			var equalStyle = self._createTrafficLightStyle(estilActual[1], 1, sorted.equalGeom);
			var higherStyle = self._createTrafficLightStyle(estilActual[2], 2, sorted.higherGeom);

			if(null == self._previsualizationLayer)
			{

				self._setupTematicLayerDialog(layer, key, pivot, sorted.min, sorted.highestLowerValue, sorted.lowestHigherValue, sorted.max);
				layer = self._createTempTrafficLightLayer(key, pivot, layer.options, layerOptions);

			}

			layer.estil = [lowerStyle, equalStyle, higherStyle];
			
			//Draw the layer
			if(null == self._previsualizationLayerOptions)
			{

				self._previsualizationLayerOptions = layerOptions;
				self._previsualizationLayer = layer;
				self._renderFakeLayer(defer);				

			}
			else
			{

				//Update mapConfig legend if exists
				var lowerThanLabel = key + window.lang.translate(" menor de ") + pivot;
				var equalToLabel = key + window.lang.translate(" igual a ") + pivot;
				var higherThanLabel = key + window.lang.translate(" major de ") + pivot;
				if(self._capaVisualitzacio.hasOwnProperty("layer"))
				{
				
					self._updateMapLegend(layer, lowerThanLabel, equalToLabel, higherThanLabel);
					self._updateStyleRangeLegend(layer, lowerThanLabel, equalToLabel, higherThanLabel, 
						lowerStyle, equalStyle, higherStyle, pivot);

				}
				self._renderLayer(defer);

			}

			return defer.promise();

		},

		_updateStyleRangeLegend: function(layer, lowerThanLabel, equalToLabel, higherThanLabel, lowerStyle, equalStyle, higherStyle, pivot)
		{

			var self = this;
			var aux = JSON.parse(layer.options);
			aux.rangsEstilsLegend = {};
			aux.rangsEstilsLegend[layer.estil[0].businessId] = lowerThanLabel;
			aux.rangsEstilsLegend[layer.estil[1].businessId] = equalToLabel;
			aux.rangsEstilsLegend[layer.estil[2].businessId] = higherThanLabel;
			layer.options = JSON.stringify(aux);
			self._capaVisualitzacio.layer.options.rangsEstilsLegend = aux.rangsEstilsLegend;
			self._capaVisualitzacio.layer.options.estil = [lowerStyle, equalStyle, higherStyle];

			//Update the layer properties so they are saved when publishing
			self._capaVisualitzacio.layer.options.trafficLightValue = pivot;
			var newName = self._getNewLayerName(self._capaVisualitzacio.name, pivot)
			self._capaVisualitzacio.layer.options.nom = newName;
			self._capaVisualitzacio.name = newName;
			var aux = JSON.parse(self._previsualizationLayer.options);
			aux.trafficLightValue = pivot;
			self._previsualizationLayer.options = JSON.stringify(aux);

		},

		_updateMapLegend: function(layer, lowerThanLabel, equalToLabel, higherThanLabel)
		{

			var self = this;
			var _mapConfig = ("undefined" == typeof visor) ? mapConfig : visor._mapConfig;
			if(undefined != _mapConfig.legend && "" != _mapConfig.legend)
			{

				var auxLegend = JSON.parse(_mapConfig.legend);
				if(null != auxLegend)
				{

					var layerLegend;
					layerLegend = auxLegend[self._capaVisualitzacio.layer.options.businessId];

					if(null != layerLegend)
					{

						//Check which bucket is by its color (should we be using the style businessId?)
						var lowerThanColor = hexToRgb(layer.estil[0].color);
						var lowerThanFill = "fill:rgb(" + lowerThanColor.r +", " + lowerThanColor.g+ ", "+lowerThanColor.b+");"
						var equalToColor = hexToRgb(layer.estil[1].color);
						var equalToFill = "fill:rgb(" + equalToColor.r +", " + equalToColor.g+ ", "+equalToColor.b+");"
						var higherThanColor = hexToRgb(layer.estil[2].color);
						var higherThanFill = "fill:rgb(" + higherThanColor.r +", " + higherThanColor.g+ ", "+higherThanColor.b+");"
						for(var i=0; i<layerLegend.length; ++i)
						{
							
							if(-1 != layerLegend[i].symbol.indexOf(lowerThanFill))
							{
								layerLegend[i].name = lowerThanLabel;
							}
							else if(-1 != layerLegend[i].symbol.indexOf(equalToFill))
							{
								layerLegend[i].name = equalToLabel;
							}
							else if(-1 != layerLegend[i].symbol.indexOf(higherThanFill))
							{
								layerLegend[i].name = higherThanLabel;
							}

						}

						if("undefined" == typeof visor)
							mapConfig = JSON.stringify(auxLegend);
						else
							visor._mapConfig.legend = JSON.stringify(auxLegend);
						mapLegend = auxLegend;

					}

				}

			}

		},

		_getNewLayerName: function(oldName, pivot)
		{

			//If the name contains the "Reference value" string, update it with the new value
			var newName = oldName;
			var refString = window.lang.translate("(Valor de ref: ");
			var indexValor = oldName.indexOf(refString);
			if(-1 !== indexValor)
			{
				
				newName = oldName.substring(0, indexValor+refString.length) + pivot + ")";

			}

			return newName;

		},

		_updateFakeLayer: function() 
		{

			var self = this;
			var scale = self._createScaleAux(self._palette, 3, self._isPaletteReversed);
			self._previsualizationLayer.estil[0].color = scale(self._paletteColorSteps[0]).hex();
			self._previsualizationLayer.estil[1].color = scale(self._paletteColorSteps[1]).hex();
			self._previsualizationLayer.estil[2].color = scale(self._paletteColorSteps[2]).hex();

			//Removes the additional data from the map.
			reloadVisualitzacioLayer(self._capaVisualitzacio, self._previsualizationLayer, self._previsualizationLayerOptions, map);

		},

		setVisualization: function(vis)
		{

			this._capaVisualitzacio = vis;

		},

		setLayer: function(layer)
		{

			this._previsualizationLayer = layer;

		},

		setLayerOptions: function(options)
		{

			this._previsualizationLayerOptions = options;

		},

		setPalette: function(palette, isReversed)
		{

			this._palette = palette;
			this._isPaletteReversed = isReversed;

		},

	};
	
	Semaforic._init = function(isEditing){

		var self = this;

		self._isEditing = ("undefined" !== typeof isEditing && isEditing)
		self._previsualizationLayer = null;
		self._previsualizationLayerOptions = null;
		self._isInitialized = true;
		self._capaVisualitzacio = null;

		self._isPaletteDialogCreated = ( 0 != $("#interactivePalette").length);
		if(self._isPaletteDialogCreated && self._isEditing)
		{

			//Get the parameters from the palette dialog
			self._isPaletteReversed = $("#dialog_tematic_rangs").data("reverse");
			self._palette = $("#dialog_tematic_rangs").data("paleta");

		}
		else
		{

			self._isPaletteReversed = false;
			self._palette = "carto";

		}

		$("#cbSoftColors").iCheck('uncheck');
		self._useSoftColors = false;
		self._paletteColorSteps = [0, 1.5, 3];
		self._cartoPaletteColors = ["#00a84b", "#e2e174", "#cc0001"];

		return this;
	}
	
	Semaforic._init.prototype = Semaforic.prototype;
	Semaforic.sortGeometry = Semaforic.prototype.sortGeometry;
	Semaforic.getUpdatedLayerName = Semaforic.prototype._getNewLayerName;
	global.Semaforic = Semaforic;
	
}(window, jQuery));<file_sep>/geocatweb/js/instamaps.geolocal.widgets.meteo.js
/**
 * require: jquery, bootstrap
 */
(function ( $, window, document, undefined ) {
	"use strict";
	var WidgetMeteo = {
					
		init: function() {
			this.url = "http://www.aemet.es/ca/eltiempo/prediccion/municipios/mostrarwidget/widget_prov_id_municipi?w=g3p11111110ohmffffffw350z252x333333t999999r1s1n1";
        	this.containerId = '.drawWidgets';
			this.cache();
        	this.subscriptions();
        	this.bindEvents();
        	this.uiLoaded = false;                    	
            return this;
        },
        
        cache: function(){
        	var that = this;
        	that.container = $(that.containerId);
        	$.get("/geocatweb/dades/municipisAemet.json",function(data){
        		that.municipis = data;
        	});
        },
        
        getWidget: function(){
        	return this;
        },
        
        drawButton: function(container){
        	var that = this;
        	$('<div/>').addClass('widget-button').addClass('widget-meteo')
        	.on('click',function(){
        		$.publish('widgetActivated',{'target':this,'widget':that});
        		$.publish('trackEvent',{event:['_trackEvent', 'visor', 'widget_Meteo']});
        	})
        	.appendTo(container);
        },
        
        activate: function(){
        	this.active = true;
        },
        
        deactivate: function(){
        	this.active = false;
        	this.iframe = false;
        	$(this.containerId).empty();
        },
        
        getMunicipi: function(codigo){
        	var that = this;
        	var codiMeteo;
        	if (codigo != null){
        		if (codigo.length > 5){
        			codigo = codigo.substring(0,5);
        		}
        		var arrayLength = that.municipis.length;
        		for (var i = 0; i < arrayLength; i++) {
        			if (that.municipis[i].indexOf(codigo) != -1){
        				codiMeteo = that.municipis[i];
        				break;
        			}
        		}
        	}
        	return codiMeteo;
        },
        
        draw: function(data){
        	var that = this;
        	if(that.active   && data.tipusMunicipi){
        		var codi = that.getMunicipi(data.municipiCodi);
        		if (codi){
            		var url = that.url.replace("widget_prov_id_municipi", codi);
            		if (that.iframe){
            			$(that.containerId).find('iframe').prop('src',url);
                	}else{
                		$('<iframe/>').prop('src',url)
                		.attr('seamless','seamless').attr('scrolling','no')
                		.appendTo($(that.containerId));
                		that.iframe = true;
                	}
            	}else{
            		$(that.containerId).empty();
            	}
        	}
        },
                
        /**********Events**************/
        bindEvents: function(){
        },
        
        subscriptions: function() {
        	var that = this;
        	$.subscribe('changeSelectMunicipis',function(e, data){
        		if(data){
        			that.draw(data);
        		}
        	});
        }
	}
	
	//Registre module if AMD is present:
   	if(typeof define === "function" && define.amd){
   		define([], function(){return WidgetMeteo.init();} );
   	}
   	
   	//Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
   	window.WidgetMeteo = WidgetMeteo.init();
	
})( jQuery, window, document );<file_sep>/geocatweb/js/leaflet/L.IM_LikeControl.js
/**
 * L.Control.Like control que permite sumar/restar uno a los like de los mapas
 */
L.Control.Like = L.Control.extend({
	options: {
		position: 'topleft',
		id: 'dv_bt_likeMap',
		className: 'leaflet-bar  btn btn-default btn-sm',
		title: 'Vista inicial',
		langTitle: 'Vista inicial',
		html: '<span id="span_bt_likeMap" class="fa fa-heart-o grisfort"></span>',
		tooltip: 'right'
	},
	
	onAdd: function(map){
		var self = this,
			options = self.options,
			stop = L.DomEvent.stopPropagation,
			container = L.DomUtil.create('div', options.className);
		
		container.id = options.id;
		container.innerHTML = options.html;
		container.title = options.title;
		
		container.dataset.toggle = 'tooltip';
		container.dataset.placement = options.tooltip;
		container.dataset.langTitle = options.langTitle;
		
		self._div = container;
		
		map.on('loadconfig', self._updateMapConfig, self);
		map.on('visorconfig', self._updateMapConfig, self);
		
		L.DomEvent
			.on(container, 'click', stop)
			.on(container, 'mousedown', stop)
			.on(container, 'dblclick', stop)
			.on(container, 'click', self._like, self);
		return container;
	},
	
	onRemove: function (map) {
		var self = this;
		map.off('loadconfig', self._updateMapConfig, self);
		map.off('visorconfig', self._updateMapConfig, self);
	},
	
	_like: function(e){
		var self = this;
		console.debug(self.options.mapConfig);
		_mapConfig = self.options.mapConfig;
		
		var data = {
			businessId: _mapConfig.businessId
		};
		
		if(self._isLiked()){
			data.rank = -1;
			self._unLiked();
		}else{
			data.rank = 1;
			self._liked();
		}
		
		self._updateRankAplicacio(data).then(function(results){
			if (results.status=="OK"){
				var btnSpan = $(self._div).find('span');
				btnSpan.tooltip({
					placement: 'right',
			        title: results.results,
			        
			    }).tooltip('show');
				setTimeout(function(){
					btnSpan.tooltip('destroy');
			    }, 800);
			}
		});
	},
	
	_updateRankAplicacio: function(params){
		return $.ajax({
			url: paramUrl.updateRankAplicacio, //geocat.config-1.0.0
	  		data: params,
	  		method: 'post',
	  		dataType: 'jsonp'
		}).promise();
	},
	
	_isLiked: function(){
		var self = this,
		liked = false;
		
		var btnSpan = $(self._div).find('span');
		
		if($(btnSpan).hasClass('fa-heart-o')){
			liked = false;
		}else if($(btnSpan).hasClass('fa-heart')){
			liked = true;
		} 
		return liked;
	},
	
	_liked: function(){
		var self = this;
		var btnSpan = $(self._div).find('span');
		$(btnSpan).removeClass('fa-heart-o').addClass('fa-heart');
	},
	
	_unLiked: function(){
		var self = this;
		var btnSpan = $(self._div).find('span');
		$(btnSpan).removeClass('fa-heart').addClass('fa-heart-o');
	},
	
	hideBtn: function(){
		var self = this;
		$(self._div).hide();
	},
	
	showBtn: function(){
		var self = this;
		$(self._div).show();
	},
	
	_updateMapConfig: function(config){
		this.options.mapConfig = config;
	}
});

L.control.like = function(options){
	return new L.Control.Like(options);
};<file_sep>/geocatweb/js/leaflet/L.IM_Coordinates.js
/*
Exemple 
L.control.coordinates({
			position : 'bottomright', 
			'emptystring':' ',
			'numDigits': 2,
			'prefix': 'ETRS89 UTM 31N',
			'separator': ' '
		}).addTo(map);
*/

L.Control.Coordinates = L.Control.extend({
  options: {
    position: 'bottomleft',
    separator: ' : ',
    emptyString: '',
    lngFirst: true, //modifiquem el paràmetre per mostrar les coordenades igual que el Vissir (issue #554)
    numDigits: 2,
    numDigits2: 6,
	crs:new L.Proj.CRS('EPSG:25831',  '+proj=utm +zone=31 +ellps=GRS80 +datum=WGS84 +units=m +no_defs'),
    lngFormatter: undefined,
    latFormatter: undefined,
    prefix: "",
    prefix2: "",
    showETRS89: true
  },

  onAdd: function (map) {
	var self = this,
	container = L.DomUtil.create('div', 'leaflet-control-mouseposition');
	
	container.innerHTML=self.options.emptyString;
	
	self._container = container;
	self._div = self._container;
	
	map.on('mousemove', self._onMouseMove, self);
	   
	L.DomEvent.disableClickPropagation(self._container);
   
    return self._container;
  },

  hideBtn: function(){
	var self = this;
	$(self._div).hide();
  },

  showBtn: function(){
	var self = this;
	$(self._div).show();
  },
  
  onRemove: function (map) {
    map.off('mousemove', this._onMouseMove);
  },

  _onMouseMove: function (e) {
	var map = this._map;  
	
	var sC=map.miraBBContains(map.getBounds());
  
    
	var _CRS=this.options.crs.project( {lat:e.latlng.lat,lng:e.latlng.lng});
  
    //var lng = this.options.lngFormatter ? this.options.lngFormatter(e.latlng.lng) : L.Util.formatNum(e.latlng.lng, this.options.numDigits);
    //var lat = this.options.latFormatter ? this.options.latFormatter(e.latlng.lat) : L.Util.formatNum(e.latlng.lat, this.options.numDigits);
    
	var lng = this.options.lngFormatter ? this.options.lngFormatter(_CRS.x) : L.Util.formatNum(_CRS.x, this.options.numDigits);
    var lat =this.options.latFormatter ? this.options.latFormatter(_CRS.y) : L.Util.formatNum(_CRS.y, this.options.numDigits);
	
	var value = this.options.lngFirst ? lng + this.options.separator + lat : lat + this.options.separator + lng;
	
	lng = this.options.lngFormatter ? this.options.lngFormatter(e.latlng.lng) : L.Util.formatNum(e.latlng.lng, this.options.numDigits2);
	lat = this.options.latFormatter ? this.options.latFormatter(e.latlng.lat) : L.Util.formatNum(e.latlng.lat, this.options.numDigits2);
	
	var value2 = this.options.lngFirst ? lng + this.options.separator + lat : lat + this.options.separator + lng;
	
    var prefixAndValue = this.options.prefix + ' ' + value;
    var prefixAndValue2 = this.options.prefix2 + ' ' +value2;
    if((sC===0)){
    	this._container.innerHTML = prefixAndValue2;
    }
    else if((sC==1 || sC==2)){  
	    if (this.options.showETRS89) this._container.innerHTML = prefixAndValue + '<br/>'+ prefixAndValue2;
	    else this._container.innerHTML = prefixAndValue2;
    }
  }

});

L.Map.mergeOptions({
    positionControl: false
});

L.Map.addInitHook(function () {
    if (this.options.positionControl) {
        this.positionControl = new L.Control.Coordinates();
        this.addControl(this.positionControl);
    }
});

L.control.coordinates = function (options) {
    return new L.Control.Coordinates(options);
};
<file_sep>/llibreries/js/leaflet/plugin/L.TileLayer.BetterWMS.js
var control_llegenda_WMS;
L.TileLayer.BetterWMS = L.TileLayer.WMS.extend({
	onAdd: function (map) {
		this.creaControlLLegenda(map);
		// Triggered when the layer is added to a map.
		// Register a click listener, then do all the upstream WMS things
		this.options.maxZoom=20;
		this.options.queryable=true;
		L.TileLayer.WMS.prototype.onAdd.call(this, map);
		//if (this.url && this.url.indexOf('http://betaserver.icgc.cat/geoservice/')==-1){
			map.on('click', this.getFeatureInfo, this);
			var params = this.getLegendGraphic();
			this.updateControlLLegenda(params,this.wmsParams.layers,true,this.options.nom,this.options.businessId);	
		//}		
		
	},
	onRemove: function (map) {
		// Triggered when the layer is removed from a map.
		// Unregister a click listener, then do all the upstream WMS things
		L.TileLayer.WMS.prototype.onRemove.call(this, map);
		map.off('click', this.getFeatureInfo, this);
		var params = this.getLegendGraphic();
		this.updateControlLLegenda(params,this.wmsParams.layers,false,this.options.nom,this.options.businessId);
	},
	getFeatureInfo: function (evt) {
		// Make an AJAX request to the server and hope for the best
		var params = this.getFeatureInfoUrl(evt.latlng);
		params = params.replace("INFO_FORMAT=text%2Fhtml","INFO_FORMAT=text/html");
		if(this.options.queryable){
			if ((params.indexOf('instamaps.cat')!=-1 || params.indexOf('192.168.3.11')!=-1 || params.indexOf('localhost')!=-1) && params.indexOf('instaserver')==-1){
				if (params.indexOf('/geoservicelocal/')!=-1){
					params = params.replace("INFO_FORMAT=text%2Fhtml","INFO_FORMAT=text%2Fplain");
					params = params.replace("INFO_FORMAT=text/html","INFO_FORMAT=text/plain");
				}
				var dataF="<iframe style=\"display: block; width:300px; height:200px;border:none;\"  src="+params+" ></iframe></div>";
				var pop=L.popup({ maxWidth: 800})
					.setLatLng(evt.latlng)
					.setContent(dataF).openOn(map);	
			}else{
				var esNomesWMS = true;
				var teUtfGrid = false;
				//De moment, si es un wms creat pel cloudifier, demanem text/pla
				//mes endavant passarem per ogrinfo i podrem demanar HTML amb template
				//per mostrar la informacio
				if (params.indexOf('http://betaserver.icgc.cat/geoservice/')!=-1){
					params = params.replace("INFO_FORMAT=text%2Fhtml","INFO_FORMAT=text%2Fplain");
				}
				for(val in controlCapes._layers){
					if(controlCapes._layers[val].layer.options.tipus != t_wms){
						esNomesWMS = false;
					}
					if (controlCapes._layers[val].layer.options.tipus == t_vis_wms){
						teUtfGrid=true;
					}
				}
				if(esNomesWMS){
					$.ajax({
						url: paramUrl.proxy_betterWMS,
						data: {url: params},
						success: function (data, status, xhr) {
							var err = typeof data === 'string' ? null : data;

							if(data.length > 5){
								var pop=L.popup({ maxWidth: 800})
								.setLatLng(evt.latlng)
								.setContent(data).openOn(map);					
							}
						},
						error: function (xhr, status, error) {

						}
					});				
				}else{
					if (!teUtfGrid || params.indexOf('instaserver')==-1) {
						var dataF="<iframe style=\"display: block; width:300px; height:200px;border:none;\"  src="+params+" ></iframe></div>";
						var pop=L.popup({ maxWidth: 800})
							.setLatLng(evt.latlng)
							.setContent(dataF).openOn(map);	
					}
				}
			}
		}//fi querable
		return;
	},
	getFeatureInfoUrl: function (latlng) {
		var bounds = this._map.getBounds();
		var SRS=this.wmsParams.srs;
		var BBOX=bounds.toBBoxString();
		if(SRS.indexOf('3857')!=-1){
			var NW = L.CRS.EPSG3857.project(bounds.getNorthWest());
			var SE = L.CRS.EPSG3857.project(bounds.getSouthEast());
			BBOX=NW.x+","+SE.y+","+SE.x+","+NW.y;
		}
		// Construct a GetFeatureInfo request URL given a point
		var point = this._map.latLngToContainerPoint(latlng, this._map.getZoom()),
		size = this._map.getSize(),
		params = {
			request: 'GetFeatureInfo',
			service: 'WMS',
			srs: SRS,
			styles: this.wmsParams.styles,
			transparent: this.wmsParams.transparent,
			version: this.wmsParams.version,
			format: this.wmsParams.format,
			bbox: BBOX,
			height: size.y,
			width: size.x,
			//exceptions:'application/vnd.ogc.se_blank',
			layers: this.wmsParams.layers,
			query_layers: this.wmsParams.layers,
			info_format: 'text/html'
		};
		params[params.version === '1.3.0' ? 'i' : 'x'] = point.x;
		params[params.version === '1.3.0' ? 'j' : 'y'] = point.y;
		return this._url + L.Util.getParamString(params, this._url, true);
	},
	showGetFeatureInfo: function (err, latlng, content) {
		if (err) { console.log(err); return; } // do nothing if there's an error
		// Otherwise show the content in a popup, or something.
		L.popup({ maxWidth: 800})
		.setLatLng(latlng)
		.setContent(content)
		.openOn(this._map);
	},
	getLegendGraphic : function () {
		//console.debug("getLegendGraphic");
		var _format=this.wmsParams.format;
		_format=_format.replace('png8','png');
		var layers = this.wmsParams.layers.split(",");
		if(layers.length === 1){
			params = {
				request : 'GetLegendGraphic',
				service : 'WMS',
				version : this.wmsParams.version,
				format : _format,
				layer : this.wmsParams.layers
			};
			return this._url + L.Util.getParamString(params, this._url, true);
		}else{
			var legend = [];
			for(var i = 0, length = layers.length; i < length; i++){
				var layer = layers[i];
				params = {
					request : 'GetLegendGraphic',
					service : 'WMS',
					version : this.wmsParams.version,
					format : _format,
					layer : layer
				};
				legend.push(this._url + L.Util.getParamString(params, this._url, true));
			}
			return legend;
		}
		
	},
	creaControlLLegenda : function (map) {
		//console.debug("creaControlLLegenda");
		var fet = false;
		if(jQuery('#div_control_wms_llegenda').length==0){
			if (map) {
				control_llegenda_WMS = L.control({
					position : 'bottomright'
				});
				control_llegenda_WMS.onAdd = function(map) {
					this._div = L.DomUtil.create('div', 'psolar_infoLL'); // create div with a class
					this._div.id = 'div_control_wms_llegenda';
					this.update();
					return this._div;
				};
				control_llegenda_WMS.update = function(props) {
					this._div.innerHTML = props;
				};
				control_llegenda_WMS.addTo(map);
				control_llegenda_WMS.update("");
				fet = true;
				return fet;
			}
		}
		return fet;
	},
	updateControlLLegenda :function (params,layer,estat,nom,businessId){
		
		/*
		if(getModeMapa()){//si estic visor i no hi ha llegenda
			if($("#mapLegend").length==0 && $("#mapLegendEdicio").length==0){
				addLegend();
			}
			if(estat){ //afegeixo
				var html = '<div style="text-align:center" id="wms_' + businessId + '"><div class="titol-legend col-md-12 col-xs-12">'+nom+'</div><div class="titol-separate-legend-row"></div>';
				html+='<img onerror="document.getElementById(\'wms_' + businessId + '\').style.display=\'none\';"  src="' + params + '"></div>';
				//mapLegendEdicio
				var divLlegenda='mapLegendEdicio';
				if($("#mapLegend").length > 0){divLlegenda='mapLegend';}
				$("#"+divLlegenda).append(html);			
				$("#"+divLlegenda).addClass("info");
				$("#"+divLlegenda).addClass("legend");
				$("#"+divLlegenda).addClass("visor-legend");
				if(!$("#mapLegend").hasClass("mCustomScrollbar") && $("#mapLegend").length > 0){				
					$("#mapLegend").addClass("mCustomScrollbar");
					$("#mapLegend").mCustomScrollbar();
				}
				if(!$("#mapLegendEdicio").hasClass("mCustomScrollbar") && $("#mapLegendEdicio").length > 0){
					$("#mapLegendEdicio").addClass("mCustomScrollbar");
					$("#mapLegendEdicio").mCustomScrollbar();
				}
				$(".bt_legend").show();
				activaLlegenda(true);
			}else{ //esborro
				jQuery('#wms_' + businessId).remove();
			}
		}
		*/
		
	}
});

L.tileLayer.betterWms = function (url, options) {
	return new L.TileLayer.BetterWMS(url, options);
};<file_sep>/geocatweb/js/instamaps.layers-1.0.0.js
/**
 * InstamapsLayers 
 * 
 * require todos los archivos con los diferentes tipos de capas
 * require geocat.mapa.wms
 * require geocat.mapa.json
 * require geocat.mapa.tematic
 * require geocat.mapa.url-file
 * require geocat.mapa.geojsonvt
 * require geocat.mapa.dades-obertes
 * require geocat.mapa.xarxes-socials
 * require geocat.mapa.heat
 * require geocat.mapa.cluster
 * require geocat.mapa.visualitzacioWMS
 */
;(function(global, $){
	var InstamapsLayers = function(options){
		return new InstamapsLayers.init(options);
	};
	
	InstamapsLayers.prototype = {
		loadLayer: function(value){
			var self = this,
			_map = self.map,
			defer = $.Deferred();

			if (value.epsg == "4326"){
				value.epsg = L.CRS.EPSG4326;
			}else if (value.epsg == "25831"){
				value.epsg = L.CRS.EPSG25831;
			}else if (value.epsg == "23031"){
				value.epsg = L.CRS.EPSG23031;
			}else{
				value.epsg = _map.options.crs;
			}

			//Si la capa es de tipus wms
			if(value.serverType == t_wms){
				loadWmsLayer(value);
				defer.resolve();
			//Si la capa es de tipus dades obertes
			}else if(value.serverType == t_json){
				loadCapaFromJSON(value).then(function(){
					defer.resolve();
				});
			//Si la capa es de tipus url file
			}else if(value.serverType == t_url_file){
				loadURLfileLayer(value).then(function(){
					defer.resolve();
				},function(result){
					defer.reject(result);
				});
			//Si la capa es de tipus dades obertes
			}else if(value.serverType == t_geojsonvt){
				//console.debug(loadGeojsonvtLayer);
				loadGeojsonvtLayer(value);
				defer.resolve();
			//Si la capa es de tipus dades obertes
			}else if(value.serverType == t_dades_obertes){
				loadDadesObertesLayer(value).then(function(){
					defer.resolve();
				},function(result){
					defer.reject(result);
				});
			//Si la capa es de tipus xarxes socials
			}else if(value.serverType == t_xarxes_socials){
				var options = $.parseJSON( value.options );
				if(options.xarxa_social == 'twitter') loadTwitterLayer(value, options.hashtag);
				else if(options.xarxa_social == 'panoramio') loadPanoramioLayer(value);
				else if(options.xarxa_social == 'wikipedia') loadWikipediaLayer(value);
				defer.resolve();
			}else if(value.serverType == t_tematic){
				loadTematicLayer(value).then(function(){
					defer.resolve();
				});
			}else if(value.serverType == t_visualitzacio){
				if (self.edit) {
					loadVisualitzacioLayer(value).then(function(){
						defer.resolve();
					});	
				}
				else {
					loadCacheVisualitzacioLayer(value).then(function(){
						defer.resolve();
					});	
				}
			//Si la capa es de tipus vis_wms
			}else if(value.serverType == t_vis_wms || value.serverType == t_vis_wms_noedit){
				loadVisualitzacioWmsLayer(value);
				defer.resolve();
			}
			else if(value.serverType == tem_heatmap_wms || value.serverType == tem_cluster_wms){
				loadVisualitzacioWmsLayerSenseUtfGrid(value);
				defer.resolve();
			}else{
				console.error("Tipus capa no soportat");
				defer.reject({msg:"Tipus capa no soportat"});
			}

			return defer.promise();
		}, 
		
		_loadAllLayers: function(_mapConfig, _controlCapes){
			var self = this,
			dfd = $.Deferred();
			self.waitDeferred = dfd;
			
			self._loadOrigenWMS(_mapConfig, _controlCapes).then(function(results){
				var num_origen = 0;
				self.numLayers = results.origen.length + results.sublayers.length;
				if(self.numLayers === 0){
					self._waitLoadAll(0);
				}

				if (!self.edit)
				{
				
					self.map.oms = new OverlappingMarkerSpiderfier(self.map, {keepSpiderfied : false});
					var popup = new L.Popup();
					self.map.oms.addListener('click', function(marker) {

						if(marker.getPopup)
						{
						
							popup.setContent(marker.getPopup().getContent());
							popup.setLatLng(marker.getLatLng());
							self.map.openPopup(popup);

						}
						
					});

				}

				$.each(results.origen, function(index, value){

					self.loadLayer(value).then(function(){
						num_origen++;
						self._waitLoadAll(num_origen);
						if (num_origen == results.origen.length){
							$.each(results.sublayers, function(index, value){
								self.loadLayer(value).then(function(){
									num_origen++;
									self._waitLoadAll(num_origen);
								},function(){
									num_origen++;
									self._waitLoadAll(num_origen);
								});
							});
						}
					},function(){
						num_origen++;
						self._waitLoadAll(num_origen);
					});
				});
			});
			return dfd.promise();
		},
				
		_waitLoadAll: function(numLayers){
			var self = this;
			if(self.numLayers === numLayers){
				self.waitDeferred.resolve();
			}
			return self;
		},
		
		_loadOrigenWMS: function(_mapConfig, _controlCapes){
			var dfd = $.Deferred(),
			layer_map = {origen:[],sublayers:[]};
			
			$.each(_mapConfig.servidorsWMS, function(index, value){
				//TODO parsear las options y el group y dejarlo en json.
				//TODO quitar el parse de cada tipo de capa.
				if(value.options && value.capesGroup){
					var options;
					if(typeof (value.options)=="string"){
						try {
							options = JSON.parse(value.options);
						}
						catch (err) {
							options = value.options;
						}
					}else{
						options = value.options;
					}

					var group = JSON.parse(value.capesGroup);
					options.group = group;
					value.options = JSON.stringify(options);
				}
				if(value.capesOrdre == capesOrdre_sublayer){
					layer_map.sublayers.push(value);
					lsublayers.push(value); //variable global se tendría que quitar
				}else{
					layer_map.origen.push(value);
				}
			});

			$.each(layer_map.origen, function(index, value){
				var jsonOptions;
				if(typeof (value.options)=="string"){
					try {
						jsonOptions = JSON.parse(value.options);
					}
					catch (err) {
						jsonOptions = value.options;
					}
				}else{
					jsonOptions = value.options;
				}

				if(jsonOptions && jsonOptions.group){
					if(_controlCapes){
						_controlCapes._addGroupFromObject(jsonOptions.group);
					}
				}
			});

			dfd.resolve(layer_map);
			return dfd.promise();
		},

	};
	
	InstamapsLayers.init = function(options){
		var self = this;
		self = $.extend(self, options);
	};
	
	InstamapsLayers.init.prototype = InstamapsLayers.prototype;
	
	global.InstamapsLayers = InstamapsLayers;
	
}(window, jQuery));