/**
 * @class Voyeur.Tool.CorpusTypeFrequenciesChart
 * @description A panel for displaying graphs of the frequencies of types across the entire corpus.
 * @extends Ext.Panel
 * @extends Voyeur.Tool
 * @author Stéfan Sinclair
 * @since 0.1.1
 */
 
function load_empty_open_chart_data() {
	return '{ "bg_colour":"#FFFFFF", "elements": [ { "type": "line", "values": [0,1,2], "dot-style": { "type": "dot", "colour": "#FFFFFF" }, "width": 0 } ], "y_axis":{"stroke":0,"colour":"#FFFFFF","labels":[],"grid-colour":"#FFFFFF"},"x_axis":{"stroke":0, "colour": "#FFFFFF", "grid-colour" : "#FFFFFF"}}'
}
Voyeur.Tool.TypeFrequenciesChart = Ext.extend(Ext.Panel, {
	getChartObjectId : function() {return this.id.replace(/-/g,'_')+'_chart';}
	,constructor : function(config) {
		Ext.apply(this, new Voyeur.Tool(config, this))
		
		Ext.applyIf(config, {
			iconCls : 'chart-line'
			,html : '<span class="x-grid-empty">'+this.localize('noResults')+'</span>'
		});
		Voyeur.Tool.TypeFrequenciesChart.superclass.constructor.apply(this, arguments);
		
		// add exporter for image
		this.exporters.img = this.localize('exportImg');

		this.addListener('afterrender', function(src, component) {
			var id = this.getChartObjectId();
			this.body.dom.innerHTML += '<div id="'+id+'"></div>';
			swfobject.embedSWF(this.getApplication().getBaseUrl()+"resources/lib/open-flash-chart/open-flash-chart.swf", id,
	  			'100%', '100%', "9.0.0", "expressInstall.swf", {'get-data' : 'load_empty_open_chart_data'}, {wmode: 'opaque'});
		}, this);
		this.addListener('corpusTypeSelected', function(src, data, record) {
			if (record) {this.handleTypeSelection([record],'corpus');}
		});
		this.addListener('corpusTypesSelected', function(src, data, records){
			if (records) {this.handleTypeSelection(records,'corpus');}
		});
		this.addListener('documentTypeSelected', function(src, data,record){
			if (src && src.xtype==this.xtype) {return;}
			if (record) {this.handleTypeSelection([record],'document');}
		});
		this.addListener('documentTypesSelected', function(src, data,records){
			if (records) {this.handleTypeSelection(records,'document');}
		});
		this.addListener('expand', function() {
			Ext.get(this.getChartObjectId()).repaint();
		}, this)
		
		this.addListener('CorpusTypeFrequenciesResultLoaded', function(src, data) {
			this.handleTypeSelection(this.corpusTypeReader.readRecords(data).records,'corpus')
		}, this);
		this.addListener('DocumentTypeFrequenciesResultLoaded', function(src, data) {
			this.handleTypeSelection(this.documentTypeReader.readRecords(data).records,'document')
		}, this);
		this.addListener('CorpusSummaryResultLoaded', function(src, params) {
			var params = this.getApiParams();
			this.update({params : params, tool : params.mode=='corpus' ? 'CorpusTypeFrequencies' : 'DocumentTypeFrequencies'})
		}, this);

		this.addListener('export', function(exp) {
			if (exp=='img') {
				
				var img_win = window.open('', 'Charts: Export as Image')
				var img_data = document[this.getChartObjectId()].get_img_binary();
				with(img_win.document) {
					write('<html><head><title>'+this.localize('title')+'<\/title><\/head><body>' + 
							"<img src='data:image/png;base64," + img_data + "' /><br />"+this.getFooterText()+"<p>"+this.localize("exportImgSrc")+"</p><tt>&lt;img src=\"data:image/png;base64,"+img_data+"\" alt=\"\" /&gt;</tt><\/body><\/html>")
				}
				img_win.document.close(); // stop the 'loading...' message
				img_win.focus();
			}
		}, this)
	}
	
	,handleTypeSelection : function(records,mode) {
		var lastParams = {mode: mode, docIdType: null, type: null}
			if (mode=='document') {
				prefix='distribution';
				lastParams.docIdType = []
			}
			else {
				prefix='relative'
				lastParams.type = [];
			}
			if (this.collapsed) {return}
			var titles = Voyeur.application.getCorpus().getShortLabels();
			var hellip = /&hellip;/g;
			for (var i=0;i<titles.length;i++) {titles[i] = titles[i].replace(hellip,'');}

			var record;
			var min = Number.MAX_VALUE;
			var max = Number.MIN_VALUE;
			var elements = [];
			var id = this.getChartObjectId();
			for (var i=0;i<records.length;i++) {
				record = records[i];
				var counts = record.get(prefix+'Freqs');
				var values = new Array();
				var type = record.get('type');
				// track types for exporting
				if (mode=='document') {lastParams.docIdType.push(record.get('docId')+':'+type)}
				else {lastParams.type.push(type);}
				for (var j = 0; j < counts.length; j++) {
//					val = mode=='corpus' ? parseInt(counts[j]*100)/100 : counts[j];
					val = counts[j]
					if (val>max) {max=val;}
					if (val<min) {min=val;}
					values.push({
						value : val
						,tip : type+': #val#' + (mode=='corpus' ? "\n" +titles[j] : '')
						,colour : this.colors[i]
					})
				}
				var handler = id+'_'+i
				var me = this;
				window[handler] = function(index) {
					me.getApplication().dispatchEvent('documentTypeSelected', me, {docIdType : me.getCorpus().documents.get(index).get('id')+':'+arguments.callee.type}, record);
				}
				window[handler].type=record.get('type');
				
				elements.push({
					
						type: 'line'
						,colour: this.colors[i] ? this.colors[i] : '#999999'
						,text: (mode=='document' ? (1+Number(record.get('docIndex')))+') ' : '') + type
						,"font-size": 10
						,width:     1
						,"dot-style": {
							type: "solid-dot"
							,colour: "#a44a80"
							,"dot-size": 3
							,tip: record.get('term')+': #val# (#x_label#)'
							,'on-click' : handler
						}
						,values : values

				})
//				if (record.get(prefix+'Max')>max) {max=record.get(prefix+'Max')}
//				if (record.get(prefix+'Min')<min) {min=record.get(prefix+'Min')}
			}
			this.setApiParams(lastParams);
			var emptyText = this.body.child('span[@class="x-grid-empty"]');
			if (emptyText && emptyText.isVisible()) {
				emptyText.setDisplayed(false)
			}
			var chart = Ext.get(this.getChartObjectId());
			if (!chart.isVisible()) {
				chart.setDisplayed(true);
			}
			if (max-min>10) {	
				max = Math.ceil(max);
				min = Math.floor(min);
			}
			var chartData = {
				elements : elements
				,"bg_colour": "#ffffff"
				,'x_axis': {
					labels : {
						labels : mode=='corpus' ? titles : null
						,rotate : 'vertical'
					}
					,'grid-colour' : "#EEEEEE"
					,stroke : 1
					,colour : '#EEEEEE'
				}
				,"y_axis": {
		    		min: min
		    		,max: max
					,steps : (max-min > 10 ? parseInt((max-min)/10) : (max-min)/10)
					,'grid-colour' : "#EEEEEE"
					,stroke : 1
					,colour : '#EEEEEE'
				}
				,"tooltip": { "mouse": 2, "stroke": 1, "colour": "#000000", "background": "#ffffff" }
				,title : {text: this.localize(mode+"Title")}
			}
			this.updateChart(chartData);			
	}

	,updateChart : function(chartData) {
		if (this.collapsed) {return}
		var me = this;
		try {
			document[me.getChartObjectId()].load(Ext.encode(chartData))
		}
		catch (e) {
			setTimeout(function(){me.updateChart.call(me,chartData)},1000)
		}
	}
	,colors : ['#0000FF','#33C533','#FF00FF','#7933FF','#1CFFFF','#FFAE00','#1EB1FF','#B6F23A','#FF00A4','#336699','#226F34','#9B1468','#6D2B9D','#808221','#6F4C0A','#7773A5','#3DB1A9','#CA8773','#C2A9CC','#B5D4E4','#B5D4E4','#FFC5C5','#E4C87C','#E4C87C']

	,corpusTypeReader : new Ext.data.JsonReader({
			root : 'corpusTypes.types'
			,totalProperty : 'corpusTypes["@totalTypes"]'
		}, Ext.data.Record.create(Voyeur.data.CorpusTypes.fields)) 

	,documentTypeReader : new Ext.data.JsonReader({
			root : 'documentTypes.types'
			,totalProperty : 'documentTypes["@totalTypes"]'
		}, Ext.data.Record.create(Voyeur.data.DocumentTypes.fields)) 

	,api: {
		docIdType: {'default': null}
		,type: {'default': null}
		,mode: {'default': null}
	}

	,i18n : {
		title : {en: "Word Trends"}
		,help : {en: "This chart shows how terms are distributed across documents in a corpus (documents are shown in the order in which they were added)."}
		,corpusTitle : {en : 'Distribution of Types across Corpus'}
		,documentTitle: {en : 'Distribution of Types across Document'}
		,exportImg: {en : 'a static image in a new window'}
		,exportImgSrc: {en: 'HTML source code for this image:'}
	}
});

Ext.reg('voyeurTypeFrequenciesChart', Voyeur.Tool.TypeFrequenciesChart);
