/*
Copyright 2014, Oracle and/or its affiliates. All rights reserved.
Author: Matt Heimer
Version: 2014.11.18
*/

if (!window.console) {
    window.console = {
        log: function() {
        }
    };
}

(function($) {
    function OhcvCommon() {

    }
    OhcvCommon.prototype.getVideo = function(id) {
        return jQuery.getJSON(this.videoPrefix + id + this.videoPostfix);
    };
    OhcvCommon.prototype.getChannelVideos = function(id) {
        return jQuery.getJSON(this.channelPrefix + id + this.channelPostfix);
    };
    OhcvCommon.prototype.getPlaylistVideos = function(id) {
        return jQuery.getJSON(this.playlistPrefix + id + this.playlistPostfix);
    };

    OhcvCommon.prototype.videoTemplate = $(
            "<div id='' data-product-id='' class='video-container col3'>" +
            "<a class='various iframe' data-fancybox-type='iframe' href=''><img src='' alt=''></a>" +
            "<div class='video-information'>" +
            "<div class='video-title' id=''><h4></h4></div>" +
            "<div class='video-video-description' id=''></div>" +
            "</div>" +
            "</div");

    OhcvCommon.prototype.applyVideoTemplate = function(template, video) {
        template.attr("id", "container-" + video.content_id);
        template.attr("data-product-id", video.product_id);
        template.find("> a").attr("href", video.link + "?autoplay=1");
        template.find("> a > img").attr("src", video.thumbnail_link);
        template.find("> a > img").attr("alt", video.title);
        template.find(".video-title").attr("id", "title-" + video.content_id);
        template.find(".video-title > h4").text(video.title);
        template.find(".video-video-description").attr("id", "description-" + video.content_id);
        template.find(".video-video-description").html($.trim(video.description.replace(/(\r\n|\n|\r)/gm, "")));
    };

    OhcvCommon.prototype.insertVideos = function(json) {
        //oll format is our native json format, no converting
        if (!json.items) {
            json = {items: [json]};
        }
        for (i = 0; i < json.items.length; i++) {
            var h = this.videoTemplate.clone();
            this.applyVideoTemplate(h, json.items[i]);
            h.appendTo(this.node);
        }
    };

    OhcvCommon.prototype.carouselTemplate = $(
            "<h3>Featured Videos</h3><hr/><br/>" +
            "<div class='carousel-container'>" +
            "<div id='' class='carousel slide' data-ride='carousel'>" +
            "<ol class='carousel-indicators'></ol>" +
            "<div class='carousel-inner'>" +
            "</div>" +
            "<a class='left carousel-control' href='#carousel-example-generic' role='button' data-slide='prev'><span class='glyphicon glyphicon-chevron-left'></span></a>" +
            "<a class='right carousel-control' href='#carousel-example-generic' role='button' data-slide='next'><span class='glyphicon glyphicon-chevron-right'></span></a>" +
            "</div>" +
            "</div>");

    OhcvCommon.prototype.carouselTemplatePartA = $("<li data-target='' data-slide-to=''></li>");

    OhcvCommon.prototype.carouselTemplatePartB = $(
            "<div class='item carousel-video' v-id=''>" +
            "<a class='various iframe' data-fancybox-type='iframe' href=''>" +
            "<img src='' alt=''>" +
            "</a>" +
            "<div class='carousel-caption'>" +
            "<h3></h3>" +
            "<div></div>" +
            "</div>" +
            "</div>");

    OhcvCommon.prototype.applyCarouselTemplate = function(id, template, videos) {
        template.attr("id", "carousel-" + id);
        var ol = template.find("> ol.carousel-indicators");
        for (i = 0; i < videos.length; i++) {
            var li = this.carouselTemplatePartA.clone();
            li.attr("data-target", "#" + "carousel-" + id);
            li.attr("data-slide-to", i);
            if (i === 0) {
                li.addClass("active");
            }
            ol.append(li);
        }
        var div = template.find("> div.carousel-inner");
        for (i = 0; i < videos.length; i++) {
            console.log(videos[i]);
            var vid = this.carouselTemplatePartB.clone();
            vid.attr("v-id", videos[i].content_id);
            if (i === 0) {
                vid.addClass("active");
            }
            vid.find("> a").attr("href", videos[i].link + "?autoplay=1");
            vid.find("> a > img").attr("src", videos[i].thumbnail_link);
            vid.find("> a > img").attr("alt", videos[i].title);
            vid.find("> div.carousel-caption > h3").text(videos[i].title);
            vid.find("> div.carousel-caption > div").html($.trim(videos[i].description.replace(/(\r\n|\n|\r)/gm, "")));

            div.append(vid);
        }
        template.find("> a").attr("href", "#" + "carousel-" + id);
    };

    OhcvCommon.prototype.insertCarousel = function(id, json) {
        //oll format is our native json format, no converting
        if (!json.items) {
            json = {items: [json]};
        }
        if (json.items.length < 1) {
            return;
        }
        var template = this.carouselTemplate.clone();
        this.applyCarouselTemplate(id, template.find(".carousel"), json.items);
        template.appendTo(this.node);
    };

    function OhcvOLL(n) {
        this.node = n;
        this.videoPrefix = "//apex.oracle.com/pls/apex/oll_rest/oll/docs/content/";
        this.videoPostfix = "?callback=?";
        this.channelPrefix = "//apex.oracle.com/pls/apex/oll_rest/oll/docs/product/videos/";
        this.channelPostfix = "?callback=?";
        this.playlistPrefix = "//apex.oracle.com/pls/apex/oll_rest/oll/docs/playlist/";
        this.playlistPostfix = "?callback=?";
        this.allvideos = "//apex.oracle.com/pls/apex/oll_rest/oll/docs/allvideostst?callback=?";
    };
    OhcvOLL.prototype = new OhcvCommon();
    OhcvOLL.prototype.constructor = OhcvOLL;
    OhcvOLL.prototype.getAllVideos = function() {
        return jQuery.getJSON(this.allvideos);
    };
    

    function OhcvYouTube(n) {
        this.node = n;
        this.videoPrefix = "//gdata.youtube.com/feeds/api/videos/";
        this.videoPostfix = "?alt=jsonc&v=2&callback=?";
        this.channelPrefix = "//gdata.youtube.com/feeds/api/users/";
        this.channelPostfix = "/uploads?alt=jsonc&v=2&callback=?";
        this.playlistPrefix = "//gdata.youtube.com/feeds/api/playlists/";
        this.playlistPostfix = "?alt=jsonc&v=2&callback=?";
    }
    OhcvYouTube.prototype = new OhcvCommon();
    OhcvYouTube.prototype.constructor = OhcvYouTube;
    OhcvYouTube.prototype.convertData = function(json) {
        var ollJson;
        var regex = /((https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
        if (json.data.items) {
            ollJson = {"items": []};
            for (i = 0; i < json.data.items.length; i++) {
                var video = {};
                video.content_id = json.data.items[i].video ? json.data.items[i].video.id : json.data.items[i].id;
                video.product_id = json.data.items[i].video ? json.data.items[i].video.uploader : json.data.items[i].uploader;
                video.title = json.data.items[i].video ? json.data.items[i].video.title : json.data.items[i].title;
                video.link = "https://www.youtube.com/embed/" + (json.data.items[i].video ? json.data.items[i].video.id : json.data.items[i].id);
                video.thumbnail_link = json.data.items[i].video ?
                        json.data.items[i].video.thumbnail.hqDefault || json.data.items[i].video.thumbnail.sqDefault :
                        json.data.items[i].thumbnail.hqDefault || json.data.items[i].thumbnail.sqDefault;
                video.description = (json.data.items[i].video ? json.data.items[i].video.description : json.data.items[i].description).split("\n").join("<br />").replace(regex, "<a href='$1'>$1</a>");
                ollJson.items.push(video);
            }
        } else {
            var video = {};
            video.content_id = json.data.id;
            video.product_id = json.data.uploader;
            video.title = json.data.title;
            video.link = "https://www.youtube.com/embed/" + json.data.id;
            video.thumbnail_link = json.data.thumbnail.hqDefault || json.data.thumbnail.sqDefault;
            video.description = json.data.description.split("\n").join("<br />").replace(regex, "<a href='$1'>$1</a>");
            ollJson = video;
        }
        return ollJson;
    };
    OhcvYouTube.prototype.insertVideos = function(json) {
        if (json.data) {
            OhcvCommon.prototype.insertVideos.call(this, this.convertData(json));
        }
    };
    OhcvYouTube.prototype.insertCarousel = function(id, json) {
        if (json.data) {
            OhcvCommon.prototype.insertCarousel.call(this, id, this.convertData(json));
        }
    };

    $.fn.ohcv = function(options) {
        if (!options.id) {
            console.log("Invalid id");
            return this;
        }
        // set default options
        var settings = $.extend({
            source: "oll",
            carousel: false
        }, options);

        var ohcv;
        if (settings.source === "oll") {
            ohcv = new OhcvOLL(this);
        } else if (settings.source === "youtube") {
            ohcv = new OhcvYouTube(this);
        } else {
            console.log("Invalid source");
            return this;
        }

        var jqXHR;

        if (settings.display === "video") {
            jqXHR = ohcv.getVideo(settings.id);
        } else if (settings.display === "channel") {
            if (settings.source === "oll" && settings.id === "all") {
                jqXHR = ohcv.getAllVideos();
            } else {
                jqXHR = ohcv.getChannelVideos(settings.id);
            }
        } else if (settings.display === "playlist") {
            jqXHR = ohcv.getPlaylistVideos(settings.id);
        } else {
            console.log("Invalid display");
            return this;
        }
        jqXHR.done(function(data) {
            console.log(data);



            if (settings.carousel) {
                ohcv.insertCarousel(settings.display + "-" + settings.id, data);
            } else {
                ohcv.insertVideos(data);
            }
        });
    };
}(jQuery));