/**
 * partist.ru (c) 2008-2010
 * @author Telrik
 */
Ext.BLANK_IMAGE_URL = './images/default/s.gif';
Ext.ns('m7', 'Ext.ux');

m7.isLoaded = false;
textYourCart = 'Your cart:';

Ext.onReady(function(){
    if (m7.isLoaded) {
        return; //ugly opera fix
    }
    else {
        m7.isLoaded = true;
    }
    
    Ext.QuickTips.init();
    
    // Apply a set of config properties to the singleton
    Ext.apply(Ext.QuickTips.getQuickTip(), {
        trackMouse: true
    });
    
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
        expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 7)) // 2 часа 
    }));
    
    // Finally, build the main layout once all the pieces are ready. This is also a good
    // example of putting together a full-screen BorderLayout within a Viewport.
    m7.Layout = new m7.ViewPort();
    if (m7.hideTech) {
        m7.Layout.tabsPanel.remove(2);
    }
    m7.Layout.refreshCart();
    
    //var fullname = Ext.state.Manager.get('fullname', null);
    if (m7.user) {
        Ext.getCmp('user-login-button').setText("<b class='x-header-font'>Здравствуйте, " + m7.user + "</b>");
    }
    
    if (window.location.hash.length > 2) {
        var a = window.location.hash.split("/");
        
        if (a[0] == '#offers') {
            m7.Layout.tabsPanel.activate(2);
            Ext.getCmp('east-panel').collapse();
        }
        else {
            setStateByUrl(window.location.href);
        }
    }
    else {
        Ext.getCmp('east-panel').collapse();
    }
    
    Ext.getCmp('menu_basket').on('mouseover', function(e){
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        var in_cart = 0;
        var position = 1;
        var parts = '';
        for (var i in stars) {
            if (stars[i] && stars[i].star == 'set') {
                //console.log(stars[i]);
                parts += position + ".&nbsp;" + (stars[i].part_name_rus ? stars[i].part_name_rus : stars[i].part_name) + "&nbsp;" + stars[i].part_number + "&nbsp;" + stars[i].part_count + "<br />";
                position++;
                if (stars[i].part_count) {
                    in_cart += stars[i].part_count;
                }
                else {
                    in_cart++;
                }
            }
        }
        Ext.notice.msg('<b>' + textYourCart + in_cart + '</b>', '<span style="white-space: normal;">' + parts + '</span>');
    }, this);
    
    
    var flashvars = {
        'file': '/mediaplayer/mrss.xml',
        'playlist': 'bottom',//bottom
        'playlistsize': '65',
        'frontcolor': '000000', //'000000', //'ffffff',
        'lightcolor': '15428B',
        'backcolor': 'ffffff',//99BBE8', //35537e',
        'screencolor': 'ffffff',
        'repeat': 'false',
        'shuffle': 'false',
        'autostart': 'false'
    };
    
    var params = {
        'allowfullscreen': 'true',
        'allowscriptaccess': 'always',
        'wmode': 'opaque',
        'usefullscreen': 'false'
    };
    
    var attributes = {};
    
    id = Ext.get('mediaspace').parent('table').id;
    
    swfobject.embedSWF("/mediaplayer/mediaplayer.swf", 'hint-div', "373", "85", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
    Ext.get(id).setStyle({
        'margin-top': '2px',
        'margin-left': '4px'
    });
});

function setStateByUrl(url){
    var hash = url.split('#')[1];
    window.location.hash = hash;
    
    hash = hash.split('~');
    
    var path = hash[0];
    var page = hash[1];
    var id = path.split('/').pop();
    
    m7.Layout.treePanel.selectPath(path);
    m7.Layout.tabsPanel.activate(1);
    m7.Layout.tabsPanel.doLayout();
    m7.Layout.startPage.setImage(page);
    
    Ext.getCmp('east-panel').expand();
    m7.PartsList.store.load({
        params: {
            parent_id: id
        }
    });
}

function _blink(){
    Ext.getCmp('menu_basket').getEl().fadeOut({
        duration: 0.6
    });
    Ext.getCmp('menu_basket').getEl().fadeIn({
        duration: 0.5
    });
    setTimeout(_blink, 7000);
}

