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

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

Application.guestGridCompare = function(config) {

    // call parent constructor
    Application.guestGridCompare.superclass.constructor.call(this, config);
    
    // store data fields
    //if (Ext.isEmpty(config.properties)) return;
    
    var propertiesFields = [];
    var defaultPropertiesFields = [
    	{name: 'id', type: 'string'}
    	,{name: 'title', type: 'string'}
    	,{name: 'price', type: 'int'}
        ,{name: 'brand', type: 'string'}];
    
    // columnModel
    var propertiesColumns = [];
    var defaultPropertiesColumns = [
        {id:'title', header: "Наименование", sortable: true, groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю', 
                width: 300, dataIndex: 'title', defaultColumn: true, filter: {type: 'string'}, filterable: true}
        ,{header: "Артикул", sortable: true, width:100, align: "right", filter: {type: 'string'}, groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю',  dataIndex: 'id', defaultColumn: true}
        ,{header: "Производитель", sortable: true, align: 'center', groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю', filter: {type: 'string'},
                width: 90, dataIndex: 'brand', hidden: false, defaultColumn: true}
        ,{header: "Цена", sortable: true, renderer: Ext.util.Format.ruMoney, groupable: false,
                tooltip: 'Щелкните для сортировки по этому полю', align: 'right',
                width: 80, dataIndex: 'price', hidden: false, defaultColumn: true,
                filter: {type: 'numeric'}}
    ];    
    
    var filters = new Ext.ux.grid.GridFilters({
        encode: false, // json encode the filter query
        local: true,   // defaults to false (remote filtering)
        filters: []
     });
    
    // store config
    this.loadParams = config.baseParams;
    var storeConf = {
        autoLoad: false
        ,proxy: new Ext.data.HttpProxy({
            method: 'GET'
            ,url: config.url
        })
        ,baseParams: config.baseParams
        ,sortInfo:{field: 'title', direction: "ASC"}
    };
    
    // setup columns 
    function setColumns(config) {
    	propertiesFields = defaultPropertiesFields.slice(0);   //copy array
    	propertiesColumns = defaultPropertiesColumns.slice(0); //copy array
    	for (var c in config.properties) {
        	if (c == 'remove') continue;
        	var name = 'prop_' + config.properties[c].id;
        	// store records
        	propertiesFields.push({
        	   name: name
        	   ,type: 'string'
        	});
        	var hidden = true;
        	var empty = true;
        	for (var v in config.values) {
        		if (!Ext.isEmpty(config.values[v][name])) {
        		  hidden = false;
        		  empty = false
        		}
        	}
        	
        	// whether to group
        	var groupable = false;
        	
        	// custom filter creation
        	var filter = {};
        	var currColumn = config.properties[c];
        	switch (currColumn.type) {
        		case "number":
        		  filter.type = "numeric";
        		  break;
        		case "string":
        		  filter.type = "string";
        		  break;
        		case "text":
        		  filter.type = "string";
        		  break;
        		case "select":
        		  if (currColumn.variants.length > 1) {
            		  filter.type = "list";
            		  filter.options = currColumn.variants;
            		  groupable = true;
        		  } else filter = null;
        		  break;
        		 default: continue
        	}

        	// grid columns
        	propertiesColumns.push({
               dataIndex: 'prop_' + currColumn.id
               ,propId: currColumn.id
               ,header: currColumn.title
               //,width: 30
               ,filter: filter
               ,groupable: groupable
               ,align: 'right'
               ,sortable: true
               ,empty: empty
               ,hidden: true
               ,tooltip: 'Щелкните для сортировки по этому полю'
               ,renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    if (Ext.isEmpty(value)) 
                        return '-';
                    else {
                    	var unit = record.json['prop_unit_' + this.propId];
                        return value + ' ' + (typeof(unit)=='undefined' ? '' : unit);
                    }
               }
            });
        }
    	// update store conf
    	storeConf.reader = new Ext.data.JsonReader({root: 'values'}, Ext.data.Record.create(propertiesFields));
    }
    
    // make setup columns
    setColumns(config);
    
    // refresh table when new data come
    this.updateTable = function(answer, options) {
    	// set columns
    	answer.properties = answer.columns;
    	setColumns(answer);

    	// set store data
    	storeConf.data = answer;
    	storeConf.baseParams = options.params;
    	
    	// set group field
    	if (this.getTopToolbar().getComponent('btnGroupByBrand').pressed) {
    		storeConf.groupField = this.groupField;
    	} else {
    		storeConf.groupField = '';
    	}
    	
    	// reconfigure table
    	this.reconfigure(new Ext.data.GroupingStore(storeConf), new Ext.grid.ColumnModel(propertiesColumns));
    	
    	// update fields and field's menu
    	this.updateFieldsMenu();
    	var btnShowProps = this.getTopToolbar().getComponent('btnShowProps');
    	btnShowProps.toggleHandler(btnShowProps, btnShowProps.pressed);
    	
    	this.loadMask.hide();
    }
    
    // store
    this.store = new Ext.data.GroupingStore(storeConf);

    // colModel
    this.colModel = new Ext.grid.ColumnModel(propertiesColumns);
    
    // fields menu updater
    this.updateFieldsMenu = function() {
    	 var that = this;
    	 
    	 this.fieldsMenu.removeAll();
    	 var btnGroup = this.fieldsMenu.add({
            // Use the default, automatic layout to distribute the controls evenly
            // across a single row
            xtype: 'buttongroup',
            id: 'fieldsBtnGroup',
            forceLayout: true,
            autoWidth: 'true',
            title: "Доступные поля",
            columns: 3
            //items: this.fieldMenuItems
        });
    	 
    	 var cm = this.getColumnModel(), colCount = cm.getColumnCount();
         //this.fieldMenuItems = [];
         for(var i = 0; i < colCount; i++){
             if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){
                 btnGroup.add({
                 	xtype: 'button',
                 	enableToggle: 'true',
                 	text: cm.getColumnHeader(i),
                 	pressed: !cm.isHidden(i),
                 	style: 'margin: 2px',
                 	id: "col-"+cm.getColumnId(i),
                 	scope: that,
                 	listeners: {
                     	toggle: function(button, state) {
                     		 var cm = that.getColumnModel();
                              var index = cm.getIndexById(button.id.substr(4));
                              if(index != -1){
                                  if(button.pressed && cm.getColumnsBy(function(){return !cm.hidden && !cm.fixed;}).length <= 1){
                                      this.onDenyColumnHide();
                                      return false;
                                  }
                                  cm.setHidden(index, !state);
                              }                                
                              return true;
                     	}
                 	}
                 });
              }
          };
          btnGroup.doLayout();
    }
    
}; // end of Application.guestGridCompare constructor


