// Create user extension namespace (Application)
Ext.namespace('Application');

/**
  *  Application.guestGrid Extension class
  * 
  *  @author Seabor
  *  @version 1.0
  *  
  *  @class Application.guestGrid
  *  @extends Ext.grid.GridPanel
  *  @constructor
  *  @param {Object} config Configuration options
  */

Application.guestGrid = function(config) {

    // call parent constructor
	Application.guestGrid.superclass.constructor.call(this, config);

	// store
	this.store = new Ext.data.GroupingStore({
        autoLoad: false
        ,remoteSort: true
        ,reader: new Ext.data.JsonReader({root: 'rows', totalProperty: 'totalCount'}, Ext.data.Record.create([
            {name: 'title', type: 'string'}
            ,{name: 'cat_name', type: 'string'}
            ,{name: 'brand_title', type: 'string'}
            ,{name: 'price', type: 'int'}
            ,{name: 'discount_neva', type: 'int'}
            ,{name: 'avail', type: 'int'}
            ,{name: 'reserve', type: 'int'}
            ,{name: 'ordered', type: 'int'}
            ,{name: 'props_qty', type: 'int'}
            ,{name: 'images_qty', type: 'int'}
            ,{name: 'has_descr', type: 'bool'}
            ,{name: 'instructions_qty', type: 'int'}
            ,{name: 'details_qty', type: 'int'}
            ,{name: 'certs_qty', type: 'int'}
            ,{name: 'arrival_date', type: 'string'}
            ,{name: 'id', type: 'string', mapping: 'id'}
            ]))
        ,url: config.url
        ,baseParams: config.loadParams
        ,sortInfo:{field: 'title', direction: "ASC"}
        ,groupOnSort: true
        ,groupField: "brand_title"
    });
    
    this.loadParams = config.loadParams; // Current category Id
    
    this.columns = [
         {id:'title', header: "Наименование", sortable: true, 
                tooltip: 'Щелкните для сортировки по этому полю', groupable: false,
                width: 300, dataIndex: 'title', filter: {type: 'string'}}
        ,{header: "Артикул", sortable: true, width:100, align: "right", groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю',  dataIndex: 'id', filter: {type: 'string'}}
        ,{id:'cat_name', header: "Категория", sortable: true, 
                tooltip: 'Щелкните для сортировки по этому полю', 
                width: 80, dataIndex: 'cat_name', hidden: true, filter: {type: 'string'}}
        ,{header: "Производитель", sortable: true, 
                tooltip: 'Щелкните для сортировки по этому полю', filter: {type: 'string'},
                width: 60, dataIndex: 'brand_title', hidden: true, groupable: true}
        ,{header: "Цена", sortable: true, align: "right", groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю', width:100, 
                dataIndex: 'price', renderer: Ext.util.Format.ruMoney, filter: {type: 'numeric'}}
        ,{header: "Скидка", sortable: true, align: "right", groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю', width:30, 
                dataIndex: 'discount_neva', renderer: function(v){ 
                    if (v < 1)return '<span style="color:ddd">-</span>'
                    else return '<span style="color:#2FBF07">-' + v + '%</span>';
                }, filter: {type: 'numeric'}}
        ];
    
    this.colModel = new Ext.grid.ColumnModel(this.columns);
    
}; // end of Application.guestGrid constructor

Ext.extend(Application.guestGrid, Ext.grid.GridPanel, {
	
    // configurables
    // anything what is here can be configured from outside
	loadMask: true
    ,enableHdMenu: true
    ,enableColumnHide: false
    ,emptyText: 'Ничего нет'
    ,stripeRows: true
    ,farme: true
    ,border: false
    ,header: false
    ,disableSelection: false
    ,groupField: 'brand_title'
    ,deferRowRender: false
    ,plugins: [
        new Ext.ux.grid.GridFilters({
            encode: false, // json encode the filter query
            local: true,   // defaults to false (remote filtering)
            filters: []
        })
    ]
    ,initComponent: function(){
    	// {{{
    	Ext.apply(this, {
    	   tbar: new Ext.Toolbar({cls: 'x-toolbar-tab'})
    	  ,bbar: new Ext.PagingToolbar({
                //store: store,
                pageSize: 50,
                displayInfo: true,
                displayMsg: 'Товары {0} - {1} из {2}',
                emptyMsg: "Нет данных для отображения"
            })
    	}); // }}} e/o apply
    	Application.guestGrid.superclass.initComponent.apply(this, arguments);
    }
    ,afterRender: function() {
        var that = this; 
    	this.getStore().clearGrouping();
        this.getBottomToolbar().bindStore(this.getStore());
        
        // toolbar fields menu
        this.fieldsMenu = new Ext.menu.Menu({id:this.id + "-hcols-menu"});
        var cm = this.getColumnModel(),  colCount = cm.getColumnCount();
        for(var i = 0; i < colCount; i++){
            if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){
                this.fieldsMenu.add(new Ext.menu.CheckItem({
                    id: "col2-"+cm.getColumnId(i),
                    text: cm.getColumnHeader(i),
                    checked: !cm.isHidden(i),
                    hideOnClick:false,
                    disabled: cm.hideable === false
                }));
             }
         };
            
         this.fieldsMenu.addListener('itemclick', function(item){
             var cm = that.getColumnModel();
             var index = cm.getIndexById(item.id.substr(5));
             if(index != -1){
                 if(item.checked && cm.getColumnsBy(function(){return !cm.hidden && !cm.fixed;}).length <= 1){
                     this.onDenyColumnHide();
                     return false;
                 }
                 cm.setHidden(index, item.checked);
             }                                
             return true;
         }); // e/o toolbar fields menu

    	// {{{
        this.getTopToolbar().add( 
            { 
                text: 'Группировать по производителям'
                ,enableToggle: true 
                ,pressed: false
                ,scope: this
                ,handler: function(item){
                  if(!item.pressed){
                     this.getStore().clearGrouping();
                     this.getColumnModel().setHidden(this.getColumnModel().findColumnIndex(this.groupField), true);
                     this.expandAllBtn.disable();
                     this.collapseAllBtn.disable();
                  }
                  else {
                	 this.getView().enableGrouping = true;
                     this.getStore().groupBy(this.groupField);
                     this.expandAllBtn.enable();
                     this.collapseAllBtn.enable(); 
                     //console.log(this.getView()); //.refresh();
                  }}
             },'-',{ 
                  text: '' 
                  ,id: 'btn_expand_all_2'
                  ,disabled: true
                  ,tooltip: {text:'Раскрыть все группы'}
                  ,icon: '/js/ext/resources/images/default/grid/expand-all.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,scope: this
                  ,handler: function(){this.getView().expandAllGroups();}
             },{
                  text: ''
                  ,id: 'btn_collapse_all_2'
                  ,disabled: true
                  ,tooltip: {text:'Свернуть все группы'}
                  ,icon: '/js/ext/resources/images/default/grid/collapse-all.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,scope: this
                  ,handler: function(){this.getView().collapseAllGroups();}
             },'-',{
                  text: "В наличии"
                  ,enableToggle: true 
                  ,pressed: true
                  ,hidden: false
                  ,id: 'btn_in_sight_2'
                  ,scope: this
                  ,handler: function(item){
                  	  this.loadParams.store = true;
                  	  this.loadParams.in_sight = item.pressed;
                      this.store.load({
                        params: this.loadParams
                      });
                   }
              },'-',{ 
                  text: 'Выбор полей'
                  ,menu: that.fieldsMenu
              },'-','Поиск',' ',
              new Ext.ux.form.SearchField({
                    store: this.store,
                    width:220
              })
              ,'-',{
                  text: 'Сравнить товары'
              },'-',{
                  icon: '/i/excel.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,tooltip: {text:'Экспортировать таблицу в Excel'}
              }
        ); // e/o Toolbar.add
        // }}}
        
        this.inSightBtn = this.getTopToolbar().items.itemAt(5);
        this.groupBtn = this.getTopToolbar().items.itemAt(0);
        this.expandAllBtn = this.getTopToolbar().items.itemAt(2);
        this.collapseAllBtn = this.getTopToolbar().items.itemAt(3);
        this.fieldsBtn = this.getTopToolbar().items.itemAt(7);
        this.printBtn = this.getTopToolbar().items.itemAt(15);
        this.compareBtn = this.getTopToolbar().items.itemAt(13);
        this.compareBtnSep = this.getTopToolbar().items.itemAt(14);
        
        // call parent
        Application.guestGrid.superclass.afterRender.apply(this, arguments);
    
        // Хэндлеры на кнопки тулбара
        this.printBtn.on('click', function() {
               // Узнаем, какие параметры надо передавать
               var cm = this.getColumnModel();
               var columns = cm.getColumnsBy(function(c, i) {
                    if (!c.hidden)
                        return true;
                    else
                        return true;
               });
               // Массив с отправляемыми параметрами
               var params = new Array();
               var fields = new Object();
               Ext.each(columns, function(c) {
                    fields[c.dataIndex] = c.header;
               });
               params.push({
                    tag: 'input',
                    type: 'hidden',
                    name: 'fields',
                    value: Ext.urlEncode(fields)
               });
               
               var sortState = this.getStore().getSortState();
               var loadOptions = this.getStore().lastOptions.params || this.getStore().baseParams;
               loadOptions['sort'] = sortState.field;// + ' ' + sortState.direction; 
               loadOptions['excel'] = true;
               
               // Отправим последние параметры загрузки стора
               for (op in loadOptions) {
                   params.push({
                        tag: 'input',
                        type: 'hidden',
                        name: op,
                        value: loadOptions[op]
                   });
               }
            	
               // Создадим iFrame
               var iFrame = Ext.DomHelper.append(document.body, {
                    tag: 'iframe',
                    id: 'specialPostFrame',
                    frameBorder: 0,
                    width: 0,
                    height: 0,
                    css: 'display:none;visibility:hidden;height:1px;',
                    src: ''
               },true); 
               
               var isLoaded = false;
               // Создадим форму
               if (Ext.isIE) {
                   iFrame.on({
                        scope: this
                        ,'load': function() {
                        	if (isLoaded) return;
                            var Form = Ext.DomHelper.append(iFrame.dom.contentWindow.document.body, {
                            tag: 'form',
                            id: 'specialPostForm',
                            action: document.location.protocol +'//'+ document.location.host + "/grid",
                            method: 'post',
                            target: '_self',
                            children: params
                         }, true);
                   
                            Form.dom.submit(); 
                            isLoaded = true;
                        }
                   });
               }
               else {
                    var Form = Ext.DomHelper.append(iFrame.dom.contentWindow.document.body, {
                        tag: 'form',
                        id: 'specialPostForm',
                        action: document.location.protocol +'//'+ document.location.host + "/grid",
                        method: 'post',
                        target: '_self',
                        children: params
                     }, true);
                        
                        Form.dom.submit(); 
                        isLoaded = true;
               }
               // Clear load options
               delete(loadOptions['excel']);
               return;
            
        }, this);
        
    }
    ,view: new Ext.grid.GroupingView({
    	 forceFit: true
        ,autoFill: true
        ,emptyText: 'Товары по запросу отсутствуют'
        ,enableGrouping: true
        ,enableNoGroups: true
        ,showGroupName: false
        ,groupTextTpl: '{text}'
        ,startCollapsed: false
        ,hideGroupedColumn: true
        })
    //,cm: new Ext.grid.ColumnModel(this.columns)
});

// register new xtype
Ext.reg('guestGrid', Application.guestGrid);