m7.ViewPort = Ext.extend(Ext.Viewport, {
    textInterface: 'Interface',
    textSearch: 'Search',
    textHelp: 'Help',
    textCatalog: 'Catalog',
    textSpareparts: 'Spareparts',
    textOrder: 'For ordering parts please contact us by e-mail komatsu@partist.ru',
    textCart: 'ORDER SPAREPARTS',
    textCartFull: 'ORDER NOW, TOTAL PARTS:',
    textHint: 'Hint',
    textSkin: 'Skin',
    textSearchTitle: 'Search',
    textSearchModel: 'Model',
    textKomatsu: 'Komatsu spareparts',
    textSearchCatalog: 'Catalog search',
    textCatalogPage: 'Catalog page',
    textAskQuestion: 'Ask question',
    textPrint: 'Print',
    refreshCart: function(){
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        var in_cart = 0;
        
        for (var i in stars) {
            if (stars[i] && stars[i].star == 'set') {
                if (stars[i].part_count) {
                    in_cart += parseInt(stars[i].part_count);
                }
                else {
                    in_cart++;
                }
            }
        }
        
        if (in_cart > 0) {
        
            Ext.getCmp('menu_basket').setIconClass('ux-icon-cart_go-png');
            Ext.getCmp('menu_basket').setText("<b class='x-header-font'><font size='2' color=#FFFFFF>" + this.textCartFull + " " + in_cart + "</font></b>");
            if (!Ext.isIE) {
                _blink();
            }
        }
        else {
            Ext.getCmp('menu_basket').setIconClass('ux-icon-cart-png');
            Ext.getCmp('menu_basket').setText("<b class='x-header-font'><font size='2' color=#FFFFFF>" + this.textCart + "</font></b>");
        }
    },
    initComponent: function(){
        var theme = Ext.state.Manager.get('theme', 'default');
        Ext.util.CSS.swapStyleSheet(theme, './css/xtheme-' + theme + '.css');
        
        // Go ahead and create the TreePanel now so that we can use it below
        this.treePanel = new m7.ModulesTree();
        //this.treePanelTech = new m7.TechTree();
        
        var westPanel = {
            split: true,
            height: 605,
            minSize: 150,
            layoutConfig: {
                // layout-specific configs go here
                titleCollapse: false,
                animate: true,
                activeOnTop: false
            },
            // collapseMode: 'mini',
            // collapsible: false,
            id: 'accordion-panel',
            title: this.textCatalog,
            iconCls: 'ux-icon-book_key',
            region: 'center',
            layout: 'accordion',
            bodyBorder: false, // useful for accordion containers since the inner panels have borders already
            bodyStyle: 'background-color:#DFE8F6', // if all accordion panels are collapsed, this looks better in this layout
            defaults: {},
            items: [{
                autoScroll: true,
                //hideCollapseTool: true,
                titleCollapse: true,
                layout: 'fit',
                //autoHeight: true,
                title: '<b>' + this.textKomatsu + '</b>',
                tools: [{
                    id: 'refresh',
                    //scope: this.treePanel,
                    on: {
                        click: function(z){
                            m7.Layout.treePanel.root.reload();
                        }
                    }
                }],
                items: this.treePanel
            }            /*{
             autoScroll: true,
             titleCollapse: true,
             //hideCollapseTool: true,
             layout: 'fit',
             hidden: true,
             //disabled: true,
             title: 'Предложения по технике',
             tools: [{
             id: 'refresh',
             on: {
             click: function(z){
             m7.Layout.treePanelTech.root.reload();
             }
             }
             }],
             items: this.treePanelTech
             }*/
            ]
        };
        
        // This is the Details panel that contains the description for each example layout.
        var detailsPanel = {
            id: 'details-panel',
            height: 130,
            hidden: true,
            title: this.textHint,
            region: 'south',
            split: true,
            //layout: 'fit',
            collapseMode: 'mini',
            collapsible: true,
            // collapsed: true,
            bodyStyle: 'padding-bottom:15px;background:#eee;',
            autoScroll: true,
            contentEl: 'hint-div'
        };
        
        /*
         * <li><tt>toggle</tt> (Created by default when {@link #collapsible} is <tt>true</tt>)</li>
         * <li><tt>close</tt></li>
         * <li><tt>minimize</tt></li>
         * <li><tt>maximize</tt></li>
         * <li><tt>restore</tt></li>
         * <li><tt>gear</tt></li>
         * <li><tt>pin</tt></li>
         * <li><tt>unpin</tt></li>
         * <li><tt>right</tt></li>
         * <li><tt>left</tt></li>
         * <li><tt>up</tt></li>
         * <li><tt>down</tt></li>
         * <li><tt>refresh</tt></li>
         * <li><tt>minus</tt></li>
         * <li><tt>plus</tt></li>
         * <li><tt>help</tt></li>
         * <li><tt>search</tt></li>
         * <li><tt>save</tt></li>
         * <li><tt>print</tt></li>
         */
        m7.PartsList = new m7.PartsGrid();
        var eastPanel = {
            title: this.textSpareparts,
            iconCls: 'ux-icon-wrench',
            id: 'east-panel',
            region: 'east',
            margins: '2 5 5 0',
            split: true,
            left: 600, //opera megafix 
            width: 290,
            items: m7.PartsList,
            //hidden: true,
            collapseMode: 'mini',
            layout: 'fit',
            collapsible: true,
            collapsed: true,
            minSize: 100,
            maxSize: 1280,
            html: '<p class="details-info">У нас самые выгодные цены, сроки и доставка по СНГ. Для заказа нажмите на звездочку.</p>'
        };
        
        /*
         * ================ Start page config ========= ==============
         */
        // The default start page, also a simple example of a FitLayout.
        var startPage = this.startPage = new Ext.ux.PanPanel({
            minSize: 0,
            border: false,
            id: 'startPage',
            tbar: [{
                iconCls: 'ux-icon-zoom_in',
                scope: this,
                handler: function(s){
                    var height = startPage.clientel.getHeight() * 1.3;
                    var width = startPage.clientel.getWidth() * 1.3;
                    
                    startPage.clientel.setHeight(height);
                    startPage.clientel.setWidth(width);
                    
                    startPage.shiftImage(306, 370);
                }
            }, {
                iconCls: 'ux-icon-zoom_out',
                scope: this,
                handler: function(s){
                    var height = startPage.clientel.getHeight() / 1.3;
                    var width = startPage.clientel.getWidth() / 1.3;
                    
                    startPage.clientel.setHeight(height);
                    startPage.clientel.setWidth(width);
                }
            }, '->', {
                iconCls: 'ux-icon-user_comment',
                text: this.textAskQuestion,
                handler: function(s){
                    var win = new m7.QuestionWindow();
                    win.show();
                }
            }, {
                iconCls: 'ux-icon-printer',
                text: this.textPrint,
                handler: function(s){
                    window.open("print.php?q=" + window.location.hash.substr(1), "_blank");
                }
            }],
            title: this.textOrder,
            //  contentEl: 'start-div', // pull existing content from the page
            listeners: {
                render: function(p){
                
                }
            }
        });
        
        /*
         * ================ CardLayout config (TabPanel) =======================
         */
        // Note that the TabPanel component uses an internal CardLayout -- it's not
        // something you have to explicitly configure. However, it's still a perfect
        // example of how this layout style can be used in a complex component.
        
        m7.offersGrid = new m7.OffersGrid();
        
        
        m7.searchGrid = new m7.SearchGrid();
        this.tabsPanel = new Ext.TabPanel({
            // resizeTabs: true,
            // minTabWidth: 115,
            // tabWidth: 135,
            enableTabScroll: true,
            // deferredRender: true,
            id: 'card-tabs-panel',
            // plain: true, // remove the header border
            activeItem: 0,
            defaults: {
                bodyStyle: 'padding:0px',
                autoScroll: true
            },
            items: [            /*{
             id: 'welcome-panel',
             title: 'Добро пожаловать',
             hidden: true,
             contentEl: 'start-div',
             listeners: {
             'activate': function(){
             }
             }
             }, */
            {
                items: m7.searchGrid,
                id: 'none-panel',
                title: this.textSearchCatalog,
                hidden: false,
                listeners: {
                    'activate': function(){
                        this.doLayout();
                    }
                }
            }, {
                layout: 'fit',
                id: 'image-panel',
                title: this.textCatalogPage,
                items: startPage
            }, {
                id: 'tehnika-panel',
                title: '<b style="color:green;">Предложения по технике</b>',
                hidden: true,
                //bodyStyle: 'padding:4px 4px 4px 4px',
                items: m7.offersGrid,
                listeners: {
                    'activate': function(){
                        this.doLayout();
                        if (!window.location.hash) {
                            window.location.hash = 'offers';
                        }
                    }
                }
                //contentEl: 'tehnika-div'
            }]
        });
        this.tabsPanel.on('activate', function(e){
            // alert(e)
        }, this);
        // This is the main content center region that will contain each example layout panel.
        // It will be implemented as a CardLayout since it will contain multiple panels with
        // only one being visible at any given time.
        var contentPanel = {
            resizable: false,
            id: 'content-panel',
            layoutConfig: {
                deferredRender: true
            },
            region: 'center', // this is what makes this panel into a region within the containing layout
            layout: 'card',
            margins: '2 2 5 2',
            activeItem: 0,
            border: false,
            //width: 1000,
            frame: false,
            items: [this.tabsPanel]
        };
        
        //contentPanelthis.tabsPanel
        
        Ext.apply(this, {
            layout: 'border',
            items: [{
                xtype: 'panel',
                region: 'north',
                height: 28,
                border: true,
                tbar: new Ext.Toolbar({
                    id: 'navigation-panel',
                    cls: 'header',
                    items: [{
                        text: "<b class='x-header-font'>Регистрация</b>",
                        iconCls: 'ux-icon-user_gray',
                        hidden: true,
                        scope: this,
                        handler: function(s){
                            window.location = '/z_system2/register.php'
                        }
                    }, {
                        id: 'user-login-button',
                        text: "<b class='x-header-font'>Войти</b>",
                        hidden: true,
                        iconCls: 'ux-icon-user_suit',
                        scope: this,
                        handler: function(s){
                            //var fullname = Ext.state.Manager.get('fullname', null);
                            
                            if (m7.user) {
                                window.location = '/z_system2/system/autor.php';
                                return;
                            }
                            
                            var form = new Ext.FormPanel({
                                labelWidth: 50,
                                //url: 'save-form.php',
                                frame: true,
                                monitorValid: 'true',
                                
                                border: false,
                                buttonAlign: 'right',
                                bodyStyle: 'padding:5px 5px 0',
                                width: 350,
                                defaults: {
                                    width: 210
                                },
                                defaultType: 'textfield',
                                items: [{
                                    //vtype: 'email',
                                    fieldLabel: 'Логин',
                                    name: 'e-mail',
                                    allowBlank: false
                                }, {
                                    inputType: 'password',
                                    fieldLabel: 'Пароль',
                                    name: 'password',
                                    allowBlank: false
                                }],
                                buttons: [{
                                    formBind: true,
                                    iconCls: 'ux-icon-user_go',
                                    text: 'Войти',
                                    scope: this,
                                    handler: function(){
                                    
                                        Ext.Ajax.request({
                                            url: '/z_system2/system/autor.php',
                                            params: {
                                                PHPSESSID: m7.sessionId,
                                                logins: form.getForm().findField('e-mail').getValue(),
                                                pswd: form.getForm().findField('password').getValue(),
                                                ajax: true
                                            },
                                            scope: this,
                                            success: function(r){
                                                var o = Ext.decode(r.responseText);
                                                if (o.sucess == "true") {
                                                    Ext.getCmp('user-login-button').setText("<b class='x-header-font'>Здравствуйте, " + o.name + "</b>");
                                                    Ext.state.Manager.set('fullname', o.name);
                                                    m7.user = o.name;
                                                    m7.email = o.email;
                                                    m7.PartsList.store.reload();
                                                    
                                                    win.close();
                                                }
                                                else {
                                                    Ext.MessageBox.show({
                                                        title: 'Ошибка',
                                                        msg: o.message,
                                                        buttons: Ext.MessageBox.OK,
                                                        icon: Ext.MessageBox.ERROR
                                                    });
                                                }
                                            }
                                        });
                                        
                                        /* form.getForm().submit({
                                         url: 'ws.php?f=LoginUser',
                                         waitMsg: 'Авторизация...',
                                         success: function(f, o){
                                         win.close();
                                         Ext.state.Manager.set('fullname', o.result.fullname);
                                         Ext.getCmp('user-login-button').setText("<b class='x-header-font'>Здравствуйте, " + o.result.fullname + "</b>");
                                         //Ext.getCmp('user-login-button').setText("<b class='x-header-font'>" + o.result.fullname + "</b>");
                                         },
                                         failure: function(f, o){
                                         win.close();
                                         Ext.MessageBox.show({
                                         title: 'Регистрация',
                                         msg: 'На ваш емейл направлены данные об аккаунте',
                                         buttons: Ext.MessageBox.OK,
                                         icon: Ext.MessageBox.INFO
                                         });
                                         }
                                         });*/
                                    }
                                }, {
                                    hidden: true,
                                    formBind: true,
                                    iconCls: 'ux-icon-user_add',
                                    text: 'Зарегестрироватся'
                                }]
                            });
                            var win = new Ext.Window({
                                iconCls: 'ux-icon-user_suit',
                                title: 'Логин',
                                layout: 'fit',
                                width: 300,
                                height: 140,
                                border: false,
                                closeAction: 'hide',
                                plain: true,
                                items: form
                            });
                            win.on('beforeshow', function(){
                                win.alignTo(document, 'tl-tl', [0, 0]);
                            }, win);
                            
                            win.show();
                            
                            /*Ext.MessageBox.prompt('Name', 'Please enter your name:', function(btn, text){
                             Ext.example.msg('Button Click', 'You clicked the {0} button and entered the text "{1}".', btn, text);
                             });*/
                        }
                    }, {
                        iconCls: "ux-icon-application_view_icons",
                        text: "<b class='x-header-font'>" + this.textInterface + "</b>",
                        menu: {
                            items: [{
                                text: this.textSkin, //'Оформление',
                                iconCls: 'ux-icon-images',
                                menu: {
                                    items: ['<b class="menu-title">Выберите тему</b>', {
                                        text: 'Небесный сапфир',
                                        value: 'default',
                                        group: 'theme',
                                        checked: theme == 'default' ? true : false,
                                        handler: function(s){
                                            Ext.util.CSS.swapStyleSheet('theme', './css/xtheme-' + s.value + '.css');
                                            Ext.state.Manager.set('theme', s.value);
                                        }
                                    }, {
                                        text: 'Спелая олива',
                                        value: 'olive',
                                        group: 'theme',
                                        checked: theme == 'olive' ? true : false,
                                        handler: function(s){
                                            Ext.util.CSS.swapStyleSheet('theme', './css/xtheme-' + s.value + '.css');
                                            Ext.state.Manager.set('theme', s.value);
                                        }
                                    }, {
                                        text: 'Мрачная сталь',
                                        value: 'darkgray',
                                        group: 'theme',
                                        checked: theme == 'darkgray' ? true : false,
                                        handler: function(s){
                                            Ext.util.CSS.swapStyleSheet('theme', './css/xtheme-' + s.value + '.css');
                                            Ext.state.Manager.set('theme', s.value);
                                        }
                                    }]
                                }
                            }]
                        }
                    }, '-', {
                        hidden: true,
                        text: "<b class='x-header-font'>Добавь в избранное</b>",
                        iconCls: "ux-icon-star-png",
                        handler: function(s){
                            var win = new m7.SelectManufacturerWindow();
                            win.show();
                        }
                    }, {
                        xtype: 'iconcombo',
                        width: 100,
                        //fieldLabel: 'IconCombo',
                        store: new Ext.data.SimpleStore({
                            fields: ['countryCode', 'countryName', 'countryFlag'],
                            data: [['ru', 'Русский', 'ux-flag-ru'], ['en', 'English', 'ux-flag-en']]
                        }),
                        valueField: 'countryCode',
                        displayField: 'countryName',
                        iconClsField: 'countryFlag',
                        triggerAction: 'all',
                        editable: false,
                        mode: 'local',
                        onSelect: function(record){ // override default onSelect to do redirect
                            if (record.data.countryCode == 'ru') {
                                window.location.href = '/index.php';
                            }
                            else {
                                window.location.href = '/index.' + record.data.countryCode + '.php';
                            }
                            Ext.state.Manager.set('language', record.data.countryCode);
                        },
                        
                        value: Ext.state.Manager.get('language', 'ru')
                    }, {
                        text: '<div id="mediaspace">',
                        hidden: true
                        //template: new Ext.Template('<table border="0" cellpadding="0" cellspacing="0" ><tbody><tr>', '<td></td><td class="x-btn-center"><em unselectable="on"><div id="mediaspace"></div><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>', "</tr></tbody></table>")
                        //new Ext.Template('<div id="mediaspace1"></div>')
                    
                    }, {
                        hidden: true,
                        text: "<b class='x-header-font'>Language/Язык</b>",
                        menu: [{
                            text: 'Русский',
                            value: 'ru',
                            iconCls: 'ux-flag-ru',
                            handler: function(s){
                                window.location.href = '/index.php';
                            }
                        }, {
                            text: 'English',
                            value: 'en',
                            iconCls: 'ux-flag-en',
                            handler: function(s){
                                window.location.href = '/index.en.php';
                            }
                        }]
                    }, '->', {
                        width: 500,
                        text: '<b style="width:500px;" class="x-header-font">E-mail: komatsu@partist.ru</b>'
                    },                    /*, {
                     id: 'outersearchfield',
                     width: 350,
                     xtype: 'textfield'
                     
                     }, {
                     id: 'outersearchbutton',
                     text: "<b class='x-header-font'>" + this.textSearch + "</b>",
                     iconCls: "ux-icon-find",
                     handler: function(s){
                     var grid = new m7.SearchGrid();
                     
                     var win = new Ext.Window({
                     title: this.SearchTitle, //'Поиск',
                     layout: 'fit',
                     modal: false,
                     buttonAlign: 'right',
                     width: 920,
                     //minimizable: true,
                     maximizable: true,
                     
                     height: 440,
                     border: false,
                     items: grid,
                     iconCls: 'ux-icon-find'
                     });
                     win.show();
                     }
                     }*/
                    {
                        text: "<b class='x-header-font'>" + this.textHelp + "</b>",
                        iconCls: "ux-icon-help",
                        hidden: true,
                        handler: function(s){
                            if (!m7.HelpWindow) {
                                m7.HelpWindow = new Ext.Window({
                                    title: 'Полезная информация',
                                    layout: 'fit',
                                    modal: true,
                                    autoScroll: true,
                                    buttonAlign: 'right',
                                    closeAction: 'hide',
                                    width: 740,
                                    height: 550,
                                    border: false,
                                    items: new Ext.TabPanel({
                                        //renderTo: 'tabs1',
                                        width: 450,
                                        activeTab: 0,
                                        frame: true,
                                        defaults: {
                                            autoHeight: true,
                                            autoScroll: true
                                        },
                                        items: [{
                                            contentEl: 'help1',
                                            autoScroll: true,
                                            title: 'Полезная информация'
                                        }, {
                                            contentEl: 'help2',
                                            title: 'Реквизиты'
                                        }]
                                    }),
                                    
                                    
                                    iconCls: 'ux-icon-help'
                                });
                                
                            }
                            m7.HelpWindow.show();
                        }
                    }, '-', {
                        text: "<b class='x-header-font'>Заявка</b>",
                        id: 'menu_basket',
                        iconCls: 'ux-icon-cart-p',
                        listeners: {
                            'mouseleave': function(){
                                console.log('');
                            }
                        },
                        scope: this,
                        handler: function(s){
                            var win = new m7.CartWindow();
                            win.show();
                        }
                    }]
                })
            }, {
                layout: 'border',
                id: 'layout-browser',
                region: 'west',
                border: false,
                split: true,
                margins: '2 0 0 5',
                width: 375,
                minSize: 100,
                maxSize: 500,
                items: [westPanel, detailsPanel]
            }, contentPanel, eastPanel]
        });
        
        m7.ViewPort.superclass.initComponent.call(this);
    }
});

