jQuery(document).ready(function($) {
    try {
        var player = _V_('kult1tv-player');
    } catch(e) {
        return; // if browser is not supported by videojs, stop here
    }

    player.ready(function() {
        var playlist_position = 0;

        if(typeof(window["kult1tv_videojs_playlist"]) == "undefined" ||
           kult1tv_videojs_playlist.length == 0 ||
           kult1tv_videojs_playlist.length % 2 == 1)
            return;

        var switch_next_video = function() {
            if(playlist_position >= kult1tv_videojs_playlist.length)
                return false;

            var sources = [
                // WebM
                {
                    'src' : kult1tv_videojs_playlist[playlist_position],
                    'type' : 'video/webm'
                },
                // H.264
                {
                    'src' : kult1tv_videojs_playlist[playlist_position+1],
                    'type' : 'video/mp4'
                }
            ]

            player.src(sources);
            player.load();

            playlist_position += 2;
            return true;
        }

        player.addEvent('ended', function() {
            if(switch_next_video()) {
                player.ready(player.play);
            }
        });
        switch_next_video();
    });

});

