/**
 * 	PDA Client Code
 *	Author: Tung Nguyen
 *	Email: nltung@gmail.com
 */
// reference local blank image
Ext.BLANK_IMAGE_URL = './lib/ext/resources/images/default/s.gif';

// create namespace
Ext.namespace('Ext.ux.plugins');

//install plugin
Ext.ux.plugins.FitToParent = function(){
    return {
        init: function(c){
            c.monitorResize = true;
            c.doLayout = c.doLayout.createInterceptor(function(){
                var pos = this.getPosition(), size = Ext.get(this.el.dom.parentNode).getViewSize();
                this.setSize(size.width - pos[0], size.height - pos[1]);
            }, c);
        }
    }
}

// fix bug in radio check event
Ext.override(Ext.form.Radio, {
    onClick: function(){
        if (this.el.dom.checked != this.checked) {
            var els = this.el.up('form').select('input[name=' +
            this.el.dom.name +
            ']');
            els.each(function(el){
                if (el.dom.id == this.id) {
                    this.setValue(true);
                }
                else {
                    Ext.getCmp(el.dom.id).setValue(false);
                }
            }, this);
        }
    }
});

//Prevent emptyText to be submitted
Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createInterceptor(function(){
    this.form.items.each(function(item){
        if (item.el.getValue() == item.emptyText) {
            item.el.dom.value = '';
        }
    });
});
Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createSequence(function(){
    this.form.items.each(function(item){
        if (item.el.getValue() == '' && item.emptyText) {
            item.el.dom.value = item.emptyText;
        }
    });
});