m7.OffersGrid = Ext.extend(Ext.grid.GridPanel, {
    onRowAction: function(grid, record, action, row, col){
        if (action == 'ux-icon-cart_add') {
            var a = window.location.hash.split("/");
            if (a[0] == '#offers') {
                //a.shift(); 
                var is_added = false;
                for (var i = 0; i < a.length; i++) {
                    if (record.data.id == a[i]) {
                        is_added = true;
                        break;
                    }
                }
                
                if (!is_added) {
                    a.push(record.data.id);
                }
                window.location.hash = a.join('/');
                record.data.icon = 'ux-icon-cart_delete';
                record.commit();
            }
        }
        if (action == 'ux-icon-cart_delete') {
            var a = window.location.hash.split("/");
            var newa = [];
            if (a[0] == '#offers') {
                for (var i = 0; i < a.length; i++) {
                    if (record.data.id != a[i]) {
                        newa.push(a[i]);
                    }
                }
                window.location.hash = newa.join('/');
                record.data.icon = 'ux-icon-cart_add';
                record.commit();
            }
        }
    },
    onRowClick: function(grid, rowIndex, e){
        if (e.getTarget('.x-grid3-row-expander') || e.getTarget('.ux-row-action-item')) {
            return;
        }
        this.expander.toggleRow(rowIndex);
    },
    onRenderEvent: function(){
        Ext.select('a.offer-image-anchor').on('click', function(e){
            var win = new Ext.Window({
                layout: 'fit',
                width: 800,
                height: 600,
                plain: true,
                html: '<table height="100%" width="100%"><tr><td align="center" valign="middle"><img src="/phpthumb/phpThumb.php?src=' + this.href + '&wl=800&hp=600" alt="" /></td></tr></table>',
                buttons: [{
                    text: 'Close',
                    handler: function(){
                        win.hide();
                    }
                }]
            });
            win.show();
            
            e.stopEvent();
        });
    },
    initComponent: function(){
        function onItemCheck(item, checked){
            alert('Item Check', 'You {1} the "{0}" menu item.', item.text, checked ? 'checked' : 'unchecked')
            //Ext.example.msg('Item Check', 'You {1} the "{0}" menu item.', item.text, checked ? 'checked' : 'unchecked');
        }
        
        // row expander
        this.expander = new Ext.grid.RowExpander({
            tpl: new Ext.XTemplate('<div style="padding:4px;float:left;border:1px dotted black;width:56%;height:200px;">', '<b>Описание:</b><p>{desc}</p><br />', '<b>Технические характеристики:</b><br />', '<tpl for="model_attrs">', '<tpl>{#}.<b>{attr}</b> : {value}<br /></tpl>', '</tpl>', '</div>', '<div style="overflow:auto;padding:4px;float:right;border:1px dotted navy;width:40%;height:200px;">', '<b>Прикрепленные файлы:</b><br />', '<tpl for="files">', '<tpl if="ext==\'jpg\'">', '<a target="_blank" class="offer-image-anchor" href="/z_system2/user_files/{file}">', '<img style="padding:4px" src="/phpthumb/phpThumb.php?src=/z_system2/user_files/{file}&w=75" alt="{comments}" />', '</a>', '</tpl>', '<tpl if="ext==\'doc\'">', '<img src="/images/icons/page_white_word.gif" alt="word" />', '<a target="_blank" href="/z_system2/user_files/{file}">{file}', '<tpl if="comments!=\'\'">', ' ({comments})', '</tpl>', '</a><br />', '</tpl>', '<tpl if="ext==\'pdf\'">', '<img src="/images/icons/page_white_acrobat.gif" alt="acrobat" />', '<a target="_blank" href="/z_system2/user_files/{file}">{file}', '<tpl if="comments!=\'\'">', ' ({comments})', '</tpl>', '</a><br />', '</tpl>', '</tpl>', '</div>', '<div style="clear:both;"></div>')
        });
        this.expander.on('expand', this.onRenderEvent, this);
        
        var rowactions1 = new Ext.ux.grid.RowActions({
            actions: [{
                iconIndex: 'icon',
                iconCls: 'ux-icon-cart_add',
                qtip: 'Добавить в корзину'
            }],
            widthIntercept: Ext.isSafari ? 4 : 2
        });
        rowactions1.on('action', this.onRowAction, this);
        
        var store = new Ext.data.JsonStore({
            url: 'ws.php?f=SelectOffers',
            root: 'offers',
            fields: ['spec_pred', 'weightname', 'icon', 'id', 'files', 'model_attrs', 'desc', 'date_mod', 'cityname', 'price_trade', 'time_work', 'yare', 'typename', 'markname', 'name', 'model', 'company', 'url', {
                name: 'size',
                type: 'float'
            }, {
                name: 'lastmod',
                type: 'date',
                dateFormat: 'timestamp'
            }]
        });
        
        
        var config = [];
        config[config.length] = '<b class="menu-title">Выберите вид техники</b>';
        
        for (var i = 0; i < m7.techTypes.length; i++) {
            var item = m7.techTypes[i];
            
            //item.iconCls = 'ux-icon-fc-lorry';
            item.text += ' (<b>' + item.count + '</b>)';
            item.group = 'types';
            item.checked = false;
            
            item.handler = function(item){
                store.load({
                    params: {
                        type: item.id,
                        start: 0
                    }
                });
            };
            
            //Submenu
            var submenu = [];
            for (var j = 0; j < item.models.length; j++) {
                var model = item.models[j];
                model.iconCls = 'ux-icon-fc-lorry';
                model.text = model.markname + ' ' + model.text + '(<b>' + model.count + '</b>)';
                model.handler = function(item){
                    store.load({
                        params: {
                            type: item.type,
                            model: item.id,
                            start: 0
                        }
                    });
                };
                submenu[submenu.length] = model;
            }
            if (submenu.length > 0) {
                item.menu = submenu;
            }
            delete item.models;
            
            //delete item.id; // += 'tech_';
            if (i == 1) {
                config[config.length] = '-';
            }
            config[config.length] = item;
        };
        //config[config.length] = '-';
        //  m7.techMarks.unshift('<b class="menu-title">Выберите производителя</b>');
        
        Ext.apply(this, {
        
            loadMask: {
                msg: 'Идёт загрузка предложений...'
            },
            store: store,
            border: false,
            tbar: [{
                text: '<b>Выбор техники</b>',
                iconCls: 'ux-icon-lorry_add',
                menu: new Ext.menu.Menu({
                    autoScroll: true,
                    enableScrolling: true,
                    maxHeight: 600,
                    boxMaxHeight: 600,
                    autoHeight: false,
                    monitorResize: true,
                    height: 600,
                    id: 'techTypes',
                    width: 280,
                    items: config
                })
            }, '->', {
                text: '<b>Сброс</b>',
                iconCls: 'ux-icon-lorry_error',
                scope: this,
                handler: function(s){
                    window.location.hash = 'offers';
                    this.store.load();
                }
            }]            /*,
             tbar: [{
             text: '<b>Вид техники</b>',
             menu: new Ext.menu.Menu({
             id: 'techTypes',
             items: m7.techTypes
             })
             }, {
             text: '<b>Производитель</b>',
             menu: {
             items: m7.techMarks
             }
             }, {
             text: '<b>Модель</b>',
             menu: { // <-- submenu by nested config object
             items: ['<b class="menu-title">Выберите модель</b>', {
             text: 'Komatsu',
             checked: true,
             group: 'theme',
             checkHandler: onItemCheck
             }, {
             text: 'Vista Black',
             checked: false,
             group: 'theme',
             checkHandler: onItemCheck
             }, {
             text: 'Gray Theme',
             checked: false,
             group: 'theme',
             checkHandler: onItemCheck
             }, {
             text: 'Default Theme',
             checked: false,
             group: 'theme',
             checkHandler: onItemCheck
             }]
             }
             
             }]            ,
             store: new Ext.data.Store({
             reader: reader,
             data: Ext.grid.dummyData
             })*/
            ,
            cm: new Ext.grid.ColumnModel([this.expander, {
                id: 'type-tech',
                locked: true,
                header: "Вид техники",
                //width: 30,
                sortable: true,
                dataIndex: 'typename'
            }, {
                header: "Производитель",
                //width: 20,
                sortable: true,
                dataIndex: 'markname'
            }, {
                header: "Вес",
                width: 45,
                fixed: true,
                sortable: true,
                dataIndex: 'weightname'
            }, {
                header: "Модель",
                //width: 20,
                sortable: true,
                dataIndex: 'model'
            }, {
                header: "Год",
                width: 45,
                fixed: true,
                sortable: true,
                dataIndex: 'yare'
            }, {
                header: "Наработка",
                width: 65,
                fixed: true,
                sortable: true,
                dataIndex: 'time_work',
                renderer: function(val){
                    return val == 0 ? 'Новый' : val;
                }
            }, {
                header: "<b>Цена, р</b>",
                //width: 20,
                sortable: true,
                //renderer: Ext.util.Format.ruMoney,
                dataIndex: 'price_trade',
                renderer: function(v, params, record){
                    if (record.data.spec_pred == 1) {
                        return v + '<br /><s qtip="Спецпредложение" style="color:red;">' + (v * 1.1).toFixed(2) + '</s>';
                    }
                    return v;
                }
                
            }, {
                header: "Город",
                //width: 20,
                sortable: true,
                dataIndex: 'cityname'
            }, {
                header: "Дата размещения",
                //width: 20,
                sortable: true,
                //renderer: Ext.util.Format.dateRenderer('m/d/Y'),
                dataIndex: 'date_mod'
            }, rowactions1]),
            viewConfig: {
                forceFit: true
            },
            //width: 600,
            height: 600,
            //autoHeight: true,
            autoWidth: true,
            plugins: [this.expander, rowactions1],
            collapsible: true,
            animCollapse: false,
            title: 'Актуальные предложения техники'
            //iconCls: 'ux-icon-lorry'
        });
        this.on('rowclick', this.onRowClick, this);
        
        var a = window.location.hash.split("/");
        if (a.length > 1 && a[0] == '#offers') {
            a.shift();
            this.store.load({
                params: {
                    url: a.join(',')
                }
            });
        }
        else {
            this.store.load();
        }
        
        
        m7.OffersGrid.superclass.initComponent.call(this);
    }
})

