/* Minification failed. Returning unminified contents.
(2484,66-67): run-time error JS1195: Expected expression: >
(2486,22-23): run-time error JS1195: Expected expression: )
(2513,45-46): run-time error JS1195: Expected expression: )
(2513,48-49): run-time error JS1195: Expected expression: >
(2513,76-77): run-time error JS1004: Expected ';': )
(2517,29-33): run-time error JS1193: Expected ',' or ')': else
(2520,29-30): run-time error JS1002: Syntax error: }
(2529,37-38): run-time error JS1195: Expected expression: )
(2529,40-41): run-time error JS1195: Expected expression: >
(2529,59-60): run-time error JS1004: Expected ';': )
(2532,21-22): run-time error JS1002: Syntax error: }
(2533,37-38): run-time error JS1195: Expected expression: )
(2533,39-40): run-time error JS1004: Expected ';': {
(2538,17-18): run-time error JS1002: Syntax error: }
(2539,58-59): run-time error JS1004: Expected ';': {
(2550,18-19): run-time error JS1195: Expected expression: )
(2555,31-32): run-time error JS1195: Expected expression: )
(2555,33-34): run-time error JS1004: Expected ';': {
(2565,5-6): run-time error JS1002: Syntax error: }
(2567,38-39): run-time error JS1197: Too many errors. The file might not be a JavaScript file: )
 */
/*
 * Global
 * This file contains global functions that are used
 * across the site
 */
this.StarterKit = this.StarterKit || {};

$(document).ready(function () {

    StarterKit.init = function () {
        this.alerts.bind();
        this.selects.bind();
        this.socialpagesharing.bind();
        this.ipdetection.bind();
    };

    var toggle = true;

    $(".sk-sidebar-icon").click(function (e) {
        e.preventDefault();
        if (toggle) {
            $(".sk-sidebar-container-nav").addClass("sk-sidebar-collapsed").removeClass("sk-sidebar-collapsed-back");
            $("#menu span").css({ "position": "absolute", "right": "20px" });
            $(".sk-sidebar-icon").removeClass("open");
        }
        else {
            $(".sk-sidebar-container-nav").removeClass("sk-sidebar-collapsed").addClass("sk-sidebar-collapsed-back");
            $(".sk-sidebar-icon").addClass("open");
            setTimeout(function () {
                $("#menu span").css({ "position": "relative" });
            }, 200);
        }
        toggle = !toggle;
    });

    StarterKit.alerts = {
        bind: function () {
            $('#sk-language-select').change(function () {
                window.location = $('#sk-language-select option:selected').val();
            });

            $('.js-lightbox').magnificPopup({
                type: 'image',
                gallery: {
                    enabled: true,
                    navigateByImgClick: true,
                    preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
                }
            });

            // init magnific popup for iframes (videos)
            $('body').magnificPopup({
                delegate: '.js-iframe-lightbox',
                type: 'iframe',
                iframe: {
                    markup:
                    '<div class="mfp-iframe-scaler">' +
                    '<div class="mfp-title"></div>' +
                    '<div class="mfp-close"></div>' +
                    '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>' +
                    '<div class="mfp-socialshare"></div>' +
                    '</div>'
                },
                callbacks: {
                    markupParse: function (template, values, item) {
                        values.title = item.el.data('video-title');

                        if (item.el.data('share') === 'True') {
                            var socialShareHtml = "<span>" + item.el.data("share-text") + "</span>";

                            if (item.el.data('share-facebook') === 'True') {
                                socialShareHtml += "<a href=\"http://www.facebook.com/share.php?u=" + item.el.attr("href") + "\" target=\"popup\" onclick=\"window.open('http://www.facebook.com/share.php?u=" + item.el.attr("href") + "','name','width=600,height=400')\"><i class='fa fa-facebook-square'></i></a>";
                            }

                            if (item.el.data('share-twitter') === 'True') {
                                socialShareHtml += "<a href=\"http://twitter.com/intent/tweet?status=" + item.el.attr("href") + "\" target=\"popup\" onclick=\"window.open('http://twitter.com/intent/tweet?status=" + item.el.attr("href") + "','name','width=600,height=400')\"><i class='fa fa-twitter-square'></i>";
                            }

                            if (item.el.data('share-google') === 'True') {
                                socialShareHtml += "<a href=\"https://plus.google.com/share?url=" + item.el.attr("href") + "\" target=\"popup\" onclick=\"window.open('https://plus.google.com/share?url=" + item.el.attr("href") + "','name','width=600,height=400')\"><i class='fa fa-google-plus-square'></i>";
                            }

                            if (item.el.data('share-pinterest') === 'True') {
                                socialShareHtml += "<a href=\"http://pinterest.com/pin/create/bookmarklet/?url=" + item.el.attr("href") + "\" target=\"popup\" onclick=\"window.open('http://pinterest.com/pin/create/bookmarklet/?url=" + item.el.attr("href") + "','name','width=600,height=400')\"><i class='fa fa-pinterest-square'></i>";
                            }

                            if (item.el.data('share-tumblr') === 'True') {
                                socialShareHtml += "<a href=\"http://www.tumblr.com/share?v=3&u=" + item.el.attr("href") + "\" target=\"popup\" onclick=\"window.open('http://www.tumblr.com/share?v=3&u=" + item.el.attr("href") + "','name','width=600,height=400')\"><i class='fa fa-tumblr-square'></i>";
                            }

                            values.socialshare = socialShareHtml;
                        }
                    }
                }
            });

            $('.js-popup-lightbox').magnificPopup({
                type: 'inline',
                modal: true
            });

            // For instructions on how to modify magnific popup's
            // behaviour see: http://dimsemenov.com/plugins/magnific-popup/
            $('.sk-gallery, .sk-product-images').magnificPopup({
                delegate: 'a',
                type: 'image',
                gallery: {
                    enabled: true,
                    navigateByImgClick: true,
                    preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
                },
                image: {
                }
            });

            $('.alert').on('click', '.close', function () {

                var alert = $(this).closest('.alert');
                alert.alert('close');

                var cookieName = alert.attr('id');

                var sessionMessage = alert.attr('data-show-on-every-session');
                var expiryDate = new Date();
                if (sessionMessage === "True") {
                    var date = new Date();
                    var day = date.getDate();
                    var month = date.getMonth() + 1;
                    var year = date.getFullYear();
                    var hours = date.getHours();
                    var minutes = date.getMinutes();
                    var seconds = date.getSeconds();

                    if ((String(day)).length === 1)
                        day = '0' + day;
                    if ((String(month)).length === 1)
                        month = '0' + month;
                    if ((String(hours)).length === 1)
                        hours = '0' + hours;
                    if ((String(minutes)).length === 1)
                        minutes = '0' + minutes;
                    if ((String(seconds)).length === 1)
                        seconds = '0' + seconds;

                    var dateClosed = day + "/" + month + "/" + year + " " + hours + ":" + minutes + ":" + seconds;

                    expiryDate.setTime(expiryDate.getTime() + (60 * 1000 * 15));
                    document.cookie = cookieName + "=" + dateClosed + ";path=/;expires=" + expiryDate.toUTCString();

                } else {
                    expiryDate = new Date();
                    expiryDate.setDate(expiryDate.getDate() + 100 * 365);
                    document.cookie = cookieName + "=1;path=/;expires=" + expiryDate.toUTCString();
                }

                return false;
            });

            $('.alert').bind('closed.bs.alert', function () {
                $(this).remove();
                if ($('.sk-message').length == 0) { $('#site-message-container').remove(); }
            })
        }
    };

    // config for dropdown selects
    StarterKit.selects = {
        bind: function () {
            $('.js-select').selectpicker();
        }
    };

    // setup social page sharing new window
    StarterKit.socialpagesharing = {
        bind: function () {
            $(".sk-social-page-sharing a").click(function (e) {
                e.preventDefault();
                window.open(
                    $(this).attr("href"), "shared_dialog", "width=626,height=436");
                return false;
            });
        }
    };
    StarterKit.ipdetection = {
        bind: function () {
            $("#rb-ipredirect-accept").click(function (e) {
                e.preventDefault();
                var form = $(this).closest('form');
                $.post(form.attr("action"), form.serialize(), function () {
                    $('#rb-ipredirect-container').remove();
                    window.location.reload(true);
                })
            });
            $("#rb-ipredirect-close").click(function (e) {
                e.preventDefault();
                $('#rb-ipredirect-container').remove();
            });
            var removeClass = function (element, value) {
                $(element).attr('class', function (index, classNames) {
                    return classNames.replace(value, '').trim();
                });
            }
            var addClass = function (element, value) {
                $(element).attr('class', function (index, classNames) {
                    return classNames + ' ' + value;
                });
            }
            $(".js-selector").click(function (e) {
                e.preventDefault();
                $('.clp-area-picker>a').each(function () {
                    $(this).removeClass("is-active");
                });
                var href = $(this).attr("href");
                var current = $(href);
                var buttonClicked = $("a[href='" + href + "']")
                $("li.js-area").each(function () {
                    var currentMapElement = '#map-' + $(this).attr('id');
                    if (current.attr("id") !== $(this).attr("id")) {
                        $(this).removeClass("is-active");
                        removeClass(currentMapElement, "is-active");
                    }
                    else if ($(this).hasClass("is-active")) {
                        $(this).removeClass("is-active");
                        removeClass(currentMapElement, "is-active");
                    }
                    else {
                        $(this).addClass("is-active");
                        addClass(currentMapElement, "is-active");
                        buttonClicked.addClass("is-active");
                    }
                });
                if ($("li.js-area.is-active").length) {
                    $("#js-areas").removeClass("is-inactive");
                }
                else {
                    $("#js-areas").addClass("is-inactive");
                }
            });
        }
    };

    StarterKit.c4c = {
        bind: function () {
            // Example bind date field with datepicker
            $('#c4c-contact-us-form').on('c4c-form:loaded', function () {
                $('.c4c-datepicker .form-control').datepicker({
                    format: 'yyyy-mm-dd',
                    startDate: '-150y',
                    startView: 2
                });
            });
        }
    }

    StarterKit.init();

    /* Nav Related
     * Scrollspy/Affix/scrollTo
     **/
    (function () {
        var $body = $('body');
        var resultNav = $('#result-nav');
        var resultNavHeight = 0;
        var updateNavHeight = function () {
            resultNavHeight = (resultNav.length > 0) ? resultNav.height() : 0;
        };
        updateNavHeight();

        // scroll top
        $('.js-scroll-to').on('click', function () {
            var target = $(this).attr('href');

            $('html, body').animate({ scrollTop: $(target).offset().top - resultNavHeight + 1 }, 400);
            return false;
        });

        //scrollspy
        if ($body.hasClass('scrollspy')) {
            $body.scrollspy({ offset: resultNavHeight, target: '#result-nav' });
        }

        // affix
        resultNav.affix({
            offset: {
                top: function () {
                    return (this.top = resultNav.offset().top - 31)
                },
                bottom: 0
            }
        })


        // on windows resize update nav height and
        // correct the scrollspy offset
        var timer;
        $(window).resize(function () {
            clearTimeout(timer);
            timer = setTimeout(function () {
                updateNavHeight();
                if ($body.data('bs.scrollspy'))
                    $body.data('bs.scrollspy').options.offset = resultNavHeight;
            }, 1000);
        })

        // alter next sibling element's padding on
        // affix and unaffix (at top)
        resultNav.on('affix.bs.affix', function () {
            var nextItem = resultNav.next();
            nextItem.css('padding-top', resultNavHeight);
        });

        resultNav.on('affixed-top.bs.affix', function () {
            var nextItem = resultNav.next();
            nextItem.css('padding-top', 0);
        });
    })()

});
/*
 * Tip Exchange 2.0 Landing Page
 * Functions that are specific to TE 2.0
 */



StarterKit.TipExchangeLanding = StarterKit.TipExchangeLanding || {

    Init: function () {
        this.IsotopeInit.bind();
        this.InitSelectBoxes.bind();

        //$('.sk-tip-exchange-load-more-container').on('click', '#sk-tip-exchange-load-more', StarterKit.TipExchangeLanding.BeforeSubmit);

        $('#sk-tip-exchange-load-more').on('click', StarterKit.TipExchangeLanding.Blocks.BeforeSubmit);

        $('.js-sk-tip-exchange-category-toggle').on('click', StarterKit.TipExchangeLanding.Filters.Submit);

        $('.js-tip-exchange-filter-selectbox').on('change', StarterKit.TipExchangeLanding.Filters.Submit);

        $('body').on('click', '.js-social-share', StarterKit.TipExchangeLanding.InitSocialIcons);

    },

    IsotopeInit: {
        bind: function () {
            $(window).load(function () {
                $('.js-tip-exchange-tiles').isotope({
                    itemSelector: '.sk-tip-exchange-tile',
                    layoutMode: 'packery',
                    percentPosition: true,
                    masonry: {
                        columnWidth: '.sk-tip-exchange-col-sizer'
                    }
                });
            });
        }
    },

    IsotopeRefresh: function () {
        $('.js-tip-exchange-tiles').isotope('reloadItems').isotope();
    },

    InitSocialIcons: function (e) {
        $.magnificPopup.open({
            items: {
                src: '#social-sharing',
                type: 'inline',
                closeBtnInside: true
            }
        });
        $(".sk-social-page-sharing").show();
    },

    InitSelectBoxes: {
        bind: function () {
            $(window).load(function () {
                $('.js-tip-exchange-filter-selectbox').selectpicker({
                });
            });
        }
    }
}

StarterKit.TipExchangeLanding.Blocks = StarterKit.TipExchangeLanding.Blocks || {
    NextPageNumber: 2,
    HasNextPage: true,

    BeforeSubmit: function (event) {
        if ($(this).is("[disabled]")) {
            console.log('No more pages!');
            event.preventDefault();
        }
        $('#sk-tip-exchange-tiles-form').attr('data-ajax-mode', 'after');
    },

    Success: function (data, status, xhr) {
        StarterKit.TipExchangeLanding.Blocks.NextPageNumber = xhr.getResponseHeader('Pager-Next-Page-Number');
        StarterKit.TipExchangeLanding.Blocks.HasNextPage = xhr.getResponseHeader('Pager-Has-Next').toLowerCase() === 'true';
        if (StarterKit.TipExchangeLanding.Blocks.HasNextPage) {
            $('#sk-tip-exchange-load-more').removeAttr("disabled");
        }
        else {
            $('#sk-tip-exchange-load-more').attr("disabled", "disabled");
        }
        StarterKit.TipExchangeLanding.IsotopeRefresh();
    },

    Reset: function () {
        StarterKit.TipExchangeLanding.Blocks.NextPageNumber = 1;
        StarterKit.TipExchangeLanding.Blocks.HasNextPage = true;
    }
}

StarterKit.TipExchangeLanding.Filters = StarterKit.TipExchangeLanding.Filters || {

    Get: function (ajaxContext) {
        if (StarterKit.TipExchangeLanding.Blocks.HasNextPage) {
            var pageNo = "&p=" + StarterKit.TipExchangeLanding.Blocks.NextPageNumber;
            var filters = StarterKit.TipExchangeLanding.Filters.GetActiveFilters();
            this.url = this.url + pageNo + filters;
            return true;
        }
        return false;
    },

    GetActiveFilters: function () {
        var filters = "";
        var activeCategoryFilters = $('.js-sk-tip-exchange-category-toggle.active-cat');
        activeCategoryFilters.each(function (e) {
            var categoryId = $(this).attr('data-category-id');
            filters += '&categoryfilters=' + categoryId;
        });
        //.class('sk-tip-exchange-landing-tag-filter')
        var tagFilters = $(".js-tip-exchange-filter-selectbox");
        tagFilters.each(function (e) {
            var tagId = $(this).find(":selected").val();
            if (tagId !== "-1") {
                filters += '&tagfilters=' + tagId;
            }
        });

        return filters;
    },

    Submit: function () {
        var that = $(this);
        if (!that.hasClass('active-cat')) {
            that.addClass('active-cat');
        } else {
            that.removeClass('active-cat');
        }
        StarterKit.TipExchangeLanding.Blocks.Reset();
        $('#sk-tip-exchange-tiles-form').attr('data-ajax-mode', 'replace');
        $('#sk-tip-exchange-tiles-form').submit();
    }
}

$(document).ready(function () {
    StarterKit.TipExchangeLanding.Init();
});
/*
 * RB StarterKit Tip Exchange
 */

// TipExchange is declared on RBStarterKitTipExchange.cshtml
var recaptchaTipForm;
var recaptchaQuestionForm;
var onloadReCaptchaCallback = function () {
    var isRecaptchaValidationEnabled = ($("#ReCaptchaValidationEnabled").val() == "true");

    if (isRecaptchaValidationEnabled == true) {
        var recaptchaSiteKey = $("#ReCaptchaSiteKey").val();
        recaptchaTipForm = grecaptcha.render('ReCaptchaTipForm', {
            'sitekey': recaptchaSiteKey
        });
        recaptchaQuestionForm = grecaptcha.render('ReCaptchaQuestionForm', {
            'sitekey': recaptchaSiteKey
        });
    }
}

