function showAuthWindow(){
    $("html, body").animate({ scrollTop: 0 });
    $('.login-container').show();
    $('.login-container').addClass('active');
    $('.white-space').toggle();
    $('.white-space').toggleClass('active');
    $('.forgot-password-transparent-overlay').show();
    $("body").addClass("no-scroll");
    $('#news-receiver-corner').hide();
}

function checkAuthentification(host, successCallback, falseCallback) {
    if (navigator.vendor.indexOf('Goog') > -1) { // Cross-site login enabled only for Chrome right now. Other browser default settings prevent cross-site login
        $.ajax({
            type: "POST",
            url: host + "/public/users/check_authentication_JSON",
            data: {},
            xhrFields: {
                withCredentials: true
            },
            dataType: "json",
            success: function (data) {
                if ($(data).attr('status') == 'success') {
                    successCallback($(data).attr('a_tk'));
                } else {
                    falseCallback(host);
                }
            },
            fail: function (data) {
                return false;
            }
        });
    } else {
        console.log('Cross-site logon disabled');
    }
};

function authorise(host, tk, successCallback) {

    $.ajax({
        type: "POST",
        url: host + "/users/authentificate?data=" + tk + "&ajax=true",
        data: {},
        dataType: "json",
        success: function (data) {
            if ($(data).attr('success')) {
                successCallback();
                return true;
            } else {
                return false;
            }
        },
        fail: function (data) {
            // console.log(data);
            return false;
        }
    });
};

$(function () {

    current_domain = window.location.hostname.split('.')[0];
    // current_domain = window.location.hostname.split('.')[1]; // For demo testing
    top_level_domain = window.location.hostname.split('.')[1];
    domains = ['ifinanses', 'itiesibas', 'ibizness', 'iaudio'];

    if (current_domain == 'iaudio') {
        FB.init({
            appId            : '3207016976289796',
            autoLogAppEvents : true,
            xfbml            : true,
            version          : 'v12.0'
        });
    }

    // CROSS DOMAIN VERIFICATION DISABLED!

    // if(window.location.href.indexOf('logout') != -1){
    //     // logout all pages
    //     // if (!auth_status) {
    //         for (i = 0; i < domains.length; i++) {
    //             domain = domains[i];
    //             if (domain === current_domain) {
    //                 // skip this one.
    //                 continue;
    //             }

    //             src = window.location.protocol + "//" + domain + "." + top_level_domain + "/users/logout?iframe=true";
    //             // src = window.location.protocol + "//ralfs." + domain + ".izurnali.xyz" + "/users/logout?iframe=true"; // For demo testing
    //             ifr = $('<iframe width="1" height="1" src="' + src + '"></iframe>', {css: {'display': 'none'}});
    //             $('body').append(ifr);
    //         }
    //     // }


    // } else {
    //     //login all pages


    //     //if current domain is authorised, check other
    //     if (auth_status && a_tk) {
    //         for (i = 0; i < domains.length; i++) {
    //             domain = domains[i];
    //             if (domain === current_domain) {
    //                 // skip this one.
    //                 continue;
    //             }

    //             checkAuthentification(
    //                 window.location.protocol + "//" + domain + "." + top_level_domain,
    //                 // window.location.protocol + "//ralfs." + domain + ".izurnali.xyz", // For demo testing
    //                 function (a_tk) {
    //                 },
    //                 function (host) {
    //                     // Take host because in an async response domain will be the last from array
    //                     src = host + "/users/authentificate?data=" + a_tk + "&iframe=true";
    //                     ifr = $('<iframe width="1" height="1" src="' + src + '"></iframe>', {css: {'display': 'none'}});
    //                     $('body').append(ifr);
    //                 })
    //         }
    //     }

    //     // If current domain is not authorised, check others
    //     if (!auth_status) {

    //         for (i = 0; i < domains.length; i++) {
    //             domain = domains[i];
    //             if (domain === current_domain) {
    //                 // skip this one.
    //                 continue;
    //             }

    //             checkAuthentification(
    //                 window.location.protocol + "//" + domain + "." + top_level_domain,
    //                 // window.location.protocol + "//ralfs." + domain + ".izurnali.xyz", // For demo testing
    //                 function (a_tk) {
    //                     authorise(window.location.protocol + "//" + current_domain + "." + top_level_domain, a_tk, function () {
    //                     // authorise(window.location.protocol + "//ralfs." + current_domain + ".izurnali.xyz", a_tk, function () { // For demo testing
    //                         console.log("reloading...");
    //                         window.location.reload();
    //                     });
    //                 },
    //                 function () {
    //                     console.log('checkAuthentification failed');
    //                 }
    //             )
    //         }
    //     }
    // }
});

