﻿
__trGroup('Table in grid');Ext.namespace('NPSL','NPSL.Cms','NPSL.Cms.Grid');(function(){var Cms=NPSL.Cms,Grid=Cms.Grid,ColType=Cms.ColType,Form=Cms.Form;Grid.FileGridView=function(config){Grid.FileGridView.superclass.constructor.call(this,config);this.addEvents("fileupload","filedownload","save");}
Ext.extend(Grid.FileGridView,Ext.grid.GridView,{init:function(grid){Grid.FileGridView.superclass.init.call(this,grid);this.on("rowupdated",function(vw,idx,record){var rows=this.getRows();this.attachUploadButtons(rows[idx],idx);},this);this.on("rowsinserted",function(vw,firstRow,lastRow){var rows=this.getRows();for(var i=firstRow;i<=lastRow;++i){this.attachUploadButtons(rows[i],i);}},this);},attachUploadButtons:function(row,i){var els=Ext.fly(row).query('div.cms-icon-attach');for(var j=0;j<els.length;++j){var colIndex=this.findCellIndex(els[j]);var col=this.cm.getColumnById(this.findCellIndex(els[j]));var uplConfig=this.fileUploadConfig||{};new Ext.ux.UploadButton(Ext.apply({renderTo:els[j],hideLabel:true,tooltip:__tr('Click to upload a file'),renderImage:"/fp/shared/images/ic_open.gif",listeners:{"addfile":{fn:function(upl){if(this.view.fireEvent("fileupload",upl,this.view,this.record,colIndex)!==false){}},scope:{view:this,col:col,record:this.ds.getAt(i)}}}},uplConfig));}},processRows:function(startRow,skipStripe){Grid.FileGridView.superclass.processRows.call(this,startRow,skipStripe);if(this.ds.getCount()<1){return;}
startRow=startRow||0;var rows=this.getRows(),len=rows.length;for(var i=startRow;i<len;i++){this.attachUploadButtons(rows[i],i);}},createFileColumn:function(col,dataIndex,iconIndex){var config={_col:col,dataIndex:dataIndex,actions:[{iconCls:'cms-icon-attach',tooltip:__tr('Upload a file')},{iconIndex:iconIndex,tooltip:__tr('Download file')},{iconIndex:iconIndex,tooltip:__tr('Delete file')}],callbacks:{'cms-icon-clip':function(grid,record,action,row,col){this.fireEvent("filedownload",grid,record,action,row,col);}.createDelegate(this)},header:col.description||col.name};config.tpl=new Ext.XTemplate('<tpl for=".">','<div class="ux-row-action">','<div class="ux-row-action-item cms-icon-attach style="" qtip="Upload a file"></div>','<tpl if="typeof('+col.name+')!=\'undefined\' &amp;&amp; '+col.name+' != 0">','<div class="ux-row-action-item cms-icon-clip" qtip="Download file"></div>','<div class="ux-row-action-item cms-icon-delete" qtip="Delete file"></div>','</tpl>','</div>','</tpl>');return new Ext.ux.grid.RowActions(config);}});Ext.layout.FitLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,onLayout:function(ct,target){Ext.layout.FitLayout.superclass.onLayout.call(this,ct,target);if(!this.container.collapsed){this.setItemSize(this.activeItem||ct.items.itemAt(0),target.getStyleSize());}},setItemSize:function(item,size){if(item&&size.height>0){item.setSize(size);}}});Ext.Container.LAYOUTS['fit2']=Ext.layout.FitLayout;Grid.GridPanel=function(config){if(!config.table){throw"No table found in Grid.GridPanel constructor";}
config.layout="fit2";Grid.GridPanel.superclass.constructor.call(this,config);if(this.keys){this.setKeys(this.keys);}}
Ext.extend(Grid.GridPanel,Ext.Panel,{setSize:function(w,h){Grid.GridPanel.superclass.setSize.call(this,w,h);},createComboStore:function(data,nullable){var rdr=new Ext.data.JsonReader({root:"data",id:"value"},Ext.data.Record.create([{name:"value"},{name:"description"}]));if(nullable){data=[{value:null,description:__tr('n/a')}].concat(data);}
var store=new Ext.data.Store({proxy:new Ext.data.MemoryProxy({data:data}),reader:rdr});store.load();return store;},renderComboValue:function(store,val){var r=store.query('value',val);if(r.getCount()==0)
return'';return r.get(0).get('description');},createCombo:function(store){return new Ext.form.ComboBox({lazyRender:true,store:store,mode:'local',editable:false,triggerAction:'all',forceSelection:true,valueField:'value',displayField:'description',listClass:'x-combo-list-small'})},createGrid:function(){var storeId=Form.makeStoreId(this.table,this.keys);var orderBy;if(this.orderBy){orderBy=this.orderBy;}else{orderBy=[];var pk=this.table.pk;for(var i=0;i<pk.length;++i){orderBy.push({name:pk.columns[i].name,direction:"Asc"});}}
var store=this.store=new NPSL.Cms.DataStore({storeId:this.storeId,rpc:GridHandler.getTableData,totalProperty:"total",root:"data",remoteSort:true,prepareRpcParams:function(params){var fetchKeys=this.parent.keys.makeTableKeys(this.parent.table.name);return[this.parent.table.sid,fetchKeys,null,null,this.orderBy];},parent:this,table:this.table,orderBy:orderBy,pruneModifiedRecords:true});var pagingBar=new Ext.PagingToolbar({pageSize:10,store:store,displayInfo:true,emptyMsg:__tr('No records to display')});var cols=[];var plugins=[];var fileGridView=new Grid.FileGridView({fileUploadConfig:{url:'/fp/cms/upload/upload.ashx'}});fileGridView.on("filedownload",function(grid,record,action,row,col){var c=cols[col]._col;var tempUploadId=record.get(c.name);if(tempUploadId==-1){xsrf_nav("/fp/cms/upload/download.ashx?id="+record.get(this.table.pk.columns[0].name)+"&col="+cols[col]._col.sid+"&tab="+this.table.sid);}else{xsrf_nav("/fp/cms/upload/downloadTemp.ashx?id="+tempUploadId);}},this);fileGridView.on("fileupload",function(upl,view,record,col){if(!upl.hasFile()){Ext.Msg.show({title:__tr('Errors on form'),msg:__tr('Please choose a file to upload.'),buttons:Ext.MessageBox.OK,icon:Ext.MessageBox.ERROR});return;}
var cancelled=false;Ext.MessageBox.show({msg:__tr('Uploading the document, please wait...'),progressText:__tr('Uploading...'),width:300,progress:true,icon:'ext-mb-download',animEl:'mb7',buttons:Ext.MessageBox.CANCEL,fn:function(){cancelled=true;upl.cancel();},scope:this});if(!upl._handlerAttached){upl.on('allfinished',function(o){if(cancelled)
return;var r=this.store.getAt(0);var err=r.get('error');if(err){Ext.MessageBox.show({title:__tr('Error'),msg:__tr('An error occurred uploading the document: {0}',err),buttons:Ext.MessageBox.OK,icon:Ext.MessageBox.ERROR});return;}
var info=r.get('info');record.set(cols[col]._col.name,info.info.tempUploadId);Ext.MessageBox.hide();});upl._handlerAttached=true;}
upl.upload({id:record.get(this.table.pk.columns[0].name)||0,tab:this.table.sid,col:cols[col]._col.sid});},this);for(var i=0;i<this.table.columns.length;++i){var c=this.table.columns[i];var cn=c.name;if(c.name==this.table.pk.columns[0].name&&!this.showPk){continue;}
if(this.keys.has(c.table.name,c.name)){continue;}
if(c.colType==ColType.FileName||c.colType==ColType.FileMime){}else if(c.colType==ColType.FileData){var fc=fileGridView.createFileColumn(c,cn,cn);cols.push(fc);plugins.push(fc);}else{var cfg={_col:c,id:c.name,header:c.description||c.name,dataIndex:cn};cfg.editor=Form.createEditField(c);cfg.renderer=function(val){var values={};values[this.column.name]=val;return Form.renderItem(this.column,values);}.createDelegate({column:c});cols.push(cfg);}}
var gpCfg={view:fileGridView,plugins:plugins,enableHdMenu:false,store:store,clicksToEdit:1,stripeRows:true,enableColumnHide:false,cm:new Ext.grid.ColumnModel(cols),viewConfig:{emptyText:__tr('No data entered.'),autoFill:true,forceFit:true},bbar:pagingBar};var me=this;if(this.readOnly!==true){gpCfg.tbar=new Ext.Toolbar({buttons:[{text:__tr('Add row'),iconCls:'new-icon',handler:function(){var Record=store.recordType;var r=new Record({});r.fields.each(function(fld){var c=this.table.columnsByName[fld.name];if(c&&c.colType==ColType.Enumerated&&!c.nullable&&c.enumeratedValues.length>0){r.set(fld.name,c.enumeratedValues[0].value);}else if(c&&!c.nullable&&c.type=="NUMBER"){r.set(fld.name,0);}else{r.set(fld.name,'');}},this);r.set(this.table.pk.columns[0].name,0);this.keys.each(function(keys,tableKey,colKey,value){r.set(colKey,value);});grid.stopEditing();store.add(r);if(!this.added){this.added=[];}
this.added.push(r);grid.startEditing(store.getCount()-1,0);},scope:me},{text:__tr('Cancel changes'),iconCls:'back-icon',handler:function(){store.rejectChanges();if(this.added){for(var i=0;i<this.added.length;++i){store.remove(this.added[i]);}
delete this.added;}},scope:me},{text:__tr('Save changes'),iconCls:'save-icon',handler:function(){var records=[];var storeRecords=[];var grid=this;store.each(function(record){if(record.dirty){var id=record.get(grid.table.pk.columns[0].name);if(id==0){records.push(record.data);storeRecords.push(record);}else{var data={};data[grid.table.pk.columns[0].name]=id;records.push(Ext.apply(data,record.getChanges()));storeRecords.push(record);}}
return true;});if(records.length<1){return;}
GridHandler.updateGrid({tab:this.table.sid,data:records},function(obj){var ids=obj.ids;for(var i=0;i<storeRecords.length;++i){storeRecords[i].set(this.table.pk.columns[0].name,ids[i]);}
store.commitChanges();delete this.added;this.fireEvent("save",this.table);},this);},scope:me}]});}
var grid=this.readOnly===true?new Ext.grid.GridPanel(gpCfg):new Ext.grid.EditorGridPanel(gpCfg);this.add(grid);this.on("show",function(){var sz=this.getSize();});},setKeys:function(keys){Ext.apply(this.keys,keys);if(!this.store){this.createGrid();var sz=this.getSize();this.doLayout();this.store.load();}else{this.store.reload();}}});}());