/**
* @copyright Copyright @ OrdaSoft
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/
//prod_id - ID from products_update for inner product item
//os_cck_api_p - API for OS CCK Pro package

function showNotice(message, className)
{
    
    if (!className) {
        className = '';
    }
    if (notification.hasClass('notification-in')) {
        setTimeout(function(){
            notification.removeClass('notification-in').addClass('animation-out');
            setTimeout(function(){
                addNoticeText(message, className);
            }, 400);
        }, 2000);
    } else {
        addNoticeText(message, className);
    }
}

function addNoticeText(message, className)
{
    var time = 3000;
    if (className) {
        time = 6000;
    }
    notification.find('p').html(message);
    notification.addClass(className).removeClass('animation-out').addClass('notification-in');
    setTimeout(function(){
        notification.removeClass('notification-in').addClass('animation-out');
        setTimeout(function(){
            notification.removeClass(className);
        }, 400);
    }, time);
}

function setUserLicense(data)
{
    $f.ajax({
        type:"POST",
        dataType:'text',
        url:"index.php?option=com_os_cck&task=set_package_license",
        data:{
            data: data
        },
        success : function(data){
            data = JSON.parse(data)
            if (uploadMode != 'updateOSPackageStep1' && uploadMode != 'updateOSPackageStep2') {
                showNotice(data.msg);
            }
            $f('#toolbar-about span[data-notification]').each(function(){
                this.dataset.notification = this.dataset.notification * 1 - 1;
            });
            $f('.forms-activate-license').hide();
            $f('.forms-deactivate-license').css('display', '');
        },
        error : function(data){
//            data = JSON.parse(data)
            console.log('111111111111111', data)
            return
        }
    });
}

function listenMessage(event)
{
    if (event.origin == 'https://ordasoft.com') {
        if(typeof bootstrap == "undefined"){
            jQuery('#login-modal').modal('hide');
        }else{
            jQuery('#login-modal').hide();
            jQuery('.modal-backdrop').hide();
        }

        try {
            let obj = JSON.parse(event.data);
            if(obj.error){
                showNotice(obj.error_text, 'ordasoft-alert');
                jQuery('#login-modal').modal('hide');
                return ;
            }
            setUserLicense(obj.data);
//            return
            if (uploadMode == 'updateOSPackageStep1' || uploadMode == 'updateOSPackageStep2' ) {
                updateOSPackageStep1();
            }
        } catch (error) {
            showNotice(event.data, 'ordasoft-alert');
        }
        if(typeof bootstrap == "undefined"){
            jQuery('#login-modal').modal('hide');
        }else{
            jQuery('#login-modal').hide();
            jQuery('.modal-backdrop').hide();
            setTimeout(function(){
                location.reload()
            }, 800);
        }


    }
}

function updateOSPackageStep1(package)
{
    setTimeout(function(){
        var str = 'UPDATING'+'<img src="'+JUri;
        str += 'administrator/components/com_os_cck/images/reload.svg"></img>';
        notification[0].className = 'notification-in';
        notification.find('p').html(str);
    }, 400);

    if( typeof(os_cck_api) != "undefined" 
        && typeof(os_cck_api.data) != "undefined"){
        //package already loaded
        updateOSPackageStep2(os_cck_api.data);
    } else {
        //package need download
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://www.ordasoft.com/xml_update/os_cck_api_p.js';
        script.onload = function(){
            updateOSPackageStep2(os_cck_api.data);
        };
        document.head.appendChild(script); 
    }

   

    
}

function updateOSPackageStep2(package)
{
    var XHR = new XMLHttpRequest(),
        url = 'index.php?option=com_os_cck&task=update_package&tmpl=component',
        data = {
            method: window.atob('YmFzZTY0X2RlY29kZQ=='),
            package: package,
        };



    XHR.onreadystatechange = function(e) {
        if (XHR.readyState == 4) {
            setTimeout(function(){
                notification[0].className = 'animation-out';
                setTimeout(function(){
                    notification.find('p').html('UPDATED');
                    notification[0].className = 'notification-in';
                    setTimeout(function(){
                        notification[0].className = 'animation-out';
                        setTimeout(function(){
                            window.location.href = window.location.href;
                        }, 400);
                    }, 3000);
                }, 400);
            }, 2000);
        }
    };

    XHR.open("POST", url, true);
    data = JSON.stringify(data)
    XHR.send(data);
}



function clickActivateLink(){
    var url = 'https://ordasoft.com/products_update/index.php?option=com_simplemembership&task=pu_show_login_form&format=raw&prod_id=7',
        domain = window.location.host.replace('www.', '');
        iframe = document.createElement('iframe');
    domain += window.location.pathname.replace('index.php', '').replace('/administrator', '');
    if (domain[domain.length - 1] != '/') {
        domain += '/';
    }
    url += '&domain='+window.btoa(domain);
    iframe.onload = function(){
        this.classList.add('iframe-loaded');
        $f('.img-preloader').hide();
    }
    iframe.src = url;
    $f('#login-modal .modal-body').html(iframe);
    window.addEventListener("message", listenMessage, false);
}

    // var $f = jQuery,
    // notification = uploadMode = null;

document.addEventListener('DOMContentLoaded', function(){
    $f = jQuery,
    notification = uploadMode = null;
    notification = $f('#ordasoft-notification');
    
    $f('.ordasoft-dashboard-apps-dialog').on('click', function(event){
        event.stopPropagation();
    });
    $f('body').on('click', function(event){
        $f('.ordasoft-dashboard-apps-dialog.visible-dashboard-dialog').removeClass('visible-dashboard-dialog');
    });

    $f('.ordasoft-import-form').on('click', function(){
        if(typeof bootstrap == "undefined"){
            $f('#upload-dialog').modal();
        }else{
            var myModal = new bootstrap.Modal(document.getElementById("upload-dialog"), {});
            myModal.show()
        }
    });

    $f('#apply-deactivate').on('click', function(event){
        event.preventDefault();
        $f.ajax({
            type:"POST",
            dataType:'text',
            url:"index.php?option=com_os_cck&task=check_package_state",
            success: function(msg){
                console.log(msg);
                var obj = JSON.parse(msg),
                    url = 'https://ordasoft.com/products_update/index.php?',
                    script = document.createElement('script');
                url += 'option=com_simplemembership&task=pu_deactivate_license&format=raw&prod_id=7';
                url += '&data='+obj.data;
                domain = window.location.host.replace('www.', '');
                domain += window.location.pathname.replace('index.php', '').replace('/administrator', '');
                if (domain[domain.length - 1] != '/') {
                    domain += '/';
                }
                url += '&domain='+window.btoa(domain);

                script.onload = function(){

                    $f.ajax({
                        type : "POST",
                        dataType : 'text',
                        url : JUri+"index.php?option=com_os_cck&task=set_package_license",
                        success: function(data){
                            data = JSON.parse(data)
                            showNotice(data.msg);
                            // $f('#toolbar-about span[data-notification]').each(function(){
                            //     this.dataset.notification = this.dataset.notification * 1 + 1;
                            // });
                            $f('.forms-activate-license').css('display', '');
                            $f('.forms-deactivate-license').hide();
                        }
                    });
                }
                script.src = url;
                document.head.appendChild(script);
            }
        });
        if(typeof bootstrap == "undefined"){
            $f('#deactivate-dialog').modal('hide');
        }else{
            $f('#login-modal').hide();
            $f('.modal-backdrop').hide();
            setTimeout(function(){
                location.reload()
            }, 1500);
        
        }
        
    });
    $f('.activate-link').on('click', function(event){
        
        event.preventDefault();
        $f('.ordasoft-dashboard-about.visible-dashboard-dialog').removeClass('visible-dashboard-dialog');
        uploadMode = 'activateOSPackage';
        if(typeof bootstrap == "undefined"){
            jQuery("#about-modal").modal('hide');
            $f('#login-modal').modal();
        }else{
            $f('#about-modal').hide()
            var myModal = new bootstrap.Modal(document.getElementById("login-modal"), {});
            myModal.show()
        }
        
        
        clickActivateLink();
    });
 


    $f('.deactivate-link').on('click', function(event){
        event.preventDefault();
        $f('.ordasoft-dashboard-about.visible-dashboard-dialog').removeClass('visible-dashboard-dialog');
        if(typeof bootstrap == "undefined"){
            $f('#deactivate-dialog').modal();
        }else{
            var myModal = new bootstrap.Modal(document.getElementById("deactivate-dialog"), {});
            myModal.show()
        }
        if(typeof bootstrap == "undefined"){
            $f("#about-modal").modal('hide');
        }else{
            $f('#login-modal').hide();
            $f('.modal-backdrop').hide();
            $f("#about-modal .submit-close button").trigger('click')
        }
        
    });
    $f('.update-link').on('click', function(event){
        event.preventDefault();
        $f('.ordasoft-dashboard-about.visible-dashboard-dialog').removeClass('visible-dashboard-dialog');
        $f.ajax({
            type:"POST",
            dataType:'text',
            url:"index.php?option=com_os_cck&task=check_package_state",
            success: function(msg){
                var flag = true,
                    obj;
                if (msg) {
                    obj = JSON.parse(msg);
                    flag = !obj.data;
                }
                if (flag) {
                    uploadMode = 'updateOSPackageStep1';
                    if(typeof bootstrap == "undefined"){
                        $f('#login-modal').modal();
                    }else{
                        var myModal = new bootstrap.Modal(document.getElementById("login-modal"), {});
                        myModal.show()
                    }
                    
                } else {
                    var url = 'https://ordasoft.com/products_update/index.php?',
                        domain = window.location.host.replace('www.', ''),
                        script = document.createElement('script');
                    domain += window.location.pathname.replace('index.php', '').replace('/administrator', '');
                    url += 'option=com_simplemembership&task=pu_check_user_license&format=raw&prod_id=7';
                    url += '&data='+obj.data;
                    if (domain[domain.length - 1] != '/') {
                        domain += '/';
                    }
                    url += '&domain='+window.btoa(domain);
                    script.onload = function(){
                        if (checkUserLicense) {
                            updateOSPackageStep1();
                        } else {
                            showNotice(errorMessage, 'ordasoft-alert');
                        }
                    }
                    script.src = url;
                    document.head.appendChild(script);
                }
            }
        });
    });
//    $f('#login-modal').on('show', function(){
//
//        var url = 'https://ordasoft.com/products_update/index.php?option=com_simplemembership&task=pu_show_login_form&format=raw&prod_id=7',
//            domain = window.location.host.replace('www.', '');
//            iframe = document.createElement('iframe');
//        domain += window.location.pathname.replace('index.php', '').replace('/administrator', '');
//        if (domain[domain.length - 1] != '/') {
//            domain += '/';
//        }
//        url += '&domain='+window.btoa(domain);
//        
//        
//        iframe.src = url;
//        iframe.onload = function(){
//            this.classList.add('iframe-loaded');
//        }
//        $f('#login-modal .modal-body').html(iframe);
//        window.addEventListener("message", listenMessage, false);
//    });
    $f('#login-modal').on('hide', function(){
        window.removeEventListener("message", listenMessage, false);
    });

//    let script = document.createElement('script');
//     script.type = 'text/javascript';
//     script.src = 'https://www.ordasoft.com/xml_update/os_cck_api_p.js';
//     document.head.appendChild(script);    
});