$(function () {

    /*
     * Show auth window when an unauthenticated user tries to access protected resources
     */
    if (window.location.search.includes('showAuth=true')) {
        showAuthWindow();
        $('#UserEmail').focus();
    }

    /*
     * Display message on failed login
     */
    if (window.location.search.includes('invalid-login=1')) {
        alert("Nepareizs lietotājvārds un/vai parole!");
    }

    /*
     * Scroll settings into view when redirected to profile from email
     */
    if (window.location.search.includes('fromEmail=true')) {
        $settings = $('.profile-settings-container');

        if ($settings.length) {
            $settings[0].scrollIntoView();
        }
    }

    if (window.location.search.includes('email')) {
        emailInput = $('#email-input');
        var emailFromQuery = new URLSearchParams(window.location.search).get('email');
        emailInput.val(emailFromQuery);
    }


    if (window.location.search.includes('forgotPassword=true')) {
        $('.login-container').hide();
        $('.authorization-popup').hide();
        $('.forgot-password-transparent-overlay').show();
        $('.forgot-password-text').show();
    }
    
    $('.article-text table').removeAttr('height');

    /*
     * Authentification button toggle functionality
     */
    $('.auth-btn, .auth-btn-mob-big').click(function () {
        //Conditional states allow the dropdown box appear and disappear
        showAuthWindow();
    });

    // Allow to hide the dropdown box if you click anywhere on the document
    $('.login-container, .auth-btn, .login-required, .auth-btn-mob-big').click(function (e) {
        e.stopPropagation();
    });

    $('.login-required').click(function () {
        showAuthWindow();
    });
    
    $('.forgot-password-transparent-overlay').click(function () {
        $('.login-container').hide();
        $('.imput-error').hide();
        $('.auth-btn').removeClass('active');
        $('.auth-btn-mob-big').removeClass('active');
        $('.white-space').hide();
        $('.white-space').removeClass('active');
        $('.forgot-password-transparent-overlay, .forgot-password-text, .add-bookmark-container').hide();
        $("body").removeClass("no-scroll");
        $('.mob-menu').hide();
        $('.article-send-to-mail-container').hide();
        $('.authorization-popup').hide();
        $('.popup-message').hide();
        $('#news-receiver-popup').hide();
        $('#news-receiver-corner').show();

    });

    $('.mobile-menu-transparent-overlay').click(function () {
        $('.mobile-menu-transparent-overlay').hide();
        $("body").removeClass("no-scroll-mob-menu");
        $('.mob-menu').hide();

        const iframe = $('#chatbot-iframe')[0];
        iframe.contentWindow.postMessage({ action: 'closePopup' }, iframe.src);
    });

    let topBottomShown = false;

    $(window).scroll(() => {        
        if ($(this).scrollTop() > 90 && !topBottomShown) {
            $('.mobile-scroll-top-button').fadeIn(400);
            topBottomShown = true;
        } else if ($(this).scrollTop() < 90 && topBottomShown) {
            $('.mobile-scroll-top-button').fadeOut(400);
            topBottomShown = false;
        }
    })

    if ($(window).scrollTop() > 90) {
        $('.mobile-scroll-top-button').show()
    }

    $('.mobile-scroll-top-button').click(() => {
        $(window).scrollTop(0);
    })

    
    $('.main-menu-chevron').click(function() {
        var menuRow = $(this).parent().parent();
        $('.subMenus').not(menuRow.find('.subMenus')).hide(200);
        $('.subMenus', menuRow).toggle(200);
        $('.active-mobile-menu').css('transform', 'rotate(0deg)');

        menuBlock = menuRow.children('.mainMenuName');

        if (!menuBlock.hasClass('active')) {
            $('.fa-chevron-circle-right', menuBlock).css('transform', 'rotate(90deg)');
            $('.fa-chevron-circle-right', menuBlock).addClass('active-mobile-menu');
        }

        $('.mainMenuName.active').not(menuBlock).removeClass('active');
        $('.mainMenuName', menuRow).toggleClass('active');
    });

    /*
     * Auth button functionality
     */
    $(".login-submit.fixed").click(function (e) {
        // authentificate(e, 'default');
    });

    var authentificate = function (e, place) {
        e.preventDefault();
        if (place == 'default') {
            var email = ".login-email";
            var password = ".login-password";
            var form = '.login';
        }
        if (place == 'popup') {
            var email = ".login-email.popup";
            var password = ".login-password.popup";
            var form = '.login.popup';
        }
        $.ajax({
            type: "POST",
            url: "/users/authentificate",
            dataType: "json",
            data: {
                User: {
                    email: $(email).val(),
                    password: $(password).val()
                },
            },
            success: function (data) {
                if (data.result == 'invalid') {
                    $('.imput-error').show();
                } else {
                    location.reload();
                }
            },
            error: function () {
                $('.imput-error').show();
            }
        });
    };

    /* 
     * Search
     */
    $('.header-search-btn').click(function () {
        $('.header-search').show();
        $('#search-menu').focus();
    });

    // if pressed enter in search field
    // then submit the form
    $('#search-menu').keypress(function (e) {
        if (e.keyCode == 13) {
            $('#keyword').val($.trim($(this).val()));
            $(this).closest('form').submit();
        }
    });

    $(document).mouseup(function (e) {
        var container = $('#search-popup');
        if (e.target.id != container.attr('id') && !container.has(e.target).length)
        {
            container.hide();
        }
    });

    $('.search-choose-btn').click(function () {
        chooseToggle();
        if ($('.search-choose').is(":visible")) {
            $(".search-choose").slideUp("slow", function () {
                $('.search-choose').hide();
            });
        } else {
            $(".search-choose").slideDown("slow", function () {
                $('.search-choose').show();
            });
        }
    });

    $('.search-choose-item').click(function () {
        chooseToggle();
        $('.search-category').data('category-id', $(this).data('category-id'));
        $('.search-category').text($(this).text());

        $(".search-choose").slideUp("slow", function () {
            $('.search-choose').hide();
        });
    });

    $('.search-go-mob').on("click", function () {
        $('#keyword-mob').val($.trim($('#search-menu-mob').val()));
        $(this).closest('form').submit();
    });

    $('#search-menu-mob, .search-form-container #SearchFind').on("keypress", function (e) {
        if (e.which == 13) {
            $('#keyword-mob').val($.trim($('#search-menu-mob').val()));
            $(this).closest('form').submit();
        }
    });

    $('.search-go').on("click", function () {
        $('#keyword').val($.trim($('#search-menu').val()));
        $('#search-cat').val($('.search-category').data('category-id'));
        $(this).closest('form').submit();
        // if ($('.input-search').val() != '') {
        //     var search_url = $('#search-popup #search_url').val();
        //     window.location.href = search_url + "?find=" + $('.input-search').val() + "&category=" + $('.search-category').data('category-id') + "&filter=all&sort=date";
        // }
    });

    function chooseToggle() {
        $('.search-chevron').toggleClass("rotate-arrow-180");
        $('.search-chevron').toggleClass("rotate-arrow-reset");
    }


    /*
     * Authorization popup
     */
    $('.authorization-popup .popup-btn-close, .authorization-popup .popup-anchor-close,'+
    '.popup-message .popup-btn-close, .popup-message .popup-anchor-close').click(function (event) {
        $('.forgot-password-transparent-overlay').hide();
        $("body").removeClass("no-scroll");
        $('.authorization-popup').hide();
        $('.popup-message').hide();
    });


    
    $(".login-submit.popup").click(function (e) {
        // authentificate(e, 'popup');
    });
    
    /*
     * Disable scroll on modal popup
     */
    $(".public-modal-open").click(function () {
        $("body").addClass("no-scroll");
    });
    
    $(".public-modal-close").click(function () {
        $("body").removeClass("no-scroll");
    });

    /*
     * Image captions for tiny images
     */
    var images = $('.tiny-image');
    images.each(function (i) {
        var alt = $(this).attr('alt');
        if (typeof alt !== 'undefined' && alt) {
            var float = $(this).css('float');

            var width = $(this).width();
            var height = $(this).height();
            var bottom = 0;
            var marginLeft = 0;
            var marginRight = 0;
            var display = 'inline-block';
            $(this).hide();
            var margin_left = $(this).css('margin-left');
            var margin_right = $(this).css('margin-right');
            $(this).show();
            if (margin_left != "0px" && margin_right != "0px") {
                marginLeft = 'auto';
                marginRight = 'auto';
                display = 'block';
            }
            if (float == 'none' && display != 'block') {
                bottom = 4;
            } else if (float == 'right') {
                right = float;
                bottom = 0;
            } else {
                bottom = 0;
            }

            $(this).wrap('<div class="img-caption-sibling" style="display: ' + display + '; float: ' + float + ';z-index: 2; position: relative; width: ' + width + 'px; margin-left: ' + marginLeft + ';  margin-right: ' + marginRight + ';"></div>');
            var dataToAdd = '<div style="position: absolute; bottom: ' + bottom + 'px; width: ' + width + 'px;"> \
                                        <div style="background-color: #000; opacity: 0.2; height: 24px;"></div> \
                                        <div style="line-height: 0px;  color: #fff; opacity: 1; position: absolute; bottom: 6px; font-size: 11px; margin-left: 10px; padding-right: 5px;"> \
                                            <i class="fa fa-camera"></i><div class="img-cation-text" style="display: inline-block; padding-left: 3px;">' + alt + '</div>\
                                        <div>\
                                    </div>';
            $(dataToAdd).insertBefore($(this));
        }
    });
    $('.login-facebook').on('click', function () {
        FB.login(function(response) {
            if (response.authResponse) {
                console.log('Welcome!  Fetching your information.... ');
                console.log(response);
                FB.api('/me?fields=id,email,first_name,last_name', function(responseMe) {
                    responseMe.signedRequest = response.authResponse.signedRequest;
                    if(responseMe.email === undefined) {
                        responseMe.email = responseMe.id + '@facebook.com';
                    }

                    console.log('response2', responseMe);
                    $.ajax({
                        type: "POST",
                        url: "/users/authentificate_facebook?ajax=true",
                        data: responseMe,
                        dataType: "json",
                        success: function (data) {
                            console.log('DATA', data);
                            if(data.Redirect) {
                                window.location.href = data.Redirect;
                            }

                        },
                        fail: function (data) {
                            console.log(data);
                            if(data.Redirect) {
                                window.location.href = data.Redirect;
                            }

                            return false;
                        }
                    });
                });
            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
        }, {scope: 'public_profile, email'});
    });

    $('.open-cookie-consent').click(function() {
        showCookieDetailsModal();
    });

    window.getCookie = function (key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    window.setCookie = function (key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
    }

    $('.show-mobile-menu').click(function () {
        $('.mob-menu').fadeIn(200)
        $('.mobile-menu-transparent-overlay').show();
        $("body").addClass("no-scroll-mob-menu");
    });

    $('.hide-mobile-menu').click(function () {
        $('.mob-menu').hide(200)
        $('.mobile-menu-transparent-overlay').hide();
        $("body").removeClass("no-scroll-mob-menu");
    });

    if ($('.invoice-iframe').length && $('.main-podcasts').length) {
        width = $('.main-podcasts').width() - 30;

        if (width > 790) {
            width = 790
        }

        $('.invoice-iframe').prop('width', width);
    }


    function chooseToggle() {
        $('.site-chevron').toggleClass("rotate-arrow-180");
        $('.site-chevron').toggleClass("rotate-arrow-reset");
    }

    $('.site-chevron-wrapper').click(function () {
        chooseToggle();
        if ($('.site-choose-body').is(":visible")) {
            $("body").removeClass("no-scroll-mob-menu");
            $('.site-choose-transparent-overlay').hide();
            $(".site-choose-body").slideUp(200, function () {
                $('.site-choose-body').hide();
            });
        } else {
            $("body").addClass("no-scroll-mob-menu");
            $('.site-choose-transparent-overlay').show();
            $(".site-choose-body").slideDown(200, function () {
                $('.site-choose-body').show();
            });
        }
    });

    $('.site-choose-transparent-overlay').click(function() {
        chooseToggle();
        $('.site-choose-transparent-overlay').hide();
        $("body").removeClass("no-scroll-mob-menu");
        $(".site-choose-body").slideUp(200, function () {
            $('.site-choose-body').hide();
        });
    });


    $('.site-choose-item-body').click(function () {
        chooseToggle();
        $("body").removeClass("no-scroll-mob-menu");
        $('.site-choose-transparent-overlay').hide();
        $(".site-choose-body").slideUp("slow", function () {
            $('.site-choose-body').hide();
        });
    });

    $('.news-popup-checkbox-item').click(function() {
        checkbox = $(this).find('input[type="checkbox"]');
        checkbox.prop('checked', !checkbox.is(':checked'));

        if (checkbox.attr('id') == 'client_get_news_popup' && checkbox.prop('checked')) {
            $('#client_get_news_ru_popup').prop('checked', false);
        } else if (checkbox.attr('id') == 'client_get_news_ru_popup' && checkbox.prop('checked')) {
            $('#client_get_news_popup').prop('checked', false);
        }
    });



});

$(document).ready(function() {
    const $articleText = $('#article-text');
    if ($articleText.length) {
        const $tablesAndImgs = $articleText.find('table, img');
        $tablesAndImgs.each(function() {
            const $elem = $(this);
            const $wrapperDiv = $('<div>').addClass('horizontal-scroll');
            $elem.before($wrapperDiv);
            $wrapperDiv.append($elem);
        }); 
    }
  
    
    var $textContainers = $(".article-category-open-text");
    $textContainers.each(function() {
        var originalText = $(this).text();
        var isMobile = window.innerWidth <= 1000;
        if (isMobile) {
            var truncatedText = originalText.trim().split(" ").slice(0, 20).join(" ");
            $(this).text(truncatedText += "...");
        }
    });

    let popup = $('#notification-popup');
    if (popup.length && getCookie('notification_popup_seen') !== 'true') {
        popup.fadeIn(500)

        setCookie('notification_popup_seen', 'true', 1);

        let offsetTop = popup.offset().top;
        let offsetLeft = popup.offset().left;

        $(window).scroll(function () {
            if ($(window).scrollTop() > offsetTop - 15) {
            popup.css({ position: 'fixed', top: '15px', left: offsetLeft });
            } else {
                popup.css({ position: '', top: '', left: '' });
            }
        });

    }
    
});

$(window).on('message', function (event) {
    let origin = event.originalEvent.origin;
    let { action, size: { x = '0', y = '0' } = {} } = event.originalEvent.data;

    if (origin === 'https://chatbot.ifinanses.lv' && action === 'showAuthWindow') {
        const iframe = $('#chatbot-iframe')[0];
        iframe.contentWindow.postMessage({ action: 'closePopup' }, iframe.src);
        showAuthWindow();
    }

    if (origin === 'https://chatbot.ifinanses.lv' && action === 'navigateToSubscribe') {
        window.location.href = '/abonesana';
    }

    if (origin === 'https://chatbot.ifinanses.lv' && action === 'getATK') {
        const iframe = $('#chatbot-iframe')[0];
        const message = { type: 'a_tk', message: window.a_tk };
        iframe.contentWindow.postMessage(message, iframe.src);
    }

    if (origin === 'https://chatbot.ifinanses.lv' && action === 'adjustSize') {
        const iframe = $('#chatbot-iframe');
        let isMobile = window.innerWidth <= 1000;

        if (isMobile) {
            if (y === '100%') { // open
                iframe.css({ 'width': '50%', 'height': '50%', 'bottom': '0', 'right': '0', 'z-index': '999' });
                $('.mobile-menu-transparent-overlay').show();
                $("body").addClass("no-scroll");
            } else { // closed
                iframe.css({ 'width': x, 'height': y, 'bottom': '10px', 'right': '10px', 'z-index': '2' });
                $('.mobile-menu-transparent-overlay').hide();
                $("body").removeClass("no-scroll");
            }
        } else {
            iframe.css({ 'width': x, 'height': y, 'bottom': '10px', 'right': '10px' });
        }
    }
});
