// Es necesario sobrescribir el Radio para corregir el bug del evento check
// (solo se dispara una vez)
Ext.override(Ext.form.Radio, {
    onClick : function(){
        if(this.el.dom.checked != this.checked){
            var els = this.el.up('form').select('input[name='+this.el.dom.name+']');
            els.each(function(el){
                if(el.dom.id == this.id){
                    this.setValue(true);
                }else{
                    Ext.getCmp(el.dom.id).setValue(false);
                }
            }, this);
        }
    }
});

// Extension: boton toggle no desactivable
Ext.ToggleButton = Ext.extend(Ext.Toolbar.Button, {
  onClick: function(e) {
    if (this.pressed){
        return false;
    }
    Ext.ToggleButton.superclass.onClick.apply(this, arguments);
  }
});

// Clase boton para edicion del simbolo ----------------------------------------

Ext.EditImgButton = function(config) {
    Ext.Button.superclass.constructor.call(this);
    if (config) {
        Ext.apply(this, config);
        if (config.listeners) Ext.apply(this,{listeners: config.listeners});
    }
}

Ext.extend(Ext.EditImgButton, Ext.Button, {
    icon: imagesdir + 'ico_nueva_capa.png',
    cls: 'x-btn-icon',

    setValue: function(value) {
        // en este caso se pasa la direccion de la imagen
        var btn = Ext.get('btnSimbolo');
        nuevoSimbolo = value;
        btn.dom.innerHTML = '<tbody><tr><td id="ext-gen221"' +
                            ' class="x-btn-left"><i>&nbsp;</i></td><td id="ext-gen220"' +
                            ' class="x-btn-center"><em unselectable="on"><button ' +
                            'style="background-image: url(' +
                            nuevoSimbolo + ');"' +
                            ' id="ext-gen211" class="x-btn-text" type="button">&nbsp;' +
                            ' </button></em></td><td class="x-btn-right"><i>&nbsp;</i>' +
                            ' </td></tr></tbody>';
    },

    getValue: function() {
	var arr = simboloSel.split('/');
	console.log(simboloSel);
        return arr[arr.length -1];
	//return simboloSel;
    },

    setSize: function(w, h) {
        return true;
    },

    isValid: function() {
    // validacion aqui
        return true;
    }

});

Ext.BLANK_IMAGE_URL = '../ext/ext-2.0/resources/images/default/s.gif';

// Cambiar el encabezado del PropertyGrid a traves de prototype necesariamente
Ext.grid.PropertyColumnModel.prototype.nameText = 'Nombre';
Ext.grid.PropertyColumnModel.prototype.valueText = 'Valor';

var tipoCapa = "";
var vNuevaCapa, vSelSimbolo, vEliminarCapa, tbpEdicion, grid, frmEdicion, frmNuevaCapa, pnlSimbolos;
var anchoTxf = 78;
var anchoCpf = 61;
var imagesdir = './geoweb/plugins/edit/htdocs/gfx/';
var phpdir = './geoweb/plugins/edit/common/';
var nuevoSimbolo = 'simbolos/bug.png';
var simboloSel = "";
var pgPropiedades;

