//<![CDATA[
/*

visorLocal 06 abril Versio 1.2

this library is based on:

inlineWMS
Copyright (c) 2002 The University of Kansas Natural History Museum and 
Biodiversity Research Center (NHM & BRC)

All rights reserved.

Developed by: 		Dave Vieglais
                    NHM & BRC 
                    http://speciesanalyst.net
----------

Also has been modified by Nedjo Rogers (nedjo@gworks.ca)

----------

Finally modified by ideLocal

*/
//06 abr                    
var clickX=new Array(); //holds accumulated X clicks
var clickY=new Array(); //holds accumulated Y clicks
var clicks=0; //holds accumulated click count
 var geometria=1;
                    
function event_false() {
         window.event.returnValue = false
}
//Comentar para habilitar el boton derecho
//document.onselectstart = event_false;   
//document.onmousedown = nrc;               
 
function nrc(e) {
	if(document.all){
		if(event.button >1){alert('ideLocal');return false;}
	}else{
		if(e.which >1){alert('ideLocal');return false;}
	}
}


window.status="ideLocal";

asdf=0;
var pass="1";
var coordInici= new Array(260383.88,4491989,527495.1,4748184);
var estatInicial="inici";
var pasZoom="punter";
function ogcmap_convertGeom(type,pts) {
  geom = "";
  switch(type) {
    case "point":
      geom += "POINT:";
      geom += "(";
      geom += pts[0][0] + " " + pts[0][1];
      geom += ")";
      break;
    case "line":
      geom += "LINESTRING:";
      geom += "(";
        for(i=0;i<pts.length;i++) {
          geom += pts[i][0] + " " + pts[i][1];
          if(i<pts.length-1) {
            geom += ",";
          }
        }
      geom += ")";
      break;
    case "polygon":
      geom += "POLYGON:";
      geom += "(";
      geom += "(";
      for(i=0;i<pts.length;i++) {
        geom += pts[i][0] + " " + pts[i][1];
        if(i<pts.length-1) {
          geom += ",";
        }
      }
      geom += ")";
      geom += ")";
      break;
  }
  return geom;
}

// the global set of dynamically generated maps within the document
var g_ogcMaps = new Array();

//finds the image with "name" within the document "doc".
//In netscape, this method recurses through all layers until the
//image is found or not found.
//in:
//  name: the name of the image
//  doc: the document to search in - usually start with window.document.
//out: image object or null if not found.
function ogcmap_findImage(name, doc) {
  var i, img;
  for (i = 0; i < doc.images.length; i++) {
  if (doc.images[i].name == name)
    return doc.images[i];
  }
  for (i = 0; i < doc.layers.length; i++) {
    if ((img = ogcmap_findImage(name, doc.layers[i].document)) != null) {
      img.container = doc.layers[i];
      return img;
    }
  }
  return null;
}

function ogcmap_getElt () {
  if(document.getElementById && document.getElementsByName) { 
    var name = ogcmap_getElt.arguments[ogcmap_getElt.arguments.length-1];
    if(document.getElementById(name))
      return document.getElementById(name);
    else if (document.getElementsByName(name))
      return document.getElementsByName(name)[0];
  }
  else if (document.layers){
    var currentLayer = document.layers[ogcmap_getElt.arguments[0]];
    for (var i=1; i<ogcmap_getElt.arguments.length && currentLayer; i++) {
      currentLayer = currentLayer.document.layers[ogcmap_getElt.arguments[i]];
    }
    return currentLayer;
  }
  else if (document.all) {
    var elt = eval('document.all.' + ogcmap_getElt.arguments[ogcmap_getElt.arguments.length-1]);
    return(elt);
  }
}

//objects

function ogcmap_Tool(opcode,name,title,description,targetFunction,enabled) {
  this.opcode = opcode;
  this.name = name;
  this.description = description;
  this.targetFunction = targetFunction;
  this.enabled = enabled;
}

function ogcmap_Label(pt,str) {
  this.pt = pt;
  this.str = str;
}

function ogcmap_transferPoints(type, pts) {

}

function ogcmap_setZoomBox(pt1,pt2) {
  layer = this.zoomBox.style;	
  if (pt1[0]>pt2[0]){
    layer.left=pt2[0] + "px";layer.width=pt1[0]-pt2[0] + "px";
  }
  else {
    layer.left=pt1[0] + "px";layer.width=pt2[0]-pt1[0] + "px";
  }
  if (pt1[1]>pt2[1]){
    layer.top=pt2[1] + "px";layer.height=pt1[1]-pt2[1] + "px";
  }
  else {
    layer.top=pt1[1] + "px";layer.height=pt2[1]-pt1[1] + "px";
  }
}

function ogcmap_capabilities_url(aLayer) {
  var sURL = aLayer.url;
  sURL += "&REQUEST=GetCapabilities";
  return sURL;
}

function ogcmap_queryLayerURL(i,aLayer,x,y) {
var capaQ="";
  var sURL = aLayer.url;
  sURL += "REQUEST=GetFeatureInfo";
  sURL += "&VERSION=" + aLayer.version;
   for (k=0; k< this.servidores.length; k++) {
  		if (this.servidores[k][0] == i) {
  			if (this.servidores[k][3] == true) {
 			 	capaQ +=this.servidores[k][1]+",";
   			}
   		}
   }
   var gfh=(capaQ.length-1);
   capaQ=capaQ.substring(0,gfh);
   
   sURL += "&QUERY_LAYERS="+capaQ;
   sURL += "&LAYERS="+capaQ;
  sURL += "&SRS="+aLayer.epsg;
  sURL += "&X=" + x;
  sURL += "&Y=" + y;
  sURL += "&WIDTH="+this.mapWidthPX;
  sURL += "&HEIGHT="+this.mapHeightPX;
  sURL += "&FEATURE_COUNT=1";
  alert(this.cBounds[3]);
  sURL += "&BBOX=" + this.cBounds[0] + "," + this.cBounds[1] + "," + this.cBounds[2] + "," + this.cBounds[3];
  //sURL += "&INFO_FORMAT=application/vnd.ogc.gml";
  //sURL += "&INFO_FORMAT=text/html";
  //14 feb
  sURL += "&INFO_FORMAT=text/plain";
  //14 feb fin
  return sURL;
}

//Nova funcio per fer Ajax
function ogcmap_queryLayerURLAjax(aLayer,x,y) {
index=document.getElementById('select').value;

if(index.indexOf(",")!=-1){
coma=index.indexOf(",");
index=index.substring(0,coma);
}
var servidor=aLayer.url;
servidor=servidor.replace('?','&');
  var sURL ="SERVIDOR="+servidor;
 
   //sURL += "&LAYERS="+document.getElementById('Escull').value;
   //14 feb
   
   sURL += "LAYERS="+index;
  //14 feb fin
  sURL += "&X=" + x;
  sURL += "&Y=" + y;
  sURL += "&WIDTH="+this.mapWidthPX;
  sURL += "&HEIGHT="+this.mapHeightPX;
  sURL += "&Xmin=" + this.cBounds[0];
  sURL += "&Ymin=" + this.cBounds[1];
  sURL += "&Xmax=" + this.cBounds[2];
  sURL += "&Ymax=" + this.cBounds[3];
  return sURL;
}


//converts pixel to projected (or decimal degree) coordinates
//in: xp = x coordinate, yp= y coordinate
//out: array[0..1], 0 = xcoord, 1 = ycoord
function ogcmap_pixelToProj(xp,yp) {
  var aPt = new Array(0,0);
  var dx = this.cBounds[2] - this.cBounds[0];
  var dy = this.cBounds[3] - this.cBounds[1];
  aPt[0] = this.cBounds[0] + (dx*xp)/this.mapWidthPX;
  aPt[1] = this.cBounds[3] - (dy*yp)/this.mapHeightPX;
  return aPt;
}

//converts projected (or decimal degree) coordinates to pixel
//in: xp = x coordinate, yp= y coordinate
//out: array[0..1], 0 = pixelx, 1 = pixely
function ogcmap_projToPixel(xp,yp) {
  var aPt = new Array(0,0);
  var dx = this.cBounds[2] - this.cBounds[0];
  var dy = this.cBounds[3] - this.cBounds[1];
  aPt[0]=(this.mapWidthPX/dx)*(xp-this.cBounds[0]);
  aPt[1] = this.mapHeightPX-((this.mapHeightPX/dy)*(yp - this.cBounds[1]));
  return aPt;
}



//adds a tool to the map

function ogcmap_addTool(opcode,name,title,description,targetFunction,enabled) {
  this.tools[this.tools.length] = new ogcmap_Tool(opcode,name,title,description,targetFunction,enabled);
}

function ogcmap_addLabel(pt,str) {
  this.labels[this.labels.length] = new ogcmap_Label(pt,str);
  this.writeLabels();
}

function ogcmap_queryUI(x,y) {
var sURL

dataWindow=open("","","toolbar=0,directories=0,menu=0,scrollbars=0,location=0,resizable=1,status=0,top=100,left=150,width=350,height=350,menubar=0,dependent=0,hotkeys=0")
dataWindow.document.open();
dataWindow.document.write("<html><head><title>GetfeatureInfo</title></head>");
dataWindow.document.write('<link rel="stylesheet" href="css/'+codiMun+'.css">');
dataWindow.document.write('<script>');
dataWindow.document.write('function getInfo(index,template,format){document.getElementById("ifrFeatureInfo").src=document.getElementById(index).value;}');
dataWindow.document.write('</script>');
dataWindow.document.write('<form name="frmInfo"><u><b>GetFeatureInfo</b></u>');
dataWindow.document.write('<div style=height:140;overflow:auto><table border="1" cellspacing="0" cellpadding="0" bgcolor="#F4F5F7" bordercolor="#FFFFFF" width="100%">');
//10 NOV
var control = 0;
for (i=0;i < this.layers.length;i++){

	if (this.layers[i].queryable){
			var visib = this.serVisible(i);
			//alert(visib);
			if (visib){
			//if (this.layers[i].visible){
				//alert(i);
				control = 1;
				dataWindow.document.write("<tr><td class=\"normal\">"+this.layers[i].srvname+" <img OnClick=\"getInfo("+i+",'si','text/html')\" alt=\"Informació objecte seleccionat\" style=\" cursor:pointer;cursor:hand\" src=\"images/info.png\" width=\"17\" height=\"17\"></td></tr>");
		 		var rutaServ=this.queryLayerURL(i,this.layers[i],x,y);
		 		//alert(rutaServ);
		   		dataWindow.document.write('<input type="hidden" id="'+i+'" value="'+rutaServ+'" > ');
		 	}
		
		//sURL = this.queryLayerURL(this.layers[this.queryLayer],x,y);
		//window.open(sURL,this.prefix + "_QlayerUI","height=300,width=300,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes",false);
	}
}
if (control == 0){dataWindow.document.write('No hi ha cap capa activada');}
//10 NOV fin
dataWindow.document.write('</table></div><IFRAME frameborder="0" id="ifrFeatureInfo" width="100%" height="80%">');
dataWindow.document.write("</iframe></form></html>");
dataWindow.document.close();

/*
 	    } 
*/
/*
  if (!this.query)
    return;
  if (this.queryLayer < 0)
    return;
  if (this.queryLayer >= this.layers.length)
    return;
  var sURL = this.queryLayerURL(this.layers[this.queryLayer],x,y);
  */
  //alert(this.query);
 //alert(sURL);
 //var w =window.open(sURL,this.prefix + "_QlayerUI","height=300,width=300,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes",false);
}


//Nova funcio per industria

function ogcmap_queryAjax(x,y) {
  if (!this.query)
    return;
  if (this.queryLayer < 0)
    return;
  if (this.queryLayer >= this.layers.length)
    return;
  //alert(this.queryLayer);
  //14 feb
  var servisible = 0;
  for (i=0;i < this.layers.length;i++){
	if (this.layers[i].queryable){
			var visib = this.serVisible(i);
			//alert(visib);
			if (visib){
			//if (this.layers[i].visible){
				//alert(i);
				control = 1;
				servisible = i;
		 	}
		//sURL = this.queryLayerURL(this.layers[this.queryLayer],x,y);
		//window.open(sURL,this.prefix + "_QlayerUI","height=300,width=300,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes",false);
	}
  }
  
  if (servisible != 0){
  	 var sURL = this.queryLayerURLAjax(this.layers[servisible],x,y);
  	 getFeatureAjax(sURL);
  }else{
  alert("Has de visualitzar una capa de la llista");
  }
 //14 feb fin
 
 //var sURL = this.queryLayerURLAjax(this.layers[this.queryLayer],x,y);
  	 //getFeatureAjax(sURL);
  //document.getElementById('einesCerca').innerHTML=sURL;
 //var w =window.open(sURL,this.prefix + "_QlayerUI","height=300,width=300,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes",false);
}

function ogcmap_setTool(idx) {
  if(this.toolbar == true) {
    if(this.opcode > -1) {
      prevCell = ogcmap_getElt(this.gid + "_toolcell_"+this.tools[this.opcode].opcode);
      //13 Octubre
      //prevCell.style.backgroundColor="white";
     
      prevCell.className="normal"
    }
  }
  this.opcode = idx;
  if(this.toolbar == true) {
    var toolCell = ogcmap_getElt(this.gid + "_toolcell_"+this.tools[this.opcode].opcode);
    //toolCell.style.backgroundColor="green";
 
    
      toolCell.className="sobre"
  }
}

//10 NOV
function ogcmap_serVisible(idx) {
  if (idx < 0)
    return;
  if (idx >= this.layers.length)
    return;
    var ver = false;
    //alert(this.servidores[idx][3]);
   for (l=0; l < this.servidores.length; l++){
   		if (this.servidores[l][0] == idx){
   			if (this.servidores[l][3] == true){
   				ver = true;
   			}	
   		}
   } 
   return ver;
}

function ogcmap_setDefault(type,idx) {
  switch(type) {
    case "tool":
      if(idx) {
        this.setTool(idx);
      }
      else {
        var ntools = this.tools.length;
        for (var i=0; i < ntools-1; i++) {
          if(this.tools[i].enabled == true) {
            this.setTool(i);
            break;
          }
        }
      }
      break;
    case "queryLayer":
      if(idx) {
         this.setQueryLayer(idx);
      }
      else {
        var nlayers = this.layers.length;
        for (var i=0; i < nlayers-1; i++) {
          if(this.layers[i].queryable == true) {
            this.setQueryLayer(i);
            break;
          }
        }
      }
      break;
  }
}

function ogcmap_setQueryLayer(idx) {
  this.queryLayer = idx;
}



function ogcmap_writeLabels() {
  if(!this.labelsDiv) {
    return;
  }
  s = "";
  for(i=0;i<this.labels.length;i++){
    pt = this.projToPixel(this.labels[i].pt[0],this.labels[i].pt[1]);
    //s += "<div style=\"position:absolute;left:" + pt[0]+ "px;top:" + pt[1] + "px;\">" + this.labels[i].str + "</div>\n";
  
  s += "<div style=\"color:white;position:absolute;left:" + (pt[0]+1) + "px;top:" + (pt[1]) + "px;\">" + this.labels[i].str + "</div>\n";
s += "<div style=\"color:white;position:absolute;left:" + (pt[0]) + "px;top:" + (pt[1]+1) + "px;\">" + this.labels[i].str + "</div>\n";
s += "<div style=\"color:white;position:absolute;left:" + (pt[0]-1) + "px;top:" + (pt[1]) + "px;\">" + this.labels[i].str + "</div>\n";
s += "<div style=\"color:white;position:absolute;left:" + (pt[0]) + "px;top:" + (pt[1]-1) + "px;\">" + this.labels[i].str + "</div>\n";
s += "<div style=\"color:red;position:absolute;left:" + pt[0]+ "px;top:" + pt[1] + "px;\">" + this.labels[i].str + "</div>\n";
     
  
  
  }
  this.labelsDiv.innerHTML = s;
}

