/* Copyright 2007 Google Inc.
 * All Rights Reserved
 */

/*
 * Main web  client mapping application to view Map databases
 * published by Fusion.
 *
 * optional URL parameters:
 *   ll             : override default initial view latitude & longitude
 *   z              : override default initial zoom level
 *   search_timeout : override default search timeout value
 *   debug          : enables a debug dialog
 */

/*
 * preference constants
 */

var INITIAL_VIEW_LAT = 32.898;
if (typeof(INITIAL_VIEW_LAT_OVERRIDE) != "undefined") {
    if (INITIAL_VIEW_LAT_OVERRIDE > -90 &&
        INITIAL_VIEW_LAT_OVERRIDE < 90) {
        INITIAL_VIEW_LAT = INITIAL_VIEW_LAT_OVERRIDE;
    }
}

var INITIAL_VIEW_LON = -110.39;
if (typeof(INITIAL_VIEW_LON_OVERRIDE) != "undefined") {
    if (INITIAL_VIEW_LON_OVERRIDE > -180 &&
        INITIAL_VIEW_LON_OVERRIDE < 180) {
        INITIAL_VIEW_LON = INITIAL_VIEW_LON_OVERRIDE;
    }
}

var MAX_ZOOM_LEVEL = 23;
if (typeof(MAX_ZOOM_LEVEL_OVERRIDE) != "undefined") {
    if (MAX_ZOOM_LEVEL_OVERRIDE > 0 && MAX_ZOOM_LEVEL_OVERRIDE < MAX_ZOOM_LEVEL)
        MAX_ZOOM_LEVEL = MAX_ZOOM_LEVEL_OVERRIDE;
}

var INITIAL_VIEW_ZOOM = 6;
if (typeof(INITIAL_VIEW_ZOOM_OVERRIDE) != "undefined") {
    if (INITIAL_VIEW_ZOOM_OVERRIDE > 0 &&
        INITIAL_VIEW_ZOOM_OVERRIDE <= MAX_ZOOM_LEVEL) {
        INITIAL_VIEW_ZOOM = INITIAL_VIEW_ZOOM_OVERRIDE;
    }
}

var FUSION_MAP_SERVER = "";
if (typeof(FUSION_MAP_SERVER_OVERRIDE) != "undefined") {
    FUSION_MAP_SERVER = FUSION_MAP_SERVER_OVERRIDE;
}

var FUSION_PATH = FUSION_MAP_SERVER + "/maps/mapfiles/";

SendCategorias      = new Array ("Casa","Negocios","Acantilado","Aeropuerto","Agua Potable","Alquiler De Automóviles","Arco","Área De Natación","Area de Picnic","Arena","Arroyo","Auditorio Pasillo","Auto Club","Bahía","Banca","Banco","Bar","Barra De Arena","Bell","Biblioteca","Bodega","Boliche","Bomberos","Bosque","Bueno","Cabinas","Cabo","Cama Y Desayuno","Campamento","Campo De Golf","Campos Petroleros","Canal","Casa","Cascada","Casino","Cementerio","Centro Comercial","Centro Comunitario","Centro De Esquí","Cine","Ciudad 100K","Ciudad 10K","Ciudad 10M","Ciudad 1M","Ciudad 200K","Ciudad 20K","Ciudad 2M","Ciudad 5 K","Ciudad 500K","Ciudad 50K","Ciudad 5M","Ciudad Desconocido","Ciudad Histórica","Ciudad Lt5K","Ciudad Mediana","Ciudad Pequeña","Comercio Especializado Al Por Menor","Condado","Conducto Crateríco","Cordillera","Corte Geológico","Cráter","Cruce","Cuenca","Cueva","Cumbre","Deporte Airport","Depósito","Dique","Distribuidor","División Política Mayor","División Política Menor","Duchas","Edificio Civil","Edificio","El Cruce De Fronteras","Escenario","Escuela","Escuela","Estación De Policía","Estado","Farmacia","Faro Cuadrado Verde","Faro Triángulo Rojo","Ferrocarril","Flujo De La Lava","Formación Rocas","Garmin Concesionarios","Gasolinera","Géiser","Gimnasio","Glaciar","Gran Ciudad","Grandes Almacenes","Grua","Hito o Lugar Importante","Horn Columna (Geolgia)","Hospital","Hotel de Descanso","Hotel","Iglesia","Información Turismo","Información","Isla","Istmo","Jardin","Lago","Lavado de Automoviles","Llanura","Lugar De Culto","Lugar De Pesca","Maderas","Mar","Marina","Militares","Mina","Mojon","Muebles Para El Hogar","Municipalidad","Museos","Oficina De Correos","Oficina de Gobierno","Paisajes","Pantano","Parada Bus","Parada De Camiones","Parque Temático","Parque","Parqueo Aparcamiento","Patinaje Sobre Hielo","Pendiente","Pilar Arquitectonico","Piscina","Playa","Presa","Primeros Auxilios","Provincia","Puente","Puerto","Rápidos","Reparación De Automóviles","Reserva","Restaurante Alemán","Restaurante Asiatico","Restaurante Barbacoa","Restaurante Británicos","Restaurante Cafeterías","Restaurante Carnes Rojas","Restaurante Chino","Restaurante Comidas Rapidas","Restaurante De América","Restaurante Donas","Restaurante Francés","Restaurante Internacional","Restaurante Italiano","Restaurante Mariscos","Restaurante Mexicano","Restaurante Pizza","Restaurante Soda","Restaurante","Restaurante","Restos","Río","Ropa Venta Al Por Menor","Servicio De Reparación","Servicios Agua y Luz","Servicios De Comunicación","Servicios De Tránsito","Servicios Empresariales","Servicios Personales","Servicios Sociales","Software Venta Al Por Menor","Spot Elevación","Spot Sondeo","Spring","Subdivisión","Supermercado","Teatro","Telecomunicaciones","Teléfono","Tienda para La Casa y El Jardín","Tienda","Tiendas De Conveniencia","Torre","Transporte Terrestre","Tribunales","Túneles","Valle Glaciar","Valle","Zona Controlada","Zona De Buceo","Zona De Peligro","Zona Restringida","Zoológico");

TextCategorias      = new Array ("Aeropuerto","Alquiler De Automóviles","Auditorio","Banco","Bar","Biblioteca","Bomberos","Cama Y Desayuno","Campamento","Campo De Golf","Cascada","Casino","Cementerio","Centro Civil","Centro Comercial","Centro Comunitario","Cine","Ciudad","Cruce","Edificio","Escuela","Estación De Policía","Farmacia","Ferrocarril","Gasolinera","Gimnasio","Grandes Almacenes","Hospital","Hotel","Iglesia","Información","Información Turismo","Lavado de Automóviles","Muebles Para El Hogar","Municipalidad","Museos","Negocios","Oficina De Correos","Oficina de Gobierno","Parque","Parqueo Aparcamiento","Parque Temático","Piscina","Playa","Puente","Puerto","Rápidos","Reparación De Automóviles","Reserva","Restaurante","Restaurante Asiatico","Restaurante Asiático","Restaurante Barbacoa","Restaurante Cafeterías","Restaurante Carnes Rojas","Restaurante Chino","Restaurante Comidas Rapidas","Restaurante De América","Restaurante Italiano","Restaurante Mariscos","Restaurante Mexicano","Restaurante Pizza","Restaurante Soda","Ropa Venta Al Por Menor","Servicio De Reparación","Servicios De Comunicación","Servicios Empresariales","Servicios Personales","Servicios Sociales","Software Venta Al Por Menor","Supermercado","Teatro","Tienda","Transporte Terrestre","Tribunales","Zoológico");
ValueCategorias     = new Array ("Aeropuerto","Alquiler De Automóviles","Auditorio","Banco","Bar","Biblioteca","Bomberos","Cama Y Desayuno","Campamento","Campo De Golf","Cascada","Casino","Cementerio","Centro Civil","Centro Comercial","Centro Comunitario","Cine","Ciudad","Cruce","Edificio","Escuela","Estación De Policía","Farmacia","Ferrocarril","Gasolinera","Gimnasio","Grandes Almacenes","Hospital","Hotel","Iglesia","Información","Información Turismo","Lavado de Automóviles","Muebles Para El Hogar","Municipalidad","Museos","Negocios","Oficina De Correos","Oficina de Gobierno","Parque","Parqueo Aparcamiento","Parque Temático","Piscina","Playa","Puente","Puerto","Rápidos","Reparación De Automóviles","Reserva","Restaurante","Restaurante Asiatico","Restaurante Asiático","Restaurante Barbacoa","Restaurante Cafeterías","Restaurante Carnes Rojas","Restaurante Chino","Restaurante Comidas Rapidas","Restaurante De América","Restaurante Italiano","Restaurante Mariscos","Restaurante Mexicano","Restaurante Pizza","Restaurante Soda","Ropa Venta Al Por Menor","Servicio De Reparación","Servicios De Comunicación","Servicios Empresariales","Servicios Personales","Servicios Sociales","Software Venta Al Por Menor","Supermercado","Teatro","Tienda","Transporte Terrestre","Tribunales","Zoológico");
var cat_array_results = new Array(ValueCategorias.length);
var cat_array_check = new Array(ValueCategorias.length);

TextEspeciales      = new Array ("Guía comercial","Centros comerciales");
ValueEspeciales     = new Array ("Guia","Centro Comercial");
var esp_array_results = new Array(ValueEspeciales.length);
var esp_array_check = new Array(ValueEspeciales.length);

TextGuia      = new Array ("Alquiler De Automóviles","Bancos","Bares","Bibliotecas","Bomberos","Casinos","Cementerios","Centros Civil","Centros Comerciales","Cines","Escuelas","Farmacias","Gasolineras","Gimnasios","Hospitales","Hoteles","Iglesias","Lavado de Automóviles","Muebles Para El Hogar","Municipalidades","Museos","Negocios","Oficinas De Correos","Oficinas de Gobierno","Parqueos","Reparación De Automóviles","Restaurantes","Restaurantes Asiaticos","Restaurantes Asiáticos","Restaurantes Barbacoa","Cafeterías","Restaurantes Carnes Rojas","Restaurantes Chino","Restaurantes Comidas Rapidas","Restaurantes De América","Restaurantes Italiano","Restaurantes Mariscos","Restaurantes Mexicano","Restaurantes Pizza","Restaurantes Sodas","Servicios De Comunicación","Servicios Personales","Supermercados","Teatros","Tiendas","Transportes Terrestre","Tribunales");
ValueGuia     = new Array ("Alquiler De Automóviles","Banco","Bar","Biblioteca","Bomberos","Casino","Cementerio","Centro Civil","Centro Comercial","Cine","Escuela","Farmacia","Gasolinera","Gimnasio","Hospital","Hotel","Iglesia","Lavado de Automóviles","Muebles Para El Hogar","Municipalidad","Museos","Negocios","Oficina De Correos","Oficina de Gobierno","Parqueo Aparcamiento","Reparación De Automóviles","Restaurante","Restaurante Asiatico","Restaurante Asiático","Restaurante Barbacoa","Restaurante Cafeterías","Restaurante Carnes Rojas","Restaurante Chino","Restaurante Comidas Rapidas","Restaurante De América","Restaurante Italiano","Restaurante Mariscos","Restaurante Mexicano","Restaurante Pizza","Restaurante Soda","Servicios De Comunicación","Servicios Personales","Supermercado","Teatro","Tienda","Transporte Terrestre","Tribunales");

var guia_array_results = new Array(ValueGuia.length);
var guia_array_check = new Array(ValueGuia.length);

var TAG1_NAME = "Comercial";
var TAG2_NAME = "Galería";
var TAG3_NAME = "Acciones";


//CREADOS POR RICARDO FRANCO
var FUSION_FRAME_LAYERS_NAME = "Capas";
var FUSION_FRAME_MYPLACES_NAME = "Mis lugares";
var FUSION_FRAME_SEARCHRESULT_NAME = "Resultados";
var FUSION_FRAME_INTEREST_POINT = "Categorías de interés";
var FUSION_FRAME_ESPECIALES = "Especiales";
var FUSION_FRAME_GUIA = "Guía comercial";
var MAPBOUNDS_RESTRICTION_PLACE_SEARCH = false;
var FUSION_POST_PRINT = false;

// how long to wait (in milliseconds) before determining the search failed
var SEARCH_TIMEOUT = 45000;  // 30 seconds seems OK

/*
 * interface to add additional tile layers
 */
var layer_manager = null;
var indexarraycolorpoly=0;
var limitadd=4;//limite para agregar puntos en el ruteo 
var arraycolorpoly = new Array ("#0000ff","#00FF00","#ff0000","#00ffff","#FF00FF");

var costo= 0; // distancia de la ruta
/*
 * the Google Fusion Maps API object
 */
var gmap;
var cerca_results = null;
var sidepanel_docker;
var search_manager = null;
var DebugMsg = null;
var placemark_manager = null;

var interest_point_manager = null;
var guia_manager = null;
var especiales_manager = null;

//CREADOS POR RICARDO FRANCO
var large_map_control = null;
var scale_control = null;
var zcontrol = null;

var iTimer;
var sidepanel_real_width = 380;

// allow user to override the default search timeout
// this could be useful when debugging slow network connections
// for example, append "?search_timeout=10000" on URL for 10 second timeout
var search_timeout = SEARCH_TIMEOUT;
// override with "?ll=32.898,-100.30" on URL
var initial_view = new GLatLng(INITIAL_VIEW_LAT, INITIAL_VIEW_LON);
// override with "?z=8" on URL
var initial_zoom = INITIAL_VIEW_ZOOM;

var results_container;

var banderaguardarpunto = 0;
var nombreguardarpunto = "";
var cfg= null;
var point= null;


// Global variables dibujar lineas poligonos
//var mapdiv = document.getElementById("gmap");
//var map;
var poly;
var count = 0;
var pointslp = new Array();
var markers = new Array();
var icon_url ="/maps/gnresources/";
var tooltip;
var lineColor = "#0000af";
var fillColor = "#335599";
var lineWeight = 3;
var lineOpacity = .8;
var fillOpacity = .2;
var tipodibujo;


// === The basis of the arrow icon information ===
var arrowIcon = new GIcon();
arrowIcon.iconSize = new GSize(14,14);
//arrowIcon.shadowSize = new GSize(1,1);
arrowIcon.iconAnchor = new GPoint(7,7);
//arrowIcon.infoWindowAnchor = new GPoint(0,0);
      
// === Returns the bearing in degrees between two points. ===
// North = 0, East = 90, South = 180, West = 270.
var degreesPerRadian = 180.0 / Math.PI;
var overlay_direction = [];
      
      

function formatSearchTerm(term) {
    /*
    term = term.replace(/á/gi,"a");
    term = term.replace(/é/gi,"e");
    term = term.replace(/í/gi,"i");
    term = term.replace(/ó/gi,"o");
    term = term.replace(/ú/gi,"u");
    term = term.replace(/ñ/gi,"n");
     */

    return term;
}
var cadena = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        arreglar = string.split('+');
        arreglar = arreglar.join(' ');
        return this._utf8_decode(unescape(arreglar));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function recuperarParametro( campo ) {

    var RE = new RegExp("[&?]" + campo + "=([^&]*)&");

    var href = location.href + "&";

    if( RE.test(href) ) {
        RE.exec(href);
        return unescape(RegExp.$1);
    }
    return false
}
ControlTipoMapa.prototype = new GControl();

ControlTipoMapa.prototype.initialize = function(gmap) {
    var container = document.createElement("div");

    var NormalDiv = document.createElement("a");
    this.setButtonStyle_(NormalDiv);

    container.appendChild(NormalDiv);
    NormalDiv.appendChild(document.createTextNode("Mapa"));
    GEvent.addDomListener(NormalDiv, "click", function() {
        gmap.addMapType(G_PHYSICAL_MAP);
        gmap.removeMapType(G_SATELLITE_MAP);

    });

    var SateliteDiv = document.createElement("a");
    this.setButtonStyle_(SateliteDiv);

    container.appendChild(SateliteDiv);
    SateliteDiv.appendChild(document.createTextNode("Satelite"));
    GEvent.addDomListener(SateliteDiv, "click", function() {
        gmap.addMapType(G_SATELLITE_MAP);
        gmap.removeMapType(G_PHYSICAL_MAP);
    });

    gmap.getContainer().appendChild(container);
    container.style.marginTop = "10px";
    return container;
}

ControlTipoMapa.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT);
}

ControlTipoMapa.prototype.setButtonStyle_ = function(button) {
    // button.style.textDecoration = "underline";

    button.style.color = "black";
    button.style.backgroundColor = "white";
    button.style.font = "small Arial";
    button.style.border = "1px solid black";
    button.style.padding = "1px";
    button.style.marginBottom = "2px";
    button.style.marginRight = "3px";
    button.style.textAlign = "center";
    button.style.width = "4em";
//button.style.cursor = "pointer";
}

function ControlTipoMapa() {
}

function CambioMapa() {
    gmap.removeMapType(G_PHYSICAL_MAP);
    gmap.removeMapType(G_HYBRID_MAP);
    gmap.removeMapType(G_NORMAL_MAP);
    gmap.addMapType(G_SATELLITE_MAP);

}

function LoadMap() {

    InitBaseIcon();
    Login();
    var fusionmap_elem = FindElement("fusion_map");
    if (!fusionmap_elem) {
        alert("Cannot initialize map!  HTML document is corrupt.");
        return;
    }

    if (GetPageURLParameter("ll")) {
        var latlng = GetPageURLParameter("ll").split(',');

        if (latlng.length == 2) {

            initial_view = new GLatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));

        }
    }

    // Get the default view if the initial view is not already initialized.
    if (initial_view == 0)
        initial_view = new GLatLng(INITIAL_VIEW_LAT, INITIAL_VIEW_LON);

    if (GetPageURLParameter("z")) {
        initial_zoom = parseInt(GetPageURLParameter("z"));
    }

    if (GetPageURLParameter("search_timeout")) {
        search_timeout = GetPageURLParameter("search_timeout");
    }

    if (GBrowserIsCompatible()) {


        // We need a new div element for GMap to own.
        var map_elem = CreateElement(fusionmap_elem, "div", "map");

        gmap = new GFusionMap(map_elem);
        gmap.setCenter(initial_view, initial_zoom);
        gmap.showInitialFusionLayers();

        // enable debug msg dialog if requested
        // to enable debug mode, append "?debug" on URL
        if (GetPageURLParameter("debug")) {
            debug_dialog = new Dialog(fusionmap_elem, "debug_dialog",
                "DEBUG MESSAGES", "600px", "200px");
            debug_dialog.Show();
            debug_dialog.AppendText(navigator.userAgent);
            DebugMsg = function(txt) {
                debug_dialog.AppendText(txt);
            }
        } else {
            DebugMsg = function() {}
        }

        large_map_control = new GLargeMapControl3D();
        scale_control = new GScaleControl();
        zcontrol = setupDragZoom();

        gmap.addControl(zcontrol,new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(sidepanel_real_width+15,250)));
        gmap.addControl(large_map_control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(sidepanel_real_width-5,10)));
        gmap.addControl(scale_control, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(sidepanel_real_width,4)));

        gmap.addControl(new MStatusControl());

        gmap.addControl(new ControlTipoMapa());

        new GKeyboardHandler(gmap);
        //a solicitud de alejandro urbina se desabilida el zoom y se cambia por agregar un punto
        gmap.enableDoubleClickZoom();

        gmap.enableScrollWheelZoom();
        gmap.enableContinuousZoom();
        //click para dibujo de puntos y poligonos
        GEvent.addListener(gmap, "click", leftClick);

        var sidepanel_elem = FindElement("sidepanel");
        if (sidepanel_elem)
            sidepanel_docker = new SidePanel(sidepanel_elem);

        //gmap.addControl(new GMapTypeControl());
        gmap.addControl(new GOverviewMapControl());


        G_SATELLITE_MAP.getMinimumResolution = function(){
            return 3;
        }
        G_PHYSICAL_MAP.getMinimumResolution = function(){
            return 3;
        }

        G_SATELLITE_MAP.getMaximumResolution = function(){
            return 18;
        }
        G_PHYSICAL_MAP.getMaximumResolution = function(){
            return 18
        };

        Resize();
        placemark_manager = new PlacemarkManager(fusionmap_elem);

        InitializeDirSearch(fusionmap_elem);
        InitializeSearch(fusionmap_elem);
        InitializeLayers(fusionmap_elem);
        interest_point_manager = new Interest_Point_Manager(fusionmap_elem);
        //especiales_manager = new Especiales_Manager(fusionmap_elem);
        esp_array_results[0] = new SearchManager(FindElement("fusion_map"));


        guia_manager = new Guia_Manager(fusionmap_elem);
        CambioMapa();
    //if (place_search_manager) GEvent.addListener(gmap, "moveend", function(){ place_search_manager.RefreshGeomLines(); });
    }

    var search_term  = FindElement("SearchTerm").value;

    if ( search_term != undefined && search_term != "") {

        SubmitSearch();

    }

    if (GetPageURLParameter("etiqueta") ) {
        if (latlng.length == 2) {
            var marker = new GMarker(new GLatLng(parseFloat(latlng[0]), parseFloat(latlng[1])));
            //gmap.addOverlay(marker);
            placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),recuperarParametro("etiqueta"));
            gmap.removeOverlay(marker);
        }
    }
    if (GetPageURLParameter("bdirecta") ) {
        FindElement("SearchTerm").value = "\""+recuperarParametro("bdirecta")+"\"";
        SubmitSearch();
    }
 _tsSITIO = escape("Nacion-Mapas");
    _tsROOT = "http://appmapas.nacion.co.cr/tschat/";
    tsTrackPage(true);
}
var WindowObjectReference = null; // POPUP

function bearing( from, to ) {
    // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
    // Convert to radians.
    var lat1 = from.latRadians();
    var lon1 = from.lngRadians();
    var lat2 = to.latRadians();
    var lon2 = to.lngRadians();

    // Compute the angle.
    var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
    if ( angle < 0.0 )
        angle  += Math.PI * 2.0;

    // And convert result to degrees.
    angle = angle * degreesPerRadian;
    angle = angle.toFixed(1);

    return angle;
}
       
// === A function to create the arrow head at the end of the polyline ===
function arrowHead(points) {
    // == obtain the bearing between the last two points
    var p1=points[points.length-1];
    var p2=points[points.length-2];
    var dir = bearing(p2,p1);
    // == round it to a multiple of 3 and cast out 120s
    var dir = Math.round(dir/3) * 3;
    while (dir >= 120) {
        dir -= 120;
    }
    // == use the corresponding triangle marker
    arrowIcon.image = "http://www.google.com/intl/en_ALL/mapfiles/dir_"+dir+".png";
    overlay_direction.push(new GMarker(p1, arrowIcon));
    gmap.addOverlay(overlay_direction[overlay_direction.length-1]);
}
      
// === A function to put arrow heads at intermediate points
function midArrows(points) {
    for (var i=1; i < points.length-1; i+=30) {
        var p1=points[i-1];
        var p2=points[i+1];
        var dir = bearing(p1,p2);
        // == round it to a multiple of 3 and cast out 120s
        var dir = Math.round(dir/3) * 3;
        while (dir >= 120) {
            dir -= 120;
        }
        // == use the corresponding triangle marker
        arrowIcon.image = "http://www.google.com/intl/en_ALL/mapfiles/dir_"+dir+".png";
        overlay_direction.push(new GMarker(points[i], arrowIcon))
        gmap.addOverlay(overlay_direction[overlay_direction.length-1]);
    }
}

function setupDragZoom() {
    var styleOpts = {};
    var otherOpts = {};
    styleOpts.opacity = 0.5;
    //styleOpts.border = '3px solid blue';
    otherOpts.backButtonEnabled = true;
    otherOpts.buttonHTML = '<img src=/maps/gnresources/zoomdeactivate2.png />';
    otherOpts.backButtonHTML = '<img src=/maps/gnresources/zoomreturn.png />';
    otherOpts.buttonZoomingHTML = '<img src=/maps/gnresources/zoomactivate2.png />';
    otherOpts.overlayRemoveTime= 1;

    otherOpts.backButtonStyle = {
        display: 'none',
        background: '#FFF'
    };
    otherOpts.buttonStyle = {
        background: '#FFF'

    };
    otherOpts.buttonStartingStyle = {
        width: '19px',
        height: '19px'

    };
    otherOpts.buttonZoomingStyle = {
        background: '#FFF'

    };
    var zcon = new DragZoomControl(styleOpts, otherOpts, {});
    return zcon
}

//CREADO POR RICARDO FRANCO
function OpenPrintWindow(strUrl) {
    strUrl += "?ll="+gmap.getCenter()+"&z="+gmap.getZoom();
    strUrl = strUrl.replace("(","").replace(")","").replace(" ","");

    if (FUSION_POST_PRINT) {
        var form = CreateElement(FindElement("fusion_map_toolbar"),"form");
        form.style.display = "none";
        form.action = strUrl;
        form.target = "_black";
        form.method = "POST";
        var inputP = CreateInputElement(form,"text");
        inputP.name = "points";
        inputP.id = "points";
        inputP.value = place_search_manager.GetEncodedPoints();
        var inputL = CreateInputElement(form,"text");
        inputL.name = "levels";
        inputL.id = "levels";
        inputL.value = place_search_manager.GetEncodedLevels();
        form.submit();
        form.parentNode.removeChild(form);
    } else {
        if (place_search_manager.GetEncodedPoints() && place_search_manager.GetEncodedLevels())
            strUrl += "&points="+place_search_manager.GetEncodedPoints()+"&levels="+place_search_manager.GetEncodedLevels();
        if(WindowObjectReference == null || WindowObjectReference.closed)
        {
            WindowObjectReference = window.open(strUrl, "Imprimir","menubar=no,location=no,resizable=no,scrollbars=yes,status=yes,width=725,height=625");
            WindowObjectReference.focus();
        } else {
            alert("Ya tiene una ventana de impresión abierta, gracias.");
        }
    }
}

