﻿var outerLayout, innerLayout;

var map, controls, wkt_trans, controlHighlight, controlSelect;

var style_mark, style_mark_sel;

var currentPixelPos;

var selectionParams = { streetid: "-1", planoid: "-1" };

var planos = null;

/*#######################
* INNER LAYOUT SETTINGS
*#######################
*
* These settings are set in 'list format' - no nested data-structures
* Default settings are specified with just their name, like: fxName:"slide"
* Pane-specific settings are prefixed with the pane name + 2-underscores: north__fxName:"none"
*/
layoutSettings_Inner = {
    applyDefaultStyles:				false // basic styling for testing & demo purposes
,	fxName:							"slide" // do not confuse this with "slidable" option!
,	fxSpeed:						"slow"
,	north__fxName:					"none"
,	south__fxName:					"none"
,	spacing_closed:					0
,   north__spacing_open:            0
,   south__spacing_open:            0
, initClosed: false
};

/*
*#######################
* OUTER LAYOUT SETTINGS
*#######################
*
* This configuration illustrates how extensively the layout can be customized
* ALL SETTINGS ARE OPTIONAL - and there are more available than shown below
*
* These settings are set in 'json format' - ALL data must be in a nested data-structures
* All default settings (applied to all panes) go inside the defaults:{} key
* Pane-specific settings go inside their keys: north:{}, south:{}, center:{}, etc
*/
var layoutSettings_Outer = {
    name: "outerLayout" // NO FUNCTIONAL USE, but could be used by custom code to 'identify' a layout
    // options.defaults apply to ALL PANES - but overridden by pane-specific settings
	    , defaults: {
	        size: "auto"
		    , minSize: 50
		    , paneClass: "pane" 		// default = 'ui-layout-pane'
		    , resizerClass: "resizer"	// default = 'ui-layout-resizer'
		    , togglerClass: "toggler"	// default = 'ui-layout-toggler'
		    , buttonClass: "button"	// default = 'ui-layout-button'
		    , contentSelector: ".content"	// inner div to auto-size so only it scrolls, not the entire pane!
		    , contentIgnoreSelector: "span"		// 'paneSelector' for content to 'ignore' when measuring room for content
		    , togglerLength_open: 35			// WIDTH of toggler on north/south edges - HEIGHT on east/west edges
		    , togglerLength_closed: 35			// "100%" OR -1 = full height
		    , hideTogglerOnSlide: true		// hide the toggler when pane is 'slid open'
		    , togglerTip_open: "Close This Pane"
		    , togglerTip_closed: "Open This Pane"
		    , resizerTip: "Resize This Pane"
		    , fxName: "slide"		// none, slide, drop, scale
		    , fxSpeed: "slow"		// slow, normal, fast, 1000, nnn		    
	    }
	    , north: {
	        spacing_open: 0			// cosmetic spacing
		    , togglerLength_open: 0			// HIDE the toggler button
		    , togglerLength_closed: -1			// "100%" OR -1 = full width of pane
		    , resizable: false
		    , slidable: false
		    , fxName: "none"
	    }
	    , south: {
	        spacing_open: 0			// cosmetic spacing
		    , togglerLength_open: 0			// HIDE the toggler button
		    , togglerLength_closed: -1			// "100%" OR -1 = full width of pane
		    , resizable: false
		    , slidable: false
		    , fxName: "none"
	    }
	    , west: {
	        size: 250
		    , spacing_closed: 21			// wider space when closed
		    , togglerLength_closed: 21			// make toggler 'square' - 21x21
		    , togglerAlign_closed: "top"		// align to top of resizer
		    , togglerLength_open: 0			// NONE - using custom togglers INSIDE west-pane
		    , togglerTip_open: "Fechar painel"
		    , togglerTip_closed: "Abrir painel"
		    , resizerTip_open: "Redimensionar painel"
		    , sliderTip: "Expandir painel"
		    , slideTrigger_open: "Click" 	// default
			, onopen: function() { map.updateSize(); }
		    , onclose: function() { map.updateSize(); }
	        , onresize: function() { map.updateSize(); }
	    }
	    , east: {
	        size: 270
		    , spacing_closed: 21			// wider space when closed
		    , togglerLength_closed: 21			// make toggler 'square' - 21x21
		    , togglerAlign_closed: "top"		// align to top of resizer
		    , togglerLength_open: 0 			// NONE - using custom togglers INSIDE east-pane
		    , togglerTip_open: "Fechar painel"
		    , togglerTip_closed: "Abrir painel"
		    , resizerTip_open: "Redimensionar panel"
		    , sliderTip: "Expandir painel"
		    , slideTrigger_open: "Click"
			, onopen: function() { map.updateSize(); }
		    , onclose: function() { map.updateSize(); }
	        , onresize: function() { map.updateSize(); }
	    }
	    , center: {
	        paneSelector: "#mainContent" 			// sample: use an ID to select pane instead of a class
		    , onresize: "innerLayout.resizeAll"	// resize INNER LAYOUT when center pane resizes
	    }
};


