/**
 * @overview Video Manager.js
 * Collection of components for dealing with video streaming
 * @author Chris Scott
 * modifications Vincent Maillot    vincent.maillot@cossette.com
 */


/**
 * BQ.video.Player
 * NOTE: this is a wrapper for streamtheworld player which sets up a global variable "_stwVar" for its params.  this components
 * writes values to this global.  also not several streamtheworld functions which have been over-ridden above in order to return
 * strings rather than call document.write directly.
 * @author Chris Scott
 */
/**
 * Vincent Maillot vincent.maillot@cossette.com
 * (ticket : 5903) Video panel avec carousel pour afficher l'objet Flowplayer
 * /!\ 3 types de flowplayer : avec carousel (comme ici), avec tag ahref virtuel (voir ModerationManager.js), avec tag ahref préfixé (voir video/player.html)
**/
BQ.video.Panel = Ext.extend(Ext.Panel, {

    mediaId : null,
    record : null,
    border: false,
    stateful:false,
    
    first_video_url : null,
    first_video_thumb : null,

    player_container_id : 'video_player_ct3',

    player_height : 300,
    player_width  : 358,
    
    /**
     * @cfg {Number} pageSize [3]
     * Nombre de video dans le carousel
     */
    pageSize: 2,

    initComponent: function(){
        this.addClass('bq-video-player');
        this.footer = true;
        this.title = '&nbsp;';
        
        this.items = {
            id:"parent_column",
            layout: 'column',
            border: false,
            items: [
                {
                columnWidth: 0.60, //new column
                border: false,
                items: [
                    // le panel qui va contenir le player video
                    new Ext.Panel({
                        id: 'videoplayerpanel',
                        border: false,
                        layout: 'fit',
                        html : '<a  '+
                               '    href=""  '+
                               '    style="display:block;width:'+this.player_width+'px;height:'+this.player_height+'px;cursor:pointer;"'+
                               '    id="'+this.player_container_id+'">'+
                               '    <div style="width:'+this.player_width+'px;height:'+this.player_height+'px;background-color:#000000;background-image:url('+this.first_video_thumb+');background-repeat: no-repeat; background-position: center;"></div>'+
                               '    <div style="position:relative;top:-'+(this.player_height/2)+'px;left:'+(this.player_width/2)+'px;"><img src="/static/images/css_images/overlay_video.png" alt="" /></div>'+
                               '</a> '
                    })
                    /*,
                    // le panel qui va contenir les tags (caché)
                    {
                        id: this.id + '_tags',
                        xtype: 'videotagpanel',
                        border: false
                    }*/
                ]
            }
            
            
            ,{
                columnWidth: 0.40,
                border: false,
                id:'info_column',
                items: [
                    // le panel qui va contenir les informations à propos de la vidéo (titre/publié par/...)
                    {
                        id: this.id + '_info',
                        xtype: 'videoinfopanel',
                        border: false,
                        style:"margin-bottom:10px; padding-right:10px; padding-left:10px;"
                    },
                    
                    new BQ.Caroussel({
                        url: '/json/BQAContent/caroussel',
                        cls:'video sml_car',
                        width:210,
                        height: 100,
                        style:"margin-left:10px;",
                        types: 'video',
                        metadata: '1',
                        pageSize: this.pageSize,
                        navigateOnClick: false,
                        listeners : {
                            // initialisations au chargement du caroussel
                            load : function(ds, rs, opts) {
                                        var first = rs[0];
                                        if (this.record == null && first) {
                                            this.record = first;
                                            this.init(first);
                                        }
                                    },

                            // initialisations au moment où on clique sur une miniature dans le caroussel
                            click : function(dv, index, node, ev) {
                                        var rec = dv.store.getAt(index)
                                        if (typeof this.onClick == 'function') {
                                            this.onClick(rec);
                                        }
                                        ev.stopEvent();
                                    },
                            scope: this
                        }
                    })
                
              
              ]
            }]
        };

        this.on('render', function(p) {
            p.footer.update('<a href="' + BQJSConfig.http_prefix + '/search' + BQJSConfig.app_media + '/video"></a>');

        });

        // superclasse
        BQ.video.Panel.superclass.initComponent.call(this);


    },

    // initialisations au chargement du caroussel
    init: function(rec) {
            this.record = rec;

            this.getInfoPanel().update(rec);
            //this.getTagPanel().update(rec);
            
            flowplayer( this.player_container_id, 
                        { src : "/static/swf/flowplayer.commercial-3.1.5.swf", wmode : 'transparent'},
                        {
                            key: '#@b20ca20864b4a80aeac',
                            playlist: [ 
                                // la video
                                { 
                                    autoPlay: true, 
                                    autoBuffering: true,
                                    url: rec.data.encoded,
                                    scaling: 'fit' 
                                },
                                // image finale
                                {
                                    url: rec.data.thumb_normal, 
                                    onBegin: function () { 
                                        // disable play button for this playlist item 
                                        this.getPlugin("play").css({opacity: 0}); 
                                    },
                                    scaling: 'fit' 
                                } 
                            ],
                            plugins: {            // load one or more plugins 
                                controls: {            // load the controls plugin 
                                    url: '/static/swf/flowplayer.controls-3.1.5.swf',    // always: where to find the Flash object 
                                    playlist: false,                // now the custom options of the Flash object 
                                    backgroundColor: '#9F978B', 
                                    timeBgColor: '#9F978B',
                                    tooltips: {                // this plugin object exposes a 'tooltips' object 
                                        buttons: true,
                                        play: App.t('player_play'),
                                        mute: App.t('player_mute'),
                                        unmute: App.t('player_unmute'),
                                        fullscreen: App.t('player_fullscreen'),
                                        fullscreenExit: App.t('player_fullscreenexit')
                                    } 
                                }
                            }
                        }
                    );
    },
    
    
    // initialisations au moment où on clique sur une miniature dans le caroussel
    onClick : function(rec) {

            this.record = rec;
            this.getInfoPanel().update(rec);
            //this.getTagPanel().update(rec);

            flowplayer( this.player_container_id, 
                        { src : "/static/swf/flowplayer.commercial-3.1.5.swf"},
                        {
                            key: '#@b20ca20864b4a80aeac',
                            playlist: [ 
                            
                                // image initiale
                                {
                                    url: rec.data.thumb_normal, 
                                    scaling: 'fit' 
                                },
                                // la video
                                { 
                                    autoPlay: false, 
                                    autoBuffering: true,
                                    url: rec.data.encoded,
                                    scaling: 'fit' 
                                },
                                // image finale
                                {
                                    url: rec.data.thumb_normal, 
                                    onBegin: function () { 
                                        // disable play button for this playlist item 
                                        this.getPlugin("play").css({opacity: 0}); 
                                    },
                                    scaling: 'fit' 
                                } 
                            ],
                            plugins: {            // load one or more plugins 
                                controls: {            // load the controls plugin 
                                    url: '/static/swf/flowplayer.controls-3.1.5.swf',    // always: where to find the Flash object 
                                    playlist: false,                // now the custom options of the Flash object 
                                    backgroundColor: '#9F978B', 
                                    timeBgColor: '#9F978B',
                                    tooltips: {                // this plugin object exposes a 'tooltips' object 
                                        buttons: true,
                                        play: App.t('player_play'),
                                        mute: App.t('player_mute'),
                                        unmute: App.t('player_unmute'),
                                        fullscreen: App.t('player_fullscreen'),
                                        fullscreenExit: App.t('player_fullscreenexit')
                                    } 
                                }
                            }
                        }
                    );
            
    },

    // getInfoPanel
    getInfoPanel : function() {
        return this.items.first().items.last().items.first();
    }
    /*
    ,
    //getTagPanel
    getTagPanel : function() {
        return this.items.first().items.first().items.last();
    }
    */
});



