var jg; /*canvas*/
var map_2_0;
var markerComercio;
var info_comercios = [];
var mapaNoCreado;
var actualScale;

//******************************************************************************
// SERVICIOS
//******************************************************************************

//Se carga al iniciar el JSP del mapa
function CargaServicios() {
    url = 'ListaServicios.jsp';
    //if (!confirm("ANTES " + url)) throw 1;
    new Ajax.Request(url , {
        method:'get',
        onSuccess: function(transport) {
            var response = transport.responseText || "no response text";      
            //alert(response); 
            $('tab_herramientas_content').update(response);


        },
        onFailure: function() {
            alert('Something went wrong...'); 
        }
    });

}

//******************************************************************************
// BOTONES
//******************************************************************************

//Se carga al iniciar el JSP del mapa
function CargaBotones() {
    url = 'ListaServicios.jsp';
    //if (!confirm("ANTES " + url)) throw 1;
    new Ajax.Request(url , {
        method:'get',
        onSuccess: function(transport) {
            var response = transport.responseText || "no response text";      
            //alert(response); 
            $('tab_herramientas_content').update(response);


        },
        onFailure: function() {
            alert('Something went wrong...'); 
        }
    });

}

//******************************************************************************
// BUSQUEDA DE DIRECCIONES
//******************************************************************************

//Buscar Direcciones
function jsBuscaDireccion(idNombreVia,idAltura,idComuna,idInterseccion,idTipoVia){
    var url;   
 
    var tipoVia	=	document.getElementById(idTipoVia); 
    var calle	=	document.getElementById(idNombreVia);
    var numero	=	document.getElementById(idAltura);
    var comuna	=	document.getElementById(idComuna);
    var calle2	=	document.getElementById(idInterseccion);
    var vNombreVia;
    
    ActualizarTamMapa();
    
    if (mapaNoCreado){
        CrearMapa();
        mapaNoCreado = false;
    }
    

    Cargando(1);
    document.getElementById("divListadoDir").style.visibility = 'hidden';            
    url = "./ServletBuscarDireccion?tipovia=" + tipoVia.value + "&nombrevia=" + calle.value + "&altura=" + numero.value + "&comuna=" + comuna.value + "&nombreviaint=" + calle2.value;     
    new Ajax.Request(url , {
        method:'get',
        onSuccess: function(transport) {
            var response = transport.responseText || "no response text";                          
            //alert(response);
            ListarDirecciones(response);                   
                                                    
     
        },
        onFailure: function() {
            alert('Something went wrong...'); 
        }
    });
}

//Listar Direcciones
function ListarDirecciones(response){
    var div = $('divListadoDir');
    var html,data,item; 
    var tipoCalle,calle,altura,tipoCalleInt,calleInt,comuna,este,norte;
    var estado,descripcion,recomendacion,tagAddress,contador;
    var direccion,direccionCompleta;
    
    
    //alert(response);	  
    data = response.evalJSON();                                                           
    contador = data.CONTADOR;
    recomendacion = data.RECOMMENDATION;
    descripcion =  data.DESCRIPTION;
    
    if (contador == 0){
        html = "<table border='1' class = 'tablaListaDir' width='400px'>";
        html += "<tr><td><br>La calle no fue encontrada<br><br>";	          
        html += "<b>Sugerencia</b><br>" + recomendacion ;	                  
        //html += "<b>Descripción</b><br>" + descripcion ;	                          
        html += "<br><br></td></tr></table>";	
        document.getElementById("divListadoDir").style.visibility = 'visible';        
        MapaVisible(0);
        div.innerHTML = html;
    }else{    
        cercania = document.getElementById("idMCBuscadorCercania").value;
        item = 0;
        html = "<table border='0' class = 'tablaListaDir' cellpadding='3' cellspacing='3'>";
        html += "<tr><td></td>";	                  
        html += "<td>Dirección</td>";	          
        html += "<td>Comuna</td>";	              
        html += "<td></td></tr>";	              
        while (item < contador){
            tipoCalle = data.ADDRESS[item].CLASE_TYPE;                        
            calle = data.ADDRESS[item].STREET;                        
            altura = data.ADDRESS[item].NUMBER;                        
            tipoCalleInt = data.ADDRESS[item].INTERSECTION_CLASE_TYPE;                        
            calleInt = data.ADDRESS[item].INTERSECTION_STREET;                        
            comuna = data.ADDRESS[item].COMMUNE;                                
            este = data.ADDRESS[item].EAST;                        
            norte = data.ADDRESS[item].NORTH;    
            if (calleInt == ""){
                direccion = direccion = tipoCalle + " " + calle + " " + altura;                                
            }else{
                direccion = tipoCalle + " " + calle + " con " + tipoCalleInt + 
                    " " + calleInt ;                
            }
            direccionCompleta = direccion + " " + comuna;  
           
            tag = "<input type=hidden id = 'idDireccion" + item + "' value = '" + direccionCompleta + "'>";            
            tag += "<input type=hidden id = 'idtipoCalle" + item + "' value = '" + tipoCalle + "'>";            
            tag += "<input type=hidden id = 'idcalle" + item + "' value = '" + calle + "'>";            
            tag += "<input type=hidden id = 'idaltura" + item + "' value = '" + altura + "'>";            
            tag += "<input type=hidden id = 'idcomuna" + item + "' value = '" + comuna + "'>";            
            tag += "<input type=hidden id = 'idcalleInt" + item + "' value = '" + calleInt + "'>";                        
            tag += "<input type=hidden id = 'idEste" + item + "' value = '" + este + "'>";                        
            tag += "<input type=hidden id = 'idNorte" + item + "' value = '" + norte + "'>";
            

            if (item == 0){                
                tagChk = "<input class ='textos' type='radio'  id = 'idDireccionChk" + item + "' onclick='CargaDatosDir(" + item + ")'  name='direcciones' value='" + item + "' checked='checked'/>";    
            }else{
                tagChk = "<input class ='textos' type='radio'  id = 'idDireccionChk" + item + "' onclick='CargaDatosDir(" + item + ")'  name='direcciones' value='" + item + "' />";
            }                           
            html += "<tr><td class = 'textoListaDir' >" + tagChk + "</td>";	                      
            html += "<td class = 'textoListaDir' >" + tag + "&nbsp;&nbsp;" + direccion + "&nbsp;&nbsp;</td>";	          
            html += "<td class = 'textoListaDir'>&nbsp;&nbsp;" + comuna + "&nbsp;&nbsp;</td>";	          
            //html += "<td class = 'textoLinkListaDir' style='cursor:pointer;' onclick='CargaMapa(" + este + "," + norte+ "," + item + ")' >&nbsp;&nbsp;Mapa&nbsp;&nbsp;</td></tr>";	                      
            html += "<td class = 'textoLinkListaDir' style='cursor:pointer;' onclick='CargaMapaDesdeLista(" + este + "," + norte+ "," + item + "," + cercania + ")' >&nbsp;&nbsp;Mapa&nbsp;&nbsp;</td></tr>";	                      
            item++;
        }
        html += "</table>";	               
        
        //Si se encontró sólo 1 dirección
  
        if (contador == 1){
            //MapaVisible(0);
            CargaMapa(este,norte,0);   
            //alert(este + " " + norte);
            DibujarRadio(este,norte,cercania);                   
            document.getElementById("divListadoDir").style.visibility = 'visible';                 
            div.innerHTML = tag;                         
        }else{
            MapaVisible(0);
            document.getElementById("divListadoDir").style.visibility = 'visible';                                    
            div.innerHTML = html;  
        }   
    
        CargaDatosDir(0);
        
        alto = 1400 + (contador * 35 );                                                    
        alto = alto + "px";
        
        try{
            //parent.document.getElementById("FrameMain").style.height= alto;            
        } catch (e){}        

        if (contador == 1){
            //AceptarBusqueda();
        }       

    }   
        
    Cargando(0);
     
}


