//
// Wrapper for the JW flash player.
//
function VIET_vnl_ui_Player() {
    this.sContainerId = 'adaptvDiv';
    this.container = null;
    this.swfObj = null;
    this.swfOndemandMsg = null;
    this.sFlashId = 'floPlayer';
    this.flashObj = null;
    this.bInited = false;
    this.sMode = 'max';
    this.isPlaying = false;
    this.iCurrentOnDemandGuideId = 0;
    this.bIsTodayOnDemand = false; // true if the current playing is on-demand and aired today

    this.playerReady = false;
    this.playlistReady = false;
    this.playlistLoaded = false;

    this.arFlashVars = {
        autostart: 'true',
        shuffle: 'false',
        enablejs: 'true',
        usekeys: 'true',
        width: '639',
        height: '357',
        //displayheight: 9999,
        overstretch: 'fit',
        repeat: 'list',
        largecontrols: 'true',
	pid: 'yy248',
	zid: 'default',
	keywords: 'vietnam, tv, htv',
	duration: '3600',
	categories: 'entertainment',
	// new for jw_player version 5
	controlbar: 'over',
	stretching: 'exactfit',
	'logo.hide': 'false',
	'logo.file': '/images/vietnamlivetvonyoutube.png',
	'logo.position': 'bottom-right',
	plugins: 'ltas',
	'ltas.cc': 'wapfibwitycodvt',
	playerready: 'oPlayer.playerReadyCallback'
 	};
    this.arFlashParams = {
        allowfullscreen: 'true',
        allowscriptaccess: 'always',
        bgcolor: '#000000' };
    
    this.arTopPrograms = [
	27056, 27035, 27094,

    27957, 27928, 27713, 27056, 25230, 25150, 20206, 19768, 19735, 17778, 17204, 16407, 15084, 14443, 12132, // thay loi muon noi
    27733, 27658, 26707, 24478, 24094, // album vang

//    22858, 22855, 22695, 22693, 22763, 22469, 22601, 22554, 22087,  // ca nhac, am nhac
//    23010, 22788, 22113, 21899, 21872, 21238, 20053, 20022, 19874, 19242, 22496, 11477, 9543, 15033, // cai luong, chuyen xua tich cu
//    18964, 17849, 16988, 16414, 15846, 22868, 22140, 21731, 20902, 19747, 19398, 18712, // chuyen nho & not nhac vui
//    22368, 21765, 20937, 19782, 19395, 18709, 22137, 21728, 20899, 19744, 19197, 18670, // hoi ngo bat ngo & chung suc

    28182, 27970, 27767, 27557, 27351, 27107, 26724, 26399, 25868, 25244, 24760, 24113, 23292, 22868, 22140, 21731, // not nhac vui
    28025, 27822, 27611, 27395, 27164, 26971, 26792, 26551, 25937, 24858, 24209, 23532, 22938, 22403, 21800, 20973, // hat voi ngoi sao
    28079, 27884, 27667, 27454, 27245, 27021, 26621, 26122, 25564, 24963, 24277, // tim nguoi thong minh
    27995, 27796, 27580, 27375, 26937, 26755, 26434, 25275, 24672, 22903, 22368, 21765, 20937, 19782, 19395, // hoi ngo bat ngo
    28179, 27967, 27763, 27554, 27104, 26721, 26396, 24636, 24110, 25865, 23289, 22865, 22137, 21728, 20899, // chung suc
    27774, 27561, 27358, 27114, 26478, 25316, 24715, 24040, 23456, 23020, 22306, 20462, 19938, // kim tu thap

    26633, 26266, 24534, 23825, 23544, 22950, 22752, 21384, 20984, 20796, 19829, 28123, 27742, 27497, 27294, 27054, // nhat ky khong do
    28086, 28059, 27875, 27858, 27674, 27647, 27461, 27435, 27252, 27200, 27026, 26997, 26832, 26627, 26566, 26128, // cuoi chut choi
    27679, 27659, 26109, 24949, 23401, 28214, 27625, 27413, 26809, 24876, 23466, 23154, 27837, 27144, 26598, 22600, 22379, 22252, // chuyen 4 mua, chuyen canh giac, sieu thi cuoi


    26840, 27333, 27947 // phim viet nam
    //20782, 15779, 20203, 19587, 12774, 20858, 18643, 5513 // phim viet nam

//    4816, 13414, 14817, 15399, 14484, 11444, 15394, 15316, 15087, 11981, 9766, 15020, 14754, 15545, 15084,
//	18156, 17252, 16716, 16141, 17923, 17796, 17778, 17408, 17175, 17147, 17073, 16643, 18159, 17255, 16719, 16144
	];

}
VIET_vnl_ui_Player.prototype = {

    init: function(type, iGuideId, iChannelId) {
        this.container = $(this.sContainerId);

        if( type=='ondemand' ) {
            iGuideId = iGuideId<0 ? this.getRandomTopProgram() : iGuideId;
            this.playOnDemand(iGuideId);
            //oGlobal.updateChannelDisplayForOnDemandPlay(iGuideId);
        }
        else if( type=='live' ) { // live tv
            this.playLive(iChannelId);
        }

        this.bInited = true;
    },
    
    getRandomTopProgram: function() {
        return this.arTopPrograms[ Math.round(Math.random()*1000)%this.arTopPrograms.length ];
    },

    buildFlashObj: function(sFile, bForcePlay) {

	var sPlayerUrl = '/jw_mediaplayer_5-1/player-licensed.swf';
	//var sPlayerUrl = '/jw_flv_player/flvplayer.jwf'; // old version
	//'/jw_flv_player/integratedjwplayer.jwf'; // adaptv integration
	//this.arFlashParams['wmode'] = 'opaque';
	this.arFlashVars['largecontrols'] = 'false';
	this.arFlashVars['backcolor'] = '0x909090';
	this.arFlashVars['frontcolor'] = '0xffffff';

        // JW player mode: original or custom
        /*var sPlayerUrl = '/jw_flv_player_3_16/mediaplayer.jwf';
        if( typeof iPM != 'undefined' ) {
	    if( iPM==3 ) {
                sPlayerUrl = '/jw_flv_player/integratedjwplayer.jwf'; // adaptv integration
		this.arFlashParams['wmode'] = 'opaque';
	    }
	    else if( iPM==1 ) {
                sPlayerUrl = '/jw_flv_player/flvplayer.jwf';
	    }
            this.arFlashVars['largecontrols'] = 'false';
            this.arFlashVars['backcolor'] = '0x909090';
            this.arFlashVars['frontcolor'] = '0xffffff';
        }*/

        this.swfObj = new SWFObject(sPlayerUrl, this.sFlashId, "100%", "100%", "7", "#000000");

        for( var key in this.arFlashParams )
            this.swfObj.addParam(key, this.arFlashParams[key]);

	var paidUser = oUser.isSubscribedUser();
        for( var key in this.arFlashVars ) {
	    if( /*paidUser &&*/ (key=='plugins' || key=='ltas.cc') ) // no ad for paid user
		continue; 
            this.swfObj.addVariable(key, this.arFlashVars[key]);
	}

	var sFileEscaped = escape(sFile);
	this.swfObj.addVariable('ltas.mediaid', sFileEscaped);
	//this.swfObj.addVariable('provider', 'youtube');
        //this.swfObj.addVariable("file", sFileEscaped);
	this.swfObj.addVariable("file", 'http://www.youtube.com/watch?v=kmaHVVcSfoo');
	//this.swfObj.addVariable("file", '/images/logo.jpg');
        this.swfObj.useExpressInstall('/swf/expressinstall.swf');

	this.playerReady = false;
        this.playlistReady = false;
	this.playlistLoaded = false;

	// preload
        this.swfObj.write(this.sContainerId);
        this.flashObj = $(this.sFlashId);

	oGlobal.arCurrSegments = [];

        
        //
        // check to see if playlist is empty; for live tv, channel is not currently airing anything
        // for ondemand, it is probably an error
        // also update clips indication
        //
        var me = this;
        YAHOO.util.Connect.asyncRequest('GET', sFile + '.json', {success:function(o){
                try {
                    var arSegments = eval("(" + o.responseText + ")");

                    if( arSegments.length<=0 ) {
                        if( oGlobal.bIsLive )
                            $('showTitle').innerHTML = '<div id="showTitle_unavail">' + (oGlobal.sCurrLang=='en' ? 'No live signal for this channel. Please use <a href="javascript:oGlobal.showTvGuide()">TV GUIDE</a> to watch today programs.' : 'Kênh hiện không phát trực tiếp. Xin dùng trang <a href="javascript:oGlobal.showTvGuide()">LỊCH PHÁT</a> để xem những chương trình hôm nay.') + '</div>';
                        else
                            $('showTitle').innerHTML = '<div id="showTitle_unavail">' + (oGlobal.sCurrLang=='en' ? 'Requested program not available.' : 'Chương trình này hiện bị lỗi.') + '</div>';

                        $('showOtherInfo').style.visibility = 'hidden';

                        oGlobal.arCurrSegments = [];
                    }
                    else { // update clip indication

                        oGlobal.arCurrSegments = arSegments;

                        if( $('statusBar_obj')!=null && oGlobal.bIsLive==false )
                            $('statusBar_obj').as_setSegment(1, arSegments.length);
                    }

		    if( !me.playlistLoaded && me.playerReady ) {
			me.loadPlaylist();
		    }

		    me.playlistReady = true;
                }
                catch(ex) { }
            }, failure:function() {}});
        
        //if( bForcePlay==true )
        //    this.forcePlay(sFile);
    },
  
    loadPlaylist: function() {
            var playlist = new Array();
            for( var i=0, len=oGlobal.arCurrSegments.length; i<len; i++ ) {
                playlist[i] = {
                    author: 'Vietnam Live TV',
                    description: 'vietnam live tv',
                    duration: oGlobal.arCurrSegments[i].duration,
                    file: (oGlobal.arCurrSegments[i].hostedAt==3 ? 'http://www.youtube.com/watch?v=' + oGlobal.arCurrSegments[i].docId : 'http://vietnamlive.tv/zf/video/index/hostedAt/' + oGlobal.arCurrSegments[i].hostedAt + '/idAtHost/' + oGlobal.arCurrSegments[i].docId + '.flv'),
		    start: 0,
                    title: oGlobal.arCurrSegments[i].guideTitle,
		    type: (oGlobal.arCurrSegments[i].hostedAt==3 ? 'youtube' : 'video')
                };
            }

            this.flashObj.sendEvent('LOAD', playlist);

	this.playlistLoaded = true;
    },
 
    playerReadyCallback: function(obj) {
	this.flashObj.addControllerListener('ITEM', 'getUpdate_Item');
	this.flashObj.addModelListener('STATE', 'getUpdate_State');

//this.flashObj.sendEvent('LOAD', 'http://www.youtube.com/watch?v=vMFJJdfV-so');
//this.flashObj.sendEvent('LOAD', 'http://www.youtube.com/watch?v=5aRBgHMa8zM');

	if( !this.playlistLoaded && this.playlistReady ) {
	    this.loadPlaylist();
	}

	this.playerReady = true;
    },

    /*playerOnStateChange: function(evt) {
var pl = this.flashObj.getPlaylist();
var s = '';
for( var i=0; i<pl.length; i++ ) {
s += '\n';
	for( var a in pl[i] ) {
		s += a + '=' + pl[i][a] + ',';
	}
}
//alert(s);
    },*/
 
    playOnDemand: function(iGuideId) {
        this.iCurrentOnDemandGuideId = iGuideId;

        //
        // first find out if the guide is aired today (free Today On-demand)
        var me = this;
        var handleSuccess = function(o){
            var obj;
            try {
                obj = eval("(" + o.responseText + ")");
                if( $('statusBar_obj')!=null )
                    $('statusBar_obj').as_setChannel(VIET_vnl_util_GetChannelName(obj['channelId']));

                var bIsAiredToday = me.isAiredToday(obj.airTime);
                me.bIsTodayOnDemand = bIsAiredToday;

                if( bIsAiredToday==false && !oUser.isSubscribedUser() && obj.free!=1 )
		{
			// adap.tv integration
			me.arFlashVars['id'] = obj['id'];
			me.arFlashVars['title'] = obj['title'];
			me.arFlashVars['duration'] = obj['duration'];
			me.arFlashVars['description'] = obj['dTitle'];

                    	me.buildFlashObj(getJsonUrl({action:'playlist', type:'ondemand', guideId:iGuideId}));
                }
		else
                	me.buildFlashObj(getJsonUrl({action:'playlist', type:'ondemand', preview:'no', guideId:iGuideId}));

                // google analytics
                pageTracker._trackPageview('/play/' + obj['id'] + '-' + obj['title'].replace(' ', '-') );
            }
            catch(ex) {}
        }
        YAHOO.util.Connect.asyncRequest('GET', getJsonUrl({action:'program-item', type:'info', guideId:iGuideId, format:'json'}), {success:handleSuccess, failure:function() {}});
    },
    
    // util function to return true if this air time is today
    isAiredToday: function(sAirTime) {
        var dtAirTime = VIET_vnl_util_ParseDateTimeFromMySQL(sAirTime);
        var dtServerTime = getServerTime();
        var dtServerDate = new Date(dtServerTime.getFullYear(), dtServerTime.getMonth(), dtServerTime.getDate(), 0, 0, 0, 0);
        var bIsAiredToday = ( (dtServerDate.getTime()-12*3600*1000)<=dtAirTime.getTime() ) && ( dtAirTime.getTime()<dtServerTime.getTime()+24*3600*1000 );
        return bIsAiredToday;
    },
    
    playSigninMessage: function(error) {
        this.pause();
        oGlobal.showPlayer();
        this.container.className = 'playerhide';
        $('ondemandmsg').style.display = 'block';
        this.swfOndemandMsg = new SWFObject('/swf/ondemand_login.swf', 'ondemandmsg_beginobj', "100%", "100%", "7", "#000000");
        this.swfOndemandMsg.addVariable('mainTitle', (oGlobal.sCurrLang=='en' ? 'ON DEMAND' : 'THEOYÊUCẦU'));
        if( error===true )
            this.swfOndemandMsg.addVariable('subTitle', (oGlobal.sCurrLang=='en' ? 'Login error. Please try again.' : 'Truy nhập không thành công.'));
        else
            this.swfOndemandMsg.addVariable('subTitle', (oGlobal.sCurrLang=='en' ? 'Login to skip this message' : 'Truy nhập hoặc đăng ký.'));
        this.swfOndemandMsg.addVariable('loginNowTitle', (oGlobal.sCurrLang=='en' ? 'Don\'t have an account? <u><a href=\'asfunction:new_user\'>Sign up here.</a></u>' : 'Chưa có tài khoản? <u><a href=\'asfunction:new_user\'>Xin hãy Đăng ký.</a></u>'));
        this.swfOndemandMsg.addVariable('loginNow', (oGlobal.sCurrLang=='en' ? 'Login' : 'Truy nhập'));
        this.swfOndemandMsg.addVariable('registerNowTitle', (oGlobal.sCurrLang=='en' ? 'Already have an account? <u><a href=\'asfunction:login_user\'>Log in here.</a></u>' : 'Đã có tài khoản? <u><a href=\'asfunction:login_user\'>Xin hãy Đăng nhập.</a></u>'));
        this.swfOndemandMsg.addVariable('registerNow', (oGlobal.sCurrLang=='en' ? 'Register' : 'Đăng ký'));
        this.swfOndemandMsg.addVariable('skipButton', (oGlobal.sCurrLang=='en' ? 'Skip' : 'Xem tiếp'));

        this.swfOndemandMsg.useExpressInstall('/swf/expressinstall.swf');
        this.swfOndemandMsg.write('ondemandmsg');
    },

    /*playOnDemandPreview: function() {
        this.buildFlashObj(getJsonUrl({action:'playlist', type:'ondemand', guideId:this.iCurrentOnDemandGuideId}));
    },
    
    playOnDemandMessageBegin: function() {
        $('player').style.display = 'none';
        $('ondemandmsg').style.display = 'block';

        this.swfOndemandMsg = new SWFObject('/swf/ondemand_begin.swf', 'ondemandmsg_beginobj', "100%", "100%", "7", "#000000");
        //this.swfOndemandMsg.addVariable('listTitle', 'Become a Premium Member to enjoy the following benefits:');
        //this.swfOndemandMsg.addVariable('bullet1', 'Over 7,000 hours of On Demand television growing every day.');
        //this.swfOndemandMsg.addVariable('bullet2', 'Sử dụng không giới hạn mọi lúc mọi nơi');//'Unlimited use of your Premium Membership anytime, anywhere.');
        //this.swfOndemandMsg.addVariable('bullet3', 'Lock down price, cancel anytime.');
        this.swfOndemandMsg.addVariable('commercialLength', '6');
        //this.swfOndemandMsg.addVariable('buyLink', '/#p=/account/subscribe');
        //this.swfOndemandMsg.addVariable('learnLink', '/#p=/help/faq');
        this.swfOndemandMsg.useExpressInstall('/swf/expressinstall.swf');
        this.swfOndemandMsg.write('ondemandmsg');
    },*/
    
    playOnDemandMessageEnd: function() {
        if( oUser.isSubscribedUser() )
            return;

        if( this.sMode=='min' )
            return;
            
        if( oGlobal.bIsLive==true )
            return;

        if( this.bIsTodayOnDemand==true )
            return;
            
        pageTracker._trackPageview('ondemandMessageEnd');

        this.container.style.display = 'none';
        $('ondemandmsg').style.display = 'block';

        this.swfOndemandMsg = new SWFObject('/swf/ondemand_end.swf', 'ondemandmsg_endobj', "100%", "100%", "7", "#000000");
        this.swfOndemandMsg.addVariable('mainTitle', (oGlobal.sCurrLang=='en' ? 'ON DEMAND' : 'THEOYÊUCẦU'));
        this.swfOndemandMsg.addVariable('subTitle', (oGlobal.sCurrLang=='en' ? 'BECOME A PREMIUM MEMBER' : 'DÀNH RIÊNG CHO THÀNH VIÊN VIP'));
        this.swfOndemandMsg.addVariable('listTitle', (oGlobal.sCurrLang=='en' ? 'Become a Premium Member to enjoy the following benefits:' : 'Đăng ký thành viên VIP để có những lợi ích sau đây:'));
        this.swfOndemandMsg.addVariable('bullet1', (oGlobal.sCurrLang=='en' ? 'Over 7,000 hours and 30,000 program of On Demand television growing every day.' : 'Hơn 7.000 giờ và 30.000 chương trình truyền hình Theo Yêu Cầu, cập nhật hàng ngày.'));
        this.swfOndemandMsg.addVariable('bullet2', (oGlobal.sCurrLang=='en' ? 'Unlimited use of your Premium Membership anytime, anywhere.': 'Sử dụng không giới hạn mọi lúc, mọi nơi.'));
        this.swfOndemandMsg.addVariable('bullet3', (oGlobal.sCurrLang=='en' ? 'Guaranteed price - buy now and never pay more; guaranteed satisfaction - cancel anytime.' : 'Giữ giá ngày hôm nay, hủy bất cứ lúc nào.'));
        this.swfOndemandMsg.addVariable('buyText', (oGlobal.sCurrLang=='en' ? 'Buy a Premium Membership' : 'Đăng ký thành viên VIP'));
        this.swfOndemandMsg.addVariable('buyLink', "javascript:oPlayer.subscribeButton_ondemandMsg_click()");
        this.swfOndemandMsg.addVariable('learnText', (oGlobal.sCurrLang=='en' ? 'Learn more' : 'Tìm hiểu thêm'));
        this.swfOndemandMsg.addVariable('learnLink', "javascript:oPlayer.learnmoreButton_ondemandMsg_click()");
        this.swfOndemandMsg.useExpressInstall('/swf/expressinstall.swf');
        this.swfOndemandMsg.write('ondemandmsg');

        $('showTitle').innerHTML = (oGlobal.sCurrLang=='en' ? 'To watch FREE Today-On-Demand TV, please use <a class="dotted_white" href="javascript:oGlobal.showTvGuide()">TV GUIDE</a>.' : 'Để xem MIỄN PHÍ chương trình TV hôm nay, xin xem trang <a class="dotted_white" href="javascript:oGlobal.showTvGuide()">LỊCH PHÁT</a>.');
        $('showOtherInfo').style.visibility = 'hidden';
        $('showRating_starcurr').style.visibility = 'hidden';
    },
    
    subscribeButton_ondemandMsg_click: function() {
        pageTracker._trackPageview('subscribeButton_ondemandMsg_click');
        oGlobal.navigate_textcontent('/account/subscribe');
    },
    
    learnmoreButton_ondemandMsg_click: function() {
        pageTracker._trackPageview('learnmoreButton_ondemandMsg_click');
        oGlobal.navigate_textcontent('/help/faq');
    },
    
    playLive: function(iChannelId) {
        this.buildFlashObj(getJsonUrl({action:'playlist', type:'live', channel:iChannelId}), true);
    },
    
    //
    // check feed if not available then force playing something that is for sure available
    //
    /*forcePlay: function(sFile) {
        var sUrl = sFile + '.json';
        var me = this;
        var handleSuccess = function(o){
            try {
                var arSegments = eval("(" + o.responseText + ")");

                if( arSegments.length<=0 ) {
                    $('showTitle').innerHTML = 'Requested program not available. Loading alternative ...';
                    //$('showTags').innerHTML = '';
                    //playGuide(me.getRandomTopProgram());
                }

            }
            catch(ex) {}
        }

        var handleFailure = function() {
        }

        YAHOO.util.Connect.asyncRequest('GET', sUrl, {success:handleSuccess, failure:handleFailure});
    },*/
    
    //
    // toggle between min and max showing
    //
    toggleMode: function() {
        if( !this.bInited ) return;

        this.sMode = (this.sMode=='max' ? 'min' : 'max');

        //
        // first time, flash object has not been built -> go to live by default
        //
        if( this.sMode!='min' && this.flashObj==null ) {
            this.playLive(oGlobal.iChannelId);
        }

        // make sure that on-demand message is not on
        this.container.style.display = 'block';
        $('ondemandmsg').style.display = 'none';

        $('player_container').className = 'player_container_' + this.sMode;
        this.container.className = 'player' + this.sMode;
        $('status_bar').style.visibility = (this.sMode=='max' ? 'visible' : 'hidden');
        $('playingInfo').style.display = (this.sMode=='max' ? 'block' : 'none');
        $('player_resume').style.display = (this.sMode=='max' ? 'none' : 'block');
    },
    
    minimize: function() {
        this.sMode = 'max';
        this.toggleMode();
    },
    
    maximize: function() {
        this.sMode = 'min';
        this.toggleMode();
    },
    
    hide: function() {
        if( this.flashObj!=null )
//            this.flashObj.style.display = 'none';
		this.flashObj.style.visibility = 'hidden';
    },
    
    show: function() {
        if( this.flashObj!=null )
//            this.flashObj.style.display = 'block';
		this.flashObj.style.visibility = 'visible';
    },

    getFlashObject: function() {
        if(navigator.appName.indexOf("Microsoft") != -1) {
            return window[this.sFlashId];
        } else {
            return document[this.sFlashId];
        }
    },
    
    stop: function() {
        var o = this.getFlashObject();
        if( o!=null && typeof o.sendEvent != 'undefined' )
            o.sendEvent('STOP');
    },

    playpause: function() {
        var o = this.getFlashObject();
        if( o!=null && typeof o.sendEvent != 'undefined' ) 
            o.sendEvent('PLAY');
    },
    
    play: function() {
	/*
        if( this.isPlaying==true )
            return;
        else
            this.playpause();
	*/
        var o = this.getFlashObject();
        if( o!=null && typeof o.sendEvent != 'undefined' ) 
            o.sendEvent('PLAY', true);
    },
    
    playItem: function(ind) {
        var o = this.getFlashObject();
        if( o!=null && typeof o.sendEvent != 'undefined' )
            o.sendEvent('ITEM', ind);
    },
    
    pause: function() {
	/*
        if( this.isPlaying==false )
            return;
        else
            this.playpause();
	*/
        var o = this.getFlashObject();
        if( o!=null && typeof o.sendEvent != 'undefined' ) 
            o.sendEvent('PLAY', false);
    }
    
}
var oPlayer = new VIET_vnl_ui_Player();