//14 NOV
//redondea numero
function redondear(cantidad, decimales) {
	var cantidad = parseFloat(cantidad);
	var decimales = parseFloat(decimales);
	decimales = (!decimales ? 2 : decimales);
	return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
}    

function ogcmap_limpiar(){
	this.inputPts.splice(0,this.inputPts.length);
	this.PtsPoli.splice(0,this.PtsPoli.length);
	this.PtsLine.splice(0,this.PtsLine.length);
	this.jg.clear();
	this.drawPts();
	escriuValorInfo("");
	this.labelsDiv.innerHTML="";
	document.getElementById('y1').value = "";
  	document.getElementById('y0').value = "";
  	document.getElementById('x1').value = "";
  	document.getElementById('x0').value = "";
  	document.getElementById('boxSpatial').value = "";
  	document.getElementById('puntInci').style.visibility='hidden';
}



function ogcmap_drawPts() {
//alert("drawPts");
  if(!this.jg) {
    return;
  }
  s = "";
  // convert all geographic coords into image space and draw
  var imgxs = new Array();
  var imgys = new Array();
  var linewidth = 2;
  var markerdiam = linewidth * 2;
  var markerrad = markerdiam * 2;
  var raiz = 0;
  var total = 0;
  var poligono = 0;
  var puntos = 0;
  var linea = 0;
  
  //14 feb
  //dibujar linea
  if (this.PtsLine.length > 0){
  	this.jg.setColor("red");
  	this.jg.setStroke(2);
  	linea = 1;
  }
  for (j=0; j<this.PtsLine.length; j++){
  	tmp = new Array();
  	tmp = this.projToPixel(this.PtsLine[j][0],this.PtsLine[j][1]);
    imgxs[imgxs.length] = parseInt(tmp[0]);
    imgys[imgys.length] = parseInt(tmp[1]);
  }
  //dibujar poligono
  if (this.PtsPoli.length > 0){
  	//alert(this.PtsPoli.length);
  	
  	this.jg.setColor("red");
  	this.jg.setStroke(2);
  	this.dibujo.style.filter="alpha(opacity=25)";
  	this.dibujo.style.opacity=.25;
  	poligono = 1;
  	//alert(this.PtsPoli);
  }
  for (j=0; j<this.PtsPoli.length; j++){
  	tmp = new Array();
  	tmp = this.projToPixel(this.PtsPoli[j][0],this.PtsPoli[j][1]);
    imgxs[imgxs.length] = parseInt(tmp[0]);
    imgys[imgys.length] = parseInt(tmp[1]);
  }
  //14 feb fin
  
  //var k = 0;
  //alert(this.inputPts.length);
  if (this.inputPts.length > 0){
  	puntos = 1;
  }
  for (i=0; i<this.inputPts.length; i++) {
    tmp = new Array();
    tmp = this.projToPixel(this.inputPts[i][0],this.inputPts[i][1]);
    
    //14 NOV
  //alert(k);
  if (i != 0) {
    //alert("entra");
    var xmin = this.inputPts[i-1][0];
    var ymin = this.inputPts[i-1][1];
    var xmax = this.inputPts[i][0];
    var ymax = this.inputPts[i][1];
    
    
    
    var filtre=xmin+'p';
    
     filtre=filtre.indexOf('.');
     
    if(filtre < 4){ 
    //estem parlant de coord no metrica
    var xy = new Array(2);
	var xy1 = new Array(2);  
    var lon = parseFloat (xmin);
    var lat = parseFloat (ymin);
      
 zone = Math.floor ((lon + 180.0) / 6) + 1;
 zone = LatLonToUTMXY (DegToRad (lat), DegToRad (lon), zone, xy);

       xmin=xy[0];
       ymin=xy[1];
        
        lon1 = parseFloat (xmax);
        lat1 = parseFloat (ymax); 
        zone = Math.floor ((lon + 180.0) / 6) + 1;   
        zone = LatLonToUTMXY (DegToRad (lat1), DegToRad (lon1), zone, xy1);

       xmax=xy1[0];
       ymax=xy1[1];
    }
    var x = xmax - xmin;
    var y = ymax - ymin;
    x = x*x;
    y = y*y;
    var suma = x + y
    //alert((xmax - xmin) + " ,  " + (ymax - ymin));
    var raiz = Math.sqrt(suma)
    total = total + raiz;
    total = redondear(total,2);
    raiz = redondear(raiz,2);
    if (i == (this.inputPts.length - 1)){
    	var stotal = "Últim tram: "+raiz+" metres. Total: " + total + " metres.";
    	//alert(total + " mts");
    	escriuValorInfo(stotal);
    }
   }
  //14 NOV fin
    imgxs[imgxs.length] = parseInt(tmp[0]);
    imgys[imgys.length] = parseInt(tmp[1]);
    s += this.getSelectionPoint(i,tmp,total);
  }
  if(imgxs.length > 1) {
  	//borra el tramo se elimina un punto
    this.jg.clear();
    //crea la linea
    if (poligono == 1){
    	//alert("poligono");
    	this.jg.fillPolygon(imgxs, imgys);
    }
    if (puntos == 1){
    	//alert("puntos");
    	this.jg.drawPolyline(imgxs, imgys);
    }
    if (linea == 1){
    	//alert("puntos");
    	this.jg.drawPolyline(imgxs, imgys);
    } 
  }
  //dibuja la linea
  this.jg.paint();
  //escribe el punto
  this.selectionDiv.innerHTML = s;
}

function ogcmap_getSelectionPoint(idx,pt,dist) {
	
//  return "<div id=\"" + this.gid + "_selection_" + idx + "\" style=\"padding:1px;cursor:move;border:1px solid black;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 3) + "px;top:" + ((pt[1]) - 3) + "px;\"><img src=\"" + this.baseDir + "point.gif\"></img>" + idx + "</div>";
  //11 NOV
  var sj = "<div id=\"" + this.gid + "_selection_" + idx + "\" style=\"padding:1px;cursor:move;border:0px solid white;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 0) + "px;top:" + ((pt[1]) - 1) + "px;\"><p STYLE=\"color: white\">" + dist + "</p></div>";
  var sj1 = "<div id=\"" + this.gid + "_selection_" + idx + "1\" style=\"padding:1px;cursor:move;border:0px solid white;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 1) + "px;top:" + ((pt[1]) - 0) + "px;\"><p STYLE=\"color: white\">" + dist + "</p></div>";
  var sj2 = "<div id=\"" + this.gid + "_selection_" + idx + "2\" style=\"padding:1px;cursor:move;border:0px solid white;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 0) + "px;top:" + ((pt[1]) + 1) + "px;\"><p STYLE=\"color: white\">" + dist + "</p></div>";
  var sj3 = "<div id=\"" + this.gid + "_selection_" + idx + "3\" style=\"padding:1px;cursor:move;border:0px solid white;position:absolute;width:5px;height:5px;left:" + ((pt[0]) + 1) + "px;top:" + ((pt[1]) - 0) + "px;\"><p STYLE=\"color: white\">" + dist + "</p></div>";
  var sj4 = "<div id=\"" + this.gid + "_selection_" + idx + "4\" style=\"padding:1px;cursor:move;border:0px solid white;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 0) + "px;top:" + ((pt[1]) - 0) + "px;\"><p STYLE=\"color: blue\">" + dist + "</p></div>";
  var sj = sj + sj1 + sj2 + sj3 + sj4;
  return sj;
}

//20Gener
function idec_getSeleccioPunt(idx,pt,dist) {

  var sj="<div  id=\"" + this.gid + "_punt_" + idx + "\" style=\"z-index:1000;padding:1px;cursor:pointer;cursor:hand;border:0px none black;position:absolute;width:5px;height:5px;left:" + ((pt[0]) - 3) + "px;top:" + ((pt[1]) - 3) + "px;\"><img  src=\"images/point.gif\"></img></div>";
   sj += "<div id=\"" + this.gid + "_punt_" + idx + "\"  style=\"background-color: #FFFFE7;z-index:1000;font-family:Verdana,Helvetica,sans-serif;font-size:11px;color:#FF0000;border:2px solid ridge;border-style: outset;border-color:#FFFFE7;filter:alpha(opacity=80);-moz-opacity:0.8;padding-left:2px;padding-right:2px;position:absolute; ;height:5px;left:" + ((pt[0]) + 15) + "px;top:" + ((pt[1]) - 15) + "px;\"><p STYLE=\"color: blue\"><b>" + dist + "</b></p></div>";
  
  return sj;
}
//

function ogcmap_toggleRefresh() {
  this.autoRefresh = !this.autoRefresh;
}

//Gestor capes
function ogcmap_gestorCapes(id) {

  var sURL = "";
  
  for (var i=0; i < this.layers.length; i++) {
 
 if(i==id){
 
    img = ogcmap_findImage(this.prefix+i,document);
    
    sURL = this.layer_url(this.layers[i]);
    //alert("sURL"+i+":"+sURL);
    var img = 0;
    if (document.all) {
      img = document.images[this.prefix+i];
    
    }
    else {
      img = ogcmap_findImage(this.prefix+i,document);
     
    }
    //this.layers[i].loaded = false;
    
    if (this.layers[i].visible == false) {
      img.src = sURL;
      //alert("sURL0"+i+":"+sURL);
    }
    else {
      img.src = this.baseDir + "blank.gif";
    }
 
 
 }
 
  }
  this.container.style.visibility = "hidden";
  //this.showLoading();
  this.drawPts();
  this.writeLabels();
}




function ogcmap_setLoaded(idx) {
//alert(this.loadDiv);
  if(this.loadDiv) {
    this.layers[idx].loaded = true;
    this.testLoaded();
    //ogcmap_hideLoading();
  }
}


function ogcmap_showLoading() {
  this.loadDiv.style.visibility = "visible";
 
 var nom=this.loadDiv.id;
 
  setTimeout('ogcmap_hideLoading()',1500);
  
  
}

function ogcmap_hideLoading() {
	 
  if(this.loadDiv) {
    this.loadDiv.style.visibility = "hidden";
     this.container.style.left = "0px";
  this.container.style.top = "0px";
  }else{
 
 document.getElementById('0_loadDiv').style.visibility = "hidden";
 document.getElementById('0_container').style.left = "0px";
   document.getElementById('0_container').style.top = "0px";
}

 

}


//sets the current map extents to the full extents and redraws the layers
function ogcmap_fullExtent() {
  this.cBounds[0] = this.mapBounds[0];
  this.cBounds[1] = this.mapBounds[1];
  this.cBounds[2] = this.mapBounds[2];
  this.cBounds[3] = this.mapBounds[3];
  this.redraw();
}

//sets the current extent to the previous extent and redraws the layers
function ogcmap_previousExtent() {
  this.cBounds[0] = this.prevBounds[0];
  this.cBounds[1] = this.prevBounds[1];
  this.cBounds[2] = this.prevBounds[2];
  this.cBounds[3] = this.prevBounds[3];
 if ((this.cBounds[0] == 0) && (this.cBounds[1] == 0) && (this.cBounds[2] == 0) && (this.cBounds[3] == 0)){
  	//alert("entra");
  	this.fullExtent();
  }else {
  	this.redraw();
  }
}

function ogcmap_afegirServidor() {

var divServ =document.getElementById('posServer');
var ifrmServ=document.getElementById('ifrServer');


finestra = window.open("obert.jsp?estil=resultats","nouserv","top=50,left=150,width=350,height=360,scrollbars=yes,status=yes"); 
finestra.focus() ;
/*
if(divServ.style.display=='block'){
divServ.style.display='none';
}else{
  divServ.style.display='block';
  
  ifrmServ.src='obert.jsp?estil=resultats';
 }
*/ 
  
}

//zooms in on the specified pixel coordinate
function ogcmap_zoom(xp,yp) {
//alert("zoom");
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];

  var dx = this.cBounds[2] - this.cBounds[0];
  dx = dx / this.zoomFactor;
  var dy = this.cBounds[3] - this.cBounds[1];
  dy = dy / this.zoomFactor;

  var pt = this.pixelToProj(xp,yp);
  this.cBounds[0] = pt[0]-(dx/2.0);
  this.cBounds[2] = pt[0]+(dx/2.0);
  this.cBounds[1] = pt[1]-(dy/2.0);
  this.cBounds[3] = pt[1]+(dy/2.0);

  this.redraw();
}




function ogcmap_zoomToBox() {
//alert("zoomToBox");
  pt1 = new Array();
  pt2 = new Array();
  if(this.pt1[0]<this.pt2[0]){
    pt1[0]=this.pt1[0];
    pt2[0]=this.pt2[0];
  }
  else{
    pt1[0]=this.pt2[0];
    pt2[0]=this.pt1[0];
  }
  if(this.pt1[1]<this.pt2[1]){
    pt1[1]=this.pt1[1];
    pt2[1]=this.pt2[1];
  }
  else{
    pt1[1]=this.pt2[1];
    pt2[1]=this.pt1[1];
  }
  pt1=this.pixelToProj(pt1[0],pt1[1]);
  pt2=this.pixelToProj(pt2[0],pt2[1]);
  bbox = new Array();
  bbox[0]=pt1[0];
  bbox[2]=pt2[0];
  bbox[1]=pt2[1];
  bbox[3]=pt1[1];
  bbox = this.adjustExtent(bbox);
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];
  this.cBounds[0] = bbox[0];
  this.cBounds[2] = bbox[2];
  this.cBounds[1] = bbox[1];
  this.cBounds[3] = bbox[3];
  this.redraw();
}

function ogcmap_zoomFinestra(minX,minY,maxX,maxY){
//alert("zoomFinestra");
bbox = new Array();
  bbox[0]=minX;
  bbox[2]=maxX;
  bbox[1]=minY;
  bbox[3]=maxY;
  bbox = this.adjustExtent(bbox);
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];
  this.cBounds[0] = bbox[0];
  this.cBounds[2] = bbox[2];
  this.cBounds[1] = bbox[1];
  this.cBounds[3] = bbox[3];
  this.redraw()

}


//Does the opposite of zoom()
function ogcmap_zoomOut(xp,yp) {
//alert("zoomOut");
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];

  var dx = this.cBounds[2] - this.cBounds[0];
  dx = dx * this.zoomFactor;
  var dy = this.cBounds[3] - this.cBounds[1];
  dy = dy * this.zoomFactor;

  var pt = this.pixelToProj(xp,yp);

  this.cBounds[0] = pt[0]-(dx/2.0);
  this.cBounds[2] = pt[0]+(dx/2.0);
  this.cBounds[1] = pt[1]-(dy/2.0);
  this.cBounds[3] = pt[1]+(dy/2.0);

  this.redraw();
}

function ogcmap_zoomescala(valor){
//alert(valor);
var L = parseFloat(this.cBounds[0]);
var D = parseFloat(this.cBounds[1]);
var R = parseFloat(this.cBounds[2]);
var T = parseFloat(this.cBounds[3]);
valor=parseFloat(valor);

var ampla=parseFloat(R-L);
var alta=parseFloat(D-T);
var C_X = parseFloat(ampla/2);
var C_Y = parseFloat(alta/2);
var Center_X = parseFloat(L+C_X);
var Center_Y = (T+C_Y);
theValue = (this.mapWidthPX) / (72 * 39.3701) * valor;
this.cBounds[0] = Center_X - (theValue/2);
this.cBounds[2] = Center_X + (theValue/2);

this.cBounds[1] = Center_Y - (theValue/2);

this.cBounds[3] = Center_Y + (theValue/2);

this.redraw();
}

function ogcmap_zoomPt(x,y) {
//alert("zoomPt");
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];

  var dx = this.cBounds[2] - this.cBounds[0];
  dx = dx / this.zoomFactor;
  var dy = this.cBounds[3] - this.cBounds[1];
  dy = dy / this.zoomFactor;

  this.cBounds[0] = x-(dx/2.0);
  this.cBounds[2] = x+(dx/2.0);
  this.cBounds[1] = y-(dy/2.0);
  this.cBounds[3] = y+(dy/2.0);

  this.redraw();
}