function CargaMapaDesdeLista(este,norte,item,cercania) {      
    CargaMapa(este,norte,item);
    DibujarRadio(este,norte,cercania);
}


//Se carga al iniciar el JSP del mapa
function CargaDatosDir(item) {  
    
    var objTipoCalle   =	document.getElementById("idMCBuscadorTipoVia");    
    var objCalle       =	document.getElementById("idMCBuscadorNombreVia");
    var objNumero      =	document.getElementById("idMCBuscadorAltura");
    var objComuna      =	document.getElementById("idMCBuscadorComuna");
    var objCalle2      =	document.getElementById("idMCBuscadorInterseccion");
    var objEste      =	document.getElementById("idEste");
    var objNorte      =	document.getElementById("idNorte");
    
    objId = "idtipoCalle" + item;
    var objTipoCalleVar   =	document.getElementById(objId);    
    objId = "idcalle" + item;
    var objCalleVar       =	document.getElementById(objId);    
    objId = "idaltura" + item;
    var objNumeroVar      =	document.getElementById(objId);    
    objId = "idcomuna" + item;
    var objComunaVar      =	document.getElementById(objId);    
    objId = "idcalleInt" + item;
    var objCalle2Var      =	document.getElementById(objId);    
    objId = "idEste" + item;
    var objEsteVar      =	document.getElementById(objId);    
    objId = "idNorte" + item;
    var objNorteVar      =	document.getElementById(objId);    

    objTipoCalle.value  = objTipoCalleVar.value ;
    objCalle.value      = objCalleVar.value;
    objNumero.value     = objNumeroVar.value;
    objComuna.value     = objComunaVar.value;
    objCalle2.value     = objCalle2Var.value;
    objEste.value     = objEsteVar.value;
    objNorte.value     = objNorteVar.value;       
    
}    
//******************************************************************************
// MANEJO DE MAPA
//******************************************************************************

function CargaMapa(este,norte,idDireccion){
    var codEntrada,codSalida,geometry;
    var utm_x,utm_y;
    utm_x = este - 62;
    utm_y = norte - 40;

    codEntrada = "29179";
    codSalida="4326";
    geometry="POINT(" + utm_x + " " + utm_y + ")";    
        
    url = "./ServletFuncionesGIS?codEntrada=" + codEntrada + "&codSalida=" + codSalida + "&geometry=" + geometry;
     
    new Ajax.Request(url , {
        method:'get',
        onSuccess: function(transport) {
            var response = transport.responseText || "no response text";                                              
                    
            data = response.evalJSON();                                                           
            X = data.X;   
            Y = data.Y;                     
            if(X != ""){
                IniciarMapa(X,Y,idDireccion);
            }
                    
        },
        onFailure: function() {
            alert('Something went wrong...'); 
            return "";
        }
    });
    
}

//Se carga al iniciar el JSP del mapa
function IniciarMapa(x,y,idDireccion) {  
            
    //CerrarMapa();
    MapaVisible(1);
    Limpiar();   

    //Obtenemos el zoom a partir del radio
    cercania = document.getElementById("idMCBuscadorCercania").value;        
    switch (cercania){
        case "500":
            zoom = "11";
            break;        
        case "1000":
            zoom = "10";
            break;
        case "5000":
            zoom = "8";
            break;
        case "10000":
            zoom = "7";
            break;
        case "25000":
            zoom = "6";
            break;
        case "50000":
            zoom = "5";
            break;            
        default:
            zoom = "12";
            break;
    }    

    //Centrar Mapa
    CentrarMapa(x,y,zoom);
    
    //Agregar Marker Estrella
    //x = -70.5940820288761;
    //y = -33.4423938319504;
    var LonLat1= new OpenLayers.LonLat(x,y);                                                         
    w = 30;
    h = 30;
    icon = "./imgs/imagesCenso/Mapa/estrellanew.gif";
    var sizeIcon = new OpenLayers.Size(w,h);
    var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
    var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
    var markerEstrella = new OpenLayers.Marker(LonLat1,iconObj);

    if (markerEstrella){
        markers_busqueda.clearMarkers();
    }
    markers_busqueda.addMarker(markerEstrella);
    
    //Mostramos la dirección en la parte inferior del mapa
    idDir = "idDireccion" + idDireccion;
    direccion = document.getElementById(idDir).value;                
    
    html = "<table align=center class='textos'><tr><td align=right valign=middle>";
    html+= "<img src='./imgs/imagesCenso/Mapa/estrella.gif'></td><td align=left valign=middle>&nbsp;&nbsp;" + direccion;
    html+= "</td></tr></table>";
    
    var div = $('divDireccion');   
    div.innerHTML = html;          

}//end function 

//Se carga al iniciar el JSP del mapa
function CentrarMapa(x,y,zoom) {  
    try{
        //Centrar Mapa
        var LonLat= new OpenLayers.LonLat(x,y);            
        map_2_0.setCenter(LonLat,zoom);
    }catch(e){
        MapaVisible(0);
        alert("Mapa cargando. Intente nuevamente.");        
    }
}
function MapaVisible(estado){
    
    objDiv = document.getElementById("divMapaMain");
    if (estado == 1){
        objDiv.style.visibility = 'visible';        
    }else{
        objDiv.style.visibility = 'hidden';        
    }
    
}

