/*!
 * notifly-core.js
 * https://www.themexpert.com/
 * Version: 1.0.0
 *
 * Copyright ThemeXpert
 * Released under the MIT license
 * https://www.themexpert.com/notifly
 */
;
(function($, scope) {
    "use strict";
    var NotiflyTimeout;
    var Notifly = scope.Notifly = { 

        /**
         * Basic setup
         *
         * @return  void
         */
        initialize: function() {
            /*console.log(Joomla.getOptions('notifly').params);*/
            /*Get the cookie value*/
            if (Cookies.get('notifly_hide_message') === 'true') {
                return;
            }
            /*get the list first*/
            this.items = this.getList();
            if(!this.items.length){
                console.warn('Notifly:', 'Events are empty! Please configure your integrations.');
                return;
            }

            this.makeWrapper();
            this.checked = false;
            this.time = 0;
            this.totalShown = 0;
            this.max_bypage = parseInt(Joomla.getOptions('notifly').params.max_bypage);
            this.initial_delay = parseInt(Joomla.getOptions('notifly').params.initial_delay) * 1000;
            this.display_time = parseInt(Joomla.getOptions('notifly').params.display_time) * 1000;
            this.delay_time = parseInt(Joomla.getOptions('notifly').params.delay_time) * 1000;

            /* 
            notify_max per user per session
            if(Joomla.getOptions('notifly').params.notify_max == '1'){
                $.session.set("notifly", "value");
            }
            $.session.set("myVar", "value");
            */
            this.showList(this.items);

            $('#notifly-wrapper #text,#notifly-wrapper #image').on('click', function() {
                /*console.warn('Clicked');*/
                Notifly.updateClickLog();
            });

            $('#notifly-wrapper #close').on('click', function() {
                /*console.warn('Clicked');*/
                Notifly.hideMessage();
            });

            if (!this.checked) {
                if ($(window).width() < 768) { /*if width is less than 768px*/
                    this.mobileFunctions(); /*execute mobile function*/
                } else { /*if width is more than 768px*/
                    this.desktopFunctions(); /*execute desktop function*/
                }
                this.checked = true;
            }
        },

        /**
         * Called from outside. Only ever called with task 'folder.delete'
         *
         * @param   string  task  [description]
         *
         * @return  void
         */
        makeWrapper: function() {
            var wrapperWidth = Joomla.getOptions('notifly').params.wrapper_width;
            var show_branding = parseInt(Joomla.getOptions('notifly').params.show_branding);
            
            var htmlNotifly = '<div id="notifly-wrapper" style="width:' + wrapperWidth + ';" class="out"><div class="card-small"><div class="row flex flex--align-vertical">';
            htmlNotifly = htmlNotifly + '<div id="image" class="col-nano-3"><img src="" /></div>';
            htmlNotifly = htmlNotifly + '<div id="text" class="col-nano-9"></div>';
            if(show_branding){
                htmlNotifly = htmlNotifly + '<div class="poweredBy"><i class="svg"><svg width="7" height="13" viewBox="0 0 7 13" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path d="M4.127.496C4.51-.12 5.37.356 5.16 1.07L3.89 5.14H6.22c.483 0 .757.616.464 1.044l-4.338 6.34c-.407.595-1.244.082-1.01-.618L2.72 7.656H.778c-.47 0-.748-.59-.48-1.02L4.13.495z" fill="#F6A623 "></path><path fill="#FEF79E " d="M4.606.867L.778 7.007h2.807l-1.7 5.126 4.337-6.34H3.16"></path></g></svg></i> <span>by</span> <a target="_blank" href="https://www.themexpert.com/notifly?utm_campaign=notifly&utm_medium=powerd_by&utm_source=' + window.location.protocol + '//' + window.location.hostname + Joomla.getOptions('notifly').baseurl + '">Notifly</a></div>';
            }
            
            htmlNotifly = htmlNotifly + '</div>';
            if (Joomla.getOptions('notifly').params.allow_close == 1) {
                htmlNotifly = htmlNotifly + '<div id="close"><span>x</span></div>';
            }
            htmlNotifly = htmlNotifly + '</div></div>';

            $('body').append(htmlNotifly);
        },

        /**
         * Called from outside. Only ever called with task 'folder.delete'
         *
         * @param   string  task  [description]
         *
         * @return  void
         */
        getList: function() {
            /*console.warn('getList');*/
            return Joomla.getOptions('notifly').items;
        },

        /**
         * Called from outside. Only ever called with task 'folder.delete'
         *
         * @param   string  task  [description]
         *
         * @return  void
         */
        showList: function(items) {

            this.initial_delay = parseInt(Joomla.getOptions('notifly').params.initial_delay) * 1000;
            this.display_time = parseInt(Joomla.getOptions('notifly').params.display_time) * 1000;
            this.delay_time = parseInt(Joomla.getOptions('notifly').params.delay_time) * 1000;
            /*set initial delay time*/
            this.time = this.initial_delay;

            $.each(items, function(index, item) {

                /*max per page has crossed!*/
                if (Notifly.totalShown > Notifly.max_bypage) {
                    return;
                }

                var explode = function() {
                    var converter = new showdown.Converter();
                    var renderedHtml = converter.makeHtml(item.message);
                    Notifly.showMessage(index, renderedHtml, item.image);
                };
                setTimeout(explode, Notifly.time);
                Notifly.time = Notifly.time + Notifly.display_time + Notifly.delay_time;
                Notifly.totalShown++;

            });

            /*after all times over, wait and repeat if allowed*/
            if (Joomla.getOptions('notifly').params.notifly_loop == '1') {
                setTimeout(
                    function() {
                        if (Notifly.totalShown > Notifly.max_bypage) {
                            return;
                        }
                        Notifly.destroy();
                        Notifly.initialize();
                    },
                    Notifly.time + Notifly.initial_delay
                );
            }

        },

        showMessage: function(index, text, image) {
            /*Get the cookie value*/
            if (Cookies.get('notifly_hide_message') === 'true') {
                return;
            }

            /*console.warn('showMessage');*/
            $('#notifly-wrapper #text').html(text);
            $('#notifly-wrapper #image img').attr('src', image);
            /*$( '#notifly-wrapper' ).fadeIn('slow').delay(Notifly.display_time).fadeOut('fast');*/
            $('#notifly-wrapper').show().removeClass('out').addClass('active');

            setTimeout(function() {
                $('#notifly-wrapper').removeClass('active').addClass('out').fadeOut('fast');
            }, Notifly.display_time);
            this.updateViewLog();
        },
        hideMessage: function() {

            $('#notifly-wrapper').removeClass('active').addClass('out').fadeOut('fast');

            /*set cookie*/
            var expire_cookie = Joomla.getOptions('notifly').params.expire_cookie;
            expire_cookie = (expire_cookie * 60 * 60); /*60*60 = 1 hour 1*60 = 1 min*/

            Cookies.set('notifly_hide_message', 'true', {
                expires: expire_cookie
            });
            /*console.log('notifly disabled for ' + Joomla.getOptions('notifly').params.expire_cookie + 'hours');*/

        },
        updateViewLog: function() {
            /*
            console.warn(Joomla.getOptions('notifly').baseurl);
            console.warn('updateViewLog');
            call ajax api
            index.php?option=com_ajax&plugin=notifly&format=json&action=click
            Joomla.getOptions('notifly').baseurl + 
            console.log(Joomla.getOptions('notifly').baseurl + "/index.php?option=com_ajax&plugin=notifly&format=json");
            */
            if (Joomla.getOptions('notifly').params.enable_hitcounter == '0') return;
            var updateViewLogInfo = jQuery.get(Joomla.getOptions('notifly').baseurl + "/index.php?option=com_ajax&plugin=notifly&format=json", function(data, status) {
                if (status = !'success') {
                    console.error('failed to update notifly hitlog!');
                }
                /*console.warn('update view log');*/
            });
        },
        updateClickLog: function() {
            /*
            console.warn(Joomla.getOptions('notifly').baseurl);
            console.warn('updateClickLog');
            call ajax api
            index.php?option=com_ajax&plugin=notifly&format=json&action=click
            */
            if (Joomla.getOptions('notifly').params.enable_hitcounter == '0') return;
            var updateClickLogInfo = jQuery.get(Joomla.getOptions('notifly').baseurl + "/index.php?option=com_ajax&plugin=notifly&action=click&format=json", function(data, status) {
                if (status = !'success') {
                    console.error('failed to update notifly clicklog!');
                }
                /*console.warn('updated click');*/
            });
        },
        mobileFunctions: function() {
            /*console.warn('mobileFunctions');*/
            if (Joomla.getOptions('notifly').params.hide_mobile == '1') {
                this.destroy();
            } else if (!$('#notifly-wrapper').length) {
                this.initialize();
            }
        },
        desktopFunctions: function() {
            /*            
            console.warn('desktopFunctions');
            console.warn(Joomla.getOptions('notifly').params.hide_desktop);
            */
            if (Joomla.getOptions('notifly').params.hide_desktop == '1') {
                this.destroy();
            } else if (!$('#notifly-wrapper').length) {
                this.initialize();
            }
        },
        destroy: function() {
            /*console.warn('destroy');*/
            $('#notifly-wrapper').remove();
        },
        resize: function() {
            /*console.warn('resize');*/
            if ($(window).width() < 768) { /*if width is less than 768px*/
                this.mobileFunctions(); /*execute mobile function*/
            } else { /*if width is more than 768px*/
                this.desktopFunctions(); /*execute desktop function*/
            }
        }

    };

    $(function() {
        /*Added to populate data on iframe load*/
        Notifly.initialize();
        $(window).resize(function() {
            Notifly.resize();
        });
    });

}(jQuery, window));