var cookieid;
var StreamingPlayer = {
    refreshId: 0
};

//Live Player - mainly for weekends
function CreateStreamingPlayer(divToReplace, playerWidth, playerHeight, playerHeightDisplay, autoStart, streamName, multicastID, imageURL, mediaLibraryID) {
    var baseUrl = 'rtmp://cp40631.live.edgefcs.net/live';
    var wowzaVodLiveIP = '204.236.131.5';
    var androidUrl = "rtsp://" + wowzaVodLiveIP + "/rtplive/svcc.sdp";
    var iOSUrl = "http://" + wowzaVodLiveIP + "/live/iphone/playlist.m3u8";
    var iOSHighQualityUrl = "http://" + wowzaVodLiveIP + "/live/ipad/playlist.m3u8";
    var jwPlayerSWF = 'http://sitekick.s3.amazonaws.com/flash/jw5.2/player.swf';
    var cookieKey = 'SaddlebackLiveStream';

    if (mediaLibraryID === undefined) {
        mediaLibraryID = '3668';
    }

    if (streamName == null || streamName === undefined) {
        //streamName = "SaddlebackChurch@1274"; 
        streamName = "SaddlebackChurch_1@3073";
    }
    if (multicastID == null || multicastID === undefined) {
        //multilcastID = "1q82er74";
        //multicastID = "fmx9afvq";
        multicastID = "u946a1or";

    }
    if (divToReplace == null || divToReplace === undefined) {
        divToReplace = "liveplayer";
    }
    if (autoStart == null || autoStart === undefined) {
        autoStart = true;
    }
    if (imageURL == null || imageURL === undefined) {
        imageURL = null;
    }

    var flashvars = {
        streamer: baseUrl,
        file: streamName,
        provider: 'rtmp',
        e: multicastID,
        'rtmp.subscribe': 'true',
        width: playerWidth,
        height: playerHeight,
        autostart: autoStart,
        image: imageURL,
        displayheight: playerHeightDisplay,
        quality: 'true',
        showdigits: 'true',
        showicons: 'true',
        backcolor: '000000',
        frontcolor: 'CCCCCC',
        controlbar: 'over',
        skin: 'http://sitekick.s3.amazonaws.com/flash/stylish_slim.swf'
    };
    var params = { allowfullscreen: 'true',
        allowscriptaccess: 'always',
        menu: 'false',
        stretching: 'uniform',
        wmode: 'opaque'
    };
    var attributes = { id: divToReplace, name: divToReplace };

    var deviceAgent = navigator.userAgent.toLowerCase();
    if (deviceAgent.match(/(iphone|ipod|ipad)/)) {
        if (deviceAgent.match(/(ipad)/)) {
            iOSUrl = iOSHighQualityUrl;
        }
        var player = '<video id="html5iOS" controls preload="none" autoplay height="' + playerHeight + '" width="' + playerWidth + '">';
        player += '<source src="' + iOSUrl + '" />';
        player += '</video>';
        $('#' + divToReplace).html(player);
    }
    else if (deviceAgent.match(/(android)/)) {
        window.location = androidUrl;
    }
    else {
        swfobject.embedSWF(jwPlayerSWF, divToReplace, playerWidth, playerHeight, "9", false, flashvars, params, attributes);
    }

    cookieid = $.cookie(cookieKey);

    if (cookieid == null) {
        cookieid = 1;
        cookieid = Math.random().toString(16).substring(2);
        $.cookie(cookieKey, cookieid);
    }

    MediaLibraryStatUpdate(mediaLibraryID, cookieid);
    // Polling Loop every 5 mins
    if (StreamingPlayer.refreshId > 0) {
        clearInterval(StreamingPlayer.refreshId);
    }
    StreamingPlayer.refreshId = setInterval(function () {
        MediaLibraryStatUpdate(mediaLibraryID, cookieid);
    }, 300000);

};

