/**
 * BQ.CarousselToolbar
 * @author Chris Scott
 * A special extension of Ext.PagingToolbar where the Panel's body gets rendered on top of the toolbar.
 * | | +-----+ +-----+ | |
 * |<| |thumb| |thumb| |>|  <-- prev/next buttons
 * | | +-----+ +-----+ | |
 * @param {Object} ct
 * @param {Object} position
 */
BQ.CarousselToolbar = Ext.extend(Ext.PagingToolbar, {

    onRender : function(ct, position){
        Ext.PagingToolbar.superclass.onRender.call(this, ct, position);

        this.first = this.addButton({
            tooltip: this.firstText,
            iconCls: "x-tbar-page-first",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["first"])
        });
        this.first.hide();

        this.prev = this.addButton({
            tooltip: this.prevText,
            ctCls: 'page-prev',
            iconCls: 'x-tbar-page-prev',
            disabled: false,
            handler: this.onClick.createDelegate(this, ["prev"])
        });

        /*
        this.add(this.beforePageText);
        this.field = Ext.get(this.addDom({
           tag: "input",
           type: "text",
           size: "3",
           value: "1",
           cls: "x-tbar-page-number"
        }).el);
        this.field.on("keydown", this.onPagingKeydown, this);
        this.field.on("focus", function(){this.dom.select();});
        this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
        this.field.setHeight(18);
        this.addSeparator();
        */
       this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
       this.afterTextEl.hide();

        this.field = Ext.get(this.addDom({
           tag: "input",
           type: "text",
           value: "1",
           cls: "x-tbar-page-number"
        }).el);
        this.field.hide();

        this.next = this.addButton({
            tooltip: this.nextText,
            ctCls: 'page-next',
            iconCls: "x-tbar-page-next",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["next"])
        });

        this.last = this.addButton({
            tooltip: this.lastText,
            iconCls: "x-tbar-page-last",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["last"])
        });
        this.last.hide();

        /*
        this.addSeparator();
        */

        this.loading = this.addButton({
            tooltip: this.refreshText,
            iconCls: "x-tbar-loading",
            handler: this.onClick.createDelegate(this, ["refresh"])
        });
        this.loading.hide();

        if(this.displayInfo){
            //this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'});
        }
        if(this.dsLoaded){
            this.onLoad.apply(this, this.dsLoaded);
        }
    }

});

/**
 * BQ.Caroussel
 * A typical Panel with DataView.  uses special CarousselToolbar.
 * @author Chris Scott
 */
