Ext.BLANK_IMAGE_URL = '../../ext-2.2/resources/images/default/s.gif';


var lvent_cons;
var lcolumnas = new Array();
var lvalores  = new Array();
var lcampo_select = null;
var lvalor_select = null;
var _layer = new Array();
var _curent = -1;
var laction= 1;

var lstore_campos =  new Ext.data.SimpleStore({
        fields: ['campo'],
        data : this.lcolumnas,
        autoload: true
    });


var lstore_valores =  new Ext.data.SimpleStore({
        fields: ['valor'],
        data : this.lvalores,
        autoload: true
    });



lgrid_campos = new Ext.grid.GridPanel({
		xtype:'grid',
		store: lstore_campos,
          disabled : false,
          name : 'lgrid_campos',
		columns: [{id:'Nombre', sortable: false, header: "Nombre", width: 180, dataIndex: 'campo'}],
                sm: new Ext.grid.RowSelectionModel({
                                                    singleSelect: false,
                                                    listeners: { 'rowselect': function(sm,row,rec)
								    {
                                                                      lcampo_select = lcolumnas[row];
								    },
                                                                 'rowdeselect': function(sm,row,rec)
								    {
                                                                      lcampo_select = null;
								    }
							        }
						   }),
		viewConfig: { forceFit: true },
		width:280,
		height:150,
		frame:true,
		autoExpandColumn: 'Nombre',
          listeners: { 'rowdblclick': function(grid_campos,row,rec)
						{ 
						    var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
						    lpnel_consulta.getForm().findField('txt_pred').setValue(value+lcolumnas[row]);	
						    lcampo_select = lcolumnas[row];
                                  lgrid_campos.disable();
                                  loperadores.enable();
						    laction = 1;
						}
	                   }
});
lgrid_valor = new Ext.grid.GridPanel({
			xtype:'grid',
               id: 'lgrid_valor',
			store: lstore_valores,
               disabled : true,
			columns: [{id:'Valor', sortable: true, header: "Valor", width: 180, dataIndex: 'valor'}],
			sm: new Ext.grid.RowSelectionModel({
                                                    singleSelect: true,
                                                    listeners: { 'rowselect': function(sm,row,rec)
								    						{
                                                                      	lvalor_select = lvalores[row];
						 							     }
							        }
						   }),
			viewConfig: { forceFit: true},
			width:280,
			height:150,
			frame:true,
			autoExpandColumn: 'Nombre',
                         listeners: { 'rowdblclick': function(grid_campos,row,rec)
				                   { 
				           			var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
		                           		lpnel_consulta.getForm().findField('txt_pred').setValue(value+'\''+lvalores[row]+'\'');
									lgrid_valor.disable();
		                            loperadores.enable();
									laction = 2;
				       		    }
	                             }
                });


var lstore_layer =  new Ext.data.SimpleStore({
                                              fields: ['layer','conex','data','type','proyect']
                                            });


var combo_layer = new Ext.form.ComboBox({
               xtype:'combo',	
               store: lstore_layer,
			typeAhead: true,
               id: 'cboxLayer',
			displayField:'layer',
               laberAlign: 'left',
			forceSelection: true,
	        	mode: 'local',
			triggerAction: 'all',
			emptyText:"Selecione una capa",
			selectOnFocus:true,																					
			fieldLabel: 'Capas Visibles',
			anchor:'98%',
               listeners:{'select': function(combo_layer,record,index)
	                     {  
                               _curent=index;
                               Get_Columnas(_layer[index][1],_layer[index][2]);
			           }	
			  }
		}); 

loperadores = new Ext.form.FieldSet({
							title: 'Operaciones',																	
							height:80,
                                   disabled: true,
							width: 580,
							items: 
							[{
								layout:'column',
								items:
								[{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '=',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'= ');
										  Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '<',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'< ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '>',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'> ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'COMO',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'LIKE ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '%',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'% ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'EN',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'IN ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'NO EN',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'NOT IN ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '<=',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'<= ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '>=',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'>= ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : '!=',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'!= ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'DISTINTO',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'ILIKE ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'Y',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'AND ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'O',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'OR ');
                                                    Active_Acction();
										}
									}]
								},{
									columnWidth:0.142,
									defaultType: 'button',
									items: 
									[{
										text : 'NO',
										disabled : false,
										cls: 'btn_operacion',
										handler : function()
										{
										  var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
										  lpnel_consulta.getForm().findField('txt_pred').setValue(value+' '+'NOT ');
                                                    Active_Acction();
										}
									}]
								}
								]
							}]
						});