//CREADO POR RICARDO FRANCO
function LoadMapPrint() {

    InitBaseIcon();

    var fusionmap_elem = FindElement("fusion_map");
    if (!fusionmap_elem) {
        alert("Cannot initialize map!  HTML document is corrupt.");
        return;
    }

    if (GetPageURLParameter("ll")) {
        var latlng = GetPageURLParameter("ll").split(',');
        if (latlng.length == 2) {
            initial_view = new GLatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
        }
    }
    // Get the default view if the initial view is not already initialized.
    if (initial_view == 0)
        initial_view = new GLatLng(INITIAL_VIEW_LAT, INITIAL_VIEW_LON);

    if (GetPageURLParameter("z")) {
        initial_zoom = parseInt(GetPageURLParameter("z"));
    }

    if (GetPageURLParameter("search_timeout")) {
        search_timeout = GetPageURLParameter("search_timeout");
    }

    var points = null;
    var levels = null;
    if (window.location.href.indexOf("&points=") >= 0) {
        var geom_parms = window.location.href.split("&points=")[1];
        points = unescape(geom_parms.split("&levels=")[0]);
        levels = unescape(geom_parms.split("&levels=")[1]);
    }

    if (GBrowserIsCompatible()) {
        // We need a new div element for GMap to own.
        var map_elem = CreateElement(fusionmap_elem, "div", "map");
        gmap = new GFusionMap(map_elem);
        gmap.setCenter(initial_view, initial_zoom);
        gmap.showInitialFusionLayers();

        gmap.enableDoubleClickZoom();
        gmap.addControl(new GSmallZoomControl3D());
        gmap.addControl(new GScaleControl());
        gmap.addControl(new ControlTipoMapa());
        gmap.enableScrollWheelZoom();
        gmap.enableContinuousZoom();
        CambioMapa();

        G_SATELLITE_MAP.getMinimumResolution = function(){
            return 3;
        }
        G_PHYSICAL_MAP.getMinimumResolution = function(){
            return 3;
        }

        G_SATELLITE_MAP.getMaximumResolution = function(){
            return 18;
        }
        G_PHYSICAL_MAP.getMaximumResolution = function(){
            return 18
        };


        //Verificar si viene la linea en el url
        if (points && levels) {
            place_search_manager = new PlaceSearchManager(gmap);
            place_search_manager.SetEncodedPoints(points);
            place_search_manager.Points(points);
            place_search_manager.SetEncodedLevels(levels);
            place_search_manager.DrawGeom();
        }
    //window.print();
    }
}

//MODIFICADA POR RICARDO FRANCO
function Resize() {
    var new_height = -1;
    var new_width = -1;

    var header_elem = FindElement("header_bar");
    var sidepanel_elem = FindElement("sidepanel");

    if (!IsBrowser("MSIE")) {   // Firefox, Safari, etc.
        new_height = document.body.clientHeight - parseInt(GetElementStyle(header_elem, "height"));
        new_width = document.body.clientWidth;
        DebugMsg("Firefox -> w,h:" + new_width + ", " + new_height);
    } else {                    // MSIE
        new_height = document.body.clientHeight - parseInt(header_elem.currentStyle.height);
        new_width = document.body.clientWidth;
        DebugMsg("MSIE w,h:" + new_width + ", " + new_height);
    }

    FindElement("fusion_map").style.height = new_height + "px";
    FindElement("fusion_map").style.width = new_width + "px";

    if (sidepanel_elem)
        sidepanel_elem.style.height = new_height + "px";
}

//CREADO POR RICARDO FRANCO
function ToogleSidePanel()
{
    sidepanel_elem = FindElement("sidepanel");
    if (!IsBrowser("MSIE")) {   // Firefox, Safari, etc.
        sidepanel_visibility = GetElementStyle(sidepanel_elem, "visibility");
    } else {                    // MSIE
        sidepanel_visibility = sidepanel_elem.currentStyle.visibility;
    }
    if (sidepanel_visibility  == "visible") {
        HideSidePanel();
    } else {
        ShowSidePanel();
    }
}

//CREADO POR RICARDO FRANCO
function HideSidePanel() {
    sidepanel_elem = FindElement("sidepanel");
    if (!IsBrowser("MSIE")) {   // Firefox, Safari, etc.
        sidepanel_width = parseInt(GetElementStyle(sidepanel_elem, "width"));
    } else {                    // MSIE
        sidepanel_width = parseInt(sidepanel_elem.currentStyle.width);
    }
    if (sidepanel_width > 0) {
        if (sidepanel_width < 50) {
            sidepanel_elem.style.width = "0px";
        } else {
            sidepanel_elem.style.width = sidepanel_width - 50 + "px";
        }
        FindElement("sidepanel_top_bar").style.width = sidepanel_elem.style.width;
        iTimer = setTimeout("HideSidePanel()", 10);
    } else {
        clearTimeout(iTimer);
        sidepanel_elem.style.visibility = "hidden";
        FindElement("sidepanel_top_bar").style.visibility = "hidden";
        FindElement("sidepanel_top_bar_buttom").style.backgroundPosition = "bottom";
        gmap.removeControl(zcontrol);
        gmap.removeControl(large_map_control);
        gmap.removeControl(scale_control);
        zcontrol = setupDragZoom();
        gmap.addControl(zcontrol,new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20,250)));
        gmap.addControl(large_map_control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(1,10)));
        gmap.addControl(scale_control, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(4,4)));
    }
}

//CREADO POR RICARDO FRANCO
function ShowSidePanel() {
    sidepanel_elem = FindElement("sidepanel");
    sidepanel_elem.style.visibility = "visible";
    FindElement("sidepanel_top_bar").style.visibility = "visible";
    if (!IsBrowser("MSIE")) {   // Firefox, Safari, etc.
        sidepanel_width = parseInt(GetElementStyle(sidepanel_elem, "width"));
    } else {                    // MSIE
        sidepanel_width = parseInt(sidepanel_elem.currentStyle.width);
    }
    if (sidepanel_width < sidepanel_real_width) {
        if (sidepanel_width + 50 > sidepanel_real_width) {
            sidepanel_elem.style.width = sidepanel_real_width + "px";
            FindElement("sidepanel_top_bar").style.width = sidepanel_real_width - 9 + "px";
        } else {
            sidepanel_elem.style.width = sidepanel_width + 50 + "px";
            FindElement("sidepanel_top_bar").style.width = sidepanel_elem.style.width;
        }
        iTimer = setTimeout("ShowSidePanel()", 10);
    } else {
        clearTimeout(iTimer);
        FindElement("sidepanel_top_bar_buttom").style.backgroundPosition = "top";
        gmap.removeControl(zcontrol);
        gmap.removeControl(large_map_control);
        gmap.removeControl(scale_control);
        zcontrol = setupDragZoom();
        gmap.addControl(zcontrol,new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(sidepanel_real_width + 15,250)));
        gmap.addControl(large_map_control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(sidepanel_real_width-5,10)));
        gmap.addControl(scale_control, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(sidepanel_real_width,4)));
    }
}

function InitializeLayers(parent) {
    // if we can find a sidepanel element, place the layer controls in it
    // otherwise, create a floating dialog
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_LAYERS_NAME);
        layer_manager = new GF_Layers(pane.GetBodyDiv());
        pane.Show();
    } else {
        var layers_dialog = new Dialog(parent, "layers_dialog", FUSION_FRAME_LAYERS_NAME);
        layers_dialog.Show();
        layer_manager = new GF_Layers(layers_dialog.GetBodyDiv());
    }

    // fusion built layers
    var layer_count = gmap.getFusionLayerCount();
    if (layer_count > 0) {
        for (var lyr = 0; lyr < layer_count; ++lyr) {
            layer_manager.AddLayer(gmap.getFusionLayerName(lyr),
                gmap.getFusionLayerIcon(lyr),
                gmap.isFusionLayerVisible(lyr),
                FusionCheckLayerToggle(lyr),
                "checkbox");
        }
    }
}

function FusionCheckLayerToggle(layerId) {
    return function() {        
        if (layerId=='1' && gmap.isFusionLayerVisible(layerId))
        {
            if (!gmap.isFusionLayerVisible('0'))
                gmap.showFusionLayer('0');
            if (!gmap.isFusionLayerVisible('2'))
                gmap.showFusionLayer('2');
            document.getElementById("Rios").checked=true;
            document.getElementById("Calles").checked=true;
        }
        if (layerId=='1' && !(gmap.isFusionLayerVisible(layerId)))
        {
            if (gmap.isFusionLayerVisible('0'))
                gmap.hideFusionLayer('0');
            if (gmap.isFusionLayerVisible('2'))
                gmap.hideFusionLayer('2');
            document.getElementById("Rios").checked=false;
            document.getElementById("Calles").checked=false;
        }

        if (gmap.isFusionLayerVisible(layerId))
            gmap.hideFusionLayer(layerId);
        else
            gmap.showFusionLayer(layerId);
    };
}

function FusionRadioLayerToggle(layerId) {
    return function() {
        var layer_count = gmap.getFusionLayerCount();
        for (var lyr = 0; lyr < layer_count; ++lyr) {
            if (lyr != layerId) {
                gmap.hideFusionLayer(lyr);
            }
        }
        gmap.showFusionLayer(layerId);
    };
    
}

function StartLoading() {
    var loading_msg = FindElement("loader");
    if (loading_msg) {
        loading_msg.innerHTML ="Cargando...";
        loading_msg.style.visibility = 'visible';
    }
}

function EndLoading() {
    var loading_msg = FindElement("loader");
    if (loading_msg) {
        loading_msg.style.visibility = 'hidden';
    }
}

/******************************************************************************
 * Context Menu // CREADO POR RICARDO FRANCO
 ******************************************************************************/

function ContextMenu(oMap){
    this.initialize(oMap);
}

//Construct the DOM tree of the menu
ContextMenu.prototype.initLink = function(oMap){

    var that=this;

    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Buscar Puntos Cerca  </a>";
    
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        that.map.panTo(point);
        SubmitSearchCerca(point);
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Crear Punto  </a>";
    GEvent.addDomListener(a_link, 'click', function() {

        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        placemark_manager.NewPlacemarkAtPoint(point,"");
        point = null;
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Crear Líneas  </a>";
    GEvent.addDomListener(a_link, 'click', function() {

        tipodibujo = true;
        document.getElementById("status").style.visibility = 'visible'
        toggleMode();
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Crear Polígonos  </a>";
    GEvent.addDomListener(a_link, 'click', function() {

        tipodibujo = false;
        document.getElementById("status").style.visibility = 'visible'
        toggleMode();
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.className = "separator";
    a_link.innerHTML="<a href='javascript:void(0);'> Ruta desde aquí  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        var id = firstItem();
        showDirSearch();
        if (id) {
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(point, point.y+", "+point.x, id, false);
            //if (FindElement("A").value && FindElement("B").value){
            if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                SubmitDirSearch();
            }
        }
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);
    
    
        
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Ruta hasta aquí  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        var id = lastItem();
        showDirSearch();
        if (id) {
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(point, point.y+", "+point.x, id, false);
            //if (FindElement("A").value && FindElement("B").value){
            if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                SubmitDirSearch();
            }
        }
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Añadir destino aquí  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        AddDirSearch();
        var id = lastItem();
        showDirSearch();
        if (id) {
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(point, point.y+", "+point.x, id, false);

            SubmitDirSearch();

        }
        that.contextmenu.style.display='none';
    });

    this.ul_container.appendChild(a_link);
    a_link = document.createElement("li");
    a_link.className = "separator";
    a_link.innerHTML="<a href='javascript:void(0);'> Ampliar  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        that.map.zoomIn(point,true);
        that.contextmenu.style.display="none";
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'> Reducir  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        that.map.zoomOut();
        that.contextmenu.style.display='none';
    });
    this.ul_container.appendChild(a_link);

    a_link = document.createElement("li");
    a_link.className = "separator";
    a_link.innerHTML="<a href='javascript:void(0);'> Centrar el mapa aquí  </a>";
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
        that.map.panTo(point);
        that.contextmenu.style.display="none";
    });
    this.ul_container.appendChild(a_link);
}

ContextMenu.prototype.bind = function(method) {
    var self = this;
    var opt_args = [].slice.call(arguments, 1);
    return function() {
        var args = opt_args.concat([].slice.call(arguments));
        return method.apply(self, args);
    }
}

//The object 'constructor'
ContextMenu.prototype.initialize = function(oMap){
    this.map = oMap;
    var that=this;

    this.contextmenu = document.createElement("div");
    this.contextmenu.style.display="none";
    //CSS class name of the menu
    this.contextmenu.className="contextmenu";
    this.ul_container = document.createElement("ul");
    this.ul_container.id="context_menu_ul";
    this.contextmenu.appendChild(this.ul_container);
    this.initLink();
    this.map.getContainer().appendChild(this.contextmenu);

    //Event listeners that will interact with our context menu
    GEvent.addListener(oMap,"singlerightclick",function(pixel,tile) {
        that.clickedPixel = pixel;
        var x=pixel.x;
        var y=pixel.y;
        //Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
        if (x > that.map.getSize().width - 160) {
            x = that.map.getSize().width - 160
        }
        if (y >that.map.getSize().height - 120) {
            y = that.map.getSize().height - 120
        }

        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
        pos.apply(that.contextmenu);
        that.contextmenu.style.display = "";
    });
    GEvent.addListener(oMap, "move", function() {
        that.contextmenu.style.display="none";
    });
    GEvent.addListener(oMap, "click", function(overlay,point) {
        that.contextmenu.style.display="none";
    });
}

/******************************************************************************
 * Search
 ******************************************************************************/

//MODIFICADO POR RICARDO FRANCO
function InitializeSearch(map_elem) {
    // install 'loading...' status message object
    var loading_msg = CreateElement(document.body, "div", "loader");
    loading_msg.style.visibility = 'hidden';
    loading_msg.appendChild(document.createTextNode("Cargando..."));
    cerca_results = new SearchManager(map_elem);
    search_manager = new SearchManager(map_elem);
}

function SubmitSearchEsp(caterm) {

    var search_term  = caterm;
    if ( search_term == undefined || search_term == "") {
        alert("Por favor, especifique los términos a buscar.");
        return;
    }
    StartLoading();
    var center = gmap.getCenter().x + ", " + gmap.getCenter().y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&categoria="+formatSearchTerm(search_term)+"&center="+center;
    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {
        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }

    //alert (baseUrl);
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandleResultsEsp(results,caterm)
        });
}
function SubmitSearchCerca(point) {

    var search_term  = "cerca";
    if ( search_term == undefined || search_term == "") {
        alert("Por favor, especifique los términos a buscar.");
        return;
    }
    StartLoading();
    var center = point.x + ", " + point.y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&cerca="+formatSearchTerm(search_term)+"&center="+center;
    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {
        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }

    //alert (baseUrl);
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandleResultsCerca(results);
        });
}
function SubmitSearchCat(caterm) {

    var search_term  = caterm;
    if ( search_term == undefined || search_term == "") {
        alert("Por favor, especifique los términos a buscar.");
        return;
    }
    StartLoading();
    var center = gmap.getCenter().x + ", " + gmap.getCenter().y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&categoria="+formatSearchTerm(search_term)+"&center="+center;
    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {
        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }

    //alert (baseUrl);
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandleResultsCat(results,caterm)
        });
}
function SubmitSearchGuia(caterm) {

    var search_term  = caterm;
    if ( search_term == undefined || search_term == "") {
        alert("Por favor, especifique los términos a buscar.");
        return;
    }
    StartLoading();
    var center = gmap.getCenter().x + ", " + gmap.getCenter().y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&guia="+formatSearchTerm(search_term)+"&center="+center;
    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {
        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }

    //alert (baseUrl);
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandleResultsGuia(results,caterm)
        });
}
//MODIFICADO POR RICARDO FRANCO
function SubmitSearch() {
    var search_term  = FindElement("SearchTerm").value;
    if ( search_term == undefined || search_term == "") {
        alert("Por favor, especifique los términos a buscar.");
        return;
    }
    StartLoading();
    var center = gmap.getCenter().x + ", " + gmap.getCenter().y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&place="+formatSearchTerm(search_term)+"&center="+center;
    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {

        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }
    //alert( baseUrl);
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandleResults(results)
        });
}

//MODIFICADO POR RICARDO FRANCO
function HandleResults(reply) {

    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    // cleanup any previous results only if the search was successful
    search_manager.Reset();
    var places_count = 0;

    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);

        if (response.success == false) {
            DebugMsg("[" + r + "] errorMessage: " + response.errorMessage);
        } else {

            if (response.data != undefined) {

                DebugMsg("[" + r + "] data.length: " + response.data.length);
                places_count += (1*response.data.length);
                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];
                    DebugMsg("element # " + d + " raw-->" + data);
                    if (!data || !data.lon)
                        break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon);
                    DebugMsg("--> [" + d + "] lat: " + data.lat);
                    DebugMsg("--> [" + d + "] name: " + data.name);
                    if (data.description)
                        DebugMsg("--> [" + d + "] description: " + data.description);
                    if (data.snippet)
                        DebugMsg("--> [" + d + "] snippet: " + data.snippet);

                    var txt = "";
                    if (data.name)
                        txt += "Name: " + data.name + "<br>";
                    if (data.description){
                        var comercial = (data.description.slice(data.description.indexOf("COMERCIAL"),data.description.length)).split(",");

                        data.description = data.description.slice(0,data.description.indexOf("COMERCIAL"));
                        txt += data.description + "<br>";
                    }
                    search_manager.AddMarker(data,comercial);
                }
            }
        }
    }

    if (places_count == 1) {
        search_manager.GozoomFirstResult();
    }
    else {
        search_manager.GotoFirstResult();
    }

}

function HandleResultsEsp(reply,caterm) {

    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    // cleanup any previous results only if the search was successful
    //search_manager.Reset();
    for (var f = 0; f < ValueEspeciales.length; ++f) {
        if (ValueEspeciales[f] == caterm){
            var g =f;
        }
    }

    esp_array_results[g] = new SearchManager(FindElement("fusion_map"));
    var places_count = 0;

    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);
        if (response.success == false) {
            DebugMsg("[" + r + "] errorMessage: " + response.errorMessage);
        } else {
            if (response.data != undefined) {
                DebugMsg("[" + r + "] data.length: " + response.data.length);
                places_count += (1*response.data.length);

                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];
                    DebugMsg("element # " + d + " raw-->" + data);
                    if (!data || !data.lon)
                        break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon);
                    DebugMsg("--> [" + d + "] lat: " + data.lat);
                    DebugMsg("--> [" + d + "] name: " + data.name);
                    if (data.description)
                        DebugMsg("--> [" + d + "] description: " + data.description);
                    if (data.snippet)
                        DebugMsg("--> [" + d + "] snippet: " + data.snippet);

                    var txt = "";
                    if (data.name)
                        txt += "Name: " + data.name + "<br>";

                    if (data.description){
                        var comercial = (data.description.slice(data.description.indexOf("COMERCIAL"),data.description.length)).split(",");
                        data.description = data.description.slice(0,data.description.indexOf("COMERCIAL"));
                        txt += data.description + "<br>";
                    }

                    esp_array_results[g].AddMarkerCat(data,comercial);
                }
            }
        }
    }

    if (places_count == 1) {
        esp_array_results[g].GozoomFirstResult();
    }
    else {
        esp_array_results[g].GotoFirstResult();
    }
//if (places_count == 1) esp_array_results[g].GotoFirstResult();
//if (places_count > 0) hideDirSearch();
}


function HandleResultsCat(reply,caterm) {

    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    // cleanup any previous results only if the search was successful
    //search_manager.Reset();
    for (var f = 0; f < ValueCategorias.length; ++f) {
        if (ValueCategorias[f] == caterm){
            var g =f;
        }
    }

    cat_array_results[g] = new SearchManager(FindElement("fusion_map"));
    var places_count = 0;

    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);

        if (response.success == false) {
            DebugMsg("[" + r + "] errorMessage: " + response.errorMessage);
        } else {
            if (response.data != undefined) {
                DebugMsg("[" + r + "] data.length: " + response.data.length);
                places_count += (1*response.data.length);
                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];
                    DebugMsg("element # " + d + " raw-->" + data);
                    if (!data || !data.lon)
                        break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon);
                    DebugMsg("--> [" + d + "] lat: " + data.lat);
                    DebugMsg("--> [" + d + "] name: " + data.name);
                    if (data.description)
                        DebugMsg("--> [" + d + "] description: " + data.description);
                    if (data.snippet)
                        DebugMsg("--> [" + d + "] snippet: " + data.snippet);

                    var txt = "";
                    if (data.name)
                        txt += "Name: " + data.name + "<br>";
                    if (data.description){
                        comercial = (data.description.slice(data.description.indexOf("COMERCIAL"),data.description.length)).split(",");
                        data.description = data.description.slice(0,data.description.indexOf("COMERCIAL"));
                        txt += data.description + "<br>";
                    }
                    cat_array_results[g].AddMarkerCat(data,comercial);
                }
            }
        }
    }
    if (places_count == 1) {
        cat_array_results[g].GozoomFirstResult();
    }
    else {
        cat_array_results[g].GotoFirstResult();
    }
//if (places_count == 1) cat_array_results[g].GotoFirstResult();
//if (places_count > 0) hideDirSearch();
}
function HandleResultsCerca(reply) {

    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    // cleanup any previous results only if the search was successful
    cerca_results.Reset();

    var places_count = 0;

    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);

        if (response.success == false) {
            DebugMsg("[" + r + "] errorMessage: " + response.errorMessage);
        } else {
            if (response.data != undefined) {
                DebugMsg("[" + r + "] data.length: " + response.data.length);
                places_count += (1*response.data.length);
                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];
                    DebugMsg("element # " + d + " raw-->" + data);
                    if (!data || !data.lon)
                        break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon);
                    DebugMsg("--> [" + d + "] lat: " + data.lat);
                    DebugMsg("--> [" + d + "] name: " + data.name);
                    if (data.description)
                        DebugMsg("--> [" + d + "] description: " + data.description);
                    if (data.snippet)
                        DebugMsg("--> [" + d + "] snippet: " + data.snippet);

                    var txt = "";
                    if (data.name)
                        txt += "Name: " + data.name + "<br>";
                    if (data.description){
                        comercial = (data.description.slice(data.description.indexOf("COMERCIAL"),data.description.length)).split(",");
                        data.description = data.description.slice(0,data.description.indexOf("COMERCIAL"));
                        txt += data.description + "<br>";
                    }
                    cerca_results.AddMarkerCat(data,comercial);
                }
            }
        }
    }
    if (places_count == 1) {
        cerca_results.GozoomFirstResult();
    }
    else {
        cerca_results.GotoFirstResult();
    }
//if (places_count == 1) cat_array_results[g].GotoFirstResult();
//if (places_count > 0) hideDirSearch();
}
function HandleResultsGuia(reply,caterm) {

    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    // cleanup any previous results only if the search was successful
    //search_manager.Reset();
    for (var f = 0; f < ValueGuia.length; ++f) {
        if (ValueGuia[f] == caterm){
            var g =f;
        }
    }

    guia_array_results[g] = new SearchManager(FindElement("fusion_map"));
    var places_count = 0;

    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);

        if (response.success == false) {
            DebugMsg("[" + r + "] errorMessage: " + response.errorMessage);
        } else {
            if (response.data != undefined) {
                DebugMsg("[" + r + "] data.length: " + response.data.length);
                places_count += (1*response.data.length);
                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];
                    DebugMsg("element # " + d + " raw-->" + data);
                    if (!data || !data.lon)
                        break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon);
                    DebugMsg("--> [" + d + "] lat: " + data.lat);
                    DebugMsg("--> [" + d + "] name: " + data.name);
                    if (data.description)
                        DebugMsg("--> [" + d + "] description: " + data.description);
                    if (data.snippet)
                        DebugMsg("--> [" + d + "] snippet: " + data.snippet);

                    var txt = "";
                    if (data.name)
                        txt += "Name: " + data.name + "<br>";
                    if (data.description){
                        comercial = (data.description.slice(data.description.indexOf("COMERCIAL"),data.description.length)).split(",");
                        data.description = data.description.slice(0,data.description.indexOf("COMERCIAL"));
                        txt += data.description + "<br>";
                    }
                    guia_array_results[g].AddMarkerCat(data,comercial);
                }
            }
        }
    }
    if (places_count == 1) {
        guia_array_results[g].GozoomFirstResult();
    }
    else {
        guia_array_results[g].GotoFirstResult();
    }
//if (places_count == 1) guia_array_results[g].GotoFirstResult();
// if (places_count > 0) hideDirSearch();
}

/******************************************************************************
 * SearchManager class
 ******************************************************************************/

function tildes (string) {

    var utftext = "";
    var sarreglo = string.split('Á');
    utftext = sarreglo.join('A');
    sarreglo = utftext.split('É');
    utftext = sarreglo.join('E');
    sarreglo = utftext.split('Í');
    utftext = sarreglo.join('I');
    sarreglo = utftext.split('Ó');
    utftext = sarreglo.join('O');
    sarreglo = utftext.split('Ú');
    utftext = sarreglo.join('U');
    sarreglo = utftext.split('á');
    utftext = sarreglo.join('a');
    sarreglo = utftext.split('é');
    utftext = sarreglo.join('e');
    sarreglo = utftext.split('í');
    utftext = sarreglo.join('i');
    sarreglo = utftext.split('ó');
    utftext = sarreglo.join('o');
    sarreglo = utftext.split('ú');
    utftext = sarreglo.join('u');
    sarreglo = utftext.split('Ñ');
    utftext = sarreglo.join('N');
    sarreglo = utftext.split('ñ');
    utftext = sarreglo.join('n');
    sarreglo = utftext.split('´');
    utftext = sarreglo.join(' ');
    sarreglo = utftext.split('\'');
    utftext = sarreglo.join(' ');
    return utftext;
}

//MODIFICADO POR RICARDO FRANCO
function SearchManager(map_elem) {
    this.results_map_markers = [];
    this.first_result = null;
    this.open_info_window = false;

    this.showme = null;
    this.hideme = null;

    var div;
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_SEARCHRESULT_NAME);
        div = pane.GetBodyDiv();
        this.showme = function() {
            pane.Show();
        };
        this.hideme = function() {
            this.Reset(); pane.Hide();
        };
        pane.AddCloseButton(this, function() {
            this.Reset();
        });
    } else {
        var results_dialog = new Dialog(map_elem, "search_dialog",FUSION_FRAME_SEARCHRESULT_NAME, "400px", "200px");
        div = results_dialog.GetBodyDiv();
        this.showme = function() {
            results_dialog.Show();
        };
        this.hideme = function() {
            this.Reset(); results_dialog.Hide();
        };
    }
    this.search_results_div = div;
    this.search_results_tbody = CreateElement(div, "div");
}

SearchManager.prototype.Hide = function() {
    this.hideme();
}

SearchManager.prototype.Reset = function() {
    // cleanup map markers
    for (var i = 0; i < this.results_map_markers.length; i++)
        gmap.removeOverlay(this.results_map_markers[i]);
    this.results_map_markers.length = 0;
    RemoveAllChildren(this.search_results_tbody);
    //this.search_results_tbody = null;
    this.first_result = null;
    if (this.open_info_window) {
        gmap.closeInfoWindow();
        this.open_info_window = false;
    }
}