$j(document).ready(function() {
    // create the OUTER LAYOUT
    outerLayout = $j("body").layout(layoutSettings_Outer);

    // save selector strings to vars so we don't have to repeat it
    // must prefix paneClass with "body > " to target ONLY the outerLayout panes
    var westSelector = "body > .ui-layout-west"; // outer-west pane
    var eastSelector = "body > .ui-layout-east"; // outer-east pane

    //    // CREATE SPANs for pin-buttons - using a generic class as identifiers
    //    $j("<span></span>").addClass("pin-button").prependTo(westSelector);
    //    $j("<span></span>").addClass("pin-button").prependTo(eastSelector);
    //    // BIND events to pin-buttons to make them functional
    //    outerLayout.addPinBtn(westSelector + " .pin-button", "west");
    //    outerLayout.addPinBtn(eastSelector + " .pin-button", "east");

    // CREATE SPANs for close-buttons - using unique IDs as identifiers
    $j("<span></span>").attr("id", "west-closer").prependTo(westSelector);
    $j("<span></span>").attr("id", "east-closer").prependTo(eastSelector);
    // BIND layout events to close-buttons to make them functional
    outerLayout.addCloseBtn("#west-closer", "west");
    outerLayout.addCloseBtn("#east-closer", "east");

    /* Create the INNER LAYOUT - nested inside the 'center pane' of the outer layout */
    innerLayout = $j(outerLayout.options.center.paneSelector).layout(layoutSettings_Inner);

    // DEMO HELPER: prevent hyperlinks from reloadin page when 'base.href' is set
    $j("a").each(function() {
        var path = document.location.href;
        if (path.substr(path.length - 1) == "#") path = path.substr(0, path.length - 1);
        if (this.href.substr(this.href.length - 1) == "#") this.href = path + "#";
    });



    panels = { "legend": new Panel("legend", true, "", function() { $("#sidebar").css("background-color", "white"); $("#img_legend").attr("src", gMC.legendImageUrl); }),
        "help": new Panel("help", true, "", null),
        "coordinates": new Panel("coordinates", true, "", null)
    }

    var lang = getCurrentLanguage();

    $j("#txtScale").bind("onkeypress", function(e) { return txtScale_onKeyPress(this, e); });
    $j("#btnZoomScale").bind("click", function(e) { DoZoomScale(); });

    $j("#loading").css("display", "none");
    $j("#taskbar").css("visibility", "visible");

    //Inicializar o Mapa
    initMap();

    if (map != null) {
        $j.post("toc.aspx", { id: "", lang: lang }, showTOC_CallBack);

        //Carregar Planos

        var urlPlanos = "/App_Resource/Geo.Plugins/Geo.Plugins.Ajax.ajaxPlanos.aspx";

        $j.getJSON(urlPlanos, null, loadPlanos_CallBack);

        map.zoomToMaxExtent();
    }

    var panel = $j(document).getUrlParam("panel");

    if (panel != null) {
        var plano = $j(document).getUrlParam("plano");

        if (plano != null) {
            showPanel("", { id: panel, plano: plano }, 'west');
        } else {
            showPanel(panel, null, 'west');
        }
    }

    $j('#dialogTest').dialog({ autoOpen: false, title: "Informação" });    

});

