var mapPanel, storeVias, gridVias;
var fronteira = 3; // só se vê as ruas se a resolução for inferior a 6
var escalaMax = 3; // só se vê as ruas se o zoom for superior a 4 (igual não mostra)
var oUtilizador = "";
var oEmail = "";

///////////////////////////

Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field){
        var date = field.parseDate(val);
        
        if (!date) {
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        }
        else 
            if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
                var end = Ext.getCmp(field.endDateField);
                end.setMinValue(date);
                end.validate();
                this.dateRangeMin = date;
            }
        
        return true;
    },
    
    NIF: function(val, field){
        //alert(field.getValue);
        //Validação do NIF
        var nif = val;
        var c;
        var checkDigit = 0;
        if (!nif) {
            return;
        }
        if (nif !== null && nif.match(/^\d+$/) && nif.length == 9) {
            c = nif.charAt(0);
            if (c == '1' || c == '2' || c == '5' || c == '6' || c == '8' || c == '9') {
                checkDigit = c * 9;
                var i = 0;
                for (i = 2; i <= 8; i++) {
                    checkDigit += nif.charAt(i - 1) * (10 - i);
                }
                checkDigit = 11 - (checkDigit % 11);
                
                if (checkDigit >= 10) {
                    checkDigit = 0;
                }
                if (checkDigit == nif.charAt(8)) {
                    return true;
                }
            }
        }
        return false;
    },
    
    NIFText: 'Número de contribuinte inválido.',
    
    password: function(val, field){
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    
    passwordText: 'A password não é igual'
});

///////////////////////////