function Cargando(estado){    
    try{
        objDiv = document.getElementById("divLoading");    
        if (estado == 1){
            objDiv.style.visibility = 'visible';             
        }else{
            objDiv.style.visibility = 'hidden';                
        }
    }catch(e){
        alert(e.message);
    }
}

function Test(){
    /*
    var objDiv;    
    objDiv = document.getElementById("idDivTest");    
    objDiv.style.visibility = 'visible';     
     */
    tag = "<div style='position:absolute;top:100px;left:100px;z-index:50000;'>DATA</div>";         
    var element = new Element('span', {}).update(tag);            
    element.setStyle({ opacity: '0.9',cursor:'pointer'});       
    $('divMapa').insert(element, { position: "content" });	  
    $('idDivTest').insert(element, { position: "content" });	  
    alert("CARGO 1");
}
function HerramientasRubrosVisible(){
    
    objDiv = document.getElementById("tab_rubros_content");        
    estado = objDiv.style.visibility;
    if (estado == 'visible'){
        objDiv.style.visibility = 'hidden';                
    }else{
        objDiv.style.visibility = 'visible';        
    }
    
}

function MostrarTabHerramientas(){
    
    document.getElementById("tab_rubros_tool_1").style.visibility = 'visible';
    document.getElementById("tab_rubros_tool_2").style.visibility = 'visible';
    document.getElementById("tab_rubros_tool_3").style.visibility = 'visible';
    
}
//Creación del objeto Mapa
function CrearMapa() {       
    var x_left,y_bottom,x_right,y_top;
    var v_numZoomLevels,v_maxResolutionDeg,v_maxResolutionPx;                               
    try{    
        //alert('crea');

        //Creamos el objeto para dibujar los comercios
        //jg = new jsGraphics("divMapa");         
    
        size=new OpenLayers.Size(500,500);
        sizeOverview=new OpenLayers.Size(256,256);            
        ////v_numZoomLevels = 15;
        ////v_maxResolution = 0.07902398403828125;//0.087890625; // 0.087890625
        //Extents
        x_left   = -91.04770;
        y_bottom = -58.0000;
        x_right  = -43.23819;
        y_top    = -16.95350;
        v_maxResolution=0.07902398403828125;
        v_numZoomLevels = 14;            

        map_2_0 = new OpenLayers.Map( $('divMapa'),
        {
            controls: [
                new OpenLayers.Control.MouseDefaults()
                ,new OpenLayers.Control.PanZoomBar({div:$('divCustomPanZoomBar')})
            
            ]
            ,maxResolution: v_maxResolution
            ,tileSize:new OpenLayers.Size(400,400)
            ,maxExtent: new OpenLayers.Bounds(x_left,y_bottom,x_right,y_top)
            ,numZoomLevels:v_numZoomLevels
        });
        //Fin opciones del Mapa

        //Creación del Mapa
        //map_2_0 = new OpenLayers.Map("divMapa",opt);			


        //Capa Base del Mapa
    
    
        //BLADE  SERVIDOR DE PRUEBA (172.16.1.168)    
        /*
    layer_base_chile = new OpenLayers.Layer.WMS( "Chile",
        "http://proxy.sblade1/cgi-bin/mapserv?map=/var/www/mapcity_2_0/map/chile_tiled_censo.map"
        ,{layers: 'Oceano,raster_sudamerica,Boundaries,Park,urban,Elevation,Lakes,Hidrography,Escaleras,Calles,Avenidas,Autopistas,Caminos,america,bound_limit,Locality,Metro,t_comercios',format: 'image/gif'}
        ,{singleTile:false, gutter:8});

     layer_label_comunas_chile = new OpenLayers.Layer.MapServer( "Chile Label",
                            "http://proxy.sblade1/cgi-bin/mapserv?",
                            {map:'/var/www/mapcity_2_0/map/chile_label_comunas.map', format: 'image/gif'},
                            {singleTile:true});
         */
    
        //BLADE 5 SERVIDOR DE PRODUCCION 
        /*
    layer_base_chile = new OpenLayers.Layer.WMS( "Chile",
        "http://l5.mapcity.com/cgi-bin/mapserv?map=/var/www/mapcity_2_0/map/chile_tiled.map"
        ,{layers: 'Oceano,raster_sudamerica,Boundaries,Park,urban,Elevation,Lakes,Hidrography,Escaleras,Calles,Avenidas,Autopistas,Caminos,america,bound_limit,Locality',format: 'image/gif'}
        ,{singleTile:false, gutter:8});
         */
        /*
        layer_base_chile = new OpenLayers.Layer.WMS( "Chile",
        "http://l5.mapcity.com/cgi-bin/mapserv?map=/var/www/mapcity_2_0/map/chile_tiled.map"
        ,{layers: 'Oceano,raster_sudamerica,Boundaries,Park,urban,Elevation,Lakes,Hidrography,Escaleras,Calles,Avenidas,Autopistas,Caminos,america,bound_limit,Locality',format: 'image/gif'}
        ,{singleTile:false, gutter:8});


        layer_label_comunas_chile = new OpenLayers.Layer.MapServer( "Chile Label",
        "http://l5.mapcity.com/cgi-bin/mapserv?",
        {map:'/var/www/mapcity_2_0/map/chile_label_comunas.map', format: 'image/gif'},
        {singleTile:true});
         */
       
        //BLADE 192.168.1.15 NUEVO SERVIDOR DE PRODUCCION 
        layer_base_chile = new OpenLayers.Layer.TileCache( "VMap0",
        [
            "http://mapa1.mapcity.com/tiles/"
            ,"http://mapa2.mapcity.com/tiles/"
            ,"http://mapa3.mapcity.com/tiles/"
            ,"http://mapa4.mapcity.com/tiles/"
        ]
        ,'chile_base'
        //,{layers: 'chile_base', format: 'image/jpeg'}
        ,{singleTile:false,buffer:0,gutter:0,transitionEffect: 'resize',format:'image/jpeg'} );
    

        layer_label_comunas_chile = new OpenLayers.Layer.MapServer( "Chile Label",
        "http://mapa.mapcity.com/fmapserv/mapserv?",
        {map:'/var/www/mapcity_2_0/map/chile_label_comunas.map', format: 'image/gif'},
        {singleTile:true});
    
        map_2_0.addLayers([layer_base_chile]);
        ////layer_label_comunas_chile.setIsBaseLayer(false);
        //layer_base_chile.setIsBaseLayer(false);
        ////layer_label_comunas_chile.setVisibility(true);
        layer_base_chile.setVisibility(true);
        ///layer_label_comunas_chile.setOpacity(0.3);
    
        //Crear Markers
        markers_busqueda = new OpenLayers.Layer.Markers( "Busqueda" );
        markers_busqueda.setZIndex(15010);
    
        map_2_0.addLayer(markers_busqueda);

        addImageLogo('./imgs/imagesCenso/Mapa/LogoMapcity.gif');
        addImageFlecha('./imgs/imagesCenso/Mapa/flecha_NORTE.gif');
        //debugger;
        IniciarEventos();
        
       
    }catch(e){
        alert("Error al crear Mapa. Descripcion: " + e.message);
    }
}  
function ActualizarTamMapa(){
    
    try{
        document.getElementById("divMapa").style.width='680px';
        document.getElementById("divMapa").style.height='550px';
    }catch(e){
        alert(e.message);
    }
}

