// JavaScript File

// ********************************************* //
// ***** Definición de variables generales ***** //
// ********************************************* //
var mapActivated = false; // Si el mapa está activado
var map, actualWindowOpen, actualToDrag;
// ===== Variables para los marcadores =====
var listener = null;
var markers = new Array();
var points = new Array();
var titleMarker = new Array();
var htmls = new Array();
var tagsMarker = new Array();
//var icons = new Array();
// ===== Variables para las líneas =====
var allLines = new Array(); // Guardar las líneas
var lineActivated = false;
var titleLines = new Array(); // Títulos de las líneas
var tagsLines = new Array(); // Tags de las líneas
var vertexLine = new Array();
// ===== Variables para los polígonos =====
var allShapes = new Array(); // Guardar los polígonos
var shapeActivated = false;
var titleShapes = new Array(); // Títulos de los polígonos
var tagsShapes = new Array(); // Tags de los polígonos
var stylestrokeShapes = new Array(); // Estilo del borde del polígono
// ===== Estilo para las líneas/polígonos =====
var strokeColor = "#000080"; // Color (en formato RGB) inicial de la línea
var strokeWeight = 4; // Ancho (en pixeles) inicial de la línea
var strokeOpacity = 0.7; // Opacidad (entre 0 y 1) inicial de la línea
var fillColor = "#ff9900"; // Color (en formato RGB) inicial del relleno
var fillOpacity = 0.3; // Opacidad (entre 0 y 1) inicial del relleno
// ===== Variables par el funcionamiento de las líneas y polígonos =====
var clicked = false;
var actualPoly =  null;
var oldLine = null;
var polyActivated = false;
var nowWritingPoly = null;
var fromStartOption = {fromStart: false};

// ==== Variables para visualizar los marcadores en el mapa =====
var side_bar_pois = "";
var gmarkers = new Array();
var htmlsPois = new Array();
var side_bar_routes = "";
var groutes = new Array();
var htmlsRoutes = new Array();
var gpolygons = new Array();
var htmlsPolygons = new Array();
var tempObject = new Array();
var temphtml = new Array();
var side_bar_polygons = "";
// ===== Controles del Mapa =====
var ZoneEditorControl;
var EditorControl = null;
var FormControl = null;
var modificarBoton;
var abandonarBoton;

var bounds =  null;
var counter= 0;
var mantener = false;
var TitlesAll = new Array(); // Guardar los títulos de los mapas

var timeout2 = null;
var identificador = 0;

var Abuses = new Array();
var MapBuses = new Array();

var ModifMarkers = new Array();
var ModifHtml = new Array();
var IDsMarkers = new Array();
var ModifAgr = new Array();
var Modifrutas = new Array();
var ModifHtmlrutas = new Array();
var IDsRutas = new Array();
var ModifAreas = new Array();
var ModifHtmlAreas = new Array ();
var IDsAreas = new Array();
var ModifstyleAreas = new Array();
var actualWindowOpenM;
//var actualPolyM;

var Icon = new GIcon(G_DEFAULT_ICON);
Icon.image = "./img/map_icons/marker_red-dot.png";
Icon.iconSize = new GSize(32,32);
Icon.shadow = "./img/map_icons/marker_s.png";
Icon.shadowSize = new GSize(59,32);
Icon.iconAnchor = new GPoint(16,32);
Icon.infoWindowAnchor = new GPoint(16,0);
Icon.transparent = "img/map_icons/32x32trans.png";
Icon.dragCrossImage = "img/map_icons/drag_cross_17x17.png"
Icon.dragCrossSize = new GSize(17,17);
Icon.dragCrossAnchor = new GPoint(9,9);


//var opts = {onOpenFn:toinit()};


// ********************************************* //
// *****    Definición de las funciones    ***** //
// ********************************************* //
function FirstMap(cargar) {
    // ===== Si el Navegador es compatible =====
    if (GBrowserIsCompatible()) {
        // Se crea el mapa de Google
        map = new GMap2(document.getElementById("map"));
        // +++++ Se añaden los controles al mapa +++++
        // Control con flechas para mover el mapa, barra de zoom...
        map.addControl(new GLargeMapControl());
        // Tipos de Mapa (el tipo "Híbrido" aparece como un hijo del de "Satélite")
        map.addControl(new GHierarchicalMapTypeControl());
        // Añade el Tipo de Mapa "Relieve"
        map.addMapType(G_PHYSICAL_MAP);
        // Escala del mapa
        map.addControl(new GScaleControl());
        // Estabelecer el Centro y zoom inicial del mapa
        map.setCenter(new GLatLng(40.4166,-3.7039), 6);
        map.savePosition();
        // Se permite hacer zoom con la rueda del ratón
        map.enableScrollWheelZoom();
        // El zoom se realiza de forma contiunada
        map.enableContinuousZoom();
        // Se oculta el "overflow" de la flechas rojas cuando se hace zoom cerca del borde del mapa
        map.getContainer().style.overflow = "hidden";
        // Poner el logotipo de CEDETEL en el fondo mientras se carga el mapa
        document.getElementById("map").style.background = "#C8C5C5 center no-repeat url(img/carga_mapa_cedetel.jpg)";
        
        map.addControl(new buttonSizeMap(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));

        if (cargar) {
            // Se cargan los POIS iniciales
            
            initialPOIS();
        } else {
        aportacionUsuario();
    }
}
// ===== Mostrar una advertencia si el Navegador no es compatible =====
else {
    alert("Lo sentimos. El API de Google Maps no es compatible con este Navegador.");
}
}


function initialPOIS() {
    showWait();
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=InitialPOIS", true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            
            //loadIbox();
            // document.getElementById("loadInfoMap").innerHTML = "<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span><br />";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado
            unloadIbox();
            var xmlDoc = request.responseXML; // Se transforma a XML

            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                // Se recoge el tipo de error
                side_bar_pois = error[0].getAttribute("tipoError");
            }
            else { // Si no existe ningún error
                var POIs = xmlDoc.documentElement.getElementsByTagName("datos_poi");
                // Se recorre el array de marcadores
                for (var i = 0; i < POIs.length; i++) {
                    // Se obtienen los atributos de cada marcador
                    var lat = parseFloat(POIs[i].getAttribute("latitud")); // La latitud del marcador
                    var lng = parseFloat(POIs[i].getAttribute("longitud")); // La longitud del marcador
                    var point = new GLatLng(lat,lng); // Se crea el punto donde se situará el marcador en el mapa
                    var imagen = POIs[i].getAttribute("icono"); // El icono del marcador
                    var id = parseInt(POIs[i].getAttribute("id_poi"));
                    var titulo = POIs[i].getAttribute("titulo"); // El título del marcador
                    var tagsPOI = POIs[i].getAttribute("tags"); // Los tags del marcador
                    var html = POIs[i].getAttribute("html"); // La información del marcador
                    var autor = POIs[i].getAttribute("login"); // El autor del marcador
                    var created = POIs[i].getAttribute("fecha_creacion"); // La fecha de creación del marcador
                    var expired = POIs[i].getAttribute("fecha_caducidad"); // La fecha de expiración del marcador
                    var icono = testIcon(imagen);
                    /*var icono = new GIcon (Icon);
                    icono.image = imagen;
                    icono.shadow = testShadow(imagen);*/
                    var id_region = parseInt(POIs[i].getAttribute("id_region"));

                    // Se crea el marcador y se añade al mapa
                    var marker = createMarkerPOI(point, id, icono, titulo, html, tagsPOI, autor, created, expired, counter, i, true, id_region);
                    map.addOverlay(marker);
                    marker.disableDragging();
                }
                showWait();
            }
            // Se añade al div "loadInfoMap" la información que haya en la variable 'side_bar_poisrute'
            //            document.getElementById("loadInfoMap").innerHTML = "<div style=\"font-size: 0.9em\">" + side_bar_pois + side_bar_routes + side_bar_polygons + "</div>";
            //    document.getElementById("loadInfoMap").innerHTML = "";

        }
    }
    request.send(null);
}

/**
* Función que crea y carga el mapa de las zonas
*/
function loadMap(latS, lngS, zoomS) {
    // ===== Si el Navegador es compatible =====
    if (GBrowserIsCompatible()) {
        // Se crea el mapa de Google
        map = new GMap2(document.getElementById("map"));
        // +++++ Se añaden los controles al mapa +++++
        // Control con flechas para mover el mapa, barra de zoom...
        map.addControl(new GLargeMapControl());
        // Tipos de Mapa (el tipo "Híbrido" aparece como un hijo del de "Satélite")
        map.addControl(new GHierarchicalMapTypeControl());
        // Añade el Tipo de Mapa "Relieve"
        map.addMapType(G_PHYSICAL_MAP);
        // Escala del mapa
        map.addControl(new GScaleControl());
        // Estabelecer el Centro y zoom inicial del mapa
        map.setCenter(new GLatLng(parseFloat(latS),parseFloat(lngS)), parseInt(zoomS));
        map.savePosition();
        // Se permite hacer zoom con la rueda del ratón
        map.enableScrollWheelZoom();
        // El zoom se realiza de forma contiunada
        map.enableContinuousZoom();
        // Se oculta el "overflow" de la flechas rojas cuando se hace zoom cerca del borde del mapa
        map.getContainer().style.overflow = "hidden";

        // Poner el logotipo de CEDETEL en el fondo mientras se carga el mapa
        document.getElementById("map").style.background = "#C8C5C5 center no-repeat url(img/carga_mapa_cedetel.jpg)";
        
        map.addControl(new buttonSizeMap(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
    }
    // ===== Mostrar una advertencia si el Navegador no es compatible =====
    else {
        alert("Lo sentimos. El API de Google Maps no es compatible con este Navegador.");
    }
}

/**
* Función que obtiene los títulos de las agrupaciones que hay en un servicio
*
* @param (serviceID) Identificador del servicio
* @param (zoneID) Identificador de la zona
*/
function getTitlesOfService(serviceID,zoneID) {
    if (mapActivated) {
        var continuePetition = deshabilitar();

        if(!continuePetition) {
            return;
        }
        else {
            mapActivated = false;
        }
    }
    if (timeout2 != null) {
        clearTimeout(timeout2);
        timeout2 = null;
    }

    //loadIbox();
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=getTitlesOfService&serviceID=" + serviceID + "&zoneID=" + zoneID, true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            // Se utiliza el DOM para que lo lea el IE6, ya que lo que se modifican son tablas (que son de tipo 'SóloLectura' en IE6)
            /* var tbody = document.createElement("tbody"); tbody.setAttribute("id","loadData");
            var tr = document.createElement("tr");
            var td = document.createElement("td");
            var div = document.createElement("div");

            div.innerHTML= "<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span>";
            td.appendChild(div);
            tr.appendChild(td);
            tbody.appendChild(tr);

            document.getElementById("loadData").parentNode.replaceChild(tbody, document.getElementById("loadData"));
            */ document.getElementById("loadData").innerHTML ="<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span>";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado

            var xmlDoc = request.responseXML; // Se transforma a XML
            // Se oculta las posibles ventanas de información abiertas, se limpia el mapa
            // y se limpia el div 'loadInfoMap' que contiene los nombres de los marcadores de las rutas
            map.getInfoWindow().hide();
            if (!mantener){
                //                map.clearOverlays();
                //                map.returnToSavedPosition();
            }
            //  document.getElementById("loadInfoMap").innerHTML = "";
            // Se resetean la variable que guardan los enlaces de las agrupaciones y puntos
            // Se utiliza el DOM para que lo lea el IE6, ya que lo que se modifican son tablas (que son de tipo 'SóloLectura' en IE6)
            //var side_bar_total = "";
            var tbody = "";
            var side_bar_agrupations = "";
            var side_bar_allowLine = "";
            TitlesAll = [];
            var total_all = 0;

            // Se obtiene un array de errores
            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Error</div></div>"
                + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p class=\"InfoBox\">" + error[0].getAttribute("title") + "</p></div>"
                + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\">&nbsp;</div>";

                /*var tr1 = document.createElement("tr");var tr2 = document.createElement("tr");var tr3 = document.createElement("tr");
                var td1 = document.createElement("td");var td2 = document.createElement("td");var td3 = document.createElement("td");

                td1.setAttribute("class","widthCell"); td1.setAttribute((document.all ? "className" : "class"), "widthCell"); td1.style.backgroundImage = "url(img/cabeza_menu.png)"; td1.style.height = "34px";
                td2.setAttribute("class","widthCellData"); td2.setAttribute((document.all ? "className" : "class"), "widthCellData"); td2.style.backgroundImage = "url(img/cuerpo_menu.png)"; td2.style.textAlign = "center";
                td3.setAttribute("class","widthCell"); td3.setAttribute((document.all ? "className" : "class"), "widthCell"); td3.style.backgroundImage = "url(img/pie_menu.png)"; td3.style.height = "21px";

                var p = document.createElement("p");
                p.setAttribute((document.all ? "className" : "class"), "InfoBox");
                p.innerHTML = error[0].getAttribute("title");

                var div = document.createElement("div");
                div.setAttribute((document.all ? "className" : "class"), "TitleZone");
                div.innerHTML = "Error";

                td1.appendChild(div); tr1.appendChild(td1);
                td2.appendChild(p); tr2.appendChild(td2);
                td3.value = "&nbsp;"; tr3.appendChild(td3);

                tbody.appendChild(tr1);
                tbody.appendChild(tr2);
                tbody.appendChild(tr3);*/

                // Se cambia el valor del total
                total_all = -1;
            }
            else { // Si no existe ningún error
                // ========= Se procesan los títulos de las agrupaciones y POIs sueltos ===========
                var list_all = "";
                var count_all = 0;

                // Se obtiene un array de las agrupaciones
                var agrupaciones = xmlDoc.documentElement.getElementsByTagName("agrupation");
                // Si existe algún elemento en el array de agrupaciones
                if (agrupaciones[0]) {
                    // Se recorre el array de las agrupaciones
                    for (var i = 0; i < agrupaciones.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada agrupación
                        var titleAgrupation = agrupaciones[i].getAttribute("title"); // El título de la agrupación
                        var IdAgrupation = parseInt(agrupaciones[i].getAttribute("IdAgrupacion")); // El Id de la agrupación
                        var infoAgrup = agrupaciones[i].getAttribute("Info");
                        var canModify = agrupaciones[i].getAttribute("canModify");

                        // Se crea el enlace para cargar la agrupación en el mapa
                        list_all += "<a class=\"initLink\" href=\"javascript:void(0)\" onclick=\"loadService('" + IdAgrupation + "', 1, " + canModify + ", " + zoneID + "," + serviceID + ")\" title=\"'" + titleAgrupation + "'\">" + titleAgrupation + "</a>" + infoAgrup;
                        if (IdAgrupation == 2) {
                            list_all += "&nbsp;&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"BusSimulator()\" title=\"Simulador de Autobuses\"><img class=\"imgInfo\" src=\"img/busblue.png\" alt=\"Simulador\"></a>";
                        }

                        list_all += "\n<br />";

                        if (count_all == 10){
                            TitlesAll.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }
                }

                // Se obtiene un array de los POIs
                var POIS = xmlDoc.documentElement.getElementsByTagName("pois");
                // Si existe algún elemento en el array de POIS
                if (POIS[0]) {
                    // Se recorre el array de los POIs
                    for (var i = 0; i < POIS.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada POI
                        var titlePOI = POIS[i].getAttribute("title"); // El título del POI
                        var IdPOI = parseInt(POIS[i].getAttribute("IdPOI")); // El Id del POI
                        var infoPOI = POIS[i].getAttribute("Info");
                        var canModify = POIS[i].getAttribute("canModify");

                        // Se crea el enlace para cargar el POI en el mapa
                        list_all += "<a class=\"initLink\" href=\"javascript:void(0)\" onclick=\"loadService('" + IdPOI + "', 0, " + canModify + ", " + zoneID + "," + serviceID + ")\" title=\"" + titlePOI + "\">" + titlePOI + "</a> " + infoPOI + "\n<br />";

                        if (count_all == 10){
                            TitlesAll.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }
                }

                if (list_all != "") {
                    TitlesAll.push(list_all);
                    total_all++;
                }
            }

            if (total_all != -1) {
                var servicio = xmlDoc.documentElement.getElementsByTagName("service");

                tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px; text-align: right;\"><div class=\"TitleZone\" style=\"float: left;\">" + servicio[0].getAttribute("name") + "</div><div class=\"botonera\">" + servicio[0].getAttribute("write") + "<button class=\"buttons but_act\" title=\"Buscar información en este servicio\" onclick=\"PageSearchIntoService('" + servicio[0].getAttribute("name") + "','" + zoneID + "','" + serviceID + "');\" type=\"button\"><img src=\"img/ico_buscar.png\" alt=\"Buscar\" /></button></div></div>"
                + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p id=\"TitlesAll\" class=\"InfoBox\"></p></div>"
                + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center; height: 5px;\">&nbsp;</div>"
                + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\"><div id=\"numAll\" class=\"numeration\"></div></div>";
                /*


                var tr1 = document.createElement("tr");var tr2 = document.createElement("tr");var tr3 = document.createElement("tr");var tr4 = document.createElement("tr");
                var td1 = document.createElement("td");var td2 = document.createElement("td");var td3 = document.createElement("td");var td4 = document.createElement("td");

                td1.setAttribute("class","widthCell"); td1.setAttribute((document.all ? "className" : "class"), "widthCell"); td1.style.backgroundImage = "url(img/cabeza_menu.png)"; td1.style.height = "34px"; td1.style.textAlign = "right";
                td2.setAttribute("class","widthCellData"); td2.setAttribute((document.all ? "className" : "class"), "widthCellData"); td2.style.backgroundImage = "url(img/cuerpo_menu.png)"; td2.style.textAlign = "center";
                td3.setAttribute("class","widthCellData"); td3.setAttribute((document.all ? "className" : "class"), "widthCellData"); td3.style.backgroundImage = "url(img/cuerpo_menu.png)"; td3.style.textAlign = "center"; td3.style.lineHeight = "5px";
                td4.setAttribute("class","widthCell"); td4.setAttribute((document.all ? "className" : "class"), "widthCell"); td4.style.backgroundImage = "url(img/pie_menu.png)"; td4.style.height = "21px";

                var p = document.createElement("p");
                p.setAttribute("id","TitlesAll");
                p.setAttribute((document.all ? "className" : "class"), "InfoBox");



                var divcab = document.createElement("div");
                divcab.setAttribute((document.all ? "className" : "class"), "TitleZone");
                divcab.innerHTML = servicio[0].getAttribute("name");
                divcab.style.cssFloat = "left";
                divcab.style.styleFloat = "left";

                var divboton = document.createElement("div");
                divboton.setAttribute((document.all ? "className" : "class"), "botonera");
                divboton.innerHTML = servicio[0].getAttribute("write") + "<button class=\"buttons but_act\" title=\"Buscar información en este servicio\" onclick=\"PageSearchIntoService('" + servicio[0].getAttribute("name") + "','" + zoneID + "','" + serviceID + "');\" type=\"button\"><img src=\"img/ico_buscar.png\" alt=\"Buscar\" /></button>"

                var div = document.createElement("div");
                div.setAttribute("id","numAll");
                div.setAttribute((document.all ? "className" : "class"), "numeration");

                td1.appendChild(divcab); td1.appendChild(divboton); tr1.appendChild(td1);
                td2.appendChild(p); tr2.appendChild(td2);
                td3.value = "&nbsp;"; tr3.appendChild(td3);
                td4.appendChild(div); tr4.appendChild(td4);

                tbody.appendChild(tr1);
                tbody.appendChild(tr2);
                tbody.appendChild(tr3);
                tbody.appendChild(tr4);*/
            }
            // Se añade los enlaces de las rutas al tr 'loadData'
            // document.getElementById("loadData").parentNode.replaceChild(tbody,document.getElementById("loadData"));
            //document.getElementById("loadData").innerHTML = side_bar_total;
            document.getElementById("loadData").innerHTML = tbody;

            if (total_all != -1 && total_all != 0) {
                cargarInfo(1, total_all);
            }
        }
    }
    request.send(null);
}

/**
* Función que carga la ruta en el mapa
*
* @param (IdAgrupacion) Identificador de la ruta
*/
function loadService(AgrOrPoiID, allowLine, canModify, ZoneID, ServiceID, zonausuario) {
    if (mapActivated) {
        var continuePetition = deshabilitar();

        if(!continuePetition) {
            return;
        }
        else {
            mapActivated = false;
        }
    }
    // ===== Start with an empty GLatLngBounds object =====
    if (!mantener){
        bounds = new GLatLngBounds();
    }
    if (timeout2 != null) {
        clearTimeout(timeout2);
        timeout2 = null;
    }
    showWait();
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=loadService&AgrOrPoiID=" + AgrOrPoiID + "&allowLine=" + allowLine, true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            //loadIbox();
            document.getElementById("MapInfoData").innerHTML = "<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span><br />";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado
            unloadIbox();
            var xmlDoc = request.responseXML; // Se transforma a XML

            // Se resetean la variable que guardan los enlaces de los marcadores, líneas y polígonos
            side_bar_pois = "";
            side_bar_routes = "";
            side_bar_polygons = "";

            // Se oculta las posibles ventanas de información abiertas y se limpia el mapa
            map.getInfoWindow().hide();
            counter = 0;
            if (!mantener){
                map.clearOverlays();



                // Se resetean los arrays
               // counter = 0;
                gmarkers = [];
                htmlsPois = [];
                groutes = [];
                htmlsRoutes = [];
                gpolygons = [];
                htmlsPolygons = [];
            }
            else {
                //   counter++;
            }

            // Se resetan los contenidos
            var titulin = "";
            var contenido = "";
            // Se obtiene un array de errores
            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                // Se recoge el tipo de error
                titulin = "Error";
                contenido = error[0].getAttribute("tipoError");
            }
            else { // Si no existe ningún error
                var agrupa = xmlDoc.documentElement.getElementsByTagName("datos_agrupacion");

                for (var a = 0; a < agrupa.length; a++) {
                    titulin = agrupa[a].getAttribute("titulo");

                    var tagsAgr = agrupa[a].getAttribute("tags");
                    if (tagsAgr != "null" && tagsAgr != "") {
                        contenido = "<span style=\"font-size: 0.7em;\">Etiquetas: " + processTags(tagsAgr, true) + "</span><br />";
                    }

                    var modification = false;
                    if (agrupa[a].getAttribute("permiso_escritura") == "si") {
                        modification = true;
                    }

                    ModifAgr = new Array(titulin, processTags(tagsAgr, false), modification)
                }
                // ========= Se procesan las líneas ===========
                // Se obtiene un array de la ruta
                var lines = xmlDoc.documentElement.getElementsByTagName("datos_ruta");
                tempObject = [];
                temphtml= [];

                Modifrutas = [];
                ModifHtmlrutas = [];
                IDsRutas = [];

                if (lines.length > 0) {
                    contenido += "<img class=\"imgInfo\" title=\"Itinerarios\" alt=\"Itinerario\" src=\"img/Blu.png\" /> - Itinerarios<br />";
                }

                // Se recorre el array de la ruta
                for (var a = 0; a < lines.length; a++) {
                    // Se obtienen los atributos de la ruta
                    var colour = "#" + lines[a].getAttribute("linea_color"); // El color de la línea
                    var width  = parseInt(lines[a].getAttribute("linea_ancho")); // El ancho de la línea
                    var opacity  = parseFloat(lines[a].getAttribute("linea_opacidad")); // La opacidad de la línea
                    // Se obtiene un array con los vértices o puntos de la línea
                    var pointsRoute = lines[a].getElementsByTagName("rutas_vertices");
                    // Array donde se guardarán los puntos para dibujar la línea
                    var pts = [];
                    // Se recorre el array de los vértices
                    for (var i = 0; i < pointsRoute.length; i++) {
                        // se insertan en el array de puntos los vértices
                        pts[i] = new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud")));
                        // ==== Each time a point is found, extent the bounds ato include it =====
                        bounds.extend(new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud"))));
                    }
                    var tituloRuta = lines[a].getAttribute("nombre_ruta"); // El título de la ruta
                    var authorR = lines[a].getAttribute("login"); // El autor de la ruta
                    var tagsR = lines[a].getAttribute("tags"); // Los tags de la ruta
                    var idR = lines[a].getAttribute("id_ruta");

                    // Se crea la línea y se añade al mapa
                    var ruta = createRoute(pts, colour, width, opacity, tituloRuta, authorR, tagsR, counter, a);
                    map.addOverlay(ruta);

                    if (lines[a].getAttribute("permiso_escritura") == "si") {
                        Modifrutas.push(ruta);
                        ModifHtmlrutas.push(new Array(tituloRuta, processTags(tagsR, false)));
                        IDsRutas.push(idR);
                    }
                }

                groutes.push(tempObject);
                htmlsRoutes.push(temphtml);

                contenido += side_bar_routes;
                // ================================================
                // ========= Se procesan los poligonos ===========
                // Se obtiene un array de los poligonos
                var polygon = xmlDoc.documentElement.getElementsByTagName("datos_poligono");
                tempObject = [];
                temphtml= [];

                ModifAreas = [];
                ModifHtmlAreas = [];
                IDsAreas = [];
                ModifstyleAreas = [];

                if (polygon.length > 0) {
                    contenido += "<img class=\"imgInfo\" title=\"Espacios\" alt=\"Espacio\" src=\"img/Bpu.png\" /> - Espacios<br />";
                }
                // Se recorre el array de la ruta
                for (var a = 0; a < polygon.length; a++) {
                    // Se obtienen los atributos del polígono
                    var colour = "#" + polygon[a].getAttribute("linea_color"); // El color del borde del polígono
                    var width  = parseInt(polygon[a].getAttribute("linea_ancho")); // El ancho del borde del polígono
                    var opacity  = parseFloat(polygon[a].getAttribute("linea_opacidad")); // La opacidad del borde del polígono
                    var fillcolour = "#" + polygon[a].getAttribute("color_relleno"); // El color del relleno del polígono
                    var fillopacity  = parseFloat(polygon[a].getAttribute("opacidad_relleno")); // La opacidad del relleno del polígono
                    // Se obtiene un array con los vértices o puntos del polígono
                    var pointsPolygon = polygon[a].getElementsByTagName("poligonos_vertices");
                    // Array donde se guardarán los puntos para dibujar el polígono
                    var pts = [];
                    // Se recorre el array de los vértices
                    for (var i = 0; i < pointsPolygon.length; i++) {
                        // se insertan en el array de puntos los vértices
                        pts[i] = new GLatLng(parseFloat(pointsPolygon[i].getAttribute("latitud")),
                            parseFloat(pointsPolygon[i].getAttribute("longitud")));
                        // ==== Each time a point is found, extent the bounds ato include it =====
                        bounds.extend(new GLatLng(parseFloat(pointsPolygon[i].getAttribute("latitud")),
                            parseFloat(pointsPolygon[i].getAttribute("longitud"))));
                    }
                    var tituloPolygon = polygon[a].getAttribute("nombre_poligono"); // El título del polígono
                    var authorP = polygon[a].getAttribute("login"); // El autor del polígono
                    var tagsP = polygon[a].getAttribute("tags"); // Los tags del polígono
                    var idP = polygon[a].getAttribute("id_poligono");

                    // Se crea el polígono y se añade al mapa
                    var area = createPolygon (pts, colour, width, opacity, fillcolour, fillopacity, tituloPolygon, authorP, tagsP, counter, a);
                    map.addOverlay(area);

                    if (polygon[a].getAttribute("permiso_escritura") == "si") {
                        ModifAreas.push(area);
                        ModifHtmlAreas.push(new Array(tituloPolygon, processTags(tagsP, false)));
                        IDsAreas.push(idP);
                        ModifstyleAreas.push(new Array(colour, width, opacity));
                    }
                }
                gpolygons.push(tempObject);
                htmlsPolygons.push(temphtml);

                contenido += side_bar_polygons;
                // ================================================
                // ========= Se procesan los marcadores ===========
                // Se obtiene un array de los marcadores
                var POIs = xmlDoc.documentElement.getElementsByTagName("datos_poi");
                tempObject = [];
                temphtml= [];


                ModifMarkers = [];
                ModifHtml = [];
                IDsMarkers = [];

                if (POIs.length > 0) {
                    contenido += "<img class=\"imgInfo\" title=\"Puntos de Interés\" alt=\"Pois\" src=\"img/Bmu.png\" /> - Puntos de Interés<br />";
                }
                // Se recorre el array de marcadores
                for (var i = 0; i < POIs.length; i++) {
                    // Se obtienen los atributos de cada marcador
                    var lat = parseFloat(POIs[i].getAttribute("latitud")); // La latitud del marcador
                    var lng = parseFloat(POIs[i].getAttribute("longitud")); // La longitud del marcador
                    var point = new GLatLng(lat,lng); // Se crea el punto donde se situará el marcador en el mapa
                    var imagen = POIs[i].getAttribute("icono"); // El icono del marcador
                    var id = parseInt(POIs[i].getAttribute("id_poi"));
                    var titulo = POIs[i].getAttribute("titulo"); // El título del marcador
                    var tagsPOI = POIs[i].getAttribute("tags"); // Los tags del marcador
                    var html = POIs[i].getAttribute("html"); // La información del marcador
                    var autor = POIs[i].getAttribute("login"); // El autor del marcador
                    var created = POIs[i].getAttribute("fecha_creacion"); // La fecha de creación del marcador
                    var expired = POIs[i].getAttribute("fecha_caducidad"); // La fecha de expiración del marcador
                    var icono = testIcon(imagen);
                    /*var icono = new GIcon (Icon);
                    icono.image = imagen;
                    icono.shadow = testShadow(imagen);*/

                    // Se crea el marcador y se añade al mapa
                    var marker = createMarkerPOI(point, id, icono, titulo, html, tagsPOI, autor, created, expired, counter, i);

                    map.addOverlay(marker);
                    marker.disableDragging();

                    if (POIs[i].getAttribute("permiso_escritura") == "si") {
                        ModifMarkers.push(marker);
                        ModifHtml.push(new Array(titulo, html, processTags(tagsPOI, false)));
                        IDsMarkers.push(id);
                    }
                    // ==== Each time a point is found, extent the bounds ato include it =====
                    bounds.extend(point);
                }
                gmarkers.push(tempObject);
                htmlsPois.push(temphtml);

                contenido += side_bar_pois;
            }

            var information = "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">" + titulin + "</div></div>"
            + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p class=\"InfoBox\">" + contenido + "</p></div>"
            + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\">&nbsp;</div>";

            // Se añade al div "loadInfoMap" la información que haya en la variable 'side_bar_poisrute'
            //            document.getElementById("loadInfoMap").innerHTML = "<div style=\"font-size: 0.9em\">" + side_bar_pois + side_bar_routes + side_bar_polygons + "</div>";
            document.getElementById("MapInfoData").innerHTML = information;
            // ===== determine the zoom level from the bounds =====
            map.setZoom(map.getBoundsZoomLevel(bounds));

            // ===== determine the centre from the bounds ======
            map.setCenter(bounds.getCenter());
            showWait();
        }
    }
    request.send(null);

    showTypefilesAndRates (AgrOrPoiID, allowLine);

    if (allowLine == 1) {
        getComentarios(AgrOrPoiID);
    } else {
    document.getElementById("comentarios").innerHTML = "";
}


    if(canModify){
        BotonModificar(AgrOrPoiID, allowLine, ZoneID, ServiceID, zonausuario);
    } else {
        document.getElementById("ModifMap").innerHTML = "";
    }
}

