/**********************************************************************
 *
 * $Id: kaLegend.js,v 1.36 2006/06/28 01:04:16 pspencer Exp $
 *
 * purpose: a structured legend that supports grouped layers, visibility, 
 *          expand/collapse, and queryability
 *
 * author: Paul Spencer (pspencer@dmsolutions.ca)
 *
 * The original kaLegend code was written by DM Solutions Group.  Lorenzo
 * Becchi and Andrea Cappugi contributed a bunch of code too!
 *
 * TODO:
 * 
 *   - drag and drop layer re-ordering would be nice, see script.alicio.us
 *
 **********************************************************************
 *
 * Copyright (c) 2005, DM Solutions Group Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************
 *
 * To use kaLegend:
 * 
 * 1) add a script tag to your page:
 * 
 * <script type="text/javascript" src="kaLegend.js"></script>
 *
 * 2) add a <div> element to your page to contain the legend.  The div must
 *    have a unique id:
 *
 * <div id="legend"></div>
 * 
 * 3) create a new instance of kaLegend and pass it the id of the div:
 * 
 * myKaLegend = new kaLegend( 'legend' );
 *
 * and that's it :)
 * 
 *****************************************************************************/

/******************************************************************************
 * kaLegend
 * 
 * internal class to handle the legend.
 * 
 * oKaMap - the ka-Map object to attach to.
 * szID - string, the id of a div that will contain the legend
 * bStatic - boolean, true to use static legends, false to use dynamic legends
 *
 *****************************************************************************/
function kaLegend(oKaMap, szID, bStatic, options) {
    oKaMap.KaLegend = this;
    this.kaMap = oKaMap;
    this.domObj = this.kaMap.getRawObject(szID);
    this.type = (bStatic)?'static':'dynamic';
    this.expanders = [];
    this.queryCBs = [];

    this.urlBase = this.kaMap.server;
    this.urlBase += (this.urlBase!=''&&this.urlBase.substring(-1)!='/')?'':'/';

    this.showQueryCBs = true;    

    if (this.type == 'static') {
        this.domImg = document.createElement( 'img' );
        this.domImg.src = this.kaMap.aPixel.src;
        this.domObj.appendChild( this.domImg );
		this.GroupObj = null
    } else {
        //this.domObj.innerHTML = '&nbsp;';
		this.GroupObj = null
		this.aGroups = []
    }
	
    this.showVisibilityControl = true;
    this.showQueryControl = true;
    
    if (typeof options != 'undefined') {
        this.showVisibilityControl = typeof options.visibility != 'undefined' ? options.visibility : true;
        this.showQueryControl = typeof options.query != 'undefined' ? options.query : true;
        this.showOpacityControl = typeof options.opacity != 'undefined' ? options.opacity : true;
        this.showOrderControl = typeof options.order != 'undefined' ? options.order : true;
    }
    this.showOpacityControl = true;
    this.showOrderControl = true;
    

	this.kaMap.registerForEvent( KAMAP_SCALE_CHANGED, this, this.update );
    this.kaMap.registerForEvent( KAMAP_MAP_INITIALIZED, this, this.update );
    this.kaMap.registerForEvent( KAMAP_LAYERS_CHANGED, this, this.update );
    this.kaMap.registerForEvent( KAMAP_LAYER_STATUS_CHANGED, this, this.update );
	this.kaMap.registerForEvent( KAMAP_HL_LAYER_ADD, this, this.update );
    this.kaMap.registerForEvent( KAMAP_HL_LAYER_DEL, this, this.update );
	this.kaMap.registerForEvent( KAMAP_WMS_LAYER_ADD, this, this.update );
    this.kaMap.registerForEvent( KAMAP_WMS_LAYER_DEL, this, this.update );
	this.kaMap.registerForEvent( KAMAP_WFS_LAYER_ADD, this, this.update );
    this.kaMap.registerForEvent( KAMAP_WFS_LAYER_DEL, this, this.update );
    this.kaMap.registerForEvent( KAMAP_LAYER_ORDER_CHANGE, this, this.update );
};

kaLegend.prototype.AddGroup = function( szGroup ){
	
}

kaLegend.prototype.update = function(eventID)
{
//Debug('kaLegend.prototype.update: '+eventID+', '+arguments[1]);
	var map = this.kaMap.currentMap;
    var url = '';
    if (this.type == 'static') {
        this.domImg.src = 'legend.php?map=' + 
                          this.kaMap.currentMap + 
						  '&epsgMap=' + map.epsg + 
                          '&scale='+this.kaMap.getCurrentScale();
						  
    } else {
        if (eventID == KAMAP_MAP_INITIALIZED) {
			while(this.domObj.childNodes.length > 0) {
				this.domObj.removeChild(this.domObj.childNodes[0]);
            } 
			this.draw();
			this.checkLayersVisibility();
        } else if (eventID == KAMAP_HL_LAYER_ADD) {
			var olayer = arguments[1];
			this.GroupObj.insertBefore( this.createHighLightLayerHTML( olayer ), this.GroupObj.firstChild );
		} else if (eventID == KAMAP_HL_LAYER_DEL) {
			var oLegend = arguments[1];
			this.RemoveCB(oLegend.oLayer);
			this.GroupObj.removeChild(oLegend);
        } else if (eventID == KAMAP_WMS_LAYER_ADD) {			
			var olayer = arguments[1];
			this.GroupObj.insertBefore( this.createWmsLayerHTML( olayer ), this.GroupObj.firstChild );
		} else if (eventID == KAMAP_WMS_LAYER_DEL) {
			var oLegend = arguments[1];
			this.RemoveCB(oLegend.oLayer);
			this.GroupObj.removeChild(oLegend);
        } else if (eventID == KAMAP_WFS_LAYER_ADD) {
			var olayer = arguments[1];
			this.GroupObj.insertBefore( this.createWfsLayerHTML( olayer ), this.GroupObj.firstChild );
		} else if (eventID == KAMAP_WFS_LAYER_DEL) {
			var oLegend = arguments[1];
			this.RemoveCB(oLegend.oLayer);
			this.GroupObj.removeChild(oLegend);
        } else if (eventID == KAMAP_SCALE_CHANGED) {
            var oMap = this.kaMap.getCurrentMap();
            var aLayers = oMap.getAllLayers();
            var s = this.kaMap.getCurrentScale();
            for (var i in aLayers) {
                var oLayer = aLayers[i];

				var oImg = this.kaMap.getRawObject( 'legendImg_' + oLayer.id/*eb*/);
                if (oImg) {
                    //added by Lorenzo
                    var oParent = oImg.parentNode; 
                    var tId = oImg.id;
                    var tVisibility = oImg.visibility;
                    oParent.removeChild(oImg);
                    oImg = document.createElement('img');
					oImg.Layer = oLayer;
					oImg.Legend = this;
				    oImg.onerror = kaLegend_imgOnError;
				    oImg.onload = kaLegend_imgOnLoad;
                    oImg.id = tId;
                    oImg.title = tId;
                    oImg.visibility = tVisibility;
					if ( oLayer.wms_server )
						oImg.src = oLayer.baseLegendURL
					else if ( oLayer.wfs_server )
						oImg.src = oLayer.baseLegendURL
					else
						this.SetImg(oImg,false)						;
    	                //oImg.src = 'legend.php?map='+this.kaMap.currentMap+'&scale='+s+'&g='+oLayer.name;
                    oParent.appendChild(oImg);
                    expander = getRawObject('expander_'+oLayer.id/*eb*/);
                    expander.expandable = oImg;
                    expander.expanded = true;
                    kaLegend_expander.apply( expander );
                }

				//added by cappu
                this.setOnOffLayer(oLayer);
            }
        } else if (eventID == KAMAP_LAYER_STATUS_CHANGED) {
			var layer = arguments[1];
			for (var i=0; i<this.queryCBs.length; i++) {
				if (this.queryCBs[i].oLayer == layer) {
					this.queryCBs[i].checked = layer.visible;
				}
			}
			//this.checkLayersVisibility();
			kaLegend_ToggleOnlyVisibleLayer();

//			printGroupLayer();
			
        } else if (eventID == KAMAP_LAYER_ORDER_CHANGE) {
		
//			printGroupLayer()

			kaLegend_ToggleOnlyVisibleLayer();
		}
    }
};

