﻿//$(document).ready(function() {

   jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	// $("body").append(results);
	$("#ctl00_CPH_TC_RCMI_txtAutocomplete").after(results); 
	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				else 
				{
				    $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Località non trovata');
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
	    $.get('/risorse/AjaxJSon/getDatiAutocomplete.aspx?descr=' + encodeURI($('#ctl00_CPH_TC_RCMI_txtAutocomplete').val()), function(data) {
	        if (data == ''){
		        $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Località non trovata');
	        }
	    });
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();
    
	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
	    if (!li) {
		    li = document.createElement("li");
		    li.extra = [];
		    li.selectValue = "";
	    }
	    if (li.selectValue == undefined)
	    {
	        li2 = document.createElement("li");
		    li2.extra = li.extra;
		    li2.selectValue = li.value;
		    li = li2;
	    }
	    $.get('/risorse/AjaxJSon/getDatiAutocomplete.aspx?descr=' + encodeURI(li.selectValue), function(data) {
	        if (data != ''){
		        var DatiAutocomplete = data.split('|');
		        settaMappaItalia(DatiAutocomplete[0], DatiAutocomplete[1], DatiAutocomplete[2], DatiAutocomplete[3], DatiAutocomplete[4], DatiAutocomplete[5]);
	        }
	        else{
	            $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Località non trovata');
	            return false;
	        }
	    });
	    
	    var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
	    input.lastSelected = v;
	    prev = v;
	    $results.html("");
	    $input.val(v);
	    hideResultsNow();
	    if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
		
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			//width: parseInt(iWidth) + "px",
			//top: (pos.y + input.offsetHeight) + "px",
		    //left: pos.x + "px"		    
		    top: "24px",
		    left: "75px"			
		}).show();
		
		crea_overlay_auto();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				//$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); 
			selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
	
	function setClassDropDown(ddname, ddvalue) {
	    $('#' + ddname).removeClass('valued');
        if (ddvalue != '' && ddvalue != null)
            $('#' + ddname).addClass('valued');
        $('#' + ddname).removeAttr('disabled');
        $('#' + ddname + ' option').removeClass('current');
        $('#' + ddname + ' option').removeAttr('selected');
        $('#' + ddname + ' option[value=' + ddvalue + ']').addClass('current');
        $('#' + ddname + ' option[value=' + ddvalue + ']').attr('selected', 'selected');
        $('#' + ddname).val(ddvalue);
	}
	
	function crea_overlay_auto() {
        if ($("#overlayAutoC").length == 0) {
            var altezza = getHeightDocument();
            var newdivCont = document.createElement("div");
            $(newdivCont).attr('id', 'overlayAutoC');
            $(document.body).prepend(newdivCont)
            var newdiv = document.createElement("div");
            $(newdiv).attr('class', 'overlay');
            $(newdiv).attr('style', 'height:' + altezza + 'px');
            $('#overlayAutoC').append(newdiv)

            $('.overlay').click(function() {
                distruggi_overlay_auto();
                if( selectCurrent() ){
					$input.get(0).blur();
					//e.preventDefault();
				}
            });
            
        }
    }
    function distruggi_overlay_auto() {
        $('.overlay').remove();
        $('#overlayAutoC').remove();        
    }
    
    function disabilita_dropdown(nome_dropdown) {
        $('#' + nome_dropdown + ' >option').remove();
        $('#' + nome_dropdown).attr('disabled', 'true').removeClass('valued');
    };
    
    

	function settaMappaItalia(codRegione, codProvincia, codComune, mappa_zone, codDdZoneRaggioFrazioni, codZoneRaggioFrazioni) {
        svuota_mappa_sx();
        close_all();
        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        $.getJSON('/risorse/AjaxJSon/getRegioni.aspx', function(data) {
            setClassDropDown('ctl00_CPH_TC_RCMI_ddRegione', codRegione);
            $.getJSON('/risorse/AjaxJSon/getProvince.aspx?regione=' + codRegione, function(data) {
                popola_dropdown_province(data, 'ctl00_CPH_TC_RCMI_ddProvincia');
                if (codComune == ''){
                    popola_dl_regione(data, '.mappaSx');
                    if (codProvincia != '')
                        $('#MappaItalia a[id=' + codProvincia.toLowerCase() + ']').addClass('current');
                }
                if (codProvincia != '')   
                {
                    setClassDropDown('ctl00_CPH_TC_RCMI_ddProvincia', codProvincia);
                    $.getJSON('/risorse/AjaxJSon/getComuni.aspx?provincia=' + codProvincia, function(data) {
                        popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddComuni');
                        if (codComune != '')
                        {
                            setClassDropDown('ctl00_CPH_TC_RCMI_ddComuni', codComune);
                            $.get('/risorse/AjaxJSon/getMappaZone.aspx?codiceistat=' + codComune, function(data) {
                                popola_mappa_zone(data);
                                $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codComune + '&tipozonafraz=Zona', function(data) {
                                    popola_dl_zone(data);
                                    $.getJSON('/risorse/AjaxJSon/getComuniLimitrofi.aspx?codiceistat=' + codComune, function(data) {
                                        popola_dl_bolle_e_tab_comuni_limitrofi(data);
                                        $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codComune + '&tipozonafraz=Frazione', function(data) {
                                            popola_tab_frazioni(data);
                                            if (mappa_zone == '1')
                                            {
                                                setClassDropDown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'COMUNE_ZONE');
                                                $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').change();
                                            }
                                            else
                                            {
                                                if (codDdZoneRaggioFrazioni != '')
                                                {
                                                    setClassDropDown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', codDdZoneRaggioFrazioni);
                                                    $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').change();
                                                    if (codDdZoneRaggioFrazioni == 'FRAZ')
                                                        $('#ctl00_CPH_TC_RCMI_dlFrazioni input[id=' + codZoneRaggioFrazioni + ']').attr('checked', 'checked');
                                                    else
                                                    {
                                                        $('#ctl00_CPH_TC_RCMI_dlZone input[id=z_' + codZoneRaggioFrazioni + ']').attr('checked', 'checked');
                                                        var li = $('#ul_z_' + codComune + ' li[id=z' + codZoneRaggioFrazioni + ']');
                                                        var li_style = li.attr('style');
                                                        li.attr('style',"display:block; " + li_style);
                                                    }
                                                }
                                                else
                                                {
                                                    setClassDropDown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'COMUNE');
                                                    $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').change();
                                                }
                                            }
                                            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
                                        });
                                    });
                                });
                            });
                        }
                        else
                        {
                            $('#ctl00_CPH_TC_RCMI_ddComuni').removeClass('valued');
                            $('#ctl00_CPH_TC_RCMI_ddComuni option').removeClass('current');
                            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
                            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
                            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
                        }
                    });
                }
                else
                {
                    $('#ctl00_CPH_TC_RCMI_ddProvincia').removeClass('valued');
                    $('#ctl00_CPH_TC_RCMI_ddProvincia option').removeClass('current');
                    disabilita_dropdown('ctl00_CPH_TC_RCMI_ddComuni');
                    $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
                    disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
                }   
            });
            
        });

    };
	
}


jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};


    var chiudi_panel = false;
    var chiudi_feedback = false;
    var testo_dove = '';
    
    $('.frmFeedback').mouseover(function() {
        chiudi_feedback = false;
        return false;
    });

    $('.frmFeedback').mouseout(function() {
        chiudi_feedback = true;
        setTimeout(function() { if (chiudi_feedback == true) { $('.frmFeedback').fadeOut('fast'); } }, 3000);
        return false;
    });

    $('#lblFeedback').click(function() {
        $('#ctl00_iframeFeedback').attr('src', $('#ctl00_hiddenSrcFeedback').val());
        $('.frmFeedback').fadeIn('fast');
        return false;
    });

    $('.fbclose').click(function() {
        $('.frmFeedback').fadeOut('fast');
        return false;
    });

    function assegna_bc_click() {
        //var a = $('#bc');
        var a = $('.bcMappaItalia > a');
        a.click(function() {
            close_all();
            $('#map').remove();
            var attributo = $('#bc').attr('href');
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddProvincia');
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddComuni');
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
            if (attributo == '/') {
                caricaRegioni();
                $('#ctl00_CPH_TC_RCMI_ddRegione').val('0');
                rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddRegione');
                $('#ctl00_CPH_TC_RCMI_ddProvince').change();
                $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('');
            }
            else {
                //seleziono una regione
                setClassOnSelected('ctl00_CPH_TC_RCMI_ddRegione', $('#ctl00_CPH_TC_RCMI_ddRegione').val(), 'valued', 'current');
                caricaProvince($('#ctl00_CPH_TC_RCMI_ddRegione').val());
                if ($('#ctl00_CPH_TC_RCMI_ddRegione option')[$('#ctl00_CPH_TC_RCMI_ddRegione').val()].text != 'Seleziona')
                    $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Regione ' + $('#ctl00_CPH_TC_RCMI_ddRegione option')[$('#ctl00_CPH_TC_RCMI_ddRegione').val()].text);
                else    
                    $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('');
            }

            return false;
        });
    }

    function bcMappaItalia(classe, descrizione, link) {
        $('.bcMappaItalia >a').remove();
        //$('.bcMappaItalia').text('');
        var contenitore = $('.bcMappaItalia');
        var newa = document.createElement("a");
        if (classe != '')
            $(newa).attr('class', classe);
        $(newa).attr('id', 'bc');
        $(newa).attr('href', link);
        var newtext = document.createTextNode(descrizione);
        newa.appendChild(newtext);
        contenitore.append(newa);
        assegna_bc_click();
    }

    function getHeightDocument() {
        var yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        return pageHeight;

    }


    function dropdownTextSelected(selectId, selectedValue) {
        var mySelect = document.getElementById(selectId);
        var currValue;
        for (var cont = 0; cont < mySelect.options.length; cont++) {
            if (mySelect.options[cont].value == selectedValue) {
                currValue = mySelect.options[cont].text;
            }
        }
        return currValue;
    };

    //zone click
    function zona_clicked(codiceZona, bChangeCheckBox, valore_cb) {
        var valore_da_assegnare;
        dl_SlideDown($('#ctl00_CPH_TC_RCMI_dlZone'));
        if (bChangeCheckBox) { selectOptionByValue('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'ZONE'); }
        var zona_CodiceZona = document.getElementById(codiceZona);
        var indexSelected = $(zona_CodiceZona).attr('style').toLowerCase().indexOf('display: block;');
        if ((indexSelected == -1 && valore_cb == null) || valore_cb == true) {
            valore_da_assegnare = true;
            if (indexSelected == -1) {
                var a = $(zona_CodiceZona).attr("style");
                if (a.toLowerCase().indexOf('display: inline;') != -1) {
                    a = a.substring(16, a.length);
                };
                if (a.toLowerCase().indexOf('display: block;') == -1) {
                    a = "display: block;" + a;
                    $(zona_CodiceZona).removeAttr('style');
                    $(zona_CodiceZona).attr('style', a);
                };

            }
        }
        //altrimenti lo toglie dalla zona
        else {
            valore_da_assegnare = false;
            if (indexSelected != -1) {
                var a = $(zona_CodiceZona).attr("style");
                if (a.toLowerCase().indexOf('display: block;') != -1) {
                    a = a.substring(15, a.length);
                };
                $(zona_CodiceZona).removeAttr('style');
                $(zona_CodiceZona).attr('style', a);
            }
        }
        var panel_raggio = document.getElementById('ctl00_CPH_TC_RCMI_panelRaggio');
        if (panel_raggio != null)
            panel_raggio.removeAttribute('style');
        if (bChangeCheckBox) {
            setClassOnSelected('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'ZONE', 'valued', 'current');
            var z_CodiceZona = document.getElementById('z_' + codiceZona.substring(1, codiceZona.length));
            if (z_CodiceZona != null)
                z_CodiceZona.checked = valore_da_assegnare;
        }
        return false;
    };

    //click sul checkbox del comule limitrofo
    function assegna_check_zona_click() {
        var a = $('#ctl00_CPH_TC_RCMI_dlZone input');
        a.click(function() {
            var title = $(this).attr('id');
            var Zona = title.substr(2);
            return cbZona_Click('z' + Zona, this.checked);
        });
    };

    function assegna_zona_click() {
        var a = $('.zona_frazione');
        a.click(function() {
            var title = $(this).attr('id');
            var Zona = title.substr(5);
            return zona_clicked(Zona, true);
        });
    };

    function cbZona_Click(codiceZona, checked) {
        zona_clicked(codiceZona, false, checked);
    };

    //ho tolto a MappaItalia il runat=server. se da problemi deve essere rimesso e deve essere trovato un modo per far sparire la mappa
    function DecodeHtml(stringa) {
        var a = stringa.replace('&agrave;', 'à');
        a = a.replace('Ã', 'à');
        a = a.replace('&egrave;', 'è');
        a = a.replace('&eacute;', 'é');
        a = a.replace('&igrave;', 'ì');
        a = a.replace('&ograve;', 'ò');
        return a.replace('&ugrave;', 'ù');
    };
    function add_option_to_dropdown(dropdown, value, html) {
        if (dropdown != null) {
            var newOption = document.createElement("option");
            dropdown.options.add(newOption);
            newOption.value = value;
            newOption.innerHTML = html;
        }
    };
    function disabilita_dropdown(nome_dropdown) {
        $('#' + nome_dropdown + ' >option').remove();
        $('#' + nome_dropdown).attr('disabled', 'true').removeClass('valued');
    };
    function rimuovi_selezioni_dropdown(nome_dropdown) {
        $('#' + nome_dropdown).removeClass('valued').removeClass('current');
        $('#' + nome_dropdown + ' >option').removeAttr('selected').removeClass('current');
    };
    function selectOptionByValue(selectId, selectedValue) {
        var mySelect = document.getElementById(selectId);
        var alreadySelected = false;
        if (mySelect != null) {
            for (var cont = 0; cont < mySelect.options.length; cont++) {
                if (mySelect.options[cont].value == selectedValue) {
                    alreadySelected = mySelect.options[cont].selected;
                    mySelect.options[cont].setAttribute('selected', 'selected');
                    mySelect.options[cont].selected = 'selected';
                }
                mySelect.options[cont].selected = (mySelect.options[cont].value == selectedValue);
            }
        }
        //ho remmato questo if per fare in modo che non si blocchi quando si clicca su un oggetto (es regione) che deve azionare il change
        //della dropdown, e questa essendo già selezionata non esegue il change. verificare se non da altri problemi
        if (!alreadySelected)
            $('#' + selectId).change();
    };
    function setClassOnSelected(selectId, selectedValue, classObject, classOption) {
        var mySelect = document.getElementById(selectId);
        if (mySelect != null) {
            //aggiungere un parametro che se il valore è vuoto assegnare la classe oppure no
            $('#' + selectId).removeClass(classObject)
            if (selectedValue != '' && selectedValue != null)
                mySelect.className = classObject;

            for (var cont = 0; cont < mySelect.options.length; cont++) {
                //mySelect.options[cont].removeAttribute('selected');
                mySelect.options[cont].removeAttribute('class');
                mySelect.options[cont].removeAttribute('className');
                mySelect.options[cont].selected = false;
                if (mySelect.options[cont].value != "") {

                    if (mySelect.options[cont].value == selectedValue) {
                        mySelect.options[cont].className = classOption;
                        mySelect.options[cont].setAttribute('selected', 'selected');
                        mySelect.options[cont].selected = 'selected';
                    }
                }
            }
        }
    };
    
    function setClassOnSelectedForGroupTipologie(selectId, selectedValue, classObject, classOption) {
        var mySelect = document.getElementById(selectId);
        var classe_cg;
        if (mySelect != null) {
            //aggiungere un parametro che se il valore è vuoto assegnare la classe oppure no
            $('#' + selectId).removeClass(classObject)
            if (selectedValue != '' && selectedValue != null)
                mySelect.className = classObject;
            for (var cont = 0; cont < mySelect.options.length; cont++) {
                //mySelect.options[cont].removeAttribute('selected');
                mySelect.options[cont].removeAttribute('class');
                mySelect.options[cont].removeAttribute('className');
                mySelect.options[cont].selected = false;
                if (mySelect.options[cont].value != "") {

                    if (mySelect.options[cont].value >= 1000)
                    {
                        classe_cg = " cg";
                    }
                    else
                    {
                        classe_cg = "";
                    }

                    if (mySelect.options[cont].value == selectedValue) {
                        mySelect.options[cont].className = classOption + classe_cg;
                        mySelect.options[cont].setAttribute('selected', 'selected');
                        mySelect.options[cont].selected = 'selected';
                    }
                    else
                    {
                        if (classe_cg != '')
                        {
                            mySelect.options[cont].className = classe_cg.substr(1,2);
                            }
                    }
                }
            }
        }
    };

    function cbRaggio_Click(codiceIstat1, codiceIstat2, checked) {
        bolla_clicked(codiceIstat1, codiceIstat2, false, checked);
    };

    function conta_checked(selectId) {
        var mySelect = document.getElementById(selectId);
        var cont_cheched = 0;
        for (var cont = 0; cont < mySelect.options.length; cont++) {
            if (mySelect.options[cont].checked == true) {
                cont_cheched = cont_cheched + 1;
            }
        }
        return cont_cheched;
    }

    function bolla_clicked(codiceIstat1, codiceIstat2, bChangeCheckBox, valore_cb) {
        var valore_da_assegnare;
        dl_SlideDown($('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi'));
        if (bChangeCheckBox) { selectOptionByValue('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'LIMITROFI'); }
        // Se stessa palla esco senza fare nulla
        if (codiceIstat1 != codiceIstat2) {
            var bolla_CodiceIstat2 = document.getElementById('bolla_' + codiceIstat2);
            var indexSelected = bolla_CodiceIstat2.className.indexOf(' rSelected');
            //controlla che se non c'è "rSelected" lo mette nella bolla
            if ((indexSelected == -1 && valore_cb == null) || valore_cb == true) {
                valore_da_assegnare = true;
                if (indexSelected == -1) {
                    // Se era ad es 'r30b' (per via di un cliet precedente senza onmouseout), metto 'r30 rSelected'
                    var indexB = bolla_CodiceIstat2.className.lastIndexOf('b');
                    if (indexB == bolla_CodiceIstat2.className.length - 1)
                        bolla_CodiceIstat2.className = bolla_CodiceIstat2.className.substring(0, indexB);
                    bolla_CodiceIstat2.className = bolla_CodiceIstat2.className + ' rSelected';
                }
            }
            //altrimenti lo toglie dalla bolla
            else {
                valore_da_assegnare = false;
                if (indexSelected != -1) {
                    // Se era ad es 'r30', metto 'r30b', che è lo stesso stile senza l'hover,
                    // in questo modo pulisco subito l'interno, senza aspettare che il mouse esca (per non avere più l'hover)
                    bolla_CodiceIstat2.className = bolla_CodiceIstat2.className.substring(0, indexSelected) + 'b';
                    if (bolla_CodiceIstat2.onmouseout == null)
                        bolla_CodiceIstat2.onmouseout = function() {
                            // Sul mouseout, se era ad es 'r30b', metto 'r30'
                            var indexB = bolla_CodiceIstat2.className.lastIndexOf('b');
                            if (indexB == bolla_CodiceIstat2.className.length - 1)
                                bolla_CodiceIstat2.className = bolla_CodiceIstat2.className.substring(0, indexB);
                        }
                }
            }
            var panel_raggio = document.getElementById('ctl00_CPH_TC_RCMI_panelRaggio');
            if (panel_raggio != null)
                panel_raggio.removeAttribute('style');
            if (bChangeCheckBox) {
                //selectOptionByValue('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'LIMITROFI');
                setClassOnSelected('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', 'LIMITROFI', 'valued', 'current');
                var cb_CodiceIstat2 = document.getElementById('cb_' + codiceIstat2);
                if (cb_CodiceIstat2 != null)
                    cb_CodiceIstat2.checked = valore_da_assegnare;
                //                cb_CodiceIstat2.checked = !cb_CodiceIstat2.checked;
            }
        }
        return false;
    };

    function dl_SlideDown(dl) {
        $('.tab_zone_raggio_frazioni').attr('style', 'display:block');
        $('#MappaItalia[hide=yes]').attr('style', 'display:block');
        dl.slideDown('fast');
        $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style') + ';background-image:url(/risorse/images/ddclose.png);')
        crea_overlay();
    };
    function dl_SlideUp(dl) {
        dl.slideUp('fast');
        $('.tab_zone_raggio_frazioni').attr('style', 'display:none');
        $('#MappaItalia[hide=yes]').attr('style', 'display:none');
        //$('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:block');
        chiudi_panel = false;
        distruggi_overlay();
    };
    function popola_dropdown_province(data, nome_dropdown) {
        var dropdown = document.getElementById(nome_dropdown);
        if (dropdown != null) {
            $('#' + nome_dropdown + ' >option').remove();
            for (var i = 0; i < data.JSonProvince.length; i++) {
                var newOption = document.createElement("option");
                dropdown.options.add(newOption);
                newOption.value = data.JSonProvince[i].CodiceAlfabeticoProvincia;
                newOption.innerHTML = data.JSonProvince[i].DescrizioneProvincia;
            }
            dropdown.options[0].selected = true;
            dropdown.removeAttribute('disabled');
        }
    };
    function popola_dropdown(data, nome_dropdown) {
        var dropdown = document.getElementById(nome_dropdown);
        if (dropdown != null) {
            $('#' + nome_dropdown + ' >option').remove();
            for (var i = 0; i < data.JSonEntity.length; i++) {
                var newOption = document.createElement("option");
                dropdown.options.add(newOption);
                newOption.value = data.JSonEntity[i][0];
                newOption.innerHTML = DecodeHtml(data.JSonEntity[i][1]);
                if (data.JSonEntity[i][3] != undefined && data.JSonEntity[i][3] != '') {
                    $(newOption).addClass(data.JSonEntity[i][3])
                }
            }
            dropdown.options[0].selected = true;
            dropdown.removeAttribute('disabled');
        }
    };
    
    function popola_dl_list(data, classe_dd_list, id_list) {
        $(classe_dd_list + ' dt').remove();
        $(classe_dd_list + ' dd').remove();
        $(classe_dd_list).attr('id', id_list);
        var dd_list = document.getElementById(id_list);
        for (var i = 0; i < data.JSonEntity.length; i++) {
            var newOption = document.createElement("dd");
            //dd_list.add(newOption);
            newOption.value = data.JSonEntity[i][0];
            newOption.innerHTML = data.JSonEntity[i][1];
            newOption.appendTo(dd_list);
        }
    };
    //click su ogni regione e passo alla visualizzazione della regione
    function assegna_regione_click() {
        $('.regione').click(function() {
            var currRegione = $(this).attr('cod_reg');
            selectOptionByValue('ctl00_CPH_TC_RCMI_ddRegione', currRegione);
            return false;
        });
    };
    function assegna_regione_change() {
        $('#ctl00_CPH_TC_RCMI_ddRegione').change(function() {
            if ($('#ctl00_CPH_TC_RCMI_ddRegione option')[$('#ctl00_CPH_TC_RCMI_ddRegione').val()].text != 'Seleziona')
                $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Regione ' + $('#ctl00_CPH_TC_RCMI_ddRegione option')[$('#ctl00_CPH_TC_RCMI_ddRegione').val()].text);
            else
                $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('');
            close_all();
            $('.mappaSx div').remove();
            $('#ctl00_CPH_TC_RCMI_dlZone').remove();
            $('#ctl00_CPH_TC_RCMI_dlFrazioni').remove();
            $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').remove();
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddProvincia');
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddComuni');
            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
            //$('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
            //seleziono italia
            if ($(this).val() == 0) {
                caricaRegioni();
                //rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddRegione')
                setClassOnSelected('ctl00_CPH_TC_RCMI_ddRegione', $(this).val(), '', '');
                $('#ctl00_CPH_TC_RCMI_ddProvince').change();
            }
            else {
                //seleziono una regione
                setClassOnSelected('ctl00_CPH_TC_RCMI_ddRegione', $(this).val(), 'valued', 'current');
                caricaProvince($(this).val());
            }
            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
            return false;
        });
    };
    function assegna_provincia_click() {
        $('.provincia').click(function() {
            var currProvincia = $(this).attr('id').toUpperCase();
            $('.provincia').removeClass('current');
            $(this).addClass('current');
            selectOptionByValue('ctl00_CPH_TC_RCMI_ddProvincia', currProvincia);
            bcMappaItalia('', '< Italia', "/");
            
            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
            
            //            $('.bc_provincia').remove();
            //            var contenitore = $('.bcMappaItalia');
            //            //a
            //            $('.bcMappaItalia >a').remove();

            //            var newa = document.createElement("a");
            //            newa.setAttribute('class', 'bc_provincia');
            //            newa.setAttribute('href', $(this).attr('href'));
            //            var newtext = document.createTextNode(currProvincia);
            //            newa.appendChild(newtext);
            //            contenitore.append(newa);

            return false;
        });
    };
    //click sulla bolla del comune limitrofo
    function assegna_bolla_click() {
        $('.bolla').click(function() {
            var title = $(this).attr('id');
            var IstatCode1 = $('#ctl00_CPH_TC_RCMI_ddComuni').val();
            var IstatCode2 = title.substr(title.length - 6);
            var a = bolla_clicked(IstatCode1, IstatCode2, true);
            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
            return a;      
        });
    };

    //click sul checkbox del comule limitrofo
    function assegna_check_limitrofo_click() {
        var a = $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi input');
        a.click(function() {
            var title = $(this).attr('id');
            var IstatCode1 = $('#ctl00_CPH_TC_RCMI_ddComuni').val();
            var IstatCode2 = title.substr(title.length - 6);
            var a = cbRaggio_Click(IstatCode1, IstatCode2, this.checked);
            caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val());
            return a;
        });
    };

    function popola_dl_italia(data, classe_dd_list) {
        $(classe_dd_list + ' div').remove();
        $(classe_dd_list + ' dl').remove();
        $(classe_dd_list + ' dt').remove();
        $(classe_dd_list + ' dd').remove();
        var contenitore = document.getElementById('MappaItalia');
        var dd_list = document.createElement("dd");
        $(dd_list).attr('id', 'italia');

        //        var newa = document.createElement("a");
        //        newa.setAttribute('id', 'dt');
        //        newa.setAttribute('href', '/');
        //        var newtext = document.createTextNode('Italia');
        //        newa.appendChild(newtext);

        //        var newdt = document.createElement("dt");
        //        newdt.setAttribute('class', 'bcMappaItalia');
        //        //newdt.appendChild(newa);
        //        dd_list.appendChild(newdt);
        for (var i = 0; i < data.JSonRegioni.length; i++) {
            var newa = document.createElement("a");
            $(newa).attr('id', data.JSonRegioni[i].DescrRegionePulita);
            $(newa).attr('class', 'regione');
            $(newa).attr('cod_reg', data.JSonRegioni[i].CodiceRegione);
            $(newa).attr('href', '/' + data.JSonRegioni[i].DescrRegionePulita + '/');
            $(newa).attr('title', data.JSonRegioni[i].DescrRegione);
            var newtext = document.createTextNode(data.JSonRegioni[i].DescrRegione);
            newa.appendChild(newtext);
            var newdd = document.createElement("dd");
            newdd.appendChild(newa);
            dd_list.appendChild(newdd);
        }
        contenitore.appendChild(dd_list);

        bcMappaItalia('', 'Italia', "/");
        assegna_regione_click();
        assegna_mouseover_maplgnd();
        assegna_mouseout_maplgnd();
        //assegna_regione_change();
        return false;
    };

    function popola_dl_bolle_e_tab_comuni_limitrofi(data) {
        if (data.JSonBolle.length > 0) {
            $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').remove();
            var ddZoneFrazioniComuniLimitrofi = document.getElementById('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'LIMITROFI', 'Comuni limitrofi');
            var contenitore = document.getElementById('MappaItalia');
            if (contenitore != null) {

                $(contenitore).attr('style', 'display:block');
                var contenitore2 = document.getElementById('ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni');
                //dl
                var dl = document.createElement('dl');
                $(dl).attr('id', 'ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf');
                $(dl).attr('class', 'mappaSx');
                if (data.MappaZone == true)
                    $(dl).attr('style', 'display:none');
                else
                    $(dl).attr('style', 'display:block');

                //dt
                var newdt = document.createElement("dt");
                $(newdt).attr('class', 'bcMappaItalia');
                dl.appendChild(newdt);

                //            var newtext = document.createTextNode('Comuni limitrofi');
                //            var newdt = document.createElement("dt");
                //            newdt.appendChild(newtext);
                //            dl.appendChild(newdt);
                for (var i = 0; i < data.JSonBolle.length; i++) {

                    var newa = document.createElement("a");
                    $(newa).attr('id', 'bolla_' + data.JSonBolle[i].CodiceIstatLimitrofo);
                    $(newa).attr('href', data.JSonBolle[i].BollaHref);
                    $(newa).attr('class', data.JSonBolle[i].BollaClass);
                    $(newa).attr('style', data.JSonBolle[i].BollaStyle);
                    $(newa).attr('title', DecodeHtml(data.JSonBolle[i].DescrizioneComune));
                    var newtext = document.createTextNode(DecodeHtml(data.JSonBolle[i].DescrizioneComune));
                    newa.appendChild(newtext);
                    var newdd = document.createElement("dd");
                    newdd.appendChild(newa);
                    dl.appendChild(newdd);
                }
                contenitore.appendChild(dl);

                bcMappaItalia('', '< ' + data.DescrRegione, '/' + data.DescrRegionePerUrl + '/');
                assegna_bolla_click();

                //dl
                var dl = document.createElement('dl');
                $(dl).attr('id', 'ctl00_CPH_TC_RCMI_dlComuniLimitrofi');
                $(dl).attr('class', 'dl_zfcl');
                $(dl).attr('style', 'display:none');
                //dt
                var newtext = document.createTextNode('Raggio');
                var newdt = document.createElement("dt");
                newdt.appendChild(newtext);
                dl.appendChild(newdt);
                for (var i = 0; i < data.JSonBolle.length; i++) {
                    if (data.JSonBolle[i].Distanza != "0.0") {
                        var newcheckbox = document.createElement("input");
                        $(newcheckbox).attr('type', 'checkbox');
                        $(newcheckbox).attr('id', 'cb_' + data.JSonBolle[i].CodiceIstatLimitrofo);
                        $(newcheckbox).attr('name', 'Raggio');
                        $(newcheckbox).attr('value', data.JSonBolle[i].CodiceIstatLimitrofo);
                        var newlabel = document.createElement("label");
                        $(newlabel).attr('for', 'cb_' + data.JSonBolle[i].CodiceIstatLimitrofo);

                        $(newlabel).attr('id', 'cb_' + data.JSonBolle[i].CodiceIstatLimitrofo);
                        $(newlabel).attr('name', 'Raggio');
                        $(newlabel).attr('value', data.JSonBolle[i].CodiceIstatLimitrofo);

                        var newtext = document.createTextNode(' ' + DecodeHtml(data.JSonBolle[i].DescrizioneComune) + ' - ' + data.JSonBolle[i].Distanza + ' km');
                        newlabel.appendChild(newtext);

                        var newdd = document.createElement("dd");
                        newdd.appendChild(newcheckbox);
                        newdd.appendChild(newlabel);
                        dl.appendChild(newdd);
                    }
                }
                contenitore2.appendChild(dl);
                assegna_check_limitrofo_click();
                assegna_mouseover_maplgnd();
                assegna_mouseout_maplgnd();
            }
        }
    };

    function popola_mappa_zone(data) {
        var ddZoneFrazioniComuniLimitrofi = document.getElementById('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');

        //davide: aggiunto trim eportato da 350 a 0 perchè ora la chiamata a imageMap non restituisce niente
        if (jQuery.trim(data).toString().length > 0) {
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'COMUNE_ZONE', 'Tutto il comune');
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'ZONE', 'Solo alcune zone');
            var a = document.getElementById('MappaItalia');
            if (a != undefined) {
                a.innerHTML = data;
                //var contenitore = document.getElementById('transparent_map');
                //var newspan = document.createElement('span');
                //$(newspan).attr('class', 'bcMappaItalia');
                //$(newspan).insertBefore('#transparent_map');
                initMappeZone();
                assegna_zona_click();
                assegna_mouseover_maplgnd();
                assegna_mouseout_maplgnd();
            };
        }
        else {
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'COMUNE', 'Solo il comune');

        }
    };


    function popola_dl_zone(data) {
        var ddZoneFrazioniComuniLimitrofi = document.getElementById('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        if (data.JSonEntity.length > 0) {
            var contenitore2 = document.getElementById('ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni');
            //dl
            if (contenitore2 != null) {
                var dl = document.createElement('dl');
                $(dl).attr('id', 'ctl00_CPH_TC_RCMI_dlZone');
                $(dl).attr('class', 'dl_zfcl');

                if (data.MappaZone == true) {
                    $(dl).attr('style', 'display:block');
                }
                else {
                    $(dl).attr('style', 'display:none');
                }
                //dt
                var newtext = document.createTextNode('Zone');
                var newdt = document.createElement("dt");
                newdt.appendChild(newtext);
                dl.appendChild(newdt);
                for (var i = 0; i < data.JSonEntity.length; i++) {
                    var newcheckbox = document.createElement("input");
                    $(newcheckbox).attr('type', 'checkbox');
                    $(newcheckbox).attr('id', 'z_' + data.JSonEntity[i][0]);
                    $(newcheckbox).attr('name', 'Zone');
                    $(newcheckbox).attr('value', data.JSonEntity[i][0]);
                    var newlabel = document.createElement("label");
                    $(newlabel).attr('for', 'z_' + DecodeHtml(data.JSonEntity[i][0]));
                    var newtext = document.createTextNode(DecodeHtml(data.JSonEntity[i][1]));
                    newlabel.appendChild(newtext);

                    var newdd = document.createElement("dd");
                    newdd.appendChild(newcheckbox);
                    newdd.appendChild(newlabel);
                    dl.appendChild(newdd);
                }
                contenitore2.appendChild(dl);
                //assegna_zona_click();
                assegna_check_zona_click();
            }
            bcMappaItalia('', '< ' + data.DescrRegione, '/' + data.DescrRegionePerUrl + '/');
        }
    };

    function popola_dl_zone_e_tab_zone(data) {
        var ddZoneFrazioniComuniLimitrofi = document.getElementById('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        if (data.JSonEntity.length > 0) {
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'COMUNE_ZONE', 'Tutto il comune');
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'ZONE', 'Solo alcune zone');
            var contenitore = document.getElementById('MappaItalia');
            var contenitore2 = document.getElementById('ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni');
            //dl
            //se c'è 0 nella tabella 'comuni_istat' campo 'mappa_zone' non devo creare questo dl
            if (contenitore != null) {
                if (data.MappaZone == true) {
                    var dl = document.createElement('dl');
                    $(dl).attr('id', 'ctl00_CPH_TC_RCMI_lvZoneInMappa_lz');
                    $(dl).attr('class', 'mappaSx');
                    $(dl).attr('style', 'display:block');
                    for (var i = 0; i < data.JSonEntity.length; i++) {
                        var newa = document.createElement("a");
                        $(newa).attr('id', 'mz_' + data.JSonEntity[i][0]);
                        $(newa).attr('href', '/');
                        $(newa).attr('class', 'zona_frazione');
                        $(newa).attr('title', DecodeHtml(data.JSonEntity[i][1]));
                        var newtext = document.createTextNode(DecodeHtml(data.JSonEntity[i][1]));
                        newa.appendChild(newtext);
                        var newdd = document.createElement("dd");
                        newdd.appendChild(newa);
                        dl.appendChild(newdd);
                    }
                    contenitore.appendChild(dl);
                    assegna_check_limitrofo_click();
                }
            }
            //assegna_bolla_click();
            //dl
            if (contenitore2 != null) {
                var dl = document.createElement('dl');
                $(dl).attr('id', 'ctl00_CPH_TC_RCMI_dlZone');
                $(dl).attr('class', 'dl_zfcl');

                if (data.MappaZone == true) {
                    $(dl).attr('style', 'display:block');
                }
                else {
                    $(dl).attr('style', 'display:none');
                }
                //dt
                var newtext = document.createTextNode('Zone');
                var newdt = document.createElement("dt");
                newdt.appendChild(newtext);
                dl.appendChild(newdt);
                for (var i = 0; i < data.JSonEntity.length; i++) {
                    var newcheckbox = document.createElement("input");
                    $(newcheckbox).attr('type', 'checkbox');
                    $(newcheckbox).attr('id', 'z_' + data.JSonEntity[i][0]);
                    $(newcheckbox).attr('name', 'Zone');
                    $(newcheckbox).attr('value', data.JSonEntity[i][0]);
                    var newlabel = document.createElement("label");
                    $(newlabel).attr('for', 'z_' + DecodeHtml(data.JSonEntity[i][0]));
                    var newtext = document.createTextNode(DecodeHtml(data.JSonEntity[i][1]));
                    newlabel.appendChild(newtext);

                    var newdd = document.createElement("dd");
                    newdd.appendChild(newcheckbox);
                    newdd.appendChild(newlabel);
                    dl.appendChild(newdd);
                }
                contenitore2.appendChild(dl);
                assegna_zona_click();
            }

        }
        else {
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'COMUNE', 'Solo il comune');

        }

    };
    function caricaZoneFrazioni() {
        $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').removeAttr('disabled');
        $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').change();

    };
    function popola_tab_frazioni(data) {
        if (data.JSonEntity.length > 0) {
            var ddZoneFrazioniComuniLimitrofi = document.getElementById('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
            add_option_to_dropdown(ddZoneFrazioniComuniLimitrofi, 'FRAZ', 'Solo alcune frazioni/località');
            //aggiungere il controllo se data è vuoto non fare nulla
            var contenitore = document.getElementById('ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni');
            if (contenitore != null) {
                //dl
                var dl = document.createElement('dl');
                $(dl).attr('id', 'ctl00_CPH_TC_RCMI_dlFrazioni');
                $(dl).attr('class', 'dl_zfcl');
                $(dl).attr('style', 'display:none');
                //dt
                var newtext = document.createTextNode('Frazioni');
                var newdt = document.createElement("dt");
                newdt.appendChild(newtext);
                dl.appendChild(newdt);
                contenitore.appendChild(dl);
                for (var i = 0; i < data.JSonEntity.length; i++) {
                    var newcheckbox = document.createElement("input");
                    $(newcheckbox).attr('type', 'checkbox');
                    $(newcheckbox).attr('id', data.JSonEntity[i][0]);
                    $(newcheckbox).attr('name', 'Frazioni');
                    $(newcheckbox).attr('value', data.JSonEntity[i][0]);
                    var newlabel = document.createElement("label");
                    $(newlabel).attr('for', DecodeHtml(data.JSonEntity[i][0]));
                    var newtext = document.createTextNode(DecodeHtml(data.JSonEntity[i][1]));
                    newlabel.appendChild(newtext);
                    var newdd = document.createElement("dd");
                    newdd.appendChild(newcheckbox);
                    newdd.appendChild(newlabel);
                    dl.appendChild(newdd);
                }
                contenitore.appendChild(dl);
                //assegna_check_limitrofo_click();
            }
        }
        //caricaZoneFrazioni();
    };

    function svuota_mappa_sx() {
        $('#MappaItalia dl').remove();
        $('#MappaItalia dt').remove();
        $('#MappaItalia dd').remove();
        $('#MappaItalia div').remove();
        $('#ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni dl').remove();
        $('#ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni dt').remove();
        $('#ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni dd').remove();
        $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni >option').remove();
    };

    function popola_mappa_sx(codiceistat) {
        svuota_mappa_sx();
        // Ho sostituito $getJSON con $get perchè IE, non avendo in risposta codice json si bloccava
        // P.S. potremmo fare questa chiamata sole se ci sono zone?
        $.get('/risorse/AjaxJSon/getMappaZone.aspx?codiceistat=' + codiceistat, function(data) {
            popola_mappa_zone(data);
            $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codiceistat + '&tipozonafraz=Zona', function(data) {
                popola_dl_zone(data);
                $.getJSON('/risorse/AjaxJSon/getComuniLimitrofi.aspx?codiceistat=' + codiceistat, function(data) {
                    popola_dl_bolle_e_tab_comuni_limitrofi(data);
                    $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codiceistat + '&tipozonafraz=Frazione', function(data) {
                        popola_tab_frazioni(data);
                    });
                });
            });
        });
    };
    
    //    function popola_mappa_sx(codiceistat) {
    //        svuota_mappa_sx();
    //        $.getJSON('/risorse/AjaxJSon/getMappaZone.aspx?codiceistat=' + codiceistat, function(data) {
    //            //popola_mappa_zone(data);
    //            $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codiceistat + '&tipozonafraz=Zona', function(data) {
    //                popola_dl_zone_e_tab_zone(data);
    //                $.getJSON('/risorse/AjaxJSon/getComuniLimitrofi.aspx?codiceistat=' + codiceistat, function(data) {
    //                    popola_dl_bolle_e_tab_comuni_limitrofi(data);
    //                    $.getJSON('/risorse/AjaxJSon/getFrazioniZone.aspx?codiceistat=' + codiceistat + '&tipozonafraz=Frazione', function(data) {
    //                        popola_tab_frazioni(data);
    //                    });
    //                });
    //            });
    //        });
    //    };
    
    function popola_dl_regione(data, classe_dd_list, currValue) {
        $(classe_dd_list + ' dl').remove();
        $(classe_dd_list + ' dt').remove();
        $(classe_dd_list + ' dd').remove();

        var contenitore = document.getElementById('MappaItalia');
        if (contenitore != null) {
            var dl_list = document.createElement("dl");
            $(dl_list).attr('id', data.DescrRegionePulita);


            var newdt = document.createElement("dt");
            $(newdt).attr('class', 'bcMappaItalia');
            dl_list.appendChild(newdt);

            for (var i = 1; i < data.JSonProvince.length; i++) {
                if (data.JSonProvince[i].CodiceAlfabeticoProvinciaMinuscolo != "") {
                    var descr_provincia = DecodeHtml(data.JSonProvince[i].DescrizioneProvincia);
                    var descr_provincia_pulita = DecodeHtml(data.JSonProvince[i].DescrizioneProvinciaPulita);
                    var newa = document.createElement("a");
                    $(newa).attr('id', data.JSonProvince[i].CodiceAlfabeticoProvinciaMinuscolo);
                    $(newa).attr('href', '/provincia-' + descr_provincia_pulita + '/');
                    $(newa).attr('title', 'Provincia di ' + descr_provincia);
                    if (currValue == data.JSonProvince[i].CodiceAlfabeticoProvinciaMinuscolo) {
                        $(newa).attr('class', 'provincia current');
                    } else {
                        $(newa).attr('class', 'provincia');
                    }
                    var newtext = document.createTextNode('Provincia di ' + descr_provincia);
                    newa.appendChild(newtext);
                    var newdd = document.createElement("dd");
                    newdd.appendChild(newa);
                    dl_list.appendChild(newdd);
                }
            }
            contenitore.appendChild(dl_list);

            bcMappaItalia('', '< Italia', '/');
            assegna_provincia_click();
            assegna_mouseover_maplgnd();
            assegna_mouseout_maplgnd();
        }
    };

    function get_object_to_open_close() {
        var a = $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        var b;
        if (a.val() == "LIMITROFI") {
            b = $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi');
        };
        if (a.val() == "FRAZ") {
            b = $('#ctl00_CPH_TC_RCMI_dlFrazioni');
        };
        if (a.val() == "ZONE" || a.val() == "COMUNE_ZONE") {
            b = $('#ctl00_CPH_TC_RCMI_dlZone');
        };
        return b;
    };

    function open_close_dl() {
        var a = get_object_to_open_close();
        if (a != undefined) {
            var attrVisible = a.attr('style');
            if (attrVisible != undefined)
                attrVisible = attrVisible.toLowerCase();
            if (attrVisible == undefined || attrVisible.indexOf('display:none') != -1 || attrVisible.indexOf('display: none') != -1) {
                dl_SlideDown(a);
                chiudi_panel = true;
            }
            else {
                dl_SlideUp(a);
                chiudi_panel = false;
            }
        }
        return false;
    };

    function close_all() {
        var a = get_object_to_open_close();
        if (a != undefined) {
            if (a[0].id == "ctl00_CPH_TC_RCMI_dlComuniLimitrofi") {$('.rSelected', document.getElementById('ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf')).removeClass('rSelected')};
            var attrVisible = a.attr('style');
            dl_SlideUp(a);
            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
            chiudi_panel = false;
        }
        return false;
    };

    function close_all_dl() {
        var a = get_object_to_open_close();
        if (a != undefined) {
            var attrVisible = a.attr('style');
            dl_SlideUp(a);
            chiudi_panel = false;
        }
        return false;
    };
    function crea_overlay() {
        if ($("#overlayCont").length == 0) {
            var altezza = getHeightDocument();
            var newdivCont = document.createElement("div");
            $(newdivCont).attr('id', 'overlayCont');
            $(document.body).prepend(newdivCont)
            var newdiv = document.createElement("div");
            $(newdiv).attr('class', 'overlay');
            $(newdiv).attr('style', 'height:' + altezza + 'px');
            $('#overlayCont').append(newdiv)

            $('.overlay').click(function() {
                close_all_dl();
                distruggi_overlay()
            });
            
        }
    }
   /* function distruggi_overlay() {
        $('.overlay').remove();
        $('#overlayCont').remove();        
    }

    //apre o chiude il panelRaggi
    $('#ctl00_CPH_TC_RCMI_ddOpenClose').click(function() {
        open_close_dl();
    });
    $('#MappaItalia').mouseenter(function() {
        chiudi_panel = false;
    });
    $('#ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni').mouseenter(function() {
        chiudi_panel = false;
    });
    $('#MappaItalia').mouseleave(function() {
        chiudi_panel = true;
        var a = get_object_to_open_close();
        if (a != undefined) {
            var attributo = a.attr('style');
            if (attributo != undefined) {
                attributo = attributo.toLowerCase();
                if (attributo.indexOf('display:block') || attributo.indexOf('display: block')) {
                    setTimeout(function() { if (chiudi_panel == true) { 
                    dl_SlideUp(a); } }, 1000);
                };
            };
        }

    });
    $('#ctl00_CPH_TC_RCMI_tabsZoneRaggioFrazioni').mouseleave(function() {
        chiudi_panel = true;
        var a = get_object_to_open_close();
        if (a != undefined) {
            var attributo = a.attr('style');
            if (attributo != undefined)
                attributo = attributo.toLowerCase();
            if (attributo.indexOf('display:block') || attributo.indexOf('display: block')) {
                setTimeout(function() { if (chiudi_panel == true) { 
                dl_SlideUp(a); } }, 1000);
            }
        }
    });


    //attiva o disattiva la chiusura del panelRaggi a seconda che mi trovi o menu nel panelRaggi
    $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').click(function() {
        chiudi_panel = false;
        //non metto return false altrimenti non checcherebbe il checkbox selezionato
    }).mouseleave(function() {
        chiudi_panel = true;
        return false;
    });
*/

    function ddProvincia_change(dd) {
        if ($('#ctl00_CPH_TC_RCMI_ddProvincia option[value=' + $('#ctl00_CPH_TC_RCMI_ddProvincia')[0].value + ']')[0].text != 'Seleziona')
            $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Provincia di ' + $('#ctl00_CPH_TC_RCMI_ddProvincia option[value=' + $('#ctl00_CPH_TC_RCMI_ddProvincia')[0].value + ']')[0].text);
        else
            $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Regione ' + $('#ctl00_CPH_TC_RCMI_ddRegione option')[$('#ctl00_CPH_TC_RCMI_ddRegione').val()].text);
        close_all();
        $('.mappaSx div').remove();
        $('#ctl00_CPH_TC_RCMI_dlZone').remove();
        $('#ctl00_CPH_TC_RCMI_dlFrazioni').remove();
        $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').remove();
        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddComuni');
        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        //$('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
        var currValue = dd;

        if (dd.value == "") {
            //caricaRegioni();
            rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddProvincia')
            $('#ctl00_CPH_TC_RCMI_ddRegione').change();
            //$('#ctl00_CPH_TC_RCMI_ddComune').change();
        }
        else {

            if ($('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').length > 0) {
                $.getJSON('/risorse/AjaxJSon/getProvince.aspx?regione=' + $('#ctl00_CPH_TC_RCMI_ddRegione').val(), function(data) {
                    popola_dl_regione(data, '.mappaSx', $(currValue).val().toLowerCase());
                });
            }
            else {
                setClassOnSelected('ctl00_CPH_TC_RCMI_ddProvincia', dd.value, 'valued', 'current');
                $('.provincia').removeClass('current');
                $('#MappaItalia a[id=' + $(currValue).val().toLowerCase() + ']').addClass('current');
            }
            caricaComuni($(currValue).val());
        }
        caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val())
        return false;
    };

    //da qui in poi le funzioni per le chiamate asincrone con JSon
    function caricaRegioni() {
        $.getJSON('/risorse/AjaxJSon/getRegioni.aspx', function(data) {
            popola_dl_italia(data, '.mappaSx');
        });
    };
    function caricaProvince(regione) {
        $.getJSON('/risorse/AjaxJSon/getProvince.aspx?regione=' + regione, function(data) {
            popola_dropdown_province(data, 'ctl00_CPH_TC_RCMI_ddProvincia');
            popola_dl_regione(data, '.mappaSx');
        });
        $('#ctl00_CPH_TC_RCMI_ddProvince').change();
    };
    function caricaComuni(provincia) {
        $.getJSON('/risorse/AjaxJSon/getComuni.aspx?provincia=' + provincia, function(data) {
            popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddComuni');
        });
        $('#ctl00_CPH_TC_RCMI_ddComune').change();


        //        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        //        if ($(provincia).val() != "") {
        //            $.getJSON('/risorse/AjaxJSon/getComuni.aspx?provincia=' + $(provincia).val(), function(data) {
        //                //alert('passo');
        //                popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddComuni');
        //            });
        //            $('#ctl00_CPH_TC_RCMI_ddComuni').change();
        //        } else {
        //            disabilita_dropdown('ctl00_CPH_TC_RCMI_ddComuni');
        //        }
        //        $('#ctl00_CPH_TC_RCMI_ddComune').change();
    };

    function caricaComuniLimitrofi(comuneistat) {
        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        $.getJSON('/risorse/AjaxJSon/getComuniLimitrofi.aspx?codiceistat=' + $(comuneistat).val(),
            function(data) {
                popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
            });
    };
    function caricaTipiContratto() {
        $.getJSON('/risorse/AjaxJSon/getTipoContratto.aspx', function(data) { popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddTipoContratto'); });
        $('#ctl00_CPH_TC_RCMI_ddTipoContratto').change();
    };
    function caricaCategorie(tipo_contratto) {
        var currDescrCategoria = document.getElementById('ctl00_CPH_TC_RCMI_ddCategoria');
        var descrCategoria = dropdownTextSelected('ctl00_CPH_TC_RCMI_ddCategoria', currDescrCategoria.value);
        rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddCategoria');
        $.getJSON('/risorse/AjaxJSon/getCategorie.aspx?tipocontr=' + tipo_contratto, function(data) {
            popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddCategoria');
            $.getJSON('/risorse/AjaxJSon/getCategorie.aspx?tipocontr=' + tipo_contratto + '&descr_categoria=' + descrCategoria, function(data) {
                if (data.JSonEntity.length > 0) {
                    $('#ctl00_CPH_TC_RCMI_ddCategoria').val(data.JSonEntity[0][0]);
                    setClassOnSelected('ctl00_CPH_TC_RCMI_ddCategoria', currDescrCategoria.value, 'valued', 'current');
                    caricaTipologie(data.JSonEntity[0][0]);
                }
                else {
                    caricaTipologie(currDescrCategoria.value);
                }
            });
        });

    };
    
//vecchia gestione dropdownTipologie
//    function caricaTipologie(categoria) {
//        var currDescrTipologia = document.getElementById('ctl00_CPH_TC_RCMI_ddTipologia');
//        var descrTipologia = dropdownTextSelected('ctl00_CPH_TC_RCMI_ddTipologia', currDescrTipologia.value);
//        rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddTipologia');
//        $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?categoria=' + categoria, function(data) {
//            popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddTipologia');
//            $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?categoria=' + categoria + '&descr_tipologia=' + descrTipologia, function(data) {
//                if (data.JSonEntity.length > 0) {
//                    $('#ctl00_CPH_TC_RCMI_ddTipologia').val(data.JSonEntity[0][0]);
//                    setClassOnSelectedForGroupTipologie('ctl00_CPH_TC_RCMI_ddTipologia', currDescrTipologia.value, 'valued', 'current');
//                    $('#ctl00_CPH_TC_RCMI_ddTipologia').change();
//                }
//            });
//        });
//    };

    function caricaTipologie(categoria) {
        var cod_comune = '';
        var com_limitrofi = '';
        var tipo_contratto = '';
        var cod_provincia = '';
        if ($('#ctl00_CPH_TC_RCMI_ddTipoContratto').length > 0)
        {
            if ($('#ctl00_CPH_TC_RCMI_ddTipoContratto').val() != null) {tipo_contratto = $('#ctl00_CPH_TC_RCMI_ddTipoContratto').val()} else {tipo_contratto=''};
            if ($('#ctl00_CPH_TC_RCMI_ddProvincia').val() != null) {cod_provincia = $('#ctl00_CPH_TC_RCMI_ddProvincia').val()} else {cod_provincia=''}
            if ($('.rSelected', document.getElementById('ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf')).length > 0) {com_limitrofi = '&limitrofi=1'}
            else if ($('#ctl00_CPH_TC_RCMI_ddComuni').val() != null) {cod_comune = '&comune=' + $('#ctl00_CPH_TC_RCMI_ddComuni').val()};
            var currDescrTipologia = document.getElementById('ctl00_CPH_TC_RCMI_ddTipologia');
            var descrTipologia = dropdownTextSelected('ctl00_CPH_TC_RCMI_ddTipologia', currDescrTipologia.value);
            descrTipologia = $.trim(descrTipologia);
            rimuovi_selezioni_dropdown('ctl00_CPH_TC_RCMI_ddTipologia');
            $.getJSON('/risorse/AjaxJSon/getTipologieConGruppo.aspx?categoria=' + categoria + '&contratto=' + tipo_contratto + '&provincia=' + cod_provincia + cod_comune + com_limitrofi, function(data) {
                popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddTipologia');
                $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?categoria=' + categoria + '&descr_tipologia=' + descrTipologia, function(data) {
            
                
                    if (data.JSonEntity.length > 0) {
                        $('#ctl00_CPH_TC_RCMI_ddTipologia').val(data.JSonEntity[0][0]);
                        
                        setClassOnSelectedForGroupTipologie('ctl00_CPH_TC_RCMI_ddTipologia', currDescrTipologia.value, 'valued', 'current');
                        $('#ctl00_CPH_TC_RCMI_ddTipologia').change();
                    }
                    
                });
            });
        }
    };

    $('#ctl00_CPH_TC_RCMI_ddProvincia').change(function() { 
        ddProvincia_change(this);
    });

    $('#ctl00_CPH_TC_RCMI_ddTipoContratto').change(function() {
        if ($(this).val() == '1') {
            var newtext = document.createTextNode('Prezzo');
        }
        else {
            var newtext = document.createTextNode('€/mese');
        }
        $('#ctl00_CPH_TC_RCMI_lblPrezzo').empty();
        $('#ctl00_CPH_TC_RCMI_lblPrezzo').append(newtext);
        $('#ctl00_CPH_TC_RCMI_txtDaPrezzo').val('');
        $('#ctl00_CPH_TC_RCMI_txtAPrezzo').val('');
        setClassOnSelected('ctl00_CPH_TC_RCMI_ddTipoContratto', $(this).val(), 'valued', 'current');
        caricaCategorie($(this).val());
    });
    $('#ctl00_CPH_TC_RCMI_ddCategoria').change(function() {
        setClassOnSelected('ctl00_CPH_TC_RCMI_ddCategoria', $(this).val(), 'valued', 'current');
        caricaTipologie($(this).val());
    });
    $('#ctl00_CPH_TC_RCMI_ddTipologia').change(function() {
        setClassOnSelectedForGroupTipologie('ctl00_CPH_TC_RCMI_ddTipologia', $(this).val(), 'valued', 'current');
    });
    $('#ctl00_CPH_TC_RCMI_ddComuni').change(function() {
        if ($('#ctl00_CPH_TC_RCMI_ddComuni option[value=' + $('#ctl00_CPH_TC_RCMI_ddComuni')[0].value + ']')[0].text != 'Tutta la provincia')
            $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val($('#ctl00_CPH_TC_RCMI_ddComuni option[value=' + $('#ctl00_CPH_TC_RCMI_ddComuni')[0].value + ']')[0].text + ' (' + $('#ctl00_CPH_TC_RCMI_ddProvincia')[0].value + ')');
        else
            $('#ctl00_CPH_TC_RCMI_txtAutocomplete').val('Provincia di ' + $('#ctl00_CPH_TC_RCMI_ddProvincia option[value=' + $('#ctl00_CPH_TC_RCMI_ddProvincia')[0].value + ']')[0].text);
            
        setClassOnSelected('ctl00_CPH_TC_RCMI_ddComuni', $(this).val(), 'valued', 'current');
        close_all();
        $('.mappaSx div').remove();
        //if ($('#ctl00_CPH_TC_RCMI_ddComuni').val() == '-1') {
        $('#ctl00_CPH_TC_RCMI_dlZone').remove();
        $('#ctl00_CPH_TC_RCMI_dlFrazioni').remove();
        $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').remove();
        //}
        disabilita_dropdown('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni');
        var a = $(this).val();
        if (a > 0) {
            popola_mappa_sx(a);
            caricaZoneFrazioni();
        }
        else if (a = -1) {
            var dl = document.getElementById('ctl00_CPH_TC_RCMI_ddProvincia');
            if ($('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').length > 0) {
                $.getJSON('/risorse/AjaxJSon/getProvince.aspx?regione=' + $('#ctl00_CPH_TC_RCMI_ddRegione').val(), function(data) {
                    popola_dl_regione(data, '.mappaSx', $('#ctl00_CPH_TC_RCMI_ddProvincia').val().toLowerCase());
                });
            };
        };
        
        caricaTipologie($('#ctl00_CPH_TC_RCMI_ddCategoria').val())

    });

  /*  function hide_dl_tabs_mappa() {
        $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').attr('style', 'display:none');
        $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').attr('style', 'display:none');
        $('#dlComuniLimitrofi').attr('style', 'display:none');
        $('#ctl00_CPH_TC_RCMI_dlZone').attr('style', 'display:none');
        $('#ctl00_CPH_TC_RCMI_lvZoneInMappa_lz').attr('style', 'display:none');
        $('#ctl00_CPH_TC_RCMI_dlFrazioni').attr('style', 'display:none');
        $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:none');
        $('.bolla').removeClass('rSelected');
        $('input[name="Raggio"]').removeAttr('checked');
        $('input[name="Frazioni"]').removeAttr('checked');
        $('input[name="Zone"]').removeAttr('checked');
        $('.tab_zone_raggio_frazioni').attr('style', 'display:none');
        $('#MappaItalia[hide=yes]').attr('style', 'display:none');
        $('#map').attr('style', 'display:none');

        //si dovrà aggiungere il "reset" delle zone di sinistra.

    };

    $('#ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni').change(function() {
        
        if ($(this).val() == "COMUNE" || $(this).val() == "COMUNE_ZONE")
            setClassOnSelected('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', $(this).val(), '', '');
        else
            setClassOnSelected('ctl00_CPH_TC_RCMI_ddZoneRaggioFrazioni', $(this).val(), 'valued', 'current');

        hide_dl_tabs_mappa();
        if ($(this).val() == "COMUNE" || $(this).val() == "COMUNE_ZONE") {
            if ($('#ul_z_' + $('#ctl00_CPH_TC_RCMI_ddComuni').val()).length > 0)
                $('#map').attr('style', 'display:block');
            else
                $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').attr('style', 'display:block');
        };
        if ($(this).val() == "LIMITROFI") {
            $('.tab_zone_raggio_frazioni').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_dlComuniLimitrofi').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:block;background-image:url(/risorse/images/ddclose.png);').text('Seleziona i comuni');
            $('#MappaItalia[hide=yes]').attr('style', 'display:block');
            chiudi_panel = true;
            crea_overlay();
        };
        if ($(this).val() == "FRAZ") {
            $('.tab_zone_raggio_frazioni').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_dlFrazioni').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:block;background-image:url(/risorse/images/ddclose.png);').text('Seleziona le frazioni/località');
            chiudi_panel = true;
            crea_overlay();
        };
        if ($(this).val() == "ZONE") {
            $('#MappaItalia[hide=yes]').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_ddOpenClose').attr('style', 'display:block;background-image:url(/risorse/images/ddclose.png);').text('Seleziona le zone');
            $('.tab_zone_raggio_frazioni').attr('style', 'display:block');
            $('#ctl00_CPH_TC_RCMI_dlZone').attr('style', 'display:block');
            //se esiste lvZone farlo vedere altrimenti i limitrofi
            if ($('#ul_z_' + $('#ctl00_CPH_TC_RCMI_ddComuni').val()).length > 0)
                $('#map').attr('style', 'display:block');
            else
                $('#ctl00_CPH_TC_RCMI_MCL_lvComuniLimitrofi_lcf').attr('style', 'display:block');
            chiudi_panel = true;
            crea_overlay();
        };
        if ($(this).val() == "COMUNE" || $(this).val() == "COMUNE_ZONE")
            togli_selezioni_da_mappa_zone();

    });

    var currentThumbnailIndex = 0;
    var totalThumbnails = $('.thumbnails').length;

    //Attenzione!!! manca il fatto di modificare l'URL da small a big
    //$('.thumb_li').click(function() {
    $('.thumb_li').click(function() {        
        //var currImage = this.childNodes[1].childNodes[0].attributes['src'].value;
        //var currAlt = this.childNodes[1].childNodes[0].attributes['alt'].value;
        //alert($(this).children().children().attr('src'));
        var currImage = $(this).children().children().attr('src');
        var currAlt = $(this).children().children().attr('alt');
        $('#bigimage').attr({ src: currImage.replace('/XS/', '/M/'), alt: currAlt });
        //$('#caption.caption').text(currAlt);
        if (!(currAlt.toLowerCase().indexOf('immagine ') != -1 && currAlt.length < 12)) {
            $('#caption.caption').text(currAlt);
        }
        else {
            $('#caption.caption').text('');
        }

        var images = $('.thumbnails');
        for (var cont = 0; cont < images.length; cont++) {
            if (images[cont].attributes['src'].value == currImage) {
                currentThumbnailIndex = cont;
            }
        }
        $('#picCounter.picCounter').text((currentThumbnailIndex + 1) + ' di ' + totalThumbnails);
        return false;
    });
    $('#link-next').click(function() {
        currentThumbnailIndex = (currentThumbnailIndex == totalThumbnails - 1) ? 0 : currentThumbnailIndex + 1;
        var image = $('.thumbnails')[currentThumbnailIndex];
        var currImage = image.attributes['src'].value;
        var currAlt = image.attributes['alt'].value;
        $('#bigimage').attr({ src: currImage.replace('/XS/', '/M/'), alt: currAlt });
        if (!(currAlt.toLowerCase().indexOf('immagine ') != -1 && currAlt.length < 12)) {
            $('#caption.caption').text(currAlt);
        }
        else {
            $('#caption.caption').text('');
        }
        $('#picCounter.picCounter').text((currentThumbnailIndex + 1) + ' di ' + totalThumbnails);
        return false;
    });
    $('#link-previous').click(function() {
        currentThumbnailIndex = (currentThumbnailIndex == 0) ? totalThumbnails - 1 : currentThumbnailIndex - 1;
        var image = $('.thumbnails')[currentThumbnailIndex];
        var currImage = image.attributes['src'].value;
        var currAlt = image.attributes['alt'].value;
        $('#bigimage').attr({ src: currImage.replace('/XS/', '/M/').replace('/XS/', '/M/'), alt: currAlt });
        if (!(currAlt.toLowerCase().indexOf('immagine ') != -1 && currAlt.length < 12)) {
            $('#caption.caption').text(currAlt);
        }
        else {
            $('#caption.caption').text('');
        }
        $('#picCounter.picCounter').text((currentThumbnailIndex + 1) + ' di ' + totalThumbnails);
        return false;
    });

    $('#ctl00_CPH_txtEmailRegistrazione').change(function() {
        $.getJSON('/risorse/AjaxJSon/getTcUsers.aspx?username=' + $(this).val(), function(data) {
            if (data.JSonTcUsers.length > 0) {
                $('#ctl00_CPH_cvMail').removeAttr('style');
                $('#ctl00_CPH_cvMail').attr('style', 'color:Red;visibility:visible;');
            }
            else {
                $('#ctl00_CPH_cvMail').removeAttr('style');
                $('#ctl00_CPH_cvMail').attr('style', 'color:Red;visibility:hidden;');
            }

        });

        return false;
    });


    $('#ctl00_CPH_wizInserimentoAnnuncio_currLoginView_txtRifAnnuncio').change(function() {
        var a = document.getElementById('ctl00_CPH_currIdAgenzia');
        var b = document.getElementById('ctl00_CPH_currIdImmobile');
        $.getJSON('/risorse/AjaxJSon/getImmobili.aspx?riferimento=' + $(this).val() + '&id_agenzia=' + a.value + '&id_immobile=' + b.value, function(data) {
            if (data.JSonImmobili.length > 0) {
                $('#ctl00_CPH_wizInserimentoAnnuncio_currLoginView_cvRifAnnuncio').removeAttr('style');
                $('#ctl00_CPH_wizInserimentoAnnuncio_currLoginView_cvRifAnnuncio').attr('style', 'color:Red;visibility:visible;');
            }
            else {
                $('#ctl00_CPH_wizInserimentoAnnuncio_currLoginView_cvRifAnnuncio').removeAttr('style');
                $('#ctl00_CPH_wizInserimentoAnnuncio_currLoginView_cvRifAnnuncio').attr('style', 'color:Red;visibility:hidden;');
            }

        });

        return false;
    });

    //validatore di regione e provincia
    $('#ctl00_CPH_TC_RCMI_submitForm').click(function() {
        var mess;
        if ($('#ctl00_CPH_TC_RCMI_ddRegione').val() == 0)
            mess = "Selezionare la Regione";
        if (($('#ctl00_CPH_TC_RCMI_ddProvincia').val() == '' || $('#ctl00_CPH_TC_RCMI_ddProvincia').val() == null) 
            && ($('#ctl00_CPH_TC_RCMI_ddTipologia').val() == '' || $('#ctl00_CPH_TC_RCMI_ddTipologia').val() == null || $('#ctl00_CPH_TC_RCMI_ddTipologia').val() > 1000)) {
            if (mess != undefined)
                mess = mess + " e la Provincia o la Tipologia";
            else
                mess = "Selezionare la Provincia o la Tipologia";
        }
        if (mess == null)
            return true;
        else {
            alert(mess);
            return false;
        }
    });

    $('.frmMin').example('min');
    $('.frmMax').example('max');

    $('.frmMin').keyup(function(event) {
        ControlloNumero(this);
    });
    $('.frmMax').keyup(function(event) {
        ControlloNumero(this);
    });

    function OnlyNumericEntry(event) {
        if ((event.which < 48 || event.which > 57) && event.which != 0 && event.which != 8 && event.which != 13) {
            alert('Attenzione!!! sono consentiti solo numeri');
            return false;
        }
    }
*/

    function isEmail(what) {
        var i = new RegExp('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
        if (!i.test(what.value)) { alert("Il campo EMAIL non è valido."); what.focus(); return false }
        return true;
    }


    $('#invia_richiesta_info').click(function() {
        var mess;
        if ($('#txtNome').val() == '' || $('#txtNome').val() == null)
            mess = "Attenzione!!! Inserire il nome";

        if ($('#txtEmail').val() == '' || $('#txtEmail').val() == null) {
            if (mess != undefined)
                mess = mess + ", la mail";
            else
                mess = "Attenzione!!! Inserire la mail";
        }
        if ($('#txtTelefono').val() == '' || $('#txtTelefono').val() == null) {
            if (mess != undefined)
                mess = mess + ", il telefono";
            else
                mess = "Attenzione!!! Inserire il telefono";
        }
        if ($('#txtRichiesta').val() == '' || $('#txtRichiesta').val() == null) {
            if (mess != undefined)
                mess = mess + ", il testo della richiesta";
            else
                mess = "Attenzione!!! Inserire il testo della richiesta";
        }
        if ($('#chPrivacy')[0].checked == false) {
            if (mess != undefined)
                mess = mess + ", autorizzare il trattamento dei dati";
            else
                mess = "Attenzione!!! Autorizzare il trattamento dei dati";
        }
        if ($('#txtEmail').val() != '' && $('#txtEmail').val() != null) {
            var a = document.getElementById('txtEmail');
            var i = new RegExp('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
            if (!i.test(a.value)) {
                if (mess != undefined)
                    mess = mess + ", coreggere il formato della mail";
                else
                    mess = "Attenzione!!! coreggere il formato della mail";
            }
        }
        if (mess == null)
            return true;
        else {
            alert(mess);
            return false;
        }
    });

    $('#invia_feedback').click(function() {
        var mess;
        if ($('#txtNome').val() == '' || $('#txtNome').val() == null)
            mess = "Attenzione!!! Inserire il nome";

        if ($('#txtEmail').val() == '' || $('#txtEmail').val() == null) {
            if (mess != undefined)
                mess = mess + ", la mail";
            else
                mess = "Attenzione!!! Inserire la mail";
        }
        if ($('#txtMessaggio').val() == '' || $('#txtMessaggio').val() == null) {
            if (mess != undefined)
                mess = mess + ", il testo del messaggio";
            else
                mess = "Attenzione!!! Inserire il testo del messaggio";
        }
        if ($('#chPrivacy')[0].checked == false) {
            if (mess != undefined)
                mess = mess + ", autorizzare il trattamento dei dati";
            else
                mess = "Attenzione!!! Autorizzare il trattamento dei dati";
        }
        if ($('#txtEmail').val() != '' && $('#txtEmail').val() != null) {
            var a = document.getElementById('txtEmail');
            var i = new RegExp('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
            if (!i.test(a.value)) {
                if (mess != undefined)
                    mess = mess + ", coreggere il formato della mail";
                else
                    mess = "Attenzione!!! coreggere il formato della mail";
            }
        }
        if (mess == null)
            return true;
        else {
            alert(mess);
            return false;
        }
    });


    //    $('#ctl00_CPH_TC_RCMI_txtDaPrezzo').change(function() {
    //        $('#ctl00_CPH_TC_RCMI_txtDaPrezzo').formatCurrency();
    //    });
    //    $('#ctl00_CPH_TC_RCMI_txtAPrezzo').change(function() {
    //        $('#ctl00_CPH_TC_RCMI_txtDaPrezzo').formatCurrency();
    //    });

    
    function getCookie(Name) {
        var search = Name + "="

        if (document.cookie.length > 0) { // if there are any cookies

            offset = document.cookie.indexOf(search)

            if (offset != -1) { // if cookie exists 

                offset += search.length

                // set index of beginning of value

                end = document.cookie.indexOf(";", offset)

                // set index of end of cookie value

                if (end == -1)

                    end = document.cookie.length

                return unescape(document.cookie.substring(offset, end))

            }

        }

    }
    function split(Name, stringa) {
        var search = Name + "="

        if (stringa.length > 0) { // if there are any cookies

            offset = stringa.indexOf(search)

            if (offset != -1) { // if cookie exists 

                offset += search.length

                // set index of beginning of value

                end = stringa.indexOf("&", offset)

                // set index of end of cookie value

                if (end == -1)

                    end = stringa.length

                return unescape(stringa.substring(offset, end))

            }

        }


    }
    function resetMappaItalia() {
        var cookie = getCookie('Ricerca');
        if (cookie != undefined && cookie != "codRegione=&codProvincia=&codComune=&codZoneRaggioFrazioni=&limitrofi=&zone=&frazioni=&codTipoContratto=&codTipologia=") {
            var codRegione = split('codRegione', cookie);
            var codProvincia = split('codProvincia', cookie);
            var codComune = split('codComune', cookie);
            var codZoneRaggioFrazioni = split('codZoneRaggioFrazioni', cookie);
            var limitrofi = split('limitrofi', cookie);
            var zone = split('zone', cookie);
            var frazioni = split('frazioni', cookie);
            var codTipoContratto = split('codTipoContratto', cookie);
            var codTipologia = split('codTipologia', cookie);
            var codCategoria = split('codCategoria', cookie);


            if (($('#ctl00_CPH_TC_RCMI_ddRegione').val() != codRegione && $('#ctl00_CPH_TC_RCMI_ddRegione').val() != 0) || $('#ctl00_CPH_TC_RCMI_ddProvincia').val() != codProvincia || ($('#ctl00_CPH_TC_RCMI_ddComuni').val() != codComune && $('#ctl00_CPH_TC_RCMI_ddComuni').val() != -1)) {
                $.getJSON('/risorse/AjaxJSon/getRegioni.aspx', function(data) {
                    //popola_dl_italia(data, '.mappaSx');
                    $('#ctl00_CPH_TC_RCMI_ddRegione').val(codRegione);
                    setClassOnSelected('ctl00_CPH_TC_RCMI_ddRegione', codRegione, 'valued', 'current');
                    $.getJSON('/risorse/AjaxJSon/getProvince.aspx?regione=' + codRegione, function(data) {
                        popola_dropdown_province(data, 'ctl00_CPH_TC_RCMI_ddProvincia');
                        if (codComune == '')
                            popola_dl_regione(data, '.mappaSx');
                        $('#ctl00_CPH_TC_RCMI_ddProvincia').val(codProvincia);
                        $('#ctl00_CPH_TC_RCMI_ddProvincia').change();
                        setClassOnSelected('ctl00_CPH_TC_RCMI_ddProvincia', codProvincia, 'valued', 'current');
                        $.getJSON('/risorse/AjaxJSon/getComuni.aspx?provincia=' + codProvincia, function(data) {
                            popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddComuni');
                            if (codComune != '') {
                                $('#ctl00_CPH_TC_RCMI_ddComuni').val(codComune);
                                setClassOnSelected('ctl00_CPH_TC_RCMI_ddComuni', codComune, 'valued', 'current');
                                popola_mappa_sx(codComune);
                                caricaZoneFrazioni();
                            }
                        });
                    });
                });
            }
            //se codTipoContratto != undefined vuol dire che siamo nella ricerca agenzie
            if (codTipoContratto != undefined) {
                if ($('#ctl00_CPH_TC_RCMI_ddTipoContratto').val() != codTipoContratto) {
                    $('#ctl00_CPH_TC_RCMI_ddTipoContratto').val(codTipoContratto);
                };

                if ($('#ctl00_CPH_TC_RCMI_ddCategoria').val() != codCategoria) {
                    $.getJSON('/risorse/AjaxJSon/getCategorie.aspx?tipocontr=' + codTipoContratto, function(data) {

                        popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddCategoria');
                        $('#ctl00_CPH_TC_RCMI_ddCategoria').val(codCategoria);

                        if ($('#ctl00_CPH_TC_RCMI_ddTipologia').val() == "" && codTipologia == "") {
                            $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?categoria=' + codCategoria, function(data) {
                                popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddTipologia');
                            });
                        };
                    });
                };

                if (($('#ctl00_CPH_TC_RCMI_ddTipologia').val() != codTipologia || $('#ctl00_CPH_TC_RCMI_ddTipologia').val() == '') && codTipologia != '') {
                    if ($('#ctl00_CPH_TC_RCMI_ddTipologia >option').length > 1) {
                        $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?tipologia=' + $('#ctl00_CPH_TC_RCMI_ddTipologia >option')[1].value, function(data) {
                            if (data.length > 0 && $('#ctl00_CPH_TC_RCMI_ddCategoria').val() != data.JSonEntity[0][2]) {
                                $.getJSON('/risorse/AjaxJSon/getTipologie.aspx?categoria=' + $('#ctl00_CPH_TC_RCMI_ddCategoria').val(), function(data) {
                                    popola_dropdown(data, 'ctl00_CPH_TC_RCMI_ddTipologia');
                                    $('#ctl00_CPH_TC_RCMI_ddTipologia').val(codTipologia);
                                    setClassOnSelectedForGroupTipologie('ctl00_CPH_TC_RCMI_ddTipologia', codTipologia, 'valued', 'current');
                                });
                            } else {
                                $('#ctl00_CPH_TC_RCMI_ddTipologia').val(codTipologia);
                                setClassOnSelectedForGroupTipologie('ctl00_CPH_TC_RCMI_ddTipologia', codTipologia, 'valued', 'current');
                            }
                        });
                    };
                };
            };
        };

    };

    resetMappaItalia();

    //mappe di google
    function initializeMap(latitude, longitude, zoom) {
        if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map_canvas"));
            //map.addControl(new GOverviewMapControl());
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            var tcIcon = new GIcon();
            tcIcon.image = "/risorse/images/icona-maps.png";
            tcIcon.shadow = "/risorse/images/ombra-maps.png";
            tcIcon.iconSize = new GSize(44, 54);
            tcIcon.shadowSize = new GSize(63, 52);
            tcIcon.iconAnchor = new GPoint(22, 54);
            tcIcon.infoWindowAnchor = new GPoint(22, 1);
            markerOptions = { icon: tcIcon };
            map.setCenter(new GLatLng(latitude, longitude), zoom);
            var point = new GLatLng(latitude, longitude);
            map.addOverlay(new GMarker(point, markerOptions));
        }
    };

    function initMappeZone() {
        // Get a reference to the containing div with id='map'
        var map = $('#map');
        // Check if map exists
        if (map) {

            // Get all the areas of the imagemap
            var country_list = $('AREA');

            // Loop through all areas
            for (var i = 0; i < country_list.length; i++) {
                $(country_list[i]).attr('display', 'none');
                $(country_list[i]).mouseover(function(e) {
                    var country_id = this.id;
                    country_id = country_id.substring(country_id.indexOf('_') + 1, country_id.length);
                    if ($('#' + country_id).attr('style').toLowerCase().indexOf('block') == -1) {
                        var a = "display: inline;" + $('#' + country_id).attr("style");
                        $('#' + country_id).attr("style", a);
                    };
                });
                $(country_list[i]).mouseout(function(e) {
                    var country_id = this.id;
                    country_id = country_id.substring(country_id.indexOf('_') + 1, country_id.length);
                    if ($('#' + country_id).attr('style').toLowerCase().indexOf('block') == -1) {
                        var a = $('#' + country_id).attr("style");
                        if (a.toLowerCase().indexOf('display: inline;') != -1) {
                            a = a.substring(16, a.length);
                        };
                        $('#' + country_id).attr("style", a);
                        //$('#' + country_id).attr("style", "display:none");
                    };
                });

            }
        }
    }

    function setMaplgnd(testo) {
        $('#maplgnd').text(testo);
    };

    function clearMaplgnd() {
        $('#maplgnd').text('');
    };

    function assegna_mouseover_maplgnd() {
        $('.regione,.provincia,.bolla,.zona_frazione').mouseover(function() {
            if ($(this).attr('class') == 'zona_frazione')
                setMaplgnd($(this).attr('alt'));
            else
                setMaplgnd($(this).text());
            return false;
        });
    };

    function assegna_mouseout_maplgnd() {
        $('.regione,.provincia,.bolla,.zona_frazione').mouseout(function() {
            clearMaplgnd();
            return false;
        });
    };

    function togli_selezioni_da_mappa_zone() {
        var li = $('#map > ul > li');
        for (var cont = 0; cont < li.length; cont++) {
            var a = $(li[cont]).attr("style");
            if (a.toLowerCase().indexOf('display: block;') != -1) {
                a = a.substring(15, a.length);
                $(li[cont]).attr("style", a);
            };
        }
        return false;
    };
    
    function assegna_click_invio_mail() {
        $('.infomail').click(function() {
            var iframe = $('#ctl00_CPH_iframeRichInfo');
            iframe.attr('src', $('#ctl00_CPH_hiddenSrcIframe').val());
            //iframe.attr('style', 'display:block');
            iframe.fadeIn('fast');
            $('.infomail').attr('style', 'display:none');
            //fixbanner("adv_300x250_right_hidden");
            return false;
        })
    };

    function ControlloNumero(obj){

      var numero = "positivo";
      if (obj.value.substr(0,1)=="-") numero = "negativo";
      valore = obj.value.replace(/[^\d]/g,'').replace(/^0+/g,'');
      nuovovalore='';
      while(valore.length>3){
        nuovovalore='.'+valore.substr(valore.length-3)+nuovovalore
        valore = valore.substr(0,valore.length-3)
      }
      if (numero=="negativo")obj.value="-"+valore+nuovovalore
      else obj.value=valore+nuovovalore
      return false;
    }
    
	$("#ctl00_CPH_TC_RCMI_txtAutocomplete").autocomplete('/risorse/AjaxJSon/getAutocomplete.aspx', {autoFill:true, selectFirst:true, minChars:3, matchContains:true, maxItemsToShow:10, delay:10});
    
    $('#ctl00_CPH_TC_RCMI_txtAutocomplete').focus(function(){
        if (this.value == 'Località non trovata')
        {
            this.value = '';
            testo_dove = '';
        }
        else if (this.value != '')
        {
            testo_dove = this.value;
            this.value = '';
        }
        else
            this.value = testo_dove;
    });
    
    $('#ctl00_CPH_TC_RCMI_txtAutocomplete').blur(function(){
        if (this.value == '' && testo_dove != 'Località non trovata')
            this.value = testo_dove;
    });
    
    function cripta_stringa(descr)
    {
        if (descr != undefined)
        {
            var newDescr = '';
            for (var i = descr.length - 1; i >= 0; i--)
                newDescr = newDescr + descr[i];
            return newDescr;
        }
    }
    
    function unisci_descr_breve(){
        $('.descrizione').append(cripta_stringa($('#descr_breve').val()));
    }
    
    function format_with_zero(expr, num_zero)
    {
        if (expr.length < num_zero)
            for( var i=0; i < num_zero - expr.length; i++ ){
                expr = '0' + expr;
            }
        return expr;
    }
    
    $('.sku').click(function AddAnalyticsTrans(){
        var sku = $(this).attr('sku').split('|');
        var currentTime = new Date();
        currentTime.toLocaleString().replace('/','').replace(':','');
        var codice = sku[0];
        var prezzo = sku[1].replace(',','.');
        var descrizione = sku[2];
        var currNow = '';
        currNow = format_with_zero(currentTime.getDate().toString(), 2);
        currNow = currNow + format_with_zero((currentTime.getMonth()+1).toString(), 2);
        currNow = currNow + format_with_zero(currentTime.getFullYear().toString(), 4);
        currNow = currNow + format_with_zero(currentTime.getHours().toString(), 2);
        currNow = currNow + format_with_zero(currentTime.getMinutes().toString(), 2);
        currNow = currNow + format_with_zero(currentTime.getSeconds().toString(), 2);
        currNow = currNow + format_with_zero(currentTime.getMilliseconds().toString(), 3);
        pageTracker._trackPageview('/click.aspx');
        pageTracker._addTrans(currNow, '', prezzo, '', '', '', '', '');
        pageTracker._addItem(currNow, codice, descrizione, 'Click', prezzo, '1');
        pageTracker._trackTrans();        
    });
    
    assegna_regione_click();
    assegna_regione_change();
    assegna_provincia_click();
    assegna_check_limitrofo_click();
    assegna_bolla_click();
    assegna_check_zona_click();
    assegna_zona_click();
    initMappeZone();
    assegna_mouseover_maplgnd();
    assegna_mouseout_maplgnd();
    assegna_bc_click();
    assegna_click_invio_mail();
    unisci_descr_breve();
    //    caricaTipiContratto();

//    var a = document.getElementById('ctl00_CPH_TC_RCMI_txtAutocomplete');
//    alert('ciao');
//    a.focus();
//    alert('ciao');