BQ.Caroussel = Ext.extend(Ext.Panel, {
    frame: false,
    border: false,
    height: 68,
    title: App.t('phrase_other_results'),

    /**
     * @cfg {String} types
     * comma-separated list of Content types to display
     * eg: types: 'album, image, video'
     */
    types: null,

    /**
     * @cfg {Number} ownerId
     * To show Content from a specific user, set ownerId to $user_id
     */
    ownerId: null,

    /**
     * @cfg {String/Number} parentId
     * eg: to show all images of a particular album, parentId would be albumId
     */
    parentId: null,

    /**
     * @cfg {Number} pageSize [3]
     * Number of thumbs to show per page.
     */
    pageSize : 3,


    /**
     * @cfg {Number} contentId [3]
     * The id of the current content so that the search can filter it out.
     */
    contentId : null,

    /**
     * @cfg {boolean} navigateOnClick [true]
     * whether to navigate to new url on clicking an item
     */
    navigateOnClick : true,

    initComponent : function() {
        this.header = true;
        var view = this.build();
        var tbar = new BQ.CarousselToolbar({
            store: view.store,
            pageSize: this.pageSize,
            displayInfo: true
        });
        this.items = view;
        this.tbar = tbar;

        this.addClass('bq-caroussel');

        this.on('resize', function(p, aw, ah, rw, rh) {
            var pw = tbar.prev.el.getWidth();   // <-- [prev] btn width
            var nw = tbar.next.el.getWidth();   // <-- [next] btn width

            this.body.setHeight(ah);
            this.body.setWidth(aw);
            tbar.el.setHeight(ah);
            tbar.el.child('table').setHeight(ah);


            if (Ext.isIE) { //Need to manually change variables for IE with hard coded pw, nw vars and next/prev heights as it doesn't read them properly, or does so too fast
                var pw = 13;
                var nw = 13;
                this.body.alignTo(tbar.el, 'tl', [pw - 3, 0]); //added vertical offset because of image borders?
                this.body.setWidth(this.body.getWidth() - pw - nw + 6); // <-- set body width to lie between [prev][ -----  body ---- ][next]
                this.body.setHeight(100);
                this.el.setHeight(100);
                this.el.setStyle({overflow:'hidden'});
                tbar.prev.el.setHeight(100);
                tbar.next.el.setHeight(100);
            }
            else {
                if (Ext.isGecko2) { //in case its FF2
                    this.body.alignTo(tbar.el, 'tl', [pw - 3, 6]); //added vertical offset because of image borders?
                }
                else {//Other Browsers
                    this.body.alignTo(tbar.el, 'tl', [pw - 3, 5]); //added vertical offset because of image borders?
                }
                this.body.setWidth(this.body.getWidth() - pw - nw + 6); // <-- set body width to lie between [prev][ -----  body ---- ][next]
                this.body.setHeight(ah - 5); //added offset because of image borders?
                var hh = 0;
                if (this.header) {
                    hh = this.header.getHeight();
                }
                this.el.setHeight(hh + this.body.getHeight());
            }

        },this);

        // super
        BQ.Caroussel.superclass.initComponent.call(this);
    },

    build : function() {

        var Record = Ext.data.Record.create([
            {name: 'id', mapping: 'id'},
            {name: 'slug', mapping: '_slug'},
            {name: 'view', mapping: 'view'},
            {name: 'vote', mapping: 'vote'},
            {name: 'ownerId', mapping: 'ownerId'},
            {name: 'ownerUsername', mapping: 'ownerUsername'},
            {name: 'time_created', mapping:'_time_created'},
            {name: 'title', mapping: 'title'},
            {name: 'type', mapping: 'type'},
            {name: 'rating', mapping: 'rating'},
            {name: 'thumb', mapping: 'thumb_square'},
            {name: 'description', mapping:'description'},
            {name: 'regions', mapping:'regions'},
            {name: 'categories', mapping:'categories'},
            {name: 'seasons', mapping: 'seasons'},
            {name: 'file', mapping: 'file'},
            {name: 'tags', mapping: 'tags'},
            {name: 'encoded', mapping: 'encoded'},
            {name: 'thumb_normal', mapping: 'thumb_normal'}
        ]);


        var store = new Ext.data.Store({
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'data',
                id: 'id'
            }, Record),
            autoLoad: {
                params : {
                    limit: this.pageSize,
                    start: 0
                }
            },
            proxy: new Ext.data.HttpProxy({
                url: this.url,
                method: "GET"
            }),
            baseParams: {
                types: this.types,
                type: this.type,
                limit: this.pageSize,
                parentId: this.albumId,  // <-- album_id?
                ownerId: this.ownerId,     // <-- userId?
                query: this.query, //<-- add query?
                metadata: this.metadata, //<-- add metadata ?
                contentId: this.contentId // <-- the id of the current content
            }
        });

        //store.load();
        this.relayEvents(store, ['load']);

        var tpl = new Ext.XTemplate(
            '<tpl for=".">',
                    '<tpl if="thumb == null "><img id="media-{type}-{id}" class="bq-caroussel-media" src="{[BQJSConfig["root"]]}/static/images/defaults/photo/thumb_square.gif" /></tpl>',
                    '<tpl if="thumb"><img id="media-{type}-{id}" class="bq-caroussel-media" src="{thumb}" /></tpl>',
            '</tpl>'
        );

        // create view
        var view = new Ext.DataView({
            id: this.id + '_view',
            store: store,
            tpl: tpl,
            cls: '',
            autoWidth: true,
            multiSelect: true,
            autoScroll: true,
            deleted: [],
            autoScroll: true,
            overClass:'bq-caroussel-media-over',
            itemSelector:'img.bq-caroussel-media',
            selectedClass: 'bq-caroussel-media-selected',
            emptyText: '<h1 class=\'no_results\'>' + App.t('no_results') + '</h1>',
            listeners: {
                render : function(v) {
                    v.tip = new Ext.ToolTip({
                        target : v.getEl(),
                        html: null,
                        width:75,
                        title:'&nbsp;',
                        listeners: {
                            render: function(p) {
                                p.el.setOpacity(0.90);
                            }
                        }

                    });
                },

                /**
                 * @event click
                 * @param {DataView} v
                 * @param {Integer} index
                 * @param {DomNode} node
                 * @param {EventObject} ev
                 */
                click: function(v, index, node, ev) {
                  var rec = v.store.getAt(index);
                  var url ="/" + rec.data.ownerUsername + BQJSConfig['app_' + rec.data.type] + "/" + BQJSConfig.see + "/" + rec.data.id;

                  if (this.navigateOnClick == true) {
                      document.location = url;
                  }
                },

                /**
                 * @event mouseenter
                 * @param {DataView} v
                 * @param {Integer} index
                 * @param {DomNode} node
                 * @param {EventObject} ev
                 */
                mouseenter : function( v, index, node, ev ) {
                    var rec= v.store.getAt(index);
                    v.tip.show();
                    v.tip.el.alignTo(node.id, 'tl-bl', [10,-10]);
                    v.tip.setTitle(Ext.util.Format.ellipsis(rec.data.title, 30));
                    v.tip.syncShadow();
                },

                scope: this
            }
        });

        this.relayEvents(view, ['click']);

        return view;
    }
});