function printGroupLayer(){
Debug('--------------------')
			var oMap = myKaMap.getCurrentMap();
			var kaLegend = myKaMap.KaLegend;
			var oMap = kaLegend.kaMap.getCurrentMap();
			var aLayers = oMap.getAllLayers();
			var aGrp = kaLegend.aGroups
		
			for( var g=0; g<aGrp.length; g++) {
				grp = aGrp[g]
				aLyr = aGrp[g].aLayer
				for( var k=0; k<aLyr.length; k++) {
Debug(grp.GroupTitle+' , '+aLyr[k].name)
				}
			}
}


kaLegend.prototype.RemoveCB = function(l) {
	var aCB=Array();
	for(i=0,a=0;i<this.queryCBs.length;i++) {
		if (this.queryCBs[i].oLayer!=l) {
			aCB[a]=this.queryCBs[i]
			a++;
		}
	}
	this.queryCBs=aCB;
	return true;
}


/**
 * legend.draw( szContents )
 *
 * render the contents of a legend template into a div
 */
kaLegend.prototype.draw = function() {
/*modificato da kappu non trova url corretto se non lo metto anche qui*/

	this.urlBase = this.kaMap.server;
    this.urlBase += (this.urlBase!=''&&this.urlBase.substring(-1)!='/')?'':'/';

	var oMap = this.kaMap.getCurrentMap();

//    this.expanders = [];
//    this.queryCBs = [];

	var aLayers = oMap.getAllLayers();
    for (var i=(aLayers.length-1);i>=0;i--) {
        if (aLayers[i].kaLegendObj == null) {
			if ( aLayers[i].highlight == '' ){
				this.createLayerHTML( aLayers[i] );
			}
        } else {
/*
//            try{this.domObj.removeChild( aLayers[i].kaLegendObj );}

			try{	
				aLayers[i].divGroup.removeChild( aLayers[i].kaLegendObj );
			}
            catch(e){};
*/
		}
    }

	if (this.domObj.childNodes.length == 0) {
        this.domObj.appendChild( this.createHeaderHTML() );
        this.GroupObj = this.createTreeHTML();
		this.domObj.appendChild( this.GroupObj );
	}


/*
    for (var i=(aLayers.length-1);i>=0;i--) {
//        this.domObj.appendChild( aLayers[i].kaLegendObj );
		if ( aLayers[i].divGroup != null ) 
			aLayers[i].divGroup.appendChild( aLayers[i].kaLegendObj );
		else
			this.domObj.appendChild( aLayers[i].kaLegendObj );

    }
*/

    if (this.kaMap.isIE4) {
        for(var i=0; i<this.queryCBs.length; i++) {
            this.queryCBs[i].checked = this.queryCBs[i].oLayer.visible;
        }
    }
    return;
};

kaLegend.prototype.createHeaderHTML = function() {
    var d, t, tb, tr, td, img;

    d = document.createElement( 'div' );
    d.className = 'kaLegendTitle';

	t = document.createElement( 'table' );

    t.setAttribute('width','320px');
    t.setAttribute('cellPadding', "0");
    t.setAttribute('cellSpacing', "0");
    t.setAttribute('border', "0");

    tb = document.createElement( "tbody" );
    tr = document.createElement( 'tr' );
    td = document.createElement( 'td' );
	td.setAttribute('width','20px');

	img = document.createElement( 'img' );
    img.src = 'images/expand.png';
    img.alt = 'espandi tutte le icone della legenda';
    img.title = 'espandi tutte le icone della legenda';
    img.kaLegend = this;
    img.onclick = kaLegend_expandAll;
    td.appendChild( img );
    
    img = document.createElement( 'img' );
    img.src = 'images/collapse.png';
    img.alt = 'comprimi tutte le icone della legenda';
    img.title = 'comprimi tutte le icone della legenda';
    img.kaLegend = this;
    img.onclick = kaLegend_collapseAll;
    td.appendChild( img );
    tr.appendChild( td );

	td = document.createElement( 'td' );
	td.appendChild(document.createTextNode( 'Visualizza/nascondi tutte le icone della legenda' ));
	td.style.paddingBottom = '5px';
    tr.appendChild( td );
    tb.appendChild(tr);
	
    tr = document.createElement( 'tr' );
    td = document.createElement( 'td' );
    td.setAttribute('width','20px');

	cb = document.createElement( 'input' );
	cb.type = 'checkbox';
	cb.name = 'layerVisAllCB';
	cb.kaLegend = this;
	this.cbAllVis = cb;
	cb.onclick = kaLegend_toggleLayerAllVisibility;
	td.appendChild( cb );

    tr.appendChild( td );

	td = document.createElement( 'td' );
    td.setAttribute('width','198px');
    td.appendChild(document.createTextNode( 'Accendi/spegni tutti i livelli' ));
    tr.appendChild( td );
	
    tb.appendChild(tr);


    tr = document.createElement( 'tr' );
    td = document.createElement( 'td' );
    td.setAttribute('width','20px');

	cb = document.createElement( 'input' );
	cb.type = 'checkbox';
	cb.name = 'layerOnlyVisCB';
	cb.kaLegend = this;
	this.cbOnlyVis = cb;
	cb.onclick = kaLegend_ToggleOnlyVisibleLayer;
	td.appendChild( cb );
	cb.checked = true;
    tr.appendChild( td );
	td = document.createElement( 'td' );
    td.appendChild(document.createTextNode( 'Visualizza/nascondi solo i livelli accesi' ));
    tr.appendChild( td );
    tb.appendChild(tr);

	t.appendChild(tb);
    d.appendChild(t);


//	this.LegendHeader = d;
	return d;
};




kaLegend.prototype.createTreeHTML = function() {
	var oGroupContainer 
	
	oGroupContainer = document.createElement( 'div' );
	oGroupContainer.id = 'layer_container';
	oGroupContainer.className = 'kaLegendGroup';
	oGroupContainer.aLayer = [];
	oGroupContainer.GroupTitle = 'Elenco strati'
	this.aGroups.push(oGroupContainer);
//	this.LegendGroup = oGroupContainer;

    var oMap = this.kaMap.getCurrentMap();
    var aLayers = oMap.getAllLayers();

	for (var i=(aLayers.length-1);i>=0;i--) {
		var TmpGrp = oGroupContainer;
		
		if ( aLayers[i].group != '' ){
			var aTmp = aLayers[i].group.split('/');
			for ( u=0; u<aTmp.length; u++ ) {
				var bAdd = true;
				for  (cn=0;cn < TmpGrp.childNodes.length;cn++) {
					var tmpDiv = TmpGrp.childNodes[cn];
					if ( tmpDiv.nodeName == 'DIV' && tmpDiv.GroupTitle == aTmp[u]  ){
						bAdd = false;
						TmpGrp = tmpDiv.GroupContainer
						break;
					}
				}
				if ( bAdd ){
					grp = document.createElement( 'div' );
					grp.className = 'kaLegendGroup';
					grp.GroupTitle = aTmp[u]

					grpTitle = document.createElement( 'div' );
					grpTitle.className = 'kaLegendGroupTitle';
					grpTitle.onclick = kaLegend_Group_Expander;
					grpTitle.Group = grp;

					expander = document.createElement( 'img' );
					expander.src = 'images/collapse.png';
					expander.expanded = true;
					grpTitle.appendChild(expander);
					txt = document.createElement( 'span' );
					txt.innerHTML = aTmp[u];
					grpTitle.appendChild(txt);

					grpTitle.Img = expander;
					grp.appendChild( grpTitle );

					grpContainer = document.createElement( 'div' );
					grpContainer.className = 'kaLegendGroupContainer';
					grpContainer.GroupTitle = aTmp[u];
					grpContainer.Group = grp;
					grpContainer.aLayer = [];
					
					grp.GroupContainer = grpContainer
					grpTitle.GroupContainer = grpContainer
					grp.appendChild( grpContainer );

					TmpGrp.appendChild( grp );
					TmpGrp = grpContainer;
					
					this.aGroups.push(TmpGrp);
				}
			}
		}

		//alert(aLayers[i].name)

		//TmpGrp.aLayer[TmpGrp.aLayer.length] = aLayers[i];
		TmpGrp.aLayer.push(aLayers[i]);
		aLayers[i].divGroup = TmpGrp;

		TmpGrp.appendChild( aLayers[i].kaLegendObj );

//		d = document.createElement( 'div' );
//		aLayers[i].TmpkaLegendObj = d;
//		TmpGrp.appendChild( d );


//		I = document.createElement( 'div' );
//		I.className = '';
//		I.appendChild(document.createTextNode( aLayers[i].name ));
//		TmpGrp.appendChild( I );
//		TmpGrp.innerHTML += '<div class="Item" style="font-size:10px;border:1px dashed orange;">'+aLayers[i].name+'</div>';
		
    }

	return oGroupContainer;

}