function ogcmap_recenter(xp,yp) {
  this.prevBounds[0] = this.cBounds[0];
  this.prevBounds[1] = this.cBounds[1];
  this.prevBounds[2] = this.cBounds[2];
  this.prevBounds[3] = this.cBounds[3];

  var dx = this.cBounds[2] - this.cBounds[0];
  var dy = this.cBounds[3] - this.cBounds[1];
  var pt = this.pixelToProj(xp,yp);

  this.cBounds[0] = pt[0]-(dx/2.0);
  this.cBounds[2] = pt[0]+(dx/2.0);
  this.cBounds[1] = pt[1]-(dy/2.0);
  this.cBounds[3] = pt[1]+(dy/2.0);

  this.redraw();
}

function ogcmap_pan(xp,yp) {

}

function ogcmap_position(e) {
  if(!e)
    e=window.event;
  var mX=null;
  var mY=null;
  var op=navigator.userAgent.toLowerCase().indexOf('opera')!=-1;
  var ie = document.all;
  if (ie || op) {
    mX = e.offsetX;
    mY = e.offsetY;
  }
  else {
    mX = e.layerX;
    mY = e.layerY;
  }
  return new Array(mX,mY);
}

function ogcmap_mouseDown(e) {
	
  position = this.position(e);
  switch(this.opcode) {
    case 0:
      this.pt1 = position;
      this.zoomBox.style.visibility="visible";
      this.zooming = true;
      break;
    case 1:
      this.zoomOut(position[0],position[1]);
      break;
    case 2:
      this.pt1 = position;
      this.panning = true;
      break;
    case 10:
      this.queryUI(position[0],position[1]);
      //this.queryAjax(position[0],position[1]);
      break;
    /*case 6:
      this.pt1 = position;
      xmin=position[0]-7;
      xmax=position[0]+7;
      ymin=position[1]-7;
      ymax=position[1]+7;
      for(i=this.inputPts.length-1;i>-1;i--) {
        pt = this.projToPixel(this.inputPts[i][0],this.inputPts[i][1]);
        if((pt[0]>xmin) && (pt[0]<xmax) && (pt[1]>ymin) && (pt[1]<ymax)) {
          this.selecting=true;
          this.selectionPoint=i;
          break;
        }
      }
      break;
    case 7:
      var pt = this.pixelToProj(position[0],position[1]);
      var str = prompt("Escriure text:","");
      if(str != null) {
        this.addLabel(pt,str);
      }
      break;*/
    //14 feb
    //case 6:
    	//alert("ventana");
    	
    	//break;
    case 7:
    	//alert("cuadro");
    	this.limpiar();
    	this.pcuad = true;
    	this.zoomBox.style.visibility="visible";
    	this.pt1 = position;
    	break;
    case 8:
    	//alert("poligono");
    	//this.limpiar();
    	this.ppoli = true;
    	gatherPoints(e);
    	this.pt1 = position;
    	break;
    case 9:
    	//alert("linea");
    	//this.limpiar();
    	/*if(this.pline){
    		this.pline = false;
    	}else{
    		this.pline = true;
    	}
    	this.pt1 = position;*/
    	this.pline = true;
    	this.pt1 = position;
    	gatherPoints(e);
    	break;
    	case 3:
    	
    	this.limpiar();
    	//this.queryUIdiv(position[0],position[1]);
    	this.queryAjax(position[0],position[1]);
    	break; 
    case 11:
    	//alert("punto");
    	this.limpiar();
    	idec_dibujaPunt(position[0],position[1]);
    	//almacenar_puntos(position);
    	break;
    
    //14 feb fin	 
  }
  return false;
}

function ogcmap_mouseMove(e) {
  position = this.position(e);
  proj = this.pixelToProj(position[0],position[1]);
  window.status = "x: " + Math.round(proj[0]*1000)/1000 + " y: " + Math.round(proj[1]*1000)/1000;
  if(this.zooming) {
    this.pt2 = position;
    this.setZoomBox(this.pt1,this.pt2);
  }
  else if(this.panning) {
    this.pt2 = position;
    this.container.style.left = (this.pt2[0] - this.pt1[0]) + "px";
    this.container.style.top = (this.pt2[1] - this.pt1[1]) + "px";
  }
  else if(this.selecting) {
    this.pt2 = position;
    div = ogcmap_getElt(this.gid + "_selection_" + this.selectionPoint);
    div.style.left = ((position[0]) - 3) + "px";
    div.style.top = ((position[1]) -3) + "px";
  }
  else if(this.pcuad){
  	this.pt2 = position;
  	this.setZoomBox(this.pt1,this.pt2); 
  }
  
  else if(this.pline){
  
  	drawLine(e);
  }
  else if(this.ppoli){
  
  	drawPoligon(e);
  }
  return false;
}

function ogcmap_mouseUp(e) {
  if(this.zooming) {
    this.zooming = false;
    this.zoomBox.style.width="0px";
    this.zoomBox.style.height="0px";
    this.zoomBox.style.visibility="hidden";
    position = this.position(e);
    if((this.pt1[0] == position[0]) && (this.pt1[1] == position[1])) {
      this.zoom(position[0],position[1]);
    }
    else {
      this.zoomToBox();
    }
  }
  else if (this.panning) {
    this.panning = false;
    
    //this.container.style.left = "0px";
    //this.container.style.top = "0px";
    this.prevBounds[0] = this.cBounds[0];
    this.prevBounds[1] = this.cBounds[1];
    this.prevBounds[2] = this.cBounds[2];
    this.prevBounds[3] = this.cBounds[3];
    down = this.pixelToProj(this.pt1[0],this.pt1[1]);
    up = this.pixelToProj(this.pt2[0],this.pt2[1]);
    this.cBounds[0] -= (up[0]-down[0]);
    this.cBounds[2] -= (up[0]-down[0]);
    this.cBounds[1] += (down[1]-up[1]);
    this.cBounds[3] += (down[1]-up[1]);
    this.redraw();
  }
  else if(this.selecting) {
    this.selecting = false;
    if((this.pt1[0] == this.position(e)[0]) && (this.pt1[1] == this.position(e)[1])) {
      if(confirm("Delete this point?")) {
        this.inputPts.splice(i,1);
        this.drawPts();
      }
      else {
        if(confirm("Clone (duplicate) this point?")) {
          this.inputPts.splice(((i) + 1),0,this.inputPts[i]);
          this.drawPts();
        }
      }
    }
    else {
      this.inputPts[this.selectionPoint] = this.pixelToProj(this.pt2[0],this.pt2[1]);
      this.drawPts();
      this.selectionPoint = null;
    }
  }
  /*else if(this.opcode == 6) {
    var pt = this.pixelToProj(position[0],position[1]);
    this.inputPts[this.inputPts.length] = pt;
    this.drawPts();
  }*/
  //14 feb
  else if (this.pcuad){
  	this.pcuad = false;
  	this.zoomBox.style.width="0px";
    this.zoomBox.style.height="0px";
    this.zoomBox.style.visibility="hidden";
  	position = this.position(e);
    if((this.pt1[0] == position[0]) && (this.pt1[1] == position[1])) {
      
    }else{
    	if (this.pt1[0]>this.pt2[0]){
    		w = this.pt1[0] - this.pt2[0];
    		x = this.pt2[0];
    	}else{
    		w = this.pt2[0] - this.pt1[0];
    		x = this.pt1[0];
    	}
    	if (this.pt1[1]>this.pt2[1]){
    		h = this.pt1[1] - this.pt2[1];
    		y = this.pt2[1];
    	}else{
    		h = this.pt2[1] - this.pt1[1];
    		y = this.pt1[1];
    	}
    	//Coloco los puntos del cuadrado en el arreglo de puntos
    	var pt = this.pixelToProj(x,y);
    	this.PtsPoli[this.PtsPoli.length] = pt;
    	pt = this.pixelToProj(x+w,y);
    	this.PtsPoli[this.PtsPoli.length] = pt;
    	pt = this.pixelToProj(x+w,y+h);
    	this.PtsPoli[this.PtsPoli.length] = pt;
    	pt = this.pixelToProj(x,y+h);
    	this.PtsPoli[this.PtsPoli.length] = pt;
    	this.drawPts();
    	//this.dibCuadro(x,y,w,h);
    	this.actualizaCoord();
    }
  }
  else if (this.opcode == 8){
  	var pt = this.pixelToProj(position[0],position[1]);
    this.PtsPoli[this.PtsPoli.length] = pt;
    this.drawPts();
    if (this.PtsPoli.length > 2){
    	//escribeMultCoord(this.PtsPoli);
    }
  }
  else if (this.opcode == 9){
  	var pt = this.pixelToProj(position[0],position[1]);
  	this.PtsLine[this.PtsLine.length] = pt;
  	this.drawPts();
  	//escribeMultCoord(this.PtsLine); 
  }
  else if (this.opcode == 11){
  	var s = "";
  	latlon = new Array(2);
  	var pt = this.pixelToProj(position[0],position[1]);
  	UTMXYToLatLon (pt[0], pt[1], 31, false, latlon);
	xmin = RadToDeg (latlon[1]);
	ymin = RadToDeg (latlon[0]);
	xmin = redondear(xmin,5);
	ymin = redondear(ymin,5);
	s = xmin + "," + ymin;
	document.getElementById('boxSpatial').value = s;
  }
  //14 feb fin
  return false;
}

function ogcmap_mouseOver(e) {

}

function ogcmap_mouseOut(e) {
  window.status = "";
}

function ogcmap_escriuCapa(){

	var sdiv = "<div style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;\">";
	var swh = "width=\"" + this.mapWidthPX + "px\" height=\"" +this.mapHeightPX + "px\"";
	
	var contenedor = "mapa";
	var gid=0;
	var nlayers = this.layers.length;
	var nou = "";
	var MapActu=document.getElementById(contenedor).innerHTML;
	for (var i=0; i < nlayers; i++) {
		nou = "<img style=\"filter:alpha(opacity=100);-moz-opacity:1;\" id=\"" + this.prefix+i+ "\" name=\"" + this.prefix+i+ "\" onload=\"g_ogcMaps["+gid+"].setLoaded(" + i + ")\" src=\"" + this.baseDir + "blank.gif\" " + swh + "></img>\n";
	}
	MapActu=nou + MapActu 
	
	document.getElementById(contenedor).innerHTML=MapActu;
	
}
function ogcmap_imprimir(){

window.open("/ideLocal/visual/imprimir.htm", "Imprimir", 'width=650,height=600,left=150,top=150,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes');
}
  // 
  // Resize a spatial extent to have the same aspect ratio
  // as an image size.
  //
  //
function ogcmap_adjustExtent(ext) {
  ext[0] = parseFloat(ext[0]);
  ext[1] = parseFloat(ext[1]);
  ext[2] = parseFloat(ext[2]);
  ext[3] = parseFloat(ext[3]);
  var dx = ext[2] - ext[0];
  var dy = ext[3] - ext[1];
  if(dx/this.mapWidthPX > dy/this.mapHeightPX){
    ext[1]=ext[1]-(((dx/this.mapWidthPX*this.mapHeightPX)-dy)/2);
    ext[3]=ext[3]+(((dx/this.mapWidthPX*this.mapHeightPX)-dy)/2);
  }
  else{
    ext[0]=ext[0]-(((dy/this.mapHeightPX*this.mapWidthPX)-dx)/2);
    ext[2]=ext[2]+(((dy/this.mapHeightPX*this.mapWidthPX)-dx)/2);
  }
  return ext;
}

function ogcmap_testLoaded() {
this.container.style.visibility = "hidden";
  for(i=0;i<this.layers.length;i++) {
    if(this.layers[i].loaded == false) {
      return;
    }
  }
  //this.hideLoading();
  this.container.style.visibility = "visible";
}

function ogcmap_postWrite() {
  this.setDefault("tool");
  this.setDefault("queryLayer");
  if(editEnabled) {
    this.jg = new jsGraphics(this.gid + "mapCanvas");
    this.jg.setStroke(2);
    this.jg.setColor("yellow");
    //this.jg1 = new jsGraphics(this.gid + "mapCanvas1");
    //this.jg1.setStroke(3);
    //this.jg1.setColor("cyan");
  }
  //14 feb
  this.dibujo = ogcmap_getElt(this.gid + "mapCanvas");
  // this.dibujo1 = ogcmap_getElt(this.gid + "mapCanvas1");
  //14 feb fin
  
  
  this.labelsDiv = ogcmap_getElt(this.gid + "_labelsDiv");
  this.selectionDiv = ogcmap_getElt(this.gid + "_selectionDiv");
  
  //20Gener
   this.selectionDiv1 = ogcmap_getElt(this.gid + "_selectionDiv1");
   //
   
  this.zoomBox = ogcmap_getElt(this.gid+"_zoomBox");
  this.container = ogcmap_getElt(this.gid + "_container");

  this.loadDiv = ogcmap_getElt(this.gid + "_loadDiv");
  this.glassPane = ogcmap_getElt(this.gid + "_glassPane");
  this.redraw();
}

function ogcmap_calculaEscala(){

var escala2;
   escalaN=(this.cBounds[2]-this.cBounds[0])/2;
 
   
   	escalaN=escalaN/2
   	//escalaN=Math.round(escalaN*10)/10;
   	
   	
   	return escalaN;
  
   }

function ogcmap_init() {
  this.mapBounds = this.adjustExtent(this.mapBounds);
  this.cBounds[0] = this.mapBounds[0];
  this.cBounds[1] = this.mapBounds[1];
  this.cBounds[2] = this.mapBounds[2];
  this.cBounds[3] = this.mapBounds[3];
  if((this.editType == "none") || (this.editType == "undefined")) {
    editEnabled = false;
  }
  else {
    editEnabled = true;
  }
  this.addTool(0,"zoom","zoom in","Marcar i ampliar una zona rectangular del mapa","setTool(0)",true);
  this.addTool(1,"zoomout","zoom out","Reduir i centrar el mapa on es faci clic","setTool(1)",true);
  this.addTool(2,"centrar","recenter map","Moure el mapa arrastrant el ratolí","setTool(2)",true);
  //this.addTool(3,"identificar","add point","Obtenir informació capes","setTool(3)",this.query);
 this.addTool(3,"punto","punto","Seleccionar Objecte","setTool(3)",true);
  this.addTool(4,"inici","home","Mapa inicial","fullExtent()",true);
  
  //14 feb
  this.addTool(5,"esborrar","borrar","Esborrar gràfics","limpiar()",true);
  this.addTool(6,"ventana","ventana","Seleccionar finestra","selecVentana()",true);
  this.addTool(7,"cuadro","cuadro","Dibuixar rectangle","dibujaCuadro()",true);
  this.addTool(8,"poligono","poligono","Dibuixar polígon","dibujaPoligono()",true);
  this.addTool(9,"linea","linea","Dibuixar línia","dibujaLinea()",true);
  //this.addTool(10,"punto","punto","Dibuixar punto","setTool(10)",true);
  //this.addTool(10,"punto","punto","Seleccionar Objecte","setTool(10)",true);
  //this.addTool(12,"stop","stop","Fin edicion","finEdicion()",true);
  //14 feb fin
}