SearchManager.prototype.GotoFirstResult = function() {
    if (this.first_result)
        gmap.panTo(this.first_result);
}

SearchManager.prototype.GozoomFirstResult = function() {
    if (this.first_result){
        gmap.setCenter(new GLatLng(this.first_result.lat() , this.first_result.lng()+ -0.0043220520),15);
    }
}

SearchManager.prototype.AddMarkerCat = function(cfg,comercial) {

    var index = this.results_map_markers.length;
    point = new GLatLng(cfg.lat, cfg.lon);
    if (index == 0)
        this.first_result = point;

    var desc = "";
    if (cfg.description)
        desc = cfg.description;
    var name = "";


    var categoria = "";
    categoria = desc.split(' en ');
    categoria = tildes(categoria[0]);


    if (cfg.name)
        name = cfg.name;

    var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
        function() {
            placemark_manager.AddPlacemark({
                txt: cfg.name,
                lat: cfg.lat,
                lng: cfg.lon,
                zoom: gmap.getZoom()
            } );
            gmap.closeInfoWindow();
            placemark_manager.Save();
            alert (cfg.name+" ha sido guardado en sus puntos!");
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            if (cokie !="") {
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
            //gmap.getInfoWindow().hide();
            //gmap.removeOverlay(marker);
            }
        //SubmitSearch();

        },"Subir imagen",function()
        {
            // var WindowObjectReference
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                //var cokie = cadena.decode(cookie);
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                gmap.closeInfoWindow();
                //SubmitSearch();
                return false;
            }
            alert("Ingrese como usuario del sistema.");
            return false;

        },"Sugerir cambio de nombre y ubicación",function()
        {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                banderaguardarpunto = 1000;
                nombreguardarpunto = cfg.name;
                // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                //search_manager.Reset();
                placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                //gmap.closeInfoWindow();
                return false;
            }

            alert("Ingrese como usuario del sistema.");
            return false;


        },"Sugerir eliminar punto",function()
        {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                alert("Su sugerencia será evaluada y tomada en cuenta")
                return false;
            }

            alert("Ingrese como usuario del sistema.");
            return false;


        },"Desde aquí",function()
        {
            var id = firstItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                place_search_manager.SetPlace(point,tildes(cfg.name), id);
                FindElement("search_dir_box").style.display = "block";

                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();

                }
            //showDirSearch();
            }
        },"Hasta aquí",function(){
            var id = lastItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                place_search_manager.SetPlace(point,tildes(cfg.name), id);
                FindElement("search_dir_box").style.display = "block";

                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();

                }
            //showDirSearch();

            }
        },"Clientes comerciales",function(){
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            var place = cokie.split('|');
            var parms = place[0].split('&');
            if (parms != null && parms!=""){
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                var usuariobd= " ";
                var comer;

                for (var p = 1; p < comercial.length; p++) {
                    comer = comercial[p].split(":");

                    if(comer[0] == "Usuario") usuariobd =comer[1];
                }
                if (usuariobd == usux) {
                    banderaguardarpunto = 1000;
                    nombreguardarpunto = cfg.name;

                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    //search_manager.Reset();
                    placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                    return false;
                }else{

                    alert("Ingrese como usuario del punto.");
                    return false;
                }
            }else{
                alert("Ingrese como usuario del sistema.");
                return false;
            }
        },"Enviar E-mail",function()
        {
            window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

        });
    var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

    var popup3 = CreateInfoBody(cfg.name, desc,
        "Subir imagen",function()
        {
            // var WindowObjectReference
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                //var cokie = cadena.decode(cookie);
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                gmap.closeInfoWindow();
                //SubmitSearch();
                return false;
            }
            alert("Ingrese como usuario del sistema.");
            return false;

        });

    var marker = CreateMarkerCat(point, popup,popup2 ,popup3 ,categoria);

    // keep track of info window openings in order to close
    // when the search results are cleared
    GEvent.bindDom(marker, "infowindowopen", this,
        function() {
            this.open_info_window = true;
        });
    GEvent.bindDom(marker, "infowindowclose", this,
        function() {
            this.open_info_window = false;
        });

    gmap.addOverlay(marker);
    this.results_map_markers.push(marker);

    GEvent.addListener(marker, "click", function() {
        var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
            function() {
                placemark_manager.AddPlacemark({
                    txt: cfg.name,
                    lat: cfg.lat,
                    lng: cfg.lon,
                    zoom: gmap.getZoom()
                } );
                gmap.closeInfoWindow();
                placemark_manager.Save();
                alert (cfg.name+" ha sido guardado en sus puntos!");
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                if (cokie !="") {
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                    FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                //gmap.getInfoWindow().hide();
                //gmap.removeOverlay(marker);
                }
            //SubmitSearch();

            },"Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            },"Sugerir cambio de nombre y ubicación",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    banderaguardarpunto = 1000;
                    nombreguardarpunto = cfg.name;
                    // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    //search_manager.Reset();
                    placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                    //gmap.closeInfoWindow();
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Sugerir eliminar punto",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    alert("Su sugerencia será evaluada y tomada en cuenta")
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Desde aquí",function()
            {
                var id = firstItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,tildes(cfg.name), id);
                    FindElement("search_dir_box").style.display = "block";

                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();
                }
            },"Hasta aquí",function(){
                var id = lastItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,tildes(cfg.name), id);
                    FindElement("search_dir_box").style.display = "block";

                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();

                }
            },"Clientes comerciales",function(){
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                var place = cokie.split('|');
                var parms = place[0].split('&');
                if (parms != null && parms!=""){
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    var usuariobd= " ";
                    var comer;

                    for (var p = 1; p < comercial.length; p++) {
                        comer = comercial[p].split(":");

                        if(comer[0] == "Usuario") usuariobd =comer[1];
                    }
                    if (usuariobd == usux) {
                        banderaguardarpunto = 1000;
                        nombreguardarpunto = cfg.name;

                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        //search_manager.Reset();
                        placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                        return false;
                    }else{

                        alert("Ingrese como usuario del punto.");
                        return false;
                    }
                }else{
                    alert("Ingrese como usuario del sistema.");
                    return false;
                }
            },"Enviar E-mail",function()
            {
                window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

            });
        var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

        var popup3 = CreateInfoBody(cfg.name, desc,
            "Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            });

        var tabs = [];
        //alert("here");
        if (comercial.length != 1){
            tabs.push(new GInfoWindowTab(TAG1_NAME,  popup2));
        }
        tabs.push(new GInfoWindowTab(TAG2_NAME,popup3));
        tabs.push(new GInfoWindowTab(TAG3_NAME,popup));

        marker.openInfoWindowTabsHtml(tabs);
    });
    var place = CreateElement(this.search_results_tbody, "div");
    var icon_place = CreateElement(place, "div", "search_results_icon");

    var img_elem = CreateElement(icon_place, "img");

    if (categoria) {
        img_elem.setAttribute("src", "/maps/gnresources/iconosesp/"+categoria+".png");

    } else {
        img_elem.setAttribute("src", "/maps/gnresources/icon.png");

    }
    img_elem.style.cursor = "pointer";

    GEvent.bindDom(img_elem, "click", this,
        function() {
            this.NewCenterViewFunc(point);
            gmap.setCenter(marker.getLatLng(), 15);
            var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
                function() {
                    placemark_manager.AddPlacemark({
                        txt: cfg.name,
                        lat: cfg.lat,
                        lng: cfg.lon,
                        zoom: gmap.getZoom()
                    } );
                    gmap.closeInfoWindow();
                    placemark_manager.Save();
                    alert (cfg.name+" ha sido guardado en sus puntos!");
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    if (cokie !="") {
                        var place = cokie.split('|');
                        var parms = place[0].split('&');
                        var codigo = parms[0].split(':');
                        var user = parms[1].split(':');
                        var usux =user[1].substr(0,user[1].indexOf ('"'));
                        //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                        FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                    //gmap.getInfoWindow().hide();
                    //gmap.removeOverlay(marker);
                    }
                //SubmitSearch();

                },"Subir imagen",function()
                {
                    // var WindowObjectReference
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    //if (cookie) {
                    if (cokie !="") {
                        //var cokie = cadena.decode(cookie);
                        var place = cokie.split('|');
                        var parms = place[0].split('&');
                        var codigo = parms[0].split(':');
                        var user = parms[1].split(':');
                        var usux =user[1].substr(0,user[1].indexOf ('"'));
                        window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                        gmap.closeInfoWindow();
                        //SubmitSearch();
                        return false;
                    }
                    alert("Ingrese como usuario del sistema.");
                    return false;

                },"Sugerir cambio de nombre y ubicación",function()
                {
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    //if (cookie) {
                    if (cokie !="") {
                        banderaguardarpunto = 1000;
                        nombreguardarpunto = cfg.name;
                        // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        //search_manager.Reset();
                        placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                        //gmap.closeInfoWindow();
                        return false;
                    }

                    alert("Ingrese como usuario del sistema.");
                    return false;


                },"Sugerir eliminar punto",function()
                {
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    //if (cookie) {
                    if (cokie !="") {
                        alert("Su sugerencia será evaluada y tomada en cuenta")
                        return false;
                    }

                    alert("Ingrese como usuario del sistema.");
                    return false;


                },"Desde aquí",function()
                {
                    var id = firstItem();
                    if (id) {

                        unselectItems();
                        place_search_manager.Reset();
                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        place_search_manager.SetPlace(point,tildes(cfg.name), id);
                        FindElement("search_dir_box").style.display = "block";

                        //if (FindElement("A").value && FindElement("B").value){
                        if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                            SubmitDirSearch();

                        }
                    //showDirSearch();
                    }
                },"Hasta aquí",function(){
                    var id = lastItem();
                    if (id) {

                        unselectItems();
                        place_search_manager.Reset();
                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        place_search_manager.SetPlace(point,tildes(cfg.name), id);
                        FindElement("search_dir_box").style.display = "block";

                        //if (FindElement("A").value && FindElement("B").value){
                        if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                            SubmitDirSearch();

                        }
                    //showDirSearch();

                    }
                },"Clientes comerciales",function(){
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    if (parms != null && parms!=""){
                        var user = parms[1].split(':');
                        var usux =user[1].substr(0,user[1].indexOf ('"'));
                        var usuariobd= " ";
                        var comer;

                        for (var p = 1; p < comercial.length; p++) {
                            comer = comercial[p].split(":");

                            if(comer[0] == "Usuario") usuariobd =comer[1];
                        }
                        if (usuariobd == usux) {
                            banderaguardarpunto = 1000;
                            nombreguardarpunto = cfg.name;

                            juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                            divilatlon = juntoslatlon.split(',');
                            point = new GLatLng(divilatlon[1],divilatlon[0]);
                            //search_manager.Reset();
                            placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                            return false;
                        }else{

                            alert("Ingrese como usuario del punto.");
                            return false;
                        }
                    }else{
                        alert("Ingrese como usuario del sistema.");
                        return false;
                    }
                },"Enviar E-mail",function()
                {
                    window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

                });
            var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

            var popup3 = CreateInfoBody(cfg.name, desc,
                "Subir imagen",function()
                {
                    // var WindowObjectReference
                    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                    //if (cookie) {
                    if (cokie !="") {
                        //var cokie = cadena.decode(cookie);
                        var place = cokie.split('|');
                        var parms = place[0].split('&');
                        var codigo = parms[0].split(':');
                        var user = parms[1].split(':');
                        var usux =user[1].substr(0,user[1].indexOf ('"'));
                        window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                        gmap.closeInfoWindow();
                        //SubmitSearch();
                        return false;
                    }
                    alert("Ingrese como usuario del sistema.");
                    return false;

                });
            var tabs = [];
            //alert("here");
            if (comercial.length != 1){
                tabs.push(new GInfoWindowTab(TAG1_NAME,  popup2));
            }
            tabs.push(new GInfoWindowTab(TAG2_NAME,popup3));
            tabs.push(new GInfoWindowTab(TAG3_NAME,popup));
            marker.openInfoWindowTabsHtml(tabs);

        });

    // name should always be defined
    var name_div = CreateElement(place, "div", "search_results_name");
    name_div.innerHTML = cfg.name;
    // only show snippet if one is defined
    if (cfg.snippet != undefined) {
        var snippet_div = CreateElement(place, "div", "search_results_snippet");
        snippet_div.innerHTML = cfg.snippet;
    }

    this.showme();
}
//MODIFICADO POR RICARDO FRANCO
SearchManager.prototype.AddMarker = function(cfg,comercial) {

    var index = this.results_map_markers.length;
    point = new GLatLng(cfg.lat, cfg.lon);
    if (index == 0)
        this.first_result = point;

    var desc = "";
    if (cfg.description)
        desc = cfg.description;
    var name = "";

    if (cfg.name)
        name = cfg.name;

    var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
        function() {
            placemark_manager.AddPlacemark({
                txt: cfg.name,
                lat: cfg.lat,
                lng: cfg.lon,
                zoom: gmap.getZoom()
            } );
            gmap.closeInfoWindow();
            placemark_manager.Save();
            alert (cfg.name+" ha sido guardado en sus puntos!");
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            if (cokie !="") {
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
            //gmap.getInfoWindow().hide();
            //gmap.removeOverlay(marker);
            }
        //SubmitSearch();

        },"Subir imagen",function()
        {
            // var WindowObjectReference
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                //var cokie = cadena.decode(cookie);
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                gmap.closeInfoWindow();
                //SubmitSearch();
                return false;
            }
            alert("Ingrese como usuario del sistema.");
            return false;

        },"Sugerir cambio de nombre y ubicación",function()
        {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                banderaguardarpunto = 1000;
                nombreguardarpunto = cfg.name;
                // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                search_manager.Reset();
                placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                //gmap.closeInfoWindow();
                return false;
            }

            alert("Ingrese como usuario del sistema.");
            return false;


        },"Sugerir eliminar punto",function()
        {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                alert("Su sugerencia será evaluada y tomada en cuenta")
                return false;
            }

            alert("Ingrese como usuario del sistema.");
            return false;


        },"Desde aquí",function(){
            var id = firstItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                place_search_manager.SetPlace(point,cfg.name, id);
                FindElement("search_dir_box").style.display = "block";
                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();

                }
            //showDirSearch();
            }
        },"Hasta aquí",function(){
            var id = lastItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                divilatlon = juntoslatlon.split(',');
                point = new GLatLng(divilatlon[1],divilatlon[0]);
                place_search_manager.SetPlace(point,cfg.name, id);

                FindElement("search_dir_box").style.display = "block";
                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();

                }
            //showDirSearch();

            }
        },"Clientes comerciales",function(){
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            var place = cokie.split('|');
            var parms = place[0].split('&');
            if (parms != null && parms!=""){
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                var usuariobd= " ";
                var comer;

                for (var p = 1; p < comercial.length; p++) {
                    comer = comercial[p].split(":");

                    if(comer[0] == "Usuario") usuariobd =comer[1];
                }
                if (usuariobd == usux) {
                    banderaguardarpunto = 1000;
                    nombreguardarpunto = cfg.name;

                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    //search_manager.Reset();
                    placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                    return false;
                }else{

                    alert("Ingrese como usuario del punto.");
                    return false;
                }
            }else{
                alert("Ingrese como usuario del sistema.");
                return false;
            }
        },"Enviar E-mail",function()
        {
            window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

        });

    var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

    var popup3 = CreateInfoBody(cfg.name, desc,
        "Subir imagen",function()
        {
            // var WindowObjectReference
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            //if (cookie) {
            if (cokie !="") {
                //var cokie = cadena.decode(cookie);
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                gmap.closeInfoWindow();
                //SubmitSearch();
                return false;
            }
            alert("Ingrese como usuario del sistema.");
            return false;

        });

    var marker = CreateMarker(point, popup,popup2,popup3, this.results_map_markers.length);

    // keep track of info window openings in order to close
    // when the search results are cleared
    GEvent.bindDom(marker, "infowindowopen", this,
        function() {
            this.open_info_window = true;
        });
    GEvent.bindDom(marker, "infowindowclose", this,
        function() {
            this.open_info_window = false;
        });

    gmap.addOverlay(marker);
    this.results_map_markers.push(marker);

    GEvent.addListener(marker, "click", function() {
        var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
            function() {
                placemark_manager.AddPlacemark({
                    txt: cfg.name,
                    lat: cfg.lat,
                    lng: cfg.lon,
                    zoom: gmap.getZoom()
                } );
                gmap.closeInfoWindow();
                placemark_manager.Save();
                alert (cfg.name+" ha sido guardado en sus puntos!");
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                if (cokie !="") {
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                    FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                //gmap.getInfoWindow().hide();
                //gmap.removeOverlay(marker);
                }
            //SubmitSearch();

            },"Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            },"Sugerir cambio de nombre y ubicación",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    banderaguardarpunto = 1000;
                    nombreguardarpunto = cfg.name;
                    // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    search_manager.Reset();
                    placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                    //gmap.closeInfoWindow();
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Sugerir eliminar punto",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    alert("Su sugerencia será evaluada y tomada en cuenta")
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Desde aquí",function(){
                var id = firstItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,cfg.name, id);
                    FindElement("search_dir_box").style.display = "block";
                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();
                }
            },"Hasta aquí",function(){
                var id = lastItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,cfg.name, id);

                    FindElement("search_dir_box").style.display = "block";
                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();

                }
            },"Clientes comerciales",function(){
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                var place = cokie.split('|');
                var parms = place[0].split('&');
                if (parms != null && parms!=""){
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    var usuariobd= " ";
                    var comer;

                    for (var p = 1; p < comercial.length; p++) {
                        comer = comercial[p].split(":");

                        if(comer[0] == "Usuario") usuariobd =comer[1];
                    }
                    if (usuariobd == usux) {
                        banderaguardarpunto = 1000;
                        nombreguardarpunto = cfg.name;

                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        //search_manager.Reset();
                        placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                        return false;
                    }else{

                        alert("Ingrese como usuario del punto.");
                        return false;
                    }
                }else{
                    alert("Ingrese como usuario del sistema.");
                    return false;
                }
            },"Enviar E-mail",function()
            {
                window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

            });

        var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

        var popup3 = CreateInfoBody(cfg.name, desc,
            "Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            });


        var tabs = [];
        //alert("here");

        if (comercial.length != 1){
            tabs.push(new GInfoWindowTab(TAG1_NAME,  popup2));
        }
        tabs.push(new GInfoWindowTab(TAG2_NAME,  popup3));
        tabs.push(new GInfoWindowTab(TAG3_NAME,  popup));


        marker.openInfoWindowTabsHtml(tabs);
    });


    var place = CreateElement(this.search_results_tbody, "div");
    var icon_place = CreateElement(place, "div", "search_results_icon");
    // drop icons after A-Z has belabel, body_texten used
    var img_elem = CreateElement(icon_place, "img");
    if (index < 26) {
        var letter = String.fromCharCode("A".charCodeAt(0) + index);
        img_elem.setAttribute("src", "/maps/gnresources/" + "icon" + letter + ".png");
    //img_elem.setAttribute("src", FUSION_PATH + "marker" + letter + ".png");
    } else {
        img_elem.setAttribute("src", "/maps/gnresources/icon.png");
    //img_elem.setAttribute("src", FUSION_PATH + "marker.png");
    }
    img_elem.style.cursor = "pointer";

    GEvent.bindDom(img_elem, "click", this, function() {
        this.NewCenterViewFunc(point);
        gmap.setCenter(marker.getLatLng(), 15);
        var popup = CreateInfoBody3(cfg.name, desc,"Guardar en mis lugares",
            function() {
                placemark_manager.AddPlacemark({
                    txt: cfg.name,
                    lat: cfg.lat,
                    lng: cfg.lon,
                    zoom: gmap.getZoom()
                } );
                gmap.closeInfoWindow();
                placemark_manager.Save();
                alert (cfg.name+" ha sido guardado en sus puntos!");
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                if (cokie !="") {
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
                    FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+cfg.name+"&descripcion="+''+"&categoria="+''+"&latitud="+cfg.lat+"&longitud="+cfg.lon+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                //gmap.getInfoWindow().hide();
                //gmap.removeOverlay(marker);
                }
            //SubmitSearch();

            },"Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            },"Sugerir cambio de nombre y ubicación",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    banderaguardarpunto = 1000;
                    nombreguardarpunto = cfg.name;
                    // alert ("Indique su nueva ubicacion o nuevo nombre con doble click en el mapa");
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    search_manager.Reset();
                    placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
                    //gmap.closeInfoWindow();
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Sugerir eliminar punto",function()
            {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    alert("Su sugerencia será evaluada y tomada en cuenta")
                    return false;
                }

                alert("Ingrese como usuario del sistema.");
                return false;


            },"Desde aquí",function(){
                var id = firstItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,cfg.name, id);
                    FindElement("search_dir_box").style.display = "block";
                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();
                }
            },"Hasta aquí",function(){
                var id = lastItem();
                if (id) {

                    unselectItems();
                    place_search_manager.Reset();
                    juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                    divilatlon = juntoslatlon.split(',');
                    point = new GLatLng(divilatlon[1],divilatlon[0]);
                    place_search_manager.SetPlace(point,cfg.name, id);

                    FindElement("search_dir_box").style.display = "block";
                    //if (FindElement("A").value && FindElement("B").value){
                    if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                        SubmitDirSearch();

                    }
                //showDirSearch();

                }
            },"Clientes comerciales",function(){
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                var place = cokie.split('|');
                var parms = place[0].split('&');
                if (parms != null && parms!=""){
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    var usuariobd= " ";
                    var comer;

                    for (var p = 1; p < comercial.length; p++) {
                        comer = comercial[p].split(":");

                        if(comer[0] == "Usuario") usuariobd =comer[1];
                    }
                    if (usuariobd == usux) {
                        banderaguardarpunto = 1000;
                        nombreguardarpunto = cfg.name;

                        juntoslatlon =(desc.slice(desc.indexOf("(")+1,desc.indexOf(")")));
                        divilatlon = juntoslatlon.split(',');
                        point = new GLatLng(divilatlon[1],divilatlon[0]);
                        //search_manager.Reset();
                        placemark_manager.SendPlacemarkComercialAtPoint(point,nombreguardarpunto,comercial,divilatlon[1],divilatlon[0]);

                        return false;
                    }else{

                        alert("Ingrese como usuario del punto.");
                        return false;
                    }
                }else{
                    alert("Ingrese como usuario del sistema.");
                    return false;
                }
            },"Enviar E-mail",function()
            {
                window.open("/maps/envioemail.html?tenvio=2&etiqueta=" + cadena.encode(cfg.name), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');

            });

        var popup2 = CreateInfoBody2(cfg.name, desc,comercial);

        var popup3 = CreateInfoBody(cfg.name, desc,
            "Subir imagen",function()
            {
                // var WindowObjectReference
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                //if (cookie) {
                if (cokie !="") {
                    //var cokie = cadena.decode(cookie);
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    window.open("/maps/subirfoto.html?lonlatname="+ tildes(desc.slice(desc.indexOf("(")+1,desc.indexOf(")"))+name+"&cod="+codigo[1]+"&user="+usux), "SubirImagen", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=320,left = 340,top = 312');
                    gmap.closeInfoWindow();
                    //SubmitSearch();
                    return false;
                }
                alert("Ingrese como usuario del sistema.");
                return false;

            });
        var tabs = [];
        //alert("here");
        if (comercial.length != 1){
            tabs.push(new GInfoWindowTab(TAG1_NAME,  popup2));
        }
        tabs.push(new GInfoWindowTab(TAG2_NAME,  popup3));
        tabs.push(new GInfoWindowTab(TAG3_NAME,  popup));


        marker.openInfoWindowTabsHtml(tabs);

    });

    // name should always be defined
    var name_div = CreateElement(place, "div", "search_results_name");
    name_div.innerHTML = cfg.name;
    // only show snippet if one is defined
    if (cfg.snippet != undefined) {
        var snippet_div = CreateElement(place, "div", "search_results_snippet");
        snippet_div.innerHTML = cfg.snippet;
    }

    this.showme();
    var tabs = [];
    //alert("here");

    if (comercial.length != 1){
        tabs.push(new GInfoWindowTab(TAG1_NAME,  popup2));
    }
    tabs.push(new GInfoWindowTab(TAG2_NAME,  popup3));
    tabs.push(new GInfoWindowTab(TAG3_NAME,  popup));

    //abre info cuando crea el punto
    if (index==0){
        marker.openInfoWindowTabsHtml(tabs);
    }
}

SearchManager.prototype.NewCenterViewFunc = function(pos) {
    return function(e) {
        gmap.setCenter(pos.getLatLng(), 15);
        cancelEvent(e);
        return false;
    }
}

