//['3', 'Acer'], 
var marca = [
['%', 'Todas Las Marcas'], ['84', '3COM'], ['1', 'A4 Tech'], ['2', 'Accesorios Para Ipod'], 
['4', 'Acteck'], ['5', 'AMD'], ['6', 'AOC'], ['71', 'Aopen'], ['7', 'Apc'], ['8', 'Apex'], ['9', 'Aspel'], 
['80', 'Asus'], ['77', 'Barkan'], ['10', 'Benq'], ['11', 'Biostar'], ['12', 'Broadway'], ['13', 'Brother'],
['14', 'Canon'], ['89', 'Case Logic'], ['15', 'Cdp'], ['16', 'Centra Ups'], ['17', 'Complet'], 
['18', 'Computacion En Accion'], ['83', 'Conceptronic'], ['19', 'Creative'], ['23', 'D-Link'], 
['20', 'Daewoo'], ['21', 'Datapac'], ['78', 'Datashield'], ['85', 'Dell'], ['22', 'Discos Duros'],
['76', 'Disney'], ['24', 'Easy Line'], ['90', 'Ec Line'], ['25', 'Ecs'], ['87', 'Emachines'],
['26', 'Encore'], ['27', 'Epson'], ['74', 'Exigo'], ['28', 'Foxconn'], ['86', 'Gateway'], ['29', 'Genius'], 
['73', 'Ghia'], ['30', 'Hp'], ['31', 'Imation'], ['32', 'Intel'], ['33', 'Interwrite'], ['34', 'Iogear'], 
['35', 'Ipod'], ['36', 'Kingston'], ['37', 'Kme'], ['82', 'Koblenz'], ['38', 'Labtec'], ['39', 'Lenovo/Ibm'], 
['75', 'Lexmark'], ['40', 'Lg'], ['41', 'Linea Italia'], ['42', 'Linksys'], ['43', 'Lite-On'], ['44', 'Logitech'], 
['45', 'Maxtor'], ['46', 'Microsoft'], ['47', 'Msi'], ['94', 'Offiho'], ['48', 'Panda'], ['49', 'Pc Chips'], 
['50', 'Perfect Choice'], ['51', 'Pinnacle'], ['52', 'Pleomax/Samsung'], ['79', 'Pny'], ['53', 'Powercolor'], 
['54', 'Prolicom'], ['55', 'Samsung'], ['56', 'Sandisk'], ['57', 'Seagate'], ['58', 'Silimex'], ['59', 'Smart Control'], 
['60', 'Smc'], ['61', 'Sony'], ['72', 'Space'], ['91', 'Star Micronics'], ['62', 'Supermicro'], ['92', 'Supertalent'], 
['63', 'Targus'], ['64', 'Tde'], ['81', 'Tech Zone'], ['65', 'Toshiba'], ['66', 'Transcend'], ['67', 'Tripp-Lite'], 
['70', 'Varios'], ['68', 'Verbatim'], ['88', 'Vica'], ['69', 'Zogis'], ['93', 'Zone Alarm']
	];

var grupo = [	
['%', 'Todos los grupos'], ['261', 'Accesorios'], ['262', 'Aire Acondicionado'], ['263', 'Almacenamiento'],
['264', 'Audifonos y Micro'], ['266', 'Audio y Sonido'], ['267', 'Back Pack (Mochila)'], 
['1182', 'Bases para Pantallas LCD y Plasma'], ['268', 'Bocinas'], ['269', 'Cables'], ['270', 'Camaras'],
['281', 'Consumibles'], ['1881', 'Controles'], ['282', 'Copiadora'], ['283', 'Digitalizador'],
['284', 'Energia'], ['286', 'Fax'], ['287', 'Gabinetes'], ['288', 'Games'], ['2063', 'Herramientas'],
['289', 'Impresoras'], ['462', 'Kits'], ['290', 'Maletines'], ['291', 'Memorias'], ['292', 'Monitores'],
['293', 'Mouse'], ['294', 'Muebles para Oficina'], ['295', 'Multifuncionales'], ['1561', 'Netbook'],
['296', 'Notebook'], ['297', 'Opticos'], ['298', 'Paquetes'], ['299', 'PCs'], ['300', 'Pda'],
['1961', 'Polizas De Garantia'], ['301', 'Porta Retrato Digital'], ['2101', 'Presentador'], ['302', 'Procesadores'],
['1641', 'Punto De Venta'], ['1821', 'Rack'], ['303', 'Redes'], ['304', 'Reproductores'], ['285', 'Scanner'],
['305', 'Seguridad'], ['306', 'Servidores'], ['307', 'Software'], ['308', 'Solucion Interwrite'], ['2502', 'Soluciones Gms'],
['1183', 'Soportes Para Videoproyectores'], ['310', 'Tarjeta Controladora'], ['309', 'Tarjeta Madre'],
['461', 'Teclado Y Mouse'], ['311', 'Teclados'], ['312', 'Telefonia'], ['313', 'Televisor'],
['314', 'Tipo De Conectividad'], ['363', 'Unidad De Negocio Hp'], ['315', 'Ventiladores'], ['316', 'Video'],
['317', 'Videoproyector']
];