function ogcMap(gid,prefix,width,height,srs,xmin,ymin,xmax,ymax,baseDir,skin,toolbar,editType,query,leyenda) {
//properties
  this.gid = gid;
  this.prefix = prefix;
  this.mapWidthPX = width;
  this.mapHeightPX = height;
  this.srs = srs;
  this.mapBounds = new Array(xmin,ymin,xmax,ymax);
  this.baseDir = baseDir;
  this.skin = skin;
  this.toolbar = toolbar;
  this.editType = editType;
  this.query = query;
  this.layers = new Array();
  this.tools = new Array();
  this.labels = new Array();
  this.bgColor = "0xFFFFFF";
  this.cBounds = new Array(0,0,0,0);
  this.prevBounds = new Array(0,0,0,0);
  this.zoomFactor = 2;
  this.autoRefresh = false;
  this.queryLayer = 0;
  this.opcode = -1;
  this.inputPts = new Array();
  this.zooming = false;
  this.panning = false;
  this.selecting = false;
  this.selectionPoint = null;
  this.pt1 = new Array();
  this.pt2 = new Array();
  this.zoomBox = null;
  this.container = null;
  this.loadDiv = null;
  this.labelsDiv = null;
  this.selectionDiv = null;
  this.glassPane = null;
  //nuevo
  this.servidores = new Array();
  this.leyenda = leyenda;
  //14 feb
  this.pcuad = false;
  this.ppoli = false;
  this.pline = false;
  this.ppoint = false;
  this.dibujo = null;
  //this.dibujo1 = null;
  this.PtsPoli = new Array();
  this.PtsLine = new Array();
  //14 feb fin
    
//methods
//14 feb
this.selecVentana = ogcmap_selecVentana;
this.actualizaCoord = ogcmap_actualizaCoord;
this.dibujaCuadro = ogcmap_dibujaCuadro;
this.dibujaPoligono = ogcmap_dibujaPoligono;
this.dibujaLinea = ogcmap_dibujaLinea;
//this.queryUIdiv = ogcmap_queryUIdiv;
//14 feb fin
this.imprimir=ogcmap_imprimir;
this.limpiar=ogcmap_limpiar;
this.zoomescala=ogcmap_zoomescala;
this.zoomFinestra=ogcmap_zoomFinestra;
this.calculaEscala=ogcmap_calculaEscala;
this.rebre=ogcmap_rebre;
this.moureSlide=ogcmap_moureSlide;
  this.layer_url = ogcmap_layer_url;
  this.pixelToProj = ogcmap_pixelToProj;
  this.projToPixel = ogcmap_projToPixel;
  this.writeInline = ogcmap_writeInline;
  this.escriuCapa =ogcmap_escriuCapa;
  this.addLayer = ogcmap_addLayer;
  this.addTool = ogcmap_addTool;
  this.addLabel = ogcmap_addLabel;
  this.redraw = ogcmap_redraw;
  this.gestorCapes =ogcmap_gestorCapes;
  this.fullExtent = ogcmap_fullExtent;
  this.previousExtent = ogcmap_previousExtent;
  this.afegirServidor=ogcmap_afegirServidor;
  this.zoom = ogcmap_zoom;
  this.zoomToBox = ogcmap_zoomToBox;
  this.zoomOut = ogcmap_zoomOut;
  this.setZoomBox = ogcmap_setZoomBox;
  this.recenter = ogcmap_recenter;
  this.pan = ogcmap_pan;
  this.mouseDown = ogcmap_mouseDown;
  this.mouseMove = ogcmap_mouseMove;
  this.mouseUp = ogcmap_mouseUp;
  this.mouseOver = ogcmap_mouseOver;
  this.mouseOut = ogcmap_mouseOut;
  this.position = ogcmap_position;
  this.zoomPt = ogcmap_zoomPt;
  this.layerUI = ogcmap_layerUI;
  this.toggleLayer = ogcmap_toggleLayer;
  this.setLoaded = ogcmap_setLoaded;
  this.toggleRefresh = ogcmap_toggleRefresh;
  this.setTool = ogcmap_setTool;
  this.setDefault = ogcmap_setDefault;
  this.setQueryLayer = ogcmap_setQueryLayer;
  this.queryLayerURL = ogcmap_queryLayerURL;
  this.queryLayerURLAjax = ogcmap_queryLayerURLAjax;
  this.queryUI = ogcmap_queryUI;
  this.queryAjax=ogcmap_queryAjax;
  this.showLoading = ogcmap_showLoading;
  this.hideLoading = ogcmap_hideLoading;
  this.testLoaded = ogcmap_testLoaded;
  this.drawPts = ogcmap_drawPts;
  this.getSelectionPoint = ogcmap_getSelectionPoint;
  this.transferPoints = ogcmap_transferPoints;
  this.adjustExtent = ogcmap_adjustExtent;
  this.postWrite = ogcmap_postWrite;
  this.writeLabels = ogcmap_writeLabels;
  this.capabilitiesURL = ogcmap_capabilities_url;
  this.init = ogcmap_init;
//10 NOV
  this.serVisible = ogcmap_serVisible;
//3 abr
  this.onDblClick = ogcmap_onDblClick;
  //this.finEdicion = ogcmap_finEdicion;
// initialization
  this.init();
}

//creates a new ogcmap, inserts it into the global map array, and returns the map object created
function addOGCMap(prefix,width,height,srs,xmin,ymin,xmax,ymax,baseDir,skin,toolbar,editType,query,leyenda) {
  var n = g_ogcMaps.length;
  prefix = prefix + "_g"+n+"_";
  var map = new ogcMap(n,prefix,width,height,srs,xmin,ymin,xmax,ymax,baseDir,skin,toolbar,editType,query,leyenda);
  g_ogcMaps[n] = map;
  return map;
}


function idec_escriuMapa(x0,y0,x1,y1){

var caixa=new Array();
caixa[0]=x0;
caixa[1]=y0;
caixa[2]=x1;
caixa[3]=y1;

caixa=map.adjustExtent(caixa);

coordInici[0]=caixa[0];
coordInici[1]=caixa[1];
coordInici[2]=caixa[2];
coordInici[3]=caixa[3];

var caixaBB=caixa[0]+","+caixa[1]+","+caixa[2]+","+caixa[3];
//var consultaWMS="http://sima.gencat.net/servlet/com.esri.wms.Esrimap?REQUEST=GetMap&VERSION=1.1.0&servicename=sima&SRS=EPSG:23031&Service=WMS&BBOX="+caixaBB+"&WIDTH=150&HEIGHT=150&LAYERS=Base%20territorial%20general,Municipis,Cartografia%201:250.000,Cartografia%201:50.000,Cobertes%20del%20sol%201993&STYLES=&FORMAT=png&EXCEPTION=INIMAGE";

var consultaWMS="http://shagrat.icc.es/lizardtech/iserv/ows?REQUEST=GetMap&VERSION=1.1.1&SRS=EPSG:23031&Service=WMS&BBOX="+caixaBB+"&WIDTH=150&HEIGHT=150&LAYERS=sat250m,orto25m&STYLES=&FORMAT=JPEG&";

//var consultaWMS="http://galileo.icc.es/wms/servlet/c_bt5m_v_r?REQUEST=GetMap&VERSION=1.1.1&SRS=EPSG:23031&Service=WMS&BBOX="+caixaBB+"&WIDTH=150&HEIGHT=150&LAYERS=BT5M_POB_Illa_urbana&STYLES=&FORMAT=image/png&";


//var consultaWMS=document.getElementById('map_g0_0').src;

//consultaWMS=consultaWMS.replace("WIDTH=500&HEIGHT=500","WIDTH=150&HEIGHT=150");
var a="<img onclick=\"idec_centarZoom(event)\" style=\"cursor:pointer;cursor:hand;\" src=\""+consultaWMS+ "\" ><div id=\"mapRef\"  style=\"z-index:20;background-image: url(images/creu.gif);position:absolute;top:70px;left:70px;overflow:hidden;width:10px;height:10px;border:1px none;border-color:#FF0000;\"></div>" ;

document.getElementById('mapaSituacio').innerHTML=a;

//return a;
}


function idec_escriuCerques(tipus,posLeft){

/*
a ="<table><tr><td>";
a +='<select class="comboLoca" id="Escull" name="Escull" >';
a +='<option value="Municipis">Municipis</option><option value="Comarques">Comarques</option></select>';
a +="</td><td>";
a +="<input type=\"text\"  class=\"comboLoca\" name=\"txtDades\" id=\"txtDades\" onkeyDown=\"capturaTecla(event);\"  >";
a +="</td></tr></table>";
*/

a='<table width="100%" border="0" cellspacing="0" cellpadding="0" >';
a +='<tr><td class=\"menu\" colspan="2">Cercar adre&ccedil;a</td>'; 
a +=' <td colspan="2" height="7">'; 
a +='<div align="left">';
a +='</div>';
 a +='</td><tr> ';
  
 if((codiMun.length < 3)&&(tipusAplicacio=="Carrerer")){
 a +='</tr><td> ';
a +='<select class="text" style="width:150px" onchange="codiMun=this.value" >';
//a +='<option selected value="'+comarca[0][0]+'">Municipis</option>';
codiMun=comarca[0][0];
for(i=0;i < comarca.length;i++){
a +='<option  value="'+comarca[i][0]+'">'+comarca[i][1]+'</option>';
}

a +='</select>';
 a +='</td><tr> ';
}
 
 
a +='<td class="text" >Tipus:';
a +='<br>'; 
a +='<select class="text" id="tipusCarrer" name="tipusCarrer">';
a +='<option value="C">Altres...</option>';
          a +='<option value="Avinguda">Avinguda</option>';
          a +='<option value="Carrer" selected>Carrer</option>';
          a +='<option value="Camí">Camí</option>';
          //a +='<option value="Carretera">Carretera</option>';
          a +='<option value="Parc">Parc</option>';
          a +='<option value="Passeig">Passeig</option>';
          a +='<option value="Plaça">Plaça</option>';
          a +='<option value="Passatge">Passatge</option>';
          a +='<option value="Rambla">Rambla</option>';
          a +='<option value="Ronda">Ronda</option>';
          a +='<option value="Travessera">Travessera</option>';
          //a +='<option value="Urbanització">Urbanització</option>';
          a +='<option value="Via">Via</option>';
          a +='<option value="Vial">Vial</option>';
        a +='</select>';
      a +='</td></tr><tr>'; 
      a +='<td class="text">Carrer:';
      a +='<br>'; 
        a +='<input class="text" id="nomCarrer" size="20" onkeyDown="idec_capturaTecla(event);" name="nomCarrer">';
      a +='</td></tr><tr>'; 
      a +='<td class="text" >N&uacute;mero:';
      a +='<br>'; 
        a +='<input class="text" id="numCarrer" size="5" onkeyDown="idec_capturaTecla(event);" name="numCarrer">';
      //a +='</td> ';
      //a +='<td> ';
        //a +='<div align="right">'; 
         a +='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input class="botoMarcGroc" onMouseOver="this.className = \'botoGroc\'" onClick="idec_cercaCarrer()" onMouseOut="this.className = \'botoMarcGroc\'" type="button" value="Cercar" name="cerca">';
        //a +='</div>';
      
a +="</td></tr></table>";


return a;
      
}

//Funcions de cerques

function capturaTecla(e) {

      //if (browser.isNS7){}else{  
        
       if(document.all){
            tecla=event.keyCode;
            //alert("keycode");
        }else{
        //alert("which");
            tecla=e.which; 
        }
        
     if(tecla==13){
      while (tecla==13){
          cercarDades();
          break;}
           
        }
        
    }
    
    function idec_capturaTecla(e) {

      //if (browser.isNS7){}else{  
        
       if(document.all){
            tecla=event.keyCode;
            //alert("keycode");
        }else{
        //alert("which");
            tecla=e.which; 
        }
        
     if(tecla==13){
      while (tecla==13){
         idec_cercaCarrer();
          break;}
           
        }
        
    }  
      
    
function canviValor(valor){

  valor=valor.toUpperCase();
  
 accent=new Array('À','È','É','Ì','Í','Ò','Ó','Ù','Ú');
 
 noaccent=new Array('A','E','E','I','I','O','O','U','U');


 for(i=0;i<accent.length;i++){
 
 if (valor.indexOf(0,accent[i])){

 valor=valor.replace(accent[i],noaccent[i]);
 }}
 return valor;
 
} 
   
//prova ajax
function makeObject(){
	var naveg; 
	var browser = navigator.appName; 
	if(browser == "Microsoft Internet Explorer"){
		naveg = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		naveg = new XMLHttpRequest();	
	}
	return naveg;
}

var xmlDoc = makeObject();

function ajax(sURL){
	//alert(sURL);
	//document.write(sURL);
	xmlDoc.open('GET', sURL,true);
	xmlDoc.setRequestHeader("Content-Type", "text/html"); 
	xmlDoc.onreadystatechange = parseInfo; 
	xmlDoc.send('');
}

function parseInfo(){

	document.getElementById('posFitxes').innerHTML="";
	tipus="estacions";
	if(xmlDoc.readyState == 1){escriuValorInfo('CERCANT...');}
	if(xmlDoc.readyState == 4){ 
		escriuValorInfo('');
		if(xmlDoc.status == 200){
			//alert(xmlDoc.responseText);
			document.getElementById('posFitxes').style.visibility='visible';
			document.getElementById('posFitxes').innerHTML=xmlDoc.responseText;
		}
	}
	//escriuValorInfo('')
}   


var xmlDoc2 = makeObject();

function idec_ajax2(sURL){
	xmlDoc2.open('GET', sURL,true);
	xmlDoc2.setRequestHeader("Content-Type", "text/html"); 
	xmlDoc2.onreadystatechange = parseInfo2; 
	xmlDoc2.send('');
}

function parseInfo2(){
	document.getElementById('posFitxes2').innerHTML="";
	if(xmlDoc2.readyState == 1){}
	if(xmlDoc2.readyState == 4){ 
		if(xmlDoc2.status == 200){
			//alert(xmlDoc.responseText);
			//document.getElementById('posFitxes').style.visibility='visible';
			document.getElementById('posFitxes2').innerHTML=xmlDoc2.responseText;
		}
	}
}   

function getFeatureAjax(sURL){
	//alert("getFeatureAjax    " + sURL);
	xmlDoc.open('GET','infoAjax1.jsp?'+sURL,true);
	
	//xmlDoc.open('GET','cercaAjax.jsp?'+sURL,true);
	xmlDoc.setRequestHeader("Content-Type", "text/html");
	//14 fe
	//xmlDoc.onreadystatechange = parseInfoAjax;  
	xmlDoc.onreadystatechange = parseInfoAjax3; 
	//14 feb fin
	xmlDoc.send('');
}

function parseInfoAjax(){
	//alert("parseInfoAjax");
	//document.getElementById('posFitxes').innerHTML="";
	tipus="estacions";
	if(xmlDoc.readyState == 1){escriuValorInfo('Cercant1...');}
	if(xmlDoc.readyState == 4){ 
		if(xmlDoc.status == 200){
			escriuValorInfo(xmlDoc.responseText);
		}
	}
}   


var idObjecte="";
var capaEqui="";
var capaM="capa";
var capaC="capaC";
var tipusAmbit="CODMUN"; 


 
function cercarDades(){
idObjecte="";
var tipu=document.getElementById('Escull').value;
var topotext1=document.getElementById('txtDades').value;
var topotext=canviValor(topotext1);
ajax("cercaAjax.jsp?capa="+tipu+"&valor="+topotext+"&cerca=0");
}

function escriuValorInfo(valor){
var capaEscriu=document.getElementById('posInfo');

capaEscriu.visibility='visible';
capaEscriu.innerHTML=valor;


}

function capturaID(id,valor){

 if (idObjecte ==""){
 idObjecte=id;
 }else{
 
 document.getElementById(idObjecte).className='normal';
 idObjecte=id;
 }
 
 escriuValorInfo(valor);
}
 
function capturaIDEqui(id,equipament){
 
 
 if (idObjecte ==""){
 idObjecte=id;
 capaEqui=equipament;
 }else{
 
 document.getElementById(idObjecte).className='normal';
 idObjecte=id;
   capaEqui=equipament;
 }
 }
 
 
 
 function tancaFR(){
 
document.getElementById('posFitxes').style.visibility='hidden'; 	

 }

function resultats(estat,capaAct){
	var cercaT="";
	if (capaAct=="Municipis"){cercaT="1"}
	if (capaAct=="Toponims"){cercaT="2"}
	if (capaAct=="Comarques"){cercaT="3"}
	if (capaAct=="localrettext"){cercaT="4"}
	if (capaAct=="industria"){cercaT="5"}
	if(idObjecte==""){alert("Has de seleccionar un resultat")}
	else{
		if (estat=='no'){
			document.getElementById('posFitxes').style.visibility='hidden'; 	
		}else{
			ajax("cercaAjax.jsp?cerca="+cercaT+"&capa="+capaAct+"&valor="+idObjecte);
		}
	}
}
//////nuevos