var juntoslatlonvar,divilatlon = null;
function CreateInfoBody3(label, body_text,btn_name, btn_func, btn_name2, btn_func2, btn_name3, btn_func3,btn_name6, btn_func6,btn_name4, btn_func4,btn_name5, btn_func5,btn_name7, btn_func7,btn_name8, btn_func8) {
    var info_div = document.createElement("div");
    var name_div = CreateElement(info_div, "div", "search_popup_name");
    name_div.innerHTML = label;

    var  body_div = CreateElement(info_div, "div", "search_popup_body");
    body_div.innerHTML = body_text;

    var acc_div = CreateElement(info_div, "div", "search_popup_name");
    acc_div.innerHTML = "Acciones sobre el punto";

    var  menbody5_div = CreateElement(info_div, "div", "search_popup_body");
    menbody5_div.innerHTML = " ";

    var btn_div = CreateElement(info_div, "div", "search_popup_body");
    var btn = CreateElement(btn_div, "a", "info_window_btn");
    btn.href = 'javascript:void(0)';
    btn.appendChild(document.createTextNode(btn_name));

    var btn_div2 = CreateElement(info_div, "div", "search_popup_body");
    var btn2 = CreateElement(btn_div2, "a", "info_window_btn");
    btn2.href = 'javascript:void(0)';
    btn2.appendChild(document.createTextNode(btn_name2));

    var btn_div3 = CreateElement(info_div, "div", "search_popup_body");
    var btn3 = CreateElement(btn_div3, "a", "info_window_btn");
    btn3.href = 'javascript:void(0);';
    btn3.appendChild(document.createTextNode(btn_name3));

    var btn_div6 = CreateElement(info_div, "div", "search_popup_body");
    var btn6 = CreateElement(btn_div6, "a", "info_window_btn");
    btn6.href = 'javascript:void(0);';
    btn6.appendChild(document.createTextNode(btn_name6));

    //var btn_div4 = CreateElement(info_div, "div", "search_popup_body");
    var btn4 = CreateElement(info_div, "a", "info_window_btn");
    btn4.href = 'javascript:void(0)';
    btn4.appendChild(document.createTextNode(btn_name4));

    //var btn_div5 = CreateElement(info_div, "div", "search_popup_body");
    var btn5 = CreateElement(info_div, "a", "info_window_btn");
    btn5.href = 'javascript:void(0);';
    btn5.appendChild(document.createTextNode(btn_name5));

    var btn_div7 = CreateElement(info_div, "div", "search_popup_body");
    var btn7 = CreateElement(btn_div7, "a", "info_window_btn");
    btn7.href = 'javascript:void(0);';
    btn7.appendChild(document.createTextNode(btn_name7));

    var btn_div8 = CreateElement(info_div, "div", "search_popup_body");
    var btn8 = CreateElement(btn_div8, "a", "info_window_btn");
    btn8.href = 'javascript:void(0);';
    btn8.appendChild(document.createTextNode(btn_name8));


    var enlace_div = CreateElement(info_div, "div", "search_popup_name");
    enlace_div.innerHTML = "Enlace del punto";
    var label_elem = CreateElement(info_div, "textarea");
    label_elem.style.width = "250px";
    //guarda cuando se arrastra el punto el nombre
    label_elem.value ="http://lnmapas.nacion.co.cr/maps/index.shtml?bdirecta="+tildes(label);

    GEvent.bindDom(btn, 'click', this, function(e) {
        btn_func();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn8, 'click', this, function(e) {
        btn_func8();
        cancelEvent(e);
        return false;
    });
    GEvent.bindDom(btn2, 'click', this, function(e) {
        btn_func2();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn3, 'click', this, function(e) {
        btn_func3();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn6, 'click', this, function(e) {
        btn_func6();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn4, 'click', this, function(e) {
        btn_func4();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn5, 'click', this, function(e) {
        btn_func5();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(btn7, 'click', this, function(e) {
        btn_func7();
        cancelEvent(e);
        return false;
    });


    return info_div;
}

function CreateInfoBody(label, body_text, btn_name2, btn_func2) {
    var info_div = document.createElement("div");
    var name_div = CreateElement(info_div, "div", "search_popup_name");
    name_div.innerHTML = label;

    var  body_div = CreateElement(info_div, "div", "search_popup_body");
    body_div.innerHTML = body_text;

    var imgtitle_div = CreateElement(info_div, "div", "search_popup_name");
    imgtitle_div.innerHTML = "Imágenes de usuarios";

    var btn_div2 = CreateElement(info_div, "div", "search_popup_body");
    var btn2 = CreateElement(btn_div2, "a", "info_window_btn");
    btn2.href = 'javascript:void(0)';
    btn2.appendChild(document.createTextNode(btn_name2));

    GEvent.bindDom(btn2, 'click', this, function(e) {
        btn_func2();
        cancelEvent(e);
        return false;
    });
    var  img_div = CreateElement(info_div, "div", "search_popup_img");
    img_div.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/ListaDirectorio?dir=imagenes/"+tildes(body_text.slice(body_text.indexOf("(")+1,body_text.indexOf(")"))+label)+"' frameborder='0' scrolling ='no'></iframe>";



    return info_div;
}

function CreateInfoBody2(label, body_text, comercial) {
    var info_div = document.createElement("div");
    var name_div = CreateElement(info_div, "div", "search_popup_name");
    name_div.innerHTML = label;

    var  body_div = CreateElement(info_div, "div", "search_popup_body");
    body_div.innerHTML = body_text;

    var divtitle_div = CreateElement(info_div, "div", "search_popup_name");
    divtitle_div.innerHTML = "Información sobre el Comercio ";

    var  menbody1_div = CreateElement(info_div, "div", "search_popup_body");

    for(var i=1; i<comercial.length; i++)
    {
        var comer = comercial[i].split(":");


        if (comer[0] =="Sitio Web"){
            //comercial[i]= "Sitio Web: <a href='http://" + comer[1] + "' target='_blank'>" + comer[1] + "</a>";
            menbody1_div.innerHTML = menbody1_div.innerHTML + "Sitio Web:&nbsp;<a href='http://" + comer[1] + "' target='_blank'>" + comer[1] + "</a>" + "<br>"
        }else{
            if (comer[0] =="E-mail"){
                //comercial[i]= "E-mail: <a href='mailto:" + comer[1] +  "'>"+ comer[1] +  "</a>";
                menbody1_div.innerHTML = menbody1_div.innerHTML + "E-mail:&nbsp;<a href='mailto:" + comer[1] +  "'>"+ comer[1] +  "</a>" + "<br>"
            }else{
                if (comer[0] !="Usuario"){
                    menbody1_div.innerHTML = menbody1_div.innerHTML + comercial[i] + "<br>"
                }

            }
        }
    }
    var  menbody5_div = CreateElement(info_div, "div", "search_popup_body");
    menbody5_div.innerHTML = " ";

    var imgtitle_div = CreateElement(info_div, "div", "search_popup_name");
    imgtitle_div.innerHTML = "Imágenes comerciales";

    var  img_div = CreateElement(info_div, "div", "search_popup_img");
    img_div.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/ListaDirectorio?dir=imagenescomercial/"+tildes(body_text.slice(body_text.indexOf("(")+1,body_text.indexOf(")"))+label)+"' frameborder='0' scrolling ='no'></iframe>";
    return info_div;
}
// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = 0; // To be initialized in LoadMap().

// Initialize variables in LoadMap() after all javascript has been loaded.
function InitBaseIcon() {
    baseIcon = new GIcon();
    baseIcon.shadow = FUSION_PATH + "shadow50.png";
    baseIcon.iconSize = new GSize(24, 38);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);
}

function CreateMarker(point, popup_body,popup_body2,popup_body3, index) {
    var icon = new GIcon(baseIcon);
    // only specialize the marker icon if the index is A-Z
    if ((index != null) && (index < 26)) {
        var letter = String.fromCharCode("A".charCodeAt(0) + index);
        icon.image = "/maps/gnresources/" + "icon" + letter + ".png";
    //icon.image = FUSION_PATH + "marker" + letter + ".png";
    } else {
        icon.image = "/maps/gnresources/icon.png";
    }

    var tabs = [];
    //alert("here");
    tabs.push(new GInfoWindowTab(TAG1_NAME,  popup_body2));
    tabs.push(new GInfoWindowTab(TAG2_NAME,  popup_body3));
    tabs.push(new GInfoWindowTab(TAG3_NAME,  popup_body));




    var marker = new GMarker(point, icon);
    GEvent.addListener(marker, "click", function() {
        //marker.openInfoWindow(popup_body);

        marker.openInfoWindowTabsHtml(tabs);
    });
    return marker;
}

function CreateMarkerCat(point, popup_body,popup_body2,popup_body3 ,cat) {
    var icon = new GIcon(baseIcon);

    if (cat) {
        icon.image = "/maps/gnresources/iconosesp/"+cat+".png";

    } else {
        icon.image = "/maps/gnresources/icon.png";
    }


    var tabs = [];
    //alert("here");
    tabs.push(new GInfoWindowTab(TAG1_NAME,popup_body2));
    tabs.push(new GInfoWindowTab(TAG2_NAME,popup_body3));
    tabs.push(new GInfoWindowTab(TAG3_NAME,popup_body));


    var marker = new GMarker(point, icon);
    GEvent.addListener(marker, "click", function() {
        //marker.openInfoWindow(popup_body);
        marker.openInfoWindowTabsHtml(tabs);
    });
    return marker;
}
/******************************************************************************
 * DRAG AND DROP LIST Directions // CREADO POR RICARDO FRANCO
 ******************************************************************************/

function Position(x, y)
{
    this.X = x;
    this.Y = y;

    this.Add = function(val)
    {
        var newPos = new Position(this.X, this.Y);
        if(val != null)
        {
            if(!isNaN(val.X))
                newPos.X += val.X;
            if(!isNaN(val.Y))
                newPos.Y += val.Y
        }
        return newPos;
    }

    this.Subtract = function(val)
    {
        var newPos = new Position(this.X, this.Y);
        if(val != null)
        {
            if(!isNaN(val.X))
                newPos.X -= val.X;
            if(!isNaN(val.Y))
                newPos.Y -= val.Y
        }
        return newPos;
    }

    this.Min = function(val)
    {
        var newPos = new Position(this.X, this.Y)
        if(val == null)
            return newPos;

        if(!isNaN(val.X) && this.X > val.X)
            newPos.X = val.X;
        if(!isNaN(val.Y) && this.Y > val.Y)
            newPos.Y = val.Y;

        return newPos;
    }

    this.Max = function(val)
    {
        var newPos = new Position(this.X, this.Y)
        if(val == null)
            return newPos;

        if(!isNaN(val.X) && this.X < val.X)
            newPos.X = val.X;
        if(!isNaN(val.Y) && this.Y < val.Y)
            newPos.Y = val.Y;

        return newPos;
    }

    this.Bound = function(lower, upper)
    {
        var newPos = this.Max(lower);
        return newPos.Min(upper);
    }

    this.Check = function()
    {
        var newPos = new Position(this.X, this.Y);
        if(isNaN(newPos.X))
            newPos.X = 0;
        if(isNaN(newPos.Y))
            newPos.Y = 0;
        return newPos;
    }

    this.Apply = function(element)
    {
        if(typeof(element) == "string")
            element = document.getElementById(element);
        if(element == null)
            return;
        if(!isNaN(this.X))
            element.style.left = this.X + 'px';
        if(!isNaN(this.Y))
            element.style.top = this.Y + 'px';
    }
}

function hookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.addEventListener)
    {
        element.addEventListener(eventName, callback, false);
    }
    else if(element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

function unhookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.removeEventListener)
        element.removeEventListener(eventName, callback, false);
    else if(element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function cancelEvent(e)
{
    e = e ? e : window.event;
    if(e.stopPropagation)
        e.stopPropagation();
    if(e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

function getEventTarget(e)
{
    e = e ? e : window.event;
    return e.target ? e.target : e.srcElement;
}

function absoluteCursorPostion(eventObj)
{
    eventObj = eventObj ? eventObj : window.event;

    if(isNaN(window.scrollX))
        return new Position(eventObj.clientX + document.documentElement.scrollLeft + document.body.scrollLeft,
            eventObj.clientY + document.documentElement.scrollTop + document.body.scrollTop);
    else
        return new Position(eventObj.clientX + window.scrollX, eventObj.clientY + window.scrollY);
}

function itemDragBegin(eventObj, element)
{
    element.style.top = element.offsetTop + 'px';
    element.style.left = element.offsetLeft + 'px';
    element.className = "drag";
    PlaceHolder.style.height = element.style.height;
    List.insertBefore(PlaceHolder, element);
    PlaceHolder.SourceI = element;
}

function itemMoved(newPos, element, eventObj)
{
    eventObj = eventObj ? eventObj : window.event;
    var yPos = newPos.Y + (eventObj.layerY ? eventObj.layerY : eventObj.offsetY);

    var temp;
    var bestItem = "end";
    for(var i=0; i<List.childNodes.length; i++)
    {
        if(List.childNodes[i].className == "list")
        {
            temp = parseInt(List.childNodes[i].style.height);
            if(temp/2 >= yPos)
            {
                bestItem = List.childNodes[i];
                break;
            }
            yPos -= temp;
        }
    }

    if(bestItem == PlaceHolder || bestItem == PlaceHolder.SourceI)
        return;

    PlaceHolder.SourceI = bestItem;
    if(bestItem != "end")
        List.insertBefore(PlaceHolder, List.childNodes[i]);
    else
        List.appendChild(PlaceHolder);
}

function itemDragEnd(element)
{
    if(PlaceHolder.SourceI != null)
    {
        PlaceHolder.SourceI = null;
        List.replaceChild(element, PlaceHolder);
    }

    element.className = 'list';
    element.style.top = '0px';
    element.style.left = '0px';

}

function firstItem() {
    for(var i=0; i<List.childNodes.length; i++)
    {
        if(List.childNodes[i].className == "list")
        {
            return List.childNodes[i].id.substring(3,4);
        }
    }
    return null;
}

function lastItem() {
    var id = null;
    for(var i=0; i<List.childNodes.length; i++)
    {
        if(List.childNodes[i].className == "list")
        {
            id = List.childNodes[i].id.substring(3,4);
        }
    }
    return id;
}

function mayorItem() {
    var id = null;
    for(var i=0; i<List.childNodes.length; i++)
    {
        if(List.childNodes[i].className == "list")
        {
            if(id){
                if(List.childNodes[i].id.substring(3,4).charCodeAt(0) > id.charCodeAt(0)  ){
                    id = List.childNodes[i].id.substring(3,4);
                }
            }else{
                id = List.childNodes[i].id.substring(3,4);
            }
        }
    }
    return id;
}

function unselectItems() {
    for(var i=0; i<List.childNodes.length; i++)
    {
        if(List.childNodes[i].className == "list") {
            List.childNodes[i].style.borderColor = "#fff";
            List.childNodes[i].style.backgroundColor = "#fff";
        }
    }
}

function dragObject(Id, lowerBound, upperBound, startCallback, moveCallback, endCallback, attachLater)
{
    var element = document.createElement("div");
    element.id = "wp_" + Id;
    element.className = "list";
    element.style.height = "26px";

    var attachElement = document.createElement("img");
    attachElement.id =  "wp_icon_" + Id;
    attachElement.heght = 16;
    attachElement.width = 16;
    attachElement.src = "gnresources/circle_marker" + Id + ".png";

    var inputElementHidden = document.createElement("input");
    inputElementHidden.id =  "wp_location_" + Id;
    inputElementHidden.type = "hidden";

    var inputElement = document.createElement("input");
    inputElement.id = Id;
    inputElement.title = "punto para dirección";
    inputElement.maxlength = 2048;

    hookEvent(inputElement, "keyup",
        function(evt) {
            if (evt.keyCode == 13) {
                if ((!IsNumeric(inputElement.value))){                    
                    document.getElementById("btnllegar").focus();                    
                    SubmitPlaceSearch(inputElement.value, inputElement.id);
                }
            }
        } );

    hookEvent(inputElement, "blur",
        function() {
            if (inputElement.value !='') {
                if ((!IsNumeric(inputElement.value))){
                    
                    SubmitPlaceSearch(inputElement.value, inputElement.id);
                    
                }
            }
        } );

   

    element.appendChild(attachElement);
    element.appendChild(inputElementHidden);
    element.appendChild(inputElement);

   
    var a = CreateElement(element, "img");
    a.setAttribute("src", FUSION_PATH + "close.gif");
    GEvent.bindDom(a, 'click', this, function() {
        DelDirSearch(inputElement.id);
    });
    a.style.cursor = "pointer";
    element.appendChild(a);
    
    

    List.appendChild(element);

    if(lowerBound != null && upperBound != null)
    {
        var temp = lowerBound.Min(upperBound);
        upperBound = lowerBound.Max(upperBound);
        lowerBound = temp;
    }

    var cursorStartPos = null;
    var elementStartPos = null;
    var dragging = false;
    var listening = false;
    var disposed = false;

    function dragStart(eventObj)
    {
        if(dragging || !listening || disposed) return null;
        dragging = true;

        if(startCallback != null)
            startCallback(eventObj, element);

        cursorStartPos = absoluteCursorPostion(eventObj);

        elementStartPos = new Position(parseInt(element.style.left), parseInt(element.style.top));

        elementStartPos = elementStartPos.Check();

        hookEvent(document, "mousemove", dragGo);
        hookEvent(document, "mouseup", dragStopHook);

        return cancelEvent(eventObj);
    }

    function dragGo(eventObj)
    {
        if(!dragging || disposed) return null;

        var newPos = absoluteCursorPostion(eventObj);
        newPos = newPos.Add(elementStartPos).Subtract(cursorStartPos);
        newPos = newPos.Bound(lowerBound, upperBound)
        newPos.Apply(element);
        if(moveCallback != null)
            moveCallback(newPos, element, eventObj);

        return cancelEvent(eventObj);
    }

    function dragStopHook(eventObj)
    {
        dragStop();
        return cancelEvent(eventObj);
    }

    function dragStop()
    {
        if(!dragging || disposed) return;
        unhookEvent(document, "mousemove", dragGo);
        unhookEvent(document, "mouseup", dragStopHook);
        cursorStartPos = null;
        elementStartPos = null;
        if(endCallback != null)
            endCallback(element);
        dragging = false;
    }

    this.Dispose = function()
    {
        if(disposed) return;
        this.StopListening(true);
        element = null;
        attachElement = null
        lowerBound = null;
        upperBound = null;
        startCallback = null;
        moveCallback = null
        endCallback = null;
        disposed = true;
    }

    this.StartListening = function()
    {
        if(listening || disposed) return;
        listening = true;
        hookEvent(attachElement, "mousedown", dragStart);
    }

    this.StopListening = function(stopCurrentDragging)
    {
        if(!listening || disposed) return;
        unhookEvent(attachElement, "mousedown", dragStart);
        listening = false;

        if(stopCurrentDragging && dragging)
            dragStop();
    }

    this.IsDragging = function(){
        return dragging;
    }
    this.IsListening = function() {
        return listening;
    }
    this.IsDisposed = function() {
        return disposed;
    }

    if(typeof(attachElement) == "string")
        attachElement = document.getElementById(attachElement);
    if(attachElement == null)
        attachElement = element;

    if(!attachLater)
        this.StartListening();
}

/******************************************************************************
 * Search Directions // CREADO POR RICARDO FRANCO
 ******************************************************************************/
var place_search_manager;
var List;
var PlaceHolder;

function InitializeDirSearch(map_elem) {

    place_search_manager = new PlaceSearchManager(gmap);

    new ContextMenu(gmap);

    List = document.getElementById("list");
    PlaceHolder = document.createElement("DIV");
    PlaceHolder.className = "holder";
    PlaceHolder.SourceI = null;

    new dragObject("A", null, null, itemDragBegin, itemMoved, itemDragEnd, false);
    new dragObject("B", null, null, itemDragBegin, itemMoved, itemDragEnd, false);
   

    place_search_manager.AddPlace("A");
    place_search_manager.AddPlace("B");
   
}

function hideDirSearch() {
    FindElement("search_dir_box").style.display = "none";
    place_search_manager.Reset();
}

function showDirSearch() {
    FindElement("search_dir_box").style.display = "block";
    search_manager.Hide();
    cerca_results.Hide();
}

function AddDirSearch(){
    var  letternew
    if (List.childNodes.length-2 < limitadd) {
        if (mayorItem()){
            if(mayorItem()=="Z"){
                return
            }else{
                letternew = String.fromCharCode(mayorItem().charCodeAt(0) + 1);
            }
        }
        else{
            letternew="A"
        }
        new dragObject(letternew, null, null, itemDragBegin, itemMoved, itemDragEnd, false);
        place_search_manager.AddPlace(letternew);
        

        if (List.childNodes.length-2 >= limitadd){
            FindElement("add_destino").style.display = "none";
        }
    }
}

function DelDirSearch(id){
    
    if (List.childNodes.length-3 < limitadd){
        FindElement("add_destino").style.display = "block";
    }
    place_search_manager.UnsetPlace(id);
    place_search_manager.Reset();
    FindElement(id).value = "";
    var adel=document.getElementById("wp_"+id);
    var pdel= adel.parentNode;
    pdel.removeChild(adel);

}

function ClearMap() {

    place_search_manager.Reset();
    place_search_manager.DeleteGeom();
    search_manager.Hide();
    cerca_results.Hide();

    var clear;
    
    for (var t = 0; t < List.childNodes.length; ++t) {
        clear = List.childNodes[t].id.substring(3,4)
        if (FindElement(clear) ){
            place_search_manager.UnsetPlace(clear);
            FindElement(clear).value = "";
            
        }
    }
    
    hideDirSearch();

    var info = FindElement("search_dir_info");
    info.innerHTML = "";

    for (var f = 0; f < cat_array_results.length; ++f) {
        if (cat_array_results[f]){
            cat_array_results[f].Hide();
            cat_array_check[f].checked = false;
        }
    }
    /*for (var g = 0; g < esp_array_results.length; ++g) {
        if (esp_array_results[g]){
            esp_array_results[g].Hide();
            esp_array_check[g].checked = false;
        }
    }*/
    for (var h = 0; h < guia_array_results.length; ++h) {
        if (guia_array_results[h]){
            guia_array_results[h].Hide();
            guia_array_check[h].checked = false;
        }
    }


    /*Lineas Poligonos*/
    if (document.getElementById("status")){
        document.getElementById("status").innerHTML = "&nbsp;";
        document.getElementById("status").style.visibility = 'hidden';
        if (markers.length>0) gmap.removeOverlay(poly);
        for(i = 0; i < markers.length; i++) {
            gmap.removeOverlay(markers[i]);
        }
        gmap.enableDoubleClickZoom();
        //gmap.clearOverlays();
        pointslp.length = 0;
        markers.length = 0;
        count = 0;
        if (document.getElementById("tooltip"))    document.getElementById("tooltip").style.display = "none";
    }
}

function IsNumeric(sText)

{
    var ValidChars = "0123456789.-, ";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++)
    {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            IsNumber = false;
        }
    }
    return IsNumber;

}

function SubmitDirSearch() {
    place_search_manager.DeleteGeom();
    var dir_list = new Array(List.childNodes.length);
    var id_point1,id_point2,id_point3,id_point4 ,id_point5,id_point6
    var val_point1, val_point2,val_point3, val_point4,val_point5, val_point6
    var baseUrl
    var geocoder
    costo= 0;

    for (var i = 0; i < dir_list.length; i++){
        dir_list[i]=List.childNodes[i].id.substring(3,4);
    }

    switch (dir_list.length){

        case 2:

            id_point1 = firstItem();
            id_point2 = lastItem();

            if ( FindElement(id_point1).value == "")
            {
                FindElement("wp_location_" + id_point1).value = "";
                alert("Especifique el lugar de origen, o bien haga clic derecho sobre el mapa.")
                FindElement(id_point1).focus();

                return;
            }
            if ( FindElement(id_point2).value == "")
            {
                FindElement("wp_location_" + id_point2).value = "";
                alert("Especifique el lugar de destino, o bien haga clic derecho sobre el mapa.")
                FindElement(id_point2).focus();

                return;
            }

            val_point1 = FindElement("wp_location_" + id_point1).value;
            val_point2 = FindElement("wp_location_" + id_point2).value;
   

            if ( val_point1 == undefined || val_point1 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point1).value, id_point1);

                return;
            }
            if (val_point2 == undefined || val_point2 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point2).value, id_point2);

                return;
            }

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point1+"&hasta="+val_point2;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
            break;

        case 3:

            id_point1 = firstItem();
            id_point2 = dir_list[1]
            id_point3 = lastItem();

            if ( FindElement(id_point1).value == "")
            {
                FindElement("wp_location_" + id_point1).value = "";
                alert("Especifique el lugar "+ id_point1+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point1).focus();

                return;
            }
            if ( FindElement(id_point2).value == "")
            {
                FindElement("wp_location_" + id_point2).value = "";
                alert("Especifique el lugar "+ id_point2+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point2).focus();

                return;
            }
            if ( FindElement(id_point3).value == "")
            {
                FindElement("wp_location_" + id_point3).value = "";
                alert("Especifique el lugar "+ id_point3+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point3).focus();

                return;
            }
            val_point1 = FindElement("wp_location_" + id_point1).value;
            val_point2 = FindElement("wp_location_" + id_point2).value;
            val_point3 = FindElement("wp_location_" + id_point3).value;

            if ( val_point1 == undefined || val_point1 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point1).value, id_point1);

                return;
            }
            if (val_point2 == undefined || val_point2 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point2).value, id_point2);

                return;
            }
            if (val_point3 == undefined || val_point3 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point3).value, id_point3);

                return;
            }

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point1+"&hasta="+val_point2;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
            StartLoading();

            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point2+"&hasta="+val_point3;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
            break;

        case 4:

            id_point1 = firstItem();
            id_point2 = dir_list[1]
            id_point3 = dir_list[2]
            id_point4 = lastItem();

            if ( FindElement(id_point1).value == "")
            {
                FindElement("wp_location_" + id_point1).value = "";
                alert("Especifique el lugar "+ id_point1+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point1).focus();

                return;
            }
            if ( FindElement(id_point2).value == "")
            {
                FindElement("wp_location_" + id_point2).value = "";
                alert("Especifique el lugar "+ id_point2+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point2).focus();

                return;
            }
            if ( FindElement(id_point3).value == "")
            {
                FindElement("wp_location_" + id_point3).value = "";
                alert("Especifique el lugar "+ id_point3+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point3).focus();

                return;
            }
            if ( FindElement(id_point4).value == "")
            {
                FindElement("wp_location_" + id_point4).value = "";
                alert("Especifique el lugar "+ id_point4+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point4).focus();

                return;
            }

            val_point1 = FindElement("wp_location_" + id_point1).value;
            val_point2 = FindElement("wp_location_" + id_point2).value;
            val_point3 = FindElement("wp_location_" + id_point3).value;
            val_point4 = FindElement("wp_location_" + id_point4).value;


            if ( val_point1 == undefined || val_point1 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point1).value, id_point1);

                return;
            }
            if (val_point2 == undefined || val_point2 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point2).value, id_point2);

                return;
            }
            if (val_point3 == undefined || val_point3 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point3).value, id_point3);

                return;
            }
            if ( val_point4 == undefined || val_point4 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point4).value, id_point4);

                return;
            }

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point1+"&hasta="+val_point2;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
              
            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point2+"&hasta="+val_point3;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point3+"&hasta="+val_point4;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
            break;

        case 5:

            id_point1 = firstItem();
            id_point2 = dir_list[1]
            id_point3 = dir_list[2]
            id_point4 = dir_list[3]
            id_point5 = lastItem()
            

            if ( FindElement(id_point1).value == "")
            {
                FindElement("wp_location_" + id_point1).value = "";
                alert("Especifique el lugar "+ id_point1+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point1).focus();

                return;
            }
            if ( FindElement(id_point2).value == "")
            {
                FindElement("wp_location_" + id_point2).value = "";
                alert("Especifique el lugar "+ id_point2+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point2).focus();

                return;
            }
            if ( FindElement(id_point3).value == "")
            {
                FindElement("wp_location_" + id_point3).value = "";
                alert("Especifique el lugar "+ id_point3+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point3).focus();

                return;
            }
            if ( FindElement(id_point4).value == "")
            {
                FindElement("wp_location_" + id_point4).value = "";
                alert("Especifique el lugar "+ id_point4+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point4).focus();

                return;
            }

            if ( FindElement(id_point5).value == "")
            {
                FindElement("wp_location_" + id_point5).value = "";
                alert("Especifique el lugar "+ id_point5+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point5).focus();

                return;
            }

            val_point1 = FindElement("wp_location_" + id_point1).value;
            val_point2 = FindElement("wp_location_" + id_point2).value;
            val_point3 = FindElement("wp_location_" + id_point3).value;
            val_point4 = FindElement("wp_location_" + id_point4).value;
            val_point5 = FindElement("wp_location_" + id_point5).value;


            if ( val_point1 == undefined || val_point1 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point1).value, id_point1);

                return;
            }
            if (val_point2 == undefined || val_point2 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point2).value, id_point2);

                return;
            }
            if (val_point3 == undefined || val_point3 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point3).value, id_point3);

                return;
            }
            if ( val_point4 == undefined || val_point4 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point4).value, id_point4);

                return;
            }
            if ( val_point5 == undefined || val_point5 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point5).value, id_point5);

                return;
            }
            
            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point1+"&hasta="+val_point2;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point2+"&hasta="+val_point3;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point3+"&hasta="+val_point4;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });


            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point4+"&hasta="+val_point5;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });


            break;
        case 6:

            id_point1 = firstItem();
            id_point2 = dir_list[1]
            id_point3 = dir_list[2]
            id_point4 = dir_list[3]
            id_point5 = dir_list[4]
            id_point6 = lastItem();
            

            if ( FindElement(id_point1).value == "")
            {
                FindElement("wp_location_" + id_point1).value = "";
                alert("Especifique el lugar "+ id_point1+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point1).focus();

                return;
            }
            if ( FindElement(id_point2).value == "")
            {
                FindElement("wp_location_" + id_point2).value = "";
                alert("Especifique el lugar "+ id_point2+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point2).focus();

                return;
            }
            if ( FindElement(id_point3).value == "")
            {
                FindElement("wp_location_" + id_point3).value = "";
                alert("Especifique el lugar "+ id_point3+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point3).focus();

                return;
            }
            if ( FindElement(id_point4).value == "")
            {
                FindElement("wp_location_" + id_point4).value = "";
                alert("Especifique el lugar "+ id_point4+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point4).focus();

                return;
            }

            if ( FindElement(id_point5).value == "")
            {
                FindElement("wp_location_" + id_point5).value = "";
                alert("Especifique el lugar "+ id_point5+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point5).focus();

                return;
            }
            if ( FindElement(id_point6).value == "")
            {
                FindElement("wp_location_" + id_point6).value = "";
                alert("Especifique el lugar "+ id_point6+", o bien haga clic derecho sobre el mapa.")
                FindElement(id_point6).focus();

                return;
            }
            
            val_point1 = FindElement("wp_location_" + id_point1).value;
            val_point2 = FindElement("wp_location_" + id_point2).value;
            val_point3 = FindElement("wp_location_" + id_point3).value;
            val_point4 = FindElement("wp_location_" + id_point4).value;
            val_point5 = FindElement("wp_location_" + id_point5).value;
            val_point6 = FindElement("wp_location_" + id_point6).value;


            if ( val_point1 == undefined || val_point1 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point1).value, id_point1);

                return;
            }
            if (val_point2 == undefined || val_point2 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point2).value, id_point2);

                return;
            }
            if (val_point3 == undefined || val_point3 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point3).value, id_point3);

                return;
            }
            if ( val_point4 == undefined || val_point4 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point4).value, id_point4);

                return;
            }
            if ( val_point5 == undefined || val_point5 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point5).value, id_point5);

                return;
            }
            if ( val_point6 == undefined || val_point6 == "" )
            {
                SubmitPlaceSearch(FindElement(id_point6).value, id_point6);

                return;
            }
            


            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point1+"&hasta="+val_point2;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point2+"&hasta="+val_point3;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point3+"&hasta="+val_point4;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });


            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point4+"&hasta="+val_point5;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });

            StartLoading();
            baseUrl = "/default_search/SearchServlet/MapsAdapter?service=RoutingPlugin&DbId=12&flyToFirstElement=true&desde="+val_point5+"&hasta="+val_point6;
            geocoder = new GF_Geocoder();
            geocoder.query(baseUrl,
                function(results) {
                    EndLoading();
                    HandleDirResults(results)
                });
                
           
            break;
    }
    
        
}


