/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */


Ext.onReady(function(){

//----- File upload box -----//
	
    Ext.QuickTips.init();
	
	var AjaxWaiting;
	Ext.Ajax.on('beforerequest', function(){AjaxWaiting = Ext.Msg.wait("contacting R server... please wait...","waiting...");});
	Ext.Ajax.on('requestcomplete', function(){AjaxWaiting.hide();});
	Ext.Ajax.on('requestexception', function(){AjaxWaiting.hide();});
    
    var msg = function(title, msg){
        Ext.Msg.show({
            title: title, 
            msg: msg,
            minWidth: 200,
            modal: true,
            icon: Ext.Msg.INFO,
            buttons: Ext.Msg.OK
        });
    };
    

    var fp = new Ext.FormPanel({
        renderTo: 'fi-form',
        fileUpload: true,
        width: 550,
        frame: true,
        title: 'File Upload Form',
        autoHeight: true,
        bodyStyle: 'padding: 10px 10px 0 10px;',
        labelWidth: 50,
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{
            xtype: 'textfield',
            emptyText: 'Name your dataset',
            fieldLabel: 'Name',
            name: 'dataname',
            id: 'dataname'
        },{
            xtype: 'fileuploadfield',
            id: 'form-file',
            emptyText: 'Select a file',
            fieldLabel: 'Datafile',
            name: 'datafile',
            buttonCfg: {
                text: '',
                iconCls: 'upload-icon'
            }
        },{
			fieldLabel: 'Headers',
			boxLabel: 'Datafile includes variable names',
			xtype: 'checkbox',
			name: 'headers',
			id: 'headers'
        }],
        buttons: [{
            text: 'Upload',
            handler: function(){
                if(fp.getForm().isValid()){
	                fp.getForm().submit({
	                    url: '../brew/upload-tryCatch.rhtml',
						//url: '../brew/echo.rhtml',
						method: 'post',
	                    waitMsg: 'Uploading your data...',
	                    success: function(fp, o){
	                        //msg('Success', 'Processed file "'+o.result.file+'" on the server.');
							grid2.getStore().loadData(o.result.variables);
							grid2.enable(true);
							grid3.currentData = o.result.file;
							selectItem();
	                    },
	                    failure: function(fp, o){
	                        msg('Failure', 'An error occured: '+o.result.error);
							grid2.enable(true);
							//msg('Failure', 'An error occured: '+o.response.responseText);
	                    }
	                });
                }
            }
        }]
    });
	 
//----- variables grid -----//
    var xg = Ext.grid;

    // json reader
    var reader = new Ext.data.ArrayReader({}, [
	   {name: 'index'},
       {name: 'variable'},
       {name: 'metric'},
	   {name: 'levels'},
	   {name: 'missing'}
    ]);
	
	var combo = new Ext.form.ComboBox({
		store: [['1pIRT','1p IRT Rasch'],['1pIRTd1','1p IRT Rasch D=1'],['1pIRTd7','1p IRT Normal Ogive'],['2pIRT','2p IRT (ltm)'],['3pIRT','3p IRT']],
		displayField:'model',
		typeAhead: true,
		editable: false,
		mode: 'local',
		triggerAction: 'all',
		emptyText:'Select a model...'
		//applyTo: 'local-states'
	});	
	combo.addListener("select",selectItem);
	
	// to warn only once about 2 levels.
	var levelWarnings = false;
	
	function selectItem(){
	
		grid3.getStore().removeAll();
		var selectedRecords = grid2.getSelectionModel().getSelections();
		var newRecords = new Array(selectedRecords.length);
		var selectedIndices = new Array(selectedRecords.length);
		
		for(thisRecord=0; thisRecord < selectedRecords.length; thisRecord++){
			
			if(selectedRecords[thisRecord].get('levels') == 2){
			
			//maybe later make this better...
			}

			var newRecord = new dataRecord({
				index: selectedRecords[thisRecord].get('index'),
				variable: selectedRecords[thisRecord].get('variable'),
				item: thisRecord+1 // item is used for the col index of the myNewData file. +1 to match R counting.
			});
			newRecords[thisRecord] = newRecord;
			selectedIndices[thisRecord] = selectedRecords[thisRecord].get('index');
			
			if(selectedRecords[thisRecord].get('levels') != 2) {
				if(!levelWarnings){
					msg("IRT","IRT only supports variable's with 2 levels!");
					levelWarnings = true;
					return;
				}
			}
		}
		grid3.selectedIndices = selectedIndices;
		grid3.getStore().add(newRecords);
		grid3.enable(true);
		document.getElementById("outputicons").style.display = 'none';
	}
	
	function updateCoef(coefmatrix){
		
		
		var records = grid3.getStore().getRange();
		var reclength = records.length;
		
		for(i=0; i<reclength;i++){
		
			thisItem = records[i].get("item");
		
			records[i].set('guess',coefmatrix[thisItem-1][0].toFixed(3));
			records[i].set('difficulty',coefmatrix[thisItem-1][1].toFixed(3));
			records[i].set('discrimination',coefmatrix[thisItem-1][2].toFixed(3));

		}
		document.getElementById("outputicons").style.display = 'block';		
	}
	
	//renderer for the 2levels
    function checkLevels(val){
        if(val ==2){
            return '<span style="color:green;">' + val + '</span>';
        }else if(val != 2){
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    }	
	
    var sm = new xg.CheckboxSelectionModel();
	sm.addListener("rowselect",selectItem);
	sm.addListener("rowdeselect",selectItem);
    var grid2 = new xg.GridPanel({
        store: new Ext.data.Store({
            reader: reader
            //a priori no data
        }),
        cm: new xg.ColumnModel([
            sm,
			{id:'index',header: "Index", width: 50, sortable: true, dataIndex: 'index'},
            {header: "Variable name", width: 200, sortable: true, dataIndex: 'variable'},
            {header: "Metric", width: 100, sortable: true, dataIndex: 'metric'},
			{header: "Levels", width: 50, sortable: true, renderer: checkLevels, dataIndex: 'levels'},
			{header: "Missing", width: 50, sortable: true, dataIndex: 'missing'}
        ]),
        sm: sm,
		disabled: true,
        width:550,
        height:300,
        frame:true,
        viewConfig: {
            forceFit:true
        },			
        title:'Select which variables you want to use.',
        iconCls:'icon-grid',
        renderTo: 'variables-grid',
		buttons: [
			combo,
			{	text: 'Fit Model!',
				handler: function() {
				
					if(grid2.getSelectionModel().getSelections().length < 2){
					
						msg("IRT",'you have not selected enough variables to fit a model');
						return;
					}
					
					if(combo.getValue()==""){
					
						msg("select a model",'You have to select a model type!');
						return;
					}					
				
					//alert("Fitting model with data: " + grid3.currentData + ", model: " + combo.getValue() + ", items:" + grid3.selectedIndices.toString());
					var thisAjax = Ext.Ajax.request({
						url: '../brew/irt.rhtml',
						method: 'POST',
						success: function(o){
							try{
								result = Ext.decode(o.responseText);
								//msg('Success',"responseText: "+o.responseText);
								if(!result.success) {
									msg('Failure', 'An error occured: '+result.error);
								}
								else{
									//msg('Success','Coef:'+result.coef);
									updateCoef(result.coef);
									document.getElementById("IIC").src = "plots/.IIC." + result.modelFile.toString() + ".png";
									document.getElementById("ICC").src = "plots/.ICC." + result.modelFile.toString() + ".png";
									document.getElementById("scores").src = "plots/.scoredensity." + result.modelFile.toString() + ".png";
									grid3.currentmodelFile = result.modelFile.toString();
									document.getElementById("dataicon").onclick = function() {window.open('../brew/getcsv.rhtml?randomnum='+grid3.currentmodelFile);}
									document.getElementById("pdficon").onclick = function() {window.open('../brew/getpdf.rhtml?randomnum='+grid3.currentmodelFile);}
									document.getElementById("infoicon").onclick = function() {window.open('plots/.info.'+grid3.currentmodelFile+".txt");}
								}
							}
							catch(err) {
								alert("error in decoding json. ResponseText: "+o.responseText+ ". Possibly server overload. Try again later.");
							}
						},
						failure: function(o){
							msg('Failure', 'An error occured: '+o.responseText);
						},
						params: { 
							IRTmodel: combo.getValue(), 
							itemstring: grid3.selectedIndices.toString(), 
							datastring: grid3.currentData
						}
					});
				}
			}		
		],
		buttonAlign:'center'
    });
	
	var dataRecord = Ext.data.Record.create([
		{name: 'index', mapping: 'index'},
		{name: 'item', mapping: 'item'},
		{name: 'variable', mapping: 'variable'},
		{name: 'difficulty', mapping: 'difficulty'},
		{name: 'discrimination', mapping: 'discrimination'},
		{name: 'guess', mapping: 'guess'}
	]);	
	
	//----- model grid -----//
	
    var reader2 = new Ext.data.ArrayReader({}, [
	   {name: 'index'},
       {name: 'variable'},
       {name: 'difficulty'},
	   {name: 'discrimination'},
	   {name: 'guess'}
    ]);	

    var grid3 = new xg.GridPanel({
        store: new Ext.data.Store({
            reader: reader2
            //a priori no data
        }),
        cm: new xg.ColumnModel([
			{id:'index',header: "Index", width: 50, sortable: true, dataIndex: 'index',hidden:true},
			{header: "Item", width: 50, sortable: true, dataIndex: 'item'},
            {header: "Variable name", width: 200, sortable: true, dataIndex: 'variable'},
            {header: "Difficulty", width: 100, sortable: true, align: 'right', dataIndex: 'difficulty'},
			{header: "Discrimination", width: 100, sortable: true, align: 'right', dataIndex: 'discrimination'},
			{header: "Guess", width: 100, sortable: true, align: 'right', dataIndex: 'guess'}
        ]),
		disabled: true,
		sortInfo:{field: 'index', direction: "ASC"},
        width:550,
        height:300,
        frame:false,
        title:'Select a model.',
        iconCls:'icon-grid',
        renderTo: 'model-grid',
		disableSelection: true,
        viewConfig: {
            forceFit:true
        }
    });
	
	var win;
    var button = Ext.get('graphicon');

    button.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!win){
            win = new Ext.Window({
                applyTo     : 'hello-win',
                layout      : 'fit',
                width       : 500,
                height      : 570,
				pageX		: 200,
				pageY		: 100,
                closeAction :'hide',
                plain       : true,
                items       : new Ext.TabPanel({
                    applyTo        : 'hello-tabs',
                    autoTabs       : true,
                    activeTab      : 0,
                    deferredRender : false,
                    border         : false
                }),

                buttons: [{
                    text     : 'Close',
                    handler  : function(){
                        win.hide();
                    }
                }]
            });
        }
        win.show(button);
    });
	
	new Ext.ToolTip({
        target: 'graphicon',
		trackMouse:true,
		title: 'Model plots',
        html: 'Click to inspect the item information and characteristic curves.'
    });

	new Ext.ToolTip({
        target: 'infoicon',
		trackMouse:true,
		title: 'Summary',
        html: 'Click to view raw summary information about the model.'
    });

	new Ext.ToolTip({
        target: 'dataicon',
		trackMouse:true,
		title: 'Export CSV',
        html: 'Click to export the datafile with latent trait scores.'
    });
	
	new Ext.ToolTip({
        target: 'pdficon',
		trackMouse:true,
		title: 'Export PDF',
        html: 'Click to export to PDF.'
    });	
	
	new Ext.ToolTip({
        target: 'demoIcon',
		trackMouse:true,
		title: 'Watch Demo Video',
        html: 'Click to watch a 2 minute instruction video about IRTtool.'
    });		
	
});