/**
 * Interfaccia grafica per il catalogo prodotti.
 *
 * @author    Domenico Testa
 * @copyright (c) 2008, Domenico Testa
 * @date      2. April 2008
 * @version   $Id$
 *
 * @license Login.js is licensed under the terms of the Open Source
 * code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 */
 
/*global Ext, cdl */

Ext.namespace('cdl');

cdl.CategorieExplorer = Ext.extend(Ext.tree.TreePanel, {

	initComponent:function() {

		Ext.apply(this, {
			rootVisible: false,
			lines: false,
			singleExpand: true,
			useArrows: true,

			height: 500,
			width: 257,

			autoScroll:true,
			animCollapse: true,
			animate: true,
			title: 'Categorie',
			iconCls: 'icon-explore',

			loader: new Ext.tree.TreeLoader({
				preloadChildren: true,
				clearOnLoad: false,
				dataUrl: 'categorie/list.json',
				listeners: {
					'load': function(treeloader, node, response) {
						node.text = node.attributes.nome;
					}
				}
			}),
			root: new Ext.tree.AsyncTreeNode({
				text:'Categorie in catalogo',
				id:'root',
				expanded:true
			}),
			collapseFirst:false
		});

		cdl.CategorieExplorer.superclass.initComponent.apply(this, arguments);
	} // eo function initComponent
});

Ext.reg('cdl.categorieexplorer', cdl.CategorieExplorer);

cdl.ProdottiDataPanel = Ext.extend(Ext.ux.LiveDataPanel, {

});