function HandleDirResults(reply) {
    if (reply.success == false) {
        alert("Búsqueda no completada!\n\nInformación: " + reply.failureMessage);
        DebugMsg("Search failed!");
        DebugMsg(". Search URL: " + reply.searchTerm);
        DebugMsg(". Failure Message: " + reply.failureMessage);
        return;
    }

    DebugMsg("displayKeys: " + reply.displayKeys);
    DebugMsg("flyToFirstElement: " + reply.flyToFirstElement);
    DebugMsg("success: " + reply.success);
    if (reply.responses.length != undefined)
        DebugMsg("responses.length = " + reply.responses.length);

    var points = [];
    for (var r = 0; r < reply.responses.length; ++r) {
        var response = reply.responses[r];

        DebugMsg("[" + r + "] datastoreName: " + response.datastoreName);
        DebugMsg("[" + r + "] success: " + response.success);
        if (response.success == false && response.errorMessage!="") {
            alert("Atención!\n\n" + response.errorMessage);
            
        } else {
            if (response.data != undefined && response.data.length > 0) {
                DebugMsg("[" + r + "] data.length: " + response.data.length);
                var old_id = response.data[0].name;
                costo = costo + (1 * response.data[0].snippet);

                for (var d = 0; d < response.data.length; ++d) {
                    var data = response.data[d];

                    if (!data || !data.lon) break;
                    DebugMsg("--> [" + d + "] lon: " + data.lon + " lat: " + data.lat);

                    if (old_id != data.name) {
                        old_id = data.name;
                        costo = costo + (1 * data.snippet);
                    }
                    points[points.length] = new GLatLng(data.lat, data.lon);
                }
                var info = FindElement("search_dir_info");
                if (info) {
                    if (costo > 0 && costo < 999 ) {
                        info.innerHTML = " Distancia: " + Math.round(costo) + " mts";
                        showDirSearch()
                    }
                    if (costo > 999) {
                        info.innerHTML = " Distancia: "  + Math.round((costo/1000)*100)/100  + " km,  " + Math.round((costo/1000*0.62137)*100)/100 + " mi";
                        showDirSearch()
                    }
                } else {
                    alert(" Distancia: "  + Math.round((costo/1000)*100)/100 + " km" + Math.round((costo/1000*0.62137)*100)/100 + " mi");
                }
            }
        }
    }

    place_search_manager.EncodePoints(points);
    place_search_manager.Points(points);
    //place_search_manager.DeleteGeom();
    place_search_manager.DrawGeom();

/*var zom=8;

    if (points.length > 1 && points.length < 50){
        zom= 18;
    }
    if (points.length > 50 && points.length < 100){
        zom= 14;
    }
    if (points.length > 100 && points.length < 150){
        zom= 14;
    }
    if (points.length > 150 && points.length < 250){
        zom= 13;
    }
    if (points.length > 250 && points.length < 350){
        zom= 13;
    }
    if (points.length > 350 && points.length < 700){
        zom= 12;
    }
    if (points.length > 700 && points.length < 1000){
        zom= 11;
    }
    if (points.length > 1000 && points.length < 1300){
        zom= 10;
    }
    if (points.length > 1300 && points.length < 1700){
        zom= 10;
    }
    if (points.length > 1700 && points.length < 2000){
        zom= 9;
    }
    if (points.length > 2000 && points.length < 3000){
        zom= 9;
    }
    if (points.length > 3000 && points.length < 3500){
        zom= 8;
    }
    
    if (points[0] != undefined && points[points.length-1] != undefined ) {
        
        gmap.setCenter(new GLatLng((points[0].lat() + points[points.length-1].lat())/2, (points[0].lng() + points[points.length-1].lng())/2),zom);
    }*/
}

function SubmitPlaceSearch(PlaceSearchTerm, PlaceId) {
    StartLoading();
    unselectItems();

    var center = gmap.getCenter().x + ", " + gmap.getCenter().y;
    var baseUrl = "/default_search/SearchServlet/MapsAdapter?service=PlacesPlugin&DbId=12&place="+formatSearchTerm(PlaceSearchTerm)+"&center="+center;

    if (MAPBOUNDS_RESTRICTION_PLACE_SEARCH) {
        var southwest = gmap.getBounds().getSouthWest().x + ", " + gmap.getBounds().getSouthWest().y;
        var northeast = gmap.getBounds().getNorthEast().x + ", " + gmap.getBounds().getNorthEast().y;
        baseUrl += "&southwest="+southwest+"&northeast="+northeast;
    }
    var geocoder = new GF_Geocoder();
    geocoder.query(baseUrl,
        function(results) {
            EndLoading();
            HandlePlaceResults(results, PlaceId)
        });
}

function HandlePlaceResults(reply, id) {
    if (reply.success == false) {
        alert("No se pudo determinar el lugar "+id+" !\n\nInformación: " + reply.failureMessage);
        return;
    }
    place_search_manager.Reset();
    var places_count = 0;
    if (reply.responses.length > 0) {
        //Se asume que el set de lugares viene en el primer response en el caso de que halla mas de uno
        var response = reply.responses[0];
        if (response.success == true) {
            if (response.data != undefined && response.data.length > 0) {
                if (response.data.length > 1) {
                    place_search_manager.AddTitle(id);
                    places_count += (1*response.data.length);
                    for (var d = 0; d < response.data.length && d < 9; ++d) {
                        var data = response.data[d];
                        if (!data || !data.lon)
                            break;
                        place_search_manager.AddMarker(data, id);
                    }
                }
                place_search_manager.SetPlace(new GLatLng(response.data[0].lat, response.data[0].lon), response.data[0].name, id, (response.data.length == 1));
            }
        } else {
            place_search_manager.UnsetPlace(id);
        }
    }
    //if (places_count == 1) place_search_manager.GotoFirstResult();
    if (places_count == 1) {
        place_search_manager.GozoomFirstResult();
    }
    else {
        place_search_manager.GotoFirstResult();
    }
}

/******************************************************************************
 * PlaceSearchManager class  // CREADO POR RICARDO FRANCO
 ******************************************************************************/
function PlaceSearchManager(map_elem) {
    this.place_map_markers = [];
    this.results_map_markers = [];
    this.encoded_points = null;
    this.points = null;
    this.encoded_levels = null;
    this.overlay = [];
    this.first_result = null;
    this.open_info_window = false;
    this.showme = function() {
        this.search_results_div.style.display = "block";
    };
    var div = CreateElement(FindElement("search_dir_box"), "div");
    this.search_results_div = div;
    this.search_results_tbody = CreateElement(div, "div");
}

PlaceSearchManager.prototype.SetEncodedPoints = function(encoded) {
    this.encoded_points = encoded;
}
PlaceSearchManager.prototype.SetEncodedLevels = function(encoded) {
    this.encoded_levels = encoded;
}
PlaceSearchManager.prototype.GetEncodedPoints = function() {
    return this.encoded_points;
}
PlaceSearchManager.prototype.GetEncodedLevels = function() {
    return this.encoded_levels;
}
/**
 * Create the encoded polyline and level strings. If moveMap is true
 * move the map to the location of the first point in the polyline.
 */
PlaceSearchManager.prototype.EncodePoints = function(points) {

    // Encode a signed number in the encode format.
    function encodeSignedNumber(num) {
        var sgn_num = num << 1;

        if (num < 0) {
            sgn_num = ~(sgn_num);
        }

        return(encodeNumber(sgn_num));
    }

    // Encode an unsigned number in the encode format.
    function encodeNumber(num) {
        var encodeString = "";

        while (num >= 0x20) {
            encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
            num >>= 5;
        }

        encodeString += (String.fromCharCode(num + 63));
        return encodeString;
    }

    var i = 0;

    var plat = 0;
    var plng = 0;

    this.encoded_points = "";
    this.encoded_levels = "";

    for(i = 0; i < points.length; ++i) {
        var point = points[i];
        var lat = point.y; //Latitude;
        var lng = point.x; //Longitude;
        var level = gmap.getZoom(); //Level;

        var late5 = Math.floor(lat * 1e5);
        var lnge5 = Math.floor(lng * 1e5);

        dlat = late5 - plat;
        dlng = lnge5 - plng;

        plat = late5;
        plng = lnge5;

        this.encoded_points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
        this.encoded_levels += encodeNumber(level);
    }
}

PlaceSearchManager.prototype.Points = function(points) {
    this.points = points
}

PlaceSearchManager.prototype.DrawGeom = function() {
    
    if (this.encoded_points && this.encoded_levels) {
        this.overlay.push(GPolyline.fromEncoded({
            color: arraycolorpoly[indexarraycolorpoly],
            weight: 6,
            opacity: 0.5,
            points: this.encoded_points,
            zoomFactor: 10,
            levels: this.encoded_levels,
            numLevels: 1
        }))
        gmap.addOverlay(this.overlay[this.overlay.length-1]);
        midArrows(this.points);
    }
    indexarraycolorpoly++
}

PlaceSearchManager.prototype.DeleteGeom = function() {
    indexarraycolorpoly=0;
    for (var i = 0; i < this.overlay.length; i++){
        if (this.overlay[i]) {
            gmap.removeOverlay(this.overlay[i]);
        }
    }
    for (var i = 0; i < overlay_direction.length; i++){
        if (overlay_direction[i]) {
            gmap.removeOverlay(overlay_direction[i]);
        }
    }
}

PlaceSearchManager.prototype.Reset = function() {
    // cleanup map markers
    for (var i = 0; i < this.results_map_markers.length; i++)
        gmap.removeOverlay(this.results_map_markers[i]);
    this.results_map_markers.length = 0;
    RemoveAllChildren(this.search_results_tbody);
    this.first_result = null;
    if (this.open_info_window) {
        gmap.closeInfoWindow();
        this.open_info_window = false;
    }
}

PlaceSearchManager.prototype.GotoFirstResult = function() {
    if (this.first_result)
        gmap.panTo(this.first_result);
}

PlaceSearchManager.prototype.AddPlace = function(id) {
    var icon = new GIcon(baseIcon);
    icon.image = "/maps/gnresources/" + "icon_green" + id + ".png";
    var marker = new GMarker(gmap.getCenter(),{
        icon:icon,
        draggable:true,
        title:'Arrastre para nueva ruta.'
    });

    gmap.addOverlay(marker);
    marker.hide();


    GEvent.addListener(marker, "dragend", function() {


        if (id =="A"){
            //FindElement("A").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }
        if (id =="B"){
            //FindElement("B").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }

        if (id =="C"){
            //FindElement("A").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }
        if (id =="D"){
            //FindElement("B").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }
        if (id =="E"){
            //FindElement("A").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }
        if (id =="F"){
            //FindElement("B").value = marker.getLatLng().toUrlValue();
            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (marker.getLatLng().toUrlValue()), id);

        }

        //if (FindElement("A").value && FindElement("B").value){
        if (firstItem() && lastItem()){
            SubmitDirSearch();
            showDirSearch();
        }
    });
    this.place_map_markers[id.charCodeAt(0) - "A".charCodeAt(0)] = marker;
}

PlaceSearchManager.prototype.SetPlace = function(point, title, id, panToPoint, callSearch) {
    for (var i = 0; i < this.results_map_markers.length; i++) {
        if (this.results_map_markers[i].getLatLng().equals(point)) {
            this.results_map_markers[i].hide();
        } else {
            this.results_map_markers[i].show();
        }
    }
    FindElement("wp_"+id).style.borderColor = "#fff1a8";
    FindElement("wp_"+id).style.backgroundColor = "#ffffe6";
    FindElement("wp_location_"+id).value = point.x + ", " + point.y;
    FindElement(id).value = title;
    if (panToPoint) gmap.panTo(point);
    var index = id.charCodeAt(0) - "A".charCodeAt(0);
    if (this.place_map_markers[index]) {
        this.place_map_markers[index].setLatLng(point);
        this.place_map_markers[index].show();
    }
    if (callSearch) {
        if (IsBrowser("MSIE 6")) showDirSearch();
        else SubmitDirSearch();
    }
}

PlaceSearchManager.prototype.UnsetPlace = function(id) {
    FindElement("wp_"+id).style.borderColor = "#fff";
    FindElement("wp_"+id).style.backgroundColor = "#fff";
    FindElement("wp_location_"+id).value = "";
    var index = id.charCodeAt(0) - "A".charCodeAt(0);
    if (this.place_map_markers[index]) {
        this.place_map_markers[index].hide();
    }
}

PlaceSearchManager.prototype.AddTitle = function(id) {
    var title = CreateElement(this.search_results_tbody, "div");
    title.innerHTML = "<div class=\"roundBorderOutYellow\"><div class=\"roundBorderInYellow\">Posibles opciones para \""+id+"\" : </div></div>";


}

PlaceSearchManager.prototype.AddMarker = function(cfg, id) {
    var index = this.results_map_markers.length;
    var point = new GLatLng(cfg.lat, cfg.lon);
    if (index == 0)
        this.first_result = point;

    var desc = "";

    if (cfg.description){
        cfg.description = cfg.description.slice(0,cfg.description.indexOf("COMERCIAL"))+"<br>";
        costo = point.distanceFrom(gmap.getCenter());
        desc = cfg.description +" A una distancia de "+ costo + " mts";
        if (costo > 0 && costo < 999 ) {
            desc = cfg.description + costo + " mts";
        }
        if (costo > 999) {

            desc = cfg.description +" A una distancia de "+ Math.round((costo/1000)*100)/100  + " km,  " + Math.round((costo/1000*0.62137)*100)/100 + " mi";
        }
    }



    var marker = CreatePlaceMarker(point, cfg.name, desc, id, this.results_map_markers.length);

    // keep track of info window openings in order to close
    // when the search results are cleared
    GEvent.bindDom(marker, "infowindowopen", this,
        function() {
            this.open_info_window = true;
        });
    GEvent.bindDom(marker, "infowindowclose", this,
        function() {
            this.open_info_window = false;
        });

    gmap.addOverlay(marker);
    this.results_map_markers.push(marker);

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow(CreatePlaceInfoWindow(marker, cfg.name, desc, id));
    });


    var place = CreateElement(this.search_results_tbody, "div");
    // drop icons after A-Z has been used
    var img_elem = CreateElement(place, "img", "search_results_icon");
    if (index < 9) {
        img_elem.setAttribute("src", "/maps/gnresources/" + "icon_yellow" + (index+1) + ".png");
    } else {
        img_elem.setAttribute("src", "/maps/gnresources/" + "icon_yellow1.png");
    }
    img_elem.style.cursor = "pointer";
    GEvent.bindDom(img_elem, "click", this, this.NewCenterViewFunc(marker, cfg.name, desc, id));

    // name should always be defined
    var name_div = CreateElement(place, "div", "search_results_name_yellow");
    name_div.innerHTML = cfg.name;
    // only show snippet if one is defined
    if (cfg.snippet != undefined) {
        var snippet_div = CreateElement(place, "div", "search_results_snippet_yellow");
        snippet_div.innerHTML = cfg.snippet;
    }

    this.showme();
}

PlaceSearchManager.prototype.NewCenterViewFunc = function(marker, label, body_text, id) {
    return function(e) {
        gmap.setCenter(marker.getLatLng(), 15);
        place_search_manager.SetPlace(marker.getLatLng(), label, id);
        marker.openInfoWindow(CreatePlaceInfoWindow(marker, label, body_text, id));
        cancelEvent(e);
        return false;
    }
}

function CreatePlaceMarker(point, label, body_text, id, index) {
    var icon;
    // only specialize the marker icon if the index is A-Z
    if ((index != null) && (index < 9)) {
        icon = new GIcon(baseIcon);
        icon.image = "/maps/gnresources/" + "icon_yellow" + (index+1) + ".png";
    }
    var marker = new GMarker(point, icon);

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow(CreatePlaceInfoWindow(marker, label, body_text, id));
    });
    return marker;
}

function CreatePlaceInfoWindow(marker, label, body_text, id) {

    var info_div = document.createElement("div");
    var name_div = CreateElement(info_div, "div", "search_popup_name_yellow");
    name_div.innerHTML = label;
    var body_div = CreateElement(info_div, "div", "search_popup_body_yellow");
    body_div.innerHTML = body_text;

    /*var btn_div = CreateElement(info_div, "div", "search_popup_body_yellow");
    var btn = CreateElement(btn_div, "a", "info_window_btn");
    btn.href = 'javascript:void(0)';
    btn.appendChild(document.createTextNode("Establecer como punto \"" + id + "\" de la ruta"));

    GEvent.bindDom(btn, 'click', this, function(e) {
        place_search_manager.SetPlace(marker.getLatLng(), label, id);
        marker.closeInfoWindow();
        cancelEvent(e);
        return false;
    });*/


    return info_div;
}

/******************************************************************************
 * Geocoder class
 ******************************************************************************/

function GF_Geocoder() {
    // create a global store object where all callbacks are added/deleted
    if (!window.__gf_queryStore) {
        window.__gf_queryStore = {};
    }
}

GF_Geocoder.prototype.query = function(baseUrl, handler) {
    // generate unique id for this "script"
    var id = "gf_query_" + new Date().getTime();

    // if the script never loads we need a way to cancel the request
    var timeout = window.setTimeout(NewErrorCallback(id, handler, baseUrl, 403), search_timeout);

    window.__gf_queryStore[id] = NewCallback(this, id, handler, timeout);

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.id = id;
    script.charset = "ISO-8859-1";
    script.src = baseUrl + "&cb=__gf_queryStore." + id;

    DebugMsg("adding script tag: " + script.src);
    try {
        document.getElementsByTagName("head")[0].appendChild(script);
    } catch(err) {
        alert("Error!");
    }
}

function RemoveScriptNode(id) {
    var script = document.getElementById(id);
    if (script && script.nodeName == "SCRIPT") {
        script.parentNode.removeChild(script);
    }
}

function NewErrorCallback(id, handler, query, error) {
    return function() {
        RemoveScriptNode(id);
        handler(NewErrorReply(query, error));
        if (id && window.__gf_queryStore[id]) {
            delete window.__gf_queryStore[id];
        }
    //alert("Search Failed.");
    }
}

function NewCallback(geocoder, id, handler, timeout) {
    return function(reply) {
        window.clearTimeout(timeout);
        RemoveScriptNode(id);
        handler(reply);
        delete window.__gf_queryStore[id];
    };
}

function NewErrorReply(query, errorCode) {
    return {
        success: false,
        searchTerm: query,
        failureMessage: "network error"
    };
}

/******************************************************************************
 * Tile Layer Checkbox Management
 ******************************************************************************/

function GF_Layers(parent) {
    var form = CreateElement(parent, "form", "layers_container");
    var table = CreateElement(form, "table", "tile_layers");
    this.main_tbody = CreateElement(table, "tbody");
}
/*
 * input_type must be "radio" or "checkbox"
 */
GF_Layers.prototype.AddLayer = function(text, icon, init_state,
    click_func, input_type) {
    var row = CreateElement(this.main_tbody, "tr");

    // configure checkbox
    var td = CreateElement(row, "td");
    var input_elem;

    if (input_type == 'radio') {
        input_elem = CreateRadioInputElement(td, 'radioLayer');
    } else {
        input_elem = CreateInputElement(td, input_type);
    }
    input_elem.id=text;
    GEvent.bindDom(input_elem, "click", this, click_func);

    if (init_state == true) {
        input_elem.checked = "checked";
    } else {
        input_elem.checked = "";
    }

    // configure (optional) icon image
    td = CreateElement(row, "td");  // always create the 'td' for spacing reasons
    if (icon) {
        var img_elem = CreateElement(td, "img");
        img_elem.setAttribute("src", icon);
        img_elem.setAttribute("align", "texttop");
    }

    // configure label string
    td = CreateElement(row, "td");
    var span = CreateElement(td, "span");
    CreateTextNode(span, text);
}
function Guia_Manager(parent) {
    this.placemark_defs = [];
    /*this.handler;
    this.main_widget;*/
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_GUIA);
        this.main_widget = pane;
    } else {
        var placemark_dialog = new Dialog(parent, "placemark_dialog", FUSION_FRAME_GUIA);
        this.main_widget = placemark_dialog;
    }
    var midiv = CreateElement(this.main_widget.GetBodyDiv(),"div","divvisible");
    var form = CreateElement(midiv,
        "form", "Interest_Point_container");

    var a = CreateElement(form, "a");
    a.href = 'javascript:void(0)';
    GEvent.bindDom(a, 'click', this, function(e) {
        midiv.style.visibility = "hidden";
        midiv.style.display = "none";
        midiv2.style.visibility = "visible";
        midiv2.style.display = "block";
    });
    a.appendChild(document.createTextNode("Ocultar guía"));

    var table = CreateElement(form, "table");
    this.main_tbody = CreateElement(table, "tbody");

    var def

    var midiv2 = CreateElement(this.main_widget.GetBodyDiv(),"div","divhidden");
    midiv2.style.visibility = "hidden";
    midiv2.style.display = "none";
    var a2 = CreateElement(midiv2, "a");
    a2.href = 'javascript:void(0)';

    for (var f = 0; f < TextGuia.length; ++f) {

        def = {
            txt: unescape(TextGuia[f]),
            value:unescape(ValueGuia[f])

        };

        this.Add_Guia(def,false,midiv,midiv2);
    }

    GEvent.bindDom(a2, 'click', this, function(e) {
        midiv2.style.visibility = "hidden";
        midiv2.style.display = "none";
        midiv.style.visibility = "visible";
        midiv.style.display = "block";
    });
    a2.appendChild(document.createTextNode("Mostrar guía"));

    this.main_widget.Show();
    midiv.style.visibility = "hidden";
    midiv.style.display = "none";
    midiv2.style.visibility = "visible";
    midiv2.style.display = "block";
}

Guia_Manager.prototype.Add_Guia = function(cfg, visible,midiv,midiv2) {

    var row = CreateElement(this.main_tbody, "tr");
    cfg.entry_elem = row;

    var td = CreateElement(row, "td");
    var input_elem = CreateInputElement(td, "checkbox", "layer_check");

    for (var f = 0; f < ValueGuia.length; ++f) {
        if (ValueGuia[f] == cfg.value){
            var g =f;
        }
    }
    guia_array_check[g]=input_elem;

    if (visible == true) {
        input_elem.checked = "checked";

    }

    td = CreateElement(row, "td");
    var img_elem = CreateElement(td, "img");
    img_elem.setAttribute("src", "/maps/gnresources/iconosesp/"+tildes(cfg.value)+".png");


    td = CreateElement(row, "td");
    var a = CreateElement(td, "a");

    a.appendChild(document.createTextNode(cfg.txt));

    // build the pushpind

    var popup_body = document.createElement("div");
    var bold_label = CreateElement(popup_body, "b");
    bold_label.appendChild(document.createTextNode(cfg.txt));
    CreateElement(popup_body, "br");
    CreateElement(popup_body, "br");


    GEvent.bindDom(input_elem, "click", this, function() {

        if (!input_elem.checked) {
            // search_manager_cat.Hide();
            for (var f = 0; f < ValueGuia.length; ++f) {
                if (ValueGuia[f] == cfg.value){
                    var g =f;
                }
            }
            guia_array_results[g].Hide();


        } else {
            SubmitSearchGuia(cfg.value);
            midiv.style.visibility = "hidden";
            midiv.style.display = "none";
            midiv2.style.visibility = "visible";
            midiv2.style.display = "block";
        }
    });

    this.placemark_defs.push(cfg);

}