Ext.namespace('at.cibiv');
// create application
at.cibiv.pda = function(){
    // do NOT access DOM from here; elements don't exist yet
    
    // private variables
    var userID = 'log_default.htm';
    // private functions
    
    // public space
    return {
        // public methods
        init: function(){
            Ext.QuickTips.init();
            
            // turn on validation errors beside the field globally
            Ext.form.Field.prototype.msgTarget = 'qtip';
            
            
            // help window
            var win = new Ext.Window({
				title : 'About',
                layout: 'fit',
                width: 280,
                height: 250,
                closeAction: 'hide',
                plain: false,
                contentEl : 'About'
            })
            
            var textfield_rootname = new Ext.form.TextField({
                id: 'text_rootname',
                height: 20,
                autoWidth: false,
                name: "rootname",
                emptyText: 'Taxon name ...',
                disabled: true,
                allowBlank: false,
                width: 120,
                grow: true,
                growMin: 120,
                // validationEvent : false,
                blankText: 'You have to provide a root taxon',
                hideLabel: true
            })
            
            //Tab panel for PD optimal analysis which contains result tab and log tabs
            var pdOptimal_tabpanel = new Ext.TabPanel({
                //plugins: [new Ext.ux.plugins.FitToParent()],									  
                xtype: 'tabpanel',
                border: true,
                bodyBorder: true,
                bodyStyle: 'padding-top: 10px',
                style: 'margin-top:25px',
                activeTab: 0,
                autoHeight: true,
                autoWidth: true,
                
                plain: false,
                defaults: {
                    bodyStyle: 'margin:10px 10px 10px 10px',
                    //plugins: [new Ext.ux.plugins.FitToParent()],
                    autoHeight: true,
                    autoScroll: true,
                    autoWidth: true
                
                },
                items: [{
                    //layout: 'fit',
                    id: 'pdOptimal_result',
                    title: 'Result',
                    //html : 'The computation result will appear here ...',
                    autoLoad: 'results/default.htm'
                }, {
                    //layout: 'fit',
                    id: 'pdOptimal_log',
                    title: 'Log',
                    disabled: true,
                    //html : 'Program log ...',
                    //autoLoad : 'results/'+userID
                    listeners: {
                        activate: function(p){
                            p.body.mask('Loading...', 'x-mask-loading');
                            p.body.load({
                                url: 'logs/' + userID + '_log.htm',
                                scripts: true,
                                method: 'GET',
                                callback: function(el){
                                    el.unmask();
                                }
                            });
                        }
                    }
                }]
            })
            
            // FormPanel for PD optimal analysis
            var pdOptimal_form = new Ext.form.FormPanel({
                //plugins: [new Ext.ux.plugins.FitToParent()],														
                labelWidth: 370, // label settings here cascade unless
                frame: false,
                waitMsgTarget: true,
                fileUpload: true,
                border: false,
                autoWidth: true,
                //bodyStyle: 'padding-bottom : 50px',
                defaults: {
                    //plugins: [new Ext.ux.plugins.FitToParent()],
                    bodyStyle: 'margin : 15px'
                },
                autoHeight: true,
                
                items: [{
                    xtype: 'fieldset',
                    
                    title: 'Tree or Network File',
                    //autoHeight: true,
                    height: 50,
                    defaults: {
                        autoWidth: true
                    },
                    
                    defaultType: 'textfield',
                    items: [{
                        id: 'tree_file',
                        xtype: 'textfield',
                        height: 20,
                        msgTarget: 'side',
                        fieldLabel: 'Please Upload Your Tree/Network File',
                        name: 'tree_file',
                        inputType: 'file',
                        allowBlank: false,
                        autoWidth: true,
                        validationEvent: false,
                        blankText: 'A tree or network file has to be provided for the computation'
                    }]
                }, { // Basic Options Field Set
                    xtype: 'fieldset',
                    title: 'Basic Options',
                    autoWidth: true,
                    //autoHeight: true,
                    height: 130,
                    //bodyStyle : 'padding: 5px,margin : 15px',
                    defaults: {
                        autowidth: true
                    },
                    
                    items: [{
                        id: 'text_SubSetSize',
                        fieldLabel: "Subset Size (explicit size or range)",
                        name: "text_SubSetSize",
                        height: 20,
                        xtype: "textfield",
                        blankText: "Please enter the subset size,you can also give a range of size like '2:10'",
                        allowBlank: false,
                        emptyText: 'Subset size ...',
                        regex: /^\d+(:\d+)?$/,
                        // validationEvent : false,
                        regexText: "You have to enter a number or a number range like '2:10'"
                    }, {
                        id: 'radio_unrooted',
                        fieldLabel: "Rooting Scheme",
                        name: "pda_root",
                        xtype: "radio",
                        boxLabel: "Unrooted",
                        checked: true,
                        inputValue: 'unrooted'
                    }, {
                        id: 'radio_newick',
                        name: "pda_root",
                        xtype: "radio",
                        boxLabel: "Rooted using newick input file (for tree only)",
                        labelSeparator: '',
                        inputValue: 'newick',
                        checked: false
                    }, {
                        layout: "column",
                        defaults: {
                            //autoHeight: true,
                            autoWidth: true
                        },
                        items: [{
                            layout: 'form',
                            bodyStyle: 'margin:5px 0px 0px 0px',
                            columnWidth: 0.5,
                            items: [{
                                id: 'radio_outgroup',
                                xtype: "radio",
                                boxLabel: "Rooted using an outgroup: \t ",
                                name: "pda_root",
                                inputValue: "outgroup",
                                labelSeparator: '',
                                hideLabel: false,
                                checked: false
                            }]
                        }, {
                            layout: 'form',
                            columnWidth: 0.5,
                            bodyStyle: 'margin:2px 2px 2px 2px',
                            items: [textfield_rootname]
                        }]
                    }]
                }, { // Advanced Options Field Set
                    xtype: 'fieldset',
                    title: 'Advanced Options',
                    autoWidth: true,
                    collapsible: true,
                    collapsed: true,
                    autoHeight: true,
                    //height: 350,
                    
                    defaultType: 'textfield',
                    items: [{
                        id: 'text_max',
                        name: "pda_minmax",
                        xtype: "radio",
                        fieldLabel: "Compute PD-Sets",
                        boxLabel: "Maximal",
                        checked: true,
                        inputValue: 'max'
                    }, {
                        id: 'text_min',
                        name: "pda_minmax",
                        xtype: "radio",
                        boxLabel: "Minimal",
                        labelSeparator: '',
                        inputValue: 'min'
                    }, new Ext.form.Checkbox({
                        name: 'checkbox_mulSet',
                        id: 'checkbox_mulSet',
                        fieldLabel: 'Identify multiple optimal PD-Sets'
                    }), {
                        id: 'text_maxSet',
                        fieldLabel: 'Maximal number of PD-Sets that should be identified',
                        name: 'text_maxSet',
                        xtype: "textfield",
                        height: 20,
                        allowBlank: true,
                        autoWidth: false,
                        // width : 100,
                        disabled: true,
                        emptyText: 'Number of sets ...',
                        regex: /^(\d)+$/,
                        regexText: 'You have to enter a number'
                    }, {
                        id: 'taxa_file',
                        xtype: 'textfield',
                        height: 20,
                        fieldLabel: 'Taxa file to be included',
                        name: 'taxa_file',
                        inputType: 'file',
                        allowBlank: true
                    }, {
                        id: 'weight_file',
                        xtype: 'textfield',
                        fieldLabel: 'Branch/Split scale and weights file',
                        name: 'weight_file',
                        inputType: 'file',
                        allowBlank: true
                    }, new Ext.form.Checkbox({
                        name: 'verbose',
                        fieldLabel: 'Verbose mode',
                        inputValue: 'yes'
                    })]
                
                }],
                
                buttons: [{
                    text: 'Run',
                    tooltip: 'Carry out the computation',
                    handler: function(){
                        if (pdOptimal_form.form.isValid()) {
                            pdOptimal_form.form.submit({
                                // Class Ext.form.Action.Submit
                                url: 'pda.php',
                                waitMsg: 'Processing,please wait .... ',
                                //clientValidation : true,
                                method: 'POST',
                                success: function(form, action){
                                    //Ext.Msg.alert('Message','It worked ');
                                    //Ext.Msg.alert('Success','results/pdaUser_'+action.result.userID+'_result.htm');
                                    
                                    
                                    //pdOptimal_tabpanel.doLayout();
                                    
                                    //Assign the User ID to local variable
                                    userID = action.result.userID;
                                    
                                    //Set the result tab to the active state
                                    pdOptimal_tabpanel.setActiveTab('pdOptimal_result');
                                    
                                    //Display result
                                    var result_tab = pdOptimal_tabpanel.findById('pdOptimal_result');
                                    result_tab.body.mask('Loading...', 'x-mask-loading');
                                    result_tab.body.load({
                                        url: 'results/' + action.result.userID + '_result.htm',
                                        scripts: true,
                                        method: 'GET',
                                        callback: function(el){
                                            var height = el.getHeight();
                                            if (height > 400) { // too long
                                            	el.setHeight(500);
                                            }
                                            el.unmask();
                                            
                                            
                                        }
                                    });
                                    
                                    
                                    //Display log
                                    var log_tab = pdOptimal_tabpanel.findById('pdOptimal_log');
                                    log_tab.enable();
                                    
                                    
                                    
                                    /*
                                     var result_tab = Ext.getCmp('pdOptimal_result');
                                     result_tab.body.mask('Loading', 'x-mask-loading');
                                     result_tab.body.load({
                                     url : 'results/'+action.result.userID+'_result.htm',
                                     method : 'GET',
                                     callback : function (el){
                                     el.unmask();
                                     }
                                     });
                                     */
                                },
                                failure: function(form, action){
                                    Ext.Msg.alert('Failure', action.result.errors.reason);
                                    
                                    //Assign the User ID to local variable
                                    userID = action.result.userID;
                                    
                                    //Set the result tab to the active state
                                    pdOptimal_tabpanel.setActiveTab('pdOptimal_result');
                                    
                                    var result_tab = pdOptimal_tabpanel.findById('pdOptimal_result');
                                    
                                    result_tab.body.update('<strong>The program could not produce the result because there were errors during the computation,please see log for more detail</strong>');
                                    
                                    //Display log
                                    var log_tab = pdOptimal_tabpanel.findById('pdOptimal_log');
                                    log_tab.enable();
                                }
                            });
                            
                        }
                        
                    }
                }, {
                    text: 'Reset',
                    tooltip: 'Reset the form for a new computation',
                    handler: function(){
                        Ext.Ajax.abort();
                        pdOptimal_form.form.reset();
                    }
                }, {
                    text: 'About',
                    tooltip: 'Information about this application',
                    handler: function(){
                        win.show(this);
                    }
                }]
            
            });
            
            // Main application panel, which contains a TabPanel. Each Tab in
            // the TabPanel represents a sub-functionality
            // of the application (e.g : tab1 : PD optimal sets analysis, tab2 :
            // Area analysis,....)
            var pd_form = new Ext.Panel({
                //plugins: [new Ext.ux.plugins.FitToParent()],
                renderTo: document.body,
                id: 'PD_Optimization',
                // overridden
                //url : 'pda.php',
                frame: true,
                waitMsgTarget: true,
                title: 'Phylogenetic Diversity Analyzer Version 0.5',
                bodyStyle: 'padding:5px',
                //width: 815,
                fileUpload: true,
                footer: true,
                border: false,
                autoHeight: true,
                autoWidth: true,
                
                items: {
                    xtype: 'tabpanel',
                    border: true,
                    plain: true,
                    activeTab: 0,
                    style: 'margin-top: 5px',
                    defaults: {
                        //autoHeight: true,
                        bodyStyle: 'padding:15px',
                        autoHeight: true
                    },
                    
                    items: [{
                        title: 'PD Optimal Sets Analysis',
                        layout: 'form',
                        autoWidth: true,
                        /*defaults: {
                         width: 760
                         },*/
                        defaultType: 'textfield',
                        tabTip: 'Find the optimal sets of taxa from a given tree or network file',
                        
                        items: [pdOptimal_form, pdOptimal_tabpanel]
                    }, // PD Area Analysis
                    {
                        title: 'PD Area Analysis',
                        layout: 'form',
                        autoWidth: true,
                        /*defaults: {
                         width: 700
                         },*/
                        tabTip: 'Will be available soon...',
                        defaultType: 'textfield',
                        html: 'This feature will be added in the future, you can use this <a href="http://www.cibiv.at/software/pda/web-pda/pd-area">site</a> instead'
                    
                    }]
                }
            });
            
            //pd_form.render('Program');
            
            Ext.getCmp('radio_outgroup').on('check', function(e){
                // Ext.MessageBox.alert('status', 'I got you ' + e.checked);
                if (e.checked == true) {
                
                    Ext.getCmp('text_rootname').enable();
                    Ext.getCmp('text_rootname').allowBlank = false;
                }
                
                else {
                    Ext.getCmp('text_rootname').allowBlank = true;
                    Ext.getCmp('text_rootname').clearInvalid();
                    Ext.getCmp('text_rootname').disable();
                    
                }
                
            });
            
            Ext.getCmp('checkbox_mulSet').on('check', function(e){
                if (e.checked == true) {
                    Ext.getCmp('text_maxSet').enable();
                }
                else 
                    Ext.getCmp('text_maxSet').disable();
            })
        }
    };
}
(); // end of app
// end of file
