﻿var playerDiv;
var _assetsBasePath = '../Assets';
var _title;

//FOR Published
var _EmailShare = "/ShareVideo.ashx";

//FOR Local server (eg: zwdev04)
//var _EmailShare = "/CB.Web.UI.Public2/ShareVideo.ashx";


var PlugInType = { SL: 0, Flash: 1, HTML: 2, None: 3 };
var CurrentPlugIn;

/*-------start helper methods --------*/
function embedSilverlightPlayer(parentElement, pluginId, userContext, movieUrl, linkUrl, embedTag, height, width,autoPlay) {
    var altHtml = pluginId == "sl2" ? null : "<!--not installed-->";

    var stretchMode = "Stretch";
    if (!autoPlay)
        stretchMode = "Fit";

    return Silverlight.createObjectEx({
    source: "/Assets/VideoPlayer/SL/OVP.xap",
        parentElement: parentElement,
        id: pluginId,
        properties: {
            width: width,
            height: height,
            background: "black",
            alt: "<!--not installed-->",
            version: "2.0.31005.0"
        },
        events: {
            onError: onSilverlightError,
            onLoad: onSLLoad
        },
        initParams: 'showstatistics=false, autoplay=' + autoPlay + ', muted=false, playlistoverlay=false, theme=../Assets/VideoPlayer/Themes/SmoothHD.xaml, stretchmode=' + stretchMode 
        + ', stretchmodefullscreen=' + stretchMode +', mediasource=' + movieUrl + ', linkurl=' + linkUrl + ', embedtag=' + embedTag + ',videotitle=' + _title + ',logoImage=http://bainv2.zaifworks.com/Assets/VideoPlayer/logo.png,emailscripturl='+_EmailShare,
        context: userContext
    });

}


function onSLLoad(plugIn, userContext, sender) {
    //            window.status +=
    //                plugIn.id + " loaded into " + userContext + ". ";
}


function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }

    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    if (errorType == "ImageError" || errorType == "MediaError") {
        return;
    }

    var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}

function IsMobileDevice() {
    return gv_IsMobileDevice || ((jQuery.browser.iPhone)
    || (jQuery.browser.iPod)
    || (jQuery.browser.iPad)
    || (jQuery.browser.Android)
    );
}


/*-------end helper methods --------*/


function PlaySLVideo(url, linkUrl, embedTag, width, height,autoPlay) {
    $('#' + playerDiv).show();
    var slcontent = document.getElementById(playerDiv);
    embedSilverlightPlayer(slcontent, 'sl2', "context", url, linkUrl, embedTag, height, width,autoPlay);
    return false;

}
//http: //releases.flowplayer.org/flowplayer.viralvideos/flowplayer.viralvideos-3.2.2.swf

function PlayFlashVideo(url, pageUrl, embedTag, width, height,autoplay) {
    $('#' + playerDiv).show();

    var stretchMode = "scale";
    if (!autoplay)
        stretchMode = "fit";
    
    var msgTemplate = '{0} \n\n Video Link:'+encodeURIComponent(pageUrl);
    flowplayer(playerDiv, _assetsBasePath+"/VideoPlayer/Flash/flowplayer-3.2.3-0.swf", {
    // player configuration goes here
        canvas: {
            // customize player background, i.e. the canvas
            backgroundColor: "#000000",
            // remove default canvas gradient
            backgroundGradient: 'none'
        },
        clip: { url: url, autoPlay: autoplay,scaling:stretchMode },
        
        plugins: {
            controls: {
                buttonColor: 'rgba(204, 204, 204, 1)',
                buttonOverColor: '#FFFFFF',
                backgroundColor: '#000000',
                backgroundGradient: 'none',

                sliderColor: '#FFFFFF',
                sliderBorder: '1px solid #666666',
                volumeSliderColor: '#FFFFFF',
                volumeBorder: '1px solid #666666', 

                timeColor: '#666666',
                durationColor: '#666666',

                tooltipColor: 'rgba(255, 255, 255, 0.7)',
                tooltipTextColor: '#000000'
            },
            viral: {
                // load the viral videos plugin
            url: _assetsBasePath + '/VideoPlayer/Flash/flowplayer.viralvideos-3.2.2.swf',
            

                //http://flowplayer.org/plugins/flash/viralvideos.html#download
                // define a video title used in sharing
            share: {
                    description: _title,
                    facebook:true,
                    twitter:true,
                    myspace:false,
                    livespaces:false,
                    digg:true,
                    orkut:false,
                    stubmbleupon:false,
                    bebo:false
                },
                email: {
                // user server-side email sending script
                    script: _EmailShare,
                    texts: {
                    template: msgTemplate
                    }
                },
                embed: {
                    // change the main title shown in the UI
                    title: 'Copy and paste following code to your page'

                }


            }
        }
    });
    return false;
}