function Interest_Point_Manager(parent) {
    this.placemark_defs = [];
    /*this.handler;
    this.main_widget;*/
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_INTEREST_POINT);
        this.main_widget = pane;
    } else {
        var placemark_dialog = new Dialog(parent, "placemark_dialog", FUSION_FRAME_INTEREST_POINT);
        this.main_widget = placemark_dialog;
    }
    var midiv = CreateElement(this.main_widget.GetBodyDiv(),"div","divvisible");
    var form = CreateElement(midiv,
        "form", "Interest_Point_container");

    var a = CreateElement(form, "a");
    a.href = 'javascript:void(0)';
    GEvent.bindDom(a, 'click', this, function(e) {
        midiv.style.visibility = "hidden";
        midiv.style.display = "none";
        midiv2.style.visibility = "visible";
        midiv2.style.display = "block";
    });
    a.appendChild(document.createTextNode("Ocultar categorías"));

    var table = CreateElement(form, "table");
    this.main_tbody = CreateElement(table, "tbody");

    var def

    var midiv2 = CreateElement(this.main_widget.GetBodyDiv(),"div","divhidden");
    midiv2.style.visibility = "hidden";
    midiv2.style.display = "none";
    var a2 = CreateElement(midiv2, "a");
    a2.href = 'javascript:void(0)';

    for (var f = 0; f < TextCategorias.length; ++f) {

        def = {
            txt: unescape(TextCategorias[f]),
            value:unescape(ValueCategorias[f])

        };

        this.Add_Interest_Point(def,false,midiv,midiv2);
    }

    GEvent.bindDom(a2, 'click', this, function(e) {
        midiv2.style.visibility = "hidden";
        midiv2.style.display = "none";
        midiv.style.visibility = "visible";
        midiv.style.display = "block";
    });
    a2.appendChild(document.createTextNode("Mostrar categorías"));

    this.main_widget.Show();
    midiv.style.visibility = "hidden";
    midiv.style.display = "none";
    midiv2.style.visibility = "visible";
    midiv2.style.display = "block";
}

Interest_Point_Manager.prototype.Add_Interest_Point = function(cfg, visible,midiv,midiv2) {

    var row = CreateElement(this.main_tbody, "tr");
    cfg.entry_elem = row;

    var td = CreateElement(row, "td");
    var input_elem = CreateInputElement(td, "checkbox", "layer_check");

    for (var f = 0; f < ValueCategorias.length; ++f) {
        if (ValueCategorias[f] == cfg.value){
            var g =f;
        }
    }
    cat_array_check[g]=input_elem;

    if (visible == true) {
        input_elem.checked = "checked";

    }

    td = CreateElement(row, "td");
    var img_elem = CreateElement(td, "img");
    img_elem.setAttribute("src", "/maps/gnresources/iconosesp/"+tildes(cfg.value)+".png");

    td = CreateElement(row, "td");
    var a = CreateElement(td, "a");

    a.appendChild(document.createTextNode(cfg.txt));

    // build the pushpin
    var popup_body = document.createElement("div");
    var bold_label = CreateElement(popup_body, "b");
    bold_label.appendChild(document.createTextNode(cfg.txt));
    CreateElement(popup_body, "br");
    CreateElement(popup_body, "br");


    GEvent.bindDom(input_elem, "click", this, function() {

        if (!input_elem.checked) {
            // search_manager_cat.Hide();
            for (var f = 0; f < ValueCategorias.length; ++f) {
                if (ValueCategorias[f] == cfg.value){
                    var g =f;
                }
            }
            cat_array_results[g].Hide();


        } else {
            SubmitSearchCat(cfg.value);
            midiv.style.visibility = "hidden";
            midiv.style.display = "none";
            midiv2.style.visibility = "visible";
            midiv2.style.display = "block";
        }
    });

    this.placemark_defs.push(cfg);

}

function Especiales_Manager(parent) {
    this.placemark_defs = [];
    /*this.handler;
    this.main_widget;*/
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_ESPECIALES);
        this.main_widget = pane;
    } else {
        var placemark_dialog = new Dialog(parent, "placemark_dialog", ESPECIALES);
        this.main_widget = placemark_dialog;
    }

    var form = CreateElement(this.main_widget.GetBodyDiv(),
        "form", "Interest_Point_container");
    var table = CreateElement(form, "table");
    this.main_tbody = CreateElement(table, "tbody");

    var def

    for (var f = 0; f < TextEspeciales.length; ++f) {

        def = {
            txt: unescape(TextEspeciales[f]),
            value:unescape(ValueEspeciales[f])

        };

        this.Add_Interest_Point(def,false);
    }

    this.main_widget.Show();
}

Especiales_Manager.prototype.Add_Interest_Point = function(cfg, visible) {

    var row = CreateElement(this.main_tbody, "tr");
    cfg.entry_elem = row;

    var td = CreateElement(row, "td");
    var input_elem = CreateInputElement(td, "checkbox", "layer_check");

    for (var f = 0; f < ValueEspeciales.length; ++f) {
        if (ValueEspeciales[f] == cfg.value){
            var g =f;
        }
    }
    esp_array_check[g]=input_elem;

    if (visible == true) {
        input_elem.checked = "checked";
    }

    td = CreateElement(row, "td");
    var a = CreateElement(td, "a");

    a.appendChild(document.createTextNode(cfg.txt));

    // build the pushpin
    var popup_body = document.createElement("div");
    var bold_label = CreateElement(popup_body, "b");
    bold_label.appendChild(document.createTextNode(cfg.txt));
    CreateElement(popup_body, "br");
    CreateElement(popup_body, "br");


    GEvent.bindDom(input_elem, "click", this, function() {
        gmap.setCenter(new GLatLng(9.947433471679688,-84.30564880371094),11);
        if (!input_elem.checked) {
            // search_manager_cat.Hide();
            for (var f = 0; f < ValueEspeciales.length; ++f) {
                if (ValueEspeciales[f] == cfg.value){
                    var g =f;

                }
            }
            esp_array_results[g].Hide();
        //gmap.setCenter(initial_view, initial_zoom);


        } else {

            for (var h = 0; h < ValueEspeciales.length; ++h) {
                if (ValueEspeciales[h] == cfg.value){
                    var j =h;
                }
            }
            if (j == 0){
                SubmitSearchEsp(cfg.value);
                gmap.setCenter(new GLatLng(9.911361873335439,-84.12403106689453),12);
            }
            else{
                SubmitSearchEsp(cfg.value);
                gmap.setCenter(new GLatLng(9.947433471679688,-84.30564880371094),11);

            }
            var midiv = document.getElementById("divvisible");
            var midiv2 = document.getElementById("divhidden");

            midiv.style.visibility = "hidden";
            midiv.style.display = "none";
            midiv2.style.visibility = "visible";
            midiv2.style.display = "block";
        }
    });

    this.placemark_defs.push(cfg);

}
/******************************************************************************
 * A simple placemark system
 *
 * Placemark data config structure:
 *   var txt (string) - Label
 *   var lat (float)  - Latitude of point
 *   var lng (float)  - Longitude of point
 *   var zoom (int)   - Zoom level
 *
 ******************************************************************************/
var MYPLACES_COOKIE = 'myplaces';
var MYPLACES_USER = 'myplaces_user';

function PlacemarkManager(parent) {
    this.placemark_defs = [];
    this.handler;
    this.main_widget;
    if (sidepanel_docker) {
        var pane = sidepanel_docker.AddPane(FUSION_FRAME_MYPLACES_NAME);
        this.main_widget = pane;
    } else {
        var placemark_dialog = new Dialog(parent, "placemark_dialog", FUSION_FRAME_MYPLACES_NAME);
        this.main_widget = placemark_dialog;
    }

    var form = CreateElement(this.main_widget.GetBodyDiv(),
        "form", "myplaces_container");
    var table = CreateElement(form, "table");
    this.main_tbody = CreateElement(table, "tbody");


    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
    var placemark_cookie;

    if (cokie !="") {
        placemark_cookie = cadena.decode(getCookie(MYPLACES_USER));
    }

    else {
        placemark_cookie = GetCookieValue(MYPLACES_COOKIE);

    }

    if (placemark_cookie) {
        var placemarks = placemark_cookie.split('|');
        for (var p = 0; p < placemarks.length; ++p) {
            var parms = placemarks[p].split(':');
            if (parms.length == 4) {
                var def = {
                    txt: unescape(parms[0]),
                    lat: parseFloat(parms[1]),
                    lng: parseFloat(parms[2]),
                    zoom: parseInt(parms[3], 10)
                };

                this.AddPlacemark(def, false);
            } else {
                DebugMsg("Bad placemark cookie: " + placemarks[p]);
            }
        }
    }

    var add_btn = CreateElement(this.main_widget.GetFooterDiv(), 'a');
    add_btn.href = 'javascript:void(0)';
    GEvent.bindDom(add_btn, 'click', this, function(e) {
        var center = gmap.getCenter();
        DebugMsg("Center: " + center);
        this.NewPlacemarkAtPoint(center,"");
        cancelEvent(e);
        return false;
    });
    add_btn.appendChild(document.createTextNode("Agregar lugar " ));

    CreateElement(FindElement("sidepanel"), "div", "status");
    document.getElementById("status").style.visibility = 'hidden';
    document.getElementById("status").style.textAlign = "center";

    var add_btn2 = CreateElement(this.main_widget.GetFooterDiv(), 'a');
    add_btn2.href = 'javascript:void(0)';
    GEvent.bindDom(add_btn2, 'click', this, function(e) {
        alert('Se activo dibujo de líneas');  tipodibujo = true;
        document.getElementById("status").style.visibility = 'visible'

        toggleMode();
    });
    add_btn2.appendChild(document.createTextNode(" Agregar líneas "));

    var add_btn3 = CreateElement(this.main_widget.GetFooterDiv(), 'a');
    add_btn3.href = 'javascript:void(0)';
    GEvent.bindDom(add_btn3, 'click', this, function(e) {
        alert('Se activo dibujo de polígonos'); tipodibujo = false;
        document.getElementById("status").style.visibility = 'visible'

        toggleMode();
    });
    add_btn3.appendChild(document.createTextNode(" Agregar polígonos"));


    this.main_widget.Show();
}

PlacemarkManager.prototype.Save = function() {
    var me = this;
    var cookie = "";

    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));

    if (cokie !="") {
        for (var p = 0; p < me.placemark_defs.length; ++p) {
            if (cookie)
                cookie += '|';
            cookie += cadena.encode(me.placemark_defs[p].txt) +
            ':' + me.placemark_defs[p].lat +
            ':' + me.placemark_defs[p].lng +
            ':' + me.placemark_defs[p].zoom;
        }

        cookie += "; max-age=" + 315360000; /* expires ten years from now */

        if ( getCookie( MYPLACES_USER ) ) document.cookie = MYPLACES_USER + '=' +
            ( ( '/maps' ) ? ';path=' + '/maps' : '') +
            ( ( 'nacion.co.cr' ) ? ';domain=' + 'nacion.co.cr' : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
        if ( getCookie( MYPLACES_USER ) ) document.cookie = MYPLACES_USER + '=' +
            ( ( '/maps/' ) ? ';path=' + '/maps' : '') +
            ( ( 'nacion.co.cr' ) ? ';domain=' + 'nacion.co.cr' : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
        SetCookieValue(MYPLACES_USER, cookie);
    }

    else {
        for (var q = 0; q < me.placemark_defs.length; ++q) {
            if (cookie)
                cookie += '|';
            cookie += escape(me.placemark_defs[q].txt) +
            ':' + me.placemark_defs[q].lat +
            ':' + me.placemark_defs[q].lng +
            ':' + me.placemark_defs[q].zoom;
        }
        cookie += "; max-age=" + 315360000; /* expires ten years from now */


        SetCookieValue(MYPLACES_COOKIE, cookie);

    }

}

PlacemarkManager.prototype.Delete = function(def) {
    var me = this;
    for (var p = 0; p < me.placemark_defs.length; ++p) {
        if (me.placemark_defs[p] == def) {
            me.placemark_defs.splice(p, 1);
            def.entry_elem.parentNode.removeChild(def.entry_elem);
            this.Save();

            break;
        }
    }
}

PlacemarkManager.prototype.NewPlacemarkAtPointLink = function(point) {
    var div_elem = document.createElement("div");
    div_elem.style.padding = "0px 10px 0px 10px";
    var name_div = CreateElement(div_elem, "div", "search_popup_name");
    name_div.innerHTML = "Copiar enlace para enviar esta vista";
    var table_elem = CreateElement(div_elem, "table");
    var tbody = CreateElement(table_elem, "tbody");
    var row0 = CreateElement(tbody, "tr");


    var row0_c1 = CreateElement(row0, "td");
    var label_elem = CreateElement(row0_c1, "textarea");
    label_elem.style.width = "300px";
    //guarda cuando se arrastra el punto el nombre
    label_elem.value ="http://lnmapas.nacion.co.cr/maps/index.shtml?ll="+point.lat()+","+point.lng()+"&z="+gmap.getZoom();



    // TODO: support dragging the marker someday
    var marker = new GMarker(point, {
        draggable: true
    });
    marker.enableDragging();
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow(div_elem);

        GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
            gmap.getInfoWindow().hide();
            gmap.removeOverlay(marker);
        });
        GEvent.addListener(marker, "dragend", function() {
            placemark_manager.NewPlacemarkAtPointLink(marker.getLatLng());
            gmap.removeOverlay(marker);
        });
    /*GEvent.bindDom(gmap, "click", this, function(e) {
            gmap.getInfoWindow().hide();
            gmap.removeOverlay(marker);
        });*/
    });

    GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
        gmap.getInfoWindow().hide();
        gmap.removeOverlay(marker);
    });
    GEvent.addListener(marker, "dragend", function() {
        placemark_manager.NewPlacemarkAtPointLink(marker.getLatLng());
        gmap.removeOverlay(marker);
    });
    /*GEvent.bindDom(gmap, "click", this, function(e) {
        gmap.getInfoWindow().hide();
        gmap.removeOverlay(marker);
    });*/

    gmap.addOverlay(marker);
    marker.openInfoWindow(div_elem);
}

PlacemarkManager.prototype.NewPlacemarkAtPoint = function(point, txt) {

    var div_elem = document.createElement("div");
    div_elem.style.padding = "0px 10px 0px 10px";
    var name_div = CreateElement(div_elem, "div", "search_popup_name");
    name_div.innerHTML = "Guardar en mis lugares";
    var table_elem = CreateElement(div_elem, "table");
    var tbody = CreateElement(table_elem, "tbody");
    var row0 = CreateElement(tbody, "tr");
    var row0_c0 = CreateElement(row0, "td");
    row0_c0.appendChild(document.createTextNode("Etiqueta:"));
    var row0_c1 = CreateElement(row0, "td");
    var form_elem = CreateElement(row0_c1, "form");
    var label_elem = CreateInputElement(form_elem, "text");
    label_elem.style.width = "200px";
    //guarda cuando se arrastra el punto el nombre
    label_elem.value =txt;

    var row1 = CreateElement(tbody, "tr");
    var row1_c0 = CreateElement(row1, "td");
    row1_c0.appendChild(document.createTextNode("Latitud:"));
    var row1_c1 = CreateElement(row1, "td");
    row1_c1.appendChild(document.createTextNode(point.lat()));

    var row2 = CreateElement(tbody, "tr");
    var row2_c0 = CreateElement(row2, "td");
    row2_c0.appendChild(document.createTextNode("Longitud:"));
    var row2_c1 = CreateElement(row2, "td");
    row2_c1.appendChild(document.createTextNode(point.lng()));

    var row3 = CreateElement(tbody, "tr");
    var row3_c0 = CreateElement(row3, "td");
    row3_c0.appendChild(document.createTextNode("Zoom:"));
    var row3_c1 = CreateElement(row3, "td");
    row3_c1.appendChild(document.createTextNode(gmap.getZoom()));

    var btn_div_elem = CreateElement(div_elem, "div");
    btn_div_elem.align = "right";
    btn_div_elem.style.borderTop = "1px solid gray";
    btn_div_elem.style.padding = "4px 0px";
    btn_form_elem = CreateElement(btn_div_elem, "form");
    var cancel_btn = CreateInputElement(btn_form_elem, "button");
    cancel_btn.value = "Cancelar";
    var ok_btn = CreateInputElement(btn_form_elem, "button");
    ok_btn.value = "OK";

    //var marker = new GMarker(point);
    // TODO: support dragging the marker someday
    var marker = new GMarker(point, {
        draggable: true
    });
    marker.enableDragging();

    GEvent.bindDom(ok_btn, "click", this, function(e) {
        if (label_elem.value) {
            placemark_manager.AddPlacemark({
                txt: label_elem.value,
                lat: point.lat(),
                lng: point.lng(),
                zoom: gmap.getZoom()
            }, true);
            gmap.getInfoWindow().hide();
            gmap.removeOverlay(marker);
            placemark_manager.Save();

        } else {
            alert("Etiqueta es requerida");
        }
        cancelEvent(e);
        return false;
    });
    GEvent.bindDom(cancel_btn, "click", this, function(e) {
        gmap.getInfoWindow().hide();
        gmap.removeOverlay(marker);
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
        gmap.removeOverlay(marker);
        //cancelEvent(e);
        return false;
    });

    var div_elem2 = document.createElement("div");
    div_elem2.style.padding = "0px 10px 0px 10px";
    var name_div2 = CreateElement(div_elem2, "div", "search_popup_name");
    name_div2.innerHTML = "Guardar mis puntos";
    var table_elem2 = CreateElement(div_elem2, "table");
    var tbody2 = CreateElement(table_elem2, "tbody");
    var row02 = CreateElement(tbody2, "tr");
    var row0_c02 = CreateElement(row02, "td");
    row0_c02.appendChild(document.createTextNode("Etiqueta:"));
    var row0_c12 = CreateElement(row02, "td");
    var form_elem2 = CreateElement(row0_c12, "form2");
    var label_elem2 = CreateInputElement(form_elem2, "text");
    label_elem2.style.width = "200px";
    //guarda cuando se arrastra el punto el nombre
    label_elem2.value =txt;

    var row022 = CreateElement(tbody2, "tr");
    var row0_c022 = CreateElement(row022, "td");
    row0_c022.appendChild(document.createTextNode("Descripcion:"));
    var row0_c122 = CreateElement(row022, "td");
    var form_elem22 = CreateElement(row0_c122, "form2");
    var label_elem22 = CreateInputElement(form_elem22, "text");
    label_elem22.style.width = "200px";

    var row0223 = CreateElement(tbody2, "tr");
    var row0_c0223 = CreateElement(row0223, "td");
    row0_c0223.appendChild(document.createTextNode("Categoria:"));
    var row0_c1223 = CreateElement(row0223, "td");
    var sele = document.createElement('select');

    for (var f = 0; f < SendCategorias.length; ++f) {
        var opt = document.createElement('option');
        opt.value = unescape(SendCategorias[f]);
        opt.innerHTML = unescape(SendCategorias[f]);
        sele.appendChild(opt);
    }
    row0_c1223.appendChild(sele);

    var row22 = CreateElement(tbody2, "tr");
    var row2_c02 = CreateElement(row22, "td");
    row2_c02.appendChild(document.createTextNode("Longitud:"));
    var row2_c12 = CreateElement(row22, "td");
    row2_c12.appendChild(document.createTextNode(point.lng()));

    var row12 = CreateElement(tbody2, "tr");
    var row1_c02 = CreateElement(row12, "td");
    row1_c02.appendChild(document.createTextNode("Latitud:"));
    var row1_c12 = CreateElement(row12, "td");
    row1_c12.appendChild(document.createTextNode(point.lat()));

    var row32 = CreateElement(tbody2, "tr");
    var row3_c02 = CreateElement(row32, "td");
    row3_c02.appendChild(document.createTextNode("Zoom:"));
    var row3_c12 = CreateElement(row32, "td");
    row3_c12.appendChild(document.createTextNode(gmap.getZoom()));

    var btn_div_elem2 = CreateElement(div_elem2, "div");
    btn_div_elem2.align = "right";
    btn_div_elem2.style.borderTop = "1px solid gray";
    btn_div_elem2.style.padding = "4px 0px";
    btn_form_elem2 = CreateElement(btn_div_elem2, "form2");
    var cancel_btn2 = CreateInputElement(btn_form_elem2, "button");
    cancel_btn2.value = "Cancelar";
    var ok_btn2 = CreateInputElement(btn_form_elem2, "button");
    ok_btn2.value = "OK";

    gmap.addOverlay(marker);

    var tabs = [];
    // Create tabs and add them to the array
    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
    if (cokie !="") {
        tabs.push(new GInfoWindowTab("Guardar", div_elem2));
    }
    else
    {
        tabs.push(new GInfoWindowTab("Guardar", div_elem));
    }

    GEvent.bindDom(ok_btn2, "click", this, function(e) {
        if (label_elem2.value && label_elem22.value) {
            var place = cokie.split('|');
            var parms = place[0].split('&');
            var codigo = parms[0].split(':');
            var user = parms[1].split(':');
            var usux =user[1].substr(0,user[1].indexOf ('"'));
            //alert("Etiqueta "+label_elem2.value+"Descripcion "+label_elem22.value+"Categoria "+sele.value+"Latitud "+point.lat()+"Longitud "+point.lng()+"Codigio Usuario "+codigo[1]+"Usuario "+usux);
            div_elem2.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarPunto?etiqueta="+label_elem2.value+"&descripcion="+label_elem22.value+"&categoria="+sele.value+"&latitud="+point.lat()+"&longitud="+point.lng()+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
            //gmap.getInfoWindow().hide();
            //gmap.removeOverlay(marker);
            placemark_manager.AddPlacemark({
                txt: label_elem2.value,
                lat: point.lat(),
                lng: point.lng(),
                zoom: gmap.getZoom()
            }, true);
            placemark_manager.Save();

        } else {
            alert("Campos son requeridos");
        }

        cancelEvent(e);
        return false;
    });
    GEvent.bindDom(cancel_btn2, "click", this, function(e) {
        gmap.getInfoWindow().hide();
        gmap.removeOverlay(marker);
        cancelEvent(e);

        return false;
    });

    GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
        gmap.removeOverlay(marker);
        //cancelEvent(e);

        return false;
    });


    GEvent.addListener(marker, "click", function() {
        if (cokie !="") {
            DebugMsg("Center: " +  marker.getLatLng());
            placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),label_elem2.value);
            gmap.removeOverlay(marker);
        }
        else
        {
            DebugMsg("Center: " +  marker.getLatLng());
            placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),label_elem.value);
            gmap.removeOverlay(marker);
        }
    });


    GEvent.addListener(marker, "dragend", function() {
        if (cokie !="") {
            DebugMsg("Center: " +  marker.getLatLng());
            placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),label_elem2.value);
            gmap.removeOverlay(marker);
        }
        else
        {
            DebugMsg("Center: " +  marker.getLatLng());
            placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),label_elem.value);
            gmap.removeOverlay(marker);
        }

    });

    // Add tabs to the InfowWindow
    marker.openInfoWindowTabsHtml(tabs);

}