//
// JWPlayer 5 deprecated getUpdate function; instead, register event listener
//
function getUpdate_Item(obj) {
    try {

	var ind = obj.index;
    	//var obj = oPlayer.flashObj.getPlaylist()[ind];

	var segment = oGlobal.arCurrSegments[ind];
	var obj = new Array();

	obj['guideId'] = segment.guideId;
	obj['title'] = segment.guideDTitle;
	obj['normTitle'] = segment.guideTitle;
	obj['date'] = segment.airTimeStamp;
	obj['id'] = segment.id;

        //obj['guideId'] = obj['title'].substring(1, obj['title'].indexOf(']'));
        //var arTemp = obj['title'].substring(obj['title'].indexOf(']')+1).split("|");
        //obj['title'] = arTemp[0];
        //obj['normTitle'] = arTemp.length>0 ? arTemp[1] : '';

        var dt = new Date();
        dt.setTime(obj['date']*1000);
        oGlobal.player_onClipChange(obj['id'], obj['guideId'], obj['title'], dt, obj['normTitle']);        

	if( oGlobal.bIsLive==false && oPlayer.bIsTodayOnDemand==true && oUser.bIsLogin==false && (ind%5==4) )
            setTimeout("oPlayer.playSigninMessage()", 10000);
        oAgent.record(obj['guideId']);

    }
    catch(ex) { /* ignore error - not important */ }
}