Map.prototype.edit = function(aDisplay)
{
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();

// --------------------- panel: Seleccion de capa a editar ---------------------

    var dataCbxCapaActiva = [
        ['Hospitales', 'Punto', 'ux-edic-punto'],
        ['Puntos de venta y cafererías', 'Punto', 'ux-edic-punto'],
        ['Calles', 'Linea', 'ux-edic-linea'],
        ['Carreteras', 'Linea', 'ux-edic-linea'],
        ['Manzanas', 'Poligono', 'ux-edic-poligono'],
        ['Edificios', 'Poligono', 'ux-edic-poligono'],
        ['Nueva...', 'Nueva']
    ];

    var storeCbxCapaActiva = new Ext.data.Store({
        //fields: ['nombre', 'tipo', 'estiloCss'],
        //data: dataCbxCapaActiva,
        autoLoad: true,
	reader: new Ext.data.JsonReader({
		fields: ['descripcion', 'ideditable', 'type'],
		root: 'rows'
    	}),
	proxy: new Ext.data.HttpProxy({
		url: './geoweb/plugins/edit/common/comboBoxLayer.php'
	 
	})

    });

    var cbxCapaActiva = new Ext.ux.IconCombo({
        id: 'cbxCapaActiva',
//         mode:'remote',
        mode: 'local',
        store: storeCbxCapaActiva,
        valueField: 'ideditable',
        displayField: 'descripcion',
        iconClsField: 'type',
        typeAhead: false,
        editable: false,
        anchor: '100%',
        qTip: 'descripcion',
        tCapa: 'type',
        forceSelection: false,
        triggerAction: 'all',
        emptyText: 'Seleccione...',
        selectOnFocus:true,
        fieldLabel: 'Capa', 
        hideLabel:false,
        listeners: {
            select: function(cbx, rec, ind){
                tipoCapa = rec.data.type.substring(8,rec.data.type.length);
                if (tipoCapa != "Nueva") activarCmps(); else fnNuevaCapa();
                var grid = Ext.getCmp('pg');
                var store = grid.getStore();
                store.filterBy(function(record, id) {
                    return (record.get('type').search(tipoCapa) != -1);
                });

//                 var tbrH = Ext.getCmp('tbarHerramientasEdicion');
//                 tbrH.enable();
                var btnNuevaGeometria = Ext.getCmp('btnNuevaGeometria');
                if (btnNuevaGeometria.disabled) btnNuevaGeometria.enable();

                var btnSeleccionarGeometrias = Ext.getCmp('btnSeleccionarGeometrias');
                if (btnSeleccionarGeometrias.disabled) btnSeleccionarGeometrias.enable();

                var btnActivar = Ext.getCmp('edit_activate');
                if (btnActivar.disabled) btnActivar.enable();
                
                var btnModificarCapaEditable = Ext.getCmp('btnModificarCapaEditable');
                if (btnModificarCapaEditable.disabled) btnModificarCapaEditable.enable();

                var btnEliminarCapaEditable = Ext.getCmp('btnEliminarCapaEditable');
                if (btnEliminarCapaEditable.disabled) btnEliminarCapaEditable.enable();

                var tbarEdicion = Ext.getCmp('tbarEdicion');
                tbarEdicion.enable();

                var tbrP = Ext.getCmp('tbarPropiedades');
                tbrP.enable();
                
                var grid = Ext.getCmp('pg');
                var store = grid.getStore();
                var cantR = store.getCount();
                for (var i = 0; i < cantR; i++){
                    store.getAt(i).data['disabled'] = false;
                }
                grid.getView().refresh();
            }
        }
    });

    // --------------------- panel: capas edicion ------------------------------
    var frmCapas = new Ext.Panel({
        layout: 'form',
        border: false,
        labelWidth: 35,
        bodyStyle: 'padding-left:5px; padding-top:0px;  padding-bottom:2px;' +
                   'padding-right:5px; background-color: #D0DEF0;',
        autoHeight: true,
        items: [cbxCapaActiva]
    });

    // --------------------- barra de herramientas: grid propiedades -----------
    var tbarPropiedades = new Ext.Toolbar ({
        id: 'tbarPropiedades',
        defaults: { xtype: 'button', enableToggle: true },
        items: [{
                xtype: 'tbspacer'
            },{
                icon: imagesdir + 'ico_pg_categorias.png',
                cls: 'x-btn-icon',
                pressed: true,
                toggleGroup: 'grupoOrdenPG',
                tooltip: 'Ordenar por categorías',
                listeners: { click: function(){ storePG.groupBy('group'); } }
            },{
                icon: imagesdir + 'ico_pg_alfabetico.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoOrdenPG',
                tooltip: 'Ordenar alfabéticamente',
                listeners: { click: function(){ storePG.clearGrouping(); } }
            },/*{
                text:'Prueba',
                toggleGroup: 'grupoOrdenPG',
                tooltip: 'fghghg',
                listeners: { click: function(){ storePG.sort('text','ASC'); } }
            },*/{
                xtype: 'tbseparator'
            }]
        });

    // --------------------- barra de herramientas: pie ------------------------
    var tbarPieEdicion = new Ext.Toolbar({
        id: 'tbarPieEdicion',
//         defaults: { xtype: 'button' },
        items: [
            { xtype: 'tbfill' },
            new Ext.Button({
                id:'btnGuardar',
                text: 'Guardar',
                tooltip: 'Mover punto',
                listeners: {
                    click: function(){
                        myform['edit_validate_all'].value = "0";
                        enableTool('edit_save', true);
                        this.disable();
//                         var obj = {};
//                         var cantR = storePG.getCount();
//                         for (var i = 0; i < cantR; i++){
//                             obj[storePG.getAt(i).data.name] = storePG.getAt(i).data.value;
//                         }
//                         alert(Ext.util.JSON.encode(obj));
                    }
                }
            }), new Ext.Button({
                id:'btnCancelar',
                text: 'Cancelar',
                tooltip: 'Mover punto',
                listeners: {
                    click: function(){
                        var elemPanel = Ext.getCmp("pContainer");
                        alert(elemPanel.getSize().width + ', ' + elemPanel.getSize().height);
                    }
                }
            })
        ]
    });

    // --------------------- barra de herramientas: principal ------------------
    var tbarEdicionHerramientas = new Ext.Toolbar({
        id: 'tbarHerramientasEdicion',
        defaults: { xtype: 'button', enableToggle: true },
        items: [{
                xtype: 'tbspacer'
            }, new Ext.ToggleButton({
                id:'btnNuevaGeometria',
                icon: imagesdir + 'ico_edicion.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                tooltip: 'Nueva geometría',
                listeners: {
                    click: function(){
                        if (tipoCapa != ""){
                            switch(tipoCapa){
                            case "punto":
                                Layer_Edit='point'+Ext.getCmp("cbxCapaActiva").getValue();
                                enableTool('edit_point', true);
                               // myform['edit_layer'].value = "edit_point";
                                break;
                            case "linea":
                                Layer_Edit='line'+Ext.getCmp("cbxCapaActiva").getValue();
                                enableTool('edit_line', true);
                               // myform['edit_layer'].value = "edit_line";
                                break;
                            case "poligono":
                                Layer_Edit='polygon'+Ext.getCmp("cbxCapaActiva").getValue();
                                enableTool('edit_polygon', true);
                               // myform['edit_layer'].value = "edit_polygon";
                                break;
                            default:
                                
                            }
                        }
                        else {
                            this.toggle(false);
                            alert("Seleccione una capa");
                        }
                    }
                }
            }), new Ext.ToggleButton({
                id:'btnSeleccionarGeometrias',
                icon: imagesdir + 'ico_editar_activar.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                enableToggle: true,
                tooltip: 'Seleccionar geometrías a editar',
                listeners: {
                    toggle: function(but,pressed){

			AjaxPlugins.Edit.params.edit_scale = Ext.getCmp("escala").getValue().split("'").join("");

                        if (pressed){
                            myform['edit_validate_all'].value = "1";
                            enableTool('edit_select', true);
                        } else {
                            myform['edit_validate_all'].value = "0";
                            enableTool('edit_select', true);
                        }
                    }
                }
            }), new Ext.ToggleButton({
                id:'btnMoverGeometria',
                icon: imagesdir + 'ico_linea_mover.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                tooltip: 'Activar y mover geometría',
                listeners: {
                    click: function(){
                        enableTool('edit_move', true);
                    }
                }
            }), new Ext.ToggleButton({
                id:'btnEliminarGeometria',
                icon: imagesdir + 'ico_linea_eliminar.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                tooltip: 'Activar y eliminar geometría',
                listeners: {
                    click: function(){
                        enableTool('edit_del_feature', true);
                    }
                }
            }),{
                xtype: 'tbseparator'
            }, new Ext.ToggleButton({
                id:'btnAdicionarNodo',
                icon: imagesdir + 'ico_nodo_adicionar.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                tooltip: 'Adicionar nodo',
                listeners: {
                    click: function(){
                        enableTool('edit_add_vertex', true);
                    }
                }
            }), new Ext.ToggleButton({
                id:'btnEliminarNodo',
                icon: imagesdir + 'ico_nodo_eliminar.png',
                cls: 'x-btn-icon',
                toggleGroup: 'grupoHerramientasEdicion',
                tooltip: 'Eliminar nodo',
                listeners: {
                    click: function(){
                        enableTool('edit_del_vertex', true);
                    }
                }
            }),{
                xtype: 'tbseparator'
            },{
                id:'edit_activate',
                icon: imagesdir + 'ico_activar_vertices.png',
                cls: 'x-btn-icon',
                enableToggle: true,
                toggleGroup: 'grupoActivarV',
                tooltip: 'Activar V&eacute;rtices',
                listeners: {
                    toggle: function(but,pressed){
                        if(pressed){
                            myform['edit_validate_all'].value = "1";
                            enableTool('edit_activate', true);
                            
                            var btnMoverGeometria = Ext.getCmp('btnMoverGeometria');
                            var btnEliminarGeometria = Ext.getCmp('btnEliminarGeometria');
                            if (btnMoverGeometria.disabled) btnMoverGeometria.enable();
                            if (btnEliminarGeometria.disabled) btnEliminarGeometria.enable();
                            
                        }else{
//                             myform['edit_validate_all'].value = "0";
//                             enableTool('edit_activate', true);
                        }
                    }
                }
            }
        ]
    });

    // --------------------- barra de herramientas: opciones generales ---------
    var tbarEdicion = new Ext.Toolbar({
        id: 'tbarEdicion',
        style: 'padding-left:5px; padding-top:5px;  padding-bottom:3px;' +
               'padding-rigth:5px; background:#D0DEF0; border:none;',
        defaults: {
            xtype: 'button'
        },
        items: [{
                xtype: 'tbspacer'
            }, new Ext.Toolbar.Button({
                id:'btnNuevaCapaEditable',
                icon: imagesdir + 'ico_nueva_capa.png',
                cls: 'x-btn-icon',
                tooltip: 'Nueva capa editable',
                listeners: {
                    click: function(){
                        fnNuevaCapa();
                    }
                }
            }), new Ext.Toolbar.Button({
                id:'btnModificarCapaEditable',
                icon: imagesdir + 'ico_capa_modificar.png',
                cls: 'x-btn-icon',
                tooltip: 'Modificar capa activa',
                listeners: {
                    click: function(){
                    }
                }
            }), new Ext.Toolbar.Button({
                id:'btnEliminarCapaEditable',
                icon: imagesdir + 'ico_capa_eliminar.png',
                cls: 'x-btn-icon',
                tooltip: 'Eliminar capa activa',
                listeners: {
                    click: function(){
			fnEliminarCapa();
                    }
                }
            }),{
                xtype: 'tbseparator'
            },{
                xtype: 'tbfill'
            }, new Ext.Toolbar.Button({
                icon: imagesdir + 'ico_editar_capas.png',
                cls: 'x-btn-icon',
                tooltip: 'Seleccionar capas editables'
            })
        ]
    });

    // --------------------- grid de propiedades -------------------------------

    // definicion de componentes de edicion que no estan por defecto
    var cedit = new Ext.grid.GridEditor(new Ext.ux.ColorField({selectOnFocus: true}));
    var sedit = new Ext.grid.GridEditor(new Ext.EditImgButton({
        id: "btnSimbolo",
        onClick: function(){ fnSelSimbolo(); }
    }));

    // funciones personalizacion de valores de celdas
    var crenderer = function(color) {
        return '<div style="background-color:' + color + '; width:12px;' +
               ' height:12px; margin: -1px 1px -1px 0px !important;' +
               ' float:left; border: #CCCCCC 1px solid;">&nbsp;' +
               '</div><span>'+color+'</span>';
    };
    var srenderer = function(imgDir) {
        return '<div style="background-image: url('+Feature.util.client_dir +imgDir+'); width:16px;' +
               ' height:16px; margin: -1px -3px -3px -3px !important;' +
               ' text-align:right;">&nbsp;</div>';
    };
    var trenderer = function(imgDir) {
        return '<div style="width:100%;' +
               ' text-align:left;">...</div>';
    };

    // definicion de los campos del grid
    var val_escala = Math.round(Ext.getCmp("escala").getValue().split("'").join(""));
    var data = {
        properties: [{
            'name': 'labelname',
            'text': '(Etiqueta)',
            'value': "",
            'group': 'Dise&ntilde;o',
            'type': 'punto|linea|poligono'
        },{
            'name': 'transparency',
            'text': 'Transparencia',
            'value': 100,
            'group': 'Estilo',
            'type': 'punto|linea|poligono'
        },{
            'name': 'minscale',
            'text': 'Escala minima',
            'value': (val_escala - Math.round(val_escala/4)),
            'group': 'Escala',
            'type': 'punto|linea|poligono'
        },{
            'name': 'maxscale',
            'text': 'Escala maxima',
            'value': (val_escala + Math.round(val_escala/4)),
            'group': 'Escala',
            'type': 'punto|linea|poligono'
        },{
            'name': 'size',
            'text': 'Tama&ntilde;o',
            'value': 2,
            'group': 'Estilo',
	    'type':  'punto|linea|poligono'
        },{
            'name': 'symbol',
            'text': 'S&iacute;mbolo',
            'value': '-',
            'group': 'Estilo',
            'type': 'punto|poligono',
            'editor': sedit,
            'renderer': srenderer
        },{
            'name': 'color',
            'text': 'Color de relleno',
            'value': '#2389ff',
            'group': 'Estilo',
            'type': 'punto|poligono',
            'editor': cedit,
            'renderer': crenderer
        },{
            'name': 'outlineColor',
            'text': 'Color Linea',
            'value': '#0054b4',
            'group': 'Estilo',
            'type': 'punto|linea|poligono',
            'editor': cedit,
            'renderer': crenderer
        },{
            'name': 'labelcolor',
            'text': 'Relleno',
            'value': '#FFFFFF',
            'group': 'Etiqueta',
            'type': 'punto|linea|poligono',
            'editor': cedit,
            'renderer': crenderer
        },{
            'name': 'labelfont',
            'text': 'Fuente',
            'value': "arial",
            'group': 'Etiqueta',
            'type': 'punto|linea|poligono',
            'editor': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                store: new Ext.data.SimpleStore({
                    fields: ['name'],
                    data:[['arial'],['tahoma'],['verdana'],['OpenSymbol'],['Purisa']]
                }),
                typeAhead: true,
                displayField: 'name',
                selectOnFocus: false,
                editable: false,
                triggerAction: 'all',
                mode: 'local'
            }))
        },{
            'name': 'labelsize',
            'text': 'Tama&ntilde;o',
            'value': '1',
            'group': 'Etiqueta',
            'type': 'punto|linea|poligono',
            'editor': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                store: new Ext.data.SimpleStore({
                    fields: ['name','valor'],
                    data:[['Muy Pequeo','0'],['Pequeo','1'],['Mediano','2'],['Grande','3'],['Muy Grande','4']]
                }),
                typeAhead: true,
                displayField: 'name',
		valueField: 'valor',
                selectOnFocus: false,
                editable: false,
                triggerAction: 'all',
                mode: 'local'
            }))
        },{
            'name': 'labeloutlineColor',
            'text': 'Borde',
            'value': '#0054b4',
            'group': 'Etiqueta',
            'type': 'punto|linea|poligono',
            'editor': cedit,
            'renderer': crenderer
        }]
    };


    // data store
    var storePG = new Ext.data.GroupingStore({
        id: 'storePG',
        recordType: Ext.ux.wam.PropertyRecord,
        groupField: 'group',
        sortInfo: {field:'name',direction:'ASC'},
        reader: new Ext.data.JsonReader({
            id: 'name',
            root: 'properties'
        }, Ext.ux.wam.PropertyRecord)
    });
    storePG.loadData(data);

    pgPropiedades = new Ext.ux.wam.PropertyGrid({
        store: storePG,
        id: 'pg',
        frame: false,
        anchor: '100% -111',
//         tbar: tbarPropiedades,
        border: false,
        viewConfig: {
            forceFit: true
        },
        width:'100%',
//         title:'Propiedades',
        view: new Ext.grid.GroupingView({
            forceFit:true,
            groupTextTpl: '{group}',
            emptyGroupText: 'No Group',
            enableGroupingMenu: true,
            showGroupName: true,
            getRowClass: function(record) {
                return (record.data['disabled']==true) ? "x-item-disabled" : "";
            }
        }),
        listeners: {
            headerclick: function(g, ic){
                alert(ic);
            },
            afteredit: function(g, ic){
                Ext.getCmp('btnGuardar').enable();
		if(mainmap.currentEditFeature){
		        var objEstilo = Feature.util.getGrid();	
			if(mainmap.currentEditFeature.type == "polyline"){
			  objEstilo.style.backgroundColor = objEstilo.style.color = objEstilo.style.outlineColor;	
			}
		        objEstilo.attributes.dataId = mainmap.currentEditFeature.attributes.dataId;
			objEstilo.operation = Feature.FEATURE_UPDATE;
		        var f = Feature.config.initialize(mainmap.currentEditFeature, objEstilo);
			mainmap.currentEditFeature = f;
		        mainmap.paintFeature(mainmap.currentEditFeature);
		}
            }
		
        }
    });

    // --------------------- panel de seleccion de geometria activa ------------

    // datos
    dataCbxGeometriaActiva = [
    ];

    // store
    storeCbxGeometriaActiva = new Ext.data.SimpleStore({
        fields: ['nombre', 'tipo', 'estiloCss'],
        data: dataCbxGeometriaActiva,
        autoLoad: true
    });

    // combo
    var cbxGeometriaActiva = new Ext.form.ComboBox({
        id: 'cbxGeometriaActiva',
        mode: 'local',
        tpl: '<tpl for="."><div ext:qtip="{nombre}" class="x-combo-list-item">{nombre}</div></tpl>',
        store: storeCbxGeometriaActiva,
        valueField: 'nombre',
        displayField: 'nombre',
        iconClsField: 'estiloCss',
        typeAhead: true,
        editable: false,
        hideLabel: true,
        anchor: '100%',
        qTip: 'tipo',
        forceSelection: false,
        triggerAction: 'all',
        emptyText: '-no hay geometria activa-',
        selectOnFocus:true,
        fieldLabel: 'Geometr&iacute;a',
        listeners: {
            select: function(cbx, rec, ind){
		var id = rec.get("tipo");
		var length = mainmap.currentLayer.features.length;
		for(var i=0;i<length;i++){
			if(mainmap.currentLayer.features[i].attributes.dataId == id){
				var aFeature = mainmap.currentLayer.features[i];
				var display = mainmap.getDisplay("map");
				var displayFeature = display.getDisplayFeature(aFeature);

				if(mainmap.currentEditFeature && aFeature.id != mainmap.currentEditFeature.id){
					var dark = display.getDisplayFeature(mainmap.currentEditFeature);
					changeStatus(dark, _OFF, true, true);
					darkFeature(mainmap.currentEditFeature);
				}

				mainmap.currentEditFeature = aFeature;
				
				changeStatus(displayFeature, _SEL, true, true);
				Feature.util.loadGrid(aFeature);
				hilightFeature(aFeature);

				return;
			}
		}
            }
        }
    });

    // --------------------- formulario de seleccion de geometria activa -------
    var frmGeometria = new Ext.Panel({
        id:'geom',
        layout: 'form',
        border: false,
        labelWidth: 70,
        bodyStyle: 'padding-left:5px; padding-top:5px;  padding-bottom:0px;' +
                   'padding-right:5px; background-color: #D0DEF0;',
        autoHeight: true,
        items: [ cbxGeometriaActiva ]
    });

    var pnlVacio = new Ext.Panel({
        id: 'pnlVacio',
        border: false,
        height: 280,
//         bodyStyle: 'padding: 10px;',
//         items: [propGrid]
    });


    // formulario para crear una nueva capa editable
    frmNuevaCapa = new Ext.form.FormPanel({
        id: 'frmNuevaCapa',
        border: false,
        labelWidth: 50,
        bodyStyle: 'padding: 10px; background-color: transparent;',
        defaults: {xtype: 'radio', anchor: '100%'},
        items: [{
	    id:'edit_nombre_capa',
            xtype: 'textfield',
            fieldLabel: 'Nombre',
            style: 'margin-bottom: 10px;'
        },{
            id: 'radioPunto',
            fieldLabel: 'Tipo',
            boxLabel: 'Punto',
            name: 'tipoCapa',
            inputValue: 'POINT',
            checked: true,
            listeners: {
                check: function(cb, checked) {
                    if (checked == true) {
                        tipoCapa = 'POINT';
                    }
                }
            }
        },{
            id: 'radioLinea',
            fieldLabel: '&nbsp;',
            labelSeparator: '',
            boxLabel: 'L&iacute;nea',
            name: 'tipoCapa',
            inputValue: 'LINESTRING',
            listeners: {
                check: function(cb, checked) {
                    if (checked == true) {
                        tipoCapa = 'LINESTRING';
                    }
                }
            }
        },{
            id: 'radioPoligono',
            fieldLabel: '',
            labelSeparator: '',
            boxLabel: 'Pol&iacute;gono',
            name: 'tipoCapa',
            inputValue: 'POLYGON',
	    listeners: {
                check: function(cb, checked) {
                    if (checked == true) {
                        tipoCapa = 'POLYGON';
                    }
                }
            }

        }]
    });

    // dataView simbolos
    var store = new Ext.data.JsonStore({
        url: phpdir + 'get-images.php',
        root: 'images',
        fields: [
            'name', 'url',
            {name:'size', type: 'float'}
        ]
    });
    store.load();

    var tpl = new Ext.XTemplate(
        '<tpl for=".">',
            '<div class="thumb-wrap" id="{name}">',
            '<div class="thumb"><img src="{url}" title="{name}"></div>',
            '<span class="x-editable">{shortName}</span></div>',
        '</tpl>',
        '<div class="x-clear"></div>'
    );

    pnlSimbolos = new Ext.Panel({
        id:'images-view',
       // width:135,
      //  height: 100,
        border: false,
        autoScroll: true,
        layout:'fit',

        items: new Ext.DataView({
            store: store,
            tpl: tpl,
            autoHeight:true,
            multiSelect: false,
            overClass:'x-view-over',
            itemSelector:'div.thumb-wrap',
            emptyText: 'No images to display',
            listeners: {
                click: function(dv, id, n) {
                       simboloSel = dv.getRecord(n).data.url;
		       console.log(dv.getRecord(n).data.url);
                }
            }
        })
    });

