Type.registerNamespace('GridManager');
/*Permet de deselectionner la checkbox du header lorsque une checkbox est décocher */
Ext.apply(Ext.grid.CheckboxSelectionModel.prototype, {
    onMouseDown: function(e, t){
        if(e.button === 0 && (this.simpleSelect || t.className == 'x-grid3-row-checker'))
        {
            e.stopEvent();
            var row = e.getTarget('.x-grid3-row');
            if(row){
                var index = row.rowIndex;
                if(this.isSelected(index))
                {
                    this.deselectRow(index);
                    var hd = Ext.DomQuery.selectNode('.x-grid3-hd-checker', this.grid.view.innerHd);
                    if(hd) Ext.fly(hd).removeClass('x-grid3-hd-checker-on');
                }else{
                    this.selectRow(index, true);
                }
            }
        }
  /*       else
            {x-grid3-row-checker
                e.stopEvent();
                var row = e.getTarget('.x-grid3-row');
               
                this.selectRow(row.rowIndex, true);
            }*/
    }

});

Ext.grid.EventGroupingView = function(config) {
        Ext.apply(this, config);
        this.addEvents({
             groupchange:true
        });
        Ext.grid.EventGroupingView.superclass.constructor.call(this);
    };
    Ext.extend(Ext.grid.EventGroupingView, Ext.grid.GroupingView, {
        onGroupByClick : function(){
            this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
            this.fireEvent("groupchange", this,this.cm.getDataIndex(this.hdCtxIndex)) ;
        },
        onShowGroupsClick : function(mi, checked){
            if(checked){
                this.onGroupByClick();
            }else{
                this.grid.store.clearGrouping();
                this.fireEvent("groupchange", this, null) ;
            }
        }
    });

GridManager.Grid = function(element) 
{
        this._dataStore = null;
        this._columnModel = null;
        this._grid = null;
        this._window = null;
        this._paging = null;
        this._cookieProvider = null;
        this._cookieMgr = null;
        this._groupView = null;
        this._clientId = null;
        this._checkColumn = null;
}

GridManager.Grid.ShowMyList = function()
{

       ListPerso.show();

}

GridManager.Grid.HideMyList = function()
{

       ListPerso.hide();

}

