﻿//LAYOUT
var outerLayout;
var centerLayout;

//MAPA
var mapfiles = { mapserver1: "http://www.algarveacolhe.com/scripts/mapserv.exe?map=c:\\inetpub\\wwwroot\\ccdr_aae\\mapserver\\mapa.map",
    //mapserver1: "http://2703.algarvedigital.pt/mapserver.ashx?key=0805",
mapserver_ov: "http://www.algarveacolhe.com/scripts/mapserv.exe?map=c:\\inetpub\\wwwroot\\ccdr_aae\\mapserver\\nav.map&mode=map"
    //mapserver_ov: "http://2703.algarvedigital.pt/mapserver.ashx?key=0805_nav"
}


var extents = { maxExtent: new OpenLayers.Bounds(-78927, -302406, 67703, -235308),
    restrictedExtent: new OpenLayers.Bounds(-78927, -302406, 67703, -235308),
    maxExtent_ov: new OpenLayers.Bounds(-78927, -302406, 67703, -235308)
}

var ZOOM_LEVEL_POI = 8;
var ZOOM_LEVEL_PLACE = 5;
var MAP_COORD_SYS = '27492';
var MAPSERVER_SELECTION = false;

var map, controls, wkt_trans, controlHighlight, controlSelect;
var style_mark, style_mark_sel, style_mark_lotes;
var currentPixelPos;
var selectionParams = { streetid: "-1", planoid: "-1", codconc: "-1" };

var layoutSettings_Outer = {
	    west: {
	        size: 250
			, onopen: function() { map.updateSize(); }
		    , onclose: function() { map.updateSize(); }
	        , onresize: function() { map.updateSize(); }
	    }
};


$(document).ready(function() {

    $.localise('script/i18n', { language: $("#language").val(), loadBase: true });
    $("#lbl_lingua").html(str_lingua);

    outerLayout = $('body').layout({ applyDefaultStyles: true
        , north__size: 80
        , north__minSize: 80
        , north__maxSize: 80
        , west__size: 290
        , west__minSize: 250
        , west__maxSize: 350
        , west__onresize: function() { $("#pesquisaAAE").accordion("resize"); }
        , west__onopen: function() { $("#pesquisaAAE").accordion("resize"); }
        , east__size: 250
        , east__minSize: 250
        , east__maxSize: 280
        , east__onresize: function() { $("#infoAAE").accordion("resize"); }
        , east__onopen: function() { $("#infoAAE").accordion("resize"); }
        , center__onresize: function() {
            map.updateSize();
        }
        , center__onresize: "centerLayout.resizeAll"
        , east__initClosed: true
    });

    centerLayout = $('div.ui-layout-center').layout({
        //minSize: 100	// ALL panes      
        north__paneSelector: ".center-north"
	    , center__paneSelector: ".center-center"
	    , south__paneSelector: ".center-south"
        //, south__size: 100
    });




    if (map != null) {
        map.zoomToMaxExtent();
    }

    // ACCORDION - in the West pane
    $("#pesquisaAAE").accordion({
        fillSpace: true
    });

    // ACCORDION - in the East pane
    $("#infoAAE").accordion({
        fillSpace: true
    });

    $('#dialogTest').dialog({ autoOpen: false, title: "Informação" });

    $("#btnOrtos").click(
	    function() {

	        var l = map.getLayer("ol_layer_mapserver1");
	        var layers = "";

	        if (l != null) {

	            if (l.params["layers"].match("aae") != null) layers = "aae";

	            if ($(this).hasClass("ui-state-active")) {
	                $(this).removeClass("ui-state-active");
	            } else {
	                $(this).addClass("ui-state-active");

	                layers = layers + " orto2007";
	            }

	            l.params["layers"] = layers;
	            l.redraw();

	        }

	        return false;

	    });

    $("#btnAAE").addClass("ui-state-active");
    $("#btnAAE").click(
	    function() {

	        var l = map.getLayer("ol_layer_mapserver1");
	        var layers = "";

	        if (l != null) {

	            if (l.params["layers"].match("orto2007") != null) layers = "orto2007";

	            if ($(this).hasClass("ui-state-active")) {
	                $(this).removeClass("ui-state-active");
	            } else {
	                $(this).addClass("ui-state-active");

	                layers = layers + " aae";
	            }

	            l.params["layers"] = layers;
	            l.redraw();

	        }

	        return false;

	    });


    $("#infoDisponibilidade").dialog({ autoOpen: false });

});

