/*
 * Ext JS Library 2.0
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
var reader = new Ext.data.JsonReader();
var jstore = new Ext.data.GroupingStore({
    reader: reader,
    url: 'live_transactions.php?output=json',
    sortInfo: {
        field: 'status',
        direction: "ASC"
    },
    groupField: 'status',
});

var mftransactionsstore = new Ext.data.JsonStore({
    url: 'mftransactions_live.php',
});

var bookclosurestore = new Ext.data.JsonStore({
    url: 'fetchbookclosures_live.php',
});

var announcementstore = new Ext.data.JsonStore({
    url: 'fetchannouncements_live.php',
});

var myData = [];
// create the data store
var store = new Ext.data.SimpleStore({
    data: myData,
    fields: [{
        name: 'NAVBasis',
        type: 'float'
    }, {
        name: 'cashInHand',
        type: 'float'
    }, {
        name: 'lastLiveUpdate'
    }, {
        name: 'lastUpdate'
    }, {
        name: 'lastFuturesUpdate'
    }, {
        name: 'totalHoldVal'
    }, {
        name: 'totalCurrentVal'
    }, {
        name: 'NAV',
        type: 'float'
    }, {
        name: 'NAVHold',
        type: 'float'
    }, ]
});
var portfoliosStore = new Ext.data.JsonStore({
    url: 'userportfolioslookup.php',
    root: 'rows',
    fields: [{
        name: 'portfolio_name'
    }, {
        name: 'portfolio_display'
    }, {
        name: 'selected'
    }, ]
});
			
Ext.onReady(function(){

    Ext.QuickTips.init();
    
    var fundStore = new Ext.data.JsonStore({
        url: 'mfcombolookup_array.php',
        root: 'rows',
        fields: [{
            name: 'mfid'
        }, {
            name: 'fund_name'
        }, ]
    });
    var stockStore = new Ext.data.JsonStore({
        url: 'combolookup_array.php',
        root: 'rows',
        fields: [{
            name: 'id'
        }, {
            name: 'description'
        }, ]
    });
    var stockSeriesStore = new Ext.data.JsonStore({
        url: 'combolookupseries.php',
        root: 'rows',
        fields: [{
            name: 'expirydate'
        }]
    });
    
    var mfTtypestore = new Ext.data.SimpleStore({
        fields: ['type', 'val'],
        data: [['BUY', 'BUY'], ['SELL', 'SELL'], ['DIVIDENT', 'DIVIDENT']]
    });
    
    var stockTtypestore = new Ext.data.SimpleStore({
        fields: ['type', 'val'],
        data: [['BUY', 'BUY'], ['SELL', 'SELL'], ['DIVIDENT', 'DIVIDENT'], ['IPO', 'IPO'], ['BONUS', 'BONUS'], ['SPLIT', 'SPLIT']]
    });
    
    var tabs = new Ext.form.FormPanel({
        labelWidth: 45,
        border: false,
        width: 190,
        
        items: {
            xtype: 'tabpanel',
            activeTab: 0,
            defaults: {
                autoHeight: true,
                bodyStyle: 'padding:3px'
            },
            items: [{
                title: 'Stock',
                id: 'stock',
                layout: 'form',
                listeners: {
                    activate: {
                        fn: function(panel){
                            tabs.getForm().setValues({
                                action: "Insert Transaction"
                            })
                        }
                    }
                },
                defaults: {
                    width: 130
                },
                defaultType: 'textfield',
                
                items: [{
                    fieldLabel: 'Date',
                    name: 'stockDate',
                    xtype: 'datefield',
                    format: 'Y-m-d',
                }, {
                    store: stockStore,
                    name: 'ComboName1',
                    hiddenName: 'ComboName',
                    fieldLabel: 'Stock',
                    emptyText: 'Select a Stock...',
                    tpl: '<tpl for="."><div ext:qtip="{description}" class="x-combo-list-item">{description}</div></tpl>',
                    typeAhead: true,
                    triggerAction: 'all',
                    mode: 'remote',
                    queryParam: 'script',
                    displayField: 'description',
                    valueField: 'id',
                    xtype: 'combo',
                    forceSelection: true
                }, {
                    store: stockSeriesStore,
                    name: 'series',
                    fieldLabel: 'Series',
                    emptyText: 'Select a Series...',
                    tpl: '<tpl for="."><div ext:qtip="{expirydate}" class="x-combo-list-item">{expirydate}</div></tpl>',
                    typeAhead: true,
                    triggerAction: 'all',
                    mode: 'remote',
                    queryParam: 'script',
                    displayField: 'expirydate',
                    valueField: 'expirydate',
                    forceSelection: true,
                    xtype: 'combo',
                }, {
                    store: stockTtypestore,
                    name: 'ttype',
                    fieldLabel: 'Type',
                    typeAhead: true,
                    triggerAction: 'all',
                    forceSelection: true,
                    displayField: 'type',
                    valueField: 'val',
                    mode: 'local',
                    xtype: 'combo',
                }, {
                    fieldLabel: 'Quantity',
                    name: 'Quantity',
                    listeners: {
                        change: {
                            fn: calculateCommision
                        }
                    }
                }, {
                    fieldLabel: 'Price',
                    name: 'Price',
                    listeners: {
                        change: {
                            fn: calculateCommision
                        }
                    }
                }, {
                    fieldLabel: 'Value',
                    name: 'tradeval',
                    readOnly: true,
                }, {
                    fieldLabel: 'Comm%',
                    name: 'Commision',
                    listeners: {
                        change: {
                            fn: calculateCommision
                        }
                    }
                }, {
                    fieldLabel: 'Comm',
                    name: 'commval',
                    listeners: {
                        change: {
                            fn: calculateReverseCommision
                        }
                    }
                }, {
                    fieldLabel: 'STT%',
                    name: 'STT',
                    readOnly: true,
                }, {
                    fieldLabel: 'STT',
                    name: 'STTval',
                    listeners: {
                        change: {
                            fn: calculateSTT
                        }
                    }
                }, {
                    fieldLabel: 'Trade Val',
                    name: 'tval',
                    readOnly: true,
                }, {
                    fieldLabel: 'Notes',
                    name: 'formStockNotes',
                    xtype: 'textarea',
                }, {
                    xtype: 'hidden',
                    name: 'action',
                    value: 'Testing the field fund',
                }, ]
            }, {
                title: 'Mutual Fund',
                id: 'fund',
                layout: 'form',
                defaults: {
                    width: 130
                },
                listeners: {
                    activate: {
                        fn: function(panel){
                            tabs.getForm().setValues({
                                action: "Insert MF Transaction"
                            })
                        }
                    }
                },
                defaultType: 'textfield',
                layoutConfig: {
                    // layout-specific configs go here
                    labelSeparator: ':',
                },
                items: [{
                    fieldLabel: 'Date',
                    name: 'smfDate',
                    xtype: 'datefield',
                    format: 'Y-m-d',
                }, {
                    store: fundStore,
                    name: 'FundName1',
                    hiddenName: 'FundName',
                    fieldLabel: 'Fund',
                    emptyText: 'Select a Fund...',
                    tpl: '<tpl for="."><div ext:qtip="{fund_name}" class="x-combo-list-item">{fund_name}</div></tpl>',
                    typeAhead: true,
                    triggerAction: 'all',
                    mode: 'remote',
                    queryParam: 'script',
                    displayField: 'fund_name',
                    valueField: 'mfid',
                    forceSelection: true,
                    xtype: 'combo',
                }, {
                    store: mfTtypestore,
                    name: 'mfttype',
                    fieldLabel: 'Type',
                    typeAhead: true,
                    triggerAction: 'all',
                    forceSelection: true,
                    displayField: 'type',
                    valueField: 'val',
                    mode: 'local',
                    xtype: 'combo',
                    listeners: {
                        change: {
                            fn: lookupMFPrice
                        }
                    }
                }, {
                    fieldLabel: 'Quantity',
                    name: 'mfQuantity',
                    listeners: {
                        change: {
                            fn: calculatemfValue
                        }
                    }
                }, {
                    fieldLabel: 'Price',
                    name: 'mfPrice',
                }, {
                    fieldLabel: 'Trade Val',
                    name: 'mftval',
                    listeners: {
                        change: {
                            fn: calculatemfQuantity
                        }
                    }
                }, {
                    fieldLabel: 'Notes',
                    name: 'mfNotes',
                    xtype: 'textarea',
                }, ]
            }]
        },
        
        buttons: [{
            text: 'Save',
            handler: function(){
                tabs.getForm().submit({
                    url: 'transaction_add.php',
                    waitMsg: 'Inserting Transaction ...',
                    success: function(){
                        jstore.reload();
                        mftransactionsstore.reload();
                        bookclosurestore.reload();
                        announcementstore.reload();
                    }
                });
            }
        }, {
            text: 'Cancel'
        }]
    });
    tabs.render('transactionFormDiv');
    tabs.getForm().setValues({
        STT: sttRate,
        Commision: portfolioCommission
    });
    
    var convertedPortfolio = new Ext.form.ComboBox({
        name: 'Portfolio1',
        hiddenName: 'Portfolio',
        store: portfoliosStore,
        tpl: '<tpl for="."><div ext:qtip="{portfolio_display}" class="x-combo-list-item">{portfolio_display}</div></tpl>',
        triggerAction: 'all',
        typeAhead: true,
        triggerAction: 'all',
        mode: 'remote',
        displayField: 'portfolio_display',
        valueField: 'portfolio_name',
        xtype: 'combo',
        forceSelection: true
    });
    
    var portfolioForm = new Ext.form.FormPanel({
        labelWidth: 1,
        border: false,
        defaults: {
            autoHeight: true,
            bodyStyle: 'padding:3px',
        },
        layoutConfig: {
            // layout-specific configs go here
            labelSeparator: '',
        },
        width: 190,
        
        items: [convertedPortfolio, {
            xtype: 'hidden',
            name: 'action',
            value: 'Switch Portfolio',
        }, ],
        buttons: [{
            text: 'Switch',
            handler: function(){
                portfolioForm.getForm().submit({
                    url: 'transaction_add.php',
                    waitMsg: 'Switching ...',
                    success: function(){
                        jstore.reload();
                        mftransactionsstore.reload();
                        bookclosurestore.reload();
                        announcementstore.reload();
                    }
                });
            }
        }]
    });
    portfolioForm.render('portfolioSwitchDiv');
    
    
    var xg = Ext.grid;
    
    // create the Grid
    var statusGrid = new Ext.grid.GridPanel({
        store: store,
        columns: [{
            header: "NAV",
            width: 35,
            sortable: true,
            dataIndex: 'NAV',
            renderer: renderNAV
        }, {
            header: "NAV on Hold",
            width: 35,
            sortable: true,
            dataIndex: 'NAVHold',
            renderer: renderNAV
        }, {
            header: "NAV Basis",
            width: 35,
            sortable: true,
            dataIndex: 'NAVBasis',
            renderer: round2
        }, {
            header: "Cash In Hand",
            width: 35,
            sortable: true,
            dataIndex: 'cashInHand',
            renderer: round2
        }, {
            header: "Last Updated",
            width: 35,
            sortable: true,
            dataIndex: 'lastUpdate'
        }, {
            header: "Last Futures Updated",
            width: 35,
            sortable: true,
            dataIndex: 'lastFuturesUpdate'
        }, {
            header: "Total Hold Val",
            width: 25,
            sortable: true,
            dataIndex: 'totalHoldVal',
            renderer: round2
        }, {
            header: "Last Live Update",
            width: 35,
            sortable: true,
            dataIndex: 'lastLiveUpdate'
        }, {
            header: "Net Returns",
            width: 25,
            sortable: true,
            dataIndex: 'totalCurrentVal',
            renderer: round2
        }, ],
        frame: true,
        footer: true,
        animCollapse: true,
        autoHeight: true,
        viewConfig: {
            forceFit: true
        },
        title: 'Summary'
    });
    
    var grid = new xg.GridPanel({
        store: jstore,
        
        columns: [{
            id: 'description',
            header: "Name",
            width: 60,
            sortable: true,
            dataIndex: 'description',
            renderer: displayStock
        }, {
            header: "Held",
            width: 20,
            sortable: true,
            dataIndex: 'held',
            renderer: round2
        }, {
            header: "U/Hold Val",
            width: 20,
            sortable: true,
            dataIndex: 'avg_buy_price',
            renderer: round2
        }, {
            header: "Hold Val",
            width: 20,
            sortable: true,
            dataIndex: 'current_hold_val',
            renderer: round2
        }, {
            header: "Returns",
            width: 20,
            sortable: true,
            dataIndex: 'returns',
            renderer: round2
        }, {
            header: "Comm",
            width: 15,
            sortable: true,
            dataIndex: 'commisions',
            renderer: round2
        }, {
            header: "Last Price",
            width: 25,
            sortable: true,
            dataIndex: 'last_close',
            renderer: change
        }, {
            header: "Current",
            width: 20,
            sortable: true,
            dataIndex: 'current_val',
            renderer: round2
        }, {
            header: "Ret%",
            width: 20,
            sortable: true,
            dataIndex: 'returns_pct',
            renderer: pctChange
        }, {
            header: "Current Returns",
            width: 20,
            sortable: true,
            dataIndex: 'returns',
            renderer: calcReturns
        }, {
            header: "Status",
            width: 20,
            sortable: true,
            hidden: true,
            dataIndex: 'status'
        }],
        
        view: new Ext.grid.GroupingView({
            forceFit: true,
            showGroupName: false,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        }),
        
        listeners: {
            cellclick: {
                fn: editStockDetails
            },
        },
        tools: [{
            id: 'refresh'
        }, {
            id: 'toggle'
        }],
        frame: true,
        footer: true,
        animCollapse: true,
        autoHeight: true,
        width: 1180,
        //autoWidth: true,
        title: 'Holdings',
        items: statusGrid,
        iconCls: 'icon-grid'
    });
    
    jstore.on('datachanged', dataChanged);
    
    // create the MF transaction Grid
    var mftransactiongrid = new Ext.grid.GridPanel({
        store: mftransactionsstore,
        columns: [{
            id: 'fund_name',
            header: "Fund",
            width: 160,
            sortable: true,
            dataIndex: 'fund_name'
        }, {
            header: "Units Held",
            width: 75,
            sortable: true,
            renderer: round3,
            dataIndex: 'held'
        }, {
            header: "Invested",
            width: 75,
            sortable: true,
            renderer: round2,
            dataIndex: 'total_invested'
        }, {
            header: "U/Hold Val",
            width: 75,
            sortable: true,
            renderer: round3,
            dataIndex: 'avg_buy_price'
        }, {
            header: "Last NAV Date",
            width: 85,
            sortable: true,
            dataIndex: 'last_nav_date'
        }, {
            header: "Last NAV",
            width: 85,
            sortable: true,
            renderer: pctChangeFund,
            dataIndex: 'last_nav'
        }, {
            header: "Current",
            width: 85,
            sortable: true,
            renderer: round3,
            dataIndex: 'current_val'
        }, {
            header: "Ret%",
            width: 85,
            sortable: true,
            renderer: round3,
            dataIndex: 'return_percent'
        }, {
            header: "Returns",
            width: 85,
            sortable: true,
            renderer: round3,
            dataIndex: 'returns_now'
        }, ],
        stripeRows: true,
        viewConfig: {
            forceFit: true
        },
        listeners: {
          cellclick: {
            fn: editFundDetails
          },
        },
        frame: true,
        footer: true,
        animCollapse: true,
        autoHeight: true,
        width: 1180,
        //autoWidth: true,
        collapsible: true,
        title: 'Mutual Fund Holdings'
    });
    
    // create the book closure grid
    var bookclosuregrid = new Ext.grid.GridPanel({
        store: bookclosurestore,
        columns: [{
            id: 'bcid',
            header: "Fund",
            sortable: true,
            dataIndex: 'bcid',
            hidden: true
        }, {
            header: "Company",
            width: 75,
            sortable: true,
            dataIndex: 'description'
        }, {
            header: "Purpose",
            width: 150,
            sortable: true,
            dataIndex: 'purpose'
        }, {
            header: "Record Date",
            width: 35,
            sortable: true,
            dataIndex: 'record_date'
        }, {
            header: "BC Start",
            width: 35,
            sortable: true,
            dataIndex: 'bc_start_date'
        }, {
            header: "BC End",
            width: 35,
            sortable: true,
            dataIndex: 'bc_end_date'
        }, {
            header: "EX Date",
            width: 35,
            sortable: true,
            dataIndex: 'ex_date'
        }, {
            header: "ND Start",
            width: 35,
            sortable: true,
            dataIndex: 'nd_start_date'
        }, {
            header: "ND End",
            width: 35,
            sortable: true,
            dataIndex: 'nd_end_date'
        }, ],
        stripeRows: true,
        viewConfig: {
            forceFit: true
        },
        frame: true,
        footer: true,
        animCollapse: true,
        autoHeight: true,
        width: 1180,
        //autoWidth: true,
        collapsible: true,
        title: 'Book Closures'
    });
    
    // create the announcement grid
    var expander = new Ext.grid.RowExpander({
        tpl: new Ext.Template('<p><b>Company:</b> {description}<br>', '<p><b>Announcement:</b> {announcement}</p>')
    });
    var announcementgrid = new Ext.grid.GridPanel({
        store: announcementstore,
        columns: [
        expander, 
        {
            id: 'announceid',
            header: "Fund",
            sortable: true,
            dataIndex: 'announceid',
            hidden: true
        }, {
            header: "Company",
            width: 40,
            sortable: true,
            dataIndex: 'description'
        }, {
            header: "Announcement",
            width: 150,
            sortable: false,
            dataIndex: 'short_announce'
        }, {
            header: "Announce Date",
            width: 25,
            sortable: true,
            dataIndex: 'announce_date'
        }, ],
        stripeRows: true,
        viewConfig: {
            forceFit: true
        },
        frame: true,
        footer: true,
        animCollapse: true,
        autoHeight: true,
        width: 1180,
        //autoWidth: true,
        plugins: expander,
        collapsible: true,
        title: 'Company Announcements'
    });
    
    if (Ext.get('held_stocks_profile') != null) {
        portfoliosStore.load({
            callback: function(){
                showDefaultPortfolio(convertedPortfolio);
            }
        });
        grid.render('held_stocks_profile');
        timedCount();
        mftransactionsstore.load({
            callback: function(){
                mftransactiongrid.render('mutual_funds_profile');
            }
        });
        bookclosurestore.load({
            callback: function(){
                bookclosuregrid.render('book_closures_tab');
            }
        });
        announcementstore.load({
            callback: function(){
                announcementgrid.render('announcements_tab');
            }
        });
    }
});

Ext.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if (!this.id) {
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype = {
    init: function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },
    
    onMouseDown: function(e, t){
        if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
        }
    },
    
    renderer: function(v, p, record){
        p.css += ' x-grid3-check-col-td';
        return '<div class="x-grid3-check-col' + (v ? '-on' : '') + ' x-grid3-cc-' + this.id + '">&#160;</div>';
    }
};
// example of custom renderer function
function change(val, metadata, record, row, col, store){
    var background_colour = "";
    if (record.data.live_price) {
        background_colour = 'font-family: courier, fixed;font-weight: bolder;font-style: italic; font-size: small;';
    }
    else {
        background_colour = 'font-size: xx-small;';
    }
    if (record.data.last_pct_change > 0) {
        return '<span style="color:green; text-align:left; ' + background_colour +
        '" >' +
        val +
        ' <img src="images/up.gif" />' +
        Math.abs(round2(record.data.last_pct_change)) +
        '</span>';
    }
    else 
        if (record.data.last_pct_change < 0) {
            return '<span style="color:red; text-align:left; ' + background_colour +
            '" >' +
            val +
            ' <img src="images/down.gif" />' +
            Math.abs(round2(record.data.last_pct_change)) +
            '</span>';
        }
    return val;
}

function pctChange(val, metadata, record, row, col, store){
    if (val > 0) {
        return '<span style="color:green;text-align:left; font-family: courier, fixed;">' + Math.abs(val) + '%</span>';
    }
    else 
        if (val < 0) {
            return '<span style="color:red;text-align:left; font-family: courier, fixed;">' + Math.abs(val) + '%</span>';
        }
    return val;
}

function pctChangeFund(val, metadata, record, row, col, store){
    var change = (record.data.last_nav - record.data.last_nav_compare) / record.data.last_nav_compare * 100;
    if (change > 0) {
        return '<span style="color:green;text-align:left; font-family: courier, fixed;">' + val + ' <img src="images/up.gif" />' +
        Math.abs(round2(change)) +
        '%</span>';
    }
    else 
        if (change < 0) {
            return '<span style="color:red;text-align:left; font-family: courier, fixed;">' + val + ' <img src="images/down.gif" />' +
            Math.abs(round2(change)) +
            '%</span>';
        }
    return val;
}

function simpleChange(val, metadata, record, row, col, store){
    if (val > 0) {
        return '<span style="color:green;text-align:left;">' + Math.abs(val) + '</span>';
    }
    else 
        if (val < 0) {
            return '<span style="color:red;text-align:left;">' + Math.abs(val) + '</span>';
        }
    return val;
}

function renderNAV(value, metadata, record, row, col, store){
    return '<span style="font-weight: bolder;font-style: italic; font-size: small; text-align:left;">' + round3(value) + '</span>';
}

function displayStock(value, metadata, record, row, col, store){
    return '<a href="' + record.data.analysis_url + '">' + value + '</a>';
}

function round2(value, metadata, record, row, col, store){
    return roundNumber(value, 2);
}

function round3(value, metadata, record, row, col, store){
    return roundNumber(value, 3);
}

function roundNumber(num, dec){
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function calcReturns(value, metadata, record, row, col, store){
    return simpleChange(roundNumber((record.data.current_val - record.data.current_hold_val), 2));
}

function timedCount(){
    t = setTimeout("timedCount()", 30000);
    jstore.reload();
}

function dataChanged(view){
    var meta = reader.meta;
    myData = [];
    var dataObj = [];
    dataObj.push(meta.NAVBasis);
    dataObj.push(meta.cashHeld);
    dataObj.push(meta.lastLiveUpdate);
    dataObj.push(meta.lastDate);
    dataObj.push(meta.lastFuturesDate);
    dataObj.push((meta.totalCurrentVal + meta.cashHeld));
    dataObj.push((meta.totalCurrentVal + meta.cashHeld - meta.totalHoldVal));
    dataObj.push(((meta.totalCurrentVal + meta.cashHeld) * 10 / meta.NAVBasis));
    dataObj.push(((meta.totalCurrentVal + meta.cashHeld) * 10 / meta.totalHoldVal));
    myData.push(dataObj);
    store.loadData(myData);
}

function calculateCommision(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    newvalues.tradeval = values.Quantity * values.Price;
    newvalues.commval = values.Quantity * values.Price * values.Commision;
    newvalues.STTval = values.Quantity * values.Price * values.STT;
    calculateTradeVal(values, newvalues);
    form.setValues(newvalues);
}

function calculateReverseCommision(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    newvalues.tradeval = values.tradeval;
    newvalues.commval = values.commval;
    newvalues.STTval = values.STTval;
    if (values.commval != 0) {
        newvalues.Commision = values.commval / (values.Quantity * values.Price);
        calculateTradeVal(values, newvalues);
        form.setValues(newvalues);
    }
}

function calculateSTT(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    newvalues.tradeval = values.tradeval;
    newvalues.commval = values.commval;
    newvalues.STTval = values.STTval;
    newvalues.STT = values.STTval / (values.Quantity * values.Price);
    calculateTradeVal(values, newvalues);
    form.setValues(newvalues);
}

function calculateTradeVal(values, newvalues){
    if (values.ttype == 'SELL') {
        var result = 0;
        result += parseFloat(newvalues.tradeval);
        result -= parseFloat(newvalues.commval);
        result -= parseFloat(newvalues.STTval);
        newvalues.tval = result;
    }
    else {
        var result = 0;
        result += parseFloat(newvalues.tradeval);
        result += parseFloat(newvalues.commval);
        result += parseFloat(newvalues.STTval);
        newvalues.tval = result;
    }
}

function calculatemfValue(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    newvalues.mftval = Math.round(values.mfPrice * values.mfQuantity * 10000) / 10000;
    form.setValues(newvalues);
}

function calculatemfQuantity(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    newvalues.mfQuantity = Math.round((values.mftval / values.mfPrice) * 10000) / 10000;
    form.setValues(newvalues);
}

function lookupMFPrice(field, newVal, oldVal){
    var form = field.ownerCt.ownerCt.ownerCt.getForm();
    var values = form.getValues();
    var newvalues = {};
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "mfpricelookup.php?mfid=" + values.FundName + "&tdate=" + values.smfDate, true);
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4) {
            var retarray = eval('(' + xmlhttp.responseText + ')');
            if (retarray.length == 1) {
                if (values.mfttype == 'BUY') 
                    newvalues.mfPrice = retarray[0][2];
                else 
                    if (values.mfttype == 'SELL') 
                        newvalues.mfPrice = retarray[0][1];
                    else 
                        newvalues.mfPrice = retarray[0][0];
            }
            else {
                newvalues.mfPrice = "No quote for data";
            }
            form.setValues(newvalues);
        }
    }
    xmlhttp.send(null);
}

function showDefaultPortfolio(combo){
    var number = portfoliosStore.find('selected', 'Y');
    var record = portfoliosStore.getAt(number);
    combo.setValue(record.data.portfolio_name);
}


function showLiveGraph(thisGrid, rowIndex, e){
  //var elem = Ext.get('indexDisplayLayer');
  //elem.dom.innerHTML = "<img border=0 src='http://ichart.yahoo.com/w?s="+thisGrid.store.data.items[rowIndex].data.yahoo_url+"' />";
  //elem.dom.style.top = window.pageYOffset +10 + "px";
  //elem.slideIn('l').pause(5).ghost('l');
  var tabs = new Ext.TabPanel({
      activeTab: 0,
      height: 320,
      plain: true,
      tabPosition: 'bottom',
      items: [{
          title: 'Day',
          html: "<img border=0 src='http://ichart.finance.yahoo.com/b?s="+thisGrid.store.data.items[rowIndex].data.yahoo_url.toLowerCase()+"' />"
      },{
          title: 'Week',
          html: "<object  data='inline_image_nse_svg.php?xs=518&ys=320&graph_type=PriceCandle&Bollinger=NONE&LinearScale=&minimal=1&tp=week&symbol="+thisGrid.store.data.items[rowIndex].data.id+"' type='image/svg+xml' style='width:520px; height: 320px;'/>"
      },{
          title: 'Month',
          html: "<object  data='inline_image_nse_svg.php?xs=518&ys=320&graph_type=PriceCandle&Bollinger=NONE&LinearScale=&minimal=1&tp=month&symbol="+thisGrid.store.data.items[rowIndex].data.id+"' type='image/svg+xml' style='width:520px; height: 320px;'/>"
      },{
          title: 'Year',
          html: "<object  data='inline_image_nse_svg.php?xs=518&ys=320&graph_type=PriceOHLC&Bollinger=NONE&LinearScale=&minimal=1&tp=year&Group=WEEK&symbol="+thisGrid.store.data.items[rowIndex].data.id+"' type='image/svg+xml' style='width:520px; height: 320px;'/>"
      }]
  });
  var win = new Ext.Window({
  layout: 'fit',
  closeAction: 'hide',
  plain: false,
  width: 525,
  title: thisGrid.store.data.items[rowIndex].data.description,
  
  items: tabs,
  
  buttons: [{
          text: 'Close',
          handler: function(){
          win.close();
          }
  }]
  });
  win.show(thisGrid);
}

function editStockDetails(thisGrid, rowIndex, cellIndex, e){
  if (cellIndex == 6) {
    showLiveGraph(thisGrid, rowIndex, cellIndex, e);
  } else {
    var transactStore = new Ext.data.JsonStore({
        url: 'transaction_detail_live.php',
        baseParams: {
            symbol: thisGrid.store.data.items[rowIndex].data.id,
            series: thisGrid.store.data.items[rowIndex].data.contract_expiry,
        },
    });
    
    var checkColumn = new Ext.grid.CheckColumn({
        header: "Show",
        dataIndex: 'show_in_portfolio',
        width: 25,
        editor: new Ext.form.Checkbox({}),
    });
    var cm = new Ext.grid.ColumnModel([{
        id: 'tid',
        header: "TransactionID",
        sortable: true,
        dataIndex: 'tid',
        hidden: true
    }, {
        header: "Series",
        width: 45,
        sortable: true,
        dataIndex: 'contract_expiry',
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        editor: new Ext.form.DateField({
            format: 'Y-m-d',
        })
    }, {
        header: "Type",
        width: 40,
        sortable: true,
        dataIndex: 'ttype',
        editor: new Ext.form.ComboBox({
            typeAhead: true,
            triggerAction: 'all',
            store: new Ext.data.SimpleStore({
                fields: ['type', 'val'],
                data: [['BUY', 'BUY'], ['SELL', 'SELL'], ['DIVIDENT', 'DIVIDENT'], ['IPO', 'IPO'], ['BONUS', 'BONUS'], ['SPLIT', 'SPLIT']]
            }),
            lazyRender: true,
            mode: 'local',
            displayField: 'type',
            valueField: 'val',
            listClass: 'x-combo-list-small'
        })
    }, {
        header: "Date",
        width: 50,
        sortable: true,
        dataIndex: 'tdate',
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        editor: new Ext.form.DateField({
            format: 'Y-m-d',
        })
    }, {
        header: "Price",
        width: 50,
        sortable: true,
        dataIndex: 'tprice',
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
        header: "Commision",
        width: 55,
        sortable: true,
        dataIndex: 'commisions',
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
        header: "Quantity",
        width: 35,
        sortable: true,
        dataIndex: 'quantity',
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
        header: "STT",
        width: 35,
        sortable: true,
        dataIndex: 'sec_transact_tax',
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, checkColumn, {
        header: "Margin",
        width: 35,
        sortable: true,
        dataIndex: 'margin',
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
      header: "Total Val",
      width: 45,
      sortable: true,
      dataIndex: 'tval',
    },]);
    var eform = new Ext.grid.EditorGridPanel({
        store: transactStore,
        height: 250,
        autoWidth: true,
        cm: cm,
        stripeRows: true,
        viewConfig: {
            forceFit: true
        },
        plugins: checkColumn,
        frame: false,
        autoScroll: true,
        collapsible: false,
        clicksToEdit: 1,
    });
    
    var win = new Ext.Window({
        layout: 'fit',
        closeAction: 'hide',
        plain: false,
        width: 700,
        title: thisGrid.store.data.items[rowIndex].data.description,
        items: eform,
        buttons: [{
            text: 'Submit',
            handler: function(){
/*              alert("Submitting");
                eform.getForm().submit({
                    url: 'null.php',
                    waitMsg: 'Submitting ...',
                    success: function(){
                    }
                });*/
              var modifiedData=[];
              for (var i=0; i < transactStore.modified.length; i++) {
                var modifiedDataObj = {};
                modifiedDataObj['id'] = transactStore.modified[i].data.tid;
                for (var j in transactStore.modified[i].modified) {
                  modifiedDataObj[j] = transactStore.modified[i].data[j];
                }
                var tradeval = transactStore.modified[i].data['tprice']
                    * transactStore.modified[i].data['quantity']
                    * transactStore.modified[i].data['margin'] / 100;
                var sttval = tradeval * transactStore.modified[i].data['sec_transact_tax'];
                var tradecomm = tradeval * transactStore.modified[i].data['commisions'];
                var tval = 0;
                if (transactStore.modified[i].data['ttype'] == 'SELL')
                {
                  tval = tradeval - sttval - tradecomm;
                }
                else
                {
                  tval = -1 * (tradeval + sttval + tradecomm);
                }
                modifiedDataObj['valchange'] = tval - transactStore.modified[i].data.tval;
                modifiedData.push(modifiedDataObj);
              }
              Ext.Ajax.request({
                url: '/quotes/edit_transactions_live.php',
                method: 'POST',
                jsonData: modifiedData,
                success: function() {
                  transactStore.reload();
                  jstore.reload();
                }
              });
            }
        },{
            text: 'Close',
            handler: function(){
                win.close();
            }
        }]
    });
    transactStore.load({
        callback: function(){
            win.show(thisGrid);
        }
    });
  }
}