GridManager.Grid.prototype = 
{
    show:function()
    {
        if (this._window != null && (this._window.hidden || !this._window.rendered) )
        {
            this._cookieProvider.set('hide', false);
            this.ShowWin();
            
        }
    },

    hide:function()
    {
        if (this._window != null && !(this._window.hidden || !this._window.rendered))
        {
            this._window.hide(false);
        }
    },
    
    initialize:function()
    {
        this._cookieProvider = new Ext.state.CookieProvider();
    Ext.state.Manager.setProvider(this._cookieProvider);
    this._cookieMgr = new Utils.CookieManager();
  /*      this._dataStore = new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({
            url: 'GetData.ashx',
            method: 'POST'
            }),  
      reader: new Ext.data.JsonReader({
        id:
         'readerId',
        root: 'rows',
        totalProperty: 'rowsCnt',
      fields: ['Product_Id', 'bid','ask'
      ]
      })
    });*/
      this._dataStore = new Ext.data.GroupingStore({
      proxy: new Ext.data.HttpProxy({
            method: 'POST',
            url: SitePath+'WebServices/GetListPersoData.asmx/Products'
        }),
       
            reader: new Ext.data.XmlReader({
               // records will have an "Item" tag
               record: 'Client',
               id: 'readeId',
               totalRecords: '@total'
               }, 
             [{name: 'id', mapping: 'id'},{name: 'product_id', mapping: 'product_id'}, 'bid','ask', 'parentname_category', 'category_name', 'underlying_name', 'isin', 'mnemo', 
               {name:'maturity', mapping: 'maturity'}, 'parity', 'underlying_id', 'delta', 'elasticite', 'category_id' , 'ParityFormat', 'Strikes', 'typeproduct_name']
               ),
               sortInfo:{field: 'underlying_name', direction: "DESC"},
               groupField:'parentname_category'
               
    });
    this._checkColumn = new Ext.grid.CheckboxSelectionModel();

    this._columnModel = new Ext.grid.ColumnModel(
    [
    this._checkColumn,
    {header: 'category_id', dataIndex: 'category_id', hidden: true, hideable : false},
      {header: 'id', dataIndex: 'id', hidden: true, hideable : false},
      {header: 'Product Id', dataIndex: 'product_id', hidden: true, hideable : false},
    {header: 'parentname_category', dataIndex: 'parentname_category', hidden: true, hideable : false},
    {header: 'Mnemo', dataIndex: 'mnemo', renderer: this.renderMnemoLinkColumn},
    {header: 'Sous-Jacent', dataIndex: 'underlying_name'},
    {header: 'Type', dataIndex: 'typeproduct_name', align :'center'},
    {header: 'Isin', dataIndex: 'isin', hidden: true},
    {header: 'Maturit&eacute;', dataIndex: 'maturity', hidden: true},
     {header: 'Parit&eacute;', dataIndex: 'ParityFormat', hidden: true},
      {header: 'Strike(s)', dataIndex: 'Strikes', align :'center'},
      {header: 'Bid', dataIndex: 'bid', align:'center'},
      {header: 'Ask', dataIndex: 'ask', align :'center'},
      {header: 'Delta', dataIndex: 'delta', align :'center', hidden: true},
      {header: 'Elasticit&eacute;', dataIndex: 'elasticite', align :'center', hidden: true}]
    );
    this._columnModel.defaultSortable= true;
    
    
    this._paging = new Ext.PagingToolbar({
                       store: this._dataStore,
                    pageSize: 12,
                    displayInfo: true,
                    displayMsg: 'Displaying results {0} - {1} of {2}',
                    emptyMsg: "No results to display"
                }); 
                
    this._groupView = new Ext.grid.EventGroupingView({
                        forceFit:true,
                        groupByText: 'Grouper par ce champ',
                        showGroupsText: 'Montrer les groupes', 
                        startGroup : new Ext.XTemplate(
                '<div id="{groupId}" class="x-grid-group x-grid-group-{gvalue}">',
                    '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div>', '{gvalue} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' ,'</div></div>',
                    '<div id="{groupId}-bd" class="x-grid-group-body">'
            )
                    });
  
    Ext.grid.GridView.prototype.columnsText = 'Colonnes';
	Ext.grid.GridView.prototype.sortAscText  = 'Tri Ascendant';
	Ext.grid.GridView.prototype.sortDescText  = 'Tri Descendant';
    this._grid = new Ext.grid.GridPanel({
                id: 'ListGrid',
                store: this._dataStore,
                sm: this._checkColumn,
                groupField:'parentname_category',
                cm: this._columnModel,
                title:'Ma Liste',
                loadMask: true,
                height:300,
                width:500,
                header: false,
                enableColLock: false,
                view: this._groupView,
                viewConfig:{emptyText:'Ajoutez des produits à vote liste pour les suivre ici.'},
                stateful :true,
                margins: '5 0 0 0',
                collapsible: false,
                region:'center',
                bbar:[
                       {
                        text: 'Supprimer',
                        iconCls: 'deleteItemList',
                        scope :this,
                        handler : this.removeItemSelected },
                        {iconCls: 'x-tbar-loading',
                    text: 'Actualiser',
                    tooltip: 'Rafraichir',
                    scope :this,
                        handler : function() {
                        /*deselectionne la checkbox dans le header si selectionné */
                                 var hd = Ext.DomQuery.selectNode('.x-grid3-hd-checker', this._grid.view.innerHd);
                    if(hd) Ext.fly(hd).removeClass('x-grid3-hd-checker-on');
                                 this._dataStore.reload();
                              } },
                      {
                        text: 'Tout Réduire',
                        iconCls: 'contractList',
                        scope :this,
                        handler : function() {
                                 this._groupView.collapseAllGroups();

                                    } },
                                    {
                        text: 'Tout Agrandir',
                        iconCls: 'expandList',
                        scope :this,
                        handler : function() {
                                 this._groupView.expandAllGroups();

                                    } },
                                     {
                        text: 'Grouper par défaut',
                        iconCls:'columnsList',
                        scope :this,
                        handler : function() {
                                 this._dataStore.groupBy('parentname_category');
                                 Ext.state.Manager.set('myList_GroupBy', this._dataStore.groupField);

                                    } }
                    ]
              /*  bbar:this._paging*/
               /* collapsible : true,
                draggable : true,
                el: 'topic-grid'*/
            });

        this._groupView.on('groupchange',this.storeGroupState); 
     this._window = new Ext.Window({
              id: 'ListWindow',
              title: 'Ma Liste',
              hideBorders:true,
              closable:true,
              collapsible:true,
              width: 500,
              height:350,
              minWidth: 200,
              minHeight: 100,
              shadow : 'drop',
              shadowOffset : 6,
              frame:true,
              layout:'border',
              stateful : true,
              items: [ this._grid /*{
                 region:'center',
		         title: 'Personal List',
		         titleCollapse: true,
		         frame:true,
		         border:true,
		         split:true,
		         layoutConfig: {
			        animate: true
		         },
		         collapsible:false,
                         layout:'border',
		         items : [{
                             region:'center',
                             layout:'fit',
                             items:this._grid 
                         }]
               } , {
            region:'west',
            id:'action-panel',
            title:'Actions',
            width: 150,
            margins: '5 0 0 0',
            cmargins: '5 5 0 0',
            minSize: 90,
            maxSize: 150,
            collapsible:true,
            items: [
                    {
                    xtype: 'button',
                    iconCls: "x-tbar-loading",
                    tooltip: 'Rafraichir',
                    scope :this,
                        handler : function() {
                                 this._dataStore.reload();
                              } },
                      {
                      xtype: 'button',
                        text: 'Réduire les groupes',
                        scope :this,
                        handler : function() {
                                 this._groupView.collapseAllGroups();

                                    } },
                                    {
                                    xtype: 'button',
                        text: 'Agrandir les groupes',
                        scope :this,
                        handler : function() {
                                 this._groupView.expandAllGroups();

                                    } },
                                     {
                                     xtype: 'button',
                        text: 'Grouper par catégorie',
                        scope :this,
                        handler : function() {
                                     
                                 this._dataStore.groupBy('parentname_category');
                                 Ext.state.Manager.set('myList_GroupBy', this._dataStore.groupField);

                                    } }
                    ]
            
        }*/
      ],
              animCollapse :false,
              cls:'ListePerso',
              closeAction: 'hide',
              /*WARNING!!! dragCls-> Is a custom  attribut add in source of ext in window.js. If update of Ext it would not work.
              add in window.js pour les sources et ext-all.js ->this.proxy = w.ghost(w.dragCls); instead of this.proxy = w.ghost(); and in parameters dragCls : '',
              */
              dragCls: 'ListePerso',
              listeners:
              {
                'collapse':{fn: this.OnCollapseWin,
                scope: this
                },
                'expand':{fn: this.OnExpandWin,
                scope:this
                },
                'hide':{fn: this.OnHideWin,
                scope:this
                }
              },
              shim: true
            });
   // this._grid.render();
    /*var grNum = this._grid.getGroups().length;
    for (var grp = 0; grp < grNum ; grp++)
    {
        this._grid.getGroups()[grp].onclick = this.storeGroupState;
    }*/
    this.ShowWin();
      
	  //this._dataStore.on('load', this.onLoadDatastore, this);
         // }

     
    },
    
    ShowWin: function ()
    {
         this._clientId = this._cookieMgr.GetCookie('DerivWar');
       var isHidden = this._cookieProvider.get('hide');
        var isCollapse = this._cookieProvider.get('collapsed');
       if (this._clientId == null)
       {
           this._clientId = this._cookieMgr.GetAspNetCookie('Logged', 'ClientId');
       }
       if (isHidden == null || isHidden == 'undefined')
       {
             this._cookieProvider.set('hide', false);
             isHidden = false;
       }
       if (this._clientId != null && !isHidden)
       {
            if (!isCollapse)
            {
          this._dataStore.load({params:{asking : 'get', clientId : this._clientId}});
          }

            this._window.show();
            var linkToShow = Ext.get('showMyList');
            if(linkToShow != null)
            {
                linkToShow.hide(false);
            }
	          if (isCollapse)
	          {
	            this._window.collapse(false);
	          }
	           var groupState = Ext.state.Manager.get('myList_GroupBy');
	           if (groupState)
	          {
	            this._dataStore.groupBy(groupState);
	           }
	      }

    },
    
    removeItemSelected: function()
    {
        if (this._checkColumn.getCount() < 1)
        {
            alert('Vous devez selectionner un item' );
        }
        else
        {
        var toSend = '';
        var selected = this._checkColumn.getSelections();
        var i = 0;
        for (i = 0; i < this._checkColumn.getCount() - 1; i++)
        {
            toSend += selected[i].data.id + ',';
        }
         toSend += selected[i].data.id;
      var conn = new Ext.data.Connection();
            conn.request({
                url: SitePath+'WebServices/GetListPersoData.asmx/Products',
                method: 'POST',
                params: {asking : 'deleting', clientId : this._clientId, columns : toSend},
                scope: this,
                success: function(responseObject) {
                     /*deselectionne la checkbox dans le header si selectionné */
                   var hd = Ext.DomQuery.selectNode('.x-grid3-hd-checker', this._grid.view.innerHd);
                    if(hd) Ext.fly(hd).removeClass('x-grid3-hd-checker-on');
                   this._dataStore.reload();
                },
                 failure: function() {
                     Ext.Msg.alert('Status', 'Unable to delete item at this time. Please try again later.');
                 }
            });
        }
    },
    
    renderMnemoLinkColumn: function(value,p,r)
    {
        return String.format("<a href='javascript:OpenProduct({0},{1})'>{2}</a>",  r.data['category_id'], r.data['product_id'], value);
    },
    
    OnCollapseWin : function()
    {
        this._cookieProvider.set('collapsed', true);
    },
    
    OnExpandWin : function()
    {
         this._dataStore.load({params:{clientId : this._clientId}});
        this._cookieProvider.set('collapsed', false);
    },
    
    OnHideWin : function()
    {
         var linkToShow = Ext.get('showMyList');
            if(linkToShow != null)
            {
                linkToShow.show(false);
            }
        this._cookieProvider.set('hide', true);
    },
    
    storeGroupState : function(gv, dataindex)
    {
         Ext.state.Manager.set('myList_GroupBy',dataindex);
    }
    
}

GridManager.Grid.registerClass('GridManager.Grid');


if (typeof(Sys) !== 'undefined') 
    Sys.Application.notifyScriptLoaded();