function initMap() {

    var options = {
        projection: new OpenLayers.Projection("EPSG:27492"),
        displayProjection: new OpenLayers.Projection("EPSG:27492"),
        units: "m",
        numZoomLevels: 18,
        maxResolution: 300,
        minResolution: 0.05,
        maxExtent: extents["maxExtent"],
        restrictedExtent: extents["restrictedExtent"]
    };


    //Simbologia
    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style.strokeWidth = 1;
    layer_style.fillOpacity = 0;

    var layer_style_aae = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style_aae.strokeWidth = 5;
    layer_style_aae.fillOpacity = 0;
    layer_style_aae.strokeOpacity = 0;


    /*
    * Mark style
    */
    style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_mark.strokeWidth = 1;
    style_mark.graphicWidth = 19;
    style_mark.graphicHeight = 22;
    style_mark.graphicXOffset = -(style_mark.graphicWidth / 2);  // this is the default value
    style_mark.graphicYOffset = -style_mark.graphicHeight;
    style_mark.externalGraphic = "/Content/images/map/poi_search2.gif";
    style_mark.fillOpacity = 0.8;

    /*
    * Mark style
    */
    style_mark_sel = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_mark_sel.strokeWidth = 1;
    style_mark_sel.strokeColor = "blue";
    style_mark_sel.graphicWidth = 19;
    style_mark_sel.graphicHeight = 22;
    style_mark_sel.graphicXOffset = -(style_mark.graphicWidth / 2);  // this is the default value
    style_mark_sel.graphicYOffset = -style_mark.graphicHeight;
    style_mark_sel.externalGraphic = "Content/images/map/poi_search_selected.gif";
    style_mark_sel.fillOpacity = 0;

    /*
    * Mark style
    */
    style_mark_lotes = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_mark_lotes.strokeWidth = 3;
    style_mark_lotes.strokeColor = "yellow";
    style_mark_lotes.graphicWidth = 19;
    style_mark_lotes.graphicHeight = 22;
    style_mark_lotes.graphicXOffset = -(style_mark.graphicWidth / 2);  // this is the default value
    style_mark_lotes.graphicYOffset = -style_mark.graphicHeight;
    style_mark_lotes.externalGraphic = "/Content/images/map/poi_search_selected.gif";
    style_mark_lotes.fillOpacity = 0;    

    // Fim de Simbologia ----------------------------------------------------------------------

    OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
        defaultHandlerOptions: {
            'single': true,
            'double': false,
            'pixelTolerance': 0,
            'stopSingle': false,
            'stopDouble': false
        },

        initialize: function(options) {
            this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
            OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    );
            this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.onClick,
                            'dblclick': this.onDblclick
                        }, this.handlerOptions
                    );
        },

        onClick: function(evt) {
            var pnt = map.getLonLatFromPixel(new OpenLayers.Pixel(evt.xy.x, evt.xy.y));

            try {
                if (map.getControlsBy("id", "ctrlGetCoordinates")[0].active) {
                    DoTransformCoordinates(pnt.lon, pnt.lat);
                }
            }
            catch (err) { };

            try {
                if (map.getControlsBy("id", "ctrlGetInfo")[0].active) {
                    DoGetInfo(pnt.lon, pnt.lat);
                }
            }
            catch (err) { };

        },

        onDblclick: function(evt) {
            var output = document.getElementById(this.key + "Output");
            var msg = "click " + evt.xy;
            alert(msg);
        }

    });


    map = new OpenLayers.Map('map', options);

    map.events.register("mousemove", map, function(e) {
        currentPixelPos = new OpenLayers.Pixel(e.xy.x, e.xy.y);
    });

    map.addControl(new OpenLayers.Control.LoadingPanel());

    wkt_trans = new OpenLayers.Format.WKT({
        'internalProjection': map.projection,
        'externalProjection': map.projection
    });


    var layer = new OpenLayers.Layer.MapServer("mapserver1",
                      mapfiles["mapserver1"],
                    { layers: "aae", map_imagetype: "jpeg" },
                    { singleTile: true, transitionEffect: 'resize' },
                    { gutter: 15 });

    layer.id = "ol_layer_mapserver1";
    layer.isBaseLayer = true;
    layer.mergeNewParams(selectionParams);

    var vector = new OpenLayers.Layer.Vector("edition");
    vector.events.register('featureadded', vector, function(e) {
        var v = new Array();

        if (this.features.length > 1) {
            for (var i = 0; i < this.features.length - 1; i++) {
                v[i] = this.features[i];
            }

            this.removeFeatures(v);
        }

        if (this.features != null && this.features.length > 0) {

            ctrl = map.getControlsBy("id", "ctrlCreatePolygon")[0];
            if (ctrl.active) {
                ctrl.deactivate();

                ctrl = map.getControlsBy("id", "ctrlModifyPolygon")[0];
                ctrl.activate();
            }
        }

    });
    vector.events.register('beforefeaturemodified', vector, onBeforeFeatureModified);


    var aaes = new OpenLayers.Layer.Vector("aaes", { style: layer_style_aae });
    var features = new OpenLayers.Layer.Vector("features", { style: layer_style });

    //ADICIONAR OS LAYERS AO MAPA
    map.addLayers([layer, vector, aaes, features]);
    //map.addLayers([layer]);

    controlHighlight = new OpenLayers.Control.SelectFeature([aaes, features, vector], {
        hover: true,
        highlightOnly: true,
        renderIntent: "temporary",
        eventListeners: {
            //beforefeaturehighlighted: onFeatureHighlight,
            featurehighlighted: onFeatureHighlight,
            featureunhighlighted: onFeatureUnhighlight
        }
    });

    controlSelect = new OpenLayers.Control.SelectFeature(
        [aaes, features, vector],
        {
            multiple: false,
            hover: false,
            //toggleKey: "ctrlKey", // ctrl key removes from selection
            //multipleKey: "shiftKey" // shift key adds to selection
            onSelect: onFeatureSelect,
            onUnselect: onFeatureUnselect
        }
    );


    // Construct overview map with non-default projection, units, and extent
    var layer_ov = new OpenLayers.Layer.MapServer("mapserver_ov", mapfiles["mapserver_ov"]);

    var ov_options = {
        layers: [layer_ov],
        minRatio: 16,
        maxRatio: 64,
        size: new OpenLayers.Size(120, 80),
        mapOptions: {
            projection: "EPSG:27492",
            units: 'm',
            numZoomLevels: 1,
            restrictedExtent: new OpenLayers.Bounds(-78927, -302406, 67703, -235208),
            maxExtent: extents["maxExtent_ov"]
        }
    };

    var overview = new OpenLayers.Control.OverviewMap(ov_options)
    map.addControl(overview);
    overview.maximizeControl();

    map.addControl(new OpenLayers.Control.MousePosition(
                { div: document.getElementById("position"),
                    numDigits: 2, prefix: "xy: "
                }));
                                                
    map.addControl(new OpenLayers.Control.ScaleLine());
    map.addControl(controlSelect);


    map.addControl(controlHighlight);
    map.addControl(controlSelect);

    var history = new OpenLayers.Control.NavigationHistory();
    history.previous.title = str_vista_anterior;
    history.next.title = str_proxima_vista;
    map.addControl(history);

    //CONTROLOS
    var panel = new OpenLayers.Control.Panel({
        id: "ctrlPanel",
        div: document.getElementById("toolbarButtons")
    });


    controls = [
        new OpenLayers.Control.ZoomBox({
            id: "ctrlZoomBoxIn",
            title: str_aproximar,
            cursorClass: "olControlZoomInBoxCursor"
        }),
        new OpenLayers.Control.ZoomBox({
            id: "ctrlZoomBoxIn",
            title: str_afastar,
            displayClass: "olControlZoomOutBox",
            out: true,
            cursorClass: "olControlZoomOutBoxCursor",
            handlerOptions: { cursorClasses: { 'startBox': 'crossHair', 'endBox': 'olControlZoomOutBoxCursor'} }
        }),
        new OpenLayers.Control.DragPan({
            id: "ctrlPan",
            title: str_mover,
            cursorClass: "olControlDragPanCursor",
            handlerOptions: { cursorClasses: { 'mousedown': 'dragMouseDown', 'mouseup': 'dragMouseUp'} }
        }),
        history.previous,
        history.next,
        new OpenLayers.Control.ZoomToMaxExtent({
            id: "ctrlZoomMaxExtent",
            title: str_ver_tudo,
            displayClass: "olControlZoomAll"
        }),
        new OpenLayers.Control.Measure(
            OpenLayers.Handler.Path,
            { id: "ctrlMeasureLine",
                title: str_medir_distancia,
                displayClass: 'olControlMeasureLine',
                persist: true,
                handlerOptions: { persist: true },
                eventListeners: ({
                    "measure": handlerMeasurements,
                    "measurepartial": handlerMeasurements
                })
            }),
        new OpenLayers.Control.Measure(
            OpenLayers.Handler.Polygon,
            { id: "ctrlMeasureArea",
                title: str_medir_area,
                displayClass: 'olControlMeasureArea',
                persist: true,
                handlerOptions: { persist: true },
                eventListeners: ({
                    "measure": handlerMeasurements,
                    "measurepartial": handlerMeasurements
                })
            }),
        new OpenLayers.Control.DrawFeature(
            vector,
            OpenLayers.Handler.Polygon,
            {
                id: "ctrlCreatePolygon",
                title: str_desenhar_elemento,
                cursorClass: 'crossHair',
                displayClass: 'olControlDrawPolygon'
            }),
        new OpenLayers.Control.ModifyFeature(
            vector,
            {
                id: "ctrlModifyPolygon",
                title: str_modificar_elemento,
                displayClass: 'olControlModifyPolygon',
                mode: OpenLayers.Control.ModifyFeature.RESHAPE |
                OpenLayers.Control.ModifyFeature.ROTATE |
                //OpenLayers.Control.ModifyFeature.RESIZE
                OpenLayers.Control.ModifyFeature.DRAG
            }),
        new OpenLayers.Control.Button({
            id: "ctrlClearMap",
            title: str_limpar_mapa,
            displayClass: "olControlClearMap",
            trigger: clearMap
        })
    ];

    panel.addControls(controls);


    //Register Control Events
    var ctrl = null;


    //Control: ModifyPolygon
    ctrl = panel.getControlsBy("id", "ctrlModifyPolygon");
    ctrl[0].events.register("activate", ctrl[0], function(e) {
        controlSelect.deactivate();

        if (this.layer.features != null && this.layer.features.length > 0) {
            var ctrl = null;

            ctrl = this.map.getControlsBy("id", "ctrlCreatePolygon")[0];
            ctrl.deactivate();

            //this.selectControl.select.apply(this.selectControl,[fea])
            this.selectControl.select(this.layer.features[0]);
        }

    });
    ctrl[0].events.register("deactivate", ctrl[0], function(e) {
        controlSelect.activate();
    });


    //Adicionar Painel ao Mapa
    map.addControl(panel);

    controlHighlight.activate();
    controlSelect.activate();

    map.events.register("zoomend", map, function() {
        try {
            document.getElementById("txtScale").value = Math.round(map.getScale());
        } catch (ex) { }
    });

    map.fractionalZoom = true;

    if (map != null) {
        if (document.getElementById("concelho").value != null && document.getElementById("concelho").value != "") {
            pesquisa_ddl_concelho_onchange();
        } else {
            map.zoomToMaxExtent();
        }

        var url = "services.aspx";

        $.getJSON(url, null, DoLoadAAEGeometries_CallBack);        
    }

}




