// Student Tab: Functions ------------------------------------------------

// Add custom validation ------------------------------------------

// student ID
Ext.form.VTypes['studentIdVal'] = /^[0-9]{4}/;
Ext.form.VTypes['studentIdMask'] = /[0-9]/;
Ext.form.VTypes['studentIdText'] = 'Please enter a 4-digit number.';
Ext.form.VTypes['studentId'] = function(v){
    return Ext.form.VTypes['studentIdVal'].test(v);
}
// phone number
Ext.form.VTypes['phoneVal'] = /^[0-9]{3}-[0-9]{3}-[0-9]{4}/;
Ext.form.VTypes['phoneMask'] = /[0-9\-]/;
Ext.form.VTypes['phoneText'] = 'Wrong format. Example: \'123-456-7890\'';
Ext.form.VTypes['phone'] = function(v){
    return Ext.form.VTypes['phoneVal'].test(v);
}
// zip code
Ext.form.VTypes['zipVal'] = /^[0-9]{5}/;
Ext.form.VTypes['zipMask'] = /[0-9]/;
Ext.form.VTypes['zipText'] = 'Please enter a 5-digit number.';
Ext.form.VTypes['zip'] = function(v){
    return Ext.form.VTypes['zipVal'].test(v);
}

// Comboboxes  --------------------------------------------------------------------

// Major comboBox
var majorComboBox = new Ext.form.ComboBox({
    store: majorDataArr,
    mode: 'local',
    valueField: 'id',
    displayField: 'name',
    fieldLabel: 'Declared Major',
    name: 'major',
    allowBlank: false,
    typeAhead: true,
    triggerAction: 'all'
});

// Grid column editor definitions ------------------------------------------------------

var name_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 50
});
var studentID_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 4,
    vtype: 'studentId'
});
var phone_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 12,
    vtype: 'phone'
});
var major_editor = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    mode: 'local',
    store: majorDataArr,
    allowBlank: false,
    displayField: 'name'
});
var street_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 50
});
var city_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 50
});
var state_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 6
});
var zip_editor = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 5,
    vtype: 'zip'
});
var dormComboBox_editor = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    mode: 'local',
    store: dormDataArr,
    allowBlank: false,
    displayField: 'id'
});

// Grid data and structures -------------------------------------------------------

var studentDataArr = new Ext.data.Store({
    // url: 'sampleData/students.json',
    // url: 'getStudentsJSON.jsp',
    url: '/mvc6c/studentSearch',
    reader: new Ext.data.JsonReader({
        root:'theArray',
        id:'id'
    }, [
    'id',
    'name',
    'studentID',
    'phone',
    'major',
    'street',
    'city',
    'state',
    'zip',
    'dorm'
    ]),
    baseParams: {
        studentName: ''
    }
});
// studentDataArr.load();
var row = Ext.data.Record.create([
    'name',
    'studentID',
    'phone',
    'major',
    'street',
    'city',
    'state',
    'zip',
    'dorm'
    ]);

// Student Grid ------------------------------------------------
var studentGrid = new Ext.FormPanel({
    title: 'Job Entry',
    height: 300,
    width: 880,         // Hard code for MS IE browser
    activeTab: 0,
    frame: true,
    items: [{
        tbar:[{
        }, '-', {
            text: 'Delete Job',
            tooltip: 'Delete Job record',
            iconCls: 'remove',
            handler: function() {
                doDeleteStudent();
            }
        },'-',{
            text:'Save Edits',
            tooltip:'Save Job Edits to the Database',
            iconCls:'save',
            handler: function() {
                doUpdateStudents();
            }
        }],
        xtype: 'editorgrid',
        store: studentDataArr,
        id: 'studentGridID',
        height: 260,
        clicksToEdit: 1,
        stripeRows: true,
        selModel: new Ext.grid.RowSelectionModel(),
        columns: [
        {
            dataIndex: 'id',
            hidden: true
        },{
            header: "Job no",
            dataIndex: 'name',
            sortable: true,
            width: 130,
            editor: name_editor
        },{
            header: "Voy no",
            dataIndex: 'studentID',
            sortable: true,
            width: 80,
            editor: studentID_editor
        },{
            header: "Phone",
            dataIndex: 'phone',
            sortable: true,
            width: 110,
            editor: phone_editor
        },{
            header: "Vessel/Airline",
            dataIndex: 'major',
            sortable: true,
            width: 110,
            editor: major_editor
        },{
            header: "Create Date",
            dataIndex: 'street',
            sortable: true,
            editor: street_editor
        },{
            header: "File Closing Date",
            dataIndex: 'city',
            sortable: true,
            editor: city_editor
        },{
            header: "Agent",
            dataIndex: 'state',
            sortable: true,
            width: 60,
            renderer: 'uppercase', // Formats a text string with all uppercase letters
            editor: state_editor
        },{
            header: "Release",
            dataIndex: 'zip',
            sortable: true,
            width: 80,
            editor: zip_editor
        },{
            header: "POD",
            dataIndex: 'dorm',
            sortable: true,
            renderer: 'capitalize', // Formats a text string to have capitalization on first letter
            width: 60,
            editor: dormComboBox_editor
        }]
    }]
});