function BusSimulator() {
    if (timeout2 != null) {
        clearTimeout(timeout2);
        timeout2 = null;
    }
    bounds = new GLatLngBounds();
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=loadService&AgrOrPoiID=2&allowLine=1", true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            // loadIbox();

            document.getElementById("MapInfoData").innerHTML = "<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span><br />";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado
            unloadIbox();
            var xmlDoc = request.responseXML; // Se transforma a XML

            // Se oculta las posibles ventanas de información abiertas y se limpia el mapa
            map.getInfoWindow().hide();
            map.clearOverlays();
            // Se resetean la variable que guardan los enlaces de los marcadores, líneas y polígonos
            side_bar_pois = "";
            side_bar_routes = "";

            // Se resetean los arrays
            gmarkers = [];
            htmlsPois = [];
            groutes = [];
            htmlsRoutes = [];
            identificador = 0;
            // Se obtiene un array de errores
            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                // Se recoge el tipo de error
                //  side_bar_pois = error[0].getAttribute("tipoError");
            }
            else { // Si no existe ningún error
                // ========= Se procesan las líneas ===========
                // Se obtiene un array de la ruta
                var lines = xmlDoc.documentElement.getElementsByTagName("datos_ruta");
                tempObject = [];
                temphtml= [];
                // Se recorre el array de la ruta
                for (var a = 0; a < lines.length; a++) {
                    // Se obtienen los atributos de la ruta
                    var colour = "#" + lines[a].getAttribute("linea_color"); // El color de la línea
                    var width  = parseInt(lines[a].getAttribute("linea_ancho")); // El ancho de la línea
                    var opacity  = parseFloat(lines[a].getAttribute("linea_opacidad")); // La opacidad de la línea
                    // Se obtiene un array con los vértices o puntos de la línea
                    var pointsRoute = lines[a].getElementsByTagName("rutas_vertices");
                    // Array donde se guardarán los puntos para dibujar la línea
                    var pts = [];
                    // Se recorre el array de los vértices
                    for (var i = 0; i < pointsRoute.length; i++) {
                        // se insertan en el array de puntos los vértices
                        pts[i] = new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud")));
                        // ==== Each time a point is found, extent the bounds ato include it =====
                        bounds.extend(new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud"))));
                    }
                    var tituloRuta = lines[a].getAttribute("nombre_ruta"); // El título de la ruta
                    var authorR = lines[a].getAttribute("login"); // El autor de la ruta
                    var tagsR = lines[a].getAttribute("tags"); // Los tags de la ruta

                    // Se crea la línea y se añade al mapa
                    var ruta = createRoute(pts, colour, width, opacity, tituloRuta, authorR, tagsR, counter, a);
                    map.addOverlay(ruta);
                }
                groutes.push(tempObject);
                htmlsRoutes.push(temphtml);
                // ================================================
                // ========= Se procesan los marcadores ===========
                // Se obtiene un array de los marcadores
                var POIs = xmlDoc.documentElement.getElementsByTagName("datos_poi");
                tempObject = [];
                temphtml= [];

                // Se recorre el array de marcadores
                for (var i = 0; i < POIs.length; i++) {
                    // Se obtienen los atributos de cada marcador
                    var lat = parseFloat(POIs[i].getAttribute("latitud")); // La latitud del marcador
                    var lng = parseFloat(POIs[i].getAttribute("longitud")); // La longitud del marcador
                    var point = new GLatLng(lat,lng); // Se crea el punto donde se situará el marcador en el mapa
                    var id = parseInt(POIs[i].getAttribute("id_poi"));
                    //var icono = POIs[i].getAttribute("icono"); // El icono del marcador
                    var titulo = POIs[i].getAttribute("titulo"); // El título del marcador
                    var tagsPOI = POIs[i].getAttribute("tags"); // Los tags del marcador
                    var html = POIs[i].getAttribute("html"); // La información del marcador
                    var autor = POIs[i].getAttribute("login"); // El autor del marcador
                    var created = POIs[i].getAttribute("fecha_creacion"); // La fecha de creación del marcador
                    var expired = POIs[i].getAttribute("fecha_caducidad"); // La fecha de expiración del marcador

                    var icono = new GIcon (Icon);
                    icono.image = "http://maps.google.com/mapfiles/kml/pal2/icon13.png";
                    icono.shadow = "http://maps.google.com/mapfiles/kml/pal2/icon13s.png";

                    // Se crea el marcador y se añade al mapa
                    var marker = createMarkerPOI(point, id, icono, titulo, html, tagsPOI, autor, created, expired, counter, i);
                    map.addOverlay(marker);
                    marker.disableDragging();

                    // ==== Each time a point is found, extent the bounds ato include it =====
                    bounds.extend(point);
                }
                gmarkers.push(tempObject);
                htmlsPois.push(temphtml);
            }
            // Se añade al div "loadInfoMap" la información que haya en la variable 'side_bar_poisrute'
            //           document.getElementById("loadInfoMap").innerHTML = "<div style=\"font-size: 0.9em\">" + side_bar_pois + side_bar_routes + side_bar_polygons + "</div>";
            document.getElementById("MapInfoData").innerHTML = "";
            // ===== determine the zoom level from the bounds =====
            map.setZoom(map.getBoundsZoomLevel(bounds));

            // ===== determine the centre from the bounds ======
            map.setCenter(bounds.getCenter());

            Abuses = [];
            MapBuses = [];
            getRealTimeBuses();
        }
    }

    request.send(null);

    showTypefilesAndRates (2, 1);
    getComentarios(2);

}


function getRealTimeBuses() {
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=getRealTimeBuses", true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 4) { // Cuando la carga ha finalizado
            var xmlDoc = request.responseXML; // Se transforma a XML

            // ================================================
            // ========= Se procesan los autobuses ===========
            // Se obtiene un array de los marcadores
            var buses = xmlDoc.documentElement.getElementsByTagName("datos_poi");
            tempObject = [];
            temphtml= [];

            for (var x = 0; x < Abuses.length; x++) {
                Abuses[x][1] = false;
            }

            // Se recorre el array de marcadores
            for (var i = 0; i < buses.length; i++) {
                // Se obtienen los atributos de cada marcador
                var lat = parseFloat(buses[i].getAttribute("latitud")); // La latitud del marcador
                var lng = parseFloat(buses[i].getAttribute("longitud")); // La longitud del marcador
                var point = new GLatLng(lat,lng); // Se crea el punto donde se situará el marcador en el mapa
                var id = parseInt(buses[i].getAttribute("id_poi"));
                var imagen = buses[i].getAttribute("icono"); // El icono del marcador
                var titulo = buses[i].getAttribute("titulo"); // El título del marcador
                var tagsPOI = buses[i].getAttribute("tags"); // Los tags del marcador
                var html = buses[i].getAttribute("html"); // La información del marcador
                var autor = buses[i].getAttribute("login"); // El autor del marcador
                var created = buses[i].getAttribute("fecha_creacion"); // La fecha de creación del marcador
                var expired = buses[i].getAttribute("fecha_caducidad"); // La fecha de expiración del marcador

                if (id > 0) {
                    for (var k = 0; k < gmarkers[0].length; k++) {
                        if (gmarkers[0][k][1] == id) {
                            var newhtml = InfoPoiWindow(titulo, html, tagsPOI, autor, created, expired);
                            htmlsPois[0][k] [1] = html;
                            if (!map.getInfoWindow().isHidden()) {
                                if (identificador == id) {
                                    document.getElementById("htmlMarker").innerHTML = html;
                                    map.updateInfoWindow(map.getInfoWindow().getTabs());
                                }
                            }
                            else {
                                gmarkers[0][k][0].bindInfoWindowHtml(newhtml);
                            }
                        }
                    }
                } else if (id < 0) {
                var contador = -1;

                for (var k = 0; k < Abuses.length; k++) {
                    if (Abuses[k][0] == id) {
                        contador = k;
                        break;
                    }
                }

                if (contador == -1) {
                    Abuses.push(new Array(id, true));
                    var icono = new GIcon (Icon);
                    icono.image = imagen;
                    icono.shadow = "http://maps.google.com/mapfiles/kml/pal4/icon62s.png";

                    var autobus = createMarkerPOIBus (point, id, icono, titulo, html, tagsPOI, autor, created, expired);
                    MapBuses.push(autobus);
                    map.addOverlay(autobus);
                } else {
                Abuses[contador][1] = true;
                MapBuses[contador].setLatLng(point);
                if (!map.getInfoWindow().isHidden()) {
                    if (identificador == id) {
                        document.getElementById("htmlMarker").innerHTML = html;
                        map.updateInfoWindow(map.getInfoWindow().getTabs());
                    }
                }
                else {
                    MapBuses[contador].bindInfoWindowHtml(InfoPoiWindow(titulo, html, "", autor, created, expired));
                }
            }
        }
    }

    for (var x = 0; x < Abuses.length; x++) {
        if(Abuses[x][1] == false) {
            Abuses.splice(x, 1);
            map.removeOverlay(MapBuses[x]);
            MapBuses.splice(x, 1);
        }
    }
}
}

request.send(null);

timeout2 = setTimeout("getRealTimeBuses()",5000);
}

function createMarkerPOIBus (point, id, icono, titulo, html, tags, autor, created, expired) {
    // Se crea el marcador
    var marker = new GMarker(point, {icon:icono, title:titulo});

    // Se añade el escuchador para que al hacer "click", aparezca la InfoWindow
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(InfoPoiWindow(titulo, html, "null", autor, created, expired));
    });

    GEvent.addListener(marker, "infowindowopen", function() {
        identificador = id;
    });
    GEvent.addListener(marker, "infowindowclose", function() {
        identificador = 0;
    });

    return marker;
}