PlacemarkManager.prototype.SendPlacemarkAtPoint = function(point, txt,lati,longi ) {

    var div_elem = document.createElement("div");
    div_elem.style.padding = "0px 10px 0px 10px";
    var name_div = CreateElement(div_elem, "div", "search_popup_name");
    name_div.innerHTML = "Si considera que el nombre esta mal escrito  <br> sugiéranos el correcto.";
    var table_elem = CreateElement(div_elem, "table");
    var tbody = CreateElement(table_elem, "tbody");
    var row0 = CreateElement(tbody, "tr");
    var row0_c0 = CreateElement(row0, "td");
    row0_c0.appendChild(document.createTextNode("Etiqueta:"));
    var row0_c1 = CreateElement(row0, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem = CreateElement(row0_c1, "form");
    var label_elem = CreateInputElement(form_elem, "text");
    label_elem.style.width = "275px";
    label_elem.value =txt;

    var name_div2 = CreateElement(div_elem, "div", "search_popup_name");
    name_div2.innerHTML = "Si la ubicación es incorrecta ingrese los datos <br> o arrastre el punto hasta la posición correcta <br> ";

    var table_elem2 = CreateElement(div_elem, "table");
    var tbody2 = CreateElement(table_elem2, "tbody");
    var row1 = CreateElement(tbody2, "tr");
    var row1_c0 = CreateElement(row1, "td");
    row1_c0.appendChild(document.createTextNode("Longitud:"));
    var row1_c1 = CreateElement(row1, "td");
    //row1_c1.appendChild(document.createTextNode(point.lat()));
    var form_elem2 = CreateElement(row1_c1, "form");
    var label_elem2 = CreateInputElement(form_elem2, "text");
    label_elem2.style.width = "150px";
    label_elem2.value =point.lng();

    var row2 = CreateElement(tbody2, "tr");
    var row2_c0 = CreateElement(row2, "td");
    row2_c0.appendChild(document.createTextNode("Latitud:"));
    var row2_c1 = CreateElement(row2, "td");
    //row2_c1.appendChild(document.createTextNode(point.lng()));
    var form_elem3 = CreateElement(row2_c1, "form");
    var label_elem3 = CreateInputElement(form_elem3, "text");
    label_elem3.style.width = "150px";
    label_elem3.value =point.lat();

    var btn_div_elem = CreateElement(div_elem, "div");
    btn_div_elem.align = "right";
    btn_div_elem.style.borderTop = "1px solid gray";
    btn_div_elem.style.padding = "4px 0px";
    btn_form_elem = CreateElement(btn_div_elem, "form");
    var cancel_btn = CreateInputElement(btn_form_elem, "button");
    cancel_btn.value = "Cancelar";
    var ok_btn = CreateInputElement(btn_form_elem, "button");
    ok_btn.value = "Enviar";

    //var marker = new GMarker(point);
    // TODO: support dragging the marker someday
    var marker = new GMarker(point, {
        draggable: true
    });
    marker.enableDragging();


    gmap.addOverlay(marker);
    marker.openInfoWindow(div_elem);

    GEvent.addListener(marker, "dragend", function(e) {

        juntoslatlon =marker.getLatLng().toUrlValue();
        divilatlon = juntoslatlon.split(',');


        var div_elem = document.createElement("div");
        div_elem.style.padding = "0px 10px 0px 10px";
        var name_div = CreateElement(div_elem, "div", "search_popup_name");
        name_div.innerHTML = "Si considera que el nombre esta mal escrito  <br> sugiéranos el correcto.";
        var table_elem = CreateElement(div_elem, "table");
        var tbody = CreateElement(table_elem, "tbody");
        var row0 = CreateElement(tbody, "tr");
        var row0_c0 = CreateElement(row0, "td");
        row0_c0.appendChild(document.createTextNode("Etiqueta:"));
        var row0_c1 = CreateElement(row0, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem = CreateElement(row0_c1, "form");
        var label_elem = CreateInputElement(form_elem, "text");
        label_elem.style.width = "275px";
        label_elem.value =txt;

        var name_div2 = CreateElement(div_elem, "div", "search_popup_name");
        name_div2.innerHTML = "Si la ubicación es incorrecta ingrese los datos <br> o arrastre el punto hasta la posición correcta <br> ";

        var table_elem2 = CreateElement(div_elem, "table");
        var tbody2 = CreateElement(table_elem2, "tbody");
        var row1 = CreateElement(tbody2, "tr");
        var row1_c0 = CreateElement(row1, "td");
        row1_c0.appendChild(document.createTextNode("Longitud:"));
        var row1_c1 = CreateElement(row1, "td");
        //row1_c1.appendChild(document.createTextNode(point.lat()));
        var form_elem2 = CreateElement(row1_c1, "form");
        var label_elem2 = CreateInputElement(form_elem2, "text");
        label_elem2.style.width = "150px";
        label_elem2.value =divilatlon[0];

        var row2 = CreateElement(tbody2, "tr");
        var row2_c0 = CreateElement(row2, "td");
        row2_c0.appendChild(document.createTextNode("Latitud:"));
        var row2_c1 = CreateElement(row2, "td");
        //row2_c1.appendChild(document.createTextNode(point.lng()));
        var form_elem3 = CreateElement(row2_c1, "form");
        var label_elem3 = CreateInputElement(form_elem3, "text");
        label_elem3.style.width = "150px";
        label_elem3.value =divilatlon[1];

        var btn_div_elem = CreateElement(div_elem, "div");
        btn_div_elem.align = "right";
        btn_div_elem.style.borderTop = "1px solid gray";
        btn_div_elem.style.padding = "4px 0px";
        btn_form_elem = CreateElement(btn_div_elem, "form");
        var cancel_btn = CreateInputElement(btn_form_elem, "button");
        cancel_btn.value = "Cancelar";
        var ok_btn = CreateInputElement(btn_form_elem, "button");
        ok_btn.value = "Enviar";

        marker.openInfoWindow(div_elem);

        GEvent.bindDom(ok_btn, "click", this, function(e) {

            if (label_elem.value && label_elem3.value && label_elem2.value) {
                var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
                if (cokie !="") {
                    var place = cokie.split('|');
                    var parms = place[0].split('&');
                    var codigo = parms[0].split(':');
                    var user = parms[1].split(':');
                    var usux =user[1].substr(0,user[1].indexOf ('"'));
                    div_elem.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarCambioPunto?etiqueta="+txt+"&longitud="+longi+"&latitud="+lati+ "&etiquetanueva="+label_elem.value+"&longitudnueva="+label_elem2.value+"&latitudnueva="+label_elem3.value+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                    banderaguardarpunto = 0;
                    nombreguardarpunto = "";
                    //search_manager.Reset();
                    cancelEvent(e);
                    return false;
                } else {
                    alert("Ingrese como usuario del sistema.");
                    return false;
                }
            } else {
                alert("Datos son requeridos");
                return false;
            }

            return false;
        });
        GEvent.bindDom(cancel_btn, "click", this, function(e) {
            gmap.getInfoWindow().hide();
            banderaguardarpunto = 0;
            nombreguardarpunto = "";
            gmap.removeOverlay(marker);
            //search_manager.Reset();
            cancelEvent(e);
            return false;
        });

        GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
            gmap.removeOverlay(marker);
            //cancelEvent(e);
            return false;
        });


        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindow(div_elem);
        });

    });



    GEvent.bindDom(ok_btn, "click", this, function(e) {

        if (label_elem.value && label_elem3.value && label_elem2.value) {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            if (cokie !="") {
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                div_elem.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarCambioPunto?etiqueta="+txt+"&longitud="+longi+"&latitud="+lati+ "&etiquetanueva="+label_elem.value+"&longitudnueva="+label_elem2.value+"&latitudnueva="+label_elem3.value+"&zoom="+gmap.getZoom()+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
                banderaguardarpunto = 0;
                nombreguardarpunto = "";
                //search_manager.Reset();
                cancelEvent(e);
                return false;
            } else {
                alert("Ingrese como usuario del sistema.");
                return false;
            }
        } else {
            alert("Datos son requeridos");
            return false;
        }

        return false;
    });
    GEvent.bindDom(cancel_btn, "click", this, function(e) {
        gmap.getInfoWindow().hide();
        banderaguardarpunto = 0;
        nombreguardarpunto = "";
        gmap.removeOverlay(marker);
        //search_manager.Reset();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
        gmap.removeOverlay(marker);
        //cancelEvent(e);
        return false;
    });


    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow(div_elem);
    });
}