function existenciaRenderer (value) {
	if (value < 1) {
		value = 'Sobre pedido';
	}
	return value;
}
function imagenRenderer (value, p, record) {
	return String.format ('<table border=0 widht="100%"><tr><td><img width="80" src="{0}" /></td><td><b>{1}</b><br>{2}</td></tr></table>', value, record.data['Name'], record.data['Code']);
}

MyDataStore = new Ext.data.Store({
	id: 'MyDataStore',
	proxy: new Ext.data.HttpProxy({
		url: 'gateway.php',      // File to connect to
		method: 'POST'
	}),
	baseParams:{task: "List"}, // this parameter asks for listing
	reader: new Ext.data.JsonReader({   // we tell the datastore where to get his data from
		totalProperty: "total",
		root: "results",
		id: "JsonReader"
	},[ 
		{name: 'Id', type: 'string', mapping: 'Id'},
		{name: 'Image', type: 'string', mapping: 'Image'},
		{name: 'Code', type: 'string', mapping: 'Code'},
		{name: 'Key', type: 'string', mapping: 'Key'},
		{name: 'Name', type: 'string', mapping: 'Name'},
		{name: 'Quantity', type: 'int', mapping: 'Quantity'},
		{name: 'Cost', type: 'float', mapping: 'Cost'}
	]),
	sortInfo:{field: 'Cost', direction: "ASC"}
});

MyColumnModel = new Ext.grid.ColumnModel(
[
	//{ readOnly: true, width: 30, hidden: false, sortable:false },
	{ header: 'Artículo', readOnly: true, dataIndex: 'Image', width: 500, hidden: false, renderer: imagenRenderer },
	{ header: 'Id', readOnly: true, dataIndex: 'Id', width: 100, hidden: true, sortable:false },
	{ header: 'Codigo', readOnly: true, dataIndex: 'Code', width: 100, hidden: true },
	{ header: 'Articulo', readOnly: true, dataIndex: 'Name', width: 300, hidden: true },
	{ header: 'Existencia', readOnly: true, dataIndex: 'Quantity', width: 100, hidden: false, renderer: existenciaRenderer, align:'center' },
	{ header: 'Precio', readOnly: true, dataIndex: 'Cost', width: 100, hidden: false, renderer: Ext.util.Format.usMoney, align:'right' }
]);
MyColumnModel.defaultSortable= true;	

var textoLibre = new Ext.form.TextField({
	id: 'textoBuscar',
	emptyText:'búsqueda libre...',
	mode: 'local',
	triggerAction: 'all',
	selectOnFocus:true	
});


var storeMarca = new Ext.data.SimpleStore({
	fields: ['value', 'marca'],
	data : marca
});
	
var comboMarca = new Ext.form.ComboBox({
	id: 'comboMarca',
	store: storeMarca,
	displayField:'marca',
	valueField:'value',
	typeAhead: true,
	mode: 'local',
	triggerAction: 'all',
	emptyText:'Seleccione marca...',
	selectOnFocus:true,
	allowBlank: false,
	forceSelection: false,
	width:135
});

var storeGrupo = new Ext.data.SimpleStore({
	fields: ['value', 'grupo'],
	data : grupo
});
	
var comboGrupo = new Ext.form.ComboBox({
	id: 'comboGrupo',
	store: storeGrupo,
	displayField:'grupo',
	valueField:'value',
	typeAhead: true,
	mode: 'local',
	triggerAction: 'all',
	emptyText:'Seleccione grupo...',
	selectOnFocus:true,
	allowBlank: false,
	forceSelection: false,
	width:170
});