function ExternalData(IdServicio, IdZona, fecha) {
    if (mapActivated) {
        var continuePetition = deshabilitar();

        if(!continuePetition) {
            return;
        }
        else {
            mapActivated = false;
        }
    }
    // ===== Start with an empty GLatLngBounds object =====
    if (!mantener){
        bounds = new GLatLngBounds();
    }

    if (IdServicio == 8 && IdZona == 1) {
        fecha = "13/10/2008";
    }

    if (IdServicio == 6 && IdZona == 1) {
        fecha = "17/03/2008";
    }

    /*var tbody  = document.createElement("tbody"); tbody.setAttribute("id","loadData");
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.style.lineHeight = "13px";
    td.value = "&nbsp;"; tr.appendChild(td);
    tbody.appendChild(tr);
    document.getElementById("loadData").parentNode.replaceChild(tbody,document.getElementById("loadData"));*/

    // Borramos los comentarios y la puntuacion
    document.getElementById("filesAndRates").innerHTML = "";
    document.getElementById("comentarios").innerHTML = "";

    document.getElementById("loadData").innerHTML = "";
    if (timeout2 != null) {
        clearTimeout(timeout2);
        timeout2 = null;
    }
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=getExternalData&serviceID=" + IdServicio + "&zoneID=" + IdZona + "&fecha=" + fecha, true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            // loadIbox();
            document.getElementById("MapInfoData").innerHTML = "<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span><br />";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado
            unloadIbox();
            var xmlDoc = request.responseXML; // Se transforma a XML

            // Se oculta las posibles ventanas de información abiertas y se limpia el mapa
            map.getInfoWindow().hide();

            side_bar_pois = "";
            side_bar_routes = "";
            side_bar_polygons = "";
            
            counter = 0;
            if (!mantener){
                map.clearOverlays();
                // Se resetean la variable que guardan los enlaces de los marcadores, líneas y polígonos


                // Se resetean los arrays
              //  counter = 0;
                gmarkers = [];
                htmlsPois = [];
                groutes = [];
                htmlsRoutes = [];
                gpolygons = [];
                htmlsPolygons = [];
            }
            else {
                //  counter++;
            }

            // Se obtiene un array de errores
            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                // Se recoge el tipo de error
                side_bar_pois = error[0].getAttribute("tipoError");
            }
            else { // Si no existe ningún error
                // ========= Se procesan las líneas ===========
                // Se obtiene un array de la ruta
                var lines = xmlDoc.documentElement.getElementsByTagName("datos_ruta");
                tempObject = [];
                temphtml= [];
                // Se recorre el array de la ruta
                for (var a = 0; a < lines.length; a++) {
                    // Se obtienen los atributos de la ruta
                    var colour = "#" + lines[a].getAttribute("linea_color"); // El color de la línea
                    var width  = parseInt(lines[a].getAttribute("linea_ancho")); // El ancho de la línea
                    var opacity  = parseFloat(lines[a].getAttribute("linea_opacidad")); // La opacidad de la línea
                    // Se obtiene un array con los vértices o puntos de la línea
                    var pointsRoute = lines[a].getElementsByTagName("rutas_vertices");
                    // Array donde se guardarán los puntos para dibujar la línea
                    var pts = [];
                    // Se recorre el array de los vértices
                    for (var i = 0; i < pointsRoute.length; i++) {
                        // se insertan en el array de puntos los vértices
                        pts[i] = new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud")));
                        // ==== Each time a point is found, extent the bounds ato include it =====
                        bounds.extend(new GLatLng(parseFloat(pointsRoute[i].getAttribute("latitud")),
                            parseFloat(pointsRoute[i].getAttribute("longitud"))));
                    }
                    var tituloRuta = lines[a].getAttribute("nombre_ruta"); // El título de la ruta
                    var authorR = lines[a].getAttribute("login"); // El autor de la ruta
                    var tagsR = lines[a].getAttribute("tags"); // Los tags de la ruta

                    // Se crea la línea y se añade al mapa
                    var ruta = createRoute(pts, colour, width, opacity, tituloRuta, authorR, tagsR, counter, a);
                    map.addOverlay(ruta);
                }
                groutes.push(tempObject);
                htmlsRoutes.push(temphtml);
                // ================================================
                // ========= Se procesan los poligonos ===========
                // Se obtiene un array de los poligonos
                var polygon = xmlDoc.documentElement.getElementsByTagName("datos_poligono");
                tempObject = [];
                temphtml= [];
                // Se recorre el array de la ruta
                for (var a = 0; a < polygon.length; a++) {
                    // Se obtienen los atributos del polígono
                    var colour = "#" + polygon[a].getAttribute("linea_color"); // El color del borde del polígono
                    var width  = parseInt(polygon[a].getAttribute("linea_ancho")); // El ancho del borde del polígono
                    var opacity  = parseFloat(polygon[a].getAttribute("linea_opacidad")); // La opacidad del borde del polígono
                    var fillcolour = "#" + polygon[a].getAttribute("color_relleno"); // El color del relleno del polígono
                    var fillopacity  = parseFloat(polygon[a].getAttribute("opacidad_relleno")); // La opacidad del relleno del polígono
                    // Se obtiene un array con los vértices o puntos del polígono
                    var pointsPolygon = polygon[a].getElementsByTagName("poligonos_vertices");
                    // Array donde se guardarán los puntos para dibujar el polígono
                    var pts = [];
                    // Se recorre el array de los vértices
                    for (var i = 0; i < pointsPolygon.length; i++) {
                        // se insertan en el array de puntos los vértices
                        pts[i] = new GLatLng(parseFloat(pointsPolygon[i].getAttribute("latitud")),
                            parseFloat(pointsPolygon[i].getAttribute("longitud")));
                        // ==== Each time a point is found, extent the bounds ato include it =====
                        bounds.extend(new GLatLng(parseFloat(pointsPolygon[i].getAttribute("latitud")),
                            parseFloat(pointsPolygon[i].getAttribute("longitud"))));
                    }
                    var tituloPolygon = polygon[a].getAttribute("nombre_poligono"); // El título del polígono
                    var authorP = polygon[a].getAttribute("login"); // El autor del polígono
                    var tagsP = polygon[a].getAttribute("tags"); // Los tags del polígono

                    // Se crea el polígono y se añade al mapa
                    var area = createPolygon (pts, colour, width, opacity, fillcolour, fillopacity, tituloPolygon, authorP, tagsP, counter, a);
                    map.addOverlay(area);
                }
                gpolygons.push(tempObject);
                htmlsPolygons.push(temphtml);
                // ================================================
                // ========= Se procesan los marcadores ===========
                // Se obtiene un array de los marcadores
                var POIs = xmlDoc.documentElement.getElementsByTagName("datos_poi");
                tempObject = [];
                temphtml= [];
                // Se recorre el array de marcadores
                for (var i = 0; i < POIs.length; i++) {
                    // Se obtienen los atributos de cada marcador
                    var lat = parseFloat(POIs[i].getAttribute("latitud")); // La latitud del marcador
                    var lng = parseFloat(POIs[i].getAttribute("longitud")); // La longitud del marcador
                    var point = new GLatLng(lat,lng); // Se crea el punto donde se situará el marcador en el mapa
                    var id = parseInt(POIs[i].getAttribute("id_poi"));
                    var imagen = POIs[i].getAttribute("icono"); // El icono del marcador
                    var titulo = POIs[i].getAttribute("titulo"); // El título del marcador
                    var tagsPOI = POIs[i].getAttribute("tags"); // Los tags del marcador
                    var autor = POIs[i].getAttribute("login"); // El autor del marcador
                    var created = POIs[i].getAttribute("fecha_creacion"); // La fecha de creación del marcador
                    var expired = POIs[i].getAttribute("fecha_caducidad"); // La fecha de expiración del marcador
                    var html1 = POIs[i].getAttribute("html0"); // La información1 del marcador
                    var html2 = POIs[i].getAttribute("html1"); // La información2 del marcador
                    var label1 = POIs[i].getAttribute("label1"); // La información1 del marcador
                    var label2 = POIs[i].getAttribute("label2"); // La información2 del marcador
                    var icono;
                    if (imagen != null && imagen != "null") {
                        icono = new GIcon(Icon);
                        icono.image = imagen;
                        //icono.image = "http://maps.google.com/intl/es_ALL/mapfiles/marker.png";
                        icono.shadow = "";
                    }
                    else {
                        icono = testIcon("./img/map_icons/pushpin_yellow.png");
                        /*icono.image = "./img/map_icons/pushpin_yellow.png";
                        icono.shadow = testShadow("./img/map_icons/pushpin_yellow.png");*/
                    }

                    var html = new Array(html1, html2);
                    var label = new Array(label1, label2);
                    // Se crea el marcador y se añade al mapa

                    if (IdServicio == 10) {
                        var htmnormal = POIs[i].getAttribute("html");
                        var marker = createMarkerPOI(point, id, icono, titulo, htmnormal, tagsPOI, autor, created, expired, counter, i);
                    } else {
                    var marker = createMarkerPOIE(point, id, icono, titulo, html1, html2, tagsPOI, autor, created, expired, counter, i, label1, label2);
                }

                map.addOverlay(marker);
                marker.disableDragging();

                // ==== Each time a point is found, extent the bounds ato include it =====
                bounds.extend(point);
            }
            gmarkers.push(tempObject);
            htmlsPois.push(temphtml);
        }
        // Se añade al div "loadInfoMap" la información que haya en la variable 'side_bar_poisrute'
        //            document.getElementById("loadInfoMap").innerHTML = "<div style=\"font-size: 0.9em\">" + side_bar_pois + side_bar_routes + side_bar_polygons + "</div>";
        document.getElementById("MapInfoData").innerHTML = "";
        // ===== determine the zoom level from the bounds =====
        map.setZoom(map.getBoundsZoomLevel(bounds));

        // ===== determine the centre from the bounds ======
        map.setCenter(bounds.getCenter());
    }
}
request.send(null);
}

function createMarkerPOIE (point, id, icono, titulo,  html1, html2, tags, autor, created, expired, i, j, label1, label2) {
    // Se crea el marcador
    var marker = new GMarker(point, {icon:icono, title:titulo, draggable: true});

    // Se añade el escuchador para que al hacer "click", aparezca la InfoWindow
    GEvent.addListener(marker, "click", function() {
        var tabs = [];

        tabs.push(new GInfoWindowTab(label1,InfoPoiWindowE(titulo, html1, tags, autor, created, expired)));
        tabs.push(new GInfoWindowTab(label2,InfoPoiWindowE(titulo, html2, tags, autor, created, expired)));

        marker.openInfoWindowTabsHtml(tabs);
    });

    // Se guarda la información que se va a usar más tarde en el side_bar
    tempObject [j]= new Array(marker, id);
    temphtml[j] = new Array(titulo, html1, html2, tags, autor, created, expired, label1, label2);
    // Se añade el enlace del marcador a la variable "side_bar_poisrute"
    //   side_bar_pois += "<a href=\"javascript:void(0)\" onclick=\"myclickpoisE(" + i + ", " + j + ")\">" + titulo + "</a><br />";

    return marker;
}


/**
* Función para crear los marcadores
*
* @param (point) Punto (coordenadas) donde está ubicado el marcador
* @param (titulo) Título del marcador
* @param (html) Contenido de la ventana de información el marcador
* @param (tags) Tags del marcador
* @param (autor) Autor del marcador
* @param (created) Fecha de creación del marcador
* @param (expired) Fecha de caducidad del marcador
* @param (i) Contador i
* @param (j) Contador j
* @return El marcador
*/
function createMarkerPOI (point, id, icono, titulo, html, tags, autor, created, expired, i, j, acceder, id_reg) {
    // Se crea el marcador
    var marker = new GMarker(point, {icon:icono, title:titulo, draggable: true});

    // Se añade el escuchador para que al hacer "click", aparezca la InfoWindow
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(InfoPoiWindow(titulo, html, tags, autor, created, expired, acceder, id_reg));
    });

    GEvent.addListener(marker, "infowindowopen", function() {
        identificador = id;
    });
    GEvent.addListener(marker, "infowindowclose", function() {
        identificador = 0;
    });
    // Se guarda la información que se va a usar más tarde en el side_bar
    tempObject [j]= new Array(marker, id);
    temphtml[j] = new Array(titulo, html, tags, autor, created, expired);

    // Se añade el enlace del marcador a la variable "side_bar_poisrute"
    side_bar_pois += "<a class=\"initLink\" href=\"javascript:void(0)\" onclick=\"myclickpois(" + i + ", " + j + ")\">" + titulo + "</a><br />";

    return marker;
}

/**
* Función para crear las líneas
*
* @param (pts) Vértices de la línea
* @param (colour) Color de la línea
* @param (width) Ancho de la línea
* @param (opacity) Opacidad de la línea
* @param (tituloRuta) Título de la línea
* @param (authorR) Autor de la línea
* @param (tagsR) Tags de la línea
* @param (i) Contador i
* @param (j) Contador j
* @return La línea
*/
function createRoute(pts, colour, width, opacity, tituloRuta, authorR, tagsR, i, j) {
    // Se crea la línea
    var ruta = new GPolyline(pts,colour,width,opacity);

    // Se añade el escuchador para que la hacer "click en la línea", aparezca una ventana
    // de información con el título, el autor y los tags de la ruta
    GEvent.addListener(ruta, "click", function(latlng, index) {
        map.openInfoWindowHtml(latlng, InfoPolyWindow(tituloRuta, authorR, tagsR, ruta.getLength(), 'R'));
    });
    // Se añade el escuchador para que al pasar el ratón por encima de la línea, el ratón cambie a forma de mano
    GEvent.addListener(ruta,"mouseover", function() {
        cursor = "pointer";
    });

    // Se guarda la información que se va a usar más tarde en el side_bar
    tempObject [j]= ruta;
    temphtml[j] = new Array(tituloRuta, authorR, tagsR, ruta.getLength(), 'R');

    // Se añade el enlace del marcador a la variable "side_bar_poisrute"
    side_bar_routes += "<a class=\"initLink\" href=\"javascript:void(0)\" onclick=\"myclickroutes(" + i + ", " + j + ")\">" + tituloRuta + "</a>\n<br />";

    return ruta;
}

/**
* Función para crear los polígonos
*
* @param (pts) Vértices del polígono
* @param (colour) Color de la línea del polígono
* @param (width) Ancho de la línea del polígono
* @param (opacity) Opacidad de la línea del polígono
* @param (fillcolour) Color del relleno del polígono
* @param (fillopacity) Opacidad del relleno del polígono
* @param (tituloRuta) Título de la línea
* @param (authorR) Autor del polígono
* @param (tagsR) Tags del polígono
* @param (i) Contador i
* @param (j) Contador j
* @return El polígono
*/
function createPolygon (pts, colour, width, opacity, fillcolour, fillopacity, tituloPolygon, authorP, tagsP, i, j) {
    // Se crea el polígono
    var area = new GPolygon(pts,colour,width,opacity,fillcolour,fillopacity);

    // Se añade el escuchador para que la hacer "click en el polígono", aparezca una ventana
    // de información con el título, el autor y los tags deel polígono
    GEvent.addListener(area, "click", function(latlng, index) {
        map.openInfoWindowHtml(latlng, InfoPolyWindow(tituloPolygon, authorP, tagsP, area.getArea(), 'P'));
    });
    // Se añade el escuchador para que al pasar el ratón por encima de la línea, el ratón cambie a forma de mano
    GEvent.addListener(area,"mouseover", function() {
        cursor = "pointer";
    });

    // Se guarda la información que se va a usar más tarde en el side_bar
    tempObject [j]= area;
    temphtml[j] = new Array(tituloPolygon, authorP, tagsP, area.getArea(), 'P');

    // Se añade el enlace del marcador a la variable "side_bar_poisrute"
    side_bar_polygons += "<a class=\"initLink\" href=\"javascript:void(0)\" onclick=\"myclickpolygons(" + i + ", " + j + ")\">" + tituloPolygon + "</a>\n<br />";

    return area;
}

/**
* Función para crear la ventana de información del marcador
*
* @param (titulo) Título del marcador
* @param (html) Contenido de la ventana de información el marcador
* @param (tags) Tags del marcador
* @param (autor) Autor del marcador
* @param (created) Fecha de creación del marcador
* @param (expired) Fecha de caducidad del marcador
* @return El HTML que aparecerá en la ventana de información
*/
function InfoPoiWindow (titulo, html, tags, autor, created, expired, acceder, id_reg) {
    var InfoPoi = "<div style=\"width: 450px; height: 100%; font-size: 16px;\">";
    
    InfoPoi += "<div><div style=\"float: left;\">";
    
    if (titulo != "null" && titulo != "") {
        InfoPoi += "<span style=\"font-size: 1.5em; font-weight: bold; color: #004696;\">" + titulo + "</span><br />";
    }
    if (tags != "null" && tags != "") { // Si existe algún tag
        InfoPoi += "<span style=\"font-size: 0.7em;\">Etiquetas: " + processTags(tags, true) + "</span>";
    }
    
    InfoPoi += "</div><div style=\"float: right;\">";
    
    if (acceder) {
        InfoPoi += "<p style=\"text-align: right;\"><span style=\"font-size: small;\"><a href=\"zonas.jsp?idZone=" + id_reg + "\"><em><strong>Acceder</strong></em></a></span></p>";
    }
    
    InfoPoi += "</div></div>";

    InfoPoi += "<br style=\"clear: both;\"/><div id=\"htmlMarker\" style=\"max-height:380px; overflow-y:auto; padding-right:3px;\">";

    if (html != "null" && html != "") { // Si existe algún comentario
        InfoPoi += buscarVideos(html);
    }
    
    InfoPoi += "</div>";

    InfoPoi += "<br /><div style=\"font-size: 0.8em; text-align: right;\">"
    + "Creado por <span style=\"text-decoration: underline\">" + autor + "</span>";

    if (created != "null" && created.length == 10) { // Si existe fecha de caducidad
        InfoPoi +=  "<br /><span>el " + formatDate(created) + "</span>";
    }
    if (expired != "null") { // Si existe fecha de caducidad
        //InfoPoi += "<br /><span>Fecha de caducidad: " + formatDate(expired) + "</span>";
    }

    InfoPoi += "</div></div>";

    return InfoPoi;
}

/**
* Función para crear la ventana de información de la ruta/polígono
*
* @param (tituloPoly) El título de la ruta/polígono
* @param (author) Autor de la ruta/polígono
* @param (tags) Etiquetas de la ruta/polígono
* @return El HTML que aparecerá en la ventana de información
*/
function InfoPolyWindow (tituloPoly, author, tags, valor, tipo) {


    var html = "<div style=\"width: 450px; height: 100%; font-size: 16px;\">"
    + "<span style=\"font-size: 1.5em; font-weight: bold; color: #004696;\">" + tituloPoly + "</span><br />";

    if (tags != "null") { // Si existe algún tag
        html += "<span style=\"font-size: 0.7em;\">Etiquetas: " + processTags(tags, true) + "</span><br />";
    }

    html += "<br /><div style=\"font-size: 0.8em;\">";

    if (tipo == "R") {
        var distanciaKm = valor / 1000;
        html += "<span>Distancia: " + redondear(distanciaKm, 3) + " Km</span><br />";
    }
    else if (tipo == "P") {
        var areaKm2 = valor / 1000000;
        html += "<span>Área: " + redondear(areaKm2, 6) + " Km<sup>2</sup></span><br />";
    }

    html += "<div style=\"text-align: right;\">Creado por <span style=\"text-decoration: underline\">" + author + "</span></div>"
    + "</div></div>";

    return html;
}

function InfoPoiWindowE (titulo, html, tags, autor, created, expired) {
    var InfoPoi = "<div style=\"width: 39em; height: 100%; font-size: 16px;\">"
    + "<span style=\"font-size: 1.5em; font-weight: bold; color: #004696;\">" + titulo + "</span><br />";

    if (tags != "null") { // Si existe algún tag
        InfoPoi += "<span style=\"font-size: 0.7em;\">Etiquetas: " + processTags(tags, true) + "</span><br />";
    }

    if (html != "null") { // Si existe algún comentario
        InfoPoi += html + "<br />";
    }

    InfoPoi += "<div style=\"font-size: 0.8em; text-align: right;\">"
    + "Creado por <span style=\"text-decoration: underline\">" + autor + "</span>";

    if (created != "null" && created.length == 10) { // Si existe fecha de caducidad
        InfoPoi +=  "<br /><span>el " + formatDate(created) + "</span>";
    }

    if (expired != "null") { // Si existe fecha de caducidad
        // InfoPoi += "<br /><span>Fecha de caducidad: " + formatDate(expired) + "</span>";
    }

    InfoPoi += "</div></div>";

    return InfoPoi;
}

/**
* Función para crear los enlaces de los tags
*
* @param (tags) Etiquetas de los que queremos crear el enlace
* @return Los enlaces de los tags
*/
function processTags (tags, isLink) {
    var linkTags = "";
    
    if (tags != null & tags != "null") {
        var TagsSubstring = tags.substring(1, tags.length - 1);
        var allTags = TagsSubstring.split(",,");


        for (var i = 0; i < allTags.length; i++) {
            if (isLink) {
                linkTags += "<a href=\"javascript:void(0)\" onclick=\"showInfo('" + allTags[i] + "', 'tag')\" title=\"Tag " + allTags[i] + "\"><span style=\"color: #FF9900\">" + allTags[i] + "</span></a>";
            }
            else {
                linkTags += allTags[i];
            }

            if (i != allTags.length - 1) {
                linkTags += ", ";
                
                if(isLink) {
                    linkTags += "\n";
                }
            }
        }
    }

    return linkTags;
}


function formatDate (date) {
    var parts = date.split("-");
    var newDate = parts[2] + "-" + parts[1] + "-" + parts[0];

    return newDate
}

function redondear(cantidad, decimales) {
    var cantidad = parseFloat(cantidad);
    var decimales = parseFloat(decimales);
    decimales = (!decimales ? 2 : decimales);

    return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
}

/**
* Función que abre la ventana seleccionada de la marcador seleccionada en el side_bar
*
* @param (i) Contador
* @param (j) Contador
*/
function myclickroutes(i, j) {
    map.openInfoWindowHtml(groutes[i][j].getVertex(1),InfoPolyWindow(htmlsRoutes[i][j] [0], htmlsRoutes[i][j] [1], htmlsRoutes[i][j] [2], htmlsRoutes[i][j] [3], htmlsRoutes[i][j] [4]));
}

/**
* Función que abre la ventana seleccionada del polígono seleccionado en el side_bar
*
* @param (i) Contador
* @param (j) Contador
*/
function myclickpolygons(i, j) {
    map.openInfoWindowHtml(gpolygons[i][j].getVertex(1),InfoPolyWindow(htmlsPolygons[i][j] [0], htmlsPolygons[i][j] [1], htmlsPolygons[i][j] [2], htmlsPolygons[i][j] [3], htmlsPolygons[i][j] [4]));
}

/**
* Función que abre la ventana seleccionada del marcador seleccionado en el side_bar
*
* @param (i) Contador
* @param (j) Contador
*/
function myclickpois(i, j) {
    gmarkers[i][j][0].openInfoWindowHtml(InfoPoiWindow(htmlsPois[i][j] [0], htmlsPois[i][j] [1], htmlsPois[i][j] [2], htmlsPois[i][j] [3], htmlsPois[i][j] [4], htmlsPois[i][j] [5]));
}

function myclickpoisE(i, j) {
    var tabs = [];

    tabs.push(new GInfoWindowTab(htmlsPois[i][j] [7],InfoPoiWindowE(htmlsPois[i][j] [0], htmlsPois[i][j] [1], htmlsPois[i][j] [3], htmlsPois[i][j] [4], htmlsPois[i][j] [5], htmlsPois[i][j] [6])));
    tabs.push(new GInfoWindowTab(htmlsPois[i][j] [8],InfoPoiWindowE(htmlsPois[i][j] [0], htmlsPois[i][j] [2], htmlsPois[i][j] [3], htmlsPois[i][j] [4], htmlsPois[i][j] [5], htmlsPois[i][j] [6])));

    gmarkers[i][j][0].openInfoWindowTabsHtml(tabs);
}

/**
* Función que carga los controles para crear los mapas
*
* @param (region) Region para la que se crea el mapa
* @param (service) Servicio para el que se crea el mapa
* @param (lineEnable) Si permite añadir rutas o no
*/
function createMap(region, service, lineEnable) {
    if (mapActivated) {
        var continuePetition = deshabilitar();

        if(!continuePetition) {
            return;
        }
        else {
            mapActivated = false;
        }
    }
    
    // Se limpian todas las capas del mapa
    map.clearOverlays();
    // Se centra el mapa en la posición guardada
    map.returnToSavedPosition();

    // Borramos los comentarios y la puntuacion
    document.getElementById("filesAndRates").innerHTML = "";
    document.getElementById("comentarios").innerHTML = "";
    document.getElementById("MapInfoData").innerHTML = "";
    document.getElementById("ModifMap").innerHTML = "";
    
    if (timeout2 != null) {
        clearTimeout(timeout2);
        timeout2 = null;
    }
    mantener = false;
    bounds = null;

    //document.getElementById("loadData").innerHTML = "";
    document.getElementById("loadInfoMap").innerHTML = "";
    mapActivated = true;
    // Se eliminan los controles del mapa si los hubiese
    map.removeControl(EditorControl);
    map.removeControl(FormControl);
    map.removeControl(modificarBoton);
    map.removeControl(abandonarBoton);
    // Se crea el control de Edición
    startToolboxControl(lineEnable);
    EditorControl = new EditToolboxControl();
    // Se crea el formulario para enviar las rutas creadas
    startFormControl(region, service);
    FormControl = new FormMapControl();
    
    abandonarBoton = new buttonOutMod();
    // Se añaden los controles al mapa
    map.addControl(EditorControl);
    map.addControl(FormControl);
    map.addControl(abandonarBoton);
    // Se selecciona la "mano" en el control de Edición
    select("hand_b");
}

/**
* Función para seleccionar el botón del editor del mapa
*
* @param (buttonId) Botón seleccionado
*/
function select(buttonId) {
    // Se deseleccionan todos los botones
    document.getElementById("hand_b").className="unselected";
    if(document.getElementById("placemark_b")) {
        document.getElementById("placemark_b").className="unselected";
    }
    if(document.getElementById("line_b")) {
        document.getElementById("line_b").className="unselected";
    }
    if(document.getElementById("shape_b")) {
        document.getElementById("shape_b").className="unselected";
    }

    // Se selecciona el botón elegido
    document.getElementById(buttonId).className="selected";
}