//activa las capas de por el menu de propiedades
function activaCapes(id, nom){

var lstCheckBoxes;
var checks;
//alert(id);
//alert(nom);

  //var str = "\"document.lyrLeyenda." + id + "\"";
  //alert(str);
  lstCheckBoxes = eval("document.lyrLeyenda." + id);
  //lstCheckBoxes = eval(str);
  
   checks = lstCheckBoxes.length;
   if (checks == null){
   		lstCheckBoxes.checked=true;
   		for (var i=0; i<map.servidores.length; i++) {
	  		if (map.servidores[i][4] == id) {
	  			if (map.servidores[i][2] == nom){
	  				map.servidores[i][3] = true;
	  			}	
	  		}
		}
   		map.redraw(1);
   }

   for (l=0; l<checks; l++) {
   	if (lstCheckBoxes[l].value == nom){
   		lstCheckBoxes[l].checked=true;
   		for (var i=0; i<map.servidores.length; i++) {
	  		if (map.servidores[i][4] == id) {
	  			if (map.servidores[i][2] == nom){
	  				map.servidores[i][3] = true;
	  			}	
	  		}
		}
   		map.redraw(1);
   	}	
   }
}

//cambia la imagen de las carpetas del arbol de la leyenda
function cambiar(item) {
//if(item==1){topo2=document.getElementById('2');topo3=document.getElementById('3');}
   obj=document.getElementById(item);
   visible=(obj.style.display!="none")
   key=document.getElementById("x" + item);
   if (visible) {
     obj.style.display="none";
     //if(item==1){topo2.style.display="none";topo3.style.display="none";}
     
     key.innerHTML="<img src='" + map.baseDir + "skin/" + map.skin + "/images/folder.gif' width='16' height='16' hspace='0' vspace='0' border='0'>";
   } else {
      obj.style.display="block";
        //if(item==1){topo2.style.display="block";topo3.style.display="block";}
      key.innerHTML="<img src='" + map.baseDir + "skin/" + map.skin + "/images/textfolder.gif' width='16' height='16' hspace='0' vspace='0' border='0'>";
      //alert(key.innerHTML);
   }
}

//desactiva la capa por medio del menu de propiedades
function desactivaCapa(id, nom){

var lstCheckBoxes;
var checks;

  lstCheckBoxes = eval("document.lyrLeyenda." + id );
   //alert(lstCheckBoxes);
  checks = lstCheckBoxes.length;
   if (checks == null){
   		lstCheckBoxes.checked=false;
   		for (var i=0; i<map.servidores.length; i++) {
	  		if (map.servidores[i][4] == id) {
	  			if (map.servidores[i][2] == nom){
	  				map.servidores[i][3] = false;
	  			}	
	  		}
		}
   		map.redraw(1);
   }
   for (l=0; l<checks; l++) {
   //alert(lstCheckBoxes[l]);
   	if (lstCheckBoxes[l].value == nom){
   		lstCheckBoxes[l].checked=false;
   		for (var i=0; i<map.servidores.length; i++) {
	  		if (map.servidores[i][4] == id) {
	  			if (map.servidores[i][2] == nom){
	  				map.servidores[i][3] = false;
	  			}	
	  		}
		}
   		map.redraw(1);
   	}	
   }
}

var capetrans = "";

function idec_retoca(id){
	
	var rut=document.getElementById(id).src;
	
	
document.getElementById(id).src="images/blank.gif";
//alert(document.getElementById(id).src);
}

function menuPropietats(capes,nom,titulo,organ,e){

	var texte= ""
	var pro=document.getElementById('propietats');
	var trt=nom.length;
	var tr1=nom.indexOf('>');
	capes.replace(' ','&nbsp;');
	
	if(nom.indexOf('>')!=-1){
	
	nom=nom.substring(parseInt(tr1+1),trt);
	}
	
	capetrans = capes;
		
	pro.style.visibility='visible';
	
	if (document.all){
		x = e.clientX - 10;
		y = e.clientY - 10;
	}else{
		x = e.pageX - 10;
		y = e.pageY - 10;
		
		
		
	}
	
	
	pro.style.left=x+"px";
	pro.style.top=y+"px";
			
	texte+='<table class="text" cellpadding="1" cellspacing="1" border="0" width="90" >';
	texte+='<tr><td class="normal1" style="font-size:9px;" onclick="activaCapes(\'' + capes + '\',\'' + nom + '\');" onmouseover="if (this.className==\'normal1\'){this.className=\'sobre1\'}" onmouseout="if (this.className==\'sobre1\'){this.className=\'normal1\'}">Activar capa</td></tr>';
	texte+='<tr><td class="normal1" style="font-size:9px;" onclick="desactivaCapa(\''+ capes + '\',\'' + nom + '\');" onmouseover="if (this.className==\'normal1\'){this.className=\'sobre1\'}" onmouseout="if (this.className==\'sobre1\'){this.className=\'normal1\'}">Desactivar capa</td></tr>';
	texte+='<tr><td class="normal1" style="font-size:9px;" onclick="transparencia(\''+ capes + '\',event);" onmouseover="if (this.className==\'normal1\'){this.className=\'sobre1\'}" onmouseout="if (this.className==\'sobre1\'){this.className=\'normal1\'}">Transparencia</td></tr>';
	
	
	if(titulo.indexOf('undefined')==0 ||titulo==""){
	
	}else{
	
	texte+='<tr><td class="normal1" style="font-size:9px;"  onclick="idec_metadades(\'' + titulo + '\',\'' + organ + '\');" onmouseover="if (this.className==\'normal1\'){this.className=\'sobre1\'}" onmouseout="if (this.className==\'sobre1\'){this.className=\'normal1\'}"> Metadades </td></tr>';
	}
	
	texte+='</table>';

//document.write(texte);
	pro.innerHTML=texte;
}

//adds a layer to the map
//in: url = base url of layer
//    name = ogc wms name of the layer
//    transparent = boolean indicating if the layer should provide a transparent background
//    visible = boolean indicating if the layer is to be retrieved and drawn
//out: no return value

function idec_metadades(capes,nom){
//alert(capes);
//alert(nom);
var id = "cercaRapida=*"+capes+"*,*"+capes+"*&org="+nom;
             latlon = new Array(2);
        var x, y, zone, southhemi;
              xmin =map.cBounds[0];
              ymin =map.cBounds[1];
              xmax =map.cBounds[2];
              ymax =map.cBounds[3];
        x = parseFloat (xmin);
        y = parseFloat (ymin);
        zone = parseFloat (31);
        
        southhemi = false;

        UTMXYToLatLon (x, y, zone, southhemi, latlon);
        
        xmin = RadToDeg (latlon[1]);
        ymin = RadToDeg (latlon[0]);

		var xn=xmin;
		var yn=ymin;

        x = parseFloat (xmax);
        y = parseFloat (ymax);
        zone = parseFloat (31);
        
        southhemi = false;

        UTMXYToLatLon (x, y, zone, southhemi, latlon);
        
        xmax = RadToDeg (latlon[1]);
        ymax = RadToDeg (latlon[0]);

var xx=xmax;
var yx=ymax;
var addNSb=0;
var nomIdiomaCurt="CA";



dataWindow=open('frameset.html','cd','menubar=no,status=no,toolbar=no,width=550,scrollbars=yes,top=100, left=100,resizable=yes,height=300');
dataWindow.document.open();
dataWindow.document.writeln("<HTML><HEAD><TITLE>ICC</TITLE>"); 
dataWindow.document.writeln("<SCRIPT LANGUAGE='JAVASCRIPT' TYPE='TEXT/JAVASCRIPT'>;function initialFunc(){ var _d='<div id=\"dd\" style=\"position:absolute;top:120px;left:185px\" ><table border=\"1\"><tr><td valign=middle align=center bordercolor=#E8E8FF bgcolor=#FFFFFF><i><font size=6 color=#0000FF><img border=0 src=\"images/carregant_01.gif\"></font></i></td></tr></table></div>';document.write(_d);}</SCRIPT>");
dataWindow.document.write("</HEAD><body bgcolor='#F2F2F2' >");
dataWindow.document.write('<script>initialFunc();document.location.href="http://delta.icc.es/wefex/client?idioma='+nomIdiomaCurt+'&do=cercaDatasetsClient&'+id+'&bbox='+(xn)+','+(yn)+','+(xx)+','+(yx)+'&";</script></body></HTML>');

dataWindow.document.write('</body></HTML>');

}

//14 NOv
function ogcmap_addLayer(url,srvname,name,title,transparent,visible,format,queryable,version,epsg,mdtitle,organismo) {
  
  
  var fmt = format;
  var nombres = new Array();
  var capas = new Array();
  var visibles = new Array();
  var mdtitulo = new Array();
  var num;
  var srvnombre = "";


	var out = "", flag = 0;
	for (k = 0; k < srvname.length; k++) {
	if ((srvname.charAt(k) != " ") && (srvname.charAt(k) != "(") && (srvname.charAt(k) != ")")) {
	srvnombre += srvname.charAt(k);
	flag = 0;
	}
	else {
	if(flag == 0) {
	srvnombre += "";
	flag = 1;
	      }
	   }
	}
	//alert(srvnombre);
	
  if ((!fmt) || (fmt == "undefined"))
    fmt = "image/png";   
  // se divide el arreglo de las capas por comas
  if (title.indexOf(';') != -1) {
  	nombres = title.split(";");
  	capas = name.split(";");
  	visibles = visible.split(";");
  	mdtitulo = mdtitle.split(";");
  	num = nombres.length;
  	for (var i=0; i<num; i++) {
  		if (visibles[i] == "true") {
  			visibles[i] = true;
  		} 
  		else { 
  			visibles[i] = false;
  		}
  	}
  	//se crea el arreglo con las capas de los distintos servidores
  	for (var i=0; i<num; i++) {
  		//alert(mdtitulo[i]);
  		this.servidores[this.servidores.length] = new Array(this.layers.length,capas[i],nombres[i],visibles[i],srvnombre,mdtitulo[i],organismo);
  	}
  	visible = true;
  	this.layers[this.layers.length] = new ogcmap_Layer(url,srvname,capas,nombres,transparent,visible,fmt,queryable,version,epsg); 
  }
  else {
  	//alert("visible" + visible);	
  	this.servidores[this.servidores.length] = new Array(this.layers.length,name,title,visible,srvnombre,mdtitle,organismo);
  	visible = true;
  	this.layers[this.layers.length] = new ogcmap_Layer(url,srvname,name,title,transparent,visible,fmt,queryable,version,epsg); 	
  }
}

function ogcmap_Layer(url,srvname,name,title,transparent,visible,format,queryable,version,epsg) {
  
  
  this.url = url;
  this.srvname = srvname;
  this.name = name;
  this.title = title;
  this.transparent = transparent;
  this.visible = visible;
  this.format = format;
  this.queryable = queryable;
  //alert(srvname+";"+queryable);
  if(this.version != null) {
    this.version = version;
  }
  else {
    this.version = "1.1.0";
  }
  //14 Nov
 
  if(epsg != null) {
 
    this.epsg = epsg;
  }
  else {
    this.epsg = "EPSG:23031";
  }
 
  this.loaded = false;
}

//============= ogcMap object ==============
//internal method to generate the url for the layer
//in: index of the layer
//out: string, url of image
function ogcmap_layer_url(aLayer,k) {
  var sURL = aLayer.url;
  var llarg=sURL.length;
  var ultim=sURL.substring(llarg-1,llarg);
 
  
  if(ultim != "?"){
  if(ultim != "&"){
  
  
  sURL=sURL+"&";
  
  }
  }
 
 
  var nom = "";    

	for (var i=0; i<this.servidores.length; i++) {
	  		if (this.servidores[i][0] == k) {
	  			if (this.servidores[i][3] == true){
	  				if (nom == "")
		  				nom = this.servidores[i][1];
		  			else
		  				nom = nom + "," + this.servidores[i][1];
	  			}	
	  		}
	}
	    
  	if (nom != "") {	
	  	sURL += "REQUEST=GetMap"; 
	  	
		sURL += "&SRS=" + aLayer.epsg;
		sURL += "&VERSION=" + aLayer.version;
		sURL += "&WIDTH=" + this.mapWidthPX;
		sURL += "&HEIGHT=" + this.mapHeightPX;
		//if(sURL.indexOf('icc_talls_v_r')!=-1){
		//sURL += "&STYLES=TALL5,TALL5A";
		//}else{
		sURL += "&STYLES=";
		//}
		
		
		if (aLayer.transparent == true)
		    sURL += "&TRANSPARENT=true";
		else
		  sURL += "&TRANSPARENT=false";
		  sURL += "&LAYERS=" + nom;
		  //14 Nov
		  
		  if((aLayer.epsg.indexOf('4326')!=-1)||(aLayer.epsg.indexOf('4230')!=-1)){
  latlon = new Array(2);
  latlonMax= new Array(2);
  UTMXYToLatLon (this.cBounds[0], this.cBounds[1], 31, false, latlon);
        xmin = RadToDeg (latlon[1]);
        ymin = RadToDeg (latlon[0]);
  UTMXYToLatLon (this.cBounds[2], this.cBounds[3], 31, false, latlonMax);    
         xmax = RadToDeg (latlonMax[1]);
        ymax = RadToDeg (latlonMax[0]);
 
   sURL += "&BBOX=" + xmin + "," + ymin + "," + xmax + "," + ymax;
   
		  }else{
		  sURL += "&BBOX=" + this.cBounds[0] + "," + this.cBounds[1] + "," + this.cBounds[2] + "," + this.cBounds[3];
		  }//14 nov estaba comentado pero no se ve el del ING
		  if (!aLayer.transparent){
		    sURL += "&BGCOLOR=" + this.bgColor;
		  }  
		  sURL += "&FORMAT=" + aLayer.format;
		
		  return sURL;
		  
	}
	else { 
		sURL = this.baseDir + "blanco.gif";
		
		return sURL;
	}
}

