/**
 * Created by pascal on 11/05/2016.
 */


var productVideoModule = (function ($) {

    // privates

    var oEmbedUrl = 'https://vimeo.com/api/oembed.json';
    var oEmbedObjectsList = [];
    var oEmbedCallbackString = "oEmbedCallback";
    var urlsList = null;

    /**
     * Loads the data from Vimeo
     * @param url
     */
    function loadScript(url) {
        ////console.log(url);
        var js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', url);
        document.getElementsByTagName('head').item(0).appendChild(js);
    }

    /**
     * puts the video on the page
     * @param video
     */
    function embedVideo(video, autoplay) {
        // Si on a cliqué sur une thumb faut faire l'autoplay.
        var videoHtml = decodeURI(video.html);
        if (autoplay !== undefined) {
            videoHtml = videoHtml.replace(video.video_id, video.video_id + "?autoplay=1");
        }
        document.getElementById('vimeoWrapper').innerHTML = videoHtml;
        //document.getElementById('vimeoWrapper').innerHTML = decodeURI('<iframe src="https://player.vimeo.com/video/159227749?autoplay=1"width="960" height="540" frameborder="0" title="Petzl - Access the Inaccessible [FR]" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');
        //"<iframe src="https://player.vimeo.com/video/160758994?autoplay=1" width="960" height="540" frameborder="0" title="Maewan - Extreme skiing and mountaineering in Greenland" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"
		
		// HK take title from back-office
		var title = urlsList[video.video_id].title;

        document.getElementById('videoTitle').innerHTML = decodeURI(title);
    }

    /**
     * Add video thumb
     * @param video
     * @param index
     */
    function addThumb(video, index) {

        // La liste des thumbs.
        var thumbsList = $('.VideoPlayerThumb');

        // La thumb.
        var $thumb = thumbsList.eq(index);
        $thumb.css("display", "inline-block");

        // L'image.
        var $img = $thumb.find('.VideoPlayerThumb_image');
        $img.css('background-image', "url(" + video.thumbnail_url + ")");

        // Le caption.
        var $caption = $thumb.find('.VideoPlayerThumb_caption');
		
		// HK take title from back-office
		var title = urlsList[video.video_id].title;
        $caption.html(title || "&nbsp;");

        // On stocke les données dans la thumb.
        $thumb.data("video", video);

        // Au clique...
        $thumb.click(function () {

            // On récupère les données.
            var video = $(this).data("video") || {};

            // On définit la vidéo courrante.
            setVideo(video, true);

        });

    }


    /**
     * Définit la vidéo à lire.
     * @param video
     */
    function setVideo(video, autoplay) {

        // On incruste la vidéo.
        embedVideo(video, autoplay);

        // On "active" le thumb qui correspond.
        // La liste des thumbs.
        var thumbsList = $('.VideoPlayerThumb');
        thumbsList.each(function (index, item) {
            if ($(item).data("video") && $(item).data("video").video_id === video.video_id) {
                $(item).addClass("active");
            } else {
                $(item).removeClass("active");
            }
        });
    }

    // Return an object exposed to the public
    return {

        /**
         * Le callback sur l'appel async de oEmbed
         * @param video
         */
        oEmbedCallback: function (video) {
            //  console.log("oEmbedCallback() ", video);
            oEmbedObjectsList.push(video);

            // L'index de la vidéo.
			// HK take title from back-office
			var index = !urlsList[video.video_id] ? -1 :  urlsList[video.video_id].index;

            index = index !== -1 ? index : oEmbedObjectsList.length - 1;

            // On ajoute la thumb.
            addThumb(video, index);

            // Si c'est la première vidéo, on l'incruste.
            if (index === 0) {
                setVideo(video);
            }

            // Si il n'y a qu'une vidéo, on cache les vignettes.
            if (urlsList.length <= 1) {
                $(".VideoPlayerThumb").css("display", "none");
            }
        },

        /**
         * Définit la liste des urls des vidéos.
         * @param videosUrlList
         */
        setVideosURL: function (videosUrlList) {

            //  console.log("setVideosURL() ", videosUrlList);
			
			// HK take title from back-office
            urlsList = videosUrlList.reduce(function(m, video, index) {
					if (!m[video.id])
						m[video.id] = video;
					video.index = index;
					return m;
			}, Object.create([].concat(videosUrlList)));

            $.each(urlsList, function (index, item) {
				// HK take title from back-office
                loadScript(oEmbedUrl + '?url=' + encodeURIComponent(item.url) + '&callback=' + oEmbedCallbackString + '&width=940');
            });
        },

        /**
         * Définit la vidéo courrante.
         */
        setVideo: setVideo

    };
})($);


/**
 * oEmbed API callback
 * @param video
 */
function oEmbedCallback(video) {

    // On passe l'objet oEmbed au module.
    productVideoModule.oEmbedCallback(video);

}
