﻿var useFlash;
//Basic player object
var player;
player = $("<div id='player' style='display:block'></div>");
//Method that is called after player is added to the document
player.init = function () {
    for (var callback in player.initCalls) {
        player.initCalls[callback]();
    }
}

//Method to allow outside addons to perform actions after player is initialized
player.initCalls = new Array();
player.addInitCallBack = function (callback) {
    player.initCalls.push(callback);
};


$(document).ready(function () {
    var currentVideo = 0;
    useFlash = !supports_h264_baseline_video() | templateInfo.isFlash; //NO HTML5 VIDEO IF USING A FLV FILE OR FLASH TEMPLATE
    $("#videoPlayerWrapper").append(player); //Add our player

    //Set up the infobox    
    if (typeof (templateInfo.infoBox) != "undefined") {
        $("#videoPlayerWrapper").append("<div id='infoBox' style='display:inline;position:absolute'></div>"); //add the infotext
        $("#infoBox").append(infoTextSource);
        //Allow hyperlinks inside the infobox to work
        $("#infoBox a").click(function (event) {
            event.stopPropagation();
        });
        $("#infoBox").css(templateInfo.infoBox);
    }

    setupTemplate();

    //Handle the playlist
    if (xmlLocation.length > 0) {
        $.ajax({
            url: xmlLocation,
            type: "GET",
            contentType: "application/xml; charset=utf-8",
            success: function (playlist, textStatus, XMLHttpRequest) {
                clips = buildClipsList(playlist);
                if (clips.length == 0) { setupVideoPlaceholder(); return; }
                useFlash = !supports_h264_baseline_video() | clips.hasFLV | templateInfo.isFlash; //NO HTML5 VIDEO IF USING A FLV FILE OR FLASH TEMPLATE

                if (useFlash) {
                    //Initialize the player
                    initFlashPlayer(clips, autoPlay);
                }
                else {
                    // Uses HTML5
                    $("#playerposition").css({
                        width: templateInfo.playerWidth + 'px'
                    });

                    $("#player").css({
                        position: 'absolute',
                        top: templateInfo.playerY,
                        left: templateInfo.playerX,
                        backgroundColor: '#000000',
                        color: '#FFFFFFF',
                        fontSize: 'xx-large',
                        width: templateInfo.playerWidth + 'px',
                        height: templateInfo.playerHeight + 'px'
                    });

                    $("#player").append('<video id="htmlPlayer" controls width="' + templateInfo.playerWidth + '" height="' + templateInfo.playerHeight + '" poster="' + clips[currentVideo].thumb + '" src="' + clips[currentVideo].url + '"/>');
                    if (autoPlay) {
                        $("#htmlPlayer").bind('canplaythrough', function () { this.play(); });
                    }

                    $("#player video").click(function () {
                        if ((this.paused == false)) { this.pause(); }
                        else { this.play(); }
                        return false;
                    });

                    $("#htmlPlayer").bind('ended', function () {
                        if (currentVideo + 1 < clips.length) {
                            currentVideo++;
                            $("#player video").attr({
                                "src": clips[currentVideo].url,
                                "poster": clips[currentVideo].thumb,
                                "autoplay": true
                            });
                            this.load();
                            this.play();
                        }
                        else {
                            if ((typeof clips.redirect != "undefined" && clips.redirect != '') && autoPlay) {
                                location.href = clips.redirect;
                            }
                            else {
                                currentVideo = 0;
                                $("#player video").attr({
                                        "src": clips[currentVideo].url,
                                        "poster": clips[currentVideo].thumb,
                                        "autoplay": false
                                    });
                                this.load();
                            }
                        }
                    });

                }
                if (!useFlash) {
                    player.init();
                }
            },
            error: function (request, textStatus, errorThrown) {
                setupVideoPlaceholder();
            }
        });
    }
    else {
        setupVideoPlaceholder();
    }
});

function setupVideoPlaceholder() {
    vplayer = $("#player");

    if (templateInfo.isFlash) {
        initFlashPlayer([{ url: '/images/vmailEdit_defaultVideo.jpg', scaling: 'orig', autoplay: true}], true);
        $f().play();
    }
    else {
        $("<img />")
            .attr("src", "/images/vmailEdit_defaultVideo.jpg")
            .css({
                top: templateInfo.playerY,
                left: templateInfo.playerX,
                width: templateInfo.playerWidth + 'px',
                height: templateInfo.playerHeight + 'px',
                position: 'absolute'
            })
            .appendTo(vplayer);
        vplayer.attr("isPlaceholder", "true");
    }
}

function setupTemplate(useFlash) {
    if (templateInfo.backgroundImage != '') {
        canvasbackground = 'url(' + templateInfo.backgroundImage + ') no-repeat';
    }

    $("#videoPlayerWrapper").css({
        "background": canvasbackground,
        height: templateInfo.templateHeight + "px",
        width: templateInfo.templateWidth + "px",
        position: "relative"
    });
}