//generates a user interface for turning on/off layers
function ogcmap_layerUI() {
  var i = 0;
  var s = "<form name='lyrLeyenda'>\n";
  var a="";
  var servidor = "";
  
  if(this.leyenda){
  	var ley=""
  	ley = "visible";
  }
  else {
  	var ley = "hidden"
  }
  document.getElementById('leyendadiv').style.visibility = ley;
  z=0;
  if(tipusAplicacio=="Carrerer"){
  
  a += "<table width='100%' class='text' border='0' cellpadding='1' cellspacing='1'>";
   a += "<tr><td class=\"menu\" >Visualització</td></tr>";
  a += "<tr><td width='14'><input type='radio' name='car' id='car'  onclick=\"idec_gestioCar(this.value);\" value='ortofoto'  CHECKED>Ortofoto</td></tr>";
  a += "<tr><td width='14'><input type='radio' name='car' id='car'  onclick=\"idec_gestioCar(this.value)\"  value='topografic'>Topogràfic</td></tr>";

   // 14 Nov
//a += "<tr><td valign='middle' width='100%'><input type='checkbox' name='carrer' id='carrrer' name='carrrer'  onclick=\"idec_estatCarrrer(this.checked)\"  value='carrer' checked><input type='text' id='txtcarrers' class='text'readOnly='true' style='border-style: none; '  value='Desactivar carrerer'></td></tr>";
   a += "<tr><td width='100%'><input type='checkbox' name='carrer' id='carrrer' name='carrrer'  onclick=\"idec_estatCarrrer(this.checked)\"  value='carrer' checked><input type='text' id='txtcarrers' class='text'readOnly='true' style='border-style: none; '  value='Desactivar carrerer'></td></tr>";
   a += "<tr><td class=\"menu\" >Servidors</td></tr>";
  a += "</table>";
  document.getElementById('vcp').innerHTML = a;
  z=4;
  }else{
  s+= "<table width='100%' class='text' border='0' cellpadding='1' cellspacing='1'>";
  s += "<tr><td class=\"menu\" >Servidors</td></tr>";
  s += "</table>";
  }
  
  for (i=z; i < this.layers.length; i++) {
  //14 Nov
  if(this.layers[i].srvname !=""){
  s += "<table class='text' border=0 cellpadding='2' cellspacing=1><tr>";
  s += "<td width='16'><a id='x" + i + "' href='javascript:cambiar(\"" + i + "\");'>";
  s += "<img src='" + this.baseDir + "skin/" + this.skin + "/images/folder.gif' width='16' height='16' hspace='0' vspace='0' border='0'></a></td>";
  s += "<td>" + this.layers[i].srvname + " </table>";
  }
  
  //s += "<div id='" + i + "' style='display: block; margin-left: 1em;'>";
  s += "<div id='" + i + "' style='display: none; margin-left: 1em;'>";
     
  for (k=0; k< this.servidores.length; k++) {
  		if (this.servidores[k][0] == i) {
   			
   			s += "<table class='text' border=0 cellpadding='1' cellspacing=1><tr>";
   			
   			if(tipusAplicacio !="Carrerer"){
   			s += "<td width='12'><img style='cursor:pointer;cursor:hand' onclick='menuPropietats(\"" + this.servidores[k][4] + "\", \"" + this.servidores[k][2] + "\", \"" + this.servidores[k][5] + "\", \"" + this.servidores[k][6] + "\", event)' src='" + this.baseDir + "skin/" + this.skin + "/images/text.gif' width='12' height='12' hspace='0' vspace='0' border='0'></td>";
      		
      		}
      		s += "<td> <input type='checkbox' name='" + this.servidores[k][4] + "'";
      		s += " value='" + this.servidores[k][2] + "'";0
      		//10 NOV agregue el == true al if
      		//alert(this.servidores[k][3]);
      		if (this.servidores[k][3] == true){
      			//alert(this.servidores[k][1] + "  " + this.servidores[k][3]);
  				s += " checked='1'";
  			}
  			s += " onclick='map.toggleLayer(" + k + ");map.redraw(1);'>";
  			s +="<i>"+ this.servidores[k][2]+"</i>"; 
  			s += "</table>";
  		}
  	}
  	
  s += "</div>";
  
  }
  s += "</form>";
  
  //4 Novembre
  
  document.getElementById('leyendadiv').innerHTML = s;	
}

//14 Nov

function idec_estatCarrrer(valor){
if(valor){
document.getElementById('fooWS').style.display='block';
document.getElementById('txtcarrers').value='Desactivar carrerer';
}else{
document.getElementById('fooWS').style.display='none';
document.getElementById('txtcarrers').value='Activar carrerer';
}

}

function idec_gestioCar(capa){
var ap=map.cBounds[2]-map.cBounds[0];

document.getElementById('visual').value=capa;

if(capa=="ortofoto"){

map.servidores[0][3]=true;
map.layers[0].visible=true;
map.servidores[1][3]=false;
map.layers[1].visible=false;
map.servidores[2][3]=false;
map.layers[2].visible=false;

//map.toggleLayer("0");
//map.toggleLayer("1");
//map.toggleLayer("2");

}

if(capa=="topografic"){
//map.toggleLayer("0");
//map.toggleLayer("1");
	
	map.servidores[1][3]=true;
	map.layers[1].visible=true;
	map.servidores[0][3]=false;
	map.layers[0].visible=false;
	map.servidores[2][3]=false;
	map.layers[2].visible=false;
	
	if((ap < 2000)&&(carto5=="SI")){

	map.servidores[1][3]=false;
	map.layers[1].visible=false;
	map.servidores[2][3]=true;
	map.layers[2].visible=true;
	}

}
map.redraw();
}

function idec_gestioCar2(capa){
var ap=map.cBounds[2]-map.cBounds[0];

if(capa=="topografic"){

	map.servidores[1][3]=true;
	map.layers[1].visible=true;
	map.servidores[0][3]=false;
	map.layers[0].visible=false;
	map.servidores[2][3]=false;
	map.layers[2].visible=false;
	
	if((ap < 2000)&&(carto5=="SI")){

	map.servidores[1][3]=false;
	map.layers[1].visible=false;
	map.servidores[2][3]=true;
	map.layers[2].visible=true;
	}

}

}

//redraws all the map layers
function ogcmap_redraw(activa) {
  var sURL = "";
//alert("redraw");
var ap=(this.cBounds[2]-this.cBounds[0]);


if(tipusAplicacio=="Carrerer"){idec_gestioCar2(document.getElementById('visual').value)}

  for (var i=0; i < this.layers.length; i++) {
    img = ogcmap_findImage(this.prefix+i,document);
    //alert(img);
    sURL = this.layer_url(this.layers[i],i);
    var img = 0;
    if (document.all) {
      img = document.images[this.prefix+i];
    
    }
    else {
      img = ogcmap_findImage(this.prefix+i,document);
     
    }
    this.layers[i].loaded = false;
    //alert(this.layers[i].visible);
    
    
   // idec_gestioCar();
    
    
    if (this.layers[i].visible == true) {
    	//alert(sURL);
         img.src = sURL;
    }
    else {
        img.src = this.baseDir + "blank.gif";
    }
    this.setLoaded(i)
  }
  if (activa != 1){
	this.showLoading();
  }
  this.drawPts();
  this.writeLabels();
  //alert(this.calculaEscala());
  idec_connexioWS("getMapaWMS")
  window.status="ideLocal";
  //13Octubre
  if(asdf==1){this.moureSlide();}
}

//refresca el mapa cuando de activa o se desactiva una capa
function ogcmap_toggleLayer(idx) {
  if (idx < 0)
    return;
  if (idx >= this.servidores.length)
    return;
    //alert(this.servidores[idx][3]);
  this.servidores[idx][3] = ! this.servidores[idx][3];
  //Capa 5000
   if((tipusAplicacio!="Carrerer")&&(idx==3)){
   if(this.servidores[idx][3]){document.getElementById('fooWS').style.visibility='visible';
   }else{document.getElementById('fooWS').style.visibility='hidden';}
   }
   
   
  if (this.autoRefresh){
    this.redraw(1);
  }
}

//crea la barra con los botones
function ogcmap_writeInline(topM,leftM,topT,leftT,nEines,posBarra,posZoom) {
 
 
 var ht=new Array();
 
  //declaracion de variables
  var gid = this.gid;
  var s="";
  var sdiv = "<div style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;\">";
  var swh = "width=\"" + this.mapWidthPX + "px\" height=\"" +this.mapHeightPX + "px\"";
  
  //contenedor del mapa
  ht.push("<div class=\"mapa\" style=\"top:"+topM+";left:"+leftM+";position:absolute;width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; \" name=\"" + this.prefix + "\" id=\"" + this.prefix + "\">");	
  	ht.push( "<div id=\"posFitxes\" style=\"background-color: #FFFFFF;position:absolute;border-color: #FFFFFF #333333 #333333;border-style: solid; border-top-width: 10px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px;visibility:hidden;width:250; height:250;overflow:hidden; z-index:140; left: 40px; top:40px\">"); 
  	ht.push("</div>");
  	ht.push( "<div id=\"posServer\" style=\"display:none;background-color: #FFFFFF;position:absolute;border-color: #FFFFFF #333333 #333333;border-style: solid; border-top-width: 10px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px;width:350; height:350;overflow:hidden; z-index:140; left: 40px; top:40px\">"); 
  		ht.push('<iframe id="ifrServer" name="ifrServer" FRAMEBORDER="0"  width="350px" height="350px" src="" ></iframe>');
  	ht.push("</div>");
  	ht.push( "<div id=\"posFitxes2\" style=\"background-color: #FFFFFF;position:absolute;border-color: #FFFFFF #333333 #333333;border-style: solid; border-top-width: 10px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px;visibility:hidden;width:250; height:250;overflow:hidden; z-index:140; left: 40px; top:40px\">"); 
  	ht.push("</div>");
  	ht.push( "<div style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;clip:rect(0," + this.mapWidthPX + "px," + this.mapHeightPX + "px,0);overflow:hidden;\">\n");
  		ht.push( "<div id=\""+gid+"_loadDiv\" style=\"background-color: #FFFFFF;z-index:500;visibility:hidden;width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;\"><img style=\"left:" + (this.mapWidthPX/2 - 35) + "px;top:" + this.mapHeightPX/2 + "px;position:absolute;\" src=\"" + this.baseDir + "skin/" + this.skin + "/images/loading.gif\"></img>\n");
  		ht.push("</div>");
  		//DIV CONTAINER
  		ht.push( "<div id=\"" + gid + "_container\" style=\"z-index:25;width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;\">");
  			var nlayers = this.layers.length;
  			for (var i=0; i < nlayers; i++) {
  				ht.push( sdiv + "<img style=\"filter:alpha(opacity=100);-moz-opacity:1;\" id=\"" + this.prefix+i+ "\"  name=\"" + this.prefix+i+ "\" onload=\"g_ogcMaps["+gid+"].setLoaded(" + i + ")\" OnError=\"idec_retoca(this.id)\" src=\"" + this.baseDir + "blank.gif\" " + swh + "></img>\n");
  				ht.push("</div>");
  			}
  			ht.push( sdiv + "<img style=\"visibility:hidden;filter:alpha(opacity=100);-moz-opacity:1;\" id=\"fooWS\"  name=\"fooWS\" OnError=\"idec_retoca(this.id)\" src=\"" + this.baseDir + "blank.gif\" " + swh + "></img>\n");
  			ht.push("</div>");
  			ht.push( sdiv + "<img style=\"visibility:hidden;filter:alpha(opacity=100);-moz-opacity:1;\" id=\"fooWSXY\"  name=\"fooWSXY\" OnError=\"idec_retoca(this.id)\"  src=\"" + this.baseDir + "blank.gif\" " + swh + "></img>\n");
  			ht.push("</div>");
  			//14 feb agregue el left y el top.
 			ht.push("<div id =\"mapa\" style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px; margin:0; padding:0; position:absolute;\">");
 			ht.push("</div>");
  			ht.push( sdiv + "<div id=\""+gid+"mapCanvas\" style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px;overflow:hidden;clip:rect(0," + this.mapWidthPX + "px," + this.mapHeightPX + "px,0); \">\n");
  				ht.push("</div>");
  			ht.push("</div>");
  			//ht.push( sdiv + "<div id=\""+gid+"mapCanvas1\" style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px;overflow:hidden;clip:rect(0," + this.mapWidthPX + "px," + this.mapHeightPX + "px,0); \">\n";
  			//	ht.push("</div>";
  			//ht.push("</div>";
  			ht.push( sdiv + "<div id=\""+gid+"_labelsDiv\" style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px;overflow:hidden;clip:rect(0," + this.mapWidthPX + "px," + this.mapHeightPX + "px,0); \">\n");
  				ht.push("</div>");
  			ht.push("</div>");
  			ht.push( sdiv + "<div id=\""+gid+"_selectionDiv\" style=\"width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px;overflow:hidden;clip:rect(0," + this.mapWidthPX + "px," + this.mapHeightPX + "px,0); \">\n");
  				ht.push("</div>");
  			ht.push("</div>");
  			
  		//Zoom BOX
  			ht.push( "<div id=\""+gid+"_zoomBox\" style=\"position:absolute;visibility:hidden;zIndex:100;border:1px solid red;width:0px;height:0px;\">");
  			ht.push("</div>");
  			ht.push( "<div id=\"efecte\" style=\"position:absolute;visibility:hidden;zIndex:100;border:2px solid red;width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px\">");
  			ht.push("</div>");
  			
  			//23 feb
			ht.push( "<div id=\"puntInci\" style=\"z-index:1000;padding:1px;border:0px none black;position:absolute;top:0px;left:0px;width:5px;height:5px;visibility:hidden;\"><img  src=\"images/pointx.gif\"></img></div>");
			//23 feb
  			
  			
  			
  		ht.push("</div>\n");
  		//FIN DIV CONTAINER
  	ht.push("</div>\n");	
    ht.push( "<div id=\""+gid+"_glassPane\" ondblclick=\"g_ogcMaps["+gid+"].onDblClick(event);\" onmousedown=\"g_ogcMaps["+gid+"].mouseDown(event);\" onmousemove=\"g_ogcMaps["+gid+"].mouseMove(event);\" onmouseup=\"g_ogcMaps["+gid+"].mouseUp(event);\" onmouseover=\"g_ogcMaps["+gid+"].mouseOver(event);\" onmouseout=\"g_ogcMaps["+gid+"].mouseOut(event);\" style=\"cursor:crosshair;border:1px black solid;background-image: url(" + this.baseDir + "blank.gif);position:absolute;width:" + this.mapWidthPX + "px; height:" + this.mapHeightPX + "px;z-index:400 \">");
    ht.push("</div>\n");
       
  ht.push("</div>\n");
 
    
  ht.push( "<input type=\"hidden\" name=\"cX\" id=\"cX\" value=0><input type=\"hidden\" name=\"cY\" id=\"cY\" value=0><input type=\"hidden\" name=\"adreca\" id=\"adreca\" value=0>");
  ht.push( "<input type=\"hidden\" name=\"inciX\" id=\"inciX\" value=0><input type=\"hidden\" name=\"inciY\" id=\"inciY\" value=0>");
  
  //crea la barra de botones
  ht.push("<div id=\"bBotondiv\" class=\"barrabotones\" style=\"top:"+topT+";left:"+leftT+";z-index:0;position:absolute;\">");
  	ht.push( "<table width=\"20px\" border=\"0\">\n");
  		ht.push( "<tr>\n");
  		if(this.toolbar) {
  			var tagPos=""
  			if(posBarra=="V"){tagPos="</tr><tr>";}else{tagPos="";}
      		var ntools = nEines;
    		for (var i=0; i < ntools; i++) {
      			if(this.tools[i].enabled == true) {
      				ht.push( tagPos +"<td class=\"normal\" id=\""+ this.gid + "_toolcell_" + this.tools[i].opcode + "\"><a href=\"javascript:g_ogcMaps["+gid+"]." + this.tools[i].targetFunction + "\"><img title=\"" + this.tools[i].description  + "\" onmouseover=\"window.status='" + this.tools[i].description + "';\" onmouseout=\"window.status=''\" border=\"0\" name=\"" + this.tools[i].name + "\" src=\"" + this.baseDir + "skin/" + this.skin + "/images/" + this.tools[i].name + ".gif\"></img></a></td>\n");
      			}
    		}
  		}
  		ht.push( "</tr>");
  	ht.push( "</table>\n");
  ht.push("</div>\n");	
  var wMenu=180;
  var tf=0;
  if(tipusAplicacio=="Carrerer"){
	  if(codiMun.length < 3){tf=20;}
	  topCerca=parseInt(topM+230+tf);
	  factor=0;
	  ampla=115;
	  topCerca1=parseInt(topM+130+tf);
	  mS=120;
	  ht.push("<div class=\"einesCerca\" id=\"EinesCerca\" style=\"position:absolute;z-index:0;width:"+wMenu+"px; border: 1px none #0000FF\">");
	  	ht.push(idec_escriuCerques(tipusAplicacio,leftM));
	  ht.push("</div>");
	 
	  ht.push( "<div class=\"vcp\" id='vcp' style='border: 1px none #0000FF;position:absolute;width:"+wMenu+"px;height:95px;' onmouseover=\"document.getElementById('propietats').style.visibility='hidden';setTimeout('tancaDivL()',2000);\"></div>");
	
  }else{
  	topCerca=parseInt(topM);
   	factor=135;
   	ampla=330;
   	mS=215
  }
  if(tipusAplicacio=="Carrerer"){
  	ht.push( "<div id=\"leyendadiv\" class=\"Cleyenda\" style='display:none;border: 1px none #0000FF;position:absolute;width:"+wMenu+"px;height:"+parseInt(ampla-tf)+"px;overflow:auto;' onmouseover=\"document.getElementById('propietats').style.visibility='hidden';setTimeout('tancaDivL()',2000);\">");
  }else{
  	ht.push( "<div id=\"leyendadiv\" class=\"leyenda\" style='display:none;border: 1px none #0000FF;position:absolute;width:"+wMenu+"px;height:"+parseInt(ampla-tf)+"px;overflow:auto;' onmouseover=\"document.getElementById('propietats').style.visibility='hidden';setTimeout('tancaDivL()',2000);\">");
  }
  ht.push("</div>\n");
  ht.push( "<div id=\"propietats\" style='position:absolute; visibility:hidden; top:0px; left: 0px' onmouseover=\"document.getElementById('divTra').style.visibility='hidden';\">");
  ht.push("</div>\n");
  ht.push( "<div id=\"divTra\" style='position:absolute; display:none; top:0px; left:0px;width:110'>");
  	ht.push( "<IMG alt=\"\" src=\"" + this.baseDir + "skin/" + this.skin + "/images/handle.gif\" width=\"10\" height=\"25\" id=\"trahand\" name=\"trahand\">");
 	ht.push( "<IMG alt=\"\" src=\"" + this.baseDir + "skin/" + this.skin + "/images/gifhorizontal.gif\" width=\"105\" height=\"15\" aling='left' id=\"lineatra\" name=\"lineatra\">");
  ht.push( "</div>");
  ht.push( "<div id=\"posInfo\" class=\"info\"  style=\"display:none;width:400px;left:"+parseInt(leftM)+"px;top:"+parseInt(topM + this.mapHeightPX)+";position:absolute \">");
  	//ht.push( "<table border='0'><tr><td><div  ></div></td></tr></table>";
  ht.push("</div>\n");
  ht.push("<div id=\"mapaSituacio\" class=\"minimapa\" style=\"display:none;position:absolute;z-index:0;width:150px;height:150px;overflow:hidden;border: 1px outset #0000FF\">");
  	ht.push("<div id=\"mapRef\" style=\"z-index:20;overflow:hidden;background-image: url(images/creu.gif);display:none;position:absolute;top:70px;left:70px;width:10px;height:10px;border:2px none;border-color:#FF0000;background-color: #FFFFFF; layer-background-color: #FFFFFF\">");
  	ht.push("</div>\n");
  ht.push("</div>");
  document.write(ht.join(' '));
  this.postWrite();
}