function checkboxGroup(elem, elemIdUncheck) {
    var chk = document.getElementsByName(elem.name);
    var chkValue = elem.checked;

    if (elemIdUncheck == null) {
        for (i = 0; i < chk.length; i++) chk[i].checked = false;
    } else {
        document.getElementById(elemIdUncheck).checked = false;
    }

    elem.checked = chkValue;
}

function handlerMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var out = "";

    var element = document.getElementById('output');

    if (order == 1) {
        out += "distância: " + measure.toFixed(3) + " " + units;
    } else {
        out += "área: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
    }
    element.innerHTML = out;
}


function Toggle(node) {

    var ss = node;


    //var n = Utils.getNextSiblingByTag(node, "DIV");
    var n = $(node).parent().find("div:first");
    var img = $(node).parent().find("img:first");

    if ($(n).css("display") != "none") {
        $(n).css("display", "none");

        //var img = $j(node).parent().find("img:first");

        img.attr("src", "/Content/images/page/node_openen.gif");

        //        // Change the image (if there is an image)
        //        if (node.childNodes.length > 0) {
        //            if (node.childNodes.item(0).nodeName == "IMG") {
        //                node.childNodes.item(0).src = "images/page/plus.gif";
        //            }
        //        }
    } else {
        $(n).css("display", "block");

        img.attr("src", "/Content/images/page/node_closed.gif");


        //        // Change the image (if there is an image)
        //        if (node.childNodes.length > 0) {
        //            if (node.childNodes.item(0).nodeName == "IMG") {
        //                node.childNodes.item(0).src = "images/page/minus.gif";
        //            }
        //        }
    }

    try {
        event.returnValue = false;
        event.cancelBubble = true;
    }
    catch (ex) { }

    return false;
}


