Ext.BLANK_IMAGE_URL = 'Includes/Images/ext-2.2.1/themes/default/s.gif';
Ext.namespace('Itransition.RightWayTrader.RightWayTraderData');
var categoriesHandlerUrl = 'Handlers/Categories.ashx';
var groupsHandlerUrl = 'Handlers/Groups.ashx';
var sectorsHandlerUrl = 'Handlers/Sectors.ashx';
var symbolsHandlerUrl = 'Handlers/SearchSymbols.ashx';
var optionsHandlerUrl = 'Handlers/Options.ashx';
var symbolsLimit = 30;
var categoryId = 0;
var comparisonType = 'match';
var searchText = '';
var searchIn = 'symbol';
var exchangeSearchIn = 'category';
var special = 'all';
var optionsSearchIn = 'option';
var minStrikePrice = 0;
var maxStrikePrice = 0;
var expirationYear = 0;
var expirationMonth = 0;
var inPut = false;
var inCall = false;
var menu = {};

Ext.onReady(function() {
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();

    var symbolsGrid;

    menu.Update = function(nodes) {
        menuToolbar.items.each(function(item) {
            item.destroy();
        });

        var nitem = new Ext.Toolbar.Button({
            text: '',
            id: '-1-btnC'
        });

        menuToolbar.addItem(nitem);

        for (var nodeIndex = 0; nodeIndex < nodes.length; nodeIndex++) {
            var node = nodes[nodeIndex];

            var item = new Ext.Toolbar.Button({
                text: node.name,
                iconCls: 'alist',
                id: node.id + '-btnC',
                handler: function(btn) {
                    categoryId = btn.id.substring(0, btn.id.lastIndexOf('-'));
                    categoriesTab.getActiveTab().fireEvent('click', categoriesTab.getActiveTab().getNodeById(categoryId));
                }
            });

            menuToolbar.insertButton(0, item);
        }
    }

    menu.UpdateGrid = function() {
        symbolsGrid.loadParams = {
            categoryId: categoryId,
            searchText: searchText,
            comparisonType: comparisonType,
            searchIn: searchIn,
            exchangeSearchIn: exchangeSearchIn,
            special: special,
            start: 0,
            limit: symbolsLimit,
            //options specific
            optionsSearchIn: optionsSearchIn,
            minStrikePrice: minStrikePrice,
            maxStrikePrice: maxStrikePrice,
            expirationYear: expirationYear,
            expirationMonth: expirationMonth,
            inPut: inPut,
            inCall: inCall
        };
        symbolsGrid.update();
    }

    function getDataFromAnchor(anchor, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&#]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(anchor);
        if (results == null)
            return '';
        else
            return results[1];
    }

    function rowDblClick(grid, rowIndex, e) {
        if (getDataFromAnchor(location.hash, 'callback') == 'ts-search') {
            if (window.parent != window) {
                window.parent.selectSymbol(grid.store.getAt(rowIndex).get('Symbol'));
            }
        }
    }

    var categoriesTree = new Itransition.RightWayTrader.RightWayTraderData.ux.SearchTree({
        id: 'category',
        tabTitle: 'Categories',
        rootNodeTitle: 'All Categories',
        handlerUrl: categoriesHandlerUrl
    });

    var groupsTree = new Itransition.RightWayTrader.RightWayTraderData.ux.SearchTree({
        id: 'group',
        tabTitle: 'Groups',
        rootNodeTitle: 'All Groups',
        handlerUrl: groupsHandlerUrl
    });

    var sectorsTree = new Itransition.RightWayTrader.RightWayTraderData.ux.SearchTree({
        id: 'sector',
        tabTitle: 'Sectors',
        rootNodeTitle: 'All Sectors',
        handlerUrl: sectorsHandlerUrl
    });

    var categoriesTab = new Ext.TabPanel({
        activeTab: 0,
        autoScroll: true,
        region: 'center',
        border: false,
        height: 600,
        items: [categoriesTree, groupsTree, sectorsTree],
        listeners: {
            'tabchange': function(panel) {
                var activeTab = categoriesTab.getActiveTab();
                exchangeSearchIn = activeTab.id;
                menu.Update([{ id: 0, name: activeTab.rootNodeTitle }]);
            }
        },
        bbar: new Ext.Toolbar({
            items: [new Ext.Toolbar.Button({
                text: 'Expand all',
                listeners: {
                    'click': function(btn, e) {
                        categoriesTab.getActiveTab().expandAll();
                    }
                }
            }), new Ext.Toolbar.Button({
                text: 'Collapse all',
                listeners: {
                    'click': function(btn, e) {
                        categoriesTab.getActiveTab().collapseAll();
                    }
                }
            })]
        })
    });

    var menuToolbar = new Ext.Toolbar({
        height: 26,
        items: []
    });

    var years = [];
    var months = [];
    var currentYear = new Date().getFullYear();

    years.push([0, 'Any']);
    for (var year = currentYear; year < (currentYear + 5); year++) {
        years.push([year, year]);
    }

    months.push([0, 'Any']);
    for (var monthIndex = 0; monthIndex < Date.monthNames.length; monthIndex++) {
        months.push([monthIndex + 1, Date.monthNames[monthIndex]]);
    }

    var expanded = false;
    var searchForm = new Ext.FormPanel({
        frame: true,
        width: '100%',
        region: 'north',
        margins: '5 5 5 5',
        autoHeight: true,
        title: 'Search',
        collapsible: true,
        collapsed: false,
        cls: 'collapsed',
        items: [{
            layout: 'column',
            labelWidth: 65,
            id: 'columns1',
            border: false,
            width: '100%',
            items: [{
                columnWidth: .78,
                layout: 'form',
                id: 'column1-1',
                border: false,
                items: [{
                    xtype: 'textfield',
                    fieldLabel: 'Search',
                    name: 'searchText',
                    id: 'searchText',
                    value: '',
                    anchor: '95%',
                    enableKeyEvents: true,
                    listeners: {
                        'keydown': function(field, e) {
                            if (e.keyCode == e.ENTER) {
                                Ext.getCmp('searchButton').fireEvent('click', Ext.getCmp('searchButton'));
                            }
                        }
                    }
                }]
            }, {
                columnWidth: .11,
                border: false,
                items: [new Ext.Button({
                    text: 'Search',
                    id: 'searchButton',
                    listeners: {
                        'click': function(btn, e) {
                            searchFromForm();
                        }
                    }
                })]
            }, {
                columnWidth: .11,
                border: false,
                items: [new Ext.Button({
                    text: 'Clear',
                    id: 'clearButton',
                    listeners: {
                        'click': function(btn, e) {
                            searchForm.getForm().reset();
                        }
                    }
                })]
            }]
        }, {
            layout: 'column',
            id: 'columns12',
            border: false,
            labelWidth: 65,
            width: '100%',
            items: [{
                layout: 'form',
                id: 'column12-1',
                border: false,
                items: [{
                    xtype: 'radiogroup',
                    fieldLabel: 'Search For',
                    id: 'searchInGr',
                    width: 166,
                    items: [{
                        boxLabel: 'Symbol',
                        name: 'searchIn',
                        inputValue: 'symbol',
                        checked: true
                    }, {
                        boxLabel: 'Name',
                        name: 'searchIn',
                        inputValue: 'name'
                    }]
                }]
            }]
        }, {
            layout: 'column',
            id: 'columns2',
            border: false,
            labelWidth: 65,
            width: '100%',
            items: [{
                id: 'column2-2',
                layout: 'form',
                border: false,
                items: [{
                    xtype: 'radiogroup',
                    fieldLabel: 'Match',
                    id: 'match',
                    width: 250,
                    items: [{
                        boxLabel: 'Match',
                        name: 'match',
                        inputValue: 'match',
                        checked: true
                    }, {
                        boxLabel: 'Starts',
                        name: 'match',
                        inputValue: 'start'
                    }, {
                        boxLabel: 'Contain',
                        name: 'match',
                        inputValue: 'contain'
                    }]
                }]
            }]
        }, {
            xtype: 'fieldset',
            checkboxToggle: true,
            id: 'optionsGroup',
            title: 'Options',
            autoHeight: true,
            items :[{
                layout: 'column',
                id: 'optionsColumns0',
                border: false,
                items: [{
                    layout: 'form',
                    id: 'optionsColumns0-1',
                    labelWidth: 90,
                    border: false,
                    items: [{
                        xtype: 'radiogroup',
                        fieldLabel: 'Search For',
                        id: 'optionsSearchInGr',
                        width: 166,
                        items: [{
                            boxLabel: 'Option',
                            name: 'optionsSearchIn',
                            inputValue: 'option',
                            checked: true
                        }, {
                            boxLabel: 'Underlying',
                            name: 'optionsSearchIn',
                            inputValue: 'underlying'
                        }]
                    }]
                }]
            }, {
                layout: 'column',
                id: 'optionsColumns',
                border: false,
                items: [{
                    layout: 'form',
                    id: 'optionsColumns-1',
                    labelWidth: 90,
                    border: false,
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: 'Strike price: >=',
                        labelSeparator: '',
                        name: 'minStrikePrice',
                        id: 'minStrikePrice',
                        value: '',
                        autoWidth: false,
                        width: 35
                    }]
                }, {
                    layout: 'form',
                    id: 'optionsColumns-2',
                    labelWidth: 15,
                    border: false,
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: '<=',
                        labelSeparator: '',
                        name: 'maxStrikePrice',
                        id: 'maxStrikePrice',
                        value: '',
                        autoWidth: false,
                        width: 35
                    }]
                }, {
                    border: false,
                    labelWidth: 35,
                    style: 'padding-left: 30px;',
                    items: [{
                        xtype: 'checkboxgroup',
                        items: [
                            {boxLabel: 'Put', name: 'inPut', checked: true},
                            {boxLabel: 'Call', name: 'inCall', checked: true}
                        ]
                    }]
                }]
            }, {
                layout: 'column',
                id: 'optionsColumns2',
                border: false,
                items: [{
                    border: false,
                    labelWidth: 90,
                    layout: 'form',
                    items: [
                        new Ext.form.ComboBox({
                            editable: false,
                            fieldLabel: 'Expiration year',
                            hiddenName: 'expirationYear',
                            store: new Ext.data.SimpleStore({
                                fields: ['value', 'name'],
                                data: years
                            }),
                            valueField: 'value',
                            displayField: 'name',
                            mode: 'local',
                            triggerAction: 'all',
                            emptyText: 'Any',
                            width: 60
                        })
                    ]
                }, {
                    border: false,
                    labelWidth: 100,
                    layout: 'form',
                    style: 'padding-left: 60px;',
                    items: [
                        new Ext.form.ComboBox({
                            editable: false,
                            fieldLabel: 'Expiration month',
                            hiddenName: 'expirationMonth',
                            store: new Ext.data.SimpleStore({
                                fields: ['value', 'name'],
                                data: months
                            }),
                            valueField: 'value',
                            displayField: 'name',
                            mode: 'local',
                            triggerAction: 'all',
                            emptyText: 'Any',
                            width: 90
                        })
                    ]
                }]
            }],
            listeners: {
                'expand': function (panel) {
                    expanded = true;
                    centerPanel.doLayout();
                },
                'collapse': function (panel) {
                    if (expanded) {
                        centerPanel.doLayout();
                    }
                }
            }
        }]
    });

    function searchFromForm() {
        comparisonType = searchForm.getForm().getValues(false)['match'];
        searchText = searchForm.getForm().getValues(false)['searchText'].trim();
        searchIn = searchForm.getForm().getValues(false)['searchIn'];
        minStrikePrice = searchForm.getForm().getValues(false)['minStrikePrice'];
        maxStrikePrice = searchForm.getForm().getValues(false)['maxStrikePrice'];
        special = searchForm.findById('optionsGroup').collapsed ? 'all' : 'options';
        //options specific
        optionsSearchIn = searchForm.getForm().getValues(false)['optionsSearchIn'];
        optionsGroup = searchForm.getForm().getValues(false)['optionsGroup'];
        expirationYear = searchForm.getForm().getValues(false)['expirationYear'];
        expirationMonth = searchForm.getForm().getValues(false)['expirationMonth'];
        inPut = (searchForm.getForm().getValues(false)['inPut'] == 'on') ? true : false;
        inCall = (searchForm.getForm().getValues(false)['inCall'] == 'on') ? true : false;

        Ext.getCmp('mainTabPanel').setActiveTab('mainSearchTab');

        menu.UpdateGrid();
    }

    function detailsClick(action, symbolRecord) {
        var tabs = Ext.getCmp('mainTabPanel');

        if (action == 'options-icon') {
            tabs.add({
                xtype: 'OptionsPanel',
                iconCls: 'options-icon',
                title: symbolRecord.Symbol + ' Options',
                id: symbolRecord.Symbol + 'OptionsTab',
                parentSymbol: symbolRecord.Symbol,
                proxyUrl: optionsHandlerUrl,
                region: 'center',
                rowDblClick: rowDblClick,
                border: false,
                enableColLock: false,
                autoScroll: true,
                loadMask: true,
                margins: '0 5 5 5',
                closable: true
            }).show();
        }
    }

    var centerPanel = new Ext.Panel({
        region: 'center',
        layout: 'border',
        bodyBorder: true,
        border: true,
        tbar: menuToolbar,
        items: [
            searchForm, {
                xtype: 'tabpanel',
                region: 'center',
                id: 'mainTabPanel',
                enableTabScroll: true,
                activeTab: 0,
                border: false,
                defaults: {autoScroll: true},
                items: [
                    symbolsGrid = new Itransition.RightWayTrader.RightWayTraderData.ux.SymbolsPanel({
                        title: 'Main tab',
                        id: 'mainSearchTab',
                        actionCallback: detailsClick,
                        rowDblClick: rowDblClick,
                        proxyUrl: symbolsHandlerUrl,
                        region: 'center',
                        symbolsLimit: 30,
                        enableColLock: false,
                        autoScroll: true,
                        loadMask: true,
                        margins: '0 5 5 5'
                    })
                ]
            }
        ]
    });

    var westRegion = new Ext.Panel({
        title: 'Category / Exchange',
        region: 'west',
        width: 250,
        margins: '0 5 0 0',
        items: categoriesTab
    });

    var main = new Ext.Viewport({
        layout: 'border',
        items: [westRegion, centerPanel]
    });

    function ResizeHandler() {
        main.doLayout();
        westRegion.doLayout();
        centerPanel.doLayout();
        categoriesTab.setHeight(westRegion.getInnerHeight());
    }

    window.onresize = function() {
        ResizeHandler();
    };

    ResizeHandler();

    searchForm.findById('optionsGroup').collapse();
    centerPanel.doLayout();

    Ext.get('loading').remove();
    Ext.get('loading-mask').fadeOut({remove: true});

    menu.UpdateGrid();
});