
/**
 * @class Voyeur.Tool.DocumentTypeCollocateFrequenciesGrid
 * @description A panel that provides per-document collocate data in a tabular format.
 * @extends Ext.grid.GridPanel
 * @extends Voyeur.Tool
 * @author Stéfan Sinclair
 * @since 0.1.1
 */
Voyeur.Tool.DocumentTypeCollocateFrequenciesGrid = Ext.extend(Ext.grid.GridPanel, {
	constructor: function(config){
		Ext.apply(this, new Voyeur.Tool(config, Voyeur.Tool.DocumentTypeCollocateFrequenciesGrid.prototype.i18n))
		var reader = new Ext.data.JsonReader({
			root: 'documentTypeCollocateFrequencies.types',
			totalProperty: 'documentTypeCollocateFrequencies["@totalTypes"]'
		}, Ext.data.Record.create([
			{name: 'type', mapping: '@type'}
			,{name: 'docId', mapping: '@docId'}
			,{name: 'docIndex', mapping: '@docIndex', type : 'int', renderer : function(val,meta,record,rowIndex,colIndex,store) {return store.reader.jsonData.corpus.documents[val]['@title']}}
			,{name: 'rawFreq', mapping: '@rawFreq', type: 'int'}
			,{name: 'relativeFreq', mapping: '@relativeFreq', type: 'float'}
			,{name: 'rawCollocateFreq', mapping: '@rawCollocateFreq', type: 'int'}
			,{name: 'relativeCollocateFreq', mapping: '@relativeCollocateFreq', type: 'float'}
			,{name: 'relativeRatio', mapping: '@relativeRatio', type: 'float'}
		]))
		
		var store = new Ext.data.GroupingStore({
			reader: reader
			,groupField:'docIndex'
			,proxy: new Ext.data.HttpProxy({url: this.getTromboneUrl()})
			,listeners : {
				'loadexception' : {
					fn: function(conn, proxy, response, error){
						var alert = Ext.MessageBox.alert("Error", "An error occurred while loading data:<pre style='overflow: auto; clear: both'>\n" + response.responseText+"</pre>");
						alert.setIcon(Ext.MessageBox.ERROR);
					}
					,scope : this
				}
			}
			,remoteSort: true,
			baseParams: {
				tool: 'DocumentTypeCollocateFrequencies',
				skin: 'trombone',
				context: 3
			},
			sortInfo: { field: 'relativeRatio', direction: "DESC"}
		});
		store.paramNames.sort='sortBy';
		store.paramNames.dir='sortDirection'
		
		var size = 50;
		
		var xtypePrefix = this.getXType() + '.';
		
		config.viewConfig = config.viewConfig ? config.viewConfig : {};
		Ext.applyIf(config.viewConfig, {
			forceFit: true,
			emptyText : this.localize('noResults','tool'),
			deferEmptyText: false
			,hideGroupedColumn: true
		})
		
		if (!config.plugins) {config.plugins=[]}
		config.plugins.push(new Ext.ux.grid.Favs())
		
		var panel = this;
		Ext.applyIf(config, {
			view: new Ext.grid.GroupingView(config.viewConfig)
			,iconCls : 'table'
			,loadMask: true,
			sm: new Ext.grid.RowSelectionModel(),
			stripeRows: true,
			colModel: new Ext.grid.ColumnModel([
				{header: 'Document',dataIndex: 'docIndex', renderer : function(val) {return panel.getCorpus().getDocument(val).getShortTitle()}, hidden: true}
				,{header: 'Type',dataIndex: 'type', sortable: true, renderer : function(val) {return '<span class="keyword">'+val+'</span>'}}
				,{header: 'Raw',dataIndex: 'rawCollocateFreq', sortable: true, renderer : function (val, meta, record) {var v = Ext.util.Format.usMoney(parseInt(val * 100) / 100); v = v.substring(1,v.length-3); var vr = Ext.util.Format.usMoney(parseInt(record.get('rawFreq') * 100) / 100); vr = vr.substring(1,vr.length-3); return v+' ('+vr+')'}}
				,{header: 'Relative',dataIndex: 'relativeCollocateFreq', renderer : function (val, meta, record) {var v = Ext.util.Format.usMoney(parseInt(val * 1000000) / 100); v = v.substring(1,v.length-3); var vr = Ext.util.Format.usMoney(parseInt(record.get('relativeFreq') * 1000000) / 100); vr = vr.substring(1,vr.length-3); return v+' ('+vr+')'}}
				,{header: 'Ratio',dataIndex: 'relativeRatio', renderer : function(val) {val = parseInt(val * 1000000) / 100; var isNeg = val < 0; var v = Ext.util.Format.usMoney(val); return (isNeg ? '-' : '<b>') + v.substring(isNeg ? 2 : 1,v.length-1) + (isNeg ? '' : '</b>')}}
			]),
			store: store,
			bbar: new Ext.PagingToolbar({
				store: store,
				pageSize: size,
				displayInfo: true
				,items : [
					'-',
					{
						text : this.localize('context')
						,tooltip : this.localize('contextTip')
						,menu : new Ext.menu.Menu({
							items : [
								new Ext.menu.CheckItem({text : '1',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '2',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '3',checked:true,group:'context'})
								,new Ext.menu.CheckItem({text : '4',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '5',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '7',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '10',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '15',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '20',checked:false,group:'context'})
								,new Ext.menu.CheckItem({text : '25',checked:false,group:'context'})
							]
							,listeners : {
								'itemclick' : {
									fn : function(item) {
										this.getStore().baseParams.context=item.text;
										this.getStore().reload();
									}
									,scope : this
								}
							}
						})
					}
				]
			
			})
		});
		Voyeur.Tool.DocumentTypeCollocateFrequenciesGrid.superclass.constructor.apply(this, arguments);
		
		this.addListener('CorpusSummaryResultLoaded', function(src, data) {
			this.getStore().baseParams.corpus=data.corpus['@id'];
		}, this);

		this.addListener('documentTypeSelected', function(src, data) {
			if (this.hidden) {return;}
			this.getStore().baseParams.corpus=this.getCorpus().getId();
			this.getStore().baseParams.docIdType = data.docIdType;
			this.getStore().load({params: {start: 0, limit: this.getBottomToolbar().pageSize}})
		}, this);

		this.addListener('documentTypesSelected', function(src, data) {
			if (this.hidden) {return;}
			this.getStore().baseParams.corpus=this.getCorpus().getId();
			this.getStore().baseParams.docIdType = data.docIdType;
			this.getStore().load({params: {start: 0, limit: this.getBottomToolbar().pageSize}})
		}, this);

		this.addListener('voyeurDocumentTermFrequenciesGrid.selectionchange', function(src, selectionModel){
			if (this.hidden) {return;}
			var records = selectionModel.getSelections();
			docIdTerms = [];
			if (records.length > 0) {
				for (var i = 0; i < records.length; i++) {
					docIdTerms.push(records[i].get('docId') + ':' + records[i].get('term'));
				}
				this.store.baseParams.docIdTerm = docIdTerms;
				this.store.load({
					params: {
						start: 0,
						limit: this.getBottomToolbar().pageSize
					}
				})
			}
		}, this);
		
		this.addListener('DocumentTypeCollocateFrequenciesResultLoaded', function(src, data) {
			this.getStore().baseParams.corpus=data.corpus['@id'];
			if (data.corpus.documents.length==1) {this.getStore().clearGrouping();}
			this.getStore().loadData(data);
		}, this);
		this.addListener('DocumentTypeCollocateFrequenciesGridBootstrap', function(src, params) {
			if (params.type) {this.getStore().baseParams.type = params.type}
			this.update({params : params, tool : ['CorpusSummary','DocumentTypeCollocateFrequencies']});
		}, this)
	}

	// private localization variables
	,i18n : {
		title : {en: "Collocates"}
		,help : {en: "This table shows the frequencies of words that appear near a specified term in a document."}
		,context : {en: "Context"}
		,contextTip : {en: "This value determines how many words to count on the left and the right of each keyword."}
		,term : {en: "Term"}
		,termTip : {en: "The term from the corpus for which data is being provided."}
		,count : {en: "Count"}
		,countTip : {en: "The raw count of this term in the entire corpus."}
		,relMax : {en: "Rel. Max"}
		,relMaxTip : {en: "This is the value for the document in the corpus with the top relative frequency (per 10,000 words)."}
		,relMeanTip : {en: "This is mean of the relative frequencies of all the value for the document in the corpus with the top relative frequency (per 10,000 words)."}
		,relMean : {en: "Rel. Mean"}
		,relStdDev : {en: "Std. Dev."}
		,relStdDevTip : {en: "Std. Dev."}
		,relSkew : {en: "Skew"}
		,relSkewTip : {en: "Skew"}
		,relKurtosis : {en: "Peakedness"}
		,relKurtosisTip : {en: "Peakedness"}
		,relTrend : {en: "Trend"}
		,relTrendTip : {en: "Trend"}
	}
});

Ext.reg('voyeurDocumentTypeCollocateFrequenciesGrid', Voyeur.Tool.DocumentTypeCollocateFrequenciesGrid);