kaLegend.prototype.createLayerHTML = function( oLayer ) {
    var d, t, tb, tr, td, expander, cb, img, name;

//alert(oLayer.name);
    d = document.createElement( 'div' );
    d.id = 'layer_' + oLayer.id/*eb*/;
    d.className = "kaLegendLayer";
    d.oLayer=oLayer;

	// cambio colore background su passaggio mouse
//    d.onmouseover = kaLegend_LayerOnMouseOver
//    d.onmouseout = kaLegend_LayerOnMouseOut

	// click su div layer
	d.onclick = kaLegend_setQueryableOnClick;
	oLayer.divLegend = d;

	name = oLayer.name;
//    if (name == '__base__') { name = 'Base';  }
	
    t = document.createElement('table');
//    t.setAttribute('width','300px');	//235
	t.width = '100%';
    t.setAttribute('cellPadding', "0");
    t.setAttribute('cellSpacing', "0");
//    t.setAttribute('border', "1");
	t.style.borderCollapse='collapse';

    tb = document.createElement( 'tbody' );
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.setAttribute( "width", "9");

    expander = document.createElement( 'img' );
    expander.src = 'images/collapse.png';
    expander.layerName = oLayer.id/*eb*/;
    expander.id = 'expander_'+oLayer.id/*eb*/;
    expander.onclick = kaLegend_expander;
    expander.expanded = true;
    
    this.expanders.push( expander );
    td.appendChild( expander );
    tr.appendChild(td);
    // layer visibility checkboxes
    // TODO: convert to images
    if (this.showVisibilityControl) {
		td = document.createElement('td');
	    td.setAttribute( "width", "17px");
//eb        if (oLayer.name != '__base__') {
            cb = document.createElement( 'input' );
            cb.type = 'checkbox';
            cb.name = 'layerVisCB';
            cb.value = oLayer.id/*eb*/;
            cb.checked = oLayer.visible;
            cb.kaLegend = this;
            cb.oLayer = oLayer;
            cb.onclick = kaLegend_toggleLayerVisibility;
			cb.style.width = '17px';
			cb.style.height = '17px';
			cb.style.padding = '0px';
			cb.style.margin = '0px';
            this.queryCBs.push(cb);
            td.appendChild( cb );
//eb        } else {
//            td.innerHTML = '&nbsp;';
//        }
        tr.appendChild(td);
    }
	
	var oMap = this.kaMap.getCurrentMap();
    var aLayers = oMap.getAllLayers();
	
	//Choose if you want base element to be movable (comment on line or the other)
	//not movable
    //if (oLayer.name != '__base__')
	// movable	 
    if (aLayers.length > 1) {
	// punto di aggiunta dei layer
        //OPACITY IMAGES
        if (this.showOpacityControl) {
            td = document.createElement('td');
		    td.setAttribute( "width", "18");
			td.setAttribute('nowrap', "nowrap");
            img = document.createElement( 'img' );
            img.src = 'images/sun_white.png';
			img.setAttribute('width', "7px");
			img.setAttribute('hspace', "1");
//            img.style.margin = '1px';
            img.alt = img.title = "Aumenta trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
			img.setAttribute('style', "cursor:hand;");
            img.kaLegend = this;
            img.oLayer = oLayer;
            img.onclick = kaLegend_opacityDown;
			oLayer.ImgOpcDn = img;
			td.appendChild( img );
			img = document.createElement( 'img' );
            img.src = 'images/sun_grey.png';
			img.setAttribute('width', "7px");
			img.setAttribute('hspace', "1");
            img.alt = img.title = "Diminuisci trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
			img.setAttribute('style', "cursor:hand;");
            img.kaLegend = this;
            img.oLayer = oLayer;
            img.onclick = kaLegend_opacityUp;
			oLayer.ImgOpcUp = img;
            td.appendChild( img );
            tr.appendChild(td);
        }
        if (this.showOrderControl) {
            //SHIFT LAYERS UP DOWN
            td = document.createElement('td');
            td.width = '10';
            td.style.padding = '1px';
			        
            img = document.createElement( 'img' );
            img.src = 'images/arrow_up.png';
            img.width = '10';
            img.height = '8';
            img.style.marginBottom = '2px';
            img.alt = "Shift Layer Up";
            img.title = "Shift Layer Up";
		    img.setAttribute('style', "cursor:crosshair;");
            img.kaLegend = this;
            img.oLayer = oLayer;
            img.myDiv = d;
            img.onclick = kaLegend_moveLayerUp;
			td.appendChild( img );
        
            img = document.createElement( 'img' );
            img.src = 'images/arrow_down.png';
            img.width = '10';
            img.height = '8';
            img.alt = "Shift Layer Down";
            img.title = "Shift Layer Down";
		    img.setAttribute('style', "cursor:crosshair;");
            img.kaLegend = this;
            img.oLayer = oLayer;
            img.myDiv = d;
            img.onclick = kaLegend_moveLayerDown;
            td.appendChild( img );
        
            tr.appendChild(td);
        }
    }

    if (this.showQueryControl) {
		// impostiamo tutti i livelli non interrogabili di default
		oLayer.setQueryable(false);
		// se il layer e' queryable mettiamo un icona con il link per
		// le info sui metadati
		td = document.createElement('td');
	    td.setAttribute( "width", "17");
        img = document.createElement( 'img' );
        img.src = 'images/icon_queryable.png';
	    img.style.width = '17';
	    img.style.height = '17';
		img.alt = "Visualizza metadato strato";
		img.title = "Visualizza metadato strato";
		img.onclick = kaLegend_LayerQuery;
		img.oLayer = oLayer;
        td.appendChild(img);
        tr.appendChild(td);
    }


		//*********** ZOOM ***********
		td = document.createElement('td');
	    td.setAttribute( "width", "19");
//		alert(oLayer.type)
//		if ( oLayer.type == 'vector' ){
			img = document.createElement( 'img' );
			img.src = 'images/icon_zoom_layer.png';
			img.style.width = '17px';
			img.style.height = '17px';
			img.style.padding = '1px';
			img.alt = "zoom strato";
			img.title = "zoom strato";

	
			img.onclick = kaLegend_ZoomLayer;
			img.oLayer = oLayer;
//		}else{
//			img = document.createElement( 'img' );
//			img.style.width = '17px';
//			img.style.height = '17px';
//			img.src = 'images/a_pixel.gif';
//		}
		
//        td = document.createElement( 'td' );
        td.appendChild(img);
        tr.appendChild(td);
	//**********************
	
    td = document.createElement( 'td' );
//	td.width = '150';
    td.innerHTML = name;
    tr.appendChild(td);
    tb.appendChild(tr);
    
    t.appendChild( tb );
    d.appendChild(t);
    
    img = document.createElement( 'img' );
	img.Layer = oLayer;
	img.Legend = this;
	img.onerror = kaLegend_imgOnError;
	img.onload = kaLegend_imgOnLoad;
	img.id = 'legendImg_' + oLayer.id/*eb*/;
	img.style.visibility = 'hidden';
//    img.src = this.urlBase +  'legend.php?map='+this.kaMap.currentMap+'&scale='+this.kaMap.getCurrentScale()+'&g='+oLayer.name;
	this.SetImg(img,false)						;

	/*modificato da kappu, nel cvs dimentica di aggiungere immagine */ 
	d.appendChild(img);
    expander.expandable = img;
    oLayer.kaLegendObj = d;
    kaLegend_expander.apply( expander );

	this.setOnOffLayer(oLayer);
	return d;
};