function IniciarEventos(){
    //    debugger;
    map_2_0.events.register("movestart", map_2_0, function(e) {
        //alert("movestart");
        LimpiarLabelComercios();
        map_2_0.events.register("movestart", map_2_0, function(e) {return false;}); 
    });
    map_2_0.events.register("moveend", map_2_0, function(e) {
        //alert("moveend");
        
        addScalebar(map_2_0.getScale());
        muestraComunaCalzada();
        //        debugger;
        RefrescarComercios();
        map_2_0.events.register("moveend", map_2_0, function(e) {return false;});
    });
    map_2_0.events.register("mousemove", map_2_0, function(e) { 
        //alert("mousemove");         
        map_2_0.events.register("mousemove", map_2_0, function(e) {return false;});
    });	
}

function addScalebar(scale){
    try{
	if(scale!=actualScale){
            if($('scalebar')) $('scalebar').remove();
            var map_Extent=map_2_0.getExtent();
            var map_Size=map_2_0.getSize();
            //var url='http://proxy.sblade1/cgi-bin/mapserv?map=/var/www/mapcity_2_0/map/chile.map&mode=scalebar&map_imagetype=gif&mapext='+map_Extent.left+'+'+map_Extent.bottom+'+'+map_Extent.right+'+'+map_Extent.top+'&map_size='+map_Size.w+'+'+map_Size.h;
            var url='http://mapa.mapcity.com/fmapserv/mapserv?map=/var/www/mapcity_2_0/map/chile.map&mode=scalebar&map_imagetype=gif&mapext='+map_Extent.left+'+'+map_Extent.bottom+'+'+map_Extent.right+'+'+map_Extent.top+'&map_size='+map_Size.w+'+'+map_Size.h;
		
            addImage(url,'scalebar');
            $('scalebar').setOpacity(0.7);
            actualScale=scale;
	}
    }catch(e){
        alert(e.message);
    }         
}

function addImage(imagen,id_imagen){
    img = new Element('img', { 'id': id_imagen, 'src':imagen});
    //$('map_2_0').insert(img, { position: "content" });
    img.setStyle({ position: 'absolute',left: '480px',top: '520px',opacity: '0.9' });                 
    $('divMapa').insert(img, { position: "content" });
}

function addImageLogo(imagen){
    id_imagen = 'Logo'
    img = new Element('img', { 'id': id_imagen, 'src':imagen});
    img.setStyle({ position: 'absolute',left: '5px',top: '475px',opacity: '0.9' });        
    $('divMapa').insert(img, { position: "content" });
    //,z-index: 19999
}

function addImageFlecha(imagen){
    id_imagen = 'LogoFlecha'
    img = new Element('img', { 'id': id_imagen, 'src':imagen});
    img.setStyle({ position: 'absolute',left: '650px',top: '5px',opacity: '0.9' });        
    $('divMapa').insert(img, { position: "content" });
    //,z-index: 19999
}

function RefrescarComercios(){        
    
    
//    var c = $('check_7').checked;
//    alert(c);
    LimpiarLabelComercios();
    LimpiarComercios();
    RecargarComecios();    
    /*
    alert("A");
    tag = "<div style='position:absolute;top:100px;left:100px'>ALGO</div>";         
    var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);            
    element.setStyle({ opacity: '0.9',cursor:'pointer'});       
    $('divMapa').insert(element, { position: "content" });	  
    alert("B");
     */
}
//Limpiamos las etiquetas de los comercios
function LimpiarLabelComercios(){        
    
    try{
        $$('.labelComercios').each(function(element) { element.remove(); })
    }catch(e){
        alert(e.message);
    }
    
}
//Limpiamos las imágenes de los mercados
function LimpiarComercios(){        
    //jg.clear();  
    try{
        if (markerComercio){
            markers_busqueda.clearMarkers();
        }    
    }catch(e){}
    
}

function RecargarComecios(){
    var x_left_min,y_bottom_min,x_right_max,y_top_max;
    var boundsObj;
    try{                      

        boundsObj = map_2_0.getExtent();			
	x_left_min = boundsObj.left;
	y_bottom_min = boundsObj.bottom;
	x_right_max = boundsObj.right;
	y_top_max = boundsObj.top;
        
        document.getElementById("x_left").value=x_left_min;            
        document.getElementById("y_bottom").value=y_bottom_min;            
        document.getElementById("x_right").value=x_right_max;            
        document.getElementById("y_top").value=y_top_max;            
        //        debugger;
        CargaComerciosDesdeServlet(x_left_min,y_bottom_min,x_right_max,y_top_max);

    } catch (e){
        //alert(e.message);
    }
}