function initMap() {

    /*var options = {
        projection: new OpenLayers.Projection("EPSG:27492"),
        displayProjection: new OpenLayers.Projection("EPSG:27492"),
        units: "m",
        //numZoomLevels: 18,
        //maxResolution: 300000,
        //minResolution: 0.05,          
        resolutions: [19.529409975722047, 9.7647049878610233, 4.8823524939305116, 2.4411762469652558, 1.2205881234826279, 0.61029406174131395, 0.30514703087065698, 0.15257351543532849, 0.076286757717664244, 0.038143378858832122, 0.019071689429416061, 0.0095358447147080305, 0.0047679223573540153, 0.0023839611786770076, 0.0011919805893385038, 0.00059599029466925191, 0.00029799514733462595, 0.00014899757366731298, 7.4498786833656488e-05, 3.7249393416828244e-05],
        maxExtent: new OpenLayers.Bounds(-20005.146483135464, -290001.5363936595, 3994.992759951474, -270001.21359415055)
        //maxExtent: new OpenLayers.Bounds(-76927.90625, -300406.15625, 65703.9296875, -237308.71875)
    };*/

    var options = {
        projection: new OpenLayers.Projection("EPSG:27492"),
        displayProjection: new OpenLayers.Projection("EPSG:27492"),
        units: "m",
        numZoomLevels: 18,
        maxResolution: 300,
        minResolution: 0.05,
        //maxExtent: new OpenLayers.Bounds(7500, -301500, 32000,  -279000),
		maxExtent: extents["maxExtent"],
		//restrictedExtent: new OpenLayers.Bounds(7500, -301500, 32000,  -279000)
		restrictedExtent: extents["restrictedExtent"]
    };

    //Simbologia
    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style.strokeWidth = 5;
    layer_style.fillOpacity = 0;

    var layer_style_planos = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style_planos.strokeWidth = 5;
    layer_style_planos.fillOpacity = 0;
    layer_style_planos.strokeOpacity = 0;         
    

    /*
    * Mark style
    */
    style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_mark.strokeWidth = 3;
    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 = "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 = 5;
    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 = "images/map/poi_search_selected.gif";
    style_mark_sel.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
    });                

    //TODO: ler a definição dos layers a partir do TOC
    //var layertc = new OpenLayers.Layer.TileCache("ortostc2007",
    //    //"http://localhost/tilecache/tilecache.py?", {layers: 'ortos2007', format: 'image/jpeg' } );	
	//	["http://localhost/tilecache/cache"], "ortos2007", { format: 'image/jpeg' });
    //layertc.id = "ol_layer_ortos2007";
    //layertc.isBaseLayer = true;    
        
    var layer = new OpenLayers.Layer.MapServer("mapserver1",
                      mapfiles["mapserver1"],                    
                    { layers: "orto2007", 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 planos = new OpenLayers.Layer.Vector("planos", { style: layer_style_planos });
    var features = new OpenLayers.Layer.Vector("features", { style: layer_style });
			
    //ADICIONAR OS LAYERS AO MAPA
    map.addLayers([layer, vector, planos, features]);

    controlHighlight = new OpenLayers.Control.SelectFeature([planos, features, vector], {
        hover: true,
        highlightOnly: true,
        renderIntent: "temporary",
        eventListeners: {
            //beforefeaturehighlighted: onFeatureHighlight,
            featurehighlighted: onFeatureHighlight,
            featureunhighlighted: onFeatureUnhighlight
        }
    });

    controlSelect = new OpenLayers.Control.SelectFeature(
        [planos, 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(80, 100),
        mapOptions: {
            projection: "EPSG:27492",
            units: 'm',
            numZoomLevels: 1,
            //maxExtent: new OpenLayers.Bounds(7500, -301500, 32000,  -279000)
            maxExtent: extents["maxExtent_ov"]
        }			
    };

    map.addControl(new OpenLayers.Control.OverviewMap(ov_options));
    
    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 = "Vista anterior";
    history.next.title = "Próxima vista";
    map.addControl(history);


    var panel = new OpenLayers.Control.Panel({
        id: "ctrlPanel",
        div: document.getElementById("toolbarButtons")
    });



    controls = [
        new OpenLayers.Control.ZoomBox({
            id: "ctrlZoomBoxIn",
            title: "Aproximar",
            cursorClass: "olControlZoomInBoxCursor"
        }),
        new OpenLayers.Control.ZoomBox({
            id: "ctrlZoomBoxIn",
            title: "Afastar",
            displayClass: "olControlZoomOutBox",
            out: true,
            cursorClass: "olControlZoomOutBoxCursor",
            handlerOptions: { cursorClasses: { 'startBox': 'crossHair', 'endBox': 'olControlZoomOutBoxCursor'} }
        }),
        new OpenLayers.Control.DragPan({
            id: "ctrlPan",
            title: "Mover",
            cursorClass: "olControlDragPanCursor",
            handlerOptions: { cursorClasses: { 'mousedown': 'dragMouseDown', 'mouseup': 'dragMouseUp'} }
        }),
        history.previous,
        history.next,
        new OpenLayers.Control.ZoomToMaxExtent({
            id: "ctrlZoomMaxExtent",
            title: "Ver tudo",
            displayClass: "olControlZoomAll"
        }),
        new OpenLayers.Control.Measure(
            OpenLayers.Handler.Path,
            { id: "ctrlMeasureLine",
                title: 'Medir distância',
                displayClass: 'olControlMeasureLine',
                persist: true,
                handlerOptions: { persist: true },
                eventListeners: ({
                    "measure": handlerMeasurements,
                    "measurepartial": handlerMeasurements
                })
            }),
        new OpenLayers.Control.Measure(
            OpenLayers.Handler.Polygon,
            { id: "ctrlMeasureArea",
                title: 'Medir área',
                displayClass: 'olControlMeasureArea',
                persist: true,
                handlerOptions: { persist: true },
                eventListeners: ({
                    "measure": handlerMeasurements,
                    "measurepartial": handlerMeasurements
                })
            }),
        new OpenLayers.Control.DrawFeature(
            vector,
            OpenLayers.Handler.Polygon,
            {
                id: "ctrlCreatePolygon",
                title: "Desenha elemento",
                cursorClass: 'crossHair',
                displayClass: 'olControlDrawPolygon'
            }),
        new OpenLayers.Control.ModifyFeature(
            vector,
            {
                id: "ctrlModifyPolygon",
                title: '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: "Limpar mapa",
            displayClass: "olControlClearMap",
            trigger: clearMap
        }),
        new OpenLayers.Control.Click({
            id: "ctrlGetCoordinates",
            title: "Obter coordenadas",
            displayClass: "olControlGetCoordinates"
        }),
        new OpenLayers.Control.Button({
            id: "ctrlPrint",
            title: 'Plantas',
            displayClass: 'olControlPrint',
            trigger: function() { showPanel('plantas', null, "west"); }
        }),
        new OpenLayers.Control.Click({
            id: "ctrlGetInfo",
            title: 'Informação',
            displayClass: 'olControlGetInfo'
        })
    ];

    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();
    });


    //Control: GetCoordinates
    ctrl = panel.getControlsBy("id", "ctrlGetCoordinates");
    ctrl[0].events.register("activate", ctrl[0], function(e) {
        showPanel('coordinates', null, 'west');
    });
    

    //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;           
}