kaLegend.prototype.createHighLightLayerHTML = function( oLayer ) {
    var d, t, tb, tr, td, expander, cb, img, name;

    d = document.createElement( 'div' );
    d.id = 'layer_' + oLayer.id/*eb*/;
    d.className = "kaLegendHighLightLayer";
    d.oLayer=oLayer;

	// click su div layer
	d.onclick = kaLegend_setQueryableOnClick;
	oLayer.divLegend = d;

	name = oLayer.name;
	
    t = document.createElement('table');
//    t.setAttribute('width','235');
	t.width = '100%';
    t.setAttribute('cellPadding', "0");
    t.setAttribute('cellSpacing', "0");
    t.setAttribute('border', "0");
	t.style.borderCollapse='collapse';

    tb = document.createElement( 'tbody' );
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.width = '9px';
	if ( oLayer.viewLegend ){
		expander = document.createElement( 'img' );
		expander.src = 'images/collapse.png';
		expander.layerName = oLayer.id/*eb*/;
		expander.id = 'expander_'+oLayer.id/*eb*/;
		expander.onclick = kaLegend_expander;
		expander.expanded = true;
		this.expanders.push( expander );
		td.appendChild( expander );
	}else{
		imgSpacer = document.createElement( 'img' );
		imgSpacer.src = this.kaMap.aPixel.src; 
		imgSpacer.setAttribute('width', "9");
		imgSpacer.width = '9';
		td.appendChild( imgSpacer );
	}
	tr.appendChild(td);

    if (this.showVisibilityControl) {
		td = document.createElement('td');
	    td.setAttribute( "width", "17px");
		cb = document.createElement( 'input' );
		cb.type = 'checkbox';
		cb.name = 'layerVisCB';
		cb.value = oLayer.id/*eb*/;
		cb.checked = oLayer.visible;
		cb.kaLegend = this;
		cb.oLayer = oLayer;
		cb.onclick = kaLegend_toggleLayerVisibility;
		cb.style.width = '17px';
		cb.style.height = '17px';
		cb.style.padding = '0px';
		cb.style.margin = '0px';
		this.queryCBs.push(cb);
		td.appendChild( cb );
        tr.appendChild(td);
    }

	//OPACITY IMAGES
	if (this.showOpacityControl) {
		td = document.createElement('td');
		td.setAttribute( "width", "18");
		td.setAttribute('nowrap', "nowrap");
		img = document.createElement( 'img' );
		img.src = 'images/sun_white.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
        img.alt = img.title = "Aumenta trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityDown;
        oLayer.ImgOpcDn = img;
		td.appendChild( img );
		img = document.createElement( 'img' );
		img.src = 'images/sun_grey.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
		img.alt = img.title = "Diminuisci trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityUp;
        oLayer.ImgOpcUp = img;
		td.appendChild( img );
		tr.appendChild(td);
	}

	if (this.showOrderControl) {
		//SHIFT LAYERS UP DOWN
		td = document.createElement('td');
		td.width = '10';
		td.style.padding = '1px';
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_up.png';
		img.width = '10';
		img.height = '8';
		img.style.marginBottom = '2px';
		img.alt = "Shift Layer Up";
		img.title = "Shift Layer Up";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerUp;
		td.appendChild( img );
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_down.png';
		img.width = '10';
		img.height = '8';
		img.alt = "Shift Layer Down";
		img.title = "Shift Layer Down";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerDown;
		td.appendChild( img );
	
		tr.appendChild(td);
	}
    if (this.showQueryControl) {
        //layer queryable images
		// impostiamo tutti i livelli non interrogabili di default
		oLayer.setQueryable(false);
		// se il layer e' queryable mettiamo un icona con il link per
		// le info sui metadati
		td = document.createElement('td');
	    td.width = '17px';
        img = document.createElement( 'img' );
	    img.style.width = '17px';
	    img.style.height = '17px';
		img.alt = "Visualizza metadato strato";
		img.title = "Visualizza metadato strato";
		img.src = 'images/icon_queryable.png';
		img.onclick = kaLegend_LayerQuery;
		img.oLayer = oLayer;
	
        td = document.createElement( 'td' );
        td.appendChild(img);
//        td.width = '16';
        tr.appendChild(td);
	
    }
	//**********************
	td = document.createElement('td');
	td.width = '19px';
	img = document.createElement( 'img' );
	img.style.width = '17px';
	img.style.height = '17px';
	img.style.padding = '1px';
	if ( oLayer.extent.minx+oLayer.extent.miny+oLayer.extent.maxx+oLayer.extent.maxy != 0 ) {
		img.alt = "zoom strato";
		img.title = "zoom strato";
		img.src = 'images/icon_zoom_layer.png';
		img.onclick = kaLegend_ZoomLayer;
		img.oLayer = oLayer;
	}else{
		img.src = this.kaMap.aPixel.src;
	}
	td.appendChild(img);
	tr.appendChild(td);
	//**********************
	
	
    td = document.createElement( 'td' );
//	td.width = '150';
    td.innerHTML = name;
    tr.appendChild(td);


	/*******	elimina HL  ********/
    td = document.createElement( 'td' );
	td.width = '14';
	img = document.createElement( 'img' );
	img.style.width = '14px';
	img.style.height = '14px';
    img.src = 'images/delete.png';
	img.oLayer = oLayer;
	img.alt = img.title = "Elimina strato selezione";
	img.onclick = kaLegend_LayerHighLightDelete;
    td.appendChild(img);
	tr.appendChild(td);
	/***********/

	tb.appendChild(tr);
    
    t.appendChild( tb );
	d.appendChild(t);

//	img = document.createElement( 'img' );
//    img.id = 'legendImg_' + oLayer.name;
//    img.src = this.urlBase +  'legend.php?map='+this.kaMap.currentMap+'&scale='+this.kaMap.getCurrentScale()+'&g='+oLayer.name;
	/*modificato da kappu, nel cvs dimentica di aggiungere immagine */ 
//	d.appendChild(img);
//    expander.expandable = img;
    oLayer.kaLegendObj = d;
//    kaLegend_expander.apply( expander );

	this.setOnOffLayer(oLayer);
	return d;
};