lpnel_consulta = new Ext.FormPanel({
		buttonAlign	: 'right',
        	url:'geoweb/plugins/layerQuery/htdocs/js/php/get_columns.php',
        	frame		: true,
		items : [{
				layout:'column',
				items:	[      {
						columnWidth: 1,
						style:'margin:5 5 5 5;',
						autoHeight:true,
						items:[combo_layer]
					},			
					{
						columnWidth: 0.5,
						style:'margin:0 5 0 5;',
						autoHeight:true,
						items:[lgrid_campos]
					},{
						columnWidth: 0.5,
						layout:'form',
						style:'margin:0 5 0 5;',
						autoHeight:true,
						items:[lgrid_valor]
					}/*,{
						columnWidth: 0.5,
						style:'margin:0 5 0 0;',
						/*buttons: 
						[{
							text : 'Agregar',
							disabled : false,
		                         handler : function()
							{
                                     if(lcampo_select!=null)
							   {
						               var value = lpnel_consulta.getForm().findField('txt_pred').getValue();
				                               lpnel_consulta.getForm().findField('txt_pred').setValue(value+lvalor_select);	
                                 		               lcampo_select = columnas[row];
							    }
							  else
							     Ext.Msg.alert("Aviso", "Debe seleccionar primero algun campo");
							}
						}]
					}*//*,{
						columnWidth: 0.5,
						style:'margin:0 5 0 0;'
						buttons: 
						[{
							text : 'Mostrar',
							disabled : false,
							handler : function()
							{
                                       if(lcampo_select!=null)
                                       {
							    		Get_Valores(curent_conex,curent_data,lcampo_select);
							    }
							    else
							    		Ext.Msg.alert("Aviso", "Debe seleccionar primero algun valor");
							}
						}]
					}*/,{
						columnWidth: 1,
						style:'margin:0 5 0 5;',
						items: loperadores
					},{
	  			          columnWidth: 1,
						style:'margin:0 0 0 5;',
						items:[{
								xtype:'fieldset',
								title: 'Predicado de la Consulta',			
								height:80,
								width: 580,
								items:[{
									width: 555,
									height:40,
									xtype: 'textarea',
									hideLabel: true,
									id : 'txt_pred',
								 }]
							}]
					},{
						columnWidth:0.4,
						layout:'column',
						style:'margin:0 5 5 5;',
						items:	[{}]
					},{
						columnWidth:0.6,
						layout:'column',
						items:	[{
							columnWidth:0.25,
							style:'margin:0 1 0 0;',
							buttons: 
							[{
								text : 'Limpiar',
								disabled : false,
								handler: function ()
								{
                                           lgrid_campos.enable();
								   lgrid_valor.store.removeAll();
								   lgrid_valor.disable();
								   loperadores.disable();
								   lpnel_consulta.getForm().findField('txt_pred').setValue('');
								}
							}]
						},{
							columnWidth:0.25,
							style:'margin:0 1 0 0;',
							buttons: 
							[{
								text : 'Validar',
								disabled : false,
                                        handler: function ()
								{
	                                     Validar(curent_conex,curent_data,lpnel_consulta.getForm().findField('txt_pred').getValue());
								}
							}]										
						},{
							columnWidth:0.25,
							style:'margin:0 1 0 0;',
							buttons: 
							[{
								text : 'Aceptar',
								disabled : false,
                                        handler: function ()
								{
	                                     lpnel_consulta.form.submit({ 
									    success: function ( result, laction)
									    {
                                                   if(lpnel_consulta.getForm().findField('txt_pred').getValue()!="")                                                      
                                           			{
		                                               document.getElementById("Qlayer").value = _layer[_curent];
          		                                	  document.getElementById("Qfilter").value= lpnel_consulta.getForm().findField('txt_pred').getValue();
                                                         lgrid_valor.store.removeAll();
 										       lgrid_campos.store.removeAll();
          		                                     doSubmit();
		                                             }
										 
           			                           //datos_conex = conex_posgis[selectedItem];                   
                                                 },   
                                                 failure: function ( result, laction )
                                                 { 
                                                	     Ext.Msg.alert("Error", 'Verifique la sintaxis');
										},									    params:{string_db: curent_conex, query: curent_data, where: lpnel_consulta.getForm().findField('txt_pred').getValue(), accion: 'e'}
								  });
                                         
  
								}
							}]										
						},{
							columnWidth:0.25,
							style:'margin:0 1 0 0;',
							buttons: 
							[{
								text : 'Cancelar',
								disabled : false,
								handler: function ()
								{
               					  lpnel_consulta.getForm().findField('txt_pred').setValue('');
								  lgrid_valor.store.removeAll();
         							  lgrid_campos.store.removeAll();
                                          lvent_cons.hide();
								}
							}]										
						}]
					}]
			}]
	})


