﻿/* init */
//var app; 
var cookies;
var langCode;
//var municipia;



//function initLayout(){
Ext.onReady(function(){
    
    
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();
    
    // INIT MAP
    initMap();
    var eastTabs = [];
    
    var toolbar = new Municipia.Toolbar({
        map: app.map, 
        configurable: false,
        id: 'map-toolbar',
        busyText : OpenLayers.i18n('Loading...'),
        //defaultText: 'Default status',
        statusAlign: 'right' // the magic config
    });

    if(app.controls!=null && app.controls.tab_layers){
                
        app.layersTab = new Ext.Panel({
                id: 'layerswitcher',
                title: OpenLayers.i18n("Legend"),
                tabName:"layerSwitcherTab",
                autoScroll:true,
                collapsed: false,
                //collapsible: true,
                fitContainer: true, 
                frame:true,
                fitToFrame: true, 
                useShadow: false,
                loadMask: true,
                contentEl : "treeView", 
                listeners:{
                    beforeshow: function() {
                        if(this.contentEl){
                            var obj = document.getElementById(this.contentEl);
                            if(obj!=null){
                                obj.style.display='block';
                            }
                        }
                    }, 
                    render:function() {
                        this.loadMask = new Ext.LoadMask(this.body, {
                            msg:'A Carregar...'
                        })
                    }                            
                 }
            });
        
        // Layer Switcher tab 
        eastTabs.push(app.layersTab); 
    }

    if(app.controls!=null && app.controls.tab_search){
           
        app.pesquisaTab = new Ext.Panel({
                id: 'pesquisa',
                title: OpenLayers.i18n("Search"),
                tabName:"pesquisaTab",
                collapsed: false,
                //collapsible: true,
                fitContainer: true, 
		        fitToFrame: true, 
		        useShadow: true,
                //html: createBoxSearch(),
                layout: 'accordion',
                autoScroll:true,
                items: getItemsTabPesquisa()      
            });
        
        // Pesquisa tab 
        eastTabs.push(app.pesquisaTab);      
    }
    
    var emitirPlantas = null;
    if(app.controls!=null && app.controls.tab_emissao_plantas_localizacao){
        
        emitirPlantas = {
            xtype: 'plantas-localizacao',
            id: 'plantaslocalizacao-emissao-form',
            title: OpenLayers.i18n("plantas.emissao.title"),
            tabName:"plantasLocalizacaoEmissaoTab",
            bodyStyle: 'padding: 7px;',
            layout: 'municipia.row',
            collapsed: false,
            frame:true,
            fitToFrame: true,
            viewConfig: {
                forceFit:true,
                enableRowBody:true,
                showPreview:true
            },
            layoutConfig:{
                animate: true,
                activeOnTop: false
            },
            formConfig: {
                labelWidth: 75 // label settings here cascade unless overridden
            },
            pedidos: app.controls.tab_pedidos_plantas_localizacao, 
            border: false,
            map: app.map,
            comment: '',
            vectorsLayer: app.vectorsLayer,
            pretensao: true,    // torna activa a combo de pretensão
            getCurDpi: function() {
                return app.dpi_print;
            },
            getCurLayout: function() {
                return app.layout_print;
            },
            getPageTitle: function() {
                return app.page_title_print;
            },
            getDivTitle: function() {
                return app.div_title_print;
            },
            getMapTitle: function() {
                return app.map_title_print;
            },
            listeners:{
                 activate : function(panel){
                    //alert(123);
                    //this.ownerCt.doLayout();
                    //panel.doLayout();
                 }
              }

        };
        //emitirPlantas.doLayout(true);
    }
    //alert(app.uRole+"*"+app.controls.tab_pedidos_plantas_localizacao);
    app.pedidosPlantas = null;
    var loginPlantas = null;
    if(app.controls!=null && app.controls.tab_pedidos_plantas_localizacao){
    //if(app.controls!=null && app.controls.tab_pedidos_plantas_localizacao && (app.uRole!="" && app.uRole.search(/emissao/i))){
        loginPlantas = {
	        id: 'plantas-localizacao-login',
	        xtype: 'plantas-localizacao-login',
	        title: OpenLayers.i18n("plantas.pedidos.title"),
	        tabName:"plantasLocalizacaoPedidosTab",
	        bodyStyle: 'padding: 7px;',
	        layout: 'municipia.row',
            collapsed: false,
            autoScroll: true,
            frame:true,
            fitToFrame: true,
            viewConfig: {
                forceFit:true
            },
            layoutConfig:{
                animate: true,
                activeOnTop: false
            },
            formConfig: {
                labelWidth: 75 // label settings here cascade unless overridden
            },
            border: false,
            map: app.map,
            comment: ''            
        };
        
        app.pedidosPlantas = {
	        id: 'plantaslocalizacao-pedidos-form',
	        xtype: 'plantas-localizacao-pedidos',
	        title: OpenLayers.i18n("plantas.pedidos.title"),
	        tabName:"plantasLocalizacaoPedidosTab",
	        bodyStyle: 'padding: 7px;',
	        layout: 'municipia.row',
            collapsed: false,
            autoScroll: true,
            frame:true,
            fitToFrame: true,
            viewConfig: {
                forceFit:true
            },
            layoutConfig:{
                animate: true,
                activeOnTop: false
            },
            formConfig: {
                labelWidth: 75 // label settings here cascade unless overridden
            },
            emissao: app.controls.tab_emissao_plantas_localizacao, 
            border: false,
            map: app.map,
            comment: '',
            vectorsLayer: app.vectorsLayer,
            pretensao: true,    // torna activa a combo de pretensão
            getCurDpi: function() {
                return app.dpi_print;
            },
            getCurLayout: function() {
                return app.layout_print;
            },
            getPageTitle: function() {
                return app.page_title_print;
            },
            getDivTitle: function() {
                return app.div_title_print;
            },
            getMapTitle: function() {
                return app.map_title_print;
            }  
        };
        
    }
    
    app.plantasTab = null;
    app.tabsPlantas = null;
    if(emitirPlantas!=null && app.pedidosPlantas!=null){
        app.tabsPlantas  =  new Ext.TabPanel({
                        border:true,
                        activeTab: 0,
                        region: 'center',
                        tabPosition:'top',
                        layoutOnTabChange:true,
                        items: [emitirPlantas, loginPlantas]
                    });

        app.plantasTab = new Ext.Panel({            
            title: OpenLayers.i18n("plantas.title"),
            tabName:"plantasLocalizacaoTab",
            collapsed: false,
            //collapsible: true,
            fitContainer: true, 
            fitToFrame: true, 
            useShadow: true,
            //html: createBoxSearch(),
            layout: 'fit',
            items: app.tabsPlantas         
               
        });
        
        //app.tabsPlantas.syncSize();
    }else if(emitirPlantas!=null){
        emitirPlantas.collapsed = false;
        app.plantasTab = emitirPlantas;
    }else if(app.pedidosPlantas!=null){
        app.pedidosPlantas.collapsed = false;
        app.plantasTab = app.pedidosPlantas;
    }
    
    if(app.plantasTab!=null){
        eastTabs.push(app.plantasTab); 
    }
    
    if(app.controls!=null && app.controls.tab_print){
    
        app.printTab = {
            xtype: 'print-simple',
            id: 'print',
            title: OpenLayers.i18n("print.print"),
            tabName:"printTab",
            bodyStyle: 'padding: 7px;',
            frame:true,
            fitToFrame: true,
            viewConfig: {
                forceFit:true,
                enableRowBody:true,
                showPreview:true
            },
            layoutConfig:{
                animate: true,
                activeOnTop: false
            },
            formConfig: {
                labelWidth: 65,
                defaults: {
                  width: 140,
                  listWidth: 140
                },
                items: [
                  {
                    xtype: 'textfield',
                    fieldLabel: OpenLayers.i18n("print.mapTitle"),
                    name: 'mapTitle'
                    //value: OpenLayers.i18n("print.mapTitle")
                  },
                  {
                    xtype: 'textarea',
                    fieldLabel: OpenLayers.i18n("print.comments"),
                    name: 'comment',
                    height: 100
                    //value: OpenLayers.i18n("print.comments")
                  }
                ]
            },
            border: false,
            map: app.map,
            intersectionLayer: app.vectorsLayer,
            configUrl: 'print/info3.json',
            intersectionTitle: OpenLayers.i18n('print.titleCross'),
            getPageTitle: function() {
                return app.page_title_print;
            },
            getDivTitle: function() {
                return app.div_title_print;
            },
            getMapTitle: function() {
                return app.map_title_print;
            },
            listeners:{
                setUp: function(){
                    app.handlersPrint = [];
                    if(this.pageDrag!=null && this.pageDrag.active)
                        app.handlersPrint.push(this.pageDrag);
                    if(this.rotateHandle!=null && this.rotateHandle.active)
                        app.handlersPrint.push(this.rotateHandle);                        
                },
                tearDown: function(){
                    app.handlersPrint = [];
                }                      
             }
              //overrides: layerOverrides
        };
        
        // Print tab 
        eastTabs.push(app.printTab);
    }   
        
    if(app.controls!=null && app.controls.tab_estatisticos){
    
        var choropleth = new Municipia.controls.estatisticos.ColorForm({
            'map': app.map
            //,'url': "handler/municipia.sync?urlwfs=aHR0cDovL2d1bGxpdmVyOjg5ODkvZ2Vvc2VydmVyMTcyL3dmcw==?service=WFS&version=1.0.0&request=GetFeature&typename=oeirasdigital%3AFREGUESIA_2001&srsName=EPSG%3A27492&globalid=86a3d394-3e08-42bc-aad5-eb32467f9e8d&tipoid=4&id_layer=327&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&SRS=EPSG%3A27492&outputformat=json"//"print/countries.json"
            ,'url': "sld/temp_polygon.xml"
            //,'featureSelection':false
            ,'loadMask' : {msg: 'Loading Data...', msgCls: 'x-mask-loading'}
            ,'legendDiv' : 'legendaEstatisticosDiv'
        });
        
        
        //choropleth.render('myChoroplethDiv');
        /*
        app.estatisticosTab = new Ext.Panel({
                id: 'estatisticos',
                title: OpenLayers.i18n("estatisticos"),
                tabName:"estatisticosTab",
                bodyStyle: 'padding: 7px;',
                autoScroll:false,
                collapsed: false,
                //collapsible: true,
                fitContainer: true, 
                frame:true,
                fitToFrame: true, 
                useShadow: false,
                loadMask: true,
                contentEl : "myChoroplethDiv", 
                listeners:{
                    render: function() {
                        this.loadMask = new Ext.LoadMask(this.body, {
                            msg:'A Carregar...'
                        })
                    }                            
                 }
            });
            */
               
        app.estatisticosTab = new Ext.Panel({
            id: 'estatisticos'
            ,title: OpenLayers.i18n("estatisticos.title")
            ,tabName:"estatisticosTab"
            ,bodyStyle: 'padding: 7px;'
            ,autoScroll:false
            ,collapsed: false
            //,collapsible: true
            ,fitContainer: true 
            ,frame:true
            ,fitToFrame: true
            ,useShadow: false
            ,loadMask: true
            ,items: choropleth
            ,listeners:{
                activate  : function(cp){
                    app.urlLegendEstatisticos = null;
                },                
                deactivate  : function(cp){
                    app.urlLegendEstatisticos = null;
                }                      
             }  
        });
                
        // Estatisticos tab 
        eastTabs.push(app.estatisticosTab);
        
    }
                
    if(app.controls!=null && app.controls.tab_help){
    
        app.ajudaTab = new Ext.Panel({
                id: 'ajuda',
                title: OpenLayers.i18n("Help"),
                tabName:"ajudaTab",
                autoScroll:true,
                collapsed: false,
                //collapsible: true,
                fitContainer: true, 
                frame:true,
                fitToFrame: true, 
                useShadow: false,
                loadMask: true,
                contentEl : "help", 
                listeners:{
                     beforeshow: function() {
                        if(this.contentEl){
                            var obj = document.getElementById(this.contentEl);
                            if(obj!=null){
                                obj.style.display='block';
                            }
                        }
                    }, 
                    render: function() {
                        this.loadMask = new Ext.LoadMask(this.body, {
                            msg:'A Carregar...'
                        })
                    }                            
                 }
            });
            
        // Ajuda tab 
        eastTabs.push(app.ajudaTab);
    }

   var mapcomponent = new Municipia.controls.MapComponent({map: app.map});
   
   var itemsViewPort = [];
   itemsViewPort.push(
            new Ext.BoxComponent({ // raw
                border:true,
                region:'north',
                el: 'divCabecalho',
                height:50,
                margins:'5 5 5 0'
            })
   );
   
   itemsViewPort.push(
        {
            region: 'center',
            margins: app.controls.side=='east'?'0 0 0 5':'0 5 0 0',
			layout: 'fit',
			animate: true,
            tbar: toolbar,
            loadMask: true,
            title: OpenLayers.i18n('Map'),
            header: false,
            listeners:{
                render:function() {
                    this.loadMask = new Ext.LoadMask(this.body, {
                        msg:'Loading. Please wait...'
                    })
                }
            },
            items: mapcomponent
       }
   );
   
   /*
   itemsViewPort.push(
        {
            region: 'center',
            tbar: toolbar,
            loadMask: true,
            title: OpenLayers.i18n('Map'),
            header: false,
            listeners:{
                render:function() {
                    this.loadMask = new Ext.LoadMask(this.body, {
                        msg:'Loading. Please wait...'
                    })
                }
            },
            xtype: 'gx_mappanel',
            map: app.map
        }
    );
    */

   if(eastTabs.length>0){
        var sizeTabPanel = (app.controls!=null && app.controls.tab_estatisticos) ? 320 : 265;
        var maxSizeTabPanel = 480;
        var tabsPanel  =  new Ext.TabPanel({
                        border:true,
                        activeTab: (app.controls!=null && app.controls.tab_estatisticos) ? 1 : 0,
                        region: 'center',
                        tabPosition:'top',
                        layoutOnTabChange:true,
                        items: eastTabs
                    });
        
        if(app.controls!=null && app.controls.regulamentos){
            itemsViewPort.push(
                {
                  id: 'toolsTabs',
                  border:true,
                  region: app.controls.side,
                  el: app.controls.side,
                  title: OpenLayers.i18n("Tools"),
                  collapsible: true,
                  split:true,
                  width: sizeTabPanel,
                  minSize: sizeTabPanel,
                  maxSize: maxSizeTabPanel,
                  collapsed: false,
                  margins:  app.controls.side=='east'?'0 5 0 0':'0 0 0 5',
                  defaults: {
                    border: true,
                    frame: true
                  },
                  layout: 'border',
                  items: [
                      tabsPanel,
                      {
                          title: OpenLayers.i18n("Regulamentos"),
                          region: 'south',
                          fieldLabel: 'Name',
                          collapsible: true,
                          collapsed: false,
                          autoHeight: true,
                          //height: 150,
                          autoScroll: true,
                          border: true,
                          frame: true,
	                      contentEl : "regulamentos",
	                      listeners:{
                             beforerender: function() {
                                if(this.contentEl){
                                    var obj = document.getElementById(this.contentEl);
                                    if(obj!=null){
                                        obj.style.display='block';
                                    }
                                }
                            }                            
                          }
                      }
                  ]
              }
           );
       }else{
           itemsViewPort.push(
                {
                    id: 'toolsTabs',
                    border:true,
                    region: app.controls.side, 
                    el: app.controls.side,
                    title: OpenLayers.i18n("Tools"),
                    collapsible: true,
                    split:true,
                    width: sizeTabPanel,
                    minSize: sizeTabPanel,
                    maxSize: maxSizeTabPanel,
                    layout:'fit',
                    margins: app.controls.side=='east'?'0 5 0 0':'0 0 0 5',
                    items: [tabsPanel]
                 }
           );
       }
   }
    
   itemsViewPort.push(
        new Ext.BoxComponent({ // raw
            region:'south',
            el: 'south',
            contentEl: 'south',
            height:5
        })
   ); 
                    
   var viewport = new Ext.Viewport({
        layout:'border',
        renderTo: 'main-div',
        items: itemsViewPort
    });
    
    viewport.doLayout();
    
    initApp(toolbar);
    
});

Ext.EventManager.on(window, 'load', function(){

    setTimeout(function(){
        if(Ext.get('loading')!=null){
            Ext.get('loading').remove();
		}
        if(Ext.get('loading-mask')!=null){
            Ext.get('loading-mask').fadeOut({remove:true});
		}
    }, 250);
    
    if(window.console && window.console.firebug){
        Ext.Msg.alert('Warning', 'Firebug is known to cause performance issues with Ext JS.');
    }
    
    // isto é util p o firefox
    /*
    if(app.bounds!=null){
        app.map.zoomToExtent(app.bounds, true);
    }
    */
});