function showTOC_CallBack(data) {

    var html = data;

    $j("#toc").html(html);


    $j("#toc").checkboxTree({
        collapsedarrow: "images/page/node_openen.gif",
        expandedarrow: "images/page/node_closed.gif",
        blankarrow: "script/jquery/checkboxtree/img-arrow-blank.gif",
        checkchildren: false,
        onCheck: setLayersVisibility,
        onUnCheck: setLayersVisibility
    });

    setLayersVisibility(null);

    return false;
}

function loadPlanos_CallBack(data) {

    planos = data;

    if (planos != null) {
    
        var layer = map.getLayersByName("planos")[0];
    
	/*
        $j.each(planos, function(i, item) {

            var feature = wkt_trans.read(item[1]);

            if (feature != null && feature != undefined) {

                var popupHTML = "<div style='font-size:.8em'>" + item[4] + "<br />" + item[5] + "</div>";

                feature.data = { tipo: "planos",
                    html: popupHTML
                };

                layer.addFeatures(feature);
            }
        });
*/
        var plano = $j(document).getUrlParam("plano");


        if (plano != null) {
        
            var layer = $j(document).getUrlParam("planta");
            
            DoZoomPlano(plano, layer);                        

            if (layer != null) {
                SetLayerExpanded(layer);
            }
        }    
    }
    
}

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 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 showTooltip(data) {
    $j.post("/App_Resource/Geo.Plugins/Geo.Plugins.View.infoPOI.aspx", data, showToolTip_CallBack);
}
function showToolTip_CallBack(response) {
    var ss = response;
}

function ddl_bookmark_onchange() {

    var elem = $j("#ddl_bookmark")[0];

    if (elem != null) {

        var x = $j(elem[elem.selectedIndex]).attr("x");
        var y = $j(elem[elem.selectedIndex]).attr("y");

        DoZoomLoc(x,y, false, ZOOM_LEVEL_PLACE);
    }            
}