/**
* Función que sólo permite arrastrar y/o editar las opciones del mapa,
* inhabilitando el crear marcadores, líneas y/o polígonos
*/
function stopEditing() {
    // Se seleciona el botón de arrastrar/editar el mapa
    select("hand_b");

    //== Se eliminan los escuchadores de "click" que estén activos ==//
    // Se evita que se cree un punto
    if (listener != null) { // Si existe el escuchador que crea un punto
        GEvent.removeListener(listener); // Se elimina el escuchador
        listener = null; // Se resetea la variable de escuchador

        // Se vuelven a activar los eventos de las líneas
        for (var i = 0; i < allLines.length; i++) {
            EditLine(allLines[i], "line");
        }
        // Se vuelven a activar los eventos de los polígonos
        for (var j = 0; j < allShapes.length; j++) {
            EditLine(allShapes[j], "polygon");
        }
    }

    // Se evita que se siga creando una forma (línea o polígono) que estaba en construcción (polyActivated = true)
    if (polyActivated == true) { // Si ya había una forma en construcción
        nowWritingPoly.disableEditing(); // Se deshabilita la edición de la forma en construcción
        map.removeOverlay(nowWritingPoly); // Se borra la forma antigua

        // Si se estaba expandiendo una línea
        if (oldLine != null) {
            map.addOverlay(oldLine); // Se añade al mapa la antigua línea
            EditLine(oldLine, "line"); // Se activan los escuchadores y las opciones de edición de la línea

            // Se busca la posición de la línea que estabamos modificando en el array "allLines"
            // y se sustituye por la línea antigua
            for(var n = 0; n < allLines.length; n++) {
                if(allLines[n] == actualPoly) {
                    allLines[n] = oldLine;
                    break;
                }
            }
        }

        // Se resetean las variables
        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        actualPoly = null; // Se resetea la variable que contiene a la forma seleccionada
        lineActivated = false; // La línea deja de estar en construcción
        shapeActivated = false; // El polígono deja de estar en construcción
        polyActivated = false; // La forma deja de estar en construcción

        // Se activan los escuchadores a los marcadores
        for (var i = 0; i < markers.length; i++) {
            markerListeners(markers[i]);
        }
    }
}

/**
* Función que crea un marcador
*
* @param (limited) Si está activado el limitador para crear marcadores
*/
function placeMarker(limited) {
    // Si está activado el limitador (sólo para crear zonas)
    if (limited == 1) {
        // Sólo se permite crear un único marcador
        if (markers.length == 1) {
            alert ("Sólo se permite dibujar un marcador para crear una zona.\nDesplace el marcador dibujado en el mapa para decidir el centro de la zona a crear.");
            return;
        }
    }

    // Se seleciona el botón de crear un marcador en el mapa
    select("placemark_b");

    //== Se eliminan los escuchadores de "click" que estén activos ==//
    // Se evita que se cree un punto
    if (listener != null) { // Si existe el escuchador que crea un punto
        GEvent.removeListener(listener); // Se elimina el escuchador
        listener = null; // Se resetea la variable de escuchador
    }

    // Se evita que se siga creando una forma (línea o polígono) que estaba en construcción (polyActivated = true)
    if (polyActivated == true) { // Si ya había una forma en construcción
        nowWritingPoly.disableEditing(); // Se deshabilita la edición de la forma
        map.removeOverlay(nowWritingPoly); // Se borra la forma antigua

        // Si se estaba expandiendo una línea
        if (oldLine != null) {
            map.addOverlay(oldLine); // Se añade al mapa la antigua línea
            EditLine(oldLine, "line"); // Se activan los escuchadores y las opciones de edición de la línea

            // Se busca la posición de la línea que estabamos modificando en el array "allLines"
            // y se sustituye por la línea antigua
            for(var n = 0; n < allLines.length; n++) {
                if(allLines[n] == actualPoly) {
                    allLines[n] = oldLine;
                    break;
                }
            }
        }

        // Se resetean las variables
        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        actualPoly = null; // Se resetea la variable que contiene a la forma seleccionada
        lineActivated = false; // La línea deja de estar en construcción
        shapeActivated = false; // El polígono deja de estar en construcción
        polyActivated = false; // La forma deja de estar en construcción
    }

    // Se eliminan todos los eventos de las líneas para que no haya problemas al insertar el marcador con el "click"
    for (var i = 0; i < allLines.length; i++) {
        GEvent.clearInstanceListeners(allLines[i]);
    }
    // Se eliminan todos los eventos de los poligonos para que no haya problemas al insertar el marcador con el "click"
    for (var j = 0; j < allShapes.length; j++) {
        GEvent.clearInstanceListeners(allShapes[j]);
    }

    //== Se dibuja el Marcador ==//
    // Se crea el escuchador de "click"
    listener = GEvent.addListener(map, "click", function(overlay, point) {
        if (point) {
            select("hand_b"); // Se seleciona el botón de arrastrar/editar el mapa
            GEvent.removeListener(listener); // Se elimina el escuchador
            listener = null; // Se resetea la variable de escuchador
            var marker = createMarker(point); // Se crea el marcador
            map.addOverlay(marker); // Se añade el marcador al mapa

            // Se vuelven a activar los eventos de las líneas
            for (var i = 0; i < allLines.length; i++) {
                EditLine(allLines[i], "line");
            }
            // Se vuelven a activar los eventos de los polígonos
            for (var j = 0; j < allShapes.length; j++) {
                EditLine(allShapes[j], "polygon");
            }
        }
    });
}

/**
* Función que crea una línea
*/
function startLine() {
    // Se seleciona el botón de crear/editar una línea
    select("line_b");

    //== Se eliminan los escuchadores de "click" que estén activos ==//
    // Se evita que se cree un punto
    if (listener != null) { // Si existe el escuchador que crea un punto
        GEvent.removeListener(listener); // Se elimina el escuchador
        listener = null; // Se resetea la variable de escuchador

        // Se vuelven a activar los eventos de las líneas
        for (var i = 0; i < allLines.length; i++) {
            EditLine(allLines[i], "line");
        }
        // Se vuelven a activar los eventos de los polígonos
        for (var j = 0; j < allShapes.length; j++) {
            EditLine(allShapes[j], "polygon");
        }
    }

    // Si ya había un polígono en construcción
    if (shapeActivated == true) {
        nowWritingPoly.disableEditing(); // Se deshabilita la edición del polígono
        map.removeOverlay(nowWritingPoly); // Se borra el polígono en construcción del mapa
        actualPoly = null; // Se resetea la variable que contiene a la forma seleccionada
        shapeActivated = false; // El polígono deja de estar en construcción
        nowWritingPoly = null; // Se resetea la variable que contiene a la forma que se está dibujando actualmente
    }

    // Se eliminan todos los eventos de los marcadores para que no haya problemas al insertar la línea con el "click"
    for (var i = 0; i < markers.length; i++) {
        GEvent.clearInstanceListeners(markers[i]);
    }

    var line; // Variable que crea la línea

    // Si ya había una línea en construcción
    if (lineActivated == true) {
        // Si se estaba expandiendo una línea (oldLine) y se ejecutó la función "startLine()"
        // de forma automática, sin hacer click en el botón de "Dibujar una línea"
        if (oldLine != null && clicked == false) {
            actualPoly.disableEditing(); // Se deshabilita la edición de la línea
            map.removeOverlay(actualPoly); // Se borra la línea antigua

            lineActivated = true; // La línea empieza a estar en construcción
            // Se crea línea con los parámetros de la línea antigua
            line = new GPolyline(vertexLine, oldLine.color, oldLine.weight, oldLine.opacity);
            startDrawing(line, "line"); // Se comienza a dibujar la línea
        }
    }
    else { // No había ninguna línea en construcción, se empieza a dibujar una;
        // Se resetean las variables
        nowWritingPoly = null; // Se resetea la variable que contiene a la forma que se está dibujando actualmente
        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        actualPoly = null; // Se resetea la variable que contiene a la forma seleccionada

        lineActivated = true; // La línea empieza a estar en construcción
        line = new GPolyline([], strokeColor, strokeWeight, strokeOpacity); // Se crea una nueva línea
        startDrawing(line, "line"); // Se comienza a dibujar la línea
    }
}

/**
* Función que crea un polígono
*/
function startShape() {
    // Se seleciona el botón de crear/editar un polígono
    select("shape_b");

    //== Se eliminan los escuchadores de "click" que estén activos ==//
    // Se existe el escuchador que crea un punto
    if (listener != null) {
        GEvent.removeListener(listener); // Se elimina el escuchador
        listener = null; // Se resetea la variable de escuchador

        // Se vuelven a activar los eventos de las líneas
        for (var i = 0; i < allLines.length; i++) {
            EditLine(allLines[i], "line");
        }
        // Se vuelven a activar los eventos de los polígonos
        for (var j = 0; j < allShapes.length; j++) {
            EditLine(allShapes[j], "polygon");
        }
    }

    // Si ya había una línea en construcción
    if (lineActivated == true) {
        nowWritingPoly.disableEditing(); // Se deshabilita la edición de la línea
        map.removeOverlay(nowWritingPoly); // Se borra la línea antigua

        // Si se estaba expandiendo una línea
        if (oldLine != null) {
            map.addOverlay(oldLine); // Se añade al mapa la antigua línea
            EditLine(oldLine, "line"); // Se activan los escuchadores y las opciones de edición de la línea

            // Se busca la posición de la línea que estabamos modificando en el array "allLines"
            // y se sustituye por la línea antigua
            for(var n = 0; n < allLines.length; n++) {
                if(allLines[n] == actualPoly) {
                    allLines[n] = oldLine;
                    break;
                }
            }
        }

        // Se resetean las variables
        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        lineActivated = false; // La línea deja de estar en construcción
    }

    // En caso de que no hubiera ningún polígono en construcción, se empieza a dibujar uno;
    // y en caso de que ya hubiera uno en construcción, no se hace nada (continúa la construcción)
    if (shapeActivated == false) {
        nowWritingPoly = null; // Se resetea la variable que contiene a la forma que se está dibujando actualmente
        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        actualPoly = null; // Se resetea la variable que contiene a la forma seleccionada

        // Se eliminan todos los eventos de los marcadores para que no haya problemas al insertar el polígono con el "click"
        for (var i = 0; i < markers.length; i++) {
            GEvent.clearInstanceListeners(markers[i]);
        }

        shapeActivated = true; // El polígono empieza estar en construcción
        // Se crea un nuevo polígono
        var polygon = new GPolygon([], strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity);
        startDrawing(polygon, "polygon"); // Se comienza a dibujar el polígono
    }
}

/**
* Función para crear los marcadores al crear el mapa
*
* @param (point) Punto (coordenadas) donde está ubicado el marcador
* @return El marcador
*/
function createMarker(point) {
    var icono = new GIcon (Icon);
    icono.image = "./img/map_icons/marker_blue-dot.png";

    // Se crea el marcador en la posición dada
    var marker = new GMarker(point, {icon: icono, draggable: true});
    // Se crea el titulo del marcador
    var title = "Título del Punto";
    // Se crea el html (contenido del globo)
    var html = "";
    // Se crean los tags del marcador
    var tags = "";

    // Se añaden los valores a los arrays
    markers.push(marker);
    points.push(point);
    titleMarker.push(title);
    htmls.push(html);
    tagsMarker.push(tags);

    // Se crean los escuchadores
    markerListeners(marker);

    return marker;
}

/**
* Función que añade los escuchadores y las opciones de edición del marcador
*
* @param (marker) El marcador
*/
function markerListeners(marker) {
    // Se habilita la posibilidad de arrastrar el marcador por el mapa
    marker.enableDragging();

    // Cuando se hace click sobre el marcador
    GEvent.addListener(marker, "click", function() {
        actualWindowOpen = marker;
        // Se crea el editor para añadir/editar comentarios
        var html = editComment();
        // Se abre una ventana con pestañas
        this.openInfoWindowTabs([new GInfoWindowTab("Editar",html), new GInfoWindowTab("Iconos",SelectIcon(this))]);
        //this.openInfoWindowTabsHtml([new GInfoWindowTab("Editar",html), new GInfoWindowTab("Coordenadas",("Lat: " + this.getLatLng().lat() +  "<br/>Lon: " + this.getLatLng().lng() + "<br/>Altitud:<br/> + srtm3 <iframe src='http://ws.geonames.org/srtm3?lat=" + this.getLatLng().lat() + "&lng=" + this.getLatLng().lng() + "' style='border:0 solid transparent;width:3.5em;height:2.1em;margin-top:-8px' align='top' scrolling='no'></iframe>m<br/><br/><br/> + gtopo30 <iframe src='http://ws.geonames.org/gtopo30?lat=" + this.getLatLng().lat() + "&lng=" + this.getLatLng().lng() + "' style='border:0 solid transparent;width:3.5m;height:2.1em;margin-top:-8px' align='top' scrolling='no'></iframe>m"))]);
    });
    // Cuando la ventana de información se ha abierto
    GEvent.addListener(marker, "infowindowopen", function() {
        // Se activa el editor TinyMCE
        tinyMCE.execCommand('mceAddControl', false, "MarkerTA");
    });
    // Cuando la ventana de información se ha cerrado
    GEvent.addListener(marker, "infowindowclose", function() {
        // Se desactiva el editor TinyMCE
        tinyMCE.execCommand('mceRemoveControl', false, "MarkerTA");
    });
    // Cuando se comienza a arrastrar el marcador
    GEvent.addListener(marker, "dragstart", function() {
        // Se cierra la ventana de información
        map.closeInfoWindow();
    });
    // Cuando se acaba de arrastrar el marcador
    GEvent.addListener(marker, "dragend", function() {
        actualToDrag = marker;
        // Se actualiza la posición del marcador
        updatePosition ();
    });
}


/**
* Función que dibuja el Textarea del globo del marcador
*
* @return El formulario y el textarea con su contenido
*/
function editComment() {
    // Se busca en el array "markers" el marcador a modificar el título y/o comentario
    for(var n = 0; n < markers.length; n++) {
        if(markers[n] == actualWindowOpen) {
            var title = titleMarker[n]; // El título del marcador
            var content = htmls[n]; // El contenido del marcador
            var tags = tagsMarker[n]; // Los tags del marcador
            break;
        }
    }

    // Se genera el formulario que aparecerá en la ventana
    var iwform = "<div style=\"width:450px;\"><form id=\"WYSIWYGform\" action=\"#\" method=\"post\" style=\"width:99%;height:280px\" onsubmit=\"saveData(this.titleMarker.value, tinyMCE.get('MarkerTA').getContent(), this.tagsMarker.value);return false;\"><div>"
    + "<label for=\"titleMarker\">Título: </label><input id=\"titleMarker\" name=\"titleMarker\" value=\"" + title + "\" />&nbsp;&nbsp;"
    + "<label for=\"tagsMarker\">Tags: </label><input id=\"tagsMarker\" name=\"tagsMarker\" value=\"" + tags + "\" /><br />"
    + "<div style=\"font-size:11px;font-style:italic;text-align:right; width:84%;\">Ej: Cedetel, Ayuntamiento, GIS</div><br />"
    + "<label for=\"MarkerTA\">Comentario: </label><br /><span style=\"font-size:14px;font-style:italic;text-align:center;\">Use el cuadro de texto para insertar el comentario.</span><br />"
    + "<textarea id=\"MarkerTA\" name=\"content\" cols=\"53\" rows=\"8\">" + content + "</textarea><br />"
    + "</div><div style=\"width:99%;\"><button type=\"submit\" style=\"float:left;\">Guardar</button><a href=\"javascript:void(0)\" onclick=\"return removeMarker();\" style=\"float:right;\">Borrar</a></div></form></div>";

    return iwform;
}

/**
* Función que actualiza el comentario del marcador
*
* @param (title) Título del marcador
* @param (details) Comentario del marcador
* @param (tags) Tags del marcador
*/
function saveData(title,details,tags) {
    // Se busca en el array "markers" el marcador a actualizar el título, tags y/o comentario
    for(var n = 0; n < markers.length; n++) {
        if(markers[n] == actualWindowOpen) {
            // Se sustituye en el array "titleMarker" el titulo del marcador por su título actual
            titleMarker[n] = title;
            // Se sustituye en el array "htmls" el comentario del marcador por su comentario actual
            htmls[n] = details;
            // Se sustituye en el array "tagsMarker" los tags del marcador por sus tags actuales
            tagsMarker[n] = tags;
            break;
        }
    }
    // Se cierra la ventana de información
    map.closeInfoWindow();
}

/**
* Función que actualiza la posición del marcador
*/
function updatePosition () {
    // Se busca en el array "markers" el marcador a actualizar
    for(var n = 0; n < markers.length; n++) {
        if(markers[n] == actualToDrag) {
            // Se sustituye en el array "points" la Latitud y la Longitud del marcador por su posición actual
            points[n] = markers[n].getLatLng();
            break;
        }
    }
}

/**
* Función que elimina el marcador
*
* @return false
*/
function removeMarker() {
    // Se pide una confirmación de la acción
    var deleteMarker = confirm("¿Desea borrar este marcador?");
    if (deleteMarker) { // Si existe la confirmación
        // Se busca en el array "markers" el marcador a eliminar
        for(var n = 0; n < markers.length; n++) {
            if(markers[n] == actualWindowOpen) {
                // Se borra el marcador del mapa
                map.removeOverlay(markers[n]);
                break;
            }
        }
        // Se borra el marcador de los arrays "markers", "points", "titleMarker", "htmls" y "tagsMarker"
        markers.splice(n, 1); points.splice(n, 1); htmls.splice(n, 1); titleMarker.splice(n, 1); tagsMarker.splice(n, 1);
    }

    return false;
}

/**
* Función que dibuja el polígono/línea
*
* @param (poly) Polígono/Línea seleccionado
* @param (type) Tipo de forma: Polígono ó Línea
*/
function startDrawing(poly, type) {
    // La forma empieza estar en construcción
    polyActivated = true;
    // Se añade la forma al mapa
    map.addOverlay(poly);
    // Se activa el construir la forma haciendo "click" en el mapa
    poly.enableDrawing(fromStartOption);
    // Se guarda la forma en construcción en la variable que contiene a la forma que se está dibujando actualmente
    nowWritingPoly = poly;

    // == Se añaden los escuchadores de eventos a las formas == //
    // Cuando se ha cancelado la construción de una forma (finalizar la forma sin el mínimo de vértices necesarios: 2 línea, 3 polígono)
    GEvent.addListener(poly, "cancelline", function() {
        nowWritingPoly.disableEditing(); // Se deshabilita la edición de la forma
        map.removeOverlay(nowWritingPoly); // Se borra la forma del mapa
        nowWritingPoly = null; // Se resetea la variable que contiene a la forma que se está dibujando actualmente
        polyActivated = false; // La forma deja de estar en construcción
        lineActivated = false; // La línea deja de estar en construcción
        shapeActivated = false; // El polígono deja de estar en construcción
        select("hand_b"); // Se seleciona el botón de arrastrar/editar el mapa

        // Se activan los escuchadores a los marcadores
        for (var i = 0; i < markers.length; i++) {
            markerListeners(markers[i]);
        }
    });
    // Cuando se ha finalizado de cosntruir la forma
    GEvent.addListener(poly, "endline", function(latlng) {
        // Se seleciona el botón de arrastrar/editar el mapa
        select("hand_b");

        if (type == "line") { // Si el tipo de forma es una línea
            // Se busca si la línea estaba ya en el array "allLines"
            var position = null; // Variable para guardar la posición
            for(var n = 0; n < allLines.length; n++) {
                // Si existe coincidencia
                if(allLines[n] == actualPoly) {
                    // Se guarda la posición de la línea en el array
                    position = n;
                    break;
                }
            }

            // Si el tipo de la variable posición es un número
            if (typeof position == "number") {
                // Se sustituye la posición "position" del array "allLines" por la forma actual
                allLines[position] = poly;
            }
            else { // En caso contrario
                allLines.push(poly); // Se añade la línea al array "allLines"
                titleLines.push("Título del Itinerario"); // Se añade el título de la línea al array "titleLines"
                tagsLines.push(""); // Se añaden los tags de la línea al array "tagsLines"
            }
        }
        else if (type == "polygon") { // Si el tipo de forma es un polígono
            allShapes.push(poly); // Se añade el polígono al array "allShapes"
            titleShapes.push("Título del Espacio"); // Se añade el título del polígono al array "titleShapes"
            tagsShapes.push(""); // Se añaden los tags del polígono al array "tagsShapes"
            stylestrokeShapes.push(new Array(strokeColor, strokeWeight, strokeOpacity));
        }

        oldLine = null; // Se resetea la variable que contiene a la antigua línea
        // Se establece que la expansión de la línea sea desde el final
        fromStartOption = {fromStart: false};
        // Se guarda la forma finalizada (en este caso se usa para que no de error
        // al abrir la ventana de información de manera automática al finalizar la forma)
        actualPoly = poly;
        actualPoly.redraw(true);
        // Se abre la ventana de información
        
        map.openInfoWindowHtml(latlng, PolyInfoWindow(poly, type));
        //toinit();
        //setTimeout("toinit()",1000); 
        
       /* GEvent.addListener(map, "infowindowopen", function() {
            // Se activa el editor TinyMCE
            //toinit();
        });*/

        //var opts = {onOpenFn:toinit()};
        // Se añaden los escuchadores y opciones de edición
        EditLine(poly, type);

        polyActivated = false; // La forma deja de estar en construcción
        lineActivated = false; // La línea deja de estar en construcción
        shapeActivated = false; // El polígono deja de estar en construcción

        // Se activan los escuchadores a los marcadores
        for (var i = 0; i < markers.length; i++) {
            markerListeners(markers[i]);
        }
    });
}

