
/********************************************************************
 * FlowPlayerAdverts.js
 * Usage:
 * - Populate a Config.videoConfig object with required settings
 * - var myVideo = new VideoManager(...)
 * - myVideo.RenderPlayer("dom-element-to-render-to")
 *
 ********************************************************************/
// if console is not defined, e.g., Firebug console is not enabled or Non-Firefox browser

//if (typeof console == 'undefined') {
    //var console = {};
/*    console.log = function(msg){
        return;
    };*/
//}

Config = {};
Config.VideoConfig = {};

// Filenames for flowplayer flash files
Config.VideoConfig.FLOWPLAYER_SWF = 'flowplayer.commercial-3.1.5.swf';
Config.VideoConfig.FLOWPLAYER_RTMP = 'flowplayer.rtmp-3.1.3.swf';
Config.VideoConfig.FLOWPLAYER_AKAMAI = 'flowplayer.akamai-3.1.3.swf';

function VideoManager(videoPlayList, minimalistMode, startMuted, autoPlay, imageSplashUrl) {

    this.videoPlayList = videoPlayList;
    // Determines if the player has been set to run in minimalist mode (fewer controls)
    this.isMinimalistMode = (typeof (minimalistMode) != "undefined" && minimalistMode == true);

    // Determines if the player should be muted on startup
    this.startMuted = (typeof (startMuted) != "undefined" && startMuted == true);

    // Determines if the player should be muted on startup
    this.autoPlay = (typeof (autoPlay) != "undefined" && autoPlay == true);
     
	//Initialises flowplayer    
	//domElement - DOM Object to replace with flowplayer
    this.RenderPlayer = function(domElement) {
        var videoUrls = this.videoPlayList;
        var mute = this.startMuted;

        //Splash image
        var image_splash = {
            onStart: function() {
                this.getControls().show();
            },
            url: typeof imageSplashUrl != 'undefined' ? imageSplashUrl : Config.VideoConfig.VideoSplashImage,
            onBeforeBegin: function() {
                this.getPlugin("canvas").css({
                    backgroundColor: '#000000',
                    backgroundGradient: 'none'
                });

                //Default to mute on mini-video on homepage
                if (mute)
                    this.mute();
                else
                    this.unmute();
            }
        };

        //Initialise clips array and insert splash image   
        var clips = new Array(videoUrls.length + 1);
        clips[0] = image_splash;

        for (var vidIdx = 0; vidIdx < videoUrls.length; vidIdx++) {
            //Add prefix to relative URLs
            if (!Config.IsAbsoluteUrl(videoUrls[vidIdx])) {
                videoUrls[vidIdx] = Config.VideoConfig.RelativePathPrefix + videoUrls[vidIdx];
            }

            var videoUrlFull = videoUrls[vidIdx];
            var videoPath = videoUrlFull.substring(0, videoUrlFull.lastIndexOf('/') + 1);
            var videoFilename = videoUrlFull.substring(videoUrlFull.lastIndexOf('/') + 1, videoUrlFull.lastIndexOf('.'));

            //Video
            var videoClip = {
                url: videoUrlFull,
                onBeforeBegin: function() {
                    this.getPlugin("canvas").css({
                        backgroundColor: '#000000',
                        backgroundGradient: 'none'
                    });
                    this.getControls().show();
                },
                autoPlay: false,
                autoBuffering: false, // Video will be buffered when splash screen is visible
                scaling:'fit',
                onStart: function() {
                    console.log('Video started');
                }
            };

            if (Config.IsRtmpStream(videoUrlFull))
                videoClip.provider = 'rtmp';
            else
                videoClip.urlResolvers = null;

            clips[vidIdx + 1] = videoClip;
        }


        //Set up pre and post rolls
        var i;
        for (i = 0; i < Config.prerolls.length; i++) {
            clips.splice(1, 0, Config.prerolls[i]);
        }

        for (i = 0; i < Config.postrolls.length; i++) {
            clips.push(Config.postrolls[i]);
        }
        
        clips[1].autoPlay = autoPlay;

        // Minimalist control settings
        var minimalistControls = {
            autoHide: 'always',
            borderRadius: '0px',
            sliderColor: '#893438',
            durationColor: '#ffffff',
            timeBgColor: '#555555',
            bufferGradient: 'none',
            volumeSliderColor: '#000000',
            sliderGradient: 'none',
            tooltipTextColor: '#ffffff',
            buttonColor: '#424242',
            backgroundColor: '#242424',
            timeColor: '#01DAFF',
            backgroundGradient: 'none',
            volumeSliderGradient: 'none',
            tooltipColor: '#5F747C',
            buttonOverColor: '#d6001b',
            progressColor: '#999999',
            bufferColor: '#3d3d3d',
            progressGradient: 'medium',
            height: 24,
            opacity: 1.0,
            mute: true,
            scrubber: true,
            volume: true,
            time: false
        };

        // Settings to use for flowplayer
        var includedPlugins = {
            rtmp: {
                url: Config.VideoConfig.FlowPlayerSwfPath + Config.VideoConfig.FLOWPLAYER_RTMP
            },
            akamai: {
                url: Config.VideoConfig.FlowPlayerSwfPath + Config.VideoConfig.FLOWPLAYER_AKAMAI
            },
            controls: {
                borderRadius: '0px',
                sliderColor: '#893438',
                durationColor: '#ffffff',
                timeBgColor: '#555555',
                bufferGradient: 'none',
                volumeSliderColor: '#000000',
                sliderGradient: 'none',
                tooltipTextColor: '#ffffff',
                buttonColor: '#424242',
                backgroundColor: '#242424',
                timeColor: '#01DAFF',
                backgroundGradient: 'none',
                volumeSliderGradient: 'none',
                tooltipColor: '#5F747C',
                buttonOverColor: '#d6001b',
                progressColor: '#999999',
                bufferColor: '#3d3d3d',
                progressGradient: 'medium',
                height: 24,
                opacity: 1,
                time: false,
                mute: true
            }
        };

        //Wait until DOM is ready before playing video to make
        //sure all prerolls, postrolls have been injected.
        $(document).ready(function() {

            // If minimalistPlayer has been set to true then show a subset
            // of the usual controls. Usually used for thumbnail-sized videos.

            //console.log("Starting flowplayer");

            if (this.isMinimalistMode)
                includedPlugins["controls"] = minimalistControls;

            flowplayer(domElement, {
                src: Config.VideoConfig.FlowPlayerSwfPath + Config.VideoConfig.FLOWPLAYER_SWF,
                wmode: 'transparent'
            },
            {
                key: Config.VideoConfig.FlowPlayerLicenceKey,
                playlist: clips,
                plugins: includedPlugins
            }
            );
        });
    }
};

