﻿// JScript File
//var temas = "92,73";
var modoZoom = false;
var map = null;
var layerPartida = null;
var layerChegada = null;
var layerTemas = null;
var layerLocal = null;
var UrlBase = null;
var mapaVisualizar = null;
var contadorPixel = -1;
var pesquisaAtual = null;

//PopUp
var smallPopUpWidth = 300;
var smallPopUpHeight = 120;
var largePopUpWidth = 700;
var largePopUpHeight = 538;

//Busy Incicator
var busyIndicatorWidth = 234;
var busyIndicatorHeight = 40;

// SAPO MARKERS
var startMarker = null;
var endMarker = null;
var markerSpot = null;

var startLegendHtml = null;
var endLegendHtml = null;

var isKyosk;

var lang = document.getElementById("lng").value;
eval(document.getElementById("localResStr").value);

//bbox
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;

// MESSAGE TEST
function addMsg(msg)
{               
    //var elem = document.getElementById('msgs');                 
    //elem.innerHTML += ' -' + msg + '- ';             
}

function getPageSize()
{
    var xScroll, yScroll;
	
    if (window.innerHeight && window.scrollMaxY) {	
	    xScroll = document.body.scrollWidth;
	    yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	    xScroll = document.body.scrollWidth;
	    yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	    xScroll = document.body.offsetWidth;
	    yScroll = document.body.offsetHeight;
    }
	
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
	    windowWidth = self.innerWidth;
	    windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    windowWidth = document.documentElement.clientWidth;
	    windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
	    windowWidth = document.body.clientWidth;
	    windowHeight = document.body.clientHeight;
    }	
	
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
	    pageHeight = windowHeight;
    } else { 
	    pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){	
	    pageWidth = windowWidth;
    } else {
	    pageWidth = xScroll;
    }
    
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}

function browserWindowWH()
{
    if( typeof(window.innerWidth) == 'number') {
        //Non-IE
        browserWidth = window.innerWidth;
        browserHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        browserWidth = document.documentElement.clientWidth;
        browserHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        browserWidth = document.body.clientWidth;
        browserHeight = document.body.clientHeight;
    }
    var wh = browserWidth + "/" + browserHeight;
    return wh;   
}

function busyIndicatorPosition()
{
    var wh = browserWindowWH();
    var arrayWH = wh.split('/');
    var browserWidth = arrayWH[0];
    var browserHeight = arrayWH[1];
    var top = ((browserHeight / 2) - (busyIndicatorHeight / 2));
    var left = ((browserWidth / 2) - (busyIndicatorWidth / 2));
    document.getElementById("BusyIndicator").style.top = top + "px";
    document.getElementById("BusyIndicator").style.left = left + "px";
}