/**
* Función que añade los escuchadores y las opciones de edición del polígono/línea
*
* @param (poly) Polígono/Línea seleccionado
* @param (type) Tipo de forma: Polígono ó Línea
*/
function EditLine(poly, type) {
    // Se habilita la edición del polígono/línea cuando el ratón está sobre el polígono/línea
    poly.enableEditing({onEvent: "mouseover"});
    // Se deshabilita la edición del polígono/línea cuando el ratón no está sobre el polígono/línea
    poly.disableEditing({onEvent: "mouseout"});

    // Cuando se hace click sobre el polígono/línea
    GEvent.addListener(poly, "click", function(latlng, index) {
        actualPoly = poly; // Se guarda la forma seleccionada

        if (typeof index == "number") { // Si el click lo hace sobre un vértice
            map.closeInfoWindow(); // Cerramos la ventana de información (si estuviera abierta)
            poly.deleteVertex(index); // Borramos el vértice
        }
        else { // Si no lo hace sobre un vértice
            // Se abre la ventana de información
            
            map.openInfoWindowHtml(latlng, PolyInfoWindow(poly, type));
            //toinit();
            //setTimeout("toinit()",1000); 
           /* GEvent.addListener(map, "infowindowopen", function() {
                // Se activa el editor TinyMCE
                toinit();
            });*/
            //var opts = {onOpenFn:toinit()};
            /*
            ddcolorpicker.init({
                colorcontainer: ['ddcolorwidget', 'ddcolorpicker'], //id of widget DIV, id of inner color picker DIV
                displaymode: 'float', //'float' or 'inline'
                floatattributes: ['DD Color Picker Widget', 'width=390px,height=250px,resize=1,scrolling=1,center=1'], //'float' window attributes
                fields: ['field1:control1'] //[fieldAid[:optionalcontrolAid], fieldBid[:optionalcontrolBid], etc]
            });*/
        }
    });
}

/**
* Función que muestra la ventana de información para editar el polígono/línea
*
* @param (poly) Polígono/Línea seleccionado
* @param (type) Tipo de forma: Polígono ó Línea
* @return El contenido de la ventana de información
*/
function PolyInfoWindow (poly, type) {
    // Se definen las variables a utilizar
    // - color: Color del polígono/línea
    // - weight: Ancho del polígono/línea
    // - opacity: Opacidad del polígono/línea
    var color, weight, opacity, title, tags;

    if (type == "line") { // Se recogen los valores (para la línea)
        color = poly.color;//strokeColor;
        weight = poly.weight//strokeWeight;
        opacity = poly.opacity*100//strokeOpacity;

        // Se busca en el array "allLines" la línea seleccionada
        for(var n = 0; n < allLines.length; n++) {
            if(allLines[n] == actualPoly) {
                title = titleLines[n]; // Se recoge el título de la línea
                tags = tagsLines[n]; // Se recogen los tags de la línea
                break;
            }
        }
    }
    else if (type == "polygon") { // Se recogen los valores (para el polígono)
        // Se busca en el array "allShapes" el polígono seleccionado
        for(var n = 0; n < allShapes.length; n++) {
            if(allShapes[n] == actualPoly) {
                title = titleShapes[n]; // Se recoge el título del polígono
                tags = tagsShapes[n]; // Se recogen los tags del polígono
                color = stylestrokeShapes[n] [0];
                weight = stylestrokeShapes[n] [1];
                opacity = stylestrokeShapes[n] [2]*100;
                break;
            }
        }
    }


    // Se crea el que aparecerá en la ventana de información
    // y que permitirá editar el polígono/línea
    var html = "<div style=\"width:405px;\"><form id=\"formPoly\" action=\"#\" onsubmit=\"UpdateStylePoly(this); return false;\"><div>"
    + "<label for=\"title\">Título: </label><input id=\"title\" name=\"title\" value=\"" + title + "\" />&nbsp;&nbsp;"
    + "<label for=\"tags\">Tags: </label><input id=\"tags\" name=\"tags\" value=\"" + tags + "\" /><br />"
    + "<div style=\"font-size:11px;font-style:italic;text-align:right; width:93%;\">Ej: Cedetel, Ayuntamiento, GIS</div><br />"
    + "<table border=\"0\" style=\"margin:0 auto;\"><tbody>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySC\">Color línea:</label></td><td><input id=\"displaySC\" name=\"displaySC\" value=\"" + color + "\" /></td></tr>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySW\">Ancho línea:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
    + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderSW\" onmousedown=\"slide(event, 'horizontal', 100, 2, 10, 9, 0, 'displaySW');\" style=\"left: " + (weight-2)*12.5 + "px;\">&nbsp;</div></div>"
    + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displaySW\" type=\"text\" value=\"" + weight + "\" onfocus=\"blur(this);\" /></div>"
    + "</div></td></tr>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySO\">Opacidad línea:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
    + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderSO\" onmousedown=\"slide(event, 'horizontal', 100, 0, 100, 101, 0, 'displaySO');\" style=\"left: " + opacity + "px;\">&nbsp;</div></div>"
    + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displaySO\" type=\"text\" value=\"" + opacity + "\" onfocus=\"blur(this);\" /></div>"
    + "</div></td></tr>";
    if (type == "polygon") {
        html += "<tr><td style=\"text-align: left;\"><label for=\"displayFC\">Color relleno:</label></td><td><input id=\"displayFC\" name=\"displayFC\" value=\"" + poly.color + "\" /></td></tr>"
        + "<tr><td style=\"text-align: left;\"><label for=\"displayFO\">Opacidad relleno:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
        + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderFO\" onmousedown=\"slide(event, 'horizontal', 100, 0, 100, 101, 0, 'displayFO');\" style=\"left: " + poly.opacity*100 + "px;\">&nbsp;</div></div>"
        + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displayFO\" type=\"text\" value=\"" + poly.opacity*100 + "\" onfocus=\"blur(this);\" /></div>"
        + "</div></td></tr>";
    }
    html += "</tbody></table>"
    + "<br /></div><div style=\"width:99%;\"><button type=\"submit\" style=\"float:left;\">Guardar Cambios</button><a href=\"javascript:void(0)\" onclick=\"return removePoly();\" style=\"float:right;\">Borrar</a></div></form></div>";
    /* if (type == "line") {
    html += "<a href=\"javascript:void(0)\" onclick=\"return ExtendLine(false);\">Editar Final</a><br />"
    + "<a href=\"javascript:void(0)\" onclick=\"return ExtendLine(true);\">Editar Principio</a>";
    } */
//html += "<div class=\"pickerdiv\">Rectangle control, preview on: <input type=\"text\" id=\"field1\" size=\"20\" value=\"#D85970\" /> <span id=\"control1\" class=\"colorpreview\">&nbsp;</span></div>";
    return html;
}

/**
* Función que permite extender una línea finalizada
*
* @param (value) Si la línea se extiende desde el pricipio (true) o desde el final (false)
*/
function ExtendLine(value) {
    vertexLine = []; // Se resetea la variable que almacena los puntos

    // Se cuentan los vértices de la línea seleccionada y se añaden a la variable que almacena los puntos
    for (var index=0; index<actualPoly.getVertexCount(); index++) {
        vertexLine.push(actualPoly.getVertex(index));
    }

    // Se crea una línea idéntica a la línea seleccionada. Se usará para reestablecer la línea
    // en caso de que el usuario cancele la extensión de la línea
    oldLine = new GPolyline(vertexLine, actualPoly.color, actualPoly.weight, actualPoly.opacity);

    map.closeInfoWindow(); // Se cierra la ventana de información
    polyActivated = true; // La forma empieza a estar en construcción
    lineActivated = true; // La línea empieza a estar en construcción
    clicked = false; // No se hizo click en el botón de "Crear un línea"

    fromStartOption = {fromStart: value}; // Se establece desde dónde se extiende la línea
    startLine(); // Se ejecuta la función de crear una línea
}

function ChangeStyle() {
    //SC = document.getElementById('displaySC').value;
    //SW = document.getElementById('displaySW').value;
    //SO = document.getElementById('displaySO').value;
    //FC = document.getElementById('displayFC').value;
    //FO = document.getElementById('displayFO').value;

    if (actualPoly.fill == true) { // Si la forma seleccionada tiene relleno (es un polígono)
        // Se busca en el array "allShapes" el polígono a actualizar
        for(var n = 0; n < allShapes.length; n++) {
            if(allShapes[n] == actualPoly) {
                stylestrokeShapes[n] [0] = document.getElementById('displaySC').value; // Se actualiza el color del borde del polígono
                stylestrokeShapes[n] [1] = document.getElementById('displaySW').value; // Se actualiza el ancho del borde del polígono
                stylestrokeShapes[n] [2] = document.getElementById('displaySO').value/100; // Se actualiza la opacidad del borde del polígono
                break;
            }
        }

        actualPoly.setFillStyle({color: document.getElementById('displayFC').value, opacity: document.getElementById('displayFO').value/100});
    }

    actualPoly.setStrokeStyle({color: document.getElementById('displaySC').value, weight: document.getElementById('displaySW').value, opacity: document.getElementById('displaySO').value/100});
}


/**
* Función que graba el nuevo estilo del polígono/línea
*
* @param (form) Formulario que contiene las variables de estilo
*/
function UpdateStylePoly(form) {
    // Se recoge el titulo y los tags del formulario
    // title = form.title.value
    // tags = form.tags.value

    if (actualPoly.fill == true) { // Si la forma seleccionada tiene relleno (es un polígono)
        // Se busca en el array "allShapes" el polígono a actualizar
        for(var n = 0; n < allShapes.length; n++) {
            if(allShapes[n] == actualPoly) {
                titleShapes[n] = form.title.value; // Se actualiza el título del polígono
                tagsShapes[n] = form.tags.value; // Se actualizan los tags del polígono

                // A quitar cuando funcione el color-picker
                stylestrokeShapes[n] [0] = form.displaySC.value; // Se actualiza el color del borde del polígono
                break;
            }
        }
        // A quitar cuando funcione el color-picker
        actualPoly.setFillStyle({color: form.displayFC.value});
    }
    else { // Si la forma seleccionada no tiene relleno (es una línea)
        // Se busca en el array "allLines" la línea a actualizar
        for(var n = 0; n < allLines.length; n++) {
            if(allLines[n] == actualPoly) {
                titleLines[n] = form.title.value; // Se actualiza el título de la línea
                tagsLines[n] = form.tags.value; // Se actualizan los tags de la línea
                break;
            }
        }
    }
    // A quitar cuando funcione el color-picker
    actualPoly.setStrokeStyle({color: form.displaySC.value});
    // Se cierra la ventana de información
    map.closeInfoWindow();
}

/**
* Función que elimina el Polígono/Línea
*
* @return false
*/
function removePoly() {
    // Se pide una confirmación de la acción
    var deletePoly = confirm("¿Desea borrar esta figura?");
    if (deletePoly) { // Si existe la confirmación
        map.closeInfoWindow(); // Se cierra la ventana de información

        if (actualPoly.fill == true) { // Si la forma seleccionada tiene relleno (es un polígono)
            // Se busca en el array "allShapes" el polígono a eliminar
            for(var n = 0; n < allShapes.length; n++) {
                if(allShapes[n] == actualPoly) {
                    // Se borra el polígono del mapa
                    map.removeOverlay(allShapes[n]);
                    break;
                }
            }
            // Se borra el polígono de los arrays "allShapes", "titleShapes", "tagsShapes" y "stylestrokeShapes"
            allShapes.splice(n, 1); titleShapes.splice(n, 1); tagsShapes.splice(n, 1); stylestrokeShapes.splice(n, 1);
        }
        else { // Si la forma seleccionada no tiene relleno (es una línea)
            // Se busca en el array "allLines" la línea a eliminar
            for(var n = 0; n < allLines.length; n++) {
                if(allLines[n] == actualPoly) {
                    // Se borra la línea del mapa
                    map.removeOverlay(allLines[n]);
                    break;
                }
            }
            // Se borra la línea de los arrays "allLines", "titleLines" y "tagsLines"
            allLines.splice(n, 1); titleLines.splice(n, 1); tagsLines.splice(n, 1);
        }

        actualPoly = null; // Se resetea la variable de la forma seleccionada
    }

    return false;
}

/**
* Función que solicita la confirmación de subir el mapa a la bbdd
*
* @return false
*/
function confirmSend() {
    // Si no ha dibujado nada en el mapa, se muestra un mensaje de error.
    if (points.length == 0 && allLines.length == 0 && allShapes.length == 0) {
        alert("No ha dibujado nada en el mapa.\nDibuje alguna ruta, algún punto de interés o algún área para poder guardar el mapa.");
        return false;
    }

    // Si no ha puesto título a la agrupación, se muestra un mensaje de error.
    if ((allLines.length != 0 || allShapes.length != 0 || points.length != 0) && document.getElementById("TitleGroup").value == "") {
        alert("El mapa no tiene título.\nPonga algún título al mapa para poder guardarlo.");
        return false;
    }

    // Advertencia de que si introduce puntos sin un título, se guardarán individualmente
   /* if((allLines.length == 0 && allShapes.length == 0 && points.length != 0) && document.getElementById("TitleGroup").value == "") {
        alert("Si guarda los puntos sin ningún título, estos se guardarán individualmente.\nSi desea que se guarden de forma conjunta, añada un título.");
    }*/

    // Se pide una confirmación de la acción
    var send = confirm("¿Desea guardar el mapa?");
    if (send) { // Si existe la confirmación
        GuardarMapas(); // Se sube la ruta
    }

    return false;
}

/**
* Función que solicita la confirmación de limpiar el mapa
*
* @return false
*/
function confirmReset() {
    // Se pide una confirmación de la acción
    var cancel = confirm("¿Desea borrar el contenido del mapa?");
    if (cancel) { // Si existe la confirmación
        ClearMap(); // Se limpia el mapa
    }

    return false;
}

/**
* Función que crea la url con todos los datos del mapa
*/
function GuardarMapas() {
    // ===== Variables para enviar el formulario =====
    var puntos = null; // Los marcadores
    var lineas = null; // Las líneas
    var poligonos = null; // Los polígonos

    // Si existe algún marcador
    if (points.length > 0) {
        // Se añaden las coordenadas de los marcadores y un separador
        puntos = points + "IWs-sEB";
        // Se añaden los títulos de los marcadores
        for (var i=0; i<titleMarker.length;i++) {
            puntos += titleMarker[i] + "IWt-tEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los comentarios de los marcadores
        for (var i=0; i<htmls.length;i++) {
            puntos += htmls[i].replace(/&/g, '%26') + "IWc-cEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los tags de los marcadores
        for (var i=0; i<tagsMarker.length;i++) {
            puntos += tagsMarker[i] + "IWc-cEB";
        }
        // Se añaden los iconos
        puntos += "IWs-sEB";
        for (var i=0; i<markers.length;i++) {
            puntos += markers[i].getIcon().image + "IWi-iEB";
        }
    }

    // Si existe alguna línea
    if (allLines.length > 0) {
        // Se inicializa la variable
        lineas = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < allLines.length; n++) {
            // Se recoge la línea
            // Se añaden los vértices de la línea
            for (var index=0; index < allLines[n].getVertexCount(); index++) {
                lineas += allLines[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != allLines[n].getVertexCount() - 1) {
                    lineas += ",";
                }
            }
            // Se añaden el resto de las características
            lineas += "IWp-cEB" + titleLines[n] + "IWc-cEB" + allLines[n].color + "IWc-cEB" + allLines[n].weight + "IWc-cEB" + allLines[n].opacity + "IWc-cEB" + tagsLines[n] + "IWl-lEB";
        }
    }

    // Si existe algún polígono
    if (allShapes.length > 0) {
        // Se inicializa la variable
        poligonos = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < allShapes.length; n++) {
            // Se recoge el polígono
            // Se añaden los vértices del polígono
            for (var index=0; index < allShapes[n].getVertexCount(); index++) {
                poligonos += allShapes[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != allShapes[n].getVertexCount() - 1) {
                    poligonos += ",";
                }
            }

            // Se añaden el resto de las características
            poligonos += "IWp-cEB" + titleShapes[n] + "IWc-cEB" + stylestrokeShapes[n] [0] + "IWc-cEB" + stylestrokeShapes[n] [1] + "IWc-cEB" + stylestrokeShapes[n] [2] + "IWc-cEB" + allShapes[n].color + "IWc-cEB" + allShapes[n].opacity + "IWc-cEB" + tagsShapes[n] + "IWp-pEB";
        }
    }

    // Se escribe la URL a la que se envía la petición de guardar el mapa
    var url = "action=writeMapInfo&zoneID=" + document.getElementById("Zone").value + "&serviceID=" + document.getElementById("Service").value + "&TitleGroup=" + document.getElementById("TitleGroup").value + "&TagsGroup=" + document.getElementById("TagsGroup").value;

    // Si existe algún marcador
    if(puntos != null) {
        // Se añade la variable (codificada) a la URL
        url += "&puntos=" + puntos;
    }
    // Si existe alguna línea
    if (lineas != null) {
        // Se añade la variable (codificada) a la URL
        url += "&lineas=" + lineas;
    } //alert();
    // Si existe algún polígono
    if (poligonos != null) {
        // Se añade la variable (codificada) a la URL
        url += "&poligonos=" + poligonos;
    }

    loadIbox();
    // Se ejecuta la función AJAX que guarda el mapa
    AjaxUploadtoServer("MapBrain", url,"infoIbox");//, "loadInfoMap"
}

/**
* Función que inhabilita la opción de crear mapas
*/
function deshabilitar() {
    if (mapActivated) {
        var exit = confirm("¿Desea salir sin guardar antes el mapa?");
        if (exit) { // Si existe la confirmación
            // Se limpia el mapa y se resetean las variables
            resetMap();
            // Se elimina el menú de editar del mapa
            map.removeControl(EditorControl);
            // Se elimina el formulario de envio del mapa
            map.removeControl(FormControl);
            map.removeControl(modificarBoton);
            map.removeControl(abandonarBoton);
            EditorControl = null;
            FormControl = null;
            modificarBoton = null;
            abandonar = null;
            return true;
        }
        else {
            return false;
        }
    }
}

/**
* Función que limpia el mapa
*/
function ClearMap() {
    resetMap();
    // Se elimina el formulario del mapa, se vuelve a generar el formulario
    // (para resetear los posibles valores modificados) y se añade al mapa
    map.removeControl(FormControl);
    FormControl = new FormMapControl();
    map.addControl(FormControl);
}


/**
* Función que resetea todas las variables del mapa
*/
function resetMap() {
    // Se cierra la ventana de información
    map.closeInfoWindow();
    // Se limpian todas las capas del mapa
    map.clearOverlays();
    // Se centra el mapa en la posición guardada
    map.returnToSavedPosition();

    // Se resetean las variables de los marcadores
    resetMarkers();
    // Se resetean las variables de las líneas
    resetLines();
    // Se resetean las variables de los polígonos
    resetShapes();
    // Se resetean el resto de variables
    side_bar_pois = "";
    gmarkers = [];
    htmlsPois = [];
    side_bar_routes = "";
    groutes = [];
    htmlsRoutes = [];
    side_bar_polygons = "";
    gpolygons = [];
    htmlsPolygons = [];

    // Se seleciona el botón de arrastrar/editar el mapa
    select("hand_b");
}

/**
* Función que resetea las variables de los marcadores
*/
function resetMarkers() {
    // ===== Variables para las marcadores =====
    if (listener != null) {
        GEvent.removeListener(listener);
    }

    listener = null;
    markers = [];
    points = [];
    titleMarker = [];
    htmls = [];
    tagsMarker = [];
    //   icons = [];
}

/**
* Función que resetea las variables de las líneas
*/
function resetLines() {
    if(actualPoly != null) {
        actualPoly.disableEditing();
    }
    if (nowWritingPoly != null){
        nowWritingPoly.disableEditing();
    }
    if (oldLine != null){
        oldLine.disableEditing();
    }

    actualPoly = null;
    nowWritingPoly = null;
    oldLine = null;
    polyActivated = false;
    lineActivated = false;
    fromStartOption = {fromStart: false};
    clicked = false;
    allLines = []; // Guardar las líneas
    titleLines = []; // Títulos de las líneas
    tagsLines = []; // Tags de las líneas
    vertexLine = [];
}

/**
* Función que resetea las variables de los polígonos
*/
function resetShapes() {
    if(actualPoly != null) {
        actualPoly.disableEditing();
    }
    if (nowWritingPoly != null){
        nowWritingPoly.disableEditing();
    }

    actualPoly = null;
    nowWritingPoly = null;
    polyActivated = false;
    shapeActivated = false;
    allShapes = [];
    titleShapes = [];
    tagsShapes = [];
    stylestrokeShapes = [];
}

startToolboxControl=function(lineEnable) {
    // We define the function first
    EditToolboxControl = function() {}

    // To "subclass" the GControl, we set the prototype object to
    // an instance of the GControl object
    EditToolboxControl.prototype = new GControl();

    // Creates a one DIV for each of the buttons and places them in a container
    // DIV which is returned as our control element. We add the control to
    // to the map container and return the element for the map class to
    // position properly.
    EditToolboxControl.prototype.initialize = function(map) {
        // Se crea el contenedor
        var container = document.createElement("div");
        container.className = "EditMenu"; // El nombre de la clase del contenedor

        // Se crean la tabla que contiene los botones y sus elementos
        var ButtonTable = document.createElement("table"); // La tabla
        ButtonTable.className = "buttons"; // El nombre de la clase de la tabla
        var tbody = document.createElement("tbody"); // El cuerpo de la tabla
        var tr = document.createElement("tr"); // La fila
        var td1 = document.createElement("td"); // Celda 1
        var td2 = document.createElement("td"); // Celda 2

        // Se crean los botones y sus acciones
        // Botón de Seleccionar el mapa
        var buttonHand = document.createElement("div");
        buttonHand.id = "hand_b";
        buttonHand.title = "Seleccionar/Editar características del mapa";
        buttonHand.style.cursor = "pointer";
        GEvent.addDomListener(buttonHand, "click", function() {
            stopEditing();
        });
        // Botón de Crear un marcador
        var buttonMarker = document.createElement("div");
        buttonMarker.id = "placemark_b";
        buttonMarker.title = "Añadir un marcador de posición";
        buttonMarker.style.cursor = "pointer";
        GEvent.addDomListener(buttonMarker, "click", function() {
            placeMarker(0);
        });

        // Se añaden lols hijos a los padres
        td1.appendChild(buttonHand);
        td2.appendChild(buttonMarker);
        tr.appendChild(td1);
        tr.appendChild(td2);

        if (lineEnable == 1) { // Si permite rutas
            var td3 = document.createElement("td"); // Celda 3
            var td4 = document.createElement("td"); // Celda 3
            // Botón de Crear una linea
            var buttonLine = document.createElement("div");
            buttonLine.id = "line_b";
            buttonLine.title = "Dibujar una línea";
            buttonLine.style.cursor = "pointer";
            GEvent.addDomListener(buttonLine, "click", function() {
                clicked = true;
                startLine();
            });
            // Botón de Crear un polígono
            var buttonShape = document.createElement("div");
            buttonShape.id = "shape_b";
            buttonShape.title = "Dibujar una forma";
            buttonShape.style.cursor = "pointer";
            GEvent.addDomListener(buttonShape, "click", function() {
                startShape();
            });
            // Se añaden lols hijos a los padres
            td3.appendChild(buttonLine);
            td4.appendChild(buttonShape);
            tr.appendChild(td3);
            tr.appendChild(td4);
        }

        tbody.appendChild(tr);
        ButtonTable.appendChild(tbody);
        container.appendChild(ButtonTable);

        map.getContainer().appendChild(container);
        return container;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    EditToolboxControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 7)); //75 de izda, 7 top
    }
};