Ext.onReady(function(){
    Ext.QuickTips.init();
    // create map instance
    var bounds = new OpenLayers.Bounds(-36002.0, 89990.0, -8000.0, 115000.0);
    /*
     var options = {
     projection: 'EPSG:27492',
     controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar()],
     // maxZoomLevel: 60,
     // maxResolution: 40.273752,
     // scales: opcional
     // getZoom(), 0,     1,     2,     3,    4,    5,    6,   7
     scales: [100000, 50000, 25000, 10000, 5000, 2000, 1000, 500],
     maxExtent: bounds,
     units: 'm'
     };
     */
    var options = {
        controls: [new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar()],
        maxExtent: bounds,
        maxResolution: 40.273752,
        maxZoomLevel: 60,
        projection: "EPSG:27492",
        title: 'Mapa',
        units: 'm'
    };
    
    var map = new OpenLayers.Map(options);
    map.addControl(new OpenLayers.Control.Scale());
    map.addControl(new OpenLayers.Control.MousePosition());
    
    var victor = new OpenLayers.Layer.Vector("Editable Vectors", {
        displayInLayerSwitcher: false
    });
    // var panelInserir = new OpenLayers.Control.EditingToolbar(victor, {'div':OpenLayers.Util.getElement('botoesEdicao')});
    // var panelInserir = new OpenLayers.Control.EditingToolbar(victor);
    // var panelModificar = new OpenLayers.Control.ModifyFeature(victor, {'div':OpenLayers.Util.getElement('botoesModificao')});
    // var panelModificar = new OpenLayers.Control.ModifyFeature(victor);
    // map.addControl(panelInserir);
    // map.addControl(panelModificar);
    
    /*
     function report(event) {
     OpenLayers.Console.log(event.type, event.feature ? event.feature.id : event.components);
     }
     victor.events.on({
     "beforefeaturemodified": report,
     "featuremodified": report,
     "afterfeaturemodified": report,
     "vertexmodified": report,
     "sketchmodified": report,
     "sketchstarted": report,
     "sketchcomplete": report
     });
     */
    var panel = new OpenLayers.Control.Panel({
        // displayClass: 'customEditingToolbar',
        div: OpenLayers.Util.getElement('botoesEdicao')
    });
    var navigate = new OpenLayers.Control.Navigation({
        title: "Pan Map"
    });
    var drawPoint = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Point, {
        title: "Marca pontos",
        displayClass: 'olControlDrawFeaturePoint',
        handlerOptions: {
            multi: true
        }
    });
    var drawPath = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Path, {
        title: "Traça linhas",
        displayClass: "olControlDrawFeaturePath",
        handlerOptions: {
            multi: true
        }
    });
    var drawPolygon = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Polygon, {
        title: "Desenha polígonos",
        displayClass: "olControlDrawFeaturePolygon",
        handlerOptions: {
            multi: true
        }
    });
    
    // já não existe!
    // var remove = new OpenLayers.Control.RemoveFeature(victor, {onDone: function(feature) {console.log(feature)} });
    
    var drag = new OpenLayers.Control.DragFeature(victor, {
        title: "Move",
        displayClass: "olControlNavigation"
    });
    
    // control.mode = OpenLayers.Control.ModifyFeature.RESIZE | OpenLayers.Control.ModifyFeature.ROTATE;
    // http://openlayers.org/dev/examples/modify-feature.html
    var edit = new OpenLayers.Control.ModifyFeature(victor, {
        title: "Altera a geometria",
        displayClass: "olControlModifyFeature"
    });
    // var del = new DeleteFeature(victor, {title: "Delete Feature"});
    /*
     var save = new OpenLayers.Control.Button({
     title: "Save Changes",
     trigger: function(){
     if (edit.feature) {
     edit.selectControl.unselectAll();
     }
     saveStrategy.save();
     },
     displayClass: "olControlSaveFeatures"
     });
     */
    panel.addControls([edit, drag, drawPolygon, drawPath, drawPoint]);
    panel.defaultControl = navigate;
    map.addControl(panel);
    
    format = 'image/png';
    var orto = new OpenLayers.Layer.WMS("Ortofotomapas IGP 2005", "/wms/tilecache.py?", {
        layers: 'orto',
        format: 'image/png',
        numZoomLevels: 60,
        transparent: true
    }, {
        isBaseLayer: true
    });
    var caop = new OpenLayers.Layer.WMS("Limites Administrativos", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:caop2006',
        styles: '',
        format: format,
        transparent: true
    }, {
        buffer: 0,
        singleTile: true,
        ratio: 1,
        isBaseLayer: false
    });
    
    var carto2k5k = new OpenLayers.Layer.WMS("Cartografia 2K/5K", "/wms/tilecache.py?", {
        layers: 'carto2k/5k',
        format: 'image/png',
        numZoomLevels: 60,
        transparent: true
    }, {
        buffer: 0,
        isBaseLayer: true
    });
    toponimia = new OpenLayers.Layer.WMS("Toponimia Rede Viaria", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:toponimia_rv',
        transparent: true,
        format: format
        // maxScale: 50000,
        // minScale: 10000
    }, {
        buffer: 0
    });
    
    limiteppzn = new OpenLayers.Layer.WMS("Limite PP ZN", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:limite_pp_zn',
        transparent: true,
        format: format
        // maxScale: 50000,
        // minScale: 10000
    }, {
        buffer: 0
    });
    
    Plano_Redolho = new OpenLayers.Layer.WMS("Plano do Redolho", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:passeios_proj1,topp:pavimento_proj1,topp:papeleiras_proj1,topp:caldeiraarvore2_proj1,topp:caldeiraarvore_proj1,topp:estaciona_proj1,topp:sinaliza_proj1,topp:floreiras_proj1,topp:arvores_proj1,topp:sinalizaln_proj1,topp:protectores_proj1',
        transparent: true,
        format: format
        // maxScale: 50000,
        // minScale: 10000
    }, {
        buffer: 0
    });
    
    var carto10k = new OpenLayers.Layer.WMS("Cartografia 10K", "/wms/tilecache.py?", {
        layers: 'carto10k',
        format: 'image/png',
        numZoomLevels: 60,
        transparent: true
    }, {
        buffer: 0,
        isBaseLayer: true
    });
    var pdm = new OpenLayers.Layer.WMS("P. de Ordenamento 1995", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:igtpdm95',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0,
        visibility: false
    });
    var npol = new OpenLayers.Layer.WMS("Num. Policia", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:npol_inter',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0
    });
    var localidades = new OpenLayers.Layer.WMS("Localidades", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:localidades_topo',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0
    });
    var rede_natura = new OpenLayers.Layer.WMS("Rede Natura 2000", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:redenatura2000',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0,
        visibility: false
    });
    var ran = new OpenLayers.Layer.WMS("RAN 1995", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:igt_ran95',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0,
        visibility: false
    });
    var ren = new OpenLayers.Layer.WMS("REN 1995", // "http://127.0.0.1:8080/geoserver/wms",
 "/geoserver/wms", {
        srs: 'EPSG:27492',
        layers: 'topp:igt_ren95',
        transparent: true,
        format: format
        // maxScale: 5000,
        // minScale: 10000
    }, {
        buffer: 0,
        visibility: false
    });
    
    
    /*
     function createTreeModel() {
     return [{
     text: 'Cartografia de Base',
     expanded: false,
     leaf: false,
     children:[{
     text: 'Cartografia 2K/5K',
     checked: true,
     layerName: 'Cartografia 2K/5K',
     leaf: true
     },{
     text: 'Cartografia 10K',
     checked: false,
     layerName: 'Cartografia 10K',
     leaf:true
     },{
     text: 'Ortofotomapas IGP 2005',
     checked: false,
     layerName: 'Ortofotomapas IGP 2005',
     leaf:true
     }
     ]
     }, {
     text: "Cartografia Temática",
     leaf: false,
     checked: true,
     expanded: true,
     children: [{
     text: "Limites Administrativos",
     layerName: 'Limites Administrativos',
     leaf: true,
     // 4.5
     icon: "icons/img2.png",
     checked: true
     },{
     text: "P. de Ordenamento 1995",
     layerName: 'P de Ordenamento 1995',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "Toponimia Rede Viaria",
     layerName: 'Toponimia Rede Viaria',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "Num. Policia",
     layerName: 'Num. Policia',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "Localidades",
     layerName: 'Localidades',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "Rede Natura 2000",
     layerName: 'Rede Natura 2000',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "RAN 1995",
     layerName: 'RAN 1995',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     },{
     text: "REN 1995",
     layerName: 'REN 1995',
     leaf: true,
     // 4.5
     icon: "icons/img1.png",
     checked: true
     }]
     }];
     
     var model = createTreeModel();
     */
    // Overview Map
    
    var enq = new OpenLayers.Layer.WMS("Enquadramento", "/geoserver/wms", {
        layers: 'topp:lim_overview1',
        srs: 'EPSG:27492',
        units: 'm'
    });
    var over = enq.clone();
    var overviewoptions = {
        projection: 'EPSG:27492',
        displayProjection: 'EPSG:27492',
        units: 'm',
        maxResolution: 25000,
        maxExtent: new OpenLayers.Bounds(-62481.00668945313, 69030.723046875, 18421.046728515626, 148981.206640625),
        theme: false,
        numZoomLevels: 10
    };
    var overview = new OpenLayers.Control.OverviewMap({
        //div: OpenLayers.Util.getElement('over'),
        size: new OpenLayers.Size(120, 120),
        layers: [over],
        minRatio: 10,
        maxRatio: 10,
        mapOptions: overviewoptions
    });
    map.addControl(overview);
    
    
    /*
     var caop = new OpenLayers.Layer.WMS("Limites Administrativos", "/geoserver/wms", {
     srs: 'EPSG:27492',
     layers: 'topp:caop',
     format: 'image/png',
     transparent: true
     }, {
     isBaseLayer: true,
     attribution: '<b>+MARIA</b>, Câmara Municipal de Águeda, 2009'
     });
     */
    var protocolVias = new OpenLayers.Protocol.HTTP({
        url: "/mapfish/vias",
        format: new OpenLayers.Format.GeoJSON()
    });
    // create vector layer
    var vecLayer = new OpenLayers.Layer.Vector("vector", {
        strategies: [new OpenLayers.Strategy.BBOX()],
        protocol: protocolVias,
        // maxScale: escalaMax,
        displayInLayerSwitcher: false,
        maxResolution: fronteira
    });
    // map.addLayers([orto, caop, vecLayer, victor]);
    map.addLayers([orto, caop, vecLayer, victor, carto2k5k, carto10k, pdm, ran, ren, rede_natura, npol, toponimia, localidades, limiteppzn, Plano_Redolho]);
    map.addControl(new OpenLayers.Control.Attribution());
    
    // create map panel
    mapPanel = new GeoExt.MapPanel({
        // title: "Map",
        region: "center",
        // height: 400,
        // width: 600,
        map: map,
        // center: new OpenLayers.LonLat(, 45),
        zoom: 0
    });
    
    // create feature store, binding it to the vector layer
    storeVias = new GeoExt.data.FeatureStore({
        layer: vecLayer,
        fields: [{
            name: 'designacao',
            type: 'string'
        }, {
            name: 'toponimia',
            type: 'string'
        }, {
            name: 'freg',
            type: 'string'
        }, {
            name: 'the_geom',
            type: 'geo'
        }],
        proxy: new GeoExt.data.ProtocolProxy({
            protocol: protocolVias
        }),
        autoLoad: false
    });
    
    /*
     map.events.register('zoomend', map, function(e){
     // jgr zumLevel=map.getZoom()+5;
     // OpenLayers.Console.log('map.getZoom()= ', map.getZoom(), ' map.getResolution()=', map.getResolution());
     if (map.getResolution() > fronteira)
     storeVias.removeAll();
     });
     */
    // create grid panel configured with feature store
    gridVias = new Ext.grid.GridPanel({
        title: "Seleccione a rua",
        region: "east",
        store: storeVias,
        collapsible: true,
        width: "100%",
        height: 160,
        columns: [ // { header: 'id', dataIndex: 'id', width: 50 },
        {
            header: 'Designação',
            dataIndex: 'designacao',
            width: 75
        }, {
            header: 'Topónimo',
            dataIndex: 'toponimia',
            width: 150
        }, {
            header: 'Freg.',
            dataIndex: 'freg',
            width: 50
        }],
        sm: new GeoExt.grid.FeatureSelectionModel(),
        listeners: {
            'rowclick': {
                'fn': function(grid, index, evt){
                    var r = grid.getStore().getAt(index);
                    var feature = r.get('feature');
                    // OpenLayers.Console.log(feature.fid, feature.attributes['toponimia']);
                    var geometry = feature.geometry;
                    var center = geometry.getBounds().getCenterLonLat();
                    map.setCenter(center, map.getZoom()); // 15 é demais
                    // map.setCenter(center, map.getZoomForExtent(geometry.getBounds(),false));  // 15 é demais
                    // OpenLayers.Console.log( geometry );
                }
            }
        }
    });
    
    var storePlanos = new Ext.data.SimpleStore({
        fields: ['value', 'text', 'bbox'],
        data: [['8', 'Estacionamento do Redolho', new OpenLayers.Bounds(-26430, 99270, -26168, 99460)]]
    });
    
    // create the data store
    /*
     var storePlanos = new Ext.data.JsonStore({
     url: 'json_planos.php',
     root: "features",
     // id: "id",
     fields: [{
     name: 'id',
     type: 'int'
     }, {
     name: 'designacao',
     type: 'string'
     }, {
     name: 'datafim'
     }, // date?
     {
     name: 'the_geom'
     } // geometry? // OpenLayers.Bounds.fromString ?
     ]
     });
     storePlanos.load();
     */
    // console.log(storePlanos);
    var shortcutsPlanos = new mapfish.widgets.Shortcuts({
        map: map,
        el: 'atalhoPlanos',
        collapsible: true,
        store: storePlanos,
        templates: {
            header: new Ext.Template(""),
            footer: new Ext.Template("")
        }
    
    
    });
    shortcutsPlanos.render();
    
    var storeFreguesias = new Ext.data.SimpleStore({
        fields: ['value', 'text', 'bbox'],
        data: [['1', 'AGADÃO', new OpenLayers.Bounds(-14893, 96390, -13893, 97390)], ['2', 'AGUADA DE BAIXO', new OpenLayers.Bounds(-27412, 93179, -26412, 94179)], ['3', 'AGUADA DE CIMA', new OpenLayers.Bounds(-23874, 94568, -22874, 95568)], ['4', 'ÁGUEDA', new OpenLayers.Bounds(-24402, 100847, -23402, 101847)], ['5', 'BARRO', new OpenLayers.Bounds(-28555, 95544, -27555, 96544)], ['6', 'BELAZAIMA DO CHAO', new OpenLayers.Bounds(-18828, 94895, -17828, 95895)], ['7', 'BORRALHA', new OpenLayers.Bounds(-24841, 97933, -23841, 98933)], ['8', 'CASTANHEIRA DO VOUGA', new OpenLayers.Bounds(-18993, 100645, -17993, 101645)], ['9', 'ESPINHEL', new OpenLayers.Bounds(-30362, 98965, -29362, 99965)], ['10', 'FERMENTELOS', new OpenLayers.Bounds(-33990, 99139, -32990, 100139)], ['11', 'LAMAS DO VOUGA', new OpenLayers.Bounds(-29033, 106715, -28033, 107715)], ['12', 'MACIEIRA DE ALCOBA', new OpenLayers.Bounds(-12356, 104988, -11356, 105988)], ['13', 'MACINHATA DO VOUGA', new OpenLayers.Bounds(-25689, 110484, -24689, 111484)], ['14', 'OIS DA RIBEIRA', new OpenLayers.Bounds(-32337, 100660, -31337, 101660)], ['15', 'PRÉSTIMO', new OpenLayers.Bounds(-17702, 105522, -16702, 106522)], ['16', 'RECARDAES', new OpenLayers.Bounds(-28439, 98665, -27439, 99665)], ['17', 'SEGADAES', new OpenLayers.Bounds(-30472, 103495, -29472, 104495)], ['18', 'TRAVASSO', new OpenLayers.Bounds(-31512, 102321, -30512, 103321)], ['19', 'TROFA', new OpenLayers.Bounds(-28839, 104335, -27839, 105335)], ['20', 'VALONGO DO VOUGA', new OpenLayers.Bounds(-23965, 106447, -22965, 107447)]]
    });
    
    var shortcuts = new mapfish.widgets.Shortcuts({
        map: map,
        el: 'atalhoFreguesias',
        collapsible: true,
        store: storeFreguesias,
        emptyText: 'Seleccione o plano',
        templates: {
            header: new Ext.Template(""),
            footer: new Ext.Template("")
        }
    });
    shortcuts.render();
    
    Ext.QuickTips.init();
    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';
    //make a new form
    var form_user = new Ext.form.FormPanel({
        frame: true,
        method: 'GET',
        title: 'Identifique-se',
        collapsible: true,
        bodyStyle: 'padding: 5px 5px 0',
        width: "100%",
        labelWidth: 70,
        defaults: {
            width: 120
        }, //this is the default field width
        defaultType: 'textfield', //this is the default field type.  You don't have to set this, but if not, you'll have to set it for each item
        items: [{
            fieldLabel: 'Utilizador',
            name: 'utilizador',
            allowBlank: false
        }, {
            fieldLabel: 'Senha',
            name: 'senha',
            inputType: 'password',
            allowBlank: false
        }],
        buttons: [{
            text: 'Entrar', //text for submit button
            type: 'submit', //type for button
            handler: function(){ //what happens when you click the button?
                form_user.form.submit({
                    url: 'verificalogin.php',
                    success: function(form, action){
                        obj = Ext.util.JSON.decode(action.response.responseText);
                        // console.debug(action.response.responseText); 
                        // console.debug( obj.data.nome );
                        form_logout.form.items.items[0].setValue(obj.data.nome);
                        // console.debug( obj.data.nif );
                        form_logout.form.items.items[1].setValue(obj.data.nif);
                        // console.debug( obj.data.ultimologin );
                        form_logout.form.items.items[2].setValue(obj.data.ultimologin);
                        // console.debug( obj.data.utilizador );
                        form_logout.form.items.items[3].setValue(obj.data.utilizador);
                        oUtilizador = obj.data.utilizador;
                        oEmail = obj.data.email;
                        form_user.hide();
                        form_user.getForm().reset();
                        form_logout.show();
                        Ext.MessageBox.alert('Informação', "Bem vindo, " + obj.data.nome);
                        // enable dos botões do form de submissão
                        form_participacao.buttons[0].enable(); // Enviar
                        form_participacao.buttons[1].enable(); // limpar
                    },
                    failure: function(form, action){
                        obj = Ext.util.JSON.decode(action.response.responseText);
                        // console.debug(action.response.responseText);
                        // console.debug(obj.errors);
                        // console.debug(obj.errors.reason);
                        Ext.MessageBox.alert('Informação', obj.errors.reason);
                    }
                });
            }
        }, {
            text: 'Registe-se', //text for submit button
            type: 'submit', //type for button
            handler: function(){
            
                window.show();
            }
            
        } // but cancelar
]
    });
    
    ////////  make form regista-se
    
    var form_regista = new Ext.form.FormPanel({
        xtype: "form",
        border: false,
        frame: true,
        url: 'regista.php',
        method: "GET",
        /* buttons:[{
         text:'Cancelar',
         scope:this,
         handler:this.onCancel },
         {
         text:'Enviar',
         formBind:true,
         scope:this,
         type: 'submit',
         handler:this.submit}],
         
         showError:function(msg, title) {
         title = title || 'Error';
         Ext.Msg.show({
         title:title,
         msg:msg,
         modal:true,
         icon:Ext.Msg.ERROR,
         buttons:Ext.Msg.OK
         });
         },
         
         onFailure:function(form, action) {
         this.showError(action.result.error || action.response.responseText);
         },
         submit:function() {
         this.getForm().submit({
         url:this.url,
         scope:this,
         //,success:this.onSuccess
         failure:this.onFailure,
         params:{cmd:'save'},
         waitMsg:'A enviar dados...'}
         );
         },*/
        title: "Registo de Utilizador",
        defaults: { // defaults are applied to items, not the container
            blankText: 'Campo de preenchimento obrigatório.'
        },
        
        
        items: [{
            xtype: "fieldset",
            autoHeight: true,
            autoWidth: true,
            title: "Dados Pessoais",
            items: [{
                xtype: "numberfield",
                minLength: 9,
                maxLength: 9,
                minLengthText: 'Este campo deve conter 9 números',
                maxLengthText: 'Este campo deve conter apenas 9 números',
                vtype: "NIF",
                allowBlank: false,
                fieldLabel: "NIF",
                name: "txtnif",
                id: 'txtnif',
                width: 180
            }, {
                xtype: "textfield",
                fieldLabel: "Nome",
                allowBlank: false,
                id: 'txtnome',
                name: "txtnome",
                autoHeight: true,
                width: 180
            }, {
                xtype: "fieldset",
                autoHeight: true,
                autoWidth: true,
                layout: 'anchor',
                title: "Sexo",
                items: [{
                    xtype: 'radiogroup',
                    fieldLabel: '',
                    //align: "left",
                    items: [{
                        xtype: "radio",
                        name: "sexo",
                        inputValue: "masculino",
                        fieldLabel: "Masculino"
                    }, {
                        xtype: "radio",
                        fieldLabel: "Feminino",
                        inputValue: "Feminino",
                        name: "sexo"
                    }]
                }]
            }, {
                xtype: "datefield",
                name: "txtdata",
                id: "txtdata",
                format: 'd/m/Y',
                fieldLabel: "Data Nascimento",
                width: 180
            }, {
                xtype: "textfield",
                allowBlank: false,
                //vtype : "phone",
                fieldLabel: "Telefone",
                name: "txttele",
                id: 'txttele',
                width: 180
            }, {
                xtype: "textfield",
                name: "txtpais",
                id: "txtpais",
                allowBlank: false,
                blankText: "Este campo é obrigatorio",
                fieldLabel: "Pais",
                width: 180
            }, {
                xtype: "textarea",
                name: "txtmorada",
                id: "txtmorada",
                fieldLabel: "Morada",
                grow: false,
                /*onKeyUp : function(e){
                 if(!e.isNavKeyPress() || (e.getKey() == e.ENTER && !e.shiftKey)){
                 this.autoSize();
                 }
                 },*/
                preventScrollbars: true,
                maxLength: 120,
                maxLengthText: "Atingiu o limite de caracteres",
                height: 40,
                width: 180
            }, {
                xtype: "textfield",
                fieldLabel: "Localidade",
                name: "txtlocalidade",
                id: "txtlocalidade",
                width: 180
            }, {
                xtype: "textfield",
                fieldLabel: "C.Postal",
                name: "txtcp",
                id: "txtcp",
                width: 180
            }]
        }, {
            xtype: "fieldset",
            autoWidth: true,
            autoHeight: true,
            title: "Dados de Utilizador",
            items: [{
                xtype: "textfield",
                fieldLabel: "Utilizador",
                allowBlank: false,
                vtype: "alpha",
                name: "txtutilizador",
                id: "txtutilizador",
                width: 180
            }, {
                xtype: "textfield",
                fieldLabel: "Password",
                name: "txtpass1",
                minLength: 5,
                //vtype : "alphanumText",
                allowBlank: false,
                inputType: 'password',
                id: "txtpass1",
                width: 180
            }, {
                xtype: "textfield",
                allowBlank: false,
                minLength: 5,
                vtype: "password",
                inputType: 'password',
                fieldLabel: "Repita a Password",
                name: "txtpass2",
                id: "txtpass2",
                initialPassField: 'txtpass1',
                width: 180
            }, {
                xtype: "textfield",
                fieldLabel: "E-Mail",
                id: 'txtmail',
                name: "txtmail",
                allowBlank: false,
                vtype: "email",
                width: 180
            }]
        }],
        json: {
            size: {
                width: 330,
                height: 471
            }
        }
    });
    
    //////////////////////////////////////
    //make a new form
    var form_logout = new Ext.form.FormPanel({
        frame: true,
        method: 'GET',
        title: 'Sessão iniciada',
        bodyStyle: 'padding: 5px 5px 0',
        width: "100%",
        labelWidth: 70,
        collapsible: true,
        defaults: {
            width: 120
        }, //this is the default field width
        defaultType: 'textfield', //this is the default field type.  You don't have to set this, but if not, you'll have to set it for each item
        items: [{
            fieldLabel: 'Nome',
            name: 'nome',
            readOnly: true,
            disabled: true
        }, {
            fieldLabel: 'Contribuinte',
            name: 'nif',
            readOnly: true,
            disabled: true
        }, {
            fieldLabel: 'Último login',
            name: 'ultimologin',
            readOnly: true,
            disabled: true
        }, {
            name: 'utilizador',
            xtype: 'hidden',
            readOnly: true
        }],
        buttons: [{
            text: 'Terminar', //text for submit button
            type: 'submit', //type for button
            handler: function(){ //what happens when you click the button?
                Ext.MessageBox.alert('Informação', "Adeus, " + form_logout.form.items.items[0].value);
                form_logout.getForm().reset();
                form_logout.hide();
                form_user.getForm().reset();
                form_user.show();
                //
                form_participacao.getForm().reset();
                form_participacao.disable();
                oUtilizador = "";
                oEmail = "";
                form_participacao.buttons[0].disable(); // Enviar
                form_participacao.buttons[1].disable(); // limpar
            }
        }]
    });
    
    
    // make a new form
    var form_participacao = new Ext.form.FormPanel({
        frame: true,
        title: 'Contribuição para a discussão',
        bodyStyle: 'padding: 5px 5px 0',
        width: "100%",
        labelWidth: 1,
        // defaults: {
        //    width: 160
        // },
        defaultType: 'textfield', //this is the default field type.  You don't have to set this, but if not, you'll have to set it for each item
        items: [        /*   new Ext.form.ComboBox({
         fieldLabel: 'Plano em discussão',
         hiddenName: 'idplano',
         store: storePlanos,
         valueField: 'id',
         displayField: 'designacao',
         triggerAction: 'all',
         emptyText: 'Seleccione...',
         selectOnFocus: true,
         editable: false
         }), */
        {
            fieldLabel: '',
            labelSeparator: '',
            xtype: 'textarea',
            name: 'participacao',
            autoScroll: true,
            height: 200,
            width: 250
        
        }        /*  ,
         {
         xtype: 'fileuploadfield',
         id: 'form-file1',
         emptyText: 'Select...',
         fieldLabel: 'Image',
         name: 'img'
         } */
        ],
        buttons: [{
            text: 'Enviar', //text for submit button
            type: 'submit', //type for button
            disabled: true,
            handler: function(){ //what happens when you click the button?
                // console.log('vai submeter');
                var coleccao = "";
                var sep = "";
                for (i = 0; i < victor.features.length; i++) {
                    var feature = victor.features[i];
                    if (i > 0) {
                        sep = ", ";
                    }
                    // console.log(feature.geometry.toString());
                    coleccao = coleccao + sep + feature.geometry.toString();
                }
                // pode não te desenhado nada...
                if (coleccao != "") {
                    coleccao = "GEOMETRYCOLLECTION(" + coleccao + ")";
                }
                // console.log("Vamos melhorar isto...");
                var plano = shortcutsPlanos.combo.value[0];
                //var iplano = shortcutsPlanos.combo.value[0];
				var tplano = shortcutsPlanos.combo.value[0];
				
				//Ext.MessageBox.alert('Message', ''+ shortcutsPlanos.combo.value[0] + tplano + '' + shortcutsPlanos.combo.selectedText);
                if (plano < 0) {
                    Ext.MessageBox.show({
                        title: 'Informação incompleta',
                        msg: 'Tem que seleccionar um dos planos em discussão.',
                        width: 400,
                        buttons: Ext.MessageBox.OK
                        // animEl: paragraph
                    });
                }
                else {
                    // console.log(shortcutsPlanos.combo.selectedIndex);                    
                    // var rec = publicidadeForm.getForm().getValues();
                    // console.debug(shortcutsPlanos);                    
                    form_participacao.form.submit({
                        // params: { utilizador: 'jgrocha', the_geom: victor.features[victor.features.length-1].geometry.toString() },
                        params: {
                            utilizador: oUtilizador, // 'jgrocha',
                            the_geom: coleccao,
                            idplano: plano,
							txtplano : tplano
                            //idplano: plano
                        },
                        url: 'forms-submit-participacao.php',
                        success: function(form, action){
                            obj = Ext.util.JSON.decode(action.response.responseText);
                            // console.debug(action.response.responseText);
                            Ext.MessageBox.alert('Message', "Obrigado pela sua participação");
                            victor.destroyFeatures();
                            form_participacao.getForm().reset();
                        },
                        failure: function(form, action){
                            obj = Ext.util.JSON.decode(action.response.responseText);
                            // console.debug(action.response.responseText);
                            // console.debug(obj.errors);
                            // console.debug(obj.errors.reason);
                            Ext.MessageBox.alert('Message', obj.errors.reason);
                        }
                    });
                    
                }
            }
        }, {
            text: 'limpar', //text for submit button
            disabled: true,
            handler: function(){ //what happens when you click the button?
                victor.destroyFeatures();
                form_participacao.getForm().reset();
                // console.log('tudo limpo');
            }
        }]
    });
    // form_user.render('autenticao-form');
    // form_participacao.render('participacao-form');
    
    ////////////////////////////////////////////////
    
    var window = new Ext.Window({
        title: 'Formulário de Registo',
        width: 360,
        height: 590,
        minWidth: 250,
        minHeight: 500,
        layout: 'fit',
        plain: true,
        bodyStyle: 'padding:3px;',
        buttonAlign: 'center',
        items: form_regista,
        
        buttons: [{
            xtype: 'button',
            formBind: true,
            scope: this,
            iconCls: 'icon-disk',
            id: 'submit_button',
            text: 'Registar',
            handler: function(){
                if (form_regista.getForm().isValid()) {
                    form_regista.getForm().submit({
                        url: this.url,
                        scope: this,
                        //envia para o php a string "frm_save"
                        params: {
                            cmd: 'save_frm'
                        },
                        
                        waitMsg: 'Gravar Dados...',
                        success: function(){
                            Ext.MessageBox.alert('Aviso!', 'Obrigado pelo registo!', function(){
                                window.hide();
                            });
                        },
                        failure: function(){
                            Ext.MessageBox.alert('Aviso!', 'Falha no registo!');
                        }
                    });
                }
            }
            
            
        }, {
            text: 'Cancelar',
            handler: function(){
                form_regista.getForm().reset();
            }
        }]
    });
    
    ////////////////////////////// GRAFICOS /////////////////////////
    
    var storeg1 = new Ext.data.JsonStore({
        url: '/estatistica/est_qrymes.php?graf=g1',
        root: 'pesquisa',
        fields: ['quantidade', 'mes']
    });
    
    storeg1.load();
    
    var storeg2 = new Ext.data.JsonStore({
        url: '/estatistica/est_qrymes.php?graf=g6',
        root: 'pesquisa',
        fields: ['nome', 'valor']
    });
    
    storeg2.load();
    
    var g1 = new Ext.Panel({
        title: 'Participações/Mês',
        // renderTo: 'container',
        width: 280,
        height: 300,
        layout: 'fit',
        
        items: {
            xtype: 'columnchart',
            store: storeg2,
            xField: 'nome',
            yField: 'valor',
            xAxis: new Ext.chart.CategoryAxis({
                title: 'Planos em Discussão'
            }),
            yAxis: new Ext.chart.NumericAxis({
                title: 'Numero de Participações'
            }),
            extraStyle: {
                xAxis: {
                    labelRotation: -90
                },
                yAxis: {
                    titleRotation: -90
                }
            },
            listeners: {
                itemclick: function(o){
                    var rec = store.getAt(o.index);
                    Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('mes'));
                }
            }
        }
    });
    /*
     var g2 = new Ext.Panel({
     title: 'Participações/Plano',
     renderTo: 'container',
     width:280,
     height:300,
     layout:'fit',
     items: {
     xtype: 'columnchart',
     store: storeg2,
     xField: 'nome',
     yField: 'valor',
     xAxis: new Ext.chart.CategoryAxis({
     title: 'Plano em Discussão'
     }),
     yAxis: new Ext.chart.NumericAxis({
     title: 'Numero Participações'
     }),
     extraStyle: {
     
     yAxis: {
     titleRotation: -90
     }
     },
     listeners: {
     itemclick: function(o){
     var rec = store.getAt(o.index);
     Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('valor'));
     }
     }
     }
     });
     */
    var tabs = new Ext.TabPanel({
        deferredRender: true,
        xtype: 'tabpanel',
        renderTo: 'container',
        id: 'main-tabs',
        height: 300,
        width: 279,
        activeTab: 0,
        margins: '0 5 5 0',
        /*
         renderTo: container,
         activeTab: 0,
         width:290,
         height:250,
         plain:true,
         border:false,
         hideBorders:true,
         frame:true,
         defaults:{autoScroll: true},*/
        //items: [{
        //	xtype: 'tabpanel',
        //title: 'Gráficos',
        //	id: 'tab1',
        //	activeTab: 0,
        tabPosition: 'bottom',
        items: [g1]
        //}]
    
    });
    
    //tabs.init();
    tabs.render();
    
    ////////////////////////////////////////////////
    
    var viewport = new Ext.Viewport({
        layout: "border",
        items: [{
            region: 'north',
            xtype: 'panel',
            height: 100,
            collapsible: true,
            border: true,
            bodyCssClass: 'painelNorte',
            contentEl: 'norte'
        }, {
            region: "west",
            id: "tools",
            //title: "Menus",
            collapsible: true,
            //border: true,
            width: 280,
            items: [form_user, form_logout, {
                title: 'Escolha o Plano em discussão',
                collapsible: true,
                contentEl: 'atalhoPlanos'
            }, {
                title: 'Seleccione a Freguesia',
                collapsible: true,
                contentEl: 'atalhoFreguesias'
            }, // form_combo_vias,
 gridVias, {
                title: 'Desenhe a Localização Pretendida',
                contentEl: 'barraEdicao'
            }, form_participacao],
            split: true
        }, {
            region: 'east',
            id: 'east-panel',
            title: 'Informações',
            //border: true,
            width: 300,
            split: true,
            collapsedTitle: 'Clique aqui para ver as Informações',
            collapsible: true,
            collapsed: true,
            //collapseMode: 'mini',
            //collapsesize: 5,
            minSize: 200,
            cmargins: '0 10 0 0',
            //headerAsText :true,
            //header:true,
            layout: 'accordion',
            layoutConfig: {
                animate: true
            },
            frame: true,
            items: [{
                title: 'Ajuda',
                id: 'help',
                autoScroll: true,
                contentEl: 'helptext'
            }, {
                title: 'Legenda',
                id: 'legenda',
                autoScroll: true,
                contentEl: 'legendapdm'
            }, {
                title: 'Gráficos',
                id: 'grafico',
                autoScroll: true,
                contentEl: 'container'
            }, {
                title: 'Mais Info',
                id: 'info',
                contentEl: 'infotext'
            }]
        }, mapPanel]
    });
    
    
    form_logout.hide();
    viewport.doLayout();
    
});