// Static variables/methods below
// -----------------------------------

Config.prerolls = [];
Config.postrolls = [];

// Determines if a specified URI looks like an RTMP (or RTMPT) stream
Config.IsRtmpStream = function(uri) {
    return uri.indexOf('rtmp://') == 0 || uri.indexOf('rtmpt://') == 0;
};

// Determines if a URI is absolute or relative
Config.IsAbsoluteUrl = function(uri) {
    return uri.indexOf('://') >= 0;
};

//Inserts a preroll video
Config.InsertPreRoll = function(video_url, link_url) {
    console.log('Insert Pre Roll');
    var preroll = Config.CreateVideoAdvert(video_url, link_url);
    Config.prerolls.splice(0, 0, Config.getShortAdvertismentSplash());
    Config.prerolls.splice(0, 0, preroll);    
}

//Inserts a postroll video
Config.InsertPostRoll = function(video_url, link_url) {
    console.log('Insert Post Roll');
    var postroll = Config.CreateVideoAdvert(video_url, link_url);
    Config.postrolls.push(Config.getShortAdvertismentSplash());
    Config.postrolls.push(postroll);
}

// Creates a clip object for the specified video and linking to the specified URL
// Created as an advert so has particular settings to prevent user skipping etc.
Config.CreateVideoAdvert = function(video_url, link_url) {
    // Add prefix to relative URLs
    if (!Config.IsAbsoluteUrl(video_url)) {
        video_url = Config.VideoConfig.RelativePathPrefix + videoUrls[vidIdx];
    }

    // Complete URI to video (e.g. http://www.test.com/video/test.flv)
    var videoUrlFull = video_url;

    // URI up to but not including the filename (e.g. http://www.test.com/video/)
    var videoPath = videoUrlFull.substring(0, videoUrlFull.lastIndexOf('/') + 1);

    // Just the filename (e.g. test.flv)
    var videoFilename = videoUrlFull.substring(videoUrlFull.lastIndexOf('/') + 1, videoUrlFull.lastIndexOf('.'));

    console.log("Creating advert clip");
    var videoClip = {
        url: videoUrlFull,
        onBeforePause: function() {
            return false;
        },
        onBeforeBegin: function() {
            this.getPlugin("canvas").css({
                backgroundColor: '#ffffff',
                backgroundGradient: 'none'
            });
        },
        onFinish: function() {
            this.getControls().show();
        },
        autoBuffering: false, // Video will be buffered when splash screen is visible
        autoPlay: true,
        scaling: 'fit',
        onStart: function() {
            console.log('Advert started');
        }
    };

    // Disable the URL resolvers from the RTMP/Akamai plugins if we have a vanilla HTTP stream
    if (Config.IsRtmpStream(videoUrlFull))
        videoClip.provider = 'rtmp';
    else
        videoClip.urlResolvers = null;

    // Where applicable, set the video link so that it can be clicked on
    if (typeof link_url != 'undefined') {
        videoClip.linkUrl = link_url;
        videoClip.linkWindow = "_blank";
    }

    return videoClip;
}

// Clip for the advert splash (image with 'ADVERTISEMENT' text)
Config.getShortAdvertismentSplash = function() {
return {
//url: Config.VideoConfig.AdvertSplashImage,
url: "http://www.condenast.co.uk/sponsorships/short-advertisement.gif",
    onBeforePause: function() {
        return false;
    },
    onBeforeBegin: function() {
        this.getControls().hide();
    },
    scaling: 'orig',
    autoPlay: true
};
};

//TODO: Get rid of this when possible, here for backwards compatibility
//whilst Adidas advert is running (14/01/2010).
function InsertPreRoll(video_url, link_url) {
    return Config.InsertPreRoll(video_url, link_url);
}

function InsertPostRoll(video_url, link_url) {
    return Config.InsertPostRoll(video_url, link_url);
}