//Se dibuja el radio en el mapa
function DibujarRadio(utm_x,utm_y,cercania) {  
    var poligono,url;
    
    utm_x = utm_x - 62;
    utm_y = utm_y - 40;
    
    if (cercania == ""){        
        return;
    }
    url = "./ServletRecuperaInfo?utm_x=" + utm_x + "&utm_y=" + utm_y + "&cercania=" + cercania;
     
    new Ajax.Request(url , {
        method:'get',
        onSuccess: function(transport) {
            var response = transport.responseText || "no response text";                                              
                    
            data = response.evalJSON();                                                           
            poligono = data.POLYGON;
            //poligono = "MULTIPOLYGON(((-70.6006500060521 -33.4120015197352,-70.599750076448 -33.4121844790631,-70.599620719988 -33.4122222207808,-70.5996640374082 -33.4122938089764,-70.6000275613242 -33.4139935883687,-70.6000371024738 -33.4141107044417,-70.6012138675763 -33.414014352744,-70.6012117161206 -33.4138971425435,-70.6011590181078 -33.4137174558301,-70.6006770335214 -33.4120643000053,-70.6006500060521 -33.4120015197352)))";
            //poligono = "POLYGON((-70.5983140085209 -33.4133003095376,-70.5983378891437 -33.4134759411617,-70.5984021678485 -33.4136442909234,-70.5985043746365 -33.4137988891702,-70.5986405818815 -33.413933794688,-70.5988055552475 -33.4140438230312,-70.5989929548365 -33.4141247457746,-70.5991955788369 -33.4141734530237,-70.5994056403079 -33.4141880729382,-70.5996150664601 -33.4141680436736,-70.5998158089254 -33.4141141349734,-70.6000001530875 -33.4140284185839,-70.6001610145804 -33.4139141886285,-70.6002922115549 -33.4137758350021,-70.6003887022491 -33.413618674655,-70.6004467787303 -33.41344874725,-70.6004642093659 -33.4132725830497,-70.6004403245511 -33.4130969519553,-70.6003760424047 -33.412928603341,-70.6002738334493 -33.4127740066844,-70.600137625641 -33.4126391029577,-70.5999726534016 -33.4125290763337,-70.5997852564575 -33.4124481549759,-70.5995826362179 -33.4123994485679,-70.5993725790508 -33.4123848288219,-70.5991631570904 -33.4124048575568,-70.5989624180668 -33.4124587651097,-70.5987780760721 -33.4125444799089,-70.5986172151426 -33.4126587080733,-70.5984860170415 -33.4127970599803,-70.5983895237023 -33.4129542189418,-70.5983314434603 -33.4131241455057,-70.5983140085209 -33.4133003095374,-70.5983140085209 -33.4133003095376))";
            //poligono = "POLYGON((-70.7535654168729 -33.4592769283884,-70.7535909596889 -33.4595362689512,-70.7536666065407 -33.4597856432017,-70.7537894503624 -33.4600154678272,-70.7539547703346 -33.4602169107962,-70.7541562133036 -33.4603822307684,-70.7543860379291 -33.4605050745901,-70.7546354121795 -33.4605807214419,-70.7548947527424 -33.4606062642579,-70.7551540933052 -33.4605807214419,-70.7554034675557 -33.4605050745901,-70.7556332921812 -33.4603822307685,-70.7558347351502 -33.4602169107963,-70.7560000551224 -33.4600154678273,-70.7561228989441 -33.4597856432018,-70.756198545796 -33.4595362689513,-70.756224088612 -33.4592769283885,-70.756198545796 -33.4590175878257,-70.7561228989442 -33.4587682135752,-70.7560000551226 -33.4585383889497,-70.7558347351504 -33.4583369459807,-70.7556332921814 -33.4581716260084,-70.7554034675559 -33.4580487821868,-70.7551540933054 -33.4579731353349,-70.7548947527426 -33.4579475925189,-70.7546354121798 -33.4579731353348,-70.7543860379293 -33.4580487821866,-70.7541562133038 -33.4581716260082,-70.7539547703348 -33.4583369459804,-70.7537894503625 -33.4585383889494,-70.7536666065408 -33.4587682135749,-70.7535909596889 -33.4590175878253,-70.7535654168729 -33.4592769283881,-70.7535654168729 -33.4592769283884))";
            var arrxy = splitBlock(poligono);
                    
            var puntos = [];
            for(var i=0; i<arrxy.length ; i++){
                var point = arrxy[i].replace(" ",",");
                var spliti = point.split(",");
                var point = new OpenLayers.Geometry.Point(parseFloat(spliti[0]),parseFloat(spliti[1]));
                puntos.push(point);
            }
            //alert(puntos);
            var ring = new OpenLayers.Geometry.LinearRing(puntos);
            var rings = [];
                                        
            rings.push(new OpenLayers.Feature.Vector(ring));
                    
            try{                      
                if (block){
                    block.destroyFeatures(block.features);
                }                        
            } catch (e){
                block = new OpenLayers.Layer.Vector("Vector Layer");    
                map_2_0.addLayer(block);                                
            }

            block.addFeatures(rings);
            block.setVisibility(true);
                    
                    
        },
        onFailure: function() {
            alert('Something went wrong...'); 
            return "";
        }
    });				

}
//FUNCION SPLIT 
function splitBlock (arreglo){
	
    var retornotmp = arreglo.substring(9,arreglo.length-2);
    var retorno = retornotmp.split(",");	
    return retorno;
}
//Se carga al iniciar el JSP del mapa
function Limpiar() {  
  
    try{
        //map_2_0.destroy();
        //markerEstrella.destroy();
        //markers_busqueda.destroy();

        // Fin           
    } catch (e){
    }
}    

//******************************************************************************
// MAPA CON COMERCIOS
//******************************************************************************
function CargaMapaComercios(este,norte){
    var cantidadRubros = 0;
    var i = 0;
    var listaComercios,rubro_id,este_x,norte_y,imagenComercio,correlativo;
    
    //Cargando(1);
        
    cantidadRubros = document.getElementById("idCantidadRubros").value;
    listaComercios = document.getElementById("idListaComercios").value;
    comercio_array=listaComercios.split("/");    
    while (i < cantidadRubros){
        comercio = Trim(comercio_array[i]);        
        comercio_array2=comercio.split(";");
        rubro_id = Trim(comercio_array2[0]);
        este_x = Trim(comercio_array2[1]);
        norte_y = Trim(comercio_array2[2]);  
        //alert(este_x);
        //alert(norte_y);
        correlativo = Trim(comercio_array2[4]);        
        imagenComercio = "./imgs/imagesCenso/comercios/" + Trim(comercio_array2[3]);    
        /**
         * 2008-06-18
         * se corrigió if (este != "") por if (este != "0") para validar si hay coordenada
         * cmancilla
         */
        if (este_x != "0"){
            CargaComercios(este_x,norte_y,imagenComercio,correlativo)
        }
        i++;
    }   
    
    /**
     * 2008-06-08
     * se corrigió if (este != "") por if (este != "0") para validar si hay coordenada
     * cmancilla
     */
    if (este != "0"){
        CargaMapa(este,norte,0);
        cercania = document.getElementById("idCercania").value;
        //DibujarRadio(utm_x,utm_y,cercania);   
    }
    //Cargando(0);

}