function editFundDetails(thisGrid, rowIndex, cellIndex, e){
    var transactStore = new Ext.data.JsonStore({
      url: 'transaction_detail_live_fund.php',
      baseParams: {
        symbol: thisGrid.store.data.items[rowIndex].data.mfid,
      },
    });
    
    var checkColumn = new Ext.grid.CheckColumn({
      header: "Show",
      dataIndex: 'show_in_portfolio',
      width: 25,
      editor: new Ext.form.Checkbox({}),
    });
    var cm = new Ext.grid.ColumnModel([{
      id: 'mftid',
      header: "TransactionID",
      sortable: true,
      dataIndex: 'mftid',
      hidden: true
    }, {
      header: "Type",
      width: 40,
      sortable: true,
      dataIndex: 'ttype',
      editor: new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        store: new Ext.data.SimpleStore({
          fields: ['type', 'val'],
          data: [['BUY', 'BUY'], ['SELL', 'SELL'], ['DIVIDENT', 'DIVIDENT']]
        }),
        lazyRender: true,
        mode: 'local',
        displayField: 'type',
        valueField: 'val',
        listClass: 'x-combo-list-small'
      })
    }, {
      header: "Date",
      width: 50,
      sortable: true,
      dataIndex: 'tdate',
      renderer: Ext.util.Format.dateRenderer('Y-m-d'),
      editor: new Ext.form.DateField({
        format: 'Y-m-d',
      })
    }, {
      header: "Price",
      width: 50,
      sortable: true,
      dataIndex: 'tprice',
      editor: new Ext.form.TextField({
        allowBlank: false
      })
    }, {
      header: "Units",
      width: 35,
      sortable: true,
      dataIndex: 'units',
      editor: new Ext.form.TextField({
        allowBlank: false
      })
    }, checkColumn, {
      header: "Total Val",
      width: 45,
      sortable: true,
      dataIndex: 'tval',
    },]);
    var eform = new Ext.grid.EditorGridPanel({
      store: transactStore,
      height: 250,
      autoWidth: true,
      cm: cm,
      stripeRows: true,
      viewConfig: {
        forceFit: true
      },
      plugins: checkColumn,
      frame: false,
      autoScroll: true,
      collapsible: false,
      clicksToEdit: 1,
    });
    
    var win = new Ext.Window({
      layout: 'fit',
      closeAction: 'hide',
      plain: false,
      width: 700,
      title: thisGrid.store.data.items[rowIndex].data.fund_name,
      items: eform,
      buttons: [{
        text: 'Submit',
        handler: function(){
/*              alert("Submitting");
          eform.getForm().submit({
          url: 'null.php',
          waitMsg: 'Submitting ...',
          success: function(){
        }
        });*/
          var modifiedData=[];
          for (var i=0; i < transactStore.modified.length; i++) {
            var modifiedDataObj = {};
            modifiedDataObj['id'] = transactStore.modified[i].data.mftid;
            for (var j in transactStore.modified[i].modified) {
              modifiedDataObj[j] = transactStore.modified[i].data[j];
            }
            var tradeval = transactStore.modified[i].data['tprice']
                * transactStore.modified[i].data['units'];
            var tval = 0;
            if (transactStore.modified[i].data['ttype'] == 'SELL')
            {
              tval = +1 * tradeval;
            }
            else
            {
              tval = -1 * tradeval;
            }
            modifiedDataObj['valchange'] = tval - transactStore.modified[i].data.tval;
            modifiedData.push(modifiedDataObj);
          }
          Ext.Ajax.request({
            url: '/quotes/edit_transactions_fund_live.php',
            method: 'POST',
            jsonData: modifiedData,
            success: function() {
              transactStore.reload();
              mftransactionsstore.reload();
            }
          });
        }
      },{
        text: 'Close',
        handler: function(){
          win.close();
        }
      }]
    });
    transactStore.load({
      callback: function(){
        win.show(thisGrid);
      }
    });
}

