
/**
 * @class Cirrus 
 * @description A simple panel which loads the Cirrus app
 * @extends Ext.Panel
 * @extends Voyeur.Tool
 * @author Andrew MacDonald
 * @since 1.0
 */
Voyeur.Tool.Cirrus = Ext.extend(Ext.Panel, {
    initialized: false,
    flashInitialized: false,
    getCirrusObjectId : function() {return this.id.replace(/-/g,'_')+'_cirrus';},
    flashvars : {
        background: '0xffffff',
        fade: true,
        smoothness: 5,
        diagonals: 'none'
    },
    initCirrus: function(params) {
        if (!this.initialized) {
            Ext.apply(this.flashvars, params);
            if (!this.flashvars.baseUrl) this.flashvars.baseUrl = this.getTromboneUrl();
            var id = this.getCirrusObjectId();
var scripts = '<script type="text/javascript">'+
'function cirrusClickHandler(word, value) {'+
'if (window.console && console.info) console.info(word, value);'+
'var cirrusTool = Ext.ComponentMgr.all.find(function(object){if (object.xtype==\'voyeurCirrus\') {return true;} else {return false;}});'+
'cirrusTool.cirrusClickHandler(word, value);'+
'}'+
'function cirrusLoaded() {'+
'if (window.console && console.info) console.info("cirrus flash loaded");'+
'var cirrusTool = Ext.ComponentMgr.all.find(function(object){if (object.xtype==\'voyeurCirrus\') {return true;} else {return false;}});'+
'cirrusTool.cirrusLoaded();'+
'}'+
'function resizeCirrus(width, height) {'+
'var flashObj = Ext.getDom("'+id+'");'+
'flashObj.setAttribute("width", width);'+
'flashObj.setAttribute("height", height);'+
'function doResize(){flashObj.resizeWords();}'+
'doResize.defer(50);'+
'}'+
'</script>';
            this.body.update(scripts+'<div id="'+id+'"></div>', true);
            var params = {
                menu: 'false',
                scale: 'showall',
                allowScriptAccess: 'always',
                bgcolor: '#222222',
                wmode: 'opaque'
            };
            var attributes = {
                id: id,
                name: id
            };
            swfobject.embedSWF(this.getApplication().getBaseUrl()+"resources/lib/cirrus/Cirrus.swf", id,
                '100%', '100%', "10.0.0", "expressInstall.swf", this.flashvars, params, attributes);
            this.initialized = true;
        }
    },
    
    cirrusLoaded: function() {
        this.flashInitialized = true;
    },
    
    cirrusClickHandler: function(word, value) {
        if (value == this.getCorpus().getId()) {
            Voyeur.application.dispatchEvent('corpusTypeSelected', this, {type: word});
        } else {
            var docIdType = value + ':' + word;
            Voyeur.application.dispatchEvent('documentTypesSelected', this, {docIdType: docIdType});
        }
    },
    
    constructor : function(config) {
        Ext.apply(this, new Voyeur.Tool(config, Voyeur.Tool.Cirrus.prototype.i18n));
        

		this.setQueryValues(this.flashvars);
		
		// copy values back into flashvars
        for (var k in this.flashvars) {if (this[k]) {this.flashvars[k]=this[k]}}

        Ext.applyIf(config, {});
        
        Voyeur.Tool.Cirrus.superclass.constructor.apply(this, arguments);

        this.addListener('afterrender', function(src, params) {
            this.initCirrus(params);
        }, this);
        this.addListener('CirrusBootstrap', function(src, params) {
            this.fetch(['CorpusSummary', params.docId ? 'DocumentTypeFrequencies' : 'CorpusTypeFrequencies'], params);
        }, this);
        this.addListener('corpusDocumentSelected', function(src, params) {
        	this.fetch('CorpusTypeFrequencies', params);
        }, this);
    	this.addListener('CorpusTypeFrequenciesResultLoaded', function(src, data) {
    		this.handleTypeData(this.corpusTypeReader.readRecords(data).records,'corpus');
    	}, this);
    	this.addListener('DocumentTypeFrequenciesResultLoaded', function(src, data) {
    		this.handleTypeData(this.documentTypeReader.readRecords(data).records,'document');
    	}, this);
        
    }
    
    ,handleTypeData : function (records, mode) {
        var words = [];
        //console.warn(records);
        var freqField = mode=='corpus' ? 'rawFreq' : 'relativeFreq';
        for (var i = 0; i < records.length; i++) {
            var word = {word: records[i].get('type'), size: records[i].get(freqField), label: records[i].get(freqField)};
            if (mode =='corpus') word.value = this.getCorpus().getId();
            else word.value = records[i].get('docId');
            words.push(word);
        }
        //console.warn(words);
        this.sendWords(words);
    }

    ,sendWords: function(words) {
		var me = this;
		try {
            var id = this.getCirrusObjectId();
            var cirrusApp = Ext.getDom(id);
            var doResize = cirrusApp.addWords(words);
            if (doResize) cirrusApp.resizeWords();
            cirrusApp.arrangeWords();
		}
		catch (e) {
			setTimeout(function(){me.sendWords.call(me,words)},750)
		}
    }
    
    /**
     * Fetch Voyeur results using the specified tool and the provided params (and other parameters as needed).
     * @params {String} tool the tool to fetch data (CorpusTypeFrequencies or DocumentTypeFrequencies)
     * @params {Object} params parameters to be sent to the tool (others may be provided by default if not specified).
     */
    ,fetch : function(tool,params) {
    	Ext.applyIf(params, {
    		limit: 75
            //,stopList: 'stop.en.smart.txt'
    	});
    	this.update({tool: tool, params: params});
    }
	,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)) 
    ,i18n : {
        title : {en: 'Cirrus'}
        ,help: {en: 'This tool organizes words into a "cloud".'}
        ,adaptedFrom: {en: 'This tool is based on this <a href="http://emumarketing.uoregon.edu/paul/2008/09/28/the-new-tag-cloud/" target="_blank">Wordle Clone</a>.'}
    }
});

Ext.reg('voyeurCirrus', Voyeur.Tool.Cirrus);