$(document).ready(function () {
    LikedItemStatus();

    //Custom Validator - Taken from Contact Form Logic
    $.fn.bootstrapValidator.validators.requiredCheckbox = {
        validate: function (validator, $field, options) {
            //If the field is checked - then I am valid
            return $field[0].checked;
        }
    };

    //Custom Validator - Verify File Upload
    //File type & then size based on type (video or image)
    $.fn.bootstrapValidator.validators.validFile = {
        html5Attributes: {
            message: 'message',
            incorrectfile: 'incorrectfile',
            bigvideo: 'bigvideo',
            bigimage: 'bigimage'
        },
        validate: function (validator, $field, options) {
            //Get the error element that we will display
            //So we can manipulate the text inside of it
            var errorElement = $field.next('small[data-bv-validator="validFile"]');

            //Get the file input as DOM not jQuery
            var fileInput = $field[0];
            if (fileInput.files != null && fileInput.files.length > 0) {
                //Get all files in the file input
                var files = fileInput.files;

                //Get first file from collection - should only ever be one
                var fileUploaded = files[0];

                //If we have a file - Get it's file extention
                var fileName = fileUploaded.name;
                var fileExtension = getFileExtension(fileName);

                if (isVideo(fileExtension)) {
                    //Yes I am a video & valid file type
                    //Let's verify size
                    var fileSizeMB = 50;
                    var fileSizeKB = fileSizeMB * 1024;
                    var fileSizeBytes = fileSizeKB * 1024;

                    if (checkFileSize(fileUploaded.size, fileSizeBytes)) {
                        //File Size is less than 50MB
                        return true;
                    } else {
                        //File size TOO big greater than 50MB
                        errorElement.text(options.bigvideo);
                        return false;
                    }
                } else if (isImage(fileExtension)) {
                    //Yes I am an image & valid file type
                    //Let's verify size
                    var fileSizeMB = 5;
                    var fileSizeKB = fileSizeMB * 1024;
                    var fileSizeBytes = fileSizeKB * 1024;

                    if (checkFileSize(fileUploaded.size, fileSizeBytes)) {
                        //File Size is less than 50MB
                        return true;
                    } else {
                        //File size TOO big greater than 50MB
                        errorElement.text(options.bigimage);
                        return false;
                    }
                } else {
                    //Not an image OR a video
                    //Invalid filetype !!
                    errorElement.text(options.incorrectfile);
                    return false;
                }
            } else {
                //No Files Selected - still valid
                return true;
            }
        }
    };

    //this will bind the tip/question forms
    $('.sk-tip-exchange-form').bootstrapValidator({
        submitHandler: function (validator, form, submitButton) {
            //DO NOTHING
            //As our native Form Submit is dealing with this
            //Unfortunately can't just use this callback function here for submit logic
            //As once from is reset it does not seem to rebind against this...?!
        }
    });

    $(document).on('submit', '.sk-tip-exchange-form, .sk-comment-form', function (e) {
        //Prevent form default submit
        e.preventDefault();

        var $this = $(this);

        //Get form validator plugin - to get it's API methods
        var validator = $this.data('bootstrapValidator');

        //Re-validate the form
        validator.validate();

        //Verify if the form is valid
        if (validator.isValid()) {
            var isRecaptchaValidationEnabled = ($("#ReCaptchaValidationEnabled").val() == "true");

            if (isRecaptchaValidationEnabled == true) {
                var nodeId = $("#ReCaptchaNodeId").val();
                var recaptchaResponse = "";
                var recaptchaValidationElement;

                if ($(e.currentTarget.parentElement).hasClass("sk-tip-exchange-question-form")) {
                    var recaptchaResponse = grecaptcha.getResponse(recaptchaQuestionForm);
                    var recaptchaValidationElement = $("#ReCaptchaQuestionFormValidation");
                } else if ($(e.currentTarget.parentElement).hasClass("sk-tip-exchange-tip-form")) {
                    var recaptchaResponse = grecaptcha.getResponse(recaptchaTipForm);
                    var recaptchaValidationElement = $("#ReCaptchaTipFormValidation");
                }

                $.post("/umbraco/api/ReCaptchaApi/Validate?nodeId=" + nodeId + "&recaptchaResponse=" + recaptchaResponse, function (data) {
                    if (data == true) {
                        recaptchaValidationElement.addClass("hidden");
                        $('.sk-tip-exchange-shadow-box').toggleClass('hidden');
                        $('.sk-tip-exchange-shadow-box-image').toggleClass('hidden');

                        //prevent scrolling
                        $('html, body').toggleClass('scroll-prevent');

                        //We are valid - run our submitForm AJAX logic
                        submitForm($this);
                    } else {
                        recaptchaValidationElement.removeClass("hidden");
                    }
                });
            }
            else
            {
                $('.sk-tip-exchange-shadow-box').toggleClass('hidden');
                $('.sk-tip-exchange-shadow-box-image').toggleClass('hidden');

                //prevent scrolling
                $('html, body').toggleClass('scroll-prevent');

                //We are valid - run our submitForm AJAX logic
                submitForm($this);
            }
        }
    });

    $('body').on('reset', '.sk-tip-exchange-form, .sk-comment-form', function () {
        $('.js-sk-attachment-name').html('');
    });

    $('body').on('click', 'a[data-toggle-show]', function (e) {
        e.preventDefault();
        var $this = $(this),
            show = $this.attr('data-toggle-show'),
            hide = $this.attr('data-toggle-hide');

        if ($(hide + ':visible').length) {
            //Hidden item is visible
            //Add .hidden class
            $(hide).addClass('hidden');
        }

        $(show).toggleClass('hidden');

        $('.js-dropdown').removeClass('open');
        $(show + ' form').show();
    });

    $('body').on('click', '.sk-tip-exchange-load-more', function (e) {
        e.preventDefault();

        //Get the value in the filter dropdown to pass to our function
        if ($('.js-dropdown.js-tag1-filter a.js-selected-dropdown').length > 0) {
            TipExchange.tag1 = $('.js-dropdown.js-tag1-filter a.js-selected-dropdown').data().tagid;
        }

        if ($('.js-dropdown.js-tag2-filter a.js-selected-dropdown').length > 0) {
            TipExchange.tag2 = $('.js-dropdown.js-tag2-filter a.js-selected-dropdown').data().tagid;
        }

        if ($('.js-dropdown.js-filter-type a.js-selected-dropdown').length > 0) {
            TipExchange.filter = $('.js-dropdown.js-filter-type a.js-selected-dropdown').data().filtervalue;
        } else {
            TipExchange.filter = 'Latest';
        }

        //When it's unaswered - only one call to API needed
        //As this uses a single/both column style view
        if (TipExchange.filter === 'Unanswered') {
            $.when(ParseItemsForFilter('question', parseInt(TipExchange.questionCurrentPage) + 1)).done(function () {
                CheckForLoadMoreButton();
                LoadVideos();
            });
        } else {
            //Filter selected/changed
            //Go & get new results
            $.when(ParseItemsForFilter('question', parseInt(TipExchange.questionCurrentPage) + 1), ParseItemsForFilter('tip', parseInt(TipExchange.tipCurrentPage) + 1)).done(function () {
                CheckForLoadMoreButton();
                LoadVideos();
            });
        }
    });

    $('body').on('click', '.panel-comment button', function (e) {
        e.preventDefault();

        var $this = $(this),
            $commentFormContainer,
            $labelElement,
            $submitElement;

        if ($this.parent('.panel-comment').find('.panel-comment-form .sk-tip-exchange-comment-form').length == 0) {
            $commentFormContainer = $('.sk-tip-exchange-comment-form.template-comment-form').clone();
            $commentFormContainer.removeClass('template-comment-form');
            $this.parent('.panel-comment').find('.panel-comment-form').append($commentFormContainer);
        } else {
            $commentFormContainer = $this.parent('.panel-comment').find('.panel-comment-form .sk-tip-exchange-comment-form');
        }

        $commentFormContainer.find('.sk-comment-form').bootstrapValidator({
            submitHandler: function (validator, form, submitButton) {
                //DO NOTHING
                //As our native Form Submit is dealing with this
                //Unfortunately can't just use this callback function here for submit logic
                //As once from is reset it does not seem to rebind against this...?!
            }
        });

        $labelElement = $commentFormContainer.find('.js-sk-tip-exchange-comment-form-message-label');
        $submitElement = $commentFormContainer.find('.js-sk-tip-exchange-comment-form-submit');

        //set dictionary values depending on the itemtype
        //if is a question item then...
        if ($commentFormContainer.parents('.sk-tip-exchange-questions-item').length > 0) {
            $labelElement.text($labelElement.data().questionlabel);
            $submitElement.val($submitElement.data().questionvalue);
        } else if ($commentFormContainer.parents('.sk-tip-exchange-tips-item').length > 0) {
            $labelElement.text($labelElement.data().tiplabel);
            $submitElement.val($submitElement.data().tipvalue);
        }

        $commentFormContainer.find('.js-comment-form-message-label').text();
        $commentFormContainer.toggleClass('hidden');
        $commentFormContainer.find('form').css('display', '');
        $commentFormContainer.find('input[name="ParentId"]').val($this.data().parentid);
        $commentFormContainer.find('#firstName-comment').focus();
    });

    $('body').on('click', '.comments-show-more', function (e) {
        e.preventDefault();

        var apiUrl = '/umbraco/Api/TipExchangeWebApi/GetComments',
            $this = $(this),
            panelComment = $this.parents('.panel-comment'),
            parentId = panelComment.children('button').data().parentid,
            commentsWrapper = panelComment.find('.comments-wrapper');

        //Comments-wrapper is hidden
        if (panelComment.find('.comments-wrapper:hidden').length) {
            //Go & fetch items from API
            $.ajax({
                type: 'GET',
                url: apiUrl,
                data: {
                    id: parentId,
                    currentPageId: TipExchange.currentNodeId
                },
                success: function (data) {
                    data.forEach(function (item) {
                        item.Created = moment(item.Created).format('DD MMMM YYYY');
                        item.CurrentNodeId = TipExchange.currentNodeId;
                        item.ReportDictionaryText = TipExchange.reportText;
                        item.ImageUrl = checkForImage(item.MediaPath);
                        item.ImageUrlWithoutProtocol = item.ImageUrl ? item.ImageUrl.replace('http://', '') : null;
                    });

                    //Creates the json object to do the mustache binding
                    var mustacheData = { comments: data };

                    var htmlString = mustacheTemplate(mustacheData, '#commentTemplate');

                    //Replace every time - rather than appned, as if we was to toggle list would just grow
                    commentsWrapper.html(htmlString);
                    LoadVideos();
                },
                error: function (request) {
                    panelComment.append(request.responseJSON.Message);
                }
            });
        }

        //Toggle visbility of comment items
        commentsWrapper.toggleClass('hidden');
    });

    $('body').on('click', '.report-item', function (e) {
        e.preventDefault();
        var $this = $(this),
            id = $this.attr('data-report-id'),
            nodeId = $this.attr('data-current-node-id'),
            apiUrl = '/umbraco/Api/TipExchangeWebApi/ReportItem';

        //Before we submit - remove any divs with .report-message
        //As if we click report multiple times we will stack the thanks/error message from API
        $('.report-message').remove();

        $.ajax({
            type: 'GET',
            url: apiUrl,
            data: { itemId: id, currentNodeId: nodeId },
            success: function (data) {
                var html = '<div class="report-message">' + data.Message + '</div>';
                $this.closest('.panel-stats').append(html);
            },
            error: function (request) {
                var html = '<div>' + request.responseJSON.Message + '</div>';
                $this.closest('.panel-stats').append(html);
            }
        });
    });

    $('body').on('click', '.js-item-like', function (e) {
        e.preventDefault();
        var $this = $(this),
            id = $this.attr('data-like-id'),
            apiUrl = '/umbraco/Api/TipExchangeWebApi/LikeItem/' + id;

        $.ajax({
            type: 'POST',
            url: apiUrl,
            success: function (data) {
                $this.text(data.Likes);
                LikedItemStatus();
            },
            error: function (request) {
            }
        });
    });

    //toggle dropdowns
    $('.js-dropdown').on('click', function () {
        $(this).toggleClass('open');
        $('.js-dropdown').not($(this)).removeClass('open');
    });

    //Filter/Tags
    $('.js-dropdown a').on('click', function (e) {
        e.preventDefault();

        var $this = $(this);

        $this.parents('.dropdown-menu').find('a').each(function () {
            $(this).removeClass('js-selected-dropdown');
        });
        $this.addClass('js-selected-dropdown');


        //change the dropdown display value
        $this.parents('.js-dropdown').find('button .sk-tip-exchange-dropdown-label').text($this.text());

        //Every time we change the filter or tag reset the pageCount back to 1
        TipExchange.tipCurrentPage = 1;
        TipExchange.tipTotalPages = 1;
        TipExchange.questionCurrentPage = 1;
        TipExchange.questionTotalPages = 1;

        //Get the value in the filter dropdown to pass to our function
        if ($this.parents('.js-dropdown.js-tag1-filter').length > 0) {
            TipExchange.tag1 = $this.data().tagid;
        }

        if ($this.parents('.js-dropdown.js-tag2-filter').length > 0) {
            TipExchange.tag2 = $this.data().tagid;
        }

        if ($this.parents('.js-dropdown.js-filter-type').length > 0) {
            TipExchange.filter = $this.data().filtervalue;
        }
        else if ($('.js-dropdown.js-filter-type .js-selected-dropdown').length > 0) {
            TipExchange.filter = $('.js-dropdown.js-filter-type .js-selected-dropdown').data().filtervalue;
        } else {
            TipExchange.filter = 'Latest';
        }

        //When it's unaswered - only one call to API needed
        //As this uses a single/both column style view
        if (TipExchange.filter === 'Unanswered') {
            $.when(ParseItemsForFilter('question', TipExchange.questionCurrentPage)).done(function () {
                CheckForLoadMoreButton();
            });
        } else {
            //Filter selected/changed
            //Go & get new results
            $.when(ParseItemsForFilter('question', TipExchange.questionCurrentPage)).then(ParseItemsForFilter('tip', TipExchange.tipCurrentPage)).done(function () {
                CheckForLoadMoreButton();
            });
        }
    });

    //Url change for addthis widget
    $('body').on('click', '.comments-share-this', function () {
        return window.addthis.update("share", "url", window.location.protocol + "//" + window.location.host + $(this).data("url")), window.addthis_sendto("more");
    });

    //close dropdowns when click outside
    $(document).on('click', function (event) {
        if (!$(event.target).closest('.js-dropdown').length) {
            if ($('.js-dropdown.open').length > 0) {
                $('.js-dropdown').removeClass('open');
            }
        }
    });

    //jplayer
    LoadVideos();
});

function LoadVideos() {
    $(':not(.jplayer-loaded).jp-video').each(function (index, item) {
        var $item = $(item),
            mp4Url = $item.data().mp4,
            flvUrl = $item.data().flv,
            webmUrl = $item.data().webm;


        var jplayer = $item.find('.jp-jplayer');

        //this is a flag so it;s clear when a video has the jplayer in place
        $item.addClass('jplayer-loaded');

        $(jplayer).jPlayer({
            ready: function () {
                $(this).jPlayer('setMedia', {
                    webmv: webmUrl,
                    m4v: mp4Url,
                    flv: flvUrl
                });
            },
            play: function () { // To avoid multiple jPlayers playing together.
                $(this).jPlayer('pauseOthers');
            },
            cssSelectorAncestor: '#' + $item.attr('id'),
            size: {
                width: '100%', height: '270px'
            },
            swfPath: '/bower_components/jplayer/dist/jplayer',
            supplied: 'webmv, m4v, flv',
            useStateClassSkin: true,
            autoBlur: false,
            smoothPlayBar: true,
            keyEnabled: true,
            remainingDuration: true,
            toggleDuration: true
        });
    });
}

//Pass the currentPage was the only quick way to manage all the different situations we need to handle
function ParseItemsForFilter(itemType, currentPage) {
    var apiUrl = '/umbraco/Api/TipExchangeWebApi/GetItems',
        pageSize = parseInt(TipExchange.pageSize),
        sortType = TipExchange.filter,
        tag1 = TipExchange.tag1,
        tag2 = TipExchange.tag2,
        market = TipExchange.market;
    return $.ajax({
        type: 'GET',
        url: apiUrl,
        data: {
            page: currentPage,
            itemsPerPage: pageSize,
            itemType: itemType,
            sortType: sortType,
            market: market,
            tag1: tag1,
            tag2: tag2
        },
        success: function (data) {
            //Setting TotalPages value just to make sure, we got the latest value
            if (data.TotalPages > 0) {
                TipExchange[itemType + 'TotalPages'] = data.TotalPages;
            }

            //Add hidden class to our message for displaying no items
            if (!$('.no-results').hasClass('hidden')) {
                $('.no-results').addClass('hidden');
            };

            data.Items.forEach(function (item) {
                item.Created = moment(item.Created).format('DD MMMM YYYY');
                item.CustomClass = sortType === 'Unanswered' ? 'sk-tip-exchange-' + item.Type.toLowerCase() + 's' + '-item col-md-6' : 'sk-tip-exchange-' + item.Type.toLowerCase() + 's' + '-item';
                item.ImageUrl = checkForImage(item.MediaPath);
                item.ImageUrlWithoutProtocol = item.ImageUrl ? item.ImageUrl.replace('http://', '') : null;
                item.CurrentNodeId = TipExchange.currentNodeId;
                item.AddCommentDictionaryText = item.Type === 'Question' ? TipExchange.addAnswerText : TipExchange.addCommentText;
                item.CommentDictionaryText = item.Type === 'Question' ? TipExchange.answersText : TipExchange.commentsText;
                item.LikeDictionaryText = TipExchange.likeText;
                item.ShareDictionaryText = TipExchange.shareText;
                item.ReportDictionaryText = TipExchange.reportText;
                item.TagOn = TipExchange.tagOn;
                item.PromotedClass = item.Promoted ? 'sk-tip-exchange-title-star' : '';

                //We must have BOTH tags. As its printed out "tagA on tagB"
                //Otherwise we just display type (question or tip)
                item.HasTags = (item.Tag1 !== null) && (item.Tag2 !== null);
            });

            //Creates the json object to do the mustache binding
            var mustacheData = { items: data.Items };

            var htmlString = mustacheTemplate(mustacheData, '#itemTemplate');

            //Unanswered requires the items to be put across both columns
            //LOGIC for showing items
            if (sortType === 'Unanswered') {
                //Hide the two columns
                $('.question-column').html('').hide();
                $('.tip-column').html('').hide();

                //First page - set entire column to this
                if (data.CurrentPage === 1) {
                    //Remove any previous dom
                    $('.unanswered-items').remove();
                }

                var unansweredItems = $(htmlString).wrapAll('<div class="unanswered-items"></div>').parent();
                $('.sk-items-container').append(unansweredItems);
            } else {
                //Remove unanswered-items div is gone
                $('.unanswered-items').remove();

                //First page - set entire column to this
                if (data.CurrentPage === 1) {
                    $('.' + itemType + '-column').html(htmlString).show();
                } else {
                    $('.' + itemType + '-column').append(htmlString).show();
                }
            }

            if (data.CurrentPage <= data.TotalPages) {
                //set the latest value to the global variable
                //don't forget we are dealing with two separates call and one single button
                //that's why we set the value where and not at the beginning
                //see "CheckForLoadMoreButton();"
                TipExchange[itemType + 'CurrentPage'] = currentPage;
            }

            //totalPages = data.TotalPages;
            //Check DOM to see if we have no results
            CheckForNoResults();

            //rebind jplayer after every ajax
            LoadVideos();
        },
        error: function (request) {
            $('.' + itemType + '-column').html('').append(request.responseJSON.Message);
        }
    });
}

function CheckForNoResults() {
    if ($('.sk-items-container').find('.panel').length === 0) {
        $('.no-results').removeClass('hidden');
        $('.unanswered-items').html('').hide();
        $('.question-column').html('').hide();
        $('.tip-column').html('').hide();
    }
}

function CheckForLoadMoreButton() {
    var loadMoreBtn = $('.sk-tip-exchange-load-more'),
        questionCurrentPage = parseInt(TipExchange.questionCurrentPage),
        questionTotalPages = parseInt(TipExchange.questionTotalPages),
        tipCurrentPage = parseInt(TipExchange.tipCurrentPage),
        tipTotalPages = parseInt(TipExchange.tipTotalPages);

    if (questionCurrentPage === questionTotalPages && tipCurrentPage === tipTotalPages) {
        loadMoreBtn.hide();
    } else {
        loadMoreBtn.show();
    }
}

function mustacheTemplate(mustacheData, selector) {
    var htmlString;
    var $template = $(selector).html();

    htmlString = Mustache.render($template, mustacheData);

    return htmlString;
}

function getFileExtension(mediaPath) {
    if (mediaPath != null) {
        //Get substring of the full url from the last position of . in the URL
        var extension = mediaPath.substring(mediaPath.lastIndexOf('.'));

        //Lower case extension - iPhone seems to set .JPG or .MOV
        extension = extension.toLowerCase();

        return extension;
    }
}

function checkForImage(mediaPath) {
    var extension = getFileExtension(mediaPath);

    if (isImage(extension)) {
        return mediaPath;
    } else {
        return null;
    }
}

