//
// Wrapper for the flash player. 2 player modes:
// - simple: using player of providers (some like dailymotion won't allow external player)
// - custom: using JW player
//
function VIET_pq_Player() {
    this.sContainerId = 'player';
    this.swfObj = null;
    this.sFlashId = 'floPlayer';
    this.bInited = false;

    //
    // visual mode:
    // - hide: show text content
    // - show: show video content
    // - max: show video content fill entire browser
    //
    this.sVMode = 'hide';

    //
    // player mode:
    // - simple: using host flash player
    // - custom: using JW flash player
    //
    this.sPMode = 'custom';
    
    this.oCurrVideo = null;
    this.arCurrClips = null
    this.iCurrClipPos = 0;
    this.bStartOut = true;  // mark first time player play, this is for picking up where left off

    this.arFlashVars = {'custom': { autostart: 'true',
                                    shuffle: 'false',
                                    enablejs: 'true',
                                    usekeys: 'true',
                                    displayheight: 9999,
                                    overstretch: 'fit',
                                    repeat: 'list',
                                    largecontrols: 'true',
                                    
                                    /*frontcolor: '0xbbbbbb',*/
                                    backcolor: '0x000000'
                                    /*lightcolor: '0xffffff'*/ },
                        'simple': { autoStart: 1,
                                    autoPlay: 1,
                                    //callback: 'player_proxy',
                                    hide: '@info@@share@' }
        };
    this.arFlashParams = {  'custom' : {allowfullscreen: 'true',
                                        allowscriptaccess: 'true',
                                        bgcolor: '#000000' },
                            'simple' : {allowfullscreen: 'true',
                                        allowscriptaccess: 'always',
                                        bgcolor: '#000000' }
        };
    
    this.iClipPageSize = 10;
}
VIET_pq_Player.prototype = {

    init: function() {
        this.bInited = true;
    },
    
    //
    // external classes call this to play a video
    //
    PlayVideo: function(iVideoId, iClipPos) {
        // reset variable
        this.oCurrVideo = null;
        this.arCurrClips = null
        this.iCurrClipPos = iClipPos==null ? 0 : iClipPos;

        this.getVideo(iVideoId);
    },

    //
    // Step 1: retrieve video info (callback_getVideo will be called)
    //
    getVideo: function(iVideoId) {
        CrossSite_getVideo(iVideoId);
    },
    
    //
    // Step 2: retrieve video clips
    //
    getClips: function(jsonObj) {
        if( jsonObj.clips_count<=0 ) {
            alert('No clip in this video.');
            return;
        }

        this.oCurrVideo = jsonObj;
        this.updateShowInfo(jsonObj.title, jsonObj.description, jsonObj.clips_count);
        
        CrossSite_getClips(jsonObj.id);
    },
    
    //
    // Step 3: parse clips to determine player_mode
    //
    parseClips: function(jsonObj) {
        this.arCurrClips = jsonObj;

        this.sPMode = 'custom';
        for( var i=0; i<jsonObj.length; i++ ) {
            if( jsonObj[i]['src_link']!=null && jsonObj[i]['src_link'].indexOf('dailymotion.com')>0 ) {
                this.sPMode = 'simple';
                break;
            }
        }
        
        this.playVideo();
    },
    
    //
    // play the current video
    //
    playVideo: function() {

        if( this.sPMode=='simple' ) {
            if( this.iCurrClipPos<this.arCurrClips.length ) {
                var currClip = this.arCurrClips[this.iCurrClipPos];
                this.swfObj = new SWFObject(CrossSite_url + '/videos/' + currClip['video_id'] + '/clips/' + currClip['position'] + '.flv', this.sFlashId, "100%", "100%", "8", "#000000");
            }
        }
        else {  // custom mode
            //this.swfObj = new SWFObject(CrossSite_url + '/swf/flvplayer2.jwf', this.sFlashId, "100%", "100%", "7", "#000000");
            //this.swfObj.addVariable("file", CrossSite_url + '/videos/' + this.oCurrVideo.id + '/clips.atom');
        
            this.swfObj = new SWFObject("http://phimquan.com/jw_flv_player2/flvplayer.jwf", this.sFlashId, "100%", "100%", "7", "#000000");
            this.swfObj.addVariable("file", CrossSite_url + '/videos/' + this.oCurrVideo.id + '/clips.atom');
        }

        var fvars = this.arFlashVars[this.sPMode];
        if( fvars!=null ) {
            for( var key in fvars ) {
                this.swfObj.addVariable(key, fvars[key]);
            }
        }
        
        var fparams = this.arFlashParams[this.sPMode];
        if( fparams!=null ) {
            for( var key in fparams )
                this.swfObj.addParam(key, fparams[key]);
        }

        this.swfObj.useExpressInstall('/swf/expressinstall.swf');
        this.swfObj.write(this.sContainerId);
    },

    //
    // play a clip in current video, this is called when user jumps to a clip
    //
    playClip: function(iClipPos) {
        if( iClipPos>=this.arCurrClips.length ) return;

        if( this.sPMode=='simple' ) {
            this.onClipChange(iClipPos);
            this.playVideo();
        }
        else {  // custom mode
            this.iCurrClipPos = iClipPos;
            $(this.sFlashId).sendEvent('playitem', iClipPos);
        }
    },
    
    //------ update current showing --------------------------------------------------------
    updateShowTitle: function(sTitle, iClipCount) {
        if( sTitle==null )
            sTitle = this.oCurrVideo['title'];
        if( iClipCount==null )
            iClipCount = this.arCurrClips.length;
        
        $('showTitle').innerHTML = sTitle + ' - ' + (this.iCurrClipPos+1) + ' <span style="font-size:90%;">/' + iClipCount + '</span>';
    },

    updateShowInfo: function(sTitle, sDesc, iClipCount) {
        this.updateShowTitle(sTitle, iClipCount);
        $('showDesc').innerHTML = (sDesc.length>100 ? sDesc.substring(0, 100) : sDesc);
        this.updateClipInfo(iClipCount, 1);
    },
    
    updateClipInfo: function(iClipCount, iClipPage) {
        var s = '';
        if( iClipCount>this.iClipPageSize )
            s += iClipPage>1 ? '<a class="lkClip" href="javascript:oPlayer.updateClipInfo(' + iClipCount + ', ' + (iClipPage-1) + ')"><b>&laquo;</b></a> &nbsp;' : '<span class="lkClip">&laquo;</span> &nbsp;';

        for( var i=(iClipPage-1)*this.iClipPageSize; i<iClipPage*this.iClipPageSize && i<iClipCount; i++ ) {
            s += '<a class="lkClip' + (i==this.iCurrClipPos ? '_A' : '') + '" href="javascript:oPlayer.playClip(' + i + ')">' + (i<9 ? '0' : '') + (i+1) + '</a> ';
        }
        s += iClipPage < Math.ceil(iClipCount/this.iClipPageSize) ? '&nbsp;<a class="lkClip" href="javascript:oPlayer.updateClipInfo(' + iClipCount + ', ' + (iClipPage+1) + ');"><b>&raquo;</b></a>' : '';

        $('clipInfoCnt').innerHTML = s;
    },

    
    //------ change mode (size) of player ---------------------------------------------------    
    setVisualMode: function(psVMode) {
        if( !this.bInited ) return;

        this.sVMode = psVMode;
        $(this.sContainerId).className = 'player' + this.sVMode;
        $('clipInfo').style.display = (this.sVMode=='show' ? 'block' : 'none');
        $('showInfo').style.display = (this.sVMode=='show' ? 'block' : 'none');
        $('resumeplayer').style.display = (this.sVMode=='hide' ? 'block' : 'none');
    },
    
    hide: function() {
        this.setVisualMode('hide');
    },
    
    show: function() {
        this.setVisualMode('show');
    },
    
    max: function() {
        this.setVisualMode('max');
    },

    //------ event handler ----------------------------------------------------------------    
    //
    // get called by JW player when moving to next clip
    //
    onClipChange: function(iNewClipPos) {
        if( this.arCurrClips!=null ) {
        
            if( this.bStartOut ) {
                this.bStartOut = false;
                this.updateClipInfo(this.arCurrClips.length, Math.ceil((this.iCurrClipPos+1)/this.iClipPageSize));
                $(this.sFlashId).sendEvent('playitem', this.iCurrClipPos); // play where left off
            }
            else {
                this.iCurrClipPos = iNewClipPos;
                this.updateShowTitle();
                this.updateClipInfo(this.arCurrClips.length, Math.ceil((this.iCurrClipPos+1)/this.iClipPageSize));

                // remember current clip
                setCookie('curc', iNewClipPos, 30);
            }

        }
    }
}
var oPlayer = new VIET_pq_Player();