function CreateSLPlayerRoundRobin(divToReplace, playerWidth, playerHeight, playerHeightDisplay, autoStart, streamName, mediaLibraryID, divDebug) {
    var edgeServer = 'edge1.saddlebackcloud.com';
    var appName = 'liverepeater';

    var deviceAgent = navigator.userAgent.toLowerCase();
    var html5 = deviceAgent.match(/(iphone|ipod|ipad|appletv|android)/);

    var url = '/services/wowza/loadbalancer.asmx/GetOptimal';
    $.ajax({
        type: "GET",
        cache: false,
        async: false,
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            edgeServer = data.d.PublicDNS;
        }
    });

    //Switch between appName liverepeater/livereapeater2
    if ($.cookie('simliveapp') === null) {
        $.cookie("simliveapp", appName);
    }
    else {
        if ($.cookie('simliveapp') == 'liverepeater') {
            appName = 'liverepeater2';
        }
        else {
            appName = 'liverepeater';
        }
    }
    $.cookie("simliveapp", appName);

    if (divDebug) {
        $('#' + divDebug).append('<br /> rtmp://' + edgeServer + '/' + appName);
    }

    var baseUrl = 'rtmp://' + edgeServer + '/' + appName;
    var jwPlayerSWF = 'http://sitekick.s3.amazonaws.com/flash/jw5.3/player.swf';
    var cookieKey = 'SaddlebackLiveStream';

    if (mediaLibraryID === undefined) {
        mediaLibraryID = '3668';
    }

    if (divToReplace == null || divToReplace === undefined) {
        divToReplace = "liveplayer";
    }
    if (autoStart == null || autoStart === undefined) {
        autoStart = true;
    }

    if (html5 == null) {
        var flashvars = {
            streamer: baseUrl,
            file: streamName,
            provider: 'rtmp',
            width: playerWidth,
            height: playerHeight,
            autostart: autoStart,
            displayheight: playerHeightDisplay,
            quality: 'true',
            showdigits: 'true',
            showicons: 'true',
            backcolor: '000000',
            frontcolor: 'CCCCCC',
            controlbar: 'over',
            stretching: 'exactfit',
            skin: 'http://sitekick.s3.amazonaws.com/flash/stylish_slim.swf'
        };
        var params = { allowfullscreen: 'true',
            allowscriptaccess: 'always',
            menu: 'false',
            stretching: 'uniform',
            wmode: 'opaque'
        };
        var attributes = { id: divToReplace, name: divToReplace };

        swfobject.embedSWF(jwPlayerSWF, divToReplace, playerWidth, playerHeight, "9", false, flashvars, params, attributes);

        cookieid = $.cookie(cookieKey);

        if (cookieid == null) {
            cookieid = 1;
            cookieid = Math.random().toString(16).substring(2);
            $.cookie(cookieKey, cookieid);
        }

        MediaLibraryStatUpdate(mediaLibraryID, cookieid);

        // Polling Loop every 5 mins
        if (StreamingPlayer.refreshId > 0) {
            clearInterval(StreamingPlayer.refreshId);
        }
        StreamingPlayer.refreshId = setInterval(function () {
            MediaLibraryStatUpdate(mediaLibraryID, cookieid);
        }, 300000);

    }
    else {
        if (streamName === "web") {
            streamName = "mobile";
        }
        if (deviceAgent.match(/(iphone|ipod|ipad)/)) {
            window.location = 'http://' + edgeServer + ':1935' + '/' + appName + '/' + streamName + '/playlist.m3u8';
        }
        if (deviceAgent.match(/(android)/)) { 
            window.location = 'rtsp://' + edgeServer + '/' + appName + '/_definst_/' + streamName;
        }
    }
}

function MediaLibraryStatUpdate(mediaLibraryID, cookieID) {
    //change url
    var url = "/mc/player/stattracking.aspx";
    if (document.URL.toLowerCase().indexOf("//conf.") >= 0 || document.URL.toLowerCase().indexOf("//conference-") >= 0 || document.URL.toLowerCase().indexOf("//conferencelocal") >= 0) {
        //Conference Tracking using Image
        url = "http://saddleback.com" + url;
        url = url.replace("stattracking.aspx", "stattrackingimage.aspx");
        url = url + "?m=" + mediaLibraryID + "&c=" + cookieID + "&_tt=" + (new Date()).getTime();
        $("#videoTracking").html('<img src="' + url + '" height="1" width="1" />');
    }
    else {
        url = url + "?m=" + mediaLibraryID + "&c=" + cookieID;
        $.ajax({
            url: url,
            cache: false
        });
    }
};