function CargaComercios(este,norte,imagenComercio,correlativo){
    var codEntrada,codSalida,geometry;

    /**
     * 2008-06-08
     * se if (este != "0") para validar si hay coordenada
     * cmancilla
     */
    if (este != "0"){
    
        utm_x = este - 62;
        utm_y = norte - 40;   
        
        codEntrada = "29179";
        codSalida="4326";
        geometry="POINT(" + utm_x + " " + utm_y + ")";    
        url = "./ServletFuncionesGIS?codEntrada=" + codEntrada + "&codSalida=" + codSalida + "&geometry=" + geometry;
     
        new Ajax.Request(url , {
            method:'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "no response text";                                              
                //alert(response);
                data = response.evalJSON();                                                           
                X = data.X;   
                Y = data.Y;  
                //alert(X);
                //alert(Y);
                /*
                 *correccion : if(X != "") a if(X != "0")
                 **/
                if(X != "0"){
                    IniciarMapaComercio(X,Y,imagenComercio,correlativo,este,norte);
                }
                    
            },
            onFailure: function() {
                alert('Something went wrong...'); 
                return "";
            }
        });
    }
}

//Se carga al iniciar el JSP del mapa
function IniciarMapaComercio(x,y,imagenComercio,correlativo,utm_x,utm_y) {  
            
    //CerrarMapa();
    MapaVisible(1);
       
    if (correlativo == 1){        
        //Obtenemos el zoom a partir del radio
        cercania = document.getElementById("idCercania").value;        
        switch (cercania){
            case "1000":
                zoom = "11";
                break;
            case "5000":
                zoom = "8";
                break;
            case "10000":
                zoom = "7";
                break;
            case "25000":
                zoom = "6";
                break;
            case "50000":
                zoom = "5";
                break;            
            default:
                zoom = "12";
                break;
        }    
        
        //Centrar Mapa
        CentrarMapa(x,y,zoom);      
    }
    
    
    //Limpiar();   
    
    var LonLat1= new OpenLayers.LonLat(x,y);                                                         
    w = 20;
    h = 20;
    //icon = "./imgs/imagesCenso/Mapa/estrella.gif";
    icon = imagenComercio
    var sizeIcon = new OpenLayers.Size(w,h);
    var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
    var iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
    var markerComercio = new OpenLayers.Marker(LonLat1,iconObj);
    markers_busqueda.addMarker(markerComercio);      
    
    //$(iconObj.imageDiv).setStyle({cursor:'pointer'});    
    info = correlativo;
    var element = new Element('span', { 'class':'etiquetaComercios'}).update("<span class='etiquetaComercios' ><b>"+info+"</b></span>");
    //element.setStyle({ position: 'absolute',left: '-20px',top: '25px',opacity: '0.9' });
    $(iconObj.imageDiv).insert(element, { position: "content" });	  

}//end function 

function CargaMapaComerciosDesdeServlet(longitud,latitud){
    
    //Cargando(1);
    ActualizarTamMapa();
    /*
    if (map_2_0){    
    }else{
        //document.getElementById("idMapaPDF").style.visibility = "visible";                
        CrearMapa();        
    }
     */
    
    CrearMapa();
        
    MapaVisible(1);
    /*
     *18-06-2008
     *correccion: if (longitud != "") por if (longitud != "0")
     *cmancilla
     **/
    if (longitud != ""){           
        CentrarMapa(longitud,latitud,12);       
    }else{
    
        longitud = '-70.7882009072';
        latitud = '-33.558006555';
        alert("AVISO");
        CentrarMapa(longitud,latitud,12);       
    }           
    
    MostrarTabHerramientas();
    //Cargando(0);

}

function CargaComerciosDesdeServlet(xmin,ymin,xmax,ymax){
    var queryParcial,url,demo;
    //    debugger;
    if (map_2_0){
        document.getElementById("idQueryNoRubros").value = "";
        queryParcial = document.getElementById("idQueryGlobal").value;
        queryDemo = document.getElementById("idQueryDemo").value;
        demo = document.getElementById("idDemo").value;
        if (demo == ""){
            queryDemo = "";
        }
        
        url = "./ServletBuscarComercio?queryParcial=" + queryParcial + 
            "&xmin=" + xmin + "&ymin=" + ymin + "&xmax=" + xmax + "&ymax=" + ymax + "&queryDemo=" + queryDemo;   
        //alert(url);    
        new Ajax.Request(url , {
            method:'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "no response text";                                              
                //alert(response);
                //               debugger;
                RecorrerComercios(response);

            },
            onFailure: function() {
                alert('Something went wrong...'); 
                return "";
            }
        });
    }else {
        alert('Cargando mapa...Intente nuevamente'); 
    }    
    
}