//----------------------------------------------------------------------------------------
// callbacks for cross-site calls
//
function callback_getVideo(jsonObj) {

    //
    // record recently watched video in cookies
    //
    setCookie('v_' +  jsonObj.id, jsonObj.title + '|' + jsonObj.image_link + '|' + jsonObj.clips_count + '|' + (new Date()).getTime(), 30);
    if( window.frames.frHome && window.frames.frHome.updateRecentlyWatched )
        window.frames.frHome.updateRecentlyWatched();

    // remember current movie
    setCookie('curm', jsonObj.id, 30);

    oPlayer.getClips(jsonObj);
}
function callback_getClips(jsonObj) {
    oPlayer.parseClips(jsonObj);
}
//----------------------------------------------------------------------------------------

//
// this function is called by the JW flash object
// - type: time (pr1 = current second), volume (pr1 = current volumn), 
//      item (array thisMovie(javascriptId).itemData(pr1) returns data from playlist feed),
//      load, state, size
//
function getUpdate(typ, pr1, pr2, pid) {
    if( typ=="item" ) {

        oPlayer.onClipChange(pr1);

        /*var obj = $("floPlayer").itemData(pr1);
        s = '';
        for( var i in obj ) {
            s += i + '=' + obj[i] + '\n';
        }
        alert(s);*/

        //try {
            //obj['guideId'] = obj['title'].substring(1, obj['title'].indexOf(']'));
            //obj['title'] = obj['title'].substring(obj['title'].indexOf(']')+1);
        //}
        //catch (ex) {}
        //var dt = new Date();
        //dt.setTime(obj['date']*1000);

        //$('showTitle').innerHTML = obj['title'];
        //oIndex.player_onClipChange(obj['id'], obj['guideId'], obj['title'], dt);
    }
}
