(function($) {

    $(function() {

        var FLOWPLAYER_KEY = "@256cd89c25de41c8cd8";

        // Default speed, if user plays a video before bandwidth detection completes
        var speed = "lo";

        // Don't remember previously detected bandwidth's
        var ignoreCookie = true;

        // Target Div on page
        var container = $("#player");

        // Video Hosting Location
        var prefix = "http://video.availablelight.tv";

        // Log debug messages, if debug element exists
        var debug = function(message) {
            $("#debug").append(message + "<br>");
        }

        // Create a cookie
        var createCookie = function(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        // Read a cookie
        var readCookie = function(name) {
            name += "=";
            var cookies = document.cookie.split(";");
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i];
                while (cookie.charAt(0) == " ") { cookie = cookie.substring(1, cookie.length); }
                if (cookie.indexOf(name) == 0) { return cookie.substring(name.length, cookie.length); }
            }
            return null;
        }

        // Make ajax call for garbage data
        var detectBandwidth = function(callback) {
            var bandwidth = parseInt(readCookie("bandwidth"));
           if (ignoreCookie || isNaN(bandwidth)) {
                var startTime = new Date().getTime();
                $.getJSON(prefix + "/bw-garbage.aspx?callback=?", function(msg) {
                    var endTime = new Date().getTime();
                    var bytes = msg;
                    bandwidth = calcBandwidth((endTime - startTime), bytes);
                    debug("bandwidth: " + bandwidth + "kbps (test)");
                    callback(bandwidth);
                });
            } else {
                debug("bandwidth: " + bandwidth + "kbps (cookie)");
                callback(bandwidth);
            }
        }

        // Calculate bandwidth
        var calcBandwidth = function(duration, bytes) {
            // convert from msecs to secs
            var duration = duration / 1000;
            // convert from bytes to kbits
            var kbits = (bytes * 8) / 1024;
            // calculate bandwidth (incl. packet header overhead ~7%)
            var bandwidth = Math.floor(kbits / duration * .93);
            createCookie("bandwidth", bandwidth);
            return bandwidth;
        }

        // Play a video
        var play = function(u, autoPlay, i) {
            var opts = { key: FLOWPLAYER_KEY };
            var url = u.replace("-hi.", "-" + speed + ".");
            if (autoPlay)
                opts["clip"] = {
                    url: url,
                    autoPlay: true,
                    scaling: 'fit' // 'orig'
                };
            else
                opts["playlist"] = [{
                    url: i.replace("-102x58.", "-384x216."),
                    scaling: 'orig'
                }, {
                    url: url,
                    autoPlay: false,
                    scaling: 'fit' // 'orig'
                }];

if (typeof OLD_FP == "undefined")
    flowplayer("fp", prefix + "/scripts/flowplayer/flowplayer.commercial-3.1.1.swf", opts);
else
    flowplayer("fp", prefix + "/scripts/flowplayer/flowplayer-3.0.7.swf", opts);

         }

        // Listen for clicks in playlist
        $(".playlist li", container).live("click", function() {
            var u = $("a", this).attr("href");
            play(u, true);
            return false;
        });

        // Create html for viewer and playlist
        container.append('<div class="viewer" id="fp"></div><div class="playlist"><ul></ul></div>');

        // Request and render playlist, load first video
        $.getJSON(prefix + "/Video/Playlist?callback=?", { thumbnail_width: 102, thumbnail_height: 58 },
            function(data) {
                $.each(data, function(i, item) {
                    var img = $("<img/>").attr("src", item.Thumbnail);
                    var a = $("<a>").attr("href", item.Url.Hi);
                    var h2 = $('<h2>').append($("<a>").attr("href", item.Url.Hi).text(item.Title));
                    var li = $("<li>");
                    li.append(a.append(img));
                    li.append(h2);
                    item.Created = new Date(parseInt(item.Created.replace("/Date(", "").replace(")/", ""), 10)).toDateString();
                    li.append($('<p class="description">').text(item.Description));
                    li.append($('<p class="date">').text(item.Created));
                    li.appendTo($(".playlist ul", container));
                });

                detectBandwidth(function(bandwidth) {
                    if (bandwidth < 800) {
                        debug("your slow");
                        speed = "lo";
                    } else if (bandwidth < 1024) {
                        debug("your med");
                        speed = "med";
                    } else {
                        debug("your fast");
                        speed = "hi";
                    }
                    play(data[0].Url.Hi, false, data[0].Thumbnail);
                });

            }
        );

    });

})(jQuery);