//muestra la barra para seleccionar la transparencia
function transparencia (capa,e){

	var pro=document.getElementById('divTra');
	pro.above;
	
	for (var i=0; i<map.layers.length; i++){
		var str = map.layers[i].srvname;
		
		var out = "", flag = 0;
		for (k = 0; k < str.length; k++) {
		if ((str.charAt(k) != " ") && (str.charAt(k) != "(") && (str.charAt(k) != ")")) {
		out += str.charAt(k);
		flag = 0;
		}
		else {
		if(flag == 0) {
		out += "";
		flag = 1;
		      }
		   }
		}
		
		if (capa == out){
			//alert("entra");
			capa = map.prefix + i;
		}
	}
		
	pro.style.visibility='visible';
	
	if (document.all){
		x = e.clientX - 40;
		y = e.clientY - 10;
		//alert(capa);
		transpa = document.getElementById(capa).filters.alpha.opacity;
		transpa = 100 - transpa;
	}else{
	
		x = e.pageX - 40;
		y = e.pageY;
		transpa = document.getElementById(capa).style.MozOpacity;
		transpa = 100 * transpa;
		transpa = 100 - transpa;
	}
	//var bro=document.getElementById('lineatra');
	dd.elements.lineatra.moveTo(x,y);
	dd.elements.lineatra.show();
	dd.elements.trahand.moveTo((x + transpa),(y-5));
	 
}

//asigna un valor de transparencia dado a una capa dada
function transpaDIV(valorDIV,capaTR){
//alert(capaTR);
	if (valorDIV > 100){
		valorDIV=100;
	}

	transp = valorDIV;
	for (var i=0; i<map.layers.length; i++){
	
		var str = map.layers[i].srvname;
		
		var out = "", flag = 0;
		for (k = 0; k < str.length; k++) {
		if ((str.charAt(k) != " ") && (str.charAt(k) != "(") && (str.charAt(k) != ")")) {
		out += str.charAt(k);
		flag = 0;
		}
		else {
		if(flag == 0) {
		out += "";
		flag = 1;
		      }
		   }
		}
		
		if (capaTR == out){
			capaTR = map.prefix + i;
		}
	}

	if (document.all){
		valorT=eval(valorDIV);
		document.getElementById(capaTR).filters.alpha.opacity=valorT;
		}else{
		valorT=eval(valorDIV/100);
		document.getElementById(capaTR).style.MozOpacity=valorT;
		}
}

//llama a transpaDiv desde extra.js para manejar la transparencia.
function haceTransp(x) {
	transpaDIV(x,capetrans);
}

function ogcmap_moureSlide(){
	var amplaIni=(coordInici[2] - coordInici[0]);
	var ampla=(this.cBounds[2]-this.cBounds[0]);
	var mouY;
	//alert("AMPLA " + ampla);
	var rango = amplaIni / 10;
	//alert (rango);
	//alert("2: " + this.cBounds[2] + " ,0: " + this.cBounds[0]);
	if (ampla < 1){ampla=2;}
	if((ampla >= 1)&&(ampla < rango)){mouY=(100) }
	if((ampla >= rango)&&(ampla < (rango*2))){mouY=(90)}
	if((ampla >= (rango*2))&&(ampla < (rango*3))){mouY=(80)}
	if((ampla >= (rango*3))&&(ampla < (rango*4))){mouY=(70)}
	if((ampla >= (rango*4))&&(ampla < (rango*5))){mouY=(60) }
	if((ampla >= (rango*5))&&(ampla < (rango*6))){mouY=(50)}
	if((ampla >= (rango*6))&&(ampla < (rango*7))){mouY=(40)}
	if((ampla >= (rango*7))&&(ampla < (rango*8))){mouY=(30)}
	if((ampla >= (rango*8))&&(ampla < (rango*9))){mouY=(20)}
	if((ampla >= (rango*9))&&(ampla < (rango*10))){mouY=(10)}
	if(ampla >= (rango*10)){mouY=(0) }
	
	//alert("ampla:"+ampla);
	//alert(mouY);
	moureBarra(mouY);

}
//27 Octubre
function idec_activaGetMapaPunt(cX,cY,adreca){
document.getElementById('posFitxes').style.visibility='hidden';
document.getElementById('fooWSXY').style.visibility='visible';
document.getElementById('cX').value=cX;
document.getElementById('cY').value=cY;
document.getElementById('adreca').value=adreca;

cX=parseFloat(cX);
cY=parseFloat(cY);
x1=eval(cX-200);
y1=eval(cY-200);

x2=eval(cX + 200);
y2=eval(cY + 200);

ogcmap_rebre(x1,y1,x2,y2,adreca)
}

function idec_canviaImatge(url,nom){

//alert(nom);
//alert(url);

document.getElementById('posFitxes').style.visibility='hidden';
document.getElementById(nom).src=url;
//alert(document.images[nom].src);

}
function idec_vgeo2MouseX(w,cx){

	return Math.round(w * (cx - coordInici[0] )/ (coordInici[2]- coordInici[0]  ) );
	}
	
	
function idec_vgeo2MouseY(h,cY){
	return Math.round( h * (coordInici[3]-cY ) / ( coordInici[3] - coordInici[1]));
	 }

function idec_mouse2GeoX(w,mX){
return coordInici[0] + mX * (coordInici[2] - coordInici[0])/w;}

function idec_mouse2GeoY(h,mY){
return coordInici[3] - mY * (coordInici[3] - coordInici[1])/ h;}	 
	 
	 
function idec_connexioWS(metode){

var capaCarrer=document.getElementById('fooWS');
xmin = map.cBounds[0];
ymin = map.cBounds[1];
xmax = map.cBounds[2];
ymax = map.cBounds[3];
mapaW=map.mapWidthPX;
mapaH=map.mapHeightPX;
var ampli=xmax - xmin;

var centreX=(xmax + xmin)/2;
var centreY=(ymax + ymin)/2;

var mapRef_left=idec_vgeo2MouseX(150,centreX);
var mapRef_top=idec_vgeo2MouseY(150,centreY);


document.getElementById('mapRef').style.top=(mapRef_top-5)+'px';
document.getElementById('mapRef').style.left=(mapRef_left-5)+'px';


mapRef_left="";
mapRef_top="";


srs="23031";
capes="CARRERS";
if(tipusAplicacio=="Carrerer"){capaCarrer.style.visibility="visible";}
//20Gener
/*
if(document.getElementById('fooWSXY').style.visibility=="visible"){

	var cX=document.getElementById('cX').value;
	var cY=document.getElementById('cY').value;
	var adreca=document.getElementById('adreca').value;

	//if((cX > xmin)&&(cX < xmax)){ 
	idec_ajax2("getGeoWS.jsp?peticio=getMapaPuntXY&xmin="+xmin+"&ymin="+ymin+"&xmax="+xmax+"&ymax="+ymax+"&width="+mapaW+"&height="+mapaH+"&cx="+cX+"&cy="+cY+"&adreca="+adreca+"&");
	
	//}else{document.getElementById('fooWSXY').style.visibility="hidden";}

	} */
//
 
if(metode=="getMapaWMS"){
if ((ampli < 1500)&&(capaCarrer.style.visibility=="visible")){

	//document.getElementById('fooWS').style.visibility="visible";
	ajax("getGeoWS.jsp?peticio=getMapaWMS&xmin="+xmin+"&ymin="+ymin+"&xmax="+xmax+"&ymax="+ymax+"&width="+mapaW+"&height="+mapaH+"&srs="+srs+"&capes="+capes+"&");
	
	}else{capaCarrer.style.visibility='hidden';}
}

document.getElementById('posFitxes').style.visibility='hidden';



}
function idec_cercaCarrer(){

	var tipusCarrer=document.getElementById('tipusCarrer').value;
	var nomCarrer=document.getElementById('nomCarrer').value;
	var numCarrer=document.getElementById('numCarrer').value;
ajax("getGeoWS.jsp?peticio=getAdrecaUTM&tipusCarrer="+tipusCarrer+"&nomCarrer="+nomCarrer+"&numCarrer="+numCarrer+"&codiMun="+codiMun+"&");

}

//14 Octubre
function ogcmap_rebre(minX,minY,maxX,maxY,valor){
/*
if(valor=="inici"){
map.zoomFinestra(minX,minY,maxX,maxY);
coordInici[0]=minX;
coordInici[1]=minY;
coordInici[2]=maxX;
coordInici[3]=maxY;
idec_escriuMapa(minX,minY,maxX,maxY);

	map.mapBounds[0]=minX;
	map.mapBounds[1]=minY;
	map.mapBounds[2]=maxX;
	map.mapBounds[3]=maxY;

}else{
*/
document.getElementById('posFitxes').style.visibility='hidden';
map.zoomFinestra(minX,minY,maxX,maxY);
escriuValorInfo(valor);
//}

// 3 NOVIEMBRE
	map.moureSlide();
}
//Funcions iniciatiques


function idec_iniciMapa(codi){
init_ajax("infoCoord.jsp?valor="+codi+"&");
}

var iniciMap = makeObject();
var tt=1;
function init_ajax(sURL){

iniciMap.open('GET', sURL,true);
iniciMap.setRequestHeader("Content-Type", "text/html"); 
iniciMap.onreadystatechange = parseInfoInit; 
iniciMap.send('');
}

function parseInfoInit(){

if(iniciMap.readyState == 1){}
if(iniciMap.readyState == 4){ 

		if(iniciMap.status == 200){
		
	if(tt==1){
	document.getElementById('initMap').innerHTML=iniciMap.responseText;
	
	tt=2;
	}else{
document.getElementById('initMap').innerHTML="";
	}
}
}
}   

function idec_centarZoom(e){
var op=navigator.userAgent.toLowerCase().indexOf('opera')!=-1;
  var ie = document.all;
  if (ie || op) {
    mX = e.clientX;
    mY = e.clientY;
  }
  else {
    mX = e.pageX;
    mY = e.pageY;
  }
  
 var leftRR;
 var topRR;
 var matriucapes=document.getElementById('mapaSituacio');
 
 if(document.all){
topRR=matriucapes.currentStyle.top;
leftRR=matriucapes.currentStyle.left;

}else{
topDN=window.getComputedStyle(matriucapes, "");
topRR=topDN.getPropertyValue("top");
leftDN=window.getComputedStyle(matriucapes, "");
leftRR=topDN.getPropertyValue("left");
}
  
 mX=(mX - parseInt(leftRR));
 mY=(mY - parseInt(topRR));
  
  mX1=(parseInt(map.mapWidthPX)*parseInt(mX))/150;
  mY1=(parseInt(map.mapHeightPX)*parseInt(mY))/150;
  
  //var dx = coordInici[2] - coordInici[0];
  //var dy = coordInici[3] - coordInici[1];

  var dx = map.cBounds[2] - map.cBounds[0];
  var dy = map.cBounds[3] - map.cBounds[1];
  var x0 = idec_mouse2GeoX(parseInt(map.mapWidthPX),mX1);
	var y0=idec_mouse2GeoY(parseInt(map.mapHeightPX),mY1);
  minX = x0-(dx/2.0);
  maxX = x0+(dx/2.0);
 minY = y0-(dy/2.0);
  maxY = y0+(dy/2.0);
  
  map.zoomFinestra(minX,minY,maxX,maxY);

}

function idec_llegenda(w,h,ll,text){

if(ll==1){ll='cobertes.gif';text='Cobertes_del_sòl_1993'}
if(ll==2){ll='cultius.gif';text='Cultius_i_aprofitaments_1977_1979'}
	
	w=window.open("", "Llegenda", 'scrollbars,width='+w+',height='+h+',left=150,top=150');
	w.document.write("<html><title>Llegenda</title><table border=0><tr><td  align=center><b>"+text+"</b></td></tr><tr>"+
	"<td align=center><img border=0 src=visual/images/llegenda/"+ll+"></td></tr></table></html>");
	w.document.close();	
}

//14 feb
function ogcmap_dibujaCuadro(){
	this.limpiar();
	this.setTool(7);
}

function ogcmap_dibujaPoligono(){
	this.limpiar();
	this.setTool(8);
	geometria=2;
}

function ogcmap_dibujaLinea(){
	this.limpiar();
	this.setTool(9);
	geometria=1;
	//idec_dibujaLinea();
}


function ogcmap_selecVentana(){
	//alert("ventana");
	var xmin = map.cBounds[0];
	var ymin = map.cBounds[1];
	var xmax = map.cBounds[2];
	var ymax = map.cBounds[3];
	this.limpiar();
	//crear el cuadro para dibujar
	var pt = [xmin,ymax];
    this.PtsPoli[this.PtsPoli.length] = pt;
    var pt = [xmax,ymax];
    this.PtsPoli[this.PtsPoli.length] = pt;
    var pt = [xmax,ymin];
    this.PtsPoli[this.PtsPoli.length] = pt;
    var pt = [xmin,ymin];
    this.PtsPoli[this.PtsPoli.length] = pt;
    this.drawPts();
	//alert("UTM XMIN: " + xmin + " YMIN: " + ymin + " XMAX: " + xmax + " YMAX: " + ymax);
	latlon = new Array(2);
  	latlonMax= new Array(2);
  	UTMXYToLatLon (this.cBounds[0], this.cBounds[1], 31, false, latlon);
        xmin = RadToDeg (latlon[1]);
        ymin = RadToDeg (latlon[0]);
  	UTMXYToLatLon (this.cBounds[2], this.cBounds[3], 31, false, latlonMax);    
        xmax = RadToDeg (latlonMax[1]);
        ymax = RadToDeg (latlonMax[0]);
    escribeCoord(ymax,ymin,xmax,xmin);
    //alert("LATLON XMIN: " + xmin + " YMIN: " + ymin + " XMAX: " + xmax + " YMAX: " + ymax);
}