/*
 m7.CartWindow = Ext.extend(Ext.Window, {
 initComponent: function(){
 Ext.apply(this, {});
 m7.CartWindow.superclass.initComponent.call(this);
 }
 });
 m7.CartWindow = Ext.extend(Ext.Window, {
 initComponent: function(){
 Ext.apply(this, {});
 m7.CartWindow.superclass.initComponent.call(this);
 }
 });*/
m7.TechTree = Ext.extend(Ext.tree.TreePanel, {
    initComponent: function(){
        this.loader = new Ext.tree.TreeLoader({
            dataUrl: 'ws.php?f=TechTree'
        });
        Ext.apply(this, {
            id: 'tech-tree-panel',
            border: false,
            animate: false,
            iconCls: 'ux-icon-lorry',
            bodyStyle: 'padding: 0px;',
            height: 405,
            minSize: 150,
            autoScroll: true,
            rootVisible: false,
            singleExpand: true,
            //useArrows: true,
            loader: this.loader,
            root: new Ext.tree.AsyncTreeNode({
                id: 'root'
            })
        });
        
        this.loader.on("beforeload", function(treeLoader, node){
            //console.log(node);
            this.baseParams.depth = node.getDepth();
            if (this.baseParams.depth == 1) {
                this.baseParams.mark = node.attributes._id;
            }
            if (this.baseParams.depth == 2) {
                this.baseParams.mark = node.parentNode.attributes._id;
                this.baseParams.type = node.attributes._id;
            }
        }, this.loader);
        
        this.on('click', function(n){
            if (n.leaf) {
                m7.Layout.tabsPanel.activate(2);
                
                /*
                 var store = new Ext.data.JsonStore({
                 url: '/1.txt',
                 root: 'images',
                 fields: ['name', 'url', {
                 name: 'size',
                 type: 'float'
                 }, {
                 name: 'lastmod',
                 type: 'date',
                 dateFormat: 'timestamp'
                 }]
                 });
                 // store.load();
                 
                 var tpl = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{name}">', '<div class="thumb"><img src="{url}" title="{name}"></div>', '<span class="x-editable">{shortName}</span></div>', '</tpl>', '<div class="x-clear"></div>');
                 
                 machinePanel = new Ext.Panel({
                 frame: true,
                 //autoWidth: true,
                 autoHeight: true,
                 //margins: '2 2 5 2',
                 //bodyStyle: 'margin:0px 5px 0px 5px',
                 collapsible: true,
                 layout: 'fit',
                 width: '500',
                 title: 'Simple DataView (0 items selected)',
                 
                 items: [{
                 xtype: 'fieldset',
                 title: 'Технические характеристики',
                 collapsible: true,
                 autoHeight: true,
                 defaults: {
                 width: 210
                 },
                 defaultType: 'textfield',
                 items: [{
                 xtype: 'label',
                 html: 'sdfsdfsadfasdffffffffffffddddddddddddddddddddddddddddddddddddf<p>sdfsdf</p>sdgfsdfgdsfg'
                 }]
                 }, new Ext.DataView({
                 store: store,
                 tpl: tpl,
                 autoHeight: true,
                 multiSelect: true,
                 overClass: 'x-view-over',
                 
                 //itemSelector: 'div.thumb-wrap',
                 emptyText: 'No images to display',
                 
                 //plugins: [new Ext.DataView.DragSelector()],
                 
                 prepareData: function(data){
                 data.shortName = Ext.util.Format.ellipsis(data.name, 15);
                 data.sizeString = Ext.util.Format.fileSize(data.size);
                 data.dateString = data.lastmod.format("m/d/Y g:i a");
                 return data;
                 },
                 
                 listeners: {
                 selectionchange: {
                 fn: function(dv, nodes){
                 //var l = nodes.length;
                 //var s = l != 1 ? 's' : '';
                 //panel.setTitle('Simple DataView (' + l + ' item' + s + ' selected)');
                 }
                 }
                 }
                 })]
                 });
                 */
                //  machinePanel.render('tehnika-panel');
                //  m7.Layout.tabsPanel.doLayout();
            }
        });
        m7.TechTree.superclass.initComponent.call(this);
    }
});

m7.ModulesTree = Ext.extend(Ext.tree.TreePanel, {
    initComponent: function(){
        // This is an inner body element within the Details panel created to provide a "slide in" effect
        // on the panel body without affecting the body's box itself. This element is created on
        // initial use and cached in this var for subsequent access.
        var detailEl;
        
        Ext.apply(this, {
            id: 'tree-panel',
            border: false,
            animate: false,
            iconCls: 'ux-icon-application',
            tbar: [{
                id: 'button-bricks',
                text: 'Расходники',
                iconCls: 'ux-icon-bricks',
                hidden: true
            }],
            bodyStyle: 'padding: 0px;',
            height: 405,
            minSize: 150,
            autoScroll: true,
            rootVisible: false,
            singleExpand: true,
            useArrows: true,
            loader: new Ext.tree.TreeLoader({
                dataUrl: 'ws.php?cmd=modules'
            }),
            root: new Ext.tree.AsyncTreeNode({
                id: 'root'
            })
        });
        this.loader.on('load', function(){
        
        }, this);
        // Assign the changeLayout function to be called on tree node click.
        this.on('click', function(n){
            if (n.getDepth() == 2) {
                Ext.getCmp('button-bricks').enable();
            }
            else {
                Ext.getCmp('button-bricks').disable();
            }
            if (n.getDepth() >= 4) {
                window.location.hash = n.getPath() + '~' + n.attributes.page;
            }
            Ext.state.Manager.set('node', n.id);
            
            var selectedNode = n;
            while (selectedNode && selectedNode.id != 'root') {
                if (selectedNode.getDepth() == 2 && Ext.getCmp('modelselection')) {
                    Ext.getCmp('modelselection').setValue(selectedNode.attributes.part_name);
                    m7.searchGrid.store.baseParams.model = selectedNode.attributes.part_name;
                }
                selectedNode = selectedNode.parentNode;
            }
            var sn = this.selModel.selNode || {}; // selNode is null on initial selection
            if (n.id != sn.id) {
                if (n.leaf) {
                    //var image = "<img width='600'  src='/src/src/" + n.attributes.page + "'/>";
                    // Ext.getCmp('start-panel').body.dom.innerHTML = image;
                    //Ext.getCmp('content-panel').getLayout().setActiveItem(0);
                    
                    m7.Layout.tabsPanel.activate(1);
                    m7.Layout.tabsPanel.doLayout();
                    
                    m7.Layout.startPage.setImage(n.attributes.page);
                    
                    
                    //Ext.getCmp('card-tabs-panel').activate(n.id + '-image-panel');
                    
                    Ext.getCmp('east-panel').expand();
                    m7.PartsList.store.load({
                        params: {
                            parent_id: n.id
                        }
                    });
                }
                else {
                    n.expand();
                    Ext.getCmp('east-panel').collapse();
                }
            }
        });
        m7.ModulesTree.superclass.initComponent.call(this);
    }
});

m7.QuestionWindow = Ext.extend(Ext.Window, {
    initComponent: function(){
        Ext.apply(this, {
            title: 'Задать вопрос',
            layout: 'fit',
            modal: true,
            buttonAlign: 'right',
            width: 620,
            height: 390,
            border: false,
            items: new Ext.FormPanel({
                monitorValid: true,
                labelAlign: 'top',
                buttonAlign: 'right',
                autoScroll: true,
                frame: true,
                layout: 'form',
                title: 'Онлайн',
                bodyStyle: 'padding:5px 5px 0',
                //width: 600,
                items: [{
                    xtype: 'textfield',
                    allowBlank: true,
                    fieldLabel: 'Контакт',
                    name: 'contact',
                    anchor: '98%'
                }, {
                    xtype: 'textarea',
                    fieldLabel: 'Вопрос',
                    name: 'question',
                    height: 200,
                    anchor: '98%'
                }],
                
                buttons: [{
                    text: '<b>Задать вопрос</b>',
                    formBind: true,
                    scope: this,
                    handler: function(s){
                        Ext.MessageBox.show({
                            title: 'Пожалуйста подождите',
                            msg: 'Отсылается запрос...',
                            progressText: 'Подождите...',
                            width: 300,
                            progress: true,
                            closable: false
                        });
                        
                        Ext.Ajax.request({
                            url: 'mail.php?cmd=question',
                            params: {
                                json: Ext.encode(this.items.get(0).form.getValues()),
                                location: window.location.href
                            },
                            scope: this,
                            success: function(r){
                                Ext.MessageBox.hide();
                                Ext.MessageBox.alert('Статус', 'Ваш запрос успешно отправлен.', function(){
                                
                                });
                                this.close();
                            }
                        });
                        
                    }
                }, {
                    text: 'Отмена',
                    scope: this,
                    handler: function(s){
                        this.close();
                    }
                }]
            }),
            iconCls: 'ux-icon-user_comment'
        });
        m7.QuestionWindow.superclass.initComponent.call(this);
    }
});