Ext.extend(Application.guestGridCompare, Ext.grid.GridPanel, {
    
    // configurables
    // anything what is here can be configured from outside
    loadMask: true
    ,enableHdMenu: true
    ,enableColumnHide: false
    ,emptyText: 'Нет товаров для сравнения'
    ,stripeRows: true
    ,frame: false
    ,border: false
    ,header: false
    ,plugins: [
        new Ext.ux.grid.GridFilters({
            encode: false, // json encode the filter query
            local: true,   // defaults to false (remote filtering)
            filters: []
        })
    ]
    ,disableSelection: false
    ,groupField: 'brand'
    ,initComponent: function(){
        // {{{
        Ext.apply(this, {
           tbar: new Ext.Toolbar({cls: 'x-toolbar-tab'})
        }); // }}} e/o apply
        
        Application.guestGridCompare.superclass.initComponent.apply(this, arguments);
    }
    ,afterRender: function() {
        var that = this; 
        
        // toolbar fields menu
        this.fieldsMenu = new Ext.menu.Menu({
            id:this.id + "-hcols-menu",
            plain: true,
            forceLayout: true,
            showSeparator: false
        });
        
        // {{{
        this.getTopToolbar().add( 
            { 
                text: 'Группировать по производителям'
                ,id: 'btnGroupByBrand'
                ,enableToggle: true 
                ,pressed: false
                ,scope: this
                ,handler: function(item){
                  if(!item.pressed){
                     this.getStore().clearGrouping();
                     this.getColumnModel().setHidden(this.getColumnModel().findColumnIndex(this.groupField), false);
                     this.expandAllBtn.disable();
                     this.collapseAllBtn.disable();
                  }
                  else {
                  	 this.getView().enableGrouping = true;
                     this.getStore().groupBy(this.groupField);
                     this.getColumnModel().setHidden(this.getColumnModel().findColumnIndex(this.groupField), true);
                     this.expandAllBtn.enable();
                     this.collapseAllBtn.enable();                                       
                  }}
             },'-',{ 
                  text: '' 
                  ,id: 'btn_expand_all'
                  ,disabled: true
                  ,tooltip: {text:'Раскрыть все группы'}
                  ,icon: '/i/nc/grid/expand-all.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,scope: this
                  ,handler: function(){this.getView().expandAllGroups();}
             },{
                  text: ''
                  ,id: 'btn_collapse_all'
                  ,disabled: true
                  ,tooltip: {text:'Свернуть все группы'}
                  ,icon: '/i/nc/grid/collapse-all.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,scope: this
                  ,handler: function(){this.getView().collapseAllGroups();}
             },'-',{
                  text: "В наличии"
                  ,enableToggle: true 
                  ,pressed: this.inSightBtn
                  ,id: 'btn_in_sight'
                  ,scope: this
                  ,handler: function(item){
                  	  this.loadParams.in_sight = item.pressed;
                      this.store.load({
                        params: {in_sight: item.pressed, store: true}
                      });
                   }
             },'-',{
                  text: 'Выбор полей'
                  ,id: 'btnFieldsMenu'
                  ,menu: that.fieldsMenu
             },'-',{ 
                  text: 'Показать характеристики',
                  id: 'btnShowProps',
                  enableToggle: true,
                  scope: that,
                  toggleHandler: function(button, state) {
                     if (state === true) {
                     	button.setText('Скрыть характеристики');
                     } else {
                     	button.setText('Показать характеристики');
                     }
                  	
                     var cm = that.getColumnModel();
                     var fieldsBtns = that.fieldsMenu.getComponent('fieldsBtnGroup');
                     
                     for(var i = 0; i < cm.getColumnCount(); i++){
                     	if (state === true && cm.config[i].defaultColumn != true && cm.config[i].empty != true) {
                     		cm.setHidden(i, !state);
                     		fieldsBtns.getComponent('col-' + i).toggle(state);
                     	} else if (state === false && cm.config[i].defaultColumn != true && cm.config[i].empty != true) {
                         	if(cm.getColumnsBy(function(){return !cm.hidden && !cm.fixed;}).length <= 1){
                                this.onDenyColumnHide();
                                continue;
                            }
                                cm.setHidden(i, !state);
                                fieldsBtns.getComponent('col-' + i).toggle(state);
                        }
                     }
                     return true;
                  }
             },'-',{
                  icon: '/i/excel.gif' 
                  ,iconCls: 'x-btn-text-icon'
                  ,hidden:false
                  ,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.compareBtn = this.getTopToolbar().items.itemAt(9);
        this.printBtn = this.getTopToolbar().items.itemAt(11);
        
        // call parent
        Application.guestGridCompare.superclass.afterRender.apply(this, arguments);
    
        // Хэндлеры на кнопки тулбара
        this.printBtn.on({
            scope: this
            ,click: function() {
                
               // Узнаем, какие параметры надо передавать
               var cm = this.getColumnModel();
               var columns = cm.getColumnsBy(function(c, i) {
                    if (!c.hidden)
                        return true;
                    else
                        return false;
               });
               
               // Массив с отправляемыми параметрами
               var params = new Array();
               var fields = new Array();
               
               Ext.each(columns, function(c) {
                    fields.push(c.dataIndex);
               });
               params.push({
                    tag: 'input',
                    type: 'hidden',
                    name: 'fields',
                    value: fields.join(',')
               });
                
               var sortState = this.getStore().getSortState();
               if (Ext.isEmpty(this.getStore().lastOptions))
                    var loadOptions = this.getStore().baseParams;
               else 
                    var loadOptions = this.getStore().lastOptions.params;
               loadOptions['sort'] = sortState.field + ' ' + sortState.direction; 

               // Отправим последние параметры загрузки стора
               for (var key in loadOptions) {
                    params.push({
                        tag: 'input',
                        type: 'hidden',
                        name: key,
                        value: loadOptions[key]
                    });                                   	
               }
               params.push({
                    tag: 'input',
                    type: 'hidden',
                    name: 'excel',
                    value: true
               });
               params.push({
                    tag: 'input',
                    type: 'hidden',
                    name: 'grid_compare',
                    value: true
               });
               //console.log(params);
                
                // Создадим 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 + "/gridcompare",
                            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 + "/gridcompare",
                        method: 'post',
                        target: '_self',
                        children: params
                     }, true);
                        
                        Form.dom.submit(); 
                        isLoaded = true;
               }
               return;
            }
        });
        
    }
    ,view: new Ext.grid.GroupingView({
        //forceFit: true
        //autoFill: true
        emptyText: 'Товары по запросу отсутствуют'
        ,enableGrouping: false
        ,enableNoGroups: true
        ,showGroupName: false
        ,groupTextTpl: '{text}'
        ,startCollapsed: false
        ,hideGroupedColumn: false
        })
});

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