function getUpdate_State(obj) {
    var currentState = obj.newstate; 
    var previousState = obj.oldstate; 

    oPlayer.isPlaying = (currentState=='PLAYING');

    if( currentState == 'COMPLETED' ) {
        oPlayer.playOnDemandMessageEnd();
        oAgent.stop();
    }
    else if( currentState == 'BUFFERING' || currentState == 'IDLE' || currentState == 'PAUSED' ) {
	oAgent.stop();
    }
    else if( currentState == 'PLAYING' ) {
	oAgent.play();
    }

}

//
// 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 (pr1= 0:stop, 1:buffer, 2:play), size
//
/*function getUpdate(typ, pr1, pr2, pid) {
    if( typ=="item" ) {

        var obj = $("floPlayer").itemData(pr1);
        try {
            obj['guideId'] = obj['title'].substring(1, obj['title'].indexOf(']'));
            var arTemp = obj['title'].substring(obj['title'].indexOf(']')+1).split("|");
            obj['title'] = arTemp[0];
            obj['normTitle'] = arTemp.length>0 ? arTemp[1] : '';
        }
        catch (ex) {}
        var dt = new Date();
        dt.setTime(obj['date']*1000);
        oGlobal.player_onClipChange(obj['id'], obj['guideId'], obj['title'], dt, obj['normTitle']);
        if( oGlobal.bIsLive==false && oPlayer.bIsTodayOnDemand==true && oUser.bIsLogin==false && (pr1%5==4) )
            setTimeout("oPlayer.playSigninMessage()", 10000);
        oAgent.record(obj['guideId']);
    }
    else if( typ=='state' ) {
        if( typeof oPlayer != 'undefined' ) {
            oPlayer.isPlaying = (pr1==2);
        }

        if( pr1==0 ) { // stop
            oPlayer.playOnDemandMessageEnd();
            oAgent.stop();
        }
        else if( pr1==1 ) { // buffer
            oAgent.stop();
        }
        else if( pr1==2 ) { // play
            oAgent.play();
        }
    }
}*/

/*function js_end_of_commercial(isEnded) {
    $('ondemandmsg').style.display = 'none';
    $('player').style.display = 'block';
    oPlayer.playOnDemandPreview(oPlayer.iCurrentOnDemandGuideId);
}*/

function js_skip_commercial(skip) {
    $('ondemandmsg').style.display = 'none';
    oGlobal.showPlayer();
    oPlayer.play();
}

function js_login(email, password) {
    oUser.signIn(email, password);
}

function js_register(firstName, lastName, email, password) {
    oUser.signUp(firstName, lastName, email, password);
}

