
var agregarCapaVect;
var fAgregarCapaVect;

var fileset;
var datos_file = new Array();
var grid_vect;

var width;
var height; 
function Form_Create(pfielset)
{

var store_vect = new Ext.data.SimpleStore({
                 fields:[
					  {name: 'tabla', mapping:'name'},
					  {name: 'proyect', mapping:'proyect'},
					  {name: 'tipo', mapping:'geometry'},
			 		  {name: 'countTipo', mapping:'length'},
				   ],
			    data: datos_file,
			    sortInfo:{field: 'tabla', direction: "ASC"}
			});

 grid_vect= new Ext.grid.GridPanel({
        store:store_vect, 
        columns: [
            {id:'Capa',header: "Tabla", autoWidth:true, menuDisabled: true , dataIndex: 'tabla'},
	       {header: "Tipo", autoWidth: true, menuDisabled: true, dataIndex: 'tipo'},
	       {header: "Proyecci&oacute;n", autoWidth:true, menuDisabled: true,align:'text-align : left', dataIndex: 'proyect'},
  	    	  {header: "Cantidad de Filas", autoWidth:true, menuDisabled: true, dataIndex: 'countTipo'}
        ],
        sm: new Ext.grid.RowSelectionModel({
	                singleSelect: false,
	                listeners: {rowselect: function(sm, row, rec)
					 		{
	                                       temp_  =  sm.getSelections();
	                                       request_ = new Array();
	                                       for (i=0;i<temp_.length;i++)
	                                       request_.push(temp_[i].data);
		                    	 }	
	                	   }
	            }),
        frame:true,
        autoHeight: true,
        autoWidth: true,
        collapsible: true,
        animCollapse: false,
        id: 'gridVect',
        title: 'Datos Capas Geoespaciales',
        iconCls: 'icon-grid'
 });


fAgregarCapaVect = new Ext.FormPanel({
	labelAlign  : 'left',
   	buttonAlign : 'right',
     frame	  : true,                            
     fileUpload  : true, 
	url: 'geoweb/plugins/fileLoader/htdocs/php/loadFile.php',
	items : [{
			layout:'column',
			items:	[{
						columnWidth:1,
						layout:'form',
						
						autoHeight:true,
						autoWidht:true,
						items:[{
								layout:'column',
								border: false,
								items:[{
										columnWidth:1,
                                                  items:[{	
												layout:'form',
												items:pfielset
                                                        }]
								        }]
							},   grid_vect,
                                   {
								layout:'column',
								items:
									[{
										columnWidth:1,
										buttonAlign: 'rigth',
										layout:'form',
										items:[{
											buttons: 
												[{
													text : 'Aceptar',
													disabled : false,
													handler: function()
														{
														 VectpreDoSubmit();
                                                                      }
												},{
													text : 'Cancelar',
													disabled : false,
													handler: function()
														{
                                                                         datos_file = new Array();
                                                                         grid_vect.store.removeAll();
														   agregarCapaVect.close();														   
														}
										                }]	
											}]									
									}]
							}]
					}]
			}]
	})

}

function  VectpreDoSubmit()
{  
	var obj_result ;
	if(fAgregarCapaVect.form.isValid())
	{    
		fAgregarCapaVect.form.submit({
		      waitTitle: "Por favor espere",
		      waitMsg: 'Subiendo datos al servidor...',
			 success: function(result, action)
			  {
				result = Ext.util.JSON.decode(action.response.responseText);
				datos_tablas = Ext.util.JSON.encode(result.data);
				document.getElementById("f_type").value  = 'FromFile';
				document.getElementById("f_data").value  = datos_tablas;
                    datos_file = new Array();
				grid_vect.store.removeAll();
				doSubmit();
				agregarCapaVect.close();  
		           
			  },
			 failure: function ( result, action )
			  { 
		  	     Ext.Msg.alert("Error", "Archivo dañado");
			  },
		 params:{action : 'l'}
		 });
	    

	}	
	
   


}

function File_Type_Loader(file)
{
       switch(file)
         {
            case 'gml':
                  {
			     fileset = new Ext.form.FieldSet({
						fileUpload: true,
                              border : true,
						frame: true,
						title: 'Fichero',
						autoHeight: true,
                              labelWidth: 25,
						defaults: {
						  	       anchor: '80%',
								  msgTarget: 'side'
							     },
						items:[{
				                    xtype: 'fileuploadfield',
                                        Tipo : 'GML',
                                        id: 'fileGML',
								name: 'userfile'					        
							 }]
					});
                     this.height = 250;
                     break;
                  }
            case 'mif':
		  {
                    fileset = new Ext.form.FieldSet({
						title: 'Ficheros',
						fileUpload: true,
                              border : true,
						frame: true,
						autoHeight: true,
					     labelWidth: 25,
						defaults: {
						  	       anchor: '80%',
								  xtype: 'fileuploadfield',
								  msgTarget: 'side'
							     },
						items:[{
                                        Tipo : 'MIF',id: 'fileMIF',
								name: 'userfile1'                                        
							  },{
                                        Tipo : 'MID',id: 'fileMID',
								name: 'userfile'	
							  }]
			});
                    this.height = 270;
                    break;
                  }
             case 'tab':  //tab/dat/map/id
		  {
                    fileset = new Ext.form.FieldSet({
						title: 'Ficheros ',
						fileUpload: true,
                              border : true,
						frame: true,
						autoHeight: true,
						labelWidth: 25,
						defaults: {
						  	       anchor: '80%',
								  xtype: 'fileuploadfield',
								  msgTarget: 'side'
								},						
						items:[{
				                    Tipo : 'TAB', id: 'fileTAB',
				                    name: 'userfile'	
							 },{								
				                    Tipo : 'DAT', id: 'fileDAT',
								name: 'file_1'	  
							 },{
				                    Tipo : 'MAP', id: 'fileMAP',
								name: 'file_2'	
							 },{
				                    Tipo : 'ID',id: 'fileID',
								name: 'file_3'	
							 },{
				                    Tipo : 'IND',id: 'fileIND',
								name: 'file_4'	
							 }]
					});
				this.height = 340;
                    break;  
		  }
               case 'shp': 
		  {
                    fileset = new Ext.form.FieldSet({
						title: 'Ficheros',
						fileUpload: true,
                              border : true,
						frame: true,
						labelWidth: 25,
						autoHeight: true,
						defaults: {
						  	       anchor: '80%',
								  xtype: 'fileuploadfield',
								  msgTarget: 'side'
								},
						items:[{
				                    Tipo : 'SHP', id: 'fileSHP',
				                    name: 'userfile'	
							 },{								
				                    Tipo : 'SHX', id: 'SHX',
								name: 'file_1'	  
							 },{
				                    Tipo : 'DBF', id: 'fileDBF',
								name: 'file_2'	
							 }]
			});
				this.height = 290;
                    break;  //(shp/shx/ddf,prj)
		  }
            default:
                 {
                   alert('Tipo incorecto')
                 }
         }
 
     Form_Create(fileset);
	agregarCapaVect = new Ext.Window({
			 title	   : 'Agregar capa vectorial',
                renderTo    : document.body,
                layout      : 'fit',
                resizable   : false,
                modal       : true,
                width       : 450,
                closeAction :'close',
                plain       : true,
			 items	   : fAgregarCapaVect
            });
        agregarCapaVect.setHeight(height);
        agregarCapaVect.show();
}