function showBusyIndicatorPosition()
{
    var wh = browserWindowWH();
    var arrayWH = wh.split('/');
    var browserWidth = arrayWH[0];
    var browserHeight = arrayWH[1];
    var top = ((browserHeight / 2) - (busyIndicatorHeight / 2));
    var left = ((browserWidth / 2) - (busyIndicatorWidth / 2));
    document.getElementById("BusyIndicator").style.top = top + "px";
    document.getElementById("BusyIndicator").style.left = left + "px";
    document.getElementById("BusyIndicator").style.display = 'block';
    //document.getElementById("shadeBg").style.display = 'block';
    
    var arrayPageSize = getPageSize();
    var objOverlay2 = document.getElementById('overlay');
    objOverlay2.style.height = (arrayPageSize[1] + 'px');
	objOverlay2.style.display = 'block';
}
function hideBusyIndicator()
{
    document.getElementById("BusyIndicator").style.display = 'none';
}
function clearTxtBoxesFromPathSearch()
{
    if(document.getElementById("txtPontoPartida")!= null)
    {
        document.getElementById("txtPontoPartida").value = "";
    }
    document.getElementById("txtPontoChegada").value = "";
}
function clearTxtBoxesFromSpotSearch()
{
    document.getElementById("txtLocal").value = "";
}
function errorMsgWindowType1(windowTitle, inputTxtLenght, txt1, txt2)
{    
    var posicaoPopUp = 0;
    var posicaoLeftPopUp = 0; 
    var browserWidth = 0;
    var browserHeight = 0;
    var wh = browserWindowWH();
    var arrayWH = wh.split('/');
    browserWidth = arrayWH[0];
    browserHeight = arrayWH[1];   
    var mapa_ctl = document.getElementById("mapaCTL").value;
    var textoTitulo = windowTitle;
    var textoCorpo = "";

    if (inputTxtLenght == 0)
    {
        textoCorpo = "<span>" + txt1 + "</span>";
        document.getElementById(mapa_ctl + "_programmaticPopup").style.width = "250px";
    }
    else
    {
        textoCorpo = "<span>" + txt2 + "</span>";
        document.getElementById(mapa_ctl + "_programmaticPopup").style.width = "350px";                
    }
    //SMALL POPUP
    posicaoPopUp = ((browserHeight / 2) - (smallPopUpHeight / 2));
    posicaoLeftPopUp = ((browserWidth / 2) - (smallPopUpWidth / 2)); 
    document.getElementById("popUpSIG").style.top = posicaoPopUp + "px";
    document.getElementById("popUpSIG").style.left = posicaoLeftPopUp + "px";
    document.getElementById("tituloPopUP").innerHTML = textoTitulo;
    document.getElementById("corpoPopUP").innerHTML = textoCorpo;
    document.getElementById("okButton").disabled = "true";
    document.getElementById(mapa_ctl + "_panelCorpoPopUP").style.height = "20px";
    ShowPopup();
}
function errorMsgWindowType2(windowTitle, txt1, windowWidth)
{
    if (typeof windowWidth == 'undefined' ) 
    {
        windowWidth = 350;
    }
    
    var posicaoPopUp = 0;
    var posicaoLeftPopUp = 0; 
    var browserWidth = 0;
    var browserHeight = 0;
    var wh = browserWindowWH();
    var arrayWH = wh.split('/');
    browserWidth = arrayWH[0];
    browserHeight = arrayWH[1];   
    var mapa_ctl = document.getElementById("mapaCTL").value;
    var textoTitulo = windowTitle;
    var textoCorpo = "";

    textoCorpo = "<span>" + txt1 + "</span>";
    document.getElementById(mapa_ctl + "_programmaticPopup").style.width = windowWidth + "px";

    //SMALL POPUP
    posicaoPopUp = ((browserHeight / 2) - (smallPopUpHeight / 2));
    posicaoLeftPopUp = ((browserWidth / 2) - (windowWidth / 2)); 
    document.getElementById("popUpSIG").style.top = posicaoPopUp + "px";
    document.getElementById("popUpSIG").style.left = posicaoLeftPopUp + "px";
    document.getElementById("tituloPopUP").innerHTML = textoTitulo;
    document.getElementById("corpoPopUP").innerHTML = textoCorpo;
    document.getElementById("okButton").disabled = "true";
    document.getElementById(mapa_ctl + "_panelCorpoPopUP").style.height = "20px";
    ShowPopup();
}
function listMsgWindowType1(title, txtBoby, responseTextHeight)
{
    var posicaoPopUp = 0;
    var posicaoLeftPopUp = 0; 
    var browserWidth = 0;
    var browserHeight = 0;
    var wh = browserWindowWH();
    var arrayWH = wh.split('/');
    browserWidth = arrayWH[0];
    browserHeight = arrayWH[1];   
    var mapa_ctl = document.getElementById("mapaCTL").value;
    //SMALL POPUP
    posicaoPopUp = ((browserHeight / 2) - (largePopUpHeight / 2));
    posicaoLeftPopUp = ((browserWidth / 2) - (largePopUpWidth / 2)); 
    document.getElementById("popUpSIG").style.top = posicaoPopUp + "px";
    document.getElementById("popUpSIG").style.left = posicaoLeftPopUp + "px";
    document.getElementById("tituloPopUP").innerHTML = title;
    document.getElementById("corpoPopUP").innerHTML = txtBoby;
    document.getElementById("okButton").disabled = "true";    
    //WINDOW MSG HEIGHT
    var tamanhoPanel = (responseTextHeight / 8)
    if (tamanhoPanel > 450)
    {
        tamanhoPanel = 400;
    }
    else
    {
        tamanhoPanel = 250;
    }
    document.getElementById(mapa_ctl + "_panelCorpoPopUP").style.height = tamanhoPanel + "px";
    document.getElementById(mapa_ctl + "_programmaticPopup").style.width = "700px";
    ShowPopup();
}
function clearSpotMarker(marker)
{
    if(!marker) 
    {
        //alert('Marker not exists');
        return false;
    }
    else
    {
        if(layerLocal != null)
        {
            layerLocal.removeMarker(marker);
            markerSpot = null;
            marker = null;
        }
    }
}
function clearOldStartMarker(marker)
{
    if(!marker) 
    {
        //alert('Marker not exists');
        return false;
    }
    else
    {
        if(layerPartida != null)
        {                       
            marker.unRegisterEvent('dragend', this, dragEndForStartPoint);
            layerPartida.removeMarker(marker);
            startMarker = null;
            marker = null;
        }
    }
}
function clearOldEndMarker(marker)
{
    if(!marker) 
    {
       //alert('Marker not exists');
        return false;
    }
    else
    {
        if(layerChegada != null)
        {             
            marker.unRegisterEvent('dragend', this, dragEndForEndPoint);
            layerChegada.removeMarker(marker);
            endMarker = null;
            marker = null;
        }
    }
}
//EVENTS FUNCTIONS
function dragEndForStartPoint()
{     
    //addMsg('dragend start');  
    var start = startMarker.getLonLat();
    addMsg(start.lat + "-" + start.lon + "<br>");
    longitudeGlobal = start.lon;
    latitudeGlobal = start.lat;
    //inserirPonto(0);
    var mapa_ctl = document.getElementById("mapaCTL").value; 
    startLegendHtml = localRes.jsInicioPercurso + "<br>" + latitudeGlobal + "<br>" + longitudeGlobal;        
    document.getElementById(mapa_ctl + "_txtCoord1").value = latitudeGlobal + '/' + longitudeGlobal;
    document.getElementById("txtPontoPartida").value = localRes.jsDefinidoNoMapa; 
}

