/**
* @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 updateOSPackageStep1(mask)
{
    // console.log(':updateOSPackageStep1:', mask);
    setTimeout(function(){
        var str = 'IMPORTING'+'<img src="'+JUri;
        str += 'administrator/components/com_os_cck/images/reload.svg"></img>';
        notification[0].className = 'notification-in';
        notification.find('p').html(str);
    }, 400);
    var lib = mask +'_api'
    // console.log('333333333333', mask)
    if( typeof(window[lib]) != "undefined" 
        && typeof(window[lib].data) != "undefined"){
        //package already loaded
// console.log(':updateOSPackageStep1 1:', lib,"::",window[lib].data);
            updateOSPackageStep2(window[lib].data);
    } else {
// console.log(':updateOSPackageStep1 3:', mask); 
        //package need download
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://www.ordasoft.com/xml_update/'+mask+'_api_p.js';
        script.onload = function(){
            // console.log('77777777777777')
            updateOSPackageStep2(window[lib].data, mask);
        };
        document.head.appendChild(script); 
    }

   

    
}

function updateOSPackageStep2(package, mask)
{

    data = {
        method: window.atob('YmFzZTY0X2RlY29kZQ=='),
        package: package,
        mask: mask,
    };
    
    data = JSON.stringify(data)

    $f.ajax({
        type : "POST",
        data : data,
        url : 'index.php?option=com_os_cck&task=importJsLibrary&tmpl=component',
        
        success: function(data){
            
            data = JSON.parse(data)
            // console.log('11111111111111', data)
            if(!data.success){
                alert(data.error);
                location.reload();
                return;
            }
            if(data.tmp_file_path != undefined){
                
                // return
                // console.log('111111111111111', data.prop_arr.entity_merge)
                if(data.prop_arr.entity_merge == undefined){
                    // console.log('2222222222222222')
                    var url = 'index.php?option=com_os_cck&task=import&step=2&tmp_file_path=' + encodeURI(data.tmp_file_path) + '&zip_file_name=' + encodeURI(data.zip_file_name)
                    window.location.href = url;
                }else{
                    // return
                    var form = document.createElement('form');
                    form.action = 'index.php?option=com_os_cck&task=import&step=3&tmp_file_path=' + encodeURI(data.tmp_file_path) + '&zip_file_name=' + encodeURI(data.zip_file_name);
                    form.method = 'POST';
                    form.innerHTML = '<input name="entity_export_type['+data.prop_arr.old_eid+']" value="merge">' +
                                     '<input name="entity_merge['+data.prop_arr.old_eid+']" value="'+data.prop_arr.ext_eid+'">' +
                                     '<input name="layout_opt['+data.prop_arr.old_eid+']" value="merge">' +
                                     '<input name="field_opt['+data.prop_arr.old_eid+']" value="merge">';
                    // form.url.name = href;
                    document.body.append(form);
                    form.submit()
                    // console.log('111111111111111', data.prop_arr.ext_eid)
                }
            }

        }
    });

}




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

document.addEventListener('DOMContentLoaded', function(){
    // console.log('33333333333333333')
    $f = jQuerOs,
    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()
        }
    });
    var href = window.location.href
    pos = window.location.href.indexOf('index.php?')
    href = href.slice(0, pos) + 'components/com_os_cck/os_cck.xml'
    
    var xml_file;

    var myVar = 0;
    // Создали промежуточный блок div#temp
    var tempDiv = $f('body').append($f('<div/>').attr('id', 'temp')).find('#temp');
    // Загрузили данные в этот блок
    tempDiv.load(href, function(response, status, xhr) {
        myVar = response
        tempDiv.remove();

        parser = new DOMParser();
        xmlDoc = parser.parseFromString(myVar,"text/xml");

        var vers = xmlDoc.getElementsByTagName("tag")[0].childNodes[0].nodeValue
        if(vers == 'free'){
            
            var tab = $f('[aria-controls=panel_2_id]')
            tab.addClass('cck-pro-version')
            tab.attr('disabled', 'disabled')

            var tab2 = $f('[aria-controls=panel_4_id]')
            tab2.addClass('cck-pro-version')
            tab2.attr('disabled', 'disabled')
        }

        $f('#importFarame').on('load', function(){
            // console.log('22222222222223', vers);
            var iframe = document.getElementById('importFarame');
            $f('#importFarame').contents().find('.import-library').show()
            $f('#importFarame').contents().find('body').addClass('iframe-body')
            if(vers == 'free'){
                $f('#importFarame').contents().find('body .tmpl_wrapper').each(function(){
                    if($f(this).find('.free_line').length == 0){
                        $f(this).find('.import-library').remove()
                        var pro_html = '<div class="free_line cck-pro-only" style="background:#ff616182;"><h3 class="thin">Pro version only!</h3></div>'
                        $f(this).append(pro_html)
                    }
                    
                })
            }
            // console.log('11111111111111111', iframe.contentWindow.document);
            $f('#importFarame').contents().find('.import-library').on('click', function(event){
                event.preventDefault();
                var mask = $f(this).attr('mask')
                // console.log('1111111111111', $f(this).attr('mask'))
                //$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;
                        }
                        // console.log('11111111111111', flag)
                        if (!flag && vers == 'pro') {
                            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(){
                                
                                // var amsk
                                if (checkUserLicense) {
                                    updateOSPackageStep1(mask);
                                } else {
                                    showNotice(errorMessage, 'ordasoft-alert');
                                }
                            }
                            script.src = url;
                            document.head.appendChild(script);
                        }else if(vers == 'free'){
                            updateOSPackageStep1(mask);
                            
                        }else if(vers == 'pro'){
                            alert('You have not activated your copy of the product, or your license has expired.');
                        }
                    }
                });
            });
            $f('#importFarame').contents().find('a').on('click', function(event){
                event.preventDefault();
                
                if(!$f(this).hasClass('import-library')){
                    var href = $f(this).attr('href')
                    if(href.indexOf('ordasoft.com') == -1){
                        href = 'https://ordasoft.com' + href
                    }
    
                    var form = document.createElement('form');
                    form.action = window.location.href;
                    form.method = 'POST';
                    form.innerHTML = '<input name="url" value="'+href+'"><input name="active" value="true">';
                    // form.url.name = href;
                    document.body.append(form);
                    form.submit()
                }
                // console.log('22222222222222', window.location.href)
            })
        });

        $f('#importLibFarame').on('load', function(){
            // console.log('22222222222223', vers);
            var iframe = document.getElementById('importFarame');
            $f('#importLibFarame').contents().find('.import-library').show()
            $f('#importLibFarame').contents().find('body').addClass('iframe-body')
            // if(vers == 'free'){
            //     $f('#importLibFarame').contents().find('body .tmpl_wrapper').each(function(){
            //         if($f(this).find('.free_line').length == 0){
            //             $f(this).find('.import-library').remove()
            //             var pro_html = '<div class="free_line cck-pro-only" style="background:#ff616182;"><h3 class="thin">Pro version only!</h3></div>'
            //             $f(this).append(pro_html)
            //         }
                    
            //     })
            // }
            // console.log('11111111111111111', iframe.contentWindow.document);
            $f('#importLibFarame').contents().find('.import-library').on('click', function(event){
                event.preventDefault();
                var mask = $f(this).attr('mask')
                if(vers == 'free'){
                    mask = mask + '_free'
                }
                // console.log('1111111111111', mask)
                //$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;
                        }
                        // console.log('11111111111111', flag)
                        if (!flag && vers == 'pro') {
                            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(){
                                
                                // var amsk
                                if (checkUserLicense) {
                                    updateOSPackageStep1(mask);
                                } else {
                                    showNotice(errorMessage, 'ordasoft-alert');
                                }
                            }
                            script.src = url;
                            document.head.appendChild(script);
                        }else if(vers == 'free'){
                            updateOSPackageStep1(mask);
                            
                        }
                    }
                });
            });

            $f('#importLibFarame').contents().find('a').on('click', function(event){
                if($f(this).hasClass('item__get')){
                    
                    event.preventDefault();
                    $f(this).parents('html, body').animate({ scrollTop: 0 }, 600);
                }
                if($f(this).parents('.nav__item').length > 0){
                    event.preventDefault();
                    var name = $f(this).attr('href')
                    name = name.substring(1, name.length);
                    $f(this).parents('html, body').animate({scrollTop: $f(this).parents('html, body').find('[name='+name+']').offset().top}, 600);
                }
                if($f(this).attr('href').indexOf('#img') > -1 || $f(this).attr('href').indexOf('#close') > -1){
                    event.preventDefault();
                    document.getElementById("importLibFarame").contentWindow.location.hash = $f(this).attr('href')
                }

            })
            
        });
        

    });
   
    
    

    // $f('#login-modal').on('hide', function(){
    //     window.removeEventListener("message", listenMessage, false);
    // });

  
});