function buildClipsList(playlist) {
    //Gather playlist from XML file
    clips = [];
    clips.hasFLV = false;
    if (templateInfo.flashdelay > 0 && templateInfo.isFlash && autoPlay) {
        clips.push({ url: 'Images/1x1.png', duration: templateInfo.flashdelay, scaling: 'orig', autoplay: true });
    }
    var count = 0;
    $(playlist).find('video').each(function () {
        url = $(this).attr("url");
        if (url != "") {
            clips.push({
                url: url,
                scaling: 'autofit',
                autoPlay: (autoPlay | count > 0),
                thumb: url.replace(".mp4", "_thumb.jpg")
            });
            count++;
            if (url.split('.').pop() == "flv") { clips.hasFLV = true; }
        }
    });
    clips.redirect = $(playlist).find('redirect').attr("url");
    if (typeof clips.redirect != "undefined" && clips.redirect.length > 8) {
        if (clips.redirect.substr(0, 7) != 'http://' && clips.redirect.substr(0, 8) != 'https://') {
            clips.redirect = 'http://' + clips.redirect;
        }
    }
    //We need a poster for the playlist if we're using the flash player without autoplay.
    if (useFlash && !autoPlay) {
        clips.unshift({
            url: clips[0].url.replace(".mp4", "_thumb.jpg"),
            scaling: 'autofit',
            autoPlay: true
        });
    }
    return clips;
}

function initFlashPlayer(clips, autoPlay) {
    if (!templateInfo.isFlash) {
        $("#player")
			.width(templateInfo.playerWidth)
			.height(templateInfo.playerHeight)
			.css({
			    top: templateInfo.playerY,
			    left: templateInfo.playerX,
			    position: 'absolute'
			});

			params = {
			    src: 'flowplayer.commercial-3.2.5.swf',
			    wmode: 'transparent',
			    width: templateInfo.playerWidth,
			    height: templateInfo.playerHeight
			};

			config = {
			    plugins: {
			        controls: {
			            autoHide: true
			        }
			    },
			    key: ['#@ca6cffecb2528c8f70f', '#@20609bda10842d66960'],
			    autoPlay: autoPlay,
			    clip: { autoPlay: autoPlay, scaling: 'fit' },
			    playlist: clips,
			    onLoad: function () {
			        player.init();
			    },
			    onFinish: function (clip) {
			        if ((typeof clips.redirect != "undefined" && clips.redirect != '') && autoPlay) {
			            if (clip.index === clips.length-1) {
			                location.href = clips.redirect;
			            }
			        }
			    }
			};
        return $("#player").flowplayer(params, config);
    }
    else {
        // This is to setup the template that uses full flash. Depreciated and only used not for legacy Vmails.
        params = {
            src: 'flowplayer.commercial-3.2.5.swf',
            wmode: 'transparent',
            width: templateInfo.templateWidth,
            height: templateInfo.templateHeight
        };

        config = {
            key: '#@ca6cffecb2528c8f70f',
            autoPlay: autoPlay,
            clip: { autoPlay: autoPlay, scaling: 'fit' },
            playlist: clips,
            canvas: { background: 'url(' + templateInfo.backgroundImage + ') no-repeat' },
            screen: {
                top: templateInfo.playerY,
                left: templateInfo.playerX,
                width: templateInfo.playerWidth,
                height: templateInfo.playerHeight
            },
            plugins: {
                controls: {
                    top: (templateInfo.playerY + templateInfo.playerHeight - 14) + "px",  //Not sure why, but the controls are 14px lower than they should be.
                    left: templateInfo.playerX + "px",
                    width: templateInfo.playerWidth
                }
            }
        };

        return $("#player").flowplayer(params, config);
    }
}

function getFlashVersion() {
    // ie
    try {
        try {
            // avoid fp6 minor version lookup issues
            // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch (e) { return '6,0,0'; }
        } catch (e) { }
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
        // other browsers
    } catch (e) {
        try {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch (e) { }
    }
    return '0,0,0';
}

function supports_h264_baseline_video() {
    if (!supports_video()) { return false; }
    var v = document.createElement("video");
    return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

function supports_video() {
    if (detectChrome()) {
        return false;
    }
    return !!document.createElement('video').canPlayType;
}

var uagent = navigator.userAgent.toLowerCase();
var deviceAndroid = "android";

//**************************
// Detects if the current device is an Android OS-based device.
function DetectAndroid() {
    if (uagent.search(deviceAndroid) > -1)
        return true;
    else
        return false;
}

function detectChrome() {
    if (uagent.search("chrome") > -1) {
        return true;
    }
    return false;
}