kaLegend.prototype.createWmsLayerHTML = function( oLayer ) {
    var d, t, tb, tr, td, expander, cb, img, name;

    d = document.createElement( 'div' );
    d.id = 'layer_' + oLayer.id/*eb*/;
    d.className = "kaLegendWmsLayer";
    d.oLayer=oLayer;

	// click su div layer
	d.onclick = kaLegend_setQueryableOnClick;
	oLayer.divLegend = d;

	name = oLayer.name;
	
    t = document.createElement('table');
//    t.setAttribute('width','235');
	t.width = '100%';

	t.setAttribute('cellPadding', "0");
    t.setAttribute('cellSpacing', "0");
//    t.setAttribute('border', "1");
	t.style.borderCollapse='collapse';

    tb = document.createElement( 'tbody' );
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.width = '9px';
	if ( oLayer.viewLegend ){
		expander = document.createElement( 'img' );
		expander.src = 'images/collapse.png';
		expander.layerName = oLayer.id/*eb*/;
		expander.id = 'expander_'+oLayer.id/*eb*/;
		expander.onclick = kaLegend_expander;
		expander.expanded = true;
		this.expanders.push( expander );
		td.appendChild( expander );
	}else{
		imgSpacer = document.createElement( 'img' );
		imgSpacer.src = this.kaMap.aPixel.src; 
		imgSpacer.setAttribute('width', "9");
		imgSpacer.width = '9';
		td.appendChild( imgSpacer );
	}
	tr.appendChild(td);


    // layer visibility checkboxes
    // TODO: convert to images
    if (this.showVisibilityControl) {
		td = document.createElement('td');
	    td.setAttribute( "width", "17px");
		cb = document.createElement( 'input' );
		cb.type = 'checkbox';
		cb.name = 'layerVisCB';
		cb.value = oLayer.id/*eb*/;
		cb.checked = oLayer.visible;
		cb.kaLegend = this;
		cb.oLayer = oLayer;
		cb.onclick = kaLegend_toggleLayerVisibility;
		cb.style.width = '17px';
		cb.style.height = '17px';
		cb.style.padding = '0px';
		cb.style.margin = '0px';
		this.queryCBs.push(cb);
		td.appendChild( cb );
        tr.appendChild(td);
    }
	//Choose if you want base element to be movable (comment on line or the other)
	//not movable
    //if (oLayer.name != '__base__')
	// movable	 
	// punto di aggiunta dei layer

	//OPACITY IMAGES
	if (this.showOpacityControl) {
		td = document.createElement('td');
		td.setAttribute( "width", "18");
		td.setAttribute('nowrap', "nowrap");
		img = document.createElement( 'img' );
		img.src = 'images/sun_white.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
        img.alt = img.title = "Aumenta trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityDown;
        oLayer.ImgOpcDn = img;
		td.appendChild( img );
		img = document.createElement( 'img' );
		img.src = 'images/sun_grey.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
		img.alt = img.title = "Diminuisci trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityUp;
        oLayer.ImgOpcUp = img;
		td.appendChild( img );
		tr.appendChild(td);
	}
	
	if (this.showOrderControl) {
		//SHIFT LAYERS UP DOWN
		td = document.createElement('td');
		td.width = '10';
		td.style.padding = '1px';
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_up.png';
		img.width = '10';
		img.height = '8';
		img.style.marginBottom = '2px';
		img.alt = "Shift Layer Up";
		img.title = "Shift Layer Up";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerUp;
		td.appendChild( img );
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_down.png';
		img.width = '10';
		img.height = '8';
		img.alt = "Shift Layer Down";
		img.title = "Shift Layer Down";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerDown;
		td.appendChild( img );
	
		tr.appendChild(td);
	}

    if (this.showQueryControl) {
		td = document.createElement('td');
	    td.width = '17px';
        img = document.createElement( 'img' );
	    img.style.width = '17px';
	    img.style.height = '17px';
		img.alt = "Visualizza metadato strato";
		img.title = "Visualizza metadato strato";
		img.src = 'images/icon_queryable.png';
		img.onclick = kaLegend_LayerQuery;
		img.oLayer = oLayer;
        td.appendChild(img);
        tr.appendChild(td);
    }
	//**********************
	td = document.createElement('td');
	td.width = '19px';
	img = document.createElement( 'img' );
	img.style.width = '17px';
	img.style.height = '17px';
	img.style.padding = '1px';
	if ( oLayer.extent.minx+oLayer.extent.miny+oLayer.extent.maxx+oLayer.extent.maxy != 0 ) {
		img.alt = "zoom strato";
		img.title = "zoom strato";
		img.src = 'images/icon_zoom_layer.png';
		img.onclick = kaLegend_ZoomLayer;
		img.oLayer = oLayer;
	}else{
		img.src = this.kaMap.aPixel.src;
	}
	td.appendChild(img);
	tr.appendChild(td);
	//**********************
	
    td = document.createElement( 'td' );
//img = document.createElement( 'img' );
//img.src = 'images/earth.png';
//td.appendChild(img);

//	td.width = '139px';
//	td.width = '100%';
    td.innerHTML = name;
    tr.appendChild(td);

	/*******	refresh img  ********/
    td = document.createElement( 'td' );
	td.width = '14';
	img = document.createElement( 'img' );
	img.style.width = '14px';
	img.style.height = '14px';
    img.src = 'images/refresh.png';
	img.oLayer = oLayer;
	img.alt = img.title = "Ricarica immagini strato WMS";
	img.onclick = kaLegend_LayerWmsRefresh;
    td.appendChild(img);
	tr.appendChild(td);

	/*******	elimina wms  ********/
    td = document.createElement( 'td' );
	td.width = '14';
	img = document.createElement( 'img' );
	img.style.width = '14px';
	img.style.height = '14px';
    img.src = 'images/delete.png';
	img.oLayer = oLayer;
	img.alt = img.title = "Elimina strato WMS";
	img.onclick = kaLegend_LayerWmsDelete;
    td.appendChild(img);
	tr.appendChild(td);
	/********************************/
	tb.appendChild(tr);
    t.appendChild( tb );
	d.appendChild(t);
	if ( oLayer.viewLegend ){
		img = document.createElement( 'img' );
		img.Layer = oLayer;
		img.Legend = this;
		img.onerror = kaLegend_imgOnError;
		img.onload = kaLegend_imgOnLoad;
		img.id = 'legendImg_' + oLayer.id/*eb*/;
		img.style.visibility = 'hidden';
		img.src = oLayer.baseLegendURL;
		/*modificato da kappu, nel cvs dimentica di aggiungere immagine */ 
		d.appendChild(img);
		expander.expandable = img;
		kaLegend_expander.apply( expander );
	}
	oLayer.kaLegendObj = d;

	this.setOnOffLayer(oLayer);
	return d;
};