m7.CartWindow = Ext.extend(Ext.Window, {
    textCartTitle: 'Cart',
    textCartHint: 'To make an application please fill in all fields during the day, you will be contacted by the manager.',
    textCartName: 'First & last name',
    textCartPhone: 'Phone',
    textCartEmail: 'Email',
    textCartSerial: 'Serial',
    textCartCompany: 'Company',
    textCartComment: 'Comment',
    textCartSend: 'Send request',
    textCartCancel: 'Cancel',
    textCartClear: 'Clear cart',
    textCartTown: 'Town',
    initComponent: function(){
        var grid = new m7.CartGrid();
        Ext.apply(this, {
            //autoShow: true,
            title: this.textCartTitle,
            layout: 'fit',
            modal: true,
            buttonAlign: 'right',
            width: 640,
            height: 440,
            border: false,
            items: new Ext.FormPanel({
                monitorValid: true,
                labelAlign: 'top',
                buttonAlign: 'right',
                autoScroll: true,
                frame: true,
                title: this.textCartHint,
                bodyStyle: 'padding:5px 5px 0',
                width: 600,
                items: [{
                    layout: 'column',
                    items: [{
                        columnWidth: .5,
                        layout: 'form',
                        items: [{
                            xtype: 'textfield',
                            allowBlank: false,
                            fieldLabel: this.textCartName, //'пмя Фамилия',
                            name: 'first',
                            anchor: '95%',
                            value: m7.user ? m7.user : ''
                        }, {
                            xtype: 'textfield',
                            allowBlank: false,
                            fieldLabel: this.textCartEmail, //'Email',
                            name: 'email',
                            vtype: 'email',
                            anchor: '95%',
                            value: m7.user ? m7.email : ''
                        }, {
                            xtype: 'textfield',
                            //allowBlank: false,
                            fieldLabel: this.textCartTown, //'Город',
                            name: 'town',
                            anchor: '95%'
                        }]
                    }, {
                        columnWidth: .5,
                        layout: 'form',
                        items: [{
                            xtype: 'textfield',
                            allowBlank: true,
                            fieldLabel: this.textCartPhone, //'Телефон',
                            name: 'phone',
                            anchor: '95%'
                        }, {
                            xtype: 'textfield',
                            //allowBlank: false,
                            fieldLabel: this.textCartSerial, //'Серийный номер и модель Komatsu',
                            name: 'serial',
                            anchor: '95%'
                        }, {
                            xtype: 'textfield',
                            //allowBlank: false,
                            fieldLabel: this.textCartCompany, //'Фирма',
                            name: 'company',
                            anchor: '95%'
                        }]
                    }]
                }, {
                    xtype: 'textarea',
                    height: 50,
                    allowBlank: true,
                    fieldLabel: this.textCartComment, //'Комментарий',
                    name: 'comment',
                    anchor: '95%'
                }, grid, {
                    xtype: 'textfield',
                    allowBlank: true,
                    fieldLabel: 'Урл',
                    name: 'url',
                    value: window.location,
                    //disabled: true,
                    readOnly: true,
                    anchor: '95%'
                }],
                
                buttons: [{
                    text: '<b>' + this.textCartSend + '</b>', // '<b>Послать заявку</b>',
                    formBind: true,
                    scope: this,
                    handler: function(s){
                        var win = this;
                        Ext.MessageBox.show({
                            title: 'Пожалуйста подождите',
                            msg: 'Отсылается запрос...',
                            progressText: 'пнициализация...',
                            width: 300,
                            progress: true,
                            closable: false
                        });
                        
                        var parts = [];
                        grid.store.each(function(r){
                            parts.push(r.data);
                        });
                        
                        Ext.Ajax.request({
                            url: 'mail.php',
                            method: 'POST',
                            params: {
                                json: Ext.encode(win.items.get(0).form.getValues()),
                                parts: Ext.encode(parts)
                            },
                            scope: this,
                            success: function(r){
                                Ext.MessageBox.hide();
                                Ext.MessageBox.alert('Статус', 'Ваш запрос успешно отправлен.', function(){
                                    if (m7.user) {
                                        window.location = '/z_system2/sets_list_client.php';
                                    }
                                    else {
                                        Ext.state.Manager.set('m7.PartsGrid.Profile', win.items.get(0).form.getValues());
                                        Ext.state.Manager.set('m7.ClassesGrid.Stars', {});
                                        m7.Layout.refreshCart();
                                        m7.PartsList.store.reload();
                                        win.close();
                                    }
                                });
                            }
                        });
                        //win.close();
                    }
                }                /*, {
                 text: this.textCartCancel, // 'Отмена',
                 handler: function(s){
                 win.close();
                 }
                 }*/
                , {
                    text: this.textCartClear, //'Очистить корзину заявки',
                    handler: function(s){
                        Ext.state.Manager.set('m7.ClassesGrid.Stars', {});
                        m7.Layout.refreshCart();
                        m7.PartsList.store.reload();
                        win.close();
                    }
                }]
            }),
            iconCls: 'ux-icon-cart_go-png'
        });
        m7.CartWindow.superclass.initComponent.call(this);
    }
});

m7.SelectManufacturerWindow = Ext.extend(Ext.Window, {
    textTitle: 'Choosing a supplier',
    textSelect: 'Select',
    textCancel: 'Cancel',
    initComponent: function(){
    
        var grid = new m7.ManufactureGrid();
        //alert(this.part_number);
        
        grid.store.load({
            params: {
                part_number: this.part_number
            }
        });
        
        Ext.apply(this, {
            iconCls: 'ux-icon-lorry',
            title: this.textTitle, //'Выбор поставщика',
            layout: 'fit',
            modal: true,
            buttonAlign: 'right',
            width: 740,
            height: 240,
            border: false,
            items: grid,
            buttons: [{
                'text': '<b>' + this.textSelect + '</b>', // '<b>Выбрать</b>',
                scope: this,
                id: 'select_button',
                disabled: true,
                handler: function(s){
                    //zzz = grid;
                    var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
                    var data = grid.selModel.getSelected().data;
                    data.star = 'set';
                    //data.basket_add = 'ux-icon-money';
                    // record.commit();
                    stars[data.part_number] = data;
                    // stars[rec.data.part_number] = rec.data;
                    Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
                    
                    
                    this.record.data.basket_add = 'ux-icon-money';
                    this.record.commit();
                    // rec.commit();
                    m7.Layout.refreshCart();
                    this.close();
                }
            }, {
                'text': this.textCancel, //'Отменить',
                scope: this,
                handler: function(s){
                    this.close();
                }
            }]
        });
        
        m7.SelectManufacturerWindow.superclass.initComponent.call(this);
    }
});

m7.ManufactureGrid = Ext.extend(Ext.grid.EditorGridPanel, {
    textTitle: 'Title',
    textClass: 'Class',
    textSearch: 'Search',
    textCreate: 'Create',
    textEdit: 'Edit',
    textDelete: 'Delete',
    textCount: 'Obj',
    textPartNumber: 'Part Number',
    textPartName: 'Part Name',
    textPartCountry: 'Part Country',
    textPartManufacturer: 'Part Manufacturer',
    textPartPrice: 'Part Price',
    textPartTime: 'Part Time',
    
    onRowAction: function(grid, record, action, row, col){
    },
    onValidateEdit: function(e){
    },
    onRowDblClick: function(grid, rowIndex, e){
    },
    onRowClick: function(grid, rowIndex, e){
        // Ext.getCmp('select_button').enable();
    },
    onRowSelect: function(sm, rowIdx, r){
        Ext.getCmp('select_button').enable();
    },
    
    onButtonToggle: function(b){
    },
    onBeforeLoad: function(s){
    },
    onLoad: function(s){
        if (s.getCount() == 1) 
            this.getSelectionModel().selectRow(0);
    },
    initComponent: function(){
    
        this.store = new Ext.data.Store({
            url: 'ws.php?f=SelectManufacturer',
            reader: new Ext.data.JsonReader({
                totalRecords: '@total'
            }, ['star', 'part_item', 'part_name', 'part_number', 'part_price', 'part_serial', 'part_count', 'part_manufacturer', 'part_time'])
        });
        
        this.rowactions = new Ext.ux.grid.RowActions({
            actions: [{
                iconCls: 'ux-icon-cart_go',
                qtip: 'Выбрать поставщика'
            }, {
                iconCls: 'ux-icon-delete',
                qtip: 'Удалить из корзины'
            }],
            widthIntercept: Ext.isSafari ? 4 : 2,
            id: 'actions'
        });
        this.rowactions.on('action', this.onRowAction, this);
        
        Ext.apply(this, {
            trackMouseOver: true,
            clicksToEdit: 1,
            loadMask: true,
            height: 500,
            border: false,
            stripeRows: true,
            selModel: new Ext.grid.RowSelectionModel({
                singleSelect: true
            }),
            columns: [{
                id: '№',
                header: '№',
                width: 35,
                sortable: true,
                hideable: false,
                renderer: function(value, meta, record, rowIndex, colIndex, store){
                    var num = 0;
                    store.each(function(r){
                        if (r._groupId == record._groupId) {
                            num++;
                        }
                        return record != r;
                    });
                    return num;
                }
            }, {
                header: this.textPartNumber, //'Кат. номер'
                width: 95,
                dataIndex: 'part_number',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartName, //'Название'
                dataIndex: 'part_name',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartCountry, //'Страна производства'
                width: 120,
                dataIndex: 'part_country',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartManufacturer, //'Производитель'
                dataIndex: 'part_manufacturer',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartPrice, //'Цена'
                dataIndex: 'part_price',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartTime, //'Срок'
                dataIndex: 'part_time',
                sortable: true,
                hideable: false
            }],
            plugins: [],
            bbar: [],
            viewConfig: {
                forceFit: true
            
            },
            listeners: {
                load: function(s){
                }
            }
        
        });
        
        if (Ext.isIE6) {
            this.width = 300;
        };
        
        
        
        this.on('validateedit', this.onValidateEdit, this);
        this.on('rowclick', this.onRowClick, this);
        this.on('rowdblclick', this.onRowDblClick, this);
        this.getSelectionModel().on('rowselect', this.onRowSelect, this);
        
        
        
        this.store.on("load", this.onLoad, this);
        //this.store.on("beforeload", this.onBeforeLoad, this);
        //this.store.load();
        
        
        m7.ManufactureGrid.superclass.initComponent.call(this);
    }
});