function PlayHTML5Video(url, linkUrl, embedTag, width, height) {
    var html5Video = '  <video id="videoHtml5" class="video-js" width="' + width + '" height="' + height + '" controls preload loop="loop" autoplay="autoplay" autobuffer="autobuffer"> ' +
                                 '      <source src="' + url + '" type="video/mp4"> ' +
                                 '  </video> ';
//    var html5Video = '<div class="video-js-box">' +
//                             '  <video id="videoHtml5" class="video-js" width="350" height="250" controls preload> ' +
//                             '      <source src="' + url + '" type="video/mp4"> ' +
//                             '  </video> ' +
//                             '</div>    ';
    $('#' + playerDiv).html('').show();
    $('#' + playerDiv).html(html5Video);

    try {
        $('#videoHtml5').attr('src', url);
        $('#videoHtml5')[0].load();
    }
    catch (Error) {  }
    //document.getElementById('videoHtml5').play();
//    $(document).load(function() {
//        VideoJS.setup();
//    });
}

function PauseVideo() {
    try {
        player = document.getElementById(playerDiv).childNodes[0];
        switch (CurrentPlugIn) {
            case PlugInType.None:
                break;
            case PlugInType.SL:
                player.content.OpenVideoPlayerControl.Pause();
                break;
            case PlugInType.Flash:
                $f().pause();
                break;
            case PlugInType.HTML:
                player.stop();
                break;
            default:
                break;

        }
    }
    catch (Error) { }
}

function LoadPlayerAndPlay(urlHD, urlMob, linkurl, embedurl, playerDivID, width, height, assetsBasePath, title,autoPlay) {
    var silverlightVersion = '3.0.40620';
    playerDiv = playerDivID;
     
    if (autoPlay == undefined)
        autoPlay = true;
    _title = title;
    var titleMaxLength = 138 - linkurl.toString().length;
    if (_title.length > titleMaxLength && titleMaxLength > 3)
        _title = _title.toString().substring(0, titleMaxLength - 3) + '...';
    _assetsBasePath = assetsBasePath;
    //detect if not an apple device
    if (!IsMobileDevice()) {
        if (jQuery.browser.sl && !jQuery.browser.mac) {
            if (!Silverlight.isInstalled(silverlightVersion)) {
                if (confirm('An earlier version of SilverLight was found. Please upgrade to version: ' + silverlightVersion + ' to view this video. Do you want to upgrade?')) {
                    Silverlight.getSilverlight(silverlightVersion);
                }
                CurrentPlugIn = PlugInType.None;
            }
            else {
                PlaySLVideo(urlHD, linkurl, embedurl, width, height,autoPlay);
                CurrentPlugIn = PlugInType.SL;
            }
        }
        else if (jQuery.browser.flash) {
        PlayFlashVideo(urlHD, linkurl, embedurl, width, height,autoPlay);
        CurrentPlugIn = PlugInType.Flash;
        
        }
        else if (jQuery.browser.html5 && jQuery.browser.h264) {
        PlayHTML5Video(urlHD, linkurl, embedurl, width, height);
        CurrentPlugIn = PlugInType.HTML;
        }
        else {
            CurrentPlugIn = PlugInType.None;
            if (confirm('To play videos you need to install Silverlight ' + silverlightVersion + '. Do you want to install?')) {
                Silverlight.getSilverlight(silverlightVersion);
            }
            else {
                $('#divMsg').show();
            }

        }

    }
    else {
        if (jQuery.browser.Android && jQuery.browser.flash) {
            PlayFlashVideo(urlHD, linkurl, embedurl, width, height, autoPlay);
            CurrentPlugIn = PlugInType.Flash;
        }
        else
            PlayHTML5Video(urlMob, linkurl, embedurl, width, height);
    }
}