/**
 * BQ.video.InfoPanel
 * An Panel that renders an XTemplate for Video description information
 * @author Chris Scott
 */
BQ.video.InfoPanel = Ext.extend(Ext.Panel, {
    stateful:false,
    templateId : 'video_info_template',

    initComponent : function() {
        RExt.util.TemplateMgr.add(this.templateId, new Ext.XTemplate(
            '<tpl for=".">',
                '<h1 class="xlrg"><a href="{[BQJSConfig.http_prefix]}/{ownerUsername}{[BQJSConfig.app_video]}/{[BQJSConfig.see]}/{values.id}">{[Ext.util.Format.ellipsis(values.title, 100)]}</a></h1>',

                '<p id="video_description">{[Ext.util.Format.ellipsis(values.description, 80)]}</p>',

                '<div class="row_breaker"></div>',

                '<span class="published">' + App.t('content_published_on') + '&nbsp;<span id="video_created">{[this.formatDate(values.time_created)]}</span>&nbsp;' + App.t('content_by') + '&nbsp;<strong id="video_owner"><a href="{[BQJSConfig.http_prefix]}/{ownerUsername}{[BQJSConfig.app_user_space]}">{ownerUsername}</a></strong></span>',
                '<a href="{[BQJSConfig.http_prefix]}/{ownerUsername}{[BQJSConfig.app_video]}/{[BQJSConfig.see]}/{values.id}#comments_section" class="pointer black">' + App.t('words_make_comment') +'</a>',
                '<a href="{[BQJSConfig.http_prefix]}/{ownerUsername}{[BQJSConfig.app_video]}/{[BQJSConfig.see]}/{values.id}#star-rater" class="pointer black">' + App.t('vote_rate') +'</a>',
                '<div class="rating_widget">',
                          '<div class="star-rating  {[this.ratingToClassName(values.rating)]} ">',
                              '<span class="one"></span>',
                              '<span class="two"></span>',
                              '<span class="three"></span>',
                              '<span class="four"></span>',
                              '<span class="five"></span>',
                            '</div>',
                          '<div id="rating-vote-count">',
                             '<span class="count">{[this.formatVotes(values.vote)]}</span>',
                          '</div>',
                '</div>',
            '</tpl>',
            BQ.content.TemplateMethods
        ));
        this.addClass('video_info_panel');
        BQ.video.InfoPanel.superclass.initComponent.call(this);
    },

    /**
     * update
     * update the info panel with new information
     * @param {BQ.data.Content} record
     */
    update : function(record) {
        var tpl = RExt.util.TemplateMgr.get(this.templateId);
        if (!this.rendered) {
            this.on('render', function(){
                tpl.overwrite(this.body, record.data)
            }, this);
        }
        else {
            tpl.overwrite(this.body, record.data);
        }
    }


});
Ext.reg('videoinfopanel', BQ.video.InfoPanel);