m7.CartGrid = Ext.extend(Ext.grid.EditorGridPanel, {
    textTitle: 'Title',
    textClass: 'Class',
    textSearch: 'Search',
    textCreate: 'Create',
    textEdit: 'Edit',
    textDelete: 'Delete',
    textCount: 'Obj',
    textPartNumber: 'Part Number',
    textPartName: 'Part Name',
    textPartPrice: 'Part Price',
    //textPartCountry: 'Part Country',
    //textPartManufacturer: 'Part Manufacturer',
    textPartCount: 'Part Count',
    textPartSerial: 'Part Serial',
    onRowAction: function(grid, record, action, row, col){
        if (action == 'ux-icon-lorry') {
            var win = new m7.SelectManufacturerWindow({
                'part_number': record.data.part_number
            });
            win.on('close', function(){
                this.data = [];
                var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
                for (var s in stars) {
                    if (stars[s]) {
                        this.data.push([stars[s].part_name_rus ? stars[s].part_name_rus : stars[s].part_name, stars[s].part_number, stars[s].part_count, stars[s].part_price]);
                    }
                }
                grid.store.loadData(this.data);
            });
            win.show();
        }
        if (action == 'ux-icon-delete') {
            Ext.MessageBox.confirm('Confirm', 'Удалить из корзины <b>' + record.data.part_name + '/' + record.data.part_number + '</b>?', function(btn){
                if (btn == 'yes') {
                    grid.store.remove(record);
                    
                    var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
                    delete stars[record.data.part_number];
                    Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
                    m7.PartsList.store.reload();
                    m7.Layout.refreshCart();
                }
            });
            
        }
        
    },
    onValidateEdit: function(e){
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        
        if (stars[e.record.data.part_number]) {
            stars[e.record.data.part_number].part_count = e.value;
        }
        Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
        
        (function(){
            e.record.commit();
        }).defer(100);
    },
    onRowDblClick: function(grid, rowIndex, e){
    
    },
    onRowClick: function(grid, rowIndex, e){
    
    },
    onButtonToggle: function(b){
    },
    onBeforeLoad: function(s){
        //this.lastSelectedRow = this.store.indexOf(this.selModel.getSelected());
    },
    onLoad: function(s){
        this.view.refresh();
    },
    initComponent: function(){
        this.data = [];
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        for (var s in stars) {
            if (stars[s] && stars[s].star != 'unset') {
                this.data.push([stars[s].part_name_rus ? stars[s].part_name_rus : stars[s].part_name, stars[s].part_number, stars[s].part_count, stars[s].part_price]);
            }
        }
        
        this.store = new Ext.data.SimpleStore({
            fields: [{
                name: 'part_name'
            }, {
                name: 'part_number'
            }, {
                name: 'part_count'
            }, {
                name: 'part_price'
            }]
        });
        
        this.rowactions = new Ext.ux.grid.RowActions({
            actions: [            /*{
             iconCls: 'ux-icon-lorry',
             qtip: 'Выбрать поставщика'
             }, */
            {
                iconCls: 'ux-icon-delete',
                qtip: 'Удалить из корзины'
            }],
            widthIntercept: Ext.isSafari ? 4 : 2,
            id: 'actions'
        });
        this.rowactions.on('action', this.onRowAction, this);
        
        Ext.apply(this, {
            clicksToEdit: 1,
            loadMask: {
                msg: 'Идёт загрузка...'
            },
            id: 'classes',
            region: 'west',
            anchor: '95%',
            height: 150,
            border: false,
            stripeRows: true,
            selModel: new Ext.grid.RowSelectionModel({
                singleSelect: true
            }),
            columns: [{
                id: '№',
                header: '№',
                width: 35,
                sortable: true,
                hideable: false,
                renderer: function(value, meta, record, rowIndex, colIndex, store){
                    var num = 0;
                    store.each(function(r){
                        if (r._groupId == record._groupId) {
                            num++;
                        }
                        return record != r;
                    });
                    return num;
                }
            }, {
                header: this.textPartName, //'Название',
                width: 140,
                dataIndex: 'part_name',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartNumber, //'Кат. номер',
                width: 95,
                dataIndex: 'part_number',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartCount, //'Кол-во',
                width: 60,
                dataIndex: 'part_count',
                sortable: true,
                menuDisabled: true,
                hideable: false,
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false
                })
            },            /*{
             header: this.textPartPrice, //'Цена',
             width: 95,
             hidden: true,
             dataIndex: 'part_price',
             sortable: true,
             hideable: false
             },*/
            this.rowactions],
            plugins: [this.rowactions],
            bbar: [],
            viewConfig: {
                forceFit: true,
                emptyText: 'Ваша корзина пуста'
            },
            listeners: {
                load: function(s){
                }
            }
        
        });
        
        if (Ext.isIE) {
            this.width = 600;
        };
        
        this.on('beforeedit', function(e){
            //alert('');
            // this.toggleStar(e.record);
        }, this);
        
        this.on('validateedit', this.onValidateEdit, this);
        this.on('rowclick', this.onRowClick, this);
        this.on('rowdblclick', this.onRowDblClick, this);
        
        
        //this.store.on("load", this.onLoad, this);
        //this.store.on("beforeload", this.onBeforeLoad, this);
        this.store.loadData(this.data);
        
        
        m7.CartGrid.superclass.initComponent.call(this);
    }
});

m7.PartsGrid = Ext.extend(Ext.grid.EditorGridPanel, {
    textTitle: 'Title',
    textClass: 'Class',
    textSearch: 'Search',
    textCreate: 'Create',
    textEdit: 'Edit',
    textDelete: 'Delete',
    textCount: 'Obj',
    textPartNumber: 'Part Number',
    textPartName: 'Part Name',
    textGetPrices: 'Get more prices and delivery terms',
    textSearchPart: 'Search by part №',
    //textPartCountry: 'Part Country',
    //textPartManufacturer: 'Part Manufacturer',
    textPartCount: 'Part Count',
    textPartSerial: 'Part Serial',
    toggleStar: function(rec){
        if (rec.data.star != 'set') {
            rec.data.star = 'set';
        }
        else {
            rec.data.star = 'unset';
        }
        
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        
        stars[rec.data.part_number] = rec.data;
        Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
        
        rec.commit();
        m7.Layout.refreshCart();
    },
    onValidateEdit: function(e){
        if (e.record.data.star != 'set') {
            this.toggleStar(e.record);
        }
        
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        
        if (stars[e.record.data.part_number]) {
            stars[e.record.data.part_number].part_count = e.value;
        }
        Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
        e.record.commit();
        m7.Layout.refreshCart();
    },
    
    onRowClick: function(grid, rowIndex, e){
        m7.PartsList.getTopToolbar().items.get(0).enable();
        m7.PartsList.getTopToolbar().items.get(1).enable();
    },
    onButtonToggle: function(b){
    },
    onBeforeLoad: function(s){
        //this.lastSelectedRow = this.store.indexOf(this.selModel.getSelected());
    },
    onLoad: function(s){
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        s.each(function(r){
            if (stars[r.data.part_number]) {
                if (stars[r.data.part_number].star == 'set') {
                    r.data.star = 'set';
                    r.data.basket_add = 'ux-icon-cart_delete';
                }
                else {
                    r.data.star = 'unset';
                }
                r.data.part_count = stars[r.data.part_number].part_count;
                
                
            }
            r.commit(true);
        });
        this.view.refresh();
    },
    onRowDblClick: function(grid, rowIndex, e){
        var record = this.store.getAt(rowIndex);
        var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
        if (stars[record.data.part_number]) {
            this.onRowAction(grid, record, 'ux-icon-cart_delete', rowIndex, null);
        }
        else {
            this.onRowAction(grid, record, 'ux-icon-cart_add', rowIndex, null);
        }
    },
    onRowAction: function(grid, record, action, row, col){
        if (action == 'ux-icon-cart_add') {
            var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
            record.data.star = 'set';
            stars[record.data.part_number] = record.data;
            record.data.basket_add = 'ux-icon-cart_delete';
            record.commit();
            Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
            
            m7.Layout.refreshCart();
        }
        
        if (action == 'ux-icon-cart_delete') {
            var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
            record.data.basket_add = 'ux-icon-cart_add';
            record.commit();
            delete stars[record.data.part_number];
            Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
            
            m7.Layout.refreshCart();
        }
        
        if (action == 'ux-icon-money') {
            Ext.Ajax.request({
                url: 'z_system2/catalogue_client_open.php?num=' + record.data.part_number, //'ws.php?f=PredictPrice',
                params: {
                    json: Ext.encode(record.data)
                },
                scope: this,
                success: function(r){
                    var win = new Ext.Window({
                        title: 'Цена запчасти',
                        border: false,
                        modal: true,
                        layout: 'fit',
                        width: 800,
                        height: 320,
                        //plain: true,
                        html: r.responseText,
                        
                        //html: '<center style="padding-top: 15px"><b>Запчасть № ' + record.data.part_number + '<br />' + r.responseText + '</b></center>',
                        buttonAlign: 'center',
                        buttons: [{
                            text: this.textGetPrices,
                            handler: function(){
                                window.location = '/z_system2/autor.php';
                            }
                        }, {
                            text: 'Закрыть',
                            handler: function(){
                                win.hide();
                            }
                        }]
                    });
                    win.show();
                    
                    // Ext.MessageBox.alert('Цена', r.responseText);
                }
            });
        }
    },
    initComponent: function(){
        this.store = new Ext.data.Store({
            url: 'ws.php?f=PartList',
            reader: new Ext.data.JsonReader({
                totalRecords: '@total'
            }, ['star', 'part_item', 'part_name_rus', 'part_number', 'part_serial', 'part_count', 'basket_add'])
        });
        
        //this.store.setDefaultSort('part_item', "ASC");
        
        this.rowactions = new Ext.ux.grid.RowActions({
            actions: [{
                iconIndex: 'basket_add',
                iconCls: 'ux-icon-cart_add',
                qtip: 'Добавить в корзину'
            }, {
                iconCls: 'ux-icon-money',
                qtip: 'Узнать цену'
            }],
            widthIntercept: Ext.isSafari ? 4 : 2
        });
        this.rowactions.on('action', this.onRowAction, this);
        
        //var fullname = Ext.state.Manager.get('fullname', null);
        
        Ext.apply(this, {
            clicksToEdit: 1,
            loadMask: {
                msg: 'Идёт загрузка...'
            },
            id: 'classes',
            region: 'west',
            //height: 500,
            border: false,
            stripeRows: true,
            selModel: new Ext.grid.RowSelectionModel({
                singleSelect: true
            }),
            columns: [this.rowactions,            /*{
             dataIndex: 'star',
             width: 25,
             hideable: false,
             sortable: false,
             menuDisabled: true,
             renderer: function(val){
             var star = val ? val : 'unset';
             return '<div class="ux-icon-star-' + star + ' icon-property" />';
             }    textPartNumber: 'Part Number',
             textPartName: 'Part Name',
             textPartCountry: 'Part Country',
             textPartManufacturer: 'Part Manufacturer',
             textPartPrice: 'Part Price',
             textPartTime: 'Part Time',
             },*/
            {
                id: 'part_item',
                header: '№',
                width: 35,
                dataIndex: 'part_item',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartName, //'Название',
                width: 140,
                dataIndex: 'part_name_rus',
                sortable: true,
                hideable: false
            }, {
                header: this.textPartNumber, //'Кат. номер',
                width: 95,
                dataIndex: 'part_number',
                sortable: true,
                hideable: false,
                renderer: function(v, params, record){
                    return v;
                    
                    if (!m7.user) {
                        return v.substring(0, v.length - 4) + '****';
                    }
                    else {
                        return v;
                    }
                }
            }, {
                header: this.textPartSerial, //'Серия',
                width: 120,
                //hidden: true,
                dataIndex: 'part_serial',
                sortable: true,
                hideable: true
            }, {
                header: this.textPartCount, //'Кол-во',
                width: 60,
                dataIndex: 'part_count',
                sortable: true,
                menuDisabled: true,
                hideable: false,
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false
                })
            }],
            plugins: [this.rowactions],
            tbar: [{
                text: this.textSearchPart,
                iconCls: 'ux-icon-time_add',
                disabled: true,
                scope: this,
                handler: function(s){
                    //zzz = this;
                    var rec = this.getSelectionModel().getSelected();
                    if (rec) {
                        m7.Layout.tabsPanel.activate(1);
                        m7.searchGrid.searchplugin.field.setValue(rec.data.part_number)
                        m7.searchGrid.searchplugin.onTriggerSearch();
                        //alert(sel.data.part_number);
                    }
                }
            }, {
                text: this.textGetPrices,
                iconCls: 'ux-icon-money',
                scope: this,
                handler: function(s){
                    window.location = '/z_system2/autor.php';
                }
            }],
            bbar: [],
            //layout: 'fit',
            viewConfig: {
                //forceFit: true,
                getRowClass: function(rec, idx, p, store){
                    if (rec.data.count == 0) {
                        return 'blight';
                    }
                    
                    if (m7.searchGrid.searchplugin.field && rec.data['part_number'] == m7.searchGrid.searchplugin.field.getValue()) {
                        return 'searched';
                    }
                }
            },
            listeners: {
                load: function(s){
                }
            }
        
        });
        
        if (Ext.isIE6) {
            this.width = 300;
        };
        
        /*this.on('render', function(){
         var clearButton = Ext.select('.x-form-clear-trigger');
         clearButton.on('click', function(s){
         this.starButton.toggle(false);
         }, this);
         }, this);*/
        this.on('beforeedit', function(e){
            //alert('');
            // this.toggleStar(e.record);
        
        }, this);
        this.on('validateedit', this.onValidateEdit, this);
        this.on('rowclick', this.onRowClick, this);
        this.on('rowdblclick', this.onRowDblClick, this);
        //this.getSelectionModel().on('rowselect', this.onRowSelect, this);
        
        
        this.store.on("load", this.onLoad, this);
        this.store.on("beforeload", this.onBeforeLoad, this);
        this.store.load();
        
        m7.PartsGrid.superclass.initComponent.call(this);
    }
});