PlacemarkManager.prototype.SendPlacemarkComercialAtPoint = function(point,txt,comercial,lati,longi ) {

    var telefono1= " ";
    var telefono2= " ";
    var telefono3= " ";
    var direccion= " ";
    var email= " ";
    var nombresa= " ";
    var horario= " ";
    var sitioweb= " ";
    var descripcion= " ";
    var comer;

    for (var p = 1; p < comercial.length; p++) {
        comer = comercial[p].split(":");

        if(comer[0] == "Teléfono1") telefono1 =comer[1];
        if(comer[0] == "Teléfono2") telefono2 =comer[1];
        if(comer[0] == "Teléfono3") telefono3 =comer[1];
        if(comer[0] == "Dirección") direccion =comer[1];
        if(comer[0] == "E-mail") email =comer[1];
        if(comer[0] == "Nombre S.A") nombresa =comer[1];
        if(comer[0] == "Horario") horario =comer[1];
        if(comer[0] == "Sitio Web") sitioweb =comer[1];
        if(comer[0] == "Descripción") descripcion =comer[1];

    }
    var div_elem = document.createElement("div");
    div_elem.style.padding = "0px 10px 0px 10px";

    /*var name_div1 = CreateElement(div_elem, "div", "search_popup_name");

    name_div1.innerHTML = "Modificación de ubicación.<br>Arrastre el punto hasta la ubicación correcta";
    var table_elem1 = CreateElement(div_elem, "table");
    var tbody1 = CreateElement(table_elem1, "tbody");

    var row7     = CreateElement(tbody1, "tr");
    var row7_c0 = CreateElement(row7, "td");
    row7_c0.appendChild(document.createTextNode("Latitud"));
    var row7_c1 = CreateElement(row7, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem7 = CreateElement(row7_c1, "form");
    var label_elem7 = CreateInputElement(form_elem7, "text");
    label_elem7.style.width = "275px";
    label_elem7.value =lati;

    var row8     = CreateElement(tbody1, "tr");
    var row8_c0 = CreateElement(row8, "td");
    row8_c0.appendChild(document.createTextNode("Longitud"));
    var row8_c1 = CreateElement(row8, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem8 = CreateElement(row8_c1, "form");
    var label_elem8 = CreateInputElement(form_elem8, "text");
    label_elem8.style.width = "275px";
    label_elem8.value =longi;*/

    var name_div = CreateElement(div_elem, "div", "search_popup_name");
    name_div.innerHTML = "Modificación de datos comerciales.";
    var table_elem = CreateElement(div_elem, "table");
    var tbody = CreateElement(table_elem, "tbody");

    var row = CreateElement(tbody, "tr");
    var row_c0 = CreateElement(row, "td");
    row_c0.appendChild(document.createTextNode("Nombre: "));
    var row_c1 = CreateElement(row, "td");
    row_c1.appendChild(document.createTextNode(txt));
    /*var form_elemn = CreateElement(row_c1, "form");
    var label_elemn = CreateInputElement(form_elemn, "text");
    label_elemn.style.width = "275px";
    label_elemn.value =txt;*/

    var row0 = CreateElement(tbody, "tr");
    var row0_c0 = CreateElement(row0, "td");
    row0_c0.appendChild(document.createTextNode("Teléfono 1: "));
    var row0_c1 = CreateElement(row0, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem = CreateElement(row0_c1, "form");
    var label_elem = CreateInputElement(form_elem, "text");
    label_elem.style.width = "275px";
    label_elem.value =telefono1;

    var row07 = CreateElement(tbody, "tr");
    var row0_c07 = CreateElement(row07, "td");
    row0_c07.appendChild(document.createTextNode("Teléfono 2: "));
    var row0_c17 = CreateElement(row07, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem7 = CreateElement(row0_c17, "form");
    var label_elem7 = CreateInputElement(form_elem7, "text");
    label_elem7.style.width = "275px";
    label_elem7.value =telefono2;

    var row08 = CreateElement(tbody, "tr");
    var row0_c08 = CreateElement(row08, "td");
    row0_c08.appendChild(document.createTextNode("Teléfono 3: "));
    var row0_c18 = CreateElement(row08, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem8 = CreateElement(row0_c18, "form");
    var label_elem8 = CreateInputElement(form_elem8, "text");
    label_elem8.style.width = "275px";
    label_elem8.value =telefono3;

    var row1 = CreateElement(tbody, "tr");
    var row1_c0 = CreateElement(row1, "td");
    row1_c0.appendChild(document.createTextNode("Dirección: "));
    var row1_c1 = CreateElement(row1, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem1 = CreateElement(row1_c1, "form");
    var label_elem1 = CreateInputElement(form_elem1, "text");
    label_elem1.style.width = "275px";
    label_elem1.value =direccion;

    var row2 = CreateElement(tbody, "tr");
    var row2_c0 = CreateElement(row2, "td");
    row2_c0.appendChild(document.createTextNode("E-mail: "));
    var row2_c1 = CreateElement(row2, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem2 = CreateElement(row2_c1, "form");
    var label_elem2 = CreateInputElement(form_elem2, "text");
    label_elem2.style.width = "275px";
    label_elem2.value =email;

    var row3     = CreateElement(tbody, "tr");
    var row3_c0 = CreateElement(row3, "td");
    row3_c0.appendChild(document.createTextNode("Nombre S.A: "));
    var row3_c1 = CreateElement(row3, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem3 = CreateElement(row3_c1, "form");
    var label_elem3 = CreateInputElement(form_elem3, "text");
    label_elem3.style.width = "275px";
    label_elem3.value =nombresa;

    var row4     = CreateElement(tbody, "tr");
    var row4_c0 = CreateElement(row4, "td");
    row4_c0.appendChild(document.createTextNode("Horario: "));
    var row4_c1 = CreateElement(row4, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem4 = CreateElement(row4_c1, "form");
    var label_elem4 = CreateInputElement(form_elem4, "text");
    label_elem4.style.width = "275px";
    label_elem4.value =horario;

    var row5     = CreateElement(tbody, "tr");
    var row5_c0 = CreateElement(row5, "td");
    row5_c0.appendChild(document.createTextNode("Sitio Web: "));
    var row5_c1 = CreateElement(row5, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem5 = CreateElement(row5_c1, "form");
    var label_elem5 = CreateInputElement(form_elem5, "text");
    label_elem5.style.width = "275px";
    label_elem5.value =sitioweb;

    var row6     = CreateElement(tbody, "tr");
    var row6_c0 = CreateElement(row6, "td");
    row6_c0.appendChild(document.createTextNode("Descripción: "));
    var row6_c1 = CreateElement(row6, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem6 = CreateElement(row6_c1, "form");
    var label_elem6 = CreateInputElement(form_elem6, "text");
    label_elem6.style.width = "275px";
    label_elem6.value =descripcion;


    var btn_div_elem = CreateElement(div_elem, "div");
    btn_div_elem.align = "right";
    btn_div_elem.style.borderTop = "1px solid gray";
    btn_div_elem.style.padding = "4px 0px";
    btn_form_elem = CreateElement(btn_div_elem, "form");
    var cancel_btn = CreateInputElement(btn_form_elem, "button");
    cancel_btn.value = "Cancelar";
    var ok_btn = CreateInputElement(btn_form_elem, "button");
    ok_btn.value = "Enviar";

    //var marker = new GMarker(point);
    // TODO: support dragging the marker someday
    var marker = new GMarker(point, {
        //draggable: true
        });
    //marker.enableDragging();


    gmap.addOverlay(marker);
    marker.openInfoWindow(div_elem);

    /*GEvent.addListener(marker, "dragend", function(e) {
telefono
            direccion
            email
            nombresa
           horario
            sitioweb
            descripcion
    });*/

    GEvent.bindDom(ok_btn, "click", this, function(e) {

        if (txt) {
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            if (cokie !="") {
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));

                if (ValidaEmail(label_elem2.value)){
                    if (ValidaURL(label_elem5.value)){
                        if (ValidaTelefono(label_elem.value)){
                            if (ValidaNombre(txt)){
                                div_elem.innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/EnviarCambioPuntoComercial?nombren="+txt+"+&telefonon="+label_elem.value+"&direccionn="+label_elem1.value+"&emailn="+label_elem2.value+ "&nombresan="+label_elem3.value +"&horarion="+label_elem4.value +"&sitiowebn="+label_elem5.value +"&descripcionn="+label_elem6.value +"&nombre="+txt +"&telefono="+telefono +"&direccion="+direccion +"&email="+email +"&nombresa="+nombresa +"&horario="+horario +"&sitioweb="+descripcion +"&descripcion="+sitioweb +"&usuario="+usux+"' frameborder='0'></iframe>";
                                banderaguardarpunto = 0;
                                nombreguardarpunto = "";
                                gmap.removeOverlay(marker);
                                search_manager.Reset();
                                alert("Se actualizo correctamente");
                                SubmitSearch();
                            }
                            else {
                                row_c1.focus();
                            }
                        }
                        else {
                            label_elem.focus();
                        }
                    }
                    else {
                        label_elem5.focus();
                    }
                }
                else {
                    label_elem2.focus();
                }
                cancelEvent(e);
                return false;

            } else {
                alert("Ingrese como usuario del sistema.");
                return false;
            }
        } else {
            alert("Dato nombre  es requerido");
            row_c1.focus();
            return false;
        }

        return false;
    });
    GEvent.bindDom(cancel_btn, "click", this, function(e) {
        gmap.getInfoWindow().hide();
        banderaguardarpunto = 0;
        nombreguardarpunto = "";
        gmap.removeOverlay(marker);
        //search_manager.Reset();
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(gmap.getInfoWindow(), "closeclick", this, function(e) {
        gmap.removeOverlay(marker);
        //cancelEvent(e);
        return false;
    });


    GEvent.addListener(marker, "click", function() {
        for (var p = 1; p < comercial.length; p++) {
            comer = comercial[p].split(":");

            if(comer[0] == "Teléfono1") telefono1 =comer[1];
            if(comer[0] == "Teléfono2") telefono2 =comer[1];
            if(comer[0] == "Teléfono3") telefono3 =comer[1];
            if(comer[0] == "Dirección") direccion =comer[1];
            if(comer[0] == "E-mail") email =comer[1];
            if(comer[0] == "Nombre S.A") nombresa =comer[1];
            if(comer[0] == "Horario") horario =comer[1];
            if(comer[0] == "Sitio Web") sitioweb =comer[1];
            if(comer[0] == "Descripción") descripcion =comer[1];

        }
        var div_elem = document.createElement("div");
        div_elem.style.padding = "0px 10px 0px 10px";

        /*var name_div1 = CreateElement(div_elem, "div", "search_popup_name");

    name_div1.innerHTML = "Modificación de ubicación.<br>Arrastre el punto hasta la ubicación correcta";
    var table_elem1 = CreateElement(div_elem, "table");
    var tbody1 = CreateElement(table_elem1, "tbody");

    var row7     = CreateElement(tbody1, "tr");
    var row7_c0 = CreateElement(row7, "td");
    row7_c0.appendChild(document.createTextNode("Latitud"));
    var row7_c1 = CreateElement(row7, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem7 = CreateElement(row7_c1, "form");
    var label_elem7 = CreateInputElement(form_elem7, "text");
    label_elem7.style.width = "275px";
    label_elem7.value =lati;

    var row8     = CreateElement(tbody1, "tr");
    var row8_c0 = CreateElement(row8, "td");
    row8_c0.appendChild(document.createTextNode("Longitud"));
    var row8_c1 = CreateElement(row8, "td");
    //row0_c1.appendChild(document.createTextNode(txt));
    var form_elem8 = CreateElement(row8_c1, "form");
    var label_elem8 = CreateInputElement(form_elem8, "text");
    label_elem8.style.width = "275px";
    label_elem8.value =longi;*/

        var name_div = CreateElement(div_elem, "div", "search_popup_name");
        name_div.innerHTML = "Modificación de datos comerciales.";
        var table_elem = CreateElement(div_elem, "table");
        var tbody = CreateElement(table_elem, "tbody");

        var row = CreateElement(tbody, "tr");
        var row_c0 = CreateElement(row, "td");
        row_c0.appendChild(document.createTextNode("Nombre:"));
        var row_c1 = CreateElement(row, "td");
        row_c1.appendChild(document.createTextNode(txt));
        /*var form_elemn = CreateElement(row_c1, "form");
    var label_elemn = CreateInputElement(form_elemn, "text");
    label_elemn.style.width = "275px";
    label_elemn.value =txt;*/

        var row0 = CreateElement(tbody, "tr");
        var row0_c0 = CreateElement(row0, "td");
        row0_c0.appendChild(document.createTextNode("Teléfono 1: "));
        var row0_c1 = CreateElement(row0, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem = CreateElement(row0_c1, "form");
        var label_elem = CreateInputElement(form_elem, "text");
        label_elem.style.width = "275px";
        label_elem.value =telefono1;

        var row07 = CreateElement(tbody, "tr");
        var row0_c07 = CreateElement(row07, "td");
        row0_c07.appendChild(document.createTextNode("Teléfono 2: "));
        var row0_c17 = CreateElement(row07, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem7 = CreateElement(row0_c17, "form");
        var label_elem7 = CreateInputElement(form_elem7, "text");
        label_elem7.style.width = "275px";
        label_elem7.value =telefono2;

        var row08 = CreateElement(tbody, "tr");
        var row0_c08 = CreateElement(row08, "td");
        row0_c08.appendChild(document.createTextNode("Teléfono 3: "));
        var row0_c18 = CreateElement(row08, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem8 = CreateElement(row0_c18, "form");
        var label_elem8 = CreateInputElement(form_elem8, "text");
        label_elem8.style.width = "275px";
        label_elem8.value =telefono3;

        var row1 = CreateElement(tbody, "tr");
        var row1_c0 = CreateElement(row1, "td");
        row1_c0.appendChild(document.createTextNode("Dirección: "));
        var row1_c1 = CreateElement(row1, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem1 = CreateElement(row1_c1, "form");
        var label_elem1 = CreateInputElement(form_elem1, "text");
        label_elem1.style.width = "275px";
        label_elem1.value =direccion;

        var row2 = CreateElement(tbody, "tr");
        var row2_c0 = CreateElement(row2, "td");
        row2_c0.appendChild(document.createTextNode("E-mail: "));
        var row2_c1 = CreateElement(row2, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem2 = CreateElement(row2_c1, "form");
        var label_elem2 = CreateInputElement(form_elem2, "text");
        label_elem2.style.width = "275px";
        label_elem2.value =email;

        var row3     = CreateElement(tbody, "tr");
        var row3_c0 = CreateElement(row3, "td");
        row3_c0.appendChild(document.createTextNode("Nombre S.A: "));
        var row3_c1 = CreateElement(row3, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem3 = CreateElement(row3_c1, "form");
        var label_elem3 = CreateInputElement(form_elem3, "text");
        label_elem3.style.width = "275px";
        label_elem3.value =nombresa;

        var row4     = CreateElement(tbody, "tr");
        var row4_c0 = CreateElement(row4, "td");
        row4_c0.appendChild(document.createTextNode("Horario: "));
        var row4_c1 = CreateElement(row4, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem4 = CreateElement(row4_c1, "form");
        var label_elem4 = CreateInputElement(form_elem4, "text");
        label_elem4.style.width = "275px";
        label_elem4.value =horario;

        var row5     = CreateElement(tbody, "tr");
        var row5_c0 = CreateElement(row5, "td");
        row5_c0.appendChild(document.createTextNode("Sitio Web: "));
        var row5_c1 = CreateElement(row5, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem5 = CreateElement(row5_c1, "form");
        var label_elem5 = CreateInputElement(form_elem5, "text");
        label_elem5.style.width = "275px";
        label_elem5.value =sitioweb;

        var row6     = CreateElement(tbody, "tr");
        var row6_c0 = CreateElement(row6, "td");
        row6_c0.appendChild(document.createTextNode("Descripción: "));
        var row6_c1 = CreateElement(row6, "td");
        //row0_c1.appendChild(document.createTextNode(txt));
        var form_elem6 = CreateElement(row6_c1, "form");
        var label_elem6 = CreateInputElement(form_elem6, "text");
        label_elem6.style.width = "275px";
        label_elem6.value =descripcion;


        var btn_div_elem = CreateElement(div_elem, "div");
        btn_div_elem.align = "right";
        btn_div_elem.style.borderTop = "1px solid gray";
        btn_div_elem.style.padding = "4px 0px";
        btn_form_elem = CreateElement(btn_div_elem, "form");
        var cancel_btn = CreateInputElement(btn_form_elem, "button");
        cancel_btn.value = "Cancelar";
        var ok_btn = CreateInputElement(btn_form_elem, "button");
        ok_btn.value = "Enviar";
        marker.openInfoWindow(div_elem);
    });
}

PlacemarkManager.prototype.AddPlacemark = function(cfg, visible) {
    // assemble the 'myplaces' entry
    DebugMsg("Add 'My Places': " + cfg.txt);
    var row = CreateElement(this.main_tbody, "tr");
    cfg.entry_elem = row;

    var td = CreateElement(row, "td");
    var input_elem = CreateInputElement(td, "checkbox", "layer_check");
    if (visible == true) {
        input_elem.checked = "checked";
    }

    td = CreateElement(row, "td");
    var a = CreateElement(td, "a");
    a.href = 'javascript:void(0)';
    GEvent.bindDom(a, 'click', this, function(e) {
        gmap.setCenter(new GLatLng(cfg.lat, cfg.lng), cfg.zoom);
        /* Smooth panning seem to not work very well
         * gmap.setZoom(cfg.zoom);
         * gmap.panTo(new GLatLng(cfg.lat, cfg.lng)); */
        cancelEvent(e);
        return false;
    });
    a.appendChild(document.createTextNode(cfg.txt));

    // build the pushpin
    var popup_body = document.createElement("div");
    var bold_label = CreateElement(popup_body, "b");
    bold_label.appendChild(document.createTextNode(cfg.txt));
    CreateElement(popup_body, "br");
    CreateElement(popup_body, "br");
    var label_lng = CreateElement(popup_body, "label");
    label_lng.appendChild(document.createTextNode("Longitud: "));
    label_lng.appendChild(document.createTextNode(cfg.lng));
    CreateElement(popup_body, "br");
    var label_lat = CreateElement(popup_body, "label");
    label_lat.appendChild(document.createTextNode("Latitud: "));
    label_lat.appendChild(document.createTextNode(cfg.lat));
    CreateElement(popup_body, "br");
    var label_zoom = CreateElement(popup_body, "label");
    label_zoom.appendChild(document.createTextNode("Zoom: "));
    label_zoom.appendChild(document.createTextNode(cfg.zoom));
    CreateElement(popup_body, "br");
    var label_enlace = CreateElement(popup_body, "label");
    label_enlace.appendChild(document.createTextNode("Enlace: "));
    var label_elem = CreateInputElement(popup_body, "textarea");
    label_elem.style.width = "250px";
    //guarda cuando se arrastra el punto el nombre
    label_elem.value ="http://lnmapas.nacion.co.cr/maps/index.shtml?ll="+cfg.lat+","+cfg.lng+"&z="+cfg.zoom+"&etiqueta="+cfg.txt;
    label_enlace.appendChild(label_elem);

    CreateElement(popup_body, "br");
    CreateElement(popup_body, "br");

    var delete_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
    delete_btn.href = 'javascript:void(0)';
    delete_btn.appendChild(document.createTextNode("Borrar"));

    var desde_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
    desde_btn.href = 'javascript:void(0)';
    desde_btn.appendChild(document.createTextNode("Desde Aquí"));

    var hasta_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
    hasta_btn.href = 'javascript:void(0)';
    hasta_btn.appendChild(document.createTextNode("Hasta Aquí"));

    var email_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
    email_btn.href = 'javascript:void(0)';
    email_btn.appendChild(document.createTextNode("Enviar Email"));

    var marker = new GMarker(new GLatLng(cfg.lat, cfg.lng),{
        draggable: true
    });
    GEvent.addListener(marker, "click", function() {
        var popup_body = document.createElement("div");
        var bold_label = CreateElement(popup_body, "b");
        bold_label.appendChild(document.createTextNode(cfg.txt));
        CreateElement(popup_body, "br");
        CreateElement(popup_body, "br");
        var label_lng = CreateElement(popup_body, "label");
        label_lng.appendChild(document.createTextNode("Longitud: "));
        label_lng.appendChild(document.createTextNode(cfg.lng));
        CreateElement(popup_body, "br");
        var label_lat = CreateElement(popup_body, "label");
        label_lat.appendChild(document.createTextNode("Latitud: "));
        label_lat.appendChild(document.createTextNode(cfg.lat));
        CreateElement(popup_body, "br");
        var label_zoom = CreateElement(popup_body, "label");
        label_zoom.appendChild(document.createTextNode("Zoom: "));
        label_zoom.appendChild(document.createTextNode(cfg.zoom));
        CreateElement(popup_body, "br");
        var label_enlace = CreateElement(popup_body, "label");
        label_enlace.appendChild(document.createTextNode("Enlace: "));
        var label_elem = CreateInputElement(popup_body, "textarea");
        label_elem.style.width = "250px";
        //guarda cuando se arrastra el punto el nombre
        label_elem.value ="http://lnmapas.nacion.co.cr/maps/index.shtml?ll="+cfg.lat+","+cfg.lng+"&z="+cfg.zoom+"&etiqueta="+cfg.txt;
        label_enlace.appendChild(label_elem);

        CreateElement(popup_body, "br");
        CreateElement(popup_body, "br");
        var delete_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
        delete_btn.href = 'javascript:void(0)';
        delete_btn.appendChild(document.createTextNode("Borrar"));

        var desde_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
        desde_btn.href = 'javascript:void(0)';
        desde_btn.appendChild(document.createTextNode("Desde Aquí"));

        var hasta_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
        hasta_btn.href = 'javascript:void(0)';
        hasta_btn.appendChild(document.createTextNode("Hasta Aquí"));

        var email_btn = CreateElement(popup_body, "a", "placemark_delete_btn");
        email_btn.href = 'javascript:void(0)';
        email_btn.appendChild(document.createTextNode("Enviar Email"));

        GEvent.bindDom(delete_btn, 'click', this, function(e) {

            placemark_manager.Delete(cfg);
            var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
            if (cokie !="") {
                var place = cokie.split('|');
                var parms = place[0].split('&');
                var codigo = parms[0].split(':');
                var user = parms[1].split(':');
                var usux =user[1].substr(0,user[1].indexOf ('"'));
                FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/InactivaPunto?etiqueta="+cfg.txt+"&longitud="+cfg.lng+"&latitud="+cfg.lat+"&zoom="+cfg.zoom+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
            }
            gmap.getInfoWindow().hide();
            gmap.removeOverlay(marker);
            cancelEvent(e);
            return false;
        });

        GEvent.bindDom(desde_btn, 'click', this, function(e) {
            var id = firstItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                place_search_manager.SetPlace(marker.getLatLng(),(cfg.lng+" ,"+cfg.lat), id);
                FindElement("search_dir_box").style.display = "block";
                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();
                    showDirSearch();
                }
            }

            cancelEvent(e);
            return false;
        });

        GEvent.bindDom(hasta_btn, 'click', this, function(e) {
            var id = lastItem();
            if (id) {

                unselectItems();
                place_search_manager.Reset();
                place_search_manager.SetPlace(marker.getLatLng(), (cfg.lng+" ,"+cfg.lat), id);
                FindElement("search_dir_box").style.display = "block";
                //if (FindElement("A").value && FindElement("B").value){
                if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                    SubmitDirSearch();
                    showDirSearch();
                }

            }

            cancelEvent(e);
            return false;
        });

        GEvent.bindDom(email_btn, 'click', this, function(e) {
            window.open("/maps/envioemail.html?tenvio=3&latlon="+cfg.lat+","+cfg.lng+"&zoom="+cfg.zoom+"&etiqueta="+cadena.encode(cfg.txt), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');
            cancelEvent(e);
            return false;
        });
        marker.openInfoWindow(popup_body);
    });
    gmap.addOverlay(marker);
    if (!visible)
        marker.hide();

    GEvent.bindDom(input_elem, "click", this, function(e) {
        /* invert state of checked because we get the signal
         * before the form element does */
        if (!input_elem.checked) {
            marker.hide();
        } else {
            marker.show();
        }
    });

    GEvent.bindDom(delete_btn, 'click', this, function(e) {

        placemark_manager.Delete(cfg);
        var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
        if (cokie !="") {
            var place = cokie.split('|');
            var parms = place[0].split('&');
            var codigo = parms[0].split(':');
            var user = parms[1].split(':');
            var usux =user[1].substr(0,user[1].indexOf ('"'));
            FindElement("loader").innerHTML = "<iframe src='http://appmapas.nacion.co.cr/GnMaps/InactivaPunto?etiqueta="+cfg.txt+"&longitud="+cfg.lng+"&latitud="+cfg.lat+"&zoom="+cfg.zoom+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";
        }
        gmap.getInfoWindow().hide();
        gmap.removeOverlay(marker);
        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(desde_btn, 'click', this, function(e) {
        var id = firstItem();
        if (id) {

            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(),(cfg.lng+" ,"+cfg.lat), id);
            FindElement("search_dir_box").style.display = "block";
            //if (FindElement("A").value && FindElement("B").value){
            if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                SubmitDirSearch();
                showDirSearch();
            }
        }

        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(hasta_btn, 'click', this, function(e) {
        var id = lastItem();
        if (id) {

            unselectItems();
            place_search_manager.Reset();
            place_search_manager.SetPlace(marker.getLatLng(), (cfg.lng+" ,"+cfg.lat), id);
            FindElement("search_dir_box").style.display = "block";
            //if (FindElement("A").value && FindElement("B").value){
            if (FindElement(firstItem()).value && FindElement(lastItem()).value){
                SubmitDirSearch();
                showDirSearch();
            }

        }

        cancelEvent(e);
        return false;
    });

    GEvent.bindDom(email_btn, 'click', this, function(e) {
        window.open("/maps/envioemail.html?tenvio=3&latlon="+cfg.lat+","+cfg.lng+"&zoom="+cfg.zoom+"&etiqueta="+cadena.encode(cfg.txt), "Enviaremail", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=280,left = 340,top = 312');
        cancelEvent(e);
        return false;
    });

    GEvent.addListener(marker, "dragend", function(e) {
        var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
        if (cokie !="") {
            var place = cokie.split('|');
            var parms = place[0].split('&');
            var codigo = parms[0].split(':');
            var user = parms[1].split(':');
            var usux =user[1].substr(0,user[1].indexOf ('"'));
            FindElement("loader").innerHTML ="<iframe src='http://appmapas.nacion.co.cr/GnMaps/InactivaPunto?etiqueta="+cfg.txt+"&longitud="+cfg.lng+"&latitud="+cfg.lat+"&zoom="+cfg.zoom+"&codigo="+codigo[1]+"&usuario="+usux+"' frameborder='0'></iframe>";

        }
        placemark_manager.NewPlacemarkAtPoint(marker.getLatLng(),cfg.txt);
        marker.hide();
        placemark_manager.Delete(cfg);
        //cancelEvent(e);
        return false;
    });
    this.placemark_defs.push(cfg);
}

/******************************************************************************
 * SidePanel class
 ******************************************************************************/
function SidePanel(parent) {
    this.main_div = CreateElement(parent, "div");
}

SidePanel.prototype.AddPane = function(text) {
    return new Frame(this.main_div, text)
}

/******************************************************************************
 * Frame class
 ******************************************************************************/

//MODIFICADO POR RICARDO FRANCO
function Frame(parent, text) {
    this.main_div = CreateElement(parent, "div", "sidepanel_pane");
    //this.main_div.style.visibility = 'hidden';
    this.main_div.style.display = 'none';

    this.caption_div = CreateElement(this.main_div, "div", "frame_caption");
    var caption_txt = document.createTextNode(text);
    this.caption_div.appendChild(caption_txt);

    this.body_div = CreateElement(this.main_div, "div", "frame_body");
    this.footer_div = CreateElement(this.main_div, "div", "frame_footer");
}

Frame.prototype.GetCaptionDiv = function() {
    return this.caption_div;
}

Frame.prototype.GetBodyDiv = function() {
    return this.body_div;
}

Frame.prototype.GetFooterDiv = function() {
    return this.footer_div;
}

Frame.prototype.Show = function() {
    //this.main_div.style.visibility = 'visible';
    this.main_div.style.display = 'block';
}

Frame.prototype.Hide = function() {
    //this.main_div.style.visibility = 'hidden';
    this.main_div.style.display = 'none';
}

Frame.prototype.AddCloseButton = function(obj, close_func) {
    this.close_btn = CreateElement(this.caption_div, "img");
    this.close_btn.setAttribute("src", FUSION_PATH + "close.gif");
    this.close_btn.setAttribute("alt", "Close");
    this.close_btn.style.position = "absolute";
    this.close_btn.style.top = "0px";
    this.close_btn.style.right = "0px";
    if (close_func) {
        GEvent.bindDom(this.close_btn, 'click', obj, close_func);
    }
    GEvent.bindDom(this.close_btn, 'click', this, this.Hide);
}

/******************************************************************************
 * Tab class
 ******************************************************************************/

function Tab(parent) {
    var main_table = CreateElement(parent, "table");
    var body = CreateElement(main_table, "tbody");
    var row1 = CreateElement(body, "tr");
    var td = CreateElement(row1, "td");
    var div = CreateElement(td, "div", "tabLabels");
    var tab_table = CreateElement(div, "table");
    var tab_tbody = CreateElement(tab_table, "tbody");
    this.tab_row = CreateElement(tab_tbody, "tr");

    var row2 = CreateElement(body, "tr");
    var pane_data = CreateElement(row2, "td");
    this.pane_div = CreateElement(pane_data, "div");

    this.tabs = [];
    this.panes = [];

    this.active = null;
}

Tab.prototype.AddTab = function(label) {
    var td = CreateElement(this.tab_row, "td");
    var tab_div = CreateElement(td, "div");
    this.tabs[label] = tab_div;
    var a = CreateElement(tab_div, "a");
    a.href = 'javascript:void(0)';
    GEvent.bindDom(a, 'click', this, function(e) {
        this.SetActive(label);
        cancelEvent(e);
        return false;
    });
    a.appendChild(document.createTextNode(label));

    var pane_div = CreateElement(this.pane_div, "div", "tabPane");
    this.panes[label] = pane_div;

    if (!this.active) {
        this.active = label;
        tab_div.className = 'selectedTab';
    } else {
        tab_div.className = 'unselectedTab';
        pane_div.style.display = 'none';
    }

    return pane_div;
}

Tab.prototype.SetActive = function(label) {
    if (this.active != label) {
        this.tabs[this.active].className = 'unselectedTab';
        this.panes[this.active].style.display = 'none';
        this.active = label;
        this.tabs[this.active].className = 'selectedTab';
        this.panes[this.active].style.display = '';
        this.active = label;
    }
}

/******************************************************************************
 * Dialog class
 ******************************************************************************/

function Dialog(parent, style_id, txt, width, height) {
    this.main_div = CreateElement(parent, "div", style_id);
    this.main_div.style.visibility = "hidden";

    // dialog caption bar
    this.caption = CreateElement(this.main_div, "div", "frame_caption");
    this.caption.style.cursor = "move";
    var caption_txt = document.createTextNode(txt);
    this.caption.appendChild(caption_txt);

    this.close_btn = CreateElement(this.caption, "img");
    GEvent.bindDom(this.close_btn, 'click', this, this.Hide);
    this.close_btn.setAttribute("src", FUSION_PATH + "close.gif");
    this.close_btn.setAttribute("alt", "Close");
    this.close_btn.style.position = "absolute";
    this.close_btn.style.top = "0px";
    this.close_btn.style.right = "0px";
    this.close_btn.style.cursor = 'auto';

    // dialog body
    this.body_div = CreateElement(this.main_div, "div", "frame_body");
    if (width) {
        this.body_div.style.width = width;
        this.body_div.style.height = height;
    }
    this.body_div.style.cursor = 'auto';
    GEvent.bindDom(this.body_div, "mousedown", this, function(e) {
        cancelEvent(e);
    });

    // dialog footer - used for controls
    this.footer_div = CreateElement(this.main_div, "div", "frame_footer");

    // use maps API to make dialog draggable
    this.drag_obj = new GDraggableObject(this.main_div, {
        container:parent
    });
}

Dialog.prototype.GetBodyDiv = function() {
    return this.body_div;
}

Dialog.prototype.GetFooterDiv = function() {
    return this.footer_div;
}

Dialog.prototype.Show = function() {
    this.main_div.style.visibility = 'visible';
}

Dialog.prototype.Hide = function() {
    this.main_div.style.visibility = 'hidden';
}

Dialog.prototype.AppendText = function(txt) {
    this.body_div.appendChild(document.createTextNode(txt));
    CreateElement(this.body_div, "br");
    var h = this.body_div.scrollHeight;
    // adjust scroll to show this new content
    this.body_div.scrollTop = this.body_div.scrollHeight;

}

Dialog.prototype.AppendSearchResults = function(results) {
    var results_div = CreateElement(this.body_div, "div", "search_results");
    for (var p = 0; p < results.length; p++) {
        var img_elem = CreateElement(results_div, "img");
        var letter = String.fromCharCode("A".charCodeAt(0) + p);
        img_elem.setAttribute("src", FUSION_PATH + "marker" + letter + ".png");
        results_div.appendChild(document.createTextNode(results[p].snippet));
        CreateElement(results_div, "br");
    }
}

/******************************************************************************
 * Utility functions
 ******************************************************************************/

function cancelEvent(e) {
    if (window.event) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    } else {
        e.preventDefault();
        e.stopPropagation();
    }
}
// determines what browser is being used
// typical types are: "Firefox" and "MSIE"
function IsBrowser(type) {
    return navigator.userAgent.match(type);
}

function GetElementStyle(elem, style) {
    var computed_style = document.defaultView.getComputedStyle(elem, null);
    return computed_style.getPropertyValue(style);
}

function GetElementWidth(elem) {
    if (IsBrowser("MSIE")) {
        return parseInt(elem.currentStyle.width);
    } else {
        return parseInt(GetElementStyle(elem, "width"));
    }
}

function GetElementHeight(elem) {
    if (IsBrowser("MSIE")) {
        return parseInt(elem.currentStyle.height);
    } else {
        return parseInt(GetElementStyle(elem, "height"));
    }
}

function CreateElement(parent, type, /* optional */ id) {
    var elem = document.createElement(type);
    if (id)
        elem.setAttribute("id", id);
    parent.appendChild(elem);
    return elem;
}

function CreateInputElement(parent, type, /* optional */ id) {
    var elem = document.createElement('input');
    elem.setAttribute('type', type);
    if (id)
        elem.setAttribute('id', id);
    parent.appendChild(elem);
    return elem;
}

function CreateRadioInputElement(parent, name, /* optional */ id) {
    var elem;
    try {
        elem = document.createElement('<input type="radio" name="' + name + '" />');
    } catch(err) {
        elem = document.createElement('input');
        elem.setAttribute('type', 'radio');
        elem.setAttribute('name', name);
    }
    if (id)
        elem.setAttribute('id', id);
    parent.appendChild(elem);
    return elem;
}

function CreateTextNode(parent, text) {
    parent.appendChild(document.createTextNode(text));
}

function FindChildById(elem, node_id) {
    for (var child = elem.firstChild; child != null; child = child.nextSibling) {
        if (child.id == node_id)
            return child;
    }
    return null;
}

function FindElement(id) {
    return (document.getElementById) ? document.getElementById(id)
    : document.all[id];
}

function RemoveAllChildren(node) {
    while (node.hasChildNodes())
        node.removeChild(node.firstChild);
}
/**
 * Gets the value of a parameter in the current page's URL
 *
 * @param {String} param  URL parameter to extract
 * @return {String || Boolean}  Extracted parameter.
 */
function GetPageURLParameter(param) {
    return GetURLParameter(window.location.href, param);
}
/**
 * Gets the value of a parameter from a URL
 *
 * @param {String} url  URL to extract from
 * @param {String} param parameter to extract
 * @return {String || Boolean}  Extracted parameter.
 */
function GetURLParameter(url, param) {
    // Look for a portion after the question mark:
    var halves = url.split('?');
    if (halves.length < 2) {
        return false;
    }
    // The second half contains the search parameters:
    var pairs = halves[1].split("&");
    for (var i = 0; i < pairs.length; i++) {
        var names = pairs[i].split("=");
        if (names[0] == param) {
            if (names.length > 1) {
                return names[1];
            } else {
                return true;  // A parameter with no = returns true
            }
        }
    }
    return false;
}

function GetCookieValue(name) {
    name = name + '=';
    var allcookies = document.cookie;
    var pos = allcookies.indexOf(name);
    if (pos != -1) {
        var start = pos + name.length;
        var end = allcookies.indexOf(';', start);
        if (end == -1)
            end = allcookies.length;
        return allcookies.substring(start, end);
    }
    return "";
}

function SetCookieValue(name, value) {
    document.cookie = name + '=' + value;

}

//var LOGIN_COOKIE = 'REG_SESSION_DATA';
var LOGIN_COOKIE = 'REG_MAP';

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

function Login() {
    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
    if (cokie !="") {
        banderaguardarpunto = 1000;
        //var cokie = cadena.decode(cookie);
        var place = cokie.split('|');
        var parms = place[0].split('&');
        var name = parms[1].split(':');
        var usux =name[1].substr(0,name[1].indexOf ('"'));
        document.getElementById('unlogin').innerHTML='Bienvenido ' + usux +  '  <a href="javascript: deleteCookie();"><u>Desconectar</u></a>';
    }
}

function deleteCookie() {

    if ( getCookie( LOGIN_COOKIE ) )
        document.cookie = LOGIN_COOKIE + '=' +
        ( ( '/' ) ? ';path=' + '/' : '') +
        ( ( 'nacion.co.cr' ) ? ';domain=' + 'nacion.co.cr' : '' ) +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';

    if ( getCookie( MYPLACES_USER ) )
        document.cookie = MYPLACES_USER + '=' +
        ( ( '/maps' ) ? ';path=' + '/maps' : '') +
        ( ( 'nacion.co.cr' ) ? ';domain=' + 'nacion.co.cr' : '' ) +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';

    if ( getCookie( MYPLACES_USER ) )
        document.cookie = MYPLACES_USER + '=' +
        ( ( '/maps/' ) ? ';path=' + '/maps/' : '') +
        ( ( 'nacion.co.cr' ) ? ';domain=' + 'nacion.co.cr' : '' ) +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';

    //if ( getCookie( MYPLACES_USER ) )

    document.cookie = MYPLACES_USER + '=' +
    ( ( '/maps/' ) ? ';path=' + '/maps/' : '') +
    ( ( 'nacion.co.cr' ) ? ';servidor=' + 'nacion.co.cr' : '' ) +
    ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    //if ( getCookie( MYPLACES_USER ) )

    document.cookie = MYPLACES_USER + '=' +
    ( ( '/maps' ) ? ';path=' + '/maps' : '') +
    ( ( 'nacion.co.cr' ) ? ';servidor=' + 'nacion.co.cr' : '' ) +
    ';expires=Thu, 01-Jan-1970 00:00:01 GMT';


    window.location = "http://lnmapas.nacion.co.cr/maps/index.shtml";
}

/*function crearpuntocentral(){
    GEvent.addListener(gmap, 'dblclick',function(overlay, point) {
        if (banderaguardarpunto)
        {
            gmap.clearOverlays();
            ClearMap();
            banderaguardarpunto--;
            placemark_manager.SendPlacemarkAtPoint(point,nombreguardarpunto,divilatlon[1],divilatlon[0]);
            return false;
        }
        else
        {
            DebugMsg("Center: " +  point);
            gmap.clearOverlays();
            ClearMap();
            placemark_manager.NewPlacemarkAtPoint(point,"");
            return false;
        }
    }

    );
}*/
function AbrirEnlace(){
    var center = gmap.getCenter();
    DebugMsg("Center: " + center);
    placemark_manager.NewPlacemarkAtPointLink(center);
}

function ValidaUsuario() {
    var cokie = cadena.decode(getCookie(LOGIN_COOKIE));
    if (cokie !="") {
        return true;
    }
    else {
        return false;
    }

}
function ValidaEmail(valor) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
        return (true)
    } else {
        alert("Email ingresado es incorrecto");
        return (false);
    }
}
function ValidaTelefono(valor) {
    if (/^([0-9]{8,8})*$/.test(valor)){
        return (true)
    } else {
        alert("Telefono ingresado es incorrecto, no utilice guiones ni separadores solo numeros(8)");
        return (false);
    }
}
function ValidaNombre(valor) {
    if (valor !=""){
        return (true)
    } else {
        alert("Nombre es requerido");
        return (false);
    }
}
function ValidaURL(url) {
    var re=/^(http|ftp)(s)?:\/\/\w+(\.\w+)*(-\w+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/;
    if  (re.test("http://"+url)){
        return true;
    } else {
        alert("Sitio web ingresado es incorrecto");
        return false;
    }
}
/*
// vars used like constants
var URL_WEB_SERVICE = "/wsApiNacionMaps/WebServiceLogin";
// global vars
var request;
// events
function callWSComplete_Handler()
{
    alert("rqst ready"+request.readyState);

    if(request.readyState == 4)
    {
        alert("rqst status"+request.status);
        //alert("rqst"+request.responseXML.text);
        if(request.status == 200)
        {
            alert("la respuesta es: " + request.responseXML.text);
        }
        else
        {
            alert("ha surgido un problema... :-(");

        }
    }
}

// functions

function callWebService(login, password)
{
    var parameters = new Array();
    parameters[0] = new Array("login", login);
    parameters[1] = new Array("password", password);

    request = createXmlHttpRequestObject();
    callWS(URL_WEB_SERVICE, callWSComplete_Handler, parameters);
}

function callWS(url, responseHandler, parameters)
{
    var strParameters = "";

    request.onreadystatechange = responseHandler;

    request.open("POST", url, true);

    if(parameters != null && parameters.length != 0)
    {
        request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');


        for(var i = 0; i < parameters.length; i++)
        {
            var p = parameters[i];

            if(strParameters != "") strParameters += "&";

            strParameters += p[0] + "=" + p[1];
        }
    }
    alert("strparameters"+strParameters);
    request.send(strParameters);
}

function createXmlHttpRequestObject()
{
    var req = false;

    if(window.XMLHttpRequest && !(window.ActiveXObject)) // branch for native XMLHttpRequest object
    {
        try
        {
            req = new XMLHttpRequest();
        }
        catch(e)
        {
            req = false;
        }
    }
    else if(window.ActiveXObject) // branch for IE/Windows ActiveX version
    {
        try
        {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                req = false;
            }
        }
    }
    alert ("req"+req);
    return req;
}*/
function addIcon(icon) { // Add icon attributes

    icon.shadow= icon_url + "mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
}

function showTooltip2(marker,area,unit) { // Display tooltips

    tooltip.innerHTML = + area.toFixed(3) + unit;
    tooltip.style.display = "block";

    // Tooltip transparency specially for IE
    if(typeof(tooltip.style.filter) == "string") {
        tooltip.style.filter = "alpha(opacity:70)";
    }

    var currtype = gmap.getCurrentMapType().getProjection();
    var point= currtype.fromLatLngToPixel(gmap.fromDivPixelToLatLng(new GPoint(0,0),true),gmap.getZoom());
    var offset= currtype.fromLatLngToPixel(marker.getVertex(0),gmap.getZoom());
    var anchor = 10;
    var width = 10 + 6;
    // var height = tooltip.clientHeight +18;
    var height = 10;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y - height));
    pos.apply(tooltip);
}
function showTooltip(marker) { // Display tooltips

    tooltip.innerHTML = marker.tooltip;
    tooltip.style.display = "block";

    // Tooltip transparency specially for IE
    if(typeof(tooltip.style.filter) == "string") {
        tooltip.style.filter = "alpha(opacity:70)";
    }

    var currtype = gmap.getCurrentMapType().getProjection();
    var point= currtype.fromLatLngToPixel(gmap.fromDivPixelToLatLng(new GPoint(0,0),true),gmap.getZoom());
    var offset= currtype.fromLatLngToPixel(marker.getLatLng(),gmap.getZoom());
    var anchor = marker.getIcon().iconAnchor;
    var width = marker.getIcon().iconSize.width + 6;
    // var height = tooltip.clientHeight +18;
    var height = 10;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y - height));
    pos.apply(tooltip);
}

function leftClick(overlay, point) {
    if (document.getElementById("status")){
        if (document.getElementById("status").style.visibility == 'visible'){

            if(point) {
                count++;

                if(count%2 != 0) {

                    // Light blue marker icons
                    var icon = new GIcon();

                    icon.image = icon_url +"mm_20_blue.png";
                    addIcon(icon);
                }
                else {
                    // Purple marker iconsmm_20_purple.png
                    var icon = new GIcon();
                    icon.image = icon_url +"mm_20_blue.png";
                    addIcon(icon);
                }

                // Make markers draggable
                var marker = new GMarker(point, {
                    icon:icon,
                    draggable:true,
                    bouncy:false,
                    dragCrossMove:true
                });
                gmap.addOverlay(marker);
                marker.content = count;
                markers.push(marker);
                marker.tooltip = "Punto "+ count;

                GEvent.addListener(marker, "mouseover", function() {
                    showTooltip(marker);
                });

                GEvent.addListener(marker, "mouseout", function() {
                    tooltip.style.display = "none";
                });

                // Drag listener
                GEvent.addListener(marker, "drag", function() {
                    tooltip.style.display= "none";
                    drawOverlay();
                });

                // Second click listener
                GEvent.addListener(marker, "click", function() {
                    tooltip.style.display = "none";

                    // Find out which marker to remove
                    for(var n = 0; n < markers.length; n++) {
                        if(markers[n] == marker) {
                            gmap.removeOverlay(markers[n]);
                            break;
                        }
                    }

                    // Shorten array of markers and adjust counter
                    markers.splice(n, 1);
                    if(markers.length == 0) {
                        count = 0;
                    }
                    else {
                        count = markers[markers.length-1].content;
                        drawOverlay();
                    }
                });
                drawOverlay();
            }
        }

    }
}


function toggleMode() {
    tooltip = document.createElement("div");
    tooltip.className="tooltip";
    gmap.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
    gmap.disableDoubleClickZoom();
    //GEvent.addListener(gmap, "click", leftClick);
    if(markers.length > 1) drawOverlay();
}


function drawOverlay(){
    var report= document.getElementById("status");
    // Check radio button
    var lineMode = tipodibujo;

    if(poly) {
        gmap.removeOverlay(poly);
    }
    pointslp.length = 0;

    for(i = 0; i < markers.length; i++) {
        pointslp.push(markers[i].getLatLng());
    }
    if(lineMode) {

        // Polyline mode
        poly = new GPolyline(pointslp, lineColor, lineWeight, lineOpacity);
        var area = poly.getLength()/1000;
        var unit = " km";
        report.innerHTML = "<b>"+" Largo de la línea: " + area.toFixed(3) + unit;

    }
    else {
        // Polygon mode
        pointslp.push(markers[0].getLatLng());
        poly = new GPolygon(pointslp, lineColor, lineWeight, lineOpacity, fillColor, fillOpacity);
        var area = poly.getArea()/(1000*1000);
        var unit = " km&sup2;";
        report.innerHTML = "<b>"+" Área del polígono: " + area.toFixed(3) + unit;

    }
    poly.tooltip = "poly";
    GEvent.addListener(poly, "mouseover", function() {
        showTooltip2(poly,area,unit);
    });

    GEvent.addListener(poly, "mouseout", function() {
        tooltip.style.display = "none";
    });
    gmap.addOverlay(poly);
}