startFormControl = function(region, service) {
    FormMapControl = function() {}

    FormMapControl.prototype = new GControl();

    FormMapControl.prototype.initialize = function(map) {
        // Se crea el contenedor
        var container = document.createElement("div");
        container.className = "FormMenu"; // El nombre de la clase del contenedor

        // Se crean el formulario para enviar los datos
        var formMap = document.createElement("form");
        formMap.id = "frm"; // El id del formulario
        formMap.method = "post"; // Forma de envio
        formMap.action = "#"; // Action del formulario
        formMap.onsubmit = confirmSend; // El onsubmit
        formMap.acceptCharset = "UTF-8"; // La codificación del formulario
        formMap.style.backgroundColor = "transparent";
        formMap.style.backgroundImage = "url(img/formulario_mapa.png)";
        formMap.style.backgroundRepeat = "no-repeat";

        var div = document.createElement("div");
        div.className = "divMap";

        var inputZone = document.createElement("input");
        inputZone.id = "Zone";
        inputZone.name = "Zone";
        inputZone.type = "hidden";
        inputZone.value = region;

        var inputService = document.createElement("input");
        inputService.id = "Service";
        inputService.name = "Service";
        inputService.type = "hidden";
        inputService.value = service;

        var labelTitle = document.createElement("label");
        labelTitle.htmlFor = "TitleGroup";
        labelTitle.innerHTML = "Título ";

        var inputTitle = document.createElement("input");
        inputTitle.className = "inputMap";
        inputTitle.id = "TitleGroup";
        inputTitle.name = "TitleGroup";
        inputTitle.type = "text";
        inputTitle.maxLength = "19";

        var labelTags = document.createElement("label");
        labelTags.htmlFor = "TagsGroup";
        labelTags.innerHTML = "Tags ";

        var inputTags = document.createElement("input");
        inputTags.className = "inputMap";
        inputTags.id = "TagsGroup";
        inputTags.name = "TagsGroup";
        inputTags.type = "text";
        //inputTags.size = "15";


        var table = document.createElement("table"); // La tabla
        var tbody = document.createElement("tbody"); // El cuerpo de la tabla
        var tr = document.createElement("tr"); // La fila
        var td1 = document.createElement("td"); // Celda 1
        var td2 = document.createElement("td"); // Celda 2

        var SubmitMap = document.createElement("div");
        SubmitMap.id = "SendMap";
        SubmitMap.className = "buttonForm";
        SubmitMap.innerHTML = "<img src=\"img/enviar_form.png\" alt=\"Enviar\" />";
        SubmitMap.title = "Guardar el contenido del Mapa"
        SubmitMap.style.cursor = "pointer";
        GEvent.addDomListener(SubmitMap, "click", function() {
            confirmSend();
        });

        var ResetMap = document.createElement("div");
        ResetMap.id = "ResetMap";
        ResetMap.className = "buttonForm";
        ResetMap.innerHTML = "<img src=\"img/borrar_form.png\" alt=\"Borrar\" />";
        ResetMap.title = "Borrar el contenido del Mapa"
        ResetMap.style.cursor = "pointer";
        GEvent.addDomListener(ResetMap, "click", function() {
            confirmReset();
        });

        td1.appendChild(SubmitMap);
        td2.appendChild(ResetMap);
        tr.appendChild(td1);
        tr.appendChild(td2);
        tbody.appendChild(tr);
        table.appendChild(tbody);

        div.appendChild(inputZone);
        div.appendChild(inputService);
        //formMap.appendChild(labelTitle);
        div.appendChild(inputTitle);
        div.appendChild(document.createElement("br"));
        //formMap.appendChild(labelTags);
        div.appendChild(inputTags);

        formMap.appendChild(div);
        formMap.appendChild(table);
        container.appendChild(formMap);

        map.getContainer().appendChild(container);
        return container;
    }

    FormMapControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 45)); //210 de izda, 7 top
    }

};

// Sets the proper CSS for the given button element.
/*EditToolboxControl.prototype.setButtonStyle_ = function(button) {
button.style.textDecoration = "underline";
button.style.color = "#0000cc";
button.style.backgroundColor = "white";
button.style.font = "small Arial";
button.style.border = "1px solid black";
button.style.padding = "2px";
button.style.marginBottom = "3px";
button.style.textAlign = "center";
button.style.width = "6em";
button.style.cursor = "pointer";
}*/

//map.addControl(new EditToolboxControl());

// Ponemos el cursor con la forma de la mano, lo que permite que si se ha cancelado la creación
// de una línea, el cursor no quede con forma de "cruz"
// map.getDragObject().setDraggableCursor("url(http://maps.google.com/intl/es_ALL/mapfiles/openhand.cur), default");


/**
* Función que crea y carga el mapa de las zonas
*/
function loadMapNewZone() {
    // ===== Si el Navegador es compatible =====
    if (GBrowserIsCompatible()) {
        // Se crea el mapa de Google
        map = new GMap2(document.getElementById("map"));
        // +++++ Se añaden los controles al mapa +++++
        // Control con flechas para mover el mapa, barra de zoom...
        map.addControl(new GLargeMapControl());
        // Tipos de Mapa (el tipo "Híbrido" aparece como un hijo del de "Satélite")
        map.addControl(new GHierarchicalMapTypeControl());
        // Añade el Tipo de Mapa "Relieve"
        map.addMapType(G_PHYSICAL_MAP);
        // Escala del mapa
        map.addControl(new GScaleControl());
        // Estabelecer el Centro y zoom inicial del mapa
        map.setCenter(new GLatLng(40.4166,-3.7039), 5);
        map.savePosition();
        // Se permite hacer zoom con la rueda del ratón
        map.enableScrollWheelZoom();
        // El zoom se realiza de forma contiunada
        map.enableContinuousZoom();
        // Se oculta el "overflow" de la flechas rojas cuando se hace zoom cerca del borde del mapa
        map.getContainer().style.overflow = "hidden";

        // Se crea el Editor del mapa
        // Se crea el control de Edición
        ZoneToolboxControl();
        ZoneEditorControl = new ZoneEditToolboxControl();
        // Se añade el control al mapa
        map.addControl(ZoneEditorControl);
        // Se selecciona la "mano" en el control de Edición
        select("hand_b");
        // Poner el logotipo de CEDETEL en el fondo mientras se carga el mapa
        document.getElementById("map").style.background = "#C8C5C5 center no-repeat url(img/carga_mapa_cedetel.jpg)";
        
        map.addControl(new buttonSizeMap(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
    }
    // ===== Mostrar una advertencia si el Navegador no es compatible =====
    else {
        alert("Lo sentimos. El API de Google Maps no es compatible con este Navegador.");
    }
}

ZoneToolboxControl=function() {
    // We define the function first
    ZoneEditToolboxControl = function() {}

    // To "subclass" the GControl, we set the prototype object to
    // an instance of the GControl object
    ZoneEditToolboxControl.prototype = new GControl();

    // Creates a one DIV for each of the buttons and places them in a container
    // DIV which is returned as our control element. We add the control to
    // to the map container and return the element for the map class to
    // position properly.
    ZoneEditToolboxControl.prototype.initialize = function(map) {
        // Se crea el contenedor
        var container = document.createElement("div");
        container.className = "EditMenu"; // El nombre de la clase del contenedor

        // Se crean la tabla que contiene los botones y sus elementos
        var ButtonTable = document.createElement("table"); // La tabla
        ButtonTable.className = "buttons"; // El nombre de la clase de la tabla
        var tbody = document.createElement("tbody"); // El cuerpo de la tabla
        var tr = document.createElement("tr"); // La fila
        var td1 = document.createElement("td"); // Celda 1
        var td2 = document.createElement("td"); // Celda 2
        var td3 = document.createElement("td"); // Celda 3

        // Se crean los botones y sus acciones
        // Botón de Seleccionar el mapa
        var buttonHand = document.createElement("div");
        buttonHand.id = "hand_b";
        buttonHand.title = "Seleccionar/Editar características del mapa";
        buttonHand.style.cursor = "pointer";
        GEvent.addDomListener(buttonHand, "click", function() {
            stopEditing();
        });
        // Botón de Crear un marcador
        var buttonMarker = document.createElement("div");
        buttonMarker.id = "placemark_b";
        buttonMarker.title = "Añadir un marcador de posición";
        buttonMarker.style.cursor = "pointer";
        GEvent.addDomListener(buttonMarker, "click", function() {
            placeMarker(1);
        });
        // Botón de Crear un polígono
        var buttonShape = document.createElement("div");
        buttonShape.id = "shape_b";
        buttonShape.title = "Dibujar una forma";
        buttonShape.style.cursor = "pointer";
        GEvent.addDomListener(buttonShape, "click", function() {
            startShape();
        });
        // Se añaden lols hijos a los padres
        td1.appendChild(buttonHand);
        td2.appendChild(buttonMarker);
        td3.appendChild(buttonShape);
        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbody.appendChild(tr);
        ButtonTable.appendChild(tbody);
        container.appendChild(ButtonTable);

        map.getContainer().appendChild(container);
        return container;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    ZoneEditToolboxControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 7)); //75 de izda, 7 top
    }
};

function confirmSendZone() {
    // Si no ha dibujado nada en el mapa, se muestra un mensaje de error.
    if (points.length == 0 && allShapes.length == 0) {
        alert("No ha dibujado nada en el mapa.\nDibuje algún área y el marcador que establece el centro para poder guardar el mapa.");
        return false;
    }
    // Si no ha dibujado el marcador en el mapa, se muestra un mensaje de error.
    if (points.length == 0) {
        alert("No ha dibujado el marcador en el mapa.\nDibuje el marcador que establece el centro para poder guardar el mapa.");
        return false;
    }
    // Si no ha dibujado alguna área en el mapa, se muestra un mensaje de error.
    if (allShapes.length == 0) {
        alert("No ha dibujado ninguna área en el mapa.\nDibuje algún área para poder guardar el mapa.");
        return false;
    }

    // Si no ha puesto título a la zona, se muestra un mensaje de error.
    if (document.getElementById("frm").ZoneName.value == "") {
        alert("La zona no tiene título.\nPonga algún título a la zona para poder guardar el mapa.");
        document.getElementById("frm").ZoneName.focus();
        return false;
    }
    // Se pide una confirmación de la acción
    var send = confirm("¿Desea crear esta zona?");
    if (send) { // Si existe la confirmación
        crearZone(); // Se sube la zona
    }

    return false;
}

function crearZone() {
    // ===== Variables para enviar el formulario =====
    var puntos = null; // Los marcadores
    var poligonos = null; // Los polígonos
    // Variable que guardará las coordenadas de los polígonos y del marcador para obtener el zoom
    var Zoombounds = new GLatLngBounds();

    // Si existe algún marcador
    if (points.length > 0) {
        // Se añaden las coordenadas de los marcadores y un separador
        puntos = points + "IWs-sEB";
        // Se añaden los títulos de los marcadores
        for (var i=0; i<titleMarker.length;i++) {
            puntos += titleMarker[i] + "IWt-tEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los comentarios de los marcadores
        for (var i=0; i<htmls.length;i++) {
            puntos += htmls[i].replace(/&/g, '%26') + "IWc-cEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los comentarios de los marcadores
        for (var i=0; i<tagsMarker.length;i++) {
            puntos += tagsMarker[i] + "IWc-cEB";
        }
        // Se añaden los iconos
        puntos += "IWs-sEB";
        for (var i=0; i<markers.length;i++) {
            puntos += markers[i].getIcon().image + "IWi-iEB";
        }

        // Se añade el punto al "bounds"
        Zoombounds.extend(points[0]);
    }

    // Si existe algún polígono
    if (allShapes.length > 0) {
        // Se inicializa la variable
        poligonos = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < allShapes.length; n++) {
            // Se recoge el polígono
            // Se añaden los vértices del polígono
            for (var index=0; index < allShapes[n].getVertexCount(); index++) {
                poligonos += allShapes[n].getVertex(index);
                // Se añade el punto al "bounds"
                Zoombounds.extend(allShapes[n].getVertex(index));
                // Si no es el último vértice, se añade una coma como separador
                if (index != allShapes[n].getVertexCount() - 1) {
                    poligonos += ",";
                }
            }

            // Se añaden el resto de las características
            poligonos += "IWp-cEB" + titleShapes[n] + "IWc-cEB" + stylestrokeShapes[n] [0] + "IWc-cEB" + stylestrokeShapes[n] [1] + "IWc-cEB" + stylestrokeShapes[n] [2] + "IWc-cEB" + allShapes[n].color + "IWc-cEB" + allShapes[n].opacity + "IWc-cEB" + tagsShapes[n] + "IWp-pEB";
        }
    }

    // Se escribe la URL a la que se envía la petición de guardar el mapa
    var url = "action=createZone&ZoneName=" + document.getElementById("ZoneName").value + "&LevelZoom=" + map.getBoundsZoomLevel(Zoombounds);

    // Si existe algún marcador
    if(puntos != null) {
        // Se añade la variable (codificada) a la URL
        url += "&puntos=" + puntos;
    }
    // Si existe algún polígono
    if (poligonos != null) {
        // Se añade la variable (codificada) a la URL
        url += "&poligonos=" + poligonos;
    }

    // Se ejecuta la función AJAX que guarda el mapa
    loadIbox();
    AjaxUploadtoServer("MapBrain", url, "infoIbox");
}

function cargarInfo (pagina, total) {
    document.getElementById("TitlesAll").innerHTML = TitlesAll[pagina - 1];
    document.getElementById("numAll").innerHTML = Numeracion (pagina, total);
}


function Numeracion (pagina, total) {
    var paginacion = "";
    var diff = total - pagina;

    if (total != 1) {
        // Símbolos iniciales
        if (pagina > 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo(1," + total + ");\" title=\"Primera página\"><span style=\"font-size:13px; vertical-align: text-top;\">«</span></a>&nbsp;";
        }
        if (pagina > 1) {
            var inter = pagina - 1;
            paginacion += "<a href=\"javascript:cargarInfo(" + inter + "," + total + ");\" title=\"Anterior\"><span style=\"font-size:13px;\"><</span></a>&nbsp;";
        }

        // Números de pagina
        if (total <= 5) {
            for (var i = 1; i <= total; i++) {
                paginacion += colorNumeracion (i, pagina, total);
            }
        }
        else {
            if (pagina <= 3) {
                for (var i = 1; i <= 4; i++) {
                    paginacion += colorNumeracion (i, pagina, total);
                }

                if (total != 6) {
                    paginacion += colorNumeracion (5, pagina, total);
                    paginacion += "<a href=\"javascript:cargarInfo(6," + total + ");\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                }
                else {
                    paginacion += "<a href=\"javascript:cargarInfo(5," + total + ");\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                }


            }
            else if (diff <= 2) {
                var prev = total - 5;
                paginacion += "<a href=\"javascript:cargarInfo(" + prev + "," + total + ");\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = total - 4; i <= total; i++) {
                    paginacion += colorNumeracion (i, pagina, total);
                }
            }
            else if (diff == 3) {
                var prev = pagina - 3;
                paginacion += "<a href=\"javascript:cargarInfo(" + prev + "," + total + ");\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = pagina - 2; i <= pagina + 1; i++) {
                    paginacion += colorNumeracion (i, pagina, total);
                }
                var inter = pagina + 2;
                paginacion += "<a href=\"javascript:cargarInfo(" + inter + "," + total + ");\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
            }
            else {
                var prev = pagina - 3;
                paginacion += "<a href=\"javascript:cargarInfo(" + prev + "," + total + ");\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = pagina - 2; i <= pagina + 2; i++) {
                    paginacion += colorNumeracion (i, pagina, total);
                }
                var inter = pagina + 3;
                paginacion += "<a href=\"javascript:cargarInfo(" + inter + "," + total + ");\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
            }
        }

        // Símbolos finales
        if (diff >= 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo(" + total + "," + total + ");\" title=\"Página " + total + "\"><span style=\"font-size:13px;\">" + total + "</span></a>&nbsp;";
        }
        if (pagina < total) {
            var inter = pagina + 1;
            paginacion += "<a href=\"javascript:cargarInfo(" + inter + "," + total + ");\" title=\"Siguiente\"><span style=\"font-size:13px;\">></span></a>&nbsp;";
        }
        if (diff >= 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo(" + total + "," + total + ");\" title=\"Última página\"><span style=\"font-size:13px; vertical-align: text-top;\">»</span></a>&nbsp;";
        }
    }

    return paginacion;
}

function colorNumeracion (i, pagina, total) {
    var color = "";;

    if (i == pagina) {
        color += "<span title=\"Página " + i + "\" style=\"color: #ff9900; font-weight: bold; font-size: 17px;\">" + i + "</span>";
    }
    else {
        color += "<a href=\"javascript:cargarInfo(" + i + "," + total + ");\" title=\"Página " + i + "\"><span style=\"font-size:13px;\">" + i + "</span></a>";
    }

    color += "&nbsp;";

    return color;
}

function BotonModificar(id, allowLine, ZoneID, ServiceID, zonausuario) {
    document.getElementById("ModifMap").innerHTML = "<button id=\"botonModf\" class=\"buttons\" onclick=\"javascript:modificarMapa(" + id + ", " + allowLine + ", " + ZoneID + ", " + ServiceID + ", '" + zonausuario+ "')\" title=\"Modificar el mapa\"><img src=\"img/modifica_mapa.png\" alt=\"Modificar mapa\" /></button>";
    //alert("bb");
}

function modificarMapa(ident, allowLine, ZoneID, ServiceID, zonausuario) {

    markers = [];
    points = [];
    titleMarker = [];
    htmls = [];
    tagsMarker = [];
    //var icons = new Array();
    // ===== Variables para las líneas =====
    allLines = []; // Guardar las líneas
    lineActivated = false;
    titleLines = []; // Títulos de las líneas
    tagsLines = []; // Tags de las líneas
    vertexLine = [];
    // ===== Variables para los polígonos =====
    allShapes = []; // Guardar los polígonos
    shapeActivated = false;
    titleShapes = []; // Títulos de los polígonos
    tagsShapes = []; // Tags de los polígonos
    stylestrokeShapes = []; // Estilo del borde del polígono


    document.getElementById("botonModf").disabled = true;
    document.getElementById("mantenerCapa").disabled = true;
    document.getElementById("botonModf").style.backgroundColor = "#E5E5E5";

    map.closeInfoWindow();
    map.removeControl(EditorControl);
    map.removeControl(modificarBoton);

    /*document.getElementById("loadInfoMap").innerHTML = "<form action=\"#\" method=\"post\" onsubmit=\"GuardarCambios(this.identMapa.value, this.identZona.value, this.identServicio.value); return false;\"><div>"
    + "<input type=\"hidden\" id=\"identMapa\" name=\"identMapa\" value=\"" + ident + "\" />"
    + "<input type=\"hidden\" id=\"identZona\" name=\"identZona\" value=\"" + ZoneID + "\" />"
    + "<input type=\"hidden\" id=\"identServicio\" name=\"identServicio\" value=\"" + ServiceID + "\" />"
    + "<button type=\"submit\">Modificar</button></div></form>";*/
    // loadService(ident, allowLine, true, ZoneID, ServiceID);
    startToolboxControl(allowLine);
    EditorControl = new EditToolboxControl();
    map.addControl(EditorControl);
    EditMapFormControl (ident, allowLine, ZoneID, ServiceID, zonausuario);
    modificarBoton = new FormEditMapControl();
    map.addControl(modificarBoton);

    mapActivated = true;
    //
    for (var a = 0; a < ModifMarkers.length; a++) {

        var marcador= ModifMarkers[a];
        ModifMarkers[a].enableDragging();

        GEvent.addListener(marcador, "click", function() {
            actualWindowOpenM = this;
            // Se crea el editor para añadir/editar comentarios
            var html = editComment2();
            // Se abre una ventana con pestañas
            this.openInfoWindowTabsHtml([new GInfoWindowTab("Editar",html), new GInfoWindowTab("Iconos",SelectIcon(this))]);
        });
        // Cuando la ventana de información se ha abierto
        GEvent.addListener(marcador, "infowindowopen", function() {
            // Se activa el editor TinyMCE
            tinyMCE.execCommand('mceAddControl', false, "MarkerTA");
        });
        // Cuando la ventana de información se ha cerrado
        GEvent.addListener(marcador, "infowindowclose", function() {
            // Se desactiva el editor TinyMCE
            tinyMCE.execCommand('mceRemoveControl', false, "MarkerTA");
            actualWindowOpenM = null;
        });
        // Cuando se comienza a arrastrar el marcador
        GEvent.addListener(marcador, "dragstart", function() {
            // Se cierra la ventana de información
            map.closeInfoWindow();
        });
    }

    for (var a = 0; a < Modifrutas.length; a++) {
        var ruta= Modifrutas[a];
        EditLine2(ruta, "line");
    }

    for (var a = 0; a < ModifAreas.length; a++) {
        var area= ModifAreas[a];
        EditLine2(area, "polygon");
    }
    //alert("aaaa");
}
//startFormControl(region, service);
//FormControl = new FormMapControl();