m7.SearchGrid = Ext.extend(Ext.grid.GridPanel, {
    textPartNumber: 'Part Number',
    textPartName: 'Part Name',
    textPartSerial: 'Part Serial',
    textPartCount: 'Part Count',
    textPartCountry: 'Part Country',
    textPartMachine: 'Machine',
    textPartManufacturer: 'Part Manufacturer',
    textPartPrice: 'Part Price',
    textModel: 'Model',
    textPartTime: 'Part Time',
    textSearch: 'Search',
    textPerPage: 'per page',
    textDeleteSelected: 'Delete selected',
    textExample: 'For example:',
    textSearchAllModels: 'Search all models',
    onRowAction: function(grid, record, action, row, col){
        if (action == 'ux-icon-cart_add') {
            var stars = Ext.state.Manager.get('m7.ClassesGrid.Stars', {});
            //alert(record.data.part_count);// = 1 + record.data.count;
            record.data.star = 'set';
            stars[record.data.part_number] = record.data;
            record.data.basket_add = 'ux-icon-cart_delete';
            record.commit();
            Ext.state.Manager.set('m7.ClassesGrid.Stars', stars);
            m7.Layout.refreshCart();
        }
    },
    onDeleteObjects: function(params){
    },
    onLoad: function(params){
        Ext.select('a.machine-anchors').on('click', function(e){
            setStateByUrl(this.href);
            e.stopEvent();
            //return false;
        
        });
        //machine-anchors
    },
    onRefresh: function(){
    },
    onMetaChange: function(store, meta){
    },
    onColumnHeaderClick: function(colIndex, width){
    },
    onReset: function(){
    },
    onColumnResize: function(colIndex, width){
    },
    onHiddenChange: function(cm, colIndex, hidden){
    },
    onRender: function(){
        // call parent 
        m7.SearchGrid.superclass.onRender.apply(this, arguments);
    },
    initComponent: function(){
        this.store = new Ext.data.Store({
            url: '/ws.php?f=SearchParts',
            baseParams: {
                meta: true
            },
            reader: new Ext.data.JsonReader({
                root: 'data',
                totalProperty: 'total'
            
            }, ['machine', 'price', 'id', 'star', 'part_item', 'part_name', 'part_number', 'part_serial', 'part_count', 'basket_add']),
            //reader: new Ext.data.JsonReader(),
            remoteSort: true
        });
        Ext.Ajax.timeout = 200000;
        
        
        this.store.on("metachange", this.onMetaChange, this);
        this.store.on("load", this.onLoad, this);
        
        // create row actions
        this.rowactions = new Ext.ux.grid.RowActions({
            actions: [{
                iconIndex: 'basket_add',
                iconCls: 'ux-icon-cart_add',
                qtip: 'Add to cart'
            } //~ , {
            //~ iconCls: 'delete',
            //~ qtip: 'Delete Object'
            //~ }
            ],
            widthIntercept: Ext.isSafari ? 4 : 2,
            id: 'actions'
        });
        this.rowactions.on('action', this.onRowAction, this);
        
        this.pagesizer = new Ext.ux.PageSizePlugin({
            afterText: '',
            beforeText: '',
            sizes: [[10], [30], [50], [100]],
            comboCfg: {
                width: 50
            }
        });
        this.tbar = [];
        this.bbar = [{
            iconCls: 'ux-icon-car_delete',
            text: this.textSearchAllModels,
            //width: 250,
            handler: function(s){
                Ext.getCmp('modelselection').setValue();
            }
        }, {
            id: 'modelselection',
            disabled: true,
            xtype: 'textfield',
            width: 250
        }, new Ext.PagingToolbar({
            textPerPage: this.textPerPage,
            pageSize: 30,
            store: this.store,
            displayInfo: true,
            plugins: this.pagesizer
            //displayMsg: 'Displaying objects {0} - {1} of {2}',
            //emptyMsg: "No objects to display"
        })];
        
        /*  this.bbar = new Ext.PagingToolbar({
         textPerPage: this.textPerPage,
         pageSize: 15,
         store: this.store,
         displayInfo: true,
         plugins: this.pagesizer
         //displayMsg: 'Displaying objects {0} - {1} of {2}',
         //emptyMsg: "No objects to display"
         });*/
        // this.colModel = new Ext.grid.ColumnModel([]);
        //this.colModel.defaultSortable = true;
        
        this.store.setDefaultSort('node_id', "DESC");
        
        // Create Search Plugin
        this.searchplugin = new Ext.ux.grid.Search({
            searchText: this.textSearch,
            position: 'top',
            mode: 'remote',
            width: 200,
            iconCls: false,
            ///disableIndexes: true,
            dateFormat: 'm/d/Y',
            minLength: 2
        });
        
        Ext.apply(this, {
            //deferredRender: true,
            //layout: 'fit',
            autoHeight: true,
            autoWidth: true,
            //height: 300,
            //id: 'objects',
            //lazyrender: false,
            columns: [            /*{
             dataIndex: 'star',
             width: 25,
             fixed: true,
             hidden: true,
             hideable: false,
             sortable: false,
             menuDisabled: true,
             renderer: function(val){
             var star = val ? val : 'unset';
             return '<div class="ux-icon-star-' + star + ' icon-property" />';
             }
             }, */
            {
                id: 'part_number',
                header: this.textPartNumber,
                dataIndex: 'part_number',
                width: 100,
                fixed: true,
                sortable: false,
                menuDisabled: true,
                hideable: false
            }, {
                //width: 220,
                id: 'part_name',
                header: this.textPartName,
                dataIndex: 'part_name',
                sortable: false,
                menuDisabled: true,
                hideable: false
            }, {
                id: 'machine',
                header: this.textPartMachine,
                dataIndex: 'machine',
                sortable: false,
                menuDisabled: true,
                hideable: false
            }, {
                id: 'part_serial',
                header: this.textPartSerial,
                dataIndex: 'part_serial',
                sortable: false,
                hideable: false
            }, {
                id: 'part_count',
                header: this.textPartCount,
                width: 50,
                fixed: true,
                dataIndex: 'part_count',
                sortable: false,
                menuDisabled: true,
                hideable: false
            }, {
                header: this.textPartPrice,
                dataIndex: 'price',
                sortable: true,
                hidden: true,
                menuDisabled: true,
                hideable: true
            }, this.rowactions],
            stripeRows: true,
            border: false,
            viewConfig: {
                forceFit: true,
                emptyText: this.textExample + ' <a id="example-search-1" href="javascript:;">20Y-970-6450</a>'
            },
            plugins: [this.searchplugin, this.rowactions],
            loadMask: true
        });
        
        this.on('render', function(){
            (function(){
                m7.searchGrid.view.refresh();
                Ext.get('example-search-1').on('click', function(){
                    //zzz = this;
                    m7.searchGrid.searchplugin.field.setValue(this.dom.innerHTML);
                    m7.searchGrid.searchplugin.onTriggerSearch();
                });
            }).defer(300);
        }, this);
        
        m7.SearchGrid.superclass.initComponent.call(this);
    }
});