Ext.reg('cdl.prodottidatapanel', cdl.ProdottiDataPanel);

Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.QuickTips.enable();

	var myStore = new Ext.data.JsonStore({
		root: 'results',
		totalProperty: 'total',
		url: 'prodotti/list.json',
		baseParams: {
			start: 0,
			limit: 20
		},
		autoLoad:false,
		fields: [
			'id',
			'anteprima',
			'categoria',
			'codice',
			'inPromozione',
			'nome',
			'ownedByMaster',
			'prezzo',
			'prezzoFormattato',
			'descrizione',
			'prezzoPromozionale',
			'prezzoPromozionaleFormattato',
			'produttore',
			'showingBadge',
			'sezione'
		]
	});

	// Creating the panel is easy
	var p = new Ext.ux.LiveDataPanel({
		frame: true,
		height: 550,
		width: 505,
		itemSelector: '.prodotto_cat',
		tpl: Ext.XTemplate.from('tpl_prodotto'),
		store: myStore
	});

	p.render('catalogo_online_thumb');

	var tree = new cdl.CategorieExplorer({
		tbar:['Filtra nella Categoria:', {
			xtype:'trigger',
			triggerClass:'x-form-clear-trigger',
			onTriggerClick:function() {
				this.setValue('');
				cdl.CategorieExplorer.filter.clear();
			},
			id:'filter',
			enableKeyEvents:true,
			listeners:{
				keyup:{buffer:150, fn:function(field, e) {
					if(Ext.EventObject.ESC == e.getKey()) {
						field.onTriggerClick();
					} else {
						var val = this.getRawValue();
						var re = new RegExp('.*' + val + '.*', 'i');
						cdl.CategorieExplorer.filter.clear();
						cdl.CategorieExplorer.filter.filter(re, 'text');
					}
				}}
			}
		}]
	});

    // Aggiunge il filtro:
    cdl.CategorieExplorer.filter = new Ext.ux.tree.TreeFilterX(tree);
    tree.filter = cdl.CategorieExplorer.filter;
	
    tree.getSelectionModel().on('selectionchange', function(sm, node){
    	var id = node.attributes.id;
    	myStore.load({
    		params: { cat: id}
    	});
    });

	var accordion = new Ext.Panel({
		renderTo: 'category-tree',

		height: 500,
		width: 257,

		layout:'accordion',
    	layoutConfig:{
    		titleCollapse: true,
    		hideCollapseTool: true,
    		animate: true,
    		activeOnTop: true
    	},
    	items:[{
        	xtype:'form',
                collapsed: true,
        	id:'prod-search-form',
        	title:'Ricerca avanzata',
        	iconCls:'icon-search',
        	bodyStyle:'padding: 10px',
                listeners: {
                    'afterlayout': {
                        fn: function(container, layout) {
                            new Ext.KeyMap(container.body, [{
                                key: Ext.EventObject.ENTER,
                                fn: function() {
                                    var f = Ext.getCmp('prod-search-form');
                                    f.getForm().submit({
                                        url:'prodotti/search.json',
                                        scope:this,
                                        success: function(form, action) {
                                            myStore.loadData(action.result);
                                        },
                                        failure: function() { /*ns.application.error('Errore', 'Impossibile effettuare la ricerca');*/ },
                                        waitMsg:'Ricerca in corso...'
                                    });
                                },
                                scope: this
                            },{
                                key: Ext.EventObject.ESC,
                                fn: function() {
                                    Ext.getCmp('prod-search-form').getForm().reset();
                                },
                                scope: this
                            }]);
                        },
                        scope: this
                    }
                },
       		defaults: {
       			anchor: '95%',
       			labelAlign:'top'
       		},

       		items:[{
       			xtype:'textfield',
       			name:'nome',
       			fieldLabel:'Cerca'
       		},{
       			xtype:'textfield',
       			name:'codice',
       			fieldLabel:'Codice'
       		},{
       			xtype:'combo',
				fieldLabel: 'Sezione',
				store: new Ext.data.Store({
					url:'sezioni/lookup.json',
					reader: new Ext.data.JsonReader({
					totalProperty: "total",
					root: "results"
					}, [
					   	{name: 'id'},
					   	{name: 'descrizione'}
					])
				}),

				hiddenName: 'sezione',
				valueField:'id',
				displayField:'descrizione',
				typeAhead: true,
				loadingText: 'Ricerca in corso...',
				emptyText: 'Digita le prime lettere del codice o della descrizione',
   				pageSize:10,
   				forceSelection: true,
   				minChars: 1,
   				hideTrigger:false,
   				tpl: new Ext.XTemplate('<tpl for="."><div class="search-item"><b>{id}</b>: {descrizione}</div></tpl>'),
   				itemSelector: 'div.search-item'
       		},{
       			xtype:'combo',
				fieldLabel: 'Produttore',
				store: new Ext.data.Store({
					url:'marchi/list.json',
					reader: new Ext.data.JsonReader({
					totalProperty: "total",
					root: "results"
				}, [
						{name: 'id'},
						{name: 'nome'},
						{name: 'img'}
					])
				}),
				hiddenName: 'produttore',
				valueField:'id',
		        displayField:'nome',
		    	typeAhead: true,
		        loadingText: 'Ricerca in corso...',
		        emptyText: 'Digita le prime lettere del produttore',
		    	pageSize:10,
		    	forceSelection: true,
		    	minChars: 1,
		    	hideTrigger:false,
		    	tpl: new Ext.XTemplate('<tpl for="."><div class="search-item"><div style="width: 150px; height: 90px; float: left; text-align: center"><img src="/cdl/UserFiles/marchi/{img}" alt="{nome}"/></div> {nome}</div></tpl>'),
    			itemSelector: 'div.search-item'
			}],
       		
       		buttons: [{
       			text:'Cerca',
       			iconCls:'icon-search',
				handler: function() {

			    	var f = Ext.getCmp('prod-search-form');
			    	f.getForm().submit({
			    		url:'prodotti/search.json',
						scope:this,
						success: function(form, action) {
							myStore.loadData(action.result);
						},
						failure: function() { /*ns.application.error('Errore', 'Impossibile effettuare la ricerca');*/ },
						waitMsg:'Ricerca in corso...'
					});

				}
       		},{
       			text:'Reimposta',
       			iconCls:'icon-cancel',
       			handler: function() {
                            Ext.getCmp('prod-search-form').getForm().reset();
                        } 
       		}]
       	},
        tree]
	});

    myStore.load({
    	params: {
    		cat: 1
    	}
    });
});