//     pEdicion = new Ext.Panel({
//         border:false,
//         layout:'fit',
//         defaults:{
// //             autoScroll: true
//         },
//         items:[ pgPropiedades]
//     });

    // --------------------- Panel edicion -------------------------------------
    frmEdicion = new Ext.FormPanel({
        title: 'Edici&oacute;n',
        id: 'frmEdicion',
        border: false,
        tbar: tbarEdicion,
        bbar: tbarPieEdicion,
        items: [frmCapas, tbarEdicionHerramientas, frmGeometria, tbarPropiedades, pgPropiedades]
    });

//     frmEdicion.doLayout();

    var tbrH = Ext.getCmp('tbarHerramientasEdicion');
    tbrH.disable();
    
    var tbrP = Ext.getCmp('tbarPropiedades');
    tbrP.disable();
    
    var grid = Ext.getCmp('pg');
    var store = grid.getStore();
    var cantR = store.getCount();
    for (var i = 0; i < cantR; i++){
        store.getAt(i).data['disabled'] = true;
    }

    var btnModificarCapaEditable = Ext.getCmp('btnModificarCapaEditable');
    if (!btnModificarCapaEditable.disabled) btnModificarCapaEditable.disable();
    var btnEliminarCapaEditable = Ext.getCmp('btnEliminarCapaEditable');
    if (!btnEliminarCapaEditable.enabled) btnEliminarCapaEditable.disable();

    Ext.getCmp('btnGuardar').disable();
    Ext.getCmp('cbxGeometriaActiva').disable();
    Ext.getCmp('btnCancelar').enable();