BQ.video.TagPanel = Ext.extend(Ext.Panel, {
    templateId : 'video_tag_panel',
    stateful:false,
    initComponent: function () {
        RExt.util.TemplateMgr.add(this.templateId, new Ext.XTemplate(
             '<tpl>',
             '<br />',
                 '<tpl if="values.categories.length + values.seasons.length + values.regions.length &gt; 0">', //determines if there are tags at all to show
                    '<h3 class="tags_label">' + App.t('content_classification') + '</h3>',
                    '<br />',
                    '<ul class="tags">',
                        '<tpl for="values.categories">',
                            '<li><a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_categories]}/{values._slug}">{values.name}</a></li>',
                        '</tpl><tpl for="regions">',
                            '<li><a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_regions]}/{values._slug}">{values.name}</a></li>',
                        '</tpl><tpl for="seasons">',
                            '<li><a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_seasons]}/{values._slug}">{values.name}</a></li>',
                        '</tpl>',
                    '</ul>',
                '</tpl>',
             '</tpl>'
        ));
        BQ.video.TagPanel.superclass.initComponent.call(this);
    },
    /**
     * update
     * update the info panel with new information
     * @param {BQ.data.Content} record
     */
    update : function(record) {
    
    var object = record.data;
    for(variable in object)
    {
        console.log(variable + ' : ' + object[variable] + "\n");
    }
    
        var tpl = RExt.util.TemplateMgr.get(this.templateId);
        if (!this.rendered) {
            this.on('render', function(){
                tpl.overwrite(this.body, record.data)
            }, this);
        }
        else {
            tpl.overwrite(this.body, record.data);
        }
    }

});
Ext.reg('videotagpanel', BQ.video.TagPanel);
