/*!
 * Ext JS Library 3.1.1
 * Copyright(c) 2006-2010 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
// Application instance for showing user-feedback messages.
var App = new Ext.App({});

// Create HttpProxy instance.  Notice new configuration parameter "api" here instead of load.  However, you can still use
// the "url" paramater -- All CRUD requests will be directed to your single url instead.
//var proxy = new Ext.data.HttpProxy({ url: 'http://localhost:4992/ExtJs_HttpProxy.aspx?f=view', method: 'GET' });
var proxy = new Ext.data.HttpProxy({ url: 'http://www.alisotech.com/extjs_json_linq/usgs_earthquakes.aspx', method: 'GET' });

// Typical JsonReader.  Notice additional meta-data params for defining the core attributes of your json-response
var reader = new Ext.data.JsonReader({
    idProperty: 'EQ_ID',
    totalProperty: 'totalCount',
    root: 'data'
}, [
    { name: 'EQ_ID', type: 'integer' },
    { name: 'EQ_Richter', type: 'integer', allowBlank: false },
    { name: 'EQ_Date', type: 'date', allowBlank: false, dateFormat: 'M$' },
    { name: 'EQ_Location', type: 'string', allowBlank: false },
    { name: 'EQ_Link', type: 'string', allowBlank: false } 
]);

// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
    encode: true,
    writeAllFields: false
});

// Typical Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.Store({
    id: 'EQ_ID',
    proxy: proxy,
    reader: reader,
    writer: writer,  // <-- plug a DataWriter into the store just as you would a Reader
    autoSave: true, // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
    remoteSort: true,    
    paramNames: {
        start: 'start',
        limit: 'limit',
        sort: 'sort',
        dir: 'dir'
    }
});

store.on('load', function() { Load_Logs(); });
store.on('update', function() { Load_Logs(); });
store.on('add', function() { Load_Logs(); });
store.on('remove', function() { Load_Logs(); });


// load the store immeditately
store.setDefaultSort('EQ_ID', 'DESC');
store.load();

////
// ***New*** centralized listening of DataProxy events "beforewrite", "write" and "writeexception"
// upon Ext.data.DataProxy class.  This is handy for centralizing user-feedback messaging into one place rather than
// attaching listenrs to EACH Store.
//
// Listen to all DataProxy beforewrite events
//
//Ext.data.DataProxy.addListener('beforewrite', function(proxy, action) {
//    App.setAlert(App.STATUS_NOTICE, "Before " + action);
//});

////
// all write events
//
//Ext.data.DataProxy.addListener('write', function(proxy, action, result, res, rs) {
//    App.setAlert(true, action + ':' + res.message);
//});

Ext.data.DataProxy.addListener('read', function(proxy, action, result, res, rs) {
    App.setAlert(true, action + ':' + res.message);
});

////
// all exception events
//
Ext.data.DataProxy.addListener('exception', function(proxy, type, action, options, res) {
    if (type === 'remote') {
        Ext.Msg.show({
            title: 'REMOTE EXCEPTION',
            msg: res.message,
            icon: Ext.MessageBox.ERROR,
            buttons: Ext.Msg.OK
        });
    }
});


function setBigEarthquake(val) {
    if (val > 5) {
        return '<span style="color:red;">' + val + '</span>';
    } else if (val <= 5) {
        return '<span style="color:green;">' + val + '</span>';
    }
    return val;
}

function setLink(val) {

    val = "<a href=\"" + val + "\" target=\"_blank\">More Details</a>";

    return val;
}

// A new generic text field
var textField = new Ext.form.TextField();
var fm = Ext.form;


    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel({
        // specify any defaults for each column
        defaults: {
            sortable: true // columns are sortable by default           
        },
        columns: [
            {
                id: 'EQ_ID',
                header: 'ID',
                dataIndex: 'EQ_ID',
                width: 30,
                // use shorthand alias defined above
                editor: new fm.TextField({
                    allowBlank: false
                })
            }, {
                header: 'Richter',
                dataIndex: 'EQ_Richter',
                width: 50,
                align: 'right',
                renderer: setBigEarthquake,
                editor: new fm.NumberField({
                    allowBlank: false
                })
            }, {
                header: 'Date',
                dataIndex: 'EQ_Date',
                width: 230,
                align: 'left',
                renderer: Ext.util.Format.dateRenderer('F j, Y, g:i:s A T'),                
                editor: new fm.DateField({
                    allowBlank: false
                })
            }, {
                header: 'Location',
                dataIndex: 'EQ_Location',
                width: 250,
                editor: new fm.TextField({
                    allowBlank: false
                })
            },  {
                header: 'Link',
                dataIndex: 'EQ_Link',
                width: 80,
                renderer: setLink, 
                sortable: false,               
                editor: new fm.TextField({
                    allowBlank: false
                })
            }
        ]
    });

Ext.onReady(function() {
    Ext.QuickTips.init();

    // create user.Form instance (@see UserForm.js)
    var userForm = new App.user.Form({
        renderTo: 'user-form',
        listeners: {
            create : function(fpanel, data) {   // <-- custom "create" event defined in App.user.Form class
                var rec = new userGrid.store.recordType(data);
                userGrid.store.insert(0, rec);
            }
        }
    });

    // create user.Grid instance (@see UserGrid.js)
    var userGrid = new App.user.Grid({
        renderTo: 'user-grid',
        store: store,
        cm: cm,
        listeners: {
            rowclick: function(g, index, ev) {
                var rec = g.store.getAt(index);
                userForm.loadRecord(rec);
            },
            destroy : function() {
                userForm.getForm().reset();
            }
        }
    });

    var winForm = new Ext.Window({
        title: 'Earthquake Form',
        x: 750,
        y: 150,        
        width: 400,
        height: 320,
        minWidth: 300,
        minHeight: 100,
        layout: 'fit',
        plain: true,
        collapsible: true,
        maximizable: true,        
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        items: userForm
    });

    var winGrid = new Ext.Window({
        title: 'USGS - Earthquakes',
        x: 20,
        y: 150,
        width: 700,
        height: 430,
        minWidth: 300,
        minHeight: 200,
        layout: 'fit',
        plain: true,
        collapsible: true,
        maximizable: true,        
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        items: userGrid
    });

    winForm.show();
    winGrid.show();    
    
});