function RecorrerComercios(response){
    //    debugger;
    var contador,item;
    var latitud,longitud,imagen,color_rubro,este,norte,rubro_id,nombre_rubro,correlativo;
    
    data = response.evalJSON();                                                           
    contador = data.CONTADOR;           
    //Cargando(1);                
    item = 0;        
    while (item < contador){

        latitud=data.COMERCIOS[item].LATITUD;
        longitud=data.COMERCIOS[item].LONGITUD;
        imagen=data.COMERCIOS[item].IMAGEN;
        color_rubro=data.COMERCIOS[item].COLOR_RUBRO;        
        este=data.COMERCIOS[item].ESTE;
        norte=data.COMERCIOS[item].NORTE;
        rubro_id=data.COMERCIOS[item].RUBRO_ID;
        nombre_rubro=data.COMERCIOS[item].NOMBRE_RUBRO;
        correlativo=data.COMERCIOS[item].CORRELATIVO;
        nombre_rubro = data.COMERCIOS[item].NOMBRE_RUBRO;
        encuesta_id = data.COMERCIOS[item].ENCUESTA_ID;                       
        mantisa_rut = data.COMERCIOS[item].MANTISA_RUT;
        dv_rut = data.COMERCIOS[item].DV_RUT;
        direccion = data.COMERCIOS[item].TIPO_VIA + " " + data.COMERCIOS[item].NOMBRE_VIA + " " + data.COMERCIOS[item].ALTURA;
        comuna = data.COMERCIOS[item].COMUNA;
        IniciarMapaComercioDesdeServlet(longitud,latitud,color_rubro,nombre_rubro,encuesta_id,correlativo,mantisa_rut,dv_rut,direccion,comuna,rubro_id);

        item++;
    }   
    
    //Cargando(0);   
    
}
var popup_comercio;
function IniciarMapaComercioDesdeServlet(x,y,color_rubro,nombre_rubro,encuesta_id,correlativo,mantisa_rut,dv_rut,direccion,comuna,rubro_id) {  
    //    debugger;
    var tag;
    var titulo;    
    var LonLat1;    
    var sizeIcon;
    var offset;
    var iconObj;
    var iconObjTitle;
    var tmp1,tmp2;
    var lonlat = new OpenLayers.LonLat(x,y);  
    //debugger;
    //Valida que se muestren solamente los rubros seleccionados
    if (!ValidarRubros(rubro_id)){
        tmp1 =document.getElementById("idQueryNoRubros").value;
        tmp2 = rubro_id + ',';
        tmp1 = tmp1.replace(tmp2,'');
        document.getElementById("idQueryNoRubros").value = tmp1;
        document.getElementById("idQueryNoRubros").value = rubro_id + "," + document.getElementById("idQueryNoRubros").value;
        return;
    }    
   
    w = 20;
    h = 20;    
    //debugger;
    //imagenComercio = "./imgs/imagesCenso/comercios/" + imagenComercio;
    //imagenComercio = "./imgs/imagesCenso/comercios/colores/general.gif";
    //imagenComercio = "./imgs/imagesCenso/Mapa/bt.gif";
    imagenComercio = "./imgs/imagesCenso/Mapa/estrellanew.gif";
    
    icon = imagenComercio;
    LonLat1= new OpenLayers.LonLat(x,y);      
    sizeIcon = new OpenLayers.Size(w,h);
    offset = new OpenLayers.Pixel(-(w/2),-(h/2));
    iconObj = new OpenLayers.Icon(icon,sizeIcon,offset);
    markerComercio = new OpenLayers.Marker(LonLat1,iconObj);    
    markers_busqueda.addMarker(markerComercio);              
    //markers_busqueda.setZIndex(15011);
    /*
    w = 52;
    h = 21;    
    icon = "./imgs/imagesCenso/Mapa/leyenda.gif";
    LonLat1= new OpenLayers.LonLat(x,y);  
    sizeIcon = new OpenLayers.Size(w,h);
    offset = new OpenLayers.Pixel(-(w/2),-(h/2));
    iconObjTitle = new OpenLayers.Icon(icon,sizeIcon,offset);    
    markerComercio = new OpenLayers.Marker(LonLat1,iconObjTitle);
    markers_busqueda.addMarker(markerComercio);              
     */
        
    try{
        //colocamos el color a rgb
        color_rubro = color_rubro.replace(" ",",");
        color_rubro = color_rubro.replace(" ",",");
        color_rubro = color_rubro.replace(" ",",");
        color_rubro = "rgb(" + color_rubro + ")";
    }catch(e){
        alert(e.message);
    }
    
    
    leftId = encuesta_id.length + 10;
    leftId = "-" + leftId + "px";
    espacio = "&nbsp;";
    
    titulo = "";
    info = "<span><img align=left width='25px' height='25px' src='./imgs/imagesCenso/simbolos/iconoCENSO.gif' ></span>";
    info += "<span>";    
    info += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";    
    info += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";    
    info += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";    
    info += "ID: " + encuesta_id + "<br>&nbsp;<br>";    
    info += "Rubro: " + nombre_rubro + "<br>";
    info += "Dirección: " + direccion + ", " + comuna +"<br>";
    if (mantisa_rut != ""){
        info += "Rut: " + mantisa_rut + "-" + dv_rut + "<br>";
    }else{
        //info += "<tr>&nbsp;</tr>";    
    }    
    info += "<br></span>";
        
    info_comercios[correlativo] = info;
    

    Event.observe($(iconObj.imageDiv),'mouseover',function(ev) {
        if(popup_comercio){
            map_2_0.removePopup(popup_comercio);
        }
        var html = info_comercios[correlativo];
        popup_comercio = new OpenLayers.Popup.FramedCloud('id_popupFramedCloud',lonlat,null,html,null,true);
    
        var sDisplayTimerPopPub = setTimeout("map_2_0.addPopup(popup_comercio)", 750);
    
        Event.stop(ev);

    } );          

 

    Event.observe($(iconObj.imageDiv),'mouseout',function(ev) {

        var sDisplayTimerPopPub = setTimeout("map_2_0.removePopup(popup_comercio)", 1000);

        Event.stop(ev);

    } );          

 
    
     
    
    if (EsIE()) {
        //alert("IE");
        var objPixel = map_2_0.getPixelFromLonLat(LonLat1);
        v_left = objPixel.x;
        v_top = objPixel.y;    
        v_left = v_left + 10;
        v_top = v_top - 20;            
          /*linea antigua para pintar popup*/
        //tag = "<div class= 'labelComercios' ><table border=0 width=60px class=TablaInfoToolTip  ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
        tag = "<div class= 'labelComercios' ><table border=0 width=60px class=TablaInfoToolTip  ><tr><td title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
        //tag = "INFO";         
        var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);            
        element.setStyle({ opacity: '0.9',cursor:'pointer'});       
        $(iconObj.imageDiv).insert(element, { position: "content" });	  
        //$('divMapaMain').insert(element, { position: "content" });	          
        
    }else{
        //alert("FireFox");
        /*
        tag = "<div style='z-index:20002;'><table border=0 width=60px class=TablaInfoToolTip ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
        var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);        
        element.setStyle({ position: 'absolute',left: '18px',top: '-10px',opacity: '0.9',cursor:'pointer'});       
        $(iconObj.imageDiv).insert(element, { position: "content" });	               
         */        
        //tag = "<div style='z-index:20002;'><table border=0 width=60px class=TablaInfoToolTip ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
        tag = "<div style='z-index:20002;'><table border=0 width=60px class=TablaInfoToolTip ><tr><td title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
        var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);        
        element.setStyle({ position: 'absolute',left: '18px',top: '-10px',opacity: '0.9',cursor:'pointer'});       
        $(iconObj.imageDiv).insert(element, { position: "content" });	               
        
    }    










    /*
    //tag = "<div style='z-index:20002;'><table border=0 width=60px class=TablaInfoToolTip ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
    //var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);        
    //element.setStyle({ position: 'absolute',left: '18px',top: '-10px',opacity: '0.9',cursor:'pointer'});       
    //$(iconObj.imageDiv).insert(element, { position: "content" });	  
    
    var objPixel = map_2_0.getPixelFromLonLat(LonLat1);
    v_left = objPixel.x;
    v_top = objPixel.y;    
    //tag = "<div style='z-index:30005;position:absolute;top:100px;left:100px'><table border=0 width=60px class=TablaInfoToolTip ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
    tag = "<div style='position:absolute;top:100px;left:100px'><table border=0 width=60px class=TablaInfoToolTip ><tr><td onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' align=center height=20px>" + encuesta_id + espacio + "</td></tr></table></div>";         
    var element = new Element('span', { 'class':'etiquetaComercios'}).update(tag);            
    element.setStyle({ opacity: '0.9',cursor:'pointer'});       
    $('divMapa').insert(element, { position: "content" });	  
    
    tag = "<span onMouseOver=MostrarInformacion(" + x + "," + y + "," + correlativo + ");  onmouseout=OcultarInformacion(); title = '" + titulo + "' alt = '" + titulo + "' onclick='CentrarMapa(" + x + "," + y + ",12);OcultarInformacion();' style='color:" + color_rubro + ";' >" + encuesta_id + "</span>";     
    var elementTitle = new Element('span', { 'class':'etiquetaComercios'}).update(tag);        
    //element.setStyle({ position: 'absolute',left: leftId,top: '0px',opacity: '0.9',cursor:'pointer'});    
    elementTitle.setStyle({ position: 'absolute',left: '50px',top: '50px',opacity: '0.9',cursor:'pointer'});        
    $(iconObjTitle.imageDiv).insert(elementTitle, { position: "content" });	  

    //$(iconObjTitle.imageDiv).setStyle({ position: 'absolute',left: left_tool_tip,top: top_tool_tip,opacity: '0.9'});        
     */

}//end function 