var botonBuscar = new Ext.Toolbar.Button({
	text: 'Buscar',
	handler: onBuscarClick,
	//cls: 'none',
	tooltip: {text:'De click en este botï¿½n para iniciar la bï¿½squeda de acuerdo al criterio definido en los campos anteriores', title:'Buscar...'}
});

var botonReiniciar = new Ext.Toolbar.Button({
	text: 'Reiniciar',
	handler: onReiniciarClick,
	cls: 'none',
	tooltip: {text:'De click en este botï¿½n para reiniciar los campos.', title:'Reiniciar...'}
});

var MyListingGrid =  new Ext.grid.GridPanel({
    id: 'MyListingGrid',
    ds: MyDataStore,
    cm: MyColumnModel,
	cls: 'in-panel',
	loadMask: true,
	enableDragDrop: true,
    enableColLock:false,
	border: false,
	    tbar: ["&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",textoLibre, "&nbsp;&nbsp;&nbsp;", comboMarca, "&nbsp;&nbsp;&nbsp;", comboGrupo, "&nbsp;&nbsp;&nbsp;", botonBuscar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", botonReiniciar],

    selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
	viewConfig: {
        forceFit: false
    }
  });
  


function onBuscarClick(btn){
	var Grupo = Ext.getCmp('comboGrupo').getValue();
	var Marca = Ext.getCmp('comboMarca').getValue();
	var Buscar = Ext.getCmp('textoBuscar').getValue();
	if (Marca=='') {Marca = '%';}
	if (Grupo=='') {Grupo = '%';}
	if ((Grupo=='%') && (Marca=='%') && (Buscar=='')) {
		Ext.Msg.alert('Advertencia', 'Introduzca un criterio de búsqueda menos amplio,<br>el criterio actual no es permitido.'  );
	} else {
		MyListingGrid.loadMask.show();
		MyDataStore.load({params:{BusquedaLibre: Buscar, Marcas: Marca, Grupos: Grupo} });
	}
	return 0;
}
function onReiniciarClick(btn){
	Ext.getCmp('comboGrupo').setValue('%');
	Ext.getCmp('comboMarca').setValue('%');
	Ext.getCmp('textoBuscar').setValue('');
	return 0;
}

var buscar = {
	id: 'buscar-panel',
	layout: 'fit',
	cls: 'main-panel',
	items: [MyListingGrid]
};



var buscador = function(f, e){
	if (e.getKey() == e.ENTER && f.getValue().length !== 0) {
		var Grupo = Ext.getCmp('comboGrupo').getValue();
		var Marca = Ext.getCmp('comboMarca').getValue();
		var Buscar = Ext.getCmp('textoBuscar').getValue();
		if (Marca=='') {Marca = '%';}
		if (Grupo=='') {Grupo = '%';}
		if ((Grupo=='%') && (Marca=='%') && (Buscar=='')) {
			//Ext.Msg.alert('Advertencia', 'Introduzca un criterio de bï¿½squeda,<br>el criterio actual no es permitido.'  );
		} else {
			//Grupo = '"' + Grupo + '"';
			//Marca = '"' + Marca + '"';
			//Buscar = '"' + Buscar + '"';
			MyListingGrid.loadMask.show();
			MyDataStore.load({params:{BusquedaLibre: Buscar, Marcas: Marca, Grupos: Grupo}});
		}
    }
	return 0;

};

textoLibre.on('specialkey', buscador);
comboGrupo.on('specialkey', buscador);
comboMarca.on('specialkey', buscador);

var DetailsWindow = new Ext.Window({
	id: 'DetailsWindow',
	layout      : 'fit',
	width       : 900,
	height      : 400,
	closeAction :'hide',
	plain       : true,
	
	items: [{
		el: 'detailWindow',
		style: 'background: #ffffff;',
		height : 1000
		}],

	buttons: [{
		text     : 'Cerrar',
		handler  : function(){
			DetailsWindow.hide();
		}
	}]
});

var detalles = function(grid, rowIndex, e){
	var r = grid.getStore().getAt(rowIndex);
	var key = r.get('Id');
	var el= Ext.get('detailWindow');
	var mgr = el.getUpdater();
	mgr.update({url:"./details.php?code="+key});
	DetailsWindow.show();	 
};
MyListingGrid.on('rowdblclick', detalles);