function dragEndForEndPoint()
{ 
    //addMsg('dragend End');
    var end = endMarker.getLonLat();
    addMsg(end.lat + "-" + end.lon + "<br>");
    longitudeGlobal = end.lon;
    latitudeGlobal = end.lat;
    //inserirPonto(1);
    var mapa_ctl = document.getElementById("mapaCTL").value;
    endLegendHtml = localRes.jsFimPercurso + "<br>" + latitudeGlobal + "<br>" + longitudeGlobal;
    document.getElementById(mapa_ctl + "_txtCoord2").value = latitudeGlobal + '/' + longitudeGlobal;
    document.getElementById("txtPontoChegada").value = localRes.jsDefinidoNoMapa;
}

function AjaxGetData(url, responseHandler) 
{ 
	 if (window.XMLHttpRequest) 
	 { 
		 // browser has native support for XMLHttpRequest object 
		 req = new XMLHttpRequest(); 
	 } 
	 else if (window.ActiveXObject) 
	 { 
		 // try XMLHTTP ActiveX (Internet Explorer) version 
		 req = new ActiveXObject("Microsoft.XMLHTTP"); 
	 } 
	  
	 if(req) 
	 { 
		 req.onreadystatechange = responseHandler; 
		 req.open('GET', url, true); 
		 req.setRequestHeader("content-type","application/x-www-form-urlencoded"); 
		 req.send(''); 
	 } 
	 else 
	 { 
		 alert('Your browser does not seem to support XMLHttpRequest.'); 
	 } 
}

function HideContextMenu()
{
    var mapa_ctl = document.getElementById("mapaCTL").value;
    
    if(document.getElementById(mapa_ctl + "_kioskLonLat").value != "")
    {
        document.getElementById("contextMenuKiosk").style.display = 'none';
    }
    else
    {
        document.getElementById("contextMenu").style.display = 'none';
    }
    map.events.unregister('click', this, HideContextMenu);
}