kaLegend.prototype.createWfsLayerHTML = function( oLayer ) {
    var d, t, tb, tr, td, expander, cb, img, name;

    d = document.createElement( 'div' );
    d.id = 'layer_' + oLayer.id/*eb*/;
    d.className = "kaLegendWfsLayer";
    d.oLayer=oLayer;

	// click su div layer
	d.onclick = kaLegend_setQueryableOnClick;
	oLayer.divLegend = d;

	name = oLayer.name;
	
    t = document.createElement('table');
//    t.setAttribute('width','235');
	t.width = '100%';

	t.setAttribute('cellPadding', "0");
    t.setAttribute('cellSpacing', "0");
//    t.setAttribute('border', "1");
	t.style.borderCollapse='collapse';

    tb = document.createElement( 'tbody' );
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.width = '9px';
	if ( oLayer.viewLegend ){
		expander = document.createElement( 'img' );
		expander.src = 'images/collapse.png';
		expander.layerName = oLayer.id/*eb*/;
		expander.id = 'expander_'+oLayer.id/*eb*/;
		expander.onclick = kaLegend_expander;
		expander.expanded = true;
		this.expanders.push( expander );
		td.appendChild( expander );
	}else{
		imgSpacer = document.createElement( 'img' );
		imgSpacer.src = this.kaMap.aPixel.src; 
		imgSpacer.setAttribute('width', "9");
		imgSpacer.width = '9';
		td.appendChild( imgSpacer );
	}
	tr.appendChild(td);


    // layer visibility checkboxes
    // TODO: convert to images
    if (this.showVisibilityControl) {
		td = document.createElement('td');
	    td.setAttribute( "width", "17px");
		cb = document.createElement( 'input' );
		cb.type = 'checkbox';
		cb.name = 'layerVisCB';
		cb.value = oLayer.id/*eb*/;
		cb.checked = oLayer.visible;
		cb.kaLegend = this;
		cb.oLayer = oLayer;
		cb.onclick = kaLegend_toggleLayerVisibility;
		cb.style.width = '17px';
		cb.style.height = '17px';
		cb.style.padding = '0px';
		cb.style.margin = '0px';
		this.queryCBs.push(cb);
		td.appendChild( cb );
        tr.appendChild(td);
    }
	//Choose if you want base element to be movable (comment on line or the other)
	//not movable
    //if (oLayer.name != '__base__')
	// movable	 
	// punto di aggiunta dei layer

	//OPACITY IMAGES
	if (this.showOpacityControl) {
		td = document.createElement('td');
		td.setAttribute( "width", "18");
		td.setAttribute('nowrap', "nowrap");
		img = document.createElement( 'img' );
		img.src = 'images/sun_white.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
        img.alt = img.title = "Aumenta trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityDown;
        oLayer.ImgOpcDn = img;
		td.appendChild( img );
		img = document.createElement( 'img' );
		img.src = 'images/sun_grey.png';
		img.setAttribute('width', "7px");
		img.setAttribute('hspace', "1");
		img.alt = img.title = "Diminuisci trasparenza\nvalore attuale: "+(100-oLayer.opacity)+"%";
		img.setAttribute('style', "cursor:hand;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.onclick = kaLegend_opacityUp;
        oLayer.ImgOpcUp = img;
		td.appendChild( img );
		tr.appendChild(td);
	}
	if (this.showOrderControl) {
		//SHIFT LAYERS UP DOWN
		td = document.createElement('td');
		td.width = '10';
		td.style.padding = '1px';
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_up.png';
		img.width = '10';
		img.height = '8';
		img.style.marginBottom = '2px';
		img.alt = "Shift Layer Up";
		img.title = "Shift Layer Up";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerUp;
		td.appendChild( img );
	
		img = document.createElement( 'img' );
		img.src = 'images/arrow_down.png';
		img.width = '10';
		img.height = '8';
		img.alt = "Shift Layer Down";
		img.title = "Shift Layer Down";
		img.setAttribute('style', "cursor:crosshair;");
		img.kaLegend = this;
		img.oLayer = oLayer;
		img.myDiv = d;
		img.onclick = kaLegend_moveLayerDown;
		td.appendChild( img );
	
		tr.appendChild(td);
	}

    if (this.showQueryControl) {
		td = document.createElement('td');
	    td.width = '17px';
        img = document.createElement( 'img' );
	    img.style.width = '17px';
	    img.style.height = '17px';
		img.alt = "Visualizza metadato strato";
		img.title = "Visualizza metadato strato";
		img.src = 'images/icon_queryable.png';
		img.onclick = kaLegend_LayerQuery;
		img.oLayer = oLayer;
        td.appendChild(img);
        tr.appendChild(td);
    }
	//**********************
	td = document.createElement('td');
	td.width = '19px';
	img = document.createElement( 'img' );
	img.style.width = '17px';
	img.style.height = '17px';
	img.style.padding = '1px';
	if ( oLayer.extent.minx+oLayer.extent.miny+oLayer.extent.maxx+oLayer.extent.maxy != 0 ) {
		img.alt = "zoom strato";
		img.title = "zoom strato";
		img.src = 'images/icon_zoom_layer.png';
		img.onclick = kaLegend_ZoomLayer;
		img.oLayer = oLayer;
	}else{
		img.src = this.kaMap.aPixel.src;
	}
	td.appendChild(img);
	tr.appendChild(td);
	//**********************
	
    td = document.createElement( 'td' );
//img = document.createElement( 'img' );
//img.src = 'images/earth.png';
//td.appendChild(img);

//	td.width = '139px';
//	td.width = '100%';
    td.innerHTML = name;
    tr.appendChild(td);

	/*******	refresh img  ********/
    td = document.createElement( 'td' );
	td.width = '14';
	img = document.createElement( 'img' );
	img.style.width = '14px';
	img.style.height = '14px';
    img.src = 'images/refresh.png';
	img.oLayer = oLayer;
	img.alt = img.title = "Ricarica immagini strato WFS";
	img.onclick = kaLegend_LayerWfsRefresh;
    td.appendChild(img);
	tr.appendChild(td);

	/*******	elimina wfs  ********/
    td = document.createElement( 'td' );
	td.width = '14';
	img = document.createElement( 'img' );
	img.style.width = '14px';
	img.style.height = '14px';
    img.src = 'images/delete.png';
	img.oLayer = oLayer;
	img.alt = img.title = "Elimina strato WFS";
	img.onclick = kaLegend_LayerWfsDelete;
    td.appendChild(img);
	tr.appendChild(td);
	/********************************/
	tb.appendChild(tr);
    t.appendChild( tb );
	d.appendChild(t);

	if ( oLayer.viewLegend ){
		img = document.createElement( 'img' );
		img.Layer = oLayer;
		img.Legend = this;
		img.onerror = kaLegend_imgOnError;
		img.onload = kaLegend_imgOnLoad;
		img.id = 'legendImg_' + oLayer.id/*eb*/;
		img.style.visibility = 'hidden';
		img.src = oLayer.baseLegendURL;
		/*modificato da kappu, nel cvs dimentica di aggiungere immagine */ 
		d.appendChild(img);
		expander.expandable = img;
		kaLegend_expander.apply( expander );
	}
	oLayer.kaLegendObj = d;

	this.setOnOffLayer(oLayer);
	return d;
};

function kaLegend_toggleLayerQueryable() {
    this.kaLegend.kaMap.setLayerQueryable( this.value, this.checked );
};

function kaLegend_queryOnMouseOver() {
    if (this.oLayer.queryable) {
        this.src = 'images/icon_query_over.png';
    }
};

function kaLegend_queryOnMouseOut() {
    if (this.oLayer.queryable) {
        if (this.oLayer.isQueryable()) {
            this.src = 'images/icon_query_on.png';
        } else {
            this.src = 'images/icon_query_off.png';
        }
    }
};

function kaLegend_queryOnClick() {
	
    if (this.oLayer.queryable) {
        if (this.oLayer.isQueryable()) {
		alert('spengo livello');
	    this.oLayer.setQueryable( false );
            this.src = 'images/icon_query_off.png';
        } else {
	    alert('accendo livello');
		// accendo il livello
            this.oLayer.setQueryable( true );
            this.src = 'images/icon_query_on.png';
	    // spengo tutti gli altri
	    var cMap = myKaMap.getCurrentMap();
	    var layers = cMap.getLayers();
	    for( var k=0; k<layers.length; k++) {
		    var layer = layers[k];
		    layer.setQueryable( false );
		    this.src = 'images/icon_query_off.png';
	    }
        }
    }
};

function kaLegend_LayerQuery() {
    var Map = myKaMap.getCurrentMap();
    var MapName = myKaMap.getCurrentMap().name;
//    var layer = this.oLayer;
//    var params = 'map=' + cMapName + '&layer=' + layer.name;    
	var l = this.oLayer
	if ( l.wms_server ){
	    var params = 'wms=' + escape(l.wms_server)
			+ '&version=' + l.wms_version
			+ '&layers=' + l.wms_layers
		WOOpenWin( 'Query', 'tools/wms/wmsQueryLayer.php?'+params, 'resizable=yes,scrollbars=yes,width=700,height=400' );
	}else if ( l.wfs_server ){
	    var params = 'wfs=' + escape(l.wfs_server)
			+ '&version=' + l.wfs_version
			+ '&layer=' + l.wfs_layer
		WOOpenWin( 'Query', 'tools/wfs/wfsQueryLayer.php?'+params, 'resizable=yes,scrollbars=yes,width=700,height=400' );
	}else{
		szLayer = l.id
		if ( l.highlight != '' )	szLayer = szLayer.replace(map.prefixHighLight,''); 
		var params = 'map=' + MapName
		+ '&layerguid=' + l.guid
		+ '&layer=' + l.id
	    WOOpenWin( 'Query', 'queryByLayer.php?'+params, 'resizable=yes,scrollbars=yes,width=700,height=400' );
	}
}

function kaLegend_LayerHighLightDelete() {
	myKaMap.removeHighLightLayer( this.oLayer ) ;
}

function kaLegend_LayerWmsDelete() {
	myKaMap.removeWmsLayer( this.oLayer ) ;
}

function kaLegend_LayerWmsRefresh() {
	myKaMap.refreshWmsLayer( this.oLayer ) ;
}

function kaLegend_LayerWfsDelete() {
	myKaMap.removeWfsLayer( this.oLayer ) ;
}

function kaLegend_LayerWfsRefresh() {
	myKaMap.refreshWfsLayer( this.oLayer ) ;
}

function kaLegend_ZoomLayer() {
	var minx = this.oLayer.extent.minx;
	var miny = this.oLayer.extent.miny;
	var maxx = this.oLayer.extent.maxx;
	var maxy = this.oLayer.extent.maxy;

	myKaMap.zoomToExtents(minx, miny, maxx, maxy);
}

function kaLegend_setQueryableOnClick() {
	//alert('kaLegend_setQueryableOnClick');

	if ( this.oLayer.isVisible() ){
		var cMap = myKaMap.getCurrentMap();
		var layers = cMap.getAllLayers();
		for( var k=0; k<layers.length; k++) {
			var layer = layers[k];
			if ( layer.divLegend == undefined ) continue;
			layer.setQueryable( false );
//		    layer.img.src = 'images/GISAmbiente/Ic_spento.gif';	
			layer.divLegend.className = layer.divLegend.className.replace(/ kaLegendLayerOn/gi,'');
			layer.divLegend.className = layer.divLegend.className.replace(/ kaLegendLayerOver/gi,'');
		}
		// impostiamo a true la sorgente
	
		this.oLayer.setQueryable(true);
	//	this.src = 'images/GISAmbiente/Ic_acceso.gif';
	//	this.oLayer.img.src = 'images/GISAmbiente/Ic_acceso.gif';
	
	//	this.div.className += ' kaLegendLayerOn';
		this.className += ' kaLegendLayerOn';
	//	this.className = this.className.replace(' kaLegendLayerOver','');
	
	//event.srcElement.checked = true;
		//alert('oLayer ' + event.srcElement.checked);
	} else {
//	    myKaMap.triggerEvent( KAMAP_LAYER_STATUS_CHANGED, this.oLayer );
	}
	myKaMap.KaLegend.checkLayersVisibility();	
};

function kaLegend_LayerOnMouseOver() {
	if ( !this.oLayer.isQueryable() )
		this.className += ' kaLegendLayerOver';
}

function kaLegend_LayerOnMouseOut() {
	if ( !this.oLayer.isQueryable() )
		this.className = this.className.replace(/ kaLegendLayerOver/gi,'');
}


function kaLegend_toggleLayerVisibility() {
/*
	if ( ! this.oLayer.isVisible() ){
		alert('livello non visibile alla scala attuale')
		return false;
	}
*/
//	alert('layer:'+this.value+'\nchecked: '+this.checked+'\n isVisible: '+this.oLayer.isVisible()+'\n visible: '+this.oLayer.visible  )
    this.kaLegend.kaMap.setLayerVisibility( this.value, this.checked );
//	alert('layer:'+this.value+'\nchecked: '+this.checked+'\n isVisible: '+this.oLayer.isVisible()+'\n visible: '+this.oLayer.visible  )
};

function kaLegend_toggleLayerAllVisibility() {
//	var oMap = this.kaLegend.kaMap.getCurrentMap();
//    var aLayers = oMap.getAllLayers();
//Debug('kaLegend_toggleLayerAllVisibility: '+this.checked)
	var cbs = this.kaLegend.queryCBs
	for (var i in cbs) {
//		if( cbs[i].oLayer.isVisible() && cbs[i].checked != this.checked ){
//		if ( cbs[i].checked != this.checked ){
			cbs[i].checked = this.checked
			this.kaLegend.kaMap.setLayerVisibility( cbs[i].oLayer.id/*eb*/, this.checked );
//		}
	}
//	kaLegend_ToggleOnlyVisibleLayer()
};

function kaLegend_Group_Expander( ){
	var d = this.GroupContainer;
	var i = this.Img;

	d.style.display = d.style.display == 'none' ? '' : 'none' ;

	i.expanded = !i.expanded;
	i.src = (i.expanded)?'images/collapse.png':'images/expand.png';
}

function kaLegend_expander() {
    this.expanded = !this.expanded;
    
    this.src = (this.expanded)?'images/collapse.png':'images/expand.png';
    this.expandable.style.display = (this.expanded)?'block':'none';
};

function kaLegend_expandAll() {
    var kaLeg = this.kaLegend;
    for (var i=0; i<kaLeg.expanders.length; i++) {
		kaLeg.expanders[i].expanded = false;
        kaLegend_expander.apply( kaLeg.expanders[i] );
    }
};

function kaLegend_collapseAll() {
    var kaLeg = this.kaLegend;
    if (kaLeg.expanders) {
        for (var i=0; i<kaLeg.expanders.length; i++) {
            kaLeg.expanders[i].expanded = true;
            kaLegend_expander.apply( kaLeg.expanders[i] );
        }
    }
};


function kaLegend_opacityDown() {
    var opc;
	if ( this.oLayer.opacity > 0){
		opc=this.oLayer.opacity-10;
		this.kaLegend.kaMap.setLayerOpacity(this.oLayer.id/*eb*/, opc );  
		this.alt = this.title = "Aumenta trasparenza\nvalore attuale: "+(100-opc)+"%";
		this.oLayer.ImgOpcUp.alt = this.oLayer.ImgOpcUp.title = "Diminuisci trasparenza\nvalore attuale: "+(100-opc)+"%";
	}
};

function kaLegend_opacityUp() {    
    var opc;
	if ( this.oLayer.opacity < 100){
		opc=this.oLayer.opacity+10;
		this.kaLegend.kaMap.setLayerOpacity(this.oLayer.id/*eb*/, opc );  
		this.alt = this.title = "Diminuisci trasparenza\nvalore attuale: "+(100-opc)+"%";
		this.oLayer.ImgOpcDn.alt = this.oLayer.ImgOpcDn.title = "Aumenta trasparenza\nvalore attuale: "+(100-opc)+"%";
	}
};

/*added by cappu used to hide layer not visible at current scala*/
kaLegend.prototype.setOnOffLayer = function(l) {
	if (l.isVisible()) {
        if (l.kaLegendObj) {
//            l.kaLegendObj.style.display='block';
			l.kaLegendObj.className = l.kaLegendObj.className.replace(/ kaLegendLayerOff/gi,'');
        } 
	} else {
        if(l.kaLegendObj) {
//            l.kaLegendObj.style.display='none';
			l.kaLegendObj.className += ' kaLegendLayerOff';
        }
    }
};

kaLegend.prototype.checkLayersVisibility = function(){
	var cbAllVis = this.cbAllVis;
	if ( cbAllVis == undefined) return ;
	var cbs = this.queryCBs;
	var CheckedCbs = 0
//Debug('kaLegend.prototype.checkLayersVisibility: ');
	for (var i in cbs) 
		if ( cbs[i].checked )
			CheckedCbs++;
	
	if ( cbs.length == CheckedCbs ) 
		cbAllVis.checked = true; 
	else 
		cbAllVis.checked = false;
}

kaLegend.prototype.SetImg = function(img, force){
	var src = '';
	var oKaMap = this.kaMap;
	var oMap = oKaMap.getCurrentMap();
	var oLayer = img.Layer;
	var CurrentScale = oKaMap.getCurrentScale()

	if ( force ){
		src = this.urlBase 
			+ 'legend.php?map='+oMap.name
			+ '&epsgMap=' + oMap.epsg
			+ '&scale='+CurrentScale
			+ '&layer='+oLayer.id/*eb*/;
	}else{
//eb        var layerDir = (oLayer.name != '') ? oLayer.name.replace(/\W/g, '_') : 'def';
        var src = oKaMap.server + oKaMap.webCache + oMap.name + '/' + CurrentScale + '/' + oLayer.id + '/' + 'legend.png';
	}
//Debug('aLegend.prototype.SetImg: '+oLayer.name+', '+img.src )

	img.style.visibility = 'hidden';
	img.src = src;
}

kaLegend_imgOnError = function (){
//Debug('kaLegend_imgOnError: '+this.src)
	var klo = this.Layer.kaLegendObj;
	if (klo.className.indexOf('kaLegendWmsLayer')!=-1 || klo.className.indexOf('kaLegendWfsLayer')!=-1){
	}else{
		this.Legend.SetImg(this,true);
	}
}

kaLegend_imgOnLoad = function (){
	this.style.visibility = 'visible';
}

/**
* kaLegend_moveLayerDown 
* About a specific Group of layer, it moves the corresponding Legend div and 
*  the Viewport div to the next one
*/

function kaLegend_moveLayerDown() {
	var myLayer= this.oLayer;
    var leg=this.myDiv.parentNode;
    var myDiv = this.myDiv;
	var lowerDiv = findLowerDiv(myDiv);
	var oMap = this.kaLegend.kaMap.getCurrentMap();

	if ( lowerDiv ){
		if ( lowerDiv.className.indexOf('kaLegendLayer')!=-1 || lowerDiv.className.indexOf('kaLegendWmsLayer')!=-1 || lowerDiv.className.indexOf('kaLegendWfsLayer')!=-1 ){
//			myDiv.oLayer.setZIndex(myDiv.oLayer.zIndex-1);
//			lowerDiv.oLayer.setZIndex(lowerDiv.oLayer.zIndex+1);
			myDiv.oLayer.SwapZIndex(lowerDiv.oLayer);
			var proxyMy = myDiv.cloneNode(true);
			var proxyLower = lowerDiv.cloneNode(true);
			myDiv.parentNode.insertBefore( proxyMy , myDiv );
			myDiv.parentNode.insertBefore( proxyLower , lowerDiv );
			myDiv.parentNode.replaceChild( lowerDiv , proxyMy );
			myDiv.parentNode.replaceChild( myDiv , proxyLower );
			oMap.SortLayerByZIndex( oMap.aLayers );				
		} else if ( lowerDiv.className == 'kaLegendGroupContainer' ){
			var parentGroup = myDiv.parentNode;
			var proxyMy = document.createElement( 'div' );
			if ( lowerDiv.firstChild )
				lowerDiv.insertBefore( proxyMy , lowerDiv.firstChild );
			else
				lowerDiv.appendChild( proxyMy );
			lowerDiv.replaceChild( myDiv, proxyMy )
			// assegna nuovo contenitore
			myDiv.oLayer.divGroup = lowerDiv;
			// rimuovi da array contenitore precedente
			for( var k=0; k<parentGroup.aLayer.length; k++) 
				if ( parentGroup.aLayer[k]==myDiv.oLayer )
					parentGroup.aLayer.splice(k,1);
			// aggiungi ad array nuovo contenitore
			lowerDiv.aLayer.push(myDiv.oLayer);
		} else if ( lowerDiv.className == 'kaLegendGroup' ){
			var parentGroupContainer = lowerDiv.parentNode;
			var proxyMy = document.createElement( 'div' );
			if ( lowerDiv.nextSibling )
				parentGroupContainer.insertBefore( proxyMy , lowerDiv.nextSibling );
			else
				parentGroupContainer.appendChild( proxyMy );
			parentGroupContainer.replaceChild( myDiv, proxyMy )
			// rimuovi da array contenitore precedente
			for( var k=0; k<lowerDiv.GroupContainer.aLayer.length; k++) 
				if ( lowerDiv.GroupContainer.aLayer[k]==myDiv.oLayer )
					lowerDiv.GroupContainer.aLayer.splice(k,1);
			// assegna nuovo contenitore
			myDiv.oLayer.divGroup = parentGroupContainer;
			// aggiungi ad array nuovo contenitore
			parentGroupContainer.aLayer.push(myDiv.oLayer);
		}

		for(var i=0; i<this.kaLegend.queryCBs.length; i++) 
			this.kaLegend.queryCBs[i].checked = this.kaLegend.queryCBs[i].oLayer.visible;

	    myKaMap.triggerEvent( KAMAP_LAYER_ORDER_CHANGE, this.oLayer );

	}else{

	}

};

/**
 * kaLegend_moveLayerUp
 * About a specific Group of layer, it moves the corresponding Legend div and 
 * the  Viewport div to the previous one
 */
function kaLegend_moveLayerUp() {
	var myLayer= this.oLayer;
    var leg=this.myDiv.parentNode;
    var myDiv = this.myDiv;
    var upperDiv = findUpperDiv(myDiv);
	var oMap = this.kaLegend.kaMap.getCurrentMap();
    
	if ( upperDiv ){
		if ( upperDiv.className.indexOf('kaLegendLayer')!=-1 || upperDiv.className.indexOf('kaLegendWmsLayer')!=-1 || upperDiv.className.indexOf('kaLegendWfsLayer')!=-1 ){
//			myDiv.oLayer.setZIndex(myDiv.oLayer.zIndex+1);
//			upperDiv.oLayer.setZIndex(upperDiv.oLayer.zIndex-1);
			myDiv.oLayer.SwapZIndex(upperDiv.oLayer);
			var proxyMy = myDiv.cloneNode(true);
			var proxyUpper = upperDiv.cloneNode(true);      
			myDiv.parentNode.insertBefore( proxyMy , myDiv );
			myDiv.parentNode.insertBefore( proxyUpper , upperDiv );
			myDiv.parentNode.replaceChild( upperDiv , proxyMy );
			myDiv.parentNode.replaceChild( myDiv , proxyUpper );
			oMap.SortLayerByZIndex( oMap.aLayers );				
		} else if ( upperDiv.className == 'kaLegendGroupContainer' ){
			var parentGroup = myDiv.parentNode;
			var proxyMy = document.createElement( 'div' );
			upperDiv.appendChild( proxyMy );
			upperDiv.replaceChild( myDiv, proxyMy )
			// assegna nuovo contenitore
			myDiv.oLayer.divGroup = upperDiv;
			// rimuovi da array contenitore precedente
			for( var k=0; k<parentGroup.aLayer.length; k++) 
				if ( parentGroup.aLayer[k]==myDiv.oLayer )
					parentGroup.aLayer.splice(k,1);
			// aggiungi ad array nuovo contenitore
			upperDiv.aLayer.push(myDiv.oLayer);
		} else if ( upperDiv.className == 'kaLegendGroup' ){
			var parentGroupContainer = upperDiv.parentNode;
			var proxyMy = document.createElement( 'div' );
			parentGroupContainer.insertBefore( proxyMy , upperDiv );
			parentGroupContainer.replaceChild( myDiv, proxyMy )
			// rimuovi da array contenitore precedente
			for( var k=0; k<upperDiv.GroupContainer.aLayer.length; k++) 
				if ( upperDiv.GroupContainer.aLayer[k]==myDiv.oLayer )
					upperDiv.GroupContainer.aLayer.splice(k,1);
			// assegna nuovo contenitore
			myDiv.oLayer.divGroup = parentGroupContainer;
			// aggiungi ad array nuovo contenitore
			parentGroupContainer.aLayer.push(myDiv.oLayer);
		}

		for(var i=0; i<this.kaLegend.queryCBs.length; i++) 
			this.kaLegend.queryCBs[i].checked = this.kaLegend.queryCBs[i].oLayer.visible;

	    myKaMap.triggerEvent( KAMAP_LAYER_ORDER_CHANGE, this.oLayer );

	}else{

	}

};

/**
* findLowerDiv
* find recursively nextSibling in legend list
*/
function findLowerDiv(div) {
	parentGroup = div.parentNode;
	lDiv = div.nextSibling;

	if( lDiv && (lDiv.className.indexOf('kaLegendLayer')!=-1 || lDiv.className.indexOf('kaLegendWmsLayer')!=-1 || lDiv.className.indexOf('kaLegendWfsLayer')!=-1 ) && lDiv.style.display=='none' ){
		findLowerDiv(lDiv);
	}else if( lDiv && lDiv.className=='kaLegendGroup' ){
		return lDiv.GroupContainer;
	}else if ( lDiv==null && parentGroup.id!='layer_container'){
		return parentGroup.Group;
	}
	return lDiv;
};
/**
* findUpperDiv
* find recursively previousSibling in legend list
*/
function findUpperDiv(div){
	parentGroup = div.parentNode;
	lDiv = div.previousSibling;

	if( lDiv && (lDiv.className.indexOf('kaLegendLayer')!=-1 || lDiv.className.indexOf('kaLegendWmsLayer')!=-1 || lDiv.className.indexOf('kaLegendWfsLayer')!=-1) && lDiv.style.display=='none' ){
		findUpperDiv(lDiv);
	}else if( lDiv && lDiv.className=='kaLegendGroup' ){
		return lDiv.GroupContainer;
	}else if ( lDiv==null && parentGroup.id!='layer_container'){
		return parentGroup.Group;
	}
	return lDiv;
}


function kaLegend_ToggleOnlyVisibleLayer(){
    var oMap = myKaMap.getCurrentMap();
	var kaLegend = myKaMap.KaLegend;
	var oMap = kaLegend.kaMap.getCurrentMap();
	var aLayers = oMap.getAllLayers();
	var aGrp = kaLegend.aGroups

	for( var k=0; k<aLayers.length; k++) {
		var l = aLayers[k];
		if (l.kaLegendObj) {
			if (!l.visible && kaLegend.cbOnlyVis.checked)
				l.kaLegendObj.style.display='none';
			else
				l.kaLegendObj.style.display='block';
		}
	}

	for( var g=0; g<aGrp.length; g++) {
		bHide = false;
		grp = aGrp[g].Group
		aLyr = aGrp[g].aLayer
		if ( grp ){
//Debug(g+' , '+grp.GroupTitle+' , '+grp.className+' , '+aLyr.length)
			for( var k=0; k<aLyr.length; k++) {
				if (aLyr[k].visible ) {
					bHide=true;
					break;
				}
			}
			if (!bHide && kaLegend.cbOnlyVis.checked)
				grp.style.display='none';
			else
				grp.style.display='block';
		}
	}

}
