﻿$(document).ready(function () {	
	//Necessario per abilitare le richieste crossdomain in Internet Explorer 
	jQuery.support.cors = true;
	
	//Layout
	var mainLayout = $('body').layout({ 
		applyDefaultStyles: true,		
		north__size:0,north__closable:false,north__resizable:false,
		east__size:300,east__closable:false,east__resizable:false,
		south__size:45,south__closable:false,south__resizable:false
	});
	
	// qTip plugin
	$('#btnPrev[title], #btnNext[title], button[title]').qtip({ 
		style: { 
			name: 'light', 
			tip: true			
		}
	});
	
	$("#overviewPanelBtn").live("click",function(){
		if($(".olControlOverviewMapElement").is(":visible")){
			 closeOverviewMap();
		}else{
			 openOverviewMap();
		}
	});
	
	hideLegendPanel();
	hideLegendBorderPanel();
	
	getEsriLayers();
	
	//initMap(); //L'inizializzazione della mappa è stata posticipata dopo aver costruito il layer di base esri
});

$(function() {
	$.format.locale({
	    number: {
	        groupingSeparator: '.',
	        decimalSeparator: ','
	    }
	});	
		
});


/*autocomplete variabile da tematizzare*/

(function( $ ) {
	$.widget( "ui.combobox", {
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = $( "<input>" )
				.insertAfter( select )
				.val( value )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {						
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
						//Modifica Davide
						legendDoClassify();
					},
					change: function( event, ui ) {						
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match anything
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );
			
			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};
			
			this.button = $( "<button type='button'><i class=\"fa fa-caret-down\"></i>&nbsp;</button>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Mostra tutte" )
				.insertAfter( input )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// work around a bug (likely same cause as #5265)
					$( this ).blur();

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
				});
		},
		_init: function(){
			this.input.val(this.element.find("option:selected").text());
		},
		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}			
	});
})( jQuery );


$.widget( "custom.catcomplete", $.ui.autocomplete, {
	_renderMenu: function( ul, items ) {
		var self = this,
			currentCategory = "";
		$.each( items, function( index, item ) {
			if ( item.category != currentCategory ) {
				ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
				currentCategory = item.category;
			}
			self._renderItem( ul, item );
		});
	}
});

/**
 * Aggiorna il controllo di Overview in modo che mostri lo stesso layer di base della mappa
 */
function updateOverviewControl(){
	if ((SISTER.Map.mapType != "undefined") &&(SISTER.Map.mapType !="") ){
		if (SISTER.Map.MAP.controls.length>0){
			
			//cicla sui controlli della mappa e quando trova quello di Overview lo distrugge e lo ricrea (non ho trovato altro modo per farlo aggiornare!!!)
			for (var i=0;i<SISTER.Map.MAP.controls.length;i++){	    	
    			if ((SISTER.Map.MAP.controls[i].displayClass != undefined) && (SISTER.Map.MAP.controls[i].displayClass == 'olControlOverviewMap')){
    				var control = SISTER.Map.MAP.controls[i];    				
    				
    				control.destroy();
    				var overviewMapSize =  new OpenLayers.Size(80, 80);
					var controlOVOptions = {
            			size: overviewMapSize,
            			div:document.getElementById("overviewPanel")
            		};
					control = new OpenLayers.Control.OverviewMap(controlOVOptions);	
    				SISTER.Map.MAP.addControl(control);		
    			}
	    	} 
		}  	
	}
};

/**
 * Modifica il layer di sfondo visibile nella mappa (tra quelli disponibili)
 */
function SetMapBaseStyle(){
	
	//imposta il tipo di mappa di sfondo
	if ((SISTER.Map.mapType !== undefined) && (SISTER.Map.mapType !== "undefined") &&(SISTER.Map.mapType !=="") ){
		if(sisterLabel!=undefined){
			setLabelVisiiblity(false);
		}
		switch(SISTER.Map.mapType)
			{
				case 'opensm':
					setEsriReferenceVisiiblity(false);
					SISTER.Map.MAP.setBaseLayer(osm);							
					
					break;
				case 'street':
					setEsriReferenceVisiiblity(false);
					SISTER.Map.MAP.setBaseLayer(gmap);
					
					break;
				case 'sat':
					setEsriReferenceVisiiblity(false);
					SISTER.Map.MAP.setBaseLayer(gsat);
					
					break;
				case 'hyb':
					setEsriReferenceVisiiblity(false);
					SISTER.Map.MAP.setBaseLayer(ghyb);
					
					break;
				case 'phy':
					setEsriReferenceVisiiblity(false);
					SISTER.Map.MAP.setBaseLayer(gphy);
					
					break;
				case 'esri':
					SISTER.Map.MAP.setBaseLayer(esriBase);
					setEsriReferenceVisiiblity(true);
					break;
				case 'sisterBase':
					SISTER.Map.MAP.setBaseLayer(sisterBase);
					if(sisterLabel!=undefined && SISTER.Map.SisterBaseLabelVis){
						setLabelVisiiblity(true);
					}
					setEsriReferenceVisiiblity(false);
					break;				
			}
	}		
	else{
		setEsriReferenceVisiiblity(false);
		SISTER.Map.MAP.setBaseLayer(osm);		
		
	}
	
	//aggiorna il controllo di Overview in modo che mostri lo stesso layer di base della mappa
	updateOverviewControl();
	
}

function setLabelVisiiblity(visibility){
	if(visibility){
		if(SISTER.Map.MAP.getLayersByName(SISTER.Map.SisterBaseMapLabel).length==0){
			SISTER.Map.MAP.addLayer(sisterLabel);
		}
		sisterLabel.setVisibility(visibility);
	}else{
		if(SISTER.Map.MAP.getLayersByName(SISTER.Map.SisterBaseMapLabel).length>0){
			SISTER.Map.MAP.removeLayer(sisterLabel);
		}
	}
}

function setEsriReferenceVisiiblity(visibility){
	if(visibility){
		if(SISTER.Map.MAP.getLayersByName('AGSCacheReference').length==0){
			SISTER.Map.MAP.addLayer(esriReference);
		}
		esriReference.setVisibility(visibility);
	}else{
		if(SISTER.Map.MAP.getLayersByName('AGSCacheReference').length>0){
			SISTER.Map.MAP.removeLayer(esriReference);
		}
	}
}