function f_scrollTop() {
    return f_filterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function showContextMenu(e)
{
    var mapa_ctl = document.getElementById("mapaCTL").value;
    
    //SET GLOBAL LAT LON
    var lonlat = map.getLonLatFromContainerPixel(e.xy);
    latitudeGlobal = lonlat.lat;           
    longitudeGlobal = lonlat.lon;
    //CONTEXT MENU POS
    var posicaoTop;
    var posicaoLeft;
    posicaoTop = e.clientY + f_scrollTop();
    posicaoLeft = e.clientX;
    
    if(document.getElementById(mapa_ctl + "_kioskLonLat").value != "")
    {           
        document.getElementById("contextMenuKiosk").style.display = 'block';
        document.getElementById("contextMenuKiosk").style.top = posicaoTop + "px";
        document.getElementById("contextMenuKiosk").style.left = posicaoLeft + "px";
    }
    else
    {
        document.getElementById("contextMenu").style.display = 'block';
        document.getElementById("contextMenu").style.top = posicaoTop + "px";
        document.getElementById("contextMenu").style.left = posicaoLeft + "px";
    }
    map.events.register('click', this, HideContextMenu);
}

function setOverlay()
{
    var objBody = document.getElementsByTagName("body").item(0);
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '1050';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
}

function inicializarMapa(kyosk) {

    if (!kyosk)
        kyosk = false;    

    setOverlay();

    UrlBase = document.getElementById("UrlBase").value;
    isKyosk = kyosk;    
    var UrlBaseAjax = UrlBase + "DesktopModules/trp_homepage/";
//    if (isKyosk) {
//        UrlBaseAjax = UrlBase + "DesktopModules/trp_kyosk_homepage/";
//    } 
          
    mapaVisualizar = document.getElementById("mapaVisualizarOcorrencias").value;

    map = new SAPO.Maps.Map(mapaVisualizar); 
    map.addControl(new SAPO.Maps.Control.MapType());
    map.addControl(new SAPO.Maps.Control.Navigation());
    var mapCenter = new OpenLayers.LonLat(-9.143220, 38.723586);
    map.setMapCenter(mapCenter, 12);

    //SAPO MAP EVENTS
    //map.events.register('click', this, MouseHandler);
    map.events.register('zoomend', this, ZoomHandler);
    map.events.register('singlerightclick', this, showContextMenu);
    map.events.register('moveend', this, actualizaTemas);

    //SAPO LAYERS
    layerLocal = new SAPO.Maps.Markers();                
    map.addMarkers(layerLocal);
    layerPartida = new SAPO.Maps.Markers();                
    map.addMarkers(layerPartida);
    layerChegada = new SAPO.Maps.Markers();
    map.addMarkers(layerChegada);
    layerEstacoes = new SAPO.Maps.Markers();
    map.addMarkers(layerEstacoes);
    if (temas != null) {
        var tema = temas.split(',');
        for (nt = 0; nt < tema.length; nt++) {
            eval("layer_Temas" + tema[nt] + " = new OpenLayers.Layer.Vector(\"layerTemas" + tema[nt] + "\");");
            map.addLayer(eval("layer_Temas" + tema[nt]));
            
            eval("layerTemas" + tema[nt] + " = new SAPO.Maps.Markers();");
            map.layers[map.layers.length - 1].name = "layerTemas" + tema[nt];
            map.addMarkers(eval("layerTemas" + tema[nt]));
        }
    }

    //map = new VEMap(mapaVisualizar);            
    //map.LoadMap(new VELatLong(38.76907496033499, -9.296493530273434), 11);
    //map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);      
}

function atacharEvento(ponto)
{
    map.events.register('click', this, MouseHandler);
    //map.AttachEvent("onclick",MouseHandler);
    if (document.body.scrollTop > 300)
    {
        window.scrollTo(0,0);
    }    
    //ERROR in FF
    //document.getElementById(mapaVisualizar).childNodes[0].style.cursor = "pointer";   
    document.getElementById(mapaVisualizar).style.cursor = "pointer";
    contadorPixel = ponto;
}

function MouseHandler(e)      
{                
    if (e.type == "click")
    {         
        //SAPO MAP XY TO LON LAT
        var lonlat = map.getLonLatFromContainerPixel(e.xy);
        latitudeGlobal = lonlat.lat;           
        longitudeGlobal = lonlat.lon;
        inserirPonto(contadorPixel);
        //ERROR in FF
        //document.getElementById(mapaVisualizar).childNodes[0].style.cursor = "";  
        document.getElementById(mapaVisualizar).style.cursor = "";      
        contadorPixel = -1;
    }  
}      

function openPopupStart(marker)
{
     marker.openPopup(startLegendHtml);
}
function openPopupEnd(marker)
{
     marker.openPopup(endLegendHtml);
}
   
//ADD START and END POINT
function inserirPonto(ponto)
{    
    //CLEAR MARKER FROM "PESQUISA RÁPIDA"
    clearSpotMarker(markerSpot);
    
    if (ponto > -1)
    {
        var mapa_ctl = document.getElementById("mapaCTL").value;   
     	    
         if (ponto == 0)
         {           
            clearOldStartMarker(startMarker);
            //SAPO MAP    
            //ADD MARKER
            startMarker = new SAPO.Maps.Marker(new OpenLayers.LonLat(longitudeGlobal, latitudeGlobal), { draggable: true }, {label: localRes.jsInicio, labelColor: 'White', labelSize: '10', labelFont: 'Arial', labelAnchor: new OpenLayers.Pixel(0, -22), markerImage: 'DesktopModules/trp_calculo_percurso/imagens/spots.png', markerAnchor: new OpenLayers.Pixel(-20, -39), size: new OpenLayers.Size(39, 41) });          
            layerPartida.addMarker(startMarker); 
            startMarker.registerEvent('dragend', this, dragEndForStartPoint);                
            startMarker.registerEvent('click', this, openPopupStart);
                        
            startLegendHtml = localRes.jsInicioPercurso + "<br>" + latitudeGlobal + "<br>" + longitudeGlobal;        
            document.getElementById(mapa_ctl + "_txtCoord1").value = latitudeGlobal + '/' + longitudeGlobal;
            document.getElementById("txtPontoPartida").value = localRes.jsDefinidoNoMapa;             
         }
         else if (ponto == 1)
         {            
            clearOldEndMarker(endMarker);
            //SAPO MAP
            //ADD MARKER
            endMarker = new SAPO.Maps.Marker(new OpenLayers.LonLat(longitudeGlobal, latitudeGlobal), { draggable: true }, { label: localRes.jsFim, labelColor: 'White', labelSize: '10', labelFont: 'Arial', labelAnchor: new OpenLayers.Pixel(0, -22), markerImage: 'DesktopModules/trp_calculo_percurso/imagens/spots.png', markerAnchor: new OpenLayers.Pixel(-20, -39), size: new OpenLayers.Size(39, 41) });
            layerChegada.addMarker(endMarker);
            endMarker.registerEvent('dragend', this, dragEndForEndPoint);                
            endMarker.registerEvent('click', this, openPopupEnd);

            endLegendHtml = localRes.jsFimPercurso + "<br>" + latitudeGlobal + "<br>" + longitudeGlobal;
            document.getElementById(mapa_ctl + "_txtCoord2").value = latitudeGlobal + '/' + longitudeGlobal;
            document.getElementById("txtPontoChegada").value = localRes.jsDefinidoNoMapa;
         }            
    }
    // CONTEXT MENU HIDE
    document.getElementById("contextMenu").style.display = 'none';
    document.getElementById("contextMenuKiosk").style.display = 'none';
    map.events.unregister('click', this, MouseHandler);
}
 


function apagarLayer(layerID)
{
    var mapa_ctl = document.getElementById("mapaCTL").value;
    if (layerID == 0)
    {   
        //SAPO MAP
        //map.removeMarkers(layerPartida);
        //map.removeMarkers(layerLocal);
        //VE
        //layerPartida.DeleteAllShapes();
        document.getElementById(mapa_ctl + "_txtCoord1").value = "";
        
    }
    else
    {
        //SAPO MAP
        //map.removeMarkers(layerChegada);
        //map.removeMarkers(layerLocal);
        //VE
        //layerChegada.DeleteAllShapes();
        document.getElementById(mapa_ctl + "_txtCoord2").value = "";
    
    }
}

function ZoomHandler(e) {
    modoZoom = true;
    //zoom interval ?
    /*
    if (e.zoomLevel == 18)
    {
    map.SetZoomLevel(17);
    
    }
    else */
    if (e.zoomLevel <= 8) {
        map.SetZoomLevel(9);
    }
}

function zoomPonto(longitude,latitude)
{
    //SapoMapa
    var mapCenter = new OpenLayers.LonLat(longitude, latitude);
    map.setMapCenter(mapCenter, 13);
    //VE
    //map.SetCenterAndZoom(new VELatLong(latitude,longitude),17);
    if (document.body.scrollTop > 300)
    {
        window.scrollTo(0,150);
    }   
}

function checkLayer(layer, cat_id, estado, min_zoom) {

    var z = map.zoom;
    if (z >= min_zoom) {
        if (estado == true) {
            // pedir pois na bbox desta cat
            var bounds = map.getBounds();
            UrlBase = document.getElementById("UrlBase").value;
            var UrlBaseAjax = UrlBase + "DesktopModules/trp_homepage/";
            AjaxGetData(UrlBaseAjax + 'Ajax/trp_homepage.ashx?cmd=getTema&cat_id=' + cat_id + '&BBox1=' + bounds.bottom + '&BBox2=' + bounds.left + '&BBox3=' + bounds.top + '&BBox4=' + bounds.right + '&UrlBase=' + UrlBase, Temas_Callback);

            //alert('bounds: minlat:' + bounds.bottom + ' minlon:' + bounds.left + ' maxlat:' + bounds.right + ' maxLon:' + bounds.top);
        }
        else {
            // apagar pois deste layer
            eval(layer + ".removeMarkers()");
        }
    }
}

function Temas_Callback()
{
    if (req.readyState == 4 || req.readyState == 'complete') {
        var result = Trim(req.responseText);
        eval(result);
    }
}

function Estacoes_Add(est) {
    var result = Trim(est);
    eval(result);
}

function Trim(str) { return str.replace(/^\s+|\s+$/g, ""); }

function actualizaTemas() {
    var z = map.zoom;
    if (z > 10) {
        var zoomin = true;
        var bounds = map.getBounds();
        if (x1 > bounds.bottom || y1 > bounds.left || x2 < bounds.top || y2 < bounds.right) zoomin = false;
        var cat_ids = "";
        for (var i = 6; i < map.layers.length - 1; i++) {
            if (map.layers[i].name.substr(0, 3) == "lay") {
                var layer_id = map.layers[i].name.substr(10);
                var img = "img" + layer_id;
                if (document.getElementById(layer_id) != null) {
                    if (modoZoom == true) {
                        if (document.getElementById(layer_id).checked && document.getElementById(layer_id).value <= z && zoomin == false) {
                            cat_ids += "," + layer_id;
                        } else if (document.getElementById(layer_id).disabled && document.getElementById(layer_id).value <= z) {
                            document.getElementById(layer_id).disabled = "";
                            document.getElementById(img).src = "DesktopModules/trp_homepage/imagens/" + layer_id + ".gif";
                        } else if (document.getElementById(layer_id).disabled == "" && document.getElementById(layer_id).value > z) {
                            document.getElementById(layer_id).disabled = "true";
                            document.getElementById(img).src = "DesktopModules/trp_homepage/imagens/" + layer_id + "_0.gif";
                        }
                    } else {
                        if (document.getElementById(layer_id).checked && document.getElementById(layer_id).value <= z && zoomin == false) {
                            cat_ids += "," + layer_id;
                        }
                    }
                }
            }
        }
        if (cat_ids.length > 0) {
            cat_ids = cat_ids.substring(1);
            checkLayers(cat_ids);
        }
        x1 = bounds.bottom;
        y1 = bounds.left;
        x2 = bounds.top;
        y2 = bounds.right;
        modoZoom = false;
    }
}

function checkLayers(cat_id) {
    // pedir pois na bbox desta cat
    var bounds = map.getBounds();
    UrlBase = document.getElementById("UrlBase").value;
    var UrlBaseAjax = UrlBase + "DesktopModules/trp_homepage/";
    AjaxGetData(UrlBaseAjax + 'Ajax/trp_homepage.ashx?cmd=getTema&cat_id=' + cat_id + '&BBox1=' + bounds.bottom + '&BBox2=' + bounds.left + '&BBox3=' + bounds.top + '&BBox4=' + bounds.right + '&UrlBase=' + UrlBase, Temas_Callback);
}

function showPtoDescription(pto) {
    msg = document.getElementById(pto.feature.id).innerHTML;
    pto.openPopup(msg);
}

function showLayersPanel(id) {
    var Temaspanel = document.getElementById(id);
    if (Temaspanel.style.display == 'none') {
        Temaspanel.style.display = 'inline';
    }
    else {
        Temaspanel.style.display = 'none';
    }
}

function localizarLugar()
{
     //CLEAR MARKERS FROM "CÁLCULO PERCURSO"
     clearOldStartMarker(startMarker);
     clearOldEndMarker(endMarker);
     
     //CLEAR SPOT MARKER
     clearSpotMarker(markerSpot);
     
     clearTxtBoxesFromPathSearch();
     
     //Verifica se foi escolhida algum local para pesquisa     
     pesquisaAtual = 2;
     
     showBusyIndicatorPosition();
     
     var textLocal = document.getElementById("txtLocal").value;
          
     var posicaoPopUp = 0;
     var posicaoLeftPopUp = 0; 
     var browserWidth = 0;
     var browserHeight = 0;
     
     var mapa_ctl = document.getElementById("mapaCTL").value;
     UrlBase = document.getElementById("UrlBase").value;
     var UrlBaseAjax = UrlBase + "DesktopModules/trp_homepage/";
          
     if (textLocal.length < 3)
     {
        errorMsgWindowType1(localRes.jsAtencao, textLocal.length,  localRes.jsIndiqueLocalPesquisar, localRes.jsLocalPesquisarPeloMenos3Caracteres);               
        return;
     }                 
      
     AjaxGetData(UrlBaseAjax + 'Ajax/trp_homepage.ashx?cmd=pesquisarLugar&Lugar=' + textLocal+'&UrlBase=' + UrlBase, DoPesquisarLugar_Callback);
}

function DoPesquisarLugar_Callback()
{
    var mapa_ctl = document.getElementById("mapaCTL").value;
 
	//readyState of 4 or 'complete' represents  
	//that data has been returned
	if (req.readyState == 4 ||  req.readyState == 'complete') 
	{
        var pontoUnico = req.responseText.split('/');
        
        if (pontoUnico[0] == "coordenadas")
        {
            //Funcao que exibe o local
            document.getElementById(mapa_ctl + "_txtCoord").value = pontoUnico[1] + "/" + pontoUnico[2]; 
            document.getElementById("txtLocal").value = pontoUnico[3];
            VisualizarLocal();
            return;        
        }
        else if (req.responseText == "Erro")
        {
            errorMsgWindowType2(localRes.jsInformacao, localRes.jsNaoFoiPossivelEncontrarLocal);  
            return;    
        }
        else
        {            
            listMsgWindowType1(localRes.jsSeleccioneLocal, req.responseText, req.responseText.length)
            return;
        }
    }
}

function ShowPopup()
{
    //esconde os combobox e listbox
    var divPopUPSIG = document.getElementById('popUpSIG');
    hideBusyIndicator();
    divPopUPSIG.style.display='block';
    //document.getElementById("shadeBg").style.display = 'block';
    
    var arrayPageSize = getPageSize();
    var objOverlay2 = document.getElementById('overlay');
    objOverlay2.style.height = (arrayPageSize[1] + 'px');
	objOverlay2.style.display = 'block';
}


function ClosePopup()
{   
    var ctl = document.getElementById("mapaCTL").value;     
    var divPopUPSIG = document.getElementById('popUpSIG');
    divPopUPSIG.style.display='none';
    //document.getElementById("shadeBg").style.display = 'none';
    var objOverlay = document.getElementById('overlay');
	objOverlay.style.display = 'none';
    
}


function fecharPopUP()
{
    ClosePopup();
}  



function VisualizarRota(kyosk) {

    if (!kyosk)
        kyosk = false;  
    
    clearTxtBoxesFromSpotSearch();
    pesquisaAtual = 0;
    
    ClosePopup();
    showBusyIndicatorPosition();

    var mapa_ctl = document.getElementById("mapaCTL").value;
    
    var latInicial = "";
    var longInicial = "";
    
    var latFinal = "";
    var longFinal = "";
    
    var coordenadasIniciais = "";
    var coordenadasFinais = "";


    var kioskStartCoords = document.getElementById(mapa_ctl + "_kioskLonLat").value
    
    if (kyosk)//WEBSITE OPERATING AT KIOSK
    {
        coordenadasIniciais = kioskStartCoords;
        var partida = coordenadasIniciais.split('/');
        textPartida = partida[2];

    }
    else//WEBSITE OPERATING OUTSIDE KIOSK
    {
        coordenadasIniciais = document.getElementById(mapa_ctl + "_txtCoord1").value
        //Verifica se foi escolhida algum ponto de partida e ponto de chegada    
        textPartida = document.getElementById("txtPontoPartida").value;
    }
    
    
    /*    
    if(kioskStartCoords != "")//WEBSITE OPERATING AT KIOSK
    {
        coordenadasIniciais = kioskStartCoords;
        var partida = coordenadasIniciais.split('/');
        textPartida = partida[2];
    }
    else//WEBSITE OPERATING OUTSIDE KIOSK
    {   
        coordenadasIniciais = document.getElementById(mapa_ctl + "_txtCoord1").value   
        //Verifica se foi escolhida algum ponto de partida e ponto de chegada    
        textPartida = document.getElementById("txtPontoPartida").value;  
    }
    */
    coordenadasFinais = document.getElementById(mapa_ctl + "_txtCoord2").value
    
    //Verifica se foi escolhida algum ponto de partida e ponto de chegada    
    textChegada = document.getElementById("txtPontoChegada").value;

    if (!kyosk && textPartida.length < 3)
    {
        errorMsgWindowType1(localRes.jsAtencao, textPartida.length, localRes.jsIndiquePontoPartida, localRes.jsTextoPartidaPeloMenos3Caracteres);               
        return;
    }
    
    if (textChegada.length < 3)
    {
        errorMsgWindowType1(localRes.jsAtencao, textChegada.length, localRes.jsIndiquePontoChegada, localRes.jsTextoChegadaPeloMenos3Caracteres); 
        return;
    }
    
    //PATH CALCULATION DNN MODULE
    //var UrlBaseAjax = UrlBase + "DesktopModules/Emobility/";
    var UrlBaseAjax = UrlBase + "DesktopModules/trp_calculo_percurso/";
    
    
    if (coordenadasIniciais != "")//IF LAT and LONG ARE KNOWN
    {
        var coordenadas = coordenadasIniciais.split('/');
        latInicial = coordenadas[0];
        longInicial = coordenadas[1];           
    }
    else//GET LIST OF START POINTS FOR USER TO CHOOSE FROM
    {
        //SENDS REQUEST TO Ajax/ajax.ashx
        //THE RESPONSE IS HANDLED BY DoDefinirPontoPartida_Callback FUNCTION
        AjaxGetData(UrlBaseAjax + 'Ajax/trp_calculo_percurso.ashx?cmd=definirPontoPartida&PontoPartida=' + textPartida+'&UrlBase=' + UrlBase, DoDefinirPontoPartida_Callback);
        return;            
    }
    
    if (coordenadasFinais != "")//IF LAT and LONG ARE KNOWN
    {
        var coordenadas = coordenadasFinais.split('/');
        latFinal = coordenadas[0];
        longFinal = coordenadas[1];           
    }
    else//GET LIST OF END POINTS FOR USER TO CHOOSE FROM
    {
        //SENDS REQUEST TO Ajax/ajax.ashx
        //THE RESPONSE IS HANDLED BY DoDefinirPontoChegada_Callback FUNCTION
        AjaxGetData(UrlBaseAjax + 'Ajax/trp_calculo_percurso.ashx?cmd=definirPontoChegada&PontoChegada=' + textChegada +'&UrlBase=' + UrlBase, DoDefinirPontoChegada_Callback);
        return;
    }
    
    
    //var mapa_ctl = document.getElementById("mapaCTL").value;        
    //var pontoPartida=document.getElementById(mapa_ctl + "_txtCoord1").value;
    //var pontoChegada=document.getElementById(mapa_ctl + "_txtCoord2").value;
    
    
    var pontoPartida = coordenadasIniciais; 
    var pontoChegada = coordenadasFinais;
    
    pontoPartida = pontoPartida.replace(',','.').replace(',','.');
    pontoChegada = pontoChegada.replace(',','.').replace(',','.');
    

	//OPEN PAGE "CÁLCULO DE PERCURSO"    
    if (kyosk) {
        self.location.href = UrlBase + 'Default.aspx?tabid=207&partida=' + pontoPartida + '&chegada=' + pontoChegada + '&begin=' + textPartida + '&end=' + textChegada; 
    }else
	    self.location.href= UrlBase + 'Default.aspx?tabid=188&partida=' + pontoPartida + '&chegada=' + pontoChegada + '&begin=' + textPartida + '&end=' + textChegada; 
	//self.location.href= UrlBase + 'Default.aspx?tabid=188&partida=' + pontoPartida + '&chegada=' + pontoChegada + '&begin=' + document.getElementById("txtPontoPartida").value + '&end=' + document.getElementById("txtPontoChegada").value ;        
}

function DoDefinirPontoPartida_Callback() {

    var mapa_ctl = document.getElementById("mapaCTL").value;

	//readyState of 4 or 'complete' represents that data has been returned  
	if (req.readyState == 4 ||  req.readyState == 'complete') 
	{

        var pontoUnico = req.responseText.split('/');
        
        if (pontoUnico[0] == "coordenadas")
        {
            document.getElementById(mapa_ctl + "_txtCoord1").value = pontoUnico[1]+"/"+pontoUnico[2];
            VisualizarRota();
            return;        
        }
        else if (req.responseText == "Erro0")
        {
            errorMsgWindowType2(localRes.jsInformacao, localRes.jsNaoFoiPossivelDefinirPontoPartida); 
            return;           
        }
        else
        {
            listMsgWindowType1(localRes.jsSeleccionePontoPartida, req.responseText, req.responseText.length)
        }
    }
}     




function DoDefinirPontoChegada_Callback() {

    

    var mapa_ctl = document.getElementById("mapaCTL").value;    
	//readyState of 4 or 'complete' represents that data has been returned  
	if (req.readyState == 4 ||  req.readyState == 'complete') 
	{	
        //Verifica se foi encontrado somente um registo
        var pontoUnico = req.responseText.split('/');
        if (pontoUnico[0] == "coordenadas")
        {
            document.getElementById(mapa_ctl + "_txtCoord2").value = pontoUnico[1]+"/"+pontoUnico[2];
            VisualizarRota();
            return;        
        }
        else if (req.responseText == "Erro1")
        {
            errorMsgWindowType2(localRes.jsInformacao, localRes.jsNaoFoiPossivelDefinirPontoChegada); 
            return; 
        }
        else
        {
            listMsgWindowType1(localRes.jsSeleccionePontoChegada, req.responseText, req.responseText.length)
        }
    }
}


function seleccionarPontoInteresse(indicePonto, indiceRadio)
{
    var mapa_ctl = document.getElementById("mapaCTL").value;
    var coordenadas = document.getElementById("rdTexto_"+indiceRadio).value;
    document.getElementById("okButton").disabled='';
    var local = coordenadas.split("/");
    
    if (indicePonto == 2)
    {
        pesquisaAtual = 2;

        document.getElementById("txtLocal").value = local[2]; 
        document.getElementById(mapa_ctl + "_txtCoord").value = local[0] + "/" + local[1]; 
    }
    else if (indicePonto == 0)
    {
        pesquisaAtual = 0;
        document.getElementById("txtPontoPartida").value = local[2]; 
        document.getElementById(mapa_ctl + "_txtCoord1").value = local[0] + "/" + local[1]; 
    }
    else if (indicePonto == 1)
    {
         pesquisaAtual = 1;
         document.getElementById(mapa_ctl + "_txtCoord2").value = local[0] + "/" + local[1];  
         document.getElementById("txtPontoChegada").value = local[2]; 
    }
    
}


function VisualizarLocal(kyosk)
{
    //recupera as coordenadas do campo texto
    if (pesquisaAtual == 2)
    {
        hideBusyIndicator();
        
        var local = document.getElementById("txtLocal").value; 
        var mapa_ctl = document.getElementById("mapaCTL").value;
        var coordenadas = document.getElementById(mapa_ctl + "_txtCoord").value;
        var coordenada = coordenadas.split('/');
 
        //SapoMapa 
        markerSpot = new SAPO.Maps.Marker(new OpenLayers.LonLat(coordenada[1], coordenada[0]), {draggable: false, popupAnchor: new OpenLayers.Pixel(0,-39)}, {markerImage: 'DesktopModules/trp_homepage/imagens/spot.png', markerAnchor: new OpenLayers.Pixel(-20, -39), size: new OpenLayers.Size(39, 41)});
        var legend = local;
        markerSpot.registerEvent('click', this, function(marker){ marker.openPopup(legend);});  
        layerLocal.addMarker(markerSpot);
         
        zoomPonto(coordenada[1],coordenada[0]);
       
        fecharPopUP();
    }
    else
    {
        VisualizarRota(kyosk);
    }
}