// Menu Functions --------------------------------------------------------------

function doDeleteStudent(){
    dh.overwrite( 'theMsgtext0', 'Menu: Delete Student...' );
    var grid = Ext.ComponentMgr.get('studentGridID');  // Get the id of the EditorGridPanel
    var sm = grid.getSelectionModel();
    var sel = sm.getSelected();
    if (!sm.hasSelection()){
        Ext.Msg.show({
            title: 'No Student Selected.',
            icon: Ext.MessageBox.INFO,
            buttons: Ext.MessageBox.OK,
            msg: 'Select Job Entry from the grid to be removed.',
            width: 325
        });
        dh.overwrite( 'theMsgtext0', 'No Job Selected.' );
        return;
    }
    dh.overwrite( 'theMsgtext0', 'Remove Job DB id: '+sel.data.id+", name: "+sel.data.name );
    Ext.Msg.show({
        title: 'Remove Job Entry',
        icon: Ext.MessageBox.QUESTION,
        buttons: Ext.MessageBox.YESNO,
        msg: 'Confirm removal of Job: '+sel.data.name+'?',
        fn: function(btn){
            if (btn == 'yes'){
                var conn = new Ext.data.Connection();
                conn.request({
                    // url: 'sampleData/success.json',
                    url: '/mvc6c/studentDelete',
                    params: {
                        delId: sel.data.id
                    },
                    success: function(resp,opt) {
                        grid.getStore().remove(sel);
                    },
                    failure: function(resp,opt) {
                        Ext.Msg.alert('Error', '*** Remove failed, could be someone else has already deleted it. Data has been refreshed.');
                    }
                });
            }
        }
    });
}

function doUpdateStudents(){
    dh.overwrite( 'theMsgtext0', 'Menu: Update: Save New and Edits' );
    var aGrid = Ext.ComponentMgr.get('studentGridID');
    var counter = 0;
    Ext.each( aGrid.getStore().getModifiedRecords(), function(record){
        counter++;
        // alert("dormInsert: counter = "+counter+": "+record.data.id+", "+record.data.name);
        studentUpdate(record);
    } );
    if (counter>0){
        aGrid.getStore().commitChanges();   // commit grid updates
        // dormDataArr.load();                // re-load the grid
    }
    dh.overwrite( 'theMsgtext0', 'Menu: Update: Save New and Edits, number of updates = '+counter );
}

function studentUpdate(record){
    dh.overwrite( 'theMsgtext0', 'Save Job data' );
    var conn = new Ext.data.Connection();
    conn.request({
        // url: 'sampleData/success.json',
        url: '/mvc6c/studentEdit',
        // http://localhost:8080/mvc5extUser/dormEdit?updateId:OK&updateId=BKK&dormType=WOMEN&dormCapacity=300
        params: {
            updateId: record.data.id,
            studentName:record.data.name ,
            studentId:record.data.studentID,
            phone:record.data.phone,
            major:record.data.major,
            street:record.data.street,
            city:record.data.city,
            state:record.data.state,
            zip:record.data.zip,
            dormName:record.data.dorm
        },
        success: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'Job Update, success: '+record.data.id );
        },
        failure: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'Job Update, failure: '+record.data.id );
        //dormDataArr.load();
        }
    });
}

// eof