EditMapFormControl = function(Agr, allowLine, region, service, zonausuario) {
    FormEditMapControl = function() {}

    FormEditMapControl.prototype = new GControl();

    FormEditMapControl.prototype.initialize = function(map) {
        // Se crea el contenedor
        var container = document.createElement("div");
        container.className = "FormMenu"; // El nombre de la clase del contenedor

        // Se crean el formulario para enviar los datos
        var formMap = document.createElement("form");
        formMap.id = "frm"; // El id del formulario
        formMap.method = "post"; // Forma de envio
        formMap.action = "#"; // Action del formulario
        formMap.onsubmit = confirmSend2; // El onsubmit
        formMap.acceptCharset = "UTF-8"; // La codificación del formulario
        formMap.style.backgroundColor = "transparent";
        formMap.style.backgroundImage = "url(img/formulario_mapa.png)";
        formMap.style.backgroundRepeat = "no-repeat";

        var div = document.createElement("div");
        div.className = "divMap";

        var inputtMap = document.createElement("input");
        inputtMap.id = "identMapa";
        inputtMap.name = "identMapa";
        inputtMap.type = "hidden";
        inputtMap.value = Agr;

        var inputZone = document.createElement("input");
        inputZone.id = "identZona";
        inputZone.name = "identZona";
        inputZone.type = "hidden";
        inputZone.value = region;

        var inputService = document.createElement("input");
        inputService.id = "identServicio";
        inputService.name = "identServicio";
        inputService.type = "hidden";
        inputService.value = service;

        var inputuserzone = document.createElement("input");
        inputuserzone.id = "userzone";
        inputuserzone.name = "userzone";
        inputuserzone.type = "hidden";
        inputuserzone.value = zonausuario;

        var labelTitle = document.createElement("label");
        labelTitle.htmlFor = "TitleGroup";
        labelTitle.innerHTML = "Título ";

        var inputTitle = document.createElement("input");
        inputTitle.className = "inputMap";
        inputTitle.id = "TitleGroup";
        inputTitle.name = "TitleGroup";
        inputTitle.type = "text";
        inputTitle.maxLength = "19";
        inputTitle.value = ModifAgr[0];
        inputTitle.disabled = !ModifAgr[2];

        var labelTags = document.createElement("label");
        labelTags.htmlFor = "TagsGroup";
        labelTags.innerHTML = "Tags ";

        var inputTags = document.createElement("input");
        inputTags.className = "inputMap";
        inputTags.id = "TagsGroup";
        inputTags.name = "TagsGroup";
        inputTags.type = "text";
        inputTags.value = ModifAgr[1];
        inputTags.disabled = !ModifAgr[2];
        //inputTags.size = "15";


        var table = document.createElement("table"); // La tabla
        var tbody = document.createElement("tbody"); // El cuerpo de la tabla
        var tr = document.createElement("tr"); // La fila
        var td1 = document.createElement("td"); // Celda 1
        var td2 = document.createElement("td"); // Celda 2

        var SubmitMap = document.createElement("div");
        SubmitMap.id = "SendMap";
        SubmitMap.className = "buttonForm";
        SubmitMap.innerHTML = "<img src=\"img/enviar_form.png\" alt=\"Enviar\" />";
        SubmitMap.title = "Guardar los cambios del Mapa"
        SubmitMap.style.cursor = "pointer";
        GEvent.addDomListener(SubmitMap, "click", function() {
            formMap.onsubmit();
        });

        var ResetMap = document.createElement("div");
        ResetMap.id = "ResetMap";
        ResetMap.className = "buttonForm";
        ResetMap.innerHTML = "<img src=\"img/abandonar.png\" alt=\"Abandonar\" />";
        ResetMap.title = "Cancelar y Salir de la edición del Mapa"
        ResetMap.style.cursor = "pointer";
        GEvent.addDomListener(ResetMap, "click", function() {
            confirmReset2(Agr, allowLine, region, service);
        });

        td1.appendChild(SubmitMap);
        td2.appendChild(ResetMap);
        tr.appendChild(td1);
        tr.appendChild(td2);
        tbody.appendChild(tr);
        table.appendChild(tbody);

        div.appendChild(inputtMap);
        div.appendChild(inputZone);
        div.appendChild(inputService);
        div.appendChild(inputuserzone);
        //formMap.appendChild(labelTitle);
        div.appendChild(inputTitle);
        div.appendChild(document.createElement("br"));
        //formMap.appendChild(labelTags);
        div.appendChild(inputTags);

        formMap.appendChild(div);
        formMap.appendChild(table);
        container.appendChild(formMap);

        map.getContainer().appendChild(container);
        return container;
    }

    FormEditMapControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 45)); //210 de izda, 7 top
    }

};

function confirmSend2(){
    var send = confirm("¿Desea guardar los cambios realizados?");

    if (send) {
        GuardarCambios(document.getElementById("frm").identMapa.value, document.getElementById("frm").identZona.value, document.getElementById("frm").identServicio.value, document.getElementById("frm").userzone.value, document.getElementById("frm").TitleGroup.value, document.getElementById("frm").TagsGroup.value);
    }

    return false;
}


function confirmReset2(Agr, allowLine, ZoneID, ServiceID) {
    // Se pide una confirmación de la acción
    var cancel = confirm("¿Desea salir de la edición de este mapa sin guardar cambios?");
    if (cancel) { // Si existe la confirmación
        resetMap2();
        mapActivated = false;
        map.removeControl(EditorControl);
        map.removeControl(modificarBoton);
        loadService(Agr, allowLine, true, ZoneID, ServiceID);
        document.getElementById("mantenerCapa").disabled = false;
        document.getElementById("botonModf").disabled = false;
        document.getElementById("botonModf").style.backgroundColor = "transparent";
    }

    return false;
}

function resetMap2() {
    // Se cierra la ventana de información
    map.closeInfoWindow();
    // Se limpian todas las capas del mapa
    map.clearOverlays();
    // Se centra el mapa en la posición guardada
    map.returnToSavedPosition();

    // Se resetean las variables de los marcadores
    resetMarkers();
    // Se resetean las variables de las líneas
    resetLines();
    // Se resetean las variables de los polígonos
    resetShapes();
    // Se resetean el resto de variables
    side_bar_pois = "";
    gmarkers = [];
    htmlsPois = [];
    side_bar_routes = "";
    groutes = [];
    htmlsRoutes = [];
    side_bar_polygons = "";
    gpolygons = [];
    htmlsPolygons = [];
    ModifMarkers = [];
    ModifHtml = [];
    IDsMarkers = [];
    ModifAgr = [];
    Modifrutas = [];
    ModifHtmlrutas = [];
    IDsRutas = [];
    ModifAreas = [];
    ModifHtmlAreas = [];
    IDsAreas = [];
    ModifstyleAreas = [];
    actualWindowOpenM = null;

    // Se seleciona el botón de arrastrar/editar el mapa
    select("hand_b");
}


function editComment2() {
    // Se busca en el array "markers" el marcador a modificar el título y/o comentario
    for(var n = 0; n < ModifMarkers.length; n++) {
        if(ModifMarkers[n] == actualWindowOpenM) {
            var title = ModifHtml[n][0]; // El título del marcador
            var content = ModifHtml[n][1]; // El contenido del marcador
            var tags = ModifHtml[n][2]; // Los tags del marcador
            break;
        }
    }

    // Se genera el formulario que aparecerá en la ventana
    var iwform = "<div style=\"width:450px;\"><form id=\"WYSIWYGform\" action=\"#\" method=\"post\" style=\"width:99%;height:280px\" onsubmit=\"saveData2(this.titleMarker.value, tinyMCE.get('MarkerTA').getContent(), this.tagsMarker.value);return false;\"><div>"
    + "<label for=\"titleMarker\">Título: </label><input id=\"titleMarker\" name=\"titleMarker\" value=\"" + title + "\" />&nbsp;&nbsp;"
    + "<label for=\"tagsMarker\">Tags: </label><input id=\"tagsMarker\" name=\"tagsMarker\" value=\"" + tags + "\" /><br />"
    + "<div style=\"font-size:11px;font-style:italic;text-align:right; width:84%;\">Ej: Cedetel, Ayuntamiento, GIS</div><br />"
    + "<label for=\"MarkerTA\">Comentario: </label><br /><span style=\"font-size:14px;font-style:italic;text-align:center;\">Use el cuadro de texto para insertar el comentario.</span><br />"
    + "<textarea id=\"MarkerTA\" name=\"content\" cols=\"53\" rows=\"8\">" + content + "</textarea><br />"
    + "</div><div style=\"width:99%;\"><button type=\"submit\" style=\"float:left;\">Guardar</button><a href=\"javascript:void(0)\" onclick=\"return removeMarker2();\" style=\"float:right;\">Borrar</a></div></form></div>";

    return iwform;
}

function saveData2(title,details,tags) {
    // Se busca en el array "markers" el marcador a actualizar el título, tags y/o comentario
    for(var n = 0; n < ModifMarkers.length; n++) {
        if(ModifMarkers[n] == actualWindowOpenM) {
            // Se sustituye en el array "titleMarker" el titulo del marcador por su título actual
            ModifHtml[n][0] = title;
            // Se sustituye en el array "htmls" el comentario del marcador por su comentario actual
            ModifHtml[n][1] = details;
            // Se sustituye en el array "tagsMarker" los tags del marcador por sus tags actuales
            ModifHtml[n][2] = tags;
            break;
        }
    }
    // Se cierra la ventana de información
    map.closeInfoWindow();
}


/**
* Función que elimina el marcador
*
* @return false
*/
function removeMarker2() {
    // Se pide una confirmación de la acción
    var deleteMarker = confirm("¿Desea borrar este marcador?");
    if (deleteMarker) { // Si existe la confirmación
        // Se busca en el array "markers" el marcador a eliminar
        for(var n = 0; n < ModifMarkers.length; n++) {
            if(ModifMarkers[n] == actualWindowOpenM) {
                // Se borra el marcador del mapa
                map.removeOverlay(ModifMarkers[n]);
                IDsMarkers[n] = -IDsMarkers[n];
               // alert(IDsMarkers[n])
                break;
            }
        }

        //markers.splice(n, 1); points.splice(n, 1); htmls.splice(n, 1); titleMarker.splice(n, 1); tagsMarker.splice(n, 1);
    }

    return false;
}

function EditLine2(poly, type) {
    // Se habilita la edición del polígono/línea cuando el ratón está sobre el polígono/línea
    poly.enableEditing({onEvent: "mouseover"});
    // Se deshabilita la edición del polígono/línea cuando el ratón no está sobre el polígono/línea
    poly.disableEditing({onEvent: "mouseout"});

    // Cuando se hace click sobre el polígono/línea
    GEvent.addListener(poly, "click", function(latlng, index) {
        actualPoly = poly; // Se guarda la forma seleccionada

        if (typeof index == "number") { // Si el click lo hace sobre un vértice
            map.closeInfoWindow(); // Cerramos la ventana de información (si estuviera abierta)
            poly.deleteVertex(index); // Borramos el vértice
        }
        else { // Si no lo hace sobre un vértice
            // Se abre la ventana de información
            map.openInfoWindowHtml(latlng, PolyInfoWindow2(poly, type));
        }
    });
}

function PolyInfoWindow2 (poly, type) {
    // Se definen las variables a utilizar
    // - color: Color del polígono/línea
    // - weight: Ancho del polígono/línea
    // - opacity: Opacidad del polígono/línea
    var color, weight, opacity, title, tags;

    if (type == "line") { // Se recogen los valores (para la línea)
        color = poly.color;//strokeColor;
        weight = poly.weight//strokeWeight;
        opacity = poly.opacity*100//strokeOpacity;

        // Se busca en el array "allLines" la línea seleccionada
        for(var n = 0; n < Modifrutas.length; n++) {
            if(Modifrutas[n] == actualPoly) {
                title = ModifHtmlrutas[n][0]; // El título del marcador; // Se recoge el título de la línea
                tags = ModifHtmlrutas[n][1]; // Se recogen los tags de la línea
                break;
            }
        }
    }
    else if (type == "polygon") { // Se recogen los valores (para el polígono)
        // Se busca en el array "allShapes" el polígono seleccionado
        for(var n = 0; n < ModifAreas.length; n++) {
            if(ModifAreas[n] == actualPoly) {
                title = ModifHtmlAreas[n][0]; // Se recoge el título del polígono
                tags = ModifHtmlAreas[n][1]; // Se recogen los tags del polígono
                color = ModifstyleAreas[n] [0];
                weight = ModifstyleAreas[n] [1];
                opacity = ModifstyleAreas[n] [2]*100;
                break;
            }
        }
    }


    // Se crea el que aparecerá en la ventana de información
    // y que permitirá editar el polígono/línea
    var html = "<div style=\"width:405px;\"><form id=\"formPoly\" action=\"#\" onsubmit=\"UpdateStylePoly2(this); return false;\"><div>"
    + "<label for=\"title\">Título: </label><input id=\"title\" name=\"title\" value=\"" + title + "\" />&nbsp;&nbsp;"
    + "<label for=\"tags\">Tags: </label><input id=\"tags\" name=\"tags\" value=\"" + tags + "\" /><br />"
    + "<div style=\"font-size:11px;font-style:italic;text-align:right; width:93%;\">Ej: Cedetel, Ayuntamiento, GIS</div><br />"
    + "<table border=\"0\" style=\"margin:0 auto;\"><tbody>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySC\">Color línea:</label></td><td><input id=\"displaySC\" name=\"displaySC\" value=\"" + color + "\" /></td></tr>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySW\">Ancho línea:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
    + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderSW\" onmousedown=\"slide(event, 'horizontal', 100, 2, 10, 9, 0, 'displaySW');\" style=\"left: " + (weight-2)*12.5 + "px;\">&nbsp;</div></div>"
    + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displaySW\" type=\"text\" value=\"" + weight + "\" onfocus=\"blur(this);\" /></div>"
    + "</div></td></tr>"
    + "<tr><td style=\"text-align: left;\"><label for=\"displaySO\">Opacidad línea:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
    + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderSO\" onmousedown=\"slide(event, 'horizontal', 100, 0, 100, 101, 0, 'displaySO');\" style=\"left: " + opacity + "px;\">&nbsp;</div></div>"
    + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displaySO\" type=\"text\" value=\"" + opacity + "\" onfocus=\"blur(this);\" /></div>"
    + "</div></td></tr>";
    if (type == "polygon") {
        html += "<tr><td style=\"text-align: left;\"><label for=\"displayFC\">Color relleno:</label></td><td><input id=\"displayFC\" name=\"displayFC\" value=\"" + poly.color + "\" /></td></tr>"
        + "<tr><td style=\"text-align: left;\"><label for=\"displayFO\">Opacidad relleno:</label></td><td><div class=\"carpe_horizontal_slider_display_combo\">"
        + "<div class=\"carpe_horizontal_slider_track\"><div class=\"carpe_slider_slit\">&nbsp;</div><div class=\"carpe_slider\" id=\"sliderFO\" onmousedown=\"slide(event, 'horizontal', 100, 0, 100, 101, 0, 'displayFO');\" style=\"left: " + poly.opacity*100 + "px;\">&nbsp;</div></div>"
        + "<div class=\"carpe_slider_display_holder\" ><input class=\"carpe_slider_display\" id=\"displayFO\" type=\"text\" value=\"" + poly.opacity*100 + "\" onfocus=\"blur(this);\" /></div>"
        + "</div></td></tr>";
    }
    html += "</tbody></table>"
    + "<br /></div><div style=\"width:99%;\"><button type=\"submit\" style=\"float:left;\">Guardar Cambios</button><a href=\"javascript:void(0)\" onclick=\"return removePoly2();\" style=\"float:right;\">Borrar</a></div></form></div>";
    /* if (type == "line") {
    html += "<a href=\"javascript:void(0)\" onclick=\"return ExtendLine(false);\">Editar Final</a><br />"
    + "<a href=\"javascript:void(0)\" onclick=\"return ExtendLine(true);\">Editar Principio</a>";
    } */

    return html;
}

/**
* Función que graba el nuevo estilo del polígono/línea
*
* @param (form) Formulario que contiene las variables de estilo
*/
function UpdateStylePoly2(form) {
    // Se recoge el titulo y los tags del formulario
    // title = form.title.value
    // tags = form.tags.value

    if (actualPoly.fill == true) { // Si la forma seleccionada tiene relleno (es un polígono)
        // Se busca en el array "allShapes" el polígono a actualizar
        for(var n = 0; n < ModifAreas.length; n++) {
            if(ModifAreas[n] == actualPoly) {
                ModifHtmlAreas[n][0] = form.title.value; // Se actualiza el título del polígono
                ModifHtmlAreas[n][1] = form.tags.value; // Se actualizan los tags del polígono

                // A quitar cuando funcione el color-picker
                ModifstyleAreas[n] [0] = form.displaySC.value; // Se actualiza el color del borde del polígono
                break;
            }
        }
        // A quitar cuando funcione el color-picker
        actualPoly.setFillStyle({color: form.displayFC.value});
    }
    else { // Si la forma seleccionada no tiene relleno (es una línea)
        // Se busca en el array "allLines" la línea a actualizar
        for(var n = 0; n < Modifrutas.length; n++) {
            if(Modifrutas[n] == actualPoly) {
                ModifHtmlrutas[n][0] = form.title.value; // Se actualiza el título de la línea
                ModifHtmlrutas[n][1] = form.tags.value; // Se actualizan los tags de la línea
                break;
            }
        }
    }
    // A quitar cuando funcione el color-picker
    actualPoly.setStrokeStyle({color: form.displaySC.value});
    // Se cierra la ventana de información
    map.closeInfoWindow();
}

/**
* Función que elimina el Polígono/Línea
*
* @return false
*/
function removePoly2() {
    // Se pide una confirmación de la acción
    var deletePoly = confirm("¿Desea borrar esta figura?");
    if (deletePoly) { // Si existe la confirmación
        map.closeInfoWindow(); // Se cierra la ventana de información

        if (actualPoly.fill == true) { // Si la forma seleccionada tiene relleno (es un polígono)
            // Se busca en el array "allShapes" el polígono a eliminar
            for(var n = 0; n < ModifAreas.length; n++) {
                if(ModifAreas[n] == actualPoly) {
                    // Se borra el polígono del mapa
                    map.removeOverlay(ModifAreas[n]);
                    IDsAreas[n] = -IDsAreas[n];
                   // alert(IDsAreas[n])
                    break;
                }
            }
            // Se borra el polígono de los arrays "allShapes", "titleShapes", "tagsShapes" y "stylestrokeShapes"
            //  allShapes.splice(n, 1); titleShapes.splice(n, 1); tagsShapes.splice(n, 1); stylestrokeShapes.splice(n, 1);
        }
        else { // Si la forma seleccionada no tiene relleno (es una línea)
            // Se busca en el array "allLines" la línea a eliminar
            for(var n = 0; n < Modifrutas.length; n++) {
                if(Modifrutas[n] == actualPoly) {
                    // Se borra la línea del mapa
                    map.removeOverlay(Modifrutas[n]);
                    IDsRutas[n] = -IDsRutas[n];
               //     alert(IDsRutas[n])
                    break;
                }
            }
            // Se borra la línea de los arrays "allLines", "titleLines" y "tagsLines"
            // allLines.splice(n, 1); titleLines.splice(n, 1); tagsLines.splice(n, 1);
        }

        actualPoly = null; // Se resetea la variable de la forma seleccionada
    }

    return false;
}

function GuardarCambios(ident, ZoneId, ServiceId, zonausuario, titleAgr, tagsAgr){
    var puntos = null;
    var nuevospuntos = null;
    var lineas = null;
    var nuevaslineas = null;
    var poligonos = null;
    var nuevospoligonos = null;

    if (ModifMarkers.length > 0) {
        var coordenadas = "";
        // Se añaden las coordenadas de los marcadores y un separador
        for (var i=0; i<ModifMarkers.length;i++) {
            coordenadas += ModifMarkers[i].getLatLng();

            if (i < ModifMarkers.length - 1) {
                coordenadas +=","
            }
        }
        puntos = coordenadas + "IWs-sEB";
        // Se añaden los títulos de los marcadores
        for (var i=0; i<ModifHtml.length;i++) {
            puntos += ModifHtml[i][0] + "IWt-tEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los comentarios de los marcadores
        for (var i=0; i<ModifHtml.length;i++) {
            puntos += ModifHtml[i][1].replace(/&/g, '%26') + "IWc-cEB";
        }
        // Se añade un separador
        puntos += "IWs-sEB";
        // Se añaden los tags de los marcadores
        for (var i=0; i<ModifHtml.length;i++) {
            puntos += ModifHtml[i][2] + "IWc-cEB";
        }
        // Se añaden los iconos
        puntos += "IWs-sEB";
        for (var i=0; i<ModifMarkers.length;i++) {
            puntos += ModifMarkers[i].getIcon().image + "IWi-iEB";
        }

    }


    if (points.length > 0) {
        // Se añaden las coordenadas de los marcadores y un separador
        nuevospuntos = points + "IWs-sEB";
        // Se añaden los títulos de los marcadores
        for (var i=0; i<titleMarker.length;i++) {
            nuevospuntos += titleMarker[i] + "IWt-tEB";
        }
        // Se añade un separador
        nuevospuntos += "IWs-sEB";
        // Se añaden los comentarios de los marcadores
        for (var i=0; i<htmls.length;i++) {
            nuevospuntos += htmls[i].replace(/&/g, '%26') + "IWc-cEB";
        }
        // Se añade un separador
        nuevospuntos += "IWs-sEB";
        // Se añaden los tags de los marcadores
        for (var i=0; i<tagsMarker.length;i++) {
            nuevospuntos += tagsMarker[i] + "IWc-cEB";
        }
        // Se añaden los iconos
        nuevospuntos += "IWs-sEB";
        for (var i=0; i<markers.length;i++) {
            nuevospuntos += markers[i].getIcon().image + "IWi-iEB";
        }
    }

    if (Modifrutas.length > 0) {
        // Se inicializa la variable
        lineas = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < Modifrutas.length; n++) {
            // Se recoge la línea
            // Se añaden los vértices de la línea
            for (var index=0; index < Modifrutas[n].getVertexCount(); index++) {
                lineas += Modifrutas[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != Modifrutas[n].getVertexCount() - 1) {
                    lineas += ",";
                }
            }
            // Se añaden el resto de las características
            lineas += "IWp-cEB" + ModifHtmlrutas[n][0] + "IWc-cEB" + Modifrutas[n].color + "IWc-cEB" + Modifrutas[n].weight + "IWc-cEB" + Modifrutas[n].opacity + "IWc-cEB" + ModifHtmlrutas[n][1] + "IWl-lEB";
        }
    }

    if (allLines.length > 0) {
        // Se inicializa la variable
        nuevaslineas = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < allLines.length; n++) {
            // Se recoge la línea
            // Se añaden los vértices de la línea
            for (var index=0; index < allLines[n].getVertexCount(); index++) {
                nuevaslineas += allLines[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != allLines[n].getVertexCount() - 1) {
                    nuevaslineas += ",";
                }
            }
            // Se añaden el resto de las características
            nuevaslineas += "IWp-cEB" + titleLines[n] + "IWc-cEB" + allLines[n].color + "IWc-cEB" + allLines[n].weight + "IWc-cEB" + allLines[n].opacity + "IWc-cEB" + tagsLines[n] + "IWl-lEB";
        }
    }

    // Si existe algún polígono
    if (ModifAreas.length > 0) {
        // Se inicializa la variable
        poligonos = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < ModifAreas.length; n++) {
            // Se recoge el polígono
            // Se añaden los vértices del polígono
            for (var index=0; index < ModifAreas[n].getVertexCount(); index++) {
                poligonos += ModifAreas[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != ModifAreas[n].getVertexCount() - 1) {
                    poligonos += ",";
                }
            }

            // Se añaden el resto de las características
            poligonos += "IWp-cEB" + ModifHtmlAreas[n][0] + "IWc-cEB" + ModifstyleAreas[n] [0] + "IWc-cEB" + ModifstyleAreas[n] [1] + "IWc-cEB" + ModifstyleAreas[n] [2] + "IWc-cEB" + ModifAreas[n].color + "IWc-cEB" + ModifAreas[n].opacity + "IWc-cEB" + ModifHtmlAreas[n][1] + "IWp-pEB";
        }
    }

    // Si existe algún polígono
    if (allShapes.length > 0) {
        // Se inicializa la variable
        nuevospoligonos = "";
        // Se recorre el array para recoger las líneas
        for(var n = 0; n < allShapes.length; n++) {
            // Se recoge el polígono
            // Se añaden los vértices del polígono
            for (var index=0; index < allShapes[n].getVertexCount(); index++) {
                nuevospoligonos += allShapes[n].getVertex(index);
                // Si no es el último vértice, se añade una coma como separador
                if (index != allShapes[n].getVertexCount() - 1) {
                    nuevospoligonos += ",";
                }
            }

            // Se añaden el resto de las características
            nuevospoligonos += "IWp-cEB" + titleShapes[n] + "IWc-cEB" + stylestrokeShapes[n] [0] + "IWc-cEB" + stylestrokeShapes[n] [1] + "IWc-cEB" + stylestrokeShapes[n] [2] + "IWc-cEB" + allShapes[n].color + "IWc-cEB" + allShapes[n].opacity + "IWc-cEB" + tagsShapes[n] + "IWp-pEB";
        }
    }

    var url = "action=updateMap&zoneID=" + ZoneId + "&serviceID=" + ServiceId + "&AgrID=" + ident + "&agrName=" + titleAgr + "&agrTags=" + tagsAgr;

    if (puntos != null) {
        url += "&modpuntos=" + puntos + "&idModPuntos=" + IDsMarkers;
    }

    if  (nuevospuntos != null) {
        url += "&nuevospuntos=" + nuevospuntos;
    }
    if (lineas != null) {
        url += "&modlineas=" + lineas + "&idModlineas=" + IDsRutas;
    }

    if (nuevaslineas != null) {
        url += "&nuevaslineas=" + nuevaslineas;
    }

    if (poligonos != null) {
        url += "&modpoligonos=" + poligonos + "&idModareas=" + IDsAreas;;
    }

    if (nuevospoligonos != null) {
        url += "&nuevospoligonos=" + nuevospoligonos;
    }

    mapActivated = false;
    AjaxUploadtoServer2("MapBrain", url, "loadInfoMap", ident, ServiceId, ZoneId, zonausuario);

    map.removeControl(EditorControl);
    map.removeControl(modificarBoton);
    /*sleep(1000);
    if (zonausuario != "undefined" && zonausuario != "" ) {
        aportacionUsuario();
    } else {
        getTitlesOfService(ServiceId,ZoneId);
    }
    
    loadService(ident, 1, true, ZoneId, ServiceId);*/
    document.getElementById("mantenerCapa").disabled = false;
    document.getElementById("botonModf").disabled = false;
    document.getElementById("botonModf").style.backgroundColor = "transparent";
}