Ext.onReady(function(){ 
      var button = Ext.get('tb6f');
      button.on('click', function(){
	 InitLoad();
      lcolumnas = new Array();
	 lvalores  = new Array();
	 lcampo_select = null;
	 lvalor_select = null;
      lgrid_campos.store.removeAll();
      lgrid_valor.store.removeAll();
      lgrid_campos.enable();
      lgrid_valor.disable();
      loperadores.disable();
      combo_layer.reset();
      if(!lvent_cons)
        {  				   lvent_cons = new Ext.Window({
								  title	    : 'Generador de Consultas',
								  renderTo    : document.body,
								  layout	    : 'fit',
								  width  	    : 620,
								  height	    : 450,
                                          resizable   : false,
								  closeAction : 'hide',
								  plain       : true,
							       items  	    : lpnel_consulta                      
						 });
        } 
       lvent_cons.show();
        });
});

function InitLoad()
{
  CartoWeb.trigger('LayerInfo.Init',"doSubmit()"); 
}


function Validar(conex_string,data,query)
{
    lpnel_consulta.form.submit({ 
    success: function ( result, laction)
	{
             Ext.Msg.alert("Ok", 'Consulta Correcta');                    
        },   
    failure: function ( result, laction )
        { 
  	     Ext.Msg.alert("Error", 'Verifique la sintaxis');
	},    params:{string_db: conex_string, query: data, where: query, accion: 'e'}
  });
}

function Get_Valores(conex_string, data,campo_s)
{
    lpnel_consulta.form.submit({ 
    success: function ( result, laction)
	{
         
          obj = Ext.util.JSON.decode(laction.response.responseText);   
          lvalores = new Array();
          for(i=0 ;i<obj.data.length;i++)
              lvalores[i] = new Array(obj.data[i]);             

       	 lgrid_valor.store.removeAll();
 	 lgrid_valor.store.loadData(lvalores);             
        },   
    failure: function ( result, laction )
        { 
         lgrid_valor.store.removeAll();
         obj = Ext.util.JSON.decode(laction.response.responseText);    
  	 Ext.Msg.alert("Error", obj.reason);
	},    params:{string_db: conex_string,query: data,campo: campo_s,accion: 'v'}
    });
}

function Active_Acction()
{
   loperadores.disable();
   if(laction==1)
      lgrid_valor.enable();
   if(laction==2)
      lgrid_campos.enable();
   Get_Valores(curent_conex,curent_data,lcampo_select);
   laction = 0;
   
}

function Get_Columnas(conex_string, data)
{
    this.curent_conex = conex_string;
    this.curent_data  = data;
    lpnel_consulta.form.submit({ 
    success: function ( result, laction)
	  {         
          obj = Ext.util.JSON.decode(laction.response.responseText);   
          lcolumnas = new Array();
                for(i=0 ;i<obj.data.length;i++)
                    lcolumnas[i] = new Array(obj.data[i]);
          lgrid_campos.store.removeAll();
          lgrid_campos.store.loadData(lcolumnas);                       
        },   
    failure: function ( result, laction )
        { 
         lgrid_valor.store.removeAll();
         lgrid_campos.store.removeAll();
         obj = Ext.util.JSON.decode(laction.response.responseText);    
  	    Ext.Msg.alert("Error", obj.reason);
	  },    params:{string_db: conex_string,query: data,accion: 'c'}
    });
}



