! function($, window, e) {
    "use strict";
    var filename    =   'jollyany_package_'+Math.random().toString(36).substring(7);
    var progress    =   $('<div/>', {"class": 'progress'}),
        progressbar =   $('<progress/>', {
            "class" :   'uk-progress',
            "value" :   '0',
            "max"   :   '100',
        }),
        textStatus  =   $('<div/>', {
            "class" :   'text-muted'
        });
    progress.append(progressbar);
    var resetProgress = function () {
        progressbar.attr('value',0);
    };
    var actionDownloadPackage = function (request, button, dialogPopup) {
        $.ajax({
            url    : 'ajax.php?t='+Math.random().toString(36).substring(7),
            type   : 'POST',
            data   : request,
            success: function (response) {
                if (response.status === 'success') {
                    progressbar.attr('value',(request['step']*100)/response.pathcount);
                    textStatus.html('Downloading Package... '+((request['step']*100)/response.pathcount)+'%')
                    if (response.pathcount <= request['step']) {
                        textStatus.text('Package download completed!');
                        request['archive']      = response.archive;
                        request['jollyany']     = 'unzip_package';
                        actionUnzipPackage(request, button, dialogPopup);
                    } else {
                        request['step']++;
                        actionDownloadPackage(request, button, dialogPopup);
                    }
                } else {
                    dialogPopup.find('.dialogDebug').text(response.message);
                    button.removeAttr('disabled','');
                }
            }
        });
    };
    var actionUnzipPackage  =   function (request, button, dialogPopup) {
        $.ajax({
            url    : 'ajax.php?t='+Math.random().toString(36).substring(7),
            type   : 'POST',
            data   : request,
            beforeSend: function(){
                textStatus.html('Unzip Package...');
            },
            success: function (response) {
                if (response.status === 'success') {
                    textStatus.text('Package unzip completed!');
                    textStatus.html('Redirect to install page...');
                    window.onbeforeunload = null;
                    window.location.href = response.url_root;
                } else {
                    dialogPopup.find('.dialogDebug').text(response.message);
                    button.find('i').remove();
                    button.removeAttr('disabled','');
                }
            }
        });
    };

    $(document).ready(function() {
        var popup, timeInterval, templatejson = null,
            btn_active = $("#jollyany-theme-activate"),
            template = $("#jollyany-form-data-json");
        if (template.length) try {
            templatejson = JSON.parse(template.html()), template.html("")
        } catch (window) {}
        if (null != templatejson) {
            var doc = $("<html>"),
                head = $("<head>"),
                body = $("<body>");
            doc.append(head).append(body);
            var style = $("<link>").attr({
                rel: "stylesheet",
                href: templatejson.api + "/components/com_tz_envato_license/css/style.css"
            });
            head.append(style), head.append("<title>Jollyany &ndash; Product Activation</title>");
            var form = $('<form style="display:none;">').attr({
                action: templatejson.api+'/index.php?option=com_tz_envato_license&view=activation',
                method: "POST",
                enctype: "multipart/form-data",
                id: "jollyany-activate-product-form",
                acceptCharset: "ISO-8859-1"
            }).append('<div class="jollyany-activation-loading"><div class="jollyany-activation-loading-content"><h2>Please wait&hellip;</h2><p>You will be redirected to Envato website in few seconds</p></div></div>');
            for (var jsonelement in templatejson) $("<input>").attr({
                type: "hidden",
                name: jsonelement,
                value: templatejson[jsonelement]
            }).appendTo(form);
            body.append(form);
            var browser = function() {
                var userAgent = window.navigator.userAgent,
                    n = userAgent.indexOf("MSIE ");
                if (n > 0) return parseInt(userAgent.substring(n + 5, userAgent.indexOf(".", n)), 10);
                if (userAgent.indexOf("Trident/") > 0) {
                    var a = userAgent.indexOf("rv:");
                    return parseInt(userAgent.substring(a + 3, userAgent.indexOf(".", a)), 10)
                }
                var o = userAgent.indexOf("Edge/");
                return o > 0 && parseInt(userAgent.substring(o + 5, userAgent.indexOf(".", o)), 10)
            }();
            browser && (form.attr("target", "jollyanyProductActivationWindow"), form.appendTo($(document.body)));
            btn_active.on("click", function(a) {
                a.preventDefault();
                var html = doc.clone(),
                    forminside = html.find("form"),
                    maxheight = 600,
                    minheight = browser ? 550 : 350,
                    screenW = screen.width / 2 - 300,
                    screenH = screen.height / 2 - minheight / 2;
                popup = window.open("", "jollyanyProductActivationWindow", "width=600, height=" + minheight + ", top=" + screenH + ", left=" + screenW);
                browser ? form.submit() : $(popup.document.body).append(html);
                popup ? browser || html.find("link").on("load", function() {
                    forminside.show(), setTimeout(function() {
                        minheight = 800, popup.resizeTo(maxheight, minheight), popup.moveBy(0, -200);
                        forminside.submit();
                    }, 1100)
                }) : alert("Your browser is blocking popups, activation process cannot continue!");
                window.clearInterval(timeInterval), timeInterval = setInterval(function() {
                    if (browser) {
                        try {
                            popup.parent
                        } catch (e) {
                            window.clearInterval(timeInterval), window.location.reload()
                        }
                    } else popup.parent || (window.clearInterval(timeInterval), window.location.reload())
                }, 300);
            });
        }

        $('.jollyany-install').on('click', function (e) {
            var $this       = $(this),
                dialogPopup = $('#jollyany-modal');
            dialogPopup.find('.uk-modal-title > .template-name').text($this.data('name'));
            dialogPopup.find('#install-action').attr('data-file',$this.data('file')).attr('data-name',$this.data('name')).removeAttr('disabled','');
            dialogPopup.find('.dialogDebug').html('');
        });

        $('#install-action').on('click', function (e) {
            var request         =   {},
                $this           =   $(this),
                dialogPopup     = $('#jollyany-modal');
            request['file_name']            = filename;
            request['step']                 = 1;
            request['install_code']         = $this.data('file');
            if (confirm($this.data('name')+" will be installed. Are you sure?")) {
                request['jollyany']          = 'download_package';
                $this.attr('disabled','disabled');
                dialogPopup.find('.dialogDebug').html('');
                resetProgress();
                dialogPopup.find('.dialogDebug').append(progress).append(textStatus);
                textStatus.text('Preparing to download package...');
                actionDownloadPackage(request, $this, dialogPopup);
            }
        });
    })
}(jQuery, window);