Ext.ns('Hdv.lot.detail');

Hdv.lot.detail.Window = Ext.extend(Ext.Window, {
    
    /**
     *----------------------------------------------------------------------
     *              Gestion des dimensions et resize
     *----------------------------------------------------------------------
     */

    /**
     * @cfg {bool} manualResize determine si c'est un resize manuel ou programme
     */
    manualResize: false,

    /**
     * Appele lorsqu'on change de thumb
     *
     * au load du store, le premier thumb est automatiquement selectionne.
     * Cette methode est donc appelee a ce moment la.
     *
     * @param Hdv.lot.detail.Gallery gallery la galerie de thumbs
     * @param Ext.data.Record record le thumb selectionne
     * @param HTMLElement node le html du thumb selectionne
     * @return void
     */
    onViewSelectionChange: function(gallery, record, node) {
        this._node = node;
        this._record = record;
        // on change de thumb, donc on redimensionne la photo
        (function(){this.getPanelPhoto().setPhoto(record, node, Hdv.lot.detail.Manager.getCache())}).defer(200, this);
    },

    /**
     * Appele lorsque le store de la galerie est loade
     *
     * @return void
     */
    onGalleryStoreLoad: function(){
        if (this.fetchAllInfoFromBd()) {
            var record = this.getPanelGallery().getDataViewStore().getAt(0);
            this.setLot(record);
        }
    },

    /**
     * Appele suite au redimensionnement de la grande image
     *
     * @param Object dims les valeurs de toutes les dimensions
     * @return void
     */
    onAfterPhotoResize: function(dims) {
        // on sauve les thumbs du lot qu'on est entrain de voir
        var records = this.getPanelGallery().getDataViewStore().getRange();
        Hdv.lot.detail.Manager.setCacheElement(records);
        // on set les dimensions de la window
        var width = this.getWidth() - dims.blankWidth;
        var height = this.getHeight() - dims.blankHeight;
        // on va resizer la window pour qu'elle fit a la photo. On ne veut
        // pas que ce resize recalcule une nouvelle fois les dims de la photo.
        this.manualResize = false;
        this.setSize(width, height);
        this.doLayout();
        this._mask.hide();
    },

    /**
     * Methode appelee au moment du resize du panel qui contient la grande
     * image
     *
     * @return void
     */
    onPanelPhotoResize: function() {
        var record = this.getCurrentRecord();
        // on va redimensionner la photo si c'est un resize manuel de la
        // fenetre.
        if (this.manualResize && record) {
            // on redimensionne la photo
            this.getPanelPhoto().setPhoto(record, this.getCurrentNode(), Hdv.lot.detail.Manager.getCache());
        }
        this.manualResize = true;
    },

    /**
     * Maximise en hauteur la dimension de la photo
     *
     * @return void
     */
    maximizePhoto: function() {
        var pos = this.getPosition(true);
        var scroll = Ext.fly(document).getScroll();
        this.setPosition(pos[0], scroll.top);
        var width = 1280;
        var height = Ext.lib.Dom.getViewportHeight();
        this.setSize(width, height);
        this.doLayout();
    },

    navigateTo: function(lotId, saleId) {
        this.currentLot = lotId;
        this.setPreviousAndNext(this.getLotConfig(lotId));
        var store = this.getPanelGallery().getDataViewStore();
        var visited = Hdv.lot.detail.Manager.isInCache(lotId, saleId);
        if (!visited) {
            Ext.apply(store.baseParams, {
                lot_id  : lotId,
                sale_id : saleId
            });
            this._mask.show();
            // on a pas encore visite ce lot, donc on va le chercher sur
            // le serveur
            store.load();
        } else {
            store.removeAll();
            store.add(visited);
            // on a deja visite le lot, donc on le recupere depuis le cache
            this.getPanelGallery().getDataView().select(0);
            this.setLot(visited[0]);
        }
    },





    /**
     *----------------------------------------------------------------------
     *                          Proprietes
     *----------------------------------------------------------------------
     */

    currentLot : null,




    /**
     *----------------------------------------------------------------------
     *                          Methodes publiques
     *----------------------------------------------------------------------
     */

    getCurrentRecord: function() {
        return this._record;
    },

    getCurrentNode: function() {
        return this._node;
    },

    getPanelGallery: function() {
        return this.getComponent(1);
    },

    getPanelPhoto: function() {
        return this.getComponent(0);
    },

    getPanelInfo: function() {
        return this.getComponent(2);
    },

    fetchAllInfoFromBd: function() {
        return this.storeParams.fetch_all_info;
    },

    getLotConfig: function(lotId) {
        return this.config.lots_group[lotId] || {};
    },

    show: function(lotId, saleId) {
        // si cette instance a deja ete ouverte et qu'on a navigue dedans, le
        // lot courant sera different du lot de base. Comme on a reclique sur
        // le lien pour voir le lot de base, on doit le recharger seulement si
        // le lot courant est different
        if (this.currentLot && lotId != this.currentLot) {
            this.navigateTo(lotId, saleId);
        } else {
            this.currentLot = lotId;
            this.setPreviousAndNext(this.getLotConfig(lotId));
        }
        Hdv.lot.detail.Window.superclass.show.call(this, this.initialConfig.animEl);
    },

    setPreviousAndNext: function(config) {
        this.disableBtnPrevious(!config.lot_previous_id);
        this.disableBtnNext(!config.lot_next_id);
    },

    disableBtnPrevious: function(disable) {
        this.btnPrevious.setDisabled(disable);
    },

    disableBtnNext: function(disable) {
        this.btnNext.setDisabled(disable);
    },

    setLot: function(record) {
        var tva_full = record.get('tva_full') ? '*' : '';
        this.setTitle(sprintf(this.config.wording.lot_detail_title, record.get('lot') + tva_full));
        this.getPanelInfo().setInfoBody(record);
        // on allume l'element html s'il existe
        var f = Ext.get('lot_tr_' + record.get('lot_id'));
        if (!f) {
            f = Ext.get('lot_div_' + record.get('lot_id'));
        }
        if (f) {
            f.highlight();
            // en test, pour le moment
            return;
            
            var scroll = Ext.fly(document).getScroll();
            var body_height = Ext.lib.Dom.getViewportHeight();
            var f_top = f.getTop();
            var f_height = f.getHeight();
            if (f_top + f_height > body_height + scroll.top) {
                window.scrollBy(scroll.left, f_height);
                var pos = this.getPosition(true);
                this.setPosition(pos[0], pos[1] + f_height);
            }
        }
    },




    /**
     *----------------------------------------------------------------------
     *              Initialisation
     *----------------------------------------------------------------------
     */

    initPanelPhoto: function() {
        return {
            config   : this.config,
            xtype    : 'hdvlotdetailphoto',
            region   : 'center',
            margins  : '4 2 2 4',
            header   : false,
            listeners: {
                afterresize: {scope: this, fn: this.onAfterPhotoResize},
                resize     : {scope: this, fn: this.onPanelPhotoResize}
            }
        }
    },

    initPanelGallery: function() {
        return {
            config     : this.config,
            xtype      : 'hdvlotdetailgallery',
            region     : 'south',
            margins    : '2 4 4 4',
            header     : false,
            height     : 150,
            storeParams: this.storeParams,
            listeners  : {
                viewselectionchange: {scope: this, fn: this.onViewSelectionChange},
                storeload          : {scope: this, fn: this.onGalleryStoreLoad}
            }
        }
    },

    initPanelInfo: function() {
        return {
            config    : this.config,
            infoEls   : this.infoEls,
            xtype     : 'hdvlotdetailinfo',
            region    : 'east',
            margins   : '4 4 2 2',
            width     : 220,
            listeners : {
                buttonorder: {scope: this, fn: function(){
                    
                }}
            }
        }
    },

    initTbar: function() {
        return [{
            text    : this.config.wording.lot_detail_info_menu_previous,
            iconCls : 'lot-item-previous',
            cls     : 'lot-item-btn',
            ref     : '../btnPrevious',
            scope   : this,
            handler : function() {
                var config = this.getLotConfig(this.currentLot);
                this.navigateTo(config.lot_previous_id, config.sale_previous_id);
            }
        },
        '-',
        {
            text    : this.config.wording.lot_detail_info_menu_next,
            iconCls : 'lot-item-next',
            cls     : 'lot-item-btn',
            ref     : '../btnNext',
            scope   : this,
            handler : function() {
                var config = this.getLotConfig(this.currentLot);
                this.navigateTo(config.lot_next_id, config.sale_next_id);
            }
        },
        '->',
        {
            text    : this.config.wording.lot_detail_info_menu_close,
            iconCls : 'lot-window-close',
            cls     : 'lot-item-btn',
            scope   : this,
            handler : function(){this.hide();}
        }];
    },

    initBbar: function() {
        return [
        '->',
        {
            text    : this.config.wording.lot_detail_info_menu_close,
            iconCls : 'lot-window-close',
            cls     : 'lot-item-btn',
            scope   : this,
            handler : function(){this.hide();}
        }];
    },

    initComponent: function() {
        var lot = '';
        if (!this.fetchAllInfoFromBd()) {
            var tds = this.infoEls.lot.select('td');
            lot = tds.item(1).dom.innerHTML;
        }

        Ext.applyIf(this, {
            modal        : false,
            title        : sprintf(this.config.wording.lot_detail_title, lot),
            layout       : 'border',
            iconCls      : 'lot-window',
            width        : 850,
            height       : 650,
            boxMaxHeight : 1280,
            boxMaxWidth  : 1280,
            boxMinHeight : 350,
            boxMinWidth  : 400,
            tbar         : this.initTbar(),
            bbar         : this.initBbar(),
            tools        : [{
                id     : 'maximize',
                scope  : this,
                handler: this.maximizePhoto
            }],
            items        : [
                this.initPanelPhoto(),
                this.initPanelGallery(),
                this.initPanelInfo()
            ]
        });

        Ext.apply(this, {
            closeAction: 'hide'
        });

        Hdv.lot.detail.Window.superclass.initComponent.call(this);

        this.on({
            render: {scope: this, single: true, fn: function(){
                this._mask = new Ext.LoadMask(this.bwrap, {msg: this.config.wording.message.wait.wait});
                this._mask.show();
                if (!this.fetchAllInfoFromBd()) {
                    this.getPanelInfo().setInfoBody();
                }
                // set le double-clic sur le header pour optimiser la taille
                this.header.on({
                    dblclick: {scope: this, fn: this.maximizePhoto}
                });
            }},
            show: {scope: this, fn: Hdv.lot.detail.Manager.enableKeyNav.createCallback(this)},
            hide: {scope: this, fn: Hdv.lot.detail.Manager.disableKeyNav.createCallback(this)}
        })
    }

});