Ext.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
    /**
     * @cfg {String} buttonText The button text to display on the upload button (defaults to
     * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
     * value will be used instead if available.
     */
    buttonText: 'Browse...',

    /*
     * Extenciones de los archivos a cargar
     */
    Tipo: '',
    /**
     * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
     * text field (defaults to false).  If true, all inherited TextField members will still be available.
     */
    buttonOnly: false,
    /**
     * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
     * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
     */
    buttonOffset: 3,
    /**
     * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
     */

    // private
    readOnly: true,
    
    /**
     * @hide 
     * @method autoSize
     */
    autoSize: Ext.emptyFn,
    
    // private
    initComponent: function(){
           this.addEvents(
            /**
             * @event fileselected
             * Fires when the underlying file input field's value has changed from the user
             * selecting a new file from the system file selection dialog.
             * @param {Ext.form.FileUploadField} this
             * @param {String} value The file value returned by the underlying file input field
             */
            'fileselected'
        );
	    	Ext.apply(this,{ 
				  labelwidth:  100,
				  emptyText:   'Agrege un archivo '+	this.Tipo,
				  fieldLabel:  this.Tipo,
                      allowBlank:  false,
                      invalidText: 'Agrege un fichero del formato especificado.',
                      blankText:   'Debe seleccionar un archivo.', 
				  buttonCfg: {
							 text: '',
				 			 iconCls: 'upload-icon'
				 		   },
				  validator: function (value)
				 		   {   
				                re = value.split('.');
                                    if(re.length>1)
							    if(re[1] == this.Tipo.toLowerCase() || re[1] == this.Tipo.toUpperCase())
								 return true;
							 else
								 return false;
			 			   }
				
			});      
        Ext.form.FileUploadField.superclass.initComponent.call(this);
        
       
    },
    
    // private
    onRender : function(ct, position){
        Ext.form.FileUploadField.superclass.onRender.call(this, ct, position);
        
        this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
        this.el.addClass('x-form-file-text');
        this.el.dom.removeAttribute('name');
        
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input', 
            type: 'file',
            size: 1
        });
        
        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
            text: this.buttonText
        });
        this.button = new Ext.Button(Ext.apply(btnCfg, {
            renderTo: this.wrap,
            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
        }));
        
        if(this.buttonOnly){
            this.el.hide();
            this.wrap.setWidth(this.button.getEl().getWidth());
        }
        
        this.fileInput.on('change', function(){
            var v = this.fileInput.dom.value;
            this.setValue(v);
            this.fireEvent('fileselected', this, v);
        }, this);


        this.on('fileselected', function()
          { 
         		Up_File_to_Server(this.Tipo);
        	});
    },
    
    // private
    getFileInputId: function(){
        return this.id+'-file';
    },
    
    // private
    onResize : function(w, h){
        Ext.form.FileUploadField.superclass.onResize.call(this, w, h);
        
        this.wrap.setWidth(w);
        
        if(!this.buttonOnly){
            var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
            this.el.setWidth(w);
        }
    },
    
    // private
    preFocus : Ext.emptyFn,
    
    // private
    getResizeEl : function(){
        return this.wrap;
    },

    // private
    getPositionEl : function(){
        return this.wrap;
    },

    // private
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }
    
});
Ext.reg('fileuploadfield', Ext.form.FileUploadField);


function Up_File_to_Server(Tipo)
{
   if(fAgregarCapaVect.form.isValid())
	   {
		  fAgregarCapaVect.form.submit({
                waitTitle: 'Por favor espere',
		      waitMsg: 'Analizando el archivo...',
			 success: function(result, action)
			  {
				 var obj = Ext.util.JSON.decode(action.response.responseText);
				 datos_file = obj.data;
				 grid_vect.store.removeAll();
				 grid_vect.store.loadData(datos_file);
			  },
			 failure: function ( result, action )
			  { 
                    obj = Ext.util.JSON.decode(action.response.responseText);
		  	     Ext.Msg.alert("Error", obj.reason.toString());
			  },
			 params:{action : 'a'}
		       
			});
	   }
}