function mantenerCapa() {
    if (document.getElementById("mantenerCapa").checked) {
        mantener = true;
        document.getElementById("ModifMap").style.display = "none";
    }
    else {
        mantener = false;
        document.getElementById("ModifMap").style.display = "block";
    }
}

var TitlesAllMapas = [];
var TitlesAllRutas = [];
var TitlesAllEspacios = [];
var TitlesAllPOIs = [];


function aportacionUsuario() {
    //loadIbox();
    var request = GXmlHttp.create(); // Se crea el objeto request
    // Se realiza una petición AJAX para leer el documento XML
    request.open("GET", "MapBrain?action=aportacionUsuario", true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.onreadystatechange = function() {
        if (request.readyState == 1) {
            // Mientras la carga no ha finalizado
            // Se añade un 'Loading' para que el usuario sepa que el sistema está trabajando
            document.getElementById("loadData").innerHTML ="<img src=\"img/loading.gif\" alt=\"Cargando...\" /><br /><span style=\"font-size: 0.9em; color: #FF0000;\">Loading...</span>";
        }
        else if (request.readyState == 4) { // Cuando la carga ha finalizado
            var xmlDoc = request.responseXML; // Se transforma a XML
            // Se resetean la variable que guardan los enlaces de las agrupaciones y puntos
            var tbody = "";
            TitlesAllMapas = [];
            TitlesAllRutas = [];
            TitlesAllEspacios = [];
            TitlesAllPOIs = [];
            var total_all = 0;
            var total_all_Mapas = 0;
            var total_all_Rutas = 0;
            var total_all_Espacios = 0;
            var total_all_POIs = 0;
            // Se obtiene un array de errores
            var error = xmlDoc.documentElement.getElementsByTagName("error");
            // Si existe algún elemento en el array de error
            if (error[0]) {
                tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Error</div></div>"
                + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p class=\"InfoBox\">" + error[0].getAttribute("title") + "</p></div>"
                + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\">&nbsp;</div>";

                // Se cambia el valor del total
                total_all = -1;
            }
            else { // Si no existe ningún error
                // ========= Se procesan los títulos de las agrupaciones y POIs sueltos ===========
                var list_all = "";
                var count_all = 0;

                // Se obtiene un array de las agrupaciones
                var mapas = xmlDoc.documentElement.getElementsByTagName("mapa");
                // Si existe algún elemento en el array de agrupaciones
                if (mapas[0]) {
                    list_all = "";
                    count_all = 0;
                    total_all = 0;
                    // Se recorre el array de las agrupaciones
                    for (var i = 0; i < mapas.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada agrupación
                        var link = mapas[i].getAttribute("link"); // El enlace

                        // Se crea el enlace para cargar la agrupación en el mapa
                        list_all += link + "\n<br />";

                        if (count_all == 10){
                            TitlesAllMapas.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }

                    tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Mis Mapas <img class=\"imgInfo\" src=\"img/Bmu_Blu.png\" alt=\"Mapa\" title=\"Mapas\" /></div></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p id=\"TitlesAllMapas\" class=\"InfoBox\"></p></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center; height: 5px;\">&nbsp;</div>"
                    + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\"><div id=\"numAllMapas\" class=\"numeration\"></div></div>";

                    if (list_all != "") {
                        TitlesAllMapas.push(list_all);
                        total_all++;
                    }
                    total_all_Mapas = total_all;
                }

                var rutas = xmlDoc.documentElement.getElementsByTagName("ruta");
                // Si existe algún elemento en el array de agrupaciones
                if (rutas[0]) {
                    list_all = "";
                    count_all = 0;
                    total_all = 0;
                    // Se recorre el array de las agrupaciones
                    for (var i = 0; i < rutas.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada agrupación
                        var link = rutas[i].getAttribute("link"); // El enlace

                        // Se crea el enlace para cargar la agrupación en el mapa
                        list_all += link + "\n<br />";

                        if (count_all == 10){
                            TitlesAllRutas.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }

                    tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Mis Itinerarios <img class=\"imgInfo\" title=\"Itinerarios\" alt=\"Itinerario\" src=\"img/Blu.png\" /></div></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p id=\"TitlesAllRutas\" class=\"InfoBox\"></p></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center; height: 5px;\">&nbsp;</div>"
                    + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\"><div id=\"numAllRutas\" class=\"numeration\"></div></div>";

                    if (list_all != "") {
                        TitlesAllRutas.push(list_all);
                        total_all++;
                    }
                    total_all_Rutas = total_all;
                }

                var espacios = xmlDoc.documentElement.getElementsByTagName("espacio");
                // Si existe algún elemento en el array de agrupaciones
                if (espacios[0]) {
                    list_all = "";
                    count_all = 0;
                    total_all = 0;
                    // Se recorre el array de las agrupaciones
                    for (var i = 0; i < espacios.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada agrupación
                        var link = espacios[i].getAttribute("link"); // El enlace

                        // Se crea el enlace para cargar la agrupación en el mapa
                        list_all += link + "\n<br />";

                        if (count_all == 10){
                            TitlesAllEspacios.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }

                    tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Mis Espacios <img class=\"imgInfo\" src=\"img/Bpu.png\" alt=\"Espacio\" title=\"Espacios\" /></div></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p id=\"TitlesAllEspacios\" class=\"InfoBox\"></p></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center; height: 5px;\">&nbsp;</div>"
                    + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\"><div id=\"numAllEspacios\" class=\"numeration\"></div></div>";

                    if (list_all != "") {
                        TitlesAllEspacios.push(list_all);
                        total_all++;
                    }
                    total_all_Espacios = total_all;
                }

                // Se obtiene un array de los POIs
                var POIS = xmlDoc.documentElement.getElementsByTagName("pois");
                // Si existe algún elemento en el array de POIS
                if (POIS[0]) {
                    list_all = "";
                    count_all = 0;
                    total_all = 0;
                    // Se recorre el array de los POIs
                    for (var i = 0; i < POIS.length; i++) {
                        count_all++;
                        // Se obtienen los atributos para cada agrupación
                        var link = POIS[i].getAttribute("link"); // El enlace

                        // Se crea el enlace para cargar la agrupación en el mapa
                        list_all += link + "\n<br />";

                        if (count_all == 10){
                            TitlesAllPOIs.push(list_all);
                            list_all = "";
                            total_all++;
                            count_all = 0;
                        }
                    }

                    tbody += "<div class=\"widthCell\" style=\"background-image: url(img/cabeza_menu.png); height: 34px;\"><div class=\"TitleZone\">Mis Puntos <img class=\"imgInfo\" src=\"img/Bmu.png\" alt=\"Pois\" title=\"Puntos de Interés\" /></div></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center;\"><p id=\"TitlesAllPOIs\" class=\"InfoBox\"></p></div>"
                    + "<div class=\"widthCellData\" style=\"background-image: url(img/cuerpo_menu.png); text-align: center; height: 5px;\">&nbsp;</div>"
                    + "<div class=\"widthCell\" style=\"background-image: url(img/pie_menu.png); height: 21px;\"><div id=\"numAllPOIs\" class=\"numeration\"></div></div>";

                    if (list_all != "") {
                        TitlesAllPOIs.push(list_all);
                        total_all++;
                    }
                    total_all_POIs = total_all;
                }
            }

            document.getElementById("loadData").innerHTML = tbody;

            if (total_all != -1) {
                if (total_all_Mapas != 0) {
                    cargarInfo2(1, total_all_Mapas, "Mapas");
                }
                if (total_all_Rutas != 0) {
                    cargarInfo2(1, total_all_Rutas, "Rutas");
                }
                if (total_all_Espacios != 0) {
                    cargarInfo2(1, total_all_Espacios, "Espacios");
                }
                if (total_all_POIs != 0) {
                    cargarInfo2(1, total_all_POIs, "POIs");
                }
            }
        }
    }
    request.send(null);
}
function cargarInfo2 (pagina, total, tipo) {
    if (tipo == "Mapas") {
        document.getElementById("TitlesAllMapas").innerHTML = TitlesAllMapas[pagina - 1];
    }
    else if (tipo == "Rutas") {
        document.getElementById("TitlesAllRutas").innerHTML = TitlesAllRutas[pagina - 1];
    }
    else if (tipo == "Espacios") {
        document.getElementById("TitlesAllEspacios").innerHTML = TitlesAllEspacios[pagina - 1];
    }
    else if (tipo == "POIs") {
        document.getElementById("TitlesAllPOIs").innerHTML = TitlesAllPOIs[pagina - 1];
    }


    document.getElementById("numAll" + tipo).innerHTML = Numeracion2 (pagina, total, tipo);
}

function Numeracion2 (pagina, total, tipo) {
    var paginacion = "";
    var diff = total - pagina;

    if (total != 1) {
        // Símbolos iniciales
        if (pagina > 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo2(1," + total + ",'" + tipo + "');\" title=\"Primera página\"><span style=\"font-size:13px; vertical-align: text-top;\">«</span></a>&nbsp;";
        }
        if (pagina > 1) {
            var inter = pagina - 1;
            paginacion += "<a href=\"javascript:cargarInfo2(" + inter + "," + total + ",'" + tipo + "');\" title=\"Anterior\"><span style=\"font-size:13px;\"><</span></a>&nbsp;";
        }

        // Números de pagina
        if (total <= 5) {
            for (var i = 1; i <= total; i++) {
                paginacion += colorNumeracion2 (i, pagina, total, tipo);
            }
        }
        else {
            if (pagina <= 3) {
                for (var i = 1; i <= 4; i++) {
                    paginacion += colorNumeracion2 (i, pagina, total, tipo);
                }

                if (total != 6) {
                    paginacion += colorNumeracion2 (5, pagina, total, tipo);
                    paginacion += "<a href=\"javascript:cargarInfo2(6," + total + ",'" + tipo + "');\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                }
                else {
                    paginacion += "<a href=\"javascript:cargarInfo2(5," + total + ",'" + tipo + "');\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                }


            }
            else if (diff <= 2) {
                var prev = total - 5;
                paginacion += "<a href=\"javascript:cargarInfo2(" + prev + "," + total + ",'" + tipo + "');\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = total - 4; i <= total; i++) {
                    paginacion += colorNumeracion2 (i, pagina, total, tipo);
                }
            }
            else if (diff == 3) {
                var prev = pagina - 3;
                paginacion += "<a href=\"javascript:cargarInfo2(" + prev + "," + total + ",'" + tipo + "');\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = pagina - 2; i <= pagina + 1; i++) {
                    paginacion += colorNumeracion2 (i, pagina, total, tipo);
                }
                var inter = pagina + 2;
                paginacion += "<a href=\"javascript:cargarInfo2(" + inter + "," + total + ",'" + tipo + "');\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
            }
            else {
                var prev = pagina - 3;
                paginacion += "<a href=\"javascript:cargarInfo2(" + prev + "," + total + ",'" + tipo + "');\" title=\"Anterior bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
                for (var i = pagina - 2; i <= pagina + 2; i++) {
                    paginacion += colorNumeracion2 (i, pagina, total, tipo);
                }
                var inter = pagina + 3;
                paginacion += "<a href=\"javascript:cargarInfo2(" + inter + "," + total + ",'" + tipo + "');\" title=\"Siguiente bloque\"><span style=\"font-size:13px;\">...</span></a>&nbsp;";
            }
        }

        // Símbolos finales
        if (diff >= 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo2(" + total + "," + total + ",'" + tipo + "');\" title=\"Página " + total + "\"><span style=\"font-size:13px;\">" + total + "</span></a>&nbsp;";
        }
        if (pagina < total) {
            var inter = pagina + 1;
            paginacion += "<a href=\"javascript:cargarInfo2(" + inter + "," + total + ",'" + tipo + "');\" title=\"Siguiente\"><span style=\"font-size:13px;\">></span></a>&nbsp;";
        }
        if (diff >= 3 && total > 5) {
            paginacion += "<a href=\"javascript:cargarInfo2(" + total + "," + total + ",'" + tipo + "');\" title=\"Última página\"><span style=\"font-size:13px; vertical-align: text-top;\">»</span></a>&nbsp;";
        }
    }

    return paginacion;
}

function colorNumeracion2 (i, pagina, total, tipo) {
    var color = "";;

    if (i == pagina) {
        color += "<span title=\"Página " + i + "\" style=\"color: #ff9900; font-weight: bold; font-size: 17px;\">" + i + "</span>";
    }
    else {
        color += "<a href=\"javascript:cargarInfo2(" + i + "," + total + ",'" + tipo + "');\" title=\"Página " + i + "\"><span style=\"font-size:13px;\">" + i + "</span></a>";
    }

    color += "&nbsp;";

    return color;
}

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

function SelectIcon(marker) {
    var iconos = new Array();
    iconos.push(new Array("marker_blue-dot", "marker_red-dot", "marker_green-dot", "marker_lightblue-dot", "marker_yellow-dot", "marker_purple-dot", "marker_pink-dot"));
    iconos.push(new Array("marker_blue", "marker_red", "marker_green", "marker_lightblue", "marker_yellow", "marker_purple", "marker_pink"));
    iconos.push(new Array("pushpin_blue", "pushpin_red", "pushpin_green", "pushpin_lightblue", "pushpin_yellow", "pushpin_purple", "pushpin_pink"));
    iconos.push(new Array("camera", "movies", "restaurant", "hiker", "POI", "hospital", "info"));

    var container = document.createElement("div");
    var div = document.createElement("div");
    div.innerHTML = "Este es el icono actual: <div id=\"actualIcon\"><img src=\"" + marker.getIcon().image + "\" alt=\"Icono actual\" /></div><br /><br />Escoja icono:<br />";

    // Se crea el elemento <table>y el elemento <tbody>
    var table = document.createElement("table");
    var tbody = document.createElement("tbody");

    // Se crean las celdas
    for (var i = 0; i < iconos.length; i++) {
        // Se crean las filas
        var tr = document.createElement("tr");

        for (var j = 0; j < iconos[i].length; j++) {
            // Se crea el elemento <td>, su contenido y sus atributos
            // y se añade el elemento <td> al final de la fila
            var td = document.createElement("td");
            td.appendChild(getIconos(marker, iconos[i][j]));
            tr.appendChild(td);
        }

        // se añade la fila al final del cuerpo de la tabla
        tbody.appendChild(tr);
    }

    table.border = 0;
    // Se añade el elemento <tbody> al elemento <table>
    table.appendChild(tbody);
    container.appendChild(div);
    container.appendChild(table);

    return container;
}

function getIconos(marker,icono) {
    // Botón de Crear un polígono
    var div = document.createElement("div");
    div.id = "icono_" + icono;
    div.setAttribute((document.all ? "className" : "class"), "iconDiv");
    div.innerHTML = "<img src=\"img/map_icons/" + icono + ".png\" alt=\"Marcador\" />";
    div.style.cursor = "pointer";
    GEvent.addDomListener(div, "click", function() {
        marker.setImage("./img/map_icons/" + icono + ".png");
        marker.getIcon().image = "./img/map_icons/" + icono + ".png";
        document.getElementById("actualIcon").innerHTML = "<img src=\"img/map_icons/" + icono + ".png\" alt=\"Marcador\" />";
    });

    return div;
}

function testIcon(imagen) {
    var icono = new GIcon(Icon);

    if (imagen != null && imagen != "null" &&imagen != "") {
        icono.image = imagen; // Se pone la imagen
        // var expression= new RegExp(/marker/i);
        if (/marker/i.test(imagen)) {
            icono.shadow = "./img/map_icons/marker_s.png"; // Se pone la sombra
        } // expression.compile(/pushpin/i);
        else if (/pushpin/i.test(imagen)) {
            icono.shadow = "./img/map_icons/pushpin_s.png"; // Se pone la sombra
            icono.iconAnchor=new GPoint(10,32); // Se cambia el ancla (para que coincida con la pinta de la chincheta)
        }
        else {
            icono.shadow = imagen.substring(0,imagen.search(/.png/i)) + "_s.png"; // Se pone la sombra
        }
    }

    return icono;
}

function mapSize() {
    var mapsize = document.getElementById("map");
    
    if(mapsize.className == "mapSmall") {
        mapsize.className = "mapGiant";
        document.getElementById("buttonChangeMap").innerHTML = "<img src=\"img/map_icons/contraer.png\" alt=\"contraer\" title=\"Contraer el mapa\" />";
        document.body.style.overflow = "hidden";
        mapsize.style.top = document.body.scrollTop;
        if (navigator.appName == "Microsoft Internet Explorer") {//&& typeof document.body.style.maxHeight == "undefined"
            mapsize.style.height = screen.height;
            mapsize.style.width = screen.width;
        }        
    } else {
        mapsize.className = "mapSmall";
        document.getElementById("buttonChangeMap").innerHTML = "<img src=\"img/map_icons/expandir.png\" alt=\"expandir\" title=\"Expandir el mapa\" />";
        document.body.style.overflow = "auto";
        if (navigator.appName == "Microsoft Internet Explorer") {
            mapsize.style.height = "445px";
            mapsize.style.width = "720px";
        }
    }
    
    map.checkResize();
}


function buttonSizeMap() {}

buttonSizeMap.prototype = new GControl();

buttonSizeMap.prototype.initialize = function(map) {
    var div = document.createElement("div");
    div.id = "buttonChangeMap"
    div.innerHTML = "<img src=\"img/map_icons/expandir.png\" alt=\"expandir\" title=\"Expandir el mapa\" />";
    div.style.cursor = "pointer";
    //div.style.border = "1px solid black";
    GEvent.addDomListener(div, "click", function() {
        mapSize();
    });

    map.getContainer().appendChild(div);
    
    return div;
}

function buscarVideos (html) {
    if (/<object/i.test(html)) {
           html = html.replace(/<object/gi, "<div style=\"height: 360px;\"><object");
           if (navigator.appName == "Microsoft Internet Explorer") {//&& typeof document.body.style.maxHeight == "undefined"
                html = html.replace(/<\/object>/gi, "</object><br />Si no consigue ver el video, instale <a href=\"http://download.macromedia.com/pub/flashplayer/updaters/10/flashplayer_10_ax_debug.exe\">este control ActiveX</a></div>");
            }
            else {
                html = html.replace(/<\/object>/gi, "</object></div>");
            }
    }
    
    return html;
}


function buttonOutMod() {};

buttonOutMod.prototype = new GControl();

buttonOutMod.prototype.initialize = function(map) {

    var buttonout = document.createElement("div");
        buttonout.id = "buttonOut";
        buttonout.className = "buttonOut";
        buttonout.innerHTML = "<img src=\"img/abandonar.png\" alt=\"Abandonar\" />";
        buttonout.title = "Cancelar y Salir de la edición del Mapa"
        buttonout.style.cursor = "pointer";
        GEvent.addDomListener(buttonout, "click", function() {
            salir();
        });

    map.getContainer().appendChild(buttonout);

    return buttonout;
}

buttonOutMod.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(50, 120)); //210 de izda, 7 top
}

function salir() {
    var continuePetition = deshabilitar();

        if(!continuePetition) {
            return;
        }
        else {
            mapActivated = false;
        }
}