function ogcmap_actualizaCoord(){
  //alert("actualizacoord");	
  pt1 = new Array();
  pt2 = new Array();
  if(this.pt1[0]<this.pt2[0]){
    pt1[0]=this.pt1[0];
    pt2[0]=this.pt2[0];
  }
  else{
    pt1[0]=this.pt2[0];
    pt2[0]=this.pt1[0];
  }
  if(this.pt1[1]<this.pt2[1]){
    pt1[1]=this.pt1[1];
    pt2[1]=this.pt2[1];
  }
  else{
    pt1[1]=this.pt2[1];
    pt2[1]=this.pt1[1];
  }
  pt1=this.pixelToProj(pt1[0],pt1[1]);
  pt2=this.pixelToProj(pt2[0],pt2[1]);
  latlon = new Array(2);
  	latlonMax= new Array(2);
  	UTMXYToLatLon (pt1[0], pt1[1], 31, false, latlon);
        xmin = RadToDeg (latlon[1]);
        ymin = RadToDeg (latlon[0]);
  	UTMXYToLatLon (pt2[0], pt2[1], 31, false, latlonMax);    
        xmax = RadToDeg (latlonMax[1]);
        ymax = RadToDeg (latlonMax[0]);
  xmin = redondear(xmin,5);
  ymin = redondear(ymin,5);
  xmax = redondear(xmax,5);
  ymax = redondear(ymax,5);
  escribeCoord(ymax,ymin,xmax,xmin);
  pt1[0] = xmin;
  pt1[1] = ymax;
  return pt1;
}

function escribeCoord(n,s,e,o){
  n = redondear(n,5);
  s = redondear(s,5);
  e = redondear(e,5);
  o = redondear(o,5);
  document.getElementById('x0').value = o;
  document.getElementById('y0').value = n;
  document.getElementById('x1').value = e;
  document.getElementById('y1').value = s;
  activaControls(1,0);
}

function escribeMultCoord(puntos){
	var s = "";
	latlon = new Array(2);
	for(i=0;i<puntos.length-1;i++){
		UTMXYToLatLon (puntos[i][0], puntos[i][1], 31, false, latlon);
	    xmin = RadToDeg (latlon[1]);
	    ymin = RadToDeg (latlon[0]);
	    xmin = redondear(xmin,5);
	    ymin = redondear(ymin,5);
	    if (s == ""){
	       	s = xmin + "," + ymin;
	    }else{
	       	s = s + " " + xmin + "," + ymin;
		}
	}
	document.getElementById('boxSpatial').value = s;
	activaControls(2,geometria);
}

/*function ogcmap_queryUIdiv(x,y) {
var sURL
var mtop = parseInt(document.getElementById('mapa').style.top);
var mleft = parseInt(document.getElementById('mapa').style.left);
//document.getElementById('infoUIdiv').style.top = y + mtop;
//document.getElementById('infoUIdiv').style.left = x + mleft + 5;
//document.getElementById('infoUIdiv').innerHTML="";
//var iframe = '<iframe frameborder="0" allowtransparency="true" id="ifrFeatureInfodiv" name="ifrFeatureInfodiv" width="100%" height="80%"></iframe>'
//document.getElementById('infoUIdiv').innerHTML=iframe;
for (i=0;i < this.layers.length;i++){

	if (this.layers[i].queryable){
		var visib = this.serVisible(i);
		//alert(visib);
		if (visib){
			//if (this.layers[i].visible){
			//alert(i);
			control = 1;
			//dataWindow.document.write("<tr><td class=\"normal\">"+this.layers[i].srvname+" <img OnClick=\"getInfo("+i+",'si','text/html')\" alt=\"Informació objecte seleccionat\" style=\" cursor:pointer;cursor:hand\" src=\"images/info.png\" width=\"17\" height=\"17\"></td></tr>");
		 	var rutaServ=this.queryLayerURL(i,this.layers[i],x,y);
		 	alert(rutaServ);
		   	//dataWindow.document.write('<input type="hidden" id="'+i+'" value="'+rutaServ+'" > ');
		 }
	}
}
document.getElementById("ifrFeatureInfodiv").src=rutaServ;

//document.getElementById('infoUIdiv').style.visibility = "visible";
}*/

function parseInfoAjax3(){
	//alert("parseInfoAjax3");
	if(xmlDoc.readyState == 1){escriuValorInfo('Cercant1...');}
	if(xmlDoc.readyState == 4){ 
		if(xmlDoc.status == 200){
			//var x = position[0];
			//var y = position[1];
			//var mtop = parseInt(document.getElementById('mapa').style.top);
			//var mleft = parseInt(document.getElementById('mapa').style.left);
			//document.getElementById('infoUIdiv').style.top = y + mtop;
			//document.getElementById('infoUIdiv').style.left = x + mleft + 5;
			//document.getElementById('infoUIdiv').innerHTML="";
			//document.getElementById('infoUIdiv').innerHTML=xmlDoc.responseText;
			//document.getElementById('infoUIdiv').style.visibility = "visible";
			document.getElementById('infoDivCerca').innerHTML = xmlDoc.responseText;
			document.getElementById('infoDivCerca').style.visibility = "visible";
			//escriuValorInfo(xmlDoc.responseText);
		}
	}
}

//14 feb fin
//27 de mar
function idec_dibujaPunt(x,y){
	var coord = new Array();
	coord = map.pixelToProj(x,y);
	document.getElementById('inciX').value=coord[0];
	document.getElementById('inciY').value=coord[1];
	document.getElementById('puntInci').style.top= (y-5) + "px";
	document.getElementById('puntInci').style.left= (x-4) + "px";
	document.getElementById('puntInci').style.visibility='visible';
}

//06 abr
function ogcmap_onDblClick(event){
	if (this.pline){
		this.pline = false;
		//almacenar_lineas(clickX, clickY);
		clicks=0;
		clickX.length=0;	
		clickY.length=0;
		escribeMultCoord(this.PtsLine);
	}
	if (this.ppoli){
		this.ppoli = false;
		//almacenar_poligonos(clickX, clickY);
		clicks=0;
		clickX.length=0;	
		clickY.length=0;
		if (this.PtsPoli.length > 2){
    		escribeMultCoord(this.PtsPoli);
    	}
	}
	this.drawPts();
}

function gatherPoints(e){
		//alert("gatherPoints " + ho + "  " + vo);
		clickX[clicks]=e.clientX-ho;
		clickY[clicks]=e.clientY-vo;
		clicks++;
		//alert("clickX: " + clickX + " clickY: " + clickY + " cliks: " + clicks);
		//alert("this.PtsLine: " + this.PtsLine);
}

function drawLine(e){
		thisX=e.clientX-ho;
		thisY=e.clientY-vo;
		if (clicks == 1) {
			//imgxs[imgxs.length];
			//imgys[imgys.length];
			//alert(clickX[0]);
			//xD = Math.abs(clickX[0] - thisX);
			//yD = Math.abs(clickY[0] - thisY);
			//mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
			//parent.showStuff.value="total: "+Math.round(totalDistance)+" units   segment: "+Math.round(mDistance)+" units";
			//map.jg.clear();
			map.jg.setColor("green");
			map.jg.drawLine(clickX[0],clickY[0],thisX,thisY);
			//this.jg.drawLine(clickX[0],clickY[0],thisX,thisY);
			//this.jg.setColor("blue");
			//this.jg.fillOval(thisX,thisY,3,3); 
			map.jg.paint();	
		}
		if (clicks >= 1) {
			//xD = Math.abs(clickX[clicks-1] - thisX);
			//yD = Math.abs(clickY[clicks-1] - thisY);
			//mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
			//parent.showStuff.value="total: "+Math.round(totalDistance)+" units   segment: "+Math.round(mDistance)+" units";
			//map.jg.clear();
			map.jg.setColor("green");
			map.jg.drawPolyline(clickX,clickY);
			map.jg.drawLine(clickX[clicks-1],clickY[clicks-1],thisX,thisY);
			//for (l=0; l <= labels-1; l++) {
			//	this.jg.drawString(labelText[l],labelX[l],labelY[l]);
			//	this.jg.setColor("blue");
			//	this.jg.fillOval(labelX[l]-2,labelY[l]-2,3,3); 
			//	this.jg.setColor("red");
			//}
			map.jg.setColor("green");					
			map.jg.paint();	
		}	
	}
	
	function drawPoligon(e){
		thisX=e.clientX-ho;
		thisY=e.clientY-vo;
		if (clicks == 1) {
			//imgxs[imgxs.length];
			//imgys[imgys.length];
			//alert(clickX[0]);
			//xD = Math.abs(clickX[0] - thisX);
			//yD = Math.abs(clickY[0] - thisY);
			//mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
			//parent.showStuff.value="total: "+Math.round(totalDistance)+" units   segment: "+Math.round(mDistance)+" units";
			//map.jg.clear();
			map.jg.setColor("green");
			map.jg.drawLine(clickX[0],clickY[0],thisX,thisY);
			//this.jg.drawLine(clickX[0],clickY[0],thisX,thisY);
			//this.jg.setColor("blue");
			//this.jg.fillOval(thisX,thisY,3,3); 
			map.jg.paint();	
		}
		if (clicks == 2) {
			//xD = Math.abs(clickX[clicks-1] - thisX);
			//yD = Math.abs(clickY[clicks-1] - thisY);
			//mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
			//parent.showStuff.value="total: "+Math.round(totalDistance)+" units   segment: "+Math.round(mDistance)+" units";
			//map.jg.clear();
			map.jg.setStroke(2);
			map.jg.setColor("green");
			map.jg.drawPolyline(clickX,clickY);
			map.jg.drawLine(clickX[clicks-1],clickY[clicks-1],thisX,thisY);
			//for (l=0; l <= labels-1; l++) {
			//	this.jg.drawString(labelText[l],labelX[l],labelY[l]);
			//	this.jg.setColor("blue");
			//	this.jg.fillOval(labelX[l]-2,labelY[l]-2,3,3); 
			//	this.jg.setColor("red");
			//}
			map.jg.setStroke(2);
			map.jg.setColor("green");					
			map.jg.paint();	
		}
		if (clicks > 2) {
			//xD = Math.abs(clickX[clicks-1] - thisX);
			//yD = Math.abs(clickY[clicks-1] - thisY);
			//mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
			//parent.showStuff.value="total: "+Math.round(totalDistance)+" units   segment: "+Math.round(mDistance)+" units";
			//map.jg.clear();
			map.jg.setStroke(2);
			map.jg.setColor("green");
			clickX[clicks] = thisX;
			clickY[clicks] = thisY;
			map.jg.fillPolygon(clickX,clickY);
			//map.jg.drawPolyline(clickX,clickY);
			//map.jg.drawLine(clickX[clicks-1],clickY[clicks-1],thisX,thisY);
			//for (l=0; l <= labels-1; l++) {
			//	this.jg.drawString(labelText[l],labelX[l],labelY[l]);
			//	this.jg.setColor("blue");
			//	this.jg.fillOval(labelX[l]-2,labelY[l]-2,3,3); 
			//	this.jg.setColor("red");
			//}
			//map.jg.setColor("blue");					
			map.jg.paint();	
		}	
	}

/*	
function idec_dibujaLinea(){
		clicks=0;
		clickX.length=0;
		clickY.length=0;
		//alert("press space bar to stop measuring");
	}

var MultiPuntos = new Array();

function almacenar_puntos(pt){
	var multpts = MultiPuntos.length;
	MultiPuntos[multpts] = pt;
	dibuja_multiPuntos(MultiPuntos);
}

function dibuja_multiPuntos(puntos){
	map.jg1.clear();
	map.jg1.setColor("green");
	for (i = 0;	i < puntos.length; i++){
		map.jg1.fillOval(puntos[i][0]-1,puntos[i][1]-1,6,6);
		map.jg1.paint();
	}
}

var MultiLineas = new Array();

function almacenar_lineas(clickX, clickY){
	var multline = MultiLineas.length;
	var clickXtmp = new Array();
	var clickYtmp = new Array();
	var tmp = new Array();
	for (i = 0; i < clickX.length; i++){
		clickXtmp[i] = clickX[i];
		clickYtmp[i] = clickY[i];	
	}
	tmp[0]= clickXtmp;
	tmp[1]= clickYtmp;
	MultiLineas[multline] = tmp;
	dibuja_multiLineas(MultiLineas);
}

function dibuja_multiLineas(lineas){
	map.jg1.clear();
	map.jg1.setColor("blue");
	for (i = 0;	i < lineas.length; i++){
		map.jg1.drawPolyline(lineas[i][0],lineas[i][1]);
		map.jg1.paint();
	}
	map.jg1.setColor("blue");
}

var MultiPoligonos = new Array();

function almacenar_poligonos(clickX, clickY){
	var multpoli = MultiPoligonos.length;
	var clickXtmp = new Array();
	var clickYtmp = new Array();
	var tmp = new Array();
	for (i = 0; i < clickX.length; i++){
		clickXtmp[i] = clickX[i];
		clickYtmp[i] = clickY[i];	
	}
	tmp[0]= clickXtmp;
	tmp[1]= clickYtmp;
	MultiPoligonos[multpoli] = tmp;
	dibuja_multiPoligonos(MultiPoligonos);
}

function dibuja_multiPoligonos(poligonos){
	map.jg1.clear();
	map.jg1.setColor("red");
	for (i = 0;	i < poligonos.length; i++){
		map.jg1.fillPolygon(poligonos[i][0],poligonos[i][1]);
		map.jg1.paint();
	}
	map.jg1.setColor("red");
}

function ogcmap_finEdicion(){
	alert("fin edicion");
	var sURL = "";
	//Puntos
	if (MultiPuntos.length != 0){
		var MultiPuntosUTM = new Array();
		MultiPuntosUTM = conviertePuntosUTM(MultiPuntos);
		sURL = formaURL(MultiPuntosUTM,1);
		dibuja_Ajax(sURL);
	}
	//Lineas
	if (MultiLineas.length != 0){
		var MultiLineasUTM = new Array();
		MultiLineasUTM = convierteLineasUTM(MultiLineas);
		sURL = formaURL(MultiLineasUTM,2);
		dibuja_Ajax(sURL);
	}
	//Poligonos
	if (MultiPoligonos.length != 0){
		var MultiPoligonoUTM = new Array();
		MultiPoligonoUTM = convierteLineasUTM(MultiPoligonos);
		sURL = formaURL(MultiPoligonoUTM,3);
		dibuja_Ajax(sURL);
	}
	limpiar_dibujo();
}

function limpiar_dibujo(){
	MultiPuntos.length = 0;
	MultiLineas.length = 0;
	MultiPoligonos.length = 0;
	clicks=0;
	clickX.length=0;	
	clickY.length=0;
	map.jg1.clear();
	//map.jg.clear();
}

function conviertePuntosUTM(puntos){
	var newPts = new Array();
	for (i = 0; i < puntos.length; i++){
		var tmpXY = map.pixelToProj(puntos[i][0],puntos[i][1]);
		newPts[newPts.length] = tmpXY; 
	}
	return newPts;
}

function convierteLineasUTM(puntos){
	var newPts = new Array();
	for (i = 0; i < puntos.length; i++){
		var linea = new Array();
		var tmpX = new Array();
		var tmpY = new Array();
		for (k = 0; k < puntos[i][0].length; k++){
			var tmpXY = map.pixelToProj(puntos[i][0][k],puntos[i][1][k]);
			tmpX[tmpX.length] = tmpXY[0];
			tmpY[tmpY.length] = tmpXY[1];
		}
		linea[0] = tmpX;
		linea[1] = tmpY;
		newPts[newPts.length] = linea; 
	}
	return newPts;
}*/
//27 mar fin
//]]>