function isImage(extensionToCheck) {
    if (extensionToCheck !== null) {
        var imageExtensions = [".jpg", ".jpeg", ".png", ".bmp", ".gif"];
        var tryFindExtension = imageExtensions.indexOf(extensionToCheck);

        //If we can't find the extension in our list/array of allowed extensions
        if (tryFindExtension === -1) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function isVideo(extensionToCheck) {
    if (extensionToCheck !== null) {
        var videoExtensions = [".mp4", ".mov", ".avi", ".mpg", ".webm", ".mpeg"];
        var tryFindExtension = videoExtensions.indexOf(extensionToCheck);

        //If we can't find the extension in our list/array of allowed extensions
        if (tryFindExtension === -1) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function fileSelect(e) {
    if (!e) e = window.event;

    var sourceElem = e.target || e.srcElement;
    var targetElement = $(sourceElem).closest('form').find('.js-sk-attachment-name');
    if (!e || !targetElement) {
        return;
    }
    if (sourceElem.files != null) {
        var fileInput = sourceElem.files[0];
        if (!fileInput || !fileInput.name) {
            $(targetElement).text('');
            return;
        }
        $(targetElement).text(fileInput.name);
    }
}

function validateFileInput(form) {
    //Validation Message Div's - that have translated text in it
    var incorrectFileType = form.find('.incorrect-filetype');
    var videoTooLarge = form.find('.filesize-video');
    var imageTooLarge = form.find('.filesize-image');

    //Hide all validation messages
    //In case we are resubmitting again after fixing a validation
    incorrectFileType.hide();
    videoTooLarge.hide();
    imageTooLarge.hide();

    //Flags
    var passesValidation = false;
    var hasValidExtension = false;

    //Get the file input field
    var fileInput = form.find('input[type="file"]')[0];
    //Check length (to see if we have file/s selected)
    if (fileInput.files.length > 0) {
        //Get al files in the file input
        var files = fileInput.files;

        //Get first file from collection - should only ever be one
        var fileUploaded = files[0];

        //If we have a file - Get it's file extention
        var fileName = fileUploaded.name;
        var fileExtension = getFileExtension(fileName);

        //Check if it is a video extension
        if (isVideo(fileExtension)) {
            //It's a video - now check for file size
            hasValidExtension = true;

            //Set max video size upload to be 50MB
            var fileSizeMB = 50;
            var fileSizeKB = fileSizeMB * 1024;
            var fileSizeBytes = fileSizeKB * 1024;

            if (checkFileSize(fileUploaded.size, fileSizeBytes)) {
                //Has valid video extension & is smaller than 10MB
                passesValidation = true;
            } else {
                //Too BIG of a video - show validation message
                videoTooLarge.show();
            }
        } else if (isImage(fileExtension)) {
            //It's an image - now check for file size
            hasValidExtension = true;

            //Set max image size upload to be 5MB
            //iPhone photos are large!!
            var fileSizeMB = 5;
            var fileSizeKB = fileSizeMB * 1024;
            var fileSizeBytes = fileSizeKB * 1024;

            if (checkFileSize(fileUploaded.size, fileSizeBytes)) {
                //Has valid image extension & is smaller than 5MB
                passesValidation = true;
            } else {
                //Too BIG of an image - show validation message
                imageTooLarge.show();
            }
        }
    } else {
        //No files on form - so pass validation
        //As file is optional
        passesValidation = true;
        hasValidExtension = true;
    }

    if (!hasValidExtension) {
        //Display hidden div - with translated not valid extension
        incorrectFileType.show();
    }

    //Return our main flag
    return passesValidation;
}

function checkFileSize(fileSize, maxFileSizeBytes) {
    //Return if fileSize is less than the max file sie bytes
    return fileSize < maxFileSizeBytes;
}

function prepareDataForMustache(item) {
    //Add extra properties needed for mustache
    item.Created = moment(item.Created).format('DD MMMM YYYY');
    item.CurrentNodeId = TipExchange.currentNodeId;
    item.CustomClass = 'sk-tip-exchange-' + item.Type.toLowerCase() + 's' + '-item';
    item.ImageUrl = checkForImage(item.MediaPath);
    item.ImageUrlWithoutProtocol = item.ImageUrl ? item.ImageUrl.replace('http://', '') : null;
    item.ReportDictionaryText = TipExchange.reportText;
    item.AddCommentDictionaryText = item.Type === 'Question' ? TipExchange.addAnswerText : TipExchange.addCommentText;
    item.CommentDictionaryText = item.Type === 'Question' ? TipExchange.answersText : TipExchange.commentsText;
    item.LikeDictionaryText = TipExchange.likeText;
    item.ShareDictionaryText = TipExchange.shareText;
    item.TagOn = TipExchange.tagOn;
    item.PromotedClass = item.Promoted ? 'sk-tip-exchange-title-star' : '';

    //We must have BOTH tags. As its printed out "tagA on tagB"
    //Otherwise we just display type (question or tip)
    item.HasTags = (item.Tag1 !== null) && (item.Tag2 !== null);

    //Push this single item into an array of 'items'
    //So we can re-use the existing mustache template that expects an array of 'items'
    var items = [];
    items.push(item);

    return items;
}

function insertNewItemDOM(response) {

    var item = response.Data;
    var apiMessage = response.Message;

    if (TipExchange && TipExchange.preModerationEnabled) {
        switch (item.Type) {
            case 'Comment':
                $('.sk-tip-exchange-comment-form form').trigger('reset').slideUp('fast');
                $('.sk-tip-exchange-comment-form form').data('bootstrapValidator').resetForm();
                $('.sk-tip-exchange-comment-form .form-message').html('');
                $('.sk-tip-exchange-comment-form .form-message').html(TipExchange.preModAddComment).fadeIn(100).delay(5000).fadeOut(100, function () {
                    $('.sk-tip-exchange-comment-form').addClass('hidden');
                });
                $('html, body').animate({
                    scrollTop: $('.comments-' + item.ParentId).parents('.sk-tip-exchange-item').offset().top
                }, 1000);
                break;
            case 'Question':
                $('.sk-tip-exchange-question-form form').trigger('reset').slideUp('fast');
                $('.sk-tip-exchange-question-form form').data('bootstrapValidator').resetForm();
                $('.sk-tip-exchange-question-form .form-message').html(TipExchange.preModAddQuestion).fadeIn(100).delay(5000).fadeOut(100, function () {
                    $('.sk-tip-exchange-question-form').addClass('hidden');
                });
                break;
            case 'Tip':
                $('.sk-tip-exchange-tip-form form').trigger('reset').slideUp('fast');
                $('.sk-tip-exchange-tip-form form').data('bootstrapValidator').resetForm();
                $('.sk-tip-exchange-tip-form .form-message').html(TipExchange.preModAddTip).fadeIn(100).delay(5000).fadeOut(100, function () {
                    $('.sk-tip-exchange-tip-form').addClass('hidden');
                });
                break;
        }
        return;
    }

    var htmlString;
    var items = prepareDataForMustache(item);

    //Check type of item we inserted/created
    switch (item.Type) {
        case 'Comment':

            //Reset form
            $('.sk-tip-exchange-comment-form form').trigger('reset');

            //Form Message of Thanks - We don't show as we hide form
            //But need to empty this out for next time form is used
            $('.sk-tip-exchange-comment-form .form-message').html('');

            //Hide Form
            $('.sk-tip-exchange-comment-form').addClass('hidden');

            //Update Comment Count
            var commentCountDom = $('.comment-count-' + item.ParentId);
            var commentCount = parseInt(commentCountDom.attr('data-comments'));

            //Update the values for comment count
            commentCountDom.text(commentCount + 1);
            commentCountDom.attr('data-comments', commentCount + 1);

            //Insert Comment into the DOM - if items/list visible
            if ($('.comments-' + item.ParentId + ':visible').length) {
                var mustacheData = { 'comments': items };
                htmlString = mustacheTemplate(mustacheData, '#commentTemplate');

                //Insert the HTML back from Mustache into the DOM
                //Find the correct place to insert this
                var col = $('.comments-' + item.ParentId);
                col.append(htmlString);

                $('html, body').animate({
                    scrollTop: col.find('.sk-tip-exchange-comment-item:last-child').offset().top
                }, 1000);
            } else {
                //move to the top of the current item
                $('html, body').animate({
                    scrollTop: $('.comments-' + item.ParentId).parents('.sk-tip-exchange-item').offset().top
                }, 1000);
            }

            break;

        case 'Question':

            //Edge case, if someone add a item without tag it will show the type as a title
            //if tag1 or tag2 exists..
            //remove the type so it will show the tags as a title
            if (item.Tag1 || item.Tag2) {
                item.Type = null;
            }

            var mustacheData = { 'items': items };
            htmlString = mustacheTemplate(mustacheData, '#itemTemplate');

            //Insert the HTML back from Mustache into the DOM
            var col = $('.question-column');
            col.prepend(htmlString);

            //Reset form & close/hide form
            $('.sk-tip-exchange-question-form form').trigger('reset').slideUp('fast');
            //$('.sk-tip-exchange-question-form form').slideUp('fast');

            var qForm = $('.sk-tip-exchange-question-form form').data('bootstrapValidator');
            qForm.resetForm();

            //Insert message from API - show for 5 seconds then hide message - followed by hiding the container
            $('.sk-tip-exchange-question-form .form-message').html(apiMessage).fadeIn(100).delay(2500).fadeOut(100, function () {
                //Final fade out animation complete of the text
                //Hide the forms once the form submission is done
                $('.sk-tip-exchange-question-form').addClass('hidden');

                //go to the new element
                $('html, body').animate({
                    scrollTop: col.find('.sk-tip-exchange-item:first-child').offset().top
                }, 1000);
            });

            break;

        case 'Tip':

            //Edge case, if someone add a item without tag it will show the type as a title
            //if tag1 or tag2 exists..
            //remove the type so it will show the tags as a title
            if (item.Tag1 || item.Tag2) {
                item.Type = null;
            }

            var mustacheData = { 'items': items };
            htmlString = mustacheTemplate(mustacheData, '#itemTemplate');

            //Insert the HTML back from Mustache into the DOM
            var col = $('.tip-column');
            col.prepend(htmlString);

            //Reset form & close/hide form
            $('.sk-tip-exchange-tip-form form').trigger('reset').slideUp('fast');

            var tForm = $('.sk-tip-exchange-tip-form form').data('bootstrapValidator');
            tForm.resetForm();

            //Insert message from API - show for 5 seconds then hide message - followed by hiding the container
            $('.sk-tip-exchange-tip-form .form-message').html(apiMessage).fadeIn(100).delay(2500).fadeOut(100, function () {
                //Final fade out animation complete of the text
                //Hide the forms once the form submission is done
                $('.sk-tip-exchange-tip-form').addClass('hidden');

                //go to the new element
                $('html, body').animate({
                    scrollTop: col.find('.sk-tip-exchange-item:first-child').offset().top
                }, 1000);
            });

            break;
    }
}

function submitForm(form) {
    var $form = form,
               domForm = form[0],
               postUrl = $form.attr('action'),
               parent = $form.parent(),
               formData = new FormData(domForm);

    //Disable submit button
    var subButton = $form.find('input[type="submit"]');
    subButton.attr('disabled', 'disabled');

    //Posting via AJAX to our WebAPI if valid

    $.ajax({
        type: 'POST',
        url: postUrl,
        data: formData,
        processData: false,
        contentType: false,
        error: function (request, status, error) {
            //Re-enable submit button
            subButton.removeAttr('disabled');

            //Reset form & close/hide form
            $form.trigger("reset").slideUp('fast');

            //hide the loader
            $('.sk-tip-exchange-shadow-box').toggleClass('hidden');
            $('.sk-tip-exchange-shadow-box-image').toggleClass('hidden');

            // remove 'prevent scrolling'
            $('html, body').toggleClass('scroll-prevent');

            //In the parent item of the form - find form-message
            //Update message from API - show for 5 seconds and hide it & container
            var message = (request.responseJSON.Message) ? request.responseJSON.Message : request.statusText;

            parent.find('.form-message').html(message).fadeIn(100).delay(5000).fadeOut(100, function () {
                //Final fade out animation complete of the text
                parent.addClass('hidden');
            });
        },
        success: function (response) {
            //Print out what we get back from our API

            //reset filters
            ResetFilters();
            //Update UI with new item in the DOM
            insertNewItemDOM(response);

            //if id a video then hide the player so the video transcoding service finish the transcoding
            if (response.Data.Mp4Url) {
                var $player = $(':not(.jplayer-loaded).jp-video');
                $('<p class="sk-tip-exchange-video-message">' + TipExchange.videoMessage + '</p>').insertBefore($player.parent('.sk-tip-exchange-item-body').find('.sk-tip-exchange-item-comment'));
                $player.hide();
            }

            LoadVideos();

            //hide the loader
            $('.sk-tip-exchange-shadow-box').toggleClass('hidden');
            $('.sk-tip-exchange-shadow-box-image').toggleClass('hidden');

            // remove 'prevent scrolling'
            $('html, body').toggleClass('scroll-prevent');

            //Re-enable button
            subButton.removeAttr('disabled');
        }
    });
}

function ResetFilters() {
    $('.filters-row select').find('option:first').attr('selected', 'selected');
    $('.filters-row .filter-type').change();
}

function LikedItemStatus() {
    var items = getCookie('TipExchangeLikesKey');

    if (items !== '') {
        items = items.split('&');

        $.each(items, function (index, itemId) {
            itemId = itemId.split('=')[1];

            $('a[data-like-id=' + itemId + ']').addClass('liked');
        });
    }
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
};
var RBCookie = RBCookie || {
    key: "RB-Cookie"
}

RBCookie.Alert = RBCookie.Alert || {
    bind : function(){
        $('#rb-cookie-accept').click(function () {
            var cookieName = RBCookie.key;
            var expires = new Date();
            expires.setDate(expires.getDate() + 100 * 365);
            document.cookie = cookieName + "=1; path=/; expires=" + expires.toUTCString();

            $('#rb-cookie-container').slideUp(function () {
                $(this).remove();
            });
            return false;
        });
    }
}

$(document).ready(function () {
    RBCookie.Alert.bind();
});
$(document).ready(function () {
    var primaryNav = $("#sk-primary-nav");

    if (primaryNav.length) {
        var currentPagePath = window.location.pathname;
        var currentPageAnchor = $("a[href='" + currentPagePath + "'], a[data-href='" + currentPagePath + "']", primaryNav);

        if (currentPageAnchor.length) {
            var parents = currentPageAnchor.parents("li");

            parents.addClass("active");
        }
    }
});
/* JQUERY IDANGEROUS SWIPER */ !function () { "use strict"; function e(e) { e.fn.swiper = function (a) { var t; return e(this).each(function () { var e = new Swiper(this, a); t || (t = e) }), t } } window.Swiper = function (e, a) { function t() { return "horizontal" === u.params.direction } function s(e) { var a, t, s = function () { "undefined" != typeof u && null !== u && (void 0 !== u.imagesLoaded && u.imagesLoaded++, u.imagesLoaded === u.imagesToLoad.length && (u.update(), u.params.onImagesReady && u.params.onImagesReady(u))) }; e.complete ? s() : (t = e.currentSrc || e.getAttribute("src"), t ? (a = new Image, a.onload = s, a.onerror = s, a.src = t) : s()) } function r() { u.autoplayTimeoutId = setTimeout(function () { u.params.loop ? (u.fixLoop(), u._slideNext()) : u.isEnd ? a.autoplayStopOnLast ? u.stopAutoplay() : u._slideTo(0) : u._slideNext() }, u.params.autoplay) } function i(e, a) { var t = m(e.target); if (!t.is(a)) if ("string" == typeof a) t = t.parents(a); else if (a.nodeType) { var s; return t.parents().each(function (e, t) { t === a && (s = a) }), s ? a : void 0 } return 0 === t.length ? void 0 : t[0] } function n(e, a) { a = a || {}; var t = window.MutationObserver || window.WebkitMutationObserver, s = new t(function (e) { e.forEach(function () { u.onResize() }) }); s.observe(e, { attributes: "undefined" == typeof a.attributes ? !0 : a.attributes, childList: "undefined" == typeof a.childList ? !0 : a.childList, characterData: "undefined" == typeof a.characterData ? !0 : a.characterData }), u.observers.push(s) } function o(e) { var a = e.keyCode || e.charCode; if (!(e.shiftKey || e.altKey || e.ctrlKey || e.metaKey)) { if (document.activeElement && document.activeElement.nodeName && ("input" === document.activeElement.nodeName.toLowerCase() || "textarea" === document.activeElement.nodeName.toLowerCase())) return !1; if (37 === a || 39 === a || 38 === a || 40 === a) { var s = !1; if (u.container.parents(".swiper-slide").length > 0 && 0 === u.container.parents(".swiper-slide-active").length) return; for (var r = { left: window.pageXOffset, top: window.pageYOffset }, i = window.innerWidth, n = window.innerHeight, o = u.container.offset(), l = [[o.left, o.top], [o.left + u.width, o.top], [o.left, o.top + u.height], [o.left + u.width, o.top + u.height]], p = 0; p < l.length; p++) { var d = l[p]; d[0] >= r.left && d[0] <= r.left + i && d[1] >= r.top && d[1] <= r.top + n && (s = !0) } if (!s) return } t() ? ((37 === a || 39 === a) && (e.preventDefault ? e.preventDefault() : e.returnValue = !1), 39 === a && u.slideNext(), 37 === a && u.slidePrev()) : ((38 === a || 40 === a) && (e.preventDefault ? e.preventDefault() : e.returnValue = !1), 40 === a && u.slideNext(), 38 === a && u.slidePrev()) } } function l(e) { var a = u._wheelEvent, s = 0; if (e.detail) s = -e.detail; else if ("mousewheel" === a) if (u.params.mousewheelForceToAxis) if (t()) { if (!(Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY))) return; s = e.wheelDeltaX } else { if (!(Math.abs(e.wheelDeltaY) > Math.abs(e.wheelDeltaX))) return; s = e.wheelDeltaY } else s = e.wheelDelta; else if ("DOMMouseScroll" === a) s = -e.detail; else if ("wheel" === a) if (u.params.mousewheelForceToAxis) if (t()) { if (!(Math.abs(e.deltaX) > Math.abs(e.deltaY))) return; s = -e.deltaX } else { if (!(Math.abs(e.deltaY) > Math.abs(e.deltaX))) return; s = -e.deltaY } else s = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? -e.deltaX : -e.deltaY; if (u.params.freeMode) { var r = u.getWrapperTranslate() + s; if (r > 0 && (r = 0), r < u.maxTranslate() && (r = u.maxTranslate()), u.setWrapperTransition(0), u.setWrapperTranslate(r), u.updateProgress(), u.updateActiveIndex(), 0 === r || r === u.maxTranslate()) return } else (new Date).getTime() - u._lastWheelScrollTime > 60 && (0 > s ? u.slideNext() : u.slidePrev()), u._lastWheelScrollTime = (new Date).getTime(); return u.params.autoplay && u.stopAutoplay(), e.preventDefault ? e.preventDefault() : e.returnValue = !1, !1 } var p = { direction: "horizontal", touchEventsTarget: "container", initialSlide: 0, speed: 300, autoplay: !1, autoplayDisableOnInteraction: !0, freeMode: !1, freeModeMomentum: !0, freeModeMomentumRatio: 1, freeModeMomentumBounce: !0, freeModeMomentumBounceRatio: 1, effect: "slide", coverflow: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows: !0 }, cube: { slideShadows: !0, shadow: !0, shadowOffset: 20, shadowScale: .94 }, scrollbar: null, scrollbarHide: !0, keyboardControl: !1, mousewheelControl: !1, mousewheelForceToAxis: !1, hashnav: !1, spaceBetween: 0, slidesPerView: 1, slidesPerColumn: 1, slidesPerColumnFill: "column", slidesPerGroup: 1, centeredSlides: !1, touchRatio: 1, touchAngle: 45, simulateTouch: !0, shortSwipes: !0, longSwipes: !0, longSwipesRatio: .5, longSwipesMs: 300, followFinger: !0, onlyExternal: !1, threshold: 0, touchMoveStopPropagation: !0, pagination: null, paginationClickable: !1, paginationHide: !1, resistance: !0, resistanceRatio: .85, nextButton: null, prevButton: null, watchSlidesProgress: !1, watchVisibility: !1, grabCursor: !1, preventClicks: !0, preventClicksPropagation: !0, releaseFormElements: !0, slideToClickedSlide: !1, updateOnImagesReady: !0, loop: !1, loopAdditionalSlides: 0, loopedSlides: null, control: void 0, controlInverse: !1, allowSwipeToPrev: !0, allowSwipeToNext: !0, swipeHandler: null, noSwiping: !0, noSwipingClass: "swiper-no-swiping", slideClass: "swiper-slide", slideActiveClass: "swiper-slide-active", slideVisibleClass: "swiper-slide-visible", slideDuplicateClass: "swiper-slide-duplicate", slideNextClass: "swiper-slide-next", slidePrevClass: "swiper-slide-prev", wrapperClass: "swiper-wrapper", bulletClass: "swiper-pagination-bullet", bulletActiveClass: "swiper-pagination-bullet-active", buttonDisabledClass: "swiper-button-disabled", paginationHiddenClass: "swiper-pagination-hidden", observer: !1, observeParents: !1 }; a = a || {}; for (var d in p) if ("undefined" == typeof a[d]) a[d] = p[d]; else if ("object" == typeof a[d]) for (var c in p[d]) "undefined" == typeof a[d][c] && (a[d][c] = p[d][c]); var u = this; u.params = a; var m; if (m = "undefined" == typeof Dom7 ? window.Dom7 || window.Zepto || window.jQuery : Dom7, m && (u.container = m(e), 0 !== u.container.length)) { if (u.container.length > 1) return void u.container.each(function () { new Swiper(this, a) }); u.container[0].swiper = u, u.container.data("swiper", u), u.container.addClass("swiper-container-" + u.params.direction), u.params.freeMode && u.container.addClass("swiper-container-free-mode"), ["cube", "coverflow"].indexOf(u.params.effect) >= 0 && (u.support.transforms3d ? (u.params.watchSlidesProgress = !0, u.container.addClass("swiper-container-3d")) : u.params.effect = "slide"), "slide" !== u.params.effect && u.container.addClass("swiper-container-" + u.params.effect), "cube" === u.params.effect && (u.params.resistanceRatio = 0, u.params.slidesPerView = 1, u.params.slidesPerColumn = 1, u.params.slidesPerGroup = 1, u.params.centeredSlides = !1, u.params.spaceBetween = 0), "fade" === u.params.effect && (u.params.watchSlidesProgress = !0, u.params.spaceBetween = 0), u.params.grabCursor && u.support.touch && (u.params.grabCursor = !1), u.wrapper = u.container.children("." + u.params.wrapperClass), u.params.pagination && (u.paginationContainer = m(u.params.pagination), u.params.paginationClickable && u.paginationContainer.addClass("swiper-pagination-clickable")), u.rtl = t() && ("rtl" === u.container[0].dir.toLowerCase() || "rtl" === u.container.css("direction")), u.rtl && u.container.addClass("swiper-container-rtl"), u.rtl && (u.wrongRTL = "-webkit-box" === u.wrapper.css("display")), u.translate = 0, u.progress = 0, u.velocity = 0, u.lockSwipeToNext = function () { u.params.allowSwipeToNext = !1 }, u.lockSwipeToPrev = function () { u.params.allowSwipeToPrev = !1 }, u.lockSwipes = function () { u.params.allowSwipeToNext = u.params.allowSwipeToPrev = !1 }, u.unlockSwipeToNext = function () { u.params.allowSwipeToNext = !0 }, u.unlockSwipeToPrev = function () { u.params.allowSwipeToPrev = !0 }, u.unlockSwipes = function () { u.params.allowSwipeToNext = u.params.allowSwipeToPrev = !0 }, u.params.slidesPerColumn > 1 && u.container.addClass("swiper-container-multirow"), u.params.grabCursor && (u.container[0].style.cursor = "move", u.container[0].style.cursor = "-webkit-grab", u.container[0].style.cursor = "-moz-grab", u.container[0].style.cursor = "grab"), u.imagesToLoad = [], u.imagesLoaded = 0, u.preloadImages = function () { u.imagesToLoad = u.container.find("img"); for (var e = 0; e < u.imagesToLoad.length; e++) s(u.imagesToLoad[e]) }, u.autoplayTimeoutId = void 0, u.autoplaying = !1, u.autoplayPaused = !1, u.startAutoplay = function () { return "undefined" != typeof u.autoplayTimeoutId ? !1 : void (u.params.autoplay && (u.autoplaying || (u.autoplaying = !0, u.params.onAutoplayStart && u.params.onAutoplayStart(u), r()))) }, u.stopAutoplay = function () { u.autoplayTimeoutId && (u.autoplayTimeoutId && clearTimeout(u.autoplayTimeoutId), u.autoplaying = !1, u.autoplayTimeoutId = void 0, u.params.onAutoplayStop && u.params.onAutoplayStop(u)) }, u.pauseAutoplay = function (e) { u.autoplayPaused || (u.autoplayTimeoutId && clearTimeout(u.autoplayTimeoutId), u.autoplayPaused = !0, 0 === e ? (u.autoplayPaused = !1, r()) : u.wrapper.transitionEnd(function () { u.autoplayPaused = !1, r() })) }, u.updateContainerSize = function () { u.width = u.container[0].clientWidth, u.height = u.container[0].clientHeight, u.size = t() ? u.width : u.height }, u.updateSlidesSize = function () { u.slides = u.wrapper.children("." + u.params.slideClass), u.snapGrid = [], u.slidesGrid = [], u.slidesSizesGrid = []; var e, a = u.params.spaceBetween, s = 0, r = 0, i = 0; "string" == typeof a && a.indexOf("%") >= 0 && (a = parseFloat(a.replace("%", "")) / 100 * u.size), u.virtualWidth = -a, u.slides.css(u.rtl ? { marginLeft: "", marginTop: "" } : { marginRight: "", marginBottom: "" }); var n; u.params.slidesPerColumn > 1 && (n = Math.floor(u.slides.length / u.params.slidesPerColumn) === u.slides.length / u.params.slidesPerColumn ? u.slides.length : Math.ceil(u.slides.length / u.params.slidesPerColumn) * u.params.slidesPerColumn); var o; for (e = 0; e < u.slides.length; e++) { o = 0; var l = u.slides.eq(e); if (u.params.slidesPerColumn > 1) { var p, d, c, m, f = u.params.slidesPerColumn; "column" === u.params.slidesPerColumnFill ? (d = Math.floor(e / f), c = e - d * f, p = d + c * n / f, l.css({ "-webkit-box-ordinal-group": p, "-moz-box-ordinal-group": p, "-ms-flex-order": p, "-webkit-order": p, order: p })) : (m = n / f, c = Math.floor(e / m), d = e - c * m), l.css({ "margin-top": 0 !== c && u.params.spaceBetween && u.params.spaceBetween + "px" }).attr("data-swiper-column", d).attr("data-swiper-row", c) } "none" !== l.css("display") && ("auto" === u.params.slidesPerView ? o = t() ? l.outerWidth(!0) : l.outerHeight(!0) : (o = (u.size - (u.params.slidesPerView - 1) * a) / u.params.slidesPerView, t() ? u.slides[e].style.width = o + "px" : u.slides[e].style.height = o + "px"), u.slides[e].swiperSlideSize = o, u.slidesSizesGrid.push(o), u.params.centeredSlides ? (s = s + o / 2 + r / 2 + a, 0 === e && (s = s - u.size / 2 - a), Math.abs(s) < .001 && (s = 0), i % u.params.slidesPerGroup === 0 && u.snapGrid.push(s), u.slidesGrid.push(s)) : (i % u.params.slidesPerGroup === 0 && u.snapGrid.push(s), u.slidesGrid.push(s), s = s + o + a), u.virtualWidth += o + a, r = o, i++) } u.virtualWidth = Math.max(u.virtualWidth, u.size); var h; if (u.rtl && u.wrongRTL && ("slide" === u.params.effect || "coverflow" === u.params.effect) && u.wrapper.css({ width: u.virtualWidth + u.params.spaceBetween + "px" }), u.params.slidesPerColumn > 1 && (u.virtualWidth = (o + u.params.spaceBetween) * n, u.virtualWidth = Math.ceil(u.virtualWidth / u.params.slidesPerColumn) - u.params.spaceBetween, u.wrapper.css({ width: u.virtualWidth + u.params.spaceBetween + "px" }), u.params.centeredSlides)) { for (h = [], e = 0; e < u.snapGrid.length; e++) u.snapGrid[e] < u.virtualWidth + u.snapGrid[0] && h.push(u.snapGrid[e]); u.snapGrid = h } if (!u.params.centeredSlides) { for (h = [], e = 0; e < u.snapGrid.length; e++) u.snapGrid[e] <= u.virtualWidth - u.size && h.push(u.snapGrid[e]); u.snapGrid = h, Math.floor(u.virtualWidth - u.size) > Math.floor(u.snapGrid[u.snapGrid.length - 1]) && u.snapGrid.push(u.virtualWidth - u.size) } 0 === u.snapGrid.length && (u.snapGrid = [0]), 0 !== u.params.spaceBetween && u.slides.css(t() ? u.rtl ? { marginLeft: a + "px" } : { marginRight: a + "px" } : { marginBottom: a + "px" }), u.params.watchSlidesProgress && u.updateSlidesOffset() }, u.updateSlidesOffset = function () { for (var e = 0; e < u.slides.length; e++) u.slides[e].swiperSlideOffset = t() ? u.slides[e].offsetLeft : u.slides[e].offsetTop }, u.update = function () { u.updateContainerSize(), u.updateSlidesSize(), u.updateProgress(), u.updatePagination(), u.updateClasses() }, u.minTranslate = function () { return -u.snapGrid[0] }, u.maxTranslate = function () { return -u.snapGrid[u.snapGrid.length - 1] }, u.updateSlidesProgress = function (e) { if ("undefined" == typeof e && (e = u.translate || 0), 0 !== u.slides.length) { "undefined" == typeof u.slides[0].swiperSlideOffset && u.updateSlidesOffset(); var a = u.params.centeredSlides ? -e + u.size / 2 : -e; u.rtl && (a = u.params.centeredSlides ? e - u.size / 2 : e); { u.container[0].getBoundingClientRect(), t() ? "left" : "top", t() ? "right" : "bottom" } u.slides.removeClass(u.params.slideVisibleClass); for (var s = 0; s < u.slides.length; s++) { var r = u.slides[s], i = u.params.centeredSlides === !0 ? r.swiperSlideSize / 2 : 0, n = (a - r.swiperSlideOffset - i) / (r.swiperSlideSize + u.params.spaceBetween); if (u.params.watchVisibility) { var o = -(a - r.swiperSlideOffset - i), l = o + u.slidesSizesGrid[s], p = o >= 0 && o < u.size || l > 0 && l <= u.size || 0 >= o && l >= u.size; p && u.slides.eq(s).addClass(u.params.slideVisibleClass) } r.progress = u.rtl ? -n : n } } }, u.updateProgress = function (e) { "undefined" == typeof e && (e = u.translate || 0), u.progress = (e - u.minTranslate()) / (u.maxTranslate() - u.minTranslate()), u.isBeginning = u.isEnd = !1, u.progress <= 0 && (u.isBeginning = !0, u.params.onReachBeginning && u.params.onReachBeginning(u)), u.progress >= 1 && (u.isEnd = !0, u.params.onReachEnd && u.params.onReachEnd(u)), u.params.watchSlidesProgress && u.updateSlidesProgress(e), u.params.onProgress && u.params.onProgress(u, u.progress) }, u.updateActiveIndex = function () { var e, a, t, s = u.rtl ? u.translate : -u.translate; for (a = 0; a < u.slidesGrid.length; a++) "undefined" != typeof u.slidesGrid[a + 1] ? s >= u.slidesGrid[a] && s < u.slidesGrid[a + 1] - (u.slidesGrid[a + 1] - u.slidesGrid[a]) / 2 ? e = a : s >= u.slidesGrid[a] && s < u.slidesGrid[a + 1] && (e = a + 1) : s >= u.slidesGrid[a] && (e = a); (0 > e || "undefined" == typeof e) && (e = 0), t = Math.floor(e / u.params.slidesPerGroup), t >= u.snapGrid.length && (t = u.snapGrid.length - 1), e !== u.activeIndex && (u.snapIndex = t, u.previousIndex = u.activeIndex, u.activeIndex = e, u.updateClasses()) }, u.updateClasses = function () { u.slides.removeClass(u.params.slideActiveClass + " " + u.params.slideNextClass + " " + u.params.slidePrevClass); var e = u.slides.eq(u.activeIndex); if (e.addClass(u.params.slideActiveClass), e.next("." + u.params.slideClass).addClass(u.params.slideNextClass), e.prev("." + u.params.slideClass).addClass(u.params.slidePrevClass), u.bullets && u.bullets.length > 0) { u.bullets.removeClass(u.params.bulletActiveClass); var a; u.params.loop ? (a = u.activeIndex - u.loopedSlides, a > u.slides.length - 1 - 2 * u.loopedSlides && (a -= u.slides.length - 2 * u.loopedSlides)) : a = "undefined" != typeof u.snapIndex ? u.snapIndex : u.activeIndex || 0, u.bullets.eq(a).addClass(u.params.bulletActiveClass) } u.params.loop || (u.params.prevButton && (u.isBeginning ? m(u.params.prevButton).addClass(u.params.buttonDisabledClass) : m(u.params.prevButton).removeClass(u.params.buttonDisabledClass)), u.params.nextButton && (u.isEnd ? m(u.params.nextButton).addClass(u.params.buttonDisabledClass) : m(u.params.nextButton).removeClass(u.params.buttonDisabledClass))) }, u.updatePagination = function () { if (u.params.pagination && u.paginationContainer && u.paginationContainer.length > 0) { for (var e = "", a = u.params.loop ? u.slides.length - 2 * u.loopedSlides : u.snapGrid.length, t = 0; a > t; t++) e += '<span class="' + u.params.bulletClass + '"></span>'; u.paginationContainer.html(e), u.bullets = u.paginationContainer.find("." + u.params.bulletClass) } }, u.onResize = function () { u.updateContainerSize(), u.updateSlidesSize(), u.updateProgress(), u.updateClasses(), "auto" === u.params.slidesPerView && u.updatePagination(), u.isEnd ? u.slideTo(u.slides.length - 1, 0, !1, !0) : u.slideTo(u.activeIndex, 0, !1, !0), u.params.scrollbar && u.scrollbar && u.scrollbar.init() }; var f = ["mousedown", "mousemove", "mouseup"]; window.navigator.pointerEnabled ? f = ["pointerdown", "pointermove", "pointerup"] : window.navigator.msPointerEnabled && (f = ["MSPointerDown", "MSPointerMove", "MSPointerUp"]), u.touchEvents = { start: u.support.touch || !u.params.simulateTouch ? "touchstart" : f[0], move: u.support.touch || !u.params.simulateTouch ? "touchmove" : f[1], end: u.support.touch || !u.params.simulateTouch ? "touchend" : f[2] }, (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) && ("container" === u.params.touchEventsTarget ? u.container : u.wrapper).addClass("swiper-wp8-" + u.params.direction), u.events = function (e) { var a = e ? "off" : "on", t = e ? "removeEventListener" : "addEventListener", s = "container" === u.params.touchEventsTarget ? u.container : u.wrapper, r = u.support.touch ? s : m(document), i = u.params.nested ? !0 : !1; s[0][t](u.touchEvents.start, u.onTouchStart, !1), r[0][t](u.touchEvents.move, u.onTouchMove, i), r[0][t](u.touchEvents.end, u.onTouchEnd, !1), window[t]("resize", u.onResize), u.params.nextButton && m(u.params.nextButton)[a]("click", u.onClickNext), u.params.prevButton && m(u.params.prevButton)[a]("click", u.onClickPrev), u.params.pagination && u.params.paginationClickable && m(u.paginationContainer)[a]("click", "." + u.params.bulletClass, u.onClickIndex), (u.params.preventClicks || u.params.preventClicksPropagation) && s[0][t]("click", u.preventClicks, !0) }, u.attachEvents = function () { u.events() }, u.detachEvents = function () { u.events(!0) }, u.allowClick = !0, u.preventClicks = function (e) { u.allowClick || (u.params.preventClicks && e.preventDefault(), u.params.preventClicksPropagation && (e.stopPropagation(), e.stopImmediatePropagation())) }, u.onClickNext = function (e) { e.preventDefault(), u.slideNext() }, u.onClickPrev = function (e) { e.preventDefault(), u.slidePrev() }, u.onClickIndex = function (e) { e.preventDefault(); var a = m(this).index() * u.params.slidesPerGroup; u.params.loop && (a += u.loopedSlides), u.slideTo(a) }, u.updateClickedSlide = function (e) { var a = i(e, "." + u.params.slideClass); if (!a) return u.clickedSlide = void 0, void (u.clickedIndex = void 0); if (u.clickedSlide = a, u.clickedIndex = m(a).index(), u.params.slideToClickedSlide && void 0 !== u.clickedIndex && u.clickedIndex !== u.activeIndex) { var t, s = u.clickedIndex; if (u.params.loop) if (t = m(u.clickedSlide).attr("data-swiper-slide-index"), s > u.slides.length - u.params.slidesPerView) u.fixLoop(), s = u.wrapper.children("." + u.params.slideClass + '[data-swiper-slide-index="' + t + '"]').eq(0).index(), setTimeout(function () { u.slideTo(s) }, 0); else if (s < u.params.slidesPerView - 1) { u.fixLoop(); var r = u.wrapper.children("." + u.params.slideClass + '[data-swiper-slide-index="' + t + '"]'); s = r.eq(r.length - 1).index(), setTimeout(function () { u.slideTo(s) }, 0) } else u.slideTo(s); else u.slideTo(s) } }; var h, w, v, g, T, b, x, S = {}, y = {}; u.animating = !1; var C, M, P = Date.now(), k = [], z = "input, select, textarea, button"; if (u.onTouchStart = function (e) { if (e.originalEvent && (e = e.originalEvent), !("mousedown" === e.type && "which" in e && 3 === e.which || u.params.noSwiping && i(e, "." + u.params.noSwipingClass) || u.params.swipeHandler && !i(e, u.params.swipeHandler))) { if (h = !0, w = !1, g = void 0, S.x = y.x = "touchstart" === e.type ? e.targetTouches[0].pageX : e.pageX, S.y = y.y = "touchstart" === e.type ? e.targetTouches[0].pageY : e.pageY, v = Date.now(), u.allowClick = !0, u.updateContainerSize(), u.swipeDirection = void 0, u.params.threshold > 0 && (x = !1), "touchstart" !== e.type) { var a = !0; m(e.target).is(z) && (a = !1), document.activeElement && m(document.activeElement).is(z) && document.activeElement.blur(), a && e.preventDefault() } u.params.onTouchStart && u.params.onTouchStart(u, e) } }, u.onTouchMove = function (e) { if (e.originalEvent && (e = e.originalEvent), !e.preventedByNestedSwiper) { if (u.params.onlyExternal) return w = !0, void (u.allowClick = !1); if (u.params.onTouchMove && u.params.onTouchMove(u, e), u.allowClick = !1, h && !(e.targetTouches && e.targetTouches.length > 1)) { y.x = "touchmove" === e.type ? e.targetTouches[0].pageX : e.pageX, y.y = "touchmove" === e.type ? e.targetTouches[0].pageY : e.pageY; var s = 180 * Math.atan2(Math.abs(y.y - S.y), Math.abs(y.x - S.x)) / Math.PI; if ("undefined" == typeof g && (g = t() ? s > u.params.touchAngle : 90 - s > u.params.touchAngle), g) return void (h = !1); u.params.onSliderMove && u.params.onSliderMove(u, e), e.preventDefault(), u.params.touchMoveStopPropagation && !u.params.nested && e.stopPropagation(), w || (a.loop && u.fixLoop(), b = "cube" === u.params.effect ? (u.rtl ? -u.translate : u.translate) || 0 : u.getWrapperTranslate(), u.setWrapperTransition(0), u.animating && u.wrapper.trigger("webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd msTransitionEnd"), u.params.autoplay && u.autoplaying && (u.params.autoplayDisableOnInteraction ? u.stopAutoplay() : u.pauseAutoplay()), M = !1, u.params.grabCursor && (u.container[0].style.cursor = "move", u.container[0].style.cursor = "-webkit-grabbing", u.container[0].style.cursor = "-moz-grabbin", u.container[0].style.cursor = "grabbing")), w = !0; var r = t() ? y.x - S.x : y.y - S.y; r *= u.params.touchRatio, u.rtl && (r = -r), u.swipeDirection = r > 0 ? "prev" : "next", T = r + b; var i = !0; if (r > 0 && T > u.minTranslate() ? (i = !1, u.params.resistance && (T = u.minTranslate() - 1 + Math.pow(-u.minTranslate() + b + r, u.params.resistanceRatio))) : 0 > r && T < u.maxTranslate() && (i = !1, u.params.resistance && (T = u.maxTranslate() + 1 - Math.pow(u.maxTranslate() - b - r, u.params.resistanceRatio))), i && (e.preventedByNestedSwiper = !0), !u.params.allowSwipeToNext && "next" === u.swipeDirection && b > T && (T = b), !u.params.allowSwipeToPrev && "prev" === u.swipeDirection && T > b && (T = b), u.params.followFinger) { if (u.params.threshold > 0) { if (!(Math.abs(r) > u.params.threshold || x)) return void (T = b); if (!x) return x = !0, S.x = y.x, S.y = y.y, void (T = b) } (u.params.freeMode || u.params.watchSlidesProgress) && u.updateActiveIndex(), u.params.freeMode && (0 === k.length && k.push({ position: S[t() ? "x" : "y"], time: v }), k.push({ position: y[t() ? "x" : "y"], time: (new Date).getTime() })), u.updateProgress(T), u.setWrapperTranslate(T) } } } }, u.onTouchEnd = function (e) { if (e.originalEvent && (e = e.originalEvent), h) { u.params.onTouchEnd && u.params.onTouchEnd(u, e), u.params.grabCursor && w && h && (u.container[0].style.cursor = "move", u.container[0].style.cursor = "-webkit-grab", u.container[0].style.cursor = "-moz-grab", u.container[0].style.cursor = "grab"); var a = Date.now(), s = a - v; u.allowClick && (u.updateClickedSlide(e), u.params.onTap && u.params.onTap(u, e), 300 > s && a - P > 300 && (C && clearTimeout(C), C = setTimeout(function () { u && (u.params.paginationHide && u.paginationContainer.length > 0 && !m(e.target).hasClass(u.params.bulletClass) && u.paginationContainer.toggleClass(u.params.paginationHiddenClass), u.params.onClick && u.params.onClick(u, e)) }, 300)), 300 > s && 300 > a - P && (C && clearTimeout(C), u.params.onDoubleTap && u.params.onDoubleTap(u, e))), P = Date.now(), setTimeout(function () { u && u.allowClick && (u.allowClick = !0) }, 0); var r = t() ? y.x - S.x : y.y - S.y; if (!h || !w || !u.swipeDirection || 0 === r || T === b) return void (h = w = !1); h = w = !1; var i; if (i = u.params.followFinger ? u.rtl ? u.translate : -u.translate : -T, u.params.freeMode) { if (i < -u.minTranslate()) return void u.slideTo(u.activeIndex); if (i > -u.maxTranslate()) return void u.slideTo(u.slides.length - 1); if (u.params.freeModeMomentum) { if (k.length > 1) { var n = k.pop(), o = k.pop(), l = n.position - o.position, p = n.time - o.time; u.velocity = l / p, u.velocity = u.velocity / 2, Math.abs(u.velocity) < .02 && (u.velocity = 0), (p > 150 || s > 300) && (u.velocity = 0) } else u.velocity = 0; k.length = 0; var d, c = 1e3 * u.params.freeModeMomentumRatio, f = u.velocity * c, g = u.translate + f, x = !1, z = 20 * Math.abs(u.velocity) * u.params.freeModeMomentumBounceRatio; g < u.maxTranslate() && (u.params.freeModeMomentumBounce ? (g + u.maxTranslate() < -z && (g = u.maxTranslate() - z), d = u.maxTranslate(), x = !0, M = !0) : g = u.maxTranslate()), g > u.minTranslate() && (u.params.freeModeMomentumBounce ? (g - u.minTranslate() > z && (g = u.minTranslate() + z), d = u.minTranslate(), x = !0, M = !0) : g = u.minTranslate()), 0 !== u.velocity && (c = Math.abs((g - u.translate) / u.velocity)), u.params.freeModeMomentumBounce && x ? (u.updateProgress(d), u.setWrapperTranslate(g), u.setWrapperTransition(c), u.onTransitionStart(), u.animating = !0, u.wrapper.transitionEnd(function () { M && (u.params.onMomentumBounce && u.params.onMomentumBounce(u), u.setWrapperTranslate(d), u.setWrapperTransition(u.params.speed), u.wrapper.transitionEnd(function () { u.onTransitionEnd() })) })) : u.velocity ? (u.updateProgress(g), u.setWrapperTranslate(g), u.setWrapperTransition(c), u.onTransitionStart(), u.animating || (u.animating = !0, u.wrapper.transitionEnd(function () { u.onTransitionEnd() }))) : u.updateProgress(g), u.updateActiveIndex() } return void ((!u.params.freeModeMomentum || s >= u.params.longSwipesMs) && (u.updateProgress(), u.updateActiveIndex())) } var E, I = 0, D = u.slidesSizesGrid[0]; for (E = 0; E < u.slidesGrid.length; E += u.params.slidesPerGroup) "undefined" != typeof u.slidesGrid[E + u.params.slidesPerGroup] ? i >= u.slidesGrid[E] && i < u.slidesGrid[E + u.params.slidesPerGroup] && (I = E, D = u.slidesGrid[E + u.params.slidesPerGroup] - u.slidesGrid[E]) : i >= u.slidesGrid[E] && (I = E, D = u.slidesGrid[u.slidesGrid.length - 1] - u.slidesGrid[u.slidesGrid.length - 2]); var G = (i - u.slidesGrid[I]) / D; if (s > u.params.longSwipesMs) { if (!u.params.longSwipes) return void u.slideTo(u.activeIndex); "next" === u.swipeDirection && u.slideTo(G >= u.params.longSwipesRatio ? I + u.params.slidesPerGroup : I), "prev" === u.swipeDirection && u.slideTo(G > 1 - u.params.longSwipesRatio ? I + u.params.slidesPerGroup : I) } else { if (!u.params.shortSwipes) return void u.slideTo(u.activeIndex); "next" === u.swipeDirection && u.slideTo(I + u.params.slidesPerGroup), "prev" === u.swipeDirection && u.slideTo(I) } } }, u._slideTo = function (e, a) { return u.slideTo(e, a, !0, !0) }, u.slideTo = function (e, a, s, r) { "undefined" == typeof s && (s = !0), "undefined" == typeof e && (e = 0), 0 > e && (e = 0), u.snapIndex = Math.floor(e / u.params.slidesPerGroup), u.snapIndex >= u.snapGrid.length && (u.snapIndex = u.snapGrid.length - 1); var i = -u.snapGrid[u.snapIndex]; u.params.autoplay && u.autoplaying && (r || !u.params.autoplayDisableOnInteraction ? u.pauseAutoplay(a) : u.stopAutoplay()), u.updateProgress(i); for (var n = 0; n < u.slidesGrid.length; n++) -i >= u.slidesGrid[n] && (e = n); if ("undefined" == typeof a && (a = u.params.speed), u.previousIndex = u.activeIndex || 0, u.activeIndex = e, i === u.translate) return u.updateClasses(), !1; s && u.onTransitionStart(); t() ? i : 0, t() ? 0 : i; 0 === a ? (u.setWrapperTransition(0), u.setWrapperTranslate(i), s && u.onTransitionEnd()) : (u.setWrapperTransition(a), u.setWrapperTranslate(i), u.animating || (u.animating = !0, u.wrapper.transitionEnd(function () { s && u.onTransitionEnd() }))), u.updateClasses() }, u.onTransitionStart = function () { u.params.onTransitionStart && u.params.onTransitionStart(u), u.params.onSlideChangeStart && u.activeIndex !== u.previousIndex && u.params.onSlideChangeStart(u) }, u.onTransitionEnd = function () { u.animating = !1, u.setWrapperTransition(0), u.params.onTransitionEnd && u.params.onTransitionEnd(u), u.params.onSlideChangeEnd && u.activeIndex !== u.previousIndex && u.params.onSlideChangeEnd(u) }, u.slideNext = function (e, a, t) { if (u.params.loop) { if (u.animating) return !1; u.fixLoop(); { u.container[0].clientLeft } return u.slideTo(u.activeIndex + u.params.slidesPerGroup, a, e, t) } return u.slideTo(u.activeIndex + u.params.slidesPerGroup, a, e, t) }, u._slideNext = function (e) { return u.slideNext(!0, e, !0) }, u.slidePrev = function (e, a, t) { if (u.params.loop) { if (u.animating) return !1; u.fixLoop(); { u.container[0].clientLeft } return u.slideTo(u.activeIndex - 1, a, e, t) } return u.slideTo(u.activeIndex - 1, a, e, t) }, u._slidePrev = function (e) { return u.slidePrev(!0, e, !0) }, u.slideReset = function (e, a) { return u.slideTo(u.activeIndex, a, e) }, u.setWrapperTransition = function (e, a) { u.wrapper.transition(e), u.params.onSetTransition && u.params.onSetTransition(u, e), "slide" !== u.params.effect && u.effects[u.params.effect] && u.effects[u.params.effect].setTransition(e), u.params.scrollbar && u.scrollbar && u.scrollbar.setTransition(e), u.params.control && u.controller && u.controller.setTransition(e, a) }, u.setWrapperTranslate = function (e, a, s) { var r = 0, i = 0, n = 0; t() ? r = u.rtl ? -e : e : i = e, u.wrapper.transform(u.support.transforms3d ? "translate3d(" + r + "px, " + i + "px, " + n + "px)" : "translate(" + r + "px, " + i + "px)"), u.translate = t() ? r : i, a && u.updateActiveIndex(), "slide" !== u.params.effect && u.effects[u.params.effect] && u.effects[u.params.effect].setTranslate(u.translate), u.params.scrollbar && u.scrollbar && u.scrollbar.setTranslate(u.translate), u.params.control && u.controller && u.controller.setTranslate(u.translate, s), u.params.hashnav && u.hashnav && u.hashnav.setHash(), u.params.onSetTranslate && u.params.onSetTranslate(u, u.translate) }, u.getTranslate = function (e, a) { var t, s, r, i; return "undefined" == typeof a && (a = "x"), r = window.getComputedStyle(e, null), window.WebKitCSSMatrix ? i = new WebKitCSSMatrix("none" === r.webkitTransform ? "" : r.webkitTransform) : (i = r.MozTransform || r.OTransform || r.MsTransform || r.msTransform || r.transform || r.getPropertyValue("transform").replace("translate(", "matrix(1, 0, 0, 1,"), t = i.toString().split(",")), "x" === a && (s = window.WebKitCSSMatrix ? i.m41 : parseFloat(16 === t.length ? t[12] : t[4])), "y" === a && (s = window.WebKitCSSMatrix ? i.m42 : parseFloat(16 === t.length ? t[13] : t[5])), u.rtl && s && (s = -s), s || 0 }, u.getWrapperTranslate = function (e) { return "undefined" == typeof e && (e = t() ? "x" : "y"), u.getTranslate(u.wrapper[0], e) }, u.observers = [], u.initObservers = function () { if (u.params.observeParents) for (var e = u.container.parents(), a = 0; a < e.length; a++) n(e[a]); n(u.container[0], { childList: !1 }), n(u.wrapper[0], { attributes: !1 }) }, u.disconnectObservers = function () { for (var e = 0; e < u.observers.length; e++) u.observers[e].disconnect(); u.observers = [] }, u.createLoop = function () { u.wrapper.children("." + u.params.slideClass + "." + u.params.slideDuplicateClass).remove(); var e = u.wrapper.children("." + u.params.slideClass); u.loopedSlides = parseInt(u.params.loopedSlides || u.params.slidesPerView, 10), u.loopedSlides = u.loopedSlides + u.params.loopAdditionalSlides, u.loopedSlides > e.length && (u.loopedSlides = e.length); var a, t = [], s = []; for (e.each(function (a, r) { var i = m(this); a < u.loopedSlides && s.push(r), a < e.length && a >= e.length - u.loopedSlides && t.push(r), i.attr("data-swiper-slide-index", a) }), a = 0; a < s.length; a++) u.wrapper.append(m(s[a].cloneNode(!0)).addClass(u.params.slideDuplicateClass)); for (a = t.length - 1; a >= 0; a--) u.wrapper.prepend(m(t[a].cloneNode(!0)).addClass(u.params.slideDuplicateClass)) }, u.deleteLoop = function () { u.wrapper.children("." + u.params.slideClass + "." + u.params.slideDuplicateClass).remove() }, u.fixLoop = function () { var e; u.activeIndex < u.loopedSlides ? (e = u.slides.length - 3 * u.loopedSlides + u.activeIndex, e += u.loopedSlides, u.slideTo(e, 0, !1, !0)) : ("auto" === u.params.slidesPerView && u.activeIndex >= 2 * u.loopedSlides || u.activeIndex > u.slides.length - 2 * u.params.slidesPerView) && (e = -u.slides.length + u.activeIndex + u.loopedSlides, e += u.loopedSlides, u.slideTo(e, 0, !1, !0)) }, u.appendSlide = function (e) { if (u.params.loop && u.deleteLoop(), "object" == typeof e && e.length) for (var a = 0; a < e.length; a++) e[a] && u.wrapper.append(e[a]); else u.wrapper.append(e); u.params.loop && u.createLoop(), u.params.observer && u.support.observer || u.update() }, u.prependSlide = function (e) { u.params.loop && u.deleteLoop(); var a = u.activeIndex + 1; if ("object" == typeof e && e.length) { for (var t = 0; t < e.length; t++) e[t] && u.wrapper.prepend(e[t]); a = u.activeIndex + e.length } else u.wrapper.prepend(e); u.params.loop && u.createLoop(), u.params.observer && u.support.observer || u.update(), u.slideTo(a, 0, !1) }, u.effects = { fade: { setTranslate: function () { for (var e = 0; e < u.slides.length; e++) { var a = u.slides.eq(e), s = a[0].swiperSlideOffset, r = -s - u.translate, i = 0; t() || (i = r, r = 0), a.css({ opacity: 1 + Math.min(Math.max(a[0].progress, -1), 0) }).transform("translate3d(" + r + "px, " + i + "px, 0px)") } }, setTransition: function (e) { u.slides.transition(e) } }, cube: { setTranslate: function () { var e, a = 0; u.params.cube.shadow && (t() ? (e = u.wrapper.find(".swiper-cube-shadow"), 0 === e.length && (e = m('<div class="swiper-cube-shadow"></div>'), u.wrapper.append(e)), e.css({ height: u.width + "px" })) : (e = u.container.find(".swiper-cube-shadow"), 0 === e.length && (e = m('<div class="swiper-cube-shadow"></div>'), u.container.append(e)))); for (var s = 0; s < u.slides.length; s++) { var r = u.slides.eq(s), i = 90 * s, n = Math.floor(i / 360); u.rtl && (i = -i, n = Math.floor(-i / 360)); var o = Math.max(Math.min(r[0].progress, 1), -1), l = 0, p = 0, d = 0; s % 4 === 0 ? (l = 4 * -n * u.size, d = 0) : (s - 1) % 4 === 0 ? (l = 0, d = 4 * -n * u.size) : (s - 2) % 4 === 0 ? (l = u.size + 4 * n * u.size, d = u.size) : (s - 3) % 4 === 0 && (l = -u.size, d = 3 * u.size + 4 * u.size * n), u.rtl && (l = -l), t() || (p = l, l = 0); var c = "rotateX(" + (t() ? 0 : -i) + "deg) rotateY(" + (t() ? i : 0) + "deg) translate3d(" + l + "px, " + p + "px, " + d + "px)"; if (1 >= o && o > -1 && (a = 90 * s + 90 * o, u.rtl && (a = 90 * -s - 90 * o)), r.transform(c), u.params.cube.slideShadows) { var f = r.find(t() ? ".swiper-slide-shadow-left" : ".swiper-slide-shadow-top"), h = r.find(t() ? ".swiper-slide-shadow-right" : ".swiper-slide-shadow-bottom"); 0 === f.length && (f = m('<div class="swiper-slide-shadow-' + (t() ? "left" : "top") + '"></div>'), r.append(f)), 0 === h.length && (h = m('<div class="swiper-slide-shadow-' + (t() ? "right" : "bottom") + '"></div>'), r.append(h)); { r[0].progress } f.length && (f[0].style.opacity = -r[0].progress), h.length && (h[0].style.opacity = r[0].progress) } } if (u.wrapper.css({ "-webkit-transform-origin": "50% 50% -" + u.size / 2 + "px", "-moz-transform-origin": "50% 50% -" + u.size / 2 + "px", "-ms-transform-origin": "50% 50% -" + u.size / 2 + "px", "transform-origin": "50% 50% -" + u.size / 2 + "px" }), u.params.cube.shadow) if (t()) e.transform("translate3d(0px, " + (u.width / 2 + u.params.cube.shadowOffset) + "px, " + -u.width / 2 + "px) rotateX(90deg) rotateZ(0deg) scale(" + u.params.cube.shadowScale + ")"); else { var w = Math.abs(a) - 90 * Math.floor(Math.abs(a) / 90), v = 1.5 - (Math.sin(2 * w * Math.PI / 360) / 2 + Math.cos(2 * w * Math.PI / 360) / 2), g = u.params.cube.shadowScale, T = u.params.cube.shadowScale / v, b = u.params.cube.shadowOffset; e.transform("scale3d(" + g + ", 1, " + T + ") translate3d(0px, " + (u.height / 2 + b) + "px, " + -u.height / 2 / T + "px) rotateX(-90deg)") } var x = u.isSafari || u.isUiWebView ? -u.size / 2 : 0; u.wrapper.transform("translate3d(0px,0," + x + "px) rotateX(" + (t() ? 0 : a) + "deg) rotateY(" + (t() ? -a : 0) + "deg)") }, setTransition: function (e) { u.slides.transition(e).find(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").transition(e), u.params.cube.shadow && !t() && u.container.find(".swiper-cube-shadow").transition(e) } }, coverflow: { setTranslate: function () { for (var e = u.translate, a = t() ? -e + u.width / 2 : -e + u.height / 2, s = t() ? u.params.coverflow.rotate : -u.params.coverflow.rotate, r = u.params.coverflow.depth, i = 0, n = u.slides.length; n > i; i++) { var o = u.slides.eq(i), l = u.slidesSizesGrid[i], p = o[0].swiperSlideOffset, d = (a - p - l / 2) / l * u.params.coverflow.modifier, c = t() ? s * d : 0, f = t() ? 0 : s * d, h = -r * Math.abs(d), w = t() ? 0 : u.params.coverflow.stretch * d, v = t() ? u.params.coverflow.stretch * d : 0; Math.abs(v) < .001 && (v = 0), Math.abs(w) < .001 && (w = 0), Math.abs(h) < .001 && (h = 0), Math.abs(c) < .001 && (c = 0), Math.abs(f) < .001 && (f = 0); var g = "translate3d(" + v + "px," + w + "px," + h + "px)  rotateX(" + f + "deg) rotateY(" + c + "deg)"; if (o.transform(g), o[0].style.zIndex = -Math.abs(Math.round(d)) + 1, u.params.coverflow.slideShadows) { var T = o.find(t() ? ".swiper-slide-shadow-left" : ".swiper-slide-shadow-top"), b = o.find(t() ? ".swiper-slide-shadow-right" : ".swiper-slide-shadow-bottom"); 0 === T.length && (T = m('<div class="swiper-slide-shadow-' + (t() ? "left" : "top") + '"></div>'), o.append(T)), 0 === b.length && (b = m('<div class="swiper-slide-shadow-' + (t() ? "right" : "bottom") + '"></div>'), o.append(b)), T.length && (T[0].style.opacity = d > 0 ? d : 0), b.length && (b[0].style.opacity = -d > 0 ? -d : 0) } } if (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) { var x = u.wrapper.style; x.perspectiveOrigin = a + "px 50%" } }, setTransition: function (e) { u.slides.transition(e).find(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").transition(e) } } }, u.scrollbar = { init: function () { if (u.params.scrollbar) { var e = u.scrollbar; e.track = m(u.params.scrollbar), e.drag = e.track.find(".swiper-scrollbar-drag"), 0 === e.drag.length && (e.drag = m('<div class="swiper-scrollbar-drag"></div>'), e.track.append(e.drag)), e.drag[0].style.width = "", e.drag[0].style.height = "", e.trackSize = t() ? e.track[0].offsetWidth : e.track[0].offsetHeight, e.divider = u.size / u.virtualWidth, e.moveDivider = e.divider * (e.trackSize / u.size), e.dragSize = e.trackSize * e.divider, t() ? e.drag[0].style.width = e.dragSize + "px" : e.drag[0].style.height = e.dragSize + "px", e.track[0].style.display = e.divider >= 1 ? "none" : "", u.params.scrollbarHide && (e.track[0].style.opacity = 0) } }, setTranslate: function () { if (u.params.scrollbar) { var e, a = u.scrollbar, s = (u.translate || 0, a.dragSize); e = (a.trackSize - a.dragSize) * u.progress, u.rtl && t() ? (e = -e, e > 0 ? (s = a.dragSize - e, e = 0) : -e + a.dragSize > a.trackSize && (s = a.trackSize + e)) : 0 > e ? (s = a.dragSize + e, e = 0) : e + a.dragSize > a.trackSize && (s = a.trackSize - e), t() ? (a.drag.transform("translate3d(" + e + "px, 0, 0)"), a.drag[0].style.width = s + "px") : (a.drag.transform("translate3d(0px, " + e + "px, 0)"), a.drag[0].style.height = s + "px"), u.params.scrollbarHide && (clearTimeout(a.timeout), a.track[0].style.opacity = 1, a.timeout = setTimeout(function () { a.track[0].style.opacity = 0, a.track.transition(400) }, 1e3)) } }, setTransition: function (e) { u.params.scrollbar && u.scrollbar.drag.transition(e) } }, u.controller = { setTranslate: function (e, a) { var t, s, r = u.params.control; if (u.isArray(r)) for (var i = 0; i < r.length; i++) r[i] !== a && r[i] instanceof Swiper && (e = r[i].rtl && "horizontal" === r[i].params.direction ? -u.translate : u.translate, t = (r[i].maxTranslate() - r[i].minTranslate()) / (u.maxTranslate() - u.minTranslate()), s = (e - u.minTranslate()) * t + r[i].minTranslate(), u.params.controlInverse && (s = r[i].maxTranslate() - s), r[i].updateProgress(s), r[i].setWrapperTranslate(s, !1, u), r[i].updateActiveIndex()); else r instanceof Swiper && a !== r && (e = r.rtl && "horizontal" === r.params.direction ? -u.translate : u.translate, t = (r.maxTranslate() - r.minTranslate()) / (u.maxTranslate() - u.minTranslate()), s = (e - u.minTranslate()) * t + r.minTranslate(), u.params.controlInverse && (s = r.maxTranslate() - s), r.updateProgress(s), r.setWrapperTranslate(s, !1, u), r.updateActiveIndex()) }, setTransition: function (e, a) { var t = u.params.control; if (u.isArray(t)) for (var s = 0; s < t.length; s++) t[s] !== a && t[s] instanceof Swiper && t[s].setWrapperTransition(e, u); else t instanceof Swiper && a !== t && t.setWrapperTransition(e, u) } }, u.hashnav = { init: function () { if (u.params.hashnav) { u.hashnav.initialized = !0; var e = document.location.hash.replace("#", ""); if (e) for (var a = 0, t = 0, s = u.slides.length; s > t; t++) { var r = u.slides.eq(t), i = r.attr("data-hash"); if (i === e && !r.hasClass(u.params.slideDuplicateClass)) { var n = r.index(); u._slideTo(n, a) } } } }, setHash: function () { u.hashnav.initialized && u.params.hashnav && (document.location.hash = u.slides.eq(u.activeIndex).attr("data-hash") || "") } }, u.disableKeyboardControl = function () { m(document).off("keydown", o) }, u.enableKeyboardControl = function () { m(document).on("keydown", o) }, u._wheelEvent = !1, u._lastWheelScrollTime = (new Date).getTime(), u.params.mousewheelControl) { if (void 0 !== document.onmousewheel && (u._wheelEvent = "mousewheel"), !u._wheelEvent) try { new WheelEvent("wheel"), u._wheelEvent = "wheel" } catch (E) { } u._wheelEvent || (u._wheelEvent = "DOMMouseScroll") } return u.disableMousewheelControl = function () { return u._wheelEvent ? (u.container.off(u._wheelEvent, l), !0) : !1 }, u.enableMousewheelControl = function () { return u._wheelEvent ? (u.container.on(u._wheelEvent, l), !0) : !1 }, u.init = function () { u.params.loop && u.createLoop(), u.updateContainerSize(), u.updateSlidesSize(), u.updatePagination(), u.params.scrollbar && u.scrollbar && u.scrollbar.init(), "slide" !== u.params.effect && u.effects[u.params.effect] && (u.params.loop || u.updateProgress(), u.effects[u.params.effect].setTranslate()), u.params.loop ? u.slideTo(u.params.initialSlide + u.loopedSlides, 0, !1) : u.slideTo(u.params.initialSlide, 0, !1), u.attachEvents(), u.params.observer && u.support.observer && u.initObservers(), u.params.updateOnImagesReady && u.preloadImages(), u.params.autoplay && u.startAutoplay(), u.params.keyboardControl && u.enableKeyboardControl && u.enableKeyboardControl(), u.params.mousewheelControl && u.enableMousewheelControl && u.enableMousewheelControl(), u.params.hashnav && u.hashnav && u.hashnav.init() }, u.destroy = function (e) { u.detachEvents(), u.disconnectObservers(), u.params.keyboardControl && u.disableKeyboard && u.disableKeyboard(), u.params.mousewheelControl && u.disableMousewheel && u.disableMousewheel(), u.params.onDestroy && u.params.onDestroy(), e !== !1 && (u = null) }, u.init(), u } }, Swiper.prototype = { isSafari: function () { var e = navigator.userAgent.toLowerCase(); return e.indexOf("safari") >= 0 && e.indexOf("chrome") < 0 && e.indexOf("android") < 0 }(), isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent), isArray: function (e) { return "[object Array]" === Object.prototype.toString.apply(e) }, support: { touch: window.Modernizr && Modernizr.touch === !0 || function () { return !!("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch) }(), transforms3d: window.Modernizr && Modernizr.csstransforms3d === !0 || function () { var e = document.createElement("div").style; return "webkitPerspective" in e || "MozPerspective" in e || "OPerspective" in e || "MsPerspective" in e || "perspective" in e }(), flexbox: function () { for (var e = document.createElement("div").style, a = "WebkitBox msFlexbox MsFlexbox WebkitFlex MozBox fles".split(" "), t = 0; t < a.length; t++) if (a[t] in e) return !0 }(), observer: function () { return "MutationObserver" in window || "WebkitMutationObserver" in window }() } }; for (var a = ["jQuery", "Zepto", "Dom7"], t = 0; t < a.length; t++) window[a[t]] && e(window[a[t]]); var s; s = "undefined" == typeof Dom7 ? window.Dom7 || window.Zepto || window.jQuery : Dom7, s && ("transitionEnd" in s.fn || ($.fn.transitionEnd = function (e) { function a(i) { if (i.target === this) for (e.call(this, i), t = 0; t < s.length; t++) r.off(s[t], a) } var t, s = ["webkitTransitionEnd", "transitionend", "oTransitionEnd", "MSTransitionEnd", "msTransitionEnd"], r = this; if (e) for (t = 0; t < s.length; t++) r.on(s[t], a); return this }), "transform" in s.fn || ($.fn.transform = function (e) { for (var a = 0; a < this.length; a++) { var t = this[a].style; t.webkitTransform = t.MsTransform = t.msTransform = t.MozTransform = t.OTransform = t.transform = e } return this }), "transition" in s.fn || ($.fn.transition = function (e) { "string" != typeof e && (e += "ms"); for (var a = 0; a < this.length; a++) { var t = this[a].style; t.webkitTransitionDuration = t.MsTransitionDuration = t.msTransitionDuration = t.MozTransitionDuration = t.OTransitionDuration = t.transitionDuration = e } return this })) }(), "undefined" != typeof module ? module.exports = Swiper : "function" == typeof define && define.amd && define([], function () { "use strict"; return Swiper });
var swiper;
var swiper_here = false;
var current_position;
var ww;

$(function () {

    // ADD ITEM TO COMPARE LIST
    // -----------------------------------
    $(document).on('click', '.js-add-compare', function () {
        var data_id = $(this).attr('data-id');
        openCompareOverlay(data_id);
    });



    // DELETE ITEM
    // -----------------------------------
    $(document).on('click', '.sk-comparison-table .js-product-delete', function () {
        var del_nr = $(this).parents('.sk-compare-product').attr('data-sort');

        var count_items = $('.sk-comparison-table .sk-compare-product').length;
        var new_count = Number(count_items) - 1;

        var cur_cols = 12 / Number(count_items);
        var new_cols = 12 / new_count;

        // CHECK IF LESS THAN 3 PRODUCTS - IF SO REMOVE DELETE BUTTONS
        if (new_count < 3) {
            $('.sk-comparison-table .js-product-delete').remove();
            $('.sk-product-list-page .swiper-container .swiper-pagination').remove();
        }

       
       
        // DELETE ITEMS WITH CORRECT NR AND DECREASE COLSPAN IN HEADERS
        var old_colspan = Number($('.panel-heading.sk-accordion td').attr("colspan"));
        var new_colspan = old_colspan - 1;
        $('.panel-heading.sk-accordion td').attr("colspan", new_colspan);

        // CHANGE TABLE WIDTH
        $(".sk-compare-product").parents(".sk-comparison-table").removeClass("sk-comparison-table--colspan_" + old_colspan).addClass("sk-comparison-table--colspan_" + new_colspan);
        $('.sk-compare-product, .sk-comparison-table .accordion-body').each(function () {
            $this = $(this);
            if ($this.attr('data-sort') == del_nr) {
                $this.parents("td").remove();
                removeProdFromSession($this);
            }
        });
        
    });

    function closeCompareOverlay() {
        $('#sk-product-comparison-overlay').modal('hide');

        $('.sk-compare-overlay').delay(150).fadeOut(function () {
            $('.sk-compare-overlay').remove();
        });
    }

    // IN OVERLAY
    $(document).on('click', '#sk-product-comparison-overlay .js-product-delete', function () {
        $inner = $('#sk-product-comparison-overlay');
        var elements = $('.sk-compare-products--overlay .js-product-delete').length;
        // Check how many products left
        if (elements == 1) {
            // Close overlay if only one product left
            closeCompareOverlay();
        } else{
            // Delete product if there are more than 1 product
            $item = $(this).parents('.sk-compare-product');
            $item.remove();
            $('.sk-compare-products').append($('#sk-compare-overlay--empty-element').html());
            if (elements == 2) {
                $inner.find('.sk-compare-product:nth-child(2)').addClass('sk-compare-product--centered').append($('#sk-compare-message--one-product').html());
            }
            if (elements < 3) {
                $inner.find('.sk-compare-product__text .closeit').css('display', 'inline-block');
                $inner.find('.sk-compare-overlay__submit').hide(0);
            }
        }
        removeProdFromSession($(this));
    });
 

    // INITIALIZE ACCORDION
    // -----------------------------------
    if ($('.ctAccordion').length > 0) {
        $('.ctAccordion').ctAccordion();
    }
});

function createDataLayerAction(nodeId, name, desc, action) {
    return {
        "event": "compareProduct" + action,
        "eventCategory": "Comparison",
        "eventAction": action,
        "eventLabel": name,
        "productData": {
            "name": name,
            "desc": desc,
            "url": window.location.origin + '/' + nodeId
        }
    }
}

// DELETE PRODUCT ITEMS
function removeProdFromSession($elem) {
    $.ajax({
        url: '/ProductComparisonSessionHandler.ashx?product_id=' + $elem.attr('data-id') + '&compareaction=delete',
        type: 'post',
        success: function () {
            var elem = createDataLayerAction($elem.data('node-id'), $elem.data('name'), $elem.data('desc'), "Remove");
            window.dataLayer.push(elem);
        }
    })
}

// COMPARE OVERLAY
function openCompareOverlay(data_id) {

	$inner = $('#sk-product-comparison-overlay').find('.modal-body');
	$inner.html($('#sk-product-comparison-overlay-base').html());
	$inner.append($("#sk-compare-message--loading").html());
    $.ajax({
        url: '/ProductComparisonSessionHandler.ashx?product_id=' + data_id + '&compareaction=add',
        type: 'post',
		success: function (data) {
		    $(".sk-compare-message--loading").remove();
			var count = data.Products.length;                
				
			// add products to overlay	
            $.each(data.Products, function (i, item) {
                $inner.find('.pi' + i).removeClass('sk-compare-product--empty').append('<div class="sk-compare-product__prod-img"><button data-id="' + item.Gtin + '" data-node-id="' + data_id + '" data-name="' + item.ProductNameWithoutSpecialCharacters + '" data-desc="' + item.ConsumerLongDescription + '" class="sk-compare-product__delete close js-product-delete" aria-hidden="true">&times;<span class="sr-only">Close</span></button><div class="align-helper"></div><img src="' + item.Images[0].Source + "?width=200" + '" alt="" /></div><span class="sk-compare-product__text">' + item.ProductNameWithoutSpecialCharacters + '</span>');
                var elem = createDataLayerAction(data_id, item.ProductNameWithoutSpecialCharacters, item.ConsumerLongDescription, "Add");
                window.dataLayer.push(elem);
			});
				
			// show message if only 1 product added
			if (count < 2) {
			    $inner.find('.sk-compare-product:nth-child(2)').addClass('sk-compare-product--centered').append($('#sk-compare-message--one-product').html());
			    $('#sk-product-comparison-overlay .sk-compare-overlay__submit').hide();
			}
				
			// show message if a fifth product is added
			if(data.Status == 'OutofRange'){ 
				$inner.prepend($('#sk-compare-message--five_products').html());
				$('.sk-compare-message--full').delay(3500).fadeOut(function () { $(this).remove(); });
			}
				
			// decide the bottom button
			if(count > 1){
				$('#sk-product-comparison-overlay').find('.sk-compare-product__text .closeit').hide(0);
				$('#sk-product-comparison-overlay .sk-compare-overlay__submit').show();
			}
        }
    });

}




// ACCORDION
(function ($) {

    $.fn.ctAccordion = function () {

        // ACCORDION ITEM CLICK
        var acc = this;
        acc.find('.accordion--item > span').on('click', function () {

            $this = $(this);
            open_new = false;
            if (!$this.parent().hasClass('opened')) { open_new = true; }

            // HIDE CURRENT
            acc.find('.opened .accordion--content').stop(true, false).slideToggle(300);
            acc.find('.opened').removeClass('opened');

            if (open_new) {
                // SHOW NEW
                $(this).parent().addClass('opened');
                $(this).next().stop(true, false).slideToggle(300);
				
				// ADJUST HIDDEN CONTENT
				adjustHiddenContent(swiper);
				
				// ADJUST HEIGHT
				adjustAccordionContentHeight();
            }

        });
    };

}(jQuery));
var ProductTagSearch = ProductTagSearch || {
    SelectedSingleTag: {},
    SelectedMultiTags: [],
    ToggleSingle: function (ele) {
        var tag = ProductTagSearch.GetTag(ele);
        $('.js-singletag').each(function (index, element) {
            $(element).removeClass("ps-tab--active");
        });
        $(ele).addClass("ps-tab--active"); 
        ProductTagSearch.SelectedSingleTag = tag;
    },
    ToggleMulti: function (ele) {
        var tag = ProductTagSearch.GetTag(ele);
        var idx = ProductTagSearch.GetIndex(ProductTagSearch.SelectedMultiTags, 'TagId', tag.TagId);
        if (idx > -1) {
            ProductTagSearch.SelectedMultiTags.splice(idx, 1);
            $(ele).parent().removeClass("ps-tile--active");
        }
        else {
            ProductTagSearch.SelectedMultiTags.push(tag);
            $(ele).parent().addClass("ps-tile--active");
        }
    },
    Submit: function (ele) {
        var container = $('.js-ps-section');
        var url = container.data('resultspage');
        url += ProductTagSearch.GetQueryString();
        window.location = url;
    },
    GetTag: function (ele) {
        var category = $(ele).data('category');
        var tagId = $(ele).data('tagid');
        var tag = new ProductTagSearch.Tag(category, tagId);
        return tag;
    },
    GetIndex: function (array, attr, value) {
        for (var i = 0; i < array.length; i += 1) {
            if (array[i][attr] === value) {
                return i;
            }
        }
        return -1;
    },
    GetQueryString: function () {
        var qs = ProductTagSearch.GetQueryStringValue(ProductTagSearch.SelectedSingleTag, true);
        for (var i = 0; i < ProductTagSearch.SelectedMultiTags.length; i++) {
            var tag = ProductTagSearch.SelectedMultiTags[i];
            qs += ProductTagSearch.GetQueryStringValue(tag, false);
        }
        return qs;
    },
    GetQueryStringValue: function (tag, isFirst) {
        var value = (isFirst) ? "?" : "&";
        value += tag.Category + "=" + tag.TagId;
        return value;
    }
}

ProductTagSearch.Tag = function (category, tagId) {
    return {
        Category: category,
        TagId: tagId
    }
}

$(document).ready(function () {
    $('.js-singletag').click(function (e) {
        ProductTagSearch.ToggleSingle(this);
    });
    $('.js-multitag').click(function (e) {
        ProductTagSearch.ToggleMulti(this);
    });
    $('.js-ps-submit').click(function (e) {
        ProductTagSearch.Submit(this);
    });

    var singleTags = $('.js-singletag');
    if (singleTags.size() > 0) {
        singleTags[0].click();
    }
});
/*
 * Product Page
 * Functions that are specific to the product page
 */
$(document).ready(function () {

    //-----------------------------------------------------------------------------------------
    // ChannelSight
    //-----------------------------------------------------------------------------------------

    // Always remove channelsight error from the page if one exists before executing ajax request
    $('.channelsight-error').remove();

    //PriceSpider.rebind();
    

    // Retrieve data required for product channel sight request
    var data = $('#channelsight-data');

    var baseUrl = data.attr('data-baseUrl');
    var currency = data.attr('data-currency');
    var gtin = data.attr('data-gtin');
    var inStock = data.attr('data-in-stock');
    var outStock = data.attr('data-out-of-stock');
    var language = data.attr('data-language');
    var country = data.attr('data-country');
    var logoOnly = data.attr('data-logoOnly') === "" ? false : ((data.attr('data-logoOnly') + '').toLowerCase() === 'true');
    var headerText = data.attr('data-headerText');
    var hidePrice = data.attr('data-hide-price') === "" ? false : ((data.attr('data-hide-price') + '').toLowerCase()==='true');
var hideStock = data.attr('data-hide-stock') === "" ? false : ((data.attr('data-hide-stock') + '').toLowerCase() === 'true');



    if (baseUrl != undefined && gtin != undefined && language != undefined && country != undefined) {
        // Append channelsight loader gif
        $('.sk-channelsight').append('<div class="sk-channelsight__loader"></div>');
        $.ajax({
            type: "GET",
            url: "/Umbraco/Api/ChannelSightApi/GetProductDetails",
            data:
                {
                    baseUrl: baseUrl,
                    productid: gtin,
                    country: country,
                    language: language
                },
            success: function (data) {
                var response = $.parseJSON(data);
                if (response.status === "OK") {
                    var htmlBuilder = '<div class="sk-channelsight__header">' + headerText + '</div>';
                    for (var i = 0; i < response.dealers.length; i++) {
                        var dealer = response.dealers[i];
                        var cleanPrice = dealer.product.price.replace(/[^\d.]/g, '');
                        var price = parseFloat(cleanPrice).toFixed(2);
                        htmlBuilder += '<div class="sk-dealer' + (logoOnly ? ' sk-dealer--logoonly' : '') + '">';
                        htmlBuilder += '<div class="sk-dealer__logo-container">';
                        htmlBuilder += '<a target="_blank" href="' + dealer.product.buyurl + '">';
                        htmlBuilder += '<img class="sk-dealer__logo" src="' + dealer.logourl + '">';
                        htmlBuilder += '</div>';
                        htmlBuilder += '<div class="sk-dealer__body">';
                        if (!logoOnly)
                            htmlBuilder += '<h5 class="sk-dealer__name">' + dealer.name + '</h5>';
                        if (!hidePrice && (price !== "NaN") && !logoOnly)
                            htmlBuilder += '<div class="sk-dealer__price">' + currency + price + '</div>';
                        if (!hideStock && !logoOnly)
                            htmlBuilder += '<div class="sk-dealer__stock">' + (dealer.product.availability === 'YES' ? inStock : (dealer.product.availability == 'NO' ? outStock : checkStock)) + '</div>';
                        htmlBuilder += '</a></div>';
                        htmlBuilder += '</div>';
                    }

                    // Remove loader gif and append data
                    $('.sk-channelsight__loader').remove();
                    $(".sk-channelsight").append(htmlBuilder);
                } else {
                    // Remove loader 
                    $('.sk-channelsight__loader').remove();
                    //$('.sk-channelsight').append('<div class="channelsight-error text-danger">No ChannelSight data exists for this product.</div>');
                }
            },
            error: function (response) {
            },
            dataType: 'json'
        });
        //}
    } else {
        // Remove loader and append error message
        $('.channelsight-loader').remove();
        //$('.sk-channelsight').append('<div class="channelsight-error text-danger">The ChannelSight data could not be loaded.</div>');
    }
});
'use strict';

const mobileWidth = 767;
const otcOpenerWidth = 690;
// Session storage state for closed otc-disclaimer tab
StarterKit.RBOtcSessionStorage = (function (module) {
    var key = 'otcDisclaimer.closed';

    module.getItem = function() {
        // converting to boolean
        return sessionStorage.getItem(key) === 'true';
    };

    module.setItem = function(val) {
        sessionStorage.setItem(key, val);
    };

    module.toggleItem = function() {
        var val = this.getItem();
        this.setItem(!val);
    };

    return module;
})(StarterKit.RBOtcSessionStorage || {});


StarterKit.RBOtcDisclaimer = (function (module) {
    var otcDisclaimer = $('.sk-otc-disclaimer');
    var width = $(window).width();

    module.load = function() {
        if (width >= otcOpenerWidth) {
            if (!StarterKit.RBOtcSessionStorage.getItem()) otcDisclaimer.addClass('sk-otc-disclaimer-open');
        }
        if( otcDisclaimer.length && $(".sk-sidebar-container-nav").length ) {
          if (width <= mobileWidth) {
             $("body").addClass("sk-sidebar-otc");
          }
        }
    };

    module.bindToggle = function () {
        $('.sk-otc-disclaimer-btn').click(function () {
            otcDisclaimer.removeClass('sk-otc-disclaimer-no-animation');
            otcDisclaimer.toggleClass('sk-otc-disclaimer-open');
            StarterKit.RBOtcSessionStorage.toggleItem();
        });

        $('.sk-otc-disclaimer-wrapper h2').click(function () {
            otcDisclaimer.removeClass('sk-otc-disclaimer-no-animation');
            otcDisclaimer.toggleClass('sk-otc-disclaimer-open');
            StarterKit.RBOtcSessionStorage.toggleItem();
        });
    };

    return module;
})(StarterKit.RBOtcDisclaimer || {});

$(document).ready(function () {
    StarterKit.RBOtcDisclaimer.load();
    StarterKit.RBOtcDisclaimer.bindToggle();

});
'use strict'

StarterKit.RBGIFImage = (function (module) {
    var gifImages = $(".sk-grid-gif-image-container-static");

    module.load = function () {
        gifImages.each(function (index) {
            var staticImage = $($(this).find(".sk-grid-gif-image-static")[0]);

            staticImage.on({
                "mouseover": function () {
                    staticImage.attr("src", staticImage.data("sk-grid-gif-image-moving"));
                },
                "mouseout": function () {
                    staticImage.attr("src", staticImage.data("sk-grid-gif-image-static"));
                }
            });            
        });
    };
    
    return module;
})(StarterKit.RBGIFImage || {});

$(document).ready(function () {
    StarterKit.RBGIFImage.load();
});
'use strict'

StarterKit.ComponentMessagesModule = (function (module) {

	module.messagesModuleGoToNextStep = function (button, currentContainer, nextContainer) {
		button.click(function () {
			currentContainer.removeClass("visible").addClass("hidden");
			nextContainer.removeClass("hidden").addClass("visible");
		});
	}

	module.messagesModuleGoToPreviousStep = function (button, currentContainer, previousContainer) {
		button.click(function () {
			currentContainer.removeClass("visible").addClass("hidden");
			previousContainer.removeClass("hidden").addClass("visible");
		});
	}

	module.wrapText = function (context, text, x, y, maxWidth, lineHeight) {
		var words = text.split(' ');
		var line = '';

		for (var n = 0; n < words.length; n++) {
			var testLine = line + words[n] + ' ';
			var metrics = context.measureText(testLine);
			var testWidth = metrics.width;
			if (testWidth > maxWidth && n > 0) {
				context.fillText(line, x, y);
				line = words[n] + ' ';
				y += lineHeight;
			}
			else {
				line = testLine;
			}
		}
		context.fillText(line, x, y);
	}

	module.drawImage = function (templateImage) {
	    var messagesModuleTemplateImageObject = new Image();

	    messagesModuleTemplateImageObject.src = templateImage.attr("data-template-src");

	    messagesModuleTemplateImageObject.onload = function () {
	        $("#MessagesModuleTemplateCanvas").attr("width", this.width);
	        $("#MessagesModuleTemplateCanvas").attr("height", this.height);

	        var messagesModuleTemplateImageCanvas = document.getElementById("MessagesModuleTemplateCanvas");
	        var messagesModuleTemplateImageCanvasContext = messagesModuleTemplateImageCanvas.getContext("2d");

	        messagesModuleTemplateImageCanvasContext.drawImage(messagesModuleTemplateImageObject, 0, 0);
	        messagesModuleTemplateImageCanvasContext.font = $("#MessagesModuleFont").val();
	        messagesModuleTemplateImageCanvasContext.textAlign = "center";
	        messagesModuleTemplateImageCanvasContext.fillStyle = $("#MessagesModuleFontColor").val();

	        var wrappedTextMaxWidth = this.width - 40;
	        var wrappedTextLineHeight = 25;
	        var wrappedTextX = this.width / 2;
	        var wrappedTextY = 60;

	        module.wrapText(messagesModuleTemplateImageCanvasContext, $("#MessagesModuleInputText").val(), wrappedTextX, wrappedTextY, wrappedTextMaxWidth, wrappedTextLineHeight);

	        templateImage.attr("src", messagesModuleTemplateImageCanvas.toDataURL());
	    };
	}

	module.sendMessage = function () {
	    var messagesModuleTemplateImage = $("#MessagesModuleTemplateImage");
	    var messagesModuleSubject = $("#MessagesModuleSubject");
	    var messagesModuleSenderEmail = $("#MessagesModuleSenderEmail");
        var messagesModuleRecipientEmail = $("#MessagesModuleRecipientEmail");
        var messagesModuleSendNotAsAttachment = $("#MessageModuleSendNotAsAttachment");

	    $.ajax({
	        url: "/umbraco/api/ComponentMessagesModuleApi/SendMessage",
	        type: "POST",
            data: { SenderEmail: messagesModuleSenderEmail.val(), RecipientEmail: messagesModuleRecipientEmail.val(), Subject: messagesModuleSubject.val(), Image: messagesModuleTemplateImage.attr("src"), SendNotAsAttachment: messagesModuleSendNotAsAttachment.val() },
	        success: function (data, textStatus, jqXHR) {
	            $("#MessagesModuleStep4").removeClass("visible").addClass("hidden");
	            $("#MessagesModuleStep5").removeClass("hidden").addClass("visible");
	        }
	    })
	}

	module.load = function () {
		if ($(".sk-grid-messages-module").length > 0) {
			module.messagesModuleGoToNextStep($("#MessagesModuleStep1Next"), $("#MessagesModuleStep1"), $("#MessagesModuleStep2"));

			module.messagesModuleGoToPreviousStep($("#MessagesModuleStep2Previous"), $("#MessagesModuleStep2"), $("#MessagesModuleStep1"));
			module.messagesModuleGoToNextStep($("#MessagesModuleStep2Next"), $("#MessagesModuleStep2"), $("#MessagesModuleStep3"));

			module.messagesModuleGoToPreviousStep($("#MessagesModuleStep3Previous"), $("#MessagesModuleStep3"), $("#MessagesModuleStep2"));
			module.messagesModuleGoToNextStep($("#MessagesModuleStep3Next"), $("#MessagesModuleStep3"), $("#MessagesModuleStep4"));

			module.messagesModuleGoToPreviousStep($("#MessagesModuleStep4Previous"), $("#MessagesModuleStep4"), $("#MessagesModuleStep3"));

			var messagesModuleTemplateImage = $("#MessagesModuleTemplateImage");
			messagesModuleTemplateImage.attr("data-template-src", $(".sk-grid-messages-module-content-template").first().data("template-src"));
			module.drawImage(messagesModuleTemplateImage);

			$(".sk-grid-messages-module-content-template").each(function (i) {
				$(this).click(function () {
					var messagesModuleTemplateImage = $("#MessagesModuleTemplateImage");
					messagesModuleTemplateImage.attr("data-template-src", $(this).data("template-src"));
					module.drawImage(messagesModuleTemplateImage);
				});
			});

			$('#MessagesModuleInputText').on('input', function (e) {
			    var messagesModuleTemplateImage = $("#MessagesModuleTemplateImage");
			    module.drawImage(messagesModuleTemplateImage);
			});

			$("#MessagesModuleStep4Send").click(function () {
			    module.sendMessage();
			});
		}
	}

	return module;
})(StarterKit.ComponentMessagesModule || {});

$(document).ready(function () {
	StarterKit.ComponentMessagesModule.load();
});
'use strict'

StarterKit.RBStoreFinder = (function (module) {
    module.load = function () {
        $("#storeFinderText").change(function () {
            var action = $(this).val();
            $("#storeFinderForm").attr("action", "https://www.google.com/maps/search/" + searchPrefix + action + searchPostfix + "/");
        });
    };
    
    return module;
})(StarterKit.RBStoreFinder || {});

$(document).ready(function () {
    StarterKit.RBStoreFinder.load();
});
'use strict'

StarterKit.RBQuiz = (function (module) {
    module.load = function () {
        var answerCookiePrefix = "QuizAnswer";
        var quizContainer = $(".quiz-container");
        var quizId = quizContainer.attr("data-quiz-id");
        var hiddenQuestionIdInput = $("#QuestionId");

        clearQuestionsCookieStorage();

        function createCookie(name, value, hours) {
            var expires;

            if (hours) {
                var date = new Date();
                date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            } else {
                expires = "";
            }
            document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = encodeURIComponent(name) + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }

        function clearQuestionsCookieStorage() {
            var cookies = document.cookie.split(";");
            for (var i = 0; i < cookies.length; i++) {
                var cookieName = cookies[i].split("=")[0];
                if (cookieName.indexOf(answerCookiePrefix) !== -1)
                    eraseCookie(cookieName.trim());
            }
        }

        function StoreAnswer(questionId) {
            createCookie(answerCookiePrefix + questionId, $("input[name=" + questionId + "]:checked").map(function (_, el) {
                return $(el).val();
            }).get(), 1);
        }

        function RenderQuestion(data) {
            hiddenQuestionIdInput.val(data.QuestionId);

            $(".question-description").text(data.QuestionDescription);
            $(".question-content").html(null);

            if (data.Type === "RBStarterKitQuizSingleChoiceAnswer") {
                $.each(data.Answers,
                    function (index, element) {
                        $(".question-content").append('<label> <input type="radio" name="' + data.QuestionId + '" value="' + element.Key + '" /> ' + (element.ImagePath !== null ? '<img class="question-image" src="' + element.ImagePath + '" />' : '') + '<span>' + element.Value + '</span></label>');
                    });

                SelectAnswer(data.QuestionId);
            } else {
                $.each(data.Answers,
                    function (index, element) {
                        $(".question-content").append('<label> <input type="checkbox" name="' + data.QuestionId + '" value="' + element.Key + '" /> ' + (element.ImagePath !== null ? ' <img class= "question-image" src = "' + element.ImagePath + '" /> ' : '') + '<span>' + element.Value + '</span></label>');
                    });

                SelectAnswer(data.QuestionId);
            }
        }

        function SelectAnswer(questionId) {
            var storedAnswerKeys = readCookie(answerCookiePrefix + questionId);

            if (storedAnswerKeys) {
                var answerKeys = storedAnswerKeys.split(',');
                var answerInputs = $("input[name=" + questionId + "]");

                $.each(answerKeys, function (answerIndex, answerKey) {
                    answerInputs.filter(function (index) {
                        return $(this).val() == answerKey;
                    }).prop("checked", true);
                });
            }
        }

        function ShowThankYouPage() {
            $.ajax({
                url: "/umbraco/api/quiz/getthankyoupagecontent?quizId=" + quizId
            })
            .done(function (data) {
                if (data) {
                    $(".quiz-thank-you-page").html(data.Content);
                }
            })
            .always(function () {
                quizContainer.addClass("hidden");
                $(".quiz-thank-you-page").removeClass("hidden");

                clearQuestionsCookieStorage();
            });
        }

        $("#NextQuestion").click(function () {
            var questionId = hiddenQuestionIdInput.val();

            if ($("input[name=" + questionId + "]:checked").length === 0) {
                $(".question-validation-" + questionId).text("Please select your answer.");

                return;
            } else {
                $(".question-validation-" + questionId).text("");
            }

            StoreAnswer(questionId);

            $.ajax({
                url: "/umbraco/api/quiz/getnextquestion?quizId=" + quizId + "&currentQuestionId=" + questionId
            })
            .done(function (data) {
                if (data) {
                    RenderQuestion(data);
                }
                else {
                    ShowThankYouPage();
                }
            });
        });

        $("#PreviousQuestion").click(function () {
            var questionId = hiddenQuestionIdInput.val();

            StoreAnswer(questionId);

            $.ajax({
                url: "/umbraco/api/quiz/getpreviousquestion?quizId=" + quizId + "&currentQuestionId=" + questionId
            })
            .done(function (data) {
                if (data) {
                    RenderQuestion(data);
                }
            });
        });

        $("#FinishQuiz").click(function () {
            var validationResults = [];
            $("input[type=hidden][name='QuestionId']").each(function () {
                var questionId = $(this).val();

                if ($("input[name=" + questionId + "]:checked").length === 0) {
                    $(".question-validation-" + questionId).text("Please select your answer.");
                    validationResults.push(false);
                    return;
                } else {
                    $(".question-validation-" + questionId).text("");
                    validationResults.push(true);
                }

                StoreAnswer(questionId);
            });

            if (!validationResults.includes(false)) {
                ShowThankYouPage();
            }
        });
    };

    return module;
})(StarterKit.RBQuiz || {});

$(document).ready(function () {
    StarterKit.RBQuiz.load();
});
$(document).ready(function () {
    function initializeSubmenu() {
        var element = $(this);
        var subMenu = $('ul', element);
        var isSubmenuLoaded = subMenu.hasClass('loaded');

        if (!isSubmenuLoaded) {
            var nodeId = element.data('nodeId');
            var parentUrl = element.data('nodeUrl');
            var sublevelImages = element.data('sublevelImage');
            var showAll = element.data('showAll');

            $.ajax({
                type: 'GET',
                url: '/umbraco/api/NavigationApi/GetNextLevel',
                data: { nodeId: nodeId, sublevelImages: sublevelImages },
                success: function (data) { fillSublevel(data, subMenu, parentUrl, showAll); }
            });
        }
    }

    function fillSublevel(data, subMenu, parentUrl, showAll) {
        subMenu.addClass('loaded');

        if (showAll === 'True')
            subMenu.prepend('<li class="nav-list-item sk-show-all"><a href="' + parentUrl + '"><span>Show All</span></a></li>');

        $.each(data, function (index, element) {
            subMenu.append(getLink(element));
        });

        $('li.loading', subMenu).remove();
    }

    function getLink(link) {
        return '<li class="nav-list-item"><a href="' + link.url
            + '"><span>' + (link.imageUrl != null && link.showImagesInSublevels ? '<img src="' + link.imageUrl + '"/>' : '')
            + link.name + '</span></a></li>';
    }

    $('.sk-sidebar-menu .sk-sidebar-main-links .nav-list-item.dropdown').click(initializeSubmenu);
});
$(document).ready(function () {
    StarterKit.Membership = StarterKit.Membership || {
        InitializeMemberPanel: function (memberPanel) {
            $('.logout-link', memberPanel).click(function () {
                $.get('/umbraco/api/membershipApi/logout', function (result) {
                    if (result.success) {
                        window.location.reload();
                        return;
                    }

                    console.error(result.message);
                });
            });
        },
        LORP: {
            GetQueryStringValue: function (key) {
                var url = new URL(window.location.href);
                if (url.searchParams.has(key))
                    return url.searchParams.get(key);

                return '/';
            },
            GetCurrentSection: function () {
                var section = location.hash.slice(1);
                if (!section)
                    section = 'sing-up';

                return section;
            },
            SetSection: function () {
                var section = StarterKit.Membership.LORP.GetCurrentSection();

                $('#sign-up-in > div[class*=sign-]').hide();
                $('#sign-up-in > .' + section).show();
            },
            ToggleMustMatchClass: function (objectArray, enable) {
                var mustMatchClassName = 'must-match';
                objectArray.map(function (element, index) {
                    if (enable)
                        $(element).addClass(mustMatchClassName);
                    else
                        $(element).removeClass(mustMatchClassName);
                });
            },
            Initialize: function (loginOrRegisterPage) {
                $(window).on('hashchange', StarterKit.Membership.LORP.SetSection);
                $('.password-match', loginOrRegisterPage).submit(function ($event) {
                    var firstelement;
                    var $this = $(this);
                    var passwordMatchError = $this.children(".password-match-error");

                    passwordMatchError.hide();

                    $this.children("input[type='password']").map(function (index, element) {
                        if (!firstelement) {
                            firstelement = element;
                        } else {
                            if (element.value !== firstelement.value) {
                                StarterKit.Membership.LORP.ToggleMustMatchClass([element, firstelement], true);
                            }
                            else {
                                StarterKit.Membership.LORP.ToggleMustMatchClass([element, firstelement], false);
                            }
                        }
                    });
                    if ($this.children("input.must-match").length) {
                        $event.preventDefault();
                        passwordMatchError.show();
                    }
                });
                //        Replace standard browser-based checkbox with checkbox facade with RB colors.
                // This script is required for "remember me" checkbox in sign-in form.
                $('.form-check').each(function () {
                    $(this).after('<div class="form-check-select"></div>');
                });
                $('.form-check-select').on('click', function () {
                    $(this).toggleClass('checked').prev().prop('checked', $(this).is('.checked'))
                });
                // Label animation for inputs. This script is required for sign-in and sign-up forms.
                //        Replace standard browser-based checkbox with checkbox facade with RB colors.
                // This script is required for "remember me" checkbox in sign-in form. Version for umbraco.
                var d = $('#cdc-form div.checkbox').add($('div.form-group > div')),
                    l = d.children('label'),
                    c = $('input:checkbox'),
                    a = $('label > a');
                d.find(l).each(function () {
                    $(this).children('input').prependTo($(this).parent(d));
                });
                d.find(c).each(function () {
                    var name = $(this).attr('name');
                    $(this).attr('id', name);
                    $(this).next('label').attr('for', name);
                });

                var signUpForm = $('.sign-up form');
                if (signUpForm) {
                    var cdsUniqEmailField = $('input[type="email"][name*="Form["]', signUpForm)[0];

                    $('#login-email', signUpForm).on('change keyup', function (event) {
                        if (cdsUniqEmailField) {
                            cdsUniqEmailField.value = $(this).val();
                        }
                    });

                    $('.cdc-image-upload').on('change', (event) => {
                        prepareImage(event.target);
                    });

                    $('.input-group.date').datepicker({
                        format: 'yyyy-mm-dd',
                        forceParse: false
                    });
                    $('.js-forms-selectbox').selectpicker();
                    $('[data-toggle="cdc-tooltip"]').tooltip();
                    $(".cdc-checkbox").change(function () {
                        $this = $(this);
                        if ($this.is(':checked')) {
                            $this.val('true');
                        } else {
                            $this.val('false');
                        }
                    });

                    $(cdsUniqEmailField).parent('.cdc-field-container').hide();

                    signUpForm.on('submit', function (event) {
                        event.preventDefault();
                        $.post('/umbraco/api/membershipApi/register', $(this).serialize(), function (result) {
                            if (!result.success) {
                                var errorField = $('.sk-membership-error', signUpForm);

                                errorField.text(result.message);
                                errorField.show(300);
                                setTimeout(() => errorField.hide(200), 3000);

                                return;
                            }
                            else {
                                $('.cdc-form-group, .lds-legal-agreement, .form-content', signUpForm).hide(200);
                                $('.cdc-form-thank-you-group', signUpForm).removeClass('hidden');
                            }
                        });
                    });
                }
                var signInForm = $('.sign-in form');
                var signInError = {
                    notification: $('.sk-membership-error'),
                    show: function () {
                        this.notification.show(300);
                        setTimeout(() => this.hide(), 5000);
                        $('input[type=email]').addClass('error');
                        $('input[type=password]').addClass('error');
                    },
                    hide: function () {
                        this.notification.hide();
                        $('input[type=email]').removeClass('error');
                        $('input[type=password]').removeClass('error');
                    }
                }
                signInForm.on('submit', function (event) {
                    event.preventDefault();
                    signInError.hide();
                    $.post('/umbraco/api/membershipApi/login', $(this).serialize(), function (result) {
                        if (!result.success) {
                            signInError.show();
                            return;
                        }

                        window.location.href = StarterKit.Membership.LORP.GetQueryStringValue("returl");
                    });
                });

                StarterKit.Membership.LORP.SetSection();
            }
        },
        Initialize: function () {
            var memberPanel = $('#member-panel');
            var loginOrRegisterPage = $('#sign-up-in');

            if (memberPanel.length > 0)
                StarterKit.Membership.InitializeMemberPanel(memberPanel);

            if (loginOrRegisterPage.length > 0)
                StarterKit.Membership.LORP.Initialize(loginOrRegisterPage);
        }
    };

    StarterKit.Membership.Initialize();
});
var toBase64 = function (file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

var prepareImage = function (imageInput) {
    if (imageInput.files.length) {
        toBase64(imageInput.files[0]).then(function (base64string) {
            $('#' + $(imageInput).attr('data-related-hidden')).val(base64string);
        });
    }
}

var RBConsumerDataCapture = RBConsumerDataCapture || {
    begin: function () {
        //todo: GR to style loading/sending process
        $('.cdc-error-summary').html('');
        $('#cdc-form-container').fadeTo(0, 0.5);
    },
    failure: function (error) {
        $('.cdc-error-summary').html('<div class="validation-summary-errors"><ul><li>' + $(".cdc-error-summary").data("default-error-message") || error.statusText + '</li></ul></div>');
        $('.input-group.date').datepicker({
            format: 'yyyy-mm-dd',
            forceParse: false
        });
    },
    complete: function (result) {
        if (result.status === 403) {
            //captcha response
            result.responseJSON = true;
            result.responseJSON.Status = 1;
            result.ValidationResult =
                [{
                    Message: $('.cdc-error-summary').data('captcha-invalid')
                }];
        }
        if (result.responseJSON && result.responseJSON.Status !== 0) {
            console.log(result.Status);
            if (!result.ValidationResult) {
                result.ValidationResult = [{
                    Message: $('.cdc-error-summary').data('default-error-message')
                }];
            }
            var cdcValidationResult = '<div class="validation-summary-errors"><ul>';
            $.each(result.ValidationResult, function (index, value) {
                cdcValidationResult += '<li>' + value.Message + '</li>';
            });
            cdcValidationResult += '</ul></div>';
            $('.cdc-error-summary').html(cdcValidationResult);
            $('.input-group.date').datepicker({
                format: 'yyyy-mm-dd',
                forceParse: false
            });
        } else {

            $('#cdc-form-container').fadeTo(0, 1);

            if ($('#cdc-form').length > 0) {
                RBConsumerDataCapture.ValidationSettings.update();
                if ($('.validation-summary-errors').length > 0) {
                    var $checkBoxesChecked = $('input.cdc-checkbox.true');
                    $checkBoxesChecked.prop('checked', true);
                    $checkBoxesChecked.trigger('change');
                } else {
                    $(".cdc-form-group-advanced-main").addClass("hidden");
                    $(".cdc-form-group--submit").addClass("hidden");
                    $(".cdc-form-thank-you-group").removeClass("hidden");
                }
            }
        }
        $('#form0').attr('action', $('#form0').attr('action') + '&currentPage=' + result)
    }
}
var checkboxColumnPicker = function () {
    if ($('.cdc-form-group--addresses-and-id > div.cdc-field-container').length) {
        $('.cdc-form-group--addresses-and-id').append($('#MarketOptIn').closest('.cdc-field-container'))
        $('.cdc-form-group--addresses-and-id').append($('#BrandOptIn').closest('.cdc-field-container'))
    }
}
var invalidLength = 0,
    s = '.cdc-error > span',
    v = 'field-validation-valid',
    e = 'field-validation-error';
var validation = {
    dropdownRequired: function (target) {
        var ancestorTarget = target.parent().parent();
        var validationElement = ancestorTarget.find(s);
        var validationRequiredElement = ancestorTarget.find(s + '.validation-required');

        if ($(target).val() == "") {
            validationElement.attr('style', 'display:none');
            validationRequiredElement.attr('style', '');
            validationRequiredElement.removeClass(v);
            validationRequiredElement.addClass(e);
            return false;
        } else {
            validationElement.attr('style', 'display:none');
            validationElement.removeClass(e);
            validationElement.addClass(v);
            return true;
        }
    },
    imageUpload: function (target) {
        var allowedFileTypes = ["image/gif", "image/tif", "image/tiff", "image/jpg", "image/jpeg", "image/jif", "image/jfif", "image/png"];
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationSizeElement = ancestorTarget.find(s + '.validation-size');
        var validationFormatElement = ancestorTarget.find(s + '.validation-format');

        var currentElement = target[0];
        if (currentElement !== undefined) {
            var currentElementFile = currentElement.files[0];
            if (currentElementFile !== undefined) {
                if (currentElementFile.size < 2097152) {
                    if (allowedFileTypes.indexOf(currentElementFile.type) > -1) {
                        validationElement.attr('style', 'display:none');
                        validationElement.removeClass(e);
                        validationElement.addClass(v);
                        return true;
                    } else {
                        validationElement.attr('style', 'display:none');
                        validationFormatElement.attr('style', '');
                        validationFormatElement.removeClass(v);
                        validationFormatElement.addClass(e);
                        return false;
                    }
                } else {
                    validationElement.attr('style', 'display:none');
                    validationSizeElement.attr('style', '');
                    validationSizeElement.removeClass(v);
                    validationSizeElement.addClass(e);
                    return false;
                }
            }
        }
    },
    valueMissingMsg: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationRequiredElement = ancestorTarget.find(s + '.validation-required');

        validationElement.attr('style', 'display:none');
        validationRequiredElement.attr('style', '');
        validationRequiredElement.removeClass(v);
        validationRequiredElement.addClass(e);
        return false;
    },
    lenghtMsg: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationLengthElement = ancestorTarget.find(s + '.validation-lenght');

        validationElement.attr('style', 'display:none');
        validationLengthElement.attr('style', '');
        validationLengthElement.removeClass(v);
        validationLengthElement.addClass(e);
        return false;
    },
    rangeOverflowMsg: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationMaxElement = ancestorTarget.find(s + '.validation-max');

        validationElement.attr('style', 'display:none');
        validationMaxElement.attr('style', '');
        validationMaxElement.removeClass(v);
        validationMaxElement.addClass(e);
        return false;
    },
    rangeUnderflowMsg: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationMinElement = ancestorTarget.find(s + '.validation-min');

        validationElement.attr('style', 'display:none');
        validationMinElement.attr('style', '');
        validationMinElement.removeClass(v);
        validationMinElement.addClass(e);
        return false;
    },
    typeMismatchMsg: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);
        var validationMismatchElement = ancestorTarget.find(s + '.validation-mismatch');

        validationElement.attr('style', 'display:none');
        validationMismatchElement.attr('style', '');
        validationMismatchElement.removeClass(v);
        validationMismatchElement.addClass(e);
        return false;
    },
    isValid: function (target) {
        var ancestorTarget = target.parent();
        var validationElement = ancestorTarget.find(s);

        validationElement.attr('style', 'display:none');
        validationElement.removeClass(e);
        validationElement.addClass(v);
        return true;
    },
    validateInput: function (target) {
        if (target.classList.contains('cdc-dropdown')) {
            if (!target.classList.contains('bootstrap-select') && target.attributes.required) {
                return validation.dropdownRequired($(target));
            }
        } else if (target.classList.contains('cdc-image-upload')) {
            return validation.imageUpload($(target));
        } else if (target.validity.rangeOverflow) {
            return validation.rangeOverflowMsg($(target));
        } else if (target.validity.rangeUnderflow) {
            return validation.rangeUnderflowMsg($(target));
        } else if (target.validity.tooLong || invalidLength == true) {
            return validation.lenghtMsg($(target));
        } else if (target.validity.typeMismatch) {
            return validation.typeMismatchMsg($(target));
        } else if (target.validity.valueMissing) {
            return validation.valueMissingMsg($(target));
        } else if (target.validity.valid) {
            return validation.isValid($(target));
        }
    }
}
RBConsumerDataCapture.ValidationSettings = RBConsumerDataCapture.ValidationSettings || {
    init: function () {
        $(document).ready(function () {
            checkboxColumnPicker();
            RBConsumerDataCapture.ValidationSettings.update();

            $('.cdc-image-upload').on('change', (event) => {
                prepareImage(event.target);
            });

            $('.input-group.date').datepicker({
                format: 'yyyy-mm-dd',
                forceParse: false
            });
            $('.js-forms-selectbox').selectpicker();
            $('[data-toggle="cdc-tooltip"]').tooltip();
            $(".cdc-checkbox").change(function () {
                $this = $(this);
                if ($this.is(':checked')) {
                    $this.val('true');
                } else {
                    $this.val('false');
                }
            });
            $('.forms-custom-validation').on('change', function (event) {
                var maxLength = parseInt($(event.target).attr("data-val-length-max"));
                var minLength = parseInt($(event.target).attr("data-val-length-min"));
                if (!maxLength)
                    maxLength = parseInt($(event.target).attr("maxlength"));
                if (!minLength)
                    minLength = parseInt($(event.target).attr("minLength"));
                if ($(this).val().length > maxLength || $(this).val().length < minLength) {
                    invalidLength = true;
                } else {
                    invalidLength = false;
                }
                validation.validateInput(event.target);
            });
            $('#cdc-form').on('submit', function (e) {
                e.preventDefault();
                var isFormValid = true;
                $.each($('.forms-custom-validation'), function (index, value) {
                    var validationResult = validation.validateInput(value);
                    if (validationResult == false) {
                        isFormValid = false;
                    }
                });

                $.each($('.js-forms-selectbox'), function (index, value) {
                    var validationResult = validation.validateInput(value);
                    if (validationResult == false) {
                        isFormValid = false;
                    }
                });

                if (isFormValid == false) {
                    return false;
                }

            });
        });
    },
    update: function () {
        var validator = RBConsumerDataCapture.ValidationSettings.get()
        validator.settings.highlight = function (el, error, valid) {
            var closestFormGroup = $(el).closest(".form-group");
            var closestCdcFieldContainer = $(el).closest(".cdc-field-container");

            if (closestFormGroup.length > 0) {
                closestFormGroup.addClass("has-error");
            }

            if (closestCdcFieldContainer.length > 0) {
                closestCdcFieldContainer.addClass("has-error");
            }
        };
        validator.settings.unhighlight = function (el, error, valid) {
            var closestFormGroup = $(el).closest(".form-group");
            var closestCdcFieldContainer = $(el).closest(".cdc-field-container");

            if (closestFormGroup.length > 0) {
                closestFormGroup.removeClass("has-error");
            }

            if (closestCdcFieldContainer.length > 0) {
                closestCdcFieldContainer.removeClass("has-error");
            }
        };
        $('.input-group.date').datepicker({
            format: 'yyyy-mm-dd',
            forceParse: false
        });
        $('#cdc-form').validate({
            ignore: '.ignoreField'
        });
        update();
    },
    get: function () {
        var form = $("#cdc-form");
        if ((typeof form.data('validator')).toString() !== 'undefined') {
            //return the validator
            return form.data('validator');
        }
        //recreate the validator
        form.data("unobtrusiveValidation", null);
        form.data("validator", null);
        $.validator.unobtrusive.parse(form);
        return form.data('validator');
    }
}
$(document).ready(function () {
    if ($("#cdc-form").length) {
        RBConsumerDataCapture.ValidationSettings.init();
        $(".js-forms-selectbox").change(function (e) {
            let selectValues = "";
            if ($(e.target).attr('multiple') && $(e.target).val()) {
                selectValues = $(e.target).val().join(',');
            } else {
                selectValues = $(e.target).val();
            }
            $(this).closest('.cdc-field-container').find('.selectbox-value').val(selectValues);
        });
    }
});

function update() {
    $('.advanced-cdc-conditional-checkbox,.advanced-cdc-checkbox').on('change', function () {
        var $this = $(this);
        var $checkBox = $this.find('.cdc-checkbox');
        var $checkBoxHiddenValue = $this.find('.cdc-checkbox-hidden');
        var $conditionalContainer = $this.siblings('.conditionalContainer');
        if ($checkBox.is(':checked')) {
            if ($conditionalContainer.length) {
                $conditionalContainer.removeClass('hidden');
                $conditionalContainer.find('input.form-control').removeClass('ignoreField');
            }
            $checkBoxHiddenValue.val('true');
        } else {
            if ($conditionalContainer.length) {
                $conditionalContainer.addClass('hidden');
                $conditionalContainer.find('input.form-control').addClass('ignoreField');
                $conditionalContainer.find('.input-group.date input.form-control').datepicker('setDate', null);
                $conditionalContainer.find('input.form-control[type=text], input.form-control[type=number]').val('');
            }
            $checkBoxHiddenValue.val('false');
        }
    });
}
$(function ($) {
    $.validator.addMethod('date', function (value, element) {
        if (this.optional(element) && !value) return true;
        try {
            //Datepicker format: yyyy-mm-dd
            var matches = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
            if (matches == null) return false;
            var y = matches[1];
            var m = matches[2] - 1;
            var d = matches[3];
            var date = new Date(y, m, d);
            return date.getFullYear() == y && date.getMonth() == m && date.getDate() == d;
        } catch (ex) {
            return false;
        }
    });
    $.validator.addMethod('customcheckbox', function (value, element) {
        if ($(element).is(':checked')) {
            return true;
        } else {
            return false;
        }
    });
});
/*
 * Visual Profile Builder Result Page
 * Functions that are specific to the visual profile builder page
 */


$(document).ready(function () {

    init();
    checkActiveCarousel();
    initChannelSight();


    $('.sk-other-products-slider a').on('click', function () {
        init();
    });
    if ($('.vpb-result-other-products-slider').length > 0) {
        $(document).ajaxSuccess(function (event, xhr, settings) {
            checkActiveCarousel();
        });
    }

});

var checkActiveCarousel = function () {
    $('.sk-other-product-slider-item').each(function () {
        var that = $(this);
        that.removeClass('active-carousel');
        if (that.attr('data-id') == $('.sk-product-slider-container').attr('data-id')) {
            that.addClass('active-carousel');
        }
    });
}
var init = function () {


    // init main products owl Carousel
    var owlCarousel = $('.owl-carousel.sk-product-slider').owlCarousel({
        loop: false,
        nav: true,
        slideBy: 3,
        responsive: {
            0: {
                items: 1
            },
            480: {
                items: 2
            },
            768: {
                items: 2
            },
            992: {
                items: 3
            }
        }
    });

    // Force rendering carousel items after window resize (hack for chrome)
    owlCarousel.on('resize.owl.carousel', function () {
        $('.owl-stage-outer').css('display', 'inline-block');
        $('.owl-nav').removeClass('disabled');
        setTimeout(function () { $('.owl-stage-outer').css('display', ''); }, 0);
    });

    owlCarousel.on('translate.owl.carousel', function () {
        $('.owl-nav').removeClass('disabled');
    });
    owlCarousel.on('translated.owl.carousel', function () {
        $('.owl-nav').removeClass('disabled');
    });

    // init other products owl Carousel
    var responsive = {};
    var lenght = 3;
    if ($('.sk-other-products-slider .sk-other-product-slider-item').length < 3) {
        length = $('.sk-other-products-slider .sk-other-product-slider-item').length;
        responsive = {
            0: {
                items: 1
            },
            768: {
                items: 2
            }
        }
    } else {
        responsive = {
            0: {
                items: 2
            },
            768: {
                items: 3
            }
        }
    }

    var otherOwlCarousel = $('.sk-other-products-slider .owl-carousel').owlCarousel({
        loop: false,
        nav: true,
        responsive: responsive
    });

    // Force rendering carousel items after window resize (hack for chrome)
    otherOwlCarousel.on('resize.owl.carousel', function () {
        $('.owl-nav').removeClass('disabled');
        $('.owl-stage-outer').css('display', 'inline-block');
        setTimeout(function () { $('.owl-stage-outer').css('display', ''); }, 0);
    });

    otherOwlCarousel.on('translate.owl.carousel', function () {
        $('.owl-nav').removeClass('disabled');
    });
    otherOwlCarousel.on('translated.owl.carousel', function () {
        $('.owl-nav').removeClass('disabled');
    });

    $('.owl-nav').removeClass('disabled');
}

function initChannelSight() {


    $('body').on('click', '.sk-channelsight-buy-now-btn', function () {

        var data = $(this);

        var baseUrl = data.attr('data-baseurl');
        var currency = data.attr('data-currency');
        var gtin = data.attr('data-gtin');
        var inStock = data.attr('data-in-stock');
        var outStock = data.attr('data-out-of-stock');
        var language = data.attr('data-language');
        var country = data.attr('data-country');
        var logoOnly = data.attr('data-logoOnly') === "" ? "False" : data.attr('data-logoOnly');
        var headerText = data.attr('data-headerText');
        var hidePrice = data.attr('data-hide-price') === "" ? "False" : data.attr('data-hide-price');
        var hideStock = data.attr('data-hide-stock') === "" ? "False" : data.attr('data-hide-stock');
        var error = data.attr('data-error');

        $.ajax(
		{
		    type: 'GET',
		    url: '/Umbraco/Api/ChannelSightApi/GetProductDetails',
		    data:
			{
			    baseUrl: baseUrl,
			    productid: gtin,
			    country: country,
			    language: language
			},
		    success: function (data) {
		        var response = $.parseJSON(data);
		        console.log(response);
		        var htmlBuilder = "";
		        if (response.status === "OK") {
		            htmlBuilder = '<div class="sk-channelsight__header">' + headerText + '</div>';
		            for (var i = 0; i < response.dealers.length; i++) {
		                var dealer = response.dealers[i];
		                var cleanPrice = dealer.product.price.replace(/[^\d.]/g, '');
		                var price = parseFloat(cleanPrice).toFixed(2);
		                htmlBuilder += '<div class="sk-dealer' + ((logoOnly === 'True') ? ' sk-dealer--logoonly' : '') + '">';
		                htmlBuilder += '<div class="sk-dealer__logo-container">';
		                htmlBuilder += '<a target="_blank" href="' + dealer.product.buyurl + '">';
		                htmlBuilder += '<img class="sk-dealer__logo" src="' + dealer.logourl + '">';
		                htmlBuilder += '</div>';
		                htmlBuilder += '<div class="sk-dealer__body">';
		                if (logoOnly !== 'True')
		                    htmlBuilder += '<h5 class="sk-dealer__name">' + dealer.name + '</h5>';
		                if ((hidePrice === 'False') && (price !== "NaN") && (logoOnly === 'False'))
		                    htmlBuilder += '<div class="sk-dealer__price">' + currency + price + '</div>';
		                if ((hideStock === 'False') && (logoOnly === 'False'))
		                    htmlBuilder += '<div class="sk-dealer__stock">' + (dealer.product.availability === 'YES' ? inStock : (dealer.product.availability == 'NO' ? outStock : checkStock)) + '</div>';
		                htmlBuilder += '</a></div>';
		                htmlBuilder += '</div>';
		            }

		            // Remove loader gif and append data
		            $('.sk-channelsight__loader').remove();
		            $(".sk-channelsight").append(htmlBuilder);
		        } else {
		            htmlBuilder = error;
		        }

		        $.magnificPopup.open({
		            type: 'inline',
		            items:
					{
					    src: '<div class="white-popup sk-channelsight">' + htmlBuilder + '</div>'
					}
		        });
		    }
		});

    });
};
/*
 * Iframe Page
 * Functions that are specific to the iframe page
 */

var IframePage = IframePage || {
    Hosts: [],
    GetIframeByIndex: function (idx) {
        var iframe = document.getElementsByTagName('iframe')[idx];
        return iframe;

    },
    Resize: function (iframe, height) {
        try {
            if (iframe) {
                iframe.height = height;
            }
        }
        catch (e) {
            console.log(e.message);
        }
    },
    ReceiveMessage: function (evt) {
        var idx = IframePage.Hosts.indexOf(evt.origin);
        if (idx > -1) {
            var data = evt.data;
            if (data.hasOwnProperty('skFrameResize')) {
                var iframe = IframePage.GetIframeByIndex(idx);
                IframePage.Resize(iframe, evt.data.skFrameResize);
            }
        }
    },
    BindSameDomainFrameResize: function () {
        $('iframe').load(function (event) {
            IframePage.Resize(event.target, event.target.contentWindow.document.body.scrollHeight);
        });
    }
};
/*
 * Partner Campaign
 */


$(document).ready(function () {
    // toggle nav (used on mobile)
    $('.js-pc-nav-toggle').on('click', function (e) {
        $(this).closest('.pc-nav-group').toggleClass('is-open');
        return false;
    });
    // hide nav when nav item clicked
    $('.js-pc-nav-hide').on('click', function (e) {
        $(this).closest('.pc-nav-group').removeClass('is-open');
    });


    $(".js-quote-text").fitText();
    $(".js-pc-description-title").fitText(0.7);




    //$('.js-scroll-to').on('click', function () {
    //    var target = $(this).attr('href');

    //    $('html, body').animate({ scrollTop: $(target).offset().top - resultNavHeight + 1 }, 400);
    //    return false;
    //});

    $('.js-pc-overlay').on('mousedown', function () {
        $(this).addClass('is-hidden');
    });

    /* Nav Related
     * Scrollspy/Affix/scrollTo
     **/
    (function () {
        var $body = $('body');
        var scrollTimeout;
        var sections = $('.pc-section');
        var subSections = $('.pc-section__sub, .pc-prod-section');
        var players = $('.pc-player');

        var lastScrollPos = 0;
        // caches
        var highlightTimeout;
        var lastSectionId;

        function updateNav() {
            var currentScroll = $(this).scrollTop();
            var currentSection;
            var currentSubsection;
            var windowHeight = $(window).height();
            var windowBottom = currentScroll + windowHeight;



            sections.each(function () {
                // divPosition is the position down the page in px of the current section we are testing      
                var divPosition = $(this).offset().top;

                // If the divPosition is less the the currentScroll position the div we are testing has moved above the window edge.
                // the -1 is so that it includes the div 1px before the div leave the top of the window.
                if (divPosition < (currentScroll + windowHeight / 2) && (currentScroll + windowHeight / 2) < (divPosition + $(this).outerHeight())) {
                    // We have either read the section or are currently reading the section so we'll call it our current section
                    currentSection = $(this);

                    //console.log(currentSection.data('item-number'));

                    // update scroll number
                    $('.pc-scroll-report__number').text(currentSection.data('item-number'));

                    // If the next div has also been read or we are currently reading it we will overwrite this value again. This will leave us with the LAST div that passed.


                    // This is the bit of code that uses the currentSection as its source of ID
                    var id = currentSection.attr('id');
                    if (id !== lastSectionId) {
                        clearTimeout(highlightTimeout);
                        $('.pc-nav-link').removeClass('is-active is-highlighted');
                        $(".pc-nav-link[href=#" + id + "]").addClass('is-active');
                        if ($('.pc-nav-link:hover').length < 1) { //checks nav is not already being hovered over
                            $(".pc-nav-link[href=#" + id + "]").addClass('is-active is-highlighted');
                            highlightTimeout = setTimeout(function () {
                                $(".pc-nav-link[href=#" + id + "]").removeClass('is-highlighted');
                            }, 3000);
                        }
                        lastSectionId = id;
                    }

                }
            });

            subSections.each(function () {
                // divPosition is the position down the page in px of the current section we are testing      
                var divPosition = $(this).offset().top;

                // If the divPosition is less the the currentScroll position the div we are testing has moved above the window edge.
                // the -1 is so that it includes the div 1px before the div leave the top of the window.
                if (divPosition < (currentScroll + windowHeight / 2) && (currentScroll + windowHeight / 2) < (divPosition + $(this).outerHeight())) {
                    // We have either read the section or are currently reading the section so we'll call it our current section
                    currentSubsection = $(this);
                    // This is the bit of code that uses the currentSection as its source of ID
                    var modifyNav = currentSubsection.data('nav-modify');

                    //note: true will come through as string
                    if (modifyNav == "True") {
                        $('.pc-nav-group').addClass('pc-nav-group--modified')
                    }
                    else {
                        $('.pc-nav-group').removeClass('pc-nav-group--modified')
                    }

                }
            });

            // nav modifications on mobile
            if (currentScroll == 0) {
                //if at top add 'top' class
                $('.pc-nav-group').addClass('pc-nav-group--at-top')
            }
            else {
                $('.pc-nav-group').removeClass('pc-nav-group--at-top')
            }


            if (currentScroll > lastScrollPos) {
                // then scrolling down and should shrink nav
                $('.pc-nav-group').addClass('pc-nav-group--shrunk')
            }
            else {
                // scrolling up and shoudl grow nav
                $('.pc-nav-group').removeClass('pc-nav-group--shrunk')
            }

            // update the lastScrollPos last
            lastScrollPos = currentScroll;

        }
        //run once
        updateNav();
        // then bind to run on scroll
        $(document).on('scroll', throttle(updateNav, 200));

        //$(document).one('scroll', function () {
        //    $('.pc-scroll-instructions').addClass('is-hidden');
        //});

        $('.pc-nav-link').on('mouseover', function () {
            $('.pc-nav-link').removeClass('is-highlighted');
        });

        $('.js-lazy-load').lazyload({
            effect: 'fadeIn',
            placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAA7EAAAOxAGVKw4bAAA4EmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxMTEgNzkuMTU4MzI1LCAyMDE1LzA5LzEwLTAxOjEwOjIwICAgICAgICAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgICAgICAgICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgICAgICAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgICAgICAgICAgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIj4KICAgICAgICAgPHhtcDpDcmVhdG9yVG9vbD5BZG9iZSBQaG90b3Nob3AgQ0MgMjAxNSAoTWFjaW50b3NoKTwveG1wOkNyZWF0b3JUb29sPgogICAgICAgICA8eG1wOkNyZWF0ZURhdGU+MjAxNi0wMy0yMVQwOTo1OToxNVo8L3htcDpDcmVhdGVEYXRlPgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAxNi0wMy0yMVQxMDowNDoyMlo8L3htcDpNb2RpZnlEYXRlPgogICAgICAgICA8eG1wOk1ldGFkYXRhRGF0ZT4yMDE2LTAzLTIxVDEwOjA0OjIyWjwveG1wOk1ldGFkYXRhRGF0ZT4KICAgICAgICAgPGRjOmZvcm1hdD5pbWFnZS9wbmc8L2RjOmZvcm1hdD4KICAgICAgICAgPHBob3Rvc2hvcDpDb2xvck1vZGU+MzwvcGhvdG9zaG9wOkNvbG9yTW9kZT4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+eG1wLmlpZDoxNjNkY2FiNy00MjBkLTQxYzctYTk5YS1iNTQxODQzOTM5MjA8L3htcE1NOkluc3RhbmNlSUQ+CiAgICAgICAgIDx4bXBNTTpEb2N1bWVudElEPnhtcC5kaWQ6MTYzZGNhYjctNDIwZC00MWM3LWE5OWEtYjU0MTg0MzkzOTIwPC94bXBNTTpEb2N1bWVudElEPgogICAgICAgICA8eG1wTU06T3JpZ2luYWxEb2N1bWVudElEPnhtcC5kaWQ6MTYzZGNhYjctNDIwZC00MWM3LWE5OWEtYjU0MTg0MzkzOTIwPC94bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ+CiAgICAgICAgIDx4bXBNTTpIaXN0b3J5PgogICAgICAgICAgICA8cmRmOlNlcT4KICAgICAgICAgICAgICAgPHJkZjpsaSByZGY6cGFyc2VUeXBlPSJSZXNvdXJjZSI+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDphY3Rpb24+Y3JlYXRlZDwvc3RFdnQ6YWN0aW9uPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6aW5zdGFuY2VJRD54bXAuaWlkOjE2M2RjYWI3LTQyMGQtNDFjNy1hOTlhLWI1NDE4NDM5MzkyMDwvc3RFdnQ6aW5zdGFuY2VJRD4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OndoZW4+MjAxNi0wMy0yMVQwOTo1OToxNVo8L3N0RXZ0OndoZW4+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDpzb2Z0d2FyZUFnZW50PkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE1IChNYWNpbnRvc2gpPC9zdEV2dDpzb2Z0d2FyZUFnZW50PgogICAgICAgICAgICAgICA8L3JkZjpsaT4KICAgICAgICAgICAgPC9yZGY6U2VxPgogICAgICAgICA8L3htcE1NOkhpc3Rvcnk+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjk2MDAwMC8xMDAwMDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+OTYwMDAwLzEwMDAwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjY1NTM1PC9leGlmOkNvbG9yU3BhY2U+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4xPC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjE8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/PkQDvvYAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAABNJREFUeNpi+P//PwMAAAD//wMACPwC/tOldWEAAAAASUVORK5CYII='
        });

    })();
});

function throttle(fn, threshhold, scope) {
    threshhold || (threshhold = 250);
    var last,
    deferTimer;
    return function () {
        var context = scope || this;

        var now = +new Date,
        args = arguments;
        if (last && now < last + threshhold) {
            // hold on to it
            clearTimeout(deferTimer);
            deferTimer = setTimeout(function () {
                last = now;
                fn.apply(context, args);
            }, threshhold);
        } else {
            last = now;
            fn.apply(context, args);
        }
    };
};
/*
 * Google AdSense
 * Functions that are specific to google adsense
 */
$(document).ready(function () {
    StarterKit.Product = StarterKit.Product || {
        pageOptions: {
            //stub for adsense page options
        }
    }

    /*
    * Buy onliine button
    * - Google Adsense popup trigger
    */
    $('body').on('click', '.js-buy-online', function (e) {
        var afshBlock = {
            "container": "buyonline",
            "adLoadedCallback": function (containerName, adsLoaded) {
                if (adsLoaded) {
                }
                else {
                    $('#buyonline').prepend(StarterKit.Product.noAdMessage);
                }
            },
            "width": 300,
            "height": 400
        };

        // Google Buy Online Ad Popup
        $.magnificPopup.open({
            items: {
                src: '#buy-online-lightbox',
                type: 'inline',
                closeBtnInside: true
            }
        });

        var options = StarterKit.Product.pageOptions;
        var gtin = e.currentTarget.getAttribute('data-gtin');
        options.gtin = gtin;

        _googCsa("single-product", options, afshBlock);
        return false;
    });
});


$(document).ready(function ()
{
	// Attach Validation plugin
    EnableValidation();

    //$('body').tooltip({
    //    'trigger': 'hover',
    //    'placement': 'top',
    //    'selector': '.c4c-form .form-control',
    //    'title': 'Some very long description text, Lorem ipsum dolor sit amet'
    //});

    //$('body').append('<input class="form-control apppended" type="text">');
});


function SubmitConsumerFormBegin()
{
    $("#c4c-contact-us-form").html('<div class="c4c-form__loader"></div>');
    recaptchaContainer = $("#recaptcha-container").find(".g-recaptcha");
}

function SubmitConsumerFormComplete(data)
{
	$(".js-c4c-form").hide().html(data.responseText).fadeIn("normal");
	
	// Re-Attach Validation plugin
	EnableValidation();

	// Don't reapply message controls if ticket submit confirmation is returned
	if(data.responseText.indexOf("c4c-form--ticket") > 0)
	{		
		// Attach ticket form message listeners
		updateCountdown();
		$('#message').change(updateCountdown);
		$('#message').keyup(updateCountdown);
	}

}

function EnableValidation()
{
    // Trigger event when form is loaded
    $('#c4c-contact-us-form').trigger("c4c-form:loaded");

    // Define validation patterns
    var patterns = {
        email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
        date: /[0-9]{4}-[0-9]{2}-[0-9]{2}/g,
        phone: /^[0-9 ]+$/
    };
    //$('.c4c-form__field input').click(function () {
    //    console.log($(this).val().length);
    //});
    // Define validators for different type of fields
    var c4cValidator = $('#c4c-contact-us-form').validator({
        disable: true,
        custom: {
            required: function($el){
                return $el.val();
            },
            email: function($el){
                return !$el.val() || patterns.email.test($el.val());
            },
            phone: function ($el) {
                return !$el.val() || patterns.phone.test($el.val());
            },
            maxlength: function ($el) {
                var maxlength = $el.data('maxlength');
                return !$el.val() || ($el.val().length <= maxlength)
            },
        },
        
        // Define default validation messages - we can change them depending by adding data-{VALIDATOR}-error attribute to input.
        errors: {
            required: 'This field is required',
            email: 'Enter correct email',
            date: 'Enter date with correct format (YYYY-MM-DD)',
            phone: "Please fill out this field correctly. You can use only numbers and spaces.",
            maxlength: "Please do not enter more than allowed amount of characters"
        }
    });
    $('#c4c-contact-us-form').on('submit', function (e) {
        if (e.isDefaultPrevented())
        {
        	return false;
        } 
        else 
        {
            return true;
        	// everything looks good!
        }
    });
}

function updateCountdown() {
    // 255 is the max message length
    var remaining = $("#message").attr("data-maxlength") - $('#message').val().length;
    if (remaining <= 0) {
        remaining = 0;
    }
    $('.countdown').text(remaining);
}

// Example bind 
$('#c4c-contact-us-form').on('c4c-form:loaded', function () {
    $('.c4c-datepicker .form-control').datepicker({
        format: 'yyyy-mm-dd',
        startDate: '-150y',
        startView: 2
    });
});
/*
 * Solution Finder Page
 * Functions that are specific to the visual profile builder page
 */
StarterKit.SolutionFinders = StarterKit.SolutionFinders || [];

StarterKit.SolutionFinder = function (uid,isSingle) {
    return {
        Id: uid,        
        getElementId: function (name, isSelector) {
            var id = '';
            if (isSelector) id += '#';
            id += 'sf-' + uid + '-' + name;
            return id;
        },
        Init: function () {
            $(this.getElementId('errors', true)).hide();

            var itemsSelect = document.getElementById(this.getElementId('items'));
            if (itemsSelect)
            {
                var items = this.Results.Items;
                if (itemsSelect) {

                    var option = document.createElement("option");
                    option.value = '';
                    option.text = '';
                    itemsSelect.add(option);

                    for (var prop in items) {
                        if (items.hasOwnProperty(prop)) {
                            var option = document.createElement("option");
                            option.value = prop;
                            option.text = items[prop].Name;
                            itemsSelect.add(option);
                        }
                    }

                    $(itemsSelect).selectpicker('refresh');
                    this.Bind();
                }
            }
        },
        ItemSelected: function (e) {
            var _this = e.data;
            var locationsSelect = document.getElementById(_this.getElementId('locations'));
            if (!locationsSelect) {
                return;
            }

            while (locationsSelect.firstChild) {
                locationsSelect.removeChild(locationsSelect.firstChild);
            }

            var option = document.createElement("option");
            option.value = '';
            option.text = '';
            locationsSelect.add(option);

            var hasNoLocations = true;
            var itemName = e.target.value;
            var item = _this.Results.Items[itemName];
            if (item != undefined) {
                var locations = item.Locations;
                if (locations != undefined) {
                    for (var i = 0; i < locations.length; i++) {
                        var location = locations[i];
                        option = document.createElement("option");
                        option.value = location;
                        option.text = location;
                        locationsSelect.add(option);
                    }
                    hasNoLocations = false;
                }
            }
            $(locationsSelect).prop('disabled', hasNoLocations);
            $(locationsSelect).selectpicker('refresh');
        },
        Submit: function (e) {
            var _this = e.data;
            var item = $(_this.getElementId('items', true)).val();
            var itemName = $(_this.getElementId('items', true) + ' option:selected').text();
            var location = "";
            var locationName = "";
            if (!isSingle) {
                location = $(_this.getElementId('locations', true)).val();
                locationName = $(_this.getElementId('locations', true) + ' option:selected').text();
            }
            var valid = (isSingle) ? item != '' : item != '' && location != '';
            if (!valid) {
                $(_this.getElementId('errors', true)).fadeIn(300);
                return false;
            }
            var combinedName = (item + location).replace(/\s/g, '');
            var detail = _this.Results[combinedName];
            _this.Redirect(detail, itemName, locationName);
            return false;
        },
        HasCookies: function()
        {
            var cookieEnabled = (navigator.cookieEnabled) ? true : false;

            if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
            { 
                document.cookie="testcookie";
                cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
            }
            return cookieEnabled;
        },
        SetCookie: function (url, item, location) {
            document.cookie = encodeURI('SolutionDetail=url=' + url + '&item=' + item + '&location=' + location + ';path=/');
        },
        Redirect: function (detail, item, location) {
            if (this.HasCookies()) {
                this.SetCookie(detail.Url, item, location);
                window.location.href = detail.Url;
            } else {
                window.location.href = detail.Url + '?i=' + item + '&l=' + location;
            }
        },
        Bind: function(){
            $(this.getElementId('items', true)).on('change', this, this.ItemSelected);
            $(this.getElementId('submit', true)).on('click', this, this.Submit);
        },
        Results: {

        }
    }
}

$(document).ready(function () {
    for (var i = 0; i < StarterKit.SolutionFinders.length; i++) {
        var solutionFinder = StarterKit.SolutionFinders[i];
        solutionFinder.Init();
    }
});
'use strict'

const requestTypeAttrName = 'data-type';
const initializedAttrName = 'data-pr-initialized';
const apiKeyAttrName = 'data-api-key';
const localeAttrName = 'data-locale';
const merchantIdAttrName = 'data-merchant-id';
const merchantGroupIdAttrName = 'data-merchant-group-id';
const pageIdAttrName = 'data-page-id';
const pageIdVariantAttrName = 'data-page-id-variant';
const reviewDisplayAttrName = 'data-review-display-id';
const reviewSnippetAttrName = 'data-review-snippet-id';
const reviewWriteAttrName = 'data-review-write-id';
const reviewCategoryAttrName = 'data-review-category-id';
const cssPath = '/css/power-review.css';

$(document).ready(function () {
    StarterKit.PowerReview = StarterKit.PowerReview || {
        RequestTypes: { DISPLAY: 'ProductPageDisplay', WRITE: 'ProductPageWrite', CATEGORY: 'ProductListPageCategory' },
        PowerReviewElements: [],
        LinkCollapseOnProductPage: function () {
            var containerId = 'power-review';
            var readLink = $('.pr-snippet-review-count');

            readLink.attr('role', 'button');
            readLink.attr('href', '#' + containerId);
            readLink.attr('aria-controls', containerId);
            readLink.attr('data-toggle', 'collapse');
            readLink.attr('data-parent', '#product-accordion');
            readLink.attr('aria-expanded', 'false');
        },
        OpenWriteDialog: function (page_id, page_id_variant) {
            var formUrl = '/umbraco/surface/RBStarterKitPowerReviewSurface/WriteReview'
                + '?page_id=' + page_id
                + '&page_id_variant=' + (page_id_variant ? page_id_variant : '')
                + '&node_id=' + $('body').data('node');

            $.magnificPopup.open({
                items: {
                    src: formUrl,
                    type: 'ajax',
                    closeBtnInside: true,
                    midClick: true,
                }
            });
        },
        GetProperties: function (htmlElement, type) {
            var result = {
                api_key: htmlElement.getAttribute(apiKeyAttrName),
                locale: htmlElement.getAttribute(localeAttrName),
                merchant_id: htmlElement.getAttribute(merchantIdAttrName),
                merchant_group_id: htmlElement.getAttribute(merchantGroupIdAttrName),
                page_id: htmlElement.getAttribute(pageIdAttrName),
                page_id_variant: htmlElement.getAttribute(pageIdVariantAttrName),
                style_sheet: cssPath
            };

            if (type == StarterKit.PowerReview.RequestTypes.DISPLAY) {
                result['on_write_review_click'] = () => StarterKit.PowerReview.OpenWriteDialog(result.page_id, result.page_id_variant);
                result['on_render'] = StarterKit.PowerReview.LinkCollapseOnProductPage;
                result['REVIEW_DISPLAY_SNAPSHOT_TYPE'] = 'SIMPLE';
                result['components'] = {
                    ReviewSnippet: htmlElement.getAttribute(reviewSnippetAttrName),
                    ReviewDisplay: htmlElement.getAttribute(reviewDisplayAttrName),
                };
            }
            else if (type == StarterKit.PowerReview.RequestTypes.WRITE) {
                result['return_url'] = window.location.href;
                result['components'] = {
                    Write: htmlElement.getAttribute(reviewWriteAttrName)
                };
            }
            else if (type == StarterKit.PowerReview.RequestTypes.CATEGORY) {
                result['components'] = {
                    CategorySnippet: htmlElement.getAttribute(reviewCategoryAttrName)
                };
            }

            return result;
        },
        CollectData: function (elements) {
            $.each(elements, function (index, htmlElement) {
                var elementType = htmlElement.getAttribute(requestTypeAttrName);
                var element = {
                    powerReviewObject: StarterKit.PowerReview.GetProperties(htmlElement, elementType),
                    htmlElement: htmlElement,
                    type: elementType,
                    initialized: false
                };
                StarterKit.PowerReview.PowerReviewElements.push(element);
            });
        },
        SendData: function () {
            var displayAndCategoryObjects = StarterKit.PowerReview.PowerReviewElements.filter(function (item, i) {
                if ((item.type === StarterKit.PowerReview.RequestTypes.DISPLAY || item.type === StarterKit.PowerReview.RequestTypes.CATEGORY) && !item.initialized)
                    return item;
            });
            var writeObjects = StarterKit.PowerReview.PowerReviewElements.filter(function (item, i) {
                if (item.type === StarterKit.PowerReview.RequestTypes.WRITE && !item.initialized)
                    return item;
            });

            if (displayAndCategoryObjects.length > 0) {
                var prObjs = displayAndCategoryObjects.map(function (item) { return item.powerReviewObject; });
                displayAndCategoryObjects.forEach(function (item) {
                    item.initialized = true;
                    item.htmlElement.setAttribute(initializedAttrName, '');
                });
                POWERREVIEWS.display.render(prObjs);
            }

            if (writeObjects.length == 1) {
                var item = writeObjects[0];
                item.initialized = true;
                item.htmlElement.setAttribute(initializedAttrName, '');
                POWERREVIEWS.display.render(item.powerReviewObject);
            }
            else if (writeObjects.length > 1)
                console.error('StarterKit.PowerReview.SendData: Cannot render more than one WRITE object');
        },
        RunWithProviderScript: function (callback) {
            if (typeof POWERREVIEWS == 'undefined')
                $.ajax({
                    url: 'http://ui.powerreviews.com/stable/4.0/ui.js',
                    dataType: 'script',
                    success: callback,
                    async: true
                });
            else
                callback();
        },
        Initialize: function () {
            StarterKit.PowerReview.RunWithProviderScript(function () {
                var elements = $('[data-module="PowerReview"]:not([data-pr-initialized])');
                if (!elements.length)
                    return;

                StarterKit.PowerReview.CollectData(elements);

                if (StarterKit.PowerReview.PowerReviewElements.length)
                    StarterKit.PowerReview.SendData();
            });
        },
    };

    StarterKit.PowerReview.Initialize();
});