Ext.ux.PageSizePlugin = function(){
    Ext.ux.PageSizePlugin.superclass.constructor.call(this, {
        store: new Ext.data.SimpleStore({
            fields: ['text', 'value'],
            data: [['10', 10], ['25', 25], ['50', 50], ['100', 100]]
        }),
        mode: 'local',
        displayField: 'text',
        valueField: 'value',
        editable: false,
        allowBlank: false,
        triggerAction: 'all',
        width: 50
    });
};
Ext.extend(Ext.ux.PageSizePlugin, Ext.form.ComboBox, {
    textPerPage: 'на странице',
    init: function(paging){
        if (paging.textPerPage) {
            this.textPerPage = paging.textPerPage;
        }
        paging.on('render', this.onInitView, this);
    },
    onInitView: function(paging){
        paging.add('-', this, this.textPerPage);
        this.setValue(paging.pageSize);
        this.on('select', this.onPageSizeChanged, paging);
    },
    onPageSizeChanged: function(combo){
        this.pageSize = parseInt(combo.getValue());
        this.doLoad(0);
    }
});

Ext.ux.PanPanel = Ext.extend(Ext.Panel, {
    constructor: function(config){
        config.autoScroll = false;
        Ext.ux.PanPanel.superclass.constructor.apply(this, arguments);
    },
    onRender: function(){
        Ext.ux.PanPanel.superclass.onRender.apply(this, arguments);
        // this.body.appendChild(this.client);
        // this.client = Ext.get(this.client);
        // this.client.on('mousedown', this.onMouseDown, this);
        // this.client.setStyle('cursor', 'move');
    },
    onMouseDown: function(e){
        e.stopEvent();
        this.mouseX = e.getPageX();
        this.mouseY = e.getPageY();
        Ext.getBody().on('mousemove', this.onMouseMove, this);
        Ext.getDoc().on('mouseup', this.onMouseUp, this);
        //this.clientel.addClass('closedhand');
        this.clientel.replaceClass('openhand', 'closedhand');
    },
    onMouseMove: function(e){
        e.stopEvent();
        var x = e.getPageX();
        var y = e.getPageY();
        if (e.within(this.body)) {
            var xDelta = x - this.mouseX;
            var yDelta = y - this.mouseY;
            this.body.dom.scrollLeft -= xDelta;
            this.body.dom.scrollTop -= yDelta;
        }
        this.mouseX = x;
        this.mouseY = y;
    },
    onMouseUp: function(e){
        Ext.getBody().un('mousemove', this.onMouseMove, this);
        Ext.getDoc().un('mouseup', this.onMouseUp, this);
        this.clientel.replaceClass('closedhand', 'openhand');
    },
    setImage: function(imgsrc, w, h, st, sl, sz){
        //alert();
        // var body = this.body;
        var ext = imgsrc.substring(imgsrc.lastIndexOf(".") + 1);
        if (ext == 'htm') {
            Ext.Ajax.request({
                scope: this,
                url: '/src/htm/' + imgsrc,
                success: function(r){
                    this.body.dom.innerHTML = r.responseText;
                }
            });
            return;
        }
        this.body.dom.innerHTML = '';
        this.newimg = document.createElement('img');
        
        this.newimg.src = "/src/scr/" + imgsrc;
        
        this.body.appendChild(this.newimg);
        this.clientel = Ext.get(this.newimg);
        this.clientel.originalWidth = w;
        this.clientel.on('mousedown', this.onMouseDown, this);
        
        this.clientel.addClass('openhand');
        
        if (!Ext.isIE) {
            this.newimg.onload = this.moveImage(st, sl);
        }
        
        if (sz < 100) {
            this.clientel.setWidth(this.clientel.originalWidth * sz / 100);
        }
        
        var newHeight = 750;
        this.clientel.setHeight(newHeight);
        if (Ext.isIE) {
            var newWidth = this.clientel.getWidth() * newHeight / this.clientel.getHeight();
            this.clientel.setWidth(newWidth);
        }
    },
    moveImage: function(st, sl){
        this.body.dom.scrollTop = st;
        this.body.dom.scrollLeft = sl;
    },
    shiftImage: function(st, sl){
        this.body.dom.scrollTop += st;
        this.body.dom.scrollLeft += sl;
    }
});
/*
 Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node){
 if (!node) {
 return;
 }
 var s = HTMLElement.prototype.toString.call(node);
 if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
 return;
 };
 return node.nodeType == 3 ? node.parentNode : node;
 }
 : function(node){
 return node && node.nodeType == 3 ? node.parentNode : node;
 };
 */
Ext.notice = function(){
    var msgCt;
    var allownew = true;
    
    function createBox(t, s){
        //left:65% !important;top:100px;width:250px;z-index: 9999 !important;
        return ['<div style="" class="msg">', '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>', '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', '</div>'].join('');
    }
    return {
        msg: function(title, format){
            if (!allownew) 
                return;
            
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(document.body, {
                    id: 'msg-div'
                }, true);
            }
            
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {
                html: createBox(title, s)
            }, true);
            
            msgCt.alignTo(document, 't-t');
            msgCt.setLeft(Ext.getCmp('menu_basket').getEl().getLeft() - (Ext.isIE ? 85 : 15));
            //msgCt.setRight(document.width - 270);
            
            msgCt.setTop(45);
            msgCt.setStyle('z-index', 9999);
            msgCt.setStyle('width', 250);
            msgCt.setStyle('display', 'block');
            
            m.slideIn('t').pause(2).ghost("t", {
                remove: true
            });
            
            allownew = false;
            
            (function(){
                allownew = true;
            }).defer(2000);
        },
        
        init: function(){
            var lb = Ext.get('lib-bar');
            if (lb) {
                lb.show();
            }
        }
    };
}();

// vim: ts=4:sw=4:nu:fdc=2:nospell
/**
 * Ext.ux.IconCombo Extension Class for Ext 2.x Library
 *
 * @author  Ing. Jozef Sakalos
 * @version $Id: Ext.ux.IconCombo.js 617 2007-12-20 11:29:56Z jozo $
 *
 * @class Ext.ux.IconCombo
 * @extends Ext.form.ComboBox
 */
Ext.ux.IconCombo = Ext.extend(Ext.form.ComboBox, {
    initComponent: function(){
    
        Ext.apply(this, {
            tpl: '<tpl for=".">' +
            '<div class="x-combo-list-item ux-icon-combo-item ' +
            '{' +
            this.iconClsField +
            '}">' +
            '{' +
            this.displayField +
            '}' +
            '</div></tpl>'
        });
        
        // call parent initComponent
        Ext.ux.IconCombo.superclass.initComponent.call(this);
        
    }, // end of function initComponent
    onRender: function(ct, position){
        // call parent onRender
        Ext.ux.IconCombo.superclass.onRender.call(this, ct, position);
        
        // adjust styles
        this.wrap.applyStyles({
            position: 'relative'
        });
        this.el.addClass('ux-icon-combo-input');
        
        // add div for icon
        this.icon = Ext.DomHelper.append(this.el.up('div.x-form-field-wrap'), {
            tag: 'div',
            style: 'position:absolute'
        });
    }, // end of function onRender
    setIconCls: function(){
        var rec = this.store.query(this.valueField, this.getValue()).itemAt(0);
        if (rec) {
            this.icon.className = 'ux-icon-combo-icon ' + rec.get(this.iconClsField);
        }
    }, // end of function setIconCls
    setValue: function(value){
        Ext.ux.IconCombo.superclass.setValue.call(this, value);
        this.setIconCls();
    } // end of function setValue
});

// register xtype
Ext.reg('iconcombo', Ext.ux.IconCombo);

// Array data for the grids
Ext.grid.dummyData = [['3m Co', 71.72, 0.02, 0.03, '9/1 12:00am', 'Manufacturing'], ['Alcoa Inc', 29.01, 0.42, 1.47, '9/1 12:00am', 'Manufacturing'], ['Altria Group Inc', 83.81, 0.28, 0.34, '9/1 12:00am', 'Manufacturing'], ['American Express Company', 52.55, 0.01, 0.02, '9/1 12:00am', 'Finance'], ['American International Group, Inc.', 64.13, 0.31, 0.49, '9/1 12:00am', 'Services'], ['AT&T Inc.', 31.61, -0.48, -1.54, '9/1 12:00am', 'Services'], ['Boeing Co.', 75.43, 0.53, 0.71, '9/1 12:00am', 'Manufacturing'], ['Caterpillar Inc.', 67.27, 0.92, 1.39, '9/1 12:00am', 'Services'], ['Citigroup, Inc.', 49.37, 0.02, 0.04, '9/1 12:00am', 'Finance'], ['E.I. du Pont de Nemours and Company', 40.48, 0.51, 1.28, '9/1 12:00am', 'Manufacturing'], ['Exxon Mobil Corp', 68.1, -0.43, -0.64, '9/1 12:00am', 'Manufacturing'], ['General Electric Company', 34.14, -0.08, -0.23, '9/1 12:00am', 'Manufacturing'], ['General Motors Corporation', 30.27, 1.09, 3.74, '9/1 12:00am', 'Automotive'], ['Hewlett-Packard Co.', 36.53, -0.03, -0.08, '9/1 12:00am', 'Computer'], ['Honeywell Intl Inc', 38.77, 0.05, 0.13, '9/1 12:00am', 'Manufacturing'], ['Intel Corporation', 19.88, 0.31, 1.58, '9/1 12:00am', 'Computer'], ['International Business Machines', 81.41, 0.44, 0.54, '9/1 12:00am', 'Computer'], ['Johnson & Johnson', 64.72, 0.06, 0.09, '9/1 12:00am', 'Medical'], ['JP Morgan & Chase & Co', 45.73, 0.07, 0.15, '9/1 12:00am', 'Finance'], ['McDonald\'s Corporation', 36.76, 0.86, 2.40, '9/1 12:00am', 'Food'], ['Merck & Co., Inc.', 40.96, 0.41, 1.01, '9/1 12:00am', 'Medical'], ['Microsoft Corporation', 25.84, 0.14, 0.54, '9/1 12:00am', 'Computer'], ['Pfizer Inc', 27.96, 0.4, 1.45, '9/1 12:00am', 'Services', 'Medical'], ['The Coca-Cola Company', 45.07, 0.26, 0.58, '9/1 12:00am', 'Food'], ['The Home Depot, Inc.', 34.64, 0.35, 1.02, '9/1 12:00am', 'Retail'], ['The Procter & Gamble Company', 61.91, 0.01, 0.02, '9/1 12:00am', 'Manufacturing'], ['United Technologies Corporation', 63.26, 0.55, 0.88, '9/1 12:00am', 'Computer'], ['Verizon Communications', 35.57, 0.39, 1.11, '9/1 12:00am', 'Services'], ['Wal-Mart Stores, Inc.', 45.45, 0.73, 1.63, '9/1 12:00am', 'Retail'], ['Walt Disney Company (The) (Holding Company)', 29.89, 0.24, 0.81, '9/1 12:00am', 'Services']];

// add in some dummy descriptions
for (var i = 0; i < Ext.grid.dummyData.length; i++) {
    Ext.grid.dummyData[i].push('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.<br/><br/>Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt diam nec urna. Curabitur velit.');
}


