/**
 * Default CBS Accordion implemented with jQuery UI.
 *
 * @param context Context path
 */

document.addEventListener("DOMContentLoaded", function () {
    applyAccordion(window.cbs.contextPath);
    $('.accordion').each(function (i) {
        $(this).find('.acco:last').addClass('last');
        $(this).find('.accoH:last').addClass('last');
    });
});

function applyAccordionStatus(accordionTag, context) {
    if (accordionTag.next(".accoH").is(':hidden')) {
        accordionTag.next(".accoH").animate({"height": "toggle"}, "slow");
        accordionTag.addClass("act");
        updateAccordionSetting(accordionTag.next(".accoH").attr("id"), true, context);
    } else {
        accordionTag.next(".accoH").animate({"height": "toggle"}, "slow");
        accordionTag.removeClass("act");
        updateAccordionSetting(accordionTag.next(".accoH").attr("id"), false, context);
    }
}

/*
* This function is for AJAX call accordion.
* Otherwise the accordion will break down
*/
function applyAccordion2(context, boxId) {
    $("#" + boxId + "> .acco").on({
        click: function () {
            applyAccordionStatus($(this), context);
            return false;
        }
    });
}


function applyAccordion(context) {
    $('.acco').on({
        click: function () {
            applyAccordionStatus($(this), context);
            return false;
        }
    });
}

/**
 * Update accordion setting to to user settings using AJAX.
 * @param idStr Accordion component id
 * @param open True if this accordion is open, otherwise false
 * @param context Context path
 */
function updateAccordionSetting(idStr, open, context) {
    if (idStr == null || idStr.length == 0) {
        return false;
    }
    var id = idStr.substring("accordion".length, idStr.length);
    var urlJSON = context + '/customsettings/updateAccordionSetting.do?id=' + id + '&open=' + open;
    $.getJSON(urlJSON, function (data) {
        if (!data.status) {
            // An error occurred
            return;
        }
    });
}

/**
 * Global easy to use accordion plugin
 * @usage $('container-selector').cbsAccordion();
 *          The container should contain elements with class "trigger" which when clicked will open up the
 *          next sibling element. If the trigger element has class "open" the element will be open when page loads.
 */
(function ($) {
    $.fn.cbsAccordion = function () {
        this.each(function () {
            var container = $(this);
            var triggerers = $('.trigger', container);
            // Hide all accordions
            triggerers.each(function () {
                var triggerer = $(this);
                if (!triggerer.is('.open'))
                    triggerer.next().hide();
            });
            triggerers.click(function () {
                if ($(this).next().is(':visible')) {
                    $(this).next().slideUp();
                    return;
                }
                triggerers.each(function () {
                    var triggerer = $(this);
                    triggerer.next().slideUp();
                });
                $(this).next().slideDown();
            });
        });
    };
})(jQuery);

// Fixes for known browser bugs

var cbsBrowserFix = (function ($) {
    function init() {
        // Function calls here which need to be invoked on init
    }

    // Here goes function definitions

    return {
        init: init
    }
})($);

$(document).ready(function() {
    cbsBrowserFix.init();
});
// Socialmedia links
window.cbs = window.cbs || {};
var cbs = window.cbs;