function ValidarRubros(rubro_id){
    //    debugger;
    var cantidadRubrosDistintos;
    var objRubro;
    var resultado=true;

    cantidadRubrosDistintos = document.getElementById("idCantidadRubrosDistintos").value;      
    objRubro = document.getElementById("check_" + rubro_id);        
    if (objRubro.checked){
        resultado=true;
    }        
    return resultado;
    
}

function MostrarInformacion(x,y,correlativo){    
    var objPixel,html,div,pixTop,pixLeft;
    var html,left,top;
    
    try{
        html = info_comercios[correlativo];
        var LonLat= new OpenLayers.LonLat(x,y);                                                         
        var objPixel = map_2_0.getPixelFromLonLat(LonLat);

        left = objPixel.x;
        top = objPixel.y;
        
        //alert("left:" + left + " top:" + top);
        
        top = top + 2;
        left = left + 10;
        pixTop = top + "px";
        pixLeft = left + "px";

        div = $('divMuestraInfo');
        //div.innerHTML = html;    

        var element = new Element('span', { 'class':'tooltip_ol','id':'effect-busqueda'} ).update("<span class='top'></span><span class='center'>" + html + "</span><span class='bottom'></span>");

        $('divMuestraInfo').insert(element, { position: "content" });	  

        document.getElementById("divMuestraInfo").style.top = pixTop;        
        document.getElementById("divMuestraInfo").style.left = pixLeft;        
        document.getElementById("divMuestraInfo").style.visibility = 'visible';            
        
    }catch(e){
        alert("Se ha producido un error: " + e.message);
    }
    
}

function OcultarInformacion(){
    div = $('divMuestraInfo');
    div.innerHTML = "";    
    cerrar_tool_busqueda("effect-busqueda");
    document.getElementById("divMuestraInfo").style.visibility = 'hidden';        
    
}

function cerrar_tool_busqueda(tool){
    if($(tool)) $(tool).remove()
}
         
//Función TRIM
function Trim( str ) {
    var resultStr = "";

    resultStr = str.replace(/^\s*|\s*$/g,"");

    return resultStr;
}

function PintarComercio(puntox,puntoy,texto,codColorEsfera) {    
    var stroke=2; /*stroke*/   
    var tamEsfera=14;
    
    //puntox = 300;
    //puntoy = 300;                              
    puntox = puntox - (tamEsfera / 2);                
    puntoy = puntoy - (tamEsfera / 2);                
                
    jg.setStroke(1);		
    ///jg.setColor("#FFFF00"); /*amarillo*/
    jg.setColor(codColorEsfera); /*amarillo*/
    jg.fillEllipse(puntox,puntoy,tamEsfera,tamEsfera);

    jg.setColor("#555555");/*plomo*/
    jg.drawEllipse(puntox,puntoy,12,12);


    jg.setColor("#FFFFFF");	/*blanco*/	
    jg.fillRect(puntox - 4,puntoy+14,20,12);

		
    jg.setColor("#555555");/*plomo*/
    jg.drawRect(puntox - 4,puntoy+14,20,12);

    jg.setColor("#000000"); /*negro */
    jg.setFont("arial","14px",Font.BOLD);
		
    if (texto < 10)	delta=0;
    else if ((texto >= 10)&&(texto < 100)) delta=4;
    else if ((texto >= 100)&&(texto < 1000)) delta=8;
		
    jg.drawString(texto,puntox + 3 - delta ,puntoy+12);
                
    jg.paint();
}

function IniMapaPopUp(este,norte,idDireccion){
    alert(este + " " + norte + " " + idDireccion);
}    

function muestraComunaCalzada(){
    if(map_2_0.getLayersByName("ComunasExtent").length!=0){
        map_2_0.getLayersByName("ComunasExtent")[0].clearMarkers();
        
    }
    var opt={ method:'post',onComplete:function(transport){
            var comerciosLayer;
            var objJSON = transport.responseText.evalJSON();
            if(objJSON.status == 200){
                if(map_2_0.getLayersByName("ComunasExtent").length==0){
                    comerciosLayer = new OpenLayers.Layer.Markers("ComunasExtent");
                    map_2_0.addLayer(comerciosLayer);
                }else{
                    comerciosLayer = map_2_0.getLayersByName("ComunasExtent")[0];
                }
		
                objJSON.comunas.each(function(comuna){
                    var w = comuna.nombre.length * 25;
                    var h = 50 ;
                    var lonlat = new OpenLayers.LonLat(comuna.longitud,comuna.latitud);
                    var sizeIcon = new OpenLayers.Size(w,h);
                    var offset = new OpenLayers.Pixel(-(w/2),-(h/2));
                    var iconObj = new OpenLayers.Icon(comuna.foto,sizeIcon,offset);
                    var markerObj = new OpenLayers.Marker(lonlat,iconObj);
                    comerciosLayer.addMarker(markerObj);
                    markerObj.setOpacity(0.5);
                });
            }
        },onFailure:function(){}
    };
    var objBound = map_2_0.getExtent();
    if(map_2_0.getScale()<50000)
        new Ajax.Request('./ServletObtieneLabelComuna?method=comunasPorExtension&xmin='+objBound.left+'&ymin='+objBound.bottom+'&xmax='+objBound.right+'&ymax='+objBound.top,opt);     
}