var FPWidgetController = function(){

    var jQuery;
    var self = this;

    this.run = function() {
        // Make sure to load jQuery if the user doesn't already have it.
        if (window.jQuery === undefined) {
            var script_tag = document.createElement('script');
            script_tag.setAttribute('type', 'text/javascript');
            script_tag.setAttribute('src', "https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js");

            if (script_tag.readyState) {
                script_tag.onreadystatechange = function () {
                    //For old versions of IE
                    if (this.readyState == 'complete' || this.readyState == 'loaded') {
                        scriptLoadHandler();
                    }
                };
            } else {
                script_tag.onload = scriptLoadHandler;
            }

            (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);

            // If the user already loaded jQuery, just get that one instead
        } else {
            jQuery = window.jQuery;
            main();
        }
    };

    function scriptLoadHandler() {
        jQuery = window.jQuery.noConflict(true);
        main();
    }

    /* For dynamic widgets.
        Also gets called whenever a resize occurs.
        Looks for all .fp-widget-dynamic tags (added automatically by this loader) and updates them according
        to their width.
     */
    function autoWidgetStyle($) {
        $('.fp-widget-dynamic').each(function(){
            var widget_width = $(this).width();
            $(this).find('.fp-widget-base').hide();
            $(this).find('.fp-widget-card').toggle(widget_width < 290);
            $(this).find('.fp-widget-banner').toggle(widget_width >= 290 && widget_width < 500);
            $(this).find('.fp-widget-banner-large').toggle(widget_width >= 500);
        });
    }

    /* For static widget.
        Arguments:
            $widget: jQuery object holding the widget
            style: String specifying style. ie. 'banner'

            Note: This function is exposed to allow changing widget style from another javascript module
     */
    this.applyWidgetStyle = function($widget, style) {
        if (style === 'dynamic'){
            $widget.addClass('fp-widget-dynamic');
        } else {
            $widget.removeClass('fp-widget-dynamic');
            $widget.find('.fp-widget-base').hide();
            $widget.find('.fp-widget-banner').toggle(style === 'banner');
            $widget.find('.fp-widget-banner-large').toggle(style === 'banner-large');
            $widget.find('.fp-widget-card').toggle(style === 'card');
            $widget.find('.fp-widget-simple').toggle(style=='simple');
        }
    };

    /* Append widget after fp_widget.
        Checks for widget configurations in fp_widget, builds and appends the respective widget.
        Arguments:
            $: jQuery
            fp_widget: tag with widget configuration as its attributes.
     */
    function loadWidget($, fp_widget) {
        // Perform the JSONP request. This is integral for x-origin to work with the widget.

         const widget_origin = fp_widget.data('widget-origin') || "https://books.friesenpress.com/widget"

        $.getJSON(widget_origin + "/?callback=?", {
            'color': fp_widget.attr('data-widget-color'),
            'book': fp_widget.attr('data-book'),
            'title': fp_widget.attr('data-title'),
            'subtitle': fp_widget.attr('data-subtitle')

        }, function (data) {

            $widget = $($.parseHTML(data.html));  //Generate a jQuery object from the obtained HTML.

            var style = fp_widget.attr('data-widget-style');
            if (!style){  //No style specified means it's a dynamic widget
                $widget.addClass('fp-widget-dynamic');  // First identify added widget as dynamic before inserting it
                fp_widget.after($widget);
            } else { //Or simply apply the widget style.
                fp_widget.after($widget);
                self.applyWidgetStyle($widget, style)
            }

            // Refresh all existing dynamic widgets
            autoWidgetStyle($);

        }).fail(function (e) {
            console.log('FP-Widget error: ' + e.responseText);
        });
    }

    function main() {
        jQuery(document).ready(function($) {

            // Load css resources
            $.each(['widget.css'], function(key, value){
                $("<link>", {
                    rel: "stylesheet",
                    type: "text/css",
                    href: "https://books.friesenpress.com/static/widget/" + value
                }).appendTo('head')
            });

            // Look for all the widgets on the document and load them according to their individual configurations
            $('.fp-widget').each(function(){
                loadWidget($, $(this))
            });

            // Add an event handler for dynamic widgets. TODO: avoid doing this if no dynamic widget is added.
            $(window).resize(function(){
                autoWidgetStyle($);
            });
        });
    }
};

var fp_widget_controller = new FPWidgetController();
fp_widget_controller.run();