cbs.socialLinks = (function () {

    function _extractParams(str) {
        // slices up url params, encodes the values, puts it back together
        var paramArr = [];
        var encodedArr = [];
        var encodedStr;

        paramArr = str.split("&").map(function (kv) {
            return kv.split("=", 2);
        });

        for (var i = 0; i < paramArr.length; i++) {
            encodedArr[i] = paramArr[i][0] + '=' + encodeURIComponent(paramArr[i][1]);
        }

        encodedStr = encodedArr.join('&');

        return encodedStr;
    }

    function init(context) {
        if (!(context instanceof Element || context instanceof HTMLDocument)) {
            context = document;
        }
        var anchors = context.querySelectorAll('.js-social-links');
        for (var i = 0; i < anchors.length; i++) {
            var element = anchors[i];
            element.addEventListener('click', openShareUrl, false);
        }
    }

    function openShareUrl(event) {
        var width;
        var height;
        var location;

        width = 620;
        height = 480;
        location = this.getAttribute('href');
        location = _extractParams(location);

        if (location.match(/linkedin/g)) {
            width = 1080;
            height = 700;
        } else if (location.match(/google/g)) {
            height = 600;
        }

        var foowin = openWithFocus(location, 'DETAILS', 'width=' + width + ',height=' + height
            + ',scrollbars=yes,location=no,left=8,top=8,menubar=yes,resizable=yes,toolbar=no,status=no');
        event.preventDefault();
        return false;
    }


    function openWithFocus(location, windowName, params) {
        var newWindow = window.open(location, windowName, params);
        if (newWindow !== null && newWindow !== undefined) {
            newWindow.focus();
            return newWindow;
        }
    }

    return {
        init: init,
        openShareUrl: openShareUrl
    }
})();

if (document.readyState === 'complete') {
    // DOM content already loaded, fire once the current script block has finished
    cbs.socialLinks.init();
} else {
    // Listen for the content loaded event
    document.addEventListener('DOMContentLoaded', cbs.socialLinks.init, {once: true});
}



// Higlighting errors
$(function() {
    $('form').find('.row','li', '.grid-x').addClass('c_form__item');

    //$('form').find('label').addClass('c_checkbox__label');

    var formItem = $('.c_form__item');

    formItem.each(function() {
        if (($(this).find('span.error').length > 0) || ($(this).find('label.error').length > 0)) {
            $(this).closest('.c_form__item').addClass('has-error');
            $(this).closest('.c_form__item').find('input').addClass('is-invalid').attr("aria-invalid", "true");
            $(this).closest('.c_form__item').find('select').addClass('is-invalid').attr("aria-invalid", "true");
            $(this).closest('.c_form__item').find('textarea').addClass('is-invalid').attr("aria-invalid", "true");

            if($(this).find('label.show-for-sr').length > 0) {
                $('<span class="exclaim hide-for-sr"></span>').insertAfter($(this).find('label.show-for-sr'));
            }
        }
    });

});
/* Adds css class demo-user to body - this file can be scrapped when proper JSP solution replaces it */
$(function() {
    if ($('.customer-name').text().trim() === "ANNA DEMO") {
        $('body').addClass('demo-user');
    }
});
var cbsMenu = (function ($) {
    function init() {
        $('.js-res-menu-toggle').on('click', function () {
            $('.c_page').toggleClass('mobileNav-open');
            $('.mobile-menu').toggleClass('is-open');
        });
    }
    return {
        init: init
    };
})($);

$(function() {
    cbsMenu.init();
    //special color class needs to be added c_service container has p.error message.
    $("p.error").parents('.c_service').addClass("c_error");
});

(function () {

    var addclass = function(el, className) {
        if (el.classList)
            el.classList.add(className);
        else
            el.className += ' ' + className;
    };

    var remclass = function(el, className) {
        if (el.classList)
            el.classList.remove(className);
        else
            el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    };

    var last_known_scroll_position = 0;
    var ticking = false;

    window.addEventListener('scroll', function(e) {

        last_known_scroll_position = window.scrollY;

        if (!ticking) {

            window.requestAnimationFrame(function() {
                if (last_known_scroll_position > (window.innerHeight * 0.15)) {
                    addclass(document.querySelector('.c_btn--backtotop'), 'active');
                    if ((window.innerHeight/document.querySelector('.c_btn--backtotop').clientHeight) < 6) {
                        // If the back to top button is higher than 20% of the available viewport size, add a inline class
                        addclass(document.querySelector('.c_btn--backtotop'), 'inline');
                    } else {
                        remclass(document.querySelector('.c_btn--backtotop'), 'inline');
                    }
                } else {
                    if (last_known_scroll_position < 1) {
                        remclass(document.querySelector('.c_btn--backtotop'), 'active');
                    }
                }
                ticking = false;
            });

            ticking = true;

        }

    });


}());
