(function() {
    "use strict";

    onReady(() => {

        var VIDEO_ID = location.pathname.match(/\/video\/([^_]+)/);
        // asyncGet http://www.dailymotion.com/json/video/<VIDEO_ID>?fields=stream_audio_url,stream_h264_hd1080_url,stream_h264_hd_url,stream_h264_hq_url,stream_h264_ld_url,stream_h264_url,stream_hls_url,stream_live_hls_url,thumbnail_120_url,thumbnail_240_url,thumbnail_url
        // returns a json
        //poster;
        var auth = document.body.innerHTML.match(/auth=[a-z0-9-A-Z-]*/);
        if (!auth || !VIDEO_ID)
            return;
        VIDEO_ID = VIDEO_ID[1];
        auth = auth[0];
        var fmts = {};
        for (var fmt of["1280x720", "848x480", "512x384", "320x240"]) {
            var reg = new RegExp("(https?:\\\\\/\\\\\/|)(www.|)dailymotion.com\\\\?\\/cdn\\\\?\\/H264-" + fmt + "\\\\?\\/video\\\\?\\\\/" + VIDEO_ID + ".mp4\\?auth=[a-zA-Z0-9-]+", "ig");
            var url = document.body.innerHTML.match(reg);
            if (url)
                fmts[fmt] = url[0].replace("\\/", "/", "g");
        }
        /*
        if (unsafeWindow.info) {
            urls = unsafeWindow.info;
            poster = unsafeWindow.info.thumbnail_url ||
                unsafeWindow.info.thumbnail_240_url ||
                unsafeWindow.info.thumbnail_120_url;
        } else {
            var streams_r = /"stream_h264[^"]*_url":"[^"]*"/g;
            var url_r = /"(stream_h264[^"]*_url)":"([^"]*)"/;
            var streams = document.body.innerHTML.match(streams_r);
            streams.forEach(u => {
                var r = u.match(url_r);
                urls[r[1]] = r[2].replace("\\/", "/", "g");
            });
        }*/
        var poster = (document.body.innerHTML.match(/"poster_url":"([^"]*)"/) || ["", ""])[1].replace("\\/", "/", "g");
        logify(poster, fmts);
        var isEmbed = location.pathname.match(/dailymontion.com\/embed\/video\//) !== null;
        var container;
        if (isEmbed)
            container = document.body;
        else
            container = document.getElementById("player_container");
        var vp = new VP(container);
        vp.srcs(fmts, {
            "higher/mp4": "1280x720",
            "high/mp4": "848x480",
            "medium/mp4": "512x384",
            "low/mp4": "320x240"
        });
        vp.props({
            controls: true,
            autoplay: autoPlay(),
            preload: preLoad(),
            loop: isLoop(),
            poster: poster
        });
        vp.style({
            width: "100%",
            height: "100%"
        });
        vp.setup();
    });
}());