function btnTemas_activate() {
    if (!$("#btnOrtos").hasClass("ui-state-active")) {
        $("#btnOrtos").addClass("ui-state-active");
    }
    if (!$("#btnAAE").hasClass("ui-state-active")) {
        $("#btnAAE").addClass("ui-state-active");
    }    

    if (map.getLayer("ol_layer_mapserver1") != null) {
        map.getLayer("ol_layer_mapserver1").params["layers"] = "orto2007 aae";
    }
}


function DoShowReportLoteAAE(gid) {

    var lang = getCurrentLanguage();

    var url = "report.aspx?tipo=2&id=" + gid + "&lang=" + lang;
}

function DoShowReportAEE(id) {

    var lang = getCurrentLanguage();

    var url = "report.aspx?tipo=1&id=" + id + "&lang=" + lang;

    window.open(url);
}

function DoShowAcessibilidades() {
    if ($('#info_acessibilidades').dialog('isOpen') == undefined)
    {
        $('#info_acessibilidades').dialog();
    } else {
        $('#info_acessibilidades').dialog('open');
    }
}

function DoLoadAAEGeometries_CallBack(data) {

    if (data != null) {

        var layer = map.getLayersByName("aaes")[0];

        $.each(data, function(i, item) {

            var feature = wkt_trans.read(item[2]);

            if (feature != null && feature != undefined) {

                var popupHTML = "<div style='color: #0078AE; font-weight: bold; margin-top: 10px; margin-left: 5px; margin-right: 5px;'>";
                popupHTML += item[0] + " - " + item[1] + "</div>";
                popupHTML += "<div style='text-align: center; margin-top: 20px; margin-bottom: 10px;'>";
                popupHTML += "<a href='#' class='ui-state-default ui-corner-all button' onclick='DoShowAEEInfoSimple(\"" + item[0] + "\"); outerLayout.open(\"east\");'>" + str_ver_informacao + "</a>";
                popupHTML += "</div>";


                feature.data = { tipo: "aae",
                    html: popupHTML
                };

                layer.addFeatures(feature);
            }
        });
    }

}



function getCurrentLanguage() {
    var lang = "";

    if (document.getElementById("language") != null && document.getElementById("language").value != "") {
        lang = document.getElementById("language").value
    }

    return lang;
}
function selectCurrentLanguage(lang) {
    if (document.getElementById("language") != null) {
        document.getElementById("language").value = lang;

        document.form1.submit();
    }

    return false;
}
function setCurrentLanguage() {
    var lang = document.getElementById("language").value;

    var obj = document.getElementById("imgLang-" + lang);

    if (obj != null) {
        obj.className = "languageAreaImageSelected";
    }

}

function doWaitingSearch(controlId) {
    $("#" + controlId).html($("#tmpLoadingBar").html());
}