//     var grid = Ext.getCmp('pg');
//     grid.disable();

    //fnEdicion();


// --------------------- activar componentes segun el tipo de capa -------------
    function activarCmps(){
        
    }

// --------------------- Ventanas ------------------------------------------

   var vEdicion;
    /*function fnEdicion(){
        
        var leftCapas = Ext.getCmp("leftCapas");
        var elemPanel = Ext.getCmp("pContainer");
        var clonePanel = leftCapas.cloneConfig();
        elemPanel.setTitle("Capas y Edici&oacute;n");
        elemPanel.remove(leftCapas);

        var pLeftCapas = new Ext.Panel({
            id:'TabLeftCapas',
            title:'Capas',
            border:false,
            items:[leftCapas]
        });

        var tabPanel = new Ext.TabPanel({
            id:'psi-Tab',
            layoutOnTabChange:true,
            activeTab:0,
            tabWidth:96,
            minTabWidth:96,
            resizeTabs:true
        });

        tabPanel.add(pLeftCapas);
        pLeftCapas.doLayout(true);

        tabPanel.add(frmEdicion);

        elemPanel.add(tabPanel);
        elemPanel.doLayout(true);

        //tabPanel.addClass('liketoolbar');
        tabPanel.activate(1);

    }*/ // Fin funcion ventana edicion

    function fnNuevaCapa(){
        // crear la ventana en el primer click y reusarla
        if(!vNuevaCapa){
            vNuevaCapa = new Ext.Window({
                title: 'Nueva capa',
                layout: 'fit',
                width: 245,
                height: 200,
                y: 140,
                modal:true,
                closeAction: 'hide',
                plain: false,
                bodyStyle: 'padding: 1px; background-color: transparent;',
                items: frmNuevaCapa,
                buttonAlign: 'center',
                buttons: [{
                    text: 'Crear',
                    disabled: false,
		    handler:function(){
			var nameLayer = Ext.getCmp('edit_nombre_capa').getValue();
			var _type = tipoCapa;
			//console.log("nombre:" + nameLayer );
			//console.log("tipo:" + _type );
			// Basic request
			Ext.Ajax.request({
			   url: phpdir + 'AddGeometry.php',
			   success: function(val){;},
			   params: { layername: nameLayer,type:_type}
			});
			vNuevaCapa.hide();	
		    }
                },{
                    text: 'Cancelar',
                    handler: function(){
                        vNuevaCapa.hide();
                    }
                }]
            }); // Fin vNuevaCapa
        }
        vNuevaCapa.show(this);
    } // Fin funcion ventana nueva capa

    function fnEliminarCapa(){
	var tree,nameLayer;
        // crear la ventana en el primer click y reusarla
        if(!vEliminarCapa){
            tree = new Ext.tree.TreePanel({
				 animCollapse:true,
				 enableDD:true,
				 width:200,
				 loader : new Ext.tree.TreeLoader({
   					dataUrl: phpdir + 'comboBoxLayer.php'
				 }),
				 listeners:{
					click:function(node,evt){
					    nameLayer = node.attributes.text;
					}
				 }
	     });
		
	    var root = new Ext.tree.AsyncTreeNode({
                text: 'Capas de Edici&oacute;n', 
		expanded:true,
                draggable:false, // disable root node dragging
                id:'capas'
            });
            tree.setRootNode(root);

            vEliminarCapa = new Ext.Window({
                title: 'Eliminar capa',
                layout: 'fit',
                width: 245,
                height: 200,
                y: 140,
                modal:true,
                closeAction: 'hide',
                plain: false,
                bodyStyle: 'padding: 1px; background-color: transparent;',
                items: [
			tree
		],
                buttonAlign: 'center',
                buttons: [{
                    text: 'Eliminar',
                    disabled: false,
		    handler:function(){
			// Basic request
			Ext.Ajax.request({
			   url: phpdir + 'DropGeometry.php',
			   success: function(val){;},
			   params: { layername: nameLayer}
			});
			vEliminarCapa.hide();	
		    }
                },{
                    text: 'Cancelar',
                    handler: function(){
                        vEliminarCapa.hide();
                    }
                }]
            }); // Fin vNuevaCapa
	    
	   // root.expand(false, /*no anim*/ false);
	    
        }
        vEliminarCapa.show(this);
    } // Fin funcion ventana nueva capa

    function fnSelSimbolo(){
        // crear la ventana en el primer click y reusarla
        if(!vSelSimbolo){
            vSelSimbolo = new Ext.Window({
                title: 'Seleccionar s&iacute;mbolo',
                ///layout: 'fit',
                width: 315,
                height: 200,
                y: 140,
                bodyBorder: true,
                border: false,
                modal:true,
                closeAction: 'hide',
                plain: false,
                bodyStyle: 'padding: 1px; background-color: white;',
                buttonAlign: 'center',
                autoScroll: true,
                items: pnlSimbolos,
                buttons: [{
                    text: 'Aceptar',
                    disabled: false,
                    handler: function(){
                        
                            var btnS = Ext.get('btnSimbolo');
                            if (simboloSel != "") nuevoSimbolo = simboloSel;
                            btnS.dom.innerHTML = '<tbody><tr><td id="ext-gen221" ' +
                            'class="x-btn-left"><i>&nbsp;</i></td><td id="ext-gen220"' +
                            ' class="x-btn-center"><em unselectable="on"><button ' +
                            'style="background-image: url(' +
                            simboloSel + ');"' +
                            ' id="ext-gen211" class="x-btn-text" type="button">&nbsp;' +
                            '</button></em></td><td class="x-btn-right"><i>&nbsp;</i>' +
                            '</td></tr></tbody>';
                      
                        vSelSimbolo.hide();
                    }
                },{
                    text: 'Cancelar',
                    handler: function(){
                        vSelSimbolo.hide();
                    }
                }]
            }); // Fin vNuevaCapa
        }
        vSelSimbolo.show(this);
	tree.render();
	
    } // Fin funcion ventana seleccion de simbolo
    
    DestruirMontarPanel(frmEdicion);
    
}

