/* An error occurred during minification, see Sitecore log for more details - returning concatenated content unminified.
 */
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\site.js
//version="2"
jQuery.fn.outerHTML = function (s) {
    return (s)
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
}

//_________________________________________
//HEADER
//_________________________________________
function changeHeaderInformation(position) {
    var newHeader = $('#block-hero .slide').eq(position).find('.slide-header').text();
    var newBody = $('#block-hero .slide').eq(position).find('.slide-body').text();
    var newCTAlink = $('#block-hero .slide').eq(position).find('.slide-cta-link').text();

    $('#block-hero .page-header .headline h1').text(newHeader);
    $('#block-hero .page-header .body span').text(newBody);
    $('#block-hero .page-header .cta a').attr('href', newCTAlink);
}

function InitializeHeaderSlider() {
    //slider nav JS
    var slider = {
        // Not sure if keeping element collections like this
        // together is useful or not.
        el: {
            slider: $("#block-hero .slider"),
            allSlides: $("#block-hero .slide"),
            sliderNav: $("#block-hero .slider-nav"),
            allNavButtons: $("#block-hero .slider-nav > a")
        },

        timing: 800,
        slideWidth: 1280, // could measure this

        // In this simple example, might just move the
        // binding here to the init function
        init: function () {
            this.bindUIEvents();
        },

        bindUIEvents: function () {
            this.el.sliderNav.on("click", "a", function (event) {
                slider.handleNavClick(event, this);
            });
            // What would be cool is if it had touch
            // events where you could swipe but it
            // also kinda snapped into place.
        },

        handleNavClick: function (event, el) {
            event.preventDefault();
            var position = $(el).attr("href").split("-").pop();

            this.el.slider.animate({
                scrollLeft: position * this.slideWidth
            }, this.timing);

            this.changeActiveNav(el);

            changeHeaderInformation(position);
        },

        changeActiveNav: function (el) {
            this.el.allNavButtons.removeClass("active");
            $(el).addClass("active");
        }
    };

    slider.init();
}

function InitializeSlider(pSlider, pAllSlides, pSliderNav, pAllNavButtons, pSlide) {
    //alert('InitializeSlider/ ' + pSlideWidth + '/' );
    //slider nav JS
    var slider = {
        el: {
            slider: pSlider,
            allSlides: pAllSlides,
            sliderNav: pSliderNav,
            allNavButtons: pAllNavButtons
        },

        timing: 400,
        slideWidth: mobileSlideWidth, // could measure this

        // In this simple example, might just move the
        // binding here to the init function
        init: function () {
            this.bindUIEvents();
        },

        bindUIEvents: function () {
            this.el.sliderNav.on("click", "a", function (event) {
                slider.handleNavClick(event, this);
            });
            // What would be cool is if it had touch
            // events where you could swipe but it
            // also kinda snapped into place.
        },

        handleNavClick: function (event, el) {
            event.preventDefault();
            var position = $(el).attr("href").split("-").pop();

            this.el.slider.animate({
                scrollLeft: position * mobileSlideWidth
            }, this.timing);

            this.changeActiveNav(el);
        },

        changeActiveNav: function (el) {
            this.el.allNavButtons.removeClass("active");
            $(el).addClass("active");
        }
    };

    slider.init();
}

//BUG #425783 - Removed unnecessary variable declarations
function displayCommentButton() {
    var mobileview = $(window).width();
    if (mobileview <= 767) {
        var commentSectionHeader = $('#displayCommentSectionHeader');
        commentSectionHeader.removeClass("commentHeader");
        commentSectionHeader.removeClass("hidden-xs");
        $('#displayCommentsButton').addClass("hidden-xs");
        $('#postCommentButton').removeClass("hidden-xs");
        $('#displayLoadMore').removeClass("hidden-xs");
        $('#commentSection').removeClass("hidden-xs");
    }
}

//BUG #425783 - Removed unnecessary variable declarations
function displayCommentSection() {
    var postacomment = $('#postacomment');
    var textSignInToPost = $('#signinToPost').html();
    //BUG #425783
    $('#postCommentButton').addClass("hidden-xs");

    //BUG #425783
    var header = $('#header');
    header.append(postacomment);

    postacomment.removeClass("hidden-xs");
    $('#displayPostACommentSection').remove(".commentHeader");
    //$('#mobileCommentsTitle').removeClass("hidden-xs");
    $('#userYourAccentureLogin').text(textSignInToPost);
}

$(window).on("load", function () {
    //prevents the modal from closing when clicking the background and hitting the keyboard
    $('.modal').modal({
        backdrop: 'static',
        keyboard: false,
        show: false
    });

    $('#main-modal').modal({
        backdrop: 'static',
        keyboard: false,
        show: false
    });

    //Bug 390596: Disables autocomplete
    $("#search-input").autocomplete({
        disabled: true
    });

    InitializeHeaderSlider();

    if ($('#accent').length > 0) {
        $("#content-wrapper div div").first().addClass("first");
    }

    $(".btn-group-country .dropdown-menu li a").on("click", function () {
        $(".btn1:first-child").text($(this).text());
        $(".btn1:first-child").val($(this).text());
    });

    $(".btn-group-state .dropdown-menu li a").on("click", function () {
        $(".btn2:first-child").text($(this).text());
        $(".btn2:first-child").val($(this).text());
    });

    $(".acn-popover .top").popover({
        placement: 'top'
    });
    $(".acn-popover .top").popover('show');

    $("[rel='tooltip']").popover({
        placement: 'top',
        html: 'true',
        title: '' +
            '<button type="button" id="close" class="close close-popover">&times;</button>',
        content: ''
    }).on('shown.bs.popover', function () {
        var $popup = $(this);
        $(this).next('.popover').find('button.close-popover').on("click", function (e) {
            $popup.popover('hide');
        });
    });;;

    document.createElement('header');
    document.createElement('section');
    document.createElement('article');
    document.createElement('aside');
    document.createElement('nav');
    document.createElement('footer');

    //Enable swiping...
    //AddSwipeToCarousel(); transferred to ui.styleCore-engine.js for now

    //Transfered function to jumplink.js

    //$(window).on("scroll", function () {
    //    var activeNav = $('li.active');
    //    var currentsection = $('li.active > a').data("jump-link-number");

    //    //if (currentsection != "0") {
    //    //    $("#block-jumplink").css("display", "block")
    //    //}
    //    //else {
    //    //    $("#block-jumplink").css("display", "none")
    //    //}

    //    $("#current-navigation").html(currentsection);
    //    $("#jump-link-headline").html(activeNav.text());
    //});

    var jumbnavcount = $("#scrollspy > ul > li").length - 1;
    $("#total-navigation").html(jumbnavcount);

    $(function () {
        InitializeBootstrapValidator();

        //Bug Fix for Bug 303345 - Page Headline and Sub-headline adjustment for docked first blocks
        if ($('.dock').length > 0) {
            $('.page-title').addClass('page-title-dock');
        }
    });

    //Fix for Bug:343313 - Webpart - Contact Us: Article Utility Control container should not be displayed.
    if ($('.placeholder').length == 0) {
        $('#toolbar-container').hide();
    } else if ($('.placeholder').length > 1 && $('.placeholder:has(.print)')) {
        //Bug 423966: Updated selector for social media sharing and how the toolbar-container is hidden for mobile and tablet resolutions.
        if ($('.social-likes_single-w').length == 0 && $('#DownloadModule').length == 0) {
            $('#toolbar-container').addClass("visible-lg");
            //if ($(window).width() <= 1024) {
            //$('#toolbar-container').hide();

            //} else { $('#toolbar-container').show(); }
        }
    }

    //Cookies Statements Alignment
    if ($('#announcement-carousel').length != 0) {
        $('#ui-wrapper').addClass('has-announcement-module');
    }
    // $('#cookie-disclaimer-long p').addClass('dotdot');

    if ($('.bottom-block-spacing').length > 0) {
        $('#ui-wrapper').addClass('has-bottom-block-spacing');
    }

    if ($('.top-block-spacing').length > 0) {
        $('#ui-wrapper').addClass('has-top-block-spacing');
    }
});

//set the callback url
$(window).on("unload", function () {
    if (typeof (Storage) !== "undefined") {
        sessionStorage.setItem("hashCallback", window.location.href);
    }
});

function closeButton() {
    $.sidr('close', 'main-menu');

    var buttoncollapse = $('.acn-icon-close');
    buttoncollapse.attr("class", "acn-icon acn-icon-nav-top-menu");
}

var activeSectionIndex = -1;

function changeHeaderSectionText(newName, newActiveCount) {
    //console.log('changeHeaderSectionText == ' + newActiveCount + 1);

    if (typeof newName != 'undefined') {
        $('#header-section-nav-text').text(newName);
        $('#activeSectionNo').text(newActiveCount + 1);
    }
}
//var fadeEffectHandler = null;

//function fadeSuccessMessage(control) {
//    //closest has-success
//    var form = $(control).closest('.has-success');

//    //check if it has one
//    if (form.length > 0) {
//        clearTimeout(fadeEffectHandler);
//        //find the success-message and animate it to fade.
//        fadeEffectHandler = setTimeout(function () {
//            form.find('.success-message').animate({ opacity: 0 }, 1400);
//        }, 100);
//    } else {
//        form.find('.success-message').css("opacity", 1);
//    }
//}

function scrollEventHandler() {
    //console.log('scrollEventHandler START');

    var screen_offset = $(window).scrollTop();
    var anchor_text_active = '';
    var anchor_index_active = -1;

    $('.block-title h2').each(function (index) {
        if (screen_offset + 100 >= $(this).offset().top) {
            anchor_text_active = $(this).text();
            anchor_index_active = index;
        }
    });

    //console.log('global.activeSectionIndex == ' + activeSectionIndex);
    //console.log('scrollEventHandler.anchor_index_active == ' + anchor_index_active);

    if (activeSectionIndex != anchor_index_active) {
        changeHeaderSectionText(anchor_text_active, anchor_index_active);
        activeSectionIndex = anchor_index_active;
    }
}

function scrollToAnchor(id) {
    //console.log('scrollToAnchor == ' + id);

    var aTag = $("#" + id);
    var newName = '';
    var scrollTop = $(window).scrollTop();
    var headerNav = $('#header-topnav').height();
    var blockOffset = $(aTag).offset().top;
    var editRibbon = 0;
    var addOffset = 18;

    if (typeof aTag != 'undefined' || typeof aTag.offset() != 'undefined') {
        if (!$(aTag).hasClass('c-ui-square')) {
            headerNav = 0;
            addOffset = 0;
        }

        if (document.getElementById('scWebEditRibbon') !== null) {
            editRibbon = $('#scWebEditRibbon').height();
        }

        $('html,body').animate({ scrollTop: blockOffset - (headerNav + editRibbon + addOffset) }, 750);
        newName = $(aTag).text();
    }

    //change header name
    if (id != 'block-hero' && id != 'block-footer') {
        changeHeaderSectionText(newName, activeSectionIndex);
    }
    else {
        changeHeaderSectionText("", -1);
    }
}

function ScrollSection(direction) {
    //console.log('ScrollSection == ' + direction);
    //console.log('activeSectionIndex = ' + activeSectionIndex);

    event.preventDefault();

    var newIndex = activeSectionIndex + direction;
    //console.log('newIndex = ' + newIndex);

    if (newIndex < 0) {
        //scroll to hero
        $(window).scrollTop(0)
        changeHeaderSectionText("", -1);
        return;
    }

    if (newIndex > $('.block-title h2').length - 1) {
        //scroll to footer
        //scrollToAnchor('block-footer');
        return;
    }

    activeSectionIndex = newIndex;
    //console.log('new_activeSectionIndex = ' + activeSectionIndex);

    scrollToAnchor(activeSectionIndex + '-block-title');

    //console.log('ScrollSection == END');
}

$(window).on("load", function () {
    //InitializeHeaderSlider();
    //InitializeSpotlightSlider();

    $('#layout-homepage').on('DOMMouseScroll mousewheel keyup keydown keypress', function (e) {
        scrollEventHandler();
    });

    $(document).on("keydown", function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 38 || code == 40) {
            scrollEventHandler();
        }
    });

    //total count
    //$('#totalSectionCount').text($('.block-title h2').length);
});

function isEditMode() {
    return $('html').hasClass('edit-mode');
}

//$(window).on('load resize', function () {
//    $('.ui-terminator').each(function (index) {
//        var xBorderWidth = $(this).parent().width();
//        var yBorderWidth = xBorderWidth * 106 / 260;
//        $(this).css({
//            'border-top-width': $(this).hasClass('top') ? yBorderWidth : 0,
//            'border-bottom-width': $(this).hasClass('bottom') ? yBorderWidth : 0,
//            'border-left-width': $(this).hasClass('left') ? xBorderWidth : 0,
//            'border-right-width': $(this).hasClass('right') ? xBorderWidth : 0,
//            'margin-top': $(this).hasClass('top') ? yBorderWidth * -1.25 : 0
//        });

//        //set previous
//        if (isEditMode()) {
//            var prev = $(this).parent('.term-after-image').prevUntil('.block').prev();
//            if (prev.length > 0 && prev.hasClass("block")) {
//                $(prev[prev.length - 1]).css('padding-bottom', yBorderWidth);
//            }

//            //set next
//            var next = $(this).parent('.term-after-image').nextUntil('.block').next();

//            if (next.length > 0 && next.hasClass("block")) {
//                $(next[next.length - 1]).css('margin-top', (yBorderWidth - 1) * -1);
//            }
//        }
//        else {
//            $(this).parent('.term-after-image').prev().css('padding-bottom', yBorderWidth);
//            $(this).parent('.term-after-image').next().css('margin-top', (yBorderWidth - 1) * -1);
//        }
//    });

//});

//////////////////////////
//BLOG INDUSTRY SELECTOR
//////////////////////////

function realWidth(obj) {
    var clone = obj.clone();
    clone.css("visibility", "hidden");
    $('body').append(clone);
    var width = clone.outerWidth();
    clone.remove();

    return width;
}

if (ComponentRegistry.BlogIndustrySelectorHeader) {
    $(function () {
        //show selection
        var text = $('#block-blog-industry-selector .dropdown-menu a[href*="' + window.location.pathname + '"]').text();

        if (text.length > 0) {
            //show first selection
            $('#block-blog-industry-selector label').text(text);
        }

        //set offset height
        //var height = $('#header-topnav').outerHeight();
        //$('#block-blog-industry-selector').css('margin-top', height + 'px');
    });
}

//////////////////////////
//BLOG POST LIST
//////////////////////////

function isJSONBlogPostDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined')
        return true;

    return false;
}

function getJSONBlogPostData() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-post-list']['posts'];
}

function getJSONBlogPostDataFeatured() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-post-list']['posts-featured'];
}

function bindBlogPosts(JSONposts) {
    //featured
    $(".module-blog-featured-post > div").loadTemplate($('.module-blog-featured-post .json-template'), getJSONBlogPostDataFeatured());

    //non featured
    $(".module-blog-post-list ul").loadTemplate($('.module-blog-post-list .json-template'), JSONposts);
    $('.module-blog-post-list ul li').slice(0, 4).removeClass('hidden-xs'); //show only first 4 on mobile
}

if ((ComponentRegistry.BlogPostList || ComponentRegistry.BlogArchiveList) && isJSONBlogPostDataAvailable()) {
    $(function () {
        //INIT
        bindBlogPosts(getJSONBlogPostData());

        //EVENT HANDLERS
        //add show more button event handler
        $('.module-blog-post-list button').on("click", function (event) {
            event.preventDefault();

            $('.module-blog-post-list ul li[class=hidden-xs]').removeClass('hidden-xs');

            $(this).addClass('clicked');
        });

        var url = window.location.href;
        var arr = url.split("/");
        var result = arr[0] + "//" + arr[2];

        $('.social-likes-post').each(function () {
            $(this).attr('data-url', result + $(this).attr('data-url'));
        });

        $('.social-likes-post').socialLikes();

        BlogPostListAuthors();
        BlogPostTags();
        BlogPostArchiveYears();
    });
}

//////////////////////////
//BLOG POST LIST - AUTHORS
//////////////////////////
function isJSONBlogPostAuthorDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined')
        return true;

    return false;
}

function getJSONBlogPostAuthorData() {
    return _dataBlogPostList['GetBlogPosts-return']['author-list'];
}

function bindBlogAuthors() {
    //load authors
    $("#author-carousel .carousel-inner").loadTemplate($('.module-blog-authors .json-template'), getJSONBlogPostAuthorData());

    //create nav
    var indicators = "";
    for (ctr = 0; ctr < $("#author-carousel .carousel-inner .item").length; ctr++) {
        indicators += '<li data-target="#author-carousel" data-slide-to="' + ctr + '"></li>';
    }
    $("#author-carousel .carousel-indicators").html(indicators);

    //set first author as active
    $("#author-carousel .carousel-inner .item").eq(0).addClass('active');
    $("#author-carousel .carousel-indicators li").eq(0).addClass('active');

    //generate author pop up content
    $(".module-blog-authors .author-full-bio").loadTemplate($('.module-blog-authors .json-template-fullbio'), getJSONBlogPostAuthorData());
}

function BlogPostListAuthors() {
    //INIT
    bindBlogAuthors();

    //EVENT HANDLERS
    //add author show full bio event handler
    $('.module-blog-authors a.cta').on("click", function (event) {
        event.preventDefault();

        //get index of author
        var index = $('#author-carousel .item.active').index();

        //ready pop up HTML content
        var content = $('.author-full-bio > div').eq(index).html();

        //change pop up content
        $('#main-modal .modal-body').html(content);

        //show pop up content
        $('#main-modal').modal('show');
    });
}

if ((ComponentRegistry.BlogPostAuthors || ComponentRegistry.BlogArchiveAuthor) && isJSONBlogPostAuthorDataAvailable()) {
    $(function () {
        BlogPostListAuthors();
    });
}

//////////////////////////
//BLOG POST LIST - TAGS
//////////////////////////

function isJSONBlogPostTagDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined')
        return true;

    return false;
}

function getJSONBlogPostTagData() {
    return _dataBlogPostList['GetBlogPosts-return']['tag-list'];
}

function bindBlogTags() {
    $(".module-blog-tags ul").loadTemplate($('.module-blog-tags .json-template'), getJSONBlogPostTagData());
}

function BlogPostTags() {
    //INIT
    bindBlogTags();

    //EVENT HANDLERS
    //add tag event handler
    //$('.module-blog-tags a').on("click", function (event) {
    //    //event.preventDefault();
    //});
}

if ((ComponentRegistry.BlogPostTags || ComponentRegistry.BlogArchiveTags) && isJSONBlogPostTagDataAvailable()) {
    $(function () {
        BlogPostTags();
    });
}

//////////////////////////
//BLOG POST LIST - ARCHIVE YEARS
//////////////////////////
function isJSONBlogPostYearDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined')
        return true;

    return false;
}

function getJSONBlogPostYearData() {
    return _dataBlogPostList['GetBlogPosts-return']['year-published-list'];
}

function bindBlogArchiveYears() {
    $(".module-blog-archive ul").loadTemplate($('.module-blog-archive .json-template'), getJSONBlogPostYearData());

    //add ALL
    $(".module-blog-archive ul").append('<li><a href="#" title="Show All">Show All</a></li>');
}

function filterPostsByYear(year) {
    if (year == 'Show All') {
        $('.module-blog-featured-post').removeClass('hidden');
        return getJSONBlogPostData();
    } else {
        $('.module-blog-featured-post').addClass('hidden');
        return $.grep(getJSONBlogPostData(), function (element, index) {
            return element.dateYear == year;
        });
    }
}

function BlogArchiveYears() {
    //INIT
    bindBlogArchiveYears();

    //EVENT HANDLERS
    //add archive event handler
    $('.module-blog-archive a').on("click", function (event) {
        event.preventDefault();

        var year = $(this).text();

        bindBlogPosts(filterPostsByYear(year));

        $('.social-likes-post').socialLikes();
    });
}

if (ComponentRegistry.BlogPostListArchiveYears && isJSONBlogPostYearDataAvailable()) {
    $(function () {
        BlogArchiveYears();
    });
}

function BlogPostArchiveYears() {
    //INIT
    bindBlogArchiveYears();

    //EVENT HANDLERS
    //add archive event handler
    $('.module-blog-archive a').on("click", function (event) {
        event.preventDefault();

        var year = $(this).text();
        var author = '';
        //var author = document.getElementById("author-name").innerText.replace(/ /g, "%20");
        if ($('#authorId').length == 1) {
            author = $('#authorId').val().replace(/ /g, "%20"); //document.getElementById("author-name").innerText.replace(/ /g, "%20");
        }
        else {
            var authors = $('#authorId').map(function () { return $(this).text(); });//.val().replace(/ /g, "%20");
        }
        var path = location.pathname;
        path = path.substr(0, path.indexOf("/", 1));
        if (path == "") {
            path = "/" + $('#currentSite').val();
        }
        window.open(location.protocol + "//" + location.hostname + path + "/home/blogs/blogarchive?year=" + year + "&author=" + author, "_self");
    });
}

if ((ComponentRegistry.BlogPostArchiveYears || ComponentRegistry.BlogArchiveYears) && isJSONBlogPostYearDataAvailable()) {
    $(function () {
        BlogPostArchiveYears();
    });
}

//////////////////////////
//BLOG POST - MULTI SUBJECT - AUTHORS
//////////////////////////

if (ComponentRegistry.BlogPostMultipleSubjectAuthors) {
    $('#author-carousel').on("click", ".module-body a, .item-sm > a", function (event) {
        event.preventDefault();

        //get index of author
        var index = $(this).attr('href').substring('1');

        //ready pop up HTML content
        var content = $('.author-full-bio > div').eq(index).html();

        //change pop up content
        $('#main-modal .modal-body').html(content);

        //show pop up content
        $('#main-modal').modal('show');
    });
}

//TALENT SEGMENT SELECTOR
//if (ComponentRegistry.TalentSegmentSelector) {
//    $(function () {
//        //EVENT
//        //bind event publisher
//        $('#talent-segment-selector .dropdown-menu a').on('click', function (event) {
//            event.preventDefault();

//            //change text
//            $('#talent-segment-selector .text').text($(this).text());

//            //raise event
//            $('#talent-segment-selector').trigger('talentSegmentSelector_change', [($(this).attr('data-search-value'))]);
//        });

//        //event subscriber sample
//        //$('#talent-segment-selector').on('talentSegmentSelector_change', function (event, val) {
//        //    event.preventDefault();
//        //    alert('talentSegmentSelector_change, search value == ' + val);
//        //});
//    });
//}

function SetTalentSegmentSelectorValue(value) {
    if (ComponentRegistry.TalentSegmentSelector) {
        //find text of value on list
        var text = $('#talent-segment-selector .dropdown-menu a[data-search-value="' + value + '"]').eq(0).text();

        $('#talent-segment-selector .text').text(text.substring(0, 30));
    }
}

///////////////////////////////////////////////////////////////////////////////
//START EVENT CALENDAR
///////////////////////////////////////////////////////////////////////////////

Date.prototype.addDays = function (days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
}

Date.prototype.addMonths = function (months) {
    var dat = new Date(this.valueOf());
    dat.setMonth(dat.getMonth() + months);
    return dat;
}

//removed: redundant. in stylecore.engine as well
//function replaceAll(find, replace, str) {
//    return typeof str == 'undefined' || str == null ? '' : str.replace(new RegExp(find, 'g'), replace);
//}

//gets a week's starting Sunday based on a given date. This assumes Sun to Sat format
function GetWeekSundayDate(dateFrom) {
    return dateFrom.addDays(dateFrom.getDay() * -1);
}

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 11;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months;
}

function wsCall(wsUrl, wsCallback) {
    $.getJSON(wsUrl, wsCallback);
}

function getLastDayOfMonth(month, year) {
    return new Date(year, month + 1, 0);
}

//END EVENT CALENDAR

//////////////////////////
//BLOG POST - RECENT POSTS
//////////////////////////

function isJSONBlogRecentPostDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined')
        return true;

    return false;
}

function getJSONBlogRecentPostData() {
    return _dataBlogPostList['GetBlogPosts-return']['recentpost-list'];
}

function bindBlogRecentPosts() {
    $(".module-blog-recent ul").loadTemplate($('.module-blog-recent .json-template'), getJSONBlogRecentPostData());
    if ($(".module-blog-recent ul li").length == 0) {
        $(".module-blog-recent").hide();
    }
}

if (ComponentRegistry.AuthorRecentPosts && isJSONBlogRecentPostDataAvailable()) {
    $(function () {
        //INIT
        bindBlogRecentPosts();

        //EVENT HANDLERS
        //add tag event handler
        //$('.module-blog-recent a').on("click", function (event) {
        //    event.preventDefault();
        //});
    });
}

//////////////////////
//TEAM MEMBERS MODULE
/////////////////////

if (ComponentRegistry.TeamMembersModule) {
    $('.cta.member-fullbio').on("click", function (event) {
        event.preventDefault();

        //get index of author
        var index = $(this).attr('href').substring('1');

        //ready pop up HTML content
        var maincontent = $('.member-fullbio').parents('.col-sm-4.member-index-' + index).html();

        $('.member-item-header').empty();
        $('.member-item-header').append($(maincontent).filter('img'));

        $('.member-item-details').empty();
        $('.member-item-details').append($(maincontent).children());

        //Remove short description and show full biography.
        $('.member-item-details .shortdescription').remove();
        $('.member-item-details .fullbiography').removeClass('hidden');

        //Remove Full bio link
        $('.member-item-details a.cta.member-fullbio').remove();

        //change header text.
        $('h4#myModalLabel.modal-title').text('Member');

        var membermodalcontent = $('#member-item-modal');
        $(membermodalcontent).removeClass('hidden');

        //change pop up content
        $('#main-modal .modal-body').html(membermodalcontent);

        //show pop up content
        $('#main-modal').modal('show');
    });
}

function placeholderIsSupported() {
    var test = document.createElement('input');
    return ('placeholder' in test);
}

if (!placeholderIsSupported()) {
    $('input, textarea').placeholder();
}

function checkThumbnail(playerId, eventName) {
    var playerParent = document.getElementById(playerId);
    var playIcon = $(playerParent).parent().siblings("#media-video-thumbnail");

    if (eventName == "onMediaLoad") {
        $(playIcon).children('.acn-icon').show()
    }
    else {
        $(playIcon).children('.acn-icon').hide()
    }
}

function playVideo(playerId) {
    try {
        var vid2 = document.getElementById(playerId).getElementsByTagName('video')[0];
        if (vid2.paused)
            vid2.play();
        else
            vid2.pause();
    } catch (e) {
        document.getElementById(playerId).doPlay();
    }
}

function doOnPlayStateChanged(e, pid) {
    //Bug302043 Careers Meet Our People: Video is not display in the page upon clicking of Play button.
    if (!e.isPlaying && !e.isBusy) {
        $("#" + pid + "-overlay").css("visibility", "visible");
        $("#" + pid + "-play").css("visibility", "visible");
        $("#" + pid + "-play").closest(".mop-vid").removeClass('playing');
    }
}
function limitText(limitField, limitCount, limitNum) {
    //[2/18/15] Merge 1/29 from Main Release Branch
    //if (limitField.value.length > limitNum) {
    //    limitField.value = limitField.value.substring(0, limitNum);
    //} else {
    //    limitCount.value = limitNum - limitField.value.length;
    var $textArea = $('#' + limitField);
    var $counter = $('#' + limitCount);
    var maxCount = Number(limitNum);
    if ($textArea.val().length > maxCount) {
        $textArea.val($textArea.val().substring(0, maxCount));
        var evt = this.event || window.event; // IE compatibility
        if (evt.preventDefault) {
            evt.preventDefault();
        } else {
            evt.returnValue = false;
            evt.cancelBubble = true;
        }
    }
    if ($textArea.val() == $('#commentContent').val()) {
        $counter.val(maxCount - $textArea.val().length + " " + $('#commentContent').attr('data-characters-remaining'));
    }
    else {
        $counter.val(maxCount - $textArea.val().length);
    }
}

//returns true if page is in Sitecore's Preview mode.
function isPreviewMode() {
    return ($('#scCrossPiece').length > 0 && $("#scFieldValues").length == 0);
}

//Cookies alignment

$(window).on("resize", function () {
    if ($('#announcement-carousel').length != 0) {
        $('#ui-wrapper').addClass('has-announcement-module');
    }
});

// LINE CLAMPING

// added reusable function
// SIR #433133: Webpart - Business Services Module: in US-EN page, the artilces pulled in to the page are NOT arranged properly.
function PackeryDynamicFeaturedArticle() {
    var container = document.querySelectorAll('.packery-container');
    if (container != null && container != undefined) {
        $.each(container, function () {
            var packery = new Packery(this, {
                containerStyle: null,
                itemSelector: '.packery-item'
            });
        });
    }
    return false;
}

function Bootstraploader() {
    var validatorExists = $('head').find("script[src*='bootstrapValidator.js']").length > 0;

    if (!validatorExists) {
        var bootstrapScript = document.createElement('script'), d = false;
        bootstrapScript.async = true;
        bootstrapScript.src = "/Scripts/lib/bootstrapValidator.js";
        bootstrapScript.type = "text/javascript";
        bootstrapScript.onload = bootstrapScript.onreadystatechange = function () {
            var bootstrapReadyState = this.readyState;
            //Validate if script is downloaded successfully.
            if (!d && bootstrapReadyState == "complete" || bootstrapReadyState == "loaded") {
                d = true;
                InitializeBootstrapValidator(); //Callback
            }
        };
        $('head').append(bootstrapScript);
    }
}

function InitializeBootstrapValidator() {
    if ($(document).bootstrapValidator) {
        if ($('.acn-form').length > 0) {
            $('.acn-form').bootstrapValidator({
                submitHandler: function (validator, form, submitButton) {
                    // remove undefined 'control'
                    //var form = $(control).closest('form');
                    //if (form > 0) {
                    //    form.find('.has-success .success-message').css("opacity", 1).animate({ opacity: 0 }, 1500);
                    //}
                },
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                }
            });
        }
    }
}

var packeryResizeTimeoutHandle = null;
$(function () {
    //Bug 465653: Fix for framekiller. Will only be implemented on Live Pages
    if ((typeof isNormal !== "undefined") && (isNormal != "")) {
        if (isNormal == "true") {
            if (top.location.hostname != self.location.hostname) {
                top.location = self.location
            }
        }
    }

    packeryResizeTimeoutHandle = window.setTimeout(function () {
        // refresh packery
        PackeryDynamicFeaturedArticle();
    }, 800);

    //MGDL 10.29.2014
    //[BUG#337547] - Collection of R1.1 requirements that's in scope for R1.2 & Tracking of scope changes - Careers MOP: Add Photo/Video and Add Pull Quote buttons not working
    var onboardingpage = $('.onboarding');
    if (onboardingpage.length == 0) {
        var packeryContainer = $('.packery-container');
        var isPageEditor = $('#webedit');

        if (typeof packeryContainer != 'undefined' && packeryContainer.length > 0 && isPageEditor.length == 0) {
            packeryContainer.moduleClamping({
                moduleSelector: ".module-article",
                titleSelector: "h4",
                bodySelector: ".module-body",
                titleMaximumRowCount: 3,
                bodyMaximumRowCount: 3,
                totalMaximumRowCount: 5,
                mouseOver: 'expand',
                onMouseOver: function () {
                    // refresh packery
                    PackeryDynamicFeaturedArticle();
                },
                onMouseOut: function () {
                    // refresh packery
                    PackeryDynamicFeaturedArticle();
                }
            });
            $(window).on('load', function () {
                $('.packery-container .module-article').addClass('disable-link-analysis');

                if (isDesktop() && !IsTouch()) {
                    $('.packery-container .module-article').trigger('mouseenter').trigger('mouseleave');
                }
                else {
                    $('.packery-container .module-article').addClass('mouse-entered-onload');
                    $('.packery-container .module-article').trigger('click').trigger('click');
                    $('.packery-container .module-article').removeClass('mouse-entered-onload');
                }

                $('.packery-container .module-article').removeClass('disable-link-analysis');
            });

        }
    }
    $(window).on("resize", function () {
        clearTimeout(packeryResizeTimeoutHandle);
        packeryResizeTimeoutHandle = window.setTimeout(function () {
            // refresh packery
            PackeryDynamicFeaturedArticle();
        }, 100);
    });

    //[BUG#318584] - Layouts for top level pages on accenture.com: Clamping approach for the FeaturedSection module is not working on the page
    var clampFeaturedSection = $('.clamp-featured-section');
    if (typeof clampFeaturedSection != 'undefined' && clampFeaturedSection.length > 0) {
        clampFeaturedSection.moduleClamping({
            moduleSelector: ".module-article",
            titleSelector: "h4",
            bodySelector: "p",
            titleMaximumRowCount: 3,
            bodyMaximumRowCount: 3,
            totalMaximumRowCount: 5,
            mouseOver: 'expand',
            onMouseOver: function () { },
            onMouseOut: function () { }
        });
    }
});
//returns true if page is in Sitecore's Preview mode.
function isPreviewMode() {
    return ($('#scCrossPiece').length > 0 && $("#scFieldValues").length == 0);
}

var isMobileDevice = {
    Android: function () {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function () {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function () {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function () {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function () {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function () {
        return (isMobileDevice.Android() || isMobileDevice.BlackBerry() || isMobileDevice.iOS() || isMobileDevice.Opera() || isMobileDevice.Windows());
    }
};

var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';

var tagOrComment = new RegExp(
    '<(?:'
    // Comment body.
    + '!--(?:(?:-*[^->])*--+|-?)'
    // Special "raw text" elements whose content should be elided.
    + '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
    + '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
    // Regular name
    + '|/?[a-z]'
    + tagBody
    + ')>',
    'gi');
function removeTags(html) {
    if (html) {
        var oldHtml;
        do {
            oldHtml = html;
            html = html.replace(tagOrComment, '');
        } while (html !== oldHtml);
        return html.replace(/</g, '');
    }
    return "";
}

$(function () {
    RemoveDuplicateID('#SSOErrorID');
    var err = '';
    var ErrorID = $('#SSOErrorID');
    if (ErrorID != undefined && ErrorID.length > 0) {
        err = ErrorID.val();
        if (err == '1')//Social.Error.Email.Used
            $('#SocialEmailModal').modal('show');//continue button redirect to registration
        else if (ComponentRegistry.ClientEditProfile || ComponentRegistry.EditProfile || ComponentRegistry.ClientAccount) {
            if (err == '0')//Social.Error.Duplicate
                $('#SocialMediaModal').modal('show');
        }
        else if (ComponentRegistry.Registration) {
            if (err == '2' || err == '0')//SocialConnect.Error.Email.Used & Social.Error.Duplicate
                $('#SocialMediaModal').modal('show');//continue button close the modal
        }
    }

    var vp = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var w = vp < 768 ? 95 : (vp < 1000 ? 110 : 120);
    $('.map area.first').attr("coords", "0,0," + w + ",50");
    $('.map area.second').attr("coords", +w + ",0,300,50");
});

$(window).on('load', function () {
    $('.social-likes__button.social-likes__button_single').on("click", function () {
        $(this).closest('.packery-item').css("overflow", "visible");
    });

    clearTimeout(packeryResizeTimeoutHandle);
    packeryResizeTimeoutHandle = window.setTimeout(function () {
        // refresh packery
        PackeryDynamicFeaturedArticle();
    }, 100);
});
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\DownArrowScroll.js
// version="4"
if (ComponentRegistry.DownArrowScroll) {
    $(function () {

        $('#scroll-button').on("click", function () {
            var firstBlock = $('.ui-container').first();

            // if there is announcement module
            if ($('#ui-wrapper').hasClass('has-announcement-module')) {
                firstBlock = $('.ui-container:nth-child(2)');
            }

            var accentLogo = $('#accent');
            var uiwrapper = $('#ui-wrapper');
            var scrollTo = 0;

            if (firstBlock.length !== 0 && uiwrapper.length !== 0) {
                var uiwrapperOffset = uiwrapper.offset().top;
                var firstBlockAcnLogoOffset = firstBlock.offset().top - uiwrapperOffset;
                var firstBlockTitle = firstBlock.find('.block-title');

                if (accentLogo.length > 0) {
                    scrollTo = firstBlockAcnLogoOffset;
                }
                // if there is block-title
                else if (firstBlockTitle.length > 0) {
                    var firstBlockNoAcnLogoOffset = firstBlockTitle.offset().top - uiwrapperOffset;

                    scrollTo = firstBlockNoAcnLogoOffset;
                }
                else {
                    scrollTo = firstBlockAcnLogoOffset;
                }
            }

            $('html,body').animate({ scrollTop: scrollTo }, 2000);
        });

        $('#scroll-button').on("keydown", function (e) {
            if (e.which == 13) {
                $(this).trigger("click");
            }
        });

    });

    $(window).on('load', function () {
        var animationTime = $('#scroll-button span.acn-icon').data('animation-time');
        var arrowIcon = $('#scroll-button span.acn-icon');

        // Down Arrow Animation for IE8 and IE9
        if (IsIE8() || IsIE9()) {
            var iconTop = $('#scroll-button span.acn-icon').css('top');
            var animateNumberOfTimes = 4;

            if (animationTime != 'null' || animationTime != '') {
                animateNumberOfTimes = animationTime / 2.5;
            }

            for (var x = 1; x <= animateNumberOfTimes; x++) {
                var animateTop = '35px';
                if (x == animateNumberOfTimes) {
                    animateTop = iconTop;
                }

                $('#scroll-button span.acn-icon').animate({ top: '55px', opacity: 0 }, 2500)
                    .animate({ top: animateTop, opacity: 1 }, 0);
            }
        }

        if (animationTime != 'null' || animationTime != '') {
            arrowIcon.addClass('animation-' + animationTime + '-sec');
        }
        else {
            arrowIcon.addClass('animation-10-sec');
        }
    });

    function IsIE9() {
        var IE = InternetExplorer();
        return (IE == 9);
    }

    //RMT 1033 - Fix for 1136x640 issue

    $(function () {
        moveScrollDownArrow();
    });

    $(window).on("resize", function () {
        moveScrollDownArrow();
    });

    function moveScrollDownArrow() {
        var heightLimit = 670;
        var widthLimit = 1250;
        var scrollButton = $('#scroll-button');
        var heroScrollButton = $('.large-hero #scroll-button, .special-large-hero #scroll-button');
        var buttonTop = 400;
        var heroButtonTop = 446;

        var outerHeight = Math.max(document.documentElement.clientHeight, window.outerHeight || 0);
        var outerWidth = Math.max(document.documentElement.clientWidth, window.outerWidth || 0);

        if (outerHeight <= heightLimit || widthLimit > outerWidth) {
            scrollButton.css('top', '310px');
        }
        else {
            scrollButton.css('top', '400px');
            heroScrollButton.css('top', '446px');

        }

    }

}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\ads.js
/* version="9" */
Ads = {
    name: 'Ads',
    data: null,
    filterCategoryViewAllIsClicked: [],
    maxFilterItemsLoaded: 5,
    initialLoad: true,
    timeoutHandle: 0,
    currentPageNo: 0,
    currentSort: '',
    queryType: 'searchbymetadata.query',
    currentFacetDisplayname: '',
    currentMetadataFieldname: '',
    mobileAcnFacets: null,
    advertisementLoadedArticles: null,
    protocol: location.protocol === 'https:' ? 'https://' : 'http://',
    hostName: location.hostname,
    isLoaded: false,

    getAdBoxType: function () {
        switch (AdsConfig.contentType) {
            case "47ed666e-5b8e-45d4-84d6-6473ebd62205": //advertisement
                return 3;
                break;
            case "852b3170-0397-4d61-81a2-fd5b68fb778b": //stats
                return 2;
                break;
            default: //trends and perspectives
                return 1;
        }
    },

    createAdBox: function (article) {
        if (article == null) return;

        var isArticlesLoaded = (Ads.advertisementLoadedArticles != null);
        if (!isArticlesLoaded) {
            Ads.advertisementLoadedArticles = article;
        }

        var type = Ads.getAdBoxType();

        //generate box
        var adBoxes = '';
        for (var ctr = 0; ctr < article.length; ctr++) {

            switch (type) {
                case 3:
                    adBoxes += Ads.createAdBox3(article[ctr]);
                    if (isArticlesLoaded) {
                        var isExists = false;
                        for (var i = 0; i < Ads.advertisementLoadedArticles.length; i++) {
                            if (article[ctr].SitecoreItemId.toString() == Ads.advertisementLoadedArticles[i].SitecoreItemId.toString()) {
                                isExists = true;
                                break;
                            }
                        }
                        if (!isExists) {
                            Ads.advertisementLoadedArticles.push(article[ctr]);
                        }
                    }

                    break;
                case 2:
                    adBoxes += Ads.createAdBox2(article[ctr]);
                    break;
                default: //1
                    adBoxes += Ads.createAdBox1(article[ctr]);
                    break;
            }
        }

        //add shares count

        return adBoxes;
    },
    createAdBox1: function (article) {
        if (article == null) return '';

        var template_container = '<div class="col-sm-4 trends-and-perspective ad-card packery-item"><div class="module-ad">{0}</div></div>';

        if (!$('.module-ad-cards-filter #accordion-filter-results').is(':hidden')) {
            template_container = '<div class="col-sm-6 trends-and-perspective ad-card packery-item"><div class="module-ad">{0}</div></div>'
        }

        var content = ('<div class="header"><h3 class="ucase">{INDUSTRY}</h3></div>').replace('{INDUSTRY}', typeof article.ArticleCategory == 'undefined' || article.ArticleCategory == null
            ? '' : article.ArticleCategory.toUpperCase());

        content += '<div class="media">';

        if (typeof article.FeaturedMediaType != 'undefined' && article.FeaturedMediaType != null && article.FeaturedMediaType != '') {

            var icon = '';
            var color = 'periwinkle-blue'
            var image = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null
                && article.FeaturedImage.Path != '' ? article.FeaturedImage.Path : ''

            var imageAlt = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null
                && article.FeaturedImage.Path != '' ? article.FeaturedImage.Alt : ''

            if (article.FeaturedMediaType.toUpperCase() == 'VIDEO') {
                icon = 'video';
            } else if (article.FeaturedMediaType.toUpperCase() == 'IMAGE' && article.ImagesInGallery > 0) {
                icon = 'gallery';
            }

            var imageLinkName = "";
            if (imageAlt) {
                imageLinkName = imageAlt.toLowerCase();
            }
            else if(image){
                imageLinkName = image.split('/').pop().toLowerCase();
            }


            content += ('<a href="{URL}" {IMAGEGALLERY-AND-ARTICLE-ID}  data-analytics-content-type= "image" data-analytics-link-name="{IMAGELINKNAME}"><span class="image-holder" data-src="{IMAGE}" data-alt="{ALT}" data-title="{TITLE}"></span></a>')
                .replace('{IMAGE}', image)
                .replace('{URL}', icon.length > 0 ? '#' : article.RelativePath)
                .replace('{ALT}', imageAlt)
                .replace('{IMAGELINKNAME}', imageLinkName)
                .replace('{TITLE}', imageAlt);

            if (icon.length > 0) {
                var media = article.FeaturedVideo == null ? '' : article.FeaturedVideo.Id;
                var articleid = '';

                if (article.SitecoreItemId != undefined) {
                    articleid = article.SitecoreItemId.toString().toLowerCase()
                        .replace('{', '')
                        .replace('}', '')
                        .replace('-', '')
                        .replace('-', '')
                        .replace('-', '')
                        .replace('-', '');
                }

                content = content.replace('{IMAGEGALLERY-AND-ARTICLE-ID}', 'class="ui-link ' + icon + '" data-article-id="' + articleid + '" ' + (icon == 'video' ? 'data-video-id="' + media + '"' : ''));

                content += ('<div><a href="#" class="ui-link ' + icon + '" {VIDEO} data-article-id="' + articleid + '"><i class="acn-icon ads icon-ads-' + icon + '"></i></a></div>')
                    .replace('{URL}', article.RelativePath)
                    .replace('{VIDEO}', icon == 'video' ? 'data-video-id="' + media + '"' : '');
            }
            else {
                content = content.replace('{IMAGEGALLERY-AND-ARTICLE-ID}', '');
            }
        }

        content += '</div>';

        var headlineLinkName = "";
        if (article.Title) {
            headlineLinkName = article.Title.toLowerCase();
        }
        content += ('<div class="body"><h2><a href="{URL}"data-analytics-content-type= "headline" data-analytics-link-name="{HEADLINELINKNAME}">{TITLE}</a></h2></div>').replace('{TITLE}', article.Title).replace('{URL}',
            article.RelativePath).replace('{HEADLINELINKNAME}', headlineLinkName);

        content += Ads.createSocialShare(article);

        return template_container.replace('{0}', content);
    },
    createAdBox2: function (article) {
        if (article == null) return '';

        var color = (article.PrimaryColor == null || typeof article.PrimaryColor == 'undefined') ? '' : article.PrimaryColor;

        var image = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null
            && article.FeaturedImage.Path != '' ? article.FeaturedImage.Path : ''

        var imageAlt = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null
            && article.FeaturedImage.Path != '' ? article.FeaturedImage.Alt : ''

        var template_container = '<div class="col-sm-4 ad-card packery-item"><div class="module-ad module-ad-2">{0}</div></div>';

        if (!$('.module-ad-cards-filter #accordion-filter-results').is(':hidden')) {
            template_container = '<div class="col-sm-6 ad-card packery-item"><div class="module-ad module-ad-2">{0}</div></div>'
        }

        var content = ('<div class="header {BG_COLOR}"><h3 class="ucase">{INDUSTRY}</h3></div>')
            .replace('{INDUSTRY}', (article.PrimaryColor == null || typeof article.ArticleCategory == 'undefined') ? '' : article.ArticleCategory)
            .replace('{BG_COLOR}', 'bg-color-' + color);

        content += ('<div class="media {BG_COLOR}"><a href="{URL}"><span class="image-holder" data-src="{IMAGE}" data-alt="{ALT}" data-title="{TITLE}"></span></a>')
            .replace('{IMAGE}', image)
            .replace('{URL}', article.RelativePath)
            .replace('{ALT}', imageAlt)
            .replace('{TITLE}', imageAlt)
            .replace('{BG_COLOR}', 'bg-color-' + color);
        content += '</div>';

        content += ('<div class="social-share">');
        content += ('<div class="col-xs-6 left">');

        content += Ads.createSocialShare(article, color);

        content += '</div>';
        content += ('<div class="col-xs-6 right">');
        content += ('<a href="{URL}" class="cta {COLOR}">READ MORE</a>')
            .replace('{URL}', article.RelativePath)
            .replace('{COLOR}', 'color-' + color);
        content += '</div>';
        content += '</div>';

        return template_container.replace('{0}', content);
    },
    createAdBox3: function (article) {
        if (article == null) return '';

        var image = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null && article.FeaturedImage.Path != '' ? article.FeaturedImage.Path : '';

        var imageAlt = typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null
            && article.FeaturedImage.Path != '' ? article.FeaturedImage.Alt : ''

        var template_container = ('<div class="col-sm-{0} ad-card packery-item"><div class="module-ad module-ad-3">{1}</div></div>').replace('{0}', article.ArticleWidth > 2 ? 8 : 4);

        //if filter is shown
        if (!$('.module-ad-cards-filter #accordion-filter-results').is(':hidden')) {
            template_container = ('<div class="col-sm-{0} ad-card packery-item"><div class="module-ad module-ad-3">{1}</div></div>').replace('{0}', article.ArticleWidth > 2 ? 12 : 6);
        }

        var content = ('<div class="media">');

        var hasFeaturedVideo = (article.FeaturedMediaType != null && article.FeaturedMediaType.toUpperCase() == 'VIDEO');

        var showGalleryClass = 'class="ui-link adsGallery"';
        var media = '';
        var articleid = '';

        if (hasFeaturedVideo) {
            media = article.FeaturedVideo == null ? '' : article.FeaturedVideo.Id;

            if (article.SitecoreItemId != undefined) {
                articleid = article.SitecoreItemId.toString().toLowerCase().replace('{', '').replace('}', '')
                    .replace('-', '').replace('-', '').replace('-', '').replace('-', '');
            }

            showGalleryClass = 'class="ui-link video" data-video-id="' + media + '" data-article-id="' + articleid + '"';
        }

        content += ('<a href="{URL}" {SHOWGALLERY}><span class="image-holder " data-src="{IMAGE}" data-alt="{ALT}" data-title="{TITLE}"></span></a>')
            .replace('{URL}', article.RelativePath)
            .replace('{IMAGE}', image)
            .replace('{ALT}', imageAlt)
            .replace('{TITLE}', imageAlt)
            .replace('{SHOWGALLERY}', AdsConfig.enableAdsArticleRedirection ? '' : showGalleryClass);

        if (hasFeaturedVideo) {

            var icon = 'video';

            content += ('<div><a href="#" class="ui-link ' + icon + '" {VIDEO} data-article-id="' + articleid + '"><i class="acn-icon ads icon-ads-' + icon + '"></i></a></div>')
                .replace('{URL}', article.RelativePath)
                .replace('{VIDEO}', 'data-video-id="' + media + '"');
        }

        content += '</div>';

        //content += '<div class="social-share">';
        content += Ads.createSocialShare(article);
        //content += '</div>';

        return template_container.replace('{1}', content);
    },

    createVideoBox: function (videoItem) {

        if (videoItem == null || videoItem == '') {
            return '';
        }

        var mediaPlayerNetwork = '//assets.delvenetworks.com/player/loader.swf';

        var videoHeight = isMobile() ? 169 : 338;
        var videoWidth = isMobile() ? 300 : 600;

        var videoHtml = '';

        //if with transcript
        if (videoItem.DownloadTranscriptLink != null && videoItem.DownloadTranscriptLink != 'undefined') {

            //icon-video-transcript
            videoHtml += ('<a href="{0}" class="transcript"><i class="acn-icon {4}"></i>{1} ({2} {3}KB)</a>')
                .replace('{0}', videoItem.DownloadTranscriptLink)
                .replace('{1}', videoItem.DownloadText)
                .replace('{2}', videoItem.TranscriptType)
                .replace('{3}', videoItem.SizeInKB)
                .replace('{4}', videoItem.DownloadIcon);
        }

        return videoHtml;
    },
    createSocialShare: function (article, color) {
        var color = typeof color == 'undefined' ? '' : 'data-color="' + color + '"';
        var articleUrl = Ads.protocol + Ads.hostName + article.RelativePath;

        var share = '<div class="social-share bg-color-white" ' + color + '>';
        share += ('<div class="social-likes social-likes_single" data-url="{URL}" data-title="{seotitle}" data-single-title="Share">').replace('{URL}', articleUrl).replace('{seotitle}', article.seotitle);
        share += '<div class="arrow">Share</div>';
        share += '<div class="facebook" title="Share link on Facebook" data-analytics-content-type= "share intent" data-analytics-link-name="facebook"></div>';
        share += '<div class="twitter" data-via="df" data-related="df" title="Share link on Twitter" data-analytics-content-type= "share intent" data-analytics-link-name="twitter"></div>';
        share += '<div class="plusone" title="Share link on Google+" data-analytics-content-type= "share intent" data-analytics-link-name="googleplus"></div>';
        share += '<div class="pinterest" title="Share image on Pinterest" data-media=""data-analytics-content-type= "share intent" data-analytics-link-name="pinterest"></div>';
        share += '</div>';
        share += '</div>';

        return share;
    },

    showAdsGallery: function () {
        var galleryItems = '';
        var articles = Ads.advertisementLoadedArticles;
        for (var ctr = 0; ctr < articles.length; ctr++) {

            var article = articles[ctr];

            if (article == null || (article.FeaturedMediaType != null && article.FeaturedMediaType.toUpperCase() == 'VIDEO')) {
                continue;
            }

            var imagePath = '#'
            var altText = '';
            var container = '<div class="gallery-item">{0}</div>';

            if (typeof article.FeaturedImage != 'undefined' && article.FeaturedImage != null) {
                if (article.FeaturedImage.Path != '') {
                    imagePath = article.FeaturedImage.Path;
                }

                if (article.FeaturedImage.Alt != '') {
                    altText = article.Alt;
                }
            }

            var img = ('<span class="image-holder" data-src="{0}" data-alt="{1}"></span>').replace('{0}', imagePath).replace('{1}', altText);
            var desc = ('<p>{0}</p>').replace('{0}', article.Description);

            galleryItems += container.replace('{0}', img + desc);

        }

        $("#gallery-carouselindustryAllAds").html(galleryItems);
        ViewGallery("industryAllAds");
    },
    showVideo: function (mediaId) {
        if (mediaId != null && mediaId != '') {
            var countrySite = Ads.getCountrySite();
            var df = "{\"vid\":" + "\"" + mediaId + "\"" + "}";
            var path = (countrySite == null || countrySite == "") ? "/us-en/" : "/" + countrySite + "/";

            $.ajax({
                type: "POST",
                url: path + 'getvideobyid.search',
                data: df,
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

                    if (response != null && response != '') {
                        $('#main-modal .modal-body').html(Ads.createVideoBox(response));
                        $('#main-modal').removeClass('video gallery');
                        $('#main-modal').addClass('module-ad-board-modal video');
                        $('#main-modal ').modal('show');

                        $('#main-modal .modal-header button.close').on('click', function () {
                            $('#main-modal.module-ad-board-modal').removeClass('module-ad-board-modal video gallery')
                                .find('.modal-body').html('');
                        });
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log("The server encounters an error when retrieving the video... " + thrownError);
                }

            });
        }
    },
    showGallery: function (images) {
        var galleryItems = '';

        for (var i = 0; i < images.length; i++) {

            var container = '<div class="gallery-item">{0}</div>';
            var image = images[i].Image;
            var altText = '';
            var imagePath = '#';

            if (image != null && image != 'undefined') {
                altText = image.Alt; //images[i].alt
                imagePath = image.Path; //images[i].source
            }

            var img = ('<span class="image-holder" data-src="{0}" data-alt="{1}"></span>').replace('{0}', imagePath).replace('{1}', altText);
            var desc = ('<p>{0}</p>').replace('{0}', images[i].Description);

            galleryItems += container.replace('{0}', img + desc);
        }

        $("#gallery-carouselindustryAllAds").html(galleryItems);
        ViewGallery("industryAllAds");
    },

    updateCurrentSort: function () {
        Ads.currentSort = $('.module-ad-board .cta.sort.active').data('filtername').replace(' ', '');
    },
    getSortByParam: function () { //0 = relevancy, 1 = article date(desc), 2 = article date (asc)
        var sort = 0;

        var activeSort = $('.module-ad-board .cta.sort.active').data('filtername');

        if (activeSort != null) {
            switch (Ads.currentSort) {
                //TODO: Uncomment when R1.3 will commence
                //SIR: 428904
                //case 'MostPopular': //for R1.3
                //    sort = 0;
                //    break;

                case 'MostPopular':
                case 'MostRecent':
                    sort = 1;
                    break;
                default: //featured
                    sort = 0;
                    break;
            }
        }
        else {
            if (Ads.currentSort == null || Ads.currentSort == '') {
                this.setDefaultSorting();
            }

            switch (Ads.currentSort) {

                //TODO: Uncomment when R1.3 will commence
                //SIR: 428904
                //case 'MostPopular':
                //    sort = 0;
                //    break;

                case 'MostPopular':
                case 'MostRecent':
                    sort = 1;
                    break;
                default: //featured
                    sort = 0;
                    break;
            }
        }

        return sort;
    },

    addFilterTracker: function (facet) {
        var filterItems = facet.items;
        if (typeof filterItems != undefined && filterItems != null && filterItems.length > Ads.maxFilterItemsLoaded && Ads.initialLoad) {
            Ads.filterCategoryViewAllIsClicked.push({ metadatafieldname: facet.metadatafieldname, clicked: false });
        }
    },
    updateFilter: function () {
        if (Ads.data != null && Ads.data.acnfacets != null && Ads.data.acnfacets.length > 0) {

            var content = '';
            var contentMobile = '';

            if (Ads.initialLoad) {
                Ads.mobileAcnFacets = Ads.data.acnfacets;
            }

            if (isMobile()) {
                if (Ads.initialLoad) {
                    for (var ctr = 0; ctr < Ads.mobileAcnFacets.length; ctr++) {
                        var facet = Ads.mobileAcnFacets[ctr];

                        //industry filter
                        if (facet.items.length > 0) {
                            //add view all tracker
                            Ads.addFilterTracker(facet);
                            content += Ads.createFilterGroup(facet.metadatafieldname, facet.facetdisplayname, facet.items, facet.metadatafieldname);
                            contentMobile += Ads.createFilterGroupMobile(facet.metadatafieldname, facet.facetdisplayname, facet.items, facet.metadatafieldname);
                        }
                    }
                }

            }
            else {
                for (var ctr = 0; ctr < Ads.data.acnfacets.length; ctr++) {
                    var facet = Ads.data.acnfacets[ctr];

                    //industry filter
                    if (facet.items.length > 0) {
                        //add view all tracker
                        Ads.addFilterTracker(facet);
                        content += Ads.createFilterGroup(facet.metadatafieldname, facet.facetdisplayname, facet.items, facet.metadatafieldname);

                        if (Ads.initialLoad) {
                            contentMobile += Ads.createFilterGroupMobile(facet.metadatafieldname, facet.facetdisplayname, facet.items, facet.metadatafieldname);
                        }

                    }
                }
            }

            // sort by - most popular, most recent, featured
            var sortContainer = '<div class="col-sm-12 filter-group"><h3>SORT BY</h3><hr><div class="sort-options">{0}</div></div>'
            var sortContent = '';
            var sortContentFeatured = '';
            var sortContentPopular = '';
            var sortContentRecent = '';

            var sortContainerMobile = '<div class="filter sort">{0}</div>';
            var sortContentMobile = '<select id="sort" class="form-control dropup" name="sort" onchange="Ads.onDropdownFilterChange(this);">{0}</select>';
            var sortContentFeaturedMobile = '';
            var sortContentPopularMobile = '';
            var sortContentRecentMobile = '';

            var currentsort = Ads.currentSort.toLowerCase();

            if (AdsConfig.mostFeaturedSortText != '' && AdsConfig.enableCherryPick) {
                sortContentFeatured += Ads.createSortGroup(AdsConfig.mostFeaturedSortText, currentsort == AdsConfig.mostFeaturedSortText.replace(' ', '').toLowerCase());
                sortContentFeaturedMobile = ('<option value="{0}" {2}>{1}</option>')
                    .replace('{0}', 'FeaturedSort')
                    .replace('{1}', AdsConfig.mostFeaturedSortText)
                    .replace('{2}', currentsort == "featuredsort" ? 'selected="selected"' : '');
            }

            if (AdsConfig.mostRecentText != '') {
                sortContentPopular += Ads.createSortGroup(AdsConfig.mostRecentText, currentsort == AdsConfig.mostRecentText.replace(' ', '').toLowerCase());
                sortContentPopularMobile = ('<option value="{0}" {2}>{1}</option>')
                    .replace('{0}', 'MostRecent')
                    .replace('{1}', AdsConfig.mostRecentText)
                    .replace('{2}', currentsort == "mostrecent" ? 'selected="selected"' : '');
            }

            //TODO: Uncomment when R1.3 will commence
            //SIR: 428904
            //if (AdsConfig.mostPopularText != '') {
            //    sortContentRecent = Ads.createSortGroup(AdsConfig.mostPopularText, currentsort == AdsConfig.mostPopularText.replace(' ', '').toLowerCase());
            //    sortContentRecentMobile = ('<option value="{0}" {2}>{1}</option>')
            //        .replace('{0}', 'MostPopular')
            //        .replace('{1}', AdsConfig.mostPopularText)
            //        .replace('{2}', currentsort == "mostpopular" ? 'selected="selected"' : '');
            //}
            //End here

            switch (AdsConfig.defaultSorting) {
                case "MostRecent":
                    sortContent = sortContentRecent + sortContentFeatured + sortContentPopular;
                    sortContentMobile = sortContentMobile.replace('{0}', sortContentRecentMobile + sortContentFeaturedMobile + sortContentPopularMobile);
                    break;
                case "MostPopular":
                    sortContent = sortContentPopular + sortContentFeatured + sortContentRecent;
                    sortContentMobile = sortContentMobile.replace('{0}', sortContentPopularMobile + sortContentFeaturedMobile + sortContentRecentMobile);
                    break;
                case "FeaturedSort":
                    sortContent = sortContentFeatured + sortContentRecent + sortContentPopular;
                    sortContentMobile = sortContentMobile.replace('{0}', sortContentFeaturedMobile + sortContentRecentMobile + sortContentPopularMobile);
                    break;
            }

            if (AdsConfig.defaultSorting != "") {
                content += sortContainer.replace('{0}', sortContent);
                contentMobile += sortContainerMobile.replace('{0}', sortContentMobile);
            }

            //add to filter
            $('.module-ad-board .module-ad-cards-filter #accordion-filter-results .panel-body.laptop').html(content);
            if (isMobile()) {
                if (Ads.initialLoad) {
                    $('.module-ad-board .module-ad-cards-filter #accordion-filter-results .panel-body.mobile').html(contentMobile);
                }
            }

            //add event handlers
            //filter checkboxes
            $('#accordion-filter-results .filter-group input[type=checkbox]').on('click', function (event) {
                var filtername = $(this).data('filtername');
                var metadatafieldname = $(this).data('metadatafieldname');

                Ads.advertisementLoadedArticles = null;

                //perform search
                Ads.currentPageNo = 0; //reset to 0
                $('.module-ad-cards .ad-cards').html(''); //clear all cards
                Ads.isLoaded = false;
                Ads.performSearch();
                ImageLoadChecker();
            });

            //clear checkboxes
            $('#ads-clear-filter').on('click', function (event) {
                RemoveAllFilters();
                ImageLoadChecker();
            });

            // Removes all filters.
            function RemoveAllFilters() {
                $('#accordion-filter-results input:checked').each(function () {
                    $(this).prop('checked', false);
                });

                Ads.currentPageNo = 0; //reset to 0
                $('.module-ad-cards .ad-cards').html(''); //clear all cards

                for (var ctr = 0; ctr < Ads.filterCategoryViewAllIsClicked.length; ctr++) {
                    var $this = Ads.filterCategoryViewAllIsClicked[ctr];
                    $this.clicked = false;
                };

                $('#accordion-filter-results .filter-group .cta-view').show();

                if (isMobile()) {
                    Ads.initialLoad = true;
                    Ads.currentFacetDisplayname = null;
                    Ads.currentMetadataFieldname = null;

                    var facets = Ads.data.acnfacets;
                    for (var ctr = 0; ctr < facets.length; ctr++) {
                        var currentFacet = facets[ctr];

                        if (currentFacet.items != null) {
                            for (var i = 0; i < currentFacet.items.length; i++) {
                                Ads.data.acnfacets[ctr].items[i].selected = false;
                            }
                        }
                    }

                    Ads.advertisementLoadedArticles = null;
                }
                Ads.isLoaded = false;
                Ads.performSearch();
            }

            //view more
            $('#accordion-filter-results .filter-group .cta-view').on('click', function (event) {
                event.preventDefault();

                var filtername = $(this).data('filtername');
                var metadatafieldname = $(this).data('metadatafieldname');

                $('#accordion-filter-results .filter-group li.' + filtername).filter('.hidden').removeClass('hidden');
                $(this).addClass('hidden');

                //update click tracker
                for (var ctr = 0; ctr < Ads.filterCategoryViewAllIsClicked.length; ctr++) {
                    var $this = Ads.filterCategoryViewAllIsClicked[ctr];

                    if ($this.metadatafieldname == metadatafieldname && $this.clicked == false) {
                        $this.clicked = true;
                    }
                };
            });

            //sort by
            $('#accordion-filter-results .sort-options .cta').on('click', function (event) {
                event.preventDefault();

                var filtername = $(this).data('filtername');

                //clear all active sort
                $('#accordion-filter-results .sort-options .cta').removeClass('active');

                //change active sort
                $(this).addClass('active');

                //perform search
                Ads.currentPageNo = 0; //reset to 0
                $('.module-ad-cards .ad-cards').html(''); //clear all cards

                Ads.updateCurrentSort();
                Ads.isLoaded = false;
                Ads.performSearch();
            });
        }
    },
    setDefaultSorting: function () {
        Ads.currentSort = AdsConfig.defaultSorting;
        if (Ads.currentSort == null || Ads.currentSort == '') {
            var type = Ads.getAdBoxType();
            switch (type) {
                case 3: //ads
                    if (AdsConfig.enableCherryPick) {
                        Ads.currentSort = 'FeaturedSort';
                    }
                    else {
                        Ads.currentSort = 'MostRecent';
                    }

                    break;
                default: //stats, trends, and perspectives
                    Ads.currentSort = 'MostRecent';
                    break;
            }
        }
        else {

            //TODO: Remove (|| Ads.currentSort == 'MostPopular') when R1.3 will commence
            //SIR: 428904
            if ((Ads.currentSort == 'FeaturedSort' && !AdsConfig.enableCherryPick) || Ads.currentSort == 'MostPopular') {
                Ads.currentSort = 'MostRecent';
            }
        }
    },

    createFilterGroup: function (filterName, filterTitle, filterItems, fieldName) {
        if (typeof filterName != 'undefined' && filterName.length > 0) {

            var viewMore = "#ViewMore";

            //check if clicked
            var itemClicked = $.grep(Ads.filterCategoryViewAllIsClicked, function (e) { if (e.metadatafieldname == fieldName) return true; });
            var isClicked = itemClicked.length <= 0 ? false : itemClicked[0].clicked;

            var container = '<div class="col-sm-12 filter-group">{0}</div>'

            var content = ('<h3>{0}</h3><hr>').replace('{0}', filterTitle.toUpperCase());

            content += '<ul>';
            if (typeof filterItems != undefined && filterItems != null) {
                for (var ctr = 0; ctr < filterItems.length; ctr++) {
                    var filterItem = filterItems[ctr];

                    content += ('<li class="filter ' + filterName + ' {0}"><input type="checkbox" data-filtername="{1}" data-metadatafieldname="{2}" data-term="{6}" {5}>{3} ({4})</li>')
                        .replace('{0}', !isClicked && ctr >= Ads.maxFilterItemsLoaded ? 'hidden' : '')
                        .replace('{1}', filterName)
                        .replace('{2}', fieldName)
                        .replace('{3}', filterItem.term)
                        .replace('{4}', filterItem.count)
                        .replace('{5}', filterItem.selected ? 'checked' : '')
                        .replace('{6}', filterItem.term);
                }
            }
            content += '</ul>';

            content += (!isClicked && typeof filterItems != undefined && filterItems != null && filterItems.length > Ads.maxFilterItemsLoaded)
                ? '<a class="cta-view view-more" href="#" data-filtername="' + filterName + '" data-metadatafieldname="' + fieldName + '" data-analytics-content-type= "cta" data-analytics-link-name="+' + $(viewMore).val().toLowerCase() + '">+' + $(viewMore).val() + '</a>' : '';

            return container.replace('{0}', content);
        }

        return '';
    },
    createFilterGroupMobile: function (filterName, filterTitle, filterItems, fieldName) {
        if (typeof filterName != 'undefined' && filterName.length > 0) {
            var container = '<div class="filter">{0}</div>'

            var content = ('<select id="{0}" class="form-control dropup" name="{1}" onchange="Ads.onDropdownFilterChange(this);">').replace('{0}', filterName).replace('{1}', filterName);

            content += ('<option value="" selected="selected">{0}</option>').replace('{0}', filterTitle);
            if (typeof filterItems != undefined && filterItems != null) {
                for (var ctr = 0; ctr < filterItems.length; ctr++) {
                    var filterItem = filterItems[ctr];

                    content += ('<option value="{0}" data-metadatafieldname="{2}" {3}>{1}</option>')
                        .replace('{0}', filterItem.term)
                        .replace('{1}', filterItem.term)
                        .replace('{2}', fieldName)
                        .replace('{3}', ((Ads.currentMetadataFieldname == fieldName && Ads.currentFacetDisplayname == filterItem.term) ? 'selected="selected"' : ''));
                }
            }
            content += '</select>';

            return container.replace('{0}', content);
        }

        return '';
    },
    createSortGroup: function (sortName, isActive, sortText) {
        if (typeof sortName != 'undefined' && sortName.length > 0) {
            return ('<a class="cta sort {0}" href="#" data-filtername="{1}" data-analytics-content-type="cta" data-analytics-link-name="{3}">{2}</a>')
                .replace('{0}', isActive ? 'active' : '')
                .replace('{1}', sortName)
                .replace('{2}', sortName.toUpperCase())
                .replace('{3}', sortName.toLowerCase());

        }

        return '';
    },

    displayData: function (data) {
        if (data == null) return;

        //Bug #348943: Industry Program All Ads pages Layout: Trends and Stats - Displays error message: 'console' is undefined
        //console.log('displayData');
        //console.log(data);

        Ads.data = data;

        //display cards
        if (!Ads.isLoaded) {
            var industryResults = AdsConfig.cherryPickArticles.concat(data.documents);
            var adCards = Ads.createAdBox(industryResults);
        }
        else {
            var adCards = Ads.createAdBox(data.documents);
        }

        $('.module-ad-cards .ad-cards').append(adCards)

        if (ComponentRegistry.OptimizeImages) {
            $('.module-ad-cards .ad-cards').find("span.image-holder").imageloader();
        }

        //init cards
        Ads.initAdPackery();

        if (isMobile()) {
            if (Ads.data != null && Ads.currentPageNo * AdsConfig.countInitial >= Ads.data.total) {
                $('.module-ad-cards #IndustryAllAddsLoadMore').removeClass('visible-xs');
                $('.module-ad-cards #IndustryAllAddsLoadMore').css({ 'display': "none" });
            }
            else {
                if (!$('.module-ad-cards #IndustryAllAddsLoadMore').hasClass('visible-xs')) {
                    $('.module-ad-cards #IndustryAllAddsLoadMore').addClass('visible-xs');
                }
            }

        }

        //add card events
        switch (Ads.getAdBoxType()) {
            case 1: //1: for trends and perpective only
                $('.module-ad .media a.ui-link.video').on('click', function (event) {
                    event.preventDefault();
                    Ads.showVideo($(this).data('video-id'));
                });

                $('.module-ad .media a.ui-link.gallery').on('click', function (event) {
                    event.preventDefault();

                    var articleId = $(this).data('article-id');

                    //get article images (stub)
                    var countrySite = Ads.getCountrySite();
                    var imagedata = "{\"pid\":" + "\"" + articleId + "\"" + ", \"f\":1, \"s\":12}";
                    var path = (countrySite == null || countrySite == "") ? "/us-en/" : "/" + countrySite + "/";

                    $.ajax({
                        type: "POST",
                        url: path + 'getimagesinpagegallery.search',
                        data: imagedata,
                        async: false,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            //show gallery
                            Ads.showGallery(response);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            console.log("The server encounters an error when retrieving the images.");
                            console.log(thrownError);
                        }
                    });
                });
                break;

            case 3: //ads
                $('.module-ad .media a.ui-link.video').on('click', function (event) {
                    event.preventDefault();
                    Ads.showVideo($(this).data('video-id'));
                });

                $('.module-ad .media a.ui-link.adsGallery').on('click', function (event) {
                    event.preventDefault();

                    Ads.showAdsGallery();
                });

                break;

            default:
                break;
        }

        //display filter


        //init filters
        Ads.updateFilter();

        //init shares
        $('.module-ad-board .social-likes').socialLikes();

        //change article share colors for ads 2
        if (Ads.getAdBoxType() == 2) {
            $('.module-ad-board span.countText.clickable, .module-ad-board span.title.clickable, .module-ad-board .social-likes__icon.acn-icon.icon-share')
                .each(function () {
                    var $this = $(this);

                    var color = $this.closest('.social-share').data('color');
                    $this.addClass('color-' + color);
                });
        }

        //apply colors
        $('.social-share').filter('[data-color]').each(function () {
            var $this = $(this);
            var color = $this.data('color');


        });
    },
    showFilter: function (event) {
        var clearFilter =  $('#ads-clear-filter');
        $('.panel-heading h4').addClass('col-xs-8');
        $('#ads-clear-filter').css('display', 'block');
        $('#ads-clear-filter').attr('data-analytics-content-type', 'cta');
        if (clearFilter !== null && clearFilter !== undefined)
            $('#ads-clear-filter').attr('data-analytics-link-name', clearFilter.text().toLowerCase());

        var $id = $(event.target).closest('.module-ad-board').find('.module-ad-cards');

        //adjust width of ad cards container
        $ads = $id.find('.ad-cards').closest('div.ads');
        $id.closest('.module-ad-board').find('div.ads').addClass('col-sm-8');
        $id.closest('.module-ad-board').find('div.ads').removeClass('col-sm-12');

        //adjust width of ad cards
        //4col to 6col 
        $id.find('.ad-card.col-sm-4').addClass('col-sm-6');
        $id.find('.ad-card.col-sm-4.col-sm-8').removeClass('col-sm-8');
        $id.find('.ad-card.col-sm-4').removeClass('col-sm-4');

        //8col to 12col
        $id.find('.ad-card.col-sm-8').addClass('col-sm-12');
        $id.find('.ad-card.col-sm-8').removeClass('col-sm-8');

        //if filter is right aligned, move cards to temp container
        var $adfilter = $(event.target).closest('.ad-filter');
        if ($adfilter.hasClass('right') && !isMobile()) {
            $ads = $adfilter.parent().find('div.ads');

            //copy ads content
            adsContent = $ads.html();

            //clear adds on bottom container
            $ads.html('');
            $ads.addClass('hidden');

            //add ads on top container
            $adsRightTemp = $adfilter.parent().find('.ads-right-temp');
            $adsRightTemp.html(adsContent);
            $adsRightTemp.removeClass('hidden');

            //change offset of filter
            $adfilter.removeClass('col-sm-offset-8');
        }

        //re-initialize packery
        Ads.initAdPackery();

        //add open indicator on filter
        $adfilter.find('.module-ad-cards-filter').addClass('open-filter');
    },
    hideFilter: function (event) {
        $('.panel-heading h4').removeClass('col-xs-8');
        $('#ads-clear-filter').css('display', 'none');
        var $id = $(event.target).closest('.module-ad-board').find('.module-ad-cards');

        //adjust width of ad cards container
        $id.closest('.module-ad-board').find('div.ads').addClass('col-sm-12');
        $id.closest('.module-ad-board').find('div.ads').removeClass('col-sm-8');

        //adjust width of ad cards          
        //4col to 6col -- UNDO
        $id.find('.ad-card.col-sm-6').addClass('col-sm-4');
        $id.find('.ad-card.col-sm-6.col-sm-12').removeClass('col-sm-12');
        $id.find('.ad-card.col-sm-6').removeClass('col-sm-6');

        //8col to 12col -- UNDO
        $id.find('.ad-card.col-sm-12').addClass('col-sm-8');
        $id.find('.ad-card.col-sm-12').removeClass('col-sm-12');

        //if filter is right aligned, move cards to temp container
        var $adfilter = $(event.target).closest('.ad-filter');
        if ($adfilter.hasClass('right') && !isMobile()) {
            $ads = $adfilter.parent().find('div.ads');

            //copy ads content from temp
            $adsRightTemp = $adfilter.parent().find('.ads-right-temp');
            adsContent = $adsRightTemp.html();

            //clear adds on top container
            $adsRightTemp.html('');
            $adsRightTemp.addClass('hidden');

            //add ads to bottom container
            $ads.html(adsContent);
            $ads.removeClass('hidden');

            //change offset of filter
            $adfilter.addClass('col-sm-offset-8');
        }

        //re-initialize packery            
        Ads.initAdPackery();

        //remove open indicator on filter
        $adfilter.find('.module-ad-cards-filter').removeClass('open-filter');
    },

    mobileModeOn: function () {
        $('.module-ad-board .module-ad-cards .ad-card').addClass('col-xs-12');
    },
    mobileModeOff: function () {
        $('.module-ad-board .module-ad-cards .ad-card').removeClass('col-xs-12');
    },

    initAdPackery: function () {
        //use timeout to delay the code execution.
        //without delay, distances between items can SOMETIMES be incorrect

        clearTimeout(Ads.timeoutHandle);

        Ads.timeoutHandle = setTimeout(function () {
            var container = document.querySelector('.ad-cards.packery-container');
            if (container != 'undefined' && container != null) {
                var packery = new Packery(container, {
                    containerStyle: null
                });
            }

        }, 100);
    },
    getQueryDataCategoryIndustries: function () {
        return '"industry1","industry2","industry3"';
    },
    getQueryData: function () {
        var queryData = {
            "contentType": '"' + AdsConfig.contentType + '"',
            "industries": Ads.getQueryDataCategoryIndustries(),
            "pageNo": 0, "pageNo": 0, "pageCount": 12
        };

    },

    formatValue: function (val) {
        if (val != null)
            return val.replace(/\\/gi, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"");

        return val;
    },
    getSearchPath: function () {
        var path = window.location.pathname;
        if (path.substr(path.length - 1) != "/") {
            var pathArray = window.location.pathname.split('/');
            path = "";
            for (var i = 0; i < pathArray.length - 1; i++) {
                path += pathArray[i] + "/";
            }
        }

        return path;
    },
    getCountrySite: function () {
        return typeof AdsConfigCountrySite == 'undefined' ? 'us-en' : AdsConfigCountrySite;
    },
    getCherryPickArticles: function () {
        //Expected: “{guid}, {guid}, {guid}”
        var list = '';

        for (var ctr = 0; ctr < AdsConfig.cherryPickArticles.length; ctr++) {
            if (AdsConfig.cherryPickArticles[ctr].SitecoreItemId != null && AdsConfig.cherryPickArticles[ctr].SitecoreItemId != '') {
                list += ctr > 0 ? ',' : '';
                list += AdsConfig.cherryPickArticles[ctr].SitecoreItemId;
            }
        }

        return list;
    },
    getFilterItems: function (metadata) {
        switch (metadata) {
            case 'contenttype':
                return '';
                break;
            case 'servicecapability':
                return '';
                break;
            default:
                return '';
        }
    },
    getSearchFacetsInitial: function () {
        var dfTemplate = '{"facetdisplayname":"{facetdisplayname}","metadatafieldname":"{metadatafieldname}","excludedmetadataitems":{excludeditems},"items":[{items}],"excludedmetadataids":{excludedids}}';
        var df = '[';
        for (var i = 0; i < AdsConfig.keywordSearchFilter.length; i++) {
            var facet = AdsConfig.keywordSearchFilter[i];
            df += dfTemplate
                .replace('{facetdisplayname}', facet.facetdisplayname)
                .replace('{metadatafieldname}', facet.metadatafieldname)
                .replace('{items}', facet.items)
                .replace('{excludeditems}', JSON.stringify(facet.excludedmetadataitems))
                .replace('{excludedids}', JSON.stringify(facet.excludedmetadataids));

            if ((i + 1) < AdsConfig.keywordSearchFilter.length) {
                df += ',';
            }

        }
        df += ']';

        return JSON.stringify(df);
    },
    getUpdatedFacets: function () {
        var facets = Ads.data.acnfacets;

        for (var ctr = 0; ctr < facets.length; ctr++) {
            var currentFacet = facets[ctr];
            var currentFacetItems = [];

            for (var ctrItems = 0; ctrItems < currentFacet.items.length; ctrItems++) {
                var currentItem = currentFacet.items[ctrItems];

                switch (isMobile()) {
                    case true:
                        if (currentItem.selected) {
                            currentFacetItems.push(currentItem);
                        }
                    default:
                        var itemInFilter = $('input[type=checkbox][data-metadatafieldname="' + currentFacet.metadatafieldname + '"][data-term="' + currentItem.term + '"]');

                        if (itemInFilter.length > 0 && itemInFilter.prop('checked')) {
                            currentItem.selected = true;
                            currentFacetItems.push(currentItem);
                        }
                }
            }

            currentFacet.items = currentFacetItems;
        }

        return facets;
    },
    getSearchFacets: function () {
        //check if initial search
        if (Ads.data == null) {
            return this.getSearchFacetsInitial();
        }

        var updatedFacets = Ads.getUpdatedFacets();
        return '"' + Ads.formatValue(JSON.stringify(updatedFacets)) + '"';
    },

    onDropdownFilterChange: function (currentFilter) {

        Ads.currentFacetDisplayname = currentFilter.value;
        Ads.currentMetadataFieldname = currentFilter.name;

        var facets = Ads.data.acnfacets;
        for (var ctr = 0; ctr < facets.length; ctr++) {
            var currentFacet = facets[ctr];

            if (currentFacet.metadatafieldname == Ads.currentMetadataFieldname) {
                for (var i = 0; i < currentFacet.items.length; i++) {
                    Ads.data.acnfacets[ctr].items[i].selected = (currentFacet.items[i].term == Ads.currentFacetDisplayname);
                }
            }
        }

        //perform search
        Ads.advertisementLoadedArticles = null;
        Ads.currentPageNo = 0; //reset to 0
        $('.module-ad-cards .ad-cards').html(''); //clear all cards
        Ads.isLoaded = false;
        Ads.performSearch();
    },
    performSearch: function (industryAllAdsFilter) {
        //check if current items already exceed total count
        if (Ads.data != null && Ads.currentPageNo * AdsConfig.countInitial >= Ads.data.total) {
            return;
        }

        var countrySite = Ads.getCountrySite();
        var searchParamSourceId = AdsConfig.searchMetadataParametersId;
        var cherryPickArticles = this.getCherryPickArticles();    //Expected: “{guid}, {guid}, {guid}”

        var returnType = 'ArticleItem';
        var queryType = 'featuredarticles.search';
        var pageTemplate = (AdsConfig.pageTemplate == null || AdsConfig.pageTemplate == 'undefined') ? 'DotComArticlePage,DotComOpenLayoutPage' : AdsConfig.pageTemplate;

        var pt = '\"' + pageTemplate + '\"';
        var cp = '\"' + cherryPickArticles + '\"';
        var sortBy = Ads.getSortByParam();
        var sp = '\"' + searchParamSourceId + '\"';
        var rt = '\"' + returnType + '\"';
        var enableDateFilter = (AdsConfig.enableDateFilter == null || AdsConfig.enableDateFilter == 'undefined') ? false : AdsConfig.enableDateFilter;

        var from = (Ads.currentPageNo * AdsConfig.countInitial) + 1;
        Ads.currentPageNo++;

        var size = AdsConfig.countInitial;
        var df = typeof industryAllAdsFilter != 'undefined' ? industryAllAdsFilter : this.getSearchFacets();

        if (typeof digitalData != 'undefined' && digitalData.pageInstanceId != "") {
            currentPage = digitalData.pageInstanceId.toLowerCase();
        }
        else {
            currentPage = document.URL.toLowerCase();
        }

        var jsonUpdate = {
            page: currentPage,
            cacheFilter: df,
            activeSort: Ads.currentSort
        }

        acncm.CacheManager.write("industryAllAdsCache", JSON.stringify(jsonUpdate));


        //var df = '\"' + FormatValue(JSON.stringify(null)) + '\"'; //facets
        var data = "{\"pt\":" + pt + ", \"sp\":" + sp + ", \"rt\":" + rt + ", \"f\":" + from + ", \"s\":" + size + ", \"sb\":" + sortBy + ", \"df\":" + df + ", \"cp\":" + cp + ", \"edf\":" + enableDateFilter + "}";

        var path = (countrySite == null || countrySite == "") ? "/us-en/" : "/" + countrySite + "/";

        //graceful error message
        var errorMessage = $("#graceful-error-message").val();
        var errorElement = "<div class='col-sm-12'><p class='align-center'>{0}</p></div>";

        // Performs REST service call.
        //Bug #348943: Industry Program All Ads pages Layout: Trends and Stats - Displays error message: 'console' is undefined
        //console.log(data);
        $('#pre-loader').css("display", "block");
        $.ajax({
            type: "POST",
            url: path + queryType,
            data: data,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response != null) {
                    Ads.displayData(response);

                    if (Ads.initialLoad) {
                        Ads.initialLoad = false;
                    }
                }
                else {
                    $(".ad-filter").hide();
                    $(".module-ad-board").append(errorElement.replace('{0}', errorMessage));
                    $(".module-ad-cards").remove();
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                sortOnly = false;

                $(".ad-filter").hide();
                $(".module-ad-board").append(errorElement.replace('{0}', errorMessage));

                //Bug #348943: Industry Program All Ads pages Layout: Trends and Stats - Displays error message: 'console' is undefined
                //console.log(xhr.status + ' ' + ajaxOptions + ' ' + thrownError);
            },
            complete: function () {
                setTimeout(function () {
                    $('#pre-loader').hide();
                }, 100);
            }
        });
    },
    loadMore: function () {
        Ads.performSearch();
    },

    updateCacheValue: function (isCollapsed) {
        var industryAllAdsCache = acncm.CacheManager.read("industryAllAdsCache");

        if (typeof industryAllAdsCache != 'undefined') {
            var industryAllAdsJson = JSON.parse(industryAllAdsCache);

            var jsonUpdate = {
                page: industryAllAdsJson.page,
                cacheFilter: industryAllAdsJson.cacheFilter,
                activeSort: industryAllAdsJson.activeSort,
                isFilterCollapsed: isCollapsed
            }

            acncm.CacheManager.write("industryAllAdsCache", JSON.stringify(jsonUpdate));
        }
    },

    initControls: function () {
        var filterOptions = (AdsConfig.filtername == null || AdsConfig.filtername == undefined) ? '' : AdsConfig.filtername;
        var template = '<a href="#" onclick="return false;"data-analytics-content-type="cta" data-analytics-link-name="' + filterOptions.toLowerCase() + '">{0}</a>';
        $('.module-ad-board .module-ad-cards-filter .panel-title').html(template.replace('{0}', filterOptions.toUpperCase()));

        $('.module-ad-board .module-ad-cards button').on('click', function () {
            Ads.loadMore();
        });
    },
    init: function () {
        //Bug #348943: Industry Program All Ads pages Layout: Trends and Stats - Displays error message: 'console' is undefined
        //console.log('ads.init');

        if (typeof AdsConfig != 'undefined' && AdsConfig != null) {
            this.setDefaultSorting();
            this.initControls();
            this.performSearch();


        }
    }
};

function ImageLoadChecker() {
    $("div.media").each(function () {
        if ($(this).children().length == 0) {
            $(this).hide();
        }
        else {
            var img = $(this).find(".img-responsive");
            if (img != null || img != undefined) {
                imgSrc = $(this).find(".img-responsive").attr("src");
                if (imgSrc == "" || imgSrc == null || imgSrc == "null") {
                    $(this).find(".img-responsive").closest("div.media").hide();
                }
                else {
                    $(this).find(".img-responsive").on("error", function () {
                        $(this).closest("div.media").hide();
                    });
                }
            }
        }
    });
}

//on ready 
$(function () {
    if (ComponentRegistry.IndustryAllAdsFilter) {
        //open
        $(window).on('show.bs.collapse', function (event) {
            if (ComponentRegistry.IndustryAllAdsFilter) {
                Ads.updateCacheValue(false);
                setTimeout(function () { Ads.showFilter(event); }, 500);
            }
        });

        //close
        $(window).on('hide.bs.collapse', function (event) {
            if (ComponentRegistry.IndustryAllAdsFilter) {
                Ads.updateCacheValue(true);
                setTimeout(function () { Ads.hideFilter(event); }, 500);
            }
        });

        //resize
        $(window).on('resize ready', function (event) {
            if (ComponentRegistry.IndustryAllAdsFilter) {
                if (isMobile()) {
                    //add col-xs-12 to cards
                    Ads.mobileModeOn();
                }
                else {
                    //remove col-xs-12 on cards
                    Ads.mobileModeOff();
                }
            }
        });

        //auto loader
        $(window).on("scroll", function () {
            if (!isMobile()) {

                var containerOffsetTop = parseInt($(".module-ad-cards").offset().top);
                var containerHeight = parseInt($(".module-ad-cards").height());
                var scrollTop = parseInt($(window).scrollTop());
                var windowHeight = parseInt($(window).height());
                var scrollHeight = scrollTop + windowHeight;
                var totalHeight = containerHeight + containerOffsetTop;

                if (scrollHeight - totalHeight >= 0) {
                    Ads.loadMore();
                    ImageLoadChecker();
                }
            }
            Ads.isLoaded = true;
        });

        var industryAllAdsCache = acncm.CacheManager.read("industryAllAdsCache");

        if (typeof industryAllAdsCache != 'undefined') {
            var industryAllAdsJson = JSON.parse(industryAllAdsCache);


            if (typeof digitalData != 'undefined' && digitalData.pageInstanceId != "") {
                currentPage = digitalData.pageInstanceId.toLowerCase();
            }
            else {
                currentPage = document.URL.toLowerCase();
            }

            if (currentPage == industryAllAdsJson.page) {
                Ads.currentSort = industryAllAdsJson.activeSort;

                //TODO: Remove below implementation when R1.3 will commence
                //SIR: 428904
                if (Ads.currentSort == 'MostPopular') {
                    Ads.currentSort = 'MostRecent'
                }
                //End here

                Ads.initControls();
                Ads.performSearch(industryAllAdsJson.cacheFilter);


            }
            else {
                Ads.init();
            }
        }
        else {
            Ads.init();
        }

        ImageLoadChecker();
    }
});

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\type-to-search.js
//$(function () {
//    if (typeof disableWelcomeOverlay != 'undefined') {
//        if (disableWelcomeOverlay.toLowerCase() == 'true') {
//            closeCoachMark();
//            $('#coach-marks-screen').modal('hide');
//        }
//    }

//    //showCoachMark();
//    var keyword = "";
//    var ctrlMode = false;
//    if (typeof disableSmartSearch != 'undefined') {
//        if (disableSmartSearch.toLowerCase() != 'true') {
//            $(document).on("keydown", function (event) {
//                if (event.ctrlKey) {
//                    ctrlMode = true;
//                } else {
//                    ctrlMode = false;
//                }
//            });

//            $(document).keypress(function (e) {
//                var activeElement = $(document.activeElement).prop("tagName").toLowerCase();
//                if (!ctrlMode) {
//                    var isBody = (activeElement == 'body') || (activeElement == 'div');
//                    if ($('#coach-marks-screen').is(':hidden')) {
//                        if ($("#search").attr('class').indexOf('hide') > -1) {
//                            if (isBody && activeElement != 'input') {
//                                if (e.which <= 122 && e.which >= 48) {
//                                    $("#search").removeClass("hide");
//                                    $("#keywords").focus();
//                                }

//                                if (e.which == 27) {
//                                    $("#close").click();
//                                }
//                            }
//                        }
//                    }
//                }
//            });
//        }

//        if (disableSmartSearch.toLowerCase() != 'true') {
//            $('#icon-nav-top-keyboard').click(function () {
//                typeToSearchFocus();
//            });

//            $('#icon-type-to-search').click(function () {
//                typeToSearchFocus();
//            });

//            $('#icon-type-to-search-mobile').click(function () {
//                typeToSearchFocus();
//            });
//        }

//        $("#close").click(function () {
//            keyword = '';
//            $("#keywords").val('');
//            $('#search-result').empty();
//            $("#search").addClass("hide");
//        });

//        $('#btnContinue').click(function () {
//            closeCoachMark();
//        });

//        $('#keywords').keyup(function (e) {
//            if (e.which == 27) {
//                $("#close").click();
//            }
//        });

//        $('#keywords').autocomplete({
//            search: function (event, ui) {
//                $('#search-result').empty();
//            },
//            source: function (request, response) {
//                var data = {
//                    keywords: request.term
//                };

//                $.ajax({
//                    url: '/api/sitecore/Search/SearchResult',
//                    timeout: 50000,
//                    data: data,
//                    success: function (data) {
//                        response($.map(data, function (item) {
//                            return {
//                                title: item.Title,
//                                url: item.Url,
//                                desc: item.ShortDescription
//                            };
//                        }))
//                    }
//                });
//            },
//            minlength: 5,
//        }).data('ui-autocomplete')._renderItem = function (ul, item) {
//            $(ul).remove();
//            return $('<div class="result"/>')
//            .data('item.autocomplete', item)
//            .append('<h1><a href="' + item.url + '">' + item.title + '</a></h1><p>' + item.desc + '</p>')
//            .appendTo($('#search-result'));
//        };
//    }
//});

//// cookieName for coach mark
//var cookieName = 'acn_coach_mark';

//function typeToSearchFocus() {
//    if ($('#coach-marks-screen').is(':hidden')) {
//        $("#search").removeClass("hide");
//        $("#keywords").focus();
//    }
//}

//function showCoachMark() {
//    var isCoachMarkSeen = getCoachMarkCookie(cookieName);
//    if (isCoachMarkSeen == null || isCoachMarkSeen == '') {
//        // show coach mark for the first time.
//        $("#coach-marks-screen").removeClass("hide");
//        $('#coach-marks-screen').modal('show');
//        $('#header-topnav').children().addClass('disable-pointers');
//        $('#coach-marks-screen').addClass('disable-pointers');
//        $('#btnContinue').css('pointer-events', 'auto');
//        $('#header-topnav').css('z-index', '1000');

//        //Bug #212935: For IE browsers that doesnt handle pointer-events:none
//        $('#coach-marks-screen').unbind();
//    }
//}

//// Set Coachmark Cookie.
//function setCoachMarkCookie(cookieName, cookieValue) {
//    document.cookie = cookieName + "=" + cookieValue + "; path=/";
//}

//// Get Coachmark Cookie.
//function getCoachMarkCookie(cookieName) {
//    var cookieSets = document.cookie.split(';');
//    var name = cookieName + "=";
//    var cookieValue = '';

//    for (var i = 0; i < cookieSets.length; i++) {
//        var cookieItem = $.trim(cookieSets[i]);
//        if (cookieItem.indexOf(name) == 0) {
//            cookieValue = cookieItem.substring(name.length, cookieItem.length);
//        }
//    }

//    return cookieValue;
//}

//// Closes CoachMark screen.
//function closeCoachMark() {
//    setCoachMarkCookie(cookieName, '1');
//    $("#coach-marks-screen").addClass('hide');
//    $('#header-topnav').children().removeClass('disable-pointers');
//    $('#header-topnav').removeAttr('style');
//}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\function.carousel.js
// version 2
// The Containers & its elements

function CovertibleCarousel() {
    $('.carousel-convertible').each(function () {
        var breakpoint = $(this).hasClass('carousel-break-sm') ? 768 : 480;
        var root = '#' + $(this)[0].id;
        var inner = root + " .carousel-inner";
        var indicators = root + " .carousel-indicators";

        if ($(window).width() < breakpoint && !$(root).hasClass('converted-sm')) {
            var html = "";
            $(inner).data('html-lg', $(inner).html());
            $(root).find('.item-sm').each(function (index) {
                if (index == 8) return false; //don't need more than Eight carousel
                var xhtml = $(this).addClass('item').wrap('<p/>').parent().html();
                html += xhtml;
                var slidesInLg = $(indicators).find('li').length;
                if (slidesInLg <= index)
                    $(indicators).append("<li data-target='" + root + "' data-slide-to='" + index + "'  class='break-sm' ></li>")
            });
            $(inner).html(null).html(html);
            $(root).addClass('converted-sm')
                .find('item-sm').first().addClass('active');
        }
        else if ($(window).width() > breakpoint && $(root).hasClass('converted-sm')) {
            $(root).removeClass('converted-sm');
            var html = $(inner).data('html-lg');
            $(inner).html(html);
            $(indicators).find('.break-sm').remove();
        }
    });//convertible each
}

function isBreakPoint(bp) {
    var bps = [320, 480, 768, 1024],
    w = $(window).width(),
    min, max
    for (var i = 0, l = bps.length; i < l; i++) {
        if (bps[i] === bp) {
            min = bps[i - 1] || 0
            max = bps[i]
            break
        }
    }
    return w > min && w <= max
}

function pauseSleepCarouselInMobile() {
    $(".sleep-carousel").carousel();
    if (isBreakPoint(480) == false) {
        //Pause the carousel
        $(".sleep-carousel").carousel('pause');
    }
}


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\homepage.js
/*  version="3" */

$(function () {
    $('ol.carousel-indicators span.acn-icon, span#playPauseIcon').attr("title", "icon-pause");
    $('ol.carousel-indicators span.acn-icon, span#playPauseIcon').attr("aria-label", "icon-pause");
    $(".play-pause-button").attr("aria-label", "icon-pause");
    $(".play-pause-button").on("click", function () {
        var playPauseStatusSpan = $(this).children(".acn-icon");
        var playPauseStatus = $(playPauseStatusSpan).data("play-pause-status");

        $(this).closest(".carousel").carousel(playPauseStatus);
        if (playPauseStatus == 'pause') {
            $(playPauseStatusSpan).data("play-pause-status", "cycle").removeClass("icon-pause").addClass("icon-play");
            $(playPauseStatusSpan).attr("aria-label", "icon-play");
            $('.play-pause-button').attr("aria-label", "icon-play");
            $(playPauseStatusSpan).attr("title", "icon-play")
        } else {
            $(playPauseStatusSpan).data("play-pause-status", "pause").removeClass("icon-play").addClass("icon-pause");
            $(playPauseStatusSpan).attr("aria-label", "icon-pause");
            $('.play-pause-button').attr("aria-label", "icon-pause");
            $(playPauseStatusSpan).attr("title", "icon-pause")
        }
    });

    $("span#playPauseIcon").on("click", function () {
        if ($(this).hasClass("icon-pause")) {
            $("span#playPauseIcon").attr("title", "icon-play");
            $("span#playPauseIcon").attr("aria-label", "icon-play")
        }
        else {
            $("span#playPauseIcon").attr("title", "icon-pause");
            $("span#playPauseIcon").attr("aria-label", "icon-pause")
        }

    });

    jumpToCarouselSlide();

    if ($.trim($("div#toolbar-container tr td").text()) == "") {
        //Bug 212277: Instead of setting the display to none, just set the visibility to hidden. (fix for IE issue on white space)
        $("div#toolbar-container").css('visibility', 'hidden');
    }

    $('div.hero-header h2.page-identifier p').replaceWith
    (
        function () { return $(this).contents(); }
    );

    $('.video-back').on('click touchstart', function (e) {
        var url = $(this).data("url");
        if ((url != "") && ($(e.target).attr("id") != "playPauseIcon")) {
            var target = $(this).data("target").toLowerCase();
            if (target == "true") {
                window.open(url, '_blank');
            }
            else {
                window.open(url, '_self');
            }
        }
    });

    function jumpToCarouselSlide() {
        var paginationNumber = getParameterByName("PaginationNumber");
        var slideIndex = parseInt(paginationNumber) - 1;
        var heroCarousel = $('#hero-carousel');
        var heroCarouselPlayButton = $(heroCarousel).find(".play-pause-button");

        if (paginationNumber !== "" && !isNaN(slideIndex)) {
            var carouselIndicators = $("#hero-carousel .carousel-indicators li[role='navigation']");

            if (slideIndex >= 0 && slideIndex < carouselIndicators.length) {

                window.onload = function () { $(heroCarousel).carousel("pause"); }

                $(heroCarouselPlayButton).trigger("click");

                if (slideIndex > 0) {
                    //set "active" pagination dot to specified marquee item...
                    $(heroCarousel).carousel(slideIndex);
                }
            }
        }
    }
});


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\PrintPreview.js
/* version="2" */
function PrintContent(TranslatedFindThisArticle, targetId) {

    var winprint;
    var strPrintHtml;
    var strOptions;
    var pageUrl = document.location.href;
    var strTitle = document.title;
    var strFooterHtml = "";
    var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

    //var strPageContentHtml_Hero = $("div.carousel-inner").html();
    //Bug 356430: Update code to print event details only
    //Begin
    var strPageContentHtml_Main = "";
    if (typeof targetId === "undefined") {
        $.each($('.page-title, .block-title, .ui-container .ui-content-box').not('.not-printable'),
            function () {
                strPageContentHtml_Main += $(this).html();
            })

        $.each($('div, p').filter('.footer-textlink, .footer-copyright'),
            function () {
                strFooterHtml += $(this).html().replace(/&nbsp;&nbsp;/gi, '');
            })
    }
    else {
        var target = $('#' + targetId);
        if (target.parent().hasClass('event')) {
            strPageContentHtml_Main = $("<div/>").append($('.social-share, .controls', target.parent().html()).remove().end()).html();
            pageUrl = "";
        }
    }
    //End

    // .page-title, .carousel-inner

    // Get main content area and footer html markup

    // Build the print page html string

    strPrintHtml = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">';
    strPrintHtml += '<html><head>';
    strPrintHtml += '<title>' + strTitle + '</title>';
    strPrintHtml += '<link type="text/css" rel="stylesheet" href="/Content/styles/acn/MediaPrint.css"/>';
    strPrintHtml += '</head><body>';
    strPrintHtml += '<div class="print-logo-container">';
    strPrintHtml += '<img class="logo" src="/Content/images/acn-signature-gray-print.jpg"/></div>';
    strPrintHtml += '<div id="popup-content" class="popup-content">';
    //strPrintHtml += strPageContentHtml_Hero;
    strPrintHtml += strPageContentHtml_Main;
    strPrintHtml += '</div>';
    strPrintHtml += '<div class="print-footer-section">';
    strPrintHtml += '<div class="print-url-container fsize-c">';
    if (TranslatedFindThisArticle != "") {
        strPrintHtml += '<div class="print-url-lbl"><strong>' + TranslatedFindThisArticle + ':</strong></div>';
    }
    strPrintHtml += '<a class="print-url-link" href="' + pageUrl + '" target="_blank">';
    strPrintHtml += pageUrl + '</a></div>';
    strPrintHtml += '<div id="print-footer-textlink" class="print-footer-textlink">';
    strPrintHtml += '<div class="acn-footer fsize-c">' + strFooterHtml + '</div>';
    strPrintHtml += '</div></div></body></html>';

    strOptions = "toolbar=0,location=0,directories=0,menubar=0,status=0,resizable=1,scrollbars=1,";
    strOptions += "width=760,height=560,left=100,top=25";

    // Create the popup print page window
    winprint = window.open(window.location.href, "", strOptions);
    winprint.document.open();
    winprint.document.write(strPrintHtml);
    winprint.document.close();

    if (isSafari) {
        winprint.setTimeout(winprint.print, 300);
    }
    else if (/msie|MSIE 8/.test(navigator.userAgent)) {
        winprint.print();
    }
    else {
        //winprint.print();
        //Bug 288060: .Com Layout - Content Page: The the print button generates  blank pages
        winprint.onload = function () { winprint.print(); }
    }

    winprint.focus();

    // Make the links unclickable
    var linksCollection = winprint.document.getElementById("popup-content").getElementsByTagName("a");
    for (var i = 0; i < linksCollection.length; i++) {
        $(linksCollection[i]).removeAttr("href");
    }

    // Remove inline styles in Div
    var inLineDivStyleCollection = winprint.document.getElementById("popup-content").getElementsByTagName("div");
    for (var j = 0; j < inLineDivStyleCollection.length; j++) {
        if ($(inLineDivStyleCollection[j]).parent("div").attr("id") != "authors-carousel") {
            $(inLineDivStyleCollection[j]).removeAttr("style");
        }
    }

    // Remove inline styles in Span
    var inLineSpanStyleCollection = winprint.document.getElementById("popup-content").getElementsByTagName("span");
    for (var h = 0; h < inLineSpanStyleCollection.length; h++) {
        $(inLineSpanStyleCollection[h]).removeAttr("style");
    }

    // Remove link titles when hovered
    var linkTitlesCollection = winprint.document.getElementById("popup-content").getElementsByTagName("a");
    for (var m = 0; m < linkTitlesCollection.length; m++) {
        $(linkTitlesCollection[m]).removeAttr("title");
    }

    // Remove inline styles in links at footer textlinks
    if (winprint.document.getElementById("print-footer-textlink") != null) {
        var footerTextlinksCollection = winprint.document.getElementById("print-footer-textlink").getElementsByTagName("a");
        for (var p = 0; p < footerTextlinksCollection.length; p++) {
            $(footerTextlinksCollection[p]).removeAttr("style");
        }
    }

    // Add pipebars after each footer textlinks
    if (winprint.document.getElementById("print-footer-textlink") != null) {
        var footerTextlinksSpan = winprint.document.getElementById("print-footer-textlink").getElementsByTagName("a");
        for (var q = 0; q < footerTextlinksSpan.length; q++) {
            $(footerTextlinksSpan[q]).after("<span class=\"pipebar\">&nbsp;</span>");
        }
    }

    // Remove inline styles in span at footer textlinks
    if (winprint.document.getElementById("print-footer-textlink") != null) {
        var inLineSpanStyleFooterCollection = winprint.document.getElementById("print-footer-textlink").getElementsByTagName("span");
        for (var r = 0; r < inLineSpanStyleFooterCollection.length; r++) {
            $(inLineSpanStyleFooterCollection[r]).removeAttr("style");
        }
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\common-elements.js
/*  version="37" */

$(function () {
    FooterElement.AssignFooterId();
    $(window).on("resize", function () { FooterElement.AssignFooterId(); });
    RenderCarouselHeadlineVideoOverlay();

    if (window.location.pathname.toLowerCase().indexOf("jp-ja/careers") == -1 && window.location.pathname.toLowerCase().indexOf("jp-ja") >= 1) {
        $('body').addClass('jp-ja-custom-css');
    }


    $("#cookie-disclaimer-short").on('click', function () {
        $(this).hide();
        $('#cookie-disclaimer-long').removeClass('hide');
    });

    //Hero Carousel
    $('.carousel-headline').find("p").each(function () {
        if ($(this).attr('style') != '') {
            $(this).contents().unwrap();
        }
    });

    $('.header-body').find("p").each(function () {
        if ($(this).attr('style') != '') {
            $(this).contents().unwrap();
        }
    });

    $('.cta-container').find("p").each(function () {
        if ($(this).attr('style') != '') {
            $(this).contents().unwrap();
        }
    });

    $('#hero-carousel').on('slid.bs.carousel', function () {
        $('#hero-carousel .item.active video').each(function () {
            resizeHeroVideo($(this), true);
        });
    });

    function getVideoAndResize() {
        $('#hero-carousel video').each(function () {
            resizeHeroVideo($(this), true);
        });
    }

    getVideoAndResize();

    function resizeHeroVideo(video, isHtml5) {
        if (video && video.length > 0) {
            if (pageState.viewPortWidth < 768) {
                video.closest('.video-wrapper.hidden-xs, .hero-video-wrapper.hidden-xs').html('');
                return;
            }

            var $wrapper = video.closest('.item');
            var videoHeight = $wrapper.height();
            var videoWidth = videoHeight * 16 / 9;

            if (videoWidth < $wrapper.width()) {
                videoWidth = $wrapper.width();
                videoHeight = videoWidth * 9 / 16;
            }

            if (isHtml5) {
                video.attr({ 'height': 'auto', 'width': videoWidth + 'px' }).removeAttr('style');
            } else {
                video.attr({ 'height': videoHeight + 'px', 'width': videoWidth + 'px' }).removeAttr('style');
            }
        }
    }

    function playVideo(wrapper, playerId) {
        var iconBtn = wrapper.find('#playPauseIcon');
        try {
            var vid2 = document.getElementById(playerId).getElementsByTagName('video')[0];
            if (!vid2) {
                vid2 = document.getElementById(playerId);
            }

            if (vid2.paused) {
                vid2.play();
                iconBtn.removeClass('icon-play').addClass('icon-pause');
            }
            else {
                vid2.pause();
                iconBtn.removeClass('icon-pause').addClass('icon-play');
            }
        } catch (e) {
            var vid = document.getElementById(playerId); //$('#' + playerId);
            var state = vid.doGetCurrentPlayState();
            if (state.isPlaying) {
                vid.doPause();
                iconBtn.removeClass('icon-pause').addClass('icon-play');
            }
            else {
                vid.doPlay();
                iconBtn.removeClass('icon-play').addClass('icon-pause');
            }
        }
    }

    //RMT 5055 US12
    $(
        function () {
            var checkSocialBadge = $('div').hasClass('profile-image-container');
            var checkSocialModule = $('div').hasClass('social-general-marquee');
            var flagSocial = $('#block-hero').data('flag-social');
            var flagAuthenticated = $('#block-hero').data('flag-authenticated');
            var getSlideAnonymous = "#" + $('.item div.social-general-marquee').closest('.item').attr('id') + " .hero-title-wrapper";

            if (getSlideAnonymous.length > 0)
            {
                $(getSlideAnonymous).addClass('anonymous-header');
            }
            if (checkSocialBadge && flagSocial == "True")
            {
                var getSlideAuthenticated = "#" + $('.item div.profile-image-container').closest('.item').attr('id') + " .hero-title-wrapper";
                if (getSlideAuthenticated.length > 0)
                {
                    $(getSlideAuthenticated).addClass('social-header');
                    $(getSlideAuthenticated + ' .header-body').addClass('hidden-xs hidden-sm');
                    var checkBodyAuthenticated = $(getSlideAuthenticated + " .header-body").length
                    if (checkBodyAuthenticated == 0) {
                        var noBody = getSlideAuthenticated + " .find-careers";
                        $(noBody).addClass('blank-content');
                    }
                }
            }
            else if (checkSocialModule && flagAuthenticated == "True")
            {
                var getSlideAuthenticated = "#" + $('.item div.social-general-marquee').closest('.item').attr('id') + " .hero-title-wrapper";
                if (getSlideAuthenticated.length > 0)
                {
                    $(getSlideAuthenticated).addClass('social-header');
                    $(getSlideAuthenticated + ' .header-body').addClass('hidden-xs hidden-sm');
                    $(getSlideAuthenticated + ' .find-careers').addClass('blank-content');
                }

            }
            var checkBodyAnonymous = $(getSlideAnonymous + " .header-body").length
            if (checkBodyAnonymous == 0) {
                var noBody = getSlideAnonymous + " .find-careers";
                $(noBody).addClass('blank-content');
            }

            //RMT7211 Web Accessibility Issues - Share, Print, VideoCarousel controlsPagination Dots, Jumplinks
            $('ol.carousel-indicators li').on("keydown", function (e) {
                if (e.which == 13) {
                    $(this).trigger("click");
                }
            });

            $('span#playPauseIcon').on("keydown", function (e) {
                if (e.which == 13) {
                    $(this).trigger("click");
                }
            });

            $('div.social-likes__widget a').attr("style", "text-decoration: none !important");
            $('div.social-likes__widget a').on("keydown", function (e) {
                var _this = $(this);
                if (e.which == 13) {
                    $(this).trigger("click");
                }

                //RMT7569 sharing should be readaccessible thru the keyboard
                else if (e.which == 9 && $('div.popover-content').is(":visible")) {
                    e.preventDefault();
                    $('div.popover-content div[role="link"]').first().trigger("focus");

                    $('div.popover-content div.social-likes__widget').last().on("keydown", function (e) {
                        e.preventDefault();
                        $('div.popover.fade.bottom.in').remove();
                        $(_this).trigger("focus");
                    });

                    $('div.popover-content div[role="link"]').on("keydown", function (e) {
                        if (e.which == 13) {
                            $(this).trigger("click");
                        }
                    })

                }

                else if (e.which == 9 && $('div.social-likes-post').hasClass("social-likes_opened")) {

                    $('div.social-likes-post').each(function () {
                        e.preventDefault();
                        $(this).find('div.social-likes__widget').first().trigger("focus");
                        $(this).find('div.social-likes__widget').last().on("keydown", function (e) {
                            e.preventDefault();
                            $('div.social-likes-post').removeClass("social-likes_opened");
                            $(_this).trigger("focus");

                        });

                    });

                    $('div.social-likes-post div').on("keydown", function (e) {

                        if (e.which == 13) {
                            $(this).trigger("click");

                        }
                    });
                }
            });

            $('ol.carousel-indicators li').attr("tabindex", "0");
            $('div.social-likes-post div').attr("tabindex", "0");

            //RMT 7047 Web Accessibility for Share module on adjacent tiles.
            $('div[role="link"].social-likes__widget').attr("tabindex", "0");

            $('div.social-likes_single-w').each(function(){
                var firstIcon = $(this).find('#tooltipPopup div[role="link"].social-likes__widget').first();
                $(this).find('.social-likes__widget a').on("keydown", function (e) {
                    if (e.which == 9 && $('div#tooltipPopup').hasClass("social-likes_opened")) {
                        e.preventDefault();
                        firstIcon.trigger("focus");
                    }
                });
                $(this).find('#tooltipPopup div[role="link"].social-likes__widget').each(function(){
                    $(this).on("keydown", function (e) {
                        if (e.which == 13 && $('div#tooltipPopup').hasClass("social-likes_opened")) {
                            e.preventDefault();
                            $(this).trigger("click");
                        }
                    });
                    $(this).on("focus", function (e) {
                        $(this).css("border", "1px solid blue");
                    });
                    $(this).on("blur", function (e) {
                        $(this).css("border", "");
                    });
                });
            });

            $('div#tooltipPopup div.social-likes__widget').on("keydown", function(e){
                if($('div#tooltipPopup.social-likes_opened  div.social-likes__widget').last().is(":focus") && e.which == 9) {
                    e.preventDefault();
                    $('div#tooltipPopup').removeClass("social-likes_opened");
                    $(this).parent().parent().find('a').trigger("focus");
                }
            });


            var carouselpagination = $('.featured-section-module-carousel ol.carousel-indicators li');
            $('.featured-section-module-carousel ol.carousel-indicators li').each(function () {
                var ctr = parseInt($(this).attr("data-slide-to"), 10);
                ++ctr;
                var aLabel = "List item " + ctr;
                $(this).attr("aria-label", aLabel);
                $(this).attr("role", "navigation");

            });

            $('span#scroll-button').on("focus", function (e) {
                $('span#scroll-button').css("border", "1px solid blue");
            });

            $('span#scroll-button').on("blur", function (e) {
                $('span#scroll-button').css("border", "");
            });

            $('div.panel-heading h2').closest('div').attr('tabindex', '0');
            $('div.panel-heading').on("keydown", function () {
                if ($('button.filter-option') != '') {
                    $('button.filter-option').attr("role", "combobox");
                }
            });

            $('button.filter-option').attr("role", "combobox");

            //RMT9661-[Web Accessibility] Fix empty links in Footer on all Careers pages
            $('span a.acn-footerlink').each(function () {
                if (!$(this).text())
                    $(this).parent().remove();
            });

            $('a span.mobile-acn-footerlink').each(function () {
                if (!$(this).text())
                    $(this).parents('li').remove();
            });
        });

    //Merged from Main [Changeset: 744592]
    $('#hero-carousel .hero-video').each(function () {
        var $this = $(this);
        if ($this.hasClass('right')) {
            $this.css('left', $(window).width() - 50);
        }
    });

    //Announcement Block
    $('#announcement-carousel > .carousel-inner > .item > h5').find("p").each(function () {
        if ($(this).attr('style') != '') {
            $(this).contents().unwrap();
        }
    });

    $('#announcement-carousel > .carousel-inner > .item > a.cta').find("p").each(function () {
        if ($(this).attr('style') != '') {
            $(this).contents().unwrap();
        }
    });

    $('#announcement-carousel > .carousel-inner > div.item > p.announcement-content').each(function () {

    });


    function RenderCarouselHeadlineVideoOverlay() {
        $('.carousel-headline .carouselHeadlineVideoOverlayLink').each(function () {
            var dataTitle = $(this).attr("title");
            var dataRel = $(this).data("rel");
            var dataName = $(this).data("name");
            var dataLinkType = $(this).data("linktype");

            if ($(window).width() <= 767) {
                $(this).parent().append("<a class='carouselHeadlineVideoOverlayLink' href='#' title='" + dataTitle + "' data-rel='" + dataRel + "' data-name='" + dataName + "' data-linktype='" + dataLinkType + "'>" + $(this).text() + "</a>");
            }
            else {
                $(this).parent().append("<span class='carouselHeadlineVideoOverlayLink' title='" + dataTitle + "' data-rel='" + dataRel + "' data-name='" + dataName + "' data-linktype='" + dataLinkType + "'>" + $(this).text() + "</span>");
            }
            $(this).remove();
        });
    }

    $(window).on("resize", function () {
        setTimeout(function () {
            getVideoAndResize();
        }, 300);

        //resizeHeroVideo();
        adjustAnnouncementBlockCarousel();
        adjustCookieStatementForPreview();

        //Merged from Main [Changeset: 744592]
        $('#hero-carousel .hero-video').each(function () {
            if ($('#hero-carousel .hero-video').hasClass('right')) {
                $(this).css('left', $(window).width() - 50);
            }
        });
        RenderCarouselHeadlineVideoOverlay();
    });

    if (IsIOS()) {
        $('#hero-carousel').find('#playPauseIcon').each(function () {
            $(this).removeClass('icon-pause');
            $(this).addClass('icon-play');
        });
    }

    //fix for 384411
    var $locSelected = $('.block-title').find('#jump-link-headline');
    if ($locSelected.hasClass('dotdot')) {
        $('.richtext a:not([href])').css('top', '-170' + 'px');
    }

    /* SECONDARY-NAV START */
    var primaryNav = $('#primary-menu a');
    var secondaryNav = $('.secondary-nav');
    var secondaryNavDiv = $('.secondary-nav > .secondary-nav-item');
    var bgColor = $('.secondary-nav').css("background-color");
    var secondaryHeader = $('#secondary-header h3');
    var closeMenu = $('#menuClose');
    var secondaryHeaderDiv = $('#secondary-header, #secondary-header span');
    var globalCurrent;
    var selectedMenu;

    var displaySecNav = function () {
        var $this = $(this);
        var id = "secondaryNav-" + $this.text().toLowerCase().trim().replace(" ", "-");
        var current = ".secondary-nav #" + id;
        var maxWidthMobile = 767;

        globalCurrent = current;

        if ($(current).length > 0) {
            primaryNav.removeAttr("style");
            $this.css("background-color", bgColor);
            secondaryHeader.text($this.html().trim());
            secondaryNav.css("display", "block");
            secondaryNav.removeClass("hidden");
            secondaryNavDiv.addClass("hidden");
            $(current).removeClass("hidden");
            secondaryNavDiv.scrollTop(0);
            if ($(window).width() <= maxWidthMobile) {
                setTimeout(function () {
                    secondaryNav.css("z-index", "999999");
                }, 100)
            }
        } else {
            primaryNav.removeAttr("style");
            secondaryNav.addClass("hidden");
        }
    }

    var hideSecNav = function () {
        secondaryNavDiv.addClass("hidden");
        primaryNav.removeAttr("style");
        secondaryNav.addClass("hidden");
    }

    var clickSecondaryHeader = function () {
        secondaryNav.css("display", "none");
        secondaryNav.css("z-index", "9");

    }

    primaryNav.on("click", displaySecNav);
    closeMenu.on("click", hideSecNav);
    primaryNav.on("mouseover", displaySecNav);
    secondaryNav.on("mouseleave", hideSecNav);
    secondaryHeaderDiv.on("click", clickSecondaryHeader);

    primaryNav.on("keydown", function (e) {
        var tabsublinkcounter = 0; //alternative approach for aria-hidden
        var firstSecondaryItem = $(globalCurrent + " a.cta-after").first();
        selectedMenu = $(this);
        if (e.which == 9 && firstSecondaryItem.is(":visible")) {
            e.preventDefault();
            firstSecondaryItem.trigger("focus");
        }
    });

    var secondaryNavItems = $('.secondary-nav-item a.cta-after');
    secondaryNavItems.on("keydown", function (e) {
        var secondaryNavItemLast = $(globalCurrent + " a.cta-after").last();
        if (e.which == 9 && secondaryNavItemLast.is(":focus") && secondaryNavItemLast.is(":visible")) {
            hideSecNav();
            selectedMenu.trigger("focus");
        };
    });



    /* SECONDARY-NAV END */
    /*[RMT 6072][US111][About Accenture Page Tablet Background image] START*/
    /*Change the width of the video depending on the screen width*/
    $(".video-back .video-wrapper #carouselVideo").css('width', screen.width);
    /*[RMT 6072][US111][About Accenture Page Tablet Background image] END*/
});


function checkIfSocialLike(_obj) {
    var isSocialTag = true;
    _obj.parents().each(function () {
        if ($(this).attr('id') == "toolbar-container") {
            isSocialTag = false;
            return false;
        }
        else {
            isSocialTag = true;
        }
    });
    return isSocialTag;
}

//(RMT7211) Pause HeroCarousel when h1/button element has been focused
$('#hero-carousel h1').attr('tabindex', '0')
$('#hero-carousel h1, button').on("focus", function (e) {
    $('#hero-carousel').carousel("pause");
});

var scrollButton = $('span#scroll-button');
$('#hero-carousel ol.carousel-indicators li').last().on("keydown", function (e) {

    if (e.which == 9 && $(scrollButton).is(":visible")) {
        e.preventDefault();
        $(scrollButton).trigger("focus");
    }
});

$(scrollButton).on("keydown", function (e) {
    if (e.which == 9) {
        e.preventDefault();
        $('div.ui-content-box a').first().trigger("focus");
    }

});

function pauseCarousel() {
    if ($('#hero-carousel').length > 0 && $('.page-identifier').text() == "") {
        $('#hero-carousel').carousel(0);
        $('#hero-carousel').carousel("pause");
    }
}

function playCarousel() {
    if ($('#hero-carousel').length > 0 && $('.page-identifier').text() == "") {
        $('#hero-carousel').carousel("cycle");
    }
}

function putIdOnMainContent() {
    var blockHero = $('#block-hero');
    blockHero.find('*').each(function () {
        if ($(this).text() != "") {
            if ($(this).text()[0] != "\n" && $(this).text()[0] != '' && $(this).text()[0] != ' ' && checkIfSocialLike($(this))) {
                if ($(this).siblings().hasClass('carousel-headline')) {
                    $(this).siblings('.carousel-headline').attr("id", "maincontent-hero");
                    $(this).siblings('.carousel-headline').attr("tabindex", "-1");
                    return false;
                }
                else {
                    $(this).attr("id", "maincontent-hero");
                    $(this).attr("tabindex", "-1");
                    return false;
                }
            }
            else {
                var parentIdmatch = false;
                if ($(this).text()[0] == "\n") {
                    if ($(this).hasClass('carousel-headline')) {
                        $(this).parents().each(function () {
                            if ($(this).attr('id') == "hero-slide1") {
                                parentIdmatch = true;
                                return false;
                            }
                            else {
                                parentIdmatch = false;
                            }
                        });
                        if (parentIdmatch == true) {
                            $(this).attr("id", "maincontent-hero");
                            $(this).attr("tabindex", "-1");
                            return false;
                        }
                    }
                }
            }
        }




    });
}


function adjustAnnouncementBlockCarousel() {

    setTimeout(function () {
        var announcementBlock = $("#block-blockannouncement .announcement-block");
        var announcementCarousel = $("#block-blockannouncement .announcement-block .announcement");

        if (announcementCarousel.is(':visible')) {
            if (pageState.isDesktop) {
                var announcementItemCount = $('#announcement-carousel .carousel-inner').children('.item').length;

                if (announcementItemCount <= 1) {
                    announcementCarousel.css({ "width": "320px", "height": "191px" });
                    announcementBlock.css({ "margin-top": "132px" });
                }
            }
            else {
                announcementCarousel.css({ "width": "", "height": "" });
                announcementBlock.css({ "margin-top": "" });
            }
        }
    }, 600);
}

//SU - Global Nav adjustment on editor
function headerAdjustment() {
    $('.navbar-fixed-top').css('top', $('#scCrossPiece').height());
};

function adjustHeaderForPreview() {
    if ($('#scCrossPiece').length > 0 && $('#scFieldValues').length <= 0) {
        headerAdjustment();
    }
}
function adjustHeaderOnLoadEditor() {
    if ($('#scCrossPiece').length > 0 && $('#scFieldValues').length <= 0) {
        setTimeout(adjustHeaderOnLoadEditor);
        headerAdjustment();
    }
    else {
        setTimeout(adjustHeaderOnLoadEditor, 200);
        headerAdjustment();
    }
    hideRibbon();
}

function adjustCookieStatementForPreview() {
    var cookieNavHeight = 0;

    cookieNavHeight = $('.cookie-nav').height();

    if (IsIOS() && $('body.keyboard-shown').length > 0) {
        $('#header-topnav, #ui-wrapper').css('top', '');
    }
    else {
        $('#header-topnav, #ui-wrapper, #ui-error-wrapper').animate({
            top: cookieNavHeight + 'px'
        }, 300);
    }

    var headerTopNavHeight = $('#header-topnav').outerHeight() + cookieNavHeight;

    $('#block-jumplink').animate({
        top: headerTopNavHeight + 'px'
    }, 300);
}

function hideRibbon() {

    if (window.location.search.substring(1).toLowerCase().indexOf('sc_mode=preview') >= 0) {
        $('#scWebEditRibbon').css('display', 'none');
        $('#header-topnav').css('top', '0px');
        $('#scCrossPiece').css('height', '0px');
    }
}

function adjustJumplinkForPreview() {
    var ribbonHeight = $('#scCrossPiece').height();
    var headerTopNavHeight = $('#header-topnav').outerHeight();
    var jumplinkTopPos = headerTopNavHeight + ribbonHeight;

    $('#block-jumplink').css('top', jumplinkTopPos);

    if ($(window).scrollTop() === 0) {
        $("#block-jumplink").hide();
    }
}


$(window).on("load", function () {

    $(".module-body.announcement-block").fadeIn(1000);
    //[AJS 11/5] transfer inline scripts -start
    var disclaimerlocation = $('#cookie-statement-content').data('disclaimer-location');
    if (disclaimerlocation == "Marquee") {
        $("#ui-wrapper,#ui-error-wrapper").prepend($(".cookie-hero"));
        checkCookieStatementClosure(".cookie-hero");
        $("#disclaimer-cookiestatement").addClass("hide");
    }
    else if (disclaimerlocation == "Navigation Bar") {
        $("body").prepend($(".cookie-nav")).addClass('has-cookie-nav');
        checkCookieStatementClosure(".cookie-nav");
        $("#disclaimer-cookiestatement").addClass("hide");
    }
    else {
        checkCookieStatementClosure("#disclaimer-cookiestatement,#disclaimer-cookiestatement-mobile");
    }
    adjustAnnouncementBlockCarousel();
    //-end



    var frameParent = $('#scWebEditRibbon');
    if (frameParent.length > 0 && $('#scFieldValues').length <= 0) {
        adjustHeaderOnLoadEditor();
        //add event handler        
        var siteCoreButton = $("a[data-sc-id='QuickRibbon']", frameParent.contents());
        siteCoreButton.on('click dblclick', function () {
            setTimeout(adjustHeaderForPreview, 50);
            setTimeout(adjustJumplinkForPreview, 60);
        });
    }

    $("#btn-main-menu-mobile").on("click", function () {
        $.sidr('toggle', 'main-menu', function () {
        });
    });

    $('#btnMainMenu, #menuClose').on("click", function () {
        Navigation.collapseExpandMenu();
        var menuWidth = parseInt($('#main-menu').css("width"), 10);
        var jumplinkWidth = parseInt($('#block-jumplink').css('width'), 10);
        var jumplinkMoved = (jumplinkWidth - menuWidth) + "px";


        $.sidr('toggle', 'main-menu', function () {
            if ($('#main-menu').is(":visible")) {
                $('#block-jumplink').css('right', '260px');
            }

            else {

                $('#block-jumplink').css('right', '0px');
            }
        });
    });

    var mainMenu = $('#btnMainMenu');
    var mainMenuModal = $('#main-menu');
    var menuClose = $('#menuClose');
    var secondaryMenu = $('.secondary-nav');
    menuClose.on("keydown", function (e) {
        if (e.which == 13) {
            Navigation.collapseExpandMenu();
            menuClose.trigger("click");
            mainMenu.trigger("focus");
        }
    });

    mainMenuModal.on('keydown', function (e) {
        if (e.which == 27) {
            menuClose.trigger("click");
            mainMenu.trigger("focus");
        }
    });

    secondaryMenu.on('keydown', function (e) {
        if (e.which == 27) {
            menuClose.trigger("click");
            mainMenu.trigger("focus");
        }
    });

    mainMenu.on("keypress", function (e) {
        if (e.which == 13) {
            $(this).trigger("click");
        }
    });

    $("#btnCountrySelectorMenu").sidr({
        name: 'main-menu',
        side: 'right'
    });

    $('.keyboard-container-center').on("hover",
        function () {
            $('#smart-search-label-laptop').attr("class", "hide-smart-search-label");
            $('#smart-search-label-tablet').attr("class", "hide-smart-search-label");
            $('.hover-keyboard').show();
        },
        function () {
            $('#smart-search-label-laptop').attr("class", "visible-md visible-lg");
            $('#smart-search-label-tablet').attr("class", "visible-sm");
            $('.hover-keyboard').hide();
        }
    );

    /**RMT7134 Web Accessibility WAVE & AXE Tool Backend Issues**/
    $('#search-form .tt-hint').attr("aria-label", "hint");
    $('#search-form #keywords').attr("aria-label", "keywords");

    var pageIdentifier = $('.page-identifier');
    var devicePageIdentifier = $('.page-identifier.hidden-xs');
    if (pageIdentifier.text() == "") {
        pageIdentifier.remove();
    }

    if (devicePageIdentifier.text() == "") {
        devicePageIdentifier.remove();
    }

    if ($('div.page-title').children('h1').text() == "") {
        $('div.page-title').children('h1').remove();
    }

    if ($('#job-did-you-mean-section').attr('style', 'display: none') && $('#job-did-you-mean-section h3').text() == "") {
        $('#job-did-you-mean-section h3').remove();
    }

    if ($('h3.panel-title').text() == "" && $('#social-optin-section').attr('style', 'display: none')) {
        $('h3.panel-title').text("panel-title");
    }

    if ($('#did-you-mean-section .top-nav-bar').text() == "" && $('#did-you-mean-section').attr('style', 'display: none')) {
        $('#did-you-mean-section .top-nav-bar').text("top-nav-bar");
    }

    if ($('#social-optin-section .search-title').text() == "" && $('#social-optin-section').attr('style', 'display: none')) {
        $('#social-optin-section .search-title').text("search-title");
    }

    $('.carousel-headline').each(function () {
        if ($.trim($(this).html()) == '') {
            $(this).remove();
        }

    });

    $('.social a.acn-spr').each(function () {
        var socialIcon = $(this);
        if (socialIcon.hasClass("acn-spr facebook")) {
            socialIcon.attr("aria-label", "Follow us on Facebook");
        }

        else if (socialIcon.hasClass("acn-spr linkedin")) {
            socialIcon.attr("aria-label", "Follow us on LinkedIn");
        }

        else if (socialIcon.hasClass("acn-spr instagram")) {
            socialIcon.attr("aria-label", "Follow us on Instagram");
        }

        else if (socialIcon.hasClass("acn-spr twitter")) {
            socialIcon.attr("aria-label", "Follow us on Twitter");
        }

        else if (socialIcon.hasClass("acn-spr googleplus")) {
            socialIcon.attr("aria-label", "Follow us on Google+");
        }

        else if (socialIcon.hasClass("acn-spr youtube")) {
            socialIcon.attr("aria-label", "See Accenture on Youtube");
        }

        else if (socialIcon.hasClass("acn-spr accenture app")) {
            socialIcon.attr("aria-label", "Accenture Mobile Apps");
        }
    });

    $(".country-language-trigger").on("tap", function () {
        GetCountrySelectorData();

        $("#countryLanguageSelectorModal").appendTo("body").modal('show');

        /* Usability CR - CIO00759005 - removed menu button expland/collapse */
    });

    $(".country-language-trigger").on("click", function () {
        GetCountrySelectorData();

        $("#countryLanguageSelectorModal").appendTo("body").modal('show');

        /* Usability CR - CIO00759005 - removed menu button expland/collapse */
    });

    var geoGroupStoredData = "";
    var ACN_COUNTRY_SELECTOR_CAREERS = "CountryLanguageSelectorData_Careers";
    var ACN_COUNTRY_SELECTOR_DOTCOM = "CountryLanguageSelectorData_Dotcom";

    function GetCountrySelectorData() {
        var geoGroupStoredData = CheckCountrySelectorLocalStorage();
        var pageLocation = document.location.href.toLowerCase();

        if (geoGroupStoredData != 'null' && geoGroupStoredData != null && typeof geoGroupStoredData != 'undefined' && geoGroupStoredData.length > 0) { //check value condition for different type of browser.
            var geoObj = JSON.parse(geoGroupStoredData);

            //If local Storage is more than 1 day, remove localStorage.
            if (geoObj.DateCreated < 86400000) {
                if (pageLocation.indexOf("/careers") >= 0) {
                    localStorage.removeItem(ACN_COUNTRY_SELECTOR_CAREERS);
                }
                else {
                    localStorage.removeItem(ACN_COUNTRY_SELECTOR_DOTCOM);
                }
            }

            CountrySelectorTemplate(geoObj);
        } else {
            var serviceURL = '/api/sitecore/CountrySelectorModule/GetCountrySelectorData';
            $.ajax({
                type: 'GET',
                url: serviceURL,
                contentType: "application/json; charset=utf-8",
                data: { pageContext: pageContext }, //pulled from the country selector view variable.
                dataType: "json",
                async: true,
                cache: true,
                error: function () {
                    alert("Error while trying to get Geo Group List.");
                },
                success: function (data, status) {
                    if (data.GeoGroup != null && data.GeoGroup != "") {
                        if (data.GeoGroup.length > 0) {
                            if (typeof (Storage) !== "undefined") {
                                var dataObject = { GeoGroup: data.GeoGroup, DateCreated: new Date().getTime() }

                                if (pageLocation.indexOf("/careers") >= 0) {
                                    localStorage.setItem(ACN_COUNTRY_SELECTOR_CAREERS, JSON.stringify(dataObject));
                                }
                                else {
                                    localStorage.setItem(ACN_COUNTRY_SELECTOR_DOTCOM, JSON.stringify(dataObject));
                                }
                            }

                            CountrySelectorTemplate(data);
                        }
                    } else {
                        alert("Page Context is not set.");
                    }
                }
            })
        }
    }
    function CheckCountrySelectorLocalStorage() {
        var pageLocation = document.location.href.toLowerCase();

        if (typeof (Storage) !== "undefined") {
            if (pageLocation.indexOf("/careers") >= 0) {
                geoGroupStoredData = localStorage.getItem(ACN_COUNTRY_SELECTOR_CAREERS);
            }
            else {
                geoGroupStoredData = localStorage.getItem(ACN_COUNTRY_SELECTOR_DOTCOM);
            }
        }
        return geoGroupStoredData;
    }

    function CountrySelectorTemplate(data) {
        var geoGroupId = "#geo-group";
        var geoCountryGroupId = "#geo-country-group";
        var countrySelectorMarkup = "";

        data.GeoGroup.sort(function (a, b) { var a1 = a.GeoName, b1 = b.GeoName; if (a1 == b1) return 0; return a1 > b1 ? 1 : -1; });//sort

        $.each(data.GeoGroup, function (i, data) {
            if (data.GeoName != "") {
                var geoId = data.GeoName.toLowerCase().replace(' ', '-') + "geo";
                countrySelectorMarkup += "<div id='" + geoId + "' class='col-sm-2'>";
                countrySelectorMarkup += "<span class='overlay-title'>" + data.GeoName + "</span></div>";
            }
        });

        $(geoGroupId).html(countrySelectorMarkup);

        countrySelectorMarkup = "";
        $.each(data.GeoGroup, function (i, geo) {
            var geoId = geo.GeoName.toLowerCase().replace(' ', '-') + "-row";
            countrySelectorMarkup += "<div id='" + geoId + "' class='col-sm-2'>";
            countrySelectorMarkup += "<h4 class='visible-xs overlay-title'>" + geo.GeoName + "</h4>";

            $.each(geo.CountryGroup, function (i, countryGroup) {
                var countryId = geo.GeoName + countryGroup.CountryGroupName;
                countrySelectorMarkup += "<p class='" + countryId.toLowerCase().replace(' ', '-') + "'>";
                countrySelectorMarkup += "<span id='" + countryGroup.CountryGroupName.replace(/\s+/g, '-') + "' class='overlay-label'>" + countryGroup.CountryGroupName + "</span><br />";

                $.each(countryGroup.CountryList, function (i, country) {
                    var pageLocation = document.location.href.toLowerCase();
                    var pagePathName = document.location.pathname.toLowerCase();
                    var countryUrl = "";

                    if (pageLocation.indexOf("/careers") >= 0) {
                        countryUrl = country.CountryCareersUrl;
                        if (countryUrl == "" || typeof countryUrl == "undefined") {
                            countryUrl = country.Sites + "/home/careers";
                        }
                    } else {
                        countryUrl = country.CountryDotcomUrl;
                        if (countryUrl == "" || typeof countryUrl == "undefined") {
                            countryUrl = country.Sites + "/home";
                        }
                    }

                    if (i != 0) {

                        countrySelectorMarkup += "<span class='color-primary'> / </span>";
                    }

                    if (pagePathName == (countryUrl) || pagePathName == (countryUrl + "/") || pagePathName == (countryUrl + "/home")) {
                        countryUrl = "javascript:void(0);"
                    }


                    var countryLanguage = RetrieveCountryLanguageName(country.LanguageName);
                    countrySelectorMarkup += "<a aria-labelledby='" + countryGroup.CountryGroupName.replace(/\s+/g, '-') + "' href='" + countryUrl + "' class='overlay-language country-selector-module-link' title='" + countryLanguage + "' data-linktype='language'>" + countryLanguage + "</a>";
                });

                countrySelectorMarkup += "</p>";
            });

            countrySelectorMarkup += "</div>";
        });
        $(geoCountryGroupId).html(countrySelectorMarkup);

        if ($("#europe-row p").length > 7 && isDesktop()) //Expand europe to 2 columns if country site items is more than 7
        {
            ExpandEuropeGeoCountries();
        }
    }

    function RetrieveCountryLanguageName(countryLanguageName) {
        if ((countryLanguageName != null) || (countryLanguageName != "")) {
            var languageIndex = countryLanguageName.indexOf("-");
            if (languageIndex > 0) {
                countryLanguageName = countryLanguageName.substring(languageIndex + 1);
                var countryIndex = countryLanguageName.indexOf("(");

                if (countryIndex > 0) {
                    countryLanguageName = $.trim(countryLanguageName.substring(0, countryIndex));
                }
            }
        }
        return countryLanguageName;
    }

    function ExpandEuropeGeoCountries() {
        //Copy the Europe Column header and set a new Id for it.
        var colContainer = $("#europegeo").clone();
        $(colContainer).attr("id", "europegeo-expand");
        $("#europegeo").after(colContainer);

        //Copy the Europe Row container and set a new Id for it.
        var rowContainer = $("#europe-row").clone();
        $(rowContainer).attr("id", "europe-row-expand");
        $("#europe-row").after(rowContainer);

        //Clear the items of the copied Row container
        $("#europe-row-expand p").remove();

        var countryCount = $("p[class^=europe]").length;
        var expandItems = Math.floor(countryCount / 2);
        var startPos = (countryCount - expandItems) + 2;
        //Bug 240651: Removed unnecessary script that produces error in IE9

        var newLoc = "#europe-row-expand h4";
        var holdLoc = "";
        for (indx = startPos; indx <= countryCount + 1; indx++) {
            var geoChild = "p[class^=europe]:nth-child(" + startPos + ")";
            holdLoc = "." + $(geoChild).attr("class");
            $(geoChild).insertAfter($(newLoc));
            newLoc = holdLoc;
        }

        //Remove this header to avoid duplicate geo location column header
        //in mobileview or tablet(in portrait orienation)
        $("#europe-row-expand h4").remove();
    }

    var iconLang = $('.language-icon');
    var btnCloseLang = $("#countryLanguageSelectorModal button.close");
    btnCloseLang.on("keydown", function (e) {
        if (e.which == 13) {
            $(this).trigger("click");
            e.preventDefault();
            iconLang.trigger("focus");
        }
    });

    //ESC button for CountrySelector modal
    //Bug # 195475 : Common Elements - Country Language Selector: Modal window doesn't close upon hitting the "ESC" key on the keyboard.|SpilloverToPT
    $('#countryLanguageSelectorModal').on("keydown", function (e) {
        if (e.keyCode == 27) {
            btnCloseLang.trigger("click");
            e.preventDefault();
            iconLang.trigger("focus");

        }
    });

    //Bug 283855 - Image Module Tooltip
    $("img.imagemodule").attr("title", function () {
        return $(this).attr("alt");
    });

    var urlHash = window.location.hash;
    if (urlHash != '') {
        document.getElementById(urlHash.replace('#', '')).scrollIntoView();
        setTimeout(function () { scrollToAnchor(urlHash.substr(1)) }, 1000);
    }

    var urlLink = window.location.href.toLowerCase();

    if (urlLink.indexOf("onboarding/countdown-to-accenture") < 0) {
        putIdOnMainContent();
    }


    $(".btn1.dropdown-toggle.btn-primary").each(function () {
        $(this).on('keydown', function (e) {
            $('div.suggestedjobs-btn-group.dropdown.white-dropdown').each(function () {
                $(this).on('focus', 'a', function () {
                    $this = $(this);
                    $this.closest('div.suggestedjobs-btn-group.dropdown.white-dropdown').scrollTop($this.index() * $this.outerHeight());
                }).on('keydown', 'a', function (e) {
                    $this = $(this);
                    if (e.keyCode == 40) {
                        $this.parent().next().find('a').trigger("focus");
                        return false;
                    } else if (e.keyCode == 38) {
                        $this.parent().prev().find('a').trigger("focus");
                        return false;
                    } else if (e.which == 13) {
                        $this.trigger("click");
                    } else if (e.which == 9) {
                        $this.parent().parent().parent().removeClass('open');
                        $('btn-SuggestedJob-Submit').trigger("focus");
                    }
                }).find('a').first().trigger("focus");
            })
            if (e.which == 9) {
                $(this).parent().removeClass('open');
            }
        })
    })

    $("span.icon-chevronthin.icon-chevron_thin.align-right").each(function () {
        $(this).on('keydown', function (e) {
            if (e.which == 13) {
                e.preventDefault();
                $(this).parent().next().removeClass('hidden');
            }
        })
    })

    $("span.close-video-accordion.icon-accordion-close-thin.icon-x-close").each(function () {
        $(this).on('keydown', function (e) {
            if (e.which == 13) {
                e.preventDefault();
                $(this).parent().addClass('hidden');
            }
        })
    })

    $("div.media-container a").each(function () {
        $(this).on('keydown', function (e) {
            if (e.which == 9) {
                e.preventDefault();
                $(this).closest('.media-container').addClass('hidden');
                $(this).closest('#video-accordion').attr('style', '');
                $(this).closest('#video-accordion').find(".container-claster.hidden").removeClass('hidden');
                $(this).closest(".container-claster").find('.icon-chevronthin').trigger("focus");
            }
        })
    })

    //RMT5237 
    var errormsg = $(".validatorMessage,#industryErrorMessage");
    errormsg.attr("tabindex", '0');

});

Navigation = {
    collapseExpandMenu: function () {
        var menubarcollapse = $('#ui-menu-nav-collapse');
        var menubarexpand = $('#ui-menu-nav-expand');
        var topnav = $('#header-topnav, .cookie-nav');
        var menu = $('#main-menu');
        //Fix for bug# 371966 start
        var signmoveleft = $('#LoginPopoverTriggerContainer .popover');
        //Resolution size finder
        var screenWidth = $(window).width();
        //Lower resolution limit for laptop devices
        var desktopWidth = 1200;
        //Lower resolution limit for tablet devices
        var tabletWidth = 768;
        var isAuthenticated = ($('#LoginPopoverTriggerContainer').find('.authenticated').length == 0) ? true : false;
        var onboarding = $('.onboarding');
        if (menubarcollapse.length == 1 && onboarding.length == 0) {
            menubarcollapse.attr("id", "ui-menu-nav-expand");
            topnav.addClass("top-nav-menu-expand");
            menu.removeClass("hide-menu");



            if (isAuthenticated) {
                //for laptop and tablet device
                if (screenWidth >= desktopWidth) {
                    signmoveleft.attr('style', 'left: 0% !important');
                    signmoveleft.css("right", "20.5%");
                    signmoveleft.css("display", "block");

                    // Bug # 365656

                    var final_screen = $('#main-menu').width() - $('#LoginPopoverTriggerContainer').width();

                    $("#LoginPopoverTriggerContainer .popover .arrow").css('right', final_screen + 'px');
                }
                else if (screenWidth < desktopWidth && screenWidth > tabletWidth) {
                    signmoveleft.attr('style', 'left: 0% !important');
                    signmoveleft.css("right", "25%");
                    signmoveleft.css("display", "block");
                }
            }
        }

        if (menubarexpand.length == 1 && onboarding.length == 0) {
            menubarexpand.attr("id", "ui-menu-nav-collapse");
            topnav.removeClass("top-nav-menu-expand");



            if (isAuthenticated) {
                //for laptop and tablet device
                if (screenWidth >= desktopWidth) {
                    signmoveleft.css("left", "");
                    signmoveleft.css("right", "");
                }
                else if (screenWidth < desktopWidth && screenWidth > tabletWidth) {
                    signmoveleft.css("right", "");
                    signmoveleft.css("left", "");
                }
            }
            //end
        }
    }
}

var FooterElement = {
    AssignFooterId: function () {
        if ($(window).width() < 768) {
            $('#block-footer-lg').attr("id", "");
            $('#block-footer-xs').attr("id", "block-footer");
        }
        else {
            $('#block-footer-xs').attr("id", "");
            $('#block-footer-lg').attr("id", "block-footer");
        }
    }
}

$(window).on('load resize', function () {
    var maxWidth = $('#mobile-textlink').outerWidth();
    var maxWidth_careers = $('#mobile-textlink-careers').outerWidth(),
        totalWidth = 0;

    $('#mobile-textlink li').each(function () {
        var currentWidth = $(this).outerWidth(),
            nextWidth = $(this).next().outerWidth();
        totalWidth += currentWidth - 1;
        if ((totalWidth + nextWidth) > maxWidth) {
            $(this).addClass('nobordertextlink');
            $(this).removeClass('withbordertextlink');
            totalWidth = 0;
        } else {
            $(this).addClass('withbordertextlink');
            $(this).removeClass('nobordertextlink');
        }
    });

    totalWidth = 0;
    $('#mobile-textlink-careers li').each(function () {
        var currentWidth = $(this).outerWidth(),
            nextWidth = $(this).next().outerWidth();
        totalWidth += currentWidth - 1;
        if ((totalWidth + nextWidth) > maxWidth_careers) {
            $(this).addClass('nobordertextlink');
            $(this).removeClass('withbordertextlink');
            totalWidth = 0;
        } else {
            $(this).addClass('withbordertextlink');
            $(this).removeClass('nobordertextlink');
        }
    });
});

function SwapJquerySelection(elementID, otherElementID) {
    var curretnClass = $(elementID).attr('class');
    $(elementID).attr('class', $(otherElementID).attr('class'));
    $(otherElementID).attr('class', curretnClass);
}

function RemoveCookieStatement(ToBeRemoved) {
    //Bug # 342490 Common Element - Cookie Statement: Cookie Statement is missing after clicking the X button then clearing the cache and cookies
    $.ajax({
        url: "/api/sitecore/CookieStatement/NoMoreCookieStatement",
        data: { availability: 'no' },
        cache: false,
        type: "GET",
        timeout: 10000,
        dataType: "json",
        success: function (result) {
            removeCookieElement(ToBeRemoved);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error remove function! : " + errorThrown);
        }
    });
}

function animatedEntrance(selector) {
    if (selector.indexOf("nav") > -1) {
        $(selector).slideDown(300, function () {
            $('.cookie-nav.alert-neutral .alert-neutral-text').trigger("focus");
            adjustCookieStatementForPreview();
        });
    }
    else if ($(selector).length > 0) {

        $(selector).show('slow');
    }
}

function checkCookieStatementClosure(DisclaimerContainer) {
    if (!navigator.cookieEnabled) {
        removeCookieElement(DisclaimerContainer);
        return;
    }
    //Bug # 342490 Common Element - Cookie Statement: Cookie Statement is missing after clicking the X button then clearing the cache and cookies

    else {
        $.ajax({
            url: "/api/sitecore/CookieStatement/AskToShowStatement",
            cache: false,
            type: "GET",
            timeout: 10000,
            dataType: "json",
            success: function (result) {
                if (result.Success && result.Answer == "No") {
                    $(DisclaimerContainer).remove();
                }
                else {
                    animatedEntrance(DisclaimerContainer);
                }
            }
        });
    }
}

function GetQueryStringKeyValue(keyname) {
    var q = "" + document.location.search;
    if (q == "")
        return;
    q = q.replace(/^[?#]/, '');
    q = q.replace(/[&]$/, '');
    q = q.replace(/\+/g, ' ');
    var qsSet = q.split(/[&]/);
    var property = "";
    var keyword = "";

    if (!keyname) {
        var urlParam = {};
        var prevKeyword = "";
        var prevProperty = "";


        for (i = 0; i < qsSet.length; i++) {
            property = decodeURIComponent(qsSet[i].split('=')[0] || "");
            keyword = decodeURIComponent(qsSet[i].split('=')[1] || "");
            if (keyword.toLowerCase().toString() === "" && (property.toLowerCase().toString() === "sk" || property.toLowerCase().toString() === "jk" || property.toLowerCase().toString() === "dte" || property.toLowerCase().toString() === "ts" || property.toLowerCase().toString() === "aoe" || property.toLowerCase().toString() === "ct" || property.toLowerCase().toString() === "jt")) {
                urlParam[property] = keyword;
            }
            else if (keyword.toLowerCase().toString() !== "") {
                urlParam[property] = keyword;
            }
            else {
                urlParam[prevProperty] = prevKeyword + "&" + property;
            }
            prevKeyword = keyword;
            prevProperty = property;
        }
        return urlParam;
    }
    else {
        for (i = 0; i < qsSet.length; i++) {
            property = decodeURIComponent(qsSet[i].split('=')[0] || "");
            keyword = decodeURIComponent(qsSet[i].split('=')[1] || "");

            var currentQsSet = qsSet[i + 1];

            if (keyname.toString().toLowerCase() === "sk" && property.toLowerCase().toString() === "sk" || keyname.toString().toLowerCase() === "jk" && property.toLowerCase().toString() === "jk" || keyname.toString().toLowerCase() === "dte" && property.toLowerCase().toString() === "dte" || keyname.toString().toLowerCase() === "ts" && property.toLowerCase().toString() === "ts" || keyname.toString().toLowerCase() === "aoe" && property.toLowerCase().toString() === "aoe") {
                if (i + 1 < qsSet.length && !(decodeURIComponent(currentQsSet).indexOf('=') >= 0) && decodeURIComponent(currentQsSet.split('=')[1] || "").toLowerCase().toString() === "")
                    return (keyword + "&" + decodeURIComponent(currentQsSet.split('=')[0] || ""))
                else
                    return keyword;
            }
            else if (property.toLowerCase() == keyname.toLowerCase()) {
                return keyword;
            }
        }
    }
}

function UpdateQueryString(urlparams) {
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        var version = parseInt(navigator.appVersion.match(/MSIE ([\d.]+)/)[1]);
        if (version > 9) {
            SetQueryStringContent(urlparams);
        }
    }
    else {
        SetQueryStringContent(urlparams);
    }
}

function SetQueryStringContent(urlparams) {
    $(window).on("load", function () {
        var value = "" + document.location.search;
        if (IsIE()) {
            value = value.replace(/ /g, '+');
        }
        else {
            value = value.replace(/%20/g, '+');
        }
        history.replaceState({}, "", value);
    });
}

function SwapJquerySelection(elementID, otherElementID) {
    var curretnClass = $(elementID).attr('class');
    $(elementID).attr('class', $(otherElementID).attr('class'));
    $(otherElementID).attr('class', curretnClass);
}


function adjustLoginPopoverPosition() {
    var popOverUnauthenticated = $('#LoginPopoverTriggerContainer .popover .popover-content .loginpanel');
    var popOverAuthenticated = $('#LoginPopoverTriggerContainer .popover .popover-content .authenticated');
    var popOverTriggerContainer = $('#LoginPopoverTriggerContainer .popover');
    var cookieStatement = $('div.cookie-nav');
    var popoverTopValue = $('#header-topnav').height();

    if (popOverUnauthenticated.is(":visible")) {
        if (cookieStatement.is(":visible")) {
            popoverTopValue += cookieStatement.height();
        }
        popOverTriggerContainer.css({ 'top': popoverTopValue + 12 });
    }
    else if (popOverAuthenticated.is(":visible")) {
        if (isDesktop()) {
            popOverTriggerContainer.css({ 'top': popoverTopValue - 7 });
        }
        else if (isTablet()) {
            popOverTriggerContainer.css({ 'top': popoverTopValue + 2 });
        }
    }
}

function removeCookieElement(toBeRemoved) {
    $(toBeRemoved).fadeOut(300, function () {
        $(toBeRemoved).remove();
        $('#header-topnav, #ui-wrapper, #ui-error-wrapper').css('top', 0);

        $('body').removeClass('has-cookie-nav');
        if (IsIOS()) {
            $('#header-topnav, #ui-wrapper').css('top', '');
        }

        adjustJumplinkForPreview();
        adjustLoginPopoverPosition();
    }); // Bug 439229
}

function FormatValue(val) {
    if (val != null)
        return val.replace(/\\/gi, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"");

    return val;
}

//ADDED FOR SEARCH
function SetCookie(name, value, path, days, domain, secure) {
    var expires = null;
    if (days != null) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = date.toGMTString();
    }

    document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
}

function GetCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function RemoveDuplicateID(ElementID) {
    $(ElementID).each(function (i) {
        var ids = $('[id="' + this.id + '"]');
        if (ids.length > 1) $('[id="' + this.id + '"]').slice(1).remove();
    });
}

function RemoveQueryStringParameter(parameter) {
    var uri = window.location.href;
    var re = new RegExp(parameter + "=.*?(&|$)", "i");
    if (uri.match(re)) {
        uri = uri.replace(re, '');
    }
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        var version = parseInt(navigator.appVersion.match(/MSIE ([\d.]+)/)[1]);
        if (version > 9) {
            history.pushState({}, "", uri);
        }
    }
}

function SetSessionStorageCurrentUrl() {
    if (typeof (Storage) !== "undefined") {
        sessionStorage.setItem("currentUrl", window.location.pathname + window.location.search);
    }
}

if (window.onpagehide || window.onpagehide === null) {
    $(window).on("pagehide", function (event) {
        SetSessionStorageCurrentUrl();
    });
} else {
    $(window).on("unload", function () {
        SetSessionStorageCurrentUrl();
    });
}

$(document).on('click', ".authenticated ul li a", function (e) {
    var signOutNavLinkId = "signout"
    var NavLinkId = $(this).attr('id');

    if (signOutNavLinkId != NavLinkId) {
        var userNavLink = $(this).attr('href');
        if (typeof userNavLink != "undefined" && userNavLink != "") {
            location.reload(userNavLink);
        } else {
            alert("Please set Client/Careers User Link value in content editor > _Settings ComponentSettings.");
        }
    }
});

//Ellipsis Configuration RMT 3299 US036,US045, US046 , US047
function EllipsisConfigFunction($elements) {
    $elements.each(function () {
        var $element = $(this);
        $element.dotdotdot({
            // configuration goes here
            ellipsis: '... ',

            /*	How to cut off the text/html: 'word'/'letter'/'children' */
            wrap: 'word',

            /*	Wrap-option fallback to 'letter' for long words */
            fallbackToLetter: true,

            /*	jQuery-selector for the element to keep and put after the ellipsis. */
            after: null,

            /*	Whether to update the ellipsis: true/'window' */
            watch: true,

            /*	Optionally set a max-height, can be a number or function.
                If null, the height will be measured. */
            height: null,

            /*	Deviation for the height-option. */
            tolerance: 0,

            /*	Callback function that is fired after the ellipsis is added,
                receives two parameters: isTruncated(boolean), orgContent(string). */
            callback: function (isTruncated, orgContent) { },

            lastCharacter: {

                /*	Remove these characters from the end of the truncated text. */
                remove: [' ', ',', ';', '.', '!', '?'],

                /*	Don't add an ellipsis if this array contains
                    the last character of the truncated text. */
                noEllipsis: []
            }
        });
    });
}

//Show In New Tab mobile RMT 3305
function IfMobileNewTab(element) {
    if (isMobile()) {
        $(element).attr('target', '_blank');
    } else {
        $(element).attr('target', '_self');
    };
}

//set the new data attribute for the Accordion Section Module
var $accordionExpandCollapse = $(".acn-accordion .panel-heading");

$accordionExpandCollapse.on("click", function () {

    var $element = $(this);
    var panelTitle = "";

    if ($element && $element.length) {

        if ($element.find("h2.panel-title").length > 0) {
            panelTitle = $element.find("h2.panel-title").text().trim().toLowerCase();
        }

        if ($element.hasClass("collapsed")) {
            $element.attr('data-analytics-link-name', panelTitle + '-collapse');
        }
        else {
            $element.attr('data-analytics-link-name', panelTitle + '-expand');
        }
    }
});

function isCaptchaCorrect(captchaInput, captchaId, captchaInstance, userInputId, apiUrl) {
    var CaptInput = captchaInput;
    var CaptchaID = captchaId;
    var CaptInstance = captchaInstance;
    var returnVal = false;
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: JSON.stringify({
            captchaID: CaptchaID,
            captInput: CaptInput,
            captInstance: CaptInstance
        }),
        contentType: "application/json",
        async: false,
        error: function (res) {
            console.log("captcha error:" + res);
        },
        success: function (res) {
            returnVal = res.CaptchaCorrect;
            if (res.CaptchaCorrect == false) {
                var UserInputID = userInputId;
                document.getElementById(UserInputID).Captcha.ReloadImage();
            }
        }
    });
    return returnVal;
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\responsive-calendar.js
//version="3"
// Generated by CoffeeScript 1.6.1

/*!
  # Responsive Celendar widget script
  # by w3widgets
  #
  # Author: Lukasz Kokoszkiewicz
  #
  # Copyright © w3widgets 2013 All Rights Reserved
*/


(function () {

    (function ($) {
        "use strict";
        var Calendar, opts, spy;
        Calendar = function (element, options) {
            var time;
            this.$element = element;
            this.options = options;
            this.weekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
            this.time = new Date();
            this.currentYear = this.time.getFullYear();
            this.currentMonth = this.time.getMonth();
            if (this.options.time) {
                time = this.splitDateString(this.options.time);
                this.currentYear = time.year;
                this.currentMonth = time.month;
            }
            this.initialDraw();
            return null;
        };
        Calendar.prototype = {
            addLeadingZero: function (num) {
                if (num < 10) {
                    return "0" + num;
                } else {
                    return "" + num;
                }
            },
            applyTransition: function ($el, transition) {
                $el.css('transition', transition);
                $el.css('-ms-transition', '-ms-' + transition);
                $el.css('-moz-transition', '-moz-' + transition);
                return $el.css('-webkit-transition', '-webkit-' + transition);
            },
            applyBackfaceVisibility: function ($el) {
                $el.css('backface-visibility', 'hidden');
                $el.css('-ms-backface-visibility', 'hidden');
                $el.css('-moz-backface-visibility', 'hidden');
                return $el.css('-webkit-backface-visibility', 'hidden');
            },
            applyTransform: function ($el, transform) {
                $el.css('transform', transform);
                $el.css('-ms-transform', transform);
                $el.css('-moz-transform', transform);
                return $el.css('-webkit-transform', transform);
            },
            splitDateString: function (dateString) {
                var day, month, time, year;
                time = dateString.split('-');
                year = parseInt(time[0]);
                month = parseInt(time[1] - 1);
                day = parseInt(time[2]);
                return time = {
                    year: year,
                    month: month,
                    day: day
                };
            },
            initialDraw: function () {
                return this.drawDays(this.currentYear, this.currentMonth);
            },
            editDays: function (events) {
                var dateString, day, dayEvents, time, _results;
                _results = [];
                for (dateString in events) {
                    dayEvents = events[dateString];
                    this.options.events[dateString] = events[dateString];
                    time = this.splitDateString(dateString);
                    day = this.$element.find('[data-year="' + time.year + '"][data-month="' + (time.month + 1) + '"][data-day="' + time.day + '"]').parent('.day');
                    day.removeClass('active');
                    day.find('.badge').remove();
                    day.find('a').removeAttr('href');
                    if (this.currentMonth === time.month || this.options.activateNonCurrentMonths) {
                        _results.push(this.makeActive(day, dayEvents));
                    } else {
                        _results.push(void 0);
                    }
                }
                return _results;
            },
            clearDays: function (days) {
                var dateString, day, time, _i, _len, _results;
                _results = [];
                for (_i = 0, _len = days.length; _i < _len; _i++) {
                    dateString = days[_i];
                    delete this.options.events[dateString];
                    time = this.splitDateString(dateString);
                    day = this.$element.find('[data-year="' + time.year + '"][data-month="' + (time.month + 1) + '"][data-day="' + time.day + '"]').parent('.day');
                    day.removeClass('active');
                    day.find('.badge').remove();
                    _results.push(day.find('a').removeAttr('href'));
                }
                return _results;
            },
            clearAll: function () {
                var day, days, i, _i, _len, _results;
                this.options.events = {};
                days = this.$element.find('[data-group="days"] .day');
                _results = [];
                for (i = _i = 0, _len = days.length; _i < _len; i = ++_i) {
                    day = days[i];
                    $(day).removeClass('active');
                    $(day).find('.badge').remove();
                    _results.push($(day).find('a').removeAttr('href'));
                }
                return _results;
            },
            setMonth: function (dateString) {
                var time;
                time = this.splitDateString(dateString);
                return this.currentMonth = this.drawDays(time.year, time.month);
            },
            prev: function () {
                if (this.currentMonth - 1 < 0) {
                    this.currentYear = this.currentYear - 1;
                    this.currentMonth = 11;
                } else {
                    this.currentMonth = this.currentMonth - 1;
                }
                this.drawDays(this.currentYear, this.currentMonth);
                if (this.options.onMonthChange) {
                    this.options.onMonthChange.call(this);
                }
                return null;
            },
            next: function () {
                if (this.currentMonth + 1 > 11) {
                    this.currentYear = this.currentYear + 1;
                    this.currentMonth = 0;
                } else {
                    this.currentMonth = this.currentMonth + 1;
                }
                this.drawDays(this.currentYear, this.currentMonth);
                if (this.options.onMonthChange) {
                    this.options.onMonthChange.call(this);
                }
                return null;
            },
            addOthers: function (day, dayEvents) {
                var badge;
                if (typeof dayEvents === "object") {
                    if (dayEvents.number != null) {
                        badge = $("<span></span>").html(dayEvents.number).addClass("badge");
                        if (dayEvents.badgeClass != null) {
                            badge.addClass(dayEvents.badgeClass);
                        }
                        day.append(badge);
                    }
                    if (dayEvents.url) {
                        day.find("a").attr("href", dayEvents.url);
                    }
                }
                return day;
            },
            makeActive: function (day, dayEvents) {
                var classes, eventClass, i, _i, _len;
                if (dayEvents) {
                    if (dayEvents["class"]) {
                        classes = dayEvents["class"].split(" ");
                        for (i = _i = 0, _len = classes.length; _i < _len; i = ++_i) {
                            eventClass = classes[i];
                            day.addClass(eventClass);
                        }
                    } else {
                        day.addClass("active");
                    }
                    day = this.addOthers(day, dayEvents);
                }
                return day;
            },
            getDaysInMonth: function (year, month) {
                return new Date(year, month + 1, 0).getDate();
            },
            drawDay: function (lastDayOfMonth, yearNum, monthNum, dayNum, i) {
                var calcDate, dateNow, dateString, day, dayDate, pastFutureClass;
                day = $("<div></div>").addClass("day");
                dateNow = new Date();
                dateNow.setHours(0, 0, 0, 0);
                dayDate = new Date(yearNum, monthNum - 1, dayNum);
                if (dayDate.getTime() < dateNow.getTime()) {
                    pastFutureClass = "past";
                } else if (dayDate.getTime() === dateNow.getTime()) {
                    pastFutureClass = "today";
                } else {
                    pastFutureClass = "future";
                }
                day.addClass(this.weekDays[i % 7]);
                day.addClass(pastFutureClass);
                dateString = yearNum + "-" + this.addLeadingZero(monthNum) + "-" + this.addLeadingZero(dayNum);
                if (dayNum <= 0 || dayNum > lastDayOfMonth) {
                    calcDate = new Date(yearNum, monthNum - 1, dayNum);
                    dayNum = calcDate.getDate();
                    monthNum = calcDate.getMonth() + 1;
                    yearNum = calcDate.getFullYear();
                    day.addClass("not-current").addClass(pastFutureClass);
                    if (this.options.activateNonCurrentMonths) {
                        dateString = yearNum + "-" + this.addLeadingZero(monthNum) + "-" + this.addLeadingZero(dayNum);
                    }
                }
                day.append($("<a>" + dayNum + "</a>").attr("data-day", dayNum).attr("data-month", monthNum).attr("data-year", yearNum));
                if (this.options.monthChangeAnimation) {
                    this.applyTransform(day, 'rotateY(180deg)');
                    this.applyBackfaceVisibility(day);
                }
                day = this.makeActive(day, this.options.events[dateString]);
                return this.$element.find('[data-group="days"]').append(day);
            },
            drawDays: function (year, month) {
                var currentMonth, day, dayBase, days, delay, draw, firstDayOfMonth, i, lastDayOfMonth, loopBase, monthNum, multiplier, thisRef, time, timeout, yearNum, _i, _len;
                thisRef = this;
                time = new Date(year, month);
                currentMonth = time.getMonth();
                monthNum = time.getMonth() + 1;
                yearNum = time.getFullYear();
                time.setDate(1);
                firstDayOfMonth = this.options.startFromSunday ? time.getDay() + 1 : time.getDay() || 7;
                lastDayOfMonth = this.getDaysInMonth(year, month);
                timeout = 0;
                if (this.options.monthChangeAnimation) {
                    days = this.$element.find('[data-group="days"] .day');
                    for (i = _i = 0, _len = days.length; _i < _len; i = ++_i) {
                        day = days[i];
                        delay = i * 0.01;
                        this.applyTransition($(day), 'transform .5s ease ' + delay + 's');
                        this.applyTransform($(day), 'rotateY(180deg)');
                        this.applyBackfaceVisibility($(day));
                        timeout = (delay + 0.1) * 1000;
                    }
                }
                dayBase = 2;
                if (this.options.allRows) {
                    loopBase = 42;
                } else {
                    multiplier = Math.ceil((firstDayOfMonth - (dayBase - 1) + lastDayOfMonth) / 7);
                    loopBase = multiplier * 7;
                }
                this.$element.find("[data-head-year]").html(time.getFullYear());
                this.$element.find("[data-head-month]").html(this.options.translateMonths[time.getMonth()]);
                draw = function () {
                    var dayNum, setEvents;
                    thisRef.$element.find('[data-group="days"]').empty();
                    dayNum = dayBase - firstDayOfMonth;
                    i = thisRef.options.startFromSunday ? 0 : 1;
                    while (dayNum < loopBase - firstDayOfMonth + dayBase) {
                        thisRef.drawDay(lastDayOfMonth, yearNum, monthNum, dayNum, i);
                        dayNum = dayNum + 1;
                        i = i + 1;
                    }
                    setEvents = function () {
                        var _j, _len1;
                        days = thisRef.$element.find('[data-group="days"] .day');
                        for (i = _j = 0, _len1 = days.length; _j < _len1; i = ++_j) {
                            day = days[i];
                            thisRef.applyTransition($(day), 'transform .5s ease ' + (i * 0.01) + 's');
                            thisRef.applyTransform($(day), 'rotateY(0deg)');
                        }
                        if (thisRef.options.onDayClick) {
                            thisRef.$element.find('[data-group="days"] .day a').on("click", function () {
                                return thisRef.options.onDayClick.call(this, thisRef.options.events);
                            });
                        }
                        if (thisRef.options.onDayHover) {
                            thisRef.$element.find('[data-group="days"] .day a').on("hover", function () {
                                return thisRef.options.onDayHover.call(this, thisRef.options.events);
                            });
                        }
                        if (thisRef.options.onActiveDayClick) {
                            thisRef.$element.find('[data-group="days"] .day.active a').on("click", function () {
                                return thisRef.options.onActiveDayClick.call(this, thisRef.options.events);
                            });
                        }
                        if (thisRef.options.onActiveDayHover) {
                            return thisRef.$element.find('[data-group="days"] .day.active a').on("hover", function () {
                                return thisRef.options.onActiveDayHover.call(this, thisRef.options.events);
                            });
                        }
                    };
                    return setTimeout(setEvents, 0);
                };
                setTimeout(draw, timeout);
                return currentMonth;
            }
        };
        $.fn.responsiveCalendar = function (option, params) {
            var init, options, publicFunc;
            if (params == null) {
                params = void 0;
            }
            options = $.extend({}, $.fn.responsiveCalendar.defaults, typeof option === 'object' && option);
            publicFunc = {
                next: 'next',
                prev: 'prev',
                edit: 'editDays',
                clear: 'clearDays',
                clearAll: 'clearAll'
            };
            init = function ($this) {
                var data;
                options = $.metadata ? $.extend({}, options, $this.metadata()) : options;
                $this.data('calendar', (data = new Calendar($this, options)));
                if (options.onInit) {
                    options.onInit.call(data);
                }
                return $this.find("[data-go]").on("click", function () {
                    if ($(this).data("go") === "prev") {
                        data.prev();
                    }
                    if ($(this).data("go") === "next") {
                        return data.next();
                    }
                });
            };
            return this.each(function () {
                var $this, data;
                $this = $(this);
                data = $this.data('calendar');
                if (!data) {
                    init($this);
                } else if (typeof option === 'string') {
                    if (publicFunc[option] != null) {
                        data[publicFunc[option]](params);
                    } else {
                        data.setMonth(option);
                    }
                } else if (typeof option === 'number') {
                    data.jump(Math.abs(option) + 1);
                }
                return null;
            });
        };
        $.fn.responsiveCalendar.defaults = {
            translateMonths: typeof months == 'undefined' ? ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] : months,
            events: {},
            time: void 0,
            allRows: true,
            startFromSunday: false,
            activateNonCurrentMonths: false,
            monthChangeAnimation: true,
            onInit: void 0,
            onDayClick: void 0,
            onDayHover: void 0,
            onActiveDayClick: void 0,
            onActiveDayHover: void 0,
            onMonthChange: void 0
        };
        spy = $('[data-spy="responsive-calendar"]');
        if (spy.length) {
            opts = {};
            if ((spy.data('translate-months')) != null) {
                opts.translateMonths = spy.data('translate-months').split(',');
            }
            if ((spy.data('time')) != null) {
                opts.time = spy.data('time');
            }
            if ((spy.data('all-rows')) != null) {
                opts.allRows = spy.data('all-rows');
            }
            if ((spy.data('start-from-sunday')) != null) {
                opts.startFromSunday = spy.data('start-from-sunday');
            }
            if ((spy.data('activate-non-current-months')) != null) {
                opts.activateNonCurrentMonths = spy.data('activate-non-current-months');
            }
            if ((spy.data('month-change-animation')) != null) {
                opts.monthChangeAnimation = spy.data('month-change-animation');
            }
            return spy.responsiveCalendar(opts);
        }
    })(jQuery);

}).call(this);
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\jquery.carouFredSel-6.2.1-packed.js
/*
 *	jQuery carouFredSel 6.2.1
 *	Demo's and documentation:
 *	caroufredsel.dev7studios.com
 *
 *	Copyright (c) 2013 Fred Heusschen
 *	www.frebsite.nl
 *
 *	Dual licensed under the MIT and GPL licenses.
 *	http://en.wikipedia.org/wiki/MIT_License
 *	http://en.wikipedia.org/wiki/GNU_General_Public_License
 */

/*
 * src:  
 * https://github.com/Codeinwp/carouFredSel-jQuery/blob/master/jquery.carouFredSel-6.2.1.js
 */


(function ($) {


    //	LOCAL

    if ($.fn.carouFredSel) {
        return;
    }

    $.fn.caroufredsel = $.fn.carouFredSel = function (options, configs) {

        //	no element
        if (this.length == 0) {
            debug(true, 'No element found for "' + this.selector + '".');
            return this;
        }

        //	multiple elements
        if (this.length > 1) {
            return this.each(function () {
                $(this).carouFredSel(options, configs);
            });
        }


        var $cfs = this,
            $tt0 = this[0],
            starting_position = false;

        if ($cfs.data('_cfs_isCarousel')) {
            starting_position = $cfs.triggerHandler('_cfs_triggerEvent', 'currentPosition');
            $cfs.trigger('_cfs_triggerEvent', ['destroy', true]);
        }

        var FN = {};

        FN._init = function (o, setOrig, start) {
            o = go_getObject($tt0, o);

            o.items = go_getItemsObject($tt0, o.items);
            o.scroll = go_getScrollObject($tt0, o.scroll);
            o.auto = go_getAutoObject($tt0, o.auto);
            o.prev = go_getPrevNextObject($tt0, o.prev);
            o.next = go_getPrevNextObject($tt0, o.next);
            o.pagination = go_getPaginationObject($tt0, o.pagination);
            o.swipe = go_getSwipeObject($tt0, o.swipe);
            o.mousewheel = go_getMousewheelObject($tt0, o.mousewheel);

            if (setOrig) {
                opts_orig = $.extend(true, {}, $.fn.carouFredSel.defaults, o);
            }

            opts = $.extend(true, {}, $.fn.carouFredSel.defaults, o);
            opts.d = cf_getDimensions(opts);

            crsl.direction = (opts.direction == 'up' || opts.direction == 'left') ? 'next' : 'prev';

            var a_itm = $cfs.children(),
                avail_primary = ms_getParentSize($wrp, opts, 'width');

            if (is_true(opts.cookie)) {
                opts.cookie = 'caroufredsel_cookie_' + conf.serialNumber;
            }

            opts.maxDimension = ms_getMaxDimension(opts, avail_primary);

            //	complement items and sizes
            opts.items = in_complementItems(opts.items, opts, a_itm, start);
            opts[opts.d['width']] = in_complementPrimarySize(opts[opts.d['width']], opts, a_itm);
            opts[opts.d['height']] = in_complementSecondarySize(opts[opts.d['height']], opts, a_itm);

            //	primary size not set for a responsive carousel
            if (opts.responsive) {
                if (!is_percentage(opts[opts.d['width']])) {
                    opts[opts.d['width']] = '100%';
                }
            }

            //	primary size is percentage
            if (is_percentage(opts[opts.d['width']])) {
                crsl.upDateOnWindowResize = true;
                crsl.primarySizePercentage = opts[opts.d['width']];
                opts[opts.d['width']] = ms_getPercentage(avail_primary, crsl.primarySizePercentage);
                if (!opts.items.visible) {
                    opts.items.visibleConf.variable = true;
                }
            }

            if (opts.responsive) {
                opts.usePadding = false;
                opts.padding = [0, 0, 0, 0];
                opts.align = false;
                opts.items.visibleConf.variable = false;
            }
            else {
                //	visible-items not set
                if (!opts.items.visible) {
                    opts = in_complementVisibleItems(opts, avail_primary);
                }

                //	primary size not set -> calculate it or set to "variable"
                if (!opts[opts.d['width']]) {
                    if (!opts.items.visibleConf.variable && is_number(opts.items[opts.d['width']]) && opts.items.filter == '*') {
                        opts[opts.d['width']] = opts.items.visible * opts.items[opts.d['width']];
                        opts.align = false;
                    }
                    else {
                        opts[opts.d['width']] = 'variable';
                    }
                }
                //	align not set -> set to center if primary size is number
                if (is_undefined(opts.align)) {
                    opts.align = (is_number(opts[opts.d['width']]))
                        ? 'center'
                        : false;
                }
                //	set variabe visible-items
                if (opts.items.visibleConf.variable) {
                    opts.items.visible = gn_getVisibleItemsNext(a_itm, opts, 0);
                }
            }

            //	set visible items by filter
            if (opts.items.filter != '*' && !opts.items.visibleConf.variable) {
                opts.items.visibleConf.org = opts.items.visible;
                opts.items.visible = gn_getVisibleItemsNextFilter(a_itm, opts, 0);
            }

            opts.items.visible = cf_getItemsAdjust(opts.items.visible, opts, opts.items.visibleConf.adjust, $tt0);
            opts.items.visibleConf.old = opts.items.visible;

            if (opts.responsive) {
                if (!opts.items.visibleConf.min) {
                    opts.items.visibleConf.min = opts.items.visible;
                }
                if (!opts.items.visibleConf.max) {
                    opts.items.visibleConf.max = opts.items.visible;
                }
                opts = in_getResponsiveValues(opts, a_itm, avail_primary);
            }
            else {
                opts.padding = cf_getPadding(opts.padding);

                if (opts.align == 'top') {
                    opts.align = 'left';
                }
                else if (opts.align == 'bottom') {
                    opts.align = 'right';
                }

                switch (opts.align) {
                    //	align: center, left or right
                    case 'center':
                    case 'left':
                    case 'right':
                        if (opts[opts.d['width']] != 'variable') {
                            opts = in_getAlignPadding(opts, a_itm);
                            opts.usePadding = true;
                        }
                        break;

                    //	padding
                    default:
                        opts.align = false;
                        opts.usePadding = (
                            opts.padding[0] == 0 &&
                            opts.padding[1] == 0 &&
                            opts.padding[2] == 0 &&
                            opts.padding[3] == 0
                        ) ? false : true;
                        break;
                }
            }

            if (!is_number(opts.scroll.duration)) {
                opts.scroll.duration = 500;
            }
            if (is_undefined(opts.scroll.items)) {
                opts.scroll.items = (opts.responsive || opts.items.visibleConf.variable || opts.items.filter != '*')
                    ? 'visible'
                    : opts.items.visible;
            }

            opts.auto = $.extend(true, {}, opts.scroll, opts.auto);
            opts.prev = $.extend(true, {}, opts.scroll, opts.prev);
            opts.next = $.extend(true, {}, opts.scroll, opts.next);
            opts.pagination = $.extend(true, {}, opts.scroll, opts.pagination);
            //	swipe and mousewheel extend later on, per direction

            opts.auto = go_complementAutoObject($tt0, opts.auto);
            opts.prev = go_complementPrevNextObject($tt0, opts.prev);
            opts.next = go_complementPrevNextObject($tt0, opts.next);
            opts.pagination = go_complementPaginationObject($tt0, opts.pagination);
            opts.swipe = go_complementSwipeObject($tt0, opts.swipe);
            opts.mousewheel = go_complementMousewheelObject($tt0, opts.mousewheel);

            if (opts.synchronise) {
                opts.synchronise = cf_getSynchArr(opts.synchronise);
            }


            //	DEPRECATED
            if (opts.auto.onPauseStart) {
                opts.auto.onTimeoutStart = opts.auto.onPauseStart;
                deprecated('auto.onPauseStart', 'auto.onTimeoutStart');
            }
            if (opts.auto.onPausePause) {
                opts.auto.onTimeoutPause = opts.auto.onPausePause;
                deprecated('auto.onPausePause', 'auto.onTimeoutPause');
            }
            if (opts.auto.onPauseEnd) {
                opts.auto.onTimeoutEnd = opts.auto.onPauseEnd;
                deprecated('auto.onPauseEnd', 'auto.onTimeoutEnd');
            }
            if (opts.auto.pauseDuration) {
                opts.auto.timeoutDuration = opts.auto.pauseDuration;
                deprecated('auto.pauseDuration', 'auto.timeoutDuration');
            }
            //	/DEPRECATED


        };	//	/init


        FN._build = function () {
            $cfs.data('_cfs_isCarousel', true);

            var a_itm = $cfs.children(),
                orgCSS = in_mapCss($cfs, ['textAlign', 'float', 'position', 'top', 'right', 'bottom', 'left', 'zIndex', 'width', 'height', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft']),
                newPosition = 'relative';

            switch (orgCSS.position) {
                case 'absolute':
                case 'fixed':
                    newPosition = orgCSS.position;
                    break;
            }

            if (conf.wrapper == 'parent') {
                sz_storeOrigCss($wrp);
            }
            else {
                $wrp.css(orgCSS);
            }
            $wrp.css({
                'overflow': 'hidden',
                'position': newPosition
            });

            sz_storeOrigCss($cfs);
            $cfs.data('_cfs_origCssZindex', orgCSS.zIndex);
            $cfs.css({
                'textAlign': 'left',
                'float': 'none',
                'position': 'absolute',
                'top': 0,
                'right': 'auto',
                'bottom': 'auto',
                'left': 0,
                'marginTop': 0,
                'marginRight': 0,
                'marginBottom': 0,
                'marginLeft': 0
            });

            sz_storeMargin(a_itm, opts);
            sz_storeOrigCss(a_itm);
            if (opts.responsive) {
                sz_setResponsiveSizes(opts, a_itm);
            }

        };	//	/build


        FN._bind_events = function () {
            FN._unbind_events();


            //	stop event
            $cfs.on(cf_e('stop', conf), function (e, imm) {
                e.stopPropagation();

                //	button
                if (!crsl.isStopped) {
                    if (opts.auto.button) {
                        opts.auto.button.addClass(cf_c('stopped', conf));
                    }
                }

                //	set stopped
                crsl.isStopped = true;

                if (opts.auto.play) {
                    opts.auto.play = false;
                    $cfs.trigger(cf_e('pause', conf), imm);
                }
                return true;
            });


            //	finish event
            $cfs.on(cf_e('finish', conf), function (e) {
                e.stopPropagation();
                if (crsl.isScrolling) {
                    sc_stopScroll(scrl);
                }
                return true;
            });


            //	pause event
            $cfs.on(cf_e('pause', conf), function (e, imm, res) {
                e.stopPropagation();
                tmrs = sc_clearTimers(tmrs);

                //	immediately pause
                if (imm && crsl.isScrolling) {
                    scrl.isStopped = true;
                    var nst = getTime() - scrl.startTime;
                    scrl.duration -= nst;
                    if (scrl.pre) {
                        scrl.pre.duration -= nst;
                    }
                    if (scrl.post) {
                        scrl.post.duration -= nst;
                    }
                    sc_stopScroll(scrl, false);
                }

                //	update remaining pause-time
                if (!crsl.isPaused && !crsl.isScrolling) {
                    if (res) {
                        tmrs.timePassed += getTime() - tmrs.startTime;
                    }
                }

                //	button
                if (!crsl.isPaused) {
                    if (opts.auto.button) {
                        opts.auto.button.addClass(cf_c('paused', conf));
                    }
                }

                //	set paused
                crsl.isPaused = true;

                //	pause pause callback
                if (opts.auto.onTimeoutPause) {
                    var dur1 = opts.auto.timeoutDuration - tmrs.timePassed,
                        perc = 100 - Math.ceil(dur1 * 100 / opts.auto.timeoutDuration);

                    opts.auto.onTimeoutPause.call($tt0, perc, dur1);
                }
                return true;
            });


            //	play event
            $cfs.on(cf_e('play', conf), function (e, dir, del, res) {
                e.stopPropagation();
                tmrs = sc_clearTimers(tmrs);

                //	sort params
                var v = [dir, del, res],
                    t = ['string', 'number', 'boolean'],
                    a = cf_sortParams(v, t);

                dir = a[0];
                del = a[1];
                res = a[2];

                if (dir != 'prev' && dir != 'next') {
                    dir = crsl.direction;
                }
                if (!is_number(del)) {
                    del = 0;
                }
                if (!is_boolean(res)) {
                    res = false;
                }

                //	stopped?
                if (res) {
                    crsl.isStopped = false;
                    opts.auto.play = true;
                }
                if (!opts.auto.play) {
                    e.stopImmediatePropagation();
                    return debug(conf, 'Carousel stopped: Not scrolling.');
                }

                //	button
                if (crsl.isPaused) {
                    if (opts.auto.button) {
                        opts.auto.button.removeClass(cf_c('stopped', conf));
                        opts.auto.button.removeClass(cf_c('paused', conf));
                    }
                }

                //	set playing
                crsl.isPaused = false;
                tmrs.startTime = getTime();

                //	timeout the scrolling
                var dur1 = opts.auto.timeoutDuration + del;
                dur2 = dur1 - tmrs.timePassed;
                perc = 100 - Math.ceil(dur2 * 100 / dur1);

                if (opts.auto.progress) {
                    tmrs.progress = setInterval(function () {
                        var pasd = getTime() - tmrs.startTime + tmrs.timePassed,
                            perc = Math.ceil(pasd * 100 / dur1);
                        opts.auto.progress.updater.call(opts.auto.progress.bar[0], perc);
                    }, opts.auto.progress.interval);
                }

                tmrs.auto = setTimeout(function () {
                    if (opts.auto.progress) {
                        opts.auto.progress.updater.call(opts.auto.progress.bar[0], 100);
                    }
                    if (opts.auto.onTimeoutEnd) {
                        opts.auto.onTimeoutEnd.call($tt0, perc, dur2);
                    }
                    if (crsl.isScrolling) {
                        $cfs.trigger(cf_e('play', conf), dir);
                    }
                    else {
                        $cfs.trigger(cf_e(dir, conf), opts.auto);
                    }
                }, dur2);

                //	pause start callback
                if (opts.auto.onTimeoutStart) {
                    opts.auto.onTimeoutStart.call($tt0, perc, dur2);
                }

                return true;
            });


            //	resume event
            $cfs.on(cf_e('resume', conf), function (e) {
                e.stopPropagation();
                if (scrl.isStopped) {
                    scrl.isStopped = false;
                    crsl.isPaused = false;
                    crsl.isScrolling = true;
                    scrl.startTime = getTime();
                    sc_startScroll(scrl, conf);
                }
                else {
                    $cfs.trigger(cf_e('play', conf));
                }
                return true;
            });


            //	prev + next events
            $cfs.on(cf_e('prev', conf) + ' ' + cf_e('next', conf), function (e, obj, num, clb, que) {
                e.stopPropagation();

                //	stopped or hidden carousel, don't scroll, don't queue
                if (crsl.isStopped || $cfs.is(':hidden')) {
                    e.stopImmediatePropagation();
                    return debug(conf, 'Carousel stopped or hidden: Not scrolling.');
                }

                //	not enough items
                var minimum = (is_number(opts.items.minimum)) ? opts.items.minimum : opts.items.visible + 1;
                if (minimum > itms.total) {
                    e.stopImmediatePropagation();
                    return debug(conf, 'Not enough items (' + itms.total + ' total, ' + minimum + ' needed): Not scrolling.');
                }

                //	get config
                var v = [obj, num, clb, que],
                    t = ['object', 'number/string', 'function', 'boolean'],
                    a = cf_sortParams(v, t);

                obj = a[0];
                num = a[1];
                clb = a[2];
                que = a[3];

                var eType = e.type.slice(conf.events.prefix.length);

                if (!is_object(obj)) {
                    obj = {};
                }
                if (is_function(clb)) {
                    obj.onAfter = clb;
                }
                if (is_boolean(que)) {
                    obj.queue = que;
                }
                obj = $.extend(true, {}, opts[eType], obj);

                //	test conditions callback
                if (obj.conditions && !obj.conditions.call($tt0, eType)) {
                    e.stopImmediatePropagation();
                    return debug(conf, 'Callback "conditions" returned false.');
                }

                if (!is_number(num)) {
                    if (opts.items.filter != '*') {
                        num = 'visible';
                    }
                    else {
                        var arr = [num, obj.items, opts[eType].items];
                        for (var a = 0, l = arr.length; a < l; a++) {
                            if (is_number(arr[a]) || arr[a] == 'page' || arr[a] == 'visible') {
                                num = arr[a];
                                break;
                            }
                        }
                    }
                    switch (num) {
                        case 'page':
                            e.stopImmediatePropagation();
                            return $cfs.triggerHandler(cf_e(eType + 'Page', conf), [obj, clb]);
                            break;

                        case 'visible':
                            if (!opts.items.visibleConf.variable && opts.items.filter == '*') {
                                num = opts.items.visible;
                            }
                            break;
                    }
                }

                //	resume animation, add current to queue
                if (scrl.isStopped) {
                    $cfs.trigger(cf_e('resume', conf));
                    $cfs.trigger(cf_e('queue', conf), [eType, [obj, num, clb]]);
                    e.stopImmediatePropagation();
                    return debug(conf, 'Carousel resumed scrolling.');
                }

                //	queue if scrolling
                if (obj.duration > 0) {
                    if (crsl.isScrolling) {
                        if (obj.queue) {
                            if (obj.queue == 'last') {
                                queu = [];
                            }
                            if (obj.queue != 'first' || queu.length == 0) {
                                $cfs.trigger(cf_e('queue', conf), [eType, [obj, num, clb]]);
                            }
                        }
                        e.stopImmediatePropagation();
                        return debug(conf, 'Carousel currently scrolling.');
                    }
                }

                tmrs.timePassed = 0;
                $cfs.trigger(cf_e('slide_' + eType, conf), [obj, num]);

                //	synchronise
                if (opts.synchronise) {
                    var s = opts.synchronise,
                        c = [obj, num];

                    for (var j = 0, l = s.length; j < l; j++) {
                        var d = eType;
                        if (!s[j][2]) {
                            d = (d == 'prev') ? 'next' : 'prev';
                        }
                        if (!s[j][1]) {
                            c[0] = s[j][0].triggerHandler('_cfs_triggerEvent', ['configuration', d]);
                        }
                        c[1] = num + s[j][3];
                        s[j][0].trigger('_cfs_triggerEvent', ['slide_' + d, c]);
                    }
                }
                return true;
            });


            //	prev event
            $cfs.on(cf_e('slide_prev', conf), function (e, sO, nI) {
                e.stopPropagation();
                var a_itm = $cfs.children();

                //	non-circular at start, scroll to end
                if (!opts.circular) {
                    if (itms.first == 0) {
                        if (opts.infinite) {
                            $cfs.trigger(cf_e('next', conf), itms.total - 1);
                        }
                        return e.stopImmediatePropagation();
                    }
                }

                sz_resetMargin(a_itm, opts);

                //	find number of items to scroll
                if (!is_number(nI)) {
                    if (opts.items.visibleConf.variable) {
                        nI = gn_getVisibleItemsPrev(a_itm, opts, itms.total - 1);
                    }
                    else if (opts.items.filter != '*') {
                        var xI = (is_number(sO.items)) ? sO.items : gn_getVisibleOrg($cfs, opts);
                        nI = gn_getScrollItemsPrevFilter(a_itm, opts, itms.total - 1, xI);
                    }
                    else {
                        nI = opts.items.visible;
                    }
                    nI = cf_getAdjust(nI, opts, sO.items, $tt0);
                }

                //	prevent non-circular from scrolling to far
                if (!opts.circular) {
                    if (itms.total - nI < itms.first) {
                        nI = itms.total - itms.first;
                    }
                }

                //	set new number of visible items
                opts.items.visibleConf.old = opts.items.visible;
                if (opts.items.visibleConf.variable) {
                    var vI = cf_getItemsAdjust(gn_getVisibleItemsNext(a_itm, opts, itms.total - nI), opts, opts.items.visibleConf.adjust, $tt0);
                    if (opts.items.visible + nI <= vI && nI < itms.total) {
                        nI++;
                        vI = cf_getItemsAdjust(gn_getVisibleItemsNext(a_itm, opts, itms.total - nI), opts, opts.items.visibleConf.adjust, $tt0);
                    }
                    opts.items.visible = vI;
                }
                else if (opts.items.filter != '*') {
                    var vI = gn_getVisibleItemsNextFilter(a_itm, opts, itms.total - nI);
                    opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0);
                }

                sz_resetMargin(a_itm, opts, true);

                //	scroll 0, don't scroll
                if (nI == 0) {
                    e.stopImmediatePropagation();
                    return debug(conf, '0 items to scroll: Not scrolling.');
                }
                debug(conf, 'Scrolling ' + nI + ' items backward.');


                //	save new config
                itms.first += nI;
                while (itms.first >= itms.total) {
                    itms.first -= itms.total;
                }

                //	non-circular callback
                if (!opts.circular) {
                    if (itms.first == 0 && sO.onEnd) {
                        sO.onEnd.call($tt0, 'prev');
                    }
                    if (!opts.infinite) {
                        nv_enableNavi(opts, itms.first, conf);
                    }
                }

                //	rearrange items
                $cfs.children().slice(itms.total - nI, itms.total).prependTo($cfs);
                if (itms.total < opts.items.visible + nI) {
                    $cfs.children().slice(0, (opts.items.visible + nI) - itms.total).clone(true).appendTo($cfs);
                }

                //	the needed items
                var a_itm = $cfs.children(),
                    i_old = gi_getOldItemsPrev(a_itm, opts, nI),
                    i_new = gi_getNewItemsPrev(a_itm, opts),
                    i_cur_l = a_itm.eq(nI - 1),
                    i_old_l = i_old.last(),
                    i_new_l = i_new.last();

                sz_resetMargin(a_itm, opts);

                var pL = 0,
                    pR = 0;

                if (opts.align) {
                    var p = cf_getAlignPadding(i_new, opts);
                    pL = p[0];
                    pR = p[1];
                }
                var oL = (pL < 0) ? opts.padding[opts.d[3]] : 0;

                //	hide items for fx directscroll
                var hiddenitems = false,
                    i_skp = $();
                if (opts.items.visible < nI) {
                    i_skp = a_itm.slice(opts.items.visibleConf.old, nI);
                    if (sO.fx == 'directscroll') {
                        var orgW = opts.items[opts.d['width']];
                        hiddenitems = i_skp;
                        i_cur_l = i_new_l;
                        sc_hideHiddenItems(hiddenitems);
                        opts.items[opts.d['width']] = 'variable';
                    }
                }

                //	save new sizes
                var $cf2 = false,
                    i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'),
                    w_siz = cf_mapWrapperSizes(ms_getSizes(i_new, opts, true), opts, !opts.usePadding),
                    i_siz_vis = 0,
                    a_cfs = {},
                    a_wsz = {},
                    a_cur = {},
                    a_old = {},
                    a_new = {},
                    a_lef = {},
                    a_lef_vis = {},
                    a_dur = sc_getDuration(sO, opts, nI, i_siz);

                switch (sO.fx) {
                    case 'cover':
                    case 'cover-fade':
                        i_siz_vis = ms_getTotalSize(a_itm.slice(0, opts.items.visible), opts, 'width');
                        break;
                }

                if (hiddenitems) {
                    opts.items[opts.d['width']] = orgW;
                }

                sz_resetMargin(a_itm, opts, true);
                if (pR >= 0) {
                    sz_resetMargin(i_old_l, opts, opts.padding[opts.d[1]]);
                }
                if (pL >= 0) {
                    sz_resetMargin(i_cur_l, opts, opts.padding[opts.d[3]]);
                }

                if (opts.align) {
                    opts.padding[opts.d[1]] = pR;
                    opts.padding[opts.d[3]] = pL;
                }

                a_lef[opts.d['left']] = -(i_siz - oL);
                a_lef_vis[opts.d['left']] = -(i_siz_vis - oL);
                a_wsz[opts.d['left']] = w_siz[opts.d['width']];

                //	scrolling functions
                var _s_wrapper = function () { },
                    _a_wrapper = function () { },
                    _s_paddingold = function () { },
                    _a_paddingold = function () { },
                    _s_paddingnew = function () { },
                    _a_paddingnew = function () { },
                    _s_paddingcur = function () { },
                    _a_paddingcur = function () { },
                    _onafter = function () { },
                    _moveitems = function () { },
                    _position = function () { };

                //	clone carousel
                switch (sO.fx) {
                    case 'crossfade':
                    case 'cover':
                    case 'cover-fade':
                    case 'uncover':
                    case 'uncover-fade':
                        $cf2 = $cfs.clone(true).appendTo($wrp);
                        break;
                }
                switch (sO.fx) {
                    case 'crossfade':
                    case 'uncover':
                    case 'uncover-fade':
                        $cf2.children().slice(0, nI).remove();
                        $cf2.children().slice(opts.items.visibleConf.old).remove();
                        break;

                    case 'cover':
                    case 'cover-fade':
                        $cf2.children().slice(opts.items.visible).remove();
                        $cf2.css(a_lef_vis);
                        break;
                }

                $cfs.css(a_lef);

                //	reset all scrolls
                scrl = sc_setScroll(a_dur, sO.easing, conf);

                //	animate / set carousel
                a_cfs[opts.d['left']] = (opts.usePadding) ? opts.padding[opts.d[3]] : 0;

                //	animate / set wrapper
                if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') {
                    _s_wrapper = function () {
                        $wrp.css(w_siz);
                    };
                    _a_wrapper = function () {
                        scrl.anims.push([$wrp, w_siz]);
                    };
                }

                //	animate / set items
                if (opts.usePadding) {
                    if (i_new_l.not(i_cur_l).length) {
                        a_cur[opts.d['marginRight']] = i_cur_l.data('_cfs_origCssMargin');

                        if (pL < 0) {
                            i_cur_l.css(a_cur);
                        }
                        else {
                            _s_paddingcur = function () {
                                i_cur_l.css(a_cur);
                            };
                            _a_paddingcur = function () {
                                scrl.anims.push([i_cur_l, a_cur]);
                            };
                        }
                    }
                    switch (sO.fx) {
                        case 'cover':
                        case 'cover-fade':
                            $cf2.children().eq(nI - 1).css(a_cur);
                            break;
                    }

                    if (i_new_l.not(i_old_l).length) {
                        a_old[opts.d['marginRight']] = i_old_l.data('_cfs_origCssMargin');
                        _s_paddingold = function () {
                            i_old_l.css(a_old);
                        };
                        _a_paddingold = function () {
                            scrl.anims.push([i_old_l, a_old]);
                        };
                    }

                    if (pR >= 0) {
                        a_new[opts.d['marginRight']] = i_new_l.data('_cfs_origCssMargin') + opts.padding[opts.d[1]];
                        _s_paddingnew = function () {
                            i_new_l.css(a_new);
                        };
                        _a_paddingnew = function () {
                            scrl.anims.push([i_new_l, a_new]);
                        };
                    }
                }

                //	set position
                _position = function () {
                    $cfs.css(a_cfs);
                };


                var overFill = opts.items.visible + nI - itms.total;

                //	rearrange items
                _moveitems = function () {
                    if (overFill > 0) {
                        $cfs.children().slice(itms.total).remove();
                        i_old = $($cfs.children().slice(itms.total - (opts.items.visible - overFill)).get().concat($cfs.children().slice(0, overFill).get()));
                    }
                    sc_showHiddenItems(hiddenitems);

                    if (opts.usePadding) {
                        var l_itm = $cfs.children().eq(opts.items.visible + nI - 1);
                        l_itm.css(opts.d['marginRight'], l_itm.data('_cfs_origCssMargin'));
                    }
                };


                var cb_arguments = sc_mapCallbackArguments(i_old, i_skp, i_new, nI, 'prev', a_dur, w_siz);

                //	fire onAfter callbacks
                _onafter = function () {
                    sc_afterScroll($cfs, $cf2, sO);
                    crsl.isScrolling = false;
                    clbk.onAfter = sc_fireCallbacks($tt0, sO, 'onAfter', cb_arguments, clbk);
                    queu = sc_fireQueue($cfs, queu, conf);

                    if (!crsl.isPaused) {
                        $cfs.trigger(cf_e('play', conf));
                    }
                };

                //	fire onBefore callback
                crsl.isScrolling = true;
                tmrs = sc_clearTimers(tmrs);
                clbk.onBefore = sc_fireCallbacks($tt0, sO, 'onBefore', cb_arguments, clbk);

                switch (sO.fx) {
                    case 'none':
                        $cfs.css(a_cfs);
                        _s_wrapper();
                        _s_paddingold();
                        _s_paddingnew();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        _onafter();
                        break;

                    case 'fade':
                        scrl.anims.push([$cfs, { 'opacity': 0 }, function () {
                            _s_wrapper();
                            _s_paddingold();
                            _s_paddingnew();
                            _s_paddingcur();
                            _position();
                            _moveitems();
                            scrl = sc_setScroll(a_dur, sO.easing, conf);
                            scrl.anims.push([$cfs, { 'opacity': 1 }, _onafter]);
                            sc_startScroll(scrl, conf);
                        }]);
                        break;

                    case 'crossfade':
                        $cfs.css({ 'opacity': 0 });
                        scrl.anims.push([$cf2, { 'opacity': 0 }]);
                        scrl.anims.push([$cfs, { 'opacity': 1 }, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingnew();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    case 'cover':
                        scrl.anims.push([$cf2, a_cfs, function () {
                            _s_paddingold();
                            _s_paddingnew();
                            _s_paddingcur();
                            _position();
                            _moveitems();
                            _onafter();
                        }]);
                        _a_wrapper();
                        break;

                    case 'cover-fade':
                        scrl.anims.push([$cfs, { 'opacity': 0 }]);
                        scrl.anims.push([$cf2, a_cfs, function () {
                            _s_paddingold();
                            _s_paddingnew();
                            _s_paddingcur();
                            _position();
                            _moveitems();
                            _onafter();
                        }]);
                        _a_wrapper();
                        break;

                    case 'uncover':
                        scrl.anims.push([$cf2, a_wsz, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingnew();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    case 'uncover-fade':
                        $cfs.css({ 'opacity': 0 });
                        scrl.anims.push([$cfs, { 'opacity': 1 }]);
                        scrl.anims.push([$cf2, a_wsz, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingnew();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    default:
                        scrl.anims.push([$cfs, a_cfs, function () {
                            _moveitems();
                            _onafter();
                        }]);
                        _a_wrapper();
                        _a_paddingold();
                        _a_paddingnew();
                        _a_paddingcur();
                        break;
                }

                sc_startScroll(scrl, conf);
                cf_setCookie(opts.cookie, $cfs, conf);

                $cfs.trigger(cf_e('updatePageStatus', conf), [false, w_siz]);

                return true;
            });


            //	next event
            $cfs.on(cf_e('slide_next', conf), function (e, sO, nI) {
                e.stopPropagation();
                var a_itm = $cfs.children();

                //	non-circular at end, scroll to start
                if (!opts.circular) {
                    if (itms.first == opts.items.visible) {
                        if (opts.infinite) {
                            $cfs.trigger(cf_e('prev', conf), itms.total - 1);
                        }
                        return e.stopImmediatePropagation();
                    }
                }

                sz_resetMargin(a_itm, opts);

                //	find number of items to scroll
                if (!is_number(nI)) {
                    if (opts.items.filter != '*') {
                        var xI = (is_number(sO.items)) ? sO.items : gn_getVisibleOrg($cfs, opts);
                        nI = gn_getScrollItemsNextFilter(a_itm, opts, 0, xI);
                    }
                    else {
                        nI = opts.items.visible;
                    }
                    nI = cf_getAdjust(nI, opts, sO.items, $tt0);
                }

                var lastItemNr = (itms.first == 0) ? itms.total : itms.first;

                //	prevent non-circular from scrolling to far
                if (!opts.circular) {
                    if (opts.items.visibleConf.variable) {
                        var vI = gn_getVisibleItemsNext(a_itm, opts, nI),
                            xI = gn_getVisibleItemsPrev(a_itm, opts, lastItemNr - 1);
                    }
                    else {
                        var vI = opts.items.visible,
                            xI = opts.items.visible;
                    }

                    if (nI + vI > lastItemNr) {
                        nI = lastItemNr - xI;
                    }
                }

                //	set new number of visible items
                opts.items.visibleConf.old = opts.items.visible;
                if (opts.items.visibleConf.variable) {
                    var vI = cf_getItemsAdjust(gn_getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr), opts, opts.items.visibleConf.adjust, $tt0);
                    while (opts.items.visible - nI >= vI && nI < itms.total) {
                        nI++;
                        vI = cf_getItemsAdjust(gn_getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr), opts, opts.items.visibleConf.adjust, $tt0);
                    }
                    opts.items.visible = vI;
                }
                else if (opts.items.filter != '*') {
                    var vI = gn_getVisibleItemsNextFilter(a_itm, opts, nI);
                    opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0);
                }

                sz_resetMargin(a_itm, opts, true);

                //	scroll 0, don't scroll
                if (nI == 0) {
                    e.stopImmediatePropagation();
                    return debug(conf, '0 items to scroll: Not scrolling.');
                }
                debug(conf, 'Scrolling ' + nI + ' items forward.');


                //	save new config
                itms.first -= nI;
                while (itms.first < 0) {
                    itms.first += itms.total;
                }

                //	non-circular callback
                if (!opts.circular) {
                    if (itms.first == opts.items.visible && sO.onEnd) {
                        sO.onEnd.call($tt0, 'next');
                    }
                    if (!opts.infinite) {
                        nv_enableNavi(opts, itms.first, conf);
                    }
                }

                //	rearrange items
                if (itms.total < opts.items.visible + nI) {
                    $cfs.children().slice(0, (opts.items.visible + nI) - itms.total).clone(true).appendTo($cfs);
                }

                //	the needed items
                var a_itm = $cfs.children(),
                    i_old = gi_getOldItemsNext(a_itm, opts),
                    i_new = gi_getNewItemsNext(a_itm, opts, nI),
                    i_cur_l = a_itm.eq(nI - 1),
                    i_old_l = i_old.last(),
                    i_new_l = i_new.last();

                sz_resetMargin(a_itm, opts);

                var pL = 0,
                    pR = 0;

                if (opts.align) {
                    var p = cf_getAlignPadding(i_new, opts);
                    pL = p[0];
                    pR = p[1];
                }

                //	hide items for fx directscroll
                var hiddenitems = false,
                    i_skp = $();
                if (opts.items.visibleConf.old < nI) {
                    i_skp = a_itm.slice(opts.items.visibleConf.old, nI);
                    if (sO.fx == 'directscroll') {
                        var orgW = opts.items[opts.d['width']];
                        hiddenitems = i_skp;
                        i_cur_l = i_old_l;
                        sc_hideHiddenItems(hiddenitems);
                        opts.items[opts.d['width']] = 'variable';
                    }
                }

                //	save new sizes
                var $cf2 = false,
                    i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'),
                    w_siz = cf_mapWrapperSizes(ms_getSizes(i_new, opts, true), opts, !opts.usePadding),
                    i_siz_vis = 0,
                    a_cfs = {},
                    a_cfs_vis = {},
                    a_cur = {},
                    a_old = {},
                    a_lef = {},
                    a_dur = sc_getDuration(sO, opts, nI, i_siz);

                switch (sO.fx) {
                    case 'uncover':
                    case 'uncover-fade':
                        i_siz_vis = ms_getTotalSize(a_itm.slice(0, opts.items.visibleConf.old), opts, 'width');
                        break;
                }

                if (hiddenitems) {
                    opts.items[opts.d['width']] = orgW;
                }

                if (opts.align) {
                    if (opts.padding[opts.d[1]] < 0) {
                        opts.padding[opts.d[1]] = 0;
                    }
                }
                sz_resetMargin(a_itm, opts, true);
                sz_resetMargin(i_old_l, opts, opts.padding[opts.d[1]]);

                if (opts.align) {
                    opts.padding[opts.d[1]] = pR;
                    opts.padding[opts.d[3]] = pL;
                }

                a_lef[opts.d['left']] = (opts.usePadding) ? opts.padding[opts.d[3]] : 0;

                //	scrolling functions
                var _s_wrapper = function () { },
                    _a_wrapper = function () { },
                    _s_paddingold = function () { },
                    _a_paddingold = function () { },
                    _s_paddingcur = function () { },
                    _a_paddingcur = function () { },
                    _onafter = function () { },
                    _moveitems = function () { },
                    _position = function () { };

                //	clone carousel
                switch (sO.fx) {
                    case 'crossfade':
                    case 'cover':
                    case 'cover-fade':
                    case 'uncover':
                    case 'uncover-fade':
                        $cf2 = $cfs.clone(true).appendTo($wrp);
                        $cf2.children().slice(opts.items.visibleConf.old).remove();
                        break;
                }
                switch (sO.fx) {
                    case 'crossfade':
                    case 'cover':
                    case 'cover-fade':
                        $cfs.css('zIndex', 1);
                        $cf2.css('zIndex', 0);
                        break;
                }

                //	reset all scrolls
                scrl = sc_setScroll(a_dur, sO.easing, conf);

                //	animate / set carousel
                a_cfs[opts.d['left']] = -i_siz;
                a_cfs_vis[opts.d['left']] = -i_siz_vis;

                if (pL < 0) {
                    a_cfs[opts.d['left']] += pL;
                }

                //	animate / set wrapper
                if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') {
                    _s_wrapper = function () {
                        $wrp.css(w_siz);
                    };
                    _a_wrapper = function () {
                        scrl.anims.push([$wrp, w_siz]);
                    };
                }

                //	animate / set items
                if (opts.usePadding) {
                    var i_new_l_m = i_new_l.data('_cfs_origCssMargin');

                    if (pR >= 0) {
                        i_new_l_m += opts.padding[opts.d[1]];
                    }
                    i_new_l.css(opts.d['marginRight'], i_new_l_m);

                    if (i_cur_l.not(i_old_l).length) {
                        a_old[opts.d['marginRight']] = i_old_l.data('_cfs_origCssMargin');
                    }
                    _s_paddingold = function () {
                        i_old_l.css(a_old);
                    };
                    _a_paddingold = function () {
                        scrl.anims.push([i_old_l, a_old]);
                    };

                    var i_cur_l_m = i_cur_l.data('_cfs_origCssMargin');
                    if (pL > 0) {
                        i_cur_l_m += opts.padding[opts.d[3]];
                    }

                    a_cur[opts.d['marginRight']] = i_cur_l_m;

                    _s_paddingcur = function () {
                        i_cur_l.css(a_cur);
                    };
                    _a_paddingcur = function () {
                        scrl.anims.push([i_cur_l, a_cur]);
                    };
                }

                //	set position
                _position = function () {
                    $cfs.css(a_lef);
                };


                var overFill = opts.items.visible + nI - itms.total;

                //	rearrange items
                _moveitems = function () {
                    if (overFill > 0) {
                        $cfs.children().slice(itms.total).remove();
                    }
                    var l_itm = $cfs.children().slice(0, nI).appendTo($cfs).last();
                    if (overFill > 0) {
                        i_new = gi_getCurrentItems(a_itm, opts);
                    }
                    sc_showHiddenItems(hiddenitems);

                    if (opts.usePadding) {
                        if (itms.total < opts.items.visible + nI) {
                            var i_cur_l = $cfs.children().eq(opts.items.visible - 1);
                            i_cur_l.css(opts.d['marginRight'], i_cur_l.data('_cfs_origCssMargin') + opts.padding[opts.d[1]]);
                        }
                        l_itm.css(opts.d['marginRight'], l_itm.data('_cfs_origCssMargin'));
                    }
                };


                var cb_arguments = sc_mapCallbackArguments(i_old, i_skp, i_new, nI, 'next', a_dur, w_siz);

                //	fire onAfter callbacks
                _onafter = function () {
                    $cfs.css('zIndex', $cfs.data('_cfs_origCssZindex'));
                    sc_afterScroll($cfs, $cf2, sO);
                    crsl.isScrolling = false;
                    clbk.onAfter = sc_fireCallbacks($tt0, sO, 'onAfter', cb_arguments, clbk);
                    queu = sc_fireQueue($cfs, queu, conf);

                    if (!crsl.isPaused) {
                        $cfs.trigger(cf_e('play', conf));
                    }
                };

                //	fire onBefore callbacks
                crsl.isScrolling = true;
                tmrs = sc_clearTimers(tmrs);
                clbk.onBefore = sc_fireCallbacks($tt0, sO, 'onBefore', cb_arguments, clbk);

                switch (sO.fx) {
                    case 'none':
                        $cfs.css(a_cfs);
                        _s_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        _onafter();
                        break;

                    case 'fade':
                        scrl.anims.push([$cfs, { 'opacity': 0 }, function () {
                            _s_wrapper();
                            _s_paddingold();
                            _s_paddingcur();
                            _position();
                            _moveitems();
                            scrl = sc_setScroll(a_dur, sO.easing, conf);
                            scrl.anims.push([$cfs, { 'opacity': 1 }, _onafter]);
                            sc_startScroll(scrl, conf);
                        }]);
                        break;

                    case 'crossfade':
                        $cfs.css({ 'opacity': 0 });
                        scrl.anims.push([$cf2, { 'opacity': 0 }]);
                        scrl.anims.push([$cfs, { 'opacity': 1 }, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    case 'cover':
                        $cfs.css(opts.d['left'], $wrp[opts.d['width']]());
                        scrl.anims.push([$cfs, a_lef, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _moveitems();
                        break;

                    case 'cover-fade':
                        $cfs.css(opts.d['left'], $wrp[opts.d['width']]());
                        scrl.anims.push([$cf2, { 'opacity': 0 }]);
                        scrl.anims.push([$cfs, a_lef, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _moveitems();
                        break;

                    case 'uncover':
                        scrl.anims.push([$cf2, a_cfs_vis, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    case 'uncover-fade':
                        $cfs.css({ 'opacity': 0 });
                        scrl.anims.push([$cfs, { 'opacity': 1 }]);
                        scrl.anims.push([$cf2, a_cfs_vis, _onafter]);
                        _a_wrapper();
                        _s_paddingold();
                        _s_paddingcur();
                        _position();
                        _moveitems();
                        break;

                    default:
                        scrl.anims.push([$cfs, a_cfs, function () {
                            _position();
                            _moveitems();
                            _onafter();
                        }]);
                        _a_wrapper();
                        _a_paddingold();
                        _a_paddingcur();
                        break;
                }

                sc_startScroll(scrl, conf);
                cf_setCookie(opts.cookie, $cfs, conf);

                $cfs.trigger(cf_e('updatePageStatus', conf), [false, w_siz]);

                return true;
            });


            //	slideTo event
            $cfs.on(cf_e('slideTo', conf), function (e, num, dev, org, obj, dir, clb) {
                e.stopPropagation();

                var v = [num, dev, org, obj, dir, clb],
                    t = ['string/number/object', 'number', 'boolean', 'object', 'string', 'function'],
                    a = cf_sortParams(v, t);

                obj = a[3];
                dir = a[4];
                clb = a[5];

                num = gn_getItemIndex(a[0], a[1], a[2], itms, $cfs);

                if (num == 0) {
                    return false;
                }
                if (!is_object(obj)) {
                    obj = false;
                }

                if (dir != 'prev' && dir != 'next') {
                    if (opts.circular) {
                        dir = (num <= itms.total / 2) ? 'next' : 'prev';
                    }
                    else {
                        dir = (itms.first == 0 || itms.first > num) ? 'next' : 'prev';
                    }
                }

                if (dir == 'prev') {
                    num = itms.total - num;
                }
                $cfs.trigger(cf_e(dir, conf), [obj, num, clb]);

                return true;
            });


            //	prevPage event
            $cfs.on(cf_e('prevPage', conf), function (e, obj, clb) {
                e.stopPropagation();
                var cur = $cfs.triggerHandler(cf_e('currentPage', conf));
                return $cfs.triggerHandler(cf_e('slideToPage', conf), [cur - 1, obj, 'prev', clb]);
            });


            //	nextPage event
            $cfs.on(cf_e('nextPage', conf), function (e, obj, clb) {
                e.stopPropagation();
                var cur = $cfs.triggerHandler(cf_e('currentPage', conf));
                return $cfs.triggerHandler(cf_e('slideToPage', conf), [cur + 1, obj, 'next', clb]);
            });


            //	slideToPage event
            $cfs.on(cf_e('slideToPage', conf), function (e, pag, obj, dir, clb) {
                e.stopPropagation();
                if (!is_number(pag)) {
                    pag = $cfs.triggerHandler(cf_e('currentPage', conf));
                }
                var ipp = opts.pagination.items || opts.items.visible,
                    max = Math.ceil(itms.total / ipp) - 1;

                if (pag < 0) {
                    pag = max;
                }
                if (pag > max) {
                    pag = 0;
                }
                return $cfs.triggerHandler(cf_e('slideTo', conf), [pag * ipp, 0, true, obj, dir, clb]);
            });

            //	jumpToStart event
            $cfs.on(cf_e('jumpToStart', conf), function (e, s) {
                e.stopPropagation();
                if (s) {
                    s = gn_getItemIndex(s, 0, true, itms, $cfs);
                }
                else {
                    s = 0;
                }

                s += itms.first;
                if (s != 0) {
                    if (itms.total > 0) {
                        while (s > itms.total) {
                            s -= itms.total;
                        }
                    }
                    $cfs.prepend($cfs.children().slice(s, itms.total));
                }
                return true;
            });


            //	synchronise event
            $cfs.on(cf_e('synchronise', conf), function (e, s) {
                e.stopPropagation();
                if (s) {
                    s = cf_getSynchArr(s);
                }
                else if (opts.synchronise) {
                    s = opts.synchronise;
                }
                else {
                    return debug(conf, 'No carousel to synchronise.');
                }

                var n = $cfs.triggerHandler(cf_e('currentPosition', conf)),
                    x = true;

                for (var j = 0, l = s.length; j < l; j++) {
                    if (!s[j][0].triggerHandler(cf_e('slideTo', conf), [n, s[j][3], true])) {
                        x = false;
                    }
                }
                return x;
            });


            //	queue event
            $cfs.on(cf_e('queue', conf), function (e, dir, opt) {
                e.stopPropagation();
                if (is_function(dir)) {
                    dir.call($tt0, queu);
                }
                else if (is_array(dir)) {
                    queu = dir;
                }
                else if (!is_undefined(dir)) {
                    queu.push([dir, opt]);
                }
                return queu;
            });


            //	insertItem event
            $cfs.on(cf_e('insertItem', conf), function (e, itm, num, org, dev) {
                e.stopPropagation();

                var v = [itm, num, org, dev],
                    t = ['string/object', 'string/number/object', 'boolean', 'number'],
                    a = cf_sortParams(v, t);

                itm = a[0];
                num = a[1];
                org = a[2];
                dev = a[3];

                if (is_object(itm) && !is_jquery(itm)) {
                    itm = $(itm);
                }
                else if (is_string(itm)) {
                    itm = $(itm);
                }
                if (!is_jquery(itm) || itm.length == 0) {
                    return debug(conf, 'Not a valid object.');
                }

                if (is_undefined(num)) {
                    num = 'end';
                }

                sz_storeMargin(itm, opts);
                sz_storeOrigCss(itm);

                var orgNum = num,
                    before = 'before';

                if (num == 'end') {
                    if (org) {
                        if (itms.first == 0) {
                            num = itms.total - 1;
                            before = 'after';
                        }
                        else {
                            num = itms.first;
                            itms.first += itm.length;
                        }
                        if (num < 0) {
                            num = 0;
                        }
                    }
                    else {
                        num = itms.total - 1;
                        before = 'after';
                    }
                }
                else {
                    num = gn_getItemIndex(num, dev, org, itms, $cfs);
                }

                var $cit = $cfs.children().eq(num);
                if ($cit.length) {
                    $cit[before](itm);
                }
                else {
                    debug(conf, 'Correct insert-position not found! Appending item to the end.');
                    $cfs.append(itm);
                }

                if (orgNum != 'end' && !org) {
                    if (num < itms.first) {
                        itms.first += itm.length;
                    }
                }
                itms.total = $cfs.children().length;
                if (itms.first >= itms.total) {
                    itms.first -= itms.total;
                }

                $cfs.trigger(cf_e('updateSizes', conf));
                $cfs.trigger(cf_e('linkAnchors', conf));

                return true;
            });


            //	removeItem event
            $cfs.on(cf_e('removeItem', conf), function (e, num, org, dev) {
                e.stopPropagation();

                var v = [num, org, dev],
                    t = ['string/number/object', 'boolean', 'number'],
                    a = cf_sortParams(v, t);

                num = a[0];
                org = a[1];
                dev = a[2];

                var removed = false;

                if (num instanceof $ && num.length > 1) {
                    $removed = $();
                    num.each(function (i, el) {
                        var $rem = $cfs.trigger(cf_e('removeItem', conf), [$(this), org, dev]);
                        if ($rem) {
                            $removed = $removed.add($rem);
                        }
                    });
                    return $removed;
                }

                if (is_undefined(num) || num == 'end') {
                    $removed = $cfs.children().last();
                }
                else {
                    num = gn_getItemIndex(num, dev, org, itms, $cfs);
                    var $removed = $cfs.children().eq(num);
                    if ($removed.length) {
                        if (num < itms.first) {
                            itms.first -= $removed.length;
                        }
                    }
                }
                if ($removed && $removed.length) {
                    $removed.detach();
                    itms.total = $cfs.children().length;
                    $cfs.trigger(cf_e('updateSizes', conf));
                }

                return $removed;
            });


            //	onBefore and onAfter event
            $cfs.on(cf_e('onBefore', conf) + ' ' + cf_e('onAfter', conf), function (e, fn) {
                e.stopPropagation();
                var eType = e.type.slice(conf.events.prefix.length);
                if (is_array(fn)) {
                    clbk[eType] = fn;
                }
                if (is_function(fn)) {
                    clbk[eType].push(fn);
                }
                return clbk[eType];
            });


            //	currentPosition event
            $cfs.on(cf_e('currentPosition', conf), function (e, fn) {
                e.stopPropagation();
                if (itms.first == 0) {
                    var val = 0;
                }
                else {
                    var val = itms.total - itms.first;
                }
                if (is_function(fn)) {
                    fn.call($tt0, val);
                }
                return val;
            });


            //	currentPage event
            $cfs.on(cf_e('currentPage', conf), function (e, fn) {
                e.stopPropagation();
                var ipp = opts.pagination.items || opts.items.visible,
                    max = Math.ceil(itms.total / ipp - 1),
                    nr;
                if (itms.first == 0) {
                    nr = 0;
                }
                else if (itms.first < itms.total % ipp) {
                    nr = 0;
                }
                else if (itms.first == ipp && !opts.circular) {
                    nr = max;
                }
                else {
                    nr = Math.round((itms.total - itms.first) / ipp);
                }
                if (nr < 0) {
                    nr = 0;
                }
                if (nr > max) {
                    nr = max;
                }
                if (is_function(fn)) {
                    fn.call($tt0, nr);
                }
                return nr;
            });


            //	currentVisible event
            $cfs.on(cf_e('currentVisible', conf), function (e, fn) {
                e.stopPropagation();
                var $i = gi_getCurrentItems($cfs.children(), opts);
                if (is_function(fn)) {
                    fn.call($tt0, $i);
                }
                return $i;
            });


            //	slice event
            $cfs.on(cf_e('slice', conf), function (e, f, l, fn) {
                e.stopPropagation();

                if (itms.total == 0) {
                    return false;
                }

                var v = [f, l, fn],
                    t = ['number', 'number', 'function'],
                    a = cf_sortParams(v, t);

                f = (is_number(a[0])) ? a[0] : 0;
                l = (is_number(a[1])) ? a[1] : itms.total;
                fn = a[2];

                f += itms.first;
                l += itms.first;

                if (items.total > 0) {
                    while (f > itms.total) {
                        f -= itms.total;
                    }
                    while (l > itms.total) {
                        l -= itms.total;
                    }
                    while (f < 0) {
                        f += itms.total;
                    }
                    while (l < 0) {
                        l += itms.total;
                    }
                }
                var $iA = $cfs.children(),
                    $i;

                if (l > f) {
                    $i = $iA.slice(f, l);
                }
                else {
                    $i = $($iA.slice(f, itms.total).get().concat($iA.slice(0, l).get()));
                }

                if (is_function(fn)) {
                    fn.call($tt0, $i);
                }
                return $i;
            });


            //	isPaused, isStopped and isScrolling events
            $cfs.on(cf_e('isPaused', conf) + ' ' + cf_e('isStopped', conf) + ' ' + cf_e('isScrolling', conf), function (e, fn) {
                e.stopPropagation();
                var eType = e.type.slice(conf.events.prefix.length),
                    value = crsl[eType];
                if (is_function(fn)) {
                    fn.call($tt0, value);
                }
                return value;
            });


            //	configuration event
            $cfs.on(cf_e('configuration', conf), function (e, a, b, c) {
                e.stopPropagation();
                var reInit = false;

                //	return entire configuration-object
                if (is_function(a)) {
                    a.call($tt0, opts);
                }
                //	set multiple options via object
                else if (is_object(a)) {
                    opts_orig = $.extend(true, {}, opts_orig, a);
                    if (b !== false) reInit = true;
                    else opts = $.extend(true, {}, opts, a);

                }
                else if (!is_undefined(a)) {

                    //	callback function for specific option
                    if (is_function(b)) {
                        var val = eval('opts.' + a);
                        if (is_undefined(val)) {
                            val = '';
                        }
                        b.call($tt0, val);
                    }
                    //	set individual option
                    else if (!is_undefined(b)) {
                        if (typeof c !== 'boolean') c = true;
                        eval('opts_orig.' + a + ' = b');
                        if (c !== false) reInit = true;
                        else eval('opts.' + a + ' = b');
                    }
                    //	return value for specific option
                    else {
                        return eval('opts.' + a);
                    }
                }
                if (reInit) {
                    sz_resetMargin($cfs.children(), opts);
                    FN._init(opts_orig);
                    FN._bind_buttons();
                    var sz = sz_setSizes($cfs, opts);
                    $cfs.trigger(cf_e('updatePageStatus', conf), [true, sz]);
                }
                return opts;
            });


            //	linkAnchors event
            $cfs.on(cf_e('linkAnchors', conf), function (e, $con, sel) {
                e.stopPropagation();

                if (is_undefined($con)) {
                    $con = $('body');
                }
                else if (is_string($con)) {
                    $con = $($con);
                }
                if (!is_jquery($con) || $con.length == 0) {
                    return debug(conf, 'Not a valid object.');
                }
                if (!is_string(sel)) {
                    sel = 'a.caroufredsel';
                }

                $con.find(sel).each(function () {
                    var h = this.hash || '';
                    if (h.length > 0 && $cfs.children().index($(h)) != -1) {
                        $(this).off('click').on("click", function (e) {
                            e.preventDefault();
                            $cfs.trigger(cf_e('slideTo', conf), h);
                        });
                    }
                });
                return true;
            });


            //	updatePageStatus event
            $cfs.on(cf_e('updatePageStatus', conf), function (e, build, sizes) {
                e.stopPropagation();
                if (!opts.pagination.container) {
                    return;
                }

                var ipp = opts.pagination.items || opts.items.visible,
                    pgs = Math.ceil(itms.total / ipp);

                if (build) {
                    if (opts.pagination.anchorBuilder) {
                        opts.pagination.container.children().remove();
                        opts.pagination.container.each(function () {
                            for (var a = 0; a < pgs; a++) {
                                var i = $cfs.children().eq(gn_getItemIndex(a * ipp, 0, true, itms, $cfs));
                                $(this).append(opts.pagination.anchorBuilder.call(i[0], a + 1));
                            }
                        });
                    }
                    opts.pagination.container.each(function () {
                        $(this).children().off(opts.pagination.event).each(function (a) {
                            $(this).on(opts.pagination.event, function (e) {
                                e.preventDefault();
                                $cfs.trigger(cf_e('slideTo', conf), [a * ipp, -opts.pagination.deviation, true, opts.pagination]);
                            });
                        });
                    });
                }

                var selected = $cfs.triggerHandler(cf_e('currentPage', conf)) + opts.pagination.deviation;
                if (selected >= pgs) {
                    selected = 0;
                }
                if (selected < 0) {
                    selected = pgs - 1;
                }
                opts.pagination.container.each(function () {
                    $(this).children().removeClass(cf_c('selected', conf)).eq(selected).addClass(cf_c('selected', conf));
                });
                return true;
            });


            //	updateSizes event
            $cfs.on(cf_e('updateSizes', conf), function (e) {
                var vI = opts.items.visible,
                    a_itm = $cfs.children(),
                    avail_primary = ms_getParentSize($wrp, opts, 'width');

                itms.total = a_itm.length;

                if (crsl.primarySizePercentage) {
                    opts.maxDimension = avail_primary;
                    opts[opts.d['width']] = ms_getPercentage(avail_primary, crsl.primarySizePercentage);
                }
                else {
                    opts.maxDimension = ms_getMaxDimension(opts, avail_primary);
                }

                if (opts.responsive) {
                    opts.items.width = opts.items.sizesConf.width;
                    opts.items.height = opts.items.sizesConf.height;
                    opts = in_getResponsiveValues(opts, a_itm, avail_primary);
                    vI = opts.items.visible;
                    sz_setResponsiveSizes(opts, a_itm);
                }
                else if (opts.items.visibleConf.variable) {
                    vI = gn_getVisibleItemsNext(a_itm, opts, 0);
                }
                else if (opts.items.filter != '*') {
                    vI = gn_getVisibleItemsNextFilter(a_itm, opts, 0);
                }

                if (!opts.circular && itms.first != 0 && vI > itms.first) {
                    if (opts.items.visibleConf.variable) {
                        var nI = gn_getVisibleItemsPrev(a_itm, opts, itms.first) - itms.first;
                    }
                    else if (opts.items.filter != '*') {
                        var nI = gn_getVisibleItemsPrevFilter(a_itm, opts, itms.first) - itms.first;
                    }
                    else {
                        var nI = opts.items.visible - itms.first;
                    }
                    debug(conf, 'Preventing non-circular: sliding ' + nI + ' items backward.');
                    $cfs.trigger(cf_e('prev', conf), nI);
                }

                opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0);
                opts.items.visibleConf.old = opts.items.visible;
                opts = in_getAlignPadding(opts, a_itm);

                var sz = sz_setSizes($cfs, opts);
                $cfs.trigger(cf_e('updatePageStatus', conf), [true, sz]);
                nv_showNavi(opts, itms.total, conf);
                nv_enableNavi(opts, itms.first, conf);

                return sz;
            });


            //	destroy event
            $cfs.on(cf_e('destroy', conf), function (e, orgOrder) {
                e.stopPropagation();
                tmrs = sc_clearTimers(tmrs);

                $cfs.data('_cfs_isCarousel', false);
                $cfs.trigger(cf_e('finish', conf));
                if (orgOrder) {
                    $cfs.trigger(cf_e('jumpToStart', conf));
                }
                sz_restoreOrigCss($cfs.children());
                sz_restoreOrigCss($cfs);
                FN._unbind_events();
                FN._unbind_buttons();
                if (conf.wrapper == 'parent') {
                    sz_restoreOrigCss($wrp);
                }
                else {
                    $wrp.replaceWith($cfs);
                }

                return true;
            });


            //	debug event
            $cfs.on(cf_e('debug', conf), function (e) {
                debug(conf, 'Carousel width: ' + opts.width);
                debug(conf, 'Carousel height: ' + opts.height);
                debug(conf, 'Item widths: ' + opts.items.width);
                debug(conf, 'Item heights: ' + opts.items.height);
                debug(conf, 'Number of items visible: ' + opts.items.visible);
                if (opts.auto.play) {
                    debug(conf, 'Number of items scrolled automatically: ' + opts.auto.items);
                }
                if (opts.prev.button) {
                    debug(conf, 'Number of items scrolled backward: ' + opts.prev.items);
                }
                if (opts.next.button) {
                    debug(conf, 'Number of items scrolled forward: ' + opts.next.items);
                }
                return conf.debug;
            });


            //	triggerEvent, making prefixed and namespaced events accessible from outside
            $cfs.on('_cfs_triggerEvent', function (e, n, o) {
                e.stopPropagation();
                return $cfs.triggerHandler(cf_e(n, conf), o);
            });
        };	//	/bind_events


        FN._unbind_events = function () {
            $cfs.off(cf_e('', conf));
            $cfs.off(cf_e('', conf, false));
            $cfs.off('_cfs_triggerEvent');
        };	//	/unbind_events


        FN._bind_buttons = function () {
            FN._unbind_buttons();
            nv_showNavi(opts, itms.total, conf);
            nv_enableNavi(opts, itms.first, conf);

            if (opts.auto.pauseOnHover) {
                var pC = bt_pauseOnHoverConfig(opts.auto.pauseOnHover);
                $wrp.on(cf_e('mouseenter', conf, false), function () { $cfs.trigger(cf_e('pause', conf), pC); })
                    .on(cf_e('mouseleave', conf, false), function () { $cfs.trigger(cf_e('resume', conf)); });
            }

            //	play button
            if (opts.auto.button) {
                opts.auto.button.on(cf_e(opts.auto.event, conf, false), function (e) {
                    e.preventDefault();
                    var ev = false,
                        pC = null;

                    if (crsl.isPaused) {
                        ev = 'play';
                    }
                    else if (opts.auto.pauseOnEvent) {
                        ev = 'pause';
                        pC = bt_pauseOnHoverConfig(opts.auto.pauseOnEvent);
                    }
                    if (ev) {
                        $cfs.trigger(cf_e(ev, conf), pC);
                    }
                });
            }

            //	prev button
            if (opts.prev.button) {
                opts.prev.button.on(cf_e(opts.prev.event, conf, false), function (e) {
                    e.preventDefault();
                    $cfs.trigger(cf_e('prev', conf));
                });
                if (opts.prev.pauseOnHover) {
                    var pC = bt_pauseOnHoverConfig(opts.prev.pauseOnHover);
                    opts.prev.button.on(cf_e('mouseenter', conf, false), function () { $cfs.trigger(cf_e('pause', conf), pC); })
                        .on(cf_e('mouseleave', conf, false), function () { $cfs.trigger(cf_e('resume', conf)); });
                }
            }

            //	next butotn
            if (opts.next.button) {
                opts.next.button.on(cf_e(opts.next.event, conf, false), function (e) {
                    e.preventDefault();
                    $cfs.trigger(cf_e('next', conf));
                });
                if (opts.next.pauseOnHover) {
                    var pC = bt_pauseOnHoverConfig(opts.next.pauseOnHover);
                    opts.next.button.on(cf_e('mouseenter', conf, false), function () { $cfs.trigger(cf_e('pause', conf), pC); })
                        .on(cf_e('mouseleave', conf, false), function () { $cfs.trigger(cf_e('resume', conf)); });
                }
            }

            //	pagination
            if (opts.pagination.container) {
                if (opts.pagination.pauseOnHover) {
                    var pC = bt_pauseOnHoverConfig(opts.pagination.pauseOnHover);
                    opts.pagination.container.on(cf_e('mouseenter', conf, false), function () { $cfs.trigger(cf_e('pause', conf), pC); })
                        .on(cf_e('mouseleave', conf, false), function () { $cfs.trigger(cf_e('resume', conf)); });
                }
            }

            //	prev/next keys
            if (opts.prev.key || opts.next.key) {
                $(document).on(cf_e('keyup', conf, false, true, true), function (e) {
                    var k = e.keyCode;
                    if (k == opts.next.key) {
                        e.preventDefault();
                        $cfs.trigger(cf_e('next', conf));
                    }
                    if (k == opts.prev.key) {
                        e.preventDefault();
                        $cfs.trigger(cf_e('prev', conf));
                    }
                });
            }

            //	pagination keys
            if (opts.pagination.keys) {
                $(document).on(cf_e('keyup', conf, false, true, true), function (e) {
                    var k = e.keyCode;
                    if (k >= 49 && k < 58) {
                        k = (k - 49) * opts.items.visible;
                        if (k <= itms.total) {
                            e.preventDefault();
                            $cfs.trigger(cf_e('slideTo', conf), [k, 0, true, opts.pagination]);
                        }
                    }
                });
            }

            //	swipe
            if ($.fn.swipe) {
                var isTouch = 'ontouchstart' in window;
                if ((isTouch && opts.swipe.onTouch) || (!isTouch && opts.swipe.onMouse)) {
                    var scP = $.extend(true, {}, opts.prev, opts.swipe),
                        scN = $.extend(true, {}, opts.next, opts.swipe),
                        swP = function () { $cfs.trigger(cf_e('prev', conf), [scP]) },
                        swN = function () { $cfs.trigger(cf_e('next', conf), [scN]) };

                    switch (opts.direction) {
                        case 'up':
                        case 'down':
                            opts.swipe.options.swipeUp = swN;
                            opts.swipe.options.swipeDown = swP;
                            break;
                        default:
                            opts.swipe.options.swipeLeft = swN;
                            opts.swipe.options.swipeRight = swP;
                    }
                    if (crsl.swipe) {
                        $cfs.swipe('destroy');
                    }
                    $wrp.swipe(opts.swipe.options);
                    $wrp.css('cursor', 'move');
                    crsl.swipe = true;
                }
            }

            //	mousewheel
            if ($.fn.mousewheel) {

                if (opts.mousewheel) {
                    var mcP = $.extend(true, {}, opts.prev, opts.mousewheel),
                        mcN = $.extend(true, {}, opts.next, opts.mousewheel);

                    if (crsl.mousewheel) {
                        $wrp.off(cf_e('mousewheel', conf, false));
                    }
                    $wrp.on(cf_e('mousewheel', conf, false), function (e, delta) {
                        e.preventDefault();
                        if (delta > 0) {
                            $cfs.trigger(cf_e('prev', conf), [mcP]);
                        }
                        else {
                            $cfs.trigger(cf_e('next', conf), [mcN]);
                        }
                    });
                    crsl.mousewheel = true;
                }
            }

            if (opts.auto.play) {
                $cfs.trigger(cf_e('play', conf), opts.auto.delay);
            }

            if (crsl.upDateOnWindowResize) {
                var resizeFn = function (e) {
                    $cfs.trigger(cf_e('finish', conf));
                    if (opts.auto.pauseOnResize && !crsl.isPaused) {
                        $cfs.trigger(cf_e('play', conf));
                    }
                    sz_resetMargin($cfs.children(), opts);
                    $cfs.trigger(cf_e('updateSizes', conf));
                };

                var $w = $(window),
                    onResize = null;

                if ($.debounce && conf.onWindowResize == 'debounce') {
                    onResize = $.debounce(200, resizeFn);
                }
                else if ($.throttle && conf.onWindowResize == 'throttle') {
                    onResize = $.throttle(300, resizeFn);
                }
                else {
                    var _windowWidth = 0,
                        _windowHeight = 0;

                    onResize = function () {
                        var nw = $w.width(),
                            nh = $w.height();

                        if (nw != _windowWidth || nh != _windowHeight) {
                            resizeFn();
                            _windowWidth = nw;
                            _windowHeight = nh;
                        }
                    };
                }
                $w.on(cf_e('resize', conf, false, true, true), onResize);
            }
        };	//	/bind_buttons


        FN._unbind_buttons = function () {
            var ns1 = cf_e('', conf),
                ns2 = cf_e('', conf, false);
            ns3 = cf_e('', conf, false, true, true);

            $(document).off(ns3);
            $(window).off(ns3);
            $wrp.off(ns2);

            if (opts.auto.button) {
                opts.auto.button.off(ns2);
            }
            if (opts.prev.button) {
                opts.prev.button.off(ns2);
            }
            if (opts.next.button) {
                opts.next.button.off(ns2);
            }
            if (opts.pagination.container) {
                opts.pagination.container.off(ns2);
                if (opts.pagination.anchorBuilder) {
                    opts.pagination.container.children().remove();
                }
            }
            if (crsl.swipe) {
                $cfs.swipe('destroy');
                $wrp.css('cursor', 'default');
                crsl.swipe = false;
            }
            if (crsl.mousewheel) {
                crsl.mousewheel = false;
            }

            nv_showNavi(opts, 'hide', conf);
            nv_enableNavi(opts, 'removeClass', conf);

        };	//	/unbind_buttons



        //	START

        if (is_boolean(configs)) {
            configs = {
                'debug': configs
            };
        }

        //	set vars
        var crsl = {
            'direction': 'next',
            'isPaused': true,
            'isScrolling': false,
            'isStopped': false,
            'mousewheel': false,
            'swipe': false
        },
            itms = {
                'total': $cfs.children().length,
                'first': 0
            },
            tmrs = {
                'auto': null,
                'progress': null,
                'startTime': getTime(),
                'timePassed': 0
            },
            scrl = {
                'isStopped': false,
                'duration': 0,
                'startTime': 0,
                'easing': '',
                'anims': []
            },
            clbk = {
                'onBefore': [],
                'onAfter': []
            },
            queu = [],
            conf = $.extend(true, {}, $.fn.carouFredSel.configs, configs),
            opts = {},
            opts_orig = $.extend(true, {}, options),
            $wrp = (conf.wrapper == 'parent')
                ? $cfs.parent()
                : $cfs.wrap('<' + conf.wrapper.element + ' class="' + conf.wrapper.classname + '" />').parent();


        conf.selector = $cfs.selector;
        conf.serialNumber = $.fn.carouFredSel.serialNumber++;

        conf.transition = (conf.transition && $.fn.transition) ? 'transition' : 'animate';

        //	create carousel
        FN._init(opts_orig, true, starting_position);
        FN._build();
        FN._bind_events();
        FN._bind_buttons();

        //	find item to start
        if (is_array(opts.items.start)) {
            var start_arr = opts.items.start;
        }
        else {
            var start_arr = [];
            if (opts.items.start != 0) {
                start_arr.push(opts.items.start);
            }
        }
        if (opts.cookie) {
            start_arr.unshift(parseInt(cf_getCookie(opts.cookie), 10));
        }

        if (start_arr.length > 0) {
            for (var a = 0, l = start_arr.length; a < l; a++) {
                var s = start_arr[a];
                if (s == 0) {
                    continue;
                }
                if (s === true) {
                    s = window.location.hash;
                    if (s.length < 1) {
                        continue;
                    }
                }
                else if (s === 'random') {
                    s = Math.floor(Math.random() * itms.total);
                }
                if ($cfs.triggerHandler(cf_e('slideTo', conf), [s, 0, true, { fx: 'none' }])) {
                    break;
                }
            }
        }
        var siz = sz_setSizes($cfs, opts),
            itm = gi_getCurrentItems($cfs.children(), opts);

        if (opts.onCreate) {
            opts.onCreate.call($tt0, {
                'width': siz.width,
                'height': siz.height,
                'items': itm
            });
        }

        $cfs.trigger(cf_e('updatePageStatus', conf), [true, siz]);
        $cfs.trigger(cf_e('linkAnchors', conf));

        if (conf.debug) {
            $cfs.trigger(cf_e('debug', conf));
        }

        return $cfs;
    };



    //	GLOBAL PUBLIC

    $.fn.carouFredSel.serialNumber = 1;
    $.fn.carouFredSel.defaults = {
        'synchronise': false,
        'infinite': true,
        'circular': true,
        'responsive': false,
        'direction': 'left',
        'items': {
            'start': 0
        },
        'scroll': {
            'easing': 'swing',
            'duration': 500,
            'pauseOnHover': false,
            'event': 'click',
            'queue': false
        }
    };
    $.fn.carouFredSel.configs = {
        'debug': false,
        'transition': false,
        'onWindowResize': 'throttle',
        'events': {
            'prefix': '',
            'namespace': 'cfs'
        },
        'wrapper': {
            'element': 'div',
            'classname': 'caroufredsel_wrapper'
        },
        'classnames': {}
    };
    $.fn.carouFredSel.pageAnchorBuilder = function (nr) {
        return '<a href="#"><span>' + nr + '</span></a>';
    };
    $.fn.carouFredSel.progressbarUpdater = function (perc) {
        $(this).css('width', perc + '%');
    };

    $.fn.carouFredSel.cookie = {
        get: function (n) {
            n += '=';
            var ca = document.cookie.split(';');
            for (var a = 0, l = ca.length; a < l; a++) {
                var c = ca[a];
                while (c.charAt(0) == ' ') {
                    c = c.slice(1);
                }
                if (c.indexOf(n) == 0) {
                    return c.slice(n.length);
                }
            }
            return 0;
        },
        set: function (n, v, d) {
            var e = "";
            if (d) {
                var date = new Date();
                date.setTime(date.getTime() + (d * 24 * 60 * 60 * 1000));
                e = "; expires=" + date.toGMTString();
            }
            document.cookie = n + '=' + v + e + '; path=/';
        },
        remove: function (n) {
            $.fn.carouFredSel.cookie.set(n, "", -1);
        }
    };


    //	GLOBAL PRIVATE

    //	scrolling functions
    function sc_setScroll(d, e, c) {
        if (c.transition == 'transition') {
            if (e == 'swing') {
                e = 'ease';
            }
        }
        return {
            anims: [],
            duration: d,
            orgDuration: d,
            easing: e,
            startTime: getTime()
        };
    }
    function sc_startScroll(s, c) {
        for (var a = 0, l = s.anims.length; a < l; a++) {
            var b = s.anims[a];
            if (!b) {
                continue;
            }
            b[0][c.transition](b[1], s.duration, s.easing, b[2]);
        }
    }
    function sc_stopScroll(s, finish) {
        if (!is_boolean(finish)) {
            finish = true;
        }
        if (is_object(s.pre)) {
            sc_stopScroll(s.pre, finish);
        }
        for (var a = 0, l = s.anims.length; a < l; a++) {
            var b = s.anims[a];
            b[0].stop(true);
            if (finish) {
                b[0].css(b[1]);
                if (is_function(b[2])) {
                    b[2]();
                }
            }
        }
        if (is_object(s.post)) {
            sc_stopScroll(s.post, finish);
        }
    }
    function sc_afterScroll($c, $c2, o) {
        if ($c2) {
            $c2.remove();
        }

        switch (o.fx) {
            case 'fade':
            case 'crossfade':
            case 'cover-fade':
            case 'uncover-fade':
                $c.css('opacity', 1);
                $c.css('filter', '');
                break;
        }
    }
    function sc_fireCallbacks($t, o, b, a, c) {
        if (o[b]) {
            o[b].call($t, a);
        }
        if (c[b].length) {
            for (var i = 0, l = c[b].length; i < l; i++) {
                c[b][i].call($t, a);
            }
        }
        return [];
    }
    function sc_fireQueue($c, q, c) {

        if (q.length) {
            $c.trigger(cf_e(q[0][0], c), q[0][1]);
            q.shift();
        }
        return q;
    }
    function sc_hideHiddenItems(hiddenitems) {
        hiddenitems.each(function () {
            var hi = $(this);
            hi.data('_cfs_isHidden', hi.is(':hidden')).hide();
        });
    }
    function sc_showHiddenItems(hiddenitems) {
        if (hiddenitems) {
            hiddenitems.each(function () {
                var hi = $(this);
                if (!hi.data('_cfs_isHidden')) {
                    hi.show();
                }
            });
        }
    }
    function sc_clearTimers(t) {
        if (t.auto) {
            clearTimeout(t.auto);
        }
        if (t.progress) {
            clearInterval(t.progress);
        }
        return t;
    }
    function sc_mapCallbackArguments(i_old, i_skp, i_new, s_itm, s_dir, s_dur, w_siz) {
        return {
            'width': w_siz.width,
            'height': w_siz.height,
            'items': {
                'old': i_old,
                'skipped': i_skp,
                'visible': i_new
            },
            'scroll': {
                'items': s_itm,
                'direction': s_dir,
                'duration': s_dur
            }
        };
    }
    function sc_getDuration(sO, o, nI, siz) {
        var dur = sO.duration;
        if (sO.fx == 'none') {
            return 0;
        }
        if (dur == 'auto') {
            dur = o.scroll.duration / o.scroll.items * nI;
        }
        else if (dur < 10) {
            dur = siz / dur;
        }
        if (dur < 1) {
            return 0;
        }
        if (sO.fx == 'fade') {
            dur = dur / 2;
        }
        return Math.round(dur);
    }

    //	navigation functions
    function nv_showNavi(o, t, c) {
        var minimum = (is_number(o.items.minimum)) ? o.items.minimum : o.items.visible + 1;
        if (t == 'show' || t == 'hide') {
            var f = t;
        }
        else if (minimum > t) {
            debug(c, 'Not enough items (' + t + ' total, ' + minimum + ' needed): Hiding navigation.');
            var f = 'hide';
        }
        else {
            var f = 'show';
        }
        var s = (f == 'show') ? 'removeClass' : 'addClass',
            h = cf_c('hidden', c);

        if (o.auto.button) {
            o.auto.button[f]()[s](h);
        }
        if (o.prev.button) {
            o.prev.button[f]()[s](h);
        }
        if (o.next.button) {
            o.next.button[f]()[s](h);
        }
        if (o.pagination.container) {
            o.pagination.container[f]()[s](h);
        }
    }
    function nv_enableNavi(o, f, c) {
        if (o.circular || o.infinite) return;
        var fx = (f == 'removeClass' || f == 'addClass') ? f : false,
            di = cf_c('disabled', c);

        if (o.auto.button && fx) {
            o.auto.button[fx](di);
        }
        if (o.prev.button) {
            var fn = fx || (f == 0) ? 'addClass' : 'removeClass';
            o.prev.button[fn](di);
        }
        if (o.next.button) {
            var fn = fx || (f == o.items.visible) ? 'addClass' : 'removeClass';
            o.next.button[fn](di);
        }
    }

    //	get object functions
    function go_getObject($tt, obj) {
        if (is_function(obj)) {
            obj = obj.call($tt);
        }
        else if (is_undefined(obj)) {
            obj = {};
        }
        return obj;
    }
    function go_getItemsObject($tt, obj) {
        obj = go_getObject($tt, obj);
        if (is_number(obj)) {
            obj = {
                'visible': obj
            };
        }
        else if (obj == 'variable') {
            obj = {
                'visible': obj,
                'width': obj,
                'height': obj
            };
        }
        else if (!is_object(obj)) {
            obj = {};
        }
        return obj;
    }
    function go_getScrollObject($tt, obj) {
        obj = go_getObject($tt, obj);
        if (is_number(obj)) {
            if (obj <= 50) {
                obj = {
                    'items': obj
                };
            }
            else {
                obj = {
                    'duration': obj
                };
            }
        }
        else if (is_string(obj)) {
            obj = {
                'easing': obj
            };
        }
        else if (!is_object(obj)) {
            obj = {};
        }
        return obj;
    }
    function go_getNaviObject($tt, obj) {
        obj = go_getObject($tt, obj);
        if (is_string(obj)) {
            var temp = cf_getKeyCode(obj);
            if (temp == -1) {
                obj = $(obj);
            }
            else {
                obj = temp;
            }
        }
        return obj;
    }

    function go_getAutoObject($tt, obj) {
        obj = go_getNaviObject($tt, obj);
        if (is_jquery(obj)) {
            obj = {
                'button': obj
            };
        }
        else if (is_boolean(obj)) {
            obj = {
                'play': obj
            };
        }
        else if (is_number(obj)) {
            obj = {
                'timeoutDuration': obj
            };
        }
        if (obj.progress) {
            if (is_string(obj.progress) || is_jquery(obj.progress)) {
                obj.progress = {
                    'bar': obj.progress
                };
            }
        }
        return obj;
    }
    function go_complementAutoObject($tt, obj) {
        if (is_function(obj.button)) {
            obj.button = obj.button.call($tt);
        }
        if (is_string(obj.button)) {
            obj.button = $(obj.button);
        }
        if (!is_boolean(obj.play)) {
            obj.play = true;
        }
        if (!is_number(obj.delay)) {
            obj.delay = 0;
        }
        if (is_undefined(obj.pauseOnEvent)) {
            obj.pauseOnEvent = true;
        }
        if (!is_boolean(obj.pauseOnResize)) {
            obj.pauseOnResize = true;
        }
        if (!is_number(obj.timeoutDuration)) {
            obj.timeoutDuration = (obj.duration < 10)
                ? 2500
                : obj.duration * 5;
        }
        if (obj.progress) {
            if (is_function(obj.progress.bar)) {
                obj.progress.bar = obj.progress.bar.call($tt);
            }
            if (is_string(obj.progress.bar)) {
                obj.progress.bar = $(obj.progress.bar);
            }
            if (obj.progress.bar) {
                if (!is_function(obj.progress.updater)) {
                    obj.progress.updater = $.fn.carouFredSel.progressbarUpdater;
                }
                if (!is_number(obj.progress.interval)) {
                    obj.progress.interval = 50;
                }
            }
            else {
                obj.progress = false;
            }
        }
        return obj;
    }

    function go_getPrevNextObject($tt, obj) {
        obj = go_getNaviObject($tt, obj);
        if (is_jquery(obj)) {
            obj = {
                'button': obj
            };
        }
        else if (is_number(obj)) {
            obj = {
                'key': obj
            };
        }
        return obj;
    }
    function go_complementPrevNextObject($tt, obj) {
        if (is_function(obj.button)) {
            obj.button = obj.button.call($tt);
        }
        if (is_string(obj.button)) {
            obj.button = $(obj.button);
        }
        if (is_string(obj.key)) {
            obj.key = cf_getKeyCode(obj.key);
        }
        return obj;
    }

    function go_getPaginationObject($tt, obj) {
        obj = go_getNaviObject($tt, obj);
        if (is_jquery(obj)) {
            obj = {
                'container': obj
            };
        }
        else if (is_boolean(obj)) {
            obj = {
                'keys': obj
            };
        }
        return obj;
    }
    function go_complementPaginationObject($tt, obj) {
        if (is_function(obj.container)) {
            obj.container = obj.container.call($tt);
        }
        if (is_string(obj.container)) {
            obj.container = $(obj.container);
        }
        if (!is_number(obj.items)) {
            obj.items = false;
        }
        if (!is_boolean(obj.keys)) {
            obj.keys = false;
        }
        if (!is_function(obj.anchorBuilder) && !is_false(obj.anchorBuilder)) {
            obj.anchorBuilder = $.fn.carouFredSel.pageAnchorBuilder;
        }
        if (!is_number(obj.deviation)) {
            obj.deviation = 0;
        }
        return obj;
    }

    function go_getSwipeObject($tt, obj) {
        if (is_function(obj)) {
            obj = obj.call($tt);
        }
        if (is_undefined(obj)) {
            obj = {
                'onTouch': false
            };
        }
        if (is_true(obj)) {
            obj = {
                'onTouch': obj
            };
        }
        else if (is_number(obj)) {
            obj = {
                'items': obj
            };
        }
        return obj;
    }
    function go_complementSwipeObject($tt, obj) {
        if (!is_boolean(obj.onTouch)) {
            obj.onTouch = true;
        }
        if (!is_boolean(obj.onMouse)) {
            obj.onMouse = false;
        }
        if (!is_object(obj.options)) {
            obj.options = {};
        }
        if (!is_boolean(obj.options.triggerOnTouchEnd)) {
            obj.options.triggerOnTouchEnd = false;
        }
        return obj;
    }
    function go_getMousewheelObject($tt, obj) {
        if (is_function(obj)) {
            obj = obj.call($tt);
        }
        if (is_true(obj)) {
            obj = {};
        }
        else if (is_number(obj)) {
            obj = {
                'items': obj
            };
        }
        else if (is_undefined(obj)) {
            obj = false;
        }
        return obj;
    }
    function go_complementMousewheelObject($tt, obj) {
        return obj;
    }

    //	get number functions
    function gn_getItemIndex(num, dev, org, items, $cfs) {
        if (is_string(num)) {
            num = $(num, $cfs);
        }

        if (is_object(num)) {
            num = $(num, $cfs);
        }
        if (is_jquery(num)) {
            num = $cfs.children().index(num);
            if (!is_boolean(org)) {
                org = false;
            }
        }
        else {
            if (!is_boolean(org)) {
                org = true;
            }
        }
        if (!is_number(num)) {
            num = 0;
        }
        if (!is_number(dev)) {
            dev = 0;
        }

        if (org) {
            num += items.first;
        }
        num += dev;
        if (items.total > 0) {
            while (num >= items.total) {
                num -= items.total;
            }
            while (num < 0) {
                num += items.total;
            }
        }
        return num;
    }

    //	items prev
    function gn_getVisibleItemsPrev(i, o, s) {
        var t = 0,
            x = 0;

        for (var a = s; a >= 0; a--) {
            var j = i.eq(a);
            t += (j.is(':visible')) ? j[o.d['outerWidth']](true) : 0;
            if (t > o.maxDimension) {
                return x;
            }
            if (a == 0) {
                a = i.length;
            }
            x++;
        }
    }
    function gn_getVisibleItemsPrevFilter(i, o, s) {
        return gn_getItemsPrevFilter(i, o.items.filter, o.items.visibleConf.org, s);
    }
    function gn_getScrollItemsPrevFilter(i, o, s, m) {
        return gn_getItemsPrevFilter(i, o.items.filter, m, s);
    }
    function gn_getItemsPrevFilter(i, f, m, s) {
        var t = 0,
            x = 0;

        for (var a = s, l = i.length; a >= 0; a--) {
            x++;
            if (x == l) {
                return x;
            }

            var j = i.eq(a);
            if (j.is(f)) {
                t++;
                if (t == m) {
                    return x;
                }
            }
            if (a == 0) {
                a = l;
            }
        }
    }

    function gn_getVisibleOrg($c, o) {
        return o.items.visibleConf.org || $c.children().slice(0, o.items.visible).filter(o.items.filter).length;
    }

    //	items next
    function gn_getVisibleItemsNext(i, o, s) {
        var t = 0,
            x = 0;

        for (var a = s, l = i.length - 1; a <= l; a++) {
            var j = i.eq(a);

            t += (j.is(':visible')) ? j[o.d['outerWidth']](true) : 0;
            if (t > o.maxDimension) {
                return x;
            }

            x++;
            if (x == l + 1) {
                return x;
            }
            if (a == l) {
                a = -1;
            }
        }
    }
    function gn_getVisibleItemsNextTestCircular(i, o, s, l) {
        var v = gn_getVisibleItemsNext(i, o, s);
        if (!o.circular) {
            if (s + v > l) {
                v = l - s;
            }
        }
        return v;
    }
    function gn_getVisibleItemsNextFilter(i, o, s) {
        return gn_getItemsNextFilter(i, o.items.filter, o.items.visibleConf.org, s, o.circular);
    }
    function gn_getScrollItemsNextFilter(i, o, s, m) {
        return gn_getItemsNextFilter(i, o.items.filter, m + 1, s, o.circular) - 1;
    }
    function gn_getItemsNextFilter(i, f, m, s, c) {
        var t = 0,
            x = 0;

        for (var a = s, l = i.length - 1; a <= l; a++) {
            x++;
            if (x >= l) {
                return x;
            }

            var j = i.eq(a);
            if (j.is(f)) {
                t++;
                if (t == m) {
                    return x;
                }
            }
            if (a == l) {
                a = -1;
            }
        }
    }

    //	get items functions
    function gi_getCurrentItems(i, o) {
        return i.slice(0, o.items.visible);
    }
    function gi_getOldItemsPrev(i, o, n) {
        return i.slice(n, o.items.visibleConf.old + n);
    }
    function gi_getNewItemsPrev(i, o) {
        return i.slice(0, o.items.visible);
    }
    function gi_getOldItemsNext(i, o) {
        return i.slice(0, o.items.visibleConf.old);
    }
    function gi_getNewItemsNext(i, o, n) {
        return i.slice(n, o.items.visible + n);
    }

    //	sizes functions
    function sz_storeMargin(i, o, d) {
        if (o.usePadding) {
            if (!is_string(d)) {
                d = '_cfs_origCssMargin';
            }
            i.each(function () {
                var j = $(this),
                    m = parseInt(j.css(o.d['marginRight']), 10);
                if (!is_number(m)) {
                    m = 0;
                }
                j.data(d, m);
            });
        }
    }
    function sz_resetMargin(i, o, m) {
        if (o.usePadding) {
            var x = (is_boolean(m)) ? m : false;
            if (!is_number(m)) {
                m = 0;
            }
            sz_storeMargin(i, o, '_cfs_tempCssMargin');
            i.each(function () {
                var j = $(this);
                j.css(o.d['marginRight'], ((x) ? j.data('_cfs_tempCssMargin') : m + j.data('_cfs_origCssMargin')));
            });
        }
    }
    function sz_storeOrigCss(i) {
        i.each(function () {
            var j = $(this);
            j.data('_cfs_origCss', j.attr('style') || '');
        });
    }
    function sz_restoreOrigCss(i) {
        i.each(function () {
            var j = $(this);
            j.attr('style', j.data('_cfs_origCss') || '');
        });
    }
    function sz_setResponsiveSizes(o, all) {
        var visb = o.items.visible,
            newS = o.items[o.d['width']],
            seco = o[o.d['height']],
            secp = is_percentage(seco);

        all.each(function () {
            var $t = $(this),
                nw = newS - ms_getPaddingBorderMargin($t, o, 'Width');

            $t[o.d['width']](nw);
            if (secp) {
                $t[o.d['height']](ms_getPercentage(nw, seco));
            }
        });
    }
    function sz_setSizes($c, o) {
        var $w = $c.parent(),
            $i = $c.children(),
            $v = gi_getCurrentItems($i, o),
            sz = cf_mapWrapperSizes(ms_getSizes($v, o, true), o, false);

        $w.css(sz);

        if (o.usePadding) {
            var p = o.padding,
                r = p[o.d[1]];

            if (o.align && r < 0) {
                r = 0;
            }
            var $l = $v.last();
            $l.css(o.d['marginRight'], $l.data('_cfs_origCssMargin') + r);
            $c.css(o.d['top'], p[o.d[0]]);
            $c.css(o.d['left'], p[o.d[3]]);
        }

        $c.css(o.d['width'], sz[o.d['width']] + (ms_getTotalSize($i, o, 'width') * 2));
        $c.css(o.d['height'], ms_getLargestSize($i, o, 'height'));
        return sz;
    }

    //	measuring functions
    function ms_getSizes(i, o, wrapper) {
        return [ms_getTotalSize(i, o, 'width', wrapper), ms_getLargestSize(i, o, 'height', wrapper)];
    }
    function ms_getLargestSize(i, o, dim, wrapper) {
        if (!is_boolean(wrapper)) {
            wrapper = false;
        }
        if (is_number(o[o.d[dim]]) && wrapper) {
            return o[o.d[dim]];
        }
        if (is_number(o.items[o.d[dim]])) {
            return o.items[o.d[dim]];
        }
        dim = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight';
        return ms_getTrueLargestSize(i, o, dim);
    }
    function ms_getTrueLargestSize(i, o, dim) {
        var s = 0;

        for (var a = 0, l = i.length; a < l; a++) {
            var j = i.eq(a);

            var m = (j.is(':visible')) ? j[o.d[dim]](true) : 0;
            if (s < m) {
                s = m;
            }
        }
        return s;
    }

    function ms_getTotalSize(i, o, dim, wrapper) {
        if (!is_boolean(wrapper)) {
            wrapper = false;
        }
        if (is_number(o[o.d[dim]]) && wrapper) {
            return o[o.d[dim]];
        }
        if (is_number(o.items[o.d[dim]])) {
            return o.items[o.d[dim]] * i.length;
        }

        var d = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight',
            s = 0;

        for (var a = 0, l = i.length; a < l; a++) {
            var j = i.eq(a);
            s += (j.is(':visible')) ? j[o.d[d]](true) : 0;
        }
        return s;
    }
    function ms_getParentSize($w, o, d) {
        var isVisible = $w.is(':visible');
        if (isVisible) {
            $w.hide();
        }
        var s = $w.parent()[o.d[d]]();
        if (isVisible) {
            $w.show();
        }
        return s;
    }
    function ms_getMaxDimension(o, a) {
        return (is_number(o[o.d['width']])) ? o[o.d['width']] : a;
    }
    function ms_hasVariableSizes(i, o, dim) {
        var s = false,
            v = false;

        for (var a = 0, l = i.length; a < l; a++) {
            var j = i.eq(a);

            var c = (j.is(':visible')) ? j[o.d[dim]](true) : 0;
            if (s === false) {
                s = c;
            }
            else if (s != c) {
                v = true;
            }
            if (s == 0) {
                v = true;
            }
        }
        return v;
    }
    function ms_getPaddingBorderMargin(i, o, d) {
        return i[o.d['outer' + d]](true) - i[o.d[d.toLowerCase()]]();
    }
    function ms_getPercentage(s, o) {
        if (is_percentage(o)) {
            o = parseInt(o.slice(0, -1), 10);
            if (!is_number(o)) {
                return s;
            }
            s *= o / 100;
        }
        return s;
    }

    //	config functions
    function cf_e(n, c, pf, ns, rd) {
        if (!is_boolean(pf)) {
            pf = true;
        }
        if (!is_boolean(ns)) {
            ns = true;
        }
        if (!is_boolean(rd)) {
            rd = false;
        }

        if (pf) {
            n = c.events.prefix + n;
        }
        if (ns) {
            n = n + '.' + c.events.namespace;
        }
        if (ns && rd) {
            n += c.serialNumber;
        }

        return n;
    }
    function cf_c(n, c) {
        return (is_string(c.classnames[n])) ? c.classnames[n] : n;
    }
    function cf_mapWrapperSizes(ws, o, p) {
        if (!is_boolean(p)) {
            p = true;
        }
        var pad = (o.usePadding && p) ? o.padding : [0, 0, 0, 0];
        var wra = {};

        wra[o.d['width']] = ws[0] + pad[1] + pad[3];
        wra[o.d['height']] = ws[1] + pad[0] + pad[2];

        return wra;
    }
    function cf_sortParams(vals, typs) {
        var arr = [];
        for (var a = 0, l1 = vals.length; a < l1; a++) {
            for (var b = 0, l2 = typs.length; b < l2; b++) {
                if (typs[b].indexOf(typeof vals[a]) > -1 && is_undefined(arr[b])) {
                    arr[b] = vals[a];
                    break;
                }
            }
        }
        return arr;
    }
    function cf_getPadding(p) {
        if (is_undefined(p)) {
            return [0, 0, 0, 0];
        }
        if (is_number(p)) {
            return [p, p, p, p];
        }
        if (is_string(p)) {
            p = p.split('px').join('').split('em').join('').split(' ');
        }

        if (!is_array(p)) {
            return [0, 0, 0, 0];
        }
        for (var i = 0; i < 4; i++) {
            p[i] = parseInt(p[i], 10);
        }
        switch (p.length) {
            case 0:
                return [0, 0, 0, 0];
            case 1:
                return [p[0], p[0], p[0], p[0]];
            case 2:
                return [p[0], p[1], p[0], p[1]];
            case 3:
                return [p[0], p[1], p[2], p[1]];
            default:
                return [p[0], p[1], p[2], p[3]];
        }
    }
    function cf_getAlignPadding(itm, o) {
        var x = (is_number(o[o.d['width']])) ? Math.ceil(o[o.d['width']] - ms_getTotalSize(itm, o, 'width')) : 0;
        switch (o.align) {
            case 'left':
                return [0, x];
            case 'right':
                return [x, 0];
            case 'center':
            default:
                return [Math.ceil(x / 2), Math.floor(x / 2)];
        }
    }
    function cf_getDimensions(o) {
        var dm = [
            ['width', 'innerWidth', 'outerWidth', 'height', 'innerHeight', 'outerHeight', 'left', 'top', 'marginRight', 0, 1, 2, 3],
            ['height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'top', 'left', 'marginBottom', 3, 2, 1, 0]
        ];

        var dl = dm[0].length,
            dx = (o.direction == 'right' || o.direction == 'left') ? 0 : 1;

        var dimensions = {};
        for (var d = 0; d < dl; d++) {
            dimensions[dm[0][d]] = dm[dx][d];
        }
        return dimensions;
    }
    function cf_getAdjust(x, o, a, $t) {
        var v = x;
        if (is_function(a)) {
            v = a.call($t, v);

        }
        else if (is_string(a)) {
            var p = a.split('+'),
                m = a.split('-');

            if (m.length > p.length) {
                var neg = true,
                    sta = m[0],
                    adj = m[1];
            }
            else {
                var neg = false,
                    sta = p[0],
                    adj = p[1];
            }

            switch (sta) {
                case 'even':
                    v = (x % 2 == 1) ? x - 1 : x;
                    break;
                case 'odd':
                    v = (x % 2 == 0) ? x - 1 : x;
                    break;
                default:
                    v = x;
                    break;
            }
            adj = parseInt(adj, 10);
            if (is_number(adj)) {
                if (neg) {
                    adj = -adj;
                }
                v += adj;
            }
        }
        if (!is_number(v) || v < 1) {
            v = 1;
        }
        return v;
    }
    function cf_getItemsAdjust(x, o, a, $t) {
        return cf_getItemAdjustMinMax(cf_getAdjust(x, o, a, $t), o.items.visibleConf);
    }
    function cf_getItemAdjustMinMax(v, i) {
        if (is_number(i.min) && v < i.min) {
            v = i.min;
        }
        if (is_number(i.max) && v > i.max) {
            v = i.max;
        }
        if (v < 1) {
            v = 1;
        }
        return v;
    }
    function cf_getSynchArr(s) {
        if (!is_array(s)) {
            s = [[s]];
        }
        if (!is_array(s[0])) {
            s = [s];
        }
        for (var j = 0, l = s.length; j < l; j++) {
            if (is_string(s[j][0])) {
                s[j][0] = $(s[j][0]);
            }
            if (!is_boolean(s[j][1])) {
                s[j][1] = true;
            }
            if (!is_boolean(s[j][2])) {
                s[j][2] = true;
            }
            if (!is_number(s[j][3])) {
                s[j][3] = 0;
            }
        }
        return s;
    }
    function cf_getKeyCode(k) {
        if (k == 'right') {
            return 39;
        }
        if (k == 'left') {
            return 37;
        }
        if (k == 'up') {
            return 38;
        }
        if (k == 'down') {
            return 40;
        }
        return -1;
    }
    function cf_setCookie(n, $c, c) {
        if (n) {
            var v = $c.triggerHandler(cf_e('currentPosition', c));
            $.fn.carouFredSel.cookie.set(n, v);
        }
    }
    function cf_getCookie(n) {
        var c = $.fn.carouFredSel.cookie.get(n);
        return (c == '') ? 0 : c;
    }

    //	init function
    function in_mapCss($elem, props) {
        var css = {};
        for (var p = 0, l = props.length; p < l; p++) {
            css[props[p]] = $elem.css(props[p]);
        }
        return css;
    }
    function in_complementItems(obj, opt, itm, sta) {
        if (!is_object(obj.visibleConf)) {
            obj.visibleConf = {};
        }
        if (!is_object(obj.sizesConf)) {
            obj.sizesConf = {};
        }

        if (obj.start == 0 && is_number(sta)) {
            obj.start = sta;
        }

        //	visible items
        if (is_object(obj.visible)) {
            obj.visibleConf.min = obj.visible.min;
            obj.visibleConf.max = obj.visible.max;
            obj.visible = false;
        }
        else if (is_string(obj.visible)) {
            //	variable visible items
            if (obj.visible == 'variable') {
                obj.visibleConf.variable = true;
            }
            //	adjust string visible items
            else {
                obj.visibleConf.adjust = obj.visible;
            }
            obj.visible = false;
        }
        else if (is_function(obj.visible)) {
            obj.visibleConf.adjust = obj.visible;
            obj.visible = false;
        }

        //	set items filter
        if (!is_string(obj.filter)) {
            obj.filter = (itm.filter(':hidden').length > 0) ? ':visible' : '*';
        }

        //	primary item-size not set
        if (!obj[opt.d['width']]) {
            //	responsive carousel -> set to largest
            if (opt.responsive) {
                debug(true, 'Set a ' + opt.d['width'] + ' for the items!');
                obj[opt.d['width']] = ms_getTrueLargestSize(itm, opt, 'outerWidth');
            }
            //	 non-responsive -> measure it or set to "variable"
            else {
                obj[opt.d['width']] = (ms_hasVariableSizes(itm, opt, 'outerWidth'))
                    ? 'variable'
                    : itm[opt.d['outerWidth']](true);
            }
        }

        //	secondary item-size not set -> measure it or set to "variable"
        if (!obj[opt.d['height']]) {
            obj[opt.d['height']] = (ms_hasVariableSizes(itm, opt, 'outerHeight'))
                ? 'variable'
                : itm[opt.d['outerHeight']](true);
        }

        obj.sizesConf.width = obj.width;
        obj.sizesConf.height = obj.height;
        return obj;
    }
    function in_complementVisibleItems(opt, avl) {
        //	primary item-size variable -> set visible items variable
        if (opt.items[opt.d['width']] == 'variable') {
            opt.items.visibleConf.variable = true;
        }
        if (!opt.items.visibleConf.variable) {
            //	primary size is number -> calculate visible-items
            if (is_number(opt[opt.d['width']])) {
                opt.items.visible = Math.floor(opt[opt.d['width']] / opt.items[opt.d['width']]);
            }
            //	measure and calculate primary size and visible-items
            else {
                opt.items.visible = Math.floor(avl / opt.items[opt.d['width']]);
                opt[opt.d['width']] = opt.items.visible * opt.items[opt.d['width']];
                if (!opt.items.visibleConf.adjust) {
                    opt.align = false;
                }
            }
            if (opt.items.visible == 'Infinity' || opt.items.visible < 1) {
                debug(true, 'Not a valid number of visible items: Set to "variable".');
                opt.items.visibleConf.variable = true;
            }
        }
        return opt;
    }
    function in_complementPrimarySize(obj, opt, all) {
        //	primary size set to auto -> measure largest item-size and set it
        if (obj == 'auto') {
            obj = ms_getTrueLargestSize(all, opt, 'outerWidth');
        }
        return obj;
    }
    function in_complementSecondarySize(obj, opt, all) {
        //	secondary size set to auto -> measure largest item-size and set it
        if (obj == 'auto') {
            obj = ms_getTrueLargestSize(all, opt, 'outerHeight');
        }
        //	secondary size not set -> set to secondary item-size
        if (!obj) {
            obj = opt.items[opt.d['height']];
        }
        return obj;
    }
    function in_getAlignPadding(o, all) {
        var p = cf_getAlignPadding(gi_getCurrentItems(all, o), o);
        o.padding[o.d[1]] = p[1];
        o.padding[o.d[3]] = p[0];
        return o;
    }
    function in_getResponsiveValues(o, all, avl) {

        var visb = cf_getItemAdjustMinMax(Math.ceil(o[o.d['width']] / o.items[o.d['width']]), o.items.visibleConf);
        if (visb > all.length) {
            visb = all.length;
        }

        var newS = Math.floor(o[o.d['width']] / visb);

        o.items.visible = visb;
        o.items[o.d['width']] = newS;
        o[o.d['width']] = visb * newS;
        return o;
    }


    //	buttons functions
    function bt_pauseOnHoverConfig(p) {
        if (is_string(p)) {
            var i = (p.indexOf('immediate') > -1) ? true : false,
                r = (p.indexOf('resume') > -1) ? true : false;
        }
        else {
            var i = r = false;
        }
        return [i, r];
    }
    function bt_mousesheelNumber(mw) {
        return (is_number(mw)) ? mw : null
    }

    //	helper functions
    function is_null(a) {
        return (a === null);
    }
    function is_undefined(a) {
        return (is_null(a) || typeof a == 'undefined' || a === '' || a === 'undefined');
    }
    function is_array(a) {
        return (a instanceof Array);
    }
    function is_jquery(a) {
        return (a instanceof jQuery);
    }
    function is_object(a) {
        return ((a instanceof Object || typeof a == 'object') && !is_null(a) && !is_jquery(a) && !is_array(a) && !is_function(a));
    }
    function is_number(a) {
        return ((a instanceof Number || typeof a == 'number') && !isNaN(a));
    }
    function is_string(a) {
        return ((a instanceof String || typeof a == 'string') && !is_undefined(a) && !is_true(a) && !is_false(a));
    }
    function is_function(a) {
        return (a instanceof Function || typeof a == 'function');
    }
    function is_boolean(a) {
        return (a instanceof Boolean || typeof a == 'boolean' || is_true(a) || is_false(a));
    }
    function is_true(a) {
        return (a === true || a === 'true');
    }
    function is_false(a) {
        return (a === false || a === 'false');
    }
    function is_percentage(x) {
        return (is_string(x) && x.slice(-1) == '%');
    }


    function getTime() {
        return new Date().getTime();
    }

    function deprecated(o, n) {
        debug(true, o + ' is DEPRECATED, support for it will be removed. Use ' + n + ' instead.');
    }
    function debug(d, m) {
        if (!is_undefined(window.console) && !is_undefined(window.console.log)) {
            if (is_object(d)) {
                var s = ' (' + d.selector + ')';
                d = d.debug;
            }
            else {
                var s = '';
            }
            if (!d) {
                return false;
            }

            if (is_string(m)) {
                m = 'carouFredSel' + s + ': ' + m;
            }
            else {
                m = ['carouFredSel' + s + ':', m];
            }
            window.console.log(m);
        }
        return false;
    }



    //	EASING FUNCTIONS
    $.extend($.easing, {
        'quadratic': function (t) {
            var t2 = t * t;
            return t * (-t2 * t + 4 * t2 - 6 * t + 4);
        },
        'cubic': function (t) {
            return t * (4 * t * t - 9 * t + 6);
        },
        'elastic': function (t) {
            var t2 = t * t;
            return t * (33 * t2 * t2 - 106 * t2 * t + 126 * t2 - 67 * t + 15);
        }
    });


})(jQuery);
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\convertible-carousel.js
//CONVERTIBLE CAROUSEL
/* version="4" */
ConvertibleCarousel = {
    name: 'ConvertibleCarousel',
    removeHiddenElement: function (hiddenElements) {
        if ($(".onboarding").length < 1) {
            $(hiddenElements).detach();
        }
    },
    convert: function (convCarousel) {
        var source = $(convCarousel);
        var target = $('#' + source.attr('data-carousel-target'));
        var hiddenElements = [];

        $(target).parent().children().each(function () {
            if ($(this).hasClass("hidden")) {
                hiddenElements.push(this);
            }
        });

        $("#carouselDataSource > li").each( function () {
            if ($(this).hasClass("hidden")) {
                hiddenElements.push(this);
            }
        });

        if (isDesktop() && !target.hasClass('convCarousel-desktop')) {
            var mode = 'desktop';
            var c = ConvertibleCarousel;

            c.clearTarget(target);

            var content = '';
            if (source.hasClass('carousel-desktop')) {
                content = c.createCarousel(source, mode);
            } else if (source.hasClass('masonry-desktop')) {
                content = c.createMasonry(source);
            } else if (source.hasClass('grid-desktop')) {
                content = c.createGrid(source, mode);
            } else if (source.hasClass('tabgrid-desktop')) {
                content = c.createTabbedGrid(source, mode);
            }

            //add content to target
            target.html(content);
            target.addClass('convCarousel-container');
            target.addClass('convCarousel-' + mode);

            if (source.hasClass('carousel-desktop')) {
                addSwipeToCarousels(target.find('.carousel-inner'));
                c.addEvents(target);
            } else if (source.hasClass('masonry-desktop')) {
                var packeryContainerId = source.attr('data-carousel-id');
                new Packery(document.querySelector('#' + packeryContainerId));
            }

            ConvertibleCarousel.removeHiddenElement(hiddenElements);
        } else if (isTablet() && !target.hasClass('convCarousel-tablet')) {
            var mode = 'tablet';
            var c = ConvertibleCarousel;

            c.clearTarget(target);
            var content = '';
            if (source.hasClass('carousel-tablet')) {
                content = c.createCarousel(source, mode);
            } else if (source.hasClass('masonry-tablet')) {
                content = c.createMasonry(source);
            } else if (source.hasClass('grid-tablet')) {
                content = c.createGrid(source, mode);
            } else if (source.hasClass('tabgrid-tablet')) {
                content = c.createTabbedGrid(source, mode);
            }

            //add content to target
            target.html(content);
            target.addClass('convCarousel-container');
            target.addClass('convCarousel-' + mode);

            if (source.hasClass('carousel-tablet')) {
                addSwipeToCarousels(target.find('.carousel-inner'));
                c.addEvents(target);
            } else if (source.hasClass('masonry-tablet')) {
                var packeryContainerId = source.attr('data-carousel-id');
                new Packery(document.querySelector('#' + packeryContainerId));
            }
            ConvertibleCarousel.removeHiddenElement(hiddenElements);
        } else if (isMobile() && !target.hasClass('convCarousel-mobile')) {
            var mode = 'mobile';
            var c = ConvertibleCarousel;

            c.clearTarget(target);

            var content = '';
            if (source.hasClass('carousel-mobile')) {
                content = c.createCarousel(source, mode);
            } else if (source.hasClass('list-mobile')) {
                content = c.createList(source, mode);
            } else if (source.hasClass('tabcarousel-mobile')) {
                content = c.createTabbedCarousel(source, mode);
            }

            //add content to target
            target.html(content);
            target.addClass('convCarousel-container');
            target.addClass('convCarousel-' + mode);

            if (source.hasClass('carousel-mobile')) {
                addSwipeToCarousels(target.find('.carousel-inner'));
                c.addEvents(target);
            } else if (source.hasClass('tabcarousel-mobile')) {
                //add event handler
                addSwipeToCarousels(target.find('.carousel-inner'));
                c.addEvents(target);
            }
            ConvertibleCarousel.removeHiddenElement(hiddenElements);

            if (ComponentRegistry.FeaturedSection) {
                if (target.hasClass('indicators-left')) {
                    target.removeClass('indicators-left');
                }
                else if (target.hasClass('indicators-center')) {
                    target.removeClass('indicators-center');
                }
                else if (target.hasClass('indicators-right')) {
                    target.removeClass('indicators-right');
                }
            }
        }
    },
    clearTarget: function (target) {
        target.html('');
        target.removeClass('convCarousel-desktop');
        target.removeClass('convCarousel-tablet');
        target.removeClass('convCarousel-mobile');
    },
    createList: function (dataSource, mode) {
        var listTemplate = '<ul id="{ID}" class="conv-carousel-list">{CONTENT}</ul>';
        var listItemTemplate = '<li><span>{CONTENT}</span></li>';
        var $ds = $(dataSource);

        var items = $ds.find('li');
        var listlId = $ds.attr('data-carousel-id');
        var itemsPerList = $ds.attr('data-carousel-' + mode + '-itemcount') == null ||
            $ds.attr('data-carousel-' + mode + '-itemcount') == '' ?
            0 : parseInt($ds.attr('data-carousel-' + mode + '-itemcount'));

        var tempItems = "";
        for (var ctr = 0; ctr < itemsPerList && ctr < items.length; ctr++) {
            tempItems += listItemTemplate.replace('{CONTENT}', items.eq(ctr).html());
        }

        return listTemplate.replace('{ID}', listlId).replace('{CONTENT}', tempItems);
    },
    createCarousel: function (dataSource, mode) {
        //carousel template
        var $ds = $(dataSource);
        var carouselTemplate = '<div id="{ID}" class="carousel slide conv-carousel" data-ride="carousel" {SLIDESHOW}>';
        carouselTemplate += '<div class="carousel-inner">{ITEMS}</div>';
        carouselTemplate += '<div><ol class="carousel-indicators">{INDICATORS}</ol></div>';
        carouselTemplate += '<div class="view-all">{LINK}</div>';
        carouselTemplate += '</div>';

        var carouselItemTemplate = '<div class="item {ACTIVE}">{CONTENT}</div>';
        var carouselItemTemplateSlicer1 = '<div><div class="col-sm-12">{CONTENT1}</div></div>';
        var carouselItemTemplateSlicer2;
        if ($(".onboarding").length > 0 && $(".onboarding #carouselDataSource li").length < 2) {

            carouselItemTemplateSlicer2 = '<div><div class="col-sm-6  col-sm-offset-3">{CONTENT1}</div></div>';
        }
        else {
            carouselItemTemplateSlicer2 = '<div><div class="col-sm-6">{CONTENT1}</div><div class="col-sm-6">{CONTENT2}</div></div>';
        }
        var carouselItemTemplateSlicer3 = '<div><div class="col-sm-4">{CONTENT1}</div><div class="col-sm-4">{CONTENT2}</div><div class="col-sm-4">{CONTENT3}</div></div>';
        var carouselItemTemplateSlicer4 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div><div class="col-sm-2">{CONTENT8}</div><div class="col-sm-2">{CONTENT9}</div><div class="col-sm-2">{CONTENT10}</div><div class="col-sm-2">{CONTENT11}</div><div class="col-sm-2">{CONTENT12}</div></div>';

        //BUG#353994
        var carouselItemTemplateSlicer5 = '<div><div class="col-sm-3">{CONTENT1}</div><div class="col-sm-3">{CONTENT2}</div><div class="col-sm-3">{CONTENT3}</div><div class="col-sm-3">{CONTENT4}</div></div>';
        var carouselItemTemplateSlicer6 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div></div>';
        var carouselItemTemplateSlicer7 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div></div>';
        var carouselItemTemplateSlicer8 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div></div>';
        var carouselItemTemplateSlicer9 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div><div class="col-sm-2">{CONTENT8}</div></div>';
        var carouselItemTemplateSlicer10 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div><div class="col-sm-2">{CONTENT8}</div><div class="col-sm-2">{CONTENT9}</div></div>';
        var carouselItemTemplateSlicer11 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div><div class="col-sm-2">{CONTENT8}</div><div class="col-sm-2">{CONTENT9}</div><div class="col-sm-2">{CONTENT10}</div></div>';
        var carouselItemTemplateSlicer12 = '<div><div class="col-sm-2">{CONTENT1}</div><div class="col-sm-2">{CONTENT2}</div><div class="col-sm-2">{CONTENT3}</div><div class="col-sm-2">{CONTENT4}</div><div class="col-sm-2">{CONTENT5}</div><div class="col-sm-2">{CONTENT6}</div><div class="col-sm-2">{CONTENT7}</div><div class="col-sm-2">{CONTENT8}</div><div class="col-sm-2">{CONTENT9}</div><div class="col-sm-2">{CONTENT10}</div><div class="col-sm-2">{CONTENT11}</div></div>';

        var carouselIndicatorTemplate = '<li data-target="{TARGETID}" data-slide-to="{SLIDENUM}" class="{ACTIVE}"></li>';

        var playPauseButton = '<li data-target="#{ID}" class="play-pause-button"><span class="acn-icon icon-pause" data-play-pause-status="pause"></span></li>';

        var carouselId = $ds.attr('data-carousel-id');

        var itemsPerSlide = $ds.attr('data-carousel-' + mode + '-itemcount') == null ||
            $ds.attr('data-carousel-' + mode + '-itemcount') == '' ?
            0 : parseInt($ds.attr('data-carousel-' + mode + '-itemcount'));
        var items = $ds.find('li');

        //create temp content
        var content = carouselTemplate;
        content = content.replace('{ID}', carouselId);

        //interval
        var interval = $ds.attr('data-slideshow-interval');
        var showSlideshowInterval = interval != null ? interval : "3000";

        var slideshow = $ds.attr('data-slideshow-' + mode);
        var showSlideshow = slideshow != null && slideshow.toLowerCase() == "true" ? 'data-interval="' + showSlideshowInterval + '"' : 'data-interval="false"';
        content = content.replace('{SLIDESHOW}', showSlideshow);

        var contentItems = '';
        var contentIndicators = '';

        for (var ctr = 0; ctr < items.length && ctr < (8 * itemsPerSlide) ; ctr = ctr + itemsPerSlide) {
            //slide
            var tempItem = carouselItemTemplate;

            //content
            var itemContent = '';

            switch (itemsPerSlide) {
                case 1:
                    itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer1) : carouselItemTemplateSlicer1;
                    break;
                case 2:
                    itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer2) : carouselItemTemplateSlicer2;

                    if (isMobile()) {
                        var mobileItemSize = $ds.attr('data-carousel-mobile-item-size');

                        if (mobileItemSize) {
                            itemContent = replaceAll('6', mobileItemSize, itemContent);
                        }
                    }

                    break;
                case 3:
                    itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer3) : carouselItemTemplateSlicer3;

                    if (isMobile()) {
                        var mobileItemSize = $ds.attr('data-carousel-mobile-item-size');

                        if (mobileItemSize) {
                            itemContent = replaceAll('4', mobileItemSize, itemContent);
                        }
                    }

                    break;
                //BUG#353994
                case 4:
                    itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer5) : carouselItemTemplateSlicer5;

                    if (isMobile()) {
                        var mobileItemSize = $ds.attr('data-carousel-mobile-item-size');

                        if (mobileItemSize) {
                            itemContent = replaceAll('xs-3', 'xs-' + mobileItemSize, itemContent);
                        }
                    }
                    break;
                case 5:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer6, $ds);
                    break;
                case 6:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer7, $ds);
                    break;
                case 7:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer8, $ds);
                    break;
                case 8:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer9, $ds);
                    break;
                case 9:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer10, $ds);
                    break;
                case 10:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer11, $ds);
                    break;
                case 11:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer12, $ds);
                    break;
                case 12:
                    itemContent = CreateItemContent(carouselItemTemplateSlicer4, $ds);
                    break;
                //case 12:
                //    itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer4) : carouselItemTemplateSlicer4;
                //    break;
            }

            for (var ctr2 = 0; ctr2 < itemsPerSlide; ctr2++) {
                var contentItem = '';
                if ((ctr2 + ctr) < (items.length)) {
                    contentItem = items.eq(ctr2 + ctr).html();
                }

                itemContent = itemContent.replace('{CONTENT' + (ctr2 + 1) + '}', contentItem);
            }

            tempItem = tempItem.replace('{CONTENT}', itemContent);
            tempItem = tempItem.replace('{ACTIVE}', ctr <= 0 ? 'active' : '');

            //indicator
            var showPagination = $ds.attr('data-pagination-show');

            var tempIndicator = showPagination == null || showPagination.toLowerCase() == "true" ? carouselIndicatorTemplate : '';
            tempIndicator = tempIndicator.replace('{TARGETID}', '#' + carouselId);
            tempIndicator = tempIndicator.replace('{SLIDENUM}', ctr / itemsPerSlide);
            tempIndicator = tempIndicator.replace('{ACTIVE}', ctr <= 0 ? 'active' : '');

            //close slide item
            contentItems += tempItem;
            contentIndicators += tempIndicator;
        }

        //add items
        content = content.replace('{ITEMS}', contentItems);

        //add content indicators
        var showPlayPauseButton = $ds.attr('data-slideshow-button');
        if (showPlayPauseButton != null && showPlayPauseButton.toLowerCase() == "true" && contentIndicators.length > 0) {
            contentIndicators += playPauseButton.replace('{ID}', carouselId);
        }

        content = content.replace('{INDICATORS}', items.length <= itemsPerSlide ? '' : contentIndicators);

        var viewAll = $ds.closest('li').data('tab-view-all');

        if (typeof viewAll !== 'undefined') {
            var x = $('#' + viewAll).html();
            content = content.replace('{LINK}', (typeof x !== 'undefined' ? x : ''));
        }

        return content;
    },
    createTabbedCarousel: function (dataSource, mode) {
        //mobile only
        var $ds = $(dataSource);
        var $dsTabs = $ds.find('> li');

        var templateContainer = '<div id="{ID}" class="tab-carousel">{SECTIONS}</div>';

        var templateTabSectionTabsSection = '<div class="tabs">{TABS}</div>';
        var templateTabSectionTabs = '';
        var templateTabSectionTab = '<a href="#" class="tab {ISACTIVE}">{TITLE}</a>';

        var templateTabSections = '';
        var templateTabSection = '<section>{CONTENT}</section>';

        for (var ctr = 0; ctr < $dsTabs.length; ctr++) {
            //for each tab
            $tab = $dsTabs.eq(ctr);
            $tabDs = $tab.find('ul');

            var tabId = $tabDs.attr('data-carousel-id');

            //create header
            var tab = $(templateTabSectionTab).attr('href', '#' + tabId).wrap('<p/>').parent().html();
            templateTabSectionTabs += templateTabSectionTabs.length > 0 ? '<span> | </span>' : '';
            templateTabSectionTabs += tab.replace('{TITLE}', $tab.attr('data-tab-header-mobile')).replace('{ISACTIVE}', ctr == 0 ? 'active' : '');

            //create carousel
            var carousel = ConvertibleCarousel.createCarousel($tabDs, mode);

            carousel = ctr > 0 ? $(carousel).hide().wrap('<p/>').parent().html() : carousel;
            carousel = $(carousel).attr('id', tabId).wrap('<p/>').parent().html();

            templateTabSections += templateTabSection.replace('{CONTENT}', carousel);
        }

        return templateContainer.replace('{SECTIONS}', templateTabSectionTabsSection.replace('{TABS}', templateTabSectionTabs) + templateTabSections).replace('{ID}', $ds.attr('data-carousel-id'));
    },
    createMasonry: function (dataSource) {
        var $ds = $(dataSource);
        var templateContainer = '<section id="{ID}" class="container-block isotope-container">{ITEMS}</section>';
        var templateItem = '<div class="col-sm-{WIDTH} component">{CONTENT}</div>';

        var itemsDs = $ds.find('li');

        var items = '';
        for (var ctr = 0; ctr < itemsDs.length; ctr++) {
            items += templateItem.replace('{CONTENT}', itemsDs.eq(ctr).html()).replace('{WIDTH}', itemsDs.eq(ctr).attr('data-masonry-width'));
        }

        return templateContainer.replace('{ITEMS}', items).replace('{ID}', $ds.attr('data-carousel-id'));
    },
    createGrid: function (dataSource, mode) {
        var $ds = $(dataSource);
        var templateContainer = '<div id="{ID}" class="grid">{ITEMS}</section>';
        var templateItem = '<div class="col-sm-{WIDTH} item">{CONTENT}</div>';

        var itemsPerRow = $ds.attr('data-grid-' + mode + '-itemcount');
        var itemSize = 12 / itemsPerRow;

        var itemsDs = $ds.find('li');

        var items = '';
        for (var ctr = 0; ctr < itemsDs.length; ctr++) {
            items += templateItem.replace('{CONTENT}', itemsDs.eq(ctr).html()).replace('{WIDTH}', itemSize);
        }

        return templateContainer.replace('{ITEMS}', items).replace('{ID}', $ds.attr('data-carousel-id'));
    },

    // SIR #433133 - add classes for packery
    createTabbedGrid: function (dataSource, mode) {
        var $ds = $(dataSource);
        var $dsTabs = $ds.find('> li');

        var bgColor = $dsTabs.data('bg-color');

        var templateContainer = '<div id="{ID}" class="tabgrid">{SECTIONS}</div>';
        var templateTabSection = '<section class="packery-container">{HEADER}{ITEMS}</section>';
        var templateTabSectionHeader = '<div class="header ' + bgColor + '"><h2 class="content-title">{TITLE}</h2></div>';
        var templateTabSectionItem = '<div class="col-sm-{WIDTH} packery-item">{CONTENT}</div>';
        var templateTabSectionViewAll = '<div class="view-all">{LINK}</div>';

        var itemsPerRow = $ds.attr('data-grid-' + mode + '-itemcount');
        var itemSize = 12 / itemsPerRow;

        var sections = '';
        for (var ctr = 0; ctr < $dsTabs.length; ctr++) {
            //for each tab
            $tab = $dsTabs.eq(ctr);
            $tabItems = $tab.find('li');

            var lineBreak = $tab.data('show-line');

            if (lineBreak.toLowerCase() != 'true') {
                templateTabSectionHeader = '<div class="header ' + bgColor + '"><h2 class="content-title">{TITLE}</h2></div>';
            }
            else {
                templateTabSectionHeader = '<div class="hline header ' + bgColor + '"><h2 class="content-title">{TITLE}</h2></div>';
            }

            var newTabSectionHeader = templateTabSectionHeader.replace('{TITLE}', $tab.attr('data-tab-header'));

            var newTabSectionItems = '';
            for (var ctr2 = 0; ctr2 < $tabItems.length; ctr2++) {
                newTabSectionItems += templateTabSectionItem.replace('{CONTENT}', $tabItems.eq(ctr2).html()).replace('{WIDTH}', itemSize);
            }

            var viewAll = $tab.data('tab-view-all');

            sections += templateTabSection.replace('{HEADER}', newTabSectionHeader).replace('{ITEMS}', newTabSectionItems);
            //sections += templateTabSectionViewAll.replace('{LINK}', $('#' + viewAll).html());

            //Start Bug #415114: Webpart - Business Services Module: 'Undefined' text is displayed in VIEW ALL link section.
            if (typeof viewAll !== 'undefined') {
                var x = $('#' + viewAll).html();
                sections += templateTabSectionViewAll.replace('{LINK}', (typeof x !== 'undefined' ? x : ''));
            }
            //End Bug #415114
        }

        return templateContainer.replace('{SECTIONS}', sections).replace('{ID}', $ds.attr('data-carousel-id'));
    },
    addEvents: function (target) {
        //PlayPauseButton
        $(target).find('.convCarousel-container .play-pause-button').on('click', function (event) {
            var playPauseStatusSpan = $(this).children(".acn-icon");
            var playPauseStatus = $(playPauseStatusSpan).data("play-pause-status");

            $(this).closest(".carousel").carousel(playPauseStatus);
            if (playPauseStatus == 'pause') {
                $(playPauseStatusSpan).data("play-pause-status", "cycle").removeClass("icon-pause").addClass("icon-play");
            } else {
                $(playPauseStatusSpan).data("play-pause-status", "pause").removeClass("icon-play").addClass("icon-pause");
            }
        });

        //tabs
        $(target).find('.tab-carousel .tabs .tab').on('click', function (event) {
            event.preventDefault();
            var tab = $(this).attr('href');
            var $tabCarousel = $(this).closest('.tab-carousel');

            $tabCarousel.find('.conv-carousel').hide();
            $tabCarousel.find(tab).show();

            //change active
            $tabCarousel.find('.tab').removeClass('active');
            $(this).addClass('active');
        });
    }
};
//BUG#353994
function CreateItemContent(carouselItemTemplateSlicer, $ds) {
    var itemContent = isMobile() ? replaceAll('sm', 'xs', carouselItemTemplateSlicer) : carouselItemTemplateSlicer;

    if (isMobile()) {
        var mobileItemSize = $ds.attr('data-carousel-mobile-item-size');

        if (mobileItemSize) {
            itemContent = replaceAll('xs-2', 'xs-' + mobileItemSize, itemContent);
        }
    }

    return itemContent;
}

$(function () {
    $('.convCarousel').each(function () { ConvertibleCarousel.convert(this); });

    var carouselCache = sessionStorage.getItem("carouselCache");
    var paginationList = $('#carousel-business-service-module .carousel-indicators li');
    var tabList = $('#carousel-business-service-module .tabs a');

    if (carouselCache != null) {
        var carouselPaginationJson = JSON.parse(carouselCache);

        $(paginationList).each(function () {
            if ($(this).data('slide-to') != null) {
                if ($(this).data('slide-to') == carouselPaginationJson.slideTo) {
                    $(this).trigger('click');
                }
            }
        });
        $(tabList).each(function () {
            if ($(this).attr('href') == carouselPaginationJson.tab) {
                $(this).trigger('click');
            }
        });
    }

    $('#carousel-business-service-module .carousel-indicators li').on("click", function () {
        var list = {
            slideTo: $(this).data('slide-to'),
            tab: $(this).data('target'),
        }
        sessionStorage.setItem("carouselCache", JSON.stringify(list));
    });
    $('#carousel-business-service-module .tabs a').on("click", function () {
        var list = {
            tab: $(this).attr('href'),
        }
        sessionStorage.setItem("carouselCache", JSON.stringify(list));
    });
});

$(window).on("resize", function () {
    $('.convCarousel').each(function () { ConvertibleCarousel.convert(this); });
});

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\jquery.placeholder.js
/* Version ="2 */

/*! http://mths.be/placeholder v2.0.8 by @mathias */
;(function(window, document, $) {

	// Opera Mini v7 doesn’t support placeholder although its DOM seems to indicate so
	var isOperaMini = Object.prototype.toString.call(window.operamini) == '[object OperaMini]';
	var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
	var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
	var prototype = $.fn;
	var valHooks = $.valHooks;
	var propHooks = $.propHooks;
	var hooks;
	var placeholder;

	if (isInputSupported && isTextareaSupported) {

		placeholder = prototype.placeholder = function() {
			return this;
		};

		placeholder.input = placeholder.textarea = true;

	} else {

		placeholder = prototype.placeholder = function() {
			var $this = this;
			$this
				.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
				.not('.placeholder')
				.on({
					'focus.placeholder': clearPlaceholder,
					'blur.placeholder': setPlaceholder
				})
				.data('placeholder-enabled', true)
				.trigger('blur.placeholder');
			return $this;
		};

		placeholder.input = isInputSupported;
		placeholder.textarea = isTextareaSupported;

		hooks = {
			'get': function(element) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value;
				}

				return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
			},
			'set': function(element, value) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value = value;
				}

				if (!$element.data('placeholder-enabled')) {
					return element.value = value;
				}
				if (value == '') {
					element.value = value;
					// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
					if (element != safeActiveElement()) {
						// We can't use `triggerHandler` here because of dummy text/password inputs :(
						setPlaceholder.call(element);
					}
				} else if ($element.hasClass('placeholder')) {
					clearPlaceholder.call(element, true, value) || (element.value = value);
				} else {
					element.value = value;
				}
				// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
				return $element;
			}
		};

		if (!isInputSupported) {
			valHooks.input = hooks;
			propHooks.value = hooks;
		}
		if (!isTextareaSupported) {
			valHooks.textarea = hooks;
			propHooks.value = hooks;
		}

		$(function() {
			// Look for forms
			$(document).on('form', 'submit.placeholder', function() {
				// Clear the placeholder values so they don't get submitted
				var $inputs = $('.placeholder', this).each(clearPlaceholder);
				setTimeout(function() {
					$inputs.each(setPlaceholder);
				}, 10);
			});
		});

		// Clear placeholder values upon page reload
		$(window).on('beforeunload.placeholder', function() {
			$('.placeholder').each(function() {
				this.value = '';
			});
		});

	}

	function args(elem) {
		// Return an object of element attributes
		var newAttrs = {};
		var rinlinejQuery = /^jQuery\d+$/;
		$.each(elem.attributes, function(i, attr) {
			if (attr.specified && !rinlinejQuery.test(attr.name)) {
				newAttrs[attr.name] = attr.value;
			}
		});
		return newAttrs;
	}

	function clearPlaceholder(event, value) {
		var input = this;
		var $input = $(input);
		if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
			if ($input.data('placeholder-password')) {
				$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
				// If `clearPlaceholder` was called from `$.valHooks.input.set`
				if (event === true) {
					return $input[0].value = value;
				}
				$input.trigger("focus");
			} else {
				input.value = '';
				$input.removeClass('placeholder');
				input == safeActiveElement() && input.trigger("select");
			}
		}
	}

	function setPlaceholder() {
		var $replacement;
		var input = this;
		var $input = $(input);
		var id = this.id;
		if (input.value == '') {
			if (input.type == 'password') {
				if (!$input.data('placeholder-textinput')) {
					try {
						$replacement = $input.clone().attr({ 'type': 'text' });
					} catch(e) {
						$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
					}
					$replacement
						.removeAttr('name')
						.data({
							'placeholder-password': $input,
							'placeholder-id': id
						})
						.on('focus.placeholder', clearPlaceholder);
					$input
						.data({
							'placeholder-textinput': $replacement,
							'placeholder-id': id
						})
						.before($replacement);
				}
				$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
				// Note: `$input[0] != input` now!
			}
			$input.addClass('placeholder');
			$input[0].value = $input.attr('placeholder');
		} else {
			$input.removeClass('placeholder');
		}
	}

	function safeActiveElement() {
		// Avoid IE9 `document.activeElement` of death
		// https://github.com/mathiasbynens/jquery-placeholder/pull/99
		try {
			return document.activeElement;
		} catch (exception) {}
	}

}(this, document, jQuery));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\convertible-block-carousel.js
// version="11"
//CONVERTIBLE BLOCK CAROUSEL

BlockCarousel = {
    name: 'BlockCarousel',

    removeHidden: function (convBlockCarousel) {
        var source = convBlockCarousel;
        var blockName = $(source).closest('.ui-container');
        var blockID = blockName.attr('id');
        var hiddenClass = $('#' + blockID + ' .hidden');
        hiddenClass.remove();
    },

    convert: function (convBlockCarousel) {
        var source = convBlockCarousel;
        var target = $('#' + $(source).attr('data-carousel-target'));
        var mode = '';
        var content = '';

        if (isDesktop() && !target.hasClass('convCarousel-desktop')) {
            BlockCarousel.clearTarget(target);

            mode = 'desktop';
            content = BlockCarousel.createCarousel(source, mode, target);

            //add content to target
            target.html(content);
            target.addClass('convCarousel-' + mode);

            addSwipeToCarousels(target.find('.carousel-inner'));
            BlockCarousel.addEvents(target.find('.block-carousel'));

            //generate block carousel background
            BlockCarousel.addProxyCarousel($(source).closest('.ui-container'));
        } else if (isTablet() && !target.hasClass('convCarousel-tablet')) {
            BlockCarousel.clearTarget(target);

            mode = 'tablet';
            content = BlockCarousel.createCarousel(source, mode, target);

            //add content to target
            target.html(content);
            target.addClass('convCarousel-' + mode);

            addSwipeToCarousels(target.find('.carousel-inner'));
            BlockCarousel.addEvents(target.find('.block-carousel'));

            //generate block carousel background
            BlockCarousel.addProxyCarousel($(source).closest('.ui-container'));
        } else if (isMobile() && !target.hasClass('convCarousel-mobile')) {
            BlockCarousel.clearTarget(target);

            mode = 'mobile';

            if ($(source).hasClass('carousel-mobile')) {
                content = BlockCarousel.createCarousel(source, mode, target);
            } else if ($(source).hasClass('list-mobile')) {
                content = BlockCarousel.createList(source, mode, target);
            }

            //add content to target
            target.html(content);
            target.addClass('convCarousel-' + mode);

            addSwipeToCarousels(target.find('.carousel-inner'));
            BlockCarousel.addEvents(target.find('.block-carousel'));

            //generate block carousel background
            BlockCarousel.addProxyCarousel($(source).closest('.ui-container'));
        }

    },
    clearTarget: function (target) {
        target.html('');
        target.removeClass('convCarousel-desktop');
        target.removeClass('convCarousel-tablet');
        target.removeClass('convCarousel-mobile');
    },
    createList: function (carouselDataSource, mode) {
        var listTemplate = '<ul id="{ID}" class="conv-carousel-list">{CONTENT}</ul>';
        var listItemTemplate = '<li><span>{CONTENT}</span></li>';

        //[3/20/15] Merge 2/25 from Main Release Branch
        //var items = $(carouselDataSource).find('li');
        var items = $(carouselDataSource).children('li');
        var listlId = $(carouselDataSource).attr('data-carousel-id');
        var itemsPerList = $(carouselDataSource).attr('data-carousel-' + mode + '-itemcount') == null ||
            $(carouselDataSource).attr('data-carousel-' + mode + '-itemcount') == '' ?
            0 : parseInt($(carouselDataSource).attr('data-carousel-' + mode + '-itemcount'));

        var tempItems = "";
        for (var ctr = 0; ctr < itemsPerList && ctr < items.length; ctr++) {
            tempItems += listItemTemplate.replace('{CONTENT}', items.eq(ctr).html());
        }

        return listTemplate.replace('{ID}', listlId).replace('{CONTENT}', tempItems);
    },
    createCarousel: function (carouselDataSource, mode) {
        //carousel template
        var carouselTemplate = '<div id="{ID}" class="carousel slide conv-carousel block-carousel" data-ride="carousel" {SLIDESHOW}>';
        carouselTemplate += '<div class="carousel-inner">{ITEMS}</div>';
        carouselTemplate += '<div class="{INDICATORS_ALIGNMENT}"><ol class="carousel-indicators">{INDICATORS}</ol></div>';
        carouselTemplate += '</div>';
        var carouselItemTemplate = '<div class="item {ACTIVE}" data-bg-image="{BG-IMG}" data-bg-color="{BG-COL}" data-bg-video="{BG-VID}" data-bg-video-autoplay="{BG-VID-PLAY}">{CONTENT}</div>';

        var carouselItemTemplateSlicer1 = '<div>{CONTENT_OFFSET}<div class="col-sm-{ITEM_SIZE}">{CONTENT1}</div></div>';
        var carouselItemTemplateSlicer2 = '<div>{CONTENT_OFFSET}<div class="col-sm-{ITEM_SIZE}">{CONTENT1}</div><div class="col-sm-{ITEM_SIZE}">{CONTENT2}</div></div>';
        var carouselItemTemplateSlicer3 = '<div>{CONTENT_OFFSET}<div class="col-sm-{ITEM_SIZE}">{CONTENT1}</div><div class="col-sm-{ITEM_SIZE}">{CONTENT2}</div><div class="col-sm-{ITEM_SIZE}">{CONTENT3}</div></div>';

        var carouselIndicatorTemplate = '<li data-target="{TARGETID}" data-slide-to="{SLIDENUM}" class="{ACTIVE}" data-analytics-content-type="nav/paginate" data-analytics-link-name="nav/paginate"></li>';

        var playPauseButton = '<li data-target="#{ID}" class="play-pause-button"><span class="acn-icon icon-pause" data-play-pause-status="pause" data-analytics-content-type="nav/paginate" data-analytics-link-name="icon-pause"></span></li>';

        var carouselId = $(carouselDataSource).attr('data-carousel-id');

        var itemsPerSlide = $(carouselDataSource).attr('data-carousel-' + mode + '-itemcount') == null ||
            $(carouselDataSource).attr('data-carousel-' + mode + '-itemcount') == '' ?
            0 : parseInt($(carouselDataSource).attr('data-carousel-' + mode + '-itemcount'));
        //[3/20/15] Merge 2/25 from Main Release Branch
        //var items = $(carouselDataSource).find('li');
        var items = $(carouselDataSource).children('li');

        var itemSize = $(carouselDataSource).attr('data-carousel-' + mode + '-itemsize') == null ||
            $(carouselDataSource).attr('data-carousel-' + mode + '-itemsize') == '' ?
            0 : parseInt($(carouselDataSource).attr('data-carousel-' + mode + '-itemsize'));

        var itemOffset = $(carouselDataSource).attr('data-carousel-' + mode + '-item-offset') == null ||
            $(carouselDataSource).attr('data-carousel-' + mode + '-item-offset') == '' ?
            0 : parseInt($(carouselDataSource).attr('data-carousel-' + mode + '-item-offset'));


        var contentOffset = itemOffset <= 0 ? '' : '<div class="col-sm-' + itemOffset + '"></div>';

        var carouselIndicatorAlign = isMobile() ? "center" : $(carouselDataSource).attr('data-pagination-align');

        //create temp content
        var content = carouselTemplate;
        content = content.replace('{ID}', carouselId);

        //interval
        var interval = $(carouselDataSource).attr('data-slideshow-interval');
        var showSlideshowInterval = interval != null ? interval : "3000";

        var slideshow = $(carouselDataSource).attr('data-slideshow-' + mode);
        var showSlideshow = slideshow != null && slideshow.toLowerCase() == "true" ? 'data-interval="' + showSlideshowInterval + '"' : 'data-interval="false"';
        content = content.replace('{SLIDESHOW}', showSlideshow);

        var contentItems = '';
        var contentIndicators = '';

        for (var ctr = 0; ctr < items.length && ctr < (8 * itemsPerSlide) ; ctr = ctr + itemsPerSlide) {
            //slide
            var tempItem = carouselItemTemplate;

            //content
            var itemContent = '';

            switch (itemsPerSlide) {
                case 1:
                    itemContent = carouselItemTemplateSlicer1;
                    break;
                case 2:
                    itemContent = carouselItemTemplateSlicer2;
                    break;
                case 3:
                    itemContent = carouselItemTemplateSlicer3;
                    break;
            }

            for (var ctr2 = 0; ctr2 < itemsPerSlide; ctr2++) {
                var contentInner = '';
                if ((ctr2 + ctr) < (items.length)) {
                    contentInner = items.eq(ctr2 + ctr).html();
                }

                itemContent = itemContent.replace('{CONTENT' + (ctr2 + 1) + '}', contentInner);
                itemContent = itemContent.replace('{ITEM_SIZE}', itemSize);
                itemContent = itemContent.replace('{CONTENT_OFFSET}', contentOffset);

                //get only BG of first article and add it to slide BG
                if (ctr2 == 0) {
                    tempItem = tempItem.replace('{BG-IMG}', items.eq(ctr2 + ctr).attr('data-bg-image'));
                    tempItem = tempItem.replace('{BG-COL}', items.eq(ctr2 + ctr).attr('data-bg-color'));
                    tempItem = tempItem.replace('{BG-VID}', items.eq(ctr2 + ctr).attr('data-bg-video'));
                    tempItem = tempItem.replace('{BG-VID-PLAY}', items.eq(ctr2 + ctr).attr('data-bg-video-autoplay'));
                }
            }

            tempItem = tempItem.replace('{CONTENT}', itemContent);
            tempItem = tempItem.replace('{ACTIVE}', ctr <= 0 ? 'active' : '');

            //indicator
            var showPagination = $(carouselDataSource).attr('data-pagination-show');

            var tempIndicator = showPagination == null || showPagination.toLowerCase() == "true" ? carouselIndicatorTemplate : '';
            tempIndicator = tempIndicator.replace('{TARGETID}', '#' + carouselId);
            tempIndicator = tempIndicator.replace('{SLIDENUM}', ctr / itemsPerSlide);
            tempIndicator = tempIndicator.replace('{ACTIVE}', ctr <= 0 ? 'active' : '');

            //close slide item
            contentItems += tempItem;
            contentIndicators += tempIndicator;
        }

        //add items
        content = content.replace('{ITEMS}', contentItems);

        //add content indicators
        var showPlayPauseButton = $(carouselDataSource).attr('data-slideshow-button');
        if (showPlayPauseButton != null && showPlayPauseButton.toLowerCase() == "true" && contentIndicators.length > 0) {
            contentIndicators += playPauseButton.replace('{ID}', carouselId);
        }

        content = content.replace('{INDICATORS}', items.length <= itemsPerSlide ? '' : contentIndicators);
        content = content.replace('{INDICATORS_ALIGNMENT}', 'indicators-' + carouselIndicatorAlign.toLowerCase());

        return content;
    },
    addEvents: function (carousel) {

        //PlayPauseButton
        $(carousel).find('.play-pause-button').on('click', function (event) {
            var playPauseStatusSpan = $(this).children(".acn-icon");
            var playPauseStatus = $(playPauseStatusSpan).data("play-pause-status");

            $(this).closest(".carousel").carousel(playPauseStatus);
            if (playPauseStatus == 'pause') {
                $(playPauseStatusSpan).data("play-pause-status", "cycle").removeClass("icon-pause").addClass("icon-play");
                $(playPauseStatusSpan).attr("data-analytics-link-name", "icon-play");
            } else {
                $(playPauseStatusSpan).data("play-pause-status", "pause").removeClass("icon-play").addClass("icon-pause");
                $(playPauseStatusSpan).attr("data-analytics-link-name", "icon-pause");
            }
        });

        //block carousel BG slide
        $(carousel).on('slide.bs.carousel', function (e) {
            var index = $(e.relatedTarget).index();

            var proxyCarousel = '#proxy-' + carousel.attr('id');
            $(proxyCarousel).carousel(index);

            //update shape-color
            var shapeColor = $(e.relatedTarget).attr('data-bg-color');

            //get handle on shape
            var blockName = $(e.relatedTarget).closest('.ui-container').attr('id');
            var shapeContainer = $(proxyCarousel).closest('div[data-content-id="' + blockName + '"]');

            BlockCarousel.updateShapeColor(shapeColor, shapeContainer);
        });
    },
    addProxyCarousel: function (block) {
        //get handler on container
        var container = $('#layout-wrapper div[data-content-id="' + block.attr('id') + '"] .inner.parallax');

        //delete old carousel (e.g. proxy-carousel-example-block)
        var proxyCarouselName = '#proxy-' + block.find('.block-carousel').attr('id');
        container.find(proxyCarouselName).remove();

        //add new
        var newProxyCarouselHtml = GetCarouselBackground(block);
        container.append(newProxyCarouselHtml);

        //update shape-color
        var shapeColor = $(block).find('.item.active').attr('data-bg-color');

        //get handle on shape
        var blockName = $(block).attr('id');
        var shapeContainer = $(proxyCarouselName).closest('div[data-content-id="' + blockName + '"]');

        BlockCarousel.updateShapeColor(shapeColor, shapeContainer);

        //update container and remove paddings
        container.addClass('hasProxyCarousel');
    },
    updateShapeColor: function (newShapeColor, shapeContainer) {
        //determine shape color
        var shapeColor = 'shape-color-' + newShapeColor;

        //delete old data
        shapeContainer = $(shapeContainer).removeClassPrefix('shape-color-');

        //add new data
        $(shapeContainer).addClass(shapeColor);

    },
    resizeHeight: function () {
        $('.block-carousel.conv-carousel').each(function () {
            var $carousel = $(this);

            //compute max H
            var maxHeight = 0;
            $carousel.find('.item').each(function () {
                //load .item to temp div
                var $item = $(this);
                var $tempContainer = $item.closest('.ui-content-box').find('.tempContainer');

                $tempContainer.html($item.html());

                //get height
                maxHeight = $tempContainer.height() > maxHeight ? $tempContainer.height() : maxHeight;

                //remove temp div content
                $tempContainer.html('');
            });

            //apply to all items
            $carousel.find('.item').height(maxHeight);
        });

        //RST: For Merging
    },

    parallaxBackground: function () {
        $('#layout-wrapper .inner.parallax.hasProxyCarousel .carousel .item').each(function () {
            var $this = $(this);
            var container = $this.closest('.outer').data('content-id');

            if ($this.closest('.carousel.convertible-block-carousel').length > 0)
                container = container + "-carousel";

            if ($('#' + container).data('background-align') == 'Right')
                $this.css('background-position-x', 'right');
            else
                $this.css('background-position-x', 'left'); // default

            if ($('#' + container).data('background-cover') == 'True')
                $this.css('background-size', 'cover'); //else CSS will apply 100%, auto
        });
    },

    addAnalyticsLinkTrackingAttribute: function () {
        //PlayPauseButton
        $('#block-hero .carousel-indicators .play-pause-button').on('click', function (event) {
            var playPauseStatusSpan = $(this).children(".acn-icon");

            if (playPauseStatusSpan.hasClass('icon-pause')) {
                playPauseStatusSpan.attr('data-analytics-link-name', 'icon-pause');
            } else {
                playPauseStatusSpan.attr('data-analytics-link-name', 'icon-play');
            }
        });
    }
};

$.fn.removeClassPrefix = function (prefix) {
    this.each(function (i, el) {
        var classes = el.className.split(" ").filter(function (c) {
            return c.lastIndexOf(prefix, 0) !== 0;
        });
        el.className = classes.join(" ");
    });
    return this;
};

var cBlockCarousel = $('.convBlockCarousel');

$(function () {
    cBlockCarousel.each(function () { BlockCarousel.convert(this); });
    BlockCarousel.resizeHeight();
    //RST: For Merging
    BlockCarousel.parallaxBackground();
    cBlockCarousel.each(function () { BlockCarousel.removeHidden(this); });
    BlockCarousel.addAnalyticsLinkTrackingAttribute();
});

$(window).on("resize", function () {
    cBlockCarousel.each(function () { BlockCarousel.convert(this); });
    cBlockCarousel.each(function () { BlockCarousel.removeHidden(this); });
    BlockCarousel.resizeHeight();

});

//autoplayer
//moved this function to site.js
//function limelightPlayerCallback(playerId, eventName, data) {
//    if (eventName == 'onMediaLoad' && playerId.indexOf('blockcarousel_bg_limelight_player_') >= 0) {
//        var v = document.getElementById(playerId);
//        if (v != null && $(v).closest('.item').hasClass('autoplay'))
//            v.doPlay();
//    }
//}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\social-like.js
/*  version="28"  */
/**
 * Social Likes
 * http://sapegin.github.com/social-likes
 *
 * Sharing buttons for Russian and worldwide social networks.
 *
 * @requires jQuery
 * @author Artem Sapegin
 * @copyright 2014 Artem Sapegin (sapegin.me)
 * @license MIT
 */

/*global define:false, socialLikesButtons:false */

(function (factory) { // Try to register as an anonymous AMD module
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    }
    else {
        factory(jQuery);
    }
}(function ($, undefined) {
    'use strict';

    var prefix = 'social-likes';
    var classPrefix = prefix + '__';
    var openClass = prefix + '_opened';
    var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
    var hostName = location.hostname;
    var shareCounter = "";
    var shareLabel = "";

    /**
     * Buttons
     */
    var services = {
        facebook: {
            //popupUrl: '//www.facebook.com/sharer/sharer.php?u={url}',
            popupUrl: protocol + '//www.facebook.com/sharer/sharer.php?u={url}?quote={quote}',
            popupWidth: 650,
            popupHeight: 500
        },

        xing: {
            popupUrl: protocol + '//www.xing.com/social_plugins/share?h=1;url={url}',
            popupWidth: 650,
            popupHeight: 500
        },

        linkedin: {
            //popupUrl: '//www.linkedin.com/shareArticle?mini=true&url={url}',
            popupUrl: protocol + '//www.linkedin.com/shareArticle?mini=true&url={url}',
            popupWidth: 650,
            popupHeight: 500
        },

        twitter: {
            popupUrl: protocol + '//twitter.com/intent/tweet?url={url}&text={title}',
            popupWidth: 600,
            popupHeight: 450,
            click: function () {
                // Add colon to improve readability
                if (!/[\.:\-–—]\s*$/.test(this.options.title)) this.options.title += '';
                return true;
            }
        },
        mailru: {
            popupUrl: protocol + '//connect.mail.ru/share?share_url={url}&title={title}',
            popupWidth: 550,
            popupHeight: 360
        },
        vkontakte: {
            popupUrl: protocol + '//vk.com/share.php?url={url}&title={title}',
            popupWidth: 550,
            popupHeight: 330
        },
        odnoklassniki: {
            popupUrl: protocol + '//www.odnoklassniki.ru/dk?st.cmd=addShare&st._surl={url}',
            popupWidth: 550,
            popupHeight: 360
        },
        googleplus:
        {
            popupUrl: 'https://plus.google.com/share?url={url}',
            popupWidth: 700,
            popupHeight: 500
        },

        email: {
            popupUrl: 'mailto:?subject={title}&body={url}',
            popupWidth: 0,
            popupHeight: 0
            //popupUrl: EmailURL(),
            //popupWidth: 500,
            //popupHeight: 700
        },

        email2: {
            popupUrl: 'mailto:?subject={title}&body={url}',
            popupWidth: 0,
            popupHeight: 0
        },

        yahoomail: {
            //popupUrl: 'http://compose.mail.yahoo.com/?Subject={title}&body={url}',
            popupUrl: protocol + '//compose.mail.yahoo.com/?Subject={title}&body={url}',
            popupWidth: 630,
            popupHeight: 500
        },
        gmail: {
            //popupUrl: 'https://mail.google.com/mail/?view=cm&fs=1&su={title}&body={url}',
            popupUrl: protocol + '//mail.google.com/mail/?view=cm&fs=1&su={title}&body={url}',
            popupWidth: 630,
            popupHeight: 500
        },

        pinterest: {
            popupUrl: protocol + '//pinterest.com/pin/create/button/?url={url}&description={title}',
            popupWidth: 630,
            popupHeight: 270
        },

        weibo: {
            popupUrl: 'http://service.weibo.com/share/share.php?url={url}&title={title}',
            popupWidth: 630,
            popupHeight: 270
        },

        renren: {
            popupUrl: 'http://share.renren.com/share/buttonshare?link={url}&title={title}',
            popupWidth: 630,
            popupHeight: 270
        },

        whatsapp: {
            popupUrl: protocol + '//api.whatsapp.com/send?text={title} {url}',
            popupWidth: 650,
            popupHeight: 500

        }
    };


    /**
    * jQuery plugin
    */
    $.fn.socialLikes = function (options) {
        return this.each(function () {
            var elem = $(this);
            var instance = elem.data(prefix);
            if (instance) {
                if ($.isPlainObject(options)) {
                    instance.update(options);
                }
            }
            else {
                instance = new SocialLikes(elem, $.extend({}, $.fn.socialLikes.defaults, options, dataToOptions(elem)));
                elem.data(prefix, instance);
            }
        });
    };

    //if (!isMobile()) {
    $.fn.socialLikes.defaults = {
        url: window.location.href.replace(window.location.hash, ''),
        title: document.title,
        counters: false,
        zeroes: false,
        wait: 450,
        popupCheckInterval: 500,
        singleTitle: $('.social-likes').attr("data-single-title")
    };
    //} else {
    //    $.fn.socialLikes.defaults = {
    //        url: window.location.href.replace(window.location.hash, ''),
    //        title: document.title,
    //        counters: true,
    //        zeroes: false,
    //        wait: 450,
    //        popupCheckInterval: 500,
    //        singleTitle: ' '
    //    };
    //}

    function SocialLikes(container, options) {
        this.container = container;
        this.options = options;
        this.init();
    };

    SocialLikes.prototype = {
        init: function () {
            // Add class in case of manual initialization
            this.container.addClass(prefix);

            this.single = this.container.hasClass(prefix + '_single');

            this.number = 0;
            this.initUserButtons();
            var buttons = this.container.children();
            this.countersLeft = buttons.length;

            this.makeSingleButton();

            this.buttons = [];
            buttons.each($.proxy(function (idx, elem) {
                this.buttons.push(new Button($(elem), this.options));
            }, this));

        },
        initUserButtons: function () {
            if (!this.userButtonInited && window.socialLikesButtons) {
                $.extend(true, services, socialLikesButtons);
            }
            this.userButtonInited = true;
        },

        makeSingleButton: function () {
            if (!this.single) return;

            var container = this.container;

            //Bug # 237275 [Share and Commnets][All][All] - Display share and comment as 'Shares' and 'Comments' even if there is 0 comments or shares.
            this.options.singleTitle = $('.social-likes').data("plural-title");
            this.options.shareLabel = $('.social-likes').data("share-label");

            if (container.closest(".joblisting-container .top-links").length > 0 || container.closest(".joblisting-container .bottom-links").length > 0) {
                this.options.singleTitle = $('.social-likes').data("button-title");
                this.options.shareLabel = $('.social-likes').data("button-title");
            }
            container.addClass(prefix + '_vertical');
            container.wrap($('<div>', { 'class': prefix + '_single-w' }));
            var wrapper = container.parent();

            // Widget
            var widget = $('<div>', {
                'class': getElementClassNames('widget', 'single')
            });

            shareCounter = "";
            shareLabel = '<span class="title {clickableCls}">' + this.options.shareLabel + '</span>';

            var button = $(template(
                '<a role="button" aria-label="Shares" tabindex="0" data-toggle="popover" data-placement="bottom" class="{buttonCls}" title="{title}">' +
                '<span class="{iconCls}"  title="{title}"></span>' +
                shareCounter +
                shareLabel +
                '</a>',
                {
                    buttonCls: getElementClassNames('button', 'single'),
                    iconCls: getElementClassNames('icon', 'single acn-icon icon-share'),
                    title: this.options.singleTitle,
                    clickableCls: 'clickable'
                }
            ));
            this.sharedButton = button;
            widget.append(this.sharedButton);//widget.re
            wrapper.append(widget);

            widget.on('click touchstart', function (e) {
                var FSMHeader = widget.closest(".featured-section-module");
                var eventCalendarHeader = widget.closest(".module-event-calendar");
                if ((FSMHeader && FSMHeader.length > 0) || (eventCalendarHeader && eventCalendarHeader.length > 0)) {
                    if (e.type == "touchstart") {
                        return;
                    }
                }
                var activeClass = prefix + '__widget_active';
                widget.addClass(activeClass);
                //container.css({ top: -container.height() });
                showInViewport(container);
                closeOnClick(container, function () {
                    widget.removeClass(activeClass);
                });
                return false;
            });

            this.widget = widget;
        },
        update: function (options) {
            if (!options.forceUpdate && options.url === this.options.url) return;

            // Reset counters
            this.number = 0;
            this.countersLeft = this.buttons.length;
            if (this.widget) this.widget.find('.' + prefix + '__counter').remove();

            // Update options
            $.extend(this.options, options);
            for (var buttonIdx = 0; buttonIdx < this.buttons.length; buttonIdx++) {
                this.buttons[buttonIdx].update(options);
            }
        },

        appear: function () {
            this.container.addClass(prefix + '_visible');
        }

    };

    function Button(widget, options) {
        this.widget = widget;
        this.options = $.extend({}, options);
        this.detectService();
        if (this.service) {
            this.init();
        }
    };

    Button.prototype = {
        init: function () {
            this.detectParams();
            this.initHtml();
        },

        update: function (options) {
            $.extend(this.options, { forceUpdate: false }, options);
            this.widget.find('.' + prefix + '__counter').remove(); // Remove old counter
        },

        detectService: function () {
            var classes = this.widget[0].classList || this.widget[0].className.split(' ');
            for (var classIdx = 0; classIdx < classes.length; classIdx++) {
                var cls = classes[classIdx];
                if (services[cls]) {
                    this.service = cls;
                    $.extend(this.options, services[cls]);
                    return;
                }
            }
        },

        detectParams: function () {
            var data = this.widget.data();
            var descriptionQueryName = "&desc=";
            var thumbnail = "&tn=";
            var titleQueryName = "ti=";


            // Custom page title
                var customizeEmailSubject = $(".share-tools .share-icons-container").attr('data-email-subject');
                var customizeBPEmailSubject = $(".share-tools .side-share-container").attr('data-email-subject');
                var defaultTitle = $('meta[property="og:title"]').attr('content');

                if (customizeEmailSubject && data.network === "email") {
                    this.options.title = customizeEmailSubject;
                }
                else {
                    this.options.title = defaultTitle;
                }

                if (customizeBPEmailSubject && data.network === "email") {
                    this.options.title = customizeBPEmailSubject;
                }
                else {
                    this.options.title = defaultTitle;
                }

            // Custom page URL
            if (data.url) {
                this.options.url = data.url;
                if (data.network === "facebook") {
                    if (this.options.url.indexOf(descriptionQueryName) > -1) {
                        data.description = this.options.url.split(descriptionQueryName)[1].split("&tn")[0];
                    }
                    else if (this.options.url.indexOf(titleQueryName) > -1) {
                        data.description = " ";
                    }

                    if (this.options.url.indexOf(thumbnail) > -1) {
                        data.picture = this.options.url.split(thumbnail)[1].split("&")[0];
                    }
                }
                else if (data.network === "linkedin") {
                    if (this.options.url.indexOf(descriptionQueryName) > -1) {
                        data.summary = this.options.url.split(descriptionQueryName)[1].split("&tn")[0];
                    }
                    else if (this.options.url.indexOf(titleQueryName) > -1) {
                        data.summary = " ";
                    }
                }
            }
        },

        initHtml: function () {
            var options = this.options;
            var widget = this.widget;

            // Old initialization HTML
            var a = widget.find('a');
            if (a.length) {
                this.cloneDataAttrs(a, widget);
            }

            // Button
            var button = $('<span>', {
                'class': this.getElementClassNames('button'),
                'text': widget.text()
            });
            if (options.clickUrl) {
                var url = makeUrl(options.clickUrl, {
                    url: options.url,
                    title: options.title
                });
                var link = $('<a>', {
                    href: url
                });
                this.cloneDataAttrs(widget, link);
                widget.replaceWith(link);
                this.widget = widget = link;
            }
            else {
                widget.on("click", $.proxy(this.click, this));
            }

            widget.removeClass(this.service);
            widget.addClass(this.getElementClassNames('widget'));

            // Icon
            button.prepend($('<span>', { 'class': this.getElementClassNames('icon') }));

            widget.empty().append(button);
            this.button = button;
        },

        cloneDataAttrs: function (source, destination) {
            var data = source.data();
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    destination.data(key, data[key]);
                }
            }
        },

        getElementClassNames: function (elem) {
            return getElementClassNames(elem, this.service);
        },

        click: function (e) {
            var options = this.options;
            var process = true;
            if (typeof options.click === "function") {
                process = options.click.call(this, e);
            }
            if (options.popupUrl.indexOf("facebook") >= 0 ||
                options.popupUrl.indexOf("mail.google") >= 0 ||
                options.popupUrl.indexOf("linkedin") >= 0 ||
                options.popupUrl.indexOf("xing") >= 0 ||
                options.popupUrl.indexOf("mailto:") >= 0 ||
                options.popupUrl.indexOf("mail.yahoo") >= 0) {
                if (options.url.split("?")[1] != undefined && options.url.indexOf("id=") < 0) {
                    options.url = options.url.split("?")[0];
                }
            }
            if (process) {
                var url = makeUrl(options.popupUrl, {
                    //url: protocol + '//' + hostName + options.url,
                    url: options.url.indexOf('events-calendar') > 0 ? window.location.href : options.url,
                    title: options.title
                });
                if (options.popupUrl.indexOf("mailto:") >= 0 && $(".blog-content-module").length > 0) {
                    var articleTitle = options.title;
                    var customizeEmailSubject = $(".share-tools .share-icons-container").attr('data-email-subject');
                    if ($(".hero-wrapper .page-title").length > 0) {
                        articleTitle = $(".page-title").eq(0).text();
                    }
                    if (customizeEmailSubject) {
                        url = url.replace("subject=" + encodeURI(options.title), "subject=" + encodeURI(customizeEmailSubject));
                    }
                    else {
                        url = url.replace("subject=" + encodeURI(options.title), "subject=Check out this Accenture Blog");
                    }
                    url = url.replace("body=", "body=" + articleTitle + " ");
                }
                url = this.addAdditionalParamsToUrl(url);
                this.openPopup(url, {
                    width: options.popupWidth,
                    height: options.popupHeight
                });
            }

            if ($('.brand-purpose-social-icon').length > 0) {
                return true;
            }
            else {
                return false;
            }
        },

        addAdditionalParamsToUrl: function (url) {
            if (this.widget.data()["bs.popover"] != null) {
                return url;
            }
            if (this.widget.data()["bs.tooltip"] != null) {
                if ($(".share-tools").length > 0) {
                    this.widget.data()["bs.tooltip"] = "";
                    $(".tooltip").remove();
                }
            }

            if (this.widget.data()['url']) {
                if (this.widget.data()['url'].indexOf('events-calendar') && this.widget.data()['network'] === 'xing')
                    return url;
            }
            if (this.widget.data()["network"] === "twitter") {
                if (this.widget.data()["url"] != null) {
                    delete this.widget.data()["url"];
                }
                if (this.widget.data()["title"] != null) {
                    delete this.widget.data()["title"];
                }
            }
            var params = $.param($.extend(this.widget.data(), this.options.data));
            if ($.isEmptyObject(params)) return url;
            var glue = url.indexOf('?') === -1 ? '?' : '&';
            return url + glue + params;
        },

        openPopup: function (url, params) {
            var left = Math.round(screen.width / 2 - params.width / 2);
            var top = 0;
            if (screen.height > params.height) {
                top = Math.round(screen.height / 2 - params.height / 2);
            }
            var win = null;
            if (IsIE()) {
                win = window.open('', 'sl_' + this.service, 'top=' + top + ',' +
                    'left=' + left + ',' + 'width=' + params.width + ',height=' + params.height + ',personalbar=0,toolbar=0,scrollbars=1,resizable=1');
                win.location = url;
            }
            else if (this.service == "email") {
                win = window.open(url, 'sl_' + this.service);
            }
            else {
                win = window.open(url, 'sl_' + this.service, 'top=' + top + ',' +
                    'left=' + left + ',' + 'width=' + params.width + ',height=' + params.height + ',personalbar=0,toolbar=0,scrollbars=1,resizable=1');
            }
            if (win) {
                win.focus();
                this.widget.trigger('popup_opened.' + prefix, [this.service, win]);
                if (params.height == 0) {
                    if (this.service == "email") {
                        setTimeout(function () {
                            win.close();
                        }, 2000);
                    }
                    else {
                        win.close();
                    }
                }
                var timer = setInterval($.proxy(function () {
                    if (!win.closed) return;
                    clearInterval(timer);
                    this.widget.trigger('popup_closed.' + prefix, this.service);
                }, this), this.options.popupCheckInterval);
            }
            else {
                location.href = url;
            }
        }
    };

    /**
    * Helpers
    */

    // Camelize data-attributes
    function dataToOptions(elem) {
        function upper(m, l) {
            return l.toUpper();
        }
        var options = {};
        var data = elem.data();
        for (var key in data) {
            var value = data[key];
            if (value === 'yes') value = true;
            else if (value === 'no') value = false;
            options[key.replace(/-(\w)/g, upper)] = value;
        }
        return options;
    };

    function makeUrl(url, context) {
        return template(url, context, encodeURIComponent);
    };

    function template(tmpl, context, filter) {
        return tmpl.replace(/\{([^\}]+)\}/g, function (m, key) {
            // If key don't exists in the context we should keep template tag as is
            return key in context ? (filter ? filter(context[key]) : context[key]) : m;
        });
    };

    function getElementClassNames(elem, mod) {
        var cls = classPrefix + elem;
        return cls + ' ' + cls + '_' + mod;
    };

    function closeOnClick(elem, callback) {
        function handler(e) {
            if ((e.type === 'keydown' && e.which !== 27) || $(e.target).closest(elem).length) return;
            elem.removeClass(openClass);
            doc.off(events, handler);
            if (typeof callback === "function") callback();
        }
        var doc = $(document);
        var events = 'click touchstart keydown';
        doc.on(events, handler);
    };

    function showInViewport(elem) {
        if ($(elem).hasClass(openClass)) {
            elem.removeClass(openClass);
            return;
        }

        var offset = 10;
        if (document.documentElement.getBoundingClientRect) {
            var left = parseInt(elem.css('left'), 10);
            var top = parseInt(elem.css('top'), 10);

            var rect = elem[0].getBoundingClientRect();
            if (rect.left < offset)
                elem.css('left', offset - rect.left + left);
            else if (rect.right > window.innerWidth - offset)
                elem.css('left', window.innerWidth - rect.right - offset + left);

            if (rect.top < offset)
                elem.css('top', offset - rect.top + top);
            else if (rect.bottom > window.innerHeight - offset)
                elem.css('top', window.innerHeight - rect.bottom - offset + top);
        }
        elem.addClass(openClass);
    };

    /**
    * Auto initialization
    */
    $(function () {
        $('.' + prefix).socialLikes();
        //Bug 435554: Share overlay cannot be closed and another set of overlay is displayed in tablet
        //$(".social-likes_single-w").popover({
        //    html: true,
        //    placement: 'bottom',
        //    container: 'body',
        //    content: function () {
        //        return $('.social-likes').html();
        //    }
        //});

        //$(".social-likes__widget").on('shown.bs.popover', function () {
        //    $(".social-likes__widget").closest(".popover").addClass("social-like");
        //})
    });
}));

function EmailURL() {
    var pathArray = window.location.pathname.split("/");

    var emailPath = location.protocol + "//" + location.host + "/" + pathArray[1] + "/" + "ShareEmail" + "?Subject={title}&body={url}";
    //http://acn21326/core/shareemail/?Subject={title}&body={url}';

    return emailPath;
};

var processingSocial = false;

function socialLink(element) {
    if (!processingSocial) {
        var e2 = $(element).children("span");
        if (e2[0] != undefined) {
            var cssClass = $(e2).attr("class").split(' ')[1];
            processingSocial = true;
            $("." + cssClass).trigger("click");
        }
        processingSocial = false;
    }
};



;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\acn.image-loader.js
//This plugin converts span element to img tag.
//Created by joseph german ocena
//Created Date: 10/28/2014
//Last Modified Date: 2/3/2015
//Version: 1.2.0

(function ($, window, document, undefined) {
    var deviceWidth = window.screen.width;

    //Main functions
    $.fn.imageloader = function (option) {
        var options = $.extend({}, $.fn.imageloader.options, option);

        this.each(function () {
            var currentElement = $(this);
            var alt = currentElement.attr("data-alt");
            var src = currentElement.attr("data-src");
            var cssClass = currentElement.attr("data-class");
            var style = currentElement.attr("data-style");
            var title = currentElement.attr("data-title");
            var col = currentElement.attr("data-col");

            var fixedWidth = currentElement.attr("data-width");

            if (!fixedWidth) {
                // SiteCore compression
                // 1. Get the col // this col is half of the col-sm
                var myParentCol = $(currentElement).closest('div[class^=col-sm]');
                var col = GetCol(myParentCol);
                var w = 0;
                if (deviceWidth > 1000) {
                    if (!/\.gif$/i.test(src)) {
                        w = WidthForLaptop(col);
                    }
                }
                else {
                    w = WidthForDevice(col);
                }
            }
            else {
                w = fixedWidth;
            }
            if (typeof src != 'undefined') {
                // put a logic for adding ?w=w based on finalization of server side approach
                if (src.search(options.srcIdentifier) >= 0) {
                    src = src.replace(options.srcIdentifier, "w" + w);
                }
                else if (src.search(options.srcIdentifierSearch) >= 0) {
                    src = src.replace(options.srcIdentifierSearch, "w" + w);
                }

                var acnImage = document.createElement("img");

                acnImage.src = src;
                acnImage.alt = alt;
                acnImage.title = title;
                acnImage.setAttribute("style", style);
                acnImage.setAttribute("data-width", fixedWidth);

                if (typeof cssClass != 'undefined') {
                    //acnImage.attr = "img-responsive " + cssClass;
                    acnImage.setAttribute("class", "img-responsive " + cssClass);
                } else {
                    //acnImage.attr = "img-responsive";
                    acnImage.setAttribute("class", "img-responsive");
                }

                var curHtml = currentElement.html();
                if (curHtml != null && curHtml != '') {
                    acnImage.innerHTML = curHtml;
                }

                currentElement.replaceWith(acnImage);
            }
            return this;
        });

        return this;
    }

    function WidthForLaptop(col) {
        // calculate w
        // col 6 = 1000px
        // col 4 = 660px
        // col 3 = 490px
        // col 2 = 320px
        // col 1 = 150

        switch (col) {
            case 12: return 1000;
            case 8: return 660;
            case 6: return 490;
            case 4: return 320;
			case 3: return 250;
            case 2: return 150;
        }
        return 1000;
    }

    function WidthForDevice(col) {
        // say W
        // w = W * 0.9 * col/12
        // Ratina - if pixel density is greater than 1
        // if w < 500
        // d = window.devicePixelRatio   ///this code will be different for windows phone
        //http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
        // w = w * (d>2?2:d)

        //Fix for  Bug# 422404 and Bug# 423560
        // Start
        //var deviceWidth = window.screen.width;
        // End
        var deviceWidth = pageState.viewPortWidth;
        if (deviceWidth < 768) {
            col = 1;
        }
        var width = parseInt(deviceWidth * 0.8 * col);
        // var pdensity = window.devicePixelRatio;
        // width = width * (pdensity > 2 ? 2 : pdensity);
        return width;
    }

    function GetCol(e) {
        if (e.hasClass('col-sm-2')) return 2;
		if (e.hasClass('col-sm-3')) return 3;
        if (e.hasClass('col-sm-4')) return 4;
        if (e.hasClass('col-sm-6')) return 6;
        if (e.hasClass('col-sm-8')) return 8;
        if (e.hasClass('col-sm-12')) return 12;
        return 12;
    }
    //default settings.
    $.fn.imageloader.options = {
        srcIdentifier: "__w__",
        srcIdentifierSearch: "~"
    };
})(jQuery, window, document);

$(function () {
    $("span.image-holder").imageloader();
});
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.undoable.js
/* version 2 */
(function ($) {
    $.fn.undoable = function (options) {
        var opts = $.extend({}, $.fn.undoable.defaults, options);

        return this.each(function (i) {
            $this = $(this);

            $this.on("click", function () {
                var clickSource = $(this);
                clickSource.prop('disabled', true);
                var target = (opts.getTarget || $.fn.undoable.getTarget).call($.fn.undoable, clickSource);
                var url = opts.url;
                var data = (opts.getPostData || $.fn.undoable.getPostData).call($.fn.undoable, clickSource, target);

                $.fn.undoable.postToServer(url, data, function (response) {
                    var undoData = $.extend(response, data);
                    target.inlineStyling = opts.inlineStyling;
                    var undoable = (opts.showUndo || $.fn.undoable.showUndo).call($.fn.undoable, target, undoData, opts);
                    target.hide();

                    undoable.find('.undo a').on("click", function () {
                        $(this).prop('disabled', true);

                        var data = (opts.getUndoPostData || $.fn.undoable.getUndoPostData).call($.fn.undoable, clickSource, target, opts);
                        $.fn.undoable.postToServer(opts.undoUrl || url, data, function () {
                            (opts.hideUndo || $.fn.undoable.hideUndo).call($.fn.undoable, undoable, target, opts);
                            clickSource.prop('disabled', false);
                        }, clickSource);
                        return false;
                    });
                }, clickSource);

                return false;
            });
        });
    };

    $.fn.undoable.getTarget = function (clickSource) {
        var tr = clickSource.closest('tr');
        if (tr.length === 0) {
            return clickSource.closest('.target');
        }
        return tr;
    };

    $.fn.undoable.getPostData = function (clickSource, target) {
        var href = clickSource.attr('href');
        return { id: href.substring(href.indexOf('#') + 1) };
    };

    $.fn.undoable.getUndoPostData = function (clickSource, target, options) {
        return (options.getPostData || this.getPostData).call(this, clickSource, target, options);
    };

    $.fn.undoable.createUndoable = function (target, data, message) {
        if (target[0].tagName === 'TR') {
            var colSpan = target.children('td').length;
            target.after('<tr class="undoable"><td class="status" colspan="' + (colSpan - 1) + '">' + message + '</td><td class="undo">' + ' ' + '<a href="#' + data.id + '">Undo</a></td></tr>');
        }
        else {
            var tagName = target[0].tagName;
            var classes = target.attr('class') || "";
            var undoStmt = '<p class="undo">' + ' ' + '<a href="#' + data.id + '">Undo</a></p>';
            var pos = message.indexOf("</i>");
            message = [message.slice(0, pos + 4), undoStmt, message.slice(pos + 4)].join('');
            target.after('<' + tagName + ' class="undoable ' + classes + '"><p class="status">' + message + '</p></' + tagName + '>');
            //target.after('<' + tagName + ' class="undoable ' + classes + '"><p class="status">' + message + '</p><p class="undo">' + ' ' + '<a href="#' + data.id + '">Undo</a></p></' + tagName + '>');
            //target.after('<' + tagName + ' class="undoable ' + classes + '"><p class="status undo">' + message + '<a href="#' + data.id + '"> Undo</a></p></' + tagName + '>');
        }
        return target.next();
    };

    $.fn.undoable.showUndo = function (target, data, options) {
        var message = (options.formatStatus || this.formatStatus).call(this, data);
        var undoable = (options.createUndoable || $.fn.undoable.createUndoable).call($.fn.undoable, target, data, message);

        if (options.showingStatus) {
            options.showingStatus(undoable);
        }

        undoable.hide().fadeIn('slow').show();
        if (target.inlineStyling) {
            (options.applyUndoableStyle || $.fn.undoable.applyUndoableStyle).call($.fn.undoable, undoable);
        }
        return undoable;
    };

    $.fn.undoable.hideUndo = function (undoable, target, options) {
        if (options.hidingStatus) {
            options.hidingStatus(undoable, target);
        }
        undoable.remove();
        target.fadeIn('slow').show();
        return target;
    };

    $.fn.undoable.formatStatus = function (data) {
        //return '<strong class="subject">' + data.subject + '</strong> <span class="predicate">' + data.predicate + '</span>';
        return '<div class="undo-changes">' + data.subject + '<i> ' + data.predicate + '</i></div>';
    };

    $.fn.undoable.applyUndoableStyle = function (undoable) {
        //undoable.css('backgroundColor', '#e0e0e0');
        undoable.css('color', '#777777');
        var styled = undoable;
        if (undoable[0].tagName === 'TR') {
            styled = undoable.children('td');
            //undoable.children('td:first').css('borderLeft', 'solid 2px #bbbbbb');
        }
        else {
            //styled.css('borderLeft', 'solid 2px #bbbbbb');
        }
        //styled.css('text-align', 'center');
        //styled.css('borderTop', 'solid 2px #bbbbbb');
        // styled.css('borderBottom', 'solid 1px #cccccc');
    };

    $.fn.undoable.postToServer = function (url, data, success, clickSource) {
        if (url) {
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: data,
                success: success
            });
        }
        else {
            // demo mode
            success({ subject: 'Removed', predicate: clickSource[0].nextSibling.data });
        }
    };

    $.fn.undoable.defaults = {
        /* Applies some default styling if true. If false, all styling is done via CSS class */
        inlineStyling: true
    };
})(jQuery);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.custom-scrollbar.js
/*version 2*/
(function ($) {

    $.fn.customScrollbar = function (options, args) {

        var defaultOptions = {
            skin: undefined,
            hScroll: true,
            vScroll: true,
            updateOnWindowResize: false,
            animationSpeed: 300,
            onCustomScroll: undefined,
            swipeSpeed: 1,
            wheelSpeed: 40,
            fixedThumbWidth: undefined,
            fixedThumbHeight: undefined,
            preventDefaultScroll: false
        }

        var Scrollable = function (element, options) {
            this.$element = $(element);
            this.options = options;
            this.addScrollableClass();
            this.addSkinClass();
            this.addScrollBarComponents();
            if (this.options.vScroll)
                this.vScrollbar = new Scrollbar(this, new VSizing());
            if (this.options.hScroll)
                this.hScrollbar = new Scrollbar(this, new HSizing());
            this.$element.data("scrollable", this);
            this.initKeyboardScrolling();
            this.bindEvents();
        }

        Scrollable.prototype = {

            addScrollableClass: function () {
                if (!this.$element.hasClass("scrollable")) {
                    this.scrollableAdded = true;
                    this.$element.addClass("scrollable");
                }
            },

            removeScrollableClass: function () {
                if (this.scrollableAdded)
                    this.$element.removeClass("scrollable");
            },

            addSkinClass: function () {
                if (typeof (this.options.skin) == "string" && !this.$element.hasClass(this.options.skin)) {
                    this.skinClassAdded = true;
                    this.$element.addClass(this.options.skin);
                }
            },

            removeSkinClass: function () {
                if (this.skinClassAdded)
                    this.$element.removeClass(this.options.skin);
            },

            addScrollBarComponents: function () {
                this.assignViewPort();
                if (this.$viewPort.length == 0) {
                    this.$element.wrapInner("<div class=\"viewport\" />");
                    this.assignViewPort();
                    this.viewPortAdded = true;
                }
                this.assignOverview();
                if (this.$overview.length == 0) {
                    this.$viewPort.wrapInner("<div class=\"overview\" />");
                    this.assignOverview();
                    this.overviewAdded = true;
                }
                this.addScrollBar("vertical", "prepend");
                this.addScrollBar("horizontal", "append");
            },

            removeScrollbarComponents: function () {
                this.removeScrollbar("vertical");
                this.removeScrollbar("horizontal");
                if (this.overviewAdded)
                    this.$element.unwrap();
                if (this.viewPortAdded)
                    this.$element.unwrap();
            },

            removeScrollbar: function (orientation) {
                if (this[orientation + "ScrollbarAdded"])
                    this.$element.find(".scroll-bar." + orientation).remove();
            },

            assignViewPort: function () {
                this.$viewPort = this.$element.find(".viewport");
            },

            assignOverview: function () {
                this.$overview = this.$viewPort.find(".overview");
            },

            addScrollBar: function (orientation, fun) {
                if (this.$element.find(".scroll-bar." + orientation).length == 0) {
                    this.$element[fun]("<div class='scroll-bar " + orientation + "'><div class='thumb'></div></div>")
                    this[orientation + "ScrollbarAdded"] = true;
                }
            },

            resize: function (keepPosition) {
                if (this.vScrollbar)
                    this.vScrollbar.resize(keepPosition);
                if (this.hScrollbar)
                    this.hScrollbar.resize(keepPosition);
            },

            scrollTo: function (element) {
                if (this.vScrollbar)
                    this.vScrollbar.scrollToElement(element);
                if (this.hScrollbar)
                    this.hScrollbar.scrollToElement(element);
            },

            scrollToXY: function (x, y) {
                this.scrollToX(x);
                this.scrollToY(y);
            },

            scrollToX: function (x) {
                if (this.hScrollbar)
                    this.hScrollbar.scrollOverviewTo(x, true);
            },

            scrollToY: function (y) {
                if (this.vScrollbar)
                    this.vScrollbar.scrollOverviewTo(y, true);
            },

            scrollByX: function (x) {
                if (this.hScrollbar)
                    this.scrollToX(this.hScrollbar.overviewPosition() + x);
            },

            scrollByY: function (y) {
                if (this.vScrollbar)
                    this.scrollToY(this.vScrollbar.overviewPosition() + y);
            },

            remove: function () {
                this.removeScrollableClass();
                this.removeSkinClass();
                this.removeScrollbarComponents();
                this.$element.data("scrollable", null);
                this.removeKeyboardScrolling();
                if (this.vScrollbar)
                    this.vScrollbar.remove();
                if (this.hScrollbar)
                    this.hScrollbar.remove();
            },

            setAnimationSpeed: function (speed) {
                this.options.animationSpeed = speed;
            },

            isInside: function (element, wrappingElement) {
                var $element = $(element);
                var $wrappingElement = $(wrappingElement);
                var elementOffset = $element.offset();
                var wrappingElementOffset = $wrappingElement.offset();
                return (elementOffset.top >= wrappingElementOffset.top) && (elementOffset.left >= wrappingElementOffset.left) &&
                    (elementOffset.top + $element.height() <= wrappingElementOffset.top + $wrappingElement.height()) &&
                    (elementOffset.left + $element.width() <= wrappingElementOffset.left + $wrappingElement.width())
            },

            initKeyboardScrolling: function () {
                var _this = this;

                this.elementKeydown = function (event) {
                    if (document.activeElement === _this.$element[0]) {
                        if (_this.vScrollbar)
                            _this.vScrollbar.keyScroll(event);
                        if (_this.hScrollbar)
                            _this.hScrollbar.keyScroll(event);
                    }
                }

                this.$element
                    .attr('tabindex', '-1')
                    .on("keydown", this.elementKeydown);
            },

            removeKeyboardScrolling: function () {
                this.$element
                    .removeAttr('tabindex')
                    .off("keydown", this.elementKeydown);
            },

            bindEvents: function () {
                if (this.options.onCustomScroll)
                    this.$element.on("customScroll", this.options.onCustomScroll);
            }

        }

        var Scrollbar = function (scrollable, sizing) {
            this.scrollable = scrollable;
            this.sizing = sizing
            this.$scrollBar = this.sizing.scrollBar(this.scrollable.$element);
            this.$thumb = this.$scrollBar.find(".thumb");
            this.setScrollPosition(0, 0);
            this.resize();
            this.initMouseMoveScrolling();
            this.initMouseWheelScrolling();
            this.initTouchScrolling();
            this.initMouseClickScrolling();
            this.initWindowResize();
        }

        Scrollbar.prototype = {

            resize: function (keepPosition) {
                this.overviewSize = this.sizing.size(this.scrollable.$overview);
                this.calculateViewPortSize();
                this.sizing.size(this.scrollable.$viewPort, this.viewPortSize);
                this.ratio = this.viewPortSize / this.overviewSize;
                this.sizing.size(this.$scrollBar, this.viewPortSize);
                this.thumbSize = this.calculateThumbSize();
                this.sizing.size(this.$thumb, this.thumbSize);
                this.maxThumbPosition = this.calculateMaxThumbPosition();
                this.maxOverviewPosition = this.calculateMaxOverviewPosition();
                this.enabled = (this.overviewSize > this.viewPortSize);
                if (this.scrollPercent === undefined)
                    this.scrollPercent = 0.0;
                if (this.enabled)
                    this.rescroll(keepPosition);
                else
                    this.setScrollPosition(0, 0);
                this.$scrollBar.toggle(this.enabled);
            },

            calculateViewPortSize: function () {
                var elementSize = this.sizing.size(this.scrollable.$element);
                if (elementSize > 0 && !this.maxSizeUsed) {
                    this.viewPortSize = elementSize;
                    this.maxSizeUsed = false;
                }
                else {
                    var maxSize = this.sizing.maxSize(this.scrollable.$element);
                    this.viewPortSize = Math.min(maxSize, this.overviewSize);
                    this.maxSizeUsed = true;
                }
            },

            calculateThumbSize: function () {
                var fixedSize = this.sizing.fixedThumbSize(this.scrollable.options)
                var size;
                if (fixedSize)
                    size = fixedSize;
                else
                    size = this.ratio * this.viewPortSize
                return Math.max(size, this.sizing.minSize(this.$thumb));
            },

            initMouseMoveScrolling: function () {
                var _this = this;
                this.$thumb.on("mousedown", function (event) {
                    if (_this.enabled)
                        _this.startMouseMoveScrolling(event);
                });
                this.documentMouseup = function (event) {
                    _this.stopMouseMoveScrolling(event);
                };
                $(document).on("mouseup", this.documentMouseup);
                this.documentMousemove = function (event) {
                    _this.mouseMoveScroll(event);
                };
                $(document).on("mousemove", this.documentMousemove);
                this.$thumb.on("click", function (event) {
                    event.stopPropagation();
                });
            },

            removeMouseMoveScrolling: function () {
                this.$thumb.off();
                $(document).off("mouseup", this.documentMouseup);
                $(document).off("mousemove", this.documentMousemove);
            },

            initMouseWheelScrolling: function () {
                var _this = this;
                this.scrollable.$element.mousewheel(function (event, delta, deltaX, deltaY) {
                    if (_this.enabled) {
                        var scrolled = _this.mouseWheelScroll(deltaX, deltaY);
                        _this.stopEventConditionally(event, scrolled);
                    }
                });
            },

            removeMouseWheelScrolling: function () {
                this.scrollable.$element.off("mousewheel");
            },

            initTouchScrolling: function () {
                if (document.addEventListener) {
                    var _this = this;
                    this.elementTouchstart = function (event) {
                        if (_this.enabled)
                            _this.startTouchScrolling(event);
                    }
                    this.scrollable.$element[0].addEventListener("touchstart", this.elementTouchstart);
                    this.documentTouchmove = function (event) {
                        _this.touchScroll(event);
                    }
                    this.scrollable.$element[0].addEventListener("touchmove", this.documentTouchmove);
                    this.elementTouchend = function (event) {
                        _this.stopTouchScrolling(event);
                    }
                    this.scrollable.$element[0].addEventListener("touchend", this.elementTouchend);
                }
            },

            removeTouchScrolling: function () {
                if (document.addEventListener) {
                    this.scrollable.$element[0].removeEventListener("touchstart", this.elementTouchstart);
                    document.removeEventListener("touchmove", this.documentTouchmove);
                    this.scrollable.$element[0].removeEventListener("touchend", this.elementTouchend);
                }
            },

            initMouseClickScrolling: function () {
                var _this = this;
                this.scrollBarClick = function (event) {
                    _this.mouseClickScroll(event);
                };
                this.$scrollBar.on("click", this.scrollBarClick);
            },

            removeMouseClickScrolling: function () {
                this.$scrollBar.off("click", this.scrollBarClick);
            },

            initWindowResize: function () {
                if (this.scrollable.options.updateOnWindowResize) {
                    var _this = this;
                    this.windowResize = function () {
                        _this.resize();
                    };
                    $(window).on("resize", this.windowResize);
                }
            },

            removeWindowResize: function () {
                $(window).off("resize", this.windowResize);
            },

            isKeyScrolling: function (key) {
                return this.keyScrollDelta(key) != null;
            },

            keyScrollDelta: function (key) {
                for (var scrollingKey in this.sizing.scrollingKeys)
                    if (scrollingKey == key)
                        return this.sizing.scrollingKeys[key](this.viewPortSize);
                return null;
            },

            startMouseMoveScrolling: function (event) {
                this.mouseMoveScrolling = true;
                $("body").addClass("not-selectable");
                this.setUnselectable($("body"), "on");
                this.setScrollEvent(event);
                event.preventDefault();
            },

            stopMouseMoveScrolling: function (event) {
                this.mouseMoveScrolling = false;
                $("body").removeClass("not-selectable");
                this.setUnselectable($("body"), null);
            },

            setUnselectable: function (element, value) {
                if (element.attr("unselectable") != value) {
                    element.attr("unselectable", value);
                    element.find(':not(input)').attr('unselectable', value);
                }
            },

            mouseMoveScroll: function (event) {
                if (this.mouseMoveScrolling) {
                    var delta = this.sizing.mouseDelta(this.scrollEvent, event);
                    this.scrollThumbBy(delta);
                    this.setScrollEvent(event);
                }
            },

            startTouchScrolling: function (event) {
                if (event.touches && event.touches.length == 1) {
                    this.setScrollEvent(event.touches[0]);
                    this.touchScrolling = true;
                    event.stopPropagation();
                }
            },

            touchScroll: function (event) {
                if (this.touchScrolling && event.touches && event.touches.length == 1) {
                    var delta = -this.sizing.mouseDelta(this.scrollEvent, event.touches[0]) * this.scrollable.options.swipeSpeed;
                    var scrolled = this.scrollOverviewBy(delta);
                    if (scrolled)
                        this.setScrollEvent(event.touches[0]);
                    this.stopEventConditionally(event, scrolled);
                }
            },

            stopTouchScrolling: function (event) {
                this.touchScrolling = false;
                event.stopPropagation();
            },

            mouseWheelScroll: function (deltaX, deltaY) {
                var delta = -this.sizing.wheelDelta(deltaX, deltaY) * this.scrollable.options.wheelSpeed;
                if (delta != 0)
                    return this.scrollOverviewBy(delta);
            },

            mouseClickScroll: function (event) {
                var delta = this.viewPortSize - 20;
                if (event["page" + this.sizing.scrollAxis()] < this.$thumb.offset()[this.sizing.offsetComponent()])
                    // mouse click over thumb
                    delta = -delta;
                this.scrollOverviewBy(delta);
            },

            keyScroll: function (event) {
                var keyDown = event.which;
                if (this.enabled && this.isKeyScrolling(keyDown)) {
                    var scrolled = this.scrollOverviewBy(this.keyScrollDelta(keyDown));
                    this.stopEventConditionally(event, scrolled);
                }
            },

            scrollThumbBy: function (delta) {
                var thumbPosition = this.thumbPosition();
                thumbPosition += delta;
                thumbPosition = this.positionOrMax(thumbPosition, this.maxThumbPosition);
                var oldScrollPercent = this.scrollPercent;
                this.scrollPercent = thumbPosition / this.maxThumbPosition;
                if (oldScrollPercent != this.scrollPercent) {
                    var overviewPosition = (thumbPosition * this.maxOverviewPosition) / this.maxThumbPosition;
                    this.setScrollPosition(overviewPosition, thumbPosition);
                    this.triggerCustomScroll(oldScrollPercent);
                    return true
                }
                else
                    return false;
            },

            thumbPosition: function () {
                return this.$thumb.position()[this.sizing.offsetComponent()];
            },

            scrollOverviewBy: function (delta) {
                var overviewPosition = this.overviewPosition() + delta;
                return this.scrollOverviewTo(overviewPosition, false);
            },

            overviewPosition: function () {
                return -this.scrollable.$overview.position()[this.sizing.offsetComponent()];
            },

            scrollOverviewTo: function (overviewPosition, animate) {
                overviewPosition = this.positionOrMax(overviewPosition, this.maxOverviewPosition);
                var oldScrollPercent = this.scrollPercent;
                this.scrollPercent = overviewPosition / this.maxOverviewPosition;
                if (oldScrollPercent != this.scrollPercent) {
                    var thumbPosition = this.scrollPercent * this.maxThumbPosition;
                    if (animate)
                        this.setScrollPositionWithAnimation(overviewPosition, thumbPosition);
                    else
                        this.setScrollPosition(overviewPosition, thumbPosition);
                    this.triggerCustomScroll(oldScrollPercent);
                    return true;
                }
                else
                    return false;
            },

            positionOrMax: function (p, max) {
                if (p < 0)
                    return 0;
                else if (p > max)
                    return max;
                else
                    return p;
            },

            triggerCustomScroll: function (oldScrollPercent) {
                this.scrollable.$element.trigger("customScroll", {
                    scrollAxis: this.sizing.scrollAxis(),
                    direction: this.sizing.scrollDirection(oldScrollPercent, this.scrollPercent),
                    scrollPercent: this.scrollPercent * 100
                }
                );
            },

            rescroll: function (keepPosition) {
                if (keepPosition) {
                    var overviewPosition = this.positionOrMax(this.overviewPosition(), this.maxOverviewPosition);
                    this.scrollPercent = overviewPosition / this.maxOverviewPosition;
                    var thumbPosition = this.scrollPercent * this.maxThumbPosition;
                    this.setScrollPosition(overviewPosition, thumbPosition);
                }
                else {
                    var thumbPosition = this.scrollPercent * this.maxThumbPosition;
                    var overviewPosition = this.scrollPercent * this.maxOverviewPosition;
                    this.setScrollPosition(overviewPosition, thumbPosition);
                }
            },

            setScrollPosition: function (overviewPosition, thumbPosition) {
                this.$thumb.css(this.sizing.offsetComponent(), thumbPosition + "px");
                this.scrollable.$overview.css(this.sizing.offsetComponent(), -overviewPosition + "px");
            },

            setScrollPositionWithAnimation: function (overviewPosition, thumbPosition) {
                var thumbAnimationOpts = {};
                var overviewAnimationOpts = {};
                thumbAnimationOpts[this.sizing.offsetComponent()] = thumbPosition + "px";
                this.$thumb.animate(thumbAnimationOpts, this.scrollable.options.animationSpeed);
                overviewAnimationOpts[this.sizing.offsetComponent()] = -overviewPosition + "px";
                this.scrollable.$overview.animate(overviewAnimationOpts, this.scrollable.options.animationSpeed);
            },

            calculateMaxThumbPosition: function () {
                return Math.max(0, this.sizing.size(this.$scrollBar) - this.thumbSize);
            },

            calculateMaxOverviewPosition: function () {
                return Math.max(0, this.sizing.size(this.scrollable.$overview) - this.sizing.size(this.scrollable.$viewPort));
            },

            setScrollEvent: function (event) {
                var attr = "page" + this.sizing.scrollAxis();
                if (!this.scrollEvent || this.scrollEvent[attr] != event[attr])
                    this.scrollEvent = { pageX: event.pageX, pageY: event.pageY };
            },

            scrollToElement: function (element) {
                var $element = $(element);
                if (this.sizing.isInside($element, this.scrollable.$overview) && !this.sizing.isInside($element, this.scrollable.$viewPort)) {
                    var elementOffset = $element.offset();
                    var overviewOffset = this.scrollable.$overview.offset();
                    var viewPortOffset = this.scrollable.$viewPort.offset();
                    this.scrollOverviewTo(elementOffset[this.sizing.offsetComponent()] - overviewOffset[this.sizing.offsetComponent()], true);
                }
            },

            remove: function () {
                this.removeMouseMoveScrolling();
                this.removeMouseWheelScrolling();
                this.removeTouchScrolling();
                this.removeMouseClickScrolling();
                this.removeWindowResize();
            },

            stopEventConditionally: function (event, condition) {
                if (condition || this.scrollable.options.preventDefaultScroll) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            }

        }

        var HSizing = function () {
        }

        HSizing.prototype = {
            size: function ($el, arg) {
                if (arg)
                    return $el.width(arg);
                else
                    return $el.width();
            },

            minSize: function ($el) {
                return parseInt($el.css("min-width")) || 0;
            },

            maxSize: function ($el) {
                return parseInt($el.css("max-width")) || 0;
            },

            fixedThumbSize: function (options) {
                return options.fixedThumbWidth;
            },

            scrollBar: function ($el) {
                return $el.find(".scroll-bar.horizontal");
            },

            mouseDelta: function (event1, event2) {
                return event2.pageX - event1.pageX;
            },

            offsetComponent: function () {
                return "left";
            },

            wheelDelta: function (deltaX, deltaY) {
                return deltaX;
            },

            scrollAxis: function () {
                return "X";
            },

            scrollDirection: function (oldPercent, newPercent) {
                return oldPercent < newPercent ? "right" : "left";
            },

            scrollingKeys: {
                37: function (viewPortSize) {
                    return -10; //arrow left
                },
                39: function (viewPortSize) {
                    return 10; //arrow right
                }
            },

            isInside: function (element, wrappingElement) {
                var $element = $(element);
                var $wrappingElement = $(wrappingElement);
                var elementOffset = $element.offset();
                var wrappingElementOffset = $wrappingElement.offset();
                return (elementOffset.left >= wrappingElementOffset.left) &&
                    (elementOffset.left + $element.width() <= wrappingElementOffset.left + $wrappingElement.width());
            }

        }

        var VSizing = function () {
        }

        VSizing.prototype = {

            size: function ($el, arg) {
                if (arg)
                    return $el.height(arg);
                else
                    return $el.height();
            },

            minSize: function ($el) {
                return parseInt($el.css("min-height")) || 0;
            },

            maxSize: function ($el) {
                return parseInt($el.css("max-height")) || 0;
            },

            fixedThumbSize: function (options) {
                return options.fixedThumbHeight;
            },

            scrollBar: function ($el) {
                return $el.find(".scroll-bar.vertical");
            },

            mouseDelta: function (event1, event2) {
                return event2.pageY - event1.pageY;
            },

            offsetComponent: function () {
                return "top";
            },

            wheelDelta: function (deltaX, deltaY) {
                return deltaY;
            },

            scrollAxis: function () {
                return "Y";
            },

            scrollDirection: function (oldPercent, newPercent) {
                return oldPercent < newPercent ? "down" : "up";
            },

            scrollingKeys: {
                38: function (viewPortSize) {
                    return -10; //arrow up
                },
                40: function (viewPortSize) {
                    return 10; //arrow down
                },
                33: function (viewPortSize) {
                    return -(viewPortSize - 20); //page up
                },
                34: function (viewPortSize) {
                    return viewPortSize - 20; //page down
                }
            },

            isInside: function (element, wrappingElement) {
                var $element = $(element);
                var $wrappingElement = $(wrappingElement);
                var elementOffset = $element.offset();
                var wrappingElementOffset = $wrappingElement.offset();
                return (elementOffset.top >= wrappingElementOffset.top) &&
                    (elementOffset.top + $element.height() <= wrappingElementOffset.top + $wrappingElement.height());
            }

        }

        return this.each(function () {
            if (options == undefined)
                options = defaultOptions;
            if (typeof (options) == "string") {
                var scrollable = $(this).data("scrollable");
                if (scrollable)
                    scrollable[options](args);
            }
            else if (typeof (options) == "object") {
                options = $.extend(defaultOptions, options);
                new Scrollable($(this), options);
            }
            else
                throw "Invalid type of options";
        });

    }
        ;

})
    (jQuery);

(function ($) {

    var types = ['DOMMouseScroll', 'mousewheel'];

    $.event.special.mousewheel = {
        setup: function () {
            if (this.addEventListener) {
                for (var i = types.length; i;) {
                    this.addEventListener(types[--i], handler, false);
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function () {
            if (this.removeEventListener) {
                for (var i = types.length; i;) {
                    this.removeEventListener(types[--i], handler, false);
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function (fn) {
            return fn ? this.on("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function (fn) {
            return this.off("mousewheel", fn);
        }
    });


    function handler(event) {
        var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if (orgEvent.wheelDelta) {
            delta = orgEvent.wheelDelta / 120;
        }
        if (orgEvent.detail) {
            delta = -orgEvent.detail / 3;
        }

        // New school multidimensional scroll (touchpads) deltas
        deltaY = delta;

        // Gecko
        if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
            deltaY = 0;
            deltaX = delta;
        }

        // Webkit
        if (orgEvent.wheelDeltaY !== undefined) {
            deltaY = orgEvent.wheelDeltaY / 120;
        }
        if (orgEvent.wheelDeltaX !== undefined) {
            deltaX = orgEvent.wheelDeltaX / 120;
        }

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

})(jQuery);
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\typeahead.jquery.js
/*version = 4*/
/*!
* typeahead.js 0.10.4
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/

//JQuery v3.0 Compatible

(function ($) {
    var _ = function () {
        "use strict";
        return {
            isMsie: function () {
                return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
            },
            isBlankString: function (str) {
                return !str || /^\s*$/.test(str);
            },
            escapeRegExChars: function (str) {
                return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            },
            isString: function (obj) {
                return typeof obj === "string";
            },
            isNumber: function (obj) {
                return typeof obj === "number";
            },
            isArray: Array.isArray,
            isObject: $.isPlainObject,
            isUndefined: function (obj) {
                return typeof obj === "undefined";
            },
            toStr: function toStr(s) {
                return _.isUndefined(s) || s === null ? "" : s + "";
            },
            bind: $.proxy,
            isFunction: function (obj) {
                if (typeof obj === "function") {
                    return true;
                }
                else {
                    return false;
                }
            },
            each: function (collection, cb) {
                $.each(collection, reverseArgs);
                function reverseArgs(index, value) {
                    return cb(value, index);
                }
            },
            map: $.map,
            filter: $.grep,
            every: function (obj, test) {
                var result = true;
                if (!obj) {
                    return result;
                }
                $.each(obj, function (key, val) {
                    if (!(result = test.call(null, val, key, obj))) {
                        return false;
                    }
                });
                return !!result;
            },
            some: function (obj, test) {
                var result = false;
                if (!obj) {
                    return result;
                }
                $.each(obj, function (key, val) {
                    if (result = test.call(null, val, key, obj)) {
                        return false;
                    }
                });
                return !!result;
            },
            mixin: $.extend,
            getUniqueId: function () {
                var counter = 0;
                return function () {
                    return counter++;
                };
            }(),
            templatify: function templatify(obj) {
                return typeof obj === "function" ? obj : template;
                function template() {
                    return String(obj);
                }
            },
            defer: function (fn) {
                setTimeout(fn, 0);
            },
            debounce: function (func, wait, immediate) {
                var timeout, result;
                return function () {
                    var context = this, args = arguments, later, callNow;
                    later = function () {
                        timeout = null;
                        if (!immediate) {
                            result = func.apply(context, args);
                        }
                    };
                    callNow = immediate && !timeout;
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                    if (callNow) {
                        result = func.apply(context, args);
                    }
                    return result;
                };
            },
            throttle: function (func, wait) {
                var context, args, timeout, result, previous, later;
                previous = 0;
                later = function () {
                    previous = new Date();
                    timeout = null;
                    result = func.apply(context, args);
                };
                return function () {
                    var now = new Date(), remaining = wait - (now - previous);
                    context = this;
                    args = arguments;
                    if (remaining <= 0) {
                        clearTimeout(timeout);
                        timeout = null;
                        previous = now;
                        result = func.apply(context, args);
                    } else if (!timeout) {
                        timeout = setTimeout(later, remaining);
                    }
                    return result;
                };
            },
            noop: function () { }
        };
    }();
    var VERSION = "0.10.4";
    var tokenizers = function () {
        "use strict";
        return {
            nonword: nonword,
            whitespace: whitespace,
            obj: {
                nonword: getObjTokenizer(nonword),
                whitespace: getObjTokenizer(whitespace)
            }
        };
        function whitespace(str) {
            str = _.toStr(str);
            return str ? str.split(/\s+/) : [];
        };
        function nonword(str) {
            str = _.toStr(str);
            return str ? str.split(/\W+/) : [];
        };
        function getObjTokenizer(tokenizer) {
            return function setKey() {
                var args = [].slice.call(arguments, 0);
                return function tokenize(o) {
                    var tokens = [];
                    _.each(args, function (k) {
                        tokens = tokens.concat(tokenizer(_.toStr(o[k])));
                    });
                    return tokens;
                };
            };
        };
    }();
    var LruCache = function () {
        "use strict";
        function LruCache(maxSize) {
            this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
            this.reset();
            if (this.maxSize <= 0) {
                this.set = this.get = $.noop;
            }
        };
        _.mixin(LruCache.prototype, {
            set: function set(key, val) {
                var tailItem = this.list.tail, node;
                if (this.size >= this.maxSize) {
                    this.list.remove(tailItem);
                    delete this.hash[tailItem.key];
                }
                if (node = this.hash[key]) {
                    node.val = val;
                    this.list.moveToFront(node);
                } else {
                    node = new Node(key, val);
                    this.list.add(node);
                    this.hash[key] = node;
                    this.size++;
                }
            },
            get: function get(key) {
                var node = this.hash[key];
                if (node) {
                    this.list.moveToFront(node);
                    return node.val;
                }
            },
            reset: function reset() {
                this.size = 0;
                this.hash = {};
                this.list = new List();
            }
        });
        function List() {
            this.head = this.tail = null;
        };
        _.mixin(List.prototype, {
            add: function add(node) {
                if (this.head) {
                    node.next = this.head;
                    this.head.prev = node;
                }
                this.head = node;
                this.tail = this.tail || node;
            },
            remove: function remove(node) {
                node.prev ? node.prev.next = node.next : this.head = node.next;
                node.next ? node.next.prev = node.prev : this.tail = node.prev;
            },
            moveToFront: function (node) {
                this.remove(node);
                this.add(node);
            }
        });
        function Node(key, val) {
            this.key = key;
            this.val = val;
            this.prev = this.next = null;
        }
        return LruCache;
    }();
    var PersistentStorage = function () {
        "use strict";
        var ls, methods;
        try {
            ls = window.localStorage;
            ls.setItem("~~~", "!");
            ls.removeItem("~~~");
        } catch (err) {
            ls = null;
        }
        function PersistentStorage(namespace) {
            this.prefix = ["__", namespace, "__"].join("");
            this.ttlKey = "__ttl__";
            this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
        };
        if (ls && window.JSON) {
            methods = {
                _prefix: function (key) {
                    return this.prefix + key;
                },
                _ttlKey: function (key) {
                    return this._prefix(key) + this.ttlKey;
                },
                get: function (key) {
                    if (this.isExpired(key)) {
                        this.remove(key);
                    }
                    return decode(ls.getItem(this._prefix(key)));
                },
                set: function (key, val, ttl) {
                    if (_.isNumber(ttl)) {
                        ls.setItem(this._ttlKey(key), encode(now() + ttl));
                    } else {
                        ls.removeItem(this._ttlKey(key));
                    }
                    return ls.setItem(this._prefix(key), encode(val));
                },
                remove: function (key) {
                    ls.removeItem(this._ttlKey(key));
                    ls.removeItem(this._prefix(key));
                    return this;
                },
                clear: function () {
                    var i, key, keys = [], len = ls.length;
                    for (i = 0; i < len; i++) {
                        if ((key = ls.key(i)).match(this.keyMatcher)) {
                            keys.push(key.replace(this.keyMatcher, ""));
                        }
                    }
                    for (i = keys.length; i--;) {
                        this.remove(keys[i]);
                    }
                    return this;
                },
                isExpired: function (key) {
                    var ttl = decode(ls.getItem(this._ttlKey(key)));
                    return _.isNumber(ttl) && now() > ttl ? true : false;
                }
            };
        } else {
            methods = {
                get: _.noop,
                set: _.noop,
                remove: _.noop,
                clear: _.noop,
                isExpired: _.noop
            };
        }
        _.mixin(PersistentStorage.prototype, methods);
        return PersistentStorage;
        function now() {
            return new Date().getTime();
        };
        function encode(val) {
            return JSON.stringify(_.isUndefined(val) ? null : val);
        };
        function decode(val) {
            return JSON.parse(val);
        };
    }();
    var Transport = function () {
        "use strict";
        var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
        function Transport(o) {
            o = o || {};
            this.cancelled = false;
            this.lastUrl = null;
            this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
            this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
            this._cache = o.cache === false ? new LruCache(0) : sharedCache;
        };
        Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
            maxPendingRequests = num;
        };
        Transport.resetCache = function resetCache() {
            sharedCache.reset();
        };
        _.mixin(Transport.prototype, {
            _get: function (url, o, cb) {
                var that = this, jqXhr;
                if (this.cancelled || url !== this.lastUrl) {
                    return;
                }
                if (jqXhr = pendingRequests[url]) {
                    jqXhr.done(done).fail(fail);
                } else if (pendingRequestsCount < maxPendingRequests) {
                    pendingRequestsCount++;
                    pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
                } else {
                    this.onDeckRequestArgs = [].slice.call(arguments, 0);
                }
                function done(resp) {
                    cb && cb(null, resp);
                    that._cache.set(url, resp);
                }
                function fail() {
                    cb && cb(true);
                }
                function always() {
                    pendingRequestsCount--;
                    delete pendingRequests[url];
                    if (that.onDeckRequestArgs) {
                        that._get.apply(that, that.onDeckRequestArgs);
                        that.onDeckRequestArgs = null;
                    }
                }
            },
            get: function (url, o, cb) {
                var resp;
                if (_.isFunction(o)) {
                    cb = o;
                    o = {};
                }
                this.cancelled = false;
                this.lastUrl = url;
                if (resp = this._cache.get(url)) {
                    _.defer(function () {
                        cb && cb(null, resp);
                    });
                } else {
                    this._get(url, o, cb);
                }
                return !!resp;
            },
            cancel: function () {
                this.cancelled = true;
            }
        });
        return Transport;
        function callbackToDeferred(fn) {
            return function customSendWrapper(url, o) {
                var deferred = $.Deferred();
                fn(url, o, onSuccess, onError);
                return deferred;
                function onSuccess(resp) {
                    _.defer(function () {
                        deferred.resolve(resp);
                    });
                }
                function onError(err) {
                    _.defer(function () {
                        deferred.reject(err);
                    });
                }
            };
        };
    }();
    var SearchIndex = function () {
        "use strict";
        function SearchIndex(o) {
            o = o || {};
            if (!o.datumTokenizer || !o.queryTokenizer) {
                $.error("datumTokenizer and queryTokenizer are both required");
            }
            this.datumTokenizer = o.datumTokenizer;
            this.queryTokenizer = o.queryTokenizer;
            this.reset();
        };
        _.mixin(SearchIndex.prototype, {
            bootstrap: function bootstrap(o) {
                this.datums = o.datums;
                this.trie = o.trie;
            },
            add: function (data) {
                var that = this;
                data = _.isArray(data) ? data : [data];
                _.each(data, function (datum) {
                    var id, tokens;
                    id = that.datums.push(datum) - 1;
                    tokens = normalizeTokens(that.datumTokenizer(datum));
                    _.each(tokens, function (token) {
                        var node, chars, ch;
                        node = that.trie;
                        chars = token.split("");
                        while (ch = chars.shift()) {
                            node = node.children[ch] || (node.children[ch] = newNode());
                            node.ids.push(id);
                        }
                    });
                });
            },
            get: function get(query) {
                var that = this, tokens, matches;
                tokens = normalizeTokens(this.queryTokenizer(query));
                _.each(tokens, function (token) {
                    var node, chars, ch, ids;
                    if (matches && matches.length === 0) {
                        return false;
                    }
                    node = that.trie;
                    chars = token.split("");
                    while (node && (ch = chars.shift())) {
                        node = node.children[ch];
                    }
                    if (node && chars.length === 0) {
                        ids = node.ids.slice(0);
                        matches = matches ? getIntersection(matches, ids) : ids;
                    } else {
                        matches = [];
                        return false;
                    }
                });
                return matches ? _.map(unique(matches), function (id) {
                    return that.datums[id];
                }) : [];
            },
            reset: function reset() {
                this.datums = [];
                this.trie = newNode();
            },
            serialize: function serialize() {
                return {
                    datums: this.datums,
                    trie: this.trie
                };
            }
        });
        return SearchIndex;
        function normalizeTokens(tokens) {
            tokens = _.filter(tokens, function (token) {
                return !!token;
            });
            tokens = _.map(tokens, function (token) {
                return token.toLowerCase();
            });
            return tokens;
        };
        function newNode() {
            return {
                ids: [],
                children: {}
            };
        };
        function unique(array) {
            var seen = {}, uniques = [];
            for (var i = 0, len = array.length; i < len; i++) {
                if (!seen[array[i]]) {
                    seen[array[i]] = true;
                    uniques.push(array[i]);
                }
            }
            return uniques;
        };
        function getIntersection(arrayA, arrayB) {
            var ai = 0, bi = 0, intersection = [];
            arrayA = arrayA.sort(compare);
            arrayB = arrayB.sort(compare);
            var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
            while (ai < lenArrayA && bi < lenArrayB) {
                if (arrayA[ai] < arrayB[bi]) {
                    ai++;
                } else if (arrayA[ai] > arrayB[bi]) {
                    bi++;
                } else {
                    intersection.push(arrayA[ai]);
                    ai++;
                    bi++;
                }
            }
            return intersection;
            function compare(a, b) {
                return a - b;
            }
        };
    }();
    var oParser = function () {
        "use strict";
        return {
            local: getLocal,
            prefetch: getPrefetch,
            remote: getRemote
        };
        function getLocal(o) {
            return o.local || null;
        };
        function getPrefetch(o) {
            var prefetch, defaults;
            defaults = {
                url: null,
                thumbprint: "",
                ttl: 24 * 60 * 60 * 1e3,
                filter: null,
                ajax: {}
            };
            if (prefetch = o.prefetch || null) {
                prefetch = _.isString(prefetch) ? {
                    url: prefetch
                } : prefetch;
                prefetch = _.mixin(defaults, prefetch);
                prefetch.thumbprint = VERSION + prefetch.thumbprint;
                prefetch.ajax.type = prefetch.ajax.type || "GET";
                prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
                !prefetch.url && $.error("prefetch requires url to be set");
            }
            return prefetch;
        };
        function getRemote(o) {
            var remote, defaults;
            defaults = {
                url: null,
                cache: true,
                wildcard: "%QUERY",
                replace: null,
                rateLimitBy: "debounce",
                rateLimitWait: 300,
                send: null,
                filter: null,
                ajax: {}
            };
            if (remote = o.remote || null) {
                remote = _.isString(remote) ? {
                    url: remote
                } : remote;
                remote = _.mixin(defaults, remote);
                remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
                remote.ajax.type = remote.ajax.type || "GET";
                remote.ajax.dataType = remote.ajax.dataType || "json";
                delete remote.rateLimitBy;
                delete remote.rateLimitWait;
                !remote.url && $.error("remote requires url to be set");
            }
            return remote;
            function byDebounce(wait) {
                return function (fn) {
                    return _.debounce(fn, wait);
                };
            };
            function byThrottle(wait) {
                return function (fn) {
                    return _.throttle(fn, wait);
                };
            };
        };
    }();
    (function (root) {
        "use strict";
        var old, keys;
        old = root.Bloodhound;
        keys = {
            data: "data",
            protocol: "protocol",
            thumbprint: "thumbprint"
        };
        root.Bloodhound = Bloodhound;
        function Bloodhound(o) {
            if (!o || !o.local && !o.prefetch && !o.remote) {
                $.error("one of local, prefetch, or remote is required");
            }
            this.limit = o.limit || 5;
            this.sorter = getSorter(o.sorter);
            this.dupDetector = o.dupDetector || ignoreDuplicates;
            this.local = oParser.local(o);
            this.prefetch = oParser.prefetch(o);
            this.remote = oParser.remote(o);
            this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
            this.index = new SearchIndex({
                datumTokenizer: o.datumTokenizer,
                queryTokenizer: o.queryTokenizer
            });
            this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
        };
        Bloodhound.noConflict = function noConflict() {
            root.Bloodhound = old;
            return Bloodhound;
        };
        Bloodhound.tokenizers = tokenizers;
        _.mixin(Bloodhound.prototype, {
            _loadPrefetch: function loadPrefetch(o) {
                var that = this, serialized, deferred;
                if (serialized = this._readFromStorage(o.thumbprint)) {
                    this.index.bootstrap(serialized);
                    deferred = $.Deferred().resolve();
                } else {
                    deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
                }
                return deferred;
                function handlePrefetchResponse(resp) {
                    that.clear();
                    that.add(o.filter ? o.filter(resp) : resp);
                    that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
                }
            },
            _getFromRemote: function getFromRemote(query, cb) {
                var that = this, url, uriEncodedQuery;
                if (!this.transport) {
                    return;
                }
                query = query || "";
                uriEncodedQuery = encodeURIComponent(query);
                url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
                return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
                function handleRemoteResponse(err, resp) {
                    err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
                }
            },
            _cancelLastRemoteRequest: function cancelLastRemoteRequest() {
                this.transport && this.transport.cancel();
            },
            _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
                if (this.storage) {
                    this.storage.set(keys.data, data, ttl);
                    this.storage.set(keys.protocol, location.protocol, ttl);
                    this.storage.set(keys.thumbprint, thumbprint, ttl);
                }
            },
            _readFromStorage: function readFromStorage(thumbprint) {
                var stored = {}, isExpired;
                if (this.storage) {
                    stored.data = this.storage.get(keys.data);
                    stored.protocol = this.storage.get(keys.protocol);
                    stored.thumbprint = this.storage.get(keys.thumbprint);
                }
                isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
                return stored.data && !isExpired ? stored.data : null;
            },
            _initialize: function initialize() {
                var that = this, local = this.local, deferred;
                deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
                local && deferred.done(addLocalToIndex);
                this.transport = this.remote ? new Transport(this.remote) : null;
                return this.initPromise = deferred.promise();
                function addLocalToIndex() {
                    that.add(_.isFunction(local) ? local() : local);
                }
            },
            initialize: function initialize(force) {
                return !this.initPromise || force ? this._initialize() : this.initPromise;
            },
            add: function add(data) {
                this.index.add(data);
            },
            get: function get(query, cb) {
                var that = this, matches = [], cacheHit = false;
                matches = this.index.get(query);
                matches = this.sorter(matches).slice(0, this.limit);
                matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
                if (!cacheHit) {
                    (matches.length > 0 || !this.transport) && cb && cb(matches);
                }
                function returnRemoteMatches(remoteMatches) {
                    var matchesWithBackfill = matches.slice(0);
                    _.each(remoteMatches, function (remoteMatch) {
                        var isDuplicate;
                        isDuplicate = _.some(matchesWithBackfill, function (match) {
                            return that.dupDetector(remoteMatch, match);
                        });
                        !isDuplicate && matchesWithBackfill.push(remoteMatch);
                        return matchesWithBackfill.length < that.limit;
                    });
                    cb && cb(that.sorter(matchesWithBackfill));
                }
            },
            clear: function clear() {
                this.index.reset();
            },
            clearPrefetchCache: function clearPrefetchCache() {
                this.storage && this.storage.clear();
            },
            clearRemoteCache: function clearRemoteCache() {
                this.transport && Transport.resetCache();
            },
            ttAdapter: function ttAdapter() {
                return _.bind(this.get, this);
            }
        });
        return Bloodhound;
        function getSorter(sortFn) {
            return _.isFunction(sortFn) ? sort : noSort;
            function sort(array) {
                return array.sort(sortFn);
            };
            function noSort(array) {
                return array;
            };
        };
        function ignoreDuplicates() {
            return false;
        };
    })(this);
    var html = function () {
        return {
            wrapper: '<div class="twitter-typeahead"></div>',
            dropdown: '<div class="tt-dropdown-menu"></div>',
            dataset: '<div class="tt-dataset-%CLASS%"></div>',
            suggestions: '<ul role="listbox" class="tt-suggestions autocomplete-list"></ul>',
            suggestion: '<li role="option" aria-selected="false" class="tt-suggestion autocomplete-item"></li>'
        };
    }();
    var css = function () {
        "use strict";
        var css;
        if ($(".redesign-search-page").length === 0 && $(".job-search-hero-block").length === 0 && $(".reinvent-locations-hero-module").length === 0) {
            css = {
                wrapper: {
                    position: "relative",
                    display: "inline-block"
                },
                hint: {
                    position: "absolute",
                    top: "0",
                    left: "0",
                    borderColor: "transparent",
                    boxShadow: "none",
                    opacity: "1"
                },
                input: {
                    position: "relative",
                    verticalAlign: "top",
                    backgroundColor: "transparent"
                },
                inputWithNoHint: {
                    position: "relative",
                    verticalAlign: "top"
                },
                dropdown: {
                    position: "absolute",
                    top: "100%",
                    left: "0",
                    zIndex: "100",
                    display: "none"
                },
                suggestions: {
                    display: "block"
                },
                suggestion: {
                    whiteSpace: "nowrap",
                    cursor: "pointer"
                },
                suggestionChild: {
                    whiteSpace: "normal"
                },
                ltr: {
                    left: "0",
                    right: "auto"
                },
                rtl: {
                    left: "auto",
                    right: " 0"
                }
            };
        }
        else {
            css = {
                wrapper: {
                    position: "relative",
                    display: "initial"
                },
                hint: {
                    position: "relative",
                    top: "0",
                    left: "0",
                    borderColor: "transparent",
                    boxShadow: "none",
                    opacity: "1",
                    display: "none"
                },
                input: {
                    position: "relative",
                    verticalAlign: "top",
                    backgroundColor: "white"
                },
                inputWithNoHint: {
                    position: "relative",
                    verticalAlign: "top"
                },
                dropdown: {
                    position: "relative",
                    top: "100%",
                    left: "0",
                    zIndex: "100"
                },
                suggestions: {
                    display: "block"
                },
                suggestion: {
                    whiteSpace: "nowrap",
                    cursor: "pointer"
                },
                suggestionChild: {
                    whiteSpace: "normal"
                },
                ltr: {
                    left: "0",
                    right: "auto"
                },
                rtl: {
                    left: "auto",
                    right: " 0"
                }
            };
        }

        if (_.isMsie()) {
            _.mixin(css.input, {
                backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
            });
        }
        if (_.isMsie() && _.isMsie() <= 7) {
            _.mixin(css.input, {
                marginTop: "-1px"
            });
        }
        return css;
    }();
    var EventBus = function () {
        "use strict";
        var namespace = "typeahead:";
        function EventBus(o) {
            if (!o || !o.el) {
                $.error("EventBus initialized without el");
            }
            this.$el = $(o.el);
        }
        _.mixin(EventBus.prototype, {
            trigger: function (type) {
                var args = [].slice.call(arguments, 1);
                this.$el.trigger(namespace + type, args);
            }
        });
        return EventBus;
    }();
    var EventEmitter = function () {
        "use strict";
        var splitter = /\s+/, nextTick = getNextTick();
        return {
            onSync: onSync,
            onAsync: onAsync,
            off: off,
            trigger: trigger
        };
        function on(method, types, cb, context) {
            var type;
            if (!cb) {
                return this;
            }
            types = types.split(splitter);
            cb = context ? bindContext(cb, context) : cb;
            this._callbacks = this._callbacks || {};
            while (type = types.shift()) {
                this._callbacks[type] = this._callbacks[type] || {
                    sync: [],
                    async: []
                };
                this._callbacks[type][method].push(cb);
            }
            return this;
        };
        function onAsync(types, cb, context) {
            return on.call(this, "async", types, cb, context);
        };
        function onSync(types, cb, context) {
            return on.call(this, "sync", types, cb, context);
        };
        function off(types) {
            var type;
            if (!this._callbacks) {
                return this;
            }
            types = types.split(splitter);
            while (type = types.shift()) {
                delete this._callbacks[type];
            }
            return this;
        };
        function trigger(types) {
            var type, callbacks, args, syncFlush, asyncFlush;
            if (!this._callbacks) {
                return this;
            }
            types = types.split(splitter);
            args = [].slice.call(arguments, 1);
            while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
                syncFlush = getFlush(callbacks.sync, this, [type].concat(args));
                asyncFlush = getFlush(callbacks.async, this, [type].concat(args));
                syncFlush() && nextTick(asyncFlush);
            }
            return this;
        };
        function getFlush(callbacks, context, args) {
            return flush;
            function flush() {
                var cancelled;
                for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
                    cancelled = callbacks[i].apply(context, args) === false;
                }
                return !cancelled;
            }
        };
        function getNextTick() {
            var nextTickFn;
            if (window.setImmediate) {
                nextTickFn = function nextTickSetImmediate(fn) {
                    setImmediate(function () {
                        fn();
                    });
                };
            } else {
                nextTickFn = function nextTickSetTimeout(fn) {
                    setTimeout(function () {
                        fn();
                    }, 0);
                };
            }
            return nextTickFn;
        };
        function bindContext(fn, context) {
            return fn.bind ? fn.bind(context) : function () {
                fn.apply(context, [].slice.call(arguments, 0));
            };
        };
    }();
    var highlight = function (doc) {
        "use strict";
        var defaults = {
            node: null,
            pattern: null,
            tagName: "strong",
            className: null,
            wordsOnly: false,
            caseSensitive: false
        };

        return function hightlight(o) {
            var regex;
            o = _.mixin({}, defaults, o);
            if (!o.node || !o.pattern) {
                return;
            }
            o.pattern = _.isArray(o.pattern) ? o.pattern : [o.pattern];
            regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
            traverse(o.node, hightlightTextNode);
            function hightlightTextNode(textNode) {
                var match, patternNode, wrapperNode;
                if (match = regex.exec(textNode.data)) {
                    wrapperNode = doc.createElement(o.tagName);
                    o.className && (wrapperNode.className = o.className);
                    patternNode = textNode.splitText(match.index);
                    patternNode.splitText(match[0].length);
                    wrapperNode.appendChild(patternNode.cloneNode(true));
                    textNode.parentNode.replaceChild(wrapperNode, patternNode);
                }
                return !!match;
            };
            function traverse(el, hightlightTextNode) {
                var childNode, TEXT_NODE_TYPE = 3;
                for (var i = 0; i < el.childNodes.length; i++) {
                    childNode = el.childNodes[i];
                    if (childNode.nodeType === TEXT_NODE_TYPE) {
                        i += hightlightTextNode(childNode) ? 1 : 0;
                    } else {
                        traverse(childNode, hightlightTextNode);
                    }
                }
            };
        };
        function getRegex(patterns, caseSensitive, wordsOnly) {
            var escapedPatterns = [], regexStr;
            for (var i = 0, len = patterns.length; i < len; i++) {
                escapedPatterns.push(_.escapeRegExChars(patterns[i]));
            }
            regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
            return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
        };
    }(window.document);
    var Input = function () {
        "use strict";
        var specialKeyCodeMap;
        specialKeyCodeMap = {
            9: "tab",
            27: "esc",
            37: "left",
            39: "right",
            13: "enter",
            38: "up",
            40: "down"
        };
        function Input(o) {
            var that = this, onBlur, onFocus, onKeydown, onInput;
            o = o || {};
            if (!o.input) {
                $.error("input is missing");
            }
            onBlur = _.bind(this._onBlur, this);
            onFocus = _.bind(this._onFocus, this);
            onKeydown = _.bind(this._onKeydown, this);
            onInput = _.bind(this._onInput, this);
            this.$hint = $(o.hint);
            this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
            if (this.$hint.length === 0) {
                this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
            }
            if (!_.isMsie()) {
                this.$input.on("input.tt", onInput);
            } else {
                this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function ($e) {
                    if (specialKeyCodeMap[$e.which || $e.keyCode]) {
                        return;
                    }
                    _.defer(_.bind(that._onInput, that, $e));
                });
            }
            this.query = this.$input.val();
            this.$overflowHelper = buildOverflowHelper(this.$input);
        };
        Input.normalizeQuery = function (str) {
            return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
        };
        _.mixin(Input.prototype, EventEmitter, {
            _onBlur: function onBlur() {
                this.resetInputValue();
                this.trigger("blurred");
            },
            _onFocus: function onFocus() {
                this.trigger("focused");
            },
            _onKeydown: function onKeydown($e) {
                var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
                this._managePreventDefault(keyName, $e);
                if (keyName && this._shouldTrigger(keyName, $e)) {
                    this.trigger(keyName + "Keyed", $e);
                }
            },
            _onInput: function onInput() {
                this._checkInputValue();
            },
            _managePreventDefault: function managePreventDefault(keyName, $e) {
                var preventDefault, hintValue, inputValue;
                switch (keyName) {
                    case "tab":
                        hintValue = this.getHint();
                        inputValue = this.getInputValue();
                        preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
                        break;

                    case "up":
                    case "down":
                        preventDefault = !withModifier($e);
                        break;

                    default:
                        preventDefault = false;
                }
                preventDefault && $e.preventDefault();
            },
            _shouldTrigger: function shouldTrigger(keyName, $e) {
                var trigger;
                switch (keyName) {
                    case "tab":
                        trigger = !withModifier($e);
                        break;

                    default:
                        trigger = true;
                }
                return trigger;
            },
            _checkInputValue: function checkInputValue() {
                var inputValue, areEquivalent, hasDifferentWhitespace;
                inputValue = this.getInputValue();
                areEquivalent = areQueriesEquivalent(inputValue, this.query);
                hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
                this.query = inputValue;
                if (!areEquivalent) {
                    this.trigger("queryChanged", this.query);
                } else if (hasDifferentWhitespace) {
                    this.trigger("whitespaceChanged", this.query);
                }
            },
            focus: function focus() {
                this.$input.trigger("focus");
            },
            blur: function blur() {
                this.$input.trigger("blur");
            },
            getQuery: function getQuery() {
                return this.query;
            },
            setQuery: function setQuery(query) {
                this.query = query;
            },
            getInputValue: function getInputValue() {
                return this.$input.val();
            },
            setInputValue: function setInputValue(value, silent) {
                this.$input.val(value);
                silent ? this.clearHint() : this._checkInputValue();
            },
            resetInputValue: function resetInputValue() {
                this.setInputValue(this.query, true);
            },
            getHint: function getHint() {
                return this.$hint.val();
            },
            setHint: function setHint(value) {
                this.$hint.val(value);
            },
            clearHint: function clearHint() {
                this.setHint("");
            },
            clearHintIfInvalid: function clearHintIfInvalid() {
                var val, hint, valIsPrefixOfHint, isValid;
                val = this.getInputValue();
                hint = this.getHint();
                valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
                isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
                !isValid && this.clearHint();
            },
            getLanguageDirection: function getLanguageDirection() {
                return (this.$input.css("direction") || "ltr").toLowerCase();
            },
            hasOverflow: function hasOverflow() {
                var constraint = this.$input.width() - 2;
                this.$overflowHelper.text(this.getInputValue());
                return this.$overflowHelper.width() >= constraint;
            },
            isCursorAtEnd: function () {
                var valueLength, selectionStart, range;
                valueLength = this.$input.val().length;
                selectionStart = this.$input[0].selectionStart;
                if (_.isNumber(selectionStart)) {
                    return selectionStart === valueLength;
                } else if (document.selection) {
                    range = document.selection.createRange();
                    range.moveStart("character", -valueLength);
                    return valueLength === range.text.length;
                }
                return true;
            },
            destroy: function destroy() {
                this.$hint.off(".tt");
                this.$input.off(".tt");
                this.$hint = this.$input = this.$overflowHelper = null;
            }
        });
        return Input;
        function buildOverflowHelper($input) {
            return $('<pre aria-hidden="true"></pre>').css({
                position: "absolute",
                visibility: "hidden",
                whiteSpace: "pre",
                fontFamily: $input.css("font-family"),
                fontSize: $input.css("font-size"),
                fontStyle: $input.css("font-style"),
                fontVariant: $input.css("font-variant"),
                fontWeight: $input.css("font-weight"),
                wordSpacing: $input.css("word-spacing"),
                letterSpacing: $input.css("letter-spacing"),
                textIndent: $input.css("text-indent"),
                textRendering: $input.css("text-rendering"),
                textTransform: $input.css("text-transform")
            }).insertAfter($input);
        };
        function areQueriesEquivalent(a, b) {
            return Input.normalizeQuery(a) === Input.normalizeQuery(b);
        };
        function withModifier($e) {
            return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
        };
    }();
    var Dataset = function () {
        "use strict";
        var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
        function Dataset(o) {
            o = o || {};
            o.templates = o.templates || {};
            if (!o.source) {
                $.error("missing source");
            }
            if (o.name && !isValidName(o.name)) {
                $.error("invalid dataset name: " + o.name);
            }
            this.query = null;
            this.highlight = !!o.highlight;
            this.name = o.name || _.getUniqueId();
            this.source = o.source;
            this.displayFn = getDisplayFn(o.display || o.displayKey);
            this.templates = getTemplates(o.templates, this.displayFn);
            this.$el = $(html.dataset.replace("%CLASS%", this.name));
        };
        Dataset.extractDatasetName = function extractDatasetName(el) {
            return $(el).data(datasetKey);
        };
        Dataset.extractValue = function extractDatum(el) {
            return $(el).data(valueKey);
        };
        Dataset.extractDatum = function extractDatum(el) {
            return $(el).data(datumKey);
        };
        _.mixin(Dataset.prototype, EventEmitter, {
            _render: function render(query, suggestions) {
                if (!this.$el) {
                    return;
                }
                var that = this, hasSuggestions;
                this.$el.empty();
                hasSuggestions = suggestions && suggestions.length;
                if (!hasSuggestions && this.templates.empty) {
                    this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
                } else if (hasSuggestions) {
                    this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
                }
                this.trigger("rendered");
                function getEmptyHtml() {
                    return that.templates.empty({
                        query: query,
                        isEmpty: true
                    });
                }
                function getSuggestionsHtml() {
                    var $suggestions, nodes;
                    $suggestions = $(html.suggestions).css(css.suggestions);
                    nodes = _.map(suggestions, getSuggestionNode);
                    $suggestions.append.apply($suggestions, nodes);
                    if (($('.redesign-search-page .search-hero-keywords').is(':focus')) || ($('.job-search-hero-block .search-bar').is(':focus')) || $('.reinvent-locations-hero-module .reinvent-location-keywords').is(':focus')) {
                        that.highlight && highlight({
                            className: "tt-highlight corporate-regular",
                            node: $suggestions[0],
                            pattern: query
                        });
                    }
                    else {
                        that.highlight && highlight({
                            className: "tt-highlight",
                            node: $suggestions[0],
                            pattern: query
                        });
                    }
                    return $suggestions;
                    function getSuggestionNode(suggestion) {
                        var $el;
                        $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
                        $el.children().each(function () {
                            $(this).css(css.suggestionChild);
                        });
                        return $el;
                    }
                }
                function getHeaderHtml() {
                    return that.templates.header({
                        query: query,
                        isEmpty: !hasSuggestions
                    });
                }
                function getFooterHtml() {
                    return that.templates.footer({
                        query: query,
                        isEmpty: !hasSuggestions
                    });
                }
            },
            getRoot: function getRoot() {
                return this.$el;
            },
            update: function update(query) {
                var that = this;
                this.query = query;
                this.canceled = false;
                this.source(query, render);
                function render(suggestions) {
                    if (!that.canceled && query === that.query) {
                        that._render(query, suggestions);
                    }
                }
            },
            cancel: function cancel() {
                this.canceled = true;
            },
            clear: function clear() {
                this.cancel();
                this.$el.empty();
                this.trigger("rendered");
            },
            isEmpty: function isEmpty() {
                return this.$el.is(":empty");
            },
            destroy: function destroy() {
                this.$el = null;
            }
        });
        return Dataset;
        function getDisplayFn(display) {
            display = display || "value";
            return _.isFunction(display) ? display : displayFn;
            function displayFn(obj) {
                return obj[display];
            }
        };
        function getTemplates(templates, displayFn) {
            return {
                empty: templates.empty && _.templatify(templates.empty),
                header: templates.header && _.templatify(templates.header),
                footer: templates.footer && _.templatify(templates.footer),
                suggestion: templates.suggestion || suggestionTemplate
            };
            function suggestionTemplate(context) {
                // Job Search Hero - change tags for smart suggestion
                if (($(".job-search-hero-block")).is(":visible")) {
                    return "<a class='suggestion-item'>" + displayFn(context) + "</a>";
                }
                else if (($(".about-hero-wrapper")).is(":visible")) {
                    return "<a class='suggestion-item'>" + displayFn(context) + "</a>";
                }
                else if ($('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    return "<p>" + "<strong>" + displayFn(context) + "</strong>" + "</p>";
                }
                else if ($('.reinvent-locations-hero-module .reinvent-location-keywords').is(':focus')) {
                    return "<p>" + "<strong>" + displayFn(context) + "</strong>" + "</p>";
                }
                else {
                    return "<p>" + displayFn(context) + "</p>";
                }
            }
        };
        function isValidName(str) {
            return /^[_a-zA-Z0-9-]+$/.test(str);
        };
    }();
    var Dropdown = function () {
        "use strict";
        function Dropdown(o) {
            var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
            o = o || {};
            if (!o.menu) {
                $.error("menu is required");
            }
            this.isOpen = false;
            this.isEmpty = true;
            this.datasets = _.map(o.datasets, initializeDataset);
            onSuggestionClick = _.bind(this._onSuggestionClick, this);
            onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
            onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
            this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
            _.each(this.datasets, function (dataset) {
                that.$menu.append(dataset.getRoot());
                dataset.onSync("rendered", that._onRendered, that);
            });
        };
        _.mixin(Dropdown.prototype, EventEmitter, {
            _onSuggestionClick: function onSuggestionClick($e) {
                this.trigger("suggestionClicked", $($e.currentTarget));
            },
            _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
                this._removeCursor();
                this._setCursor($($e.currentTarget), true);
            },
            _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
                this._removeCursor();
            },
            _onRendered: function onRendered() {
                this.isEmpty = _.every(this.datasets, isDatasetEmpty);
                this.isEmpty ? this._hide() : this.isOpen && this._show();
                this.trigger("datasetRendered");
                function isDatasetEmpty(dataset) {
                    return dataset.isEmpty();
                }
            },
            _hide: function () {
                this.$menu.hide();
            },
            _show: function () {
                this.$menu.css("display", "block");

                if ($('.reinvent-location-keywords').length === 0) {
                    if ($('.redesign-search-page .tt-suggestions').is(':visible')) {
                        var isShowViewAll = ($('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle") !== null && typeof $('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle") !== 'undefined') ? $('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle").toLowerCase() : "";

                        if (isShowViewAll === "true") {
                            var viewAllKeyword = $(".redesign-search-page .tt-input.search-hero-keywords").val();
                            var viewAllContainer = ".tt-suggestion.view-all-text-container";
                            var $viewAllAttr = $('.search-hero-keywords').attr('data-view-all-results');
                            var $viewAllText = $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text');
                            var $viewAllArrow = $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .arrow-strong');

                            jQuery('<li/>', {
                                class: 'tt-suggestion view-all-text-container'
                            }).appendTo('.redesign-search-page .tt-dataset-keywordSuggestions .tt-suggestions');
                            jQuery('<p/>', {
                                class: 'view-all-container',
                            }).appendTo(viewAllContainer);
                            jQuery('<a/>', {
                                class: 'view-all-text cta d-inline corporate-regular',
                                html: $viewAllAttr
                            }).appendTo('.tt-suggestion.view-all-text-container .view-all-container');
                            jQuery('<a/>', {
                                class: 'arrow-strong cta-arrow corporate-regular'
                            }).appendTo('.tt-suggestion.view-all-text-container .view-all-container');

                            $(viewAllContainer).attr('data-attribute-view-all-keyword', viewAllKeyword);
                            $viewAllText.attr('data-analytics-link-name', $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text').text().toLowerCase());
                            $viewAllText.attr('data-analytics-content-type', 'search activity');
                            $viewAllArrow.attr('data-analytics-link-name', $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text').text().toLowerCase());
                            $viewAllArrow.attr('data-analytics-content-type', 'search activity');
                        }
                    }
                    else if ($('.job-search-hero-block-form .tt-suggestions').is(':visible')) {

                        if ($('.job-search-hero-block .tt-dataset-keywordSuggestions .tt-suggestions').is(':visible')) {
                            var smartSuggestValue = $('.job-search-hero-block .tt-suggestions .tt-suggestion .suggestion-item');

                            for (var i = 0; i < smartSuggestValue.length; i++) {
                                smartSuggestValue[i].setAttribute("data-analytics-link-name", smartSuggestValue[i].innerText.toLowerCase());
                                smartSuggestValue[i].setAttribute("data-analytics-content-type", "careers job search");
                            }
                        }
                    }
                }
            },
            _getSuggestions: function getSuggestions() {
                $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').on("mouseenter", function () {
                    $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').removeAttr('id', 'selectedOption');
                    $(this).addClass('selected');
                }).on("mouseleave",
                    function () {
                        $(this).removeClass("selected");
                    }
                );
                return this.$menu.find(".tt-suggestion");
            },
            _getCursor: function getCursor() {
                return this.$menu.find(".tt-cursor").first();
            },
            _setCursor: function setCursor($el, silent) {
                $el.first().addClass("tt-cursor");
                !silent && this.trigger("cursorMoved");
            },
            _removeCursor: function removeCursor() {
                this._getCursor().removeClass("tt-cursor");
            },
            _moveCursor: function moveCursor(increment) {
                if (!$('.redesign-search-page .tt-dataset-keywordRecentSearches').is(':visible')) {
                    if (!$('.job-search-hero-block .tt-dataset-keywordRecentSearches').is(':visible')) {
                        var $suggestions, $oldCursor, newCursorIndex, $newCursor;
                        if (!this.isOpen) {
                            return;
                        }
                        $oldCursor = this._getCursor();
                        $suggestions = this._getSuggestions();
                        this._removeCursor();
                        newCursorIndex = $suggestions.index($oldCursor) + increment;
                        newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
                        if (newCursorIndex === -1) {
                            this.trigger("cursorRemoved");
                            return;
                        } else if (newCursorIndex < -1) {
                            newCursorIndex = $suggestions.length - 1;
                        }
                        this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
                        this._ensureVisible($newCursor);
                    }
                }
            },
            _ensureVisible: function ensureVisible($el) {
                var elTop, elBottom, menuScrollTop, menuHeight;
                elTop = $el.position().top;
                elBottom = elTop + $el.outerHeight(true);
                menuScrollTop = this.$menu.scrollTop();
                menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
                if (elTop < 0) {
                    this.$menu.scrollTop(menuScrollTop + elTop);
                } else if (menuHeight < elBottom) {
                    this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
                }
            },
            close: function close() {
                if (this.isOpen) {
                    this.isOpen = false;
                    this._removeCursor();
                    this._hide();
                    this.trigger("closed");
                }
            },
            open: function open() {
                if (!this.isOpen) {
                    this.isOpen = true;
                    !this.isEmpty && this._show();
                    this.trigger("opened");
                }
            },
            setLanguageDirection: function setLanguageDirection(dir) {
                this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
            },
            moveCursorUp: function moveCursorUp() {
                this._moveCursor(-1);
            },
            moveCursorDown: function moveCursorDown() {
                this._moveCursor(+1);
            },
            getDatumForSuggestion: function getDatumForSuggestion($el) {
                var datum = null;
                var $suggestionInnerText = "";
                var $suggestionTextForAnalytics = "";
                if ($el.length) {
                    datum = {
                        raw: Dataset.extractDatum($el),
                        value: Dataset.extractValue($el),
                        datasetName: Dataset.extractDatasetName($el)
                    };

                    var $searchHeroSuggestion = $('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p');
                    $searchHeroSuggestion.attr('data-analytics-content-type', 'search activity');
                    for (var counter = 0; counter < $('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p').length; counter++) {
                        $suggestionInnerText = $searchHeroSuggestion[counter].innerText;
                        $suggestionTextForAnalytics = $searchHeroSuggestion[counter];
                        $suggestionTextForAnalytics.setAttribute('data-analytics-link-name', $suggestionInnerText.toLowerCase());
                    }

                    if ($('.reinvent-location-hero-content-container').length !== 0) {
                        var $locationHeroSuggestion = $('.reinvent-location-hero-content-container .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p');
                        var $locationResultBlock = $(".reinvent-location-result-area");
                        var $reinventLocationModule = $('.reinvent-locations-hero-module');

                        $locationHeroSuggestion.attr('data-analytics-content-type', 'engagement');
                        $locationHeroSuggestion.attr('data-linktype', 'engagement');

                        for (var index = 0; index < $locationHeroSuggestion.length; index++) {
                            $suggestionInnerText = $locationHeroSuggestion[index].innerText;
                            $suggestionTextForAnalytics = $locationHeroSuggestion[index];
                            $suggestionTextForAnalytics.setAttribute('data-analytics-link-name', $suggestionInnerText.toLowerCase());
                            if ($locationResultBlock.length === 0 && $reinventLocationModule.attr('data-attribute-hero-home-link') !== "") {
                                $suggestionTextForAnalytics.setAttribute('href', $reinventLocationModule.attr('data-attribute-hero-home-link').replace('{0}', siteName));
                            }
                        }
                    }
                }
                return datum;
            },
            getDatumForCursor: function getDatumForCursor() {
                return this.getDatumForSuggestion(this._getCursor().first());
            },
            getDatumForTopSuggestion: function getDatumForTopSuggestion() {
                return this.getDatumForSuggestion(this._getSuggestions().first());
            },
            update: function update(query) {
                _.each(this.datasets, updateDataset);
                function updateDataset(dataset) {
                    dataset.update(query);
                }
            },
            empty: function empty() {
                _.each(this.datasets, clearDataset);
                this.isEmpty = true;
                function clearDataset(dataset) {
                    dataset.clear();
                }
            },
            isVisible: function isVisible() {
                return this.isOpen && !this.isEmpty;
            },
            destroy: function destroy() {
                this.$menu.off(".tt");
                this.$menu = null;
                _.each(this.datasets, destroyDataset);
                function destroyDataset(dataset) {
                    dataset.destroy();
                }
            }
        });
        return Dropdown;
        function initializeDataset(oDataset) {
            return new Dataset(oDataset);
        };
    }();
    var Typeahead = function () {
        "use strict";
        var attrsKey = "ttAttrs";
        function Typeahead(o) {
            var $menu, $input, $hint;
            o = o || {};
            if (!o.input) {
                $.error("missing input");
            }
            this.isActivated = false;
            this.autoselect = !!o.autoselect;
            this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
            this.$node = buildDom(o.input, o.withHint);
            $menu = this.$node.find(".tt-dropdown-menu");
            $input = this.$node.find(".tt-input");
            $hint = this.$node.find(".tt-hint");
            $input.on("blur.tt", function ($e) {
                var active, isActive, hasActive;
                active = document.activeElement;
                isActive = $menu.is(active);
                hasActive = $menu.has(active).length > 0;
                if (_.isMsie() && (isActive || hasActive)) {
                    $e.preventDefault();
                    $e.stopImmediatePropagation();
                    _.defer(function () {
                        $input.trigger("focus");
                    });
                }
            });
            $menu.on("mousedown.tt", function ($e) {
                $e.preventDefault();
            });
            this.eventBus = o.eventBus || new EventBus({
                el: $input
            });
            this.dropdown = new Dropdown({
                menu: $menu,
                datasets: o.datasets
            }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
            this.input = new Input({
                input: $input,
                hint: $hint
            }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
            this._setLanguageDirection();
        };
        _.mixin(Typeahead.prototype, {
            _onSuggestionClicked: function onSuggestionClicked(type, $el) {
                var datum;
                if (datum = this.dropdown.getDatumForSuggestion($el)) {
                    this._select(datum);
                }
            },
            _onCursorMoved: function onCursorMoved() {
                var datum = this.dropdown.getDatumForCursor();
                this.input.setInputValue(datum.value, true);
                this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
            },
            _onCursorRemoved: function onCursorRemoved() {
                this.input.resetInputValue();
                this._updateHint();
            },
            _onDatasetRendered: function onDatasetRendered() {
                this._updateHint();
            },
            _onOpened: function onOpened() {
                this._updateHint();
                this.eventBus.trigger("opened");
            },
            _onClosed: function onClosed() {
                this.input.clearHint();
                this.eventBus.trigger("closed");
            },
            _onFocused: function onFocused() {
                this.isActivated = true;
                this.dropdown.open();
            },
            _onBlurred: function onBlurred() {
                this.isActivated = false;
                this.dropdown.empty();
                this.dropdown.close();
            },
            _onEnterKeyed: function onEnterKeyed(type, $e) {
                var cursorDatum, topSuggestionDatum;
                cursorDatum = this.dropdown.getDatumForCursor();
                topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();

                if (cursorDatum) {
                    this._select(cursorDatum);
                    $e.preventDefault();
                } else if (this.autoselect && topSuggestionDatum) {
                    this._select(topSuggestionDatum);
                    $e.preventDefault();
                }
            },
            _onTabKeyed: function onTabKeyed(type, $e) {
                var datum;
                if (datum = this.dropdown.getDatumForCursor()) {
                    this._select(datum);
                    $e.preventDefault();
                } else {
                    this._autocomplete(true);
                }
            },
            _onEscKeyed: function onEscKeyed() {
                this.dropdown.close();
                this.input.resetInputValue();
            },
            _onUpKeyed: function onUpKeyed() {
                var query = this.input.getQuery();
                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
                this.dropdown.open();
                if ($('.tt-suggestion.view-all-text-container').length > 1) {
                    $('.tt-suggestion.view-all-text-container')[0].remove();
                }

            },
            _onDownKeyed: function onDownKeyed() {
                var query = this.input.getQuery();
                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
                this.dropdown.open();
                if ($('.tt-suggestion.view-all-text-container').length > 1) {
                    $('.tt-suggestion.view-all-text-container')[0].remove();
                }
            },
            _onLeftKeyed: function onLeftKeyed() {
                this.dir === "rtl" && this._autocomplete();
            },
            _onRightKeyed: function onRightKeyed() {
                if (!$('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    if (!$('.job-search-hero-block .search-bar').is(':focus')) {
                        this.dir === "ltr" && this._autocomplete();
                    }
                }
            },
            _onQueryChanged: function onQueryChanged(e, query) {
                this.input.clearHintIfInvalid();
                query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
                this.dropdown.open();
                this._setLanguageDirection();
            },
            _onWhitespaceChanged: function onWhitespaceChanged() {
                this._updateHint();
                this.dropdown.open();
            },
            _setLanguageDirection: function setLanguageDirection() {
                var dir;
                if (this.dir !== (dir = this.input.getLanguageDirection())) {
                    this.dir = dir;
                    this.$node.css("direction", dir);
                    this.dropdown.setLanguageDirection(dir);
                }
            },
            _updateHint: function updateHint() {
                var datum, val, query, escapedQuery, frontMatchRegEx, match;
                datum = this.dropdown.getDatumForTopSuggestion();
                if (!$('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    if (!$('.job-search-hero-block .search-bar').is(':focus')) {
                        if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
                            val = this.input.getInputValue();
                            query = Input.normalizeQuery(val);
                            escapedQuery = _.escapeRegExChars(query);
                            frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
                            match = frontMatchRegEx.exec(datum.value);
                            match ? this.input.setHint(val + match[1]) : this.input.clearHint();
                        } else {
                            this.input.clearHint();
                        }
                    }
                }
            },
            _autocomplete: function autocomplete(laxCursor) {
                var hint, query, isCursorAtEnd, datum;
                hint = this.input.getHint();
                query = this.input.getQuery();
                isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
                if (hint && query !== hint && isCursorAtEnd) {
                    datum = this.dropdown.getDatumForTopSuggestion();
                    datum && this.input.setInputValue(datum.value);
                    this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
                }
            },
            _select: function select(datum) {
                this.input.setQuery(datum.value);
                this.input.setInputValue(datum.value, true);
                this._setLanguageDirection();
                this.eventBus.trigger("selected", datum.raw, datum.datasetName);
                this.dropdown.close();
                _.defer(_.bind(this.dropdown.empty, this.dropdown));
            },
            open: function open() {
                this.dropdown.open();
            },
            close: function close() {
                this.dropdown.close();
            },
            setVal: function setVal(val) {
                val = _.toStr(val);
                if (this.isActivated) {
                    this.input.setInputValue(val);
                } else {
                    this.input.setQuery(val);
                    this.input.setInputValue(val, true);
                }
                this._setLanguageDirection();
            },
            getVal: function getVal() {
                return this.input.getQuery();
            },
            destroy: function destroy() {
                this.input.destroy();
                this.dropdown.destroy();
                destroyDomStructure(this.$node);
                this.$node = null;
            }
        });
        return Typeahead;
        function buildDom(input, withHint) {
            var $input, $wrapper, $dropdown, $hint;
            $input = $(input);
            $wrapper = $(html.wrapper).css(css.wrapper);
            $dropdown = $(html.dropdown).css(css.dropdown);
            $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
            $hint.val("").removeData().addClass("tt-hint").prop("readonly", true).prop("required", false).removeAttr("name placeholder").attr({
                autocomplete: "off",
                spellcheck: "false",
                id: "search-form-clone"
            });
            $input.data(attrsKey, {
                dir: $input.attr("dir"),
                autocomplete: $input.attr("autocomplete"),
                spellcheck: $input.attr("spellcheck"),
                style: $input.attr("style")
            });
            $input.addClass("tt-input").attr({
                autocomplete: "off",
                spellcheck: false
            }).css(withHint ? css.input : css.inputWithNoHint);
            try {
                !$input.attr("dir") && $input.attr("dir", "auto");
            } catch (e) { }
            return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
        };
        function getBackgroundStyles($el) {
            return {
                backgroundAttachment: $el.css("background-attachment"),
                backgroundClip: $el.css("background-clip"),
                backgroundColor: $el.css("background-color"),
                backgroundImage: $el.css("background-image"),
                backgroundOrigin: $el.css("background-origin"),
                backgroundPosition: $el.css("background-position"),
                backgroundRepeat: $el.css("background-repeat"),
                backgroundSize: $el.css("background-size")
            };
        };
        function destroyDomStructure($node) {
            var $input = $node.find(".tt-input");
            _.each($input.data(attrsKey), function (val, key) {
                _.isUndefined(val) ? $input.prop(key, false) : $input.attr(key, val);
            });
            $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
            $node.remove();
        };
    }();
    (function () {
        "use strict";
        var old, typeaheadKey, methods;
        old = $.fn.typeahead;
        typeaheadKey = "ttTypeahead";
        methods = {
            initialize: function initialize(o, datasets) {
                datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
                o = o || {};
                return this.each(attach);
                function attach() {
                    var $input = $(this), eventBus, typeahead;
                    _.each(datasets, function (d) {
                        d.highlight = !!o.highlight;
                    });
                    typeahead = new Typeahead({
                        input: $input,
                        eventBus: eventBus = new EventBus({
                            el: $input
                        }),
                        withHint: _.isUndefined(o.hint) ? true : !!o.hint,
                        minLength: o.minLength,
                        autoselect: o.autoselect,
                        datasets: datasets
                    });
                    $input.data(typeaheadKey, typeahead);
                };
            },
            open: function open() {
                return this.each(openTypeahead);
                function openTypeahead() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.open();
                    }
                }
            },
            close: function close() {
                return this.each(closeTypeahead);
                function closeTypeahead() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.close();
                    }
                }
            },
            val: function val(newVal) {
                return !arguments.length ? getVal(this.first()) : this.each(setVal);
                function setVal() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.setVal(newVal);
                    }
                }
                function getVal($input) {
                    var typeahead, query;
                    if (typeahead = $input.data(typeaheadKey)) {
                        query = typeahead.getVal();
                    }
                    return query;
                }
            },
            destroy: function destroy() {
                return this.each(unattach);
                function unattach() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.destroy();
                        $input.removeData(typeaheadKey);
                    }
                }
            }
        };
        $.fn.typeahead = function (method) {
            var tts;
            if (methods[method] && method !== "initialize") {
                tts = this.filter(function () {
                    return !!$(this).data(typeaheadKey);
                });
                return methods[method].apply(tts, [].slice.call(arguments, 1));
            } else {
                return methods.initialize.apply(this, arguments);
            }
        };
        $.fn.typeahead.noConflict = function noConflict() {
            $.fn.typeahead = old;
            return this;
        };
    })();
})(window.jQuery);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\geoInfo.js
// version="2"
function ajaxJsonCall(url, data) {
    return $.ajax({
        url: url,
        datatype: "json",
        data: data,
        contentType: "application/json; charset=utf-8",
        type: "POST"
    })
}

// Bug # 458034 : Country Flag and Toll Free Number Not Reflecting on respective Geos
var $imageIcon = $('img.language-icon');

function updateCountryIconAndTitle(country) {
    if (country != null && country != "") {
        var imageIconUrl = "/Content/images/" + country + ".jpg";
        //$('span.country-language-trigger').html(imageIcon);
        //$('span.country-language-trigger').attr("title", imageIcon);
        $imageIcon.attr("src", imageIconUrl);
        $imageIcon.attr("title", country);
        $imageIcon.attr("alt", country);

        //[LHU 10.23.2014] - Footer geoip
        var $footerFlagIcon = $('div.footer-textlink span.country-language-trigger a');
        $footerFlagIcon.html(country);
        $footerFlagIcon.attr("title", country);

        //mobile footer
        var $mobileFooterFlagIcon = $('div.language-selector-mobile a.country-language-trigger');
        $mobileFooterFlagIcon.attr("title", country);
        $mobileFooterFlagIcon.find('span').html(country);
    }
}

function updatePhoneAnchor(jqAnchor, callToNumber, rawNumber) {
    if (callToNumber != null && rawNumber != null) {
        jqAnchor.attr('href', 'callto://' + callToNumber);
        jqAnchor.text(rawNumber);
    }
}

// Bug # 458034 : Country Flag and Toll Free Number Not Reflecting on respective Geos

//var currentUrlPath = $(location).attr('pathname');
//var urlCountrySite = currentUrlPath.split(/[\/-]+/);
//var countryNameList = {
//    'ae': 'UAE',
//    'an': 'Andorra',
//    'ao': 'Angola',
//    'ar': 'Argentina',
//    'au': 'Australia',
//    'at': 'Austria',
//    'be': 'Belgium',
//    'br': 'Brazil',
//    'bw': 'Botswana',
//    'ca': 'Canada',
//    'ch': 'Switzerland',
//    'cl': 'Chile',
//    'cn': 'China',
//    'co': 'Columbia',
//    'cr': 'Costa Rica',
//    'cz': 'Czech Republic',
//    'de': 'Germany',
//    'es': 'Spain',
//    'fi': 'Finland',
//    'fr': 'France',
//    'gb': 'United Kingdom',
//    'hk': 'Hong Kong SAR',
//    'hr': 'Hungary',
//    'id': 'Indonesia',
//    'ie': 'Ireland',
//    'il': 'Israel',
//    'in': 'India',
//    'it': 'Italy',
//    'jp': 'Japan',
//    'ke': 'Kenya',
//    'kr': 'South Korea',
//    'lu': 'Luxembourg',
//    'lv': 'Latvia',
//    'ma': 'Morocco',
//    'mu': 'Mauritius',
//    'mx': 'Mexico',
//    'my': 'Malaysia',
//    'mz': 'Mozambique',
//    'ne': 'Nigeria',
//    'nl': 'Netherlands',
//    'no': 'Norway',
//    'pe': 'Peru',
//    'ph': 'Philippines',
//    'pl': 'Poland',
//    'pt': 'Portugal',
//    'ro': 'Romania',
//    'ru': 'Russia',
//    'sa': 'Saudi Arabia',
//    'se': 'Sweden',
//    'sg': 'Singapore',
//    'sk': 'Slovak Republic',
//    'th': 'Thailand',
//    'tr': 'Turkey',
//    'tw': 'Taiwan',
//    'us': 'United States',
//    've': 'Venezuela',
//    'vn': 'Vietnam',
//    'za': 'South Africa',
//};

var currentCountryName = $imageIcon.attr("title");

function updateGeoElements(geoData) {
    if (currentCountryName  && currentCountryName != "") {
        if (currentCountryName.toLowerCase() != geoData.CountryName.toLowerCase()) {
            updateCountryIconAndTitle(currentCountryName);
        }
        else {
            updateCountryIconAndTitle(geoData.CountryName);
        }
    }
    else {
        updateCountryIconAndTitle(geoData.CountryName);
    }

    $("a.phone-LocalPhoneNumber").each(function () {
        updatePhoneAnchor($(this), geoData.PhoneNumberStripped, geoData.PhoneNumber);
    });

    $("a.phone-TollFreeHotLine").each(function () {
        updatePhoneAnchor($(this), geoData.TollFreeStripped, geoData.TollFree);
    });
}

function GetLocationInfo() {
    ajaxJsonCall("/api/sitecore/Footer/GetLocationInfo")
        .done(function (data) {
            updateGeoElements(data);
            if (typeof (Storage) != "undefined") {
                var _strData = JSON.stringify(data);
                sessionStorage.setItem('data', _strData);
            }
        })
        //.error(function (xhr, status, errorThrown) {
        //    alert("ERROR [Ajax call]: " + errorThrown);
        //});
}

if (ComponentRegistry.FooterModule || ComponentRegistry.NavigationModule) {
    $(function () {
        if (typeof (Storage) != "undefined" && sessionStorage.length > 0) {
            var _objData = JSON.parse(sessionStorage.getItem('data'));
            //updateGeoElements(_objData);
            if (_objData != null) {
                updateGeoElements(_objData);
            }
            else {
                GetLocationInfo();
            }
        }
        else {
            GetLocationInfo();
        }

        //ajaxJsonCall("/api/sitecore/Footer/GetLocationInfo")
        //        .success(function (data) {
        //            updateGeoElements(data);
        //        })
        //        .error(function (xhr, status, errorThrown) {
        //            alert("ERROR [Ajax call]: " + errorThrown);
        //        });
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\search-hero-module.js
/*  version="126" */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], function (jquery) {
            return (root.SearchHeroModule = factory(jquery));
        });
    }
    else {
        root.SearchHeroModule = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.SearchHeroModule) {
            $(function () {
                SearchHeroModule.Init();
            });
        }
    }
}(typeof self !== 'undefined' ? self : this, function ($) {
    var keywordSuggestions = null;
    var searchHeroSettings = null;
    var autoCompleteKeywords = null;

    var storageSearchSettings = "";
    var storageAutocompleteKeywords = "";
    var lastKeyword = "";
    var lastQueryType = "";
    var viewAllKeyword = "";
    var lastRecommendedcontentkeywords = "";
    var lastHighlightedtopickeywords = "";
    var showSuggestedTerm = "";
    var subsite = "";
    var queryString = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
    var checkspell = true;

    var lastSortBy = 0;
    var resultCount = 0;

    var storageRecentSearches = "recent_searches";
    var recentSearches = localStorage.getItem(storageRecentSearches) ? JSON.parse(localStorage.getItem(storageRecentSearches)) : [];
    var searchRedesignTemplatesFilter = $('#search-redesign-templates').length > 0 ? $('#search-redesign-templates').data('hidden-redesign-templates').split('|') : null;

    var $searchHeroKeyword = $('.search-hero-form .search-hero-keywords');
    var $searchResultsArea = $('.search-results-area');
    var $relatedJobsSection = $("#block-relatedjobssection");
    var reinventPagination = $('.search-results-block .reinvent-pagination');
    var reinventPaginationPrevious = reinventPagination.find('.reinvent-pagination-previous-container .prev-page-btn');
    var reinventPaginationNext = reinventPagination.find('.reinvent-pagination-next-container .next-page-btn');
    var reinventPaginationNumberBlock = reinventPagination.find('.pagination-numbers');
    var reinventPaginationNumber = reinventPaginationNumberBlock.find('.page-num');
    var reinventPaginationCurrent = 1;
    var reinventPaginationTotalPages = 1;
    var maximumNumberOfResults = null;
    var lastRefenceGuid = null;
    var lastCherryPickId = null;
    var lastCurrentPageId = null;
    var filtersSelected = 0;
    var lastFilterCount = 0;
    var lastAccordion = null;
    var isFromFilter = false;
    var isFiltersHidden = false;
    var isNoFilterResults = false;
    var isLessThanFilterVisiblity = false;
    var isFilterContainerClosed = true;
    var isFilterModalClosed = true;
    var lastKeywordSearchFilters = null;
    var openedAccordions = null;
    var filterResultsContainer = null;
    var $searchFiltersContainer = $(".redesign-search-filters-container");
    var $searchFilters = $searchFiltersContainer.find(".search-filter-panel");
    var $searchFiltersSortBy = $searchFiltersContainer.find(".redesign-sort");
    var $searchFilterBy = $searchFiltersContainer.find(".reinvent-filter-by");
    var $searchFilterResults = $searchFiltersContainer.find(".reinvent-filter-results");
    var $searchSortMostRelevant = $searchFiltersContainer.find("#reinvent-filter-most-relevant");
    var $searchSortMostRecent = $searchFiltersContainer.find("#reinvent-filter-most-recent");
    var $searchFilterFooter = $searchFiltersContainer.find(".reinvent-filter-footer");
    var $applyButtonFilter = $searchFiltersContainer.find(".reinvent-apply-filter-button");
    var $closeButtonFilter = $searchFiltersContainer.find(".reinvent-close-filter-button");
    var $dropDownMenuDiv = $searchFiltersContainer.find("div.dropdown-menu.dropdown-list");
    var $redesignSerpModal = $searchFiltersContainer.find(".modal");
    var $redesignFilterModal = $searchFiltersContainer.find("#reinvent-filter-list");
    var $searchFilterResultsButtonMode = $searchFilterResults.is(":visible");
    var highlightedTopicCount = 0;
    var facetTermArray = [];
    var commonTermArray = [];
    var term = "";
    var $searchResultsBlock = $('.search-results-block');
    var $viewAllClickTriggeredRedesignSERP = false;
    var $noResultsContainer = $('.no-results-container');
    var $popularSearchContainer = $('.search-results-block .popular-searches-container');
    var $searchTipsContainer = $('.search-results-block .search-tips-container');
    var $redesignlinebar = $('.search-results-block .redesign-line-bar');
    var $lastActiveElement = null;
    var isTabbingUsed = false;
    var isCheckboxFocused = false;
    var checkboxParent = "";
    var checkboxSibling = "";
    var checkSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    var urlParams = "";
    var smallMaxWidth = 1024;
    var ctaTempJSONString = "";
    var ctaTempAttrib = "";
    var ctaKeyword = "";
    var ctaComponenttype = "";
    var ctaCherryPickIds = "";
    var ctaSearchParamId = "";
    var ctaCurrentPageId = "";
    var ctaViewAllSortBy = "";
    var BlogNameKeyword = "";
    var BlogAuthorKeyword = "";
    var BlogAuthorName = "";
    var BlogPostIndustry = "";
    var BlogPostSubject = "";
    var BlogTopicKeyword = "";
    var ifCheck = "";
    var highlightedForFilters = "";
    var array = [];
    var filterArray = [];
    var isApplyClick = "";
    var totalResult = "";
    var pageNum = "";
    var isFeatureSearch = false;

    var FormatSearchHeroValue = function (value) {
        if (value) {
            return value.replace(/\\/gi, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"");
        }
        else {
            return value;
        }
    };

    var Init = function () {
        var minimumKeywordLength = 0;
        var path = GetPath();
        var tempJSONString = localStorage.getItem('ViewAllAttributes');
        var tempAttrib = JSON.parse(tempJSONString);
        if (tempAttrib != null) {
            $viewAllClickTriggeredRedesignSERP = tempAttrib.ViewAllClickTriggeredRedesignSERP;
        }

        if (path === null || path === "") {
            path = "us-en";
        }

        storageSearchSettings = "search_settings_" + path;
        storageAutocompleteKeywords = "autocomplete_keywords_" + path;

        keywordSuggestions = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            local: []
        });

        keywordSuggestions.initialize();

        if (typeof (Storage) !== "undefined") {
            searchHeroSettings = JSON.parse(sessionStorage.getItem(storageSearchSettings));
            autoCompleteKeywords = JSON.parse(sessionStorage.getItem(storageAutocompleteKeywords));
        }

        if (searchHeroSettings === null) {
            PerformSearch(false, "searchsettings.search");
        }

        if (autoCompleteKeywords === null) {
            PerformSearch(true, "suggestion.search", "", 1);
        }
        else {
            InitializeKeywordSuggestions();
        }

        if (searchHeroSettings !== null && searchHeroSettings.componentsettings !== null) {
            keywordSuggestions.limit = searchHeroSettings.componentsettings.maximumsuggestion;
            minimumKeywordLength = searchHeroSettings.componentsettings.minimumkeywordlength;
            showSuggestedTerm = searchHeroSettings.componentsettings.showsuggestedterm;
        }
        else {
            minimumKeywordLength = 0;
        }

        //Polyfill on remove() for IE
        if (!('remove' in Element.prototype)) {
            Element.prototype.remove = function () {
                if (this.parentNode) {
                    this.parentNode.removeChild(this);
                }
            };
        }

        if ($viewAllClickTriggeredRedesignSERP === true) {
            ViewAllSearch();
            $searchResultsArea.addClass('prefiltered');
        }
        //Specify page for SERP redesign
        $("body").addClass("serp-redesign-body");

        //job-listing cards align with searchresult
        var actionableSerp = $('#block-relatedjobssection .row');
        actionableSerp.css({
            "background": "#FFFFFF",
            "margin-bottom": "30px",
            "margin-top": "5px",
            "box-shadow": "0 0 0.31em 0.13em rgba(107, 107, 107, 0.15)",
            "min-width": "1270px"
        });
        if (jsUtility.isMobile()) {
            actionableSerp.css({
                "width": "90.89%",
                "min-width": "initial"
            });
        }
        else if (jsUtility.isTablet()) {
            actionableSerp.css({
                "width": "93.5%",
                "min-width": "initial"
            });
        }

        window.onresize = function () {
            var browserWidth = document.body.clientWidth;
            if (browserWidth > 1270) {
                actionableSerp.css({
                    "min-width": "1270px",
                    "width": "initial"
                });
            } else if (browserWidth < 1270 & browserWidth > 1120) {
                actionableSerp.css({
                    "width": "100%",
                    "min-width": "initial"
                });
            } else if (browserWidth < 1199 & browserWidth > 1024) {
                actionableSerp.css({
                    "width": "97.5%",
                    "min-width": "initial"
                });
            } else if (browserWidth < 1025 & browserWidth > 1000) {
                actionableSerp.css({
                    "width": "93.5%",
                    "min-width": "initial"
                });
            } else {
                actionableSerp.css({
                    "width": "90.89%",
                    "min-width": "initial"
                });
            }
        }
        $('.block-title .section-title').css({ "font-size": "2rem" });

        IncludesPolyfillForIE();
        AppendPolyfillForIE();
        Typeahead(minimumKeywordLength);
        StoreRecentSearch();
        DisplayRecentSearch();
        ClickRecentSearch();
        OnLoadPopularSearches();
        ClickPopularSearches();
        EnterPopularSearches();
        EventHandlers();
        URLSearchParamsForIE();
        removeFocusIndicatorOnClick();
        clearRelatedJobsSection();
    };

    var URLSearchParamsForIE = function () {
        (function (w) {

            w.URLSearchParams = w.URLSearchParams || function (searchString) {
                var self = this;
                self.searchString = searchString;
                self.get = function (name) {
                    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
                    if (results === null) {
                        return null;
                    }
                    else {
                        return decodeURIComponent(results[1]) || 0;
                    }
                };
            };

        })(window);
    };

    var IncludesPolyfillForIE = function () {
        if (!Array.prototype.includes) {
            Object.defineProperty(Array.prototype, "includes", {
                enumerable: false,
                value: function (obj) {
                    var newArr = this.filter(function (el) {
                        return el == obj;
                    });
                    return newArr.length > 0;
                }
            });
        }
    };

    var AppendPolyfillForIE = function () {
        (function (array) {
            array.forEach(function (item) {
                if (item.hasOwnProperty('append')) {
                    return;
                }
                Object.defineProperty(item, 'append', {
                    configurable: true,
                    enumerable: true,
                    writable: true,
                    value: function append() {
                        var argumentArray = Array.prototype.slice.call(arguments),
                            documentFragment = document.createDocumentFragment();

                        argumentArray.forEach(function (argumentItem) {
                            var isNode = argumentItem instanceof Node;
                            documentFragment.appendChild(isNode ? argItem : document.createTextNode(String(argumentItem)));
                        });

                        this.appendChild(documentFragment);
                    }
                });
            });
        })([Element.prototype, Document.prototype, DocumentFragment.prototype]);
    };

    var ImageResizingForFeaturedSearchResultArticle = function () {

        var $featuredResultsImage = $('.highlighted-topic-container .highlighted-topic-section .featured-article-image');

        //IE Image Resizing
        if (IsIE()) {
            if (!Modernizr.objectfit) {
                $featuredResultsImage.each(function () {
                    var identifyHeight = 0;
                    var idenfityWidth = 0;

                    identifyWidth = $featuredResultsImage.width();
                    identifyHeight = $featuredResultsImage.width();
                    var $container = $(this),
                        imgUrl = $container.find('img').prop('src');
                    if (imgUrl) {
                        $container
                            .css('backgroundImage', 'url(' + imgUrl + ')')
                            .css('width', 'identifyWidth')
                            .css('height', 'identifyHeight')
                            .addClass('compat-object-fit');
                    }
                });
            }
        }
    };

    var InitializeKeywordSuggestions = function () {
        if (autoCompleteKeywords.length > 0) {
            keywordSuggestions.local = $.map(autoCompleteKeywords, function (suggestion) {
                return { value: suggestion };
            });
            keywordSuggestions.initialize(true);
        }
    };

    var GetPath = function () {
        var path = window.location.pathname;
        if (typeof searchHeroCountrySite !== 'undefined') {
            path = searchHeroCountrySite;
        }
        else {
            var pathArray = path.split('/');
            path = pathArray[1];
        }

        return path;
    };

    var SetDefaultPath = function (path) {
        if (path === null || path === "") {
            path = "/us-en/";
        }
        else {
            path = "/" + path + "/";
        }

        return path;
    };

    var Typeahead = function (minimumKeywordLength) {

        $searchHeroKeyword.typeahead({
            hint: true,
            highlight: true,
            minLength: minimumKeywordLength
        },
            {
                name: 'keywordSuggestions',
                displayKey: 'value',
                source: keywordSuggestions.ttAdapter()
            });

        $searchHeroKeyword.on('typeahead:selected', function (e, datum) {
            viewAllKeyword = $(".tt-suggestion.view-all-text-container").attr('data-attribute-view-all-keyword');
            var key = event.keyCode;
            var $searchButton = $('.search-hero-form .btn');
            var $searchResultsBlock = $('.search-results-block');
            $searchResultsBlock.trigger("focus");
            $searchButton.attr('tabindex', '-1');
            if (typeof datum === "undefined") {
                SelectViewAll(key, $searchButton, viewAllKeyword);
            }
            else if (RemoveTags(lastKeyword).toLowerCase() !== datum.value.toLowerCase()) {
                var selected = datum.value;
                SelectSuggestion(key, $searchButton, selected);
            }
        });

        $searchHeroKeyword.on('typeahead:cursorchanged', function () {
            var $suggestionsContainer = $('.redesign-search-page .tt-dataset-keywordSuggestions');

            if ($('.tt-suggestion.view-all-text-container').hasClass('tt-cursor')) {
                $searchHeroKeyword.typeahead('val', ($('.tt-suggestion.view-all-text-container').attr('data-attribute-view-all-keyword')));
            }
            $suggestionsContainer.scrollTop(0);
            $suggestionsContainer.scrollTop($('.tt-cursor').first().offset().top - $suggestionsContainer.height());
        });
    };

    var ResetArrays = function () {
        filterArray = [];
        array = [];
    };

    var SelectViewAll = function (key, $searchButton, viewAllKeyword) {
        if (key === 9) {
            $searchHeroKeyword.typeahead('val', RemoveTags(viewAllKeyword));
            $searchButton.trigger("focus");
        } else {
            if (RemoveTags(lastKeyword) !== RemoveTags(viewAllKeyword)) {
                $searchHeroKeyword.typeahead('val', RemoveTags(viewAllKeyword));
                SpacesAndSingleCharacter();
                StoreLocalStorage(RemoveTags(viewAllKeyword));
                DisplayRecentSearch();
                DisableForm();
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
                ResetArrays();
                AppendToURL('srk', ReplaceEncodedKeyword(viewAllKeyword), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', "");
            } else {
                $searchHeroKeyword.typeahead('val', RemoveTags(viewAllKeyword));
            }
            if (!(checkSafari)) {
                $searchHeroKeyword.trigger("blur");
            }
            FirefoxAccessibility();
            SafariAccessibility();
        }
    };

    var SelectSuggestion = function (key, $searchButton, selected) {
        ResetArrays();

        if (key === 9) {
            $searchHeroKeyword.typeahead('val', RemoveTags(selected));
            $searchButton.trigger("focus");
        } else {
            reinventPaginationCurrent = 1;
            lastSortBy = 0;
            AppendToURL('srk', ReplaceEncodedKeyword(selected), 'pg', 1, 'sb', lastSortBy, 'filter', "");
            HideSearchResults();
            ClearedFeaturedSearchResults();
            $searchResultsBlock.trigger("focus");
            FirefoxAccessibility();
            SafariAccessibility();
            StartSearch(selected);
            recentSearches.push(RemoveTags(selected));
            localStorage.setItem(storageRecentSearches, JSON.stringify(recentSearches));
            DisableForm();
            clearRelatedJobsSection();
        }
    };

    var GeneratePagination = function (reinventPaginationTotalPages, totalResult) {

        if (totalResult <= maximumNumberOfResults) {
            reinventPagination.addClass('hide');
            return false;
        }

        var ellipsis = "...";
        var moduleName = "searchresultsblock";
        var pagenumb = "";
        var isCurrent = "";

        reinventPaginationNumberBlock.empty();
        reinventPagination.removeClass('hide');
        reinventPaginationPrevious.removeClass('disabled');
        reinventPaginationNext.removeClass('disabled');
        reinventPaginationPrevious.removeAttr('aria-disabled');
        reinventPaginationNext.removeAttr('aria-disabled');

        if (reinventPaginationCurrent == 1) {
            reinventPaginationPrevious.addClass('disabled');
            reinventPaginationPrevious.attr('aria-disabled', 'true');
        }
        if (reinventPaginationCurrent == reinventPaginationTotalPages) {
            reinventPaginationNext.addClass('disabled');
            reinventPaginationNext.attr('aria-disabled', 'true');
        }

        var paginationDropdown = $(".pagination-dropdown");
        paginationDropdown.empty();

        var pageXY = paginationDropdown.data("pagexy");
        var paginationDropdownText = $(".pagination-dropdown-text");
        var dropdownIcon = "<span class='ion-chevron-down hidden-md hidden-sm hidden-lg'></span>";

        paginationDropdownText.text(pageXY.replace("{0}", reinventPaginationCurrent).replace("{1}", reinventPaginationTotalPages));
        paginationDropdownText.append(dropdownIcon);

        for (var ctr = 1; ctr < reinventPaginationTotalPages + 1; ctr++) {
            var opt = document.createElement("option");
            opt.value = ctr;
            opt.innerHTML = opt.value;

            opt.setAttribute("data-linkcomponentname", "searchresultsblock-pagination");
            opt.setAttribute("data-linktype", "search");
            opt.setAttribute("data-analytics-content-type", "search");
            opt.setAttribute("data-linkpagesection", "searchresultsblock");
            opt.setAttribute("data-analytics-link-name", ctr);

            if (ctr == reinventPaginationCurrent) {
                opt.setAttribute("selected", true);
            }
            paginationDropdown.append(opt);
        }

        var $pageMin = 1;
        var $pagingGauge = 4;
        var $pageMax = 7;
        var $startPage = $pageMin;
        var $endPage = reinventPaginationTotalPages;
        var $ariaCurrent;

        if (reinventPaginationTotalPages > $pageMax) {
            if (reinventPaginationCurrent <= ($pagingGauge)) {
                $startPage = $pageMin;
                $endPage = $pageMin + $pagingGauge;
            } else if (reinventPaginationCurrent >= reinventPaginationTotalPages + $pageMin - $pagingGauge) {
                $endPage = reinventPaginationTotalPages;
                $startPage = (reinventPaginationTotalPages - $pagingGauge);
            } else {
                $endPage = parseInt(reinventPaginationCurrent) + $pageMin;
                $startPage = parseInt(reinventPaginationCurrent) - $pageMin;
            }
        }

        if ($startPage > $pageMin) {
            pagenumb = '<a href="javascript:void(0)" class="page-num" data-linkcomponentname="' + moduleName + '" data-linktype="search" data-analytics-content-type="search" aria-label="page ' + $pageMin + '" data-analytics-link-name="' + $pageMin + '">' + $pageMin + '</a>';
            reinventPaginationNumberBlock.append(pagenumb);
            reinventPaginationNumberBlock.append("<div class='page-num'>" + ellipsis + "</div>");
        }

        for (var $i = $startPage; $i <= $endPage; $i++) {
            isCurrent = ($i == reinventPaginationCurrent) ? "current" : "";
            $ariaCurrent = (isCurrent) ? 'aria-current="page"' : "";
            pagenumb = '<a href="javascript:void(0)" class="page-num ' + isCurrent + '" data-linkcomponentname="' + moduleName + '" data-linktype="search" data-analytics-content-type="search" aria-label="page ' + $i + '"' + $ariaCurrent + ' data-analytics-link-name="' + $i + '">' + $i + '</a>';
            reinventPaginationNumberBlock.append(pagenumb);
        }

        if ($endPage < reinventPaginationTotalPages) {
            reinventPaginationNumberBlock.append("<div class='page-num'>" + ellipsis + "</div>");
            pagenumb = '<a href="javascript:void(0)" class="page-num ' + isCurrent + '" data-linkcomponentname="' + moduleName + '" data-linktype="search" data-analytics-content-type="search" aria-label="page ' + reinventPaginationTotalPages + '" data-analytics-link-name="' + reinventPaginationTotalPages + '">' + reinventPaginationTotalPages + '</a>';
            reinventPaginationNumberBlock.append(pagenumb);
        }
        if (reinventPaginationCurrent > reinventPaginationTotalPages) {
            reinventPagination.hide();
        }
        else {
            reinventPagination.show();
        }
    };

    var GetFeaturedImagePath = function (searchResult, imgPath) {
        if (searchResult.featuredimage.Path.indexOf("~") === -1) {
            imgPath = searchResult.featuredimage.Path.replace("/sitecore/shell/", "~");
        }
        else {
            imgPath = searchResult.featuredimage.Path.replace("/sitecore/shell/", " ").trim();
        }

        return imgPath;
    };

    var CheckHighlightedTopicHeaderUrl = function (searchResult, imgPath, $featuredArticleImage) {
        if (searchResult.highlightedtopicheaderurl.Url !== null) {
            jQuery('<a/>', {
                class: 'featured-image-cta',
                href: searchResult.highlightedtopicheaderurl.Url
            }).appendTo('.highlighted-topic-container .highlighted-topic-section .featured-article-image');
            var $featuredImageReadMore = $('.highlighted-topic-container .highlighted-topic-section .featured-article-image .featured-image-cta');
            $featuredImageReadMore.attr('tabindex', '-1');

            jQuery('<img/>', {
                class: 'highlighted-topic-image',
                src: imgPath
            }).appendTo('.highlighted-topic-container .highlighted-topic-section .featured-article-image .featured-image-cta');

            if (searchResult.featuredimage.Alt !== null && searchResult.featuredimage.Alt !== "") {
                $featuredImageReadMore.attr('data-analytics-link-name', searchResult.featuredimage.Alt);
            }
            else {
                $featuredImageReadMore.attr('data-analytics-link-name', searchResult.highlightedtopicheader);
            }
            $featuredImageReadMore.attr('data-analytics-content-type', 'featured search');
            $('.highlighted-topic-container .highlighted-topic-section .featured-article-image .featured-image-cta .highlighted-topic-image').attr('alt', searchResult.featuredimage.Alt);
        }
        else {
            jQuery('<img/>', {
                class: 'highlighted-topic-image',
                src: imgPath
            }).appendTo('.highlighted-topic-container .highlighted-topic-section .featured-article-image');
            $('.highlighted-topic-container .highlighted-topic-section .featured-article-image .highlighted-topic-image').attr('alt', " ");
        }

        $featuredArticleImage.addClass('col-lg-2 col-md-2 col-sm-2 col-xs-12');
        $featuredArticleImage.addClass('featured-image-resize');
    };

    var CheckHighlightedTopicHeader = function (searchResult, $highlightedTopicReadMore, $featuredHeader) {
        if (searchResult.highlightedtopicheaderurl.Url !== null) {

            $featuredHeader.text("");
            $featuredHeader.addClass('section-title');

            jQuery('<a/>', {
                href: searchResult.highlightedtopicheaderurl.Url,
                html: searchResult.highlightedtopicheader,
                class: 'cta',
                'aria-describedby': 'highlighted-topic-desc-id'
            }).appendTo($featuredHeader);

            var $featuredTitleLink = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-content .featured-article-header .cta');
            var readMoreAriaLabel = StringFormat($(".read-more-aria-label").attr("data-attribute-vague-text"), $(".read-more-aria-label").attr("data-attribute-read-more"), searchResult.highlightedtopicheader);

            $featuredTitleLink.attr('data-analytics-link-name', searchResult.highlightedtopicheader);
            $featuredTitleLink.attr('data-analytics-content-type', 'featured search');

            $highlightedTopicReadMore.attr('href', searchResult.highlightedtopicheaderurl.Url);
            $highlightedTopicReadMore.attr('data-analytics-link-name', readMoreAriaLabel);
            $highlightedTopicReadMore.attr('data-analytics-content-type', 'featured search');
            $highlightedTopicReadMore.attr("aria-label", readMoreAriaLabel);
            $highlightedTopicReadMore.attr("data-original-title", (function () { return searchResult.highlightedtopicheaderurl.Title; }));
            $highlightedTopicReadMore.show();
        }
        else {

            $featuredHeader.removeClass('section-title');
            $featuredHeader.html(String(searchResult.highlightedtopicheader));
            $highlightedTopicReadMore.attr('aria-label', 'read more about featured search article');
            $highlightedTopicReadMore.attr('data-original-title');
            $highlightedTopicReadMore.attr('data-analytics-link-name');
            $highlightedTopicReadMore.attr('data-analytics-content-type');
            $highlightedTopicReadMore.hide();
        }
    };

    var DisplayHighlightedEventRegister = function (searchResult, $highlightedEventRegisterLink) {
        if (searchResult.highlightedeventregisterurl.Url) {
            $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-register').attr('href', searchResult.highlightedeventregisterurl.Url);
            $highlightedEventRegisterLink.attr("data-original-title", (function () { return searchResult.highlightedeventregisterurl.Title; }));
            $highlightedEventRegisterLink.attr('data-analytics-content-type', 'featured search');
            $highlightedEventRegisterLink.attr('data-analytics-module-name', 'searchresultsblock');
            $highlightedEventRegisterLink.attr('data-linkcomponentname', 'searchresultsblock');
            $highlightedEventRegisterLink.show();
        } else {
            $highlightedEventRegisterLink.hide();
        }
    };

    var DisplayFeaturedDescription = function (searchResult, $featuredDescription) {
        jQuery('<p/>', {
            class: 'featured-desc fluid dot-ellipsis',
            html: searchResult.highlightedtopicdescription,
            id: 'highlighted-topic-desc-id'
        }).appendTo($featuredDescription);
    };

    var HighlightedTopicItems = function (searchResult) {
        var $featuredArticleImage = $('.highlighted-topic-container .highlighted-topic-section .featured-article-image');
        var $featuredDescription = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-desc');
        var $featuredHeader = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-content .featured-article-header');
        var $highlightedTopicReadMore = $('.highlighted-topic-container .highlighted-topic-section .highlghted-topic-readmore');
        var $highlightedEventRegisterLink = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-register');
        var $highlightedTopicArea = $('.highlighted-topic-area');
        var imgPath = null;
        var $highlightedTopicFeatured = $('.highlighted-topic-featured');

        if (searchResult !== null || searchResult !== 0) {

            //Event Data Fallback
            if (searchResult.highlightedeventitem != null) {
                if (!searchResult.highlightedtopicheader) {
                    searchResult.highlightedtopicheader = searchResult.highlightedeventitem.eventname;
                }
                if (!searchResult.highlightedtopicdescription) {
                    searchResult.highlightedtopicdescription = searchResult.highlightedeventitem.eventdescription;
                }
                if (!searchResult.highlightedeventregisterurl.Url) {
                    searchResult.highlightedeventregisterurl.Url = searchResult.highlightedeventitem.registerlink;
                }
            }

            $highlightedTopicFeatured.show();
            //Image
            if (searchResult.featuredimage !== null) {
                imgPath = GetFeaturedImagePath(searchResult, imgPath);

                CheckHighlightedTopicHeaderUrl(searchResult, imgPath, $featuredArticleImage);
            }
            else {
                $featuredArticleImage.removeClass('col-lg-2 col-md-2 col-sm-2 col-xs-12');
                $highlightedTopicReadMore.addClass('readmore-without-image');
                $highlightedTopicReadMore.removeClass('readmore-with-image');
                $featuredArticleImage.removeClass('featured-image-resize');
            }

            if (searchResult.highlightedtopicheader !== null) {
                CheckHighlightedTopicHeader(searchResult, $highlightedTopicReadMore, $featuredHeader);
                $featuredHeader.show();
            }
            else {
                $featuredHeader.hide();
            }

            if (searchResult.highlightedeventregisterurl != null) {
                DisplayHighlightedEventRegister(searchResult, $highlightedEventRegisterLink);
            } else {
                $highlightedEventRegisterLink.hide();
            }

            $featuredDescription.empty();
            if (searchResult.highlightedtopicdescription !== null) {
                DisplayFeaturedDescription(searchResult, $featuredDescription);
                $featuredDescription.show();
            }
            else {
                $featuredDescription.hide();
            }
            ImageResizingForFeaturedSearchResultArticle();
            if (parseInt(urlParams.get('pg')) === 1 || urlParams.get('pg') === "" || urlParams.get('pg') === null) {
                $highlightedTopicArea.show();
            }
            $('.highlighted-topic-panel-container').remove();
            var topicdiv = document.createElement("div");
            topicdiv.setAttribute("class", "highlighted-topic-panel-container col-sm-12");
            topicdiv.setAttribute("aria-live", "off");
            var colTotal = 0;
            var lastColumnCount = 0;
            var appendClass = "";
            for (var i = 0; i < searchResult.highlightedsubtopics.length; i++) {
                appendClass = (colTotal == 0) ? "first" : "";
                var subtopic = searchResult.highlightedsubtopics[i];
                var maindivcontainer = document.createElement("div");
                var maindiv = document.createElement("div");
                var headerdiv = document.createElement("div");
                var subdiv = document.createElement("div");
                var subitemdiv = document.createElement("div");
                var headerwidth = searchResult.highlightedsubtopics[i].highlightedtopicheaderwidth == 0 ? 12 : searchResult.highlightedsubtopics[i].highlightedtopicheaderwidth;
                var contentwidth = searchResult.highlightedsubtopics[i].highlightedtopicitemwidth == 0 ? 4 : searchResult.highlightedsubtopics[i].highlightedtopicitemwidth;

                lastColumnCount += headerwidth;

                if (lastColumnCount == 12) {
                    appendClass = "last";
                    lastColumnCount = 0;
                }
                maindivcontainer.setAttribute("class", "highlighted-topic-panel-subcontainer");
                maindiv.setAttribute("class", "highlighted-topic-panel col-sm-" + headerwidth + " col-xs-12 " + appendClass);
                colTotal += headerwidth;
                if (!(i + 1 < searchResult.highlightedsubtopics.length && (colTotal + searchResult.highlightedsubtopics[i + 1].highlightedtopicheaderwidth) <= 12)) {
                    colTotal = 0;
                }
                highlightedTopicHeaderLinkName = "";
                if (typeof subtopic.highlightedtopicheader !== null && typeof subtopic.highlightedtopicheader !== "undefined") {
                    highlightedTopicHeaderLinkName = subtopic.highlightedtopicheader.toLowerCase().trim();
                }

                $(maindivcontainer).append(headerdiv);
                $(maindiv).append(maindivcontainer);

                subdiv.setAttribute("class", "bg-color-lighter-gray");
                subitemdiv.setAttribute("class", "panel-body");
                $(subdiv).append(subitemdiv);

                var highlightedtopicitems = searchResult.highlightedsubtopics[i].highlightedtopicitems;

                if (subtopic.subtopics.length > 0) {
                    for (var ii = 0; ii < searchResult.highlightedsubtopics[i].subtopics.length; ii++) {
                        if (searchResult.highlightedsubtopics[i].subtopics[ii].highlightedtopicitems.length > 0) {
                            for (var iii = 0; iii < searchResult.highlightedsubtopics[i].subtopics[ii].highlightedtopicitems.length; iii++) {
                                highlightedtopicitems.push(searchResult.highlightedsubtopics[i].subtopics[ii].highlightedtopicitems[iii])
                            }

                        }
                    }
                }

                highlightedtopicitems = searchResult.highlightedsubtopics[i].highlightedtopicitems.sort(function (obj1, obj2) {
                    if (!obj1.sort) return 1;
                    if (!obj2.sort) return -1;
                    if (obj1.sort == obj2.sort) return 0;
                    return obj1.sort < obj2.sort ? -1 : 1;
                });

                var columns = 3;

                if (12 % contentwidth == 0 && contentwidth > 2) {
                    columns = 12 / contentwidth;
                };

                var total_result = searchResult.highlightedsubtopics[i].maximumtopicitempertopicheader == 0 ? highlightedtopicitems.length : searchResult.highlightedsubtopics[i].maximumtopicitempertopicheader;

                highlightedtopicitems = highlightedtopicitems.filter(function (subitem) {
                    return subitem.highlightedtopicitemlink != null;
                });

                if (highlightedtopicitems.length > 0) {
                    if (subtopic.highlightedtopicheader !== null && subtopic.highlightedtopicheader !== "") {
                        $(headerdiv).append("<a data-linktype='customized - search topic details' data-analytics-content-type='customized - search topic details' data-analytics-link-name='" + highlightedTopicHeaderLinkName + "'><h3 class='eyebrow-title'>" + subtopic.highlightedtopicheader.toUpperCase() + "</h3></a>");
                    }
                    else {
                        $(headerdiv).append("<a data-linktype='customized - search topic details' data-analytics-content-type='customized - search topic details' data-analytics-link-name='customized - search topic details'></a>");
                    }
                    $(topicdiv).append(maindiv);
                }

                highlightedtopicitems = highlightedtopicitems.slice(0, total_result);
                highlightedtopicitems = highlightedtopicitems.sort(function (obj1, obj2) {
                    return obj1.highlightedtopicitemtitle.localeCompare(obj2.highlightedtopicitemtitle)
                });

                var rowsPerColumn = Math.ceil(highlightedtopicitems.length / columns);
                var rows = 0;
                for (var ii = 0; ii < highlightedtopicitems.length; ii++) {
                    rows++;
                    var topicitem = highlightedtopicitems[ii];
                    if (rows == 1) {
                        var itemdiv = document.createElement("div");
                        itemdiv.setAttribute("class", "col-sm-" + contentwidth + " col-xs-12 collapse-filter");
                    }
                    var highlightedtopicitemtitleLinkName = "";
                    if (typeof topicitem.highlightedtopicitemtitle !== null && typeof topicitem.highlightedtopicitemtitle !== "undefined") {
                        highlightedtopicitemtitleLinkName = topicitem.highlightedtopicitemtitle.toLowerCase().trim();
                    }
                    if (topicitem.highlightedtopicitemlink != null && $.trim(topicitem.highlightedtopicitemlink) != '') {
                        $(itemdiv).append("<div class='suggested-topic'><a class='fluid' href='" + topicitem.highlightedtopicitemlink + "'"
                            + "data-name='asset' data-linktype='related search' data-analytics-content-type='related search' data-linkcomponentname='searchresultsblock' data-analytics-module-name='searchresultsblock' data-analytics-link-name='" + highlightedtopicitemtitleLinkName + "' data-rel='" + topicitem.sitecoreitemid + "'"
                            + ">"
                            + topicitem.highlightedtopicitemtitle + "</a></div>");
                    }
                    else {
                        $(itemdiv).append("<p class='suggested-topic'>" + topicitem.highlightedtopicitemtitle + "</p>");
                    }
                    if (rows <= rowsPerColumn) {
                        $(subitemdiv).append(itemdiv);
                        if (rows == rowsPerColumn) {
                            rows = 0;
                        }
                    }
                }
                $(maindivcontainer).append(subdiv);
            }
            $(".highlighted-topic-section").append(topicdiv);

            highlightedtopicitemsquery = true;
            if (parseInt(urlParams.get('pg')) === 1 || urlParams.get('pg') === "" || urlParams.get('pg') === null) {
                $('.highlighted-topic-container').show();
            }
            else {
                $('.highlighted-topic-area').hide();
            }
            AddEllipsis();
        }
        else {
            $('.highlighted-topic-container').hide();
            $('.search-results-block .highlighted-topic-container').empty();
        }
    };

    var SearchResultsElements = function (indexResults) {
        jQuery('<div/>', {
            class: 'col-sm-12 search-results-' + (indexResults)
        }).appendTo('.search-results-section');
        jQuery('<hr/>', {
            class: 'all-results-line-bar'
        }).appendTo('.search-results-' + (indexResults));
        jQuery('<div/>', {
            class: 'search-results-header col-sm-8 col-md-12'
        }).appendTo('.search-results-' + (indexResults));
        jQuery('<div/>', {
            class: 'search-results-content col-sm-8 col-md-12'
        }).appendTo('.search-results-' + (indexResults));
    };

    var SearchResultsContentType = function ($searchResultsContent, contentTypeItems, sorteditems, recommendedContent) {
        for (var cnt = 0; cnt < recommendedContent.all_contenttype.length; cnt++) {
            if (contentTypeItems.indexOf(sorteditems[cnt].name) > -1) {
                jQuery('<p/>', {
                    class: 'category dotdot content-title fluid',
                    html: sorteditems[cnt].name.toUpperCase()
                }).appendTo($searchResultsContent);
                break;
            }
        }
    };

    var SearchResultsDateCategory = function (indexResults, recommendedContent, $searchResultsContent) {
        var showContentDate = searchHeroSettings.componentsettings.showcontentdate;
        var $searchResultDate = $('.search-results-' + (indexResults) + ' .date');
        var $searchResultCategory = $('.search-results-' + (indexResults) + ' .category');
        var searchBranchTemplate = recommendedContent.branchtemplate;
        var hideContentDate = false;

        if ((showContentDate !== null && !showContentDate) || (recommendedContent.all_contentdate !== null && recommendedContent.all_contentdate.ishidden)) {
            hideContentDate = true;
        }

        if (searchRedesignTemplatesFilter !== null) {
            if (searchBranchTemplate !== null) {
                if (searchRedesignTemplatesFilter.indexOf(searchBranchTemplate) >= 0) {
                    hideContentDate = true;
                }
            }
        }
        if ((!hideContentDate || recommendedContent.sitecoreitemid === null) && recommendedContent.all_contentdate !== null) {
            $searchResultDate.html(String(FormatDate(recommendedContent.all_contentdate.docdate)));
        }
        else {
            $searchResultDate.html("");
        }

        if ($searchResultDate.text().length !== 0 && $searchResultCategory.text().length !== 0) {
            $searchResultsContent.attr("hidden", false);
        }
        else if ($searchResultDate.text().length !== 0 || $searchResultCategory.text().length !== 0) {
            $searchResultsContent.attr("hidden", false);
        }
        else {
            $searchResultsContent.attr("hidden", true);
        }
    };

    var SearchResultsTitle = function (indexResults, recommendedContent) {
        var $searchResultTitle = $('.search-results-' + (indexResults) + ' .search-result-link');
        if (recommendedContent.seotitle !== null) {
            $searchResultTitle.html(String(recommendedContent.seotitle));
        }
        else {
            $searchResultTitle.html(String(recommendedContent.title));
        }

        $('.search-results-' + (indexResults) + ' .search-results-header a').attr('data-analytics-link-name', $('.search-results-' + (indexResults) + ' .search-results-header a').text().toLowerCase());
        $('.search-results-' + (indexResults) + ' .search-results-header a').attr('data-analytics-content-type', 'serp-ranked');
    };

    var SearchResultsContent = function (recommendedContent, $searchResultsHeader, $searchResultsContent, indexResults) {

        jQuery('<h4/>', {
            class: 'header title quarternary-title'
        }).appendTo($searchResultsHeader);

        var $searchResultsHeaderTitle = $('.search-results-' + (indexResults) + ' .search-results-header .header');

        jQuery('<a/>', {
            href: recommendedContent.relativepath,
            class: 'search-result-link cta'
        }).appendTo($searchResultsHeaderTitle);

        jQuery('<p/>', {
            class: 'search-results-divider fluid'
        }).appendTo($searchResultsContent);

        jQuery('<p/>', {
            class: 'date fluid'
        }).appendTo($searchResultsContent);
    };

    var SearchResultsDescription = function (indexResults, recommendedContent, $searchResultsHeader) {
        var contentDescription = "";
        if (recommendedContent.seodescription !== null) {
            contentDescription = recommendedContent.seodescription;
        }
        else {
            contentDescription = recommendedContent.description;
        }

        jQuery('<p/>', {
            class: 'content-description fluid'
        }).appendTo($searchResultsHeader);

        $('.search-results-container .search-results-section .search-results-' + (indexResults) + ' .search-results-header .content-description').addClass("dot-ellipsis");

        return contentDescription;
    };

    var HighlightContentDescription = function (indexResults, contentDescription) {
        var search = $searchHeroKeyword.typeahead('val');
        var searchKeyword = search.split(/\s/);
        var specialChars = /[ !@#$%^&*()_+\-=\[\]{};:"\\|,.<>\/?]/g;

        for (var index = 0; index < searchKeyword.length; index++) {
            searchKeyword[index] = searchKeyword[index].replace(specialChars, '\\$&');
        }

        search = search.replace(specialChars, '\\$&');

        var regex, result;
        if (RegExp("(^'[\\S\\s]*'$)", "ig").test(RemoveTags($searchHeroKeyword.typeahead('val')))) {
            search = search.replace(/(^'|'$)/g, '');
            regex = new RegExp("\\b(" + search + ")\\b", "ig");
        } else {
            regex = new RegExp("\\b(" + searchKeyword.join('|') + ")\\b", "ig");
        }
        result = contentDescription.replace(regex, '<strong>$1</strong>');

        $('.search-results-' + (indexResults) + ' .content-description').html(String(result));
    };

    var RecommendedSearchbyKeywords = function (queryType, searchResult) {
        var contentTypeItems = new Array();
        var filterVisibilityCount = searchHeroSettings.componentsettings.filtervisibilitycount;
        var showFilterSection = searchHeroSettings.componentsettings.showfiltersection;

        totalResult = searchResult.total;

        if (lastQueryType == "recommendedcontentitems.search" || lastQueryType == "default-blogsbyblogname" || lastQueryType == "default-blogsbyblogauthor" || lastQueryType == "default-blogsbyblogtopic") {
            maximumNumberOfResults = searchHeroSettings.componentsettings.maximumsearchresultsperpagination;
        }
        reinventPaginationTotalPages = Math.ceil(totalResult / maximumNumberOfResults);

        ResultsForKeyword(searchResult, reinventPaginationTotalPages);
        if (resultCount <= 0) {
            $('.search-results-container .search-results-section').empty();

            if (subsite != "newsroom") {
                if (isFromFilter === true || (searchResult.total > filterVisibilityCount && showFilterSection === true)) {
                    isFiltersHidden = false;
                    isNoFilterResults = false;
                    isLessThanFilterVisiblity = false;

                    //Hide Search Filter for BlogPostCards SERP CTA
                    if (queryType !== "default-blogsbyblogname" && queryType !== "default-blogsbyblogauthor" && queryType !== "default-blogsbyblogtopic") {
                        ShowFilters(searchResult.acnfacets);
                    } else {
                        $searchFiltersContainer.removeClass("hidden");
                        $searchFiltersContainer.addClass("invisible hidden-xs hidden-sm");
                    }
                } else {
                    if (searchResult.total > 0) {
                        isNoFilterResults = false;
                        isLessThanFilterVisiblity = true;
                    } else {
                        isLessThanFilterVisiblity = false;
                    }
                    isFiltersHidden = true;
                    HideFilters();
                }
                isFromFilter = false;
            }
        }
        GeneratePagination(reinventPaginationTotalPages, totalResult);
        DisplayContentType(searchResult, contentTypeItems);
        SearchTips(searchResult, reinventPaginationTotalPages);
        NoSearchResults(searchResult, reinventPaginationTotalPages);
        if (queryType.toLowerCase() === "recommendedcontentitems.search") {
            RecommendedContent(searchResult, reinventPaginationTotalPages);
        } else {
            AllResults(searchResult);
        }
        ShowNumberResults(searchResult, reinventPaginationTotalPages);
        DidYouMean(searchResult);
        DisplayRecentSearch();
        FeaturedSectionDisplayControl();

        var resultsPerPagination = searchHeroSettings.componentsettings.maximumsearchresultsperpagination;
        var indexResults = (queryType.toLowerCase() === "recommendedcontentitems.search" || queryType === "default-blogsbyblogname" || queryType === "default-blogsbyblogauthor" || queryType === "default-blogsbyblogtopic") ? resultsPerPagination * reinventPaginationCurrent - resultsPerPagination : 0;
        var maxIndexResults = (queryType.toLowerCase() === "recommendedcontentitems.search" || queryType === "default-blogsbyblogname" || queryType === "default-blogsbyblogauthor" || queryType === "default-blogsbyblogtopic") ? resultsPerPagination * reinventPaginationCurrent : searchResult.documents.length;

        for (; (indexResults < maxIndexResults && indexResults < searchResult.documents.length); indexResults++) {

            var recommendedContent = searchResult.documents[indexResults];

            SearchResultsElements(indexResults);

            $('.search-results-section').css({ "height": "auto" });
            $('.search-results-' + (indexResults) + ' .search-results-header').css({ "max-width": "auto" });

            var $searchResultsHeader = $('.search-results-' + (indexResults) + ' .search-results-header');
            var $searchResultsContent = $('.search-results-' + (indexResults) + ' .search-results-content');
            if (recommendedContent.all_contenttype.length > 0) {
                var sorteditems = recommendedContent.all_contenttype.sort(function (obj1, obj2) {
                    return obj1.name.localeCompare(obj2.name);
                });

                SearchResultsContentType($searchResultsContent, contentTypeItems, sorteditems, recommendedContent);
            }

            SearchResultsContent(recommendedContent, $searchResultsHeader, $searchResultsContent, indexResults);

            SearchResultsDateCategory(indexResults, recommendedContent, $searchResultsContent);

            SearchResultsTitle(indexResults, recommendedContent);

            var contentDescription = SearchResultsDescription(indexResults, recommendedContent, $searchResultsHeader);

            if (contentDescription !== null) {
                HighlightContentDescription(indexResults, contentDescription);
            }
            else {
                $('.search-results-' + (indexResults) + ' .content-description').html(contentDescription);
            }

            if ($('.search-results-' + (indexResults) + ' .date').text().length !== 0 && $('.search-results-' + (indexResults) + ' .category').text().length !== 0) {
                $('.search-results-' + (indexResults) + ' .search-results-divider').html("|");
                $('.search-results-' + (indexResults) + ' .search-results-divider').addClass('divider');
            }

            if ($('.search-results-' + (searchResult.documents.length - 1) + ' .search-results-content').is('[hidden]')) {
                $('.search-results-area').addClass('no-content-type-date');
            } else if (!$('.search-results-' + (searchResult.documents.length - 1) + ' .search-results-content').is('[hidden]')) {
                $('.search-results-area').removeClass('no-content-type-date');
            }
        }

        if (searchResult.documents.length > 0) {
            $(".search-results-container").show();
            AddEllipsis();
            resultCount = searchResult.documents.length;
        }

        if (window.location.search.indexOf('filter=') >= 0 && ifCheck === 0) {
            ManualAddFilter();
        }
    };

    var ManualAddFilter = function () {

        var arr = window.location.search.split('filter=')[1].replace(/%20/g, " ").replace(/%26/g, "&").split('+');
        for (var i = 0; i < arr.length; i++) {
            $(".redesign-search-filters input").each(function () {
                var filtername = $(this).val();
                var timeOut = "";
                if (filtername === arr[i]) {
                    $('.redesign-search-filters input[value="' + arr[i] + '"]').attr('checked', 'checked');
                    if (arr.length < 1) {
                        timeOut = 3000;
                    }
                    else {
                        timeOut = 0;
                    }
                    setTimeout(function () {
                        ifCheck = 0;
                        FilterResults();
                        if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
                            lastFilterCount = filtersSelected;
                            SearchFilterMobile();
                        }
                    }, timeOut);
                }
            });
        }
    };

    var SetSearchHeroSettings = function (data, searchResult) {
        if (typeof (Storage) !== "undefined") {
            data = JSON.stringify(searchResult);
            sessionStorage.setItem(storageSearchSettings, data);
            searchHeroSettings = JSON.parse(sessionStorage.getItem(storageSearchSettings));
        }
        else {
            searchHeroSettings = searchResult;
        }
    };

    var SetSuggestionQuery = function (data, searchResult) {
        if (typeof (Storage) !== "undefined") {
            data = JSON.stringify(searchResult);
            sessionStorage.setItem(storageAutocompleteKeywords, data);
        }

        autoCompleteKeywords = searchResult;

        if (autoCompleteKeywords != null) {
            InitializeKeywordSuggestions();
        }
    };

    var ShowResults = function (queryType, searchResult) {
        var data = "";
        lastKeyword = $searchHeroKeyword.val();
        lastKeywordSearchFilters = jQuery.extend(true, {}, searchHeroSettings);
        if (searchResult !== null) {
            if (queryType === "searchsettings.search") {
                SetSearchHeroSettings(data, searchResult);
                return;
            }
            else if (queryType === "suggestion.search") {
                SetSuggestionQuery(data, searchResult);
            }

            else if (queryType.toLowerCase() === "highlightedtopicitems.search") {
                if (searchResult !== 0) {
                    highlightedTopicCount = 1;
                    var $highlightedTopicArea = $('.highlighted-topic-area');

                    $highlightedTopicArea.removeClass('sr-only');
                }
                else {
                    highlightedTopicCount = 0;
                }
                isFeatureSearch = true;
                HighlightedTopicItems(searchResult);
            }

            else if (queryType.toLowerCase() === "recommendedcontentitems.search" || queryType.toLowerCase() === "searchbykeywords.search") {
                HideSearchResults();
                RecommendedSearchbyKeywords(queryType, searchResult);
            }

            else if (queryType.toLowerCase() === "featuredarticles.search" || queryType.toLowerCase() === "customized-featuredarticles.search" || queryType.toLowerCase() === "default-featuredarticles.search" ||
                queryType === "default-blogsbyblogname" ||
                queryType === "default-blogsbyblogauthor" || queryType === "default-blogsbyblogtopic") {
                RecommendedSearchbyKeywords(queryType, searchResult);
                $noResultsContainer.hide();
                $redesignlinebar.hide();
                $popularSearchContainer.hide();
                $searchTipsContainer.hide();
                localStorage.removeItem('ViewAllAttributes');
            }
        }
    };


    //Executing of Back Button
    $(window).on('popstate load', function () {
        if (!$viewAllClickTriggeredRedesignSERP) {
            var $redesignSearchPage = $('.redesign-search-page');
            if ($redesignSearchPage.length !== 0) {
                URLSearchParamsForIE();
                urlParams = new URLSearchParams(window.location.search);
                var $noResultsContainer = $('.no-results-container');
                var $redesignLineBar = $('.redesign-line-bar');
                var $recentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
                var $suggestionDropdown = $('.tt-dataset-keywordSuggestions .tt-suggestions');

                //This is for back only within the page
                if (window.location.search !== '' && window.location.search.indexOf('srk=') >= 0) {
                    if (lastKeyword === ReplaceEncodedKeyword(urlParams.get('srk'))) {
                        $searchHeroKeyword.typeahead('val', lastKeyword);
                    } else {
                        $searchHeroKeyword.typeahead('val', urlParams.get('srk'));
                    }
                    SpacesAndSingleCharacter();
                    if (ReplaceEncodedKeyword(urlParams.get('srk')).length > 1 && RemoveTags($searchHeroKeyword.val()) !== "" && !($searchHeroKeyword.typeahead('val').replace(/\s{1,}/g, '').length === 2 && RegExp("\"{2,}|'{2,}").test($searchHeroKeyword.typeahead('val').replace(/\s{1,}/g, '')))) {

                        reinventPaginationCurrent = urlParams.get('pg') === "" || urlParams.get('pg') === null ? 1 : parseInt(urlParams.get('pg'));

                        lastSortBy = urlParams.get('sb') === "" || urlParams.get('sb') === null ? 0 : parseInt(urlParams.get('sb'));

                        ifCheck = 0;
                        InitializeStartSearch(urlParams.get('srk').trim());
                    }
                } else {
                    //To display Popular Searches
                    lastKeyword = "";
                    if (window.performance.navigation.type !== 0 && window.location.search.indexOf('srk=') >= 0) {
                        $searchHeroKeyword.typeahead('val', urlParams.get('srk'));
                        SpacesAndSingleCharacter();
                        if (window.location.search !== '' && ReplaceEncodedKeyword(urlParams.get('srk')).length > 1 && RemoveTags($searchHeroKeyword.val()) !== "" && !($searchHeroKeyword.typeahead('val').replace(/\s{1,}/g, '').length === 2 && RegExp("\"{2,}|'{2,}").test($searchHeroKeyword.typeahead('val').replace(/\s{1,}/g, '')))) {
                            InitializeStartSearch(urlParams.get('srk').trim());
                        }
                    } else {
                        $searchHeroKeyword.typeahead('val', '');
                        SpacesAndSingleCharacter();
                    }
                    $noResultsContainer.hide();
                    $searchTipsContainer.hide();
                    $redesignLineBar.hide();
                }
                $recentSearchDropdown.hide();
                $suggestionDropdown.hide();
            }
        }
    });



    var AddEllipsis = function () {
        var ellipsis = $('.dot-ellipsis');
        var htmlLang = $("html").attr("lang");
        var isJapanese = htmlLang.match("ja");
        var isChinese = htmlLang.match("zh");
        var truncateBy = 'word';
        var isHeight = '100%';

        if (isJapanese !== null || isChinese !== null) {
            truncateBy = 'letter';
        }

        ellipsis.dotdotdot({
            ellipsis: '... ',
            /*	Whether to update the ellipsis: true/'window' */
            watch: window,
            truncate: truncateBy,
            height: isHeight
        });
    };

    var StringFormat = function (fmtstr) {
        var args = Array.prototype.slice.call(arguments, 1);
        return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
            return args[index];
        });
    };

    var GetSearchData = function (queryType, keywords, from) {
        if (queryType === "suggestion.search") {
            data = "{\"f\":" + from + ", " + "\"ss\": \"" + GetAutocompleteKeyword() + "\"}";
        }
        else {
            data = "{\"k\":\"" + FormatSearchHeroValue(keywords) + "\",\"f\":1,\"s\":10}";
        }

        return data;
    };

    var GetAutocompleteKeyword = function () {
        if (searchHeroSettings !== null) {
            return FormatSearchHeroValue(JSON.stringify(searchHeroSettings.autocomplete));
        }
        else {
            return "";
        }
    };

    var RemoveTags = function (keyword) {
        var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
        var tagOrComment = new RegExp('\\s*<(?:' + '!--(?:(?:-*[^->])*--+|-?)' + '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' + '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' + '|/?[a-z]' + tagBody + ')>', 'gi');
        var excludedCharacters = /[`%$^*()_+\=\[\]{}\\|<>\/~]/;
        var isKeywordUnclean;

        if (keyword) {
            var oldKeyword;
            do {
                oldKeyword = keyword;
                keyword = keyword.replace(tagOrComment, '').trim();
                isKeywordUnclean = excludedCharacters.test(keyword);
                if (isKeywordUnclean) {
                    keyword = keyword.replace(/[`%$^*()_+\=\[\]{}\\|<>\/~]/g, '');
                    return keyword;
                }
            } while (keyword !== oldKeyword);
            return keyword.replace(/&nbsp;|'&nbsp;'|'&nbsp'|"&nbsp;"|"&nbsp"|&nbsp|/g, '').trim();
        }
        return "";
    };

    var StoreLocalStorage = function (recentKeyword) {
        var $suggestionDropdown = $('.tt-dataset-keywordSuggestions .tt-suggestions');
        recentSearches.push(recentKeyword.replace(/\s{2,}/g, ' '));
        localStorage.setItem(storageRecentSearches, JSON.stringify(recentSearches));
        $suggestionDropdown.hide();
        InitializeStartSearch(recentKeyword);
    };

    var TabIndexAccessibility = function () {
        var $searchHeroButton = $('.search-hero-form .btn');
        $searchHeroButton.attr('tabindex', '-1');
        $searchHeroKeyword.attr('tabindex', '-1');
    };

    var FirefoxAccessibility = function () {
        if (navigator.userAgent.search("Firefox") >= 0) {
            $searchResultsBlock.attr('tabindex', '0');
            $searchResultsBlock.trigger("focus");
        }
    };

    var SafariAccessibility = function () {
        if (checkSafari) {
            $searchResultsBlock.attr('tabindex', '0');
            $searchResultsBlock.trigger("focus");
        }
    };

    var ConvertCharacter = function (keyword) {
        if (keyword.indexOf("&") > -1) {
            keyword = keyword.replace(new RegExp("&", 'g'), "%26");
        }

        return keyword;
    };

    var AddParameterURL = function (url, param, value, param2, pageVal, param3, sortVal, param4, filters) {
        var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))' + '(\\?|\\&)' + param2 + '=.*?(?=(&|$))' + '(\\?|\\&)' + param3 + '=.*?(?=(&|$))' + '(\\?|\\&)' + param4 + '=.*?(?=(&|$))'),
            qstring = /\?.+$/;
        var filterParam = '';

        if (filters.length !== 0) {
            for (var i = 0; i < filters.length; i++) {
                if (filters.length === 1) {
                    filterParam = filterParam.concat(ConvertCharacter(filters[i]));
                } else {
                    filterParam = filterParam.concat(ConvertCharacter(filters[i]), '+');

                }
            }
            if (filterParam.substr(-1) === '+') {
                filterParam = filterParam.substr(0, filterParam.length - 1);
            }
        }
        // Check if the parameter exists
        if (val.test(url)) {
            return url.replace(val, '$1' + param + '=' + value + '&' + param2 + '=' + pageVal + '&' + param3 + '=' + sortVal + '&' + param4 + '=' + filterParam);
        }
        else if (qstring.test(url)) {
            return url + '&' + param + '=' + value + '&' + param2 + '=' + pageVal + '&' + param3 + '=' + sortVal + '&' + param4 + '=' + filterParam;
        } else {
            return url + '?' + param + '=' + value + '&' + param2 + '=' + pageVal + '&' + param3 + '=' + sortVal + '&' + param4 + '=' + filterParam;
        }
    };

    var StoreRecentSearch = function () {
        var $searchHeroForm = $('.search-hero-form');
        var $viewAllContainer = $('.tt-suggestion.view-all-text-container');

        if (typeof (Storage) !== "undefined") {
            $searchHeroForm.on('submit', function (event) {
                TabIndexAccessibility();
                var $storeRecentSearch = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search');
                var $storeRecentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
                var removeTagsKeyword = RemoveTags($searchHeroKeyword.val());
                var finalKeyword = '';

                event.preventDefault();

                if (RemoveTags(lastKeyword) === "" || RemoveTags(lastKeyword) !== removeTagsKeyword) {
                    if (removeTagsKeyword !== '' && !$storeRecentSearch.hasClass('selected')) {
                        StoreLocalStorage(removeTagsKeyword);
                        finalKeyword = removeTagsKeyword;
                    }
                    else if ($storeRecentSearch.hasClass('selected')) {
                        $searchHeroKeyword.typeahead('val', $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search.selected p').text());
                        $storeRecentSearchDropdown.hide();
                        StoreLocalStorage();
                        finalKeyword = $searchHeroKeyword.val();
                    }
                }
                RecentSearchHide();
                if (!(checkSafari)) {
                    $searchHeroKeyword.trigger("blur");
                }
                FirefoxAccessibility();
                SafariAccessibility();
                SpacesAndSingleCharacter();
                lastKeyword = $searchHeroKeyword.val();

                if ($viewAllContainer.hasClass('tt-cursor')) {
                    $searchHeroKeyword.typeahead('val', ($viewAllContainer.attr('data-attribute-view-all-keyword')));
                }
            });
            SelectRecentSearch();
        }
        SearchHeroButton();
    };

    var SearchHeroButton = function () {
        var $searchHeroButton = $('.search-hero-form .btn');
        $searchHeroButton.on('click', function (event) {
            var $selectRecentSearch = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search');
            var $selectRecentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
            URLSearchParamsForIE();
            urlParams = new URLSearchParams(window.location.search);
            ResetArrays();

            if ($searchHeroKeyword.val() === "" && !$selectRecentSearch.hasClass('selected') && !$('.no-results-container').is(':visible')) {
                event.preventDefault();
                $selectRecentSearchDropdown.hide();
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', "", 'sb', "", 'filter', "");
                SpacesAndSingleCharacter();
                lastKeyword = $searchHeroKeyword.val();
                FirefoxAccessibility();
                SafariAccessibility();
            }
            else if ($searchHeroKeyword.val() === "" & lastKeyword !== "") {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', "", 'sb', "", 'filter', "");
            }
            else if ($searchHeroKeyword.val() !== "" && lastKeyword !== "" && $searchHeroKeyword.val() !== urlParams.get('srk')) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', 0, 'filter', "");
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
            }
            else if ($('.popular-searches-content').is(':visible') && !$('.search-tips-container').is(':visible')) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', 0, 'filter', "");
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
            }
            else if ($searchHeroKeyword.val() !== "" && $('.popular-searches-content').is(':visible') && $('.search-tips-container').is(':visible') && lastKeyword === "") {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', 0, 'filter', "");
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
            } else if ($searchHeroKeyword.val() !== "" && lastKeyword === "" && (typeof urlParams.get('srk') === 'undefined' || urlParams.get('srk') === null)) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', 0, 'filter', "");
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
            }
        });
    };

    var ClearSelected = function ($selectRecentSearch) {
        $selectRecentSearch.filter('[aria-selected="true"]').attr('aria-selected', 'false').attr('id', '');
    };

    var MarkSelected = function ($selectionToMark) {
        var activeItemId = 'selectedOption';
        $selectionToMark.attr('aria-selected', true).attr('id', activeItemId);
        if ($('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search#selectedOption').length === 0) {
            $searchHeroKeyword.attr('aria-activedescendant', activeItemId);
        }
        else {
            $searchHeroKeyword.attr('aria-activedescendant', '');
        }

    };

    var SelectRecentSearch = function () {
        var $selectRecentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');

        $searchHeroKeyword.on('keydown', function (event) {
            var key = event.keyCode;

            if ($selectRecentSearchDropdown.is(':visible') && (key === 40 || key === 38)) {
                var $selectRecentSearch = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search');
                var $recentSearchParent = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-searches');

                var key = event.keyCode;

                var $thisActiveItem = $selectRecentSearch.filter('[aria-selected="true"]'),
                    $nextMenuItem;

                if (!$selectRecentSearch.length) {
                    return;
                }

                if (key === 40) {
                    $nextMenuItem = ($thisActiveItem.length !== 0)
                        ? $thisActiveItem.next('li')
                        : $recentSearchParent.children().eq(0);
                }
                if (key === 38) {
                    $nextMenuItem = ($thisActiveItem.length !== 0)
                        ? $thisActiveItem.prev('li')
                        : $recentSearchParent.children().eq(-1);
                }
                ClearSelected($selectRecentSearch);
                MarkSelected($nextMenuItem);

                if ($selectRecentSearch.attr('aria-selected')) {
                    $searchHeroKeyword.typeahead('val', $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search#selectedOption').text());
                    $searchHeroKeyword.typeahead('close');
                    $('.tt-dataset-keywordSuggestions .tt-suggestions').hide();

                }



                var scrollElement;

                if ($('#search-form-label').attr('aria-activedescendant') === 'selectedOption') {
                    scrollElement = '.search-hero-keywords';
                } else if ($selectRecentSearch.attr('aria-selected')) {
                    scrollElement = $('#selectedOption').first();
                }
                $recentSearchParent.scrollTop(0);
                $recentSearchParent.scrollTop($(scrollElement).offset().top - $recentSearchParent.height());
            }
        });
    };

    var DisplayRecentSearch = function () {
        if (!RegExp("^\\s+$", "gm").test($searchHeroKeyword.val())) {
            localStorage.setItem(storageRecentSearches, JSON.stringify(recentSearches));

            for (var outerLoop = 0; outerLoop < JSON.parse(localStorage.getItem(storageRecentSearches)).length; outerLoop++) {
                for (var innerLoop = outerLoop + 1; innerLoop < JSON.parse(localStorage.getItem(storageRecentSearches)).length; innerLoop++) {
                    if (JSON.parse(localStorage.getItem(storageRecentSearches))[outerLoop].replace(/\s{2,}/g, ' ').trim() === JSON.parse(localStorage.getItem(storageRecentSearches))[innerLoop].replace(/\s{2,}/g, ' ').trim()) {
                        recentSearches.splice(outerLoop, 1);
                        localStorage.setItem(storageRecentSearches, JSON.stringify(recentSearches));
                    }
                }
            }
            if (localStorage.getItem(storageRecentSearches) !== '[]') {
                recentSearches.forEach(function (returnRecentSearch) {
                    var $displayRecentSearchParent = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-searches');
                    jQuery('<li/>', {
                        class: 'recent-search autocomplete-item'
                    }).prependTo($displayRecentSearchParent);
                    jQuery('<p/>', {
                        text: returnRecentSearch
                    }).appendTo($('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search:first-of-type'));

                    $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').attr('aria-selected', false);
                    $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').attr('role', 'option');

                    var $displayRecentSearch = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search');
                    var $recentSearchText = $('.search-hero-form .recent-search p');

                    $recentSearchText.attr('data-analytics-content-type', 'search activity');

                    if ($('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').length > searchHeroSettings.componentsettings.maximumrecentsearch) {
                        $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search:last-of-type').remove();
                    }

                    for (var outerLoop = 0; outerLoop < $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').length; outerLoop++) {
                        for (var innerLoop = outerLoop + 1; innerLoop < $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').length; innerLoop++) {
                            if ($recentSearchText[outerLoop].innerHTML.replace(/\s{2,}/g, ' ').trim() === $recentSearchText[innerLoop].innerHTML.replace(/\s{2,}/g, ' ').trim()) {
                                $displayRecentSearch[innerLoop].remove();
                            }
                        }
                        $recentSearchText[outerLoop].setAttribute('data-analytics-link-name', $recentSearchText[outerLoop].innerHTML.toLowerCase());
                    }
                });
            }
        }
    };

    var RecentSearchHide = function () {
        var $recentSearchParent = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-searches');
        var $recentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
        var $recentSearchChild = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search');

        $recentSearchParent.scrollTop(0);
        $recentSearchDropdown.hide();
        $recentSearchChild.filter('[aria-selected="true"]').attr('aria-selected', 'false').attr('id', '');
    };

    var SearchFieldMouseEvents = function ($recentSearchParent, $recentSearchDropdown) {
        $searchHeroKeyword.on('click', function () {
            if ($searchHeroKeyword.val() !== "") {
                $recentSearchDropdown.hide();
            }
        });

        //Clicking outside of recent search dropdown
        $(document).on("mouseup", function (event) {

            if (!$recentSearchParent.is(event.target) && $recentSearchParent.has(event.target).length === 0) {
                RecentSearchHide();
            }
        });
    };

    var SearchFieldKeyboardEvents = function (event, $recentSearchParent, $recentSearchDropdown) {
        $searchHeroKeyword.off('keyup').on('keyup', function (event) {
            if ($('.redesign-search-page .tt-suggestions').is(':visible')) {
                $recentSearchDropdown.hide();
            }
            if ($searchHeroKeyword.val() !== "" && !(event.keyCode === 38 || event.keyCode === 40)) {
                RecentSearchHide();
            }
        }).on('paste', function () {
            $recentSearchDropdown.hide();
        }).on('cut', function () {
            $recentSearchDropdown.show();
        });

        if (event.keyCode === 8) {
            $recentSearchParent.scrollTop(0);
            $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').removeClass('selected');
        }
        if (event.keyCode === 27) {
            RecentSearchHide();
        }

        $(document).off('keydown').on('keydown', function (e) {
            var $searchHeroButton = $('.search-hero-form .btn');
            if (e.key === 'Tab' && e.shiftKey) {
                $searchHeroButton.attr('tabindex', '0');
                $searchHeroKeyword.attr('tabindex', '0');
                if ($('.redesign-search-page .tt-suggestion.view-all-text-container').hasClass('tt-cursor')) {
                    $searchHeroKeyword.typeahead('val', $searchHeroKeyword.val());
                } else if ($('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestion').hasClass('tt-cursor')) {
                    $searchHeroKeyword.typeahead('val', $('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestion.tt-cursor').text());
                } else {
                    $recentSearchDropdown.hide();
                }
            } else if ($('.search-results-block').is(':focus')) {
                $searchHeroKeyword.attr('tabindex', '0');
                $searchHeroButton.attr('tabindex', '0');
                $searchResultsBlock.removeAttr('tabindex');
            }
            if (e.key === 'Tab' && $('.redesign-search-page .tt-dataset-keywordRecentSearches').is(':visible')) {
                $searchHeroButton.attr('tabindex', '0');
            }
        });

        $(document).on('keydown keyup', '.search-hero-form', function (event) {
            if (event.key === 'Tab' && $('.redesign-search-page .btn').is(':focus')) {
                RecentSearchHide();
            }
            else if (event.key === 'Tab' && $searchHeroKeyword.val() === '') {
                $recentSearchDropdown.show();
            } else if (event.key === 'Tab') {
                RecentSearchHide();
            }
        });
    };

    var EventHandlers = function () {
        var $recentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
        var $recentSearchParent = $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-searches');
        var $dropdownMenu = $('.redesign-search-page .tt-dropdown-menu');

        $dropdownMenu.addClass('col-xs-12 col-sm-10');

        if ($searchHeroKeyword.val() === "") {
            var $searchHeroButton = $('.search-hero-form .btn');
            $(document).on('click keyup', '.redesign-search-page .tt-input.search-hero-keywords', function () {
                if (!(checkSafari)) {
                    $searchHeroButton.attr('tabindex', '0');
                }
                if (!$('.redesign-search-page .tt-suggestions').is(':visible') && $searchHeroKeyword.val() === "") {
                    if (event.keyCode === 13) {
                        $recentSearchDropdown.hide();
                        TabIndexAccessibility();
                        if (!(navigator.userAgent.search("Firefox") >= 0) || !(checkSafari)) {
                            $searchHeroKeyword.trigger("blur");
                        }
                    } else {
                        $recentSearchDropdown.show();
                    }
                } else if (!$('.redesign-search-page .tt-suggestions').is(':visible') && $searchHeroKeyword.val() !== "") {
                    if (event.keyCode === 13) {
                        if (!(checkSafari)) {
                            $searchHeroKeyword.trigger("blur");
                        }
                        FirefoxAccessibility();
                        SafariAccessibility();
                    }
                }
                SearchFieldMouseEvents($recentSearchParent, $recentSearchDropdown);
                SearchFieldKeyboardEvents(event, $recentSearchParent, $recentSearchDropdown);

            });
            $(document).on('click', '.tt-dataset-keywordSuggestions .tt-suggestion', function () {
                $searchResultsBlock.trigger("focus");
                if (!(checkSafari)) {
                    $searchHeroKeyword.trigger("blur");
                }
                FirefoxAccessibility();
                SafariAccessibility();
            });
        } else {
            $(document).on('click keyup', '.redesign-search-page .tt-input.search-hero-keywords', function () {
                RecentSearchHide();
            });
        }
    };

    var ClearedFeaturedSearchResults = function () {
        var $highlightTopicContainer = $('.highlighted-topic-container');
        var $highlightedTopicFeaturedImage = $('.highlighted-topic-container .highlighted-topic-section .featured-article-image');
        var $featuredReadMore = $('.highlighted-topic-container .highlighted-topic-section .highlghted-topic-readmore');
        var $featuredHeader = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-content .featured-article-header');
        var $featuredDescription = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-desc');
        var $featuredRegister = $('.highlighted-topic-container .highlighted-topic-section .highlighted-topic-register');
        var $hightlightedTopicFeatured = $('.highlighted-topic-featured');

        $highlightTopicContainer.hide();
        $highlightedTopicFeaturedImage.empty();
        $featuredHeader.empty();
        $featuredHeader.text("Featured Title");
        $featuredDescription.empty();
        $featuredRegister.hide();
        $hightlightedTopicFeatured.hide();
        $featuredReadMore.hide();
    };

    var HideSearchResults = function () {
        var $recommendedHeroSection = $(".search-results-container");
        var $clearSearchResultsSection = $('.search-results-section');
        var $searchResultsContainer = $('.results-for-keyword-container');
        var $highlightedTopicContainer = $('.highlighted-topic-container');
        var $noResultsContainer = $('.no-results-container');
        var $searchTips = $('.search-tips-container');
        var $redesignLineBar = $('.redesign-line-bar');
        var $popularSearches = $('.popular-searches-container');

        $clearSearchResultsSection.empty();
        $searchResultsContainer.hide();
        $highlightedTopicContainer.hide();
        $noResultsContainer.hide();
        $searchTips.hide();
        $redesignLineBar.hide();
        $popularSearches.hide();
        $recommendedHeroSection.hide();
        // clearRelatedJobsSection();
    };

    var highlightedForFiltersDisplayControl = function (highlightedTopicCount) {
        var $highlightedTopicArea = $('.highlighted-topic-area');
        var $highlightedTopicContainer = $('.search-results-block .highlighted-topic-container');

        if (highlightedTopicCount === 1 && (parseInt(urlParams.get('pg')) === 1 || urlParams.get('pg') === "" || urlParams.get('pg') === null)) {
            $highlightedTopicContainer.show();
            $highlightedTopicArea.show();
        } else {
            $highlightedTopicContainer.hide();
            $highlightedTopicArea.hide();
        }
    };

    var FeaturedSectionDisplayControl = function () {
        var $highlightedTopicArea = $('.highlighted-topic-area');
        var $highlightedTopicContainer = $('.search-results-block .highlighted-topic-container');

        if (reinventPaginationCurrent === 1 && highlightedTopicCount > 0) {
            $highlightedTopicContainer.show();
            $highlightedTopicArea.show();
        } else {
            $highlightedTopicContainer.hide();
            $highlightedTopicArea.hide();
        }
    };

    var ReplaceAllReservedCharacter = function (str, find, replace) {
        return str.replace(new RegExp(find, 'g'), replace);
    };

    var ReplaceEncodedKeyword = function (keyword) {
        var cleanedKeyword = keyword.replace(/[`%$^*()_+\=\[\]{}\\|<>\/~]/g, '');

        if (keyword.indexOf("/") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "/", "%2F");
        if (keyword.indexOf("?") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "\\?", "%3F");
        if (keyword.indexOf(":") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, ":", "%3A");
        if (keyword.indexOf("@") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "@", "%40");
        if (keyword.indexOf("=") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "=", "%3D");
        if (keyword.indexOf("&") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "&", "%26");
        if (keyword.indexOf("#") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, "#", "%23");
        if (keyword.indexOf(" ") > -1)
            keyword = ReplaceAllReservedCharacter(cleanedKeyword, " ", "%20");

        return keyword;
    };

    var SpacesAndSingleCharacter = function () {
        var $resultsForKeywordContainer = $('.results-for-keyword-container');
        var $allResultsContainer = $('.all-results-container');
        var $noResultsHeader = $('.no-results-header');
        var $searchTips = $('.search-results-block .search-tips');
        var $searchTipsContent = $('.search-results-block .search-tips-content');
        var $searchResultsSection = $('.search-results-section');
        var searchInput = RemoveTags($searchHeroKeyword.val());
        var $highlightedTopicContainer = $('.search-results-block .highlighted-topic-container');
        var $showNumberResultsContainer = $('.show-number-of-results');
        var $reinventPagination = $('.search-results-block .reinvent-pagination');
        var $recommendedContainer = $('.recommended-content-container');
        var $searchResultsBlock = $('.search-results-block');
        var $searchResultsArea = $('.search-results-area');
        var $highlightedTopicArea = $('.highlighted-topic-area');
        var $popularSearchesLastList = $('.popular-searches-content li:last-of-type');
        var $popularSearchesLink = $('.popular-searches-content a');
        var $searchTipsContainer = $('.search-tips-container');
        var $didyoumeanContainer = $('.search-results-block .did-you-mean-container');

        if (RemoveTags(lastKeyword) === "" || RemoveTags(lastKeyword) !== searchInput) {
            HideSearchResults();
            clearRelatedJobsSection();
            ClearedFeaturedSearchResults();
            isLessThanFilterVisiblity = false;
            isNoFilterResults = true;
            HideFilters();
            if ((searchInput.length <= 1 || searchInput === '' || (searchInput.replace(/\s{1,}/g, '').length === 2 && (RegExp("\"{2,}|'{2,}").test(searchInput) || RegExp("(^'[\\S\\s]*'$)", "gm").test(searchInput) || RegExp("(^\"[\\S\\s]*\"$)", "gm").test(searchInput)))) && !$('.search-results-container .search-results-section').is(':visible')) {
                $didyoumeanContainer.hide();
                $resultsForKeywordContainer.hide();
                $allResultsContainer.hide();
                $highlightedTopicContainer.hide();
                $highlightedTopicArea.hide();
                $searchResultsBlock.addClass('search-results-block-space');
                $searchResultsArea.addClass('no-search-results-space');
                $searchResultsArea.removeClass('no-content-type-date');
                $popularSearchesLastList.removeClass('onload-space');
                $popularSearchesLink.addClass('cta');
                $highlightedTopicArea.addClass('sr-only');

                $searchTipsContainer.show();
                $searchTips.show();
                $searchTipsContent.show();
                $searchTips.empty().append($searchTipsContainer.attr('data-attribute-search-tips'));
                $searchTipsContent.empty().append($searchTipsContainer.attr('data-attribute-searchTips-content'));

                var $searchResultsAndroidList = $('.search-results-area ul');

                if (navigator.userAgent.match(/Android/i)) {
                    $searchResultsAndroidList.addClass('search-results-android-list');
                }
                lastKeyword = $searchHeroKeyword.val();
                $noResultsContainer.show();
                $noResultsHeader.empty().append($noResultsContainer.attr('data-attribute-no-results').replace('{keyword}', searchInput));
                $searchResultsSection.css('height', '0');

                $redesignlinebar.show();
                $popularSearchContainer.show();

                $showNumberResultsContainer.hide();
                $reinventPagination.hide();

                $recommendedContainer.hide();
                FeaturedSectionDisplayControl();

                DisplayRecentSearch();
            }
        }
    };

    var InitializeStartSearch = function (initializeSearchInput) {
        if (RemoveTags(lastKeyword) === "" || RemoveTags(lastKeyword) !== initializeSearchInput || urlParams.get('pg') !== null || urlParams.get('sb') !== null) {
            HideSearchResults();
            clearRelatedJobsSection();
            ClearedFeaturedSearchResults();

            if (initializeSearchInput !== '') {
                if (searchHeroSettings !== null) {
                    if (initializeSearchInput.length >= searchHeroSettings.componentsettings.minimumkeywordlength && !(initializeSearchInput.replace(/\s{1,}/g, '').length === 2 && RegExp("\"{2,}|'{2,}").test(initializeSearchInput.replace(/\s{1,}/g, '')))) {
                        AriaLiveControl($(".show-number-of-results"), false);
                        AriaLiveControl($(".results-for-keyword-container"), true);
                        StartSearch(initializeSearchInput);
                        DisableForm();
                    }
                }
            }
        }
    };

    var StartSearch = function (searchInput) {
        var hasRecommendedContents = false;

        if (searchHeroSettings != null) {
            RemoveAllFilters();
            URLSearchParamsForIE();
            urlParams = new URLSearchParams(window.location.search);
            var maximumResults = searchHeroSettings.componentsettings.maximumsearchresultsperpagination;

            pageNum = urlParams.get('pg') === null ? 1 : parseInt(urlParams.get('pg'));

            if (urlParams.get('sb') !== null) {
                lastSortBy = urlParams.get('sb') > -1 && urlParams.get('sb') < 2 ? parseInt(urlParams.get('sb')) : 0;
            }

            var searchArray = maximumResults * pageNum + 1 - maximumResults;

            if (searchHeroSettings.componentsettings.showhighlightedtopic === true && searchHeroSettings.highlightedtopickeywords !== null) {
                for (var i = 0; i < searchHeroSettings.highlightedtopickeywords.length; i++) {
                    if (searchHeroSettings.highlightedtopickeywords[i].toLowerCase() === searchInput.toLowerCase()) {

                        highlightedForFilters = 1;
                        lastHighlightedtopickeywords = searchHeroSettings.highlightedtopickeywords[i];
                        highlightedtopicitemsquery = false;
                        hasHighlightedTopic = true;
                        PerformSearch(true, "highlightedtopicitems.search", searchInput, 1,
                            searchHeroSettings.componentsettings.maxhighlightedtopicitems, null, searchHeroSettings.highlightedtopickeywords[i]);
                        break;
                    }
                    else {
                        highlightedForFilters = 0;
                    }
                }
            }

            if (searchHeroSettings.componentsettings.showrecommendedcontent === true && searchHeroSettings.recommendedcontentkeywords !== null) {
                resultCount = 0;
                for (var i = 0; i < searchHeroSettings.recommendedcontentkeywords.length; i++) {
                    for (var ii = 0; ii < searchHeroSettings.recommendedcontentkeywords[i].keywords.length; ii++) {
                        if (searchHeroSettings.recommendedcontentkeywords[i].keywords[ii].toLowerCase() === searchInput.toLowerCase()) {

                            lastRecommendedcontentkeywords = searchHeroSettings.recommendedcontentkeywords[i]._id;
                            PerformSearch(true, "recommendedcontentitems.search", searchHeroSettings.recommendedcontentkeywords[i]._id, 1,
                                searchHeroSettings.componentsettings.maxrecommendedcontentitems, lastSortBy, "", "", "", true);
                            hasRecommendedContents = true;
                            break;
                        }
                    }
                }
            }

            if (hasRecommendedContents === false) {
                resultCount = 0;

                if (RegExp("^'.*?'$", "gm").test(searchInput)) {
                    lastSortBy = GetSortOptionId("exactmatch");
                }

                PerformSearch(true, "searchbykeywords.search", searchInput, searchArray, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, "", "", "", true);
            }
            showRelatedJobs(searchInput);
        }
    };

    var GetSortOptionId = function (targetType) {
        if ((searchHeroSettings.sortType !== null || searchHeroSettings.sortType.length > 0) &&
            (targetType !== null || typeof (targetType) !== 'undefined')) { //targetType must contains value for .toLowerCase()
            var target = targetType.toLowerCase();
            for (var index = 0; index < searchHeroSettings.sortType.length; index++) {
                if (target === searchHeroSettings.sortType[index].sort.toLowerCase()) {
                    return searchHeroSettings.sortType[index].id;
                }
            }
        }
        return 0; //default - relevancy
    };

    var SearchTips = function (searchResult) {
        var $searchTips = $('.search-results-block .search-tips');
        var $searchTipsContent = $('.search-results-block .search-tips-content');
        var $searchTipsContainer = $('.search-tips-container');
        var $searchResultsSection = $('.search-results-section');
        viewAllKeyword = $(".tt-suggestion.view-all-text-container").attr('data-attribute-view-all-keyword');

        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "")) {
            $searchTips.hide();
            $searchTipsContent.hide();
            $searchTipsContainer.hide();
            $searchResultsSection.show();
        }
        else if (!$('.search-results-container .search-results-section').is(':visible')) {
            $searchTips.show();
            $searchTips.empty().append($searchTipsContainer.attr('data-attribute-search-tips'));
            $searchTipsContent.empty().append($searchTipsContainer.attr('data-attribute-searchTips-content'));
            $searchTipsContent.show();
            $searchTipsContainer.show();
        }
    };

    var RemoveQuotes = function (header, container, attribute) {
        if (RegExp("(^'[\\S\\s]*'$)", "ig").test(RemoveTags($searchHeroKeyword.typeahead('val')))) {
            header.empty().append(container.attr(attribute).replace('{keyword}', RemoveTags($searchHeroKeyword.val().replace(/(^'|'$)/g, '').trim())));
        } else if (RegExp("(^\"[\\S\\s]*\"$)", "ig").test(RemoveTags($searchHeroKeyword.typeahead('val')))) {
            header.empty().append(container.attr(attribute).replace('{keyword}', RemoveTags($searchHeroKeyword.val().replace(/(^"|"$)/g, '').trim())));
        } else if (BlogNameKeyword && RemoveTags($searchHeroKeyword.typeahead('val')) === "") {
            header.empty().append(container.attr(attribute).replace('{keyword}', BlogNameKeyword));
        } else if (BlogAuthorKeyword && RemoveTags($searchHeroKeyword.typeahead('val')) === "") {
            header.empty().append(container.attr(attribute).replace('{keyword}', BlogAuthorName ? BlogAuthorName : BlogAuthorKeyword));
        } else if (BlogTopicKeyword && RemoveTags($searchHeroKeyword.typeahead('val')) === "") {
            var keywordText = BlogTopicKeyword.split("|");
            header.empty().append(container.attr(attribute).replace('{keyword}', keywordText[1]));
        } else {
            header.empty().text(container.attr(attribute).replace('{keyword}', RemoveTags($searchHeroKeyword.val().replace(/\s{2,}/g, ' ').trim())));
        }
    };


    var NoSearchResults = function (searchResult, reinventPaginationTotalPages) {
        var $noResultsHeader = $('.no-results-header');
        var $searchResultsSection = $('.search-results-section');
        var $popularSearchesHeader = $('.search-results-block .popular-searches-container .subsection-title');
        var $popularSearchesContent = $('.search-results-block .popular-searches-container .popular-searches-content');
        var $highlightedTopicContainer = $('.highlighted-topic-container');
        var $searchResultsBlock = $('.search-results-block');
        var $searchResultsArea = $('.search-results-area');
        var $popularSearchesLastList = $('.popular-searches-content li:last-of-type');
        viewAllKeyword = $(".tt-suggestion.view-all-text-container").attr('data-attribute-view-all-keyword');

        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "")) {
            $noResultsContainer.hide();
            $searchResultsSection.show();
            $redesignlinebar.hide();
            $popularSearchContainer.hide();
            $highlightedTopicContainer.show();
            $searchResultsBlock.removeClass('search-results-block-space');
            $searchResultsArea.removeClass('no-search-results-space');
            $searchResultsArea.removeClass('prefiltered');
        }
        else if (!$('.search-results-container .search-results-section').is(':visible')) {
            RemoveQuotes($noResultsHeader, $noResultsContainer, 'data-attribute-no-results');
            $noResultsContainer.show();
            $redesignlinebar.show();
            $popularSearchContainer.show();
            $searchResultsBlock.addClass('search-results-block-space');
            $searchResultsArea.addClass('no-search-results-space');
            $popularSearchesLastList.removeClass('onload-space');
            $popularSearchesHeader.empty().append($popularSearchContainer.attr('data-attribute-popular-searches'));
            $popularSearchesContent.empty().append($popularSearchContainer.attr('data-attribute-popularSearches-content'));
            $('.popular-searches-content li a').attr('tabindex', '0').attr('data-analytics-content-type', 'search activity');
            for (var PopularSearchesCounter = 0; PopularSearchesCounter < $('.popular-searches-content a').length; PopularSearchesCounter++) {
                $popularSearchesInnerText = $('.popular-searches-content a')[PopularSearchesCounter].innerText;
                $popularSearchesTextForAnalytics = $('.popular-searches-content a')[PopularSearchesCounter];
                $popularSearchesTextForAnalytics.setAttribute('data-analytics-link-name', $popularSearchesInnerText.toLowerCase());
            }

            var $searchResultsAndroidList = $('.search-results-area ul');
            var $popularSearchesLink = $('.popular-searches-content a');

            $popularSearchesLink.addClass('cta');

            if (navigator.userAgent.match(/Android/i)) {
                $searchResultsAndroidList.addClass('search-results-android-list');
            }
        }
    };

    var ResultsForKeyword = function (searchResult, reinventPaginationTotalPages) {
        var $resultsForKeywordContainer = $('.results-for-keyword-container');
        var $resultsForKeyword = $('.results-for-keyword');
        var $highlightedTopicContainer = $('.highlighted-topic-container');
        var $noResultsContainer = $('.no-results-container');
        var $searchTips = $('.search-tips-container');
        var $redesignLineBar = $('.redesign-line-bar');
        var $popularSearches = $('.popular-searches-container');
        var $searchFilter = $('.redesign-search-filters-container');
        lastKeyword = $searchHeroKeyword.val();

        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "") || ((BlogNameKeyword || BlogAuthorKeyword || BlogTopicKeyword) && RemoveTags($searchHeroKeyword.typeahead('val')) === "")) {
            RemoveQuotes($resultsForKeyword, $resultsForKeywordContainer, 'data-attribute-results-for-keyword');
            $resultsForKeywordContainer.show();
            $highlightedTopicContainer.show();
            $searchResultsArea.removeClass('prefiltered');
            $resultsForKeywordContainer.removeClass('hide');
            $searchFilter.removeClass('hide');
        }
        else if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages) {
            $resultsForKeywordContainer.removeClass('hide');
            $searchFilter.removeClass('hide');
        }
        else {
            $highlightedTopicContainer.show();
            $resultsForKeywordContainer.hide();
            $noResultsContainer.show();
            $searchTips.show();
            $redesignLineBar.show();
            $popularSearches.show();
            $searchFilter.addClass('hide');
            $resultsForKeywordContainer.addClass('hide');
        }
    };

    var ShowNumberResults = function (searchResult) {
        var $showNumberResultsContainer = $('.show-number-of-results');
        var $shownResults = $('.number-of-results');
        var totalResult = searchResult.total;
        var first = maximumNumberOfResults * reinventPaginationCurrent + 1 - maximumNumberOfResults;
        var last = "";
        var $totalResults = $('.search-results-area .total-results');
        $totalResults.html("Showing " + totalResult + " results");

        if (lastQueryType == "recommendedcontentitems.search" || lastQueryType == "default-blogsbyblogname" || lastQueryType == "default-blogsbyblogauthor" || lastQueryType == "default-blogsbyblogtopic") {
            last = first + searchHeroSettings.componentsettings.maximumsearchresultsperpagination - 1;
        }
        else {
            last = first + searchResult.documents.length - 1;
        }

        if (totalResult <= searchHeroSettings.componentsettings.maximumsearchresultsperpagination) {
            last = totalResult;
        }

        if (reinventPaginationTotalPages == reinventPaginationCurrent) {
            last = searchResult.total;
        }
        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "" || $viewAllClickTriggeredRedesignSERP)) {
            $shownResults.empty().append($showNumberResultsContainer.attr('data-attribute-number-of-results').replace('{first}', first).replace('{last}', last).replace('{total}', totalResult));
            $showNumberResultsContainer.show();
        }
        else {
            $showNumberResultsContainer.hide();
        }
    };

    var DidYouMean = function (searchResult, hidden) {

        var $didyoumeanContainer = $('.search-results-block .did-you-mean-container');
        var $didyoumeanContent = $('.search-results-block .did-you-mean-content');
        var didYouMean = "";

        var $resultsForKeywordContainer = $('.results-for-keyword-container');

        if (showSuggestedTerm) {
            if (hidden) {
                $didyoumeanContainer.hide();
            } else if (searchResult.didYouMean != null) {

                if (searchResult.originalKeyword != null) {
                    //reserved for search instead functionality
                    $didyoumeanContainer.hide();
                }
                else {
                    didYouMean = '<a tabindex="0" id="did-you-mean-link" data-linkcomponentname="did you mean" data-linktype="search activity" data-analytics-content-type="search activity"><span class="did-you-mean-link-text" data-analytics-link-name="' + searchResult.didYouMean + '">' + searchResult.didYouMean + '</span></a>';
                    $didyoumeanContent.empty().append($didyoumeanContainer.attr('data-attribute-did-you-mean').replace('{suggestedTerm}', didYouMean));
                    $("#did-you-mean-link").addClass("cta");
                    $didyoumeanContainer.show();

                    if ($resultsForKeywordContainer.css("display", "block")) {
                        $(".did-you-mean-container").addClass("col-lg-8 col-md-8");
                    }
                }
            }
            else {
                $didyoumeanContainer.hide();
            }
        }
    };

    var AllResults = function (searchResult) {
        var $allResultsContainer = $('.all-results-container');
        var $allResults = $('.all-results');
        var $recommendedContainer = $('.recommended-content-container');
        var $highlightedTopicContainer = $('.highlighted-topic-container');
        var $highlightedTopicArea = $('.highlighted-topic-area');

        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "" || $viewAllClickTriggeredRedesignSERP)) {
            $allResults.empty().append($allResultsContainer.attr('data-attribute-all-results'));
            $allResultsContainer.show();
            $recommendedContainer.hide();
            if (highlightedTopicCount === 0) {
                $highlightedTopicContainer.hide();
                $highlightedTopicArea.hide();
            }
        }
        else {
            $allResultsContainer.hide();
            $recommendedContainer.hide();
            $highlightedTopicArea.addClass('sr-only');
        }
    };

    var RecommendedContent = function (searchResult) {
        var $recommendedContainer = $('.recommended-content-container');
        var $recommendedContent = $('.recommended-content-container .recommended-content');
        var $allResultsContainer = $('.all-results-container');

        if (searchResult.documents.length > 0 && pageNum <= reinventPaginationTotalPages && (RemoveTags($searchHeroKeyword.typeahead('val')) !== "" || RemoveTags(viewAllKeyword) !== "")) {
            $recommendedContent.empty().append($recommendedContainer.attr('data-attribute-recommended-content').toUpperCase());
            $recommendedContainer.show();
            $allResultsContainer.hide();
        }
        else {
            $recommendedContainer.hide();
            $allResultsContainer.hide();
        }
    };

    var ClickRecentSearch = function () {
        $(document).on('click', '.search-hero-form .recent-search p', function () {
            var $searchResultsBlock = $('.search-results-block');
            reinventPaginationCurrent = 1;
            lastSortBy = 0;
            AppendToURL('srk', ReplaceEncodedKeyword($(this).text()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', "");
            $searchResultsBlock.trigger("focus");
            if (IsIE()) {
                TabIndexAccessibility();
            }
            var $recentSearchDropdown = $('.redesign-search-page .tt-dataset-keywordRecentSearches');
            if (RemoveTags(lastKeyword) !== $(this).text()) {
                $searchHeroKeyword.typeahead('val', $(this).text().replace(/\s{2,}/g, ' ').trim());
                $recentSearchDropdown.hide();
                StoreLocalStorage(RemoveTags($searchHeroKeyword.val()));
                DisplayRecentSearch();
                SpacesAndSingleCharacter();
                lastKeyword = $searchHeroKeyword.val();
            }
            else {
                $searchHeroKeyword.typeahead('val', $(this).text().replace(/\s{2,}/g, ' ').trim());
                $recentSearchDropdown.hide();
                lastKeyword = $searchHeroKeyword.val();
            }
        });
    };

    var DisplayContentType = function (searchResult, contentTypeItems) {
        if (searchResult.acnfacets !== null) {
            for (var ctr = 0; ctr < searchResult.acnfacets.length; ctr++) {
                if (searchResult.acnfacets[ctr].metadatafieldname === "contenttype") {
                    for (var counter = 0; counter < searchResult.acnfacets[ctr].items.length; counter++) {
                        contentTypeItems.push(counter, searchResult.acnfacets[ctr].items[counter].term);
                    }
                    break;
                }
            }
        }
    };

    var ClickPopularSearches = function () {
        $(document).on('click', '.popular-searches-content li a', function () {
            reinventPaginationCurrent = 1;
            lastSortBy = 0;
            ResetArrays();
            AppendToURL('srk', ReplaceEncodedKeyword($(this).text()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', "");
            $searchHeroKeyword.typeahead('val', $(this).text());
            StoreLocalStorage(RemoveTags($(this).text()));
            SpacesAndSingleCharacter();
            DisplayRecentSearch();
        });
    };

    var EnterPopularSearches = function () {
        $(document).on('keyup', '.popular-searches-content li a', function (event) {
            if (event.keyCode === 13) {
                reinventPaginationCurrent = 1;
                lastSortBy = 0;
                ResetArrays();
                AppendToURL('srk', ReplaceEncodedKeyword($(this).text()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', "");
                $searchHeroKeyword.typeahead('val', $(this).text());
                StoreLocalStorage(RemoveTags($(this).text()));
                SpacesAndSingleCharacter();
                DisplayRecentSearch();
            }
        });
    };

    var OnLoadPopularSearches = function () {
        var $popularSearchesHeader = $('.search-results-block .popular-searches-container .subsection-title');
        var $popularSearchesContent = $('.search-results-block .popular-searches-container .popular-searches-content');
        var $searchResultsBlock = $('.search-results-block');
        var $searchResultsArea = $('.search-results-area');
        var $searchTipsContainer = $('.search-tips-container');

        $popularSearchesHeader.empty().append($popularSearchContainer.attr('data-attribute-popular-searches'));
        $popularSearchesContent.empty().append($popularSearchContainer.attr('data-attribute-popularSearches-content'));
        $('.popular-searches-content li a').attr('tabindex', '0').attr('data-analytics-content-type', 'search activity');
        for (var PopularSearchesCounter = 0; PopularSearchesCounter < $('.popular-searches-content a').length; PopularSearchesCounter++) {
            $popularSearchesInnerText = $('.popular-searches-content a')[PopularSearchesCounter].innerText;
            $popularSearchesTextForAnalytics = $('.popular-searches-content a')[PopularSearchesCounter];
            $popularSearchesTextForAnalytics.setAttribute('data-analytics-link-name', $popularSearchesInnerText.toLowerCase());
        }

        var $popularSearchesLink = $('.popular-searches-content a');
        var $popularSearchesLastList = $('.popular-searches-content li:last-of-type');
        var $searchResultsAndroidList = $('.search-results-area ul');


        $popularSearchesLink.addClass('cta');
        $popularSearchesLastList.addClass('onload-space');

        if (navigator.userAgent.match(/Android/i)) {
            $searchResultsAndroidList.addClass('search-results-android-list');
        }

        $searchTipsContainer.hide();
        $searchResultsArea.addClass('search-results-area-space');
        $searchResultsBlock.addClass('search-results-block-space');
    };

    var FormatDate = function (dateToConvert) {
        var convertedDate = "";
        var monthNames = new Array("January", "February", "March",
            "April", "May", "June", "July", "August", "September",
            "October", "November", "December");

        if (dateToConvert != null && dateToConvert != undefined) {
            var newDate = new Date(Date.parse(dateToConvert));
            convertedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear();
        }
        else {
            convertedDate = dateToConvert;
        }

        return convertedDate;
    };

    var AppendToURL = function (parameter, keyword, parameter2, pageNum, parameter3, sortByVal, parameter4, filters) {

        if (parameter === "" && keyword === "") {
            queryString = window.location.protocol + "//" + window.location.host + window.location.pathname;
        } else {
            queryString = AddParameterURL(queryString, parameter, keyword, parameter2, pageNum, parameter3, sortByVal, parameter4, filters);
        }
        window.history.pushState({ path: queryString }, '', queryString);
    };

    var DisableForm = function () {
        if ($searchHeroKeyword.val() !== "") {
            if (!$('.search-results-0').is(':visible')) {
                $('.search-hero-form .btn').attr('disabled', true);
                $('.search-hero-form .search-hero-keywords').attr('disabled', true);
            }
        }
    };

    var EnableForm = function () {
        if ($('.search-results-section').is(':visible') || $('.no-results-container').is(':visible')) {
            $('.search-hero-form .btn').prop('disabled', false);
            $('.search-hero-form .search-hero-keywords').prop('disabled', false);
        }
    };

    var CallBack = function (response, queryType) {
        if (response === null) {
            return;
        }
        ShowResults(queryType, response);
    };

    var PerformSuggestedTopicSearch = function (suggestedtopickeywords, keyword, maxitems, serpSetting) {
        var hasmanualtopics = false;
        suggestedtopicsquery = false;

        if (keyword != "") {
            if (serpSetting == "customized") {
                for (var i = 0; i < suggestedtopickeywords.length; i++) {
                    for (var ii = 0; ii < suggestedtopickeywords[i].keywords.length; ii++) {
                        if (suggestedtopickeywords[i].keywords[ii].toLowerCase() == keyword) {
                            suggestedtopicsquery = false;
                            PerformSearch(true, "viewall-suggestedtopics.search", keyword, 1, maxitems, null, null, suggestedtopickeywords[i]._id);
                            hasmanualtopics = true;
                            break;
                        }
                    }
                }
            }
        }
    };

    var PerformSearch = function (async, queryType, keywords, from, size, sortBy, referenceGuid, cherryPickIds, currentPageId, fromPagination) {
        var path = SetDefaultPath(GetPath());
        var data = GetSearchData(queryType, keywords, from);
        var blogKeyWords = "";
        isFeatureSearch = false;

        maximumNumberOfResults = size;
        lastQueryType = queryType;

        URLSearchParamsForIE();
        urlParams = new URLSearchParams(window.location.search);
        if (window.location.search.indexOf('srk') >= 0) {
            if (urlParams.get('srk') !== "" || urlParams.get('srk') !== null) {
                lastKeyword = urlParams.get('srk');
            }
        }
        else {
            lastKeyword = $searchHeroKeyword.val();
        }

        if (typeof cherryPickIds === 'undefined' || cherryPickIds === null) {
            cherryPickIds = "";
        }

        if (typeof currentPageId === 'undefined' || currentPageId === null) {
            currentPageId = "";
        }

        lastRefenceGuid = referenceGuid;
        lastCherryPickId = cherryPickIds;
        lastCurrentPageId = currentPageId;

        if (typeof sortBy === 'undefined' || sortBy === null) {
            sortBy = lastSortBy;
        }
        queryType = queryType.toLowerCase();
        var requestUrl = path + queryType;

        if (queryType === "suggestion.search") {
            var autoComp = "";
            if (searchHeroSettings != null) {
                autoComp = FormatSearchHeroValue(JSON.stringify(searchHeroSettings.autocomplete));
            }

            data = "{\"f\":" + from + ", " + "\"ss\": \"" + autoComp + "\"}";
        }
        else if (queryType === "recommendedcontentitems.search" || queryType === "searchbykeywords.search") {

            data = "{\"k\":\"" + FormatSearchHeroValue(keywords) + "\",\"f\":" + from + ",\"s\":" + size + ", \"sb\":" + sortBy + ", " + "\"ss\":\"" + subsite + "\", " +
                "\"df\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\",\"cs\":\"" + checkspell + "\"}";
        }
        else if (queryType === "highlightedtopicitems.search") {
            data = "{\"k\":\"" + FormatSearchHeroValue(referenceGuid) + "\",\"f\":" + from + ",\"s\":" + size + "}";
        }
        else if (queryType.toLowerCase() === "featuredarticles.search" || queryType.toLowerCase() === "customized-featuredarticles.search" || queryType.toLowerCase() === "default-featuredarticles.search") {
            data = "{\"k\":\"" + FormatSearchHeroValue(keywords) + "\",\"f\":" + from + ",\"s\":" + size + ",\"sb\":" + sortBy + ",\"cp\":\"" + cherryPickIds + "\",\"cpid\":\"" + currentPageId + "\", " +
                "\"df\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\", " + "\"rt\":\"resultitem\", " + "\"sp\": \"" + referenceGuid + "\"}";
        }
        else if (queryType === "default-blogsbyblogname") {
            blogKeyWords = keywords.split(",");
            data = "{\"blogName\":\"" + FormatSearchHeroValue(blogKeyWords[0]) + "\", \"blogIndustry\":\"" + blogKeyWords[1] + "\", \"blogSubject\":\"" + blogKeyWords[2] + "\", \"countrySite\":\"" + path.split('/')[1] + "\", \"defaultFacets\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\"}";
            requestUrl = "/api/sitecore/BlogPostcardsBlock/GetBlogsByBlogName";
        }
        else if (queryType === "default-blogsbyblogauthor") {
            data = "{\"authorEnterpriseId\":\"" + keywords + "\", \"countrySite\":\"" + path.split('/')[1] + "\", \"defaultFacets\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\"}";
            requestUrl = "/api/sitecore/BlogPostcardsBlock/GetBlogsByBlogAuthor";
        }
        else if (queryType === "default-blogsbyblogtopic") {
            keywords = keywords + "|";
            blogKeyWords = keywords.split("|");
            data = "{\"blogName\":\"" + blogKeyWords[0] + "\",\"blogTopic\":\"" + blogKeyWords[1] + "\",\"blogIndustry\":\"default\",\"blogSubject\":\"default\", \"countrySite\":\"" + path.split('/')[1] + "\", \"defaultFacets\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\"}";
            requestUrl = "/api/sitecore/BlogPostcardsBlock/GetBlogsByBlogTopic";
        }

        if (lastKeyword != keywords) {
            highlightedTopicCount = 0;
        }

        if (highlightedForFilters === 1) {
            highlightedTopicCount = 1;
        }
        else {
            highlightedTopicCount = 0;
        }

        highlightedForFiltersDisplayControl(highlightedTopicCount);

        $.ajax({
            type: "POST",
            url: requestUrl,
            data: data,
            async: async,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                CallBack(response, queryType);
                EnableForm();
                setSearchResultInDataModel();
                setInternalSearchKeywordInDataModel();
                if (fromPagination) {
                    ChangeFocus();
                    ScrollUp();
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                searchHeroSettings = null;
            }
        });
    };

    var SearchByQuery = {
        "highlightedtopicitems.search": function (from) {
            PerformSearch(true, "highlightedtopicitems.search", lastKeyword, from, maximumNumberOfResults, null, lastHighlightedtopickeywords, null, null, true);
        },
        "recommendedcontentitems.search": function (from) {
            lastKeyword = lastRecommendedcontentkeywords;
            PerformSearch(true, "recommendedcontentitems.search", lastRecommendedcontentkeywords, 1, searchHeroSettings.componentsettings.maxrecommendedcontentitems, null, null, null, null, true);
        },
        "searchbykeywords.search": function (from) {
            PerformSearch(true, lastQueryType, lastKeyword, from, maximumNumberOfResults, null, null, null, null, true);
        },
        "default-featuredarticles.search": function (from) {
            PerformSearch(true, lastQueryType, lastKeyword, from, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId, true);
        },
        "default-blogsbyblogname": function (from) {
            PerformSearch(true, lastQueryType, BlogNameKeyword + "," + BlogPostIndustry + "," + BlogPostSubject, from, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId, true);
        },
        "default-blogsbyblogauthor": function (from) {
            PerformSearch(true, lastQueryType, BlogAuthorKeyword, from, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId, true);
        },
        "default-blogsbyblogtopic": function (from) {
            PerformSearch(true, lastQueryType, BlogTopicKeyword, from, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId, true);
        }
    };

    var PreviousPage = function () {
        if (reinventPaginationCurrent > 1) {
            reinventPaginationCurrent--;
            $('.search-results-container .search-results-section').empty();
            if (/srk/.test(window.location.href)) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', filterArray);
            }
            AriaLiveControl($(".show-number-of-results"), true);
            AriaLiveControl($(".results-for-keyword-container"), false);
            var from = maximumNumberOfResults * reinventPaginationCurrent + 1 - maximumNumberOfResults;
            if (SearchByQuery[lastQueryType]) {
                ScrollUp();
                $searchHeroKeyword.typeahead('val', lastKeyword);
                SearchByQuery[lastQueryType](from);
            }
        }
    };

    var NextPage = function () {
        if (reinventPaginationCurrent < reinventPaginationTotalPages) {
            reinventPaginationCurrent++;
            $('.search-results-container .search-results-section').empty();
            if (/srk/.test(window.location.href)) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', filterArray);
            }
            AriaLiveControl($(".show-number-of-results"), true);
            AriaLiveControl($(".results-for-keyword-container"), false);
            var from = maximumNumberOfResults * reinventPaginationCurrent + 1 - maximumNumberOfResults;
            if (SearchByQuery[lastQueryType]) {
                ScrollUp();
                $searchHeroKeyword.typeahead('val', lastKeyword);
                SearchByQuery[lastQueryType](from);
            }
        }
    };

    var ChangePage = function (number) {
        if (resultCount > 0 && number != reinventPaginationCurrent) {
            $('.search-results-container .search-results-section').empty();
            if (/srk/.test(window.location.href)) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', number, 'sb', lastSortBy, 'filter', filterArray);
            }
            AriaLiveControl($(".show-number-of-results"), true);
            AriaLiveControl($(".results-for-keyword-container"), false);
            var from = maximumNumberOfResults * number + 1 - maximumNumberOfResults;
            if (SearchByQuery[lastQueryType]) {
                ScrollUp();
                $searchHeroKeyword.typeahead('val', lastKeyword);
                SearchByQuery[lastQueryType](from);
                reinventPaginationCurrent = parseInt(number);
            }
        }
    };

    var ScrollUp = function () {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    };

    var ChangeFocus = function () {
        var $firstResult = $(".search-results-container .search-results-section").first();
        $firstResult.attr("tabindex", "-1");
        $firstResult.trigger("focus");

        if (!IsIE()) {
            $firstResult.trigger("blur");
        }

        $firstResult.removeAttr("tabindex");
    };

    var AriaLiveControl = function ($element, $active) {
        if ($element) {
            if ($active) {
                $element.removeAttr("aria-live");
            } else {
                $element.attr("aria-live", "off");
            }
        }
    };

    $(reinventPaginationPrevious).on("click", function () {
        PreviousPage();
    });

    $(reinventPaginationNext).on("click", function () {
        NextPage();
    });

    $(reinventPaginationNumberBlock).on('click', reinventPaginationNumber, function (e) {
        var clickElement = e.target;
        if ($(event.target).hasClass("page-num") && clickElement.innerHTML != "...") {
            ChangePage(clickElement.innerText);
            e.preventDefault();
        }
    });


    $(document).on("click", ".did-you-mean-link-text", function (e) {
        checkspell = false;
        $('.did-you-mean-container').hide();
        var didYouMeanKeyword = e.target.innerText;
        $searchHeroKeyword.typeahead('val', didYouMeanKeyword);
        StartSearch(didYouMeanKeyword, false);
        checkspell = true;
        reinventPaginationCurrent = 1;
        lastSortBy = 0;
        ResetArrays();
        AppendToURL('srk', ReplaceEncodedKeyword($(this).val()), 'pg', reinventPaginationCurrent, 'sb', lastSortBy, 'filter', "");
    });

    $(document).on('keyup', '#did-you-mean-link', function (e) {
        if (e.keyCode == 13) {
            checkspell = false;
            $('.did-you-mean-container').hide();
            var didYouMeanKeyword = e.target.innerText;
            $searchHeroKeyword.typeahead('val', didYouMeanKeyword);
            StartSearch(didYouMeanKeyword, false);
            checkspell = true;
            reinventPaginationCurrent = 1;
            lastSortBy = 0;
            ResetArrays();
            AppendToURL('srk', ReplaceEncodedKeyword($(this).val()), 'pg', reinventPaginationCurrent = 1, 'sb', lastSortBy, 'filter', "");
        }
    });

    if (isMobile()) {
        var paginationDropdown = $(".pagination-dropdown");

        paginationDropdown.on("change", function () {
            ChangePage(parseInt($(this).val()));
        });
    }

    // checks for tablet device ranges 1024px
    var isSerpTablet = function (max) {
        var smMin = 768;
        var smMax = max || 999;
        if (window.innerWidth >= smMin && window.innerWidth <= smMax) {
            return true;
        } else {
            return false;
        }
    };

    var HideFilters = function () {
        var $filterDropdown = $dropDownMenuDiv.parent("div");
        var $didYouMeanContainer = $('.search-results-block .did-you-mean-container');

        $searchFiltersSortBy.removeClass("hidden");
        $searchFiltersContainer.removeClass("hidden");
        $searchFiltersContainer.removeClass("invisible");
        if (filterResultsContainer !== null) {
            filterResultsContainer.remove();
        }
        if (isNoFilterResults === true) {
            $searchFiltersContainer.addClass("hidden");
        }
        if (!jsUtility.isMobile() && !isSerpTablet(smallMaxWidth)) {
            if (isFiltersHidden === true) {
                $searchFiltersSortBy.addClass("hidden");
            }
            if ($filterDropdown) {
                $searchFiltersContainer.insertAfter($didYouMeanContainer);
            }
            $searchFilterResults.addClass("hidden");
            if ($filterDropdown.hasClass("modal")) {
                $filterDropdown.removeClass("modal");
            }
            if (isLessThanFilterVisiblity === true) {
                $searchFiltersSortBy.removeClass("hidden");
                $searchFiltersContainer.removeClass("hidden");
                $searchFiltersContainer.addClass("invisible");
            }
        } else {
            if (isFiltersHidden === true) {
                $searchFiltersContainer.addClass("hidden");
                $searchFiltersSortBy.addClass("hidden");
                $searchFilterResults.addClass("hidden");
            }
            if ($filterDropdown.hasClass("modal") === false) {
                $filterDropdown.addClass("modal");

            }
        }
        $searchFilters.empty();
        $searchFilterBy.empty();
        $searchFilterResults.empty();
        $searchFiltersSortBy.children("span").empty();
        $searchSortMostRelevant.empty();
        $searchSortMostRecent.empty();
        $applyButtonFilter.hide();
        $searchFilterFooter.addClass("hidden");
        $searchFilterBy.text("Filter By");
        $searchFilterResults.text("Filter Button");
    };

    var ShowSortByOnly = function () {
        $searchFilterResults.addClass("hidden");
        ToggleSort();
        var searchFiltersSortByAttr = $searchFiltersSortBy.attr("data-attribute-sort-by");
        var searchSortMostRelevantAttr = $searchSortMostRelevant.attr("data-analytics-link-name");
        var searchSortMostRecentAttr = $searchSortMostRecent.attr("data-analytics-link-name");
        $searchFiltersSortBy.children("span").prepend(searchFiltersSortByAttr);
        $searchSortMostRelevant.append(searchSortMostRelevantAttr);
        $searchSortMostRecent.append(searchSortMostRecentAttr);
        if (!isMobile()) {
            $searchFiltersSortBy.addClass("filter-sort-margin-bottom");
        }
    };

    // Display search filters
    var ShowFilters = function (acnfacets) {

        if (acnfacets) {

            HideFilters();
            ToggleSort();

            var facetCount = 0;
            var categoryCount = 0;
            var searchFiltersSortByAttr = $searchFiltersSortBy.attr("data-attribute-sort-by");
            var searchFilterByAttr = $searchFilterBy.attr("data-attribute-filter-by");
            var closeButtonAttr = $searchFiltersContainer.find(".reinvent-close-filter").attr("data-analytics-link-name");
            var searchSortMostRelevantAttr = $searchSortMostRelevant.attr("data-analytics-link-name");
            var searchSortMostRecentAttr = $searchSortMostRecent.attr("data-analytics-link-name");
            var hasDidYouMean = $('.did-you-mean-container').css("display") === "block";
            haveFilters = false;
            facetTermArray = [];
            commonTermArray = [];
            filterResultsContainer = document.createElement("div");

            $searchFilterBy.text("");
            $searchFilterBy.append(searchFilterByAttr);
            $searchFiltersSortBy.removeClass("filter-sort-margin-bottom");
            $searchFiltersSortBy.removeClass("hidden");
            $searchFilterFooter.removeClass("hidden");
            $searchFilterResults.removeClass("hidden");
            $searchFilterFooter.find(".behind").removeAttr("style");
            $searchFiltersSortBy.children("span").prepend(searchFiltersSortByAttr);
            $searchSortMostRelevant.append(searchSortMostRelevantAttr);
            $searchSortMostRecent.append(searchSortMostRecentAttr);
            $(filterResultsContainer).append("<span class='eyebrow-title filter-title corporate-bold'>" + $searchFilterResults.data("attribute-filter-results") + "</span>");
            $(filterResultsContainer).append("<span class='ion-android-close filter-close' data-analytics-link-name=" + closeButtonAttr + " data-analytics-template-zone='search filter' role='button' tabindex='0' aria-labelledby='filter-close-desc'></span>");
            $dropDownMenuDiv.prepend(filterResultsContainer);
            if ($searchFilterResultsButtonMode) {
                $searchFilterResults.text("Filter Button");
            }

            //Show Search Filter for BlogPostCards SERP CTA
            if (BlogNameKeyword || BlogAuthorKeyword || BlogTopicKeyword) {
                $searchFiltersContainer.removeClass("invisible hidden-xs hidden-sm");
            }

            //For XS and SM viewports
            if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
                ToggleFilterButton();
                $searchFiltersContainer.insertAfter('.did-you-mean-container');
                if (isSerpTablet(smallMaxWidth)) {
                    if (!hasDidYouMean) {
                        $searchFilterResults.removeAttr("style");
                    }
                } else {
                    $searchFilterResults.removeAttr("style");
                }
            } else {
                $searchFiltersContainer.insertBefore('.did-you-mean-container');
            }

            for (var i = 0; i < acnfacets.length; i++) {

                var facet = acnfacets[i];

                if (facet.items.length > 0)
                    facetCount++;

                if (facet != null && facet.items.length > 0) {
                    if (facet.displayfacet == true) {
                        //FOR META CATEGORY

                        var metaFilterCategoryContainer = document.createElement("div");
                        var metaCategoryContainer = document.createElement("div");
                        var metaFilterContainer = document.createElement("div");
                        var fieldset = document.createElement("fieldset");
                        var ul = document.createElement("ul");
                        $searchFiltersSortBy.removeAttr("style").children().removeAttr("style");
                        $(filterResultsContainer).attr("class", "search-filter-result");
                        $(metaFilterCategoryContainer).attr("class", "redesign-search-filters");
                        $(metaFilterCategoryContainer).addClass("corporate-regular");
                        $(metaFilterCategoryContainer).attr("id", facet.metadatafieldname + "-redesign-facet");
                        $(metaCategoryContainer).attr("data-analytics-content-type", "search filter");
                        $(metaCategoryContainer).attr("class", "reinvent-filter-category");
                        $(metaCategoryContainer).attr("aria-label", facet.facetdisplayname);
                        $(metaCategoryContainer).attr("role", "button");
                        $(metaCategoryContainer).attr("tabindex", "0");
                        $(metaCategoryContainer).attr("data-analytics-link-name", facet.facetdisplayname.toLowerCase() + " - expand");
                        $(metaCategoryContainer).attr("aria-expanded", "false");
                        if (categoryCount === 0) {
                            $(metaCategoryContainer).addClass("filter-border-top");
                        }
                        $(metaCategoryContainer).append("<h4>" + facet.facetdisplayname + "</h4>");
                        $(metaCategoryContainer).append("<span class='ion-chevron-down reinvent-filter-icon'></span>");
                        $(metaFilterCategoryContainer).append(metaCategoryContainer);

                        for (var ii = 0; ii < acnfacets[i].items.length; ii++) {
                            var facetitem = facet.items[ii];
                            var isselected = "";
                            var li = document.createElement("li");
                            var metaFilterLabel = document.createElement("label");
                            haveFilters = true;

                            isselected = IsFilterSelected(facet.metadatafieldname, facetitem.term) ? "checked" : "";

                            if (typeof facetitem.term !== null && typeof facetitem.term !== "undefined") {
                                checkBoxFaceItemLinkName = facetitem.term.toLowerCase().trim();
                            }

                            term = facetitem.term;
                            facetTermArray.push(facetitem.term);
                            //check the array if has duplicates
                            for (var x = 0; x < facetTermArray.length; x++) {
                                for (var y = 0; y < facetTermArray.length; y++) {
                                    if (x != y) {
                                        if (facetTermArray[x] === facetTermArray[y]) {
                                            commonTermArray.push(facetitem.term);
                                            facetTermArray.splice(x, 1);
                                        }
                                    }
                                }
                            }

                            if (commonTermArray.length > 0) {
                                for (var x = 0; x < commonTermArray.length; x++) {
                                    if (commonTermArray[x] === term.split("_")[0]) {
                                        term = commonTermArray[x] + "_" + i;
                                    }
                                }
                            }
                            //FOR META FILTERS
                            var filterCheckbox = $('<input/>')
                                .prop("class", "filter-checkbox")
                                .prop("id", term.replace(/\s+/g, '-').toLowerCase())
                                .prop("type", "checkbox")
                                .prop("name", facetitem.term)
                                .prop("value", facetitem.term)
                                .on("change", function () {
                                    ifCheck = 1;
                                    FilterResults();
                                });
                            var isChecked = "false";
                            if (isselected == "checked") {
                                filterCheckbox.attr("checked", isselected);
                                isChecked = "true";
                            }
                            $(metaFilterLabel).attr("for", term.replace(/\s+/g, '-').toLowerCase());
                            $(metaFilterLabel).attr("data-analytics-content-type", "search filter");
                            if (!jsUtility.isMobile() && !isSerpTablet(smallMaxWidth)) {
                                $(metaFilterLabel).attr("data-analytics-link-name", checkBoxFaceItemLinkName);
                            }
                            $(metaFilterLabel).addClass("corporate-regular");
                            $(metaFilterLabel).append(filterCheckbox);
                            $(metaFilterLabel).append("<span class='ion-android-checkbox-blank icon-check-checkbox' role='checkbox' aria-checked='" + isChecked + "' aria-label='" + facetitem.term + " filter" + " with " + facetitem.count + " results' tabindex='0'></span>");
                            $(metaFilterLabel).append("<span aria-hidden='true' class='text-checkbox'>" + facetitem.term + " (" + facetitem.count + ")</span>");
                            $(metaFilterContainer).attr("class", "reinvent-checkbox");
                            if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
                                $(metaFilterContainer).attr("tabindex", "-1");
                            }
                            //adds scroll depending on the value of maximumitemperfacet (works on non-mobile)
                            if (!jsUtility.isMobile() && !isSerpTablet(smallMaxWidth)) {
                                $(metaFilterContainer).css({ "overflow-y": "scroll" });
                            }
                            $(metaFilterContainer).addClass(facet.facetdisplayname.toUpperCase().replace(/\s/g, ''));
                            $(li).append(metaFilterLabel);
                            $(ul).append(li);
                            $(fieldset).append(ul);
                            $(metaFilterContainer).append(fieldset);
                            $(metaFilterCategoryContainer).append(metaFilterContainer);

                        }
                        categoryCount++;
                    }
                }
                $searchFilters.append(metaFilterCategoryContainer);
                var filterNumberData = $searchFiltersContainer.find(".reinvent-filter-number").data("attribute-filters-selected");
                if (filterNumberData) {
                    var replacedFilterNumber = filterNumberData.replace("{0}", filtersSelected);
                    $searchFiltersContainer.find(".reinvent-filter-number").text(replacedFilterNumber);
                }
            }


            if (openedAccordions !== null) {
                OpenAccordions();
            }

            if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
                $searchFilterResults.removeClass("hidden");
                if (isFilterModalClosed === false) {
                    $('.redesign-search-filters div:first-child').next().hide();
                    CheckFiltersBrowser();
                }
                if (isFilterContainerClosed == false) {
                    if (lastAccordion) {
                        var lastOpenedFacet = lastAccordion[0].innerText.toUpperCase();
                        lastOpenedFacet = lastOpenedFacet.replace(/\s/g, '');
                        $(".redesign-search-filters div:first-child").next().hide();
                        $(".reinvent-checkbox." + lastOpenedFacet).prev().addClass("corporate-semibold");
                        $(".reinvent-checkbox." + lastOpenedFacet).prev().children(".reinvent-filter-icon").removeClass("ion-chevron-down");
                        $(".reinvent-checkbox." + lastOpenedFacet).prev().children(".reinvent-filter-icon").addClass("ion-chevron-up");
                        $(".reinvent-checkbox." + lastOpenedFacet).show();
                        ShowFilterFooter();
                    }
                }
            } else {
                if (openedAccordions !== null) {
                    for (var i = 0; i < openedAccordions.length; i++) {
                        var currentAccordion = openedAccordions[i].replace(/\s/g, '').toUpperCase();
                        $(".reinvent-checkbox." + currentAccordion).prev().addClass("corporate-semibold");
                        $(".reinvent-checkbox." + currentAccordion).prev().children(".reinvent-filter-icon").removeClass("ion-chevron-down");
                        $(".reinvent-checkbox." + currentAccordion).prev().children(".reinvent-filter-icon").addClass("ion-chevron-up");
                        $(".reinvent-checkbox." + currentAccordion).prev().attr("data-analytics-link-name", facet.facetdisplayname.toLowerCase() + " - collapse ");
                        $(".reinvent-checkbox." + currentAccordion).prev().attr("aria-expanded", "true");
                        $(".reinvent-checkbox." + currentAccordion).show();
                    }

                    var $accordions = $('.redesign-search-filters div:first-child');
                    CheckOpenedAccordions($accordions);
                }
            }

            if (haveFilters == false) {
                HideFilters();
                ShowSortByOnly();
            }

            if (isFiltersHidden == true) {
                HideFilters();
            }
        }

        //Web accessibility for filters
        if (isTabbingUsed === true) {
            isTabbingUsed = false;
            if (isCheckboxFocused === true) {
                isCheckboxFocused = false;
                $(checkboxParent).find("[id='" + checkboxSibling + "']").siblings("span.ion-android-checkbox-blank").trigger("focus");
            } else if ($searchFilterResultsButtonMode) {
                $searchFilterResults.trigger("focus");
            } else {
                $lastActiveElement.trigger("focus");
            }
        } else if ($lastActiveElement != null) {
            $lastActiveElement.trigger("focus");
        }
    };

    var OpenAccordions = function () {
        var categories = $(".redesign-search-filters");

        categories.each(function () {
            var currentCategory = $(this);
            currentCategory.children("");
        });
    };

    var ToggleFilterButton = function () {
        $searchFilterResults.empty();
        if (lastFilterCount > 0) {
            var replacedModifyFilterCount = $searchFilterResults.data("attribute-modify-filters").replace("{0}", lastFilterCount);
            $searchFilterResults.attr("data-analytics-link-name", replacedModifyFilterCount);
            $searchFilterResults.append(replacedModifyFilterCount);

        } else {
            var searchFilterResultsAttr = $searchFilterResults.data("attribute-filter-results");
            $searchFilterResults.attr("data-analytics-link-name", searchFilterResultsAttr);
            $searchFilterResults.append(searchFilterResultsAttr);
        }
    };
    var PerformFilterSearch = function (async, queryType, keywords, from, size, sortBy, referenceGuid, cherryPickIds, currentPageId) {

        var path = SetDefaultPath(GetPath());
        var data = GetSearchData(queryType, keywords, from);

        if (typeof sortBy === 'undefined' || sortBy === null) {
            sortBy = lastSortBy;
        }

        queryType = queryType.toLowerCase();

        if (queryType === "recommendedcontentitems.search" || queryType === "searchbykeywords.search") {

            data = "{\"k\":\"" + FormatSearchHeroValue(keywords) + "\",\"f\":" + from + ",\"s\":" + size + ", \"sb\":" + sortBy + ", " + "\"ss\":\"" + subsite + "\", " +
                "\"df\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\",\"cs\":\"" + checkspell + "\"}";
        } else if (queryType === "default-featuredarticles.search") {
            data = "{\"k\":\"" + FormatSearchHeroValue(keywords) + "\",\"f\":" + from + ",\"s\":" + size + ",\"sb\":" + sortBy + ",\"cp\":\"" + cherryPickIds + "\",\"cpid\":\"" + currentPageId + "\", " +
                "\"df\":\"" + FormatSearchHeroValue(JSON.stringify(searchHeroSettings.keywordsearchfilters)) + "\", " + "\"rt\":\"resultitem\", " + "\"sp\": \"" + referenceGuid + "\"}";
        }

        $.ajax({
            type: "POST",
            url: path + queryType,
            data: data,
            async: async,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                FilterCallBack(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                searchHeroSettings = null;
            }
        });
    };

    var FilterCallBack = function (response) {
        if (response === null) {
            return;
        }
        if (response.total > 0) {
            isNoFilterResults = false;
        } else {
            isNoFilterResults = true;
        }
        ShowFilters(response.acnfacets);
    };

    var ResetFilterSelect = function () {
        if (lastKeywordSearchFilters !== null) {
            isFilterContainerClosed = true;
            searchHeroSettings = jQuery.extend(true, {}, lastKeywordSearchFilters);

            //Avoid ajax call in PerformFilterSearch for BlogPostCards SERP CTA
            if (lastQueryType === "default-featuredarticles.search") {
                PerformFilterSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
            } else if (lastQueryType !== "default-blogsbyblogname" && lastQueryType !== "default-blogsbyblogauthor" && lastQueryType !== "default-blogsbyblogtopic") {
                PerformFilterSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
            }
        }
    };

    $(window).on('resize', function () {
        if (isNoFilterResults === false) {
            ResetFilterSelect();
        } else {
            HideFilters();
        }
        openedAccordions = null;
        $redesignSerpModal.removeClass(RemoveClassCallback);
        if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
            $searchFilterResults.show();

        } else {
            $searchFilterResults.hide();

            $('.search-filter-result').removeClass("align-search-filter-result");
            $('.filter-close').removeClass("align-filter-close");
            $('.reinvent-filter-footer').removeClass("align-reinvent-filter-footer");
        }
        if ($redesignSerpModal.hasClass("show-modal-xs")) {
            $redesignSerpModal.removeClass("show-modal-xs");
        }
        if ($redesignSerpModal.hasClass("show-modal-sm")) {
            $redesignSerpModal.removeClass("show-modal-sm");
        }
        $redesignFilterModal.removeAttr("style");
        $redesignFilterModal.modal("hide");
    });

    // Display Search Filters on click
    $searchFilterResults.on("keydown click", function (e) {

        var isClicked = (e.originalEvent.key != undefined) ? false : true;
        var isSpaceBarEnterPressed = (isClicked == false && (e.keyCode == 13 || e.keyCode == 32)) ? true : false;

        if (isClicked || isSpaceBarEnterPressed) {
            e.preventDefault();

            $redesignFilterModal.modal();
            $redesignFilterModal.find(".dropdown-menu").addClass("bottom");
        }
    });

    $redesignFilterModal.on("show.bs.modal", function (e) {
        $redesignFilterModal.css("display", "flex");

        var isSafari = $("html").hasClass("safari");

        if (isSerpTablet(smallMaxWidth)) {
            if (isSafari) {
                $('body').addClass("reinvent-filter-position-fixed");
            }
        }
        if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
            // opens search filters
            filtersSelected = lastFilterCount;
            isFilterModalClosed = false;
            $('body').addClass("reinvent-filter-overflow-hidden");

            if (isMobile()) {
                $redesignSerpModal.addClass("show-modal-xs");
            } else {
                $redesignSerpModal.addClass("show-modal-sm");
            }

            $('.redesign-search-filters div:first-child').next().hide();

            ShowFilterFooter();
            $applyButtonFilter.hide();
            $closeButtonFilter.show();
            // hide all panels to start
            CheckFiltersBrowser();
        }
    }).on("shown.bs.modal", function (e) {
        setTimeout(function () {
            $redesignFilterModal.removeAttr("style");
            $redesignFilterModal.addClass("fade");
            $searchFilters.find("div.reinvent-filter-category").first()[0].focus();
        }, 300);
    }).on("hide.bs.modal", function (e) {
        $redesignFilterModal.find(".dropdown-menu").removeClass("bottom");
        isFilterContainerClosed = true;
        isFilterModalClosed = true;

        if (!$(document.activeElement).hasClass("reinvent-apply-filter")) {
            $redesignFilterModal.removeClass(RemoveClassCallback);
            $accordions = $('.redesign-search-filters div:first-child');
            CloseAccordions($accordions);
        }
    }).on("hidden.bs.modal", function (e) {

        $redesignFilterModal.removeAttr("style");
        $redesignFilterModal.removeClass("fade").removeClass("show-modal-xs").removeClass("show-modal-sm");
        setTimeout(function () { $searchFilterResults[0].focus(); }, 300);
    }).on("keydown", function (e) {
        //Trigger reset for selected filter when using ESC button
        if (e.keyCode == 27) {
            ResetFilterSelect();
            $searchFilterResults.trigger("focus");
            $lastActiveElement = $searchFilterResults;
        }
    });

    var CloseRedesignSerpModal = function (e) {
        var isClicked = (e.originalEvent.key != undefined) ? false : true;
        var isSpaceBarEnterPressed = (isClicked == false && (e.keyCode == 13 || e.keyCode == 32)) ? true : false;

        if (isClicked || isSpaceBarEnterPressed) {
            $lastActiveElement = $searchFilterResults;
            $redesignFilterModal.modal("hide");
            ResetFilterSelect();
        }
    };
    var RemoveClassCallback = function (index, className) {
        $('body').removeClass("reinvent-filter-position-fixed");
        $('body').removeClass("reinvent-filter-overflow-hidden");
        return (className.match(/(^|\s)show-modal-\S+/g) || []).join(' ');
    };

    // closes search filters
    $closeButtonFilter.on("keydown click", function (e) {
        CloseRedesignSerpModal(e);
    });

    $(".dropdown-menu").on("keydown click", ".filter-close", function (e) {
        if (/srk/.test(window.location.href)) {
            if (filterArray.length !== 0) {
                var arr = window.location.search.split('filter=')[1].replace(/%20/g, " ").replace(/%26/g, "&").split('+');
                for (i = 0; i < filterArray.length; i++) {
                    if (!arr.includes(filterArray[i])) {
                        filterArray.splice(filterArray[i], 1);
                        i = i - 1;
                    }
                }
            }
        }
        CloseRedesignSerpModal(e);
    });


    var CloseAccordions = function ($accordions) {
        $accordions.removeClass('is-open');
        $accordions.each(function () {
            var accordionName = $(this).text();
            if ($(this).hasClass("corporate-semibold") == true) {
                $(this).removeClass("corporate-semibold");
                $(this).children(".reinvent-filter-icon").removeClass("ion-chevron-up");
                $(this).children(".reinvent-filter-icon").addClass("ion-chevron-down");
                $(this).attr("aria-expanded", false);
                $(this).attr("data-analytics-link-name", "content type - expand");
            }
        });
        $accordions.removeClass("corporate-semibold");
    };

    // Accordion
    $searchFilters.on('click', '.redesign-search-filters div:first-child', function () {
        var $this = $(this);
        var $accordions = $('.redesign-search-filters div:first-child');
        lastAccordion = $this;
        openedAccordions = new Array();

        if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
            $accordions.next().slideUp();
        }
        if ($this.hasClass("corporate-semibold") == true && $this.hasClass("is-open") == false) {
            $this.next().slideUp();
            $this.removeClass("corporate-semibold");
            $this.addClass("corporate-regular");
            $this.children(".reinvent-filter-icon").removeClass("ion-chevron-up");
            $this.children(".reinvent-filter-icon").addClass("ion-chevron-down");
            $this.attr("data-analytics-link-name", lastAccordion[0].innerText.toLowerCase() + " - expand");
            $this.attr("aria-expanded", "false");
            CheckOpenedAccordions($accordions);
            return;
        }
        if ($this.hasClass('is-open')) {
            //if accordion is open, we need to close it
            $this.next().slideUp();
            $this.removeClass("corporate-semibold");
            $this.addClass("corporate-regular");
            $this.attr("data-analytics-link-name", lastAccordion[0].innerText.toLowerCase() + " - expand");
            $this.attr("aria-expanded", "false");
            $this.toggleClass("is-open");
        } else {
            //else accordion is close, we need to open it
            $this.next().slideDown();
            if (jsUtility.isMobile() || isSerpTablet(smallMaxWidth)) {
                CloseAccordions($accordions);
            }
            $this.attr("data-analytics-link-name", lastAccordion[0].innerText.toLowerCase() + " - collapse");
            $this.attr("aria-expanded", "true");
            $this.addClass("corporate-semibold");
            $this.removeClass("corporate-regular");
            $this.toggleClass("is-open");
        }
        CheckOpenedAccordions($accordions);
    });

    var CheckOpenedAccordions = function ($accordions) {
        $accordions.each(function () {
            var accordionName = $(this).text();
            if ($(this).hasClass("corporate-semibold") === true || $(this).hasClass('is-open')) {
                openedAccordions.push(accordionName.toLowerCase());
                //adds scroll depending on the value of maximumitemperfacet (works on non-mobile)
                if (!jsUtility.isMobile() && !isSerpTablet(smallMaxWidth)) {
                    var count = 0;
                    var totalFacetDivHeight = 40;
                    var $currentFilters = $(this).siblings(".reinvent-checkbox");
                    $currentFilters.find("li").each(function () {
                        if (count < searchHeroSettings.componentsettings.maximumitemperfacet) {
                            var facetDivHeight = $(this).height();
                            totalFacetDivHeight += facetDivHeight;
                            count++;
                        } else {
                            $currentFilters.css({ "max-height": totalFacetDivHeight + "px" });
                            return false;
                        }
                    });
                }
            }
        });
    };

    // Removes all filters from search settings.
    var RemoveAllFilters = function () {
        lastSortBy = 0;
        lastFilterCount = 0;
        isFiltersHidden = false;
        openedAccordions = null;

        if (searchHeroSettings !== null && searchHeroSettings.keywordsearchfilters !== null && searchHeroSettings.keywordsearchfilters.length > 0) {
            for (i = 0; i < searchHeroSettings.keywordsearchfilters.length; i++) {
                searchHeroSettings.keywordsearchfilters[i].items.length = 0;
            }
        }
    };

    // Determine if filter was already selected.
    var IsFilterSelected = function (facet, term) {
        var isselected = false;
        for (var i = 0; i < searchHeroSettings.keywordsearchfilters.length; i++) {
            if (searchHeroSettings.keywordsearchfilters[i].metadatafieldname == facet) {
                for (var ii = 0; ii < searchHeroSettings.keywordsearchfilters[i].items.length; ii++) {
                    if (searchHeroSettings.keywordsearchfilters[i].items[ii].term == term) {
                        isselected = true;
                        break;
                    }
                }
            }
        }

        return isselected;
    };

    var ShowFilterFooter = function () {
        var replacedFilterNumber = $searchFiltersContainer.find(".reinvent-filter-number").data("attribute-filters-selected").replace("{0}", filtersSelected);
        $searchFiltersContainer.find(".reinvent-filter-number").text(replacedFilterNumber);

        if (filtersSelected > 0 || lastFilterCount > 0) {
            $applyButtonFilter.show();
            $closeButtonFilter.hide();
        } else {
            $applyButtonFilter.hide();
            $closeButtonFilter.show();
        }
    };

    // Retrieval of search filter values.
    var FilterResults = function () {
        var selectedKeyword = "";
        var numSelected = 0;
        URLSearchParamsForIE();
        urlParams = new URLSearchParams(window.location.search);
        $(".reinvent-checkbox label").attr("for", "");
        if (window.location.search.indexOf('srk') >= 0) {
            if (urlParams.get('srk') !== "" || urlParams.get('srk') !== null) {
                lastKeyword = urlParams.get('srk');
            }
        }
        else {
            lastKeyword = $searchHeroKeyword.val();
        }
        $searchHeroKeyword.typeahead('val', lastKeyword);

        var maximumResults;
        var searchArray;

        if (searchHeroSettings != null) {
            maximumResults = searchHeroSettings.componentsettings.maximumsearchresultsperpagination;

            if (ifCheck === 0) {
                pageNum = urlParams.get('pg') === null ? 1 : parseInt(urlParams.get('pg'));
                searchArray = maximumResults * pageNum + 1 - maximumResults;
            }
            else if (ifCheck === 1) {
                searchArray = 1;
            }
        }

        if (searchHeroSettings != null && searchHeroSettings.keywordsearchfilters != null) {
            for (var i = 0; i < searchHeroSettings.keywordsearchfilters.length; i++) {
                var facet = searchHeroSettings.keywordsearchfilters[i];
                searchHeroSettings.keywordsearchfilters[i].items.length = 0;

                //for checked filter
                $("#" + facet.metadatafieldname + "-redesign-facet input[type=checkbox]:checked").each(function () {
                    var filtername = $(this).val();
                    var facetitem = {};
                    numSelected += 1;
                    selectedKeyword = filtername;
                    result = $.grep(facet.items, function (n, i) {
                        return (n.term == filtername);
                    });

                    if (result.length <= 0) {
                        facetitem.count = 1;
                        facetitem.selected = true;
                        facetitem.term = filtername;
                        facet.items.push(facetitem);
                        array.push(selectedKeyword);
                        filterArray = RemoveDuplicatedFilterStorage(array);
                    }
                });
                //for unchecked filter
                if (!jsUtility.isMobile() && !isSerpTablet(smallMaxWidth)) {
                    AddRemoveFilterFromUrl();
                }
            }
        }

        filtersSelected = numSelected;
        isFromFilter = true;
        resultCount = 0;
        if (/srk/.test(window.location.href)) {
            lastSortBy = urlParams.get('sb') === "" || urlParams.get('sb') === null ? 0 : parseInt(urlParams.get('sb'));
        }

        if (searchHeroSettings != null) {
            if (isMobile() || isSerpTablet(smallMaxWidth)) {
                ShowFilterFooter();
                if (lastQueryType == "recommendedcontentitems.search") {
                    for (var i = 0; i < searchHeroSettings.recommendedcontentkeywords.length; i++) {
                        for (var ii = 0; ii < searchHeroSettings.recommendedcontentkeywords[i].keywords.length; ii++) {
                            if (searchHeroSettings.recommendedcontentkeywords[i].keywords[ii].toLowerCase() === lastKeyword.toLowerCase()) {
                                lastKeyword = searchHeroSettings.recommendedcontentkeywords[i]._id;
                            }
                        }
                    }
                    PerformFilterSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maxrecommendedcontentitems, lastSortBy);
                } else if (lastQueryType === "default-featuredarticles.search") {
                    PerformFilterSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else if (lastQueryType === "default-blogsbyblogname") {
                    PerformSearch(true, lastQueryType, BlogNameKeyword + "," + BlogPostIndustry + "," + BlogPostSubject, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else if (lastQueryType === "default-blogsbyblogauthor") {
                    PerformSearch(true, lastQueryType, BlogAuthorKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else if (lastQueryType === "default-blogsbyblogtopic") {
                    PerformSearch(true, lastQueryType, BlogTopicKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else {
                    PerformFilterSearch(true, lastQueryType, lastKeyword, searchArray, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
                }
                isFilterContainerClosed = false;
            } else {
                lastFilterCount = filtersSelected;
                if (lastQueryType == "recommendedcontentitems.search") {
                    for (var i = 0; i < searchHeroSettings.recommendedcontentkeywords.length; i++) {
                        for (var ii = 0; ii < searchHeroSettings.recommendedcontentkeywords[i].keywords.length; ii++) {
                            if (searchHeroSettings.recommendedcontentkeywords[i].keywords[ii].toLowerCase() === lastKeyword.toLowerCase()) {
                                lastKeyword = searchHeroSettings.recommendedcontentkeywords[i]._id;
                            }
                        }
                    }
                    PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maxrecommendedcontentitems, lastSortBy);
                } else if (lastQueryType === "default-featuredarticles.search") {
                    PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId);
                } else if (lastQueryType === "default-blogsbyblogname") {
                    PerformSearch(true, lastQueryType, BlogNameKeyword + "," + BlogPostIndustry + "," + BlogPostSubject, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else if (lastQueryType === "default-blogsbyblogauthor") {
                    PerformSearch(true, lastQueryType, BlogAuthorKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else if (lastQueryType === "default-blogsbyblogtopic") {
                    PerformSearch(true, lastQueryType, BlogTopicKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid);
                } else {
                    PerformSearch(true, lastQueryType, lastKeyword, searchArray, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
                }
            }
        }

        ifCheck = 1;

        if ($(document.activeElement).parents("div").hasClass("reinvent-checkbox") && $(document.activeElement).hasClass("ion-android-checkbox-blank")) {
            RetainFocusOnFilter();
        }
    };

    var AddRemoveFilterFromUrl = function () {
        URLSearchParamsForIE();
        urlParams = new URLSearchParams(window.location.search);

        if (ifCheck === 0) {
            reinventPaginationCurrent = parseInt(urlParams.get('pg'));
        }
        else if (ifCheck === 1) {
            reinventPaginationCurrent = 1;
            pageNum = reinventPaginationCurrent;
        }

        if (searchHeroSettings != null && searchHeroSettings.keywordsearchfilters != null) {
            for (var i = 0; i < searchHeroSettings.keywordsearchfilters.length; i++) {
                var facet = searchHeroSettings.keywordsearchfilters[i];
                $("#" + facet.metadatafieldname + "-redesign-facet input[type=checkbox]").each(function () {
                    var filtername = $(this).val();
                    var checkArray = array.includes(filtername);
                    if (!$(this).is(':checked') && checkArray === true && ifCheck === 1 && isApplyClick !== 1) {
                        for (var i = 0; i < array.length; i++) {
                            if (array[i] === filtername) {
                                array.splice(i, 1);
                                if (/srk/.test(window.location.href)) {
                                    AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', pageNum, 'sb', lastSortBy, 'filter', array);
                                }
                            }
                        }
                    }
                    else if ($(this).is(':checked') && ifCheck === 1) {
                        if (/srk/.test(window.location.href)) {
                            for (var i = 0; i < array.length; i++) {
                                var arr = window.location.search.split('filter=')[1].replace(/%20/g, " ").replace(/%26/g, "&").split('+');
                                if (!arr.includes(array[i])) {
                                    AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', pageNum, 'sb', lastSortBy, 'filter', filterArray);
                                    ifCheck = 0;
                                }
                            }
                        }
                    }
                });
            }
        }

        if (isApplyClick === 1) {
            for (var i = 0; i < array.length; i++) {
                if (!$('.redesign-search-filters input[value="' + array[i] + '"]').is(":checked")) {
                    array.splice(array[i], 1);
                    i = i - 1;
                    isApplyClick = 0;
                }
            }
            if (/srk/.test(window.location.href) && isApplyClick === 0) {
                AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', pageNum, 'sb', lastSortBy, 'filter', array);
            }

        }
    };

    var RemoveDuplicatedFilterStorage = function (array) {
        for (var outerLoop = 0; outerLoop < array.length; outerLoop++) {
            for (var innerLoop = outerLoop + 1; innerLoop < array.length; innerLoop++) {
                if (array[outerLoop].replace(/\s{2,}/g, ' ').trim() === array[innerLoop].replace(/\s{2,}/g, ' ').trim()) {
                    array.splice(outerLoop, 1);
                }
            }
        }
        return array;
    };

    var RetainFocusOnFilter = function () {
        $lastActiveElement = $(document.activeElement);
        checkboxParent = "." + $lastActiveElement.parents("div")[0].classList[1];
        checkboxSibling = $lastActiveElement.siblings("input")[0].id;
        isCheckboxFocused = true;
        isTabbingUsed = true;
    };

    //Web Accessibility (search filters)
    $(document.activeElement).on('keydown', function (event) {
        var code = event.keyCode;
        var specifier = "";

        //booleans
        var isUnderSearchFiltersContainer = $(document.activeElement).parents("div").hasClass("redesign-search-filters-container");
        var isUnderRedesignSort = $(document.activeElement).parents("div").hasClass("redesign-sort");
        var isUnderSearchFilterPanel = $(document.activeElement).parent("div").hasClass("redesign-search-filters");
        var isMetaFilter = $(document.activeElement).hasClass("ion-android-checkbox-blank");
        var isUnderSearchResultsBlock = $(document.activeElement).parents("div").hasClass("search-results-container");
        var isUnderSearchResultsHeader = $(document.activeElement).parents("div").hasClass("search-results-header");
        var isUnderGlobalFooter = $(document.activeElement).parents("section#footer-block").length > 0;
        var isUnderPagination = $(document.activeElement).parents("div").hasClass("reinvent-pagination");
        var isAccordionOpened = $(".search-filter-panel").find("div.reinvent-filter-category").last().hasClass("is-open");
        var isAccordionBold = $(".search-filter-panel").find("div.reinvent-filter-category").last().hasClass("corporate-semibold");
        var isUnderDidYouMean = $(document.activeElement).parents("div").hasClass("did-you-mean-container");
        var isUnderPaginationPrevButton = $(document.activeElement).hasClass("prev-page-btn");
        var isPaginationExisiting = $(".reinvent-pagination").length > 0;
        var isPaginationVisible = $(".reinvent-pagination").css("display") !== "none";
        var isFilterPanelExisting = $(".search-filter-panel").children().length > 0;
        var isDidYouMeanExisiting = $(".did-you-mean-container").css("display") !== "none";
        var isAtSearchHeroButton = $(document.activeElement).parent("form").hasClass("search-hero-form");
        $searchFilterResultsButtonMode = $searchFilterResults.is(":visible");
        //Initial Tabbing from button
        if (isAtSearchHeroButton === true) {
            if (code === 9) {
                if (event.shiftKey === false) {
                    //check if did-you-mean exists
                    if (isDidYouMeanExisiting === true) {
                        event.preventDefault();
                        $("#did-you-mean-link").trigger("focus");
                    }
                }
            }
        }
        else if (isUnderSearchFiltersContainer == true) {

            //classnames:
            var lastFilterPanel = $(".search-filter-panel").children("div").last()[0].children[1].classList[1];
            var firstFilterPanel = $(".search-filter-panel").children("div").first().children("div")[1].classList[1];
            //manipulate the flow of tabbing
            if (code === 9) {
                if (event.shiftKey === false) {
                    if (isUnderRedesignSort === true) {
                        var lastSortFilterElement = $(".redesign-sort").children("a").last()[0].id;

                        if ($(document.activeElement)[0].id === lastSortFilterElement) {
                            event.preventDefault();
                            if ($searchFilterResultsButtonMode) {
                                $searchFilterResults.trigger("focus");
                            } else {
                                $(".search-results-section").children("div").first().find("a").trigger("focus");
                            }
                        }

                    } else if (isUnderSearchFilterPanel == true) {
                        if ($(document.activeElement)[0].innerText.toUpperCase().replace(/\s/g, '') === lastFilterPanel) {
                            if ($(document.activeElement).hasClass("is-open") == false) {
                                if (isFilterModalClosed) {
                                    $(".search-results-section").children("div").last().find("a").trigger("focus");
                                }
                            }
                        }
                    }
                    //from search filters to pagination (if it exists)
                    else if (isMetaFilter === true) {
                        specifier = "." + $(".search-filter-panel").children("div").last().find(".reinvent-checkbox")[0].classList[1];
                        if ($(".reinvent-checkbox" + specifier).find("li").last().find("input")[0].id === $(document.activeElement).siblings("input")[0].id) {
                            if (isFilterModalClosed) {
                                $(".search-results-section").children("div").last().find("a").trigger("focus");
                            }
                        }
                    } else if (!isFilterModalClosed) {
                        if ($(document.activeElement).hasClass("reinvent-close-filter") || $(document.activeElement).hasClass("reinvent-apply-filter")) {
                            $redesignSerpModal.find(".filter-close").trigger("focus");
                            event.preventDefault();
                        } else if ($(document.activeElement).hasClass("reinvent-filter-results")) {
                            $searchFilters.find("div.reinvent-filter-category").first().trigger("focus");
                            event.preventDefault();
                        }
                    }
                }
                //from search filters to search results block
                else if (event.shiftKey === true) {
                    if (isUnderSearchFilterPanel === true) {
                        if ($(document.activeElement).siblings("div")[0].classList[1] === firstFilterPanel) {
                            if (isFilterModalClosed) {
                                event.preventDefault();
                                $(".search-results-container").find("div.search-results-header").last().find("a").trigger("focus");
                            }
                        }
                    }
                    else if (isUnderRedesignSort === true) {
                        //check if did-you-mean exists
                        var firstSortFilterElement = $(".redesign-sort").children("a").first()[0].id;
                        if (isDidYouMeanExisiting === true) {
                            if ($(document.activeElement)[0].id === firstSortFilterElement) {
                                event.preventDefault();
                                $("#did-you-mean-link").trigger("focus");
                            }
                        }
                    }
                    else if (!isFilterModalClosed) {
                        if ($(document.activeElement).hasClass("reinvent-close-filter") || $(document.activeElement).hasClass("reinvent-apply-filter")) {
                            if ($searchFilters.find("div.reinvent-filter-category").last().hasClass("corporate-semibold")) {
                                $searchFilters.find("div.reinvent-filter-category").last().next().find("li:visible").last().find("span.icon-check-checkbox")[0].focus();
                            } else {
                                $searchFilters.find("div.reinvent-filter-category").last().trigger("focus");
                            }
                            event.preventDefault();
                        } else if ($(document.activeElement).hasClass("filter-close")) {
                            if ($redesignSerpModal.find(".reinvent-close-filter").is(":visible")) {
                                $redesignSerpModal.find(".reinvent-close-filter").trigger("focus");
                            } else {
                                $redesignSerpModal.find(".reinvent-apply-filter").trigger("focus");
                            }
                            event.preventDefault();
                        }
                    }
                }
            } else if ((code === 13) || (code === 32)) {
                $lastActiveElement = $(document.activeElement);

                if ($lastActiveElement.hasClass("ion-android-checkbox-blank")) {
                    if (code === 32) {
                        RetainFocusOnFilter();
                        $(document.activeElement)[0].click();
                    } else {
                        return;
                    }
                } else if ($lastActiveElement.hasClass("sort-unselected")) {
                    if (code === 13) {
                        $searchSortMostRecent.attr("aria-pressed", "false");
                        $searchSortMostRelevant.attr("aria-pressed", "false");
                        if ($lastActiveElement[0].id === "reinvent-filter-most-recent") {
                            $searchSortMostRecent.attr("aria-pressed", "true");
                        } else if ($lastActiveElement[0].id === "reinvent-filter-most-relevant") {
                            $searchSortMostRelevant.attr("aria-pressed", "true");
                        }
                        $(document.activeElement)[0].click();
                    }
                } else if ($lastActiveElement.parent("div").hasClass("redesign-search-filters")) {
                    $(document.activeElement)[0].click();
                }

                isTabbingUsed = true;
                if (!$lastActiveElement.hasClass("reinvent-filter-results")) {
                    event.preventDefault();
                }
            }
            //arrow up
            else if (code === 38) {
                if (isMetaFilter == true) {
                    event.preventDefault();
                    $(document.activeElement).parents("li").prev().find("span.icon-check-checkbox").trigger("focus");
                }


            }
            //arrow down
            else if (code === 40) {
                if (isMetaFilter === true) {
                    event.preventDefault();
                    $(document.activeElement).parents("li").next().find("span.icon-check-checkbox").trigger("focus");
                }
            }

        }
        //tabbing from search results block back to search filters
        else if (isUnderSearchResultsBlock === true) {
            var firstSearchResult = $(".search-results-container").find("div.search-results-header").first().find("a")[0].attributes[2].nodeValue;
            var lastSearchResult = $(".search-results-container").find("div.search-results-header").last().find("a")[0].attributes[2].nodeValue;
            if (event.shiftKey === true && code === 9) {
                if (isUnderSearchResultsHeader === true) {
                    if ($(document.activeElement)[0].attributes[2].nodeValue == firstSearchResult) {
                        if (isFiltersHidden === false) {
                            event.preventDefault();
                            if ($searchFilterResultsButtonMode) {
                                $searchFilterResults.trigger("focus");
                            } else {
                                $(".redesign-sort").find("a[tabindex='0']").trigger("focus");
                            }
                        }
                    }
                }
            } else if (event.shiftKey === false && code === 9) {
                if ($(document.activeElement)[0].attributes[2].nodeValue === lastSearchResult) {
                    if (isFilterPanelExisting === true) {
                        event.preventDefault();
                        if ($searchFilterResultsButtonMode) {
                            reinventPagination.find("a").first().trigger("focus");
                        } else {
                            $(".search-filter-panel").find("div.reinvent-filter-category").first().trigger("focus");
                        }
                    }
                }
            }
        }
        //tabbing from did-you-mean
        else if (isUnderDidYouMean) {
            if (event.shiftKey === false && code === 9) {
                //checks if sort by exists
                if (haveFilters === true) {
                    event.preventDefault();
                    $(".redesign-sort").children("a").first().trigger("focus");
                }
            }
            else if (event.shiftKey === true && code === 9) {
                event.preventDefault();
                $(".search-hero-form").children("button").trigger("focus");
            }
        }
        //tabbing from pagination back to search filters
        else if (isUnderPagination === true) {
            if (event.shiftKey === true && code === 9) {
                if (isUnderPaginationPrevButton === true) {
                    //checks if the filter exists
                    if (isFilterPanelExisting === true) {
                        event.preventDefault();
                        if (isAccordionOpened === true || isAccordionBold === true) {
                            $(".reinvent-checkbox" + specifier).find("li").last().find("span.ion-android-checkbox-blank").trigger("focus")
                        } else if ($searchFilterResultsButtonMode) {
                            $searchResultsArea.find("div.search-results-header").last().find("a")[0].focus();
                        } else {
                            $searchFilters.find("div.reinvent-filter-category").last().trigger("focus");
                        }
                    }
                }
            }
        }
        //current focused element is at footer
        else if (isUnderGlobalFooter === true) {
            if (event.shiftKey === true && code === 9) {
                if (!(isPaginationExisiting === true) || !(isPaginationVisible === true)) {
                    var footerClass = "." + $(document.activeElement).parent("span").parent("div")[0].classList[0];
                    var $footerMainSpecifier;
                    var footerSubSpecifier = "";

                    if (footerClass === ".col-xs-4") {
                        $footerMainSpecifier = $(document.activeElement).parents(".footer-links-container");
                        footerSubSpecifier = "div" + footerClass;

                    } else {
                        $footerMainSpecifier = $(document.activeElement).parents(footerClass).parent("div");
                        footerSubSpecifier = "span";
                    }

                    if ($footerMainSpecifier.prev().length < 1) {
                        if ($(document.activeElement).parents(footerSubSpecifier).prev().length < 1) {
                            //check if filters exist
                            if (isFilterPanelExisting === true) {
                                event.preventDefault();
                                if (isAccordionOpened === true || isAccordionBold === true) {
                                    $(".reinvent-checkbox" + specifier).find("li").last().find("span.ion-android-checkbox-blank").trigger("focus")
                                } else {
                                    $(".search-filter-panel").find("div.reinvent-filter-category").last().trigger("focus");
                                }
                            }
                        }
                    }
                }
            }

        }
    });
    $applyButtonFilter.on("keydown click", ".reinvent-apply-filter", function (e) {
        var isClicked = (e.originalEvent.key != undefined) ? false : true;
        var isSpaceBarEnterPressed = (isClicked == false && (e.keyCode == 13 || e.keyCode == 32)) ? true : false;

        if (isClicked || isSpaceBarEnterPressed) {
            $lastActiveElement = $searchFilterResults;
            isApplyClick = 1;
            AddRemoveFilterFromUrl();
            $redesignFilterModal.modal("hide");
            lastFilterCount = filtersSelected;
            SearchFilterMobile();
        }
    });

    var SearchFilterMobile = function () {
        $redesignSerpModal.removeClass(RemoveClassCallback);
        var maximumResults = searchHeroSettings.componentsettings.maximumsearchresultsperpagination;
        var searchArray = maximumResults * pageNum + 1 - maximumResults;
        if (lastQueryType == "recommendedcontentitems.search") {
            for (var i = 0; i < searchHeroSettings.recommendedcontentkeywords.length; i++) {
                for (var ii = 0; ii < searchHeroSettings.recommendedcontentkeywords[i].keywords.length; ii++) {
                    if (searchHeroSettings.recommendedcontentkeywords[i].keywords[ii].toLowerCase() === lastKeyword.toLowerCase()) {
                        lastKeyword = searchHeroSettings.recommendedcontentkeywords[i]._id;
                    }
                }
            }
            PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maxrecommendedcontentitems, lastSortBy);
        } else if (lastQueryType === "default-featuredarticles.search") {
            PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId);
        } else {
            PerformSearch(true, lastQueryType, lastKeyword, searchArray, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
        }
        ToggleFilterButton();
    };

    //Checks for other mobile browser compatibility issues
    var CheckFiltersBrowser = function () {

        // for safari
        var isSafari = $('html').hasClass(".safari");

        if (isSafari || jsUtility.isMobileBrowser() != null) {
            if (jsUtility.isMobile()) {
                $('.search-filter-result').addClass("align-search-filter-result");
                $('.filter-close').addClass("align-filter-close");
                $('.reinvent-filter-footer').addClass("align-reinvent-filter-footer");
            }
        }
    };

    $("#reinvent-filter-most-recent").on("click", function () {
        lastSortBy = 1;
        if (/srk/.test(window.location.href)) {
            AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', lastSortBy, 'filter', filterArray);
        }
        FilterSortBy(lastSortBy);
    });

    $("#reinvent-filter-most-relevant").on("click", function () {
        lastSortBy = 0;
        if (/srk/.test(window.location.href)) {
            AppendToURL('srk', ReplaceEncodedKeyword($searchHeroKeyword.val()), 'pg', 1, 'sb', lastSortBy, 'filter', filterArray);
        }
        FilterSortBy(lastSortBy);
    });

    // Sort filter
    var ToggleSort = function () {
        $("#reinvent-filter-most-recent").removeAttr("class");
        $("#reinvent-filter-most-relevant").removeAttr("class");
        $("#reinvent-filter-most-recent").attr("aria-pressed", "false");
        $("#reinvent-filter-most-relevant").attr("aria-pressed", "false");
        if (lastSortBy == 1) {
            $("#reinvent-filter-most-recent").addClass("sort-selected");
            $("#reinvent-filter-most-recent").attr("aria-pressed", "true");
            $("#reinvent-filter-most-relevant").addClass("sort-unselected");
        } else {
            $("#reinvent-filter-most-relevant").addClass("sort-selected");
            $("#reinvent-filter-most-relevant").attr("aria-pressed", "true")
            $("#reinvent-filter-most-recent").addClass("sort-unselected");
        }
    };

    var FilterSortBy = function (lastSortBy) {
        resultCount = 0;
        reinventPaginationCurrent = 1;
        isFromFilter = true;
        ToggleSort();
        $searchHeroKeyword.typeahead('val', lastKeyword);

        if (lastQueryType == "recommendedcontentitems.search") {
            for (var i = 0; i < searchHeroSettings.recommendedcontentkeywords.length; i++) {
                for (var ii = 0; ii < searchHeroSettings.recommendedcontentkeywords[i].keywords.length; ii++) {
                    if (searchHeroSettings.recommendedcontentkeywords[i].keywords[ii].toLowerCase() === lastKeyword.toLowerCase()) {
                        lastKeyword = searchHeroSettings.recommendedcontentkeywords[i]._id;
                    }
                }
            }
            PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
        } else if (lastQueryType === "default-featuredarticles.search") {
            PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, lastRefenceGuid, lastCherryPickId, lastCurrentPageId);
        } else {

            PerformSearch(true, lastQueryType, lastKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy);
        }

    };

    //stores view all data attributes to local storage
    ViewAllRedesignSerp = {
        ViewAllClick: function (viewalllink) {
            $viewAllClickTriggeredRedesignSERP = true;

            var ViewAllAttribute = {
                "ViewAllClickTriggeredRedesignSERP": $viewAllClickTriggeredRedesignSERP,
                "keyword": viewalllink.attr("data-keywords"),
                "viewAllPostIndustry": viewalllink.attr("data-blog-post-industry"),
                "viewAllPostSubject": viewalllink.attr("data-blog-post-subject"),
                "componenttype": viewalllink.attr("data-component-type"),
                "searchEnabled": viewalllink.attr("data-search-enabled"),
                "cherryPickIds": viewalllink.attr("data-cherrypick"),
                "searchParamId": viewalllink.attr("data-metadata-search-id"),
                "currentPageId": viewalllink.attr("data-current-page"),
                "pageTitleMetadata": viewalllink.attr("data-pagetitle-metadata"),
                "viewAllSortBy": viewalllink.attr("data-sort-by"),
                "hasMetadataSearchSelection": viewalllink.attr("data-has-metadata-search-selection")
            };
            var val = JSON.stringify(ViewAllAttribute);
            localStorage.setItem("ViewAllAttributes", val);
        }
    };

    var ViewAllSearch = function () {
        ctaTempJSONString = localStorage.getItem('ViewAllAttributes');
        ctaTempAttrib = JSON.parse(ctaTempJSONString);
        ctaKeyword = ctaTempAttrib.keyword;
        ctaComponenttype = ctaTempAttrib.componenttype;
        ctaCherryPickIds = ctaTempAttrib.cherryPickIds;
        ctaSearchParamId = ctaTempAttrib.searchParamId;
        ctaCurrentPageId = ctaTempAttrib.currentPageId;
        ctaViewAllSortBy = ctaTempAttrib.viewAllSortBy;
        lastSortBy = ctaViewAllSortBy;
        var hasMetadataSearchSelection = ctaTempAttrib.hasMetadataSearchSelection;

        if (ctaComponenttype === "blogsbyblogname") {
            BlogNameKeyword = ctaKeyword;
            BlogPostIndustry = ctaTempAttrib.viewAllPostIndustry;
            BlogPostSubject = ctaTempAttrib.viewAllPostSubject;
        }
        else if (ctaComponenttype === "blogsbyblogauthor") {
            var authorInfo = ctaKeyword.split("|");
            BlogAuthorKeyword = authorInfo[0] ? authorInfo[0] : "";
            BlogAuthorName = authorInfo[1] ? authorInfo[1] : "";
        } else if (ctaComponenttype === "blogsbyblogtopic") {
            BlogTopicKeyword = ctaKeyword;
        }

        var serpSetting = "";

        if (searchHeroSettings != null) {
            if (hasMetadataSearchSelection) {
                serpSetting = "default";
                if (searchHeroSettings.componentsettings.showsuggestedtopics == true && searchHeroSettings.suggestedtopickeywords != null) {
                    PerformSuggestedTopicSearch(searchHeroSettings.suggestedtopickeywords, ctaKeyword, searchHeroSettings.componentsettings.maxsuggestedtopicitems, serpSetting);
                }

                serpSetting += "-" + ctaComponenttype;
                if (ctaComponenttype === "blogsbyblogname") {
                    PerformSearch(true, serpSetting, BlogNameKeyword + "," + BlogPostIndustry + "," + BlogPostSubject, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, ctaSearchParamId, ctaCherryPickIds, ctaCurrentPageId);
                }
                else if (ctaComponenttype === "blogsbyblogauthor") {
                    PerformSearch(true, serpSetting, BlogAuthorKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, ctaSearchParamId, ctaCherryPickIds, ctaCurrentPageId);
                }
                else if (ctaComponenttype === "blogsbyblogtopic") {
                    PerformSearch(true, serpSetting, BlogTopicKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, ctaSearchParamId, ctaCherryPickIds, ctaCurrentPageId);
                }
                else {
                    PerformSearch(true, serpSetting, ctaKeyword, 1, searchHeroSettings.componentsettings.maximumsearchresultsperpagination, lastSortBy, ctaSearchParamId, ctaCherryPickIds, ctaCurrentPageId);
                }
            }
        }
    };
    //Web Accessibility for search icon in global header if it is focused/blur
    var $redesignSerpEnabled = $("a.ion-ios-search");
    var $redesignSearchContainer = $("div.search-icon-container");

    $redesignSerpEnabled.on("focus", function () {
        $redesignSearchContainer.addClass("redesign-serp");
    });
    $redesignSerpEnabled.on("blur", function () {
        $redesignSearchContainer.removeClass("redesign-serp");
    });

    var removeFocusIndicatorOnClick = function () {
        var $contentWrapper = $('.content-wrapper');
        if ($contentWrapper.hasClass('focus-indicator')) {
            $(document.activeElement).on('mousedown', function () {
                var focusableElements = $(".page-num, .search-result-link");
                setTimeout(function () {
                    focusableElements.trigger("blur");
                }, 0);
            });
        }
    };

    var setSearchResultInDataModel = function () {
        if (isFeatureSearch === true) {
            dataModel.page.internalSearch.resultType = "basic search|featured search"
        }
        else { dataModel.page.internalSearch.resultType = "basic search" }
    };

    var setInternalSearchKeywordInDataModel = function () {
        var firstPartyCookie = window.OptanonActiveGroups;
        if (firstPartyCookie && firstPartyCookie.indexOf(",2,") > -1) {
            var searchValue;
            var storageName = "internalSearchKeyword";
            var internalSearch = localStorage.getItem(storageName) ? JSON.parse(localStorage.getItem(storageName)) : [];
            var urlParams = window.location.search;
            var joinSearch;

            if (urlParams && urlParams.indexOf("&") > -1) {
                searchValue = decodeURIComponent(urlParams.split("srk=")[1].split("&")[0]);
                if (searchValue) {
                    if (internalSearch.indexOf(searchValue) < 0) {
                        internalSearch.push(searchValue);
                    }
                };
            };
            localStorage.setItem(storageName, JSON.stringify(internalSearch));
            if (internalSearch.length > 0) {
                joinSearch = JSON.parse(localStorage.getItem(storageName)).join("|").toLowerCase();
            };
            dataModel.page.internalSearch.keywordStacking = joinSearch;
        };
    };

    var latestJobsArr = [];
    var latestJobsSet = $(".update-set-jobs");
    var searchAllJobLink = $(".cta-alt-arrow");
    var searchAllURL = searchAllJobLink.length === 0 ? "" : searchAllJobLink[0].href;

    var countryName = $(".update-set-jobs").data("country-name");
    var jobsperpage = $(".job-listing-prop").data("cards-display");
    var colorBar = $(".job-listing-prop").data("color-bar");
    var showCountry = $(".job-listing-prop").data("country-label");
    var showCity = $(".job-listing-prop").data("city-label");
    var showTitle = $(".job-listing-prop").data("show-title");
    var showSkill = $(".job-listing-prop").data("show-aoi");
    var showDesc = $(".job-listing-prop").data("show-summary");
    var showDate = $(".job-listing-prop").data("show-posted-date");
    var templateName = $(".job-listing-prop").data("block-name");
    var componentName = $(".job-listing-block").data("analytics-module-name");
    var showCTA = $(".job-listing-prop").data("cta-enable");
    var ctaText = $(".job-listing-prop").data("cta-text");

    var postedText = $(".jobsearch-translations").data("posted-text");
    var yearsAgo = $(".jobsearch-translations").data("years-ago");
    var yearAgo = $(".jobsearch-translations").data("year-ago");
    var monthsAgo = $(".jobsearch-translations").data("months-ago");
    var monthAgo = $(".jobsearch-translations").data("month-ago");
    var daysAgo = $(".jobsearch-translations").data("days-ago");
    var dayAgo = $(".jobsearch-translations").data("day-ago");
    var moreThanAMonthAgo = $(".jobsearch-translations").data("a-month-ago");
    var hoursAgo = $(".jobsearch-translations").data("hours-ago");
    var hourAgo = $(".jobsearch-translations").data("hour-ago");
    var minutesAgo = $(".jobsearch-translations").data("minutes-ago");
    var minuteAgo = $(".jobsearch-translations").data("minute-ago");
    var secondsAgo = $(".jobsearch-translations").data("seconds-ago");
    var secondAgo = $(".jobsearch-translations").data("second-ago");
    var mutlipleLoc = $(".jobsearch-translations").data("multiple-locations");
    var locationNego = $(".jobsearch-translations").data("location-negotiable");
    var moreThanAMonthAgo = $(".jobsearch-translations").data("a-month-ago");
    var mutlipleLoc = $(".jobsearch-translations").data("multiple-locations");
    var locationNego = $(".jobsearch-translations").data("location-negotiable");
    var setEllipsis = function () {
        var jobDesc = $(".job-listing-description");

        jsUtility.ellipsisFunction(jobDesc);
    };


    var JobCardsTemplate =
        '<div class="module job-card-wrapper col-md-4 col-xs-12 col-sm-6 corporate-regular background-white">' +
        '<a href="{jobDetailUrl}" data-linkpagesection="{templateName}" data-linkcomponentname="{componentName}" data-linkaction="{jobTitle}" data-analytics-link-name="{jobTitle2}" data-linktype="related jobs search" data-analytics-content-type="related jobs search">' +
        '<div class="job-listing-container bg-color-white {colorBar}">' +
        '<div class="job-listing-content">' +
        '{CountryCityTemplate}' +
        '<h3 class="job-title module-title corporate-bold">{jobTitleVal}</h3>' +
        '{DescriptionSkillTemplate}' +
        '</div>' +
        '{parsedPostedDate}' +
        '{linkArrow}' +
        '</div >' +
        '</a>' +
        '</div >';

    var cleanDescription = function (jobDescription) {
        var removeHtmlTags = jobDescription.replace(/(&nbsp;\n|<([^>]+)>)/ig, "");
        var removeGtLt = removeHtmlTags.replace(/(\&gt;([^>]+)\&lt;)/ig, "");
        var removeBreaklines = removeGtLt.replace(/\r?\n|\r/g, "");
        var removeSpaces = removeBreaklines.replace(/(&nbsp;|^\s+|\s+$)/g, " ");

        return removeSpaces;
    };
    var getDateTimeDifference = function (dt) {
        var languageName = acnPage.Language;
        var datedisplay = "";
        var jobdate = new Date(dt);

        datedisplay = timeSince(jobdate, new Date(), languageName);

        return postedText + " " + datedisplay;
    };
    function timeSince(date, serverDate, languageName) {
        var seconds = Math.floor((serverDate - date) / 1000);
        var isLatin = false;

        if (languageName.toLowerCase() == "es-la") {
            isLatin = true;
        }
        //More than 30 days
        var interval = Math.floor(seconds / 86400);
        if (interval > 30) {
            return moreThanAMonthAgo;
        }
        else if (interval > 1 && interval < 31) {
            if (isLatin) {
                return daysAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + daysAgo;
        }
        else if (interval == 1) {
            if (isLatin) {
                return dayAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + dayAgo;
        }
        //Equivalent to 1 hour
        interval = Math.floor(seconds / 3600);
        if (interval == 1) {
            if (isLatin) {
                return hourAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + hourAgo;
        }
        else if (interval > 1) {
            if (isLatin) {
                return hoursAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + hoursAgo;
        }
        //Equivalent to a minute
        interval = Math.floor(seconds / 60);
        if (interval == 1) {
            if (isLatin) {
                return minuteAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + minuteAgo;
        }
        else if (interval > 1) {
            if (isLatin) {
                return minutesAgo.replace("{0}", " " + interval + " ");
            }
            return interval + " " + minutesAgo;
        }
        return Math.floor(seconds) + " " + secondAgo;
    };

    var showRelatedJobs = function (keyword) {

        if (searchHeroSettings !== null && searchHeroSettings !== undefined &&
            searchHeroSettings.componentsettings !== null && searchHeroSettings.componentsettings !== undefined) {
            var enableReletedJobs = searchHeroSettings.componentsettings.enableactionableserp;

            if (enableReletedJobs && searchHeroSettings.jobsactionableterms.length > 0) {
                var loweredActionableTerms = searchHeroSettings.jobsactionableterms.map(function (value) {
                    return value.toLowerCase();
                });

                var isActionableKeywod = loweredActionableTerms.indexOf(keyword.toLowerCase()) > -1;

                if (isActionableKeywod) {
                    getRelatedJobs(keyword);
                } else {
                    clearRelatedJobsSection();
                }
            }
        }
    };
    var clearRelatedJobsSection = function () {

        $relatedJobsSection.addClass('hide');

    }

    var jobSearchReinvent = {
        Data: {
            responseFromEs: {},
            countryInfo: {
                language: '',
                countrySite: '',
                countryName: '',
                initCountrySite: ''
            }
        },
        updateJobResults: function (response) {
            if (response !== null) {
                if (response.documents.length > 0) {
                    $relatedJobsSection.removeClass('hide');
                } else {
                    clearRelatedJobsSection();
                }
                for (var i = 0; i < response.documents.length && i < jobsperpage; i++) {
                    if (i < response.documents.length) {
                        var card = JobCardsTemplate;

                        if (response.documents[i].jobDetailUrl !== "" || response.documents[i].jobDetailUrl !== null) {
                            card = card.replace("{jobDetailUrl}", response.documents[i].jobDetailUrl.replace("{0}", jobSearchReinvent.Data.countryInfo.countrySite));
                        }
                        else {
                            card = card.replace("{jobDetailUrl}", window.location.origin + joblistingUrl.replace("{0}", response.documents[i].id));
                        }

                        if (colorBar !== null) {
                            card = card.replace("{colorBar}", "border-thick-top br-top-color-" + colorBar);
                        }

                        var countryTemplate = "<p class='small ucase job-location'>" +
                            "{jobCountry} {divider}" +
                            "<span class='corporate-semibold job-city-state'>{jobCityState}</span>" +
                            "</p>";

                        if (response.documents[i].location.length > 1) {
                            if (showCountry === "True" || showCity === "True") {
                                countryTemplate = countryTemplate.replace("{jobCityState}", mutlipleLoc);
                            } else {
                                countryTemplate = countryTemplate.replace("{jobCityState}", "");
                            }

                            countryTemplate = countryTemplate.replace("{jobCountry}", "");
                            countryTemplate = countryTemplate.replace("{divider}", "");
                        }
                        else if (response.documents[i].location.length === 0) {
                            if (showCountry === "True" || showCity === "True") {
                                countryTemplate = countryTemplate.replace("{jobCityState}", locationNego);
                            } else {
                                countryTemplate = countryTemplate.replace("{jobCityState}", "");
                            }



                            countryTemplate = countryTemplate.replace("{jobCountry}", "");
                            countryTemplate = countryTemplate.replace("{divider}", "");
                        }
                        else {

                            if (showCountry === "True" && response.documents[i].country !== "") {
                                countryTemplate = countryTemplate.replace("{jobCountry}", "<span class='corporate-semibold'>" + response.documents[i].country + "</span>");
                            }
                            else {
                                countryTemplate = countryTemplate.replace("{jobCountry}", "");
                            }

                            if (showCity === "True" && response.documents[i].location[0] !== "") {
                                countryTemplate = countryTemplate.replace("{jobCityState}", response.documents[i].location[0]);
                            }
                            else {
                                countryTemplate = countryTemplate.replace("{jobCityState}", "");
                            }

                            if (showCountry === "True" && showCity === "True") {
                                countryTemplate = countryTemplate.replace("{divider}", "<span class='vertical-divider'></span>");
                            }
                            else {
                                countryTemplate = countryTemplate.replace("{divider}", "");
                                countryTemplate = countryTemplate.replace("{jobCountry}", "");
                                countryTemplate = countryTemplate.replace("{jobCityState}", "");
                            }
                        }

                        if (showCountry === "True" || showCity === "True") {
                            card = card.replace("{CountryCityTemplate}", countryTemplate);
                        } else {
                            card = card.replace("{CountryCityTemplate}", "");
                        }

                        //for analytics
                        card = card.replace("{jobTitle}", response.documents[i].title);
                        card = card.replace("{jobTitle2}", response.documents[i].title);
                        card = card.replace("{componentName}", componentName);
                        card = card.replace("{templateName}", templateName);

                        if (showTitle === "True" && response.documents[i].title !== "") {
                            card = card.replace("{jobTitleVal}", response.documents[i].title);
                        }
                        else {
                            card = card.replace("{jobTitleVal}", "");
                        }

                        var jobDescTemplate = "<p class='card-description job-listing-description corporate-regular'><span class='areas-of-interest corporate-semibold'>{jobskill}</span>{hyphen}{jobDesc}</p>";

                        if (showSkill === "True" && response.documents[i].skill !== "") {
                            jobDescTemplate = jobDescTemplate.replace("{jobskill}", response.documents[i].skill);
                        }
                        else {
                            jobDescTemplate = jobDescTemplate.replace("{jobskill}", "");
                        }

                        var jobDescToTruncate = cleanDescription(response.documents[i].jobDescription);

                        var truncDesc = $("<div/>").html(jobDescToTruncate).text().substr(0, 350);

                        if (showDesc === "True" && truncDesc !== "") {
                            jobDescTemplate = jobDescTemplate.replace("{jobDesc}", truncDesc);
                        }
                        else {
                            jobDescTemplate = jobDescTemplate.replace("{jobDesc}", "");
                        }

                        if (showSkill === "True" && showDesc === "True") {
                            if (response.documents[i].skill !== "" && response.documents[i].jobDescription !== "") {
                                jobDescTemplate = jobDescTemplate.replace("{hyphen}", " — ");
                            }
                            else {
                                jobDescTemplate = jobDescTemplate.replace("{hyphen}", "");
                            }
                        }
                        else {
                            jobDescTemplate = jobDescTemplate.replace("{hyphen}", "");
                        }

                        if (showSkill === "True" || showDesc === "True") {
                            card = card.replace("{DescriptionSkillTemplate}", jobDescTemplate);
                        } else {
                            card = card.replace("{DescriptionSkillTemplate}", "");
                        }

                        if (showDate === "True" && response.documents[i].postedDate !== "") {
                            card = card.replace("{parsedPostedDate}", "<p class='posted-date small'>" + getDateTimeDifference(response.documents[i].postedDate) + "</p>");
                        }
                        else {
                            card = card.replace("{parsedPostedDate}", "");
                        }

                        //cta
                        if (showCTA === "True") {
                            var ctaTemplate = '<div class="job-listing - link - arrow corporate - semibold"> ' +
                                '<div class="arrow cta-arrow ucase serp-card-read-more" data-linktype="engagement" data-analytics-content-type="engagement" ' +
                                'data-analytics-link-name="{ctaText}" data-jobregiondesc="{regionDesc}" data-aob="" ' +
                                'data-analytics-jobid="{jobId}" data-analytics-jobtitle="{jobTitle}" aria-label="{ctaText2}" ' +
                                'data-analytics-link-type="engagement" data-analytics-content-class="content" data-analytics-engagement="false">' +
                                '{ctaText3}</div></div>';

                            ctaTemplate = ctaTemplate.replace("{ctaText}", ctaText);
                            ctaTemplate = ctaTemplate.replace("{ctaText2}", ctaText);
                            ctaTemplate = ctaTemplate.replace("{ctaText3}", ctaText);
                            ctaTemplate = ctaTemplate.replace("{regionDesc}", response.documents[i].regiondesc);
                            ctaTemplate = ctaTemplate.replace("{jobId}", response.documents[i].id);
                            ctaTemplate = ctaTemplate.replace("{jobTitle}", response.documents[i].title);

                            card = card.replace("{linkArrow}", ctaTemplate);
                        }
                        else {
                            card = card.replace("{linkArrow}", "");
                        }

                        latestJobsArr.push(card);
                        latestJobsSet.empty()

                        for (ctr = 0; ctr < latestJobsArr.length; ctr++) {
                            latestJobsSet.append(latestJobsArr[ctr]);
                        } 
                        setEllipsis();

                    }
                }
            }
        }
    }
    var getRelatedJobs = function (keyword) {
        var latestFrom = 1;
        var data = {
            "searchKeyword": keyword,
            "from": latestFrom,
            "size": jobsperpage,
            "lang": $("html").attr("lang"),
            "countrySites": searchHeroCountrySite,
            "country": countryName,
            "includeSynonyms": false,
            "wordDistance": 0
        };


        $.ajax({
            type: "POST",
            url: "/api/sitecore/JobListingBlock/GetRelatedJobs",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                //alert(response.JobTitle);
                if (response !== null) {
                    jobSearchReinvent.Data.responseFromEs = response;
                    jobSearchReinvent.Data.countryInfo.countrySite = searchHeroCountrySite;
                    //searchAllJobLink
                    if (searchAllJobLink != null) {
                        searchAllJobLink[0].href = (searchAllURL + "?jk=" + keyword + "&sb=0&pg=1");
                    }
                    //jobSearchReinvent.Data.dataQuery = data;
                }
            },
            complete: function () {
                latestJobsArr = [];
                jobSearchReinvent.updateJobResults(jobSearchReinvent.Data.responseFromEs);
            },
            error: function (xhr, ajaxOptions, thrownError) {
            }
        });
    };

    return {
        // properties
        keywordSuggestions: keywordSuggestions,
        searchHeroSettings: searchHeroSettings,
        autoCompleteKeywords: autoCompleteKeywords,
        // methods
        FormatSearchHeroValue: FormatSearchHeroValue,
        Init: Init,
        AppendPolyfillForIE: AppendPolyfillForIE,
        InitializeKeywordSuggestions: InitializeKeywordSuggestions,
        GetPath: GetPath,
        SetDefaultPath: SetDefaultPath,
        Typeahead: Typeahead,
        ShowResults: ShowResults,
        ShowFilters: ShowFilters,
        FilterResults: FilterResults,
        IsFilterSelected: IsFilterSelected,
        RemoveAllFilters: RemoveAllFilters,
        ToggleSort: ToggleSort,
        RetainFocusOnFilter: RetainFocusOnFilter,
        isSerpTablet: isSerpTablet,
        FilterSortBy: FilterSortBy,
        CloseAccordions: CloseAccordions,
        ToggleFilterButton: ToggleFilterButton,
        ShowFilterFooter: ShowFilterFooter,
        ResetFilterSelect: ResetFilterSelect,
        CheckOpenedAccordions: CheckOpenedAccordions,
        RemoveClassCallback: RemoveClassCallback,
        CheckFiltersBrowser: CheckFiltersBrowser,
        OpenAccordions: OpenAccordions,
        ShowSortByOnly: ShowSortByOnly,
        GetSearchData: GetSearchData,
        GetAutocompleteKeyword: GetAutocompleteKeyword,
        RemoveTags: RemoveTags,
        StoreRecentSearch: StoreRecentSearch,
        SelectRecentSearch: SelectRecentSearch,
        DisplayRecentSearch: DisplayRecentSearch,
        HideSearchResults: HideSearchResults,
        HideFilters: HideFilters,
        SpacesAndSingleCharacter: SpacesAndSingleCharacter,
        InitializeStartSearch: InitializeStartSearch,
        StartSearch: StartSearch,
        SearchTips: SearchTips,
        NoSearchResults: NoSearchResults,
        ResultsForKeyword: ResultsForKeyword,
        ShowNumberResults: ShowNumberResults,
        DidYouMean: DidYouMean,
        AllResults: AllResults,
        ClickRecentSearch: ClickRecentSearch,
        DisplayContentType: DisplayContentType,
        DisableForm: DisableForm,
        EnableForm: EnableForm,
        CallBack: CallBack,
        PerformSearch: PerformSearch,
        PreviousPage: PreviousPage,
        NextPage: NextPage,
        ChangePage: ChangePage,
        GeneratePagination: GeneratePagination,
        AddEllipsis: AddEllipsis,
        ClearedFeaturedSearchResults: ClearedFeaturedSearchResults,
        RecentSearchHide: RecentSearchHide,
        EventHandlers: EventHandlers,
        GetFeaturedImagePath: GetFeaturedImagePath,
        CheckHighlightedTopicHeaderUrl: CheckHighlightedTopicHeaderUrl,
        CheckHighlightedTopicHeader: CheckHighlightedTopicHeader,
        DisplayHighlightedEventRegister: DisplayHighlightedEventRegister,
        HighlightedTopicItems: HighlightedTopicItems,
        SearchResultsElements: SearchResultsElements,
        SearchResultsContentType: SearchResultsContentType,
        SearchResultsDateCategory: SearchResultsDateCategory,
        SearchResultsTitle: SearchResultsTitle,
        SearchResultsContent: SearchResultsContent,
        SearchResultsDescription: SearchResultsDescription,
        HighlightContentDescription: HighlightContentDescription,
        RecommendedSearchbyKeywords: RecommendedSearchbyKeywords,
        SetSearchHeroSettings: SetSearchHeroSettings,
        SetSuggestionQuery: SetSuggestionQuery,
        SelectViewAll: SelectViewAll,
        SelectSuggestion: SelectSuggestion,
        StoreLocalStorage: StoreLocalStorage,
        SearchFieldMouseEvents: SearchFieldMouseEvents,
        SearchFieldKeyboardEvents: SearchFieldKeyboardEvents,
        TabIndexAccessibility: TabIndexAccessibility,
        FirefoxAccessibility: FirefoxAccessibility,
        ViewAllSearch: ViewAllSearch,
        SafariAccessibility: SafariAccessibility,
        ScrollUp: ScrollUp,
        FeaturedSectionDisplayControl: FeaturedSectionDisplayControl,
        ChangeFocus: ChangeFocus,
        AriaLiveControl: AriaLiveControl,
        PerformSuggestedTopicSearch: PerformSuggestedTopicSearch,
        AddRemoveFilterFromUrl: AddRemoveFilterFromUrl,
        RemoveDuplicatedFilterStorage: RemoveDuplicatedFilterStorage,
        SearchFilterMobile: SearchFilterMobile,
        ManualAddFilter: ManualAddFilter,
        highlightedForFiltersDisplayControl: highlightedForFiltersDisplayControl,
        ResetArrays: ResetArrays,
        ConvertCharacter: ConvertCharacter,
        IncludesPolyfillForIE: IncludesPolyfillForIE,
        removeFocusIndicatorOnClick: removeFocusIndicatorOnClick,
        setEllipsis: setEllipsis,
    };
}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\DownloadModule.js
/*version="2"*/
if (ComponentRegistry.Download) {
        function setDownloadModuleContent(header, description, color, downloadItems) {
            var downloadItemCollection = JSON.parse(downloadItems);
            $('#download-module-header').html(header);
            $('#download-module-description').html(description);
            var el = document.getElementById('DownloadItems');
            var AnalyticsLinkName;
            while (el.hasChildNodes()) {
                el.removeChild(el.lastChild);
            }
            for (var counter = 0; counter < downloadItemCollection.length; counter++) {
                AnalyticsLinkName =  typeof downloadItemCollection[counter].LinkName !== "undefined" ? downloadItemCollection[counter].LinkName.toLowerCase() : "" ;
                $('#DownloadItems').append("<div class='wrapper-icon'><span class='acn-icon sm icon-circle color-"+color+"'><span class='icon-text text-only'>" + (counter + 1) + "</span></span></div><br/><p class='download-module-link'>" + downloadItemCollection[counter].DisplayText + "</p><a href='" + downloadItemCollection[counter].Link + "' class='color-"+color+"' target='_blank' data-analytics-link-name='" + AnalyticsLinkName + "' data-analytics-content-type='engagement'>" + downloadItemCollection[counter].LinkName + "</a><br/>");
            }
            //SU Bug 635520 - modal overlaps in edit
            var downloadModal = $('#download-module-modal');
            downloadModal.modal('show');
            if ($('#scCrossPiece').length > 0) {
                downloadModal.css({ 'margin-top': '100px' });
            };
        }

        $('#download-module-button').on('click', function (event) {
            $('#download-module-modal').modal('hide');
        });

        if (isDesktop()) {
            //JS Error - checking object if defined and not null
            var objAlive = typeof downloadLocalStorage != 'undefined' && downloadLocalStorage != null;
            if (objAlive) {
                var branchId = downloadLocalStorage.getItem("BranchId");
                //Bug 311698 : [About Culture and Values] Download is preloaded in article utility control.
                //{7FAFC20C-52C2-4F17-A73D-333D190B1A94} is the Item ID of AboutAccentureCultureAndValuesPage branch
                //{6B8238E7-322A-4172-8C0B-CB2246AE1FF6} is the Item ID of AboutAccenturePeoplePage branch
                if (branchId == '{7FAFC20C-52C2-4F17-A73D-333D190B1A94}' || branchId == '{6B8238E7-322A-4172-8C0B-CB2246AE1FF6}') {
                    $('#toolbar').find($('#DownloadModule').addClass("hidden-lg hidden-md"))
                }
            }
        }
        $('div#DownloadModule a').attr("title", "Download");

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\JumpLink.js
/* Version = "8" */

if (ComponentRegistry.JumpLink) {
    //screen sizes
    var mobile_screen = 767;//mobile
    var tab_screen_min = 768;// min tablet
    var tab_screen_max = 991;//max tablet 

    //browser height
    var browserHeight = ($(window).height() !== undefined ? $(window).height() : 0);
    var aBarOffset = 0;
    var jumpLinkDropDown = $('#jumplink-dropdown');

    //RMT 3645	
    function setDropdownHeight() {
        bHeight = ($(window).height() !== undefined ? $(window).height() : 0);
        var headerHeight = 0;
        headerHeight = $('#block-jumplink').outerHeight() + $('#header-topnav').outerHeight();
        var jumplinkListHeight = bHeight - headerHeight;
        setIOSView(bHeight);

        jumpLinkDropDown.css({
            "max-height": jumplinkListHeight + aBarOffset,
            "overflow-y": 'auto'
        });
        jumpLinkDropDown.find('li').last().css("margin-bottom", '0px');
    }

    function setIOSView(tHeight) {
        if (pageState.isIOS && !windowWidth <= mobile_screen) {

            if (tHeight < 704) {
                if (tHeight == 681) {
                    aBarOffset = 58;
                }
                if (tHeight == 671) {
                    aBarOffset = 68;
                }
                if (tHeight == 648) {
                    aBarOffset = 85;
                }
            }
            else {
                aBarOffset = 35;
            }
        }
    }
    //RMT 3645

    function changeNavTotal() {
        var totalnav = $('#jumplink-dropdown li').length - 1;
        $("#total-navigation").html(totalnav);
    }
    window.onload = function () {
        changeNavTotal();
    }

    $(function () {
        $("#block-jumplink").hide();

        changeNavTotal();

        //RMT 3645 
        //overlapping scrollbar
        if (pageState.ieno == "11" || pageState.ieno == "10") {
            jumpLinkDropDown.css('margin-right', 17);
        }
        //RMT 3645

        var dropdownCount = $('#jumplink-dropdown li').length;
        var blockCount = $('.block-title').length;

        if (branchTemplate == '{36BD0663-9AAE-4B1F-9374-2CD6261F2CE9}') {
            var dropdownCount = $('#jumplink-dropdown li').length;
            var blockCount = $('.block-title').length;
            for (i = blockCount; i < dropdownCount; i++) {
                var blockCtr = $('.block-title').length;
                $('#jumplink-dropdown li').eq(blockCtr).remove();
            }

        }

        if ($("#total-navigation").html() == "-1") {
            $("#total-navigation").html(totalnav);
        }
        ////screen sizes
        //var mobile_screen = 767;//mobile
        //var tab_screen_min = 768;// min tablet
        //var tab_screen_max = 991;//max tablet        


        //if ($("#accent").length == 0) {
        //    $(".ui-container.row .block-title").removeClass("first");
        //}
        //SIR 319314
        //$("#hero-carousel .carousel-inner").on("click", function (e) { if (!$(e.target).hasClass("btn")) { $("#icon-type-to-search").trigger("click"); } });

        //  UP ARROW
        $("#jumplink-page-up").on("click", function (event) {
            // $(this).css('text-decoration', 'none');

            var blockUp = $("#jumplink-dropdown li.activeli").prev();
            // location.hash = $(blockUp).children('a').attr('href');   
            if ($(blockUp).children('a').attr("data-jump-link-number") == 0) {
                $('#jumplink-dropdown').hide();
                event.preventDefault();
                return;
            }
            if ($('#jumplink-dropdown').is(":visible")) {
                $('#jumplink-dropdown').hide();
            }
            JumpLink.ScrollTo($(blockUp).children('a').attr('href'));
        });

        //  DOWN ARROW
        $("#jumplink-page-down").on("click", function (event) {

            // $(this).css('text-decoration', 'none');
            var blockDown = $("#jumplink-dropdown li.activeli").next();
            //  location.hash = $(blockDown).children('a').attr('href');
            if ($(blockDown).children('a').attr("data-jump-link-number") == null) {
                $('#jumplink-dropdown').hide();
                event.preventDefault();
                return;
            }
            if ($('#jumplink-dropdown').is(":visible")) {
                $('#jumplink-dropdown').hide();
            }
            JumpLink.ScrollTo($(blockDown).children('a').attr('href'));
        });


        // DROPDOWN li click

        $('.to-top').on("click", function () {

            $("html, body").animate({ scrollTop: 0 }, 500);

            if ($(window).scrollTop() === 0) {
                $('#jumplink-dropdown').hide();
                $("#block-jumplink").hide();
            }
        });

        /* This will get the distance of first block-title
        from its parent block container. And checks if the 
        first block container is a valid block by its ID prefix which is
        "block" (e.g. block-features). */
        function JumplinkWithPreCssAdj() {
            var withPreCssAdj = 0;
            var firstBlockTitle = $("#content-wrapper > section > div:first-child > div.block-title.first");
            var accentLogo = $(".customLogo");
            if (firstBlockTitle.length !== 0 && accentLogo.length !== 0) {
                var firstDivBlock = $("#content-wrapper > section > div:first-child");
                var firstDivIdBlock = firstDivBlock.attr('id');
                if (firstDivBlock.length !== 0 && firstDivIdBlock.substring(0, 5) == 'block') {
                    if (typeof firstBlockTitle.offset() !== 'undefined' && typeof firstDivBlock.offset() !== 'undefined') {
                        withPreCssAdj = firstBlockTitle.offset().top - firstDivBlock.offset().top;
                        if (withPreCssAdj < 1) {
                            /* returns zero when negative */
                            withPreCssAdj = 0;
                        }
                    }
                }
            }
            return withPreCssAdj;
        }

        $(window).on('scroll resize orientation', function () {
            var ribbonHeight = ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0);
            var headerTopNavHeight = $('#header-topnav').outerHeight();
            var cookieNavHeight = 0;
            if ($('.cookie-nav').is(":visible")) {
                cookieNavHeight = ($('.cookie-nav').height() !== undefined ? $('.cookie-nav').height() : 0);
            }

            if (!(windowWidth <= mobile_screen)) {
                setDropdownHeight();
            }


            var jumplinkTopPos = headerTopNavHeight + ribbonHeight + cookieNavHeight;

            var totalnav = $('#jumplink-dropdown li').length - 1;
            $("#total-navigation").html(totalnav);

            $('#block-jumplink').show().css('top', jumplinkTopPos);

            if ($(window).scrollTop() === 0) {
                $("#block-jumplink").hide();
            }

            var firstDropdownItem = $("#jumplink-dropdown li")[1];
            var jumplinkDDownColor = $("#jumplink-dropdown").css('background-color');
            var link = $(firstDropdownItem).children('a').attr('href');
            var scrollTop = $(window).scrollTop() + ribbonHeight;
            // alert(firstDropdownItem);
            var elementOffset = $(link).length ? $(link).offset() : 0;
            var distance = (elementOffset.top - (scrollTop) - cookieNavHeight);

            //without logo
            if ($(link).children('div').first().hasClass('iscrisscrossed')) {
                if ($(window).width() <= mobile_screen) //mobile
                    distance = distance - 100;
                else if ($(window).width() >= tab_screen_min && $(window).width() <= tab_screen_max) //tablet
                    distance = distance - 100;
                else
                    distance = distance - 125; //desktop
            }
            //with logo
            if (!$(link).children('div').first().hasClass('iscrisscrossed')) {
                if ($(window).width() <= mobile_screen && $(window).width() >= tab_screen_min && $(window).width() <= tab_screen_max) //mobile and tablet
                    distance = distance + 40;
                else
                    distance = distance + 25;

            }

            if ($(window).width() >= tab_screen_min && $(window).width() <= 960) {
                distance = distance + JumplinkWithPreCssAdj();
            }

            //if ($(link).children('div').hasClass('first')) {
            //    distance = distance;
            //}


            // 1/14 Merge Main Release: Changeset 724330 to 728897

            //fix with blocks with 'isdroop' class
            //if ($(link).children('div').hasClass('isdroop')) {
            //    distance = distance - 150;
            //}

            //fix with first blocks with 'iscrisscrossed' class
            //if ($(link).children('div').hasClass('iscrisscrossed')) {
            //    distance = distance - 150;
            //}
            // alert(distance);
            if (distance <= JumplinkWithPreCssAdj()) {
                $('#block-jumplink .lateral-navigation').animate({ top: "13px" }, 0);
                $('#jump-link-headline').css('visibility', 'visible');
                //  $('#jumplink-lateral-nav').css('visibility', 'visible');


            }
            else {
                $('#jumplink-dropdown').hide();
                $('#jump-link-headline').css('visibility', 'hidden');
                $('#block-jumplink .lateral-navigation').animate({ top: "-33px" }, 0);

            }

            $(".block-title").each(function () {
                var ribbonHeight = ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0);
                var cookieNavHeight = 0;
                if ($('.cookie-nav').is(":visible")) {
                    cookieNavHeight = ($('.cookie-nav').height() !== undefined ? $('.cookie-nav').height() : 0);
                }

                if (!$(link).children('div').first().hasClass('iscrisscrossed')) {
                    var jumpOffset = 100;
                } else {
                    var jumpOffset = 100 + ribbonHeight;
                }

                var thisOffset = $(this).length ? $(this).offset() : 0;
                if ((thisOffset.top - jumpOffset - cookieNavHeight) - $(window).scrollTop() <= 0) {
                    var blockId = $(this).parent().attr('id');
                    var linksToGoogle = $('#jumplink-dropdown a[href="#' + blockId + '"]');
                    var blockIdComp = "#" + blockId;

                    $("#jump-link-headline").html($(linksToGoogle).children("span").html());
                    $("#jumplink-dropdown li").removeClass("activeli");
                    $("#jumplink-dropdown li a").css('background-color', jumplinkDDownColor);

                    $("#jumplink-dropdown li a").each(function () {
                        if (blockIdComp == $(this).attr('href')) {
                            linksToGoogle.parent().addClass("activeli");

                            var currentLi = $(linksToGoogle).parent();
                            var jumplinkColor = $("#block-jumplink").css('background-color');

                            if (currentLi.attr("class") == "activeli") {
                                $("#current-navigation").html($(currentLi).children('a').attr('data-jump-link-number'));
                                $(".activeli a").css('background-color', jumplinkColor);
                            }

                            $("#total-navigation").html($("#jumplink-dropdown li").length - 1);
                        }
                    });
                }
            });



        });

        $("#jumplink-lateral-nav button").on("click", function () {
            JumpLink.ToggleDropdownIcon();
            if (!$('#jumplink-dropdown').is(":visible")) {

                var headerHeight = 0;
                headerHeight = $('#block-jumplink').outerHeight() + $('#header-topnav').outerHeight();
                var cookieNavHeight = 0;
                if ($('.cookie-nav').is(":visible")) {
                    cookieNavHeight = $('.cookie-nav').outerHeight();
                    headerHeight += cookieNavHeight;
                }
                var jumplinkListHeight = browserHeight - headerHeight;
                //put scrollbar
                $('#jumplink-dropdown').css("max-height", jumplinkListHeight);
                $('#jumplink-dropdown').css("overflow-y", 'auto');
                $('#jumplink-dropdown li').last().css("margin-bottom", '0px');


            }
        });

        $('#scrollspy').on("click", function () {
            setDropdownHeight();
            jumpLinkDropDown.toggle();
            return false;
        });

        $(document).on("click", function () {
            $('#jumplink-dropdown').hide();
        });

        //RMT7211 Web Accessibility Issues - Share, Print, VideoCarousel controlsPagination Dots, Jumplinks
        $('div.ui-content-box a').eq(0).on("keydown", function (e) {
            var toTop = $('#block-jumplink span.to-top a');
            if (e.which == 9 && $(toTop).is(":visible")) {
                e.preventDefault();
                $('#block-jumplink span.to-top a').trigger("focus");
            }
        });

    });

    $("#jumplink-dropdown li a").on("click", function (event) {
        var target = $(this).attr("href");
        if ($(this).parent().hasClass('activeli')) {
            $('#jumplink-dropdown').hide();
            event.preventDefault();
            return;
        }

        if ($('#jumplink-dropdown').is(":visible")) {
            $('#jumplink-dropdown').hide();
        }
        JumpLink.ScrollTo(target);
    });

    var jumplinkColor = $("#block-jumplink").css('background-color');
    var jumplinkDDownColor = $("#jumplink-dropdown").css('background-color');

    $("#jumplink-dropdown li a").on("mouseenter", function () {
        if (!$(this).parent().hasClass('activeli')) {
            $(this).css('background-color', jumplinkColor);
        }

    }).on("mouseleave", function () {
        if (!$(this).parent().hasClass('activeli')) {
            $(this).css('background-color', jumplinkDDownColor);
        }
    });

    $('#jumplink-page-up').on("mouseenter", function () {
        $(this).css('opacity', .8);

    }).on("mouseleave", function () {
        $(this).css('opacity', 1);
    });

    $('#jumplink-page-down').on("mouseenter", function () {
        $(this).css('opacity', .8);

    }).on("mouseleave", function () {
        $(this).css('opacity', 1);
    });


    var JumpLink = {


        ToggleDropdownIcon: function () {
        },

        ScrollTo: function (elementId) {
            var cookieNavHeight = 0;
            if ($('.cookie-nav').is(":visible")) {
                cookieNavHeight = ($('.cookie-nav').height() !== undefined ? $('.cookie-nav').height() : 0);
            }

            //Bug 483052 - For Block Header and First Block Title(Accenture Interactive Page)
            var blockHeightfirstbody = $("#content-wrapper > section > div:first-child > div.block-title.first").innerHeight();
            var checkCustomLogo = $('#accent').hasClass('accent-container customLogo');
            //removed 'first' to avoid confusion
            var BlockOffsetDesktop = 103;
            var BlockOffsetTablet = 95;
            var BlockOffsetMobile = 68;


            // values adjusted upon scrolling on first block whenever logo is present or not
            var firstBlockWithLogo_D = -40; // desktop
            var firstBlockWithLogo_MT = -40; // mobile and tablet

            var firstBlockNoLogo_D = 103; //desktop
            var firstBlockNoLogo_T = 99; //tablet
            var firstBlockNoLogo_M = 80; // mobile
            var elem = $("div[id='" + elementId.substr(1) + "']");
            var elemOffset = elem.length ? elem.offset() : 0;
            var offSet = elemOffset.top - 103;
            if (isMobile()) {
                firstBlockWithLogo_MT = -25;
            }

            //with acn logo
            if ($("div[id='" + elementId.substr(1) + "']" + " .block-title").first().hasClass('first')) {
                BlockOffsetDesktop = firstBlockWithLogo_D;
                BlockOffsetTablet = firstBlockWithLogo_MT;
                BlockOffsetMobile = firstBlockWithLogo_MT;
            }

            //without acn logo
            if ($("div[id='" + elementId.substr(1) + "']" + " .block-title").first().hasClass('iscrisscrossed')) {
                BlockOffsetDesktop = firstBlockNoLogo_D;
                BlockOffsetTablet = firstBlockNoLogo_T;
                BlockOffsetMobile = firstBlockNoLogo_M;
            }
            var windowWidth = $(window).width();
            //mobile         
            if (windowWidth <= mobile_screen) {
                offSet = elemOffset.top - BlockOffsetMobile;
                if ($('#jumplink-dropdown a[href="' + elementId + '"]').attr('data-jump-link-number') == 1) {
                    offSet = elemOffset.top - BlockOffsetMobile;
                }

                $('html, body').animate({ scrollTop: offSet - ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0) - cookieNavHeight }, 750);
            }

            //tablet
            else if (windowWidth >= tab_screen_min && windowWidth <= tab_screen_max) {
                offSet = elemOffset.top - BlockOffsetTablet;

                if ($('#jumplink-dropdown a[href="' + elementId + '"]').attr('data-jump-link-number') == 1) {
                    offSet = elemOffset.top - BlockOffsetTablet;
                    //Bug 483052 - For Block Header and First Block Title(Accenture Interactive Page)
                    if (checkCustomLogo) {
                        offSet += 12;
                    }
                }
                $('html, body').animate({ scrollTop: offSet + 5 - ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0) - cookieNavHeight }, 750);
            }
            //iPad Mini - Landscape
            else if (windowWidth >= tab_screen_max && windowWidth <= 1024) {
                offSet = elemOffset.top - BlockOffsetTablet;

                if ($('#jumplink-dropdown a[href="' + elementId + '"]').attr('data-jump-link-number') == 1) {
                    offSet = elemOffset.top - BlockOffsetTablet;
                    //Bug 483052 - For Block Header and First Block Title(Accenture Interactive Page)
                    if (checkCustomLogo) {
                        offSet += 15;
                    }
                }
                $('html, body').animate({ scrollTop: offSet + 5 - ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0) - cookieNavHeight }, 750);
            }
            //desktop
            else {
                if ($('#jumplink-dropdown a[href="' + elementId + '"]').attr('data-jump-link-number') == 1) {
                    offSet = elemOffset.top - BlockOffsetDesktop;
                    //Bug 483052 - For Block Header and First Block Title(Accenture Interactive Page)
                    if (checkCustomLogo) {
                        offSet -= blockHeightfirstbody;
                    }
                }
                $('html, body').animate({ scrollTop: offSet + 5 - ($('#scCrossPiece').height() !== undefined ? $('#scCrossPiece').height() : 0) - cookieNavHeight }, 750);
            }
        }
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\timeline.js
//version 3
if (ComponentRegistry.TimelineModule) {
    //Bug 220077: Update on timeline
$(function () {
        //Bug 339289 : CareersLayout-Homepage: Timeline Module in WHERE DO YOU WANT TO GO Block
        var $slider = $(".timeline-outer .timeline-slider"),
            leftValue = 0.00, difference = 0, startQueue = 0, endQueue = 0, milestoneNo, lastIndexDifference = 0, width = 0;
        makeTimeline();

        $(window).on("resize", function () {
            makeTimeline();
        });

        function makeTimeline() {
            var milestone = $(".timeline-inner .timeline-milestone");
            var ctr = 0;
            var currentStep = 0;
            var mobileEdge = false;
            var previousMilestone = 0;
            var total = milestone.length;
            var stepNo = 30;
            var nodes = total - 1;
            var maxValue = Math.floor(nodes * stepNo);
            var currentSelection = 0;
            var mobileMode = isMobile();
            var $mobileSliderExt = $('#mobile-slider-extension');
            //RST:For Merging
            var $timelineInner = $('.timeline-inner');
            //[AJS 01/08] Accessibility Relationship_between_slider_and_content_pane -start
            var valueTextMilestoneContainer = $(".timeline-inner .timeline-milestone.active");
            var valueTextMilestone = valueTextMilestoneContainer.children("p").text() + valueTextMilestoneContainer.find(".timeline-year-number").text() + valueTextMilestoneContainer.find(".module-article.item .quote.quote-text").text();
            var valueTimelineMilestoneCaption = $.trim($(".timeline-milestone.active").children(".timeline-year-number").text());
            if (valueTextMilestoneContainer.find(".btn.btn-primary").text() != "") {
                valueTextMilestone += valueTextMilestoneContainer.find(".btn.btn-primary").text() + "Button to Activate Press Shift Tab";
            }
            //-end

            var buttonLable = $(".timeline-milestone").find("button");
            for (var i = 0; i < buttonLable.length; i++) {
                $(buttonLable[i]).attr({
                    'data-analytics-link-name': $(buttonLable[i]).text(),
                    'data-analytics-content-type': 'cta'
                })
            }
            $slider.slider({
                min: 0,
                max: maxValue,
                value: currentSelection,
                step: stepNo,
                slide: function (event, ui) {
                    $(".ui-slider-handle").text("◄►");
                },
                change: function (event, ui) {
                    var stepValue = ui.value;
                    var hideExcess = false;

                    //[AJS 01/08] Accessibility Relationship_between_slider_and_content_pane -start
                    $(".ui-slider-handle").attr('aria-valuenow', stepValue);                   
                    //-end
                    milestoneNo = (stepValue / stepNo) + lastIndexDifference;
                    var currentYear = $.trim($('[data-milestone-no="' + milestoneNo + '"]').children(".timeline-year-number").text());

                    $(".ui-slider-handle").text("◄►").attr({
                        'data-analytics-link-name': 'timeline-milestone-caption-' + milestoneNo + '-' + currentYear,
                        'data-analytics-content-type': 'timeline'
                    });


                    if (mobileMode) {
                        milestoneNo = (stepValue / stepNo);
                        //Determining the current step
                        //Be careful on modifying this, you have to cover all scenarios in testing.
                        //Moving one and two steps forward/backward and so on...
                        if (milestoneNo > ctr) {
                            if (stepValue == maxValue) {
                                ctr += milestoneNo - previousMilestone;
                                currentStep = ctr * stepNo;
                            } else {
                                ctr = milestoneNo;
                                currentStep = stepValue;
                            }
                        }
                        else if (previousMilestone != 0 && (stepValue == maxValue || previousMilestone < milestoneNo)) {
                            ctr += milestoneNo - previousMilestone;
                            currentStep = ctr * stepNo;
                        }
                        else if (ctr > 0 && stepValue < maxValue && !mobileEdge) {
                            if ((previousMilestone - milestoneNo) >= 2) {
                                ctr -= previousMilestone - milestoneNo;
                            } else {
                                ctr -= 1;
                            }
                            currentStep = ctr * stepNo;
                            hideExcess = true;
                        }
                        previousMilestone = milestoneNo;
                        mobileEdge = true;
                    } else {
                        ctr = milestoneNo;
                    }

                    if (mobileMode && ui.value == maxValue && endQueue >= 0) {
                        if (endQueue > 0) {
                            $mobileSliderExt.removeClass("hidden");
                            moveSliderItems(0.00 - leftValue);
                            $slider.slider({
                                value: maxValue - stepNo
                            });
                            if (endQueue == 1) {
                                $mobileSliderExt.addClass("hidden");
                            }
                            endQueue--;
                            startQueue++;
                            milestoneNo++;

                        }
                        else {

                            milestoneNo = nodes;
                            lastIndexDifference = 1;
                        }
                    }
                    else if (mobileMode && ui.value == 0 && startQueue >= 0) {
                        if (startQueue > 0) {
                            $mobileSliderExt.removeClass("hidden");
                            moveSliderItems(leftValue);
                            $slider.slider({
                                value: 0 + stepNo
                            });
                            startQueue--;
                            endQueue++;
                            milestoneNo--;
                        }
                        else {
                            milestoneNo = 0;
                            lastIndexDifference = 0;
                        }
                    }
                    mobileEdge = false;

                    $('.timeline-milestone.active').removeClass("active");
                    $('.timeline-inner').find('[data-milestone-no="' + ctr + '"]').addClass('active');

                    //[AJS 01/08] Accessibility Relationship_between_slider_and_content_pane -start
                    valueTextMilestoneContainer = $(".timeline-inner .timeline-milestone.active");
                    valueTextMilestone = valueTextMilestoneContainer.children("p").text() + valueTextMilestoneContainer.find(".timeline-year-number").text() + valueTextMilestoneContainer.find(".module-article.item .quote.quote-text").text();

                    if (valueTextMilestoneContainer.find(".btn.btn-primary").text() != "") {
                        valueTextMilestone += valueTextMilestoneContainer.find(".btn.btn-primary").text() + "Button to Activate Press Shift Tab";
                    }
                    $(".ui-slider-handle").attr('aria-valuetext', valueTextMilestone);

                    $slider.find(".timeline-milestone-caption.active").removeClass("active");
                    var $milestoneElem = $(".timeline-milestone-caption-" + ctr);
                    $milestoneElem.addClass('active');

                    if (mobileMode) {
                        var nextMilestoneNo = ctr + 1;
                        if (nextMilestoneNo < total && nextMilestoneNo > 3) {
                            if (!$slider.find(".timeline-milestone-caption-" + nextMilestoneNo).is(":visible")) {
                                $slider.find(".timeline-milestone-caption-" + nextMilestoneNo).show();
                                $slider.find(".timeline-milestone-steps[data-step='" + nextMilestoneNo + "']").show();
                            }
                        }
                        if (hideExcess) {
                            var hideStart = 3;
                            if (ctr == 0) {
                                hideStart = 4;
                            }
                            for (var i = ctr + hideStart; i < total; i++) {
                                $slider.find(".timeline-milestone-caption-" + i).hide();
                                $slider.find(".timeline-milestone-steps[data-step='" + i + "']").hide();
                            }
                        }
                    }
                }
            });
          
            //[AJS 01/08] Accessibility Relationship_between_slider_and_content_pane -start
            var initialData = 'timeline-milestone-caption-0-' + valueTimelineMilestoneCaption;
            $(".ui-slider-handle").text("◄►").attr({
                'role': 'slider',
                'aria-valuemin': 0,
                'aria-valuemax': maxValue,
                'aria-valuenow': 0,
                'aria-valuetext': valueTextMilestone,
                'data-analytics-link-name': initialData,
                'data-analytics-content-type': 'timeline'
            });
            //-end

            //creates the dots in the jquery slider.

            var maxMilestoneMobile = 4;
            width = Number($slider.css("width").replace("px", ""));
            updateWidth(width, nodes);
            if (mobileMode) {
                //RST: For Merging
                //$mobileSliderExt.removeClass("hidden");
                $mobileSliderExt.css("left", width);
                if (total > maxMilestoneMobile) {
                    $mobileSliderExt.removeClass("hidden");
                    width = Number($slider.css("width").replace("px", ""));
                    updateWidth(width, maxMilestoneMobile - 1);
                    difference = total - maxMilestoneMobile;
                    endQueue = difference;
                }
                displayMilestones();
                maxValue = Math.floor((maxMilestoneMobile - 1) * stepNo);

                $slider.slider({
                    max: maxValue,
                    value: currentSelection,
                });

                $('.timeline-outer').closest('.floatcontainer').css('margin-top', '');
                $('.timeline-user-fullname hr').css('width', $('.timeline-user-fullname .fullname').width());
            }
            else {
                displayMilestones();
                $mobileSliderExt.addClass("hidden");
            }

            function updateWidth(totalWidth, noOfChild) {
                leftValue = totalWidth / noOfChild;
            }
            function moveSliderItems(currentPercent) {
                $slider.find("span[class^='timeline-milestone-']").each(function (index) {
                    var $sliderChild = $(this)[0];
                    $sliderChild.style.left = (Number($sliderChild.style.left.replace("px", "")) + currentPercent).toString() + "px";
                });
            }

            function displayMilestones() {
                $slider.find("span[class^='timeline-milestone-']").remove();
                for (var x = 0; x <= nodes; x++) {
                    var hide = '';

                    if (isMobile() && x >= 4) {
                        hide = 'display: none;';
                        $slider.append("<span class='timeline-milestone-steps' data-step='" + x + "' style='left:" + x * leftValue + "px;" + hide + "'></span>");
                    } else {
                        $slider.append("<span class='timeline-milestone-steps' data-step='" + x + "' style='left:" + x * leftValue + "px'></span>")
                    }

                    //var n = total - 1;
                    //var percent = 100 / n;

                    //for (var x = 0; x <= n; x++) {
                    //    $(".ui-slider").append("<span class='timeline-milestone-steps' style='left:" + x * percent + "%'></span>")

                    if (x == 0) {
                        //$(".ui-slider").append("<span class='timeline-milestone-caption timeline-milestone-caption-" + x + " active' style='left:" + x * percent + "%'>" + milestone[x].getAttribute("data-milestone") + "</span>");
                        $slider.append("<span class='timeline-milestone-caption timeline-milestone-caption-" + x + " active' style='left:" + x * leftValue + "px'>" + milestone[x].getAttribute("data-milestone") + "</span>");
                    } else {
                        //$(".ui-slider").append("<span class='timeline-milestone-caption timeline-milestone-caption-" + x + "' style='left:" + x * percent + "%'>" + milestone[x].getAttribute("data-milestone") + "</span>");
                        $slider.append("<span class='timeline-milestone-caption timeline-milestone-caption-" + x + "' style='left:" + x * leftValue + "px; " + hide + "'>" + milestone[x].getAttribute("data-milestone") + "</span>");
                    }

                }
                if (isMobile()) {
                    $('.timeline-outer').closest('.floatcontainer').css('margin-top', '');
                    $('.timeline-user-fullname hr').css('width', $('.timeline-user-fullname .fullname').width());
                }
            }
        }


    }
    )
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\richtext.js
/*  version="2" */
if (ComponentRegistry.RichText) {
    $(function () {
        var rtSpan = $('span[scfieldtype="rich text"]');

        rtSpan.children("img").each(function (i, j) {
            if (!$(this).hasClass("img-responsive")) {
                $(this).addClass("img-responsive");
            }
        });
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\event-calendar.js
/* Version = '15' */
if (ComponentRegistry.EventCalendar) {
    $(function () {
        var urlContainsHash = false;
        var hashContainsEvent = false;
        var urlParam = {};
        if (document.location.search)
            urlParam = GetQueryStringKeyValue();
        var eventId;
        //   GetHashValue(window.location.hash);

        if (typeof EventCalendarAPICallFormatGetEventFilters == 'undefined')
            return;
        if (window.location.hash)
            urlContainsHash = true;
        //RST: for Merging
        $calendarPageTitle = $('#block-hero .page-title'); // Bug fix for Bugs #357054 and 357107: Careers - Event Calendar: Fixed the spacing and some functionality
        $calendarPageHeader = $calendarPageTitle.find('h1');
        $calendarPageSubHeader = $calendarPageTitle.find('.header-body');

        function GetHashValue(hashVal) {
            if (!hashVal)
                return false;

            else {
                var splitHash;
                if (hashVal.indexOf(':') != -1) {
                    hashContainsEvent = true;
                    splitHash = hashVal.split(':');
                    splitHash[0] = ConvertHashToDate(splitHash[0]);
                    eventId = splitHash[1];
                    if (isMobile()) {
                        EventCalendar.ShowDayView(new Date(splitHash[0]));
                    }
                    else
                        EventCalendar.ShowWeekView(new Date(splitHash[0]));
                }
                else {
                    splitHash = hashVal;
                    splitHash = ConvertHashToDate(splitHash);
                    if (isMobile()) {
                        EventCalendar.ShowDayView(new Date(splitHash));
                    }
                    else
                        EventCalendar.ShowWeekView(new Date(splitHash));
                }

            }

        }
        function ConvertHashToDate(splitHash) {
            var convertedString;
            splitHash = splitHash.substr(1);
            convertedString = splitHash.substring(0, 3) + ' ' + splitHash.substring(3, 5) + ' ' + splitHash.substring(5, 9);

            return convertedString;
        }
        function UpdateHashValue(selectedDate) {
            var splitSelectedDate = new Array();
            splitSelectedDate = selectedDate.toDateString().split(" ");
            if (splitSelectedDate[2].length == 1) {
                splitSelectedDate[2] = '0' + splitSelectedDate[2];
            }
            var hashVal = splitSelectedDate[1] + splitSelectedDate[2] + splitSelectedDate[3];
            //  var hashVal = "Date=" + selectedDate;
            window.location.hash = hashVal;
            EventCalendar.UpdateUrlOnFilterChange();
        }
        function RemoveHashValue() {
            history.pushState("", document.title, window.location.pathname + window.location.search);
        }
        EventCalendar = {
            mode: 3, //1:mobile, tablet, desktop
            isMonthView: true,
            isWeekView: false,
            isDayView: false,
            currentDate: new Date(),
            currentSunday: new Date(),
            currentCalendarDate: new Date(),
            data_Events: '',
            currentCalendarDate: '', //tracks calendar date setting
            UpdateTimeInfo:
                function (selectedDate) {
                    $('.timeInfo span[data-head-month]').text(months[selectedDate.getMonth()]);
                    $('.timeInfo span[data-head-year]').text(selectedDate.getFullYear());
                },
            UpdateEventDateLabel: function (selectedDate) {
                var _date = months[selectedDate.getMonth()] + ' ' + selectedDate.getDate() + ', ' + selectedDate.getFullYear();

                $('.responsive-calendar-events .headline span.full').text(EventsForLabel + ' ' + _date);

                $('.responsive-calendar-filters .headline .mobile > span').text(_date);
            },
            ShowDayView: function (selectedDate) {
                EventCalendar.isMonthView = false;
                EventCalendar.isWeekView = false;
                EventCalendar.isDayView = true;

                EventCalendar.currentDate = selectedDate;
                if (hashContainsEvent == false)
                    UpdateHashValue(EventCalendar.currentDate);

                if (EventCalendar.isDayView) {
                    $('.responsive-calendar .day-headers').hide();
                    $('.responsive-calendar .controls').hide();
                    $('.responsive-calendar .days').hide();
                    //RST: for merging
                    //$('.responsive-calendar-filters .headline .mobile').show();
                    //$('.responsive-calendar-filters .headline').css('display', 'block');
                    $calendarPageHeader.css('display', 'none'); // Bug fix for Bugs #357054 and 357107: Careers - Event Calendar: Fixed the spacing and some functionality
                    $calendarPageSubHeader.css('display', 'none');
                    $calendarPageTitle.append('<h1 class="headline"> <a href="#"> <span class="acn-icon icon-calendar-arrow-lt"> </span> </a> <span> </span> </h1>');

                    $calendarPageHeaderMonthView = $calendarPageTitle.find('h1.headline');

                    $calendarPageHeaderMonthView.find('a').on("click", function (event) {
                        EventCalendar.ShowMonthView(EventCalendar.currentDate);
                        $calendarPageHeaderMonthView.hide();
                        RemoveHashValue();
                        EventCalendar.UpdateUrlOnFilterChange();
                    });

                    $('.responsive-calendar-events').show();

                    var month = selectedDate.getMonth();
                    var day = selectedDate.getDate();
                    var year = selectedDate.getFullYear();

                    //RST: For Merging
                    //$('.responsive-calendar .headline .mobile > span').text(months[month] + ' ' + day + ', ' + year);
                    $calendarPageHeaderMonthView.find('> span').text(months[month] + ' ' + day + ', ' + year);


                    EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);
                }
            },
            ShowWeekView: function (selectedDate) {
                EventCalendar.isMonthView = false;
                EventCalendar.isWeekView = true;
                EventCalendar.isDayView = false;

                if (hashContainsEvent == false)
                    UpdateHashValue(selectedDate);


                if (EventCalendar.isWeekView) {
                    var selectedDate = selectedDate;
                    var selectedDateSunday = selectedDate.addDays(selectedDate.getDay() * -1);

                    EventCalendar.currentSunday = selectedDateSunday;
                    EventCalendar.currentDate = selectedDate;

                    var template = '<div class="day" style="-webkit-transition: -webkit-transform 0.5s ease 0.28s; transition: -webkit-transform 0.5s ease 0.28s; -webkit-transform: rotateY(0deg);"><a data-day="{DAY}" data-month="{MONTH}" data-year="{YEAR}" analytics-no-content-click="true" data-analytics-content-type="event calendar" data-analytics-link-name="{MONTHAttr}-{DAYAttr}-{YEARAttr}">{DAY}</a></div>';

                    var week = '';
                    for (ctr = 0; ctr < 7; ctr++) {
                        var day = selectedDateSunday.addDays(ctr);
                        var temp = template;

                        if (selectedDate.getTime() == selectedDateSunday.addDays(ctr).getTime()) {
                            temp = '<div class="day selected" style="-webkit-transition: -webkit-transform 0.5s ease 0.28s; transition: -webkit-transform 0.5s ease 0.28s; -webkit-transform: rotateY(0deg);"><a data-day="{DAY}" data-month="{MONTH}" data-year="{YEAR}" analytics-no-content-click="true" data-analytics-content-type="event calendar" data-analytics-link-name="{MONTHAttr}-{DAYAttr}-{YEARAttr}">{DAY}</a></div>';
                        }

                        temp = temp.replace('{DAY}', day.getDate());
                        temp = temp.replace('{MONTH}', day.getMonth() + 1);
                        temp = temp.replace('{YEAR}', day.getFullYear());
                        temp = temp.replace('{DAY}', day.getDate());
                        temp = temp.replace('{DAYAttr}', day.getDate());
                        temp = temp.replace('{MONTHAttr}', day.getMonth() + 1);
                        temp = temp.replace('{YEARAttr}', day.getFullYear());

                        week += temp;
                    }

                    //update week calendar
                    //RST: For Merging
                    //var prev = '<div class="btn prev"><span class="acn-icon icon-calendar-arrow-lt"></div>';
                    //var next = '<div class="btn next"><span class="acn-icon icon-calendar-arrow-rt"></div>';
                    var prev = '<div class="btn prev" data-analytics-content-type="event calendar" data-analytics-link-name="last week" analytics-no-content-click="true"><span class="acn-icon icon-calendar-arrow-lt color-primary"></div>';
                    var next = '<div class="btn next" data-analytics-content-type="event calendar" data-analytics-link-name="next week" analytics-no-content-click="true"><span class="acn-icon icon-calendar-arrow-rt color-primary"></div>';

                    $('.responsive-calendar > .days.week-view').html(prev + '<div class="week">' + week + '</div>' + next);

                    //update controls to add Back To Month button
                    var backToMonthText = $('.pull-left.week-view').attr('title');
                    var _backToMonthViewControl = '<a class="pull-left week-view"><span class="acn-icon icon-back-to-month"></span><span class="text">' + backToMonthText + '</span></a>';
                    $('.controls .week-view').html(_backToMonthViewControl);

                    // Adds attrs to back-to-month btn in week view
                    var backToMonth = $('.pull-left.week-view[title] a');
                    backToMonth.attr('data-analytics-content-type', 'event calendar');
                    backToMonth.attr('data-analytics-link-name', 'back to month');
                    backToMonth.attr('analytics-no-content-click', 'true');

                    $('.controls .week-view').on("click", function () {
                        EventCalendar.ShowMonthView(selectedDate);
                        setTimeout(EventCalendar.SelectDateOnMonthCalendar, 0);
                        EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);
                        RemoveHashValue();
                        EventCalendar.UpdateUrlOnFilterChange();
                    });

                    //update time infor Month and Year to show Selected Day month and Year
                    EventCalendar.UpdateTimeInfo(selectedDate);

                    //update day headers
                    $('.responsive-calendar .day-headers').addClass('week-view');

                    //add event handlers
                    $('.responsive-calendar .days.week-view .day a').on("click", function () {
                        EventCalendar.currentDate = new Date($(this).attr('data-month') + '/' + $(this).attr('data-day') + '/' + $(this).attr('data-year'));

                        //splitSelectedDate = EventCalendar.currentDate.toDateString().split(" ");
                        //var hashVal = "Date=" + splitSelectedDate[1] + splitSelectedDate[2] + splitSelectedDate[3]
                        //window.location.hash = hashVal;
                        UpdateHashValue(EventCalendar.currentDate);
                        hashContainsEvent = false;

                        $('.responsive-calendar .days.week-view .day').removeClass('selected');
                        $(this).parent().addClass('selected');
                        EventCalendar.UpdateUrlOnFilterChange();
                        EventCalendar.UpdateTimeInfo(EventCalendar.currentDate);
                        EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);
                    });

                    $('.responsive-calendar .days.week-view .btn').on("click", function () {
                        if ($(this).hasClass('prev')) {
                            //prev
                            EventCalendar.ShowWeekView(EventCalendar.currentDate.addDays(-7));
                        } else {
                            //next
                            EventCalendar.ShowWeekView(EventCalendar.currentDate.addDays(7));
                        }
                    });

                    EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);

                    //show
                    $('.responsive-calendar > .days.week-view').show();
                    $('.controls .week-view').show();
                    $('.month-view').hide();
                    $('.controls .month-view').hide();


                }
            },
            ShowMonthView: function (selectedDate) {
                EventCalendar.isMonthView = true;
                EventCalendar.isWeekView = false;
                EventCalendar.isDayView = false;

                if (urlContainsHash == false) {
                    //change calendar to syncg with selected date
                    if (EventCalendar.currentCalendarDate.getFullYear() != selectedDate.getFullYear() ||
                        EventCalendar.currentCalendarDate.getMonth() != selectedDate.getMonth() ||
                        EventCalendar.currentCalendarDate.getDate() != selectedDate.getDate()) {

                        //calculate needed month changes, negative or positive
                        var diff = monthDiff(EventCalendar.currentCalendarDate, selectedDate);

                        //change calendar to selected date month
                        if (diff < 0) {
                            for (diff2 = 0; diff2 > diff; diff2--) {
                                $('.responsive-calendar').responsiveCalendar('prev');
                            }
                        } else {
                            for (diff2 = 0; diff2 < diff; diff2++) {
                                $('.responsive-calendar').responsiveCalendar('next');
                            }
                        }
                    }

                }
                EventCalendar.currentCalendarDate = selectedDate; //synched!

                //show it
                if (EventCalendar.mode == 1) {
                    $('.responsive-calendar .day-headers').show();
                    $('.responsive-calendar .controls').show();
                    $('.responsive-calendar .days').show();

                    //RST: for Merging
                    //$('.responsive-calendar .headline .mobile').hide();
                    //$('.responsive-calendar-filters .headline').css('display', 'none');
                    $calendarPageHeaderMonthView.remove(); // Bug fix for Bugs #357054 and 357107: Careers - Event Calendar: Fixed the spacing and some functionality
                    $calendarPageHeader.css('display', 'block');
                    $calendarPageSubHeader.css('display', 'block');

                    $('.responsive-calendar-events').hide();
                }
                else {
                    //remove possible week-view mode classes and controls
                    $('.responsive-calendar .day-headers').removeClass('week-view');
                    $('.controls .week-view').hide();
                    $('.week-view').hide();

                    //show month view
                    $('.month-view').show();
                    $('.controls .month-view').show();
                }
            },
            GetEventsData: function (dateStart, dateEnd, callBack) {
                var call = EventCalendarAPICallFormatGetEvents;

                //get filters
                var _filterLoc = $('.responsive-calendar-filters .filter .state label').attr('data-value').length <= 0 ? 'null' : $('.responsive-calendar-filters .filter .state label').attr('data-value');
                var _filterOrg = $('.responsive-calendar-filters .filter .organization label').attr('data-value').length <= 0 ? 'null' : $('.responsive-calendar-filters .filter .organization label').attr('data-value');
                var _filterType = $('.responsive-calendar-filters .filter .type label').attr('data-value').length <= 0 ? 'null' : $('.responsive-calendar-filters .filter .type label').attr('data-value');

                //multi dates
                call = call.replace('{EventCollectionPathId}', EventCollectionPathId);
                call = call.replace('{EventCollectionLanguage}', acnPage.Language);
                call = call.replace('{dateStart}', dateStart.getFullYear() + '-' + (dateStart.getMonth() + 1) + '-' + dateStart.getDate());
                call = call.replace('{dateEnd}', dateEnd.getFullYear() + '-' + (dateEnd.getMonth() + 1) + '-' + dateEnd.getDate());
                call = call.replace('{filterLocation}', _filterLoc);
                call = call.replace('{filterOrganization}', _filterOrg);
                call = call.replace('{filterType}', _filterType);

                wsCall(call, callBack);
            },
            MarkEventsOnCalendar: function (json) {
                //clear
                $('.responsive-calendar .day').removeClass('active');

                for (ctr = 0; ctr < EventCalendar.data_Events.length; ctr++) {
                    var eventName = EventCalendar.data_Events[ctr].EventName;
                    var _Edate = (new Date(EventCalendar.data_Events[ctr].EventDateTimeEndString.replace(/-/g, "/")));
                    var _Sdate = (new Date(EventCalendar.data_Events[ctr].EventDateTimeStartString.replace(/-/g, "/")));
                    var diffDays = _Edate.getDate() - _Sdate.getDate();
                    var _day = _Sdate.getDate();
                    var _month = _Sdate.getMonth() + 1;

                    if (diffDays > 0) {
                        for (i = 0; i <= diffDays; i++) {
                            var tempDate = _Sdate.addDays(i);
                            _day = tempDate.getDate();
                            _month = tempDate.getMonth() + 1;

                            $('.responsive-calendar .days a[data-month=' + _month + '][data-day=' + _day + ']').parent().addClass('active');
                        }
                    }
                    else {
                        $('.responsive-calendar .days a[data-month=' + _month + '][data-day=' + _day + ']').parent().addClass('active');
                    }
                }
            },
            ShowEventsCallback: function (json) {

                //clear all events
                $('.responsive-calendar-events .event:visible').remove();
                $('.responsive-calendar-events .no-events').hide();

                //update label date
                EventCalendar.UpdateEventDateLabel(EventCalendar.currentDate);

                //get events list
                EventCalendar.data_Events = json;

                // highlight days with event on calendar
                var events = '';
                for (ctr = 0; ctr < EventCalendar.data_Events.length; ctr++) {
                    var _Edate = (new Date(EventCalendar.data_Events[ctr].EventDateTimeEndString.replace(/-/g, "/")));
                    var _Sdate = (new Date(EventCalendar.data_Events[ctr].EventDateTimeStartString.replace(/-/g, "/")));
                    var diffDays = _Edate.getDate() - _Sdate.getDate();
                    var _day = _Sdate.getDate();
                    var _month = _Sdate.getMonth() + 1;

                    if (diffDays > 0) {
                        for (i = 0; i <= diffDays; i++) {
                            var tempDate = _Sdate.addDays(i);
                            events += EventCalendar.showEventOnDay(tempDate, EventCalendar.data_Events[ctr]);
                        }
                    }
                    else {
                        events += EventCalendar.showEventOnDay(_Sdate, EventCalendar.data_Events[ctr]);
                    }
                }
                //populate events
                $('.responsive-calendar-events').append(events);

                //show only necessary Carousel items
                $('.responsive-calendar-events .event:visible').each(
                    function () {
                        // 1/14 Merge Main Release: Changeset 724330 to 728897
                        // Bug # 297605 : Added checking of empty img fields and updated the adding of active class to elements.
                        //var itemcount = $(this).find('.media .item img[src!=null]').length;
                        //$(this).find('.media .item').each(function () {
                        var $media = $(this).find('.media .item');
                        var imgCount = $media.find('img[src!=""]').length;
                        var videoCount = $media.find('.media-container').length;
                        var itemCount = imgCount + videoCount;
                        var firstItem = true;
                        //$this.find('.media-container').length > 0
                        $media.each(function () {
                            $this = $(this);
                            $this.removeClass("active");
                            if ($this.find('img[src!=""]').length > 0 || $this.find('.media-container').length > 0) {
                                $this.css('display', '');

                                //show the navigation dot as well
                                if (itemCount > 1) {
                                    $('.responsive-calendar-events .event:visible .media .carousel-indicators li').eq($(this).index()).show();
                                }
                                if (firstItem) {
                                    $this.addClass("active");
                                }
                                firstItem = false;
                            }
                        });

                        //Bug 285185: Set display none to image if src is null
                        $(this).find('.location .content img[src=""]').css('display', 'none');
                        if ($(this).find(".remind-me").attr('data-show-option') === 'false') {
                            $(this).find(".remind-me").hide();
                        }
                        if ($(this).find(".map-it").attr('data-show-option') === 'false') {
                            $(this).find(".map-it").hide();
                        }
                    }
                );

                //expand first event
                if ($('.responsive-calendar-events .event:visible').length > 0) {
                    var event = $('.responsive-calendar-events .event:visible').eq(0);
                    event.find('>a').removeClass('collapsed');
                    event.find('>a').attr('data-analytics-link-name', 'collapse button');
                    event.find('>a').attr('analytics-no-content-click', 'true');
                    event.find('>div').removeClass('collapsed');
                    event.find('>div').addClass('in');
                    event.find('>div').css('height', 'auto');

                    event.addClass('open');
                } else {
                    //show no event message
                    $('.responsive-calendar-events .no-events').show();
                }

                if (hashContainsEvent == true) {
                    $(".responsive-calendar-events .event").each(function () {
                        var sEvent = $(this);
                        if (sEvent.children('a').children('h2').attr('id') == eventId) {
                            sEvent.find('>a').removeClass('collapsed');
                            sEvent.find('>div').removeClass('collapsed');
                            sEvent.find('>div').addClass('in');
                            sEvent.find('>div').css('height', 'auto');

                            sEvent.addClass('open');
                        }

                        else {
                            sEvent.removeClass('open');
                            sEvent.find('>a').addClass('collapsed');
                            sEvent.find('>div').addClass('collapsed');
                            sEvent.find('>div').removeClass('in');
                        }
                    });
                }

                //add event handler for event open/close
                $('.responsive-calendar-events .event > a > h2').on("click", function () {
                    $(this).parent().parent().toggleClass('open');

                    // Add attr to event calendar link
                    var status = ($('.responsive-calendar-events .event > a').attr('data-analytics-link-name') === 'expand button') ? 'collapse button' : 'expand button';
                    $('.responsive-calendar-events .event > a').attr('data-analytics-link-name', status);
                    $('.responsive-calendar-events .event > a').attr('analytics-no-content-click', true);
                });

                //Bug 212401: Share link is NOT working for careers calendar component.
                //script to set the social likes
                $('.event').each(function () {
                    //Bug 356421: Careers - Event Calendar: Duplicate Share Button Showing and No Values in Share dropdown.
                    if ($(this).parent().hasClass('event-template')) { return; }

                    $(this).find('.event-social-likes').each(function () {
                        $(this).removeClass('event-social-likes');
                        $(this).addClass('social-likes-post social-likes social-likes_single socialSharePopover popover-content');
                    });

                    $(this).find('.social-likes').socialLikes();
                    $(this).find('.social-likes__widget').each(function () {
                        $(this).popover({
                            html: true,
                            placement: 'bottom',
                            container: 'body',
                            content: function () {
                                var htmlContent = $(this).parent().find('.popover-content').html();
                                return htmlContent;
                                //return $('#tooltipPopup').html();
                            }
                        });
                    });
                });

                //mark events on calendar
                EventCalendar.MarkEventsOnCalendar(json);
            },
            showEventOnDay: function (_date, eventParam) {
                var events = '';
                var template = ''
                //show only dates for current date
                if (_date.getMonth() == EventCalendar.currentDate.getMonth() && _date.getDate() == EventCalendar.currentDate.getDate()) {
                    //var template = $('.event-template').html();
                    //Bug #356380: Careers - Event Calendar: Virtual Event Issue: 'Location:' text displays
                    var $temp = $('.event-template');

                    // START SIR #449674: Careers Event Calendar: 'Register' should be hidden when there is no link
                    var $elmRegLink = $temp.find('.register');
                    var regLink = eventParam.RegisterLink;
                    $elmRegLink.removeClass('invisible');
                    if (!regLink && regLink.length == 0) {
                        $elmRegLink.addClass('invisible');
                    }
                    // END SIR #449674

                    //For RMT 7367

                    $temp.find("a[data-href='{RegisterLink}']").attr("href", "javascript:void(0);");
                    $temp.find("a[data-href='{RegisterLink}']").attr("href", "javascript:void(0);");
                    $temp.find("img[data-src='{LocationImage}']").attr("src", "");

                    if (regLink) {
                        $temp.find("a[data-href='{RegisterLink}']").attr("href", regLink);
                    }

                    if (eventParam.LocationGoogleMapUrl) {
                        $temp.find("a[data-href='{LocationGoogleMapUrl}']").attr("href", eventParam.LocationGoogleMapUrl)
                    }

                    if (eventParam.LocationImage) {
                        $temp.find("img[data-src='{LocationImage}']").attr("src", eventParam.LocationImage);
                    }

                    var imageArray = [null, eventParam.Image1, eventParam.Image2, eventParam.Image3];
                    for (imageNum = 0; imageNum < imageArray.length; imageNum++) {
                        if (imageArray[imageNum]) {
                            $temp.find("img[data-src='{image" + imageNum + "}']").attr("src", imageArray[imageNum]);
                        }
                        else {
                            $temp.find("img[data-src='{image" + imageNum + "}']").attr("src", "");
                        }
                    }

                    template = $temp.html();

                    var eventLocation = $temp.find('#EventLocation');
                    var eventAddress = eventParam.EventLocationAddress;
                    if (!eventAddress) {
                        eventLocation.addClass('invisible');
                    }
                    else {
                        eventLocation.removeClass('invisible');
                    }
                    template = $temp.html();
                    var _time = (_date.getHours() != 0) ? ((_date.getHours() > 12) ? (_date.getHours() - 12).toString() : _date.getHours().toString()) : ((_date.getHours() + 12).toString());
                    _time += ':';
                    _time += ('0' + _date.getMinutes().toString()).slice(-2);
                    _time += _date.getHours() >= 12 ? 'pm' : 'am';

                    //RST: For Merging
                    //Bug 297605 : [Event Collection][NA][NA] Cannot add video.
                    var video1 = eventParam.Video1;
                    var video2 = eventParam.Video2;
                    var video3 = eventParam.Video3;

                    template = replaceAll('{EventId}', eventParam.Id, template);
                    template = replaceAll('{date}', _time, template);
                    template = replaceAll('{EventName}', eventParam.EventName, template);
                    template = replaceAll('{ctr}', ctr, template);
                    template = template.replace('{shares}', 555);

                    // Add attr to event calendar link
                    template = replaceAll('{linkName}', 'expand button', template);

                    //RST:For Merging
                    if (!$.isEmptyObject(video1)) {
                        template = template.replace('{Video1}', EventCalendar.UpdateEventVideo(video1))
                    }
                    if (!$.isEmptyObject(video2)) {
                        template = template.replace('{Video2}', EventCalendar.UpdateEventVideo(video2))
                    }
                    if (!$.isEmptyObject(video3)) {
                        template = template.replace('{Video3}', EventCalendar.UpdateEventVideo(video3))
                    }
                    template = template.replace('{EventDescription}', eventParam.EventDescription);
                    template = template.replace('{EventLocation}', eventParam.EventLocation);
                    //template = template.replace('{EventLocationAddress}', eventParam.EventLocationAddress);
                    template = template.replace('{EventLocationAddress}', eventAddress);
                    template = replaceAll('{EventCalendarAPICallFormatICal}', EventCalendarAPICallFormatICal, template);
                    template = replaceAll('{eventCollectionId}', EventCollectionPathId, template);
                    template = replaceAll('{eventId}', eventParam.Id, template);
                    template = replaceAll('{eventLanguage}', acnPage.Language, template);
                    template = replaceAll('{ShowMap}', eventParam.ShowMap, template);
                    template = replaceAll('{ShowRemindMe}', eventParam.ShowRemind, template);

                    //events += template;
                }
                return template;
            },
            ShowEvents: function (dateStart, dateEnd) {
                dateStart = typeof dateStart == 'undefined' ? EventCalendar.currentDate : dateStart;
                dateEnd = typeof dateEnd == 'undefined' ? EventCalendar.currentDate : dateEnd;

                //get date ranges
                if (EventCalendar.isMonthView || EventCalendar.isWeekView || EventCalendar.isDayView) {
                    dateStart = new Date(dateStart.getFullYear() + '/' + (dateStart.getMonth() + 1) + '/1');
                    dateEnd = new Date(dateStart.getFullYear() + '/' + (dateStart.getMonth() + 1) + '/' + getLastDayOfMonth(dateStart.getMonth(), dateStart.getFullYear()).getDate());
                }
                EventCalendar.GetEventsData(dateStart, dateEnd, EventCalendar.ShowEventsCallback);
            },
            ShowFiltersCallback: function (json) {
                var itemTemplate = '<li><a href="#" title="{name}">{name}</a></li>';
                var defaultTemplate = '<li id="defaultValue_{name}"><a href="#" title="{name}">{name}</a></li>';

                //Location Filter
                filter = $('.responsive-calendar-filters .filter .state ul');
                filter.html('');
                if (json.EventLocations.length > 0) {
                    filter.append(replaceAll('{name}', selectAll, defaultTemplate))
                }
                for (ctr = 0; ctr < json.EventLocations.length; ctr++) {
                    if (json.EventLocations[ctr] != '') {
                        filter.append(replaceAll('{name}', json.EventLocations[ctr], itemTemplate));
                    }
                }

                //Organization Filter
                filter = $('.responsive-calendar-filters .filter .organization ul');
                filter.html('');
                if (json.EventOrganizations.length > 0) {
                    filter.append(replaceAll('{name}', selectAll, defaultTemplate))
                }
                for (ctr = 0; ctr < json.EventOrganizations.length; ctr++) {
                    if (json.EventOrganizations[ctr] != '') {
                        filter.append(replaceAll('{name}', json.EventOrganizations[ctr], itemTemplate));
                    }
                }

                //Type Filter
                filter = $('.responsive-calendar-filters .filter .type ul');
                filter.html('');
                if (json.EventTypes.length) {
                    filter.append(replaceAll('{name}', selectAll, defaultTemplate))
                }
                for (ctr = 0; ctr < json.EventTypes.length; ctr++) {
                    if (json.EventTypes[ctr] != '') {
                        filter.append(replaceAll('{name}', json.EventTypes[ctr], itemTemplate));
                    }
                }

                var loc = EventCalendar.CheckIfLocationIsValid(),
                    org = EventCalendar.CheckIfOrgIsValid(),
                    event = EventCalendar.CheckIfEventIsValid();
                if (loc && loc != selectAll.toLowerCase()) {
                    $('.responsive-calendar-filters .filter .state label').attr("data-value", loc);
                    $('.responsive-calendar-filters .filter .state label').text(loc);
                }
                if (org && org != selectAll.toLowerCase()) {
                    $('.responsive-calendar-filters .filter .organization label').attr("data-value", org);
                    $('.responsive-calendar-filters .filter .organization label').text(org);
                }
                if (event && event != selectAll.toLowerCase()) {
                    $('.responsive-calendar-filters .filter .type label').attr("data-value", event);
                    $('.responsive-calendar-filters .filter .type label').text(event);
                }

                EventCalendar.UpdateUrlOnFilterChange();
                EventCalendar.FilterEvents();
                //bind event
                $('.responsive-calendar-filters .filter ul li').on("click", function (event) {
                    event.preventDefault();

                    //change display
                    var selected = $(this).text();
                    var label = $(this).parent().parent().find('label');

                    label.text(selected);
                    if ($(this)[0].id.indexOf('defaultValue') == -1) {
                        label.attr('data-value', selected);
                    } else {
                        label.attr('data-value', '');
                    }

                    //change displayed events
                    EventCalendar.FilterEvents();
                    EventCalendar.UpdateUrlOnFilterChange();
                });
            },
            FilterEvents: function () {
                EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);
            },
            ShowFilters: function () {
                var call = EventCalendarAPICallFormatGetEventFilters.replace('{EventCollectionPathId}', EventCollectionPathId);
                call = call.replace("{EventCollectionLanguage}", acnPage.Language);
                wsCall(call, EventCalendar.ShowFiltersCallback);
            },
            ChangeMode: function () {
                if (window.outerWidth < 768) {
                    EventCalendar.mode = 1;
                } else if (window.outerWidth < 1000) {
                    EventCalendar.mode = 2;
                } else {
                    EventCalendar.mode = 3;
                }
            },
            SelectDateOnMonthCalendar: function (date) {
                date = typeof date != 'undefined' ? date : EventCalendar.currentDate;

                $('.responsive-calendar .days .day').removeClass('selected');
                $('.responsive-calendar .days .day a[data-month=' + (date.getMonth() + 1).toString() + '][data-day=' + date.getDate().toString() + ']').parent().addClass('selected');
            },
            UpdateEventDetails: function () {
                //[2/24/15] Merge 2/5 from Main Release Branch
                var description = ""
                //Bug 357277 : Careers - Event Calendar: Location should be displayed 1st then the description 2nd.
                if (EventCalendar.mode == 1) {
                    $('div[id^="collapse"] > .event-details').each(function () {
                        $this = $(this);
                        description = $this.find('.description');
                        $this.find('#EventLocation').after(description);
                        description.find('label').addClass('hidden');
                    });
                }
                //[2/24/15] Merge 2/5 from Main Release Branch
                //SIR# 373122 - Careers - Event Calendar: Alignment of location in calendar is incorrect using tablet.
                else if (EventCalendar.mode == 2) {
                    $('div[id^="collapse"] > .event-details').each(function (index) {
                        $this = $(this);
                        description = $this.find('.description');
                        $this.find(($('.media').eq(index))).after($(description))
                        description.find('label').removeClass('hidden');
                    });
                }
            },
            //RST: For Merging
            UpdateEventVideo: function (video) {
                //Bug 297605 : [Event Collection][NA][NA] Cannot add video.
                var eventVideoMarkUp = "{Video}";
                if (video && video.PlayerId && video.MediaId) {
                    video.MediaPlayerNetwork = "//assets.delvenetworks.com/player/loader.swf";
                    var mediaPlayerTemplate = "<div class='media-container'>" +
                        "<span style='" + video.PlayerStyle + "' class='' data-orig-width='" + video.Width + "'  data-orig-height='" + video.Height + "'>" +
                        "<object type='application/x-shockwave-flash'style='" + video.PlayerStyle + "' " +
                        "id='" + video.PlayerId + "'" +
                        "name= '" + video.PlayerId + "'" +
                        "data='" + video.MediaPlayerNetwork + "'" +
                        "data-orig-width='" + video.Width + "'" +
                        "width='" + video.Width + "px'" +
                        "height='" + video.Height + "px'>" +
                        "<param name='wmode' value='" + video.WMode + "'>" +
                        "<param name='allowScriptAccess' value='sameDomain'>" +
                        "<param name='allowFullScreen' value='true'>" +
                        "<param name='flashVars' value='playerForm=" + video.PlayerForm + "&amp;mediaId=" + video.MediaId + "'>" +
                        "</object>" +
                        "</span></div>";
                    eventVideoMarkUp = mediaPlayerTemplate;
                }
                return eventVideoMarkUp;
            },
            UpdateCurrentUrl: function (month, year, loc, org, event) {
                var url = document.location.href;
                if (window.location.hash) {
                    month = "";
                }
                if (url.indexOf("?") > -1)
                    url = EventCalendar.RemoveFilterParameters(url);
                else if (url.indexOf("#") > -1)
                    url = url.substring(0, url.indexOf("#"));
                if (loc) {
                    if (url.indexOf("?") > -1) {
                        url += "&loc=" + loc;
                    } else {
                        url += "?loc=" + loc;
                    }
                }
                if (org) {
                    if (url.indexOf("?") > -1) {
                        url += "&org=" + org;
                    } else {
                        url += "?org=" + org;
                    }
                }
                if (event) {
                    if (url.indexOf("?") > -1) {
                        url += "&event=" + event;
                    } else {
                        url += "?event=" + event;
                    }
                }
                if (month) {
                    if (url.indexOf("?") > -1) {
                        url += "&month=" + month + year;
                    } else {
                        url += "?month=" + month + year;
                    }
                }
                else {
                    url += window.location.hash;
                }
                url = url.replace(/ /g, "+");
                url = url.replace("&#", "#");
                url = url.replace("?&", "?");
                url = url.replace("?#", "#");
                url = url.replace(/\&+/g, "&");
                return url;
            },
            UpdateUrlOnFilterChange: function () {
                var monthFilter = $('.timeInfo span[data-head-month]').text(),
                    yearFilter = $('.timeInfo span[data-head-year]').text();
                locFilter = $('.responsive-calendar-filters .filter .state label').attr("data-value"),
                    orgFilter = $('.responsive-calendar-filters .filter .organization label').attr("data-value"),
                    eventFilter = $('.responsive-calendar-filters .filter .type label').attr("data-value"),
                    newUrl = EventCalendar.UpdateCurrentUrl(monthFilter, yearFilter, locFilter, orgFilter, eventFilter);

                window.history.pushState({ path: newUrl }, "", newUrl);
            },
            RemoveFilterParameters: function (url) {
                var urlSub = url.substr(url.indexOf("?"));
                var newUrl = url.substring(0, url.indexOf("?"));
                if (urlSub.indexOf("loc") > -1) {
                    var locString = urlSub.substr(urlSub.indexOf("loc"));
                    var stringtoRemove;
                    if (locString.indexOf("&") > -1) {
                        stringtoRemove = locString.substring(locString.indexOf("loc"), locString.indexOf("&") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (locString.indexOf(";") > -1) {
                        stringtoRemove = locString.substring(locString.indexOf("loc"), locString.indexOf(";") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (locString.indexOf("#") > -1) {
                        stringtoRemove = locString.substring(locString.indexOf("loc"), locString.indexOf("#"));
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else {
                        urlSub = urlSub.replace(locString, "");
                    }
                }
                if (urlSub.indexOf("org") > -1) {
                    var orgString = urlSub.substr(urlSub.indexOf("org"));
                    var stringtoRemove;
                    if (orgString.indexOf("&") > -1) {
                        stringtoRemove = orgString.substring(orgString.indexOf("org"), orgString.indexOf("&") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (orgString.indexOf(";") > -1) {
                        stringtoRemove = orgString.substring(orgString.indexOf("org"), orgString.indexOf(";") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (orgString.indexOf("#") > -1) {
                        stringtoRemove = orgString.substring(orgString.indexOf("org"), orgString.indexOf("#"));
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else {
                        urlSub = urlSub.replace(orgString, "");
                    }
                }
                if (urlSub.indexOf("event") > -1) {
                    var eventString = urlSub.substr(urlSub.indexOf("event"));
                    var stringtoRemove;
                    if (eventString.indexOf("&") > -1) {
                        stringtoRemove = eventString.substring(eventString.indexOf("event"), eventString.indexOf("&") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (eventString.indexOf(";") > -1) {
                        stringtoRemove = eventString.substring(eventString.indexOf("event"), eventString.indexOf(";") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (eventString.indexOf("#") > -1) {
                        stringtoRemove = eventString.substring(eventString.indexOf("event"), eventString.indexOf("#"));
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else {
                        urlSub = urlSub.replace(eventString, "");
                    }
                }
                if (urlSub.indexOf("month") > -1) {
                    var monthString = urlSub.substr(urlSub.indexOf("month"));
                    var stringtoRemove;
                    if (monthString.indexOf("&") > -1) {
                        stringtoRemove = monthString.substring(monthString.indexOf("month"), monthString.indexOf("&") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (monthString.indexOf(";") > -1) {
                        stringtoRemove = monthString.substring(monthString.indexOf("month"), monthString.indexOf(";") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (monthString.indexOf("#") > -1) {
                        stringtoRemove = monthString.substring(monthString.indexOf("month"), monthString.indexOf("#"));
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else {
                        urlSub = urlSub.replace(monthString, "");
                    }
                }
                if (urlSub.indexOf("#") > -1) {
                    var hashString = urlSub.substr(urlSub.indexOf("#"));
                    var stringtoRemove;
                    if (hashString.indexOf("&") > -1) {
                        stringtoRemove = hashString.substring(hashString.indexOf("#"), hashString.indexOf("&") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else if (hashString.indexOf(";") > -1) {
                        stringtoRemove = hashString.substring(hashString.indexOf("#"), hashString.indexOf(";") + 1);
                        urlSub = urlSub.replace(stringtoRemove, "");
                    } else {
                        urlSub = urlSub.replace(hashString, "");
                    }
                }
                urlSub = urlSub.replace("?&", "?");
                newUrl = newUrl + urlSub;
                return newUrl;
            },
            CheckIfLocationIsValid: function () {
                var locArrLowerCase = [],
                    locArr = [];
                if (urlParam.loc) {
                    var loc = urlParam.loc;
                    loc = loc.toLowerCase();
                    $('.responsive-calendar-filters .filter .state .dropdown-menu li a').each(function () {
                        locArrLowerCase.push($(this).text().toLowerCase());
                        locArr.push($(this).text());
                    });
                    if (locArrLowerCase.indexOf(loc) > -1) {
                        return locArr[locArrLowerCase.indexOf(loc)];
                    }
                    else {
                        return null;
                    }
                }
                return null;
            },
            CheckIfOrgIsValid: function () {
                var orgArrLowerCase = [],
                    orgArr = [];
                if (urlParam.org) {
                    var org = urlParam.org;
                    org = org.toLowerCase();
                    $('.responsive-calendar-filters .filter .organization .dropdown-menu li a').each(function () {
                        orgArrLowerCase.push($(this).text().toLowerCase());
                        orgArr.push($(this).text());
                    });
                    if (orgArrLowerCase.indexOf(org) > -1) {
                        return orgArr[orgArrLowerCase.indexOf(org)];
                    }
                    else {
                        return null;
                    }
                }
                return null;
            },
            CheckIfEventIsValid: function () {
                var eventArrLowerCase = [],
                    eventArr = [];
                if (urlParam.event) {
                    var event = urlParam.event;
                    event = event.toLowerCase();
                    $('.responsive-calendar-filters .filter .type .dropdown-menu li a').each(function () {
                        eventArrLowerCase.push($(this).text().toLowerCase());
                        eventArr.push($(this).text());
                    });
                    if (eventArrLowerCase.indexOf(event) > -1) {
                        return eventArr[eventArrLowerCase.indexOf(event)];
                    }
                    else {
                        return null;
                    }
                }
                return null;
            },
            SetCurrentDateFromUrl: function (date) {
                if (urlParam.month) {
                    var monthYear = urlParam.month,
                        year;
                    monthYearArr = monthYear.split(/(\d+)/),
                        month = monthYearArr[0].toLowerCase(),
                        year = monthYearArr[1];
                    for (i = 0; i < 12; i++) {
                        if (month == months[i].toLowerCase()) {
                            date.setMonth(i);
                            date.setFullYear(year);
                            return date;
                        }
                    }
                }
                return date;
            },
            UpdateShareEventDataUrl: function () {
                jQuery(".responsive-calendar-events .event-details .event-social-likes").attr("data-url", window.location.href);
            },
            AddAnalyticsLinkTrackingAttribute: function () {
                var eventCalendar = $('.module-event-calendar');
                var filterBtnGrp = eventCalendar.find('.event-calendar-filter .btn-group');

                if (eventCalendar) {
                    $('.ui-container').attr('data-analytics-template-zone', $('.ui-container').attr('id'));

                    // Adds attrs to event filters
                    filterBtnGrp.attr('data-analytics-link-name', 'toggle');
                    filterBtnGrp.attr('analytics-no-content-click', 'true');
                    filterBtnGrp.attr('data-analytics-content-type', 'event calendar');
                    filterBtnGrp.on('click', function (event) {
                        var state = $('.state .dropdown-menu li a');
                        var organization = $('.organization .dropdown-menu li a');
                        var type = $('.type .dropdown-menu li a');

                        filterBtnGrp.find('.dropdown-menu li a').attr('data-analytics-content-type', 'event calendar');
                        state.attr('data-analytics-link-name', 'filter state/city/province');
                        state.attr('analytics-no-content-click', 'true');
                        organization.attr('data-analytics-link-name', 'filter organization/university');
                        organization.attr('analytics-no-content-click', 'true');
                        type.attr('data-analytics-link-name', 'filter event type');
                        type.attr('analytics-no-content-click', 'true');
                    });

                    // Adds attrs to calendar dates in month view
                    setTimeout(function () {
                        var date = $('.responsive-calendar .month-view .day a');
                        for (var i = 0; i < date.length; i++) {
                            date[i].setAttribute('data-analytics-link-name', date[i].getAttribute('data-month') + '-' + date[i].getAttribute('data-day') + '-' + date[i].getAttribute('data-year'));
                            date[i].setAttribute('analytics-no-content-click', true);
                        }
                        date.attr('data-analytics-content-type', 'event calendar');
                    }, 1000);
                }
            },
            Init: function () {
                //RST: for Merging
                //add event handler for day view -- back to month view link (mobile)
                // Bug fix for Bugs #357054 and 357107: Careers - Event Calendar: Fixed the spacing and some functionality
                // moved to ShowDayView function
                //$('.responsive-calendar-filters .headline .mobile a').on("click", function (event) {
                // EventCalendar.ShowMonthView(EventCalendar.currentDate);
                // $('.responsive-calendar-filters .headline .mobile').hide();
                //});

                //change mode size depending on viewport size
                $(window).on("resize", function () {
                    EventCalendar.ChangeMode();
                    EventCalendar.UpdateEventDetails();
                });

                //add event handler for month view prev/next buttons
                $('.responsive-calendar .controls a.month-view').on("click", function () {
                    var direction = $(this).attr('data-go');

                    if (direction == 'prev') {
                        EventCalendar.currentDate = EventCalendar.currentDate.addMonths(-1);
                    } else {
                        EventCalendar.currentDate = EventCalendar.currentDate.addMonths(1);
                    }

                    EventCalendar.currentCalendarDate = EventCalendar.currentDate; //update calendar date tracker
                    EventCalendar.ShowEvents(EventCalendar.currentDate, EventCalendar.currentDate);
                    EventCalendar.UpdateUrlOnFilterChange();
                });

                //show filters
                EventCalendar.ShowFilters();

                //Update position location and description event details if viewed in mobile

                EventCalendar.UpdateEventDetails();
                EventCalendar.UpdateShareEventDataUrl();
                EventCalendar.AddAnalyticsLinkTrackingAttribute();
            }
        }

        if (urlContainsHash) {
            var hashVal = window.location.hash;

            splitHash = hashVal.split(':');
            splitHash[0] = ConvertHashToDate(splitHash[0]);
            splitHash[0] = '#' + splitHash[0];
            splitHash[0] = splitHash[0].replace(/\s+/g, '');
            var hashDate = new Date(ConvertHashToDate(splitHash[0]));
            EventCalendar.currentDate = EventCalendar.SetCurrentDateFromUrl(hashDate);
        }
        else {
            EventCalendar.currentDate = EventCalendar.SetCurrentDateFromUrl(new Date());
        }
        EventCalendar.currentSunday = GetWeekSundayDate(EventCalendar.currentDate);
        EventCalendar.currentCalendarDate = EventCalendar.currentDate;

        $(".responsive-calendar").responsiveCalendar({
            time: (EventCalendar.currentDate).getFullYear().toString() + '-' + ((EventCalendar.currentDate).getMonth() + 1).toString(),
            startFromSunday: true,
            monthChangeAnimation: false,
            allRows: false,
            onDayClick: function (event) {
                if (EventCalendar.mode == 1) {
                    EventCalendar.ShowDayView(new Date($(this).attr('data-month') + '/' + $(this).attr('data-day') + '/' + $(this).attr('data-year')));
                } else {
                    EventCalendar.ShowWeekView(new Date($(this).attr('data-month') + '/' + $(this).attr('data-day') + '/' + $(this).attr('data-year')));
                }
            },
            onInit: function () {
                $('.responsive-calendar .week-view').html('');
                setTimeout(EventCalendar.SelectDateOnMonthCalendar, 0);
                //setTimeout(EventCalendar.ShowEvents, 0);
            }
            , onMonthChange: function (events) {
                setTimeout(EventCalendar.SelectDateOnMonthCalendar, 0);
                setTimeout(EventCalendar.ShowEvents, 0);
            }
        });
        GetHashValue(window.location.hash);
        EventCalendar.ChangeMode();
        EventCalendar.Init();
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\event-calendar-smartbyte.js
/* Version = '2' */
if (ComponentRegistry.EventCalendarSmartByte) {
    $(function () {
        var date = new Date();

        $('#eventSmartByte .calendar .day').text(date.getDate());
        $('#eventSmartByte .calendar .month').text(months[date.getMonth()]);

        // Adds data-analytics-content-type to clickable elements
        setTimeout(function () {
            var careersPackery = $('#careers_packery').find('.packery-component .module-article');
            for (var i = 1; i < careersPackery.length; i++) {
                if ($(careersPackery[i])[0].id === 'eventSmartByte') {
                    var tilePosition = i;
                }
            }

            var eventSmartByte = $('#careers_packery').find('.packery-component .module-article #eventSmartByte');
            var contentType = eventSmartByte.find('h3 > a').attr('data-analytics-link-name') + '~' + tilePosition;
            eventSmartByte.find('h3 > a').attr('data-analytics-content-type', contentType);
            eventSmartByte.find('h4 > a').attr('data-analytics-content-type', contentType);
        }, 1000);
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\event-list.js
/* Version 24 */
if (ComponentRegistry.EventList) {
    $(function () {
        var EventCalendarAPICallGetRecentEvents = "/api/EventCalendar/GetEvents/{eventCollectionId}/{eventCollectionLanguage}/{dateStart}/{dateEnd}/{filterLocation}/{filterOrganization}/{filterType}";
        var EventCalendarAPICallFormatGetEventFilters = "/api/EventCalendar/GetEventFilters/{EventCollectionPathId}/{EventCollectionLanguage}";
        var EventCollectionPathId = $(".events-list-module").attr("data-event-collection-id");
        var EventMaxCount = $(".events-list-module").attr("data-event-max-count");
        var EventMinCount = $(".events-list-module").attr("data-event-min-count");
        var EventTileColors = $(".events-list-module").attr("data-bgcolors");
        var ViewMoreText = $(".events-list-module").attr("data-event-view-more-text");
        var ViewMoreLink = $(".events-list-module").attr("data-event-view-more-link");
        var ViewMoreTargetType = $(".events-list-module").attr("data-event-view-more-target");
        var container = $('.ui-container');
        var dropdownMenu = $('ul.dropdown-menu');
        var dropdownMenuToggle = $('.dropdown-toggle');

        EventList = {
            ShowFiltersCallback: function (json) {
                if (json !== null && json !== undefined) {
                    var defaultTemplate = '<li id="defaultValue_{defaultId}" aria-label="{name}" aria-selected="false" role="option" tabindex="0" aria-setsize="{ariasize}" aria-posinset="1"><a tabindex="0" aria-hidden="true" id = "{default}" href="#" data-linktype="calendar filter" data-linkaction="{name}" data-analytics-link-name="{name}" data-analytics-content-type="calendar filter">{name}</a></li>';
                    var itemTemplate = '<li id="event_list_{templateId}" aria-label="{name}" aria-selected="false" role="option" tabindex="0" aria-setsize="{ariasize}" aria-posinset="{posinset}"><a tabindex="0" aria-hidden="true" href="#" data-linktype="calendar filter" data-linkaction="{name}" data-analytics-link-name="{name}" data-analytics-content-type="calendar filter">{name}</a></li>';
                    var selectAll = "Select All";
                    var filterCategory = "";
                    var tempItemTemplate = itemTemplate;
                    var tempItemTemplateReplaced = "";

                    // Filter - Locations
                    if (typeof json.EventLocations !== 'undefined' && json.EventLocations !== null) {
                        var eventLocationFinalLength = json.EventLocations.length + 1;
                        var eventLocationTemplate = tempItemTemplate.replace('{ariasize}', eventLocationFinalLength);
                        var tempDefaultTemplateLoc = defaultTemplate;
                        filterCategory = $('.responsive-calendar-filters .filter .state ul');
                        tempDefaultTemplateLoc = tempDefaultTemplateLoc.replace('{defaultId}', "Select_All_defaultLoc").replace('{default}', "defaultLoc").replace('{ariasize}', eventLocationFinalLength);
                        filterCategory.append(replaceAll('{name}', selectAll.toLowerCase(), tempDefaultTemplateLoc));

                        for (ctr = 0; ctr < json.EventLocations.length; ctr++) {
                            tempItemTemplateReplaced = eventLocationTemplate.replace('{templateId}', "location_" + json.EventLocations[ctr].replace(/ +/g, "_")).replace('{posinset}', ctr + 2);
                            filterCategory.append(replaceAll('{name}', json.EventLocations[ctr], tempItemTemplateReplaced));
                        }
                    }

                    // Filter - Organizations
                    if (typeof json.EventOrganizations !== 'undefined' && json.EventOrganizations !== null) {
                        var EventOrganizationFinalLength = json.EventOrganizations.length + 1;
                        var eventOrganizationsTemplate = tempItemTemplate.replace('{ariasize}', EventOrganizationFinalLength);
                        var tempDefaultTemplateOrg = defaultTemplate;
                        filterCategory = $('.responsive-calendar-filters .filter .organization ul');
                        tempDefaultTemplateOrg = tempDefaultTemplateOrg.replace('{defaultId}', "Select_All_defaultOrg").replace('{default}', "defaultOrg").replace('{ariasize}', EventOrganizationFinalLength);
                        filterCategory.append(replaceAll('{name}', selectAll.toLowerCase(), tempDefaultTemplateOrg));

                        for (ctr = 0; ctr < json.EventOrganizations.length; ctr++) {
                            tempItemTemplateReplaced = eventOrganizationsTemplate.replace('{templateId}', "organization" + json.EventOrganizations[ctr].replace(/ +/g, "_")).replace('{posinset}', ctr + 2);
                            filterCategory.append(replaceAll('{name}', json.EventOrganizations[ctr], tempItemTemplateReplaced));
                        }
                    }

                    // Filter - Types
                    if (typeof json.EventTypes !== 'undefined' && json.EventTypes !== null) {
                        var eventTypesFinalLength = json.EventTypes.length + 1;
                        var eventTypesTemplate = tempItemTemplate.replace('{ariasize}', json.EventTypes.length);
                        var tempDefaultTemplateCat = defaultTemplate;
                        filterCategory = $('.responsive-calendar-filters .filter .type ul');
                        tempDefaultTemplateCat = tempDefaultTemplateCat.replace('{defaultId}', "Select_All_defaultCat").replace('{default}', "defaultCat").replace('{ariasize}', eventTypesFinalLength);
                        filterCategory.append(replaceAll('{name}', selectAll.toLowerCase(), tempDefaultTemplateCat));

                        for (ctr = 0; ctr < json.EventTypes.length; ctr++) {
                            tempItemTemplateReplaced = eventTypesTemplate.replace('{templateId}', "type_" + json.EventTypes[ctr].replace(/ +/g, "_")).replace('{posinset}', ctr + 2);
                            filterCategory.append(replaceAll('{name}', json.EventTypes[ctr], tempItemTemplateReplaced));
                        }
                    }

                    // Bind Click Event
                    $('.responsive-calendar-filters .filter ul li').on("click", function (event) {
                        event.preventDefault();

                        var selected = $(this).text();
                        var label = $(this).parent().parent().find('.corporate-black2.filter-value');

                        label.text(selected);
                        if ($(this)[0].id.indexOf('defaultValue') === -1) {
                            label.attr('data-value', selected);
                        } else {
                            label.attr('data-value', '');
                        }

                        //change displayed events
                        EventList.FilterEvents();
                    });

                }
            },
            ShowEventsCallback: function (json) {
                $(".events-list-module .event-container").remove();
                //Remove No Events in view
                $(".noevents").css("display", "none");
                // Sort Event by Date ascending
                if (typeof json !== 'undefined' && json !== null && json.length > 0) {
                    json = json.sort(function (a, b) {
                        return new Date(a.EventDateTimeStart) - new Date(b.EventDateTimeStart)
                    })
                }

                if (json.length >= EventMinCount) {
                    var maxDisplay = 0;
                    var isViewMoreVisible = false;
                    var defaultTemplate = "<a href='{eventLink}' {eventTarget} class='event-container displayBlock color-container bg-color-{eventColor}' data-linktype='engagement' data-linkaction='{eventAction}' data-analytics-link-name='{eventNameAttr}' data-analytics-content-type='engagement'><div class='row'>" +
                        "<div class='vertical-align event-date'><h2 class='header2 date ucase'>{eventDate}</h2></div>" +
                        "<div class='vertical-align event-desc'>" +
                        "<p class='event-name rotis'>{eventName}<span class='event-desc2'>{eventDescription}</span></p>" +
                        "<p class='ucase font-bold event-loc rotis'>{eventLocation}</p>" +
                        "</div><div class='event-arrowlink vertical-align'><span class='icon-arrowrightarrow align-right'></span></div></div></a>"
                    var viewMoreTemplate = "<a{viewMoreLink} {targetType} class='event-container displayBlock viewmore color-container' data-linktype='engagement' data-linkaction='{viewMoreAction}' style='background-color: #6788bd' data-analytics-link-name='{viewMoreActionAttr}' data-analytics-content-type='engagement'><div class='row'>" +
                        "<h3 class='viewmore ucase'>{viewMoreText}</h3><span class='acn-icon icon-jump-links-arrow-down'></span></div></a>";
                    var headerTitle = $('.events-list-module .subheader1').text().toLowerCase();
                    var colors = [];
                    var tileColor;

                    if (json.length > EventMaxCount) {
                        maxDisplay = EventMaxCount;
                        isViewMoreVisible = true;
                    }
                    else {
                        maxDisplay = json.length;
                        isViewMoreVisible = false;
                    }

                    if (EventTileColors != null && EventTileColors != "") {
                        colors = EventTileColors.split("|");
                    }

                    for (ctr = 0; ctr < maxDisplay; ctr++) {
                        var eventTemplate = defaultTemplate;

                        if (colors[ctr] != undefined && colors[ctr] != null) {
                            tileColor = colors[ctr];
                        }
                        else {
                            tileColor = "";
                        }

                        eventTemplate = eventTemplate.replace("{eventDate}", EventList.FormatDate(json[ctr].EventDateTimeStart));
                        eventTemplate = eventTemplate.replace("{eventName}", json[ctr].EventName);
                        eventTemplate = eventTemplate.replace("{eventDescription}", json[ctr].EventName !== "" && json[ctr].EventCareersDescription !== "" ? (" - " + json[ctr].EventCareersDescription) : json[ctr].EventCareersDescription);
                        eventTemplate = eventTemplate.replace("{eventLocation}", json[ctr].EventLocation);
                        eventTemplate = eventTemplate.replace("{eventColor}", tileColor);
                        eventTemplate = eventTemplate.replace("{eventLink}", ViewMoreLink + ((ViewMoreLink != "") ? "?src=SOMS#" + EventList.EventLinkParamFormatDate(json[ctr].EventDateTimeStart) : "#"));
                        eventTemplate = eventTemplate.replace("{eventTarget}", ViewMoreTargetType);
                        eventTemplate = eventTemplate.replace("{headerText}", headerTitle);
                        eventTemplate = eventTemplate.replace("{eventAction}", json[ctr].EventName.toLowerCase());
                        eventTemplate = eventTemplate.replace("{eventNameAttr}", json[ctr].EventName);
                        $(".events-list-module").append(eventTemplate);
                    }

                    if (isViewMoreVisible) {
                        viewMoreTemplate = viewMoreTemplate.replace("{targetType}", ViewMoreTargetType);
                        viewMoreTemplate = viewMoreTemplate.replace("{viewMoreText}", ViewMoreText);
                        viewMoreTemplate = viewMoreTemplate.replace("{viewMoreLink}", ViewMoreLink === "" ? "" : " href='" + ViewMoreLink + "'");
                        viewMoreTemplate = viewMoreTemplate.replace("{headerText}", headerTitle);
                        viewMoreTemplate = viewMoreTemplate.replace("{viewMoreAction}", ViewMoreText.toLowerCase());
                        viewMoreTemplate = viewMoreTemplate.replace("{viewMoreActionAttr}", ViewMoreText.toLowerCase());
                        $(".events-list-module").append(viewMoreTemplate);
                    }
                }
                else if (json.length == undefined || json.length === 0) {
                    //Display no events in view
                    $(".noevents").css("display", "");
                }
                else {
                    $(".events-list-module").remove();
                }
                EventListResponsive.EventsListMobile();
            },
            GetEventsData: function (dateStart, dateEnd) {
                var call = EventCalendarAPICallGetRecentEvents;

                // Get filter values
                var _filterLoc = $('#btn-label-filter-location').attr('data-value').length <= 0 ? 'null' : $('#btn-label-filter-location').attr('data-value');
                var _filterOrg = $('#btn-label-filter-organization').attr('data-value').length <= 0 ? 'null' : $('#btn-label-filter-organization').attr('data-value');
                var _filterType = $('#btn-label-filter-event').attr('data-value').length <= 0 ? 'null' : $('#btn-label-filter-event').attr('data-value');

                // multi dates
                call = call.replace('{eventCollectionId}', EventCollectionPathId);
                call = call.replace('{eventCollectionLanguage}', acnPage.Language);
                call = call.replace('{dateStart}', dateStart.getFullYear() + '-' + (dateStart.getMonth() + 1) + '-' + dateStart.getDate());
                call = call.replace('{dateEnd}', dateEnd.getFullYear() + '-' + (dateEnd.getMonth() + 1) + '-' + dateEnd.getDate());
                call = call.replace('{filterLocation}', _filterLoc);
                call = call.replace('{filterOrganization}', _filterOrg);
                call = call.replace('{filterType}', _filterType);

                wsCall(call, EventList.ShowEventsCallback);
            },
            ShowFilters: function () {
                var call = EventCalendarAPICallFormatGetEventFilters.replace('{EventCollectionPathId}', EventCollectionPathId);
                call = call.replace("{EventCollectionLanguage}", acnPage.Language);
                wsCall(call, EventList.ShowFiltersCallback);
            },
            FilterEvents: function () {
                var startDate = new Date();

                // Show filters and recent events
                EventList.GetEventsData(startDate, startDate.addMonths(3));
            },
            FormatDate: function (selectedDate) {
                var formattedDate = "";
                if (selectedDate != null && selectedDate != "") {
                    var convertedDate = new Date(selectedDate);
                    if (convertedDate != null && convertedDate != "") {
                        var splitDate = convertedDate.toDateString().split(" ");
                        if (splitDate.length > 2) {
                            formattedDate = splitDate[1] + " " + splitDate[2];
                        }
                    }
                }
                else {
                    formattedDate = "";
                }

                return formattedDate;
            },
            EventLinkParamFormatDate: function (selectedDate) {
                var formattedDate = "";
                if (selectedDate != null && selectedDate != "") {
                    var convertedDate = new Date(selectedDate);
                    if (convertedDate != null && convertedDate != "") {
                        var splitDate = convertedDate.toDateString().split(" ");
                        if (splitDate.length > 2) {
                            formattedDate = splitDate[1] + splitDate[2] + splitDate[3];
                        }
                    }
                }
                else {
                    formattedDate = "";
                }

                return formattedDate;
            },
            RemoveTopAndBottomMargin: function () {
                var eventListBlock = $('div .events-list-module');
                if (eventListBlock.length > 0) {
                    var contentBox = eventListBlock.closest('.ui-content-box');
                    contentBox.attr('style', 'margin-top:0px !important;padding: 0px !important;');
                }
            },
            AddAnalyticsLinkTrackingAttribute: function () {
                if (container.has('.events-list-module')) {
                    container.attr('data-analytics-template-zone', container.attr('id'));
                }
            },
            Init: function () {
                var startDate = new Date();

                // Show filters and recent events
                EventList.ShowFilters();
                EventList.GetEventsData(startDate, startDate.addMonths(3));
                EventList.RemoveTopAndBottomMargin();
                EventList.AddAnalyticsLinkTrackingAttribute();
            }
        }

        EventList.Init();

        //ADO 1119257 keyboard navigation related to ul > li
        dropdownMenu.on('keydown', 'li', function (e) {
            var parentLabel = $(this).parent().parent().find('.corporate-black2.filter-value');
            var dropdownButton = $(this).parent().parent().find('button.dropdown-toggle');

            //9 tab and shift key
            if (e.keyCode === 9 && e.shiftKey) {
                $(this).trigger("click");
                return false;
            }

            switch (e.keyCode) {

                //home goes to the first li element
                case 36:
                    e.preventDefault();
                    $(this).attr('aria-selected', 'false');
                    $(this).parent().find('li').first().attr('aria-selected', 'true').trigger("focus");
                    parentLabel.text($(this).parent().find('li').first().attr('aria-label'));
                    break;

                //end key, goes to the last li element	
                case 35:
                    e.preventDefault();
                    $(this).attr('aria-selected', 'false');
                    $(this).parent().find('li').last().attr('aria-selected', 'true').trigger("focus");
                    parentLabel.text($(this).parent().find('li').last().attr('aria-label'));
                    break;

                //up arrow key, traverse the ul list uoward
                case 38:
                    e.preventDefault();
                    var prevLi = $(this).prev();
                    if (!prevLi.is('li'))
                        return;
                    prevLi.trigger("focus");
                    $(this).attr('aria-selected', 'false');
                    prevLi.attr('aria-selected', 'true');
                    parentLabel.text(prevLi.attr('aria-label'));
                    break;

                //down arrow key, traverse the ul list downward
                case 40:
                    e.preventDefault();
                    var nextLi = $(this).next();
                    if (!nextLi.is('li'))
                        return;
                    nextLi.trigger("focus");
                    $(this).attr('aria-selected', 'false');
                    nextLi.attr('aria-selected', 'true');
                    parentLabel.text(nextLi.attr('aria-label'));
                    break;

                //enter
                case 13:
                    e.preventDefault();
                    $(this).trigger("click");
                    break;

                //escape
                case 27:
                    $(this).trigger("click");
                    break;

                //tab
                case 9:
                    tabActiveElement = $(document.activeElement).parent().parent();
                    $(this).trigger("click");
                    tabActiveElement.next().trigger("focus");
                    break;

                //space
                case 32:
                    e.preventDefault();
                    dropdownButton.removeClass('clickable');
                    $(this).trigger("click");
                    setTimeout(function () { dropdownButton.addClass('clickable') }, 200);
                    break;

                default:
                    break;

            }

        });

        dropdownMenuToggle.on('click keydown', function (e) {
            if (e.keyCode === 27 && !$(this).parent().hasClass('open'))
                return false;

            if (e.type === 'click' || e.keyCode === 13 || e.keyCode === 20 || e.keyCode === 32)
                if ($(this).hasClass('clickable')) {
                    $(this).attr('aria-expanded', 'true');
                    var ulParent = $(this).next('ul');
                    var ariaSelected = ulParent.find('[aria-selected=true]');

                    if (ariaSelected.length === 0)
                        setTimeout(function () {
                            ulParent.find('li').first().attr('aria-selected', 'true').trigger("focus");

                        }, 0);
                    else
                        setTimeout(function () {
                            ariaSelected.trigger("focus");
                        }, 0);
                } else
                    return false;
        });

        dropdownMenu.on('click', 'li', function () {
            $(this).parent().parent().find('[aria-selected=true]').attr('aria-selected', 'false');
            $(this).attr('aria-selected', 'true');
            $(this).parent().parent().find("button").attr('aria-expanded', 'false').trigger("focus");
            $(this).parent().attr('aria-activedescendant', $(this).attr('id'));

        })
    });

    $(window).on('load orientationchange resize', function () {
        EventListResponsive.EventsListMobile();
    });

    $(document).on("click", function (e) {
        var checkForOpenClass = $('.responsive-calendar-filters .filter .btn-group');
        if (!checkForOpenClass.hasClass('open')) {
            checkForOpenClass.children('button').attr('aria-expanded', 'false');
        } else {
            checkForOpenClass.children('button').attr('aria-expanded', 'true');

        }
    })
}
//Change layout between devices on resize
EventListResponsive = {
    EventsListMobile: function () {
        var eventDesc = $('div.event-desc');
        var eventsContainer = $('div.vertical-align');
        var eventDescContainer = $('span.event-desc2');
        var eventDateContainer = $('div.event-date');
        if ($(window).width() < 768) {
            eventsContainer.css("height", "135px");
            eventDateContainer.css("position", "absolute");
            eventDesc.children().css("width", "250px");
            eventDesc.find('p.ucase.font-bold').css("margin-top", "0px");
            eventDescContainer.css("display", "none");
            if ($(window).width() >= 700 && $(window).width() < 768) {
                eventDesc.children().css("width", "635px");
                eventDesc.css("padding-top", "40px");
            }
            else if ($(window).width() >= 600 && $(window).width() < 700) {
                eventDesc.children().css("width", "550px");
                eventDesc.css("padding-top", "40px");
            }
            else if ($(window).width() >= 500 && $(window).width() < 600) {
                eventDesc.children().css("width", "485px");
                eventDesc.css("padding-top", "40px");
            }
            else if ($(window).width() >= 400 && $(window).width() < 500) {
                eventDesc.children().css("width", "340px");
                eventDesc.css("padding-top", "55px");
            }
            else {
                eventDateContainer.css("width", "250px");
                eventDesc.css("padding-top", "55px");
            }
        }
        else {
            eventsContainer.css("height", "");
            eventDateContainer.css("position", "");
            eventDateContainer.css("width", "");
            eventDesc.children().css("width", "");
            eventDesc.find('p.ucase.font-bold').css("margin-top", "");
            eventDesc.css("padding-top", "");
            eventDescContainer.css("display", "");
        }
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\suggestedjobs.js
//version="30"
if (ComponentRegistry.SuggestedJobsModule) {

	$("#RecommendedJobs-li").hide();

	var maxJobCountValue = $('#storeMaxCountValue').val();
	var minJobCountValue = $('#storeMinCountValue').val();

	var countrySite = $('#countrySite').val();
	var searchCountry = "";
	var searchLanguage = "";

	//Used to generate heading
	function createHeadingFour(headingText) {
		var heading = '<h4 class="font-black margin-fifteen">';
		heading += headingText;
		heading += '</h4>';
		return heading;
	};

	$("#span-ChangeLocation").on("click", function () {
		$("#suggestedjobs-changelocation").trigger("click");
	});

	//initially disables the City selection dropdown
	$('#btnCitySelection').prop('disabled', true);

	//Onclick event for Sumbmit button
	$("#btn-SuggestedJob-Submit").on("click", function () {
		var strCountry = "";
		strCountry = $('#dd-country').text(); //get selected country
		var strCityState = "";
		strCityState = $('#dd-citystate').attr("value"); //get selected City/State
		var moreJobLinkValue = $('#storeMoreJobLinkValue').val();
		var jobDetailsLinkValue = $('#storeJobDetailsLinkValue').val();
		var jobPreferencesValue = $('#storeJobPreferencesValue').val();
		var jobLanguage = searchLanguage;        

		var data = {
			countrySiteName: searchCountry,
			cityState: strCityState,
			minJobCountValue: minJobCountValue,
			maxJobCountValue: maxJobCountValue,
			moreJobLinkValue: moreJobLinkValue,
			jobDetailsLinkValue: jobDetailsLinkValue,
			jobPreferencesValue: jobPreferencesValue,
            language: jobLanguage
		};

		if (strCountry != $("#storeSelectCountry").val()) {
			if (strCityState != $("#storeSelectCity").val()) {
				var serviceURL = '/api/sitecore/SuggestedJobModule/OnSubmitSuggestedJob';

				$.ajax({
					//type: 'GET',
					url: serviceURL,
					data: data,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					cache: false,
					error: function () {
						//do nothing;
					},
					success: function (data, status) {
						var newheading = createHeadingFour($("#storeJobOpeningsIn").val() + ' ' + data.Country + ' <span id="span-ChangeLocation" class="suggestedjobs-cta">' + $("#storeChangeLocation").val() + '</span>');

						$("#storePreviousHeading").val(newheading)
						$("#suggestedJobsGoBack").trigger("click");
						SugJobForceColorTheme(sugJobColorTheme);

						//Clear Latest Jobs Html
						$("#Tab-LatestJobs").html();
						var latestJobsHtml = "";

						//Assign LatestJobsSet Result
						var latestJobsSet = data.LatestJobsSet;

						//Column Name
						var recommendedJobText = $("#storeRecommendedJobText").val();
						var latestJobText = $("#storeLatestJobText").val();
						var locationNegotiableText = $("#storeLocationNegotiable").val();

						if (data.IsJobPreferencesHasResult) {
							$("#LatestJobs-li").text(recommendedJobText);
						} else {
							$("#LatestJobs-li").text(latestJobText);
						}

						//Job Results for more than Minimum Job count
						function dataTwoColumn(index) {
							var latestJobsHtmlTwoColumn = "";
							var indexValue = parseInt(index + 1);
							var jobDetailsKeyword = "";

							jQuery.each(data.LatestJobsSet, function (i, val) {
								if (val.keyword !== null && typeof val.keyword !== 'undefined' && val.keyword !== "" && val.keyword !== "NULL") {
									jobDetailsKeyword = "&keyword=" + val.keyword;
									jobDetailsKeyword = "&keyword=" + processKeyword(jobDetailsKeyword);
								} else {
									jobDetailsKeyword = "";
								}
								if (i == indexValue) {
									latestJobsHtmlTwoColumn +=
										"<div class='col-sm-" + data.ColumnSize + "'>" +
										"<p>" +
										"<a class='color-primary ui-link font-normal' href='" + val.jobDetailUrl.replace("{0}", countrySite).concat(jobDetailsKeyword) + "'>" +
										val.title +
										"</a>" +
										location(val.location) +
										"</p>" +
										"</div>"
								}
							});

							latestJobsSetCounter = parseInt(indexValue + 1);
							return latestJobsHtmlTwoColumn;
						}

						//Manipulate Job Results, append to latestJobsHtml.
						if (latestJobsSet.length > data.MinJobCount) {
							//Latest Jobs Set Counter
							var latestJobsSetCounter = 0;
							var jobDetailsKeyword = "";
							if (data.LatestJobsSet.length != 0) {
								jQuery.each(data.LatestJobsSet, function (i, val) {
									if (data.LatestJobsSet.length == 0) {
										latestJobsHtml +=
											"<div class='col-sm-12'>" +
											"<div class='col-sm-12>" +
											val.noResultsFound +
											"</div>" +
											"</div>";
									} else if (latestJobsSetCounter == i) {
										if (val.keyword !== null && typeof val.keyword !== 'undefined' && val.keyword !== "" && val.keyword !== "NULL") {
											jobDetailsKeyword = "&keyword=" + val.keyword;
											jobDetailsKeyword = "&keyword=" + processKeyword(jobDetailsKeyword);
										} else {
											jobDetailsKeyword = "";
										}
										latestJobsHtml +=
											"<div class='col-sm-12'>" +
											"<div class='col-sm-" + data.ColumnSize + "'>" +
											"<p>" +
											"<a class='color-primary ui-link font-normal' href='" + val.jobDetailUrl.replace("{0}", countrySite).concat(jobDetailsKeyword) + "' data-rel='" + encodeURIComponent(val.id) + "' data-name='asset' >" +
											val.title +
											"</a>" +
											location(val.location) +
											"</p>" +
											"</div>" +
											dataTwoColumn(i) +
											"</div>";
									}
								});
							} else {
								latestJobsHtml =
									"<div class='col-sm-12'>" +
									"<div class='col-sm-12><p>" +
									"<label class='module-body Bold font-black'>" + data.NoResultsFound + "</label>" +
									"</p></div>" +
									"</div>";
							}
						} else {
							if (data.LatestJobsSet.length != 0) {
								jQuery.each(data.LatestJobsSet, function (i, val) {
									if (val.keyword !== null && typeof val.keyword !== 'undefined' && val.keyword !== "" && val.keyword !== "NULL") {
										jobDetailsKeyword = "&keyword=" + val.keyword;
										jobDetailsKeyword = "&keyword=" + processKeyword(jobDetailsKeyword);
									} else {
										jobDetailsKeyword = "";
									}
									latestJobsHtml +=
										"<div class='col-sm-12'>" +
										"<div class='col-sm-" + data.ColumnSize + "'>" +
										"<p>" +
										"<a class='color-primary ui-link font-normal' href='" + val.jobDetailUrl.replace("{0}", countrySite).concat(jobDetailsKeyword) + "' data-rel='" + encodeURIComponent(val.id) + "' data-name='asset' >" +
										val.title +
										"</a>" +
										location(val.location) +
										"</p>" +
										"</div>" +
										"</div>";
								});
							} else {
								latestJobsHtml =
									"<div class='col-sm-12'>" +
									"<div class='col-sm-12><p>" +
									"<label class='module-body Bold font-black'>" + data.NoResultsFound + "</label>" +
									"</p></div>" +
									"</div>";
							}
						}

						//Manipulate Job Locations results
						function location(joblocation) {
							var location = "";
							if (joblocation != null) {
								jQuery.each(joblocation, function (i, val) {
									if (joblocation.length > 1) {
										location = "<label class='module-body Bold font-black'>" + "&nbsp" + data.MultipleLocations + "</label>";
										return;
									} else {
										location = "<label class='module-body Bold font-black'>" + "&nbsp" + val + "</label>";
									}
								});
							} else {
								location = "<label class='module-body Bold font-black'>" + "&nbsp" + locationNegotiableText + "</label>";
							}
							return location;
						}

						var showMoreLatestJobHtml = "";
						if (data.ShowMoreLatestJob == true) {
							showMoreLatestJobHtml =
								"<div class='more-jobs-link'>" +
								"<a class='suggestedjobs-cta' href='" + data.MoreButtonLink + "'>" +
								data.MoreJobs +
								"</a>" +
								"</div>";
						}

						$("#Tab-LatestJobs").html(latestJobsHtml + showMoreLatestJobHtml);
						$("#job-description").hide();
					}
				});
			}
			else {
				$("#errorCityState").removeClass('hideobject').addClass('showobject'); //Show Error Message when no City/State selected
			}
		}
		else {
			$("#errorCountry").removeClass('hideobject').addClass('showobject'); //Show Error Message when no Country selected
		}
	});
	//End

	//Onclick event for Change Location link
	$("#suggestedjobs-changelocation").on("click", function (e) {
		var heading = $("#headingCountry").find('h4').html();
		$("#storePreviousHeading").val(createHeadingFour(heading));
		var newheading = createHeadingFour($("#storeEnterNewLocation").val());
		$("#headingCountry").empty();
		$("#headingCountry").append(newheading);
		$("#suggestedJobsTab").addClass('hidedivider');
	})

	//Onclick event for Go Back link
	$("#suggestedJobsGoBack").on("click", function (e) {
		var newheading = $("#storePreviousHeading").val();
		$("#headingCountry").empty();
		$("#headingCountry").append(newheading);
		$("#suggestedJobsTab").removeClass('hidedivider');
		$("#span-ChangeLocation").on("click", function () {
			$("#suggestedjobs-changelocation").trigger("click");
		});
		$("#SuggestedJob-Tab").trigger("click");
	})

	//Onclick event for Recommended Jobs link
	$("#RecommendedJobs-li").on("click", function (e) {
		$("#span-ChangeLocation").css("visibility", "hidden");
		$("#job-description").show();
	})

	//Onclick event for Latest Jobs link
	$("#LatestJobs-li").on("click", function (e) {
		$("#job-description").hide();
		$("#span-ChangeLocation").css("visibility", "visible");
	})

	//Function for attaching Onlick Event per City/State
	function attachDropdownEvent(data) {
		var buildID = '#' + data + ' li a';
		$(buildID).on("click", function () {
		    var citydata = $(this).attr("Value");
			if ($(this).text() != $("#dd-citystate").text()) {
				$("#dd-citystate").text($(this).text());
				$("#dd-citystate").attr("value",citydata);
				$("#dd-citystate").removeClass('ddValueNoneSelected').addClass('ddValueSelected');
				$("#errorCityState").removeClass('showobject').addClass('hideobject');
			}
		});
	};

	//Onclick event for Country Dropdown
	$("#dd-country-ul li a").on("click", function () {
		if ($(this).text() != $("#dd-country").text()) {
			$("#dd-country").removeClass('ddValueNoneSelected').addClass('ddValueSelected');
			$("#errorCountry").removeClass('showobject').addClass('hideobject');
			var serviceURL = "/api/sitecore/SuggestedJobModule/RetrieveCityState";
			var str = $(this).text();
			var country = $(this).attr("value");
			searchCountry = country;			
			var countryID = $(this).attr("value");
			var jobLanguage = $(this).data("lang");
			searchLanguage = jobLanguage;            

			var data = {
				country: country,
				countryId: countryID,
				language: jobLanguage
			};

			$.ajax({
				//type: 'GET',
				url: serviceURL,
				data: data,
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				cache: false,
				error: function () {
					//do nothing;
				},
				success: function (data, status) {
                    var option = '';
                    var valueLinkName = '';
                    $.each(data, function (key, value) {

                        if (value !== null && value !== undefined) {
                            valueLinkName = value;
                        }
                        option += '<li><a value="' + value + '" tabindex="-1" data-analytics-link-name="' + valueLinkName.toLowerCase() + '" data-analytics-content-type="cta">' + value + '</a></li>';
                    });
					$('#dd-citystate-ul').empty();
					$('#dd-citystate-ul').append(option);
					attachDropdownEvent('dd-citystate-ul');
					if (option != "") {
						$('#btnCitySelection').prop('disabled', false);
					}
					else {
						$('#btnCitySelection').prop('disabled', true);
					}
				}
			});

			$("#dd-country").text($(this).text());
			$("#dd-citystate").text($("#storeSelectCity").val());
			$("#dd-citystate").removeClass('ddValueSelected').addClass('ddValueNoneSelected');
			$('#dd-citystate').attr("value", "");
		}
	});

	//Prevent Onlick event of Suggested Job Tab
	$(function () {
		$('#SuggestedJob-Tab').on("click", function (e) {
			e.preventDefault();
		});
		$("#job-description").hide();


		if (isTablet()) {
			JobResultCarousel(4);
		}
		else if (isMobile()) {
			JobResultCarousel(2);
		}
		else {
			JobResultCarousel(5);
		}
	});

	//Overide Function H4 CSS from Stylecore
	function SugJobForceColorTheme(color) {
		$("#span-ChangeLocation").css('color', color);
	};

	var sugJobColorTheme = $('#suggestedJobsGoBack').css('color')
	SugJobForceColorTheme(sugJobColorTheme);

	//Background color change upon hovering
	var jobs = $("div.jobresults");
	var withHover = function () {
		var $this = $(this);
		var color = $this.data("bgcolor")
		$this.addClass("bg-color-" + color).addClass("color-container");
		$(".job-container-footer ").addClass("color-" + color);
		if ($this.prev().length !== 0) {
			var prevjob = $this.prev();
			prevjob = prevjob[0].childNodes[1];
			$(prevjob).css("border-right-color", "transparent");
		}
		var detailsButton = $this.find(".job-container-footer .btn.recommended-jobs");
		var moreDetailsColor = $this.find(".job-container-footer").data("button-color");
		if (moreDetailsColor != "" || typeof (moreDetailsColor) != "undefined") {
			detailsButton.removeClass("bg-color-" + moreDetailsColor);
			detailsButton.removeClass("br-color-" + moreDetailsColor);
		}
	};
	var unHover = function () {
		var $this = $(this);
		var color = $this.data("bgcolor")
		$this.removeClass("bg-color-" + color).removeClass("color-container");
		$(".job-container-footer ").removeClass("color-" + color);
		if ($this.prev().length !== 0) {
			var prevjob = $this.prev();
			prevjob = prevjob[0].childNodes[1];
			$(prevjob).css("border-right", "");
		}

		var detailsButton = $this.find(".job-container-footer .btn.recommended-jobs");
		var moreDetailsColor = $this.find(".job-container-footer").data("button-color");
		if (moreDetailsColor != "" || typeof (moreDetailsColor) != "undefined") {
			detailsButton.addClass("bg-color-" + moreDetailsColor);
			detailsButton.addClass("br-color-" + moreDetailsColor);
		}
	};

	//Bug Fix 483995
	$('div#content-wrapper.ui-content-wrapper').on("click", unHover);
	$('#search-container').on("click", unHover);

	jobs.on("mouseover", withHover);
	jobs.on("mouseout", unHover);
	jobs.on("click", withHover);

	$(window).on('load resize orientationchange', function () {

		var maxHeight = 0;
		if ($('.jobresults').parent().is("div")) {
			$('.jobresults').unwrap();
		}

		$("div.job-container-header").each(function () {
			if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
		});
		$("div.job-container-header").height(maxHeight);

		var $jobs = $('.career-recommended-jobs');
        if ($('.jobresults').length === 0 && $jobs.parents().eq(0).children().length < 2) {
            $jobs.parents().eq(4).empty();
		}
		$(".job-arrow").show();
		$('.jobresults').nextAll().removeClass("hidden");

		var jobTileHeight = $('.job-container').outerHeight() / 2;
		var rightArrowPosition = 0;
		var leftArrowPosition = 0;
		if ($(window).width() <= 767) {
			JobResultCarousel(2);
			rightArrowPosition = jobTileHeight + 16 + 'px';
			leftArrowPosition = jobTileHeight + 7 + 'px';
		}
		else if ($(window).width() === 960) {
			JobResultCarousel(5);
			rightArrowPosition = jobTileHeight + 21 + 'px';
			leftArrowPosition = jobTileHeight + 16 + 'px';
		}
		else if ($(window).width() >= 768 && $(window).width() < 1024) {
			JobResultCarousel(4);
			rightArrowPosition = jobTileHeight + 10 + 'px';
			leftArrowPosition = jobTileHeight + 4 + 'px';
		} else {
			JobResultCarousel(5);
			rightArrowPosition = jobTileHeight + 19 + 'px';
			leftArrowPosition = jobTileHeight + 13 + 'px';
		}
		$('.job-arrow').css('bottom', rightArrowPosition);
		$('.job-arrow-left').css('bottom', leftArrowPosition);

		var lastJobs = $(".jobresults .job-container:visible").last();

		if ($(".job-container").length > 0) {
			$(".jobresults-search-open-position").height($(".job-container").innerHeight());
		}

	});


	function JobResultCarousel(numOfTiles) {
		var slideName = 'slide-';
		var slideCount = 0;
		$(".job-arrow-left").hide();
		$(".job-container").removeClass("withnoborder");

		var jobResults = $("div.jobresults");
		for (i = 0; i < jobResults.length; i += numOfTiles) {
			slideCount += 1;
			var isActive = "";

			if (slideCount == 1) {
				isActive = "active";
			}
			else if (slideCount == 2) {
				isActive = "next";
			} else { isActive = ""; }

			jobResults.slice(i, i + numOfTiles).wrapAll("<div id='" + slideName + slideCount + "' class = 'item " + isActive + "'></div>");
			$("#" + slideName + slideCount + " > .jobresults .job-container").last().addClass("withnoborder");
		}
		if ($('.jobresults').length === 1) {
			$('.jobresults').children().removeClass("withnoborder");
		}
		var jobCarousel = $('.job-carousel .carousel-inner');
		if (jobCarousel.children().length <= 1 || jobCarousel.find('.jobresults-search-open-position').length == 1) {
			$(".job-arrow").hide();
		}
	}

	function JobArrowRight($items) {
		var next = $items.find('.next').index();
		$items.find('.prev.left').removeClass('prev left');
		$items.children().eq(next - 1).removeClass('active').addClass('prev left');
		$items.children().eq(next).removeClass('next').addClass('active');
		$items.children().eq(next + 1).addClass('next');

		if ((next >= ($items.children().length - 1)) || $items.children().length == 1) {
			$(".job-arrow").hide();
		}
		$(".job-arrow-left").show();
	}

	function JobArrowLeft($items) {
		var prev = $items.find('.prev').index();
		$items.find('.next').removeClass('next');
		$items.children().eq(prev + 1).removeClass('active').addClass('next');
		$items.children().eq(prev).removeClass('prev left').addClass('active');

		if (prev <= 0) {
			$(".job-arrow-left").hide();
		}
		else {
			$items.children().eq(prev - 1).addClass('prev left');
		}

		$(".job-arrow").show();
	}

	$(".job-arrow").on("click", function (e) {
		JobArrowRight($('.job-carousel .carousel-inner'));
	})

	$(".job-arrow-left").on("click", function (e) {
		JobArrowLeft($('.job-carousel .carousel-inner'));
	})
	//RMT 574
	function replaceAllReservedCharacter(str, find, replace) {
		return str.replace(new RegExp(find, 'g'), replace);
	}
	function ReplaceReservedCharacter(encodedKeyword) {
		if (encodedKeyword != undefined && encodedKeyword.length > 0) {
			if (encodedKeyword.indexOf("/") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "/", "%2F");
			if (encodedKeyword.indexOf("?") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "\\?", "%3F");
			if (encodedKeyword.indexOf(":") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, ":", "%3A");
			if (encodedKeyword.indexOf("@") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "@", "%40");
			if (encodedKeyword.indexOf("=") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "=", "%3D");
			if (encodedKeyword.indexOf("&") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "&", "%26");
			if (encodedKeyword.indexOf("#") > -1)
				encodedKeyword = replaceAllReservedCharacter(encodedKeyword, "#", "%23");
		} else {
			encodedKeyword = "";
		}

		return encodedKeyword;
	}


	function processKeyword(keywordToProcess) {
		var keyword = "";

		keyword = ReplaceReservedCharacter(keywordToProcess.split('&keyword=')[1]);
		keyword = keyword.replace(/[ ]{2,}/g, "").replace(/ , |, | ,|,|; |;| ;/g, "|").replace(/,$|\|$|;$| $/g, "").replace(/ /g, "-");

		return keyword;
	}
	//jobOpening US008
	var jobOpenings = $('#suggestedJobsTabContent2 a.color-primary').each(function () {
		var urlContent = $(this).attr('href'); //get href;
		var newKeyword = "";
		var newUrl = "";
		try {
			newKeyword = processKeyword(urlContent);
			newUrl = (newKeyword) ? urlContent.substring(0, urlContent.indexOf('&keyword=') + '&keyword='.length) + newKeyword : urlContent; //chops off url to '&keyword=' then adds the new keyword
		}
		catch (err) {
			newUrl = urlContent.substring(0, urlContent.indexOf('&keyword='));
		}

		$(this).attr('href', newUrl);
	});
	//latest-recommended jobs US007
	var latestRecommended = $("a.recommended-jobs").each(function () {
		var urlContent = $(this).attr('href'); //get href;
		var newKeyword = "";
		var newURL = "";
		try {
			newKeyword = processKeyword(urlContent);
			newUrl = (newKeyword) ? urlContent.substring(0, urlContent.indexOf('&keyword=') + '&keyword='.length) + newKeyword : urlContent; //chops off url to '&keyword=' then adds the new keyword
		}
		catch (err) {
			newUrl = urlContent.substring(0, urlContent.indexOf('&keyword='));
		}
		$(this).attr('href', newUrl);
	});
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\findjobs.js
// Version="2"
if (ComponentRegistry.FindJobsModule) {
    function findAJob(FindAJobButtonLink) {
        $("#search-error").html();
        var searchInput = $("#search-input").val();
        var url = "";
        searchInput = removeTags(searchInput);
        if (searchInput == '' || typeof searchInput === "undefined") {
            url = FindAJobButtonLink;
        } else {
            url = FindAJobButtonLink + "?jk=" + searchInput;
        }

        $(location).attr('href', url);
    }
    
    function enterKeyFindAJob(e, jobSearchLink) {
        var enterKey = 13;
        if (e.which == enterKey) {
            $('button[onclick^="javascript:findAJob"]').trigger("click");
        }
    }   

    $(function () {
        var from = 1;
        var size = 10;
        var contextItemId = $("#context-item-id").val();
        $("#search-input").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/api/sitecore/FindJobModule/FindSuggestions',
                    data: "{'contextItemId': '" + contextItemId + "','keywords': '" + request.term + "','from': '" + from + "' ,'size': '" + size + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            if (item.title != "") {
                                $("#search-error").html();
                                return {
                                    value: item.title,
                                    id: item.requisitionId
                                };
                            } else {
                                $("#search-error").html("There are no search results for these sections.");
                            }
                        }))
                    }
                });
            },
            minLength: 5,
            select: function (event, ui) {
                $("#job-selected-id").val(ui.item.value);
            }
        });
    });
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\featuredsection.js
/* version="10" */
if (ComponentRegistry.FeaturedSection) {
    $(function () {
        var carouselHeight = $('#CampaignPortal > div.carousel-inner').height();
        $('#CampaignPortal').find('[id^="CampaignPortal_item"]').each(function () {

            if ($(this).height() > carouselHeight) {
                carouselHeight = $(this).height();
            }
        });

        $(".featured-section-module-carousel .featured-section-module.module-article .media:empty").remove();

        //Bug Fix for 462576
        //Update note: new implementation to display tooltipin FSM (proposed fix is attached in SIR #462576)
        var articles = $('.featured-section-module.module-article.component');
        articles.each(function (index) {
            $this = $(this);
            var title = "";
            if ($this.find('span[class!="cta"]').length > 0) {
                title = $this.find('h4 span').html();
            }
            else {
                title = $this.find('h4').html();
            }

            console.log('title' + index + ': ' + title);
            $this.find('a').attr('title', title);
        });
        //End: Bug Fix for 462576

        if (isMobile()) {
            CarouselForMobile();
        }
    });

    $(window).on("load", function () {
        $(".featured-section-module-carousel .social-likes__widget.social-likes__widget_single").off("click");

        $(".CommonElementSharing .social-likes_single-w").popover({
            html: true,
            placement: 'bottom',
            container: 'body',
            content: function () {
                var dataUrl = $(this).find('#tooltipPopup').data('url');
                var dataTitle = $(this).find('#tooltipPopup').data('title');
                var dataParentId = $(this).closest("div[id^='block-'].ui-container").attr("id");
                $(this).find('.social-likes strong').text('');
                var socialHtml = $(this).find('.social-likes').html();
                if (dataUrl.match('/_Component')) {
                    dataUrl = dataUrl.substring(0, dataUrl.indexOf('/_Component'));
                }
                return "<div class='social-likes social-likes_vertical social-likes_visible social-likes_opened' "
                    + "data-url='" + dataUrl + "' "
                    + "data-title='" + dataTitle + "' "
                    + "data-linkpagesection='" + dataParentId + "'> "
                    + socialHtml.replace(/social-likes__widget social-likes__widget_/g, '')
                    + " </div>";
            }
        }).css("display", "table");

        $(".CommonElementSharing .social-likes_single-w").on('shown.bs.popover', function () {
            $(".popover.bottom > .arrow").remove();
            $(".arrow").css("left", "50%");
            $('.popover-content .social-likes').socialLikes();
        });
    });

    var CarouselForMobile = function () {
        //set false rotate attribute for non desktop view
        if (isMobile() || isTablet()) {
            $('.featured-section-module-carousel .carousel').each(function () {
                $(this).attr('data-interval', 'false');
            });
        }

        $('.featured-section-module-carousel').each(function () {
            var carouselId = $(this).find('div.carousel.slide.conv-carousel').attr('id');
            if (carouselId == undefined) {
                return;
            }
            carouselId = '#' + carouselId;
            var itemSelector = '.featured-section-module-carousel ' + carouselId + ' .carousel-inner .item';
            var indicatorSelector = '.featured-section-module-carousel ' + carouselId + ' ol.carousel-indicators li';
            var carouselSelector = '.featured-section-module-carousel ' + carouselId + ' .carousel-inner';
            var carouselDotSelector = '.featured-section-module-carousel ' + carouselId + ' ol.carousel-indicators';
            //get list of existing items
            var articleList = $(itemSelector + ' > div').children();
            //remove existing items in the inner carousel
            $(itemSelector).remove();
            $(indicatorSelector).remove();
            //append the items to the carousel with the new format
            if (articleList != null) {
                for (var i = 0; i < articleList.length; i++) {
                    var activeClass = i == 0 ? "active" : "";
                    var $newItem = $('<div class="item ' + activeClass + '"></div>').append($($('<div></div>').append($(articleList[i])[0])));

                    if (articleList.length > 1) {
                        var $newMobileIndicator = $(document.createElement('li'))
                            .addClass(activeClass)
                            .attr({
                                'data-target': carouselId, 'data-slide-to': i
                            });
                    }
                    $(carouselSelector).append($newItem);
                    if (articleList.length > 1) {
                        $(carouselDotSelector).append($newMobileIndicator);
                    }
                };
            };
        });

    };
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\blogs.js
/* version="24" */
//////////////////////////
//BLOG INDUSTRY SELECTOR
//////////////////////////

var _dataBlogPostList;
var blogPostData = jQuery('#blog-post-data');
var errorMessageBlogs = "";
var noResultsMessage = "";
var isPageEditor = "";
var totalBlogsRetrieved = 0;
var startIndex = 0;
var enableBlogsLazyLoad = false;

var blogPostParameters;
var paramAuthor, paramBlogTag, paramCountrySite, paramIndustryId, paramMonth, paramRelativePath, paramSizeBlogAuthors, paramSizeBlogPosts, paramSizeBlogTags, paramSubjectId, paramYear;
var path = "";

var url = window.location.href;
var arr = url.split("/");
var result = arr[0] + "//" + arr[2];

//set variables for content type and link name attributes
var dataContentType = "data-analytics-content-type";
var linkName = "data-analytics-link-name";

if (blogPostData != null && blogPostData.length > 0) {
    _dataBlogPostList = JSON.parse(blogPostData.text());
    errorMessageBlogs = blogPostData.data("error-message");

    noResultsMessage = blogPostData.data("noresults-message");
    isPageEditor = blogPostData.data("is-page-editor");
}

if ((ComponentRegistry.BlogPostList || ComponentRegistry.BlogArchiveList) && isJSONBlogPostDataAvailable()) {
    blogPostParameters = getJSONBlogPostParam();

    if (blogPostParameters != null || blogPostParameters.length > 0) {
        paramAuthor = blogPostParameters['Author'] != null ? blogPostParameters['Author'] : "";
        paramBlogTag = blogPostParameters['BlogTag'] != null ? blogPostParameters['BlogTag'] : "";
        paramCountrySite = blogPostParameters['CountrySite'] != null ? blogPostParameters['CountrySite'] : "";
        paramIndustryId = blogPostParameters['IndustryId'] != null ? blogPostParameters['IndustryId'] : "";
        paramMonth = blogPostParameters['Month'] != null ? blogPostParameters['Month'] : "";
        paramRelativePath = blogPostParameters['RelativePath'] != null ? blogPostParameters['RelativePath'] : "";
        paramSizeBlogAuthors = blogPostParameters['SizeBlogAuthors'] != null ? blogPostParameters['SizeBlogAuthors'] : "";
        paramSizeBlogPosts = blogPostParameters['SizeBlogPosts'] != null ? blogPostParameters['SizeBlogPosts'] : "";
        paramSizeBlogTags = blogPostParameters['SizeBlogTags'] != null ? blogPostParameters['SizeBlogTags'] : "";
        paramSubjectId = blogPostParameters['SubjectId'] != null ? blogPostParameters['SubjectId'] : "";
        paramYear = blogPostParameters['Year'] != null ? blogPostParameters['Year'] : "";

        path = '/api/sitecore/BlogPostList/GetBlogPostData';

        totalBlogsRetrieved = parseInt(jQuery("#TotalBlogResult").val());
        startIndex = paramSizeBlogPosts;
    }
}

function getJSONBlogPostDataEs() {
    var JSONposts = "";

    $.ajax({
        url: path,
        type: "POST",
        data: JSON.stringify({
            Author: paramAuthor,
            BlogTag: paramBlogTag,
            CountrySite: paramCountrySite,
            IncludeBlogAuthorResult: false,
            IncludeBlogPostsResult: true,
            IncludeBlogTagResult: false,
            IncludeBlogPostsDate: false,
            IndustryId: paramIndustryId,
            Month: paramMonth,
            RelativePath: paramRelativePath,
            BlogAuthorsSize: paramSizeBlogAuthors,
            BlogPostsSize: paramSizeBlogPosts,
            BlogTagsSize: paramSizeBlogTags,
            SubjectId: paramSubjectId,
            Year: paramYear,
            From: 0,
        }),
        contentType: "application/json",
        async: false,
        error: function (res) {
            result = null;
        },
        success: function (res) {
            JSONposts = JSON.parse(res);
        }
    });

    return JSONposts;
}

function realWidth(obj) {
    var clone = obj.clone();
    clone.css("visibility", "hidden");
    jQuery('body').append(clone);
    var width = clone.outerWidth();
    clone.remove();

    return width;
}

if (ComponentRegistry.BlogIndustrySelectorHeader) {
    $(function () {
        //show selection
        var text = jQuery('#block-blog-industry-selector .dropdown-menu a[href*="' + window.location.pathname + '"]').text();

        if (text.length <= 0) {
            //show first selection
            text = jQuery('#block-blog-industry-selector .dropdown-menu a').eq(0).text();
        }

        //Bug 174621: Tablet and Mobile dropdown for blog industry selector
        if (jQuery(window).width() < 1000) {
            jQuery('#block-blog-industry-selector div.dropdown'). eq(0).hide();
        } else {
            jQuery('#block-blog-industry-selector div.dropdown').eq(1).hide();
        }

        jQuery(window).on("resize", function () {
            if (jQuery(window).width() < 1000) {
                jQuery('#block-blog-industry-selector div.dropdown').eq(0).hide();
                jQuery('#block-blog-industry-selector div.dropdown').eq(1).show();
            } else {
                jQuery('#block-blog-industry-selector div.dropdown').eq(0).show();
                jQuery('#block-blog-industry-selector div.dropdown').eq(1).hide();
            }
        });

        //set width of dropdown based on menu
        var width = realWidth(jQuery('#block-blog-industry-selector .dropdown-menu'));
        jQuery('#block-blog-industry-selector .btn').css('width', (width - 1) + 'px');
    });

    jQuery(window).on("load", function () {
        //Bug #321745: Blogs: Space between Global Nav and Industry Selector
        //set offset height for preview mode only
        if (isPreviewMode()) {
            var height = jQuery('#header-topnav').height();
            jQuery('#block-blog-industry-selector').css('margin-top', height - 29 + 'px');
        }
        //END of Bug #321745: Blogs: Space between Global Nav and Industry Selector
    });
}

//////////////////////////
//BLOG POST LIST
//////////////////////////

function isJSONBlogPostDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined' && _dataBlogPostList != null)
        return true;

    return false;
}

function getJSONBlogPostData() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-post-list']['posts'];
}

function getJSONBlogPostParam() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-post-list']['params'];
}

function getJSONBlogPostDataFeatured() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-post-list']['posts-featured'];
}

function bindBlogPosts(JSONposts) {
    if (JSONposts != "blog-result-is-null") {
        //featured
        jQuery(".module-blog-featured-post > div").loadTemplate(jQuery('.module-blog-featured-post .json-template'), getJSONBlogPostDataFeatured());

        //non featured
        if (JSONposts.length > 0) {
            var blogPostList = jQuery(".module-blog-post-list ul");
            blogPostList.loadTemplate(jQuery('.module-blog-post-list .json-template'), JSONposts);

            //Blog Post List Title 
            InsertDataAnalyticsAttributes(".module-blog-post-list h4 a", "headline");

            //Blog Post List Read Post
            InsertDataAnalyticsAttributes(".module-blog-post-list p a", "cta");

            blogPostList.find('li').slice(0, 4).removeClass('hidden-xs'); //show only first 4 on mobile

            blogPostList.find("span.author").each(function () {
                var $this = jQuery(this);
                if ($this.find('span').text() == '') {
                    $this.addClass('hidden');
                }
            });           
        }
        else if (isPageEditor == 'True') {
            var blogPostList = jQuery(".module-blog-post-list");
            blogPostList.append(noResultsMessage);
        }

        if (totalBlogsRetrieved <= paramSizeBlogPosts) {
            $('#btn-blogs-load-more').addClass('clicked');
        }
    }
    else {
        var blogPostList = jQuery(".module-blog-post-list");
        blogPostList.text(errorMessageBlogs);
    }
}

if ((ComponentRegistry.BlogPostList || ComponentRegistry.BlogArchiveList) && isJSONBlogPostDataAvailable()) {
    $(function () {
        //INIT
        bindBlogPosts(getJSONBlogPostDataEs());

        //EVENT HANDLERS
        //add show more button event handler
        jQuery('.module-blog-post-list button').on("click", function (event) {
            event.preventDefault();

            jQuery('.module-blog-post-list ul li[class=hidden-xs]').removeClass('hidden-xs');
        });

        jQuery('.social-likes-post.post-is-loaded').each(function () {
            jQuery(this).attr('data-url', result + jQuery(this).attr('data-url'));
        });

        jQuery('.social-likes-post').socialLikes();
        jQuery('.social-likes-post').removeClass('post-is-loaded');

        jQuery(".social-likes-post div").attr(dataContentType, "share intent");
        jQuery(".social-likes-post div.social-likes__widget_facebook").attr(linkName, "facebook");
        jQuery(".social-likes-post div.social-likes__widget_twitter").attr(linkName, "twitter");
        jQuery(".social-likes-post div.social-likes__widget_googleplus").attr(linkName, "googleplus");
        jQuery(".social-likes-post div.social-likes__widget_email").attr(linkName, "email");

        BlogPostListAuthors();

        var IsTagsVisible = jQuery('#ShowPopularTagsInMobile').val() === "True";
        if (isMobile() && !IsTagsVisible) {
            jQuery('.module-blog-tags').hide();
        } else {
            BlogPostTags();
        }

        var IsArchiveVisible = jQuery('#ShowArchivesInMobile').val() === "True";
        if (isMobile() && !IsArchiveVisible) {
            jQuery('.module-blog-archive').hide();
        } else {
            BlogPostArchiveYears();
        }

        hideEmptySocialIcons();

        enableBlogsLazyLoad = true;
    });

    // Handles lazy loading of result
    $(window).on("scroll", function () {
        // show load more button if mobile
        if (isMobile()) {
            $('#btn-blogs-load-more').on('click', function () {
                BlogsLazyLoad();
            });
        }
        else {
            var locationContainerTop, locationScrollTop, locationHeight;
            var totalHeight, scrolledFromTop, visibleHeight;

            locationContainerTop = $('.module-blog-post-list').offset().top;
            locationScrollTop = $(window).scrollTop();
            locationHeight = $('.module-blog-post-list').height();
            totalHeight = document.body.offsetHeight;
            scrolledFromTop = locationScrollTop - locationContainerTop;
            visibleHeight = document.documentElement.clientHeight;

            if (visibleHeight + scrolledFromTop >= locationHeight) {
                BlogsLazyLoad();
            }
        }

        function BlogsLazyLoad() {
            if (startIndex < totalBlogsRetrieved && enableBlogsLazyLoad) {
                $('#pre-loader').css("display", "block");
                enableBlogsLazyLoad = false;
                $.ajax({
                    url: path,
                    type: "POST",
                    data: JSON.stringify({
                        Author: paramAuthor,
                        BlogTag: paramBlogTag,
                        CountrySite: paramCountrySite,
                        IncludeBlogAuthorResult: false,
                        IncludeBlogPostsResult: true,
                        IncludeBlogTagResult: false,
                        IncludeBlogPostsDate: false,
                        IndustryId: paramIndustryId,
                        Month: paramMonth,
                        RelativePath: paramRelativePath,
                        BlogAuthorsSize: paramSizeBlogAuthors,
                        BlogPostsSize: paramSizeBlogPosts,
                        BlogTagsSize: paramSizeBlogTags,
                        SubjectId: paramSubjectId,
                        Year: paramYear,
                        From: startIndex,
                    }),
                    contentType: "application/json",
                    error: function (res) {
                        result = null;
                    },
                    success: function (res) {
                        startIndex += paramSizeBlogPosts;

                        if (startIndex + 1 >= totalBlogsRetrieved) {
                            jQuery('#btn-blogs-load-more').addClass('clicked');
                        }

                        var blogPostList = jQuery(".module-blog-post-list ul");
                        var JSONposts = JSON.parse(res);
                        blogPostList.loadTemplate(jQuery('.module-blog-post-list .json-template'), JSONposts, { append: true });

                        //Blog Post List Title (Lazy Load)
                        InsertDataAnalyticsAttributes(".module-blog-post-list h4 a", "headline");

                        //Blog Post List Read Post (Lazy Load)
                        InsertDataAnalyticsAttributes(".module-blog-post-list p a", "cta");

                        // load social share
                        var socialShares = jQuery('.social-likes-post.post-is-loaded');                        
                        if (socialShares.length > 0 && typeof socialShares != undefined) {
                            socialShares.each(function () {
                                jQuery(this).attr('data-url', result + jQuery(this).attr('data-url'));
                            });
                            socialShares.socialLikes();
                            jQuery('.social-likes-post').removeClass('post-is-loaded');

                            //Blog Post List Share Icons (Lazy Load)
                            jQuery(".social-likes-post div").attr(dataContentType, "share intent");
                            jQuery(".social-likes-post div.social-likes__widget_facebook").attr(linkName, "facebook");
                            jQuery(".social-likes-post div.social-likes__widget_twitter").attr(linkName, "twitter");
                            jQuery(".social-likes-post div.social-likes__widget_googleplus").attr(linkName, "googleplus");
                            jQuery(".social-likes-post div.social-likes__widget_email").attr(linkName, "email");
                            hideEmptySocialIcons();
                        }
                    },
                    complete: function () {
                        $('#pre-loader').css("cssText", "display: none !important;");
                        enableBlogsLazyLoad = true;

                        $('div.social-likes__widget a').attr("style", "text-decoration: none !important");
                        $('div.social-likes__widget a').on("keydown", function (e) {
                            var _this = $(this);
                            if (e.which == 13) {
                                $(this).trigger("click");
                                $('div.social-likes-post div').attr("tabindex", "0");
                    }

                            if (e.which == 9 && $('div.social-likes-post').hasClass("social-likes_opened")) {

                                $('div.social-likes-post').each(function () {
                                    e.preventDefault();
                                    $(this).find('div.social-likes__widget').first().trigger("focus");

                                    $(this).find('div.social-likes__widget').last().on("keydown", function (e) {
                                        if (e.which == 9) {
                                            e.preventDefault();
                                            $('div.social-likes-post').removeClass("social-likes_opened");
                                            $(_this).trigger("focus");
                                        }

                });


                                });

            }

                            $('div.social-likes-post div').on("keydown", function (e) {

                                if (e.which == 13) {
                                    $(this).trigger("click");

        }
    });

                        });
}
                });
            }
        }
    });
}

//////////////////////////
//BLOG POST - RECENT POSTS
//////////////////////////

function isJSONBlogRecentPostDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined' && _dataBlogPostList != null)
        return true;

    return false;
}

function getJSONBlogRecentPostData() {
    return _dataBlogPostList['GetBlogPosts-return']['recentpost-list'];
}

function bindBlogRecentPosts() {
    jQuery(".module-blog-recent ul").loadTemplate(jQuery('.module-blog-recent .json-template'), getJSONBlogRecentPostData());

    //Blog Post Recent
    InsertDataAnalyticsAttributes(".module-blog-recent a", "cta");

    if (jQuery(".module-blog-recent ul li").length == 0) {
        jQuery(".module-blog-recent").hide();
    }
}

if (ComponentRegistry.AuthorRecentPosts && isJSONBlogRecentPostDataAvailable()) {
    $(function () {
        var IsVisible = jQuery('#ShowMostRecentInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            jQuery('.module-blog-recent').hide();
            return;
        }

        bindBlogRecentPosts();
    });
}

//////////////////////////
//BLOG POST LIST - AUTHORS
//////////////////////////
function isJSONBlogPostAuthorDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined' && _dataBlogPostList != null)
        return true;

    return false;
}

function getJSONBlogPostAuthorData() {
    localStorage.setItem("authorList", JSON.stringify(_dataBlogPostList['GetBlogPosts-return']['author-list']));
    return _dataBlogPostList['GetBlogPosts-return']['author-list'].slice(0, 8);
}

function bindBlogAuthors() {
    //load authors
    var imageHolder;  
    jQuery("#author-carousel .carousel-inner").loadTemplate(jQuery('.module-blog-authors .json-template'), getJSONBlogPostAuthorData());

    //set first author as active
    jQuery("#author-carousel .carousel-inner .item").eq(0).addClass('active');

    //Bug 200412: Hide the pagination dots if there is only one slide
    var authorCount = jQuery("#author-carousel .carousel-inner .item").length;
    var blogPostAuthor = jQuery("#author-carousel .carousel-inner .item-sm.blogpost").length;
    if (authorCount > 1 || blogPostAuthor > 1) {
        //create nav
        var indicators = "";
        for (ctr = 0; ctr < authorCount; ctr++) {
            indicators += '<li data-target="#author-carousel" data-slide-to="' + ctr + '"></li>';
        }
        jQuery("#author-carousel .carousel-indicators").html(indicators);

        //set first author as active
        jQuery("#author-carousel .carousel-inner .item").eq(0).addClass('active');
        jQuery("#author-carousel .carousel-indicators li").eq(0).addClass('active');

        //Blog Post List Full Bio
        InsertDataAnalyticsAttributes(".module-blog-authors #authors-carousel a", "cta");

        //Add launch data attributes to carousel
        jQuery("#author-carousel .carousel-indicators li").attr(dataContentType, "nav/paginate");
        jQuery("#author-carousel .carousel-indicators li").attr(linkName, "nav/paginate");
    }
    else if (authorCount == 1 || blogPostAuthor == 1) {
        jQuery('#author-carousel div ol.carousel-indicators').hide();
    }
    else {
        jQuery(".module-blog-authors").hide();
    }

    //generate author pop up content
    jQuery(".module-blog-authors .author-full-bio").loadTemplate(jQuery('.module-blog-authors .json-template-fullbio'), getJSONBlogPostAuthorData());
    imageHolder = jQuery(".module-blog-authors span.image-holder");
    setSpanAttributes(imageHolder);
    jQuery("span.image-holder").imageloader();
}

function setSpanAttributes(spans) {
    spans.each(function () {
        var src = jQuery(this).attr("src");
        var alt = jQuery(this).attr("alt");
        var title = jQuery(this).attr("title");

        jQuery(this).removeAttr("src alt title");

        jQuery(this).attr({
            "data-src": src,
            "data-alt": alt,
            "data-title": title
        });
    });
}

function BlogPostListAuthors() {
    //INIT
    bindBlogAuthors();

    //EVENT HANDLERS
    //add author show full bio event handler
    jQuery('.module-blog-authors a.cta, a.ctaViewAll').on("click", function (event) {
        event.preventDefault();
        var mainModal = jQuery("#main-modal");
        var linkId = this.id;
        if (this.id == "display-full-bio") {
            //get index of author
            var index = jQuery('#author-carousel .item.active').index();

            //ready pop up HTML content
            var content = jQuery('.author-full-bio > div').eq(index).html();

            //change pop up content
            jQuery('#main-modal #modal-full-bio .modal-body').html(content);

            $("#content-wrapper, .skip-main").attr("aria-hidden", "true");
            jQuery('#main-modal .modal-dialog').removeAttr('style');
            jQuery('#main-modal #modal-all-authors').hide();
            jQuery('#main-modal #modal-full-bio').show();
            jQuery('#main-modal #modal-all-authors-bio').hide();

        }
        //show pop up content
        if (this.id == "display-view-all") {
            var authors = JSON.parse(localStorage.getItem("authorList"));

            $('.modal-content .icon-arrowrightarrow').show();
            jQuery('#main-modal .modal-dialog').css('width', 'auto');
            jQuery('#main-modal #modal-full-bio').hide();
            jQuery('#main-modal #modal-all-authors-bio').hide();
            
            /*Display Authors Bio overlay */
            BindAuthorFullBio();


            jQuery("div.modal-content a.cta").on("click", function (event) {
                event.preventDefault();
                var authorObjSorted = $(JSON.parse(localStorage.getItem("authorList")).sort(SortAuthor)).eq($(event.target).data('author'))[0];
                if ($(window).width() < 768) {
                    $('.full-bio-back .no-underline.corporate-black').hide();
                }

                //Generate Templated Author Bio
                jQuery('#modal-all-authors-bio .modal-body').html(jQuery('.author-full-bio > div').eq(0).html());


                /* Override Templated Author Bio */
                $('#modal-all-authors-bio h4#authorname-desktop,h4#authorname-mobile').text(authorObjSorted.Name);
                $('#modal-all-authors-bio p').text(authorObjSorted.Long_Description);
                $('#modal-all-authors-bio img').attr('src', authorObjSorted.Url_Image);
                $('#modal-all-authors-bio img').attr('alt', authorObjSorted.Name);
                $('#modal-all-authors-bio img').attr('title', authorObjSorted.Name);
                $('#modal-all-authors-bio .social').html("")
                DisplaySocialLinks(authorObjSorted);

                //show pop up content
                $("#content-wrapper, .skip-main").attr("aria-hidden", "true");
                jQuery('#modal-all-authors').hide();
                jQuery('#modal-all-authors-bio').modal('show');
                jQuery('.modal-dialog').removeAttr('style');

            });

            jQuery('#modal-all-authors').show();
        }
            jQuery('#main-modal').modal('show');
            //SC8Upgrade - Bug 569271
            if ($('#scCrossPiece').length > 0) {
                ['modal-full-bio', 'modal-all-authors', 'modal-all-authors-bio'].forEach(function (id) {
                    var modalHeightAdjust = $('#scCrossPiece').height();
                    document.getElementById(id).style.marginTop = modalHeightAdjust + "px";
                });
            }


        $(".modal-backdrop, #main-modal .close").off("click").on("click", function () {
            $('.modal-content .icon-arrowrightarrow').hide();
            jQuery('.job-arrow-left').hide();
            $("#content-wrapper, .skip-main").attr("aria-hidden", "false");
        });

        $('.modal-content .full-bio-back a').on("click", function (event) {
            event.preventDefault();
            jQuery('.modal-content .carousel.slide').show();
            jQuery('#modal-all-authors').show();
            jQuery('#modal-all-authors-bio').modal('hide');
            jQuery('#main-modal .modal-dialog').css('width', 'auto');
        });

        jQuery(".modal-content .slide > .icon-arrowrightarrow").off("click").on("click", function () {
            ArrowRightClick($('.modal-content .carousel-inner'));
        });

        jQuery('.job-arrow-left').off("click").on("click", function () {
            ArrowLeftClick($('.modal-content .carousel-inner'));
        });

        function BindAuthorFullBio() {
            var indicators = "", fullBioText = "FULL BIO";

            if ($("#display-full-bio").length > 0) {
                fullBioText = $("#display-full-bio").text();
            }

            /* sort authors alphabetically before creating overlay */
            authors.sort(SortAuthor);

            for (ctr = 0; ctr < authors.length; ctr++) {
                indicators += '<div class="col-sm-4"><img src="' + authors[ctr].Url_Image + '"><div class="module-body"><h2 class="authorname-overlay">' + authors[ctr].Name + '</h2><a class="cta" data-author=' + ctr + ' href="#" title="' + fullBioText + '" ' + dataContentType + '="cta" ' + linkName + '="' + fullBioText.toLowerCase() + '">' + fullBioText + '</a><div class="hidden">' + authors[ctr].Long_Description + '</div></div></img></div>';
                jQuery("div.modal-content .carousel-inner").html(indicators);
            }
            if (isMobile()) {
                BlogAuthorCarousel(2);
            }
            else {
                BlogAuthorCarousel(3);
            }
        }

        function BlogAuthorCarousel(numOfAuthors) {
            var authorCount = $('.modal-content .carousel-inner .col-sm-4');
            var slideName = 'slide-';
            var slideCount = 0;
            for (ctr = 0; ctr < authorCount.length; ctr += numOfAuthors) {
                slideCount += 1;
                var isActive = "";
                if (slideCount == 1) {
                    isActive = "active";
                }
                else if (slideCount == 2) {
                    isActive = "next";
                }
                else { isActive = ""; }
                authorCount.slice(ctr, ctr + numOfAuthors).wrapAll("<div id='" + slideName + slideCount + "' class = 'item " + isActive + "'></div>");
            }
        }

        function DisplaySocialLinks(authorObjSorted) {
            if (authorObjSorted.Social_Linked_In.length > 0) {
                $('#modal-all-authors-bio .social').append('<span class="linkedin" title="LinkedIn"><a title="LinkedIn" href="' + authorObjSorted.Social_Linked_In + '" ' + dataContentType + '="cta" ' + linkName + '="linkedin"></a></span> ');
            }
            var twitterCount = authorObjSorted.Social_Twitter.lastIndexOf('=');
            var authorTwitter = authorObjSorted.Social_Twitter.substring(twitterCount + 1);
            if (authorTwitter.length > 0) {
                $('#modal-all-authors-bio .social').append('<span class="twitter" title="Twitter"><a title="Twitter" href="https://twitter.com/intent/user?screen_name=' + authorTwitter + '" ' + dataContentType + '="cta" ' + linkName + '="twitter"></a></span>')
            }
            var emailCount = authorObjSorted.Social_Email.lastIndexOf(':');
            var authorEmail = authorObjSorted.Social_Email.substring(emailCount + 1);
            if (authorEmail.length > 0) {
                $('#modal-all-authors-bio .social').append('<span class="email" title="Email"><a title="Email" href="mailto:' + authorEmail + '" ' + dataContentType + '="cta" ' + linkName + '="email"></a></span>')
            }
        }

        function ArrowRightClick($items) {
            var $carouselInner = $('.modal-content .carousel-inner');
            var next = $carouselInner.find(".next").index();
            $carouselInner.find('.prev.left').removeClass('prev left');
            $carouselInner.children().eq(next - 1).removeClass('active').addClass('prev left');
            $carouselInner.children().eq(next).removeClass('next').addClass('active');
            $carouselInner.children().eq(next + 1).addClass('next');

            if ((next >= ($carouselInner.children().length - 1)) || $carouselInner.children().length == 1) {
                $(".modal-content .slide > .icon-arrowrightarrow").hide();
            }
            $(".job-arrow-left").show();
        }

        function ArrowLeftClick($items) {
            var prev = $items.find('.prev').index();
            $items.find('.next').removeClass('next');
            $items.children().eq(prev + 1).removeClass('active').addClass('next');
            $items.children().eq(prev).removeClass('prev left').addClass('active');

            if (prev <= 0) {
                $(".job-arrow-left").hide();
            }
            else {
                $items.children().eq(prev - 1).addClass('prev left');
            }
            $(".modal-content .icon-arrowrightarrow").show();
        }

    });

    var authorCount = _dataBlogPostList['GetBlogPosts-return']['author-list'].length;
    if ($('#ShowAuthorViewAll').val() == "True" && authorCount > 8) {
        // Show Link
        jQuery('#view-authors').find('a').html(jQuery("#AuthorViewAll").val());
        
        var $viewAllLink = jQuery("#view-authors a");

        $viewAllLink.attr(dataContentType, "cta");

        var viewAllLinkText = $viewAllLink.text();

        viewAllLinkText = (viewAllLinkText !== undefined && viewAllLinkText !== null) ? viewAllLinkText.toLowerCase() : "";

        if (viewAllLinkText)
            $viewAllLink.attr(linkName, viewAllLinkText);
    }
}

// Sorts Author by Name
function SortAuthor(a, b) {
    if (a.Name < b.Name)
        return -1;
    if (a.Name > b.Name)
        return 1;
    return 0;
}

if ((ComponentRegistry.BlogPostAuthors || ComponentRegistry.BlogArchiveAuthor) && isJSONBlogPostAuthorDataAvailable()) {
    $(function () {
        BlogPostListAuthors();
        hideEmptySocialIcons();
    });
}

//////////////////////////
//BLOG POST LIST - TAGS
//////////////////////////

function isJSONBlogPostTagDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined' && _dataBlogPostList != null)
        return true;

    return false;
}

function getJSONBlogPostTagData() {
    return _dataBlogPostList['GetBlogPosts-return']['tag-list'];
}

function bindBlogTags() {
    // Hide Popular tags on live and preview when no tags to display
    var isEditMode = jQuery('.module-blog-tags.edit-mode');
    if (isEditMode.length > 0) {
        jQuery(".module-blog-tags ul").loadTemplate(jQuery('.module-blog-tags .json-template'), getJSONBlogPostTagData());
    }
    else {
        if (getJSONBlogPostTagData().length > 0) {
            jQuery(".module-blog-tags ul").loadTemplate(jQuery('.module-blog-tags .json-template'), getJSONBlogPostTagData());

            //Blog Post Tags and Blog Post List Tags
            InsertDataAnalyticsAttributes(".module-blog-tags a", "cta");                  
        }
        else {
            jQuery(".module-blog-tags").hide();
        }
    }
}

function BlogPostTags() {
    //INIT
    bindBlogTags();

    //EVENT HANDLERS
    //add tag event handler
    //jQuery('.module-blog-tags a').on("click", function (event) {
    //    //event.preventDefault();
    //});
}

if ((ComponentRegistry.BlogPostTags || ComponentRegistry.BlogArchiveTags) && isJSONBlogPostTagDataAvailable()) {
    $(function () {
        var IsVisible = jQuery('#ShowPopularTagsInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            jQuery('.module-blog-tags').hide();
            return;
        }

        BlogPostTags();
    });
}

//////////////////////////
//BLOG POST LIST - ARCHIVE YEARS
//////////////////////////
function isJSONBlogPostYearDataAvailable() {
    if (typeof _dataBlogPostList != 'undefined' && _dataBlogPostList != null)
        return true;

    return false;
}

function getJSONBlogPostYearData() {
    return _dataBlogPostList['GetBlogPosts-return']['year-published-list'];
}

function getJSONBlogArchiveLink() {
    return _dataBlogPostList['GetBlogPosts-return']['blog-archive-link'];
}

function bindBlogArchiveYears() {
    var isByMonth = jQuery('#ShowArchivesByMonth').val() === "True";
    var templateSelector = '.module-blog-archive .json-template';
    if (isByMonth) {
        templateSelector = '.module-blog-archive .json-template-month';
    }
    jQuery(".module-blog-archive ul").loadTemplate(jQuery(templateSelector), getJSONBlogPostYearData());

    //Blog Post Archive Years and Blog Post List Archive Years
    InsertDataAnalyticsAttributes(".module-blog-archive a", "cta");

    if (jQuery(".module-blog-archive ul li").length == 0) {
        jQuery(".module-blog-archive").removeClass("hidden-xs").hide();
    }
    else {
        //add ALL
        jQuery(".module-blog-archive ul").append('<li><a href="#" title="Show All" ' + dataContentType + '="cta" ' + linkName + '="show all">Show All</a></li>');
    }
}

function filterPostsByYear(year) {
    if (year == 'Show All' || year == "show_all") {
        jQuery('.module-blog-featured-post').removeClass('hidden');
        return getJSONBlogPostData();
    } else {
        jQuery('.module-blog-featured-post').addClass('hidden');
        return $.grep(getJSONBlogPostData(), function (element, index) {
            return element.dateYear == year;
        });
    }
}

function BlogArchiveYears() {
    //INIT
    bindBlogArchiveYears();
    var isByMonth = jQuery('#ShowArchivesByMonth').val() === "True";
    //EVENT HANDLERS
    //add archive event handler
    jQuery('.module-blog-archive a').on("click", function (event) {
        event.preventDefault();
        var $this = jQuery(this);
        var year = $this.text();
        var month = $this.text();
        if (year == 'Show All') {
            year = "show_all";
            month = "show_all";
        }
        else if (isByMonth) {
            year = $this.data('year');
            month = $this.data('month');
        }
        else {
            year = $this.attr('title');
        }

        var author = '';
        if (jQuery('#authorId').length == 1) {
            author = jQuery('#authorId').val().replace(/ /g, "%20");
        }

        var industry = jQuery('#IndustryId').val();
        var subject = jQuery('#SubjectId').val();
        var singleIndexId = jQuery('#SingleIndexId').val();
        var currentSite = jQuery('#currentSite').val();
        var blogArchiveLink = getJSONBlogArchiveLink();
        //var urlLocation = location.protocol + "//" + location.hostname + path + "/home/blogs/blogarchive?year=" + year + "&industry=" + industry + "&subject=" + subject + "&source=" + singleIndexId;                
        var urlLocation = constructUrlLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, isByMonth, month);
        //function constructUrlLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, month) {

        window.open(urlLocation, "_self");

    });
}

function BlogPostArchiveYears() {
    //INIT
    bindBlogArchiveYears();
    var isByMonth = jQuery('#ShowArchivesByMonth').val() === "True";
    //EVENT HANDLERS
    //add archive event handler
    jQuery('.module-blog-archive a').on("click", function (event) {
        event.preventDefault();
        var $this = jQuery(this);
        var year = $this.text();
        var month = $this.text();
        if (year == 'Show All') {
            year = "show_all";
            month = "show_all";
        }
        else if (isByMonth) {
            year = $this.data('year');
            month = $this.data('month');
        }
        else {
            year = $this.attr('title');
        }

        var author = '';
        if (jQuery('#authorId').length == 1) {
            author = jQuery('#authorId').val().replace(/ /g, "%20");
        }
        else if (ComponentRegistry.BlogPost) {
            author = _dataBlogPostList['GetBlogPosts-return']['author-list'][0].AuthorId;
        }
        else {
            var authors = jQuery('#authorId').map(function () { return jQuery(this).text(); });
        }

        var industry = jQuery('#IndustryId').val() !== undefined ? jQuery('#IndustryId').val() : "";
        var subject = jQuery('#SubjectId').val() !== undefined ? jQuery('#SubjectId').val() : "";
        var singleIndexId = jQuery('#SingleIndexId').val();
        var currentSite = jQuery('#currentSite').val();
        var blogArchiveLink = getJSONBlogArchiveLink();
        //var urlLocation = location.protocol + "//" + location.hostname + path + "/home/blogs/blogarchive?year=" + year + "&author=" + author + "&source=" + singleIndexId;
        //var urlLocation = location.protocol + "//" + location.hostname + path + "/home/blogs/blogarchive?year=" + year + "&industry=" + industry + "&subject=" + subject + "&source=" + singleIndexId;
        //var urlLocation = location.protocol + "//" + location.hostname + _dataBlogArchive.BlogArchive.BlogArchiveLink + "?year=" + year + "&industry=" + industry + "&subject=" + subject + "&source=" + singleIndexId;        
        var urlLocation = constructUrlLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, isByMonth, month);
        //function constructUrlLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, isByMonth, month) {

        window.open(urlLocation, "_self");
    });
}

if (ComponentRegistry.BlogPostArchiveYears && isJSONBlogPostYearDataAvailable()) {
    $(function () {
        var IsVisible = jQuery('#ShowArchivesInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            jQuery('.module-blog-archive').hide();
            return;
        }

        BlogPostArchiveYears();

        var listYearsByIndustrySubject = jQuery('#ListYearsByIndustrySubject');

        if (typeof listYearsByIndustrySubject !== 'undefined') {
            if (listYearsByIndustrySubject.val())
                BlogArchiveYears();
        }
    });
}

if ((ComponentRegistry.BlogPostListArchiveYears || ComponentRegistry.BlogArchiveYears) && isJSONBlogPostYearDataAvailable()) {
    $(function () {
        var IsVisible = jQuery('#ShowArchivesInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            jQuery('.module-blog-archive').hide();
            return;
        }

        BlogArchiveYears();
    });
}

//////////////////////////
//BLOG POST - MULTI SUBJECT - AUTHORS
//////////////////////////

if (ComponentRegistry.BlogPostMultipleSubjectAuthors) {
    jQuery('#author-carousel').on("click", ".module-body a, .item-sm > a", function (event) {
        event.preventDefault();

        //get index of author
        var index = jQuery(this).attr('href').substring('1');

        //ready pop up HTML content
        var content = jQuery('.author-full-bio > div').eq(index).html();

        //change pop up content
        jQuery('#main-modal .modal-body').html(content);

        //show pop up content
        jQuery('#main-modal').modal('show');
    });

    $(function () {
        hideEmptySocialIcons();
    });
}

// RMT 2279 Appearance of Social Media Icons in BlogPostAuthorsModule 
function hideEmptySocialIcons() {
    jQuery("div.social > span.linkedin > a, div.social > span.twitter > a ,div.social > span.email > a").each(function () {
        var hrefValue = jQuery(this).attr("href");
        jQuery(this).attr("data-analytics-content-type", "cta");
        if (jQuery(this).parent().hasClass("linkedin")) {
            jQuery(this).attr("data-analytics-link-name", "linkedin");
        }
        if (jQuery(this).parent().hasClass("twitter")) {
            jQuery(this).attr("data-analytics-link-name", "twitter");
        }
        if (jQuery(this).parent().hasClass("email")) {
            jQuery(this).attr("data-analytics-link-name", "email");
        }

        if (hrefValue === "" || hrefValue === "mailto:" || hrefValue.split("=")[1] === "")
            jQuery(this).css('display', 'none');
    });
}

$(function () {
    var urlParams = window.location.search.substring(1);
    var blogTagParam = getParam(urlParams, "blogtag");

    if (blogTagParam != null) {
        jQuery(".module-blog-tags li[value='" + blogTagParam + "']").find('a').addClass('disabled-tags');

        var disabledTag = jQuery('.disabled-tags');

        if (disabledTag.length > 0) {
            var tag = disabledTag.text();
            disabledTag.replaceWith("<span class='disabled-tags'>" + tag + "</span>")
        }
    }
});

function getParam(urlParams, param) {
    if (urlParams != "") {
        var urlVariables = urlParams.split('&');
        for (var i = 0; i < urlVariables.length; i++) {
            var paramName = urlVariables[i].split('=')[0];
            if (paramName.toLowerCase() == param) {
                return urlVariables[i].split('=')[1];
            }
        }
    }
    return null;
}

function constructUrlLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, isByMonth, month) {
    var urlLocation = location.protocol + "//" + location.hostname;
    var targetPath = "/" + currentSite + "/home/blogs/blogarchive";
    //var isBlogArchiveModuleDisplayed = jQuery('#blog-archive-years-module') && jQuery('#blog-archive-years-module').is(':visible');

    if (blogArchiveLink !== "") { // use custom archive page
        targetPath = blogArchiveLink;
    }

    urlLocation = urlLocation + targetPath + "?year=" + year + "&industry=" + industry + "&subject=" + subject + "&source=" + singleIndexId;

    if (isByMonth) {
        urlLocation += "&month=" + month;
    }

    return urlLocation;
}

//Adds content type and link name attributes to clickables
function InsertDataAnalyticsAttributes(elementSelector, contentTypeValue) {

    var $targetLinks = jQuery(elementSelector);

    for (var i = 0; i < $targetLinks.length; i++) {

        var $targetLink = jQuery($targetLinks[i]); 
        
        $targetLink.attr(dataContentType, contentTypeValue);

        var linkText = $targetLink.text();
        linkText = linkText && linkText !== null ? linkText.trim().toLowerCase() : "";

        if (linkText)
            $targetLink.attr(linkName, linkText);

    }

}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BlogPostListModule.js
// version="5"

if (ComponentRegistry.BlogPostListModule) {
$(function () {
        BlogPostListModule.Init();
    });

    $(window).on("scroll", function () {
        if (BlogPostListModule.Data.IsBlogPostDataAvailable) {
            if (isMobile()) {
                $('#btn-blogs-load-more').on('click', function () {
                    BlogPostListModule.BlogsLazyLoad();
                });
            }
            else {
                var locationContainerTop, locationScrollTop, locationHeight;
                var totalHeight, scrolledFromTop, visibleHeight;

                locationContainerTop = $('.module-blog-post-list').offset().top;
                locationScrollTop = $(window).scrollTop();
                locationHeight = $('.module-blog-post-list').height();
                totalHeight = document.body.offsetHeight;
                scrolledFromTop = locationScrollTop - locationContainerTop;
                visibleHeight = document.documentElement.clientHeight;

                if (visibleHeight + scrolledFromTop >= locationHeight) {
                    BlogPostListModule.BlogsLazyLoad();
                }
            }
        }
    });

    var BlogPostListModule = (function () {
        var urlArr = window.location.href.split("/");

        var BlogPostList = {

            // Code initialization
            Init: function () {
                BlogPostList.SetBlogPostListModuleData();
                if (BlogPostList.Data.IsBlogPostDataAvailable) {
                    BlogPostList.SetBlogPostParameters();
                    BlogPostList.BindBlogPosts(BlogPostList.GetJSONBlogPostData_Es());

                    jQuery('.module-blog-post-list button').on("click", function (event) {
                        event.preventDefault();
                        jQuery('.module-blog-post-list ul li[class=hidden-xs]').removeClass('hidden-xs');
                    });

                    BlogPostList.LoadSocialShare();
                    BlogPostList.Data.EnableBlogsLazyLoad = true;
                    BlogPostList.AddBlogPostListAnalytics();
                }
            },

            // Initializes blog post list module data
            Data: {
                IsBlogPostDataAvailable: false,
                BlogsList: null,
                ErrorMessage: "",
                NoResultsMessage: "",
                IsPageEditor: "",
                EnableBlogsLazyLoad: false,
                Result: urlArr[0] + "//" + urlArr[2],
                BlogsParam: {
                    Author: "",
                    BlogTag: "",
                    CountrySite: "",
                    IndustryId: "",
                    Month: "",
                    RelativePath: "",
                    SizeBlogAuthors: "",
                    SizeBlogPosts: "",
                    SizeBlogTags: "",
                    SubjectId: "",
                    Year: "",
                    TotalBlogsRetrieved: 0,
                    StartIndex: 0,
                    Path: ""
                },
                DefaultImage: $('.module-blog-post-list').data("defaultimage"),
                DefaultImageAlt: $('.module-blog-post-list').data("defaultimagealt")
            },

            // Sets blog post list module data
            SetBlogPostListModuleData: function () {
                var blogPostListModuleData = jQuery('#blog-post-list-module-data');

                if (blogPostListModuleData != null && blogPostListModuleData.length > 0) {
					BlogPostList.Data.BlogsList = JSON.parse(blogPostListModuleData.text());
                    BlogPostList.Data.ErrorMessage = blogPostListModuleData.data("error-message");
                    BlogPostList.Data.NoResultsMessage = blogPostListModuleData.data("noresults-message");
                    BlogPostList.Data.IsPageEditor = blogPostListModuleData.data("is-page-editor");
                    BlogPostList.Data.IsBlogPostDataAvailable = typeof BlogPostList.Data.BlogsList != 'undefined' && BlogPostList.Data.BlogsList != null;
                }
            },

            // Sets needed parameters for blog post list module
            SetBlogPostParameters: function () {
                var blogPostParameters = BlogPostList.Data.BlogsList['GetBlogPosts-return']['blog-post-list']['params'];

                if (blogPostParameters != null || blogPostParameters.length > 0) {
                    BlogPostList.Data.BlogsParam.Author = blogPostParameters['Author'] != null ? blogPostParameters['Author'] : "";
                    BlogPostList.Data.BlogsParam.BlogTag = blogPostParameters['BlogTag'] != null ? blogPostParameters['BlogTag'] : "";
                    BlogPostList.Data.BlogsParam.CountrySite = blogPostParameters['CountrySite'] != null ? blogPostParameters['CountrySite'] : "";
                    BlogPostList.Data.BlogsParam.IndustryId = blogPostParameters['IndustryId'] != null ? blogPostParameters['IndustryId'] : "";
                    BlogPostList.Data.BlogsParam.Month = blogPostParameters['Month'] != null ? blogPostParameters['Month'] : "";
                    BlogPostList.Data.BlogsParam.RelativePath = blogPostParameters['RelativePath'] != null ? blogPostParameters['RelativePath'] : "";
                    BlogPostList.Data.BlogsParam.SizeBlogAuthors = blogPostParameters['SizeBlogAuthors'] != null ? blogPostParameters['SizeBlogAuthors'] : "";
                    BlogPostList.Data.BlogsParam.SizeBlogPosts = blogPostParameters['SizeBlogPosts'] != null ? blogPostParameters['SizeBlogPosts'] : "";
                    BlogPostList.Data.BlogsParam.SizeBlogTags = blogPostParameters['SizeBlogTags'] != null ? blogPostParameters['SizeBlogTags'] : "";
                    BlogPostList.Data.BlogsParam.SubjectId = blogPostParameters['SubjectId'] != null ? blogPostParameters['SubjectId'] : "";
                    BlogPostList.Data.BlogsParam.Year = blogPostParameters['Year'] != null ? blogPostParameters['Year'] : "";
                    BlogPostList.Data.BlogsParam.Path = '/api/sitecore/BlogPostListModule/GetBlogPostData';
                    BlogPostList.Data.BlogsParam.TotalBlogsRetrieved = parseInt(jQuery("#TotalBlogResult").val());
                    BlogPostList.Data.BlogsParam.StartIndex = BlogPostList.Data.BlogsParam.SizeBlogPosts;                
                }
            },

            // Ajax call
            GetJSONBlogPostData_Es: function () {
                var JSONblogPosts = "";

                $.ajax({
                    url: BlogPostList.Data.BlogsParam.Path ,
                    type: "POST",
                    data: JSON.stringify({
                        Author: BlogPostList.Data.BlogsParam.Author,
                        BlogTag: BlogPostList.Data.BlogsParam.BlogTag,
                        CountrySite: BlogPostList.Data.BlogsParam.CountrySite,
                        IncludeBlogAuthorResult: false,
                        IncludeBlogPostsResult: true,
                        IncludeBlogTagResult: false,
                        IncludeBlogPostsDate: false,
                        IndustryId: BlogPostList.Data.BlogsParam.IndustryId,
                        Month: BlogPostList.Data.BlogsParam.Month,
                        RelativePath: BlogPostList.Data.BlogsParam.RelativePath,
                        BlogAuthorsSize: BlogPostList.Data.BlogsParam.SizeBlogAuthors,
                        BlogPostsSize: BlogPostList.Data.BlogsParam.SizeBlogPosts,
                        BlogTagsSize: BlogPostList.Data.BlogsParam.SizeBlogTags,
                        SubjectId: BlogPostList.Data.BlogsParam.SubjectId,
                        Year: BlogPostList.Data.BlogsParam.Year,
                        From: 0,
                    }),
                    contentType: "application/json",
                    async: false,
                    error: function (res) {
                        BlogPostList.Data.Result = null;
                    },
                    success: function (res) {
                        JSONblogPosts = JSON.parse(res);
                    }
                });
                BlogPostList.ReplaceNoImageToDefaultImage(JSONblogPosts);
                return JSONblogPosts;
            },

            // Replaces blank images to default image
            ReplaceNoImageToDefaultImage: function (JsonBlogPosts) {
                if (JsonBlogPosts != null) {
                    for (var i = 0; i < JsonBlogPosts.length; i++) {
                        if (JsonBlogPosts[i].Picture == "") {
                            JsonBlogPosts[i].Picture = BlogPostList.Data.DefaultImage;
                            JsonBlogPosts[i].Picture_Alt = BlogPostList.Data.DefaultImageAlt;
                        }
                    }
                }
            },

            // Hides Comment counter for zero comments and post image placeholder when no post image is provided
            HideCommentsAndPostImage: function (blogPostList) {
                blogPostList.find("span.blog-comment span:not([class])").each(function () {
                    var $this = jQuery(this);
                    if ($this.text() == '0') {
                        $this.parent().addClass('hidden');
                    }
                });
                blogPostList.find("span.title.clickable").each(function () {
                    var $this = jQuery(this);
                    $this.addClass('hidden');
                });
                blogPostList.find("img.img-responsive.post-image").each(function () {
                    var $this = jQuery(this);
                    if (!$this.attr("src")) {
                        $this.hide();
                    }
                });
            },

            // Hides social icons whenever its empty
            HideEmptySocialIcons: function () {
                jQuery("div.social > span.linkedin > a, div.social > span.twitter > a ,div.social > span.email > a").each(function () {
                    var hrefValue = jQuery(this).attr("href");
                    if (hrefValue === "" || hrefValue === "mailto:" || hrefValue.split("=")[1] === "")
                        jQuery(this).css('display', 'none');
                });
            },

            // Loads social share in every blog listed
            LoadSocialShare: function () {
                var socialShares = jQuery('.social-likes-post.post-is-loaded');
                if (socialShares.length > 0 && typeof socialShares != undefined) {
                    socialShares.each(function () {
                        jQuery(this).attr('data-url', BlogPostList.Data.Result + jQuery(this).attr('data-url'));
                    });
                    jQuery('.social-likes-post').socialLikes();
                    jQuery('.social-likes-post').removeClass('post-is-loaded');
                    BlogPostList.HideEmptySocialIcons();
                }
            },

            // Lists blogs in the blog post list module
            BindBlogPosts: function (JSONblogPosts) {
                if (JSONblogPosts != "blog-result-is-null") {
                    if (JSONblogPosts.length > 0) {
                        var blogPostList = jQuery(".module-blog-post-list ul");
                        blogPostList.loadTemplate(jQuery('.module-blog-post-list .json-template'), JSONblogPosts);
                        blogPostList.find('li').slice(0, 4).removeClass('hidden-xs');

                        BlogPostList.HideCommentsAndPostImage(blogPostList);
                    }
                    else if (BlogPostList.Data.IsPageEditor == 'True') {
                        var blogPostList = jQuery(".module-blog-post-list");
                        blogPostList.append(BlogPostList.Data.NoResultsMessage);
                    }

                    if (BlogPostList.Data.BlogsParam.TotalBlogsRetrieved <= BlogPostList.Data.BlogsParam.SizeBlogPosts) {
                        $('#btn-blogs-load-more').addClass('clicked');
                    }
                }
                else {
                    var blogPostList = jQuery(".module-blog-post-list");
                    blogPostList.text(BlogPostList.Data.ErrorMessage);
                }
            },

            // Blog post list module lazy load
            BlogsLazyLoad: function () {
                if (BlogPostList.Data.BlogsParam.StartIndex < BlogPostList.Data.BlogsParam.TotalBlogsRetrieved && BlogPostList.Data.EnableBlogsLazyLoad) {
                    $('#pre-loader').css("display", "block");
                    BlogPostList.Data.EnableBlogsLazyLoad = false;
                    $.ajax({
                        url: BlogPostList.Data.BlogsParam.Path,
                        type: "POST",
                        data: JSON.stringify({
                            Author: BlogPostList.Data.BlogsParam.Author,
                            BlogTag: BlogPostList.Data.BlogsParam.BlogTag,
                            CountrySite: BlogPostList.Data.BlogsParam.CountrySite,
                            IncludeBlogAuthorResult: false,
                            IncludeBlogPostsResult: true,
                            IncludeBlogTagResult: false,
                            IncludeBlogPostsDate: false,
                            IndustryId: BlogPostList.Data.BlogsParam.IndustryId,
                            Month: BlogPostList.Data.BlogsParam.Month,
                            RelativePath: BlogPostList.Data.BlogsParam.RelativePath,
                            BlogAuthorsSize: BlogPostList.Data.BlogsParam.SizeBlogAuthors,
                            BlogPostsSize: BlogPostList.Data.BlogsParam.SizeBlogPosts,
                            BlogTagsSize: BlogPostList.Data.BlogsParam.SizeBlogTags,
                            SubjectId: BlogPostList.Data.BlogsParam.SubjectId,
                            Year: BlogPostList.Data.BlogsParam.Year,
                            From: BlogPostList.Data.BlogsParam.StartIndex,
                        }),
                        contentType: "application/json",
                        error: function (res) {
                            BlogPostList.Data.Result.result = null;
                        },
                        success: function (res) {
                            BlogPostList.Data.BlogsParam.StartIndex += BlogPostList.Data.BlogsParam.SizeBlogPosts;

                            if (BlogPostList.Data.BlogsParam.StartIndex >= BlogPostList.Data.BlogsParam.TotalBlogsRetrieved) {
                                jQuery('#btn-blogs-load-more').addClass('clicked');
                            }

                            var blogPostList = jQuery(".module-blog-post-list ul");
                            var JSONblogPosts = JSON.parse(res);
                            BlogPostList.ReplaceNoImageToDefaultImage(JSONblogPosts);
                            blogPostList.loadTemplate(jQuery('.module-blog-post-list .json-template'), JSONblogPosts, { append: true });
                            BlogPostList.HideCommentsAndPostImage(blogPostList);
                            BlogPostList.LoadSocialShare();
                            BlogPostList.AddBlogPostListTitleAnalytics();
                        },
                        complete: function () {
                            $('#pre-loader').css("cssText", "display: none !important;");
                            BlogPostList.Data.EnableBlogsLazyLoad = true;
                        }
                    });
                }
            },

            // Blog post list module analytics
            AddBlogPostListAnalytics: function () {
                BlogPostList.AddBlogPostListTitleAnalytics();
                BlogPostList.AddBlogPostListReadPostAnalytics();
            },

            // Analytics for Title
            AddBlogPostListTitleAnalytics: function () {
                var $blogPostListElem = jQuery(".blog-post-list-title");
                var indx = 0;

                while (indx < $blogPostListElem.length) {
                    var $blogPostItem = jQuery($blogPostListElem[indx]);
                    var blogPostText = $blogPostItem && $blogPostItem.text().length ? $blogPostItem.text().toLowerCase().trim() : "";
                    if (blogPostText.length) {
                        $blogPostItem.attr("data-linkaction", blogPostText);
                        $blogPostItem.attr("data-analytics-link-name", blogPostText);
                    }
                    indx++;
                }
            },

            // Analytics for Read Post
            AddBlogPostListReadPostAnalytics: function () {
                var $readPostElem = jQuery(".new-blog-post-list .read-post");
                var readPostText = $readPostElem.length ? $readPostElem.eq(0).text() : "";
                if (readPostText.length) {
                    readPostText = readPostText.toLowerCase().trim();
                    $readPostElem.attr("data-linkaction", readPostText);

                }
            }
        };

        return BlogPostList;
    })();
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BlogPostListArchiveModule.js
// version="2"

if (ComponentRegistry.BlogPostListArchive) {
    $(function () {
        BlogArchiveModule.Init();
    });

    $(document).on("click touch", function (event) {
        $('.archive-module .btn-group.dropdown').removeClass("open");
    });

    var BlogArchiveModule = (function () {
        var BlogArchive = {

            // Code initialization
            Init: function () {
                BlogArchive.SetBlogArchiveModuleData();
                if (BlogArchive.Data.IsBlogArchiveDataAvailable) {
                    BlogArchive.SetBlogArchiveModuleData();
                    BlogArchive.SetBlogArchiveModuleVisibilityInMobile();
                    BlogArchive.ShowDropdownItems();
                }
                BlogArchive.AddArchiveAnalytics();
            },

            // Initializes blog archive module data
            Data: {
                IsBlogArchiveDataAvailable: false,
                BlogArchiveData: null,
                IsByMonth: false,
                DropdownData: "0",
                DropdownElem: ".module-blog-archive .dropdown-toggle",
                DropdownItems: ".new-blog-post-list-archive .dropdown-menu li",
                ShowArchivesByMonth: "#ShowArchivesByMonth",
                NumberOfMonths: "#NumberOfMonthsToBeDisplayed",
                ShowArchivesInMobile: "#ShowArchivesInMobile",
                IndustryID: "#IndustryId",
                SubjectID: "#SubjectId",
                SingleSubjectIndexID: "#SingleIndexId",
                CurrentSite: "#currentSite",
                ShowAllDictionaryID: "#ShowAllDictionary",
                ShowAllDictionaryValue: "Show All"
            },

            // Sets blog archive module data
            SetBlogArchiveModuleData: function () {
                var blogArchiveModuleData = jQuery("#blog-post-list-archive-data");

                if (blogArchiveModuleData != null && blogArchiveModuleData.length > 0) {
                    BlogArchive.Data.BlogArchiveData = JSON.parse(blogArchiveModuleData.text());
                    BlogArchive.Data.IsBlogArchiveDataAvailable = typeof BlogArchive.Data.BlogArchiveData != "undefined" && BlogArchive.Data.BlogArchiveData != null;
                    BlogArchive.Data.IsByMonth = jQuery(BlogArchive.Data.ShowArchivesByMonth).val() === "True";
                    BlogArchive.Data.DropdownData = jQuery(BlogArchive.Data.NumberOfMonths).val() !== "" ? jQuery(BlogArchive.Data.NumberOfMonths).val() : "empty";
                    BlogArchive.Data.ShowAllDictionaryValue = jQuery(BlogArchive.Data.ShowAllDictionaryID).val() !== "" ? jQuery(BlogArchive.Data.ShowAllDictionaryID).val() : "Show All";
                }
            },

            // Sets blog archive module visibility in mobile view
            SetBlogArchiveModuleVisibilityInMobile: function () {
                var showArchivesInMobile = jQuery(BlogArchive.Data.ShowArchivesInMobile).val() === "True";

                if (isMobile() && !showArchivesInMobile) {
                    jQuery(".module-blog-archive").hide();
                } else {
                    BlogArchive.BlogPostArchiveModuleYears();
                }
            },

            // Gets blog archive module dropdown values
            GetJSONBlogPostYearData: function () {
                return BlogArchive.Data.BlogArchiveData["GetBlogPosts-return"]["blog-post-list"]["year-published-list"];
            },

            // Gets custom blog archive link
            GetJSONBlogArchiveLink: function () {
                return BlogArchive.Data.BlogArchiveData["GetBlogPosts-return"]["blog-post-list"]["blog-archive-link"];
            },

            // Handles overall functionality of blog archive module
            BlogPostArchiveModuleYears: function () {
                BlogArchive.BindBlogArchiveModuleYears();

                jQuery(".module-blog-archive a").on("click", function (event) {
                    event.preventDefault();
                    var $this = jQuery(this);
                    var year = $this.text();
                    var month = $this.text();
                    if (year === "Show All") {
                        year = "show_all";
                        month = "show_all";
                    }
                    else if (BlogArchive.Data.IsByMonth) {
                        year = $this.data("year");
                        month = $this.data("month");
                    }
                    else {
                        year = $this.attr("title");
                    }

                    var industry = jQuery(BlogArchive.Data.IndustryID).val() !== undefined ? jQuery(BlogArchive.Data.IndustryID).val() : "";
                    var subject = jQuery(BlogArchive.Data.SubjectID).val() !== undefined ? jQuery(BlogArchive.Data.SubjectID).val() : "";
                    var singleIndexId = jQuery(BlogArchive.Data.SingleSubjectIndexID).val();
                    var currentSite = jQuery(BlogArchive.Data.CurrentSite).val();
                    var blogArchiveLink = BlogArchive.GetJSONBlogArchiveLink();
                    var urlLocation = BlogArchive.ConstructURLLocation(currentSite, year, industry, subject, singleIndexId, blogArchiveLink, BlogArchive.Data.IsByMonth, month);

                    window.open(urlLocation, "_self");
                });
            },

            // Binds blog archive module dropdown data
            BindBlogArchiveModuleYears: function () {
                var templateSelector = ".module-blog-archive .json-template";

                if (BlogArchive.Data.IsByMonth) {
                    templateSelector = ".module-blog-archive .json-template-month";
                }

                jQuery(".module-blog-archive ul").loadTemplate(jQuery(templateSelector), BlogArchive.GetJSONBlogPostYearData());

                if (jQuery(".module-blog-archive ul li").length == 0) {
                    jQuery(".module-blog-archive").removeClass("hidden-xs").hide();
                }
                else {
                    jQuery(".module-blog-archive ul").append("<li><a href='#' title='" + BlogArchive.Data.ShowAllDictionaryValue + "' data-analytics-content-type='cta'>" + BlogArchive.Data.ShowAllDictionaryValue + "</a></li>");
                }
            },

            // Constructs correct archive URL
            ConstructURLLocation: function (currentSite, year, industry, subject, singleIndexId, blogArchiveLink, isByMonth, month) {
                var urlLocation = location.protocol + "//" + location.hostname;
                var targetPath = "/" + currentSite + "/home/blogs/blogarchive";

                if (blogArchiveLink !== "" && blogArchiveLink !== "/") {
                    targetPath = blogArchiveLink;
                }

                urlLocation = urlLocation + targetPath + "?year=" + year + "&industry=" + industry + "&subject=" + subject + "&source=" + singleIndexId;

                if (isByMonth) {
                    urlLocation += "&month=" + month;
                }

                return urlLocation;
            },

            // Shows blog archive dropdown items based on the number of items set in NumberOfMonthsToBeDisplayed field
            ShowDropdownItems: function () {
                if (BlogArchiveModule.Data.IsByMonth) {
                    var dropdownItemsCnt = jQuery(BlogArchive.Data.DropdownItems).length;
                    BlogArchive.Data.DropdownData = BlogArchive.Data.DropdownData === "empty" ? dropdownItemsCnt : BlogArchive.Data.DropdownData;

                    for (var i = 0; i < dropdownItemsCnt; i++) {
                        if (i >= BlogArchive.Data.DropdownData && i !== dropdownItemsCnt - 1) {
                            jQuery(BlogArchive.Data.DropdownItems)[i].classList.add("hidden");
                        }
                    }
                }

                jQuery("#BlogPostListArchiveDropdown").addClass("show");
            },

            // Blog archive module analytics
            AddArchiveAnalytics: function () {
                BlogArchive.AddArchiveDropdownElemAnalytics();
                BlogArchive.AddArchiveDropdownAnalytics();
            },

            // Analytics for blog archive module dropdown items
            AddArchiveDropdownElemAnalytics: function () {
                var $blogArchiveItems = jQuery(".module-blog-archive ul li a");
                var indx = 0;

                while (indx < $blogArchiveItems.length) {
                    var $blogArchive = jQuery($blogArchiveItems[indx]);
                    var blogArchiveText = $blogArchive && $blogArchive.text().length ? $blogArchive.text().toLowerCase().trim() : "";
                    if (blogArchiveText.length) {
                        $blogArchive.attr("data-linkaction", blogArchiveText);
                        $blogArchive.attr("data-analytics-link-name", blogArchiveText);
                    }
                    indx++;
                }
            },

            // Analytics for blog archive module dropdown element
            AddArchiveDropdownAnalytics: function () {
                var $blogArchiveSelectDropdown = jQuery(".module-blog-archive button.dropdown-toggle");
                var blogArchiveSelectText = $blogArchiveSelectDropdown.length ? $blogArchiveSelectDropdown.text() : "";
                if (blogArchiveSelectText.length) {
                    blogArchiveSelectText = blogArchiveSelectText.toLowerCase().trim();
                    $blogArchiveSelectDropdown.attr("data-linkaction", blogArchiveSelectText);
                    $blogArchiveSelectDropdown.attr("data-analytics-link-name", blogArchiveSelectText);
                }
            },
        };

        return BlogArchive;
    })();
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BlogPostListAuthorsModule.js
// version="2"

if (ComponentRegistry.BlogPostListAuthors) {
    $(function () {
        BlogAuthorModule.Init();
    });

    var BlogAuthorModule = (function () {
        var BlogAuthor = {

            // Code initialization
            Init: function () {
                BlogAuthor.SetBlogAuthorModuleData();
                if (BlogAuthor.Data.IsBlogAuthorDataAvailable) {
                    BlogAuthor.BindBlogAuthors();
                    BlogAuthor.SetEventHandlers();
                    BlogAuthor.HideEmptySocialIcons();
                    BlogAuthor.AddClassNextItem();
                    BlogAuthorModule.MakeDescriptionDotDot();
                }
            },

            // Initializes blog contributing authors module data
            Data: {
                IsBlogAuthorDataAvailable: false,
                BlogAuthors: {
                    All: null,
                    FirstEight: null
                }
            },

            // Sets blog contributing authors module data
            SetBlogAuthorModuleData: function () {
                var blogAuthorModuleData = jQuery("#blog-post-list-authors-data");

                if (blogAuthorModuleData != null && blogAuthorModuleData.length > 0) {
                    var blogAuthorData = JSON.parse(blogAuthorModuleData.text());
                    BlogAuthor.Data.BlogAuthors.All = blogAuthorData["GetBlogPosts-return"]["blog-post-list"]["author-list"];
                    BlogAuthor.Data.BlogAuthors.FirstEight = BlogAuthor.Data.BlogAuthors.All.slice(0, 8);
                    localStorage.setItem("authorList", JSON.stringify(BlogAuthor.Data.BlogAuthors.All));
                    BlogAuthor.Data.IsBlogAuthorDataAvailable = typeof blogAuthorData != "undefined" && blogAuthorData != null;
                }
            },

            // Sets blog authors pop up and image
            BindBlogAuthors: function () {
                // Generate author pop up content
                jQuery(".module-blog-authors .author-full-bio").loadTemplate(jQuery(".module-blog-authors .json-template-fullbio"), BlogAuthor.Data.BlogAuthors.FirstEight);

                // Checks if author image should be hidden or not
                jQuery("#author-carousel .item .contributingAuthorImage").each(function () {
                    var author = jQuery(this);
                    var authorImageValue = author.attr("src");
                    if (authorImageValue == undefined || authorImageValue == null || authorImageValue === "") {
                        author.addClass("hidden");
                    }
                });
            },

            // All blog authors event handlers
            SetEventHandlers: function () {
                jQuery(".carousel-indicators li").on("click", function () {
                    BlogAuthor.LoadNextCarouselItem();
                });

                jQuery("a#display-see-more").on("click", function () {
                    jQuery(".item.active #display-see-more").addClass("hidden");
                    jQuery(".item.active #display-see-less").removeClass("hidden");
                    jQuery(".authorShortDescription").addClass("hidden");
                    jQuery(".authorLongDescription").removeClass("hidden");
                    if (jQuery(".active .blogAuthorSocial .twitter a").attr("href") !== "https://twitter.com/intent/user?screen_name=" &&
                        jQuery(".active .blogAuthorSocial .twitter a").attr("href") !== "") {
                        jQuery(".blog-contributing-authors.blogAuthorSocial").removeClass("hidden");
                    }
                });

                jQuery("a#display-see-less").on("click", function () {
                    jQuery(".item.active #display-see-more").removeClass("hidden");
                    jQuery(".item.active #display-see-less").addClass("hidden");
                    jQuery(".authorShortDescription").removeClass("hidden");
                    jQuery(".authorLongDescription").addClass("hidden");
                    jQuery(".blog-contributing-authors.blogAuthorSocial").addClass("hidden");
                });

                jQuery(".moreContributorsLinkRight").on("click", function () {
                    BlogAuthor.LoadNextCarouselItem();
                    BlogAuthor.MoreContributorsRightClick(jQuery(".module-blog-authors #author-carousel .carousel-inner#authors-carousel"));

                });

                jQuery(".moreContributorsLinkLeft").on("click", function () {
                    BlogAuthor.LoadNextCarouselItem();
                    BlogAuthor.MoreContributorsLeftClick(jQuery(".module-blog-authors #author-carousel .carousel-inner#authors-carousel"));

                });

                //add author show full bio event handler
                jQuery(".module-blog-authors a.cta, a.ctaViewAll").on("click", function (event) {
                    event.preventDefault();
                    var linkId = this.id;
                    if (linkId == "display-full-bio") {
                        var index = jQuery("#author-carousel .item.active").index();
                        var content = jQuery(".author-full-bio > div").eq(index).html();
                        jQuery("#main-modal #modal-full-bio .modal-body").html(content);
                        jQuery("#content-wrapper, .skip-main").attr("aria-hidden", "true");
                        jQuery("#main-modal .modal-dialog").removeAttr("style");
                        jQuery("#main-modal #modal-all-authors").hide();
                        jQuery("#main-modal #modal-full-bio").show();
                        jQuery("#main-modal #modal-all-authors-bio").hide();
                    }

                    //show pop up content
                    if (linkId == "display-view-all") {
                        jQuery(".modal-content .icon-arrowrightarrow").show();
                        jQuery("#main-modal .modal-dialog").css("width", "auto");
                        jQuery("#main-modal #modal-full-bio").hide();
                        jQuery("#main-modal #modal-all-authors-bio").hide();

                        BlogAuthor.BindAuthorFullBio();

                        jQuery("div.modal-content a.cta").on("click", function (event) {
                            event.preventDefault();
                            var authorObjSorted = jQuery(JSON.parse(localStorage.getItem("authorList")).sort(BlogAuthor.SortAuthor)).eq(jQuery(event.target).data("author"))[0];
                            if ($(window).width() < 768) {
                                jQuery(".full-bio-back .no-underline.corporate-black").hide();
                            }

                            jQuery("#modal-all-authors-bio .modal-body").html(jQuery(".author-full-bio > div").eq(0).html());
                            jQuery("#modal-all-authors-bio h4#authorname-desktop,h4#authorname-mobile").text(authorObjSorted.Name);
                            jQuery("#modal-all-authors-bio p").text(authorObjSorted.Long_Description);
                            jQuery("#modal-all-authors-bio img").attr("src", authorObjSorted.Url_Image);
                            jQuery("#modal-all-authors-bio img").attr("alt", authorObjSorted.Name);
                            jQuery("#modal-all-authors-bio img").attr("title", authorObjSorted.Name);
                            jQuery("#modal-all-authors-bio .social").html("")
                            BlogAuthor.DisplaySocialLinks(authorObjSorted);

                            jQuery("#content-wrapper, .skip-main").attr("aria-hidden", "true");
                            jQuery("#modal-all-authors").hide();
                            jQuery("#modal-all-authors-bio").modal("show");
                            jQuery(".modal-dialog").removeAttr("style");
                        });

                        jQuery("#modal-all-authors").show();
                    }

                    // View all and Full bio event handler
                    if (linkId === "display-full-bio" || linkId === "display-view-all") {
                        jQuery("#main-modal").modal("show");
                    }

                    jQuery(".modal-backdrop, #main-modal .close").off("click").on("click", function () {
                        jQuery(".modal-content .icon-arrowrightarrow").hide();
                        jQuery(".job-arrow-left").hide();
                        jQuery("#content-wrapper, .skip-main").attr("aria-hidden", "false");
                    });

                    jQuery(".modal-content .full-bio-back a").on("click", function (event) {
                        event.preventDefault();
                        jQuery(".modal-content .carousel.slide").show();
                        jQuery("#modal-all-authors").show();
                        jQuery("#modal-all-authors-bio").modal("hide");
                        jQuery("#main-modal .modal-dialog").css("width", "auto");
                    });

                    jQuery(".modal-content .slide > .icon-arrowrightarrow").off("click").on("click", function () {
                        BlogAuthor.ArrowRightClick(jQuery(".modal-content .carousel-inner"));
                    });

                    jQuery(".job-arrow-left").off("click").on("click", function () {
                        BlogAuthor.ArrowLeftClick(jQuery(".modal-content .carousel-inner"));
                    });
                });
            },

            // Loads next author in carousel
            LoadNextCarouselItem: function () {
                jQuery(".item #display-see-more").removeClass("hidden");
                jQuery(".item #display-see-less").addClass("hidden");
                jQuery(".authorShortDescription").removeClass("hidden");
                jQuery(".authorLongDescription").addClass("hidden");
                jQuery(".blog-contributing-authors.blogAuthorSocial").addClass("hidden");
            },

            // Social icons handler
            HideEmptySocialIcons: function () {
                jQuery("div.social > span.linkedin > a, div.social > span.twitter > a ,div.social > span.email > a").each(function () {
                    var hrefValue = jQuery(this).attr("href");
                    if (hrefValue === "" || hrefValue === "mailto:" || hrefValue.split("=")[1] === "")
                        jQuery(this).css("display", "none");
                });
            },

            // Sets blog author carousel
            BlogAuthorCarousel: function (numOfAuthors) {
                var authorCount = jQuery(".modal-content .carousel-inner .col-sm-4");
                var slideName = "slide-";
                var slideCount = 0;
                for (ctr = 0; ctr < authorCount.length; ctr += numOfAuthors) {
                    slideCount += 1;
                    var isActive = "";
                    if (slideCount == 1) {
                        isActive = "active";
                    }
                    else if (slideCount == 2) {
                        isActive = "next";
                    }
                    else { isActive = ""; }
                    authorCount.slice(ctr, ctr + numOfAuthors).wrapAll("<div id='" + slideName + slideCount + "' class = 'item " + isActive + "'></div>");
                }
            },

            // Sets author full bio
            BindAuthorFullBio: function () {
                var indicators = "", fullBioText = "FULL BIO";
                var authors = JSON.parse(localStorage.getItem("authorList"));
                if (jQuery("#display-full-bio").length > 0) {
                    fullBioText = jQuery("#display-full-bio").text();
                }

                // sort authors alphabetically before creating overlay
                authors.sort(BlogAuthor.SortAuthor);

                for (ctr = 0; ctr < authors.length; ctr++) {
                    indicators += '<div class="col-sm-4"><img src="' + authors[ctr].Url_Image + '"><div class="module-body"><h2 class="authorname-overlay">' + authors[ctr].Name + '</h2><a class="cta" data-author=' + ctr + ' href="#" title="' + fullBioText + '" data-analytics-content-type="cta" data-analytics-link-name="' + fullBioText.toLowerCase() + '">' + fullBioText + '</a><div class="hidden">' + authors[ctr].Long_Description + '</div></div></img></div>';
                    jQuery("div.modal-content .carousel-inner").html(indicators);
                }
                if (isMobile()) {
                    BlogAuthor.BlogAuthorCarousel(2);
                }
                else {
                    BlogAuthor.BlogAuthorCarousel(3);
                }
            },

            // Sets author social links
            DisplaySocialLinks: function (authorObjSorted) {
                if (authorObjSorted.Social_Linked_In.length > 0) {
                    jQuery('#modal-all-authors-bio .social').append('<span class="linkedin" title="LinkedIn"><a title="LinkedIn" href="' + authorObjSorted.Social_Linked_In + '" data-analytics-content-type="cta" data-analytics-link-name="linkedin"></a></span> ');
                }
                var twitterCount = authorObjSorted.Social_Twitter.lastIndexOf("=");
                var authorTwitter = authorObjSorted.Social_Twitter.substring(twitterCount + 1);
                if (authorTwitter.length > 0) {
                    jQuery('#modal-all-authors-bio .social').append('<span class="twitter" title="Twitter"><a title="Twitter" href="https://twitter.com/intent/user?screen_name=' + authorTwitter + '" data-analytics-content-type="cta" data-analytics-link-name="twitter"></a></span>')
                }
                var emailCount = authorObjSorted.Social_Email.lastIndexOf(":");
                var authorEmail = authorObjSorted.Social_Email.substring(emailCount + 1);
                if (authorEmail.length > 0) {
                    jQuery('#modal-all-authors-bio .social').append('<span class="email" title="Email"><a title="Email" href="mailto:' + authorEmail + '" data-analytics-content-type="cta" data-analytics-link-name="email"></a></span>')
                }
            },

            // Author carousel next item handler
            AddClassNextItem: function () {
                var $carouselInner = jQuery(".module-blog-authors #author-carousel .carousel-inner#authors-carousel");
                var nextItem = $carouselInner.find(".item.active").index();
                $carouselInner.children().eq(nextItem + 1).addClass("next");
                jQuery(".moreContributorsLinkLeft").css('visibility', 'hidden');
                jQuery(".blogAuthorLinkedInOverlay").removeClass("hidden");
            },

            // More contributors right click handler
            MoreContributorsRightClick: function ($items) {
                var $carouselInner = jQuery(".module-blog-authors #author-carousel .carousel-inner#authors-carousel");
                var $carouselItem = jQuery(".module-blog-authors #author-carousel .carousel-inner#authors-carousel .item").length - 1;
                var next = $carouselInner.find(".next").index();
                jQuery("div.item.next > div.module-body > div.authorShortDescription").triggerHandler("destroy.dot");
                $carouselInner.find(".item.active").removeClass("active");
                $carouselInner.find(".prev.left").removeClass("prev left");
                $carouselInner.children().eq(next - 1).removeClass("active").addClass("prev left");
                $carouselInner.children().eq(next).removeClass("next").addClass("active");
                $carouselInner.children().eq(next + 1).addClass("next");

                if ($carouselInner.find(".active").index() == 0) {
                    $carouselInner.find(".prev.left").removeClass("prev left");
                    jQuery(".moreContributorsLinkLeft").css("visibility", "hidden");
                }
                else {
                    jQuery(".moreContributorsLinkLeft").css("visibility", "visible");
                }
                if ($carouselInner.find(".active").index() == $carouselItem) {
                    jQuery(".moreContributorsLinkRight").css("visibility", "hidden");
                }
                BlogAuthorModule.MakeDescriptionDotDot();
            },

            // More contributors left click handler
            MoreContributorsLeftClick: function ($items) {
                var prev = $items.find(".prev").index();
                jQuery("div.item.prev > div.module-body > div.authorShortDescription").triggerHandler("destroy.dot");
                $items.find(".next").removeClass("next");
                $items.children().eq(prev + 1).removeClass("active").addClass("next");
                $items.children().eq(prev).removeClass("prev left").addClass("active");

                if (prev <= 0) {
                    jQuery(".moreContributorsLinkLeft").css("visibility", "hidden");
                }
                else {
                    $items.children().eq(prev - 1).addClass("prev left");
                }
                jQuery(".moreContributorsLinkRight").css("visibility", "visible");
                BlogAuthorModule.MakeDescriptionDotDot();
            },

            // Arrow right click handler
            ArrowRightClick: function ($items) {
                var $carouselInner = jQuery(".modal-content .carousel-inner");
                var next = $carouselInner.find(".next").index();
                $carouselInner.find(".prev.left").removeClass("prev left");
                $carouselInner.children().eq(next - 1).removeClass("active").addClass("prev left");
                $carouselInner.children().eq(next).removeClass("next").addClass("active");
                $carouselInner.children().eq(next + 1).addClass("next");

                if ((next >= ($carouselInner.children().length - 1)) || $carouselInner.children().length == 1) {
                    jQuery(".modal-content .slide > .icon-arrowrightarrow").hide();
                }
                jQuery(".job-arrow-left").show();
            },

            // Arrow left click handler
            ArrowLeftClick: function ($items) {
                var prev = $items.find(".prev").index();
                $items.find(".next").removeClass("next");
                $items.children().eq(prev + 1).removeClass("active").addClass("next");
                $items.children().eq(prev).removeClass("prev left").addClass("active");

                if (prev <= 0) {
                    jQuery(".job-arrow-left").hide();
                }
                else {
                    $items.children().eq(prev - 1).addClass("prev left");
                }
                jQuery(".modal-content .icon-arrowrightarrow").show();
            },

            // Author description ellipsis
            MakeDescriptionDotDot: function () {
                $('div.item.active > div.module-body > div.authorShortDescription').dotdotdot({
                    watch: window,
                    wrap: 'letter',
                    height: 54,
                    tolerance: 3
                });
            },

            // Sorts Author by Name
            SortAuthor: function (a, b) {
                if (a.Name < b.Name)
                    return -1;
                if (a.Name > b.Name)
                    return 1;
                return 0;
            }
        };

        return BlogAuthor;
    })();
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\blogpost.js
/* version="2" */

//////////////////////////////
//BLOG POST - RELATED CONTENT
//////////////////////////////

if (ComponentRegistry.BlogPostRelatedContent) {
    $(function () {
        var IsVisible = $('#ShowMostRecentInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            $('.blogpost-related-content').hide();
            return;
        }

        if ($(".blogpost-related-content ul li").length == 0) {
            $(".blogpost-related-content").hide();
        }
    });
}

//////////////////////////////
//BLOG POST - RELATED TOPICS
//////////////////////////////

if (ComponentRegistry.BlogPostRelatedTopics) {
    $(function () {
        var IsVisible = $('#ShowPopularTagsInMobile').val() === "True";
        if (isMobile() && !IsVisible) {
            $('.blog-related-topics').hide();
            return;
        }

        if ($(".blog-related-topics ul li").length == 0) {
            $(".blog-related-topics").hide();
        }
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\careersmodules.js
/*version = '2'*/
if (ComponentRegistry.SelfSelection) {
    $(function () {
        $(".self-selection").closest(".floatcontainer").addClass("selfselectionfloating");

        //Bug 220068: update the dropdown selected value
        $('.self-selection .dropdown-menu a').on('click', function (event) {
            $('.self-selection .text').text($(this).text());
        });

    });
}

//Bug 382305: Careers Homepage: Smart bytes/Call out Boards behaves differently in the actual versus the design.
if (ComponentRegistry.CareersSmartByteCollection) {
    $(window).on("load", function () {
        var $container = $('#careers_packery');
        
        $container.packery({
            itemSelector: '.packery-component',
            gutter: 0
        });

        $container.packery();
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\unsubscribe-topic.js
/* version="14" */
if (ComponentRegistry.Unsubscribe) {

    var isHighestDegreeValid;
    var chkBoxTalentConnection = $('#chkAcnTalentConnection');
$(function () {

        //for showing of the TC fields
        var acnTalentConnectionFields = $("#divTalentConnectionSubscription");
        acnTalentConnectionFields.hide();

        var talentConnectionCheckbox = chkBoxTalentConnection.val();
        if (talentConnectionCheckbox != undefined) {
            talentConnectionHelper.talentConnectionInit();
        }

        chkBoxTalentConnection.on("change", function () {
            var checkboxAcnSelection = $(this);
            if (typeof (checkboxAcnSelection) === 'undefined') { return; }
            if (checkboxAcnSelection.is(':checked')) {
                $("#ddHighestDegreeEarned").addClass('form-control validate-excluded-field');
                $("#ddHighestDegreeError").hide();
                $("#ddHighestDegreeChecked").hide();
                acnTalentConnectionFields.show();
                ReadOnlyDatepickerSubscription();
            }
            else {
                acnTalentConnectionFields.hide();
            }
        });

        $('#ddHighestDegreeEarned').on("change", function () {
            var ddHighestDegreeEarnedValue = $("#ddHighestDegreeEarned").val();
            var status = $('.Status:radio:checked').val();
            var isHighestDegreeValid;
            var checkBox = chkBoxTalentConnection.filter(":checked").val();
            if ((checkBox) && (status == "isProfessional")) {
                if (ddHighestDegreeEarnedValue == (talentConnectionHelper.getDefaultSelectValue()) || ddHighestDegreeEarnedValue == '') {
                    $("#ddHighestDegreeError").show();
                    $("#ddHighestDegreeChecked").hide();
                    $("#ddHighestDegreeLabel").css({ "color": "#b94a48", "font-weight": "bold" });
                    isHighestDegreeValid = false;
                }
                else {
                    $("#ddHighestDegreeError").hide();
                    $("#ddHighestDegreeChecked").show();
                    $("#ddHighestDegreeLabel").css({ "color": "black", "font-weight": "" });
                    isHighestDegreeValid = true;
                };
            }
            else {
                isHighestDegreeValid = true;
            }
        });



        // $('#emailoptinForm').attr("data-bv-display-validation-summary", false);
        //$('#emailoptinForm').attr("data-bv-message", "This value is not valid");
        //$('#emailoptinForm').attr("data-bv-feedbackicons-valid", "glyphicon glyphicon-ok");
        //$('#emailoptinForm').attr("data-bv-feedbackicons-invalid", "glyphicon glyphicon-remove");
        //$('#emailoptinForm').attr("data-bv-feedbackicons-validating", "glyphicon glyphicon-refresh");
        //$('#emailoptinForm').attr("novalidate", "novalidate");
        //$('#emailoptinForm').attr("data-bv-live", "submitted");

        //WGSJJ Fix for SIR#370025
        storeCache();
        var showModal = false;
        $('input[name=alertTopic]').on("click", function () {
            //loop thru checkboxes
            var myText = "";
            $('input[name=alertTopic]').each(function () {
                if ($(this).prop('checked') == false) {
                    myText = myText + "false|";
                }
                else {
                    myText = myText + "true|";
                }
            });//end of loop
            showModal = false;
            var checkboxesValue = myText.split('|');
            for (var iCount = 0; iCount <= checkboxesValue.length; iCount++) {
                if (checkboxesValue[iCount] == "false") {
                    showModal = true;
                }
                else if (checkboxesValue[iCount] == "true") {

                    showModal = false;
                    break;
                }
            }
            if (showModal == true) {
                //WRD Fix for Bug #408032
                //$('.modal.fade.unsubscribe').modal('show');
                $('#subs-main-modal').modal('show');
            }
        });

        $('#subsCancel').on("click", function () {
            $('input[name="emailAddress"]').val($('#EmailAddress').val());
            $('.modal').modal('hide');
        });

        $('#update-subscription').on("click", function () {
            var $formBootStrap = $('.subscriptionForm').data('bootstrapValidator');

            $formBootStrap.$submitButton = $("#subsUpdate");
            $formBootStrap.validate();

            if (!chkBoxTalentConnection.prop("checked")) {
                isHighestDegreeValid = true;
            }
            else if ($('.Status:radio:checked').val() === "isStudent") {
                isHighestDegreeValid = true;
            }
            else {
                if (typeof ($("#ddHighestDegreeEarned")) !== undefined && $("#ddHighestDegreeEarned").val() === "") {
                    $("#ddHighestDegreeError").show();
                    $("#ddHighestDegreeLabel").css({ "color": "#b94a48", "font-weight": "bold" });
                    isHighestDegreeValid = false;
                }
                else isHighestDegreeValid = true;
            }
            if ($formBootStrap.isValid() && isHighestDegreeValid) {
                var OldEmailAddress = $('#EmailAddress').val();
                var NewEmailAddress = $('input[name="emailAddress"]').val();

                //RMT 7678 & RMT 8133
                var hasBlogSubscription = $('#chkSubscribeToCareerBlog').val().toLowerCase() === 'true';
                var hasTalentConnection = $('#hasTalentConnectionId').val().toLowerCase() === 'true';
                var blogSubscription = $('#chkSubscribeToCareerBlog').prop('checked');
                var talentConnectionHasChanged = $('#talentConnectionHasChanged').val(false);
                var blogSubscriptionHasChanged = $('#careersBlogHasChanged').val(false);
                var talentConnectionData;
                if (talentConnectionHelper.getTalentConnectionModel()['Subscription'] != null
                    && talentConnectionHelper.getTalentConnectionModel()['Subscription'] != chkBoxTalentConnection.prop('checked')) {
                    talentConnectionData = talentConnectionHelper.getProfileTalentConnectionValuesSubscription();
                }
                else {
                    talentConnectionData = talentConnectionHelper.getTalentConnectionModel();
                }

                if (blogSubscription != hasBlogSubscription) {
                    blogSubscriptionHasChanged.val(true);
                }

                if (chkBoxTalentConnection.prop('checked') != hasTalentConnection) {
                    talentConnectionHasChanged.val(true);
                }

                if (OldEmailAddress == NewEmailAddress) {
                    if (talentConnectionHasChanged.val().toLowerCase() === 'true' || blogSubscriptionHasChanged.val().toLowerCase() === 'true') {
                        $.ajax({
                            url: "/api/sitecore/SubscriptionEmailAlert/SubscribeTalentConnection",
                            type: "POST",
                            async: false,
                            data: JSON.stringify({ profileTalentConnectionModel: talentConnectionData, blogSubscription: blogSubscription }),
                            dataType: "json",
                            contentType: "application/json",
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert(errorThrown);
                                jQuery("body").trigger("analytics-form-error");
                                if (typeof acncm !== 'undefined') {
                                    acncm.Forms.detectedRegistrationFormError();
                                }
                            },
                            success: function (jsonOutput, textStatus, jqXHR) {
                                if (jsonOutput == true) {
                                    $formBootStrap.defaultSubmit();
                                    jQuery("body").trigger("analytics-form-success");
                                }
                            }
                        });
                    }
                    else {
                        $formBootStrap.defaultSubmit();
                        jQuery("body").trigger("analytics-form-success");
                    }
                }
                else {
                    $('#SubscriptionChangeEmailModal').modal('show');
                }
            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        });

        $('#textarea').placeholder();
        $('#textarea').each(function () {
            var $this = $(this);
            //$this.data('placeholder', $this.attr('placeholder'))
            $this.on("focus", function () {
                if (!(/msie|MSIE 9/.test(navigator.userAgent))) {
                    $this.removeAttr('placeholder');
                }
            })
            //.on("blur", function () { $this.attr('placeholder', $this.data('placeholder')); });
        });

        $('#emailoptinForm').bootstrapValidator({
            fields: {
                unsubscribeCaptchaInput: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: 'Required Captcha'
                        },
                        callback: {
                            message: 'Incorrect Captcha',
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return isOptInCaptchaCorrect()
                                }
                            }
                        }
                    }
                }
            }
        });

        //manage alert subscriptions        
        if (($('div').hasClass('manage-alert'))
           && ($('form').hasClass('acn-form subscriptionForm form-horizontal'))) {

            //email subscription 
            //Bug #423398: Careers Newsletter and Job Alerts My Profile Subscriptions: Update button is not working in IE8.
            if ($.trim($("div[class='step-headline manage-subscription-headline']").text()) == 'E-mail Address') {
                $(".manage-alert .subscriptionForm section[class='form-section col-xs-12'] hr").hide();
                $(".manage-alert .subscriptionForm section[class='form-section col-xs-12']").attr("class", "form-section bg-color-lighter-gray col-xs-12");
                $('#subscriptionId').parent().attr("class", "form-section col-xs-12");
            }

            //client
            if ($("div").hasClass("client profile-edit")) {
                $(".manage-alert .subscriptionForm section[class='form-section col-xs-12'] hr").hide();
                $(".manage-alert .subscriptionForm section[class='form-section col-xs-12']").attr("class", "form-section bg-color-lighter-gray col-xs-12");
                $('#subscriptionId').parent().attr("class", "form-section col-xs-12");
            }
        }

        //[AJS 12/16 trasfer inline scripts from OptInModule.cshtml] -start
        var emailStatusCode = $('#optinmodule-emailstatus-content').data('emailstatus-code');
        if (emailStatusCode != null && emailStatusCode >= 200 && emailStatusCode < 300) {
            if (typeof acncm !== 'undefined') {
                acncm.EA.detectedSignUp();
            }
        }
        //-end

        // SIR 387666 - KLL
        var isUnsubscribed = $('#IsUnsubscribed').val();
        if (isUnsubscribed == "True") {
            if ($('#unsubscribe-modal').length) {
                $('#subs-main-modal').modal('show');
            }
        }

    });

    //Bug #414391 fix [HPV] 02.24.2015
    // Bug #326241 Fix
    //$(window).on('load', function () {
    //        showTextbox();  
    //});

    //$('#rb-other-reason').on("click", function () {
    //if ($(this).is(':checked')) {
    //showTextbox();
    //}
    //else {
    //hideTextbox();
    //}
    //});
    //-end

    //Bug #383639: Careers Newsletter and Job Alerts My Profile Subscriptions: The alert topics remained unchecked after clicking CANCEL button in the Unsubscribe overlay
    function storeCache() {
        var checkBoxTopics = [];

        $('input[type=checkbox]').each(function () {
            if ($(this).prop('checked') == true) {
                checkBoxTopics.push($(this).val());
            }
        });

        var jsonUpdate = { cacheTopics: checkBoxTopics }
        acncm.CacheManager.write("subscribedTopicsCache", JSON.stringify(jsonUpdate));
    }


    function OpenUnsubscribePage() {
        window.location.href = $('#unsubscribe-modal').attr('href');
        storeCache();
    }

    //Bug #383639: Careers Newsletter and Job Alerts My Profile Subscriptions: The alert topics remained unchecked after clicking CANCEL button in the Unsubscribe overlay
    function CancelSubscription() {
        var subscribedTopicsCache = acncm.CacheManager.read("subscribedTopicsCache");

        if (typeof subscribedTopicsCache != 'undefined') {
            var subscribedTopicsJSON = JSON.parse(subscribedTopicsCache);
            cachedTopics = subscribedTopicsJSON.cacheTopics;
            var noOfTopics;
            for (noOfTopics = 0; noOfTopics <= cachedTopics.length - 1; noOfTopics++) {
                $("input:checkbox[value='" + cachedTopics[noOfTopics] + "']").prop("checked", true);
            }
        }
    }


    function showTextbox() {
        //var txtOther = document.getElementById("textarea");
        var txtOther = $("#textarea");
        if (txtOther.length > 0) {
            txtOther.show();
            txtOther.val('');
        }
        //txtOther.setAttribute('placeholder', 'Please provide details(optional)');
    }

    function hideTextbox() {
        var txtOtherHide = document.getElementById("textarea");
        txtOtherHide.style.display = 'none';
    }

    function ValidateOptIn(btnoptin, emailoptinForm, alertTopics, optIn_emailaddress, userEmailAddress, itemGuid, moduleEmailAlertOptIn, countrySite) {
        var emailAddress = $('#' + optIn_emailaddress).val();
        var isAuthenticated = false;
        if (typeof (emailAddress) == 'undefined') {
            emailAddress = userEmailAddress;
            isAuthenticated = true;
        }

        var alertTopicArray = [];

        $('input[name="' + alertTopics + '"]:checked').each(function () {
            alertTopicArray.push($(this).val());
        });

        var $formBootStrap = $('#' + emailoptinForm).data('bootstrapValidator');
        //globBoot = $formBootStrap;
        $formBootStrap.$submitButton = $("#" + btnoptin);
        $formBootStrap.validate();

        if ($formBootStrap.isValid()) {
            //$formBootStrap.defaultSubmit();
            $.ajax({
                url: "/api/sitecore/OptInModule/OptInModulePost",
                type: "POST",
                async: false,
                data: JSON.stringify({
                    emailAddress: emailAddress,
                    alertTopic: alertTopicArray,
                    countrySite: countrySite,
                    itemGuid: itemGuid,
                    isAuthenticated: isAuthenticated
                }),
                contentType: "application/json",
                dataType: "json",
                traditional: true,
                error: function (response) {
                    alert('OptIn is unavailable');
                },
                success: function (response) {
                    SuccessSubscribe(response, moduleEmailAlertOptIn, isAuthenticated);
                }
            });
        }
    }

    function ValidateSubs(isbuttonclick) {

        var $formBootStrap = $('.subscriptionForm').data('bootstrapValidator');
        //globBoot = $formBootStrap;
        $formBootStrap.$submitButton = $("#subsUpdate");
        $formBootStrap.validate();

        if ($formBootStrap.isValid() && isbuttonclick == true) {
            $formBootStrap.defaultSubmit();
        }
        else {
            return;

        }

    }

    function SuccessSubscribe(response, moduleEmailAlertOptIn, isAuthenticated)
    {
        var $moduleEmailAlertOptIn = $('#' + moduleEmailAlertOptIn);
        var form_section = document.createElement("div");
        var alertTopic_section = document.createElement("ul");
        var optinmodule_emailstatus_content = document.createElement("span");
        var EmailAlertStatus = $('#optinmodule-captcha-content').data('optin-emailalert');

        if (isAuthenticated)
            var manageSubscriptionLink = $moduleEmailAlertOptIn.find('a[class="cta"]');

        $('#optinmodule-formcontent').remove();
        $moduleEmailAlertOptIn.empty();

        $(form_section).attr({
            "class": "form-section title-nonprimary",
            "id": "opt-in-bottom"
        });
        $(alertTopic_section).attr({
            "id": "opt-in-description",
            "class": "description"
        });
        $(optinmodule_emailstatus_content).attr({
            "id": "optinmodule_emailstatus_content",
            "class": "hidden",
            "data-emailstatus-code": response.emailStatusCode
        });

        $moduleEmailAlertOptIn.replaceWith(form_section);
        $(form_section).append("<hr />").append("<h2 class = 'module-headline title-nonprimary'>" + response.title + "</h2>");
        $(form_section).append("<p id='opt-in-summary'>" + response.optInSummary + "</p>");
        if (response.alertTopic.length > 0) {
            for (i = 0; i < response.alertTopic.length; i++) {
                $(alertTopic_section).append("<li>" + response.alertTopic[i] + "</li>");
            }
        }

        $(form_section).append(alertTopic_section);
        if (typeof manageSubscriptionLink != "undefined" && manageSubscriptionLink.length > 0) {
            var divManageSubsLink = document.createElement('div');
            $(divManageSubsLink).addClass("module-body col-xs-12").append(manageSubscriptionLink);
            $(form_section).append(divManageSubsLink);
        }
        else {
            if (response.emailStatusCode != EmailAlertStatus) {
                var manageSubscriptionNonAuthText = "<a class='cta' href=" + response.ManageSubsLink.Url + "?ea=" + response.EncryptedEmailAddress + "&#Subscription'>" + response.ManageSubsLink.Text + "</a>";
                $(form_section).append(manageSubscriptionNonAuthText);
            }
        }
        $(form_section).after(optinmodule_emailstatus_content);

        if (response.vCaptcha == null) {
            $(optinmodule_emailstatus_content).next().remove();
        }
    }

    function isOptInCaptchaCorrect() {
        var CaptInput = $('input[name="unsubscribeCaptchaInput"]').val();
        var returnVal = false;
        //[AJS 12/16 trasfer inline scripts from OptInModule.cshtml] -start
        var OptInCaptchaID = $('#optinmodule-captcha-content').data('optin-captchaid');
        var OptInCaptInstance = $('#optinmodule-captcha-content').data('optin-captchainstance');
        var OptInUserInputClientID = $('#optinmodule-captcha-content').data('optin-userinputclientid');

        //-end
        $.ajax({
            url: "/api/sitecore/OptInModule/IsWordCorrect",
            type: "POST",
            async: false,
            data: JSON.stringify({
                id: OptInCaptchaID,
                input: CaptInput,
                instance: OptInCaptInstance
            }),
            contentType: "application/json",
            traditional: true,
            error: function (res) {
                alert('Error on captcha validation.');
            },
            success: function (res) {
                if (res == 'True') {
                    returnVal = true;
                }
                else {
                    document.getElementById(OptInUserInputClientID).Captcha.ReloadImage();
                }
            }
        });
        return returnVal;
    }

    function emailConfirmationSettings() {
        if ($('div').hasClass('page-title')) {
            var BGColor = $('#HeaderBackgroundColor');
            var HeroTitle = $('.page-title.row > h1');
            $('.page-title.row > h1').text($('#HeaderTitle').val());
            $('#block-hero').addClass('bg-color-' + BGColor.val()).removeClass('bg-color-active');
            var cssColor = $('.bg-color-' + BGColor.val()).css('background-color');
            $('.cta').css('color', cssColor);
        }
    }

    //Insert Talent Connection in Manage Supscription Page    
    var talentConnectionHelper = {
        talentConnectionInit: function () {
            $('#talentConnectionHasChanged').val(false);
            $('#ddUniversity').append(new Option(talentConnectionHelper.getDefaultSelectValue()));
            var linkedInProfile = talentConnectionHelper.getTalentConnectionModel()["LinkedInProfileUrl"];
            if (linkedInProfile != null) {
                $('#TalentConnectionRegistration_LinkedIn').val(linkedInProfile)
            }

            var currentProgramFields = $("#CurrentProgram-fields");
            var degreeMajorFields = $("#DegreeMajor-fields");
            var schoolFields = $("#School-fields");
        
            schoolFields.hide();

            talentConnectionHelper.getUniversityByCountryOnLoad();
            talentConnectionHelper.getCurrentProgramOfStudyOther();
            talentConnectionHelper.getDegreeMajorOther();

        },
        getCurrentProgramOfStudyOther: function () {
            if ($('#ddCurrentProgramOfStudy').val() == $("#CurrentProgram-other").val()) {
                $('#currentProgram-textBox').val($('#currentProgramOtherText').val())
                $("#CurrentProgram-fields").show();
            }
            else currentProgramFields.hide();
        },
        getDegreeMajorOther: function () {
            if ($('#ddDegreeMajor').val() == $("#DegreeMajor-other").val()) {
                $('#degreeMajor-textBox').val($('#degreeMajorOtherText').val())
                $("#DegreeMajor-fields").show();
            }
            else degreeMajorFields.hide();
        },
        getUniversityByCountryOnLoad: function () {

            var countryOfSchool = $('#ddCountries').val();
            if ((countryOfSchool == "") || (countryOfSchool == undefined)) {
                $('#ddUniversity').prop("disabled", true);
            }
            else {
                var TCUniversity = $('#ddUniversity');
                var SchoolOther = $('#School-other');
                var otherTextSchool = $("#School-other").attr("name");
                var selectedSchool = talentConnectionHelper.getTalentConnectionModel()['School'];
                var hasOther = selectedSchool.substr(0, otherTextSchool.length);

                if (hasOther == otherTextSchool) {
                    otherTextSchool = selectedSchool.substr(8);
                }

                $.ajax({
                    url: "/api/sitecore/SubscriptionEmailAlert/GetUniversityByCountry",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({ countryId: $('#ddCountries').val() }),
                    dataType: "json",
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                    success: function (data) {
                        TCUniversity.prop("disabled", false);
                        var ddlValues = '<option value="">Select</option>';
                        $('#ddUniversity').empty();
                        $.each(data, function (key, value) {
                            ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                        });

                        TCUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');

                        $('#ddUniversity option').each(function () {
                            var reselectedSchool = $.trim($(this).text());
                            if (selectedSchool.length > 0) {
                                if (reselectedSchool.toLowerCase() == selectedSchool.toLowerCase())
                                {
                                    TCUniversity.selectpicker('val', $(this).val()).selectpicker('refresh');
                                    return false;
                                }
                            }
                            else {
                                schoolFields.hide();
                                return false;
                            }

                            var otherValue = $("#School-other").val();
                            TCUniversity.selectpicker('val', otherValue).selectpicker('refresh');
                            schoolFields.show();
                            $("#school-textBox").val(otherTextSchool);
                        });
                    }
                });
            }
        },
        getTalentConnectionDefaultValues: function () {
            var profileTalentConnectionModel = {};

            profileTalentConnectionModel['HighestDegreeEarned'] = null;
            profileTalentConnectionModel['CurrentProgramOfStudy'] = null;
            profileTalentConnectionModel['CountryOfSchool'] = null;
            profileTalentConnectionModel['School'] = null;
            profileTalentConnectionModel['DegreeMajor'] = null;
            profileTalentConnectionModel['DegreeStartDate'] = null;
            profileTalentConnectionModel['ExpectedGraduationDate'] = null;
            profileTalentConnectionModel['LinkedInProfileUrl'] = '';
            profileTalentConnectionModel['Subscription'] = false;

            return profileTalentConnectionModel;
        },
        getRelevantExperience: function () {
            return $(".getStatusAcn");
        },
        getDefaultSelectValue: function () {
            return $('#selectId').val();
        },
        getTalentConnectionModel: function () {

            if (JSON.parse($('#TCModel').val()) !== null) {
                return JSON.parse($('#TCModel').val());
            } else {
                return talentConnectionHelper.getTalentConnectionDefaultValues();
            }
        },
        countryOnChange: function (countryName) {
            var dropdownvalue = countryName.val();
            var ddUniversity = $('#ddUniversity');
            schoolFields.hide();
            $("#school-textBox").val('');

            if (dropdownvalue != "" && dropdownvalue != (talentConnectionHelper.getDefaultSelectValue())) {
                var SiteLanguage = $('#SiteLanguage').val();
                $.ajax({
                    url: "/api/sitecore/SubscriptionEmailAlert/GetUniversityByCountry",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({ countryId: dropdownvalue }),
                    dataType: "json",
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                    success: function (data) {
                        ddUniversity.prop("disabled", false);
                        var ddlValues = '<option value="">Select</option>';
                        $('#ddUniversity').empty();
                        $.each(data, function (key, value) {
                            ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                        });

                        ddUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');
                    }
                });
            }
            else {
                ddUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');;
            }
        },
        toggleExperienceLevelAcnTC: function (radioButton) {
            var currentStatus = $(radioButton).val();
            if ($(radioButton).is(':checked')) {
                talentConnectionHelper.getRelevantExperience().hide();

                if (currentStatus == "isStudent") {
                    $("#ddhighestDegreeEarned").removeClass('form-control validate-excluded-field');
                }
                else {
                    $("#ddhighestDegreeEarned").addClass('form-control validate-excluded-field')
                }
                $("#" + currentStatus).show();
            }
        },
        getProfileTalentConnectionValuesSubscription: function () {
            var status = $('.Status:radio:checked').val();
            var profileTalentConnectionModel = {};
            if (typeof chkBoxTalentConnection !== undefined && ($('#hasTalentConnectionId').val() == "False")) {
                if (status == 'isProfessional') {

                    //Professional fields            
                    profileTalentConnectionModel['highestDegreeEarned'] = $('#ddHighestDegreeEarned').val()
                    profileTalentConnectionModel['currentProgramOfStudy'] = null;
                    profileTalentConnectionModel['countryOfSchool'] = null;
                    profileTalentConnectionModel['school'] = null;
                    profileTalentConnectionModel['degreeMajor'] = null;
                    profileTalentConnectionModel['degreeStartDate'] = null;
                    profileTalentConnectionModel['expectedGraduationDate'] = null;

                }
                else {

                    //Student fields
                    //For Current Program of Study Dropdown
                    var currentProgramOfStudy = $('#ddCurrentProgramOfStudy :selected').val();
                    var otherCurrentProgramOfStudy = $("#CurrentProgram-other").val();
                    var currentProgramOfStudyText = $('#ddCurrentProgramOfStudy :selected').text();
                    var currentProgramDefaultValue = $('#currentProgramDefaultValue').val();
                    if (currentProgramOfStudy == otherCurrentProgramOfStudy) {

                        profileTalentConnectionModel['currentProgramOfStudy'] = PrependOther($('#currentProgram-textBox').val());
                    }
                    else {
                        if (currentProgramOfStudyText != currentProgramDefaultValue) {
                            profileTalentConnectionModel['currentProgramOfStudy'] = currentProgramOfStudyText;
                        }
                        else {
                            profileTalentConnectionModel['currentProgramOfStudy'] = null;
                        }
                    }

                    // For School/University Dropdown
                    var CountryOfSchool = $('#ddCountries :selected').val();
                    var school = $('#ddUniversity :selected').val();
                    var otherschool = $("#School-other").val();
                    var schoolText = $('#ddUniversity :selected').text();
                    var schoolDefaultValue = $('#schoolDefaultValue').val();
                    if (school == otherschool) {
                        profileTalentConnectionModel['school'] = PrependOther($('#school-textBox').val());
                    } else {
                        if (schoolText != schoolDefaultValue) {
                            profileTalentConnectionModel['school'] = schoolText;
                        }
                        else {
                            profileTalentConnectionModel['school'] = null;
                        }
                    }
                    profileTalentConnectionModel['countryOfSchool'] = CountryOfSchool;

                    // For Degree Major
                    var degreeMajor = $('#ddDegreeMajor :selected').val();
                    var otherDegreeMajorValue = $("#DegreeMajor-other").val();
                    var degreeMajorText = $('#ddDegreeMajor :selected').text();
                    var degreeMajorDefaultValue = $('#degreeMajorDefaultValue').val();
                    if (degreeMajor == otherDegreeMajorValue) {
                        profileTalentConnectionModel['degreeMajor'] = PrependOther($('#degreeMajor-textBox').val());
                    } else {
                        if (degreeMajorText != degreeMajorDefaultValue) {
                            profileTalentConnectionModel['degreeMajor'] = degreeMajorText;
                        }
                        else profileTalentConnectionModel['degreeMajor'] = null;
                    }

                    // For dates
                    var startDateStr = $('#startDateValSubscription').val();
                    if (startDateStr != '') {
                        profileTalentConnectionModel['degreeStartDate'] = FormatDateTalentConnectionSubscription(startDateStr);
                    }
                    var expectedGradDateStr = $('#gradDateValSubscription').val();
                    if (expectedGradDateStr != '') {
                        profileTalentConnectionModel['expectedGraduationDate'] = FormatDateTalentConnectionSubscription(expectedGradDateStr);
                    }

                    profileTalentConnectionModel['highestDegreeEarned'] = null;
                }

                profileTalentConnectionModel['linkedInProfileUrl'] = $('#TalentConnectionRegistration_LinkedIn').val()
                profileTalentConnectionModel['subscription'] = true;
            }
            else profileTalentConnectionModel['subscription'] = false;

            return profileTalentConnectionModel;
        }
    }


    $('#ddCountries').on("change", function () {
        var $this = $(this);
        talentConnectionHelper.countryOnChange($this);
    });

    $(".Status").each(function () {
        var instance = $(this);
        talentConnectionHelper.toggleExperienceLevelAcnTC(instance);

        instance.on("click", function () {
            talentConnectionHelper.toggleExperienceLevelAcnTC($(this));
        });
    });

    //For Pulling of Other Textbox


    $('#ddCurrentProgramOfStudy').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#CurrentProgram-other").val();

        if (ddValue == otherValue) {
            currentProgramFields.show();
        } else {
            currentProgramFields.hide();
        }
    });

    if ($('#ddCurrentProgramOfStudy').val() == $("#CurrentProgram-other").val()) {
        $('#currentProgram-textBox').val($('#currentProgramOtherText').val())
        $("#CurrentProgram-fields").show();
    }


    $('#ddDegreeMajor').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#DegreeMajor-other").val();
        if (ddValue == otherValue) {
            degreeMajorFields.show();
        } else {
            degreeMajorFields.hide();
        }
    });

    if ($('#ddDegreeMajor').val() == $("#DegreeMajor-other").val()) {
        $('#degreeMajor-textBox').val($('#degreeMajorOtherText').val())
        $("#DegreeMajor-fields").show();
    }


    $('#ddUniversity').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#School-other").val();
        if (ddValue == otherValue) {
            schoolFields.show();
        } else {
            schoolFields.hide();
        }
    });
}

function FormatDateTalentConnectionSubscription(date) {
    var formattedDate;
    //yyyy-dd-mm DB
    //dd/mm/yyyy val
    var type = $('.dtp-date.subscription').attr('type');
    if (type == "text") {
        formattedDate = date.substr(6, 4) + '/' + date.substr(3, 2) + '/' + date.substr(0, 2);
    }
    else {
        formattedDate = date;
    }
    return formattedDate;
}

function PrependOther(stringValue) {
    //to be updated when the 'Other' string source is identified

    return 'Other - ' + stringValue;
}

$('#btnUploadResumeSubscription').on("click", function (e) {
    var emailValue = $('#EditProfileEmailAddress').val();
    $.ajax({
        url: "/api/sitecore/SubscriptionEmailAlert/GetUploadLink",
        async: false,
        type: "POST",
        data: JSON.stringify({ email: emailValue }),
        contentType: "application/json",
        success: function (data) {
            uploadResume(data);
        },
        error: function (res) {
            alert("EMAIL VALIDATION ERROR");
        }
    })
});

function uploadResume(data) {
    if (typeof (data) === 'undefined' || data === '') {
        {
            alert('Email address is required');
        }
    } else {
        window.open(data, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=200,left=300,width=700,height=500");
    }
}

function ReadOnlyDatepickerSubscription() {
    var type = $('.dtp-date.subscription').attr('type');
    var degreeStartDate = talentConnectionHelper.getTalentConnectionModel()["DegreeStartDate"];
    var expectedGraduationDate = talentConnectionHelper.getTalentConnectionModel()["ExpectedGraduationDate"];

    if (degreeStartDate != null) {
        degreeStartDate = new Date(parseInt(degreeStartDate.substr(6)));

        var degreeMonth = degreeStartDate.getMonth() + 1;
        if ($(degreeMonth)[0] < 10) {
            degreeMonth = '0' + degreeMonth
        }

        var degreeDay = degreeStartDate.getDate();
        if ($(degreeDay)[0] < 10) {
            degreeDay = '0' + degreeDay
        }

        var degreeYear = degreeStartDate.getFullYear();
        if (type == "date") {
            degreeStartDate = degreeYear + "-" + degreeMonth + "-" + degreeDay;
        }
        else degreeStartDate = degreeMonth + "/" + degreeDay + "/" + degreeYear;
    }

    if (expectedGraduationDate != null) {
        expectedGraduationDate = new Date(parseInt(expectedGraduationDate.substr(6)));

        var expectedMonth = expectedGraduationDate.getMonth() + 1;
        if ($(expectedMonth)[0] < 10) {
            expectedMonth = '0' + expectedMonth
        }

        var expectedDay = expectedGraduationDate.getDate();
        if ($(expectedDay)[0] < 10) {
            expectedDay = '0' + expectedDay
        }

        var expectedYear = expectedGraduationDate.getFullYear();
        if (type == "date") {
            expectedGraduationDate = expectedYear + "-" + expectedMonth + "-" + expectedDay;
        }
        else expectedGraduationDate = expectedMonth + "/" + expectedDay + "/" + expectedYear;
    }

    if (type == "text") {
        $('#startDateValSubscription').val(degreeStartDate);
        $('#gradDateValSubscription').val(expectedGraduationDate);
        $('#startDateValSubscription').attr("readonly", true);
        $('#gradDateValSubscription').attr("readonly", true);
    }
    else if (type == "date") {
        $('#startDateValSubscription').val(degreeStartDate);
        $('#gradDateValSubscription').val(expectedGraduationDate);
        $('#startDateValSubscription').prop("readonly", false);
        $('#gradDateValSubscription').prop("readonly", false);
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\contactUs.js
// version="10"
if (ComponentRegistry.contactUs) {

    var profileClicked = "";
    var referrerUrl = '';
    var urlTrack = '';
    var isacncmAlive = typeof acncm.CacheManager != 'undefined' && acncm.CacheManager != null;
    var getReferrerUrl = document.referrer;
    var jobSeekersRelationship = $('#frmJobseekers').data('jobseekers');

    if (getReferrerUrl == '') {
        getReferrerUrl = window.location.href;
    }

    if (isacncmAlive) {
        urlTrack = acncm.CacheManager.readUrl("TrackingHistory");
    }

    $(function () {

        var externalUrl = GetExternalReferralUrl();

        $('.comment-italic').placeholder();
        // var profileClicked = "";
        var globBoot;
        //SEND QUESTION

        //Bug # 428606
        $("#newsMediaDropDown").addClass('bottom-separator');

        $('#linkNewQuestion').on("click", function () {

            $(".btn-group.bootstrap-select.form-control ul").each(function () {
                // globBoot = globBoot.destroy();
                // globBoot.options.field.
                var varSelect = $(this).find("li").find("a").first().text();

                $(this).find("li").removeClass("selected");
                $(this).find("li").first().addClass("selected");
                // $(".btn-group.bootstrap-select.form-control button.filter-option").text(varSelect).attr('title', varSelect);
                $(this).parent().parent().find(".filter-option").text(varSelect);
            });

            //globBoot.options.field.each(function () {
            //    alert(this);

            //});

            $('#SendQuestionThanksMsg').css('display', 'none');
            $('#sendQuestionPanelBody').css('display', 'block');

            $('#frmSendQuestion').find("input").val('');
            $('#frmSendQuestion').find("textarea").val('');

            if (sqValidator == 'submitted') {
                var $form = $('#frmSendQuestion').data('bootstrapValidator');
                $form.setLiveMode('disabled');
                $form.setLiveMode(sqValidator);
                //    $form.resetForm();
            }

            $('#frmSendQuestion').data('bootstrapValidator').resetForm();
            $('#sendQuestion_related').val('Select');
            $('#sendQuestion_country').val('Select Your Country/Region');

            $('#SendQuestion_Count').prop('readonly', false);
            $('#SendQuestion_Count').val(sqNumChar);
            $('#SendQuestion_Count').attr('readonly', 'readonly');
        });

        $('#frmSendQuestion').bootstrapValidator({
            fields: {
                captchaInput: {
                    trigger: 'submit',
                    validators: {
                        notEmpty: {
                            message: $("#CaptchaRequired").val()
                        },
                        callback: {
                            message: $("#IncorrectCaptcha").val()
                        }
                    }
                }
            },
            submitHandler: function (form) {
                //do nothing
            }
        });

        $("#btnSendQuestion").on("click", function () {
            var externalUrl = GetExternalReferralUrl();
            //Bug #297443: [Contact Us][Laptop][ALL]: No validation message in 'If others, please specify' field.
            var captInput = $("#sendquestionCaptcha input[name=captchaInput]").val();
            var sendQuestion_relatedvalue = $('#sendQuestion_related :selected').text();
            if (sendQuestion_relatedvalue == 'Other') {
                $('#frmSendQuestion').data('bootstrapValidator').enableFieldValidators('others', true);
            }
            else {
                $('#frmSendQuestion').data('bootstrapValidator').enableFieldValidators('others', false);
            }

            if (captInput !== "") {
                var $formBootStrap = $('#frmSendQuestion').data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', false);
            }
            else {
                var $formBootStrap = $('#frmSendQuestion').data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', true);
            }

            globBoot = $formBootStrap;
            $formBootStrap.$submitButton = this;


            $formBootStrap.validate();

            if ($formBootStrap.isValid()) {

                var SendQuestionCreatedId = $('#sendQuestion_emailaddress').val();
                var SendQuestionCountry = $('#sendQuestion_country').val();
                var SendQuestionRel = $('#sendQuestion_related').val();

                var emailBody = {

                    FirstName: $('#sendQuestion_firstname').val(),
                    LastName: $('#sendQuestion_lastname').val(),
                    UserEmail: $('#sendQuestion_emailaddress').val(),
                    UserOrg: $('#sendQuestion_company').val(),
                    UserRelationship: $('#sendQuestion_related').val(),
                    UserOther: $('#sendQuestion_others').val(),
                    Country: $('#sendQuestion_country').val(),
                    TelNumber: $('#sendQuestion_phone').val(),
                    Comments: $('#sendQuestion_description').val()
                };

                var itemId = sendquestionId;
                var contactUsPage = true;
                var currentItemLanguage = $('#currentItemLanguage').val();
                var relationship = SendQuestionRel;

                var sendQuestionFormData = "<Information>" +
                                                "<FirstName>" + $('#sendQuestion_firstname').val() + "</FirstName>" +
                                                "<LastName>" + $('#sendQuestion_lastname').val() + "</LastName>" +
                                                "<EmailAddress>" + $('#sendQuestion_firstname').val() + "</EmailAddress>" +
                                                "<Company>" + removeTags($('#sendQuestion_company').val()) + "</Company>" +
                                                "<Relationship>" + $('#sendQuestion_related').val() + "</Relationship>" +
                                                "<Others>" + removeTags($('#sendQuestion_others').val()) + "</Others>" +
                                                "<Country>" + $('#sendQuestion_country').val() + "</Country>" +
                                                "<Comments>" + removeTags($('#sendQuestion_description').val()) + "</Comments>" +
                                                "<PhoneNumber>" + $('#sendQuestion_phone').val() + "</PhoneNumber>" +
                                                    "<CountrySite>" + CountrySiteName + "</CountrySite>" +
                                                "<Status>" + ProfileId + "</Status>" +
                                                    "<CreatedId>" + SendQuestionCreatedId + "</CreatedId>" +
                                                    "<FormGuid>" + formDefinitionGuid + "</FormGuid>" +
                                           "</Information>";

                var sendQuestionFormInput =
                       {
                           FormDefinitionGuid: formDefinitionGuid,
                           CountrySite: CountrySiteName,
                           HistoricalDataTxt: sendQuestionFormData,
                           CreateUserId: SendQuestionCreatedId,
                           UserProfileId: ProfileId
                       }

                $.ajax({
                    url: "/api/sitecore/contactus/index",
                    type: "POST",
                    data: JSON.stringify({
                        contactUsInput: sendQuestionFormInput,
                        emailBody: emailBody,
                        itemId: itemId,
                        currentItemLanguage: currentItemLanguage,
                        relationship: relationship,
                        captchaID: captchaIDSnd,
                        captInput: $("#sendquestionCaptcha input[name=captchaInput]").val(),
                        captInstance: captInstanceSnd,
                        serverName: window.location.origin,
                        formName: sendQuestionFormName + " " + itemId,
                        currentUrl: window.location.href,
                        referrerUrl: getReferrerUrl,
                        trackingHistory: urlTrack,
                        external_Url: externalUrl,
                        contactUsPage: contactUsPage
                    }),
                    //dataType: "json",
                    contentType: "application/json",
                    traditional: true,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                    },
                    success: function (res) {
                        // alert(res);
                        if (res == 'True') {
                            //       alert(res);
                            var ccode = $('#sqcaptchaid').attr("data-ccode");
                            document.getElementById(ccode).Captcha.ReloadImage();
                            $('#frmSendQuestion').data('bootstrapValidator').resetForm();
                            $('#errorSummary').hide();

                            $('#sendQuestionPanelBody').css('display', 'none');
                            $('#SendQuestionThanksMsg').css('display', 'block');

                            //Bug 346949
                            $('html, body').animate({
                                scrollTop: $("#contact-us-accordion").offset().top - 100
                            }, 100);
                            jQuery("body").trigger("analytics-form-success", true);
                        }
                        else {
                            //     alert(res);
                            var ccode = $('#sqcaptchaid').attr("data-ccode");
                            document.getElementById(ccode).Captcha.ReloadImage();
                            $('#frmSendQuestion').data('bootstrapValidator').updateStatus('captchaInput', 'INVALID', 'callback');
                            $('#errorSummary').show();
                            jQuery("body").trigger("analytics-form-error");
                        }
                    }
                });
            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        });


        //JOBSEEKERS
        $('#linkNewJobs').on("click", function () {
            $(".btn-group.bootstrap-select.form-control ul").each(function () {
                var varSelect = $(this).find("li").find("a").first().text();

                $(this).find("li").removeClass("selected");
                $(this).find("li").first().addClass("selected");
                // $(".btn-group.bootstrap-select.form-control button.filter-option").text(varSelect).attr('title', varSelect);
                $(this).parent().parent().find(".filter-option").text(varSelect);
            });

            $('#JobSeekersThanksMsg').css('display', 'none');
            $('#JobseekersBody').css('display', 'block');

            $('#frmJobseekers').find("input").val('');
            $('#frmJobseekers').find("textarea").val('');
            $("#jobseeker_country").val('SELECT');

            if (jsValidator == 'submitted') {
                var $form = $('#frmJobseekers').data('bootstrapValidator');
                $form.setLiveMode('disabled');
                $form.setLiveMode(jsValidator);
                //   $form.resetForm();
            }

            $('#frmJobseekers').data('bootstrapValidator').resetForm();

            $('#jobs_char_remaining').prop('readonly', false);
            $('#jobs_char_remaining').val(jobNumChar);
            $('#jobs_char_remaining').attr('readonly', 'readonly');


        });

        $('#frmJobseekers').bootstrapValidator({
            fields: {
                captchaInput: {
                    trigger: 'submit',
                    validators: {
                        notEmpty: {
                            message: $("#CaptchaRequired").val()
                        },
                        callback: {
                            message: $("#IncorrectCaptcha").val()
                        }
                    }
                }
            },
            submitHandler: function (form) {
                //do nothing
            }
        });

        $("#btnJobseekers").on("click", function () {
            var externalUrl = GetExternalReferralUrl();
            var captInput = $("#jSeekCaptcha input[name=captchaInput]").val();

            if (captInput !== "") {
                var $formBootStrap = $('#frmJobseekers').data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', false);         
            }
            else {
                var $formBootStrap = $('#frmJobseekers').data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', true);
            }
            
            $formBootStrap.$submitButton = this;
            $formBootStrap.validate();

            if ($formBootStrap.isValid()) {

                var JobSeekerCreatedId = $('#jobseeker_emailaddress').val();
                var JobSeekerCountry = $('#jobseeker_country').val();

                var emailBody = {
                    FirstName: $('#jobseeker_firstname').val(),
                    LastName: $('#jobseeker_lastname').val(),
                    UserEmail: $('#jobseeker_emailaddress').val(),
                    UserOrg: '',
                    UserRelationship: jobSeekersRelationship,
                    UserOther: '',
                    Country: $('#jobseeker_country').val(),
                    TelNumber: '',
                    Comments: $('#jobseeker_comments').val()
                };


                var jobSeekersFormData = "<Information>" +
                                                "<FirstName>" + $('#jobseeker_firstname').val() + "</FirstName>" +
                                                "<LastName>" + $('#jobseeker_lastname').val() + "</LastName>" +
                                                "<EmailAddress>" + $('#jobseeker_emailaddress').val() + "</EmailAddress>" +
                                                "<Country>" + $('#jobseeker_country').val() + "</Country>" +
                                                "<Comments>" + removeTags($('#jobseeker_comments').val()) + "</Comments>" +
                                                    "<CountrySite>" + CountrySiteName + "</CountrySite>" +
                                                "<Status>" + ProfileId + "</Status>" +
                                                    "<CreatedId>" + JobSeekerCreatedId + "</CreatedId>" +
                                                    "<FormGuid>" + formDefinitionGuid + "</FormGuid>" +
                                           "</Information>";

                //alert(jobSeekersFormData);

                var itemId = jobSeekerId;
                var contactUsPage = true;
                var relationship = jobSeekersRelationship;
                var jobSeekersFormInput =
                        {
                            FormDefinitionGuid: formDefinitionGuid,
                            CountrySite: CountrySiteName,
                            HistoricalDataTxt: jobSeekersFormData,
                            CreateUserId: JobSeekerCreatedId,
                            UserProfileId: ProfileId
                        }


                $.ajax({
                    url: "/api/sitecore/contactus/index",
                    type: "POST",
                    data: JSON.stringify({
                        contactUsInput: jobSeekersFormInput,
                        emailBody: emailBody,
                        itemId: itemId,
                        currentItemLanguage: acnPage.Language,
                        relationship: relationship,
                        captchaID: captchaIDjSeek,
                        captInput: $("#jSeekCaptcha input[name=captchaInput]").val(),
                        captInstance: captInstancejSeek,
                        serverName: window.location.origin,
                        formName: jobseekerFormName + " " + itemId,
                        currentUrl: window.location.href,
                        referrerUrl: getReferrerUrl,
                        trackingHistory: urlTrack,
                        external_Url: externalUrl,
                        contactUsPage: contactUsPage
                    }),
                    //dataType: "json",
                    contentType: "application/json",
                    traditional: true,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                    },
                    success: function (res) {
                        if (res == 'True') {
                            //[3/20/15] Merge 2/25 from Main Release Branch
                            //alert(res);
                            var ccode = $('#jSeekcaptchaid').attr("data-ccode");
                            document.getElementById(ccode).Captcha.ReloadImage();
                            $('#frmJobseekers').data('bootstrapValidator').resetForm();
                            $('#errorSummary').hide();

                            $('#JobseekersBody').css('display', 'none');
                            $('#JobSeekersThanksMsg').css('display', 'block');

                            //Bug 346949
                            $('html, body').animate({
                                scrollTop: $("#contact-us-accordion").offset().top
                            }, 100);
                            jQuery("body").trigger("analytics-form-success", true);
                        }
                        else {
                            //[3/20/15] Merge 2/25 from Main Release Branch
                            //alert(res);
                            var ccode = $('#jSeekcaptchaid').attr("data-ccode");
                            document.getElementById(ccode).Captcha.ReloadImage();
                            $('#frmJobseekers').data('bootstrapValidator').updateStatus('captchaInput', 'INVALID', 'callback');
                            $('#errorSummary').show();
                            jQuery("body").trigger("analytics-form-error");
                        }
                    }
                });
            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        });

        //Modal 
        $("#btnSendEmailModal").on("click", function () {

            var $formBootStrap = $('#frmContactUsModal').data('bootstrapValidator');
            $formBootStrap.$submitButton = this;
            $formBootStrap.validate();

            var emailBody = {
                FirstName: $('#modal_firstName').val(),
                LastName: $('#modal_lastName').val(),
                UserEmail: $('#modal_email').val(),
                Comments: $('#modal_comments').val(),
                Country: CountryMediaSiteName,
                profileName: profileClicked,
                fromEmailAddress: $('#modal_email').val()
            };


            //var fname = $('#modal_firstName').val();
            //var lname = $('#modal_lastName').val();
            //var semail = $('#modal_email').val();
            //var scomments = $('#modal_comments').val();
            //var scompany = "";
            //var sorg = "";
            //var sother = "";
            //var scountry = "";
            //var stel = "";


            if ($formBootStrap.isValid()) {

                var NewsMediaCreatedId = $('#modal_email').val();


                var newsMediaFormData = "<Information>" +
                                                "<FirstName>" + $('#modal_firstName').val() + "</FirstName>" +
                                                "<LastName>" + $('#modal_lastName').val() + "</LastName>" +
                                                "<EmailAddress>" + $('#modal_email').val() + "</EmailAddress>" +
                                                "<Comments>" + removeTags($('#modal_comments').val()) + "</Comments>" +
                                                    "<CountrySite>" + CountryMediaSiteName + "</CountrySite>" +
                                                "<Status>" + "-1" + "</Status>" +
                                                    "<CreatedId>" + NewsMediaCreatedId + "</CreatedId>" +
                                                    "<Recipient>" + emailBody.UserEmail + "</Recipient>" +
                                                    "<FormGuid>" + "sampleGUID" + "</FormGuid>" +
                                           "</Information>";

                //alert(newsMediaFormData);
                var commentValue = $('#modal_comments').val();

                //$.post('/api/sitecore/contactus/SendModalEmail', emailBody,
                //        function (res) {
                //            //alert("SENT!");
                //            $('#contact-main-modal').modal('hide');
                //            $('#frmContactUsModal').find("input").val('');
                //            $('#frmContactUsModal').find("textarea").val('');
                //            $('#frmContactUsModal').data('bootstrapValidator').resetForm();
                //        });



                $.ajax({
                    url: "/api/sitecore/contactus/modal",
                    type: "POST",
                    data: JSON.stringify(emailBody),
                    //dataType: "json",
                    contentType: "application/json",
                    traditional: true,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                    },
                    success: function (data) {
                        $('#contact-main-modal .confirm').hide();
                        if (data.IsEmailSent == true) {
                            $('#contact-main-modal .contact-thankyou').show();
                            jQuery("body").trigger("analytics-form-success", true);
                        }
                        else {
                            $('#contact-main-modal .contact-emailnotsent').show();
                            jQuery("body").trigger("analytics-form-error");
                        }
                        // SIR #324868 - reset live mode
                        $formBootStrap.setLiveMode('disabled').setLiveMode('submitted');
                    }
                });


            }
        });

        $('#btnModalCancel').on("click", function () {
            $('#contact-main-modal').modal('hide');

            var bootVal = $('#frmContactUsModal').attr('data-bv-live');

            if (bootVal == 'submitted') {
                var $form = $('#frmContactUsModal').data('bootstrapValidator');
                $form.setLiveMode('disabled');
                $form.setLiveMode(bootVal);
                //   $form.resetForm();
            }

            $('#frmContactUsModal').data('bootstrapValidator').resetForm();

        });
        $('.contact-modal-close').on("click", function () {
            $('#contact-main-modal').modal('hide');
            $('#frmContactUsModal input, #frmContactUsModal textarea').val('');
            $('#frmContactUsModal').data('bootstrapValidator').resetForm();

            $('#contact-main-modal .countdown').prop('readonly', false);
            $('#contact-main-modal .countdown').val(2000);
            $('#contact-main-modal .countdown').attr('readonly', 'readonly');
        });

        $('#btnModalClose').on("click", function () {
            // $('#contact-main-modal').modal('hide');
            var bootVal = $('#frmContactUsModal').attr('data-bv-live');

            if (bootVal == 'submitted') {
                var $form = $('#frmContactUsModal').data('bootstrapValidator');
                $form.setLiveMode('disabled');
                $form.setLiveMode(bootVal);
                //   $form.resetForm();
            }
            $('#frmContactUsModal input, #frmContactUsModal textarea').val('');
            $('#frmContactUsModal').data('bootstrapValidator').resetForm();

            $('#contact-main-modal .countdown').prop('readonly', false);
            $('#contact-main-modal .countdown').val(2000);
            $('#contact-main-modal .countdown').attr('readonly', 'readonly');
        });



        modalClick();
        //Bug #303349, #291426: Added script for collapse toggle for IOS devices
        if (IsTouch() === true) {
            $('.panel-heading').on("click", function () {
                var $this = $(this);
                var $collapse = $this.parent().find($this.attr('data-target'));

                if ($('.panel-collapse').hasClass('collapsing')) {
                    return false;
                }

                $collapse.collapse('toggle');

                if ($this.hasClass('collapsed')) {
                    //Bug 316473: Collapsed panels other panels
                    $this.closest('.panel-group').find('.panel-heading:not(.collapsed)').each(function () {
                        $(this).parent().find($(this).attr('data-target')).collapse('toggle');
                        $(this).addClass('collapsed');
                    });
                    $this.removeClass('collapsed');
                } else {
                    $this.addClass('collapsed');
                }

            }).on("dblclick", function (e) {
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
        }
        //makeContactNumberClickable();

        //Bug 432795 Webpart - Contact Us: Contact number in Contact Us resources are clickable.
        if (isDesktop()) {
            $("button.contact-info-item-number").parent().removeAttr('onclick');
        }
    });

    //Bug 428271 Webpart - Contact Us: Contact numbers in General Inquiries is clickable.
    //function makeContactNumberClickable() {
    // if (isMobile()) {
    //var $contactNumber = $('.contact-info-item div');
    //var contactLink = $contactNumber.data('onclick-link');
    //$contactNumber.attr('onclick', contactLink);
    //}
    //}

    //Search Resources
    // SIR #294107: Added missing "/" in url
    function DropdownOnChange(selectedVal) {
        var dropdownval = selectedVal.value;
        var id = $(selectedVal).attr('id');
        var searchdiv = "#Search-" + id;
        var depdiv = "#Department-" + id;
        $.ajax({
            type: "POST",
            url: "/api/sitecore/NewsMediaSubModule/GetContactResources",
            data: "{\"dropDownValue\":\"" + dropdownval + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (res) {
                var resources = res;
                $(searchdiv).empty();
                $(depdiv).empty();
                if (res.length > 0)
                { $(depdiv).text($('#' + id + ' option:selected').text()); }
                $.each($(resources), function (idx, obj) {
                    $(searchdiv).append(
                    '<div class="col-sm-4">' +
                        '<div class="contact-info-item col-xs-12 col-sm-12">' +
                            '<h5 class="module-body contact-info-item-person">' + obj.FullName + '</h5>' +
                            '<h5 class="module-body contact-info-item-location">' + obj.Location + '</h5>' +
                            '<button class="module-body btn btn-primary col-xs-12 contact-info-item-number">' + obj.PhoneNumber + '</button>' +
                            '<div class="contact-info-item-envelope"></div>' +
                        '</div>' +
                    '</div>');
                });

                modalClick();
            },
            error: function (xhr, ajaxOptions, thrownError, msg) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }

    function modalClick() {
        $('.contact-info-item-envelope').on("click", function () {

            checkIfEdit();
            showModal();
            //Bug #429975: Webpart - Contact Us: Error message is displayed when submitting valid forms in modal window.
            profileClicked = $(this).parent().find('h5.contact-info-item-person').html();
            //$(this).parent().children('h5').each(function () {
            //    if ($(this).attr('class') == 'contact-info-item-person') {
            //        profileClicked = $(this).text();
            //        //alert(profileClicked);
            //    }

            //});
        });
    }
    //[AJS 11/10] transfer/remove inline scripts -start
    function showModal() {
        $('#contact-main-modal .confirm').show();
        $('#contact-main-modal .contact-thankyou').hide();

        // SIR #405514: Webpart - Contact Us: Error modal window is appended below the correct modal window
        $('#contact-main-modal .contact-emailnotsent').hide();

        $('#contact-main-modal').modal();
        // return false;
    }

    //Bug 513682 - adjust Send an Email modal when page is in Edit Mode
    function checkIfEdit() {
        if ($('#scCrossPiece').length > 0) {
            $('#contact-main-modal').css('margin-top', '50px');
        }
    }

    //-end
    function GetExternalReferralUrl() {
        var externalRef = sessionStorage.getItem("External_ReferrerUrl");
        if (externalRef != 'undefined' && externalRef != null && externalRef != '') {
            return externalRef;
        }
        else {
            return "None";
        }
    }

    //RMT5963 starts
    $(".panel-heading.collapsed").on("keyup", function (event) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });

    $(".contact-info-item-envelope").on("keyup", function (event) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });
}  
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\customforms.js
/* version="7" */
if (ComponentRegistry.customforms) {

    var clearValidation = function (nameField) {
        var $fields = $("input[name='" + nameField + "']");
        var formValidator = $('#' + $fields.closest('form').attr('id')).data('bootstrapValidator');
        // Reset the flag
        formValidator._submitIfValid = false;
        formValidator.updateStatus(nameField, formValidator.STATUS_NOT_VALIDATED, null);
    }

    var shareValidation = function (nameField, shareField, percentage, errorMessage) {
        this.nameField = nameField;
        this.shareField = shareField;
        this.percentage = percentage;
        this.errorMessage = errorMessage;

        //for share validation
        this.validatorInterval = null;
        this.validatorCounter = 1;
        this.maxValidatorCounter = 15;

        this.isTotalShareValid = function () {
            var nmNominee0 = this.nameField.substring(0, this.nameField.length - 1); //"FTM_EPFNomineeNmAddr0";
            var nmShare0 = this.shareField.substring(0, this.shareField.length - 1); //"FTM_EPFNomineeShare0";
            var total = 0;
            var hasNominee = false;
            var $inputs = $("input[name^='" + nmNominee0 + "']:visible");
            var shareInputs = [];
            $inputs.each(function (index) {
                if (this.value.toUpperCase() != "N/A") {
                    hasNominee = true;
                    var $share = $("input[name='" + nmShare0 + (index + 1) + "']");
                    if ($share != null && $share.length > 0) {
                        shareInputs.push($share);
                        var share = $share[0].value;
                        if (!isNaN(share)) {
                            total += parseInt(share);
                        }
                    }
                }
            });
            var isTotalValid = !hasNominee || total === this.percentage;
            if (!isTotalValid) {
                setTimeout(function () {
                    $.each(shareInputs, function (index, $obj) {
                        if (index > 0) {
                            $obj.closest('.form-group').find('i.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                        }
                    });
                }, 800);
            }
            return isTotalValid;
        }

        this.clearValidationOnBlur = function (shareField) {
            var $fields = $("input[name='" + shareField + "']");
            $fields.on("change", function (e) {
                var formID = $fields.closest('form').attr('id');
                var formValidator = $('#' + formID).data('bootstrapValidator');
                // Reset the flag
                formValidator._submitIfValid = false;
                //var nameField0  = nameField.substring(0, nameField.length - 1);
                var shareField0 = shareField.substring(0, shareField.length - 1);
                $("input[name^='" + shareField0 + "']:visible").each(function (index) {
                    formValidator.updateStatus($(this).attr("name"), formValidator.STATUS_NOT_VALIDATED, null);
                });
            });
        }

        this.addValidation = function () {
            validatorInterval = setInterval(function () {
                var formID = $("input[name='" + this.shareField + "']").closest('form').attr('id');
                var formValidator = $('#' + formID).data('bootstrapValidator');
                if (formValidator != null) {
                    clearInterval(validatorInterval);
                    $("span.outer-message").remove();
                    var validatorFields = formValidator.options.fields;
                    var nmShare0 = this.shareField.substring(0, this.shareField.length - 1);
                    var err = this.errorMessage;
                    //alert(nmShare0);
                    $("input[name^='" + nmShare0 + "']").each(function (index) {
                        var shareName = $(this).attr("name")
                        if (index == 0) {
                            var validators = validatorFields[shareName].validators;
                            validators["callback"] = {
                                message: err,
                                callback: function () {
                                    return isTotalShareValid();
                                }
                            }
                            validatorFields[shareName] = $.extend(true, validatorFields[shareName],
                                validators
                            );
                        }
                        clearValidationOnBlur(shareName);
                    });
                    for (var _field in validatorFields) {
                        formValidator._initField(_field);
                    }
                }
                else {
                    validatorCounter = validatorCounter + 1;
                    if (validatorCounter > maxValidatorCounter) {
                        clearInterval(validatorInterval);
                    }
                }
            }, 3000);
        };
        this.addValidation();
    };

    // function to reposition error messages on onboarding forms
    function updateValidationErrorPosition(fieldsToUpdateErrorPosition) {
        if (fieldsToUpdateErrorPosition != undefined && fieldsToUpdateErrorPosition != null) {
            $.each(fieldsToUpdateErrorPosition, function (i, field) {
                var $ctrl = $("[name='" + field + "']");
                if ($ctrl.length > 0) {
                    $ctrl.attr("data-bv-icon-location", ".validatorMessage");
                    var $parent = $ctrl.parents('.form-group').first();
                    if ($parent != null && $parent.length > 0) {
                        $parent.addClass("bottom-validator");
                        $.each($parent.children(), function (i, child) {
                            $(child).removeClass('col-sm-6').addClass('col-sm-11');
                        });
                    }
                }
            });
        }
    }

    $(function () {

        $(".custom-form-link").on("click", function () {
            ResetCascade($(this));
        });

        var custForm = $(this).closest("form");
        $("custForm").bootstrapValidator(
		{
		    fields: {
		        captchaInput: {
		            trigger: 'submit'
		        }
		    }
		});

        function ResetCascade(itemReset) {
            var formID = $(itemReset).closest('.acn-form');

            if (formID != null) {
                var firstDropDown = $(formID).find('.cascading_group').find('.firstDropDownDiv select');
                var secondDropDown = $(formID).find('.cascading_group').find('.secondDropDownDiv select');
                var thirdDropDown = $(formID).find('.cascading_group').find('.thirdDropDownDiv select');

                if (firstDropDown != null) {
                    var valueId = $(firstDropDown).val();
                    if (valueId != "" && valueId != null) {
                        $(".firstDropDownDiv select option:selected").attr('selected', false);
                        $(".firstDropDownDiv select option").first().attr('selected', 'selected');
                    }

                    if (secondDropDown != null) {
                        var valueId2 = $(secondDropDown).val();
                        if (valueId2 != "" && valueId2 != null) {
                            $(".secondDropDownDiv select option:selected").attr('selected', false);
                            $(".secondDropDownDiv select option").first().attr('selected', 'selected');
                        }
                    }

                    if (thirdDropDown != null) {
                        var valueId3 = $(thirdDropDown).val();
                        if (valueId3 != "" && valueId3 != null) {
                            $(".thirdDropDownDiv select option:selected").attr('selected', false);
                            $(".thirdDropDownDiv select option").first().attr('selected', 'selected');
                        }
                    }
                }
            }
        }

        $('.firstDropDownDiv select').on("change", function () {
            var valueId = $(this).val();
            var secondDropdown = $(this).closest('.cascading_group').find('#secondDropDown');

            if (valueId != "" && valueId != null) {
                $.ajax({
                    url: "/api/sitecore/FormsModule/GetSecondValues",
                    type: "POST",
                    data: {
                        selectedGuid: valueId,
                        firstValue: firstValues,
                        secondValue: secondValues,
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                    success: function (data) {
                        secondDropdown.empty();
                        secondDropdown.html(defaultValue);

                        $.each(data, function (key, value) {
                            secondDropdown.append("<option value='" + value.Key + "'>" + value.Value + "</option>");
                        });
                        secondDropdown.selectpicker('refresh');
                    }
                });
                if (secondValues != "") {
                    $(this).closest('.cascading_group').find('.secondDropDownDiv').show();
                    $(this).closest('.cascading_group').find('.secondDropDownDiv select').addClass('validate-excluded-field');
                    //$(this).closest('.cascading_group').find('.thirdDropDownDiv').show();
                    //$(this).closest('.cascading_group').find('.thirdDropDownDiv select').addClass('validate-excluded-field');
                    $('.secondDropDownDiv select').trigger("change");
                    $('.thirdDropDownDiv select').trigger("change");
                }
            }
            else {
                secondDropdown.empty();
                secondDropdown.html(defaultValue);
                secondDropdown.selectpicker('refresh');
                $('.secondDropDownDiv select').trigger("change");
                $('.thirdDropDownDiv select').trigger("change");
            }


        });

        $('.secondDropDownDiv select').on("change", function () {
            var secondValueId = $(this).val();
            var thirdDropdown = $(this).closest('.cascading_group').find('#thirdDropDown');

            if (secondValueId != "" && secondValueId != null) {
                $.ajax({
                    url: "/api/sitecore/FormsModule/GetThirdValues",
                    type: "POST",
                    data: {
                        secondSelectedGuid: secondValueId,
                        secondDDValue: secondValues,
                        thirdValue: thirdValues,
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                    success: function (data2) {
                        thirdDropdown.empty();
                        thirdDropdown.html(defaultValue);

                        $.each(data2, function (key, value) {
                            thirdDropdown.append("<option value='" + value.Key + "'>" + value.Value + "</option>");
                        });
                        thirdDropdown.selectpicker('refresh');
                    }
                });
                if (thirdValues != "") {
                    $(this).closest('.cascading_group').find('.thirdDropDownDiv').show();
                    $(this).closest('.cascading_group').find('.thirdDropDownDiv select').addClass('validate-excluded-field');
                }
            }
            else {
                thirdDropdown.empty();
                thirdDropdown.html(defaultValue);
                thirdDropdown.selectpicker('refresh');
            }
        });

        var dt = new Date();
        var yearDt = dt.getFullYear();
        var _yearStart = yearDt - 100;
        $('.dtp-date').datetimepicker({
            lang: $('#languageSelected').val(),
            timepicker: false,
            format: 'd/m/Y',
            formatDate: 'Y/m/d',
            closeOnDateSelect: true,
            scrollInput: false,
            yearStart: _yearStart,
            onSelectDate: function (currentVal, inputField) {
                var formID = $('.dtp-date').closest('form').attr('id');
                var fieldDate = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldDate, 'NOT_VALIDATED');
            }
        });

        $('.dtp-datetime-local').datetimepicker({
            dayOfWeekStart: 1,
            lang: $('#languageSelected').val(),
            scrollInput: false,
            onSelectDate: function (currentVal, inputField) {
                var formID = $('.dtp-datetime-local').closest('form').attr('id');
                var fieldDateTimeLocal = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldDateTimeLocal, 'NOT_VALIDATED');
            },
            onSelectTime: function (currentVal, inputField) {
                var formID = $('.dtp-datetime-local').closest('form').attr('id');
                var fieldDateTimeLocal = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldDateTimeLocal, 'NOT_VALIDATED');
            }
        });

        $('.dtp-time').datetimepicker({
            datepicker: false,
            format: 'H:i',
            step: 5,
            closeOnDateSelect: true,
            scrollInput: false,
            onSelectTime: function (currentVal, inputField) {
                var formID = $('.dtp-time').closest('form').attr('id');
                var fieldTime = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldTime, 'NOT_VALIDATED');
            }
        });

        $('.dtp-month-year').datetimepicker({
            lang: $('#languageSelected').val(),
            timepicker: false,
            format: 'M, Y',
            formatDate: 'M, Y',
            closeOnDateSelect: true,
            scrollInput: false,
            onSelectDate: function (currentVal, inputField) {
                var formID = $('.dtp-month-year').closest('form').attr('id');
                var fieldMonth = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldMonth, 'NOT_VALIDATED');
            }
        });

        $('.dtp-week-year').datetimepicker({
            lang: $('#languageSelected').val(),
            timepicker: false,
            weeks: true,
            format: 'W, Y',
            formatDate: 'W, Y',
            closeOnDateSelect: true,
            scrollInput: false,
            onSelectDate: function (currentVal, inputField) {
                var formID = $('.dtp-week-year').closest('form').attr('id');
                var fieldWeek = inputField.attr('data-bv-field');

                $("#" + formID).data('bootstrapValidator').updateStatus(fieldWeek, 'NOT_VALIDATED');
            }
        });

        //Bug 722500: datepicker is not validating if the value is deleted 
        $('[class*="dtp-"]').on("change", function () {
            var formID = $(this).closest('form').attr('id');
            var fieldDate = $(this).attr('data-bv-field');

            $("#" + formID).data('bootstrapValidator').updateStatus(fieldDate, 'NOT_VALIDATED');
        });

        if (IsTouch() === true) {
            $('.panel-heading').on("click", function () {
                var $this = $(this);
                var $collapse = $this.parent().find($this.attr('data-target'));

                if ($('.panel-collapse').hasClass('collapsing')) {
                    return false;
                }

                $collapse.collapse('toggle');

                if ($this.hasClass('collapsed')) {
                    //Bug 316473: Collapsed panels other panels
                    $this.closest('.panel-group').find('.panel-heading:not(.collapsed)').each(function () {
                        $(this).parent().find($(this).attr('data-target')).collapse('toggle');
                        $(this).addClass('collapsed');
                    });
                    $this.removeClass('collapsed');
                } else {
                    $this.addClass('collapsed');
                    $($this + '.panel-collapse').addClass('collapse');
                }
            }).on("dblclick", function (e) {
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
        }

        if ($('html.touch').length <= 0) {
            $.mask.definitions['~'] = '[+-]';
            $.mask.definitions['h'] = '[A-Z,a-z,0-9,/]';
            //$('.mask-date').mask('99/99/9999', {
            $('.mask-date').mask('?hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh', {
                placeholder: " ", completed: function () {

                    var validSDateformat = /^\d{2}\/\d{2}\/\d{4}$/; //Basic check for format validity
                    input = this.val();

                    if (validSDateformat.test(input)) {
                        var monthfield = input.split("/")[0]
                        var dayfield = input.split("/")[1]
                        var yearfield = input.split("/")[2]
                        var dayobj = new Date(yearfield, monthfield - 1, dayfield)
                        if ((dayobj.getMonth() + 1 != $.trim(monthfield)) || (dayobj.getDate() != $.trim(dayfield)) || (dayobj.getFullYear() != $.trim(yearfield))) {
                            var objToday = new Date();
                            var dd = objToday.getDate();
                            var mm = objToday.getMonth() + 1;
                            var yyyy = objToday.getFullYear();
                            var today = dd + '/' + mm + '/' + yyyy;
                            this.val(today);
                        }
                    }
                }
            });
        }

        //RMT 2285
        $('#dynamic-place-holder select').removeClass('validate-excluded-field');

        $('.collapsing-module select, :radio.collapsed-radio').on("change", function () {

            var selectedValue;

            if ($(this).hasClass('collapsed-radio')) {
                selectedValue = $(this).attr('data-ul-div-id');
            }
            else {
                selectedValue = $(this).find(':selected').attr('data-ul-div-id');
            }

            var targetForm = $(this).closest('form').attr('id');


            $("#" + targetForm + " #dynamic-place-holder > [id]").each(function () {
                if (selectedValue == this.id) {
                    $('#' + this.id + ' input:not(.countdown), #' + this.id + ' select, #' + this.id + ' textarea').attr('includedinemail', 'true');
                    $('#' + this.id + ' select').addClass('validate-excluded-field');
                    $('#' + selectedValue).show();
                }
                else {
                    $('#' + this.id + ' input:not(.countdown), #' + this.id + ' select, #' + this.id + ' textarea').attr('includedinemail', 'false');
                    $('#' + this.id + ' select').removeClass('validate-excluded-field');
                    $('#' + this.id).hide();
                }
            });

            $('#' + targetForm).data('bootstrapValidator').resetForm();
            $('#' + targetForm + ' #errorSummary').hide();
        });

        FormTaskListModule.Init();
    });

    $('input[type=button]').on("keyup", function (event) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });

    var FormTaskListModule = (function () {
        FormTaskList = {
            // Code initialization
            Init: function () {
                // set modal iframe setting
                FormTaskList.Render();
                FormTaskList.SetEventHandlers();
            },

            // form task list modal render
            Render: function () {
                // prepare task list modals for each form to submit/complete
                var formTaskListCount = 1;
                var formTaskListModalSelector = $('.taskListFormContent');
                var formTaskListRowLinkSelector = $('.form-action-button-complete');
                var formTaskListModal = "";

                formTaskListRowLinkSelector.each(function () {
                    //Distinct modal ID for Complete link
                    $(this).attr("data-target", "#taskListFormContent" + formTaskListCount);

                    //Distinct ID for modal
                    formTaskListModal = formTaskListModalSelector.clone();
                    formTaskListModal.attr("id", "taskListFormContent" + formTaskListCount);
                    formTaskListModal.appendTo('body');

                    //Distinct modal ID no. for Modal
                    formTaskListCount++;
                });

                // prepare task list modals for each form to submit/complete
                var formForConfirmCount = 1;
                var formForConfirmModalSelector = $('.taskListFormConfirm');
                var formForConfirmRowLinkSelector = $('.form-action-button-confirm');
                var formForConfirmModal = "";

                formForConfirmRowLinkSelector.each(function () {
                    //Distinct modal ID for Confirm link
                    $(this).attr("data-target", "#taskListFormConfirm" + formForConfirmCount);

                    //Distinct ID for modal
                    formForConfirmModal = formForConfirmModalSelector.clone();
                    formForConfirmModal.attr("id", "taskListFormConfirm" + formForConfirmCount);
                    formForConfirmModal.appendTo('body');

                    //Distinct modal ID no. for Modal
                    formForConfirmCount++;
                });

                //prepare task list modals document
                var documentTaskListModalSelector = $('.taskListDocument');
                var documentTaskListModal = "";

                documentTaskListModal = documentTaskListModalSelector.clone();
                documentTaskListModal.find("div#uploadContent > div > input#fileUpload").css("height", "inherit"); //Inherit default height of browsers file upload.
                documentTaskListModal.attr("id", "taskListDocumentIntoBody");
                documentTaskListModal.appendTo('body');

                //prepare task list modal for photo
                var photoTaskListModalSelector = $('.taskListPhoto');
                var photoTaskListModal = "";

                photoTaskListModal = documentTaskListModalSelector.clone();
                photoTaskListModal.attr("id", "taskListPhotoIntoBody");
                photoTaskListModal.appendTo('body');
            },

            // form task list event handlers
            SetEventHandlers: function () {
                /*
                 ** Event handler for checkboxe(s) in view: FormTaskList 
                 ** Handles on change event
                */
                $(document).on('change', 'input.cb-form-select-all,input.enabled', function () {
                    var checkBoxes = $("input.cb-form-select-row:enabled");

                    // verify if checbox is ticked
                    if (this.checked) {
                        checkBoxes.prop("checked", true);
                    } else {
                        checkBoxes.prop("checked", false);
                    }
                });

                // for Take Action link that opens Modal for form submission
                $(".form-action-button-complete").on("click", function (e) {
                    e.preventDefault();

                    var allowFullscreen = $(this).attr('data-bmdVideoFullscreen') || false;

                    var dataVideo = {
                        'src': $(this).attr('data-bmdSrc'),
                        'width': $(this).attr('data-bmdWidth')
                    };

                    if (allowFullscreen) dataVideo.allowfullscreen = "";

                    // set iframe
                    $($(this).attr('data-target')).find(".task-list-form-container").attr(dataVideo);
                    $($(this).attr('data-target')).find(".task-list-form-container").addClass("iframe-modal");
                });

                // for Take Action link that opens Modal for form fillup confirmation
                $(".form-action-button-confirm").on("click", function (e) {
                    e.preventDefault();

                    // get iframe attributes
                    var allowFullscreen = $(this).attr('data-bmdVideoFullscreen') || false;

                    var dataVideo = {
                        'src': $(this).attr('data-bmdSrc'),
                        'width': $(this).attr('data-bmdWidth'),
                        'submitId': $(this).attr('data-formSubmitId')
                    };

                    if (allowFullscreen) dataVideo.allowfullscreen = "";

                    // set iframe attr to yes button
                    $($(this).attr('data-target')).find(".form-confirm-yes").attr(dataVideo);
                    // set formsubmitid attr to no button
                    $($(this).attr('data-target')).find(".form-confirm-no").attr({ 'submitId': $(this).attr('data-formSubmitId') });
                });

                // for form confirm modal yes button that opens Modal for form fillup
                $(".form-confirm-yes").on("click", function (e) {
                    // get iframe attributes
                    var allowFullscreen = $(this).attr('allowFullscreen') || false;

                    var dataVideo = {
                        'src': $(this).attr('src'),
                        'width': $(this).attr('width')
                    };

                    if (allowFullscreen) dataVideo.allowfullscreen = "";

                    // prepare form modal
                    var formTaskListModalSelector = $('#taskListFormContent');
                    //Distinct ID for modal
                    formTaskListModal = formTaskListModalSelector.clone();
                    formTaskListModal.attr("id", "taskListFormContent" + $(this).attr('submitId'));
                    formTaskListModal.appendTo('body');

                    // set iframe
                    formTaskListModal.find(".task-list-form-container").attr(dataVideo);
                    formTaskListModal.find(".task-list-form-container").addClass("iframe-modal");

                    // set refresh in pop up for ESIC Only
                    formTaskListModal.find(".popup-form-close").on("click", function (e) {
                        // reload the page
                        window.location.reload(true);
                    });

                    // show form modal
                    formTaskListModal.modal("show");
                });

                // for form confirm modal no button that marks the form as not required
                $(".form-confirm-no").on("click", function (e) {
                    // get iframe attributes
                    var submitId = $(this).attr('submitId') || false;
                    // call api to mark form as not required
                    $.ajax({
                        type: "POST",
                        url: "/api/sitecore/FormStatus/UpdateStatus",
                        data: { 'submitId': submitId, 'status': "Not Required" },
                        success: function (data) {
                            // reload the page
                            window.location.reload(true);
                        }
                    });
                });

                // for pop up form - CLOSE
                $(".popup-form-close").on("click", function (e) {
                    // reload the page
                    window.location.reload(true);
                });

                //for Documents Purposes
                $(".document-action-button-upload").on("click", function (e) {
                    e.preventDefault();

                    var documentName = $(this).attr('data-documentName') || false;
                    var joinerType = $(this).attr('data-joinerType') || false;
                    var documentHeader = $(this).attr('data-documentHeader') || false;

                    //for Relieving Letter
                    var relievingLetterPopUp = false;
                    if (joinerType == "0") {
                        relievingLetterPopUp = true;
                    }

                    //clear data
                    $("#taskListDocumentIntoBody #uploadHeaderContent").empty();
                    $("#taskListDocumentIntoBody #uploadHeaderContent").append("Upload " + documentHeader);
                    //document.getElementById("#taskListDocumentIntoBody #fileUpload").value = "";
                    //$("#taskListDocumentIntoBody #fileUpload").replaceWith(input.val('').clone(true));

                    // set the refresh button for close
                    $($(this).attr('data-target')).find(".document-close").attr({ 'isUploaded': false });

                    if (documentName == "IDDOBProof") {
                        $("#taskListDocumentIntoBody #iDDOBProofContent").show();
                        $("#taskListDocumentIntoBody #relievingLetterContent").hide();
                        $("#taskListDocumentIntoBody #relievingLetterContentNotRequired").hide();
                        $("#taskListDocumentIntoBody #uploadContent").show();
                        $("#taskListDocumentIntoBody #uploadButtons").show();
                    }
                    else if (documentName == "Relievingletter" && relievingLetterPopUp == true) {
                        $("#taskListDocumentIntoBody #iDDOBProofContent").hide();
                        $("#taskListDocumentIntoBody #relievingLetterContent").show();
                        $("#taskListDocumentIntoBody #relievingLetterContentNotRequired").hide();
                        $("#taskListDocumentIntoBody #uploadContent").hide();
                        $("#taskListDocumentIntoBody #uploadButtons").hide();
                    }
                    else {
                        $("#taskListDocumentIntoBody #iDDOBProofContent").hide();
                        $("#taskListDocumentIntoBody #relievingLetterContent").hide();
                        $("#taskListDocumentIntoBody #relievingLetterContentNotRequired").hide();
                        $("#taskListDocumentIntoBody #uploadContent").show();
                        $("#taskListDocumentIntoBody #uploadButtons").show();
                    }

                    //button upload/close tagging
                    $("#taskListDocumentIntoBody #btnUpload").show();
                    $("#taskListDocumentIntoBody #btnClose").hide();

                    // set documentid attr to no button
                    $($(this).attr('data-target')).find(".document-yes").attr({ 'documentId': $(this).attr('data-documentID') });
                    $($(this).attr('data-target')).find(".document-no").attr({ 'documentId': $(this).attr('data-documentID') });

                    $($(this).attr('data-target')).find(".document-upload").attr({ 'documentId': $(this).attr('data-documentID') });
                    $($(this).attr('data-target')).find(".document-upload").attr({ 'documentName': $(this).attr('data-documentName') });
                    $($(this).attr('data-target')).find(".document-upload").attr({ 'userProfileId': $(this).attr('data-userProfileId') });
                });

                // for pop up document - CLOSE
                $(".popup-document-close").on("click", function (e) {
                    // reload the page
                    window.location.reload(true);
                });

                // for relievingLetter button - CLOSE
                $(".document-close").on("click", function (e) {
                    // reload the page
                    window.location.reload(true);
                });

                // for relievingLetter button - YES
                $(".document-yes").on("click", function (e) {
                    // get attributes
                    var documentId = $(this).attr('documentId') || false;

                    $("#taskListDocumentIntoBody #uploadContent").show();
                    $("#taskListDocumentIntoBody #uploadButtons").show();
                });

                // for relievingLetter button - NO
                $(".document-no").on("click", function (e) {
                    // get attributes
                    var documentId = $(this).attr('documentId') || false;
                    // call api to mark form as not required
                    $.ajax({
                        type: "POST",
                        url: "/api/sitecore/FormStatus/UpdateStatus",
                        data: { 'submitId': documentId, 'status': "Not Required" },
                        success: function (data) {
                            // reload the page
                            //window.location.reload(true);

                            //show Not Required label
                            $("#taskListDocumentIntoBody #relievingLetterContentNotRequired").show();
                            $("#taskListDocumentIntoBody #uploadButtons").show();

                            //for relieving letter - radio button disable
                            $(".document-yes").attr('disabled', true);
                            $(".document-no").attr('disabled', true);

                            //button upload/close tagging
                            $("#taskListDocumentIntoBody #btnUpload").hide();
                            $("#taskListDocumentIntoBody #btnClose").show();
                        }
                    });
                });

                // for button - UPLOAD
                $(".document-upload").on("click", function (e) {
                    // get attributes
                    var documentId = $(this).attr('documentId') || false;
                    var documentName = $(this).attr('documentName') || false;
                    var userProfileId = $(this).attr('userProfileId') || false;

                    var files = $("#taskListDocumentIntoBody #fileUpload").prop("files");

                    // call api to mark form as not required
                    (function (file) {
                        var fileReader = new FileReader();
                        fileReader.onload = function (f) {
                            $.ajax({
                                type: "POST",
                                url: "/api/sitecore/UploadDocument/UploadDoc",
                                data: {
                                    'documentFileName': documentName, 'fileNameExt': file.name.toLowerCase(), 'userProfileId': userProfileId, 'fileUpload': f.target.result
                                },
                                success: function (result) {

                                    //clear result first
                                    $("#taskListDocumentIntoBody #resultPreview").empty();
                                    $("#taskListDocumentIntoBody #resultPreview").append(result.split(";")[0]);

                                    if (result.split(";")[1] == "true") {
                                        $.ajax({
                                            type: "POST",
                                            url: "/api/sitecore/FormStatus/UpdateStatus",
                                            data: { 'submitId': documentId, 'status': "For Approval" },
                                            success: function (data) {

                                                //for relieving letter - radio button disable
                                                $(".document-yes").attr('disabled', true);
                                                $(".document-no").attr('disabled', true);

                                                //button upload/close tagging
                                                $("#taskListDocumentIntoBody #btnUpload").hide();
                                                $("#taskListDocumentIntoBody #btnClose").show();

                                                //for PAN Card Logic only
                                                if (documentName == "PANcardcopy") {
                                                    $.ajax({
                                                        type: "POST",
                                                        url: "/api/sitecore/FormStatus/UpdateStatus",
                                                        data: { 'submitId': "d91dbdd0-2884-421f-9e70-dd407e4b25d0", 'status': "Not Required" },
                                                        success: function (data) {
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        };

                        fileReader.readAsDataURL(file);
                    })(files[0]);
                });
            },
        };

        return FormTaskList;
    })();
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\MediaPlayerModule.js
//version=34"
if (ComponentRegistry.MediaPlayer) {
    var vid;
    var vidObj;
    var carouselIds = [];
    var widthAdjustment = 10; //10 is for the padding added for component class
    var pageCarousel = $('.carousel');
    if (!jQuery().appear) {
        /*
		 * jQuery appear plugin
		 *
		 * Copyright (c) 2012 Andrey Sidorov
		 * licensed under MIT license.
		 *
		 * https://github.com/morr/jquery.appear/
		 *
		 * Version: 0.3.3
		 */
        (function ($) {
            var selectors = [];

            var check_binded = false;
            var check_lock = false;
            var defaults = {
                interval: 250,
                force_process: false
            }
            var $window = $(window);

            var $prior_appeared;

            function process() {
                check_lock = false;
                for (var index = 0; index < selectors.length; index++) {
                    var $appeared = $(selectors[index]).filter(function () {
                        return $(this).is(':appeared');
                    });

                    $appeared.trigger('appear', [$appeared]);

                    if ($prior_appeared) {
                        var $disappeared = $prior_appeared.not($appeared);
                        $disappeared.trigger('disappear', [$disappeared]);
                    }
                    $prior_appeared = $appeared;
                }
            }

            // "appeared" custom filter
            $.expr.pseudos['appeared'] = function (element) {
                var $element = $(element);
                if (!$element.is(':visible')) {
                    return false;
                }

                var window_left = $window.scrollLeft();
                var window_top = $window.scrollTop();
                var offset = $element.offset();
                var left = offset.left;
                var top = offset.top;

                if (top + $element.height() >= window_top &&
                    top - ($element.data('appear-top-offset') || 0) <= window_top + $window.height() &&
                    left + $element.width() >= window_left &&
                    left - ($element.data('appear-left-offset') || 0) <= window_left + $window.width()) {
                    return true;
                } else {
                    return false;
                }
            }

            $.fn.extend({
                // watching for element's appearance in browser viewport
                appear: function (options) {
                    var opts = $.extend({}, defaults, options || {});
                    var selector = this.selector || this;
                    if (!check_binded) {
                        var on_check = function () {
                            if (check_lock) {
                                return;
                            }
                            check_lock = true;

                            setTimeout(process, opts.interval);
                        };

                        $(window).on("scroll", on_check).on("resize", on_check);
                        check_binded = true;
                    }

                    if (opts.force_process) {
                        setTimeout(process, opts.interval);
                    }
                    selectors.push(selector);
                    return $(selector);
                }
            });

            $.extend({
                // force elements's appearance check
                force_appear: function () {
                    if (check_binded) {
                        process();
                        return true;
                    };
                    return false;
                }
            });
        })(jQuery);
    }
    

    $(function () {
        resizeVideo();
        $(window).on("resize", function () {
            window.setTimeout(resizeVideo(), 100);
        });

        // auto-play video on click to video thumbnail
        $('#media-video-thumbnail .icon-circle, #media-video-thumbnail img').on("click touchstart", function () {

            var videoObj2 = $(this).closest('.media-container').find(".white_content");

            if (videoObj2.length > 0) {

                var headNav = $("#header-topnav").clone();
                var jumpLink = $("#block-jumplink").clone();

                $(this).closest('.media-container').prepend(headNav);
                $(this).closest('.media-container').prepend(jumpLink);

                $("#header-topnav").hide();
                $("#block-jumplink").hide()

                $(this).closest('.media-container').find("#block-jumplink").css('left', '0');
                $(this).closest('.media-container').find("#header-topnav").css('z-index', '1001');
                $(this).closest('.media-container').find(".navbar-default .navbar-nav > li > a > span").css('color', '#000');

                videoObj2.css('display', 'block');
                $(this).closest('.media-container').parent().find('.black_overlay').css('display', 'block');
                ComponentRegistry.MediaPlayer.ShowComponentsUnderVideoOverlay(false);
                if (IsTouch()) {
                    $("html").css({ "overflow": "hidden", "position": "relative" });
                }
                else {
                    $("html").css({ "overflow": "hidden" });
                }

            } else {
                $(this).closest('.media-container').find('#media-video-thumbnail').hide();
            }


        });

        $('.popupvid-x-button-container').on("click touchstart", function () {

            var videoModal = $(this).closest('.media-container').find(".white_content");
            videoModal.css('display', 'none');

            $("#header-topnav").show();
            $("#block-jumplink").show();

            $(this).closest('.media-container').find("#header-topnav").remove();
            $(this).closest('.media-container').find("#block-jumplink").remove();
            $(this).closest('.media-container').parent().find('.black_overlay').css('display', 'none');

            $("html").css({ "overflow": "auto", "position": "relative" });

            if (IsTouch() === true) {
                var vid = $(this).closest('.white_content').find("video")[0];
                if (vid.play) {
                    vid.pause();
                }
            }
            

            ComponentRegistry.MediaPlayer.ShowComponentsUnderVideoOverlay(true);

        });

        //RMT 6072 closing limelightvideo
        var accordionCloseVideo = $('.container-claster .close-video-accordion');
        accordionCloseVideo.on("click  touchstart", function () {
            //Check if the limelight player is playing.
            //Check if the limelight player is playing.
            if (IsTouch() === true) {
                var vid = $(this).closest('.container-claster').find("video")[0];
                try {
                    if (vid.play) {
                        vid.pause();
                    }
                } catch (e) {

                }
            }



        });
        //RMT 6072 playing limelightvideo
        var accordionClickVideo = $('.container-claster .icon-chevron_thin');
        accordionClickVideo.on("click", function (e) {

            if (isMobile()) {

                $accordionHeight = $(this).closest('.container-claster').find('.media-container img');

                if ($accordionHeight.length == 1) {
                    $(this).closest('#video-accordion').css({ 'overflow': 'hidden', 'height': $accordionHeight.height() });

                } else {
                    $(this).closest('#video-accordion').css({ 'overflow': 'hidden', 'height': '370px' });

                }

                $(this).closest('container-claster').find('iframe').css({ 'height': '350px' });
            }
            autoPlayVideo(videoObj); //play video       
        });

        function handleIt() {
            if ($(this).hasClass("close")) {
                $(this).removeClass("close");
                $(".widget1x1Back").next(".actionsHolder3").slideUp("fast", function () {
                    $(this).remove();
                });
            } else {

                var iconsList = $(this).closest(".top1x1").next(".hdnActnLst").find(".iconsHolder3").html();
                $(this).closest(".widget1x1").append(iconsList);
                $(this).closest(".widget1x1").find(".actionsHolder3").hide();
                $(this).closest(".widget1x1").find(".actionsHolder3").slideDown(700, "easeOutBack");
                $(this).addClass("close");
            }
        }

        $(".download-transcript-container a").on('keydown', function (e) {
            if (e.which == 9) {
                e.preventDefault();
                if ($(this).is(":focus")) {
                    $('.popupvid-x-button').trigger("focus");
                }
            }
        });

        $('.white_content span').attr("tabindex", 0);
        $('.white_content .popupvid-x-button').attr("aria-label", "close");

        // SIR #425575 - Current/Prospective Client Index page: Video files are not properly displayed on page
        $(".carousel.slide .carousel-indicators li").on("click", function () {
            window.setTimeout(function () { resizeVideo(); }, 100);
        });

        //on slide event, resize videos
        $(".convCarousel-mobile .carousel.slide, .convCarousel-tablet .carousel.slide, .convCarousel-desktop .carousel.slide").on("slide.bs.carousel", function () {
            window.setTimeout(function () { resizeVideo(); }, 100);
        });

        // attach appear plugin to video thumbnail container
        $('div[data-video-player-id]').appear();

        /* detect appearance of the video and trigger auto-play */
        function handleVideoAppear() {
            var $videoThumbnail = $('#media-video-thumbnail');
            if ($videoThumbnail.is(":visible")) {
                $(document.body).on('appear', 'div[data-video-player-id]', function (e, $affected) {
                    autoPlayVideo();
                });
            }
        };

        // attach appear plugin to video object
        var videoPlayerID = $("div[data-video-player-id]").attr("data-video-player-id");
        var videoObjectSelector = "object[id='" + videoPlayerID + "']";
        var disTimer = 0;
        $(videoObjectSelector).appear();


        // function for auto-playing the video; implements Limelight callback in order to be able to succesfully communicate with the video player
        function autoPlayVideo(selectedVideo) {
            if (selectedVideo != null) {
                var parent_container = selectedVideo.closest('.media-container');
                var playerId = selectedVideo.attr('id');

                if (selectedVideo.find('param[name="state"]').length > 0) {
                    selectedVideo.find('param[name="state"]').val("isPlaying");
                }

                resizeVideoObject(selectedVideo);

                try {
                    var vid2 = document.getElementById(playerId).getElementsByTagName('video')[0];
                    if (vid2.paused) {
                        vid2.play();
                        ComponentRegistry.MediaPlayer.SkipPlayPauseAnalyticsTracking(true, false);
                    } else {
                        ComponentRegistry.MediaPlayer.SkipPlayPauseAnalyticsTracking(false, true);
                        vid2.pause();
                    }
                } catch (e) {
                    //LimelightPlayer.registerPlayer(playerId);
                    //LimelightPlayer.getPlayer(playerId).doPlay();
                    //document.getElementById(playerId).doPlay();
                }
            }
        };

        /* RMT 3674 -- START */
        var imageContainterDownloadModule = $(".image-container #DownloadModule");
        /* Image-Container for Desktop / Tablet must use primary color */
        if (isMobile() === false && imageContainterDownloadModule.length != 0) {
            $(imageContainterDownloadModule).find("a, span").addClass("color-primary");
        }

        /* primary color must not be white */
        if ($("head link[href*='white.min.css']").length == 0) {
            if (isMobile() === true) {
                var imageContainterDownloadModule = $(".image-container.white #DownloadModule");
                if (imageContainterDownloadModule.length != 0) {
                    $(imageContainterDownloadModule).find("a, span").addClass("color-primary");
                }
            }
            var colorContainerDownloadModule = $(".color-container.white #DownloadModule");
            if (colorContainerDownloadModule.length != 0) {
                $(colorContainerDownloadModule).find("a, span").addClass("color-primary");
            }
        }
        /* RMT 3674 -- END */
    });

    function resizeVideo() {

        $("div.media-container #media-video-thumbnail img").filter(":visible").each(function (index) {
            var $this = $(this);
            var parent = $this.closest('div[class^="col-sm"]');
            var parentWidth = parent.width();
            var origWidth = parseInt($(this).data("width"));

            if ($('.onboarding').length == 0) {
                if ($this.width() > parentWidth) {
                    $this.css({ 'width': parentWidth + 'px' });
                }
                else if (origWidth > parentWidth) {
                    $this.css({
                        'width': parentWidth + 'px'
                    });
                } else {
                    $this.css({
                        'width': origWidth + 'px'
                    });
                }
            } else {
                if ($this.width() > parentWidth || origWidth > parentWidth) {
                    $this.css({ 'width': parentWidth + 'px' });
                } else {
                    $this.css({
                        'width': origWidth + 'px'
                    });
                }
            }
        });
    }
    

    function resizeVideoObject($this) {
        var onboardingPage = $('.onboarding');
        var aspectRatioHeight = 0.5625; // 16:9 default aspect ratio
        var parent, parentWidth;
        var vidOnHeroCarousel = $this.closest("#block-hero").length;
        var vidOverlay = $this.closest(".white_content").length;

        if (vidOnHeroCarousel > 0) {
            parent = $('#block-hero .item.active .hero-title-wrapper');
            parentWidth = parent.width();


            // changed native function to hardcoded condition for bug#391844
            if ($(window).width() < 767 && $(window).width() > $(window).height()) {
                parentWidth = parentWidth - 150;
                computedHeight = (parentWidth * 9) / 16;
            } else if ($(window).width() > 1000) {
                parentWidth = parentWidth - 200;
                computedHeight = (parentWidth * 9) / 16;
            } else {
                computedHeight = (parentWidth * 9) / 16;
            }

            var vidOvrlyCont = $(".white_content");
            var topPos = ($(window).height() - (computedHeight + 63)) / 2;
            var leftPos = ($(window).width() - parentWidth) / 2;
            vidOvrlyCont.css({ 'top': topPos + 'px', 'left': leftPos + 'px' });

            $this.css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', });
            if ($this.find("video").length > 0) {
                $this.find("video").css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', 'margin-left': '0px' });
            }
        } else {
            parent = $this.closest('div[class^="col-sm"]');
            parentWidth = parent.width();
            var origWidth = "";
            origWidth = parseInt($this.data("orig-width"));


            var origHeight = parseInt($this.data("orig-height"));

            if (onboardingPage.length == 0) {
                if (origWidth > 0 && origHeight > 0) {
                    var tempAR = origHeight / origWidth;
                    if (tempAR > 0.73 && tempAR < 0.77) {
                        aspectRatioHeight = 0.75;
                    }
                }

                var mediaWidth = 0;
                if ($this.closest("div.media").length > 0) {
                    mediaWidth = $this.closest("div.media").width();
                } else if ($this.closest("div.video-placeholder").length > 0) {
                    mediaWidth = $this.closest("div.video-placeholder").width() + widthAdjustment;
                } else if ($this.closest("div.component").length > 0) {
                    mediaWidth = $this.closest("div.component").width();
                }

                //Bug for videos inside packery
                if ($this.closest('.packery-item').length > 0) {
                    parentWidth = $this.closest('.packery-item').width();
                } else if ($this.closest('.packery-component').length > 0) {
                    parentWidth = $this.closest('.packery-component').width();
                }

                if ($this.width() > parentWidth) {
                    var appliedWidth = parentWidth - widthAdjustment;
                    if (mediaWidth != 0 && mediaWidth < parentWidth) {
                        appliedWidth = mediaWidth - widthAdjustment;
                    }
                    var computedHeight = appliedWidth * aspectRatioHeight;
                    $this.attr({
                        'width': appliedWidth + 'px', 'height': computedHeight + 'px'
                    }).css({ 'width': appliedWidth + 'px', 'height': computedHeight + 'px', });
                } else {
                    if (origWidth > parentWidth) {
                        var appliedWidth = parentWidth;
                        if (mediaWidth != 0 && mediaWidth < origWidth) {
                            appliedWidth = mediaWidth - widthAdjustment;
                        }
                        var computedHeight = appliedWidth * aspectRatioHeight;
                        $this.attr({
                            'width': appliedWidth + 'px', 'height': computedHeight + 'px'
                        }).css({ 'width': appliedWidth + 'px', 'height': computedHeight + 'px', });
                    } else if (!isNaN(origWidth)) {
                        var appliedWidth = origWidth;
                        if (mediaWidth != 0 && mediaWidth < origWidth) {
                            appliedWidth = mediaWidth - widthAdjustment;
                        }
                        var computedHeight = appliedWidth * aspectRatioHeight;
                        $this.attr({
                            'width': appliedWidth + 'px', 'height': computedHeight + 'px'
                        }).css({ 'width': appliedWidth + 'px', 'height': computedHeight + 'px', });
                    }
                }
            } else {

                //For videos inside blog overlay / carousel (onboarding page only)
                var parentCarousel = $this.closest('.carousel-inner');
                if (parent.width() == 100 && parentCarousel.length > 0) {	// checks if parent returns 100 from 100% width value
                    var parentItem = parentCarousel;
                    parentWidth = parentItem.width();
                } else if (parent.width() == 50 && parentCarousel.length > 0) {
                    var newParentItem = $this.closest('.module-article');
                    parentWidth = newParentItem.innerWidth();
                }

                if ($this.closest('.item > .col-sm-6').length > 0 && parentCarousel.length > 0) {
                    var newParentItem = $this.closest('.module-article');
                    parentWidth = newParentItem.innerWidth() - 20;
                }

                var browserWidth = 768;
                if ($(window).width() < browserWidth) {
                    //Bug 344945 get width of packery item on some cases
                    if ($('.packery-item').width() > 0)
                        parentWidth = $('.packery-item')[0].getBoundingClientRect().width;
                    //$("#container")[0].getBoundingClientRect().width
                    else parentWidth = $('.packery-container').width();
                    //parentWidth = '244';
                    computedHeight = (parentWidth * 9) / 16;
                    $this.css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', });
                }
                else {
                    computedHeight = (parentWidth * 9) / 16;
                    $this.css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', });
                }
                if ($this.find("video").length > 0) {
                    $this.find("video").css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', });
                }
            }


            if (vidOverlay > 0) {

                parent = $('#block-hero .item.active .hero-title-wrapper');
                parentWidth = parent.width();

                if ($(window).width() < 767 && $(window).width() > $(window).height()) {
                    parentWidth = parentWidth - 150;
                    computedHeight = (parentWidth * 9) / 16;
                } else if ($(window).width() > 1000) {
                    parentWidth = parentWidth - 200;
                    computedHeight = (parentWidth * 9) / 16;
                } else {
                    computedHeight = (parentWidth * 9) / 16;
                }

                var vidOvrlyCont = $(".white_content");
                var topPos = ($(window).height() - (computedHeight + 63)) / 2;
                var leftPos = ($(window).width() - parentWidth) / 2;
                vidOvrlyCont.css({ 'top': topPos + 'px', 'left': leftPos + 'px' });

                $this.css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px' });
                if ($this.find("video").length > 0) {
                    $this.find("video").css({ 'width': parentWidth + 'px', 'height': computedHeight + 'px', 'margin-left': '0px' });
                }
            }
        }
    }

    // Unused Function and vid variable
    function toggleFullScreen() {
        if (!vid) {
            return;
        }

        if (vid.requestFullScreen) {
            vid.requestFullScreen();
        } else if (vid.webkitRequestFullScreen) {
            vid.webkitRequestFullScreen();
        } else if (vid.mozRequestFullScreen) {
            vid.mozRequestFullScreen();
        }
    }

    ComponentRegistry.MediaPlayer = {
        Cache: {
            Keys: {
                AutoPlayExecuted: "mpm_autoplayexecuted",
                AutoPlay: "mpm_autoplay",
                AutoPause: "mpm_autopause"
            }
        },

        SkipPlayPauseAnalyticsTracking: function (isPlayerPlay, isPlayerPause) {

            acncm.CacheManager.write(ComponentRegistry.MediaPlayer.Cache.Keys.AutoPlayExecuted, 1);

            if (isPlayerPlay) {
                acncm.CacheManager.write(ComponentRegistry.MediaPlayer.Cache.Keys.AutoPlay, 1);
            }
            if (isPlayerPause) {
                acncm.CacheManager.write(ComponentRegistry.MediaPlayer.Cache.Keys.AutoPause, 1);
            }
        },

        ShowComponentsUnderVideoOverlay: function (shouldDisplay) {
            var $contentWrapper = jQuery("#content-wrapper");
            var $headerNav = jQuery("#header-topnav");
            var $jumpLink = jQuery("#block-jumplink");
            var $popover = jQuery("div.acn-popover div.popover.top");
            if (shouldDisplay) {
                $contentWrapper.removeAttr("style");
                $headerNav.removeAttr("style");
                $jumpLink.removeAttr("style");
                $popover.removeAttr("style");
            } else {
                $contentWrapper.css("z-index", "10");
                $headerNav.css("z-index", "1");
                $jumpLink.css("z-index", "10");
                $popover.css("z-index", "1001");
            }

        }

    };
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\accordionmodule.js
/* version="11"*/
if (ComponentRegistry.AccordionContentModule) {
    $(function () {
        //initialize accordionBlindControl
        accordionBlindControl.init();

        $('.accordionModule').each(function () {
            $(this).on('keydown', function (e) {
                if (e.which == 13) {
                    e.preventDefault();
                    $(this).trigger("click");
                }
            })
        })

    });

    //[RMT 6684][US004][Blinds Module - Video]
    var ratio = 0.5625;
    var accordionVideoCover = $(".accordion-video-cover");

    $(window).on('load resize orientationchange', function () {
        accordionVideoCover.css("width", accordionVideoCover.closest(".panel-group").width() + "px");
        accordionVideoCover.css("height", accordionVideoCover.closest(".panel-group").width() * ratio + "px");

        //Bug 544464 - [RMT6684][US014] Mobile Video not renderred properly in Portrait View
        if ($(window).width() < 767 && $(window).innerWidth() < $(window).innerHeight()) {
            $(".accordion-video-partial").css("overflow", "hidden");
        }
    });
}

var accordionBlindControl = (function () {
    //public api
    var init = function () {

        var panelHeading = $(".panel-heading.col-sm-12");
        var panelGrp = $(".panel-group");
        var panelCollapse = $(".panel-collapse.col-sm-12");
        var accordionLink = $(".accordion-link");
        var altTextExpand = $('#accordionContentAlternateTextCollapse').val();
        var altTextCollapse = $('#accordionContentAlternateTextExpand').val();

        panelHeading.each(function () {
            var parentContainer = $(this).parent().parent().attr("id");
            var childContainer = $(this).attr("id");

            if (parentContainer != undefined && childContainer != undefined) {
                $("#" + childContainer).attr("data-parent", "#" + parentContainer);
                $("#" + childContainer).attr("id", parentContainer + "-" + $("#" + childContainer).attr("id"));
            }
        });

        panelCollapse.each(function () {
            $(this).attr("id", "collapse-" + $(this).prev().attr("id"));
            $(this).prev().attr("href", "#" + $(this).attr("id"));
        });

        //fix for Bootstrap Accordion known bug
        panelGrp.children().on("click", function (e) {
            if ($(e.currentTarget).siblings().children(".collapsing").length > 0) {
                return false;
            }
        })

        accordionLink.on('click', function () {
            url = $(this).attr('href');
            window.open(url, '_self');
        })

        //switching class for icon
        function toggleIcon(e) {
            var current = $(e.target)
                .prev('.panel-heading')
                .find(".accordion-icon");
            current.toggleClass("icon-chevronthin icon-chevron_thin" + " " + "icon-accordion-close-thin icon-x-close");

            if ($(current).hasClass('icon-x-close')) {
                $(current).attr('title', altTextExpand);
            }
            else {
                $(current).attr('title', altTextCollapse);
            }
        }

        panelGrp.on('hidden.bs.collapse', toggleIcon);
        panelGrp.on('shown.bs.collapse', toggleIcon);

        //Analytics for Accordion Module Expand and Collapse
        var headerTitle = "";
        var $accordionModule = jQuery(".accordionModule");
        for (var i = 0; i < $accordionModule.length; i++) {
            var $accordion = jQuery($accordionModule[i]);
            getHeaderTitle($accordion);
            $accordion.attr("data-analytics-link-name", headerTitle + "/expand");
        }

        $accordionModule.on("click", function () {
            var linkType = 'engagement';
            var $element = jQuery(this);
            getHeaderTitle($element);

            var linkactioncollapse = headerTitle + '/collapse';
            var linkactionexpand = headerTitle + '/expand';

            if ($element.hasClass('collapsed')) {
                $element.attr('data-linkaction', linkactionexpand);
                $element.attr('data-analytics-link-name', linkactioncollapse);
            }
            else {
                $element.attr('data-linkaction', linkactioncollapse);
                $element.attr('data-analytics-link-name', linkactionexpand);
            }

            $element.attr('data-linktype', linkType);
            $element.attr('data-analytics-content-type', linkType);

            //RMT 8878 - Videos on accordion module playing simultaneously			
            var accordionTab = $element.closest('.panel-group');
            var tabVideo = accordionTab.find('.panel-collapse.in').find('iframe[id^="ytim-player"]');

            var stopVideoParam = {"event": "command", "func": "stopVideo", "args": ""}
            var youtubeStopVideo = JSON.stringify(stopVideoParam);

            tabVideo.each(function () {
                var $this = $(this);
                $this[0].contentWindow.postMessage(youtubeStopVideo, '*');
            });
        })

        function getHeaderTitle($element) {
            headerTitle = "";
            if ($element.find(".accordion-left h3").length) {
                headerTitle = $element.find("h3").text().trim().toLowerCase();
            }
            else {
                if ($element.find(".accordion-left img").length) {
                    if ($element.find(".accordion-right span").length) {
                        headerTitle = $element.find(".accordion-right").text().trim().toLowerCase();
                    }
                    else {
                        headerTitle = $element.find(".accordion-left img").attr("alt").toLowerCase();
                    }
                }
            }
        }
    }

    return {
        init: init,
    }
})();
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\image-gallery.js
/* version="2" */
if ((typeof (ComponentRegistry.ImageGallery) === undefined) && (typeof (ComponentRegistry.IndustryAllAdsFilter) === undefine)) {
    //undefined componentst
}
else {
    if (ComponentRegistry.ImageGallery || ComponentRegistry.IndustryAllAdsFilter) {
        var itemId;
        var finalHeight;
        var finalWidth;
        var itemsPerScreen;
        var leftDistance = 0;
        var itemType;
        var $galleryItem;
        var $paginationItem;
        var gallerycarouselid
        var gallerypagerid;
        var showModal = false;
        var itemsToRevert = 0;
        var $parentGalleryItem;
        var itemTypeDesktop = 'Desktop';
        var itemTypeTablet = 'Tablet';
        var itemTypeMobile = 'Mobile';
        var galleryCollection = window.localStorage;
        var windowWidth;
        var maxHeight;
        var currentWidth;

        //Bug # 238466 : [.Com Content Base][Mobile and Tablet][All]Multi-media plug-in for new tech: Images are compressed when viewed on mobile and tablet.
        //Bug # 383442 : All Layout: The Image galley is not displaying when View Image Gallery is clicked

$(function () {
            $('.btnviewgallery').on("keypress", function (e) {
                if (e.which == 13) {
                    $(this).trigger("click");
                }
            });

            $('.btnclose-gallery').on("keypress", function (e) {
                if (e.which == 13) {
                    $(this).trigger("click");
                }
            });

        });

        function LoadGallery() {
            windowWidth = $(window).width();
            maxHeight = $(window).height() - 298;

            gallerycarouselid = '#gallery-carousel' + itemId;
            gallerypagerid = "#gallery-pager" + itemId;

            setPrependItems();
            $parentGalleryItem = $galleryItem.parent();
            initializeGallery();
            resetGalleryItems();

            if (itemType == itemTypeMobile)
                initializeGallery();


            $paginationItem = $(gallerypagerid + " a");
            setWidthItem();

            formatPager(itemsPerScreen - 1);
        }

        function initializeGallery() {

            var prevBtn = $('#view-gallery-overlay' + itemId + ' :button#caroufredprev')
            nextBtn = $('#view-gallery-overlay' + itemId + ' :button#caroufrednext');
            var btnDisplay = "block";
            var enableMouse = false;
            var enableTouch = false;

            if (windowWidth < 1000) {
                btnDisplay = "none";
                enableMouse = true;
                enableTouch = true;
            }

            $parentGalleryItem.carouFredSel({
                items: {
                    visible: 1,
                    start: 0
                },
                circular: true,
                infinite: true,
                direction: "left",
                width: '100%',
                align: "center",
                scroll: {
                    items: 1,
                    duration: 1000,
                    pauseOnHover: true
                },
                pagination: {
                    container: gallerypagerid,
                    deviation: 0
                },
                swipe: {
                    onMouse: enableMouse,
                    onTouch: enableTouch
                },
                prev: { button: '#caroufredprev' },
                next: { button: '#caroufrednext' }
            });
            nextBtn.css("display", btnDisplay);
            prevBtn.css("display", btnDisplay);
        }

        function resetGalleryItems() {
            //SMDB 6.29.15 Edited this function for Production issue #1196 - Gallery not resetting.
                galleryCollection.setItem('galleryCollectionItems', $galleryItem.parent().html());
                galleryCollection.setItem('currentPager', '1');
                $parentGalleryItem.html(galleryCollection.getItem('galleryCollectionItems'));
                setPrependItems();
        }
        function setPrevNextButtons(height) {
            var btnTopLocation = (height / 2) + 5;
            $('#caroufredprev').css("top", btnTopLocation);
            $('#caroufrednext').css("top", btnTopLocation);
        }
        function setWidthItem() {
            var widthItem = windowWidth - 210
            widthDesktop = windowWidth / 1.5
            widthMobileTablet = widthItem;
            $paginationItem = $(gallerypagerid + " a");
            if (windowWidth < 768) {
                $galleryItem.each(function (ctr) { if (ctr > 7) { $(this).remove(); } });
                $paginationItem.each(function (ctr) { if (ctr > 7) { $(this).remove(); } });
                itemType = itemTypeMobile;
                currentWidth = widthMobileTablet;
                resizeGalleryItems();
            }
            else if (1000 > windowWidth > 768) {
                itemType = itemTypeTablet;
                currentWidth = widthDesktop;
                setPaginationItems();
                resizeGalleryItems();
            }
            else {
                itemType = itemTypeDesktop;
                currentWidth = widthDesktop;
                setPaginationItems();
                resizeGalleryItems();
                setPrevNextButtons(finalHeight);

                var defaultImagePadding = 80;
                var widthWithPadding = finalWidth + defaultImagePadding;
                itemsPerScreen = Math.floor(windowWidth / widthWithPadding);
                var excessWidth = windowWidth - (itemsPerScreen * (widthWithPadding));
                var caroufredselHeight = finalHeight + 100;
                var centerwindowWidth = windowWidth / 2;
                var totalPrependItemsWidth = (itemsPerScreen - 1) * (widthWithPadding);
                var centerWidthFirstItem = widthWithPadding / 2;
                leftDistance = 0 - ((totalPrependItemsWidth - centerwindowWidth) + centerWidthFirstItem);
                $('.caroufredsel_wrapper').css("left", leftDistance);
                //console.log(itemsPerScreen);

            }
        }
        function formatPager(itemsToPrepend) {
            if (itemType == itemTypeDesktop) {
                setPrependItems();
                while (itemsToPrepend != 0) {
                    $galleryItem.last().prependTo(gallerycarouselid);
                    itemsToPrepend--;
                    $galleryItem = $(gallerycarouselid + " .gallery-item").not('[style*="none"]');
                }

            }
        }

        function resizeGalleryItems() {
            $galleryItem.each(function () {
                $this = $(this);
                $this.width(currentWidth);
                var currentImage = $this.find('img')[0];
                var imgHeight = currentImage.height;
                var imgWidth = currentImage.width;
                var divWidth = $this.width();
                var widthDifference = divWidth - imgWidth;
                var widthPercentageIncrease = widthDifference / imgWidth;
                var heightIncrease = widthPercentageIncrease * imgHeight;
                var divHeight = heightIncrease + imgHeight;
                finalHeight = divHeight;

                if (divHeight > maxHeight) {
                    var heightDifference = divHeight - maxHeight;
                    var heightPercentageIncrease = heightDifference / divHeight;
                    var widthDecrease = heightPercentageIncrease * divWidth;
                    divWidth = divWidth - widthDecrease;
                    divHeight = maxHeight;
                    $this.width(divWidth);
                    finalHeight = maxHeight;
                }
                finalWidth = divWidth;
            });
        }

        function setPaginationItems() {
            //Bug 197860: Pagination dots 15 per row
            var pCount = ($paginationItem.length);
            if (pCount > 15) {
                var pDiv = Math.floor(pCount / 15);
                var ctr = 15;
                for (i = 1; i <= pDiv; i++) {
                    var pagerBreak = (ctr * i) + 1;
                    $(gallerypagerid + " a:nth-child(" + pagerBreak + ")").before('<br/>');
                }
            }
        }

        function setPrependItems() {
            $galleryItem = $(gallerycarouselid + " .gallery-item");
        }

        function CloseGallery(id) {

            $("#view-gallery-overlay" + id).modal("hide");
            galleryCollection.setItem('currentPager', $(gallerypagerid + ' a.selected > span').html())
            showModal = false;
            //$("#view-gallery-overlay" + id).swipe({ allowPageScroll: "auto" });
        }

        function ViewGallery(id) {
            itemId = id;
            $("#view-gallery-overlay" + id).modal("show");
            $("#ui-wrapper").after($("#view-gallery-overlay" + id));
            showModal = true;
            setTimeout(LoadGallery(), 350);
            setTimeout(setCurrentItem, 500);
            var itemCount;

            $(".gallery-pager a").each(function () {
                itemCount = 1 + $(this).index();
                if ($(this).attr("aria-label", "pagination dot" + itemCount)) {
                }
            });
            
        }

        function ViewGalleryMobile(id) {

            if ($('.btnviewgallery').is(':hidden')) {
                ViewGallery(id);
            }
        }

        function setCurrentItem() {
            $paginationItem.filter($(":nth-child(" + galleryCollection.getItem('currentPager') + ")")).trigger("click");
        }
        $(document).on("keyup", function (e) { //back and forward keyboard buttons
            if (e.keyCode == 39) { $("#caroufrednext").trigger("click"); }
            else if (e.keyCode == 37) { $("#caroufredprev").trigger("click"); }
        });

        $(window).on('resize', function () {
            afterResize();
        });

        function afterResize() {
            if (showModal) {
                $('#btnclosegallery' + itemId).trigger("click");
                setTimeout(function () { $('#btnviewgallery' + itemId).trigger("click"); }, 500);
            }
        }
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\ie.js
//Bug #304543: [About Homepage][Laptop][IE10] Not the entire Timeline Module is displayed upon scrolling the page downward
//adds ie class to html element
var isIE = document.all && document.querySelector;

(function() {
    if (isIE) {
        $('html').addClass('ie');
    }
})();

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CareersRegistration.js
// version="41"
if (ComponentRegistry.Registration) {
    var primaryJobSelected = { items: [] };
    var primaryCityList = { items: [] };
    var isFormSubmitted = false;

    var jobSelector = "#selectPrimaryJob .checkbox label input[type=checkbox]";
    var citySelector = "#selectCity .checkbox label input[type=checkbox]";
    //ADO 1083170 - For Max Primary SKill Checker 
    var checkboxPrimaryJob = $(jobSelector);
    var checkboxPrimaryCity;
    var counter = 0;

    //$(window).on("unload", function () {
    //    if (isFormSubmitted == false)
    //        //clear social session
    //        $.post("/api/sitecore/SocialSignInModule/ClearSocialSession");
    //});
    //hide disconnect link for registration
    var schoolFields = $("#School-fields")
    schoolFields.hide();
    if ($(".social-disconnect") != undefined)
        $(".social-disconnect").hide();

    $(function () {

        var CountryRegion = $('#ddBoxRegistrationCountryRegion');
        if (CountryRegion.val() != '') {
            CountryRegionOnChange($(CountryRegion));
        }

        //RMT 5947 - US011
        $('#chkJoinTalentConnection').on("change", function () {
            var checkboxSelection = $(this);
            var talentConnectionFields = $(".talent-connection-fields")
            if (checkboxSelection == undefined) { return; }
            if (checkboxSelection.is(':checked')) {
                $("#ddTalentConnectionRegistrationDegreeEarned").addClass('form-control validate-excluded-field');
                ReadOnlyDatepicker();
                talentConnectionFields.show();
            }
            else {
                talentConnectionFields.hide();
            }
        });

        $('#CareersRegistration_EmailAddress').on("blur", function () {
            var emailValueRaw = $(this).val();
            if (emailValueRaw != '') {
                if (IsEmailValid(emailValueRaw)) {
                    var validator = $('.validatorMessage span[data-bv-validator="callback"][data-bv-validator-for="CareersRegistration_EmailAddress"]');
                    var validatorDiv = validator.closest("div.form-group");
                    validatorDiv.find("i.form-control-feedback").css({ 'display': 'none' });
                    IsEmailUsed(emailValueRaw);
                }
            }
        });

        //ADO 1083170 - Apply Max Primary Skill Checker and order selection on all Primary Skill checkboxes
        checkboxPrimaryJob.on("click", function () {
            OrderSelection($(this), primaryJobSelected.items, jobSelector);
        });


        //ADO 1131574 - undo updates on city selections when selection overlay is closed
        $('#ModalRegCities .modal-header .close').on("click", function () {
            var selectedCities = $("#selectedCities .target.comment");
            var ModalCities = $('#ModalRegCities input[type=checkbox]');

            $('#ModalRegCities input[type=checkbox]:checked').each(function () {
                $(this).prop('checked', false);
            });
            $(selectedCities).each(function () {
                var cityName = $(this).children('label').attr('value');
                if ($(this).css('display') != "none") {
                    for (i = 0; i < ModalCities.length; i++) {
                        if (cityName == $(ModalCities[i]).attr('name')) {
                            $(ModalCities[i]).prop('checked', true);
                            break;
                        }
                    }
                }
            });

            for (var ctr = 0; ctr < primaryCityList.items.length; ctr++) {
                if (!$("#ModalRegCities input[type=checkbox][value='" + primaryCityList.items[ctr].value + "']").prop('checked')) {
                    primaryCityList.items.splice(ctr, 1);
                    ctr--;
                } else {
                    primaryCityList.items[ctr].isPending = false;
                }
            }
            checkMaxPrimary(citySelector);
        });

        //ADO 1131574 - undo updates on industry selections when selection overlay is closed
        $('#ModalRegIndustries .modal-header .close').on("click", function () {
            var selectedIndustries = $("#selectedIndustries .target.comment");
            var ModalIndustries = $('#ModalRegIndustries input[type=checkbox]');

            $('#ModalRegIndustries input[type=checkbox]:checked').each(function () {
                $(this).prop('checked', false);
            });
            $(selectedIndustries).each(function () {
                var industryName = $(this).children('label').attr('value');
                if ($(this).css('display') != "none") {
                    for (i = 0; i < ModalIndustries.length; i++) {
                        if (industryName == $(ModalIndustries[i]).attr('name')) {
                            $(ModalIndustries[i]).prop('checked', true);
                            break;
                        }
                    }
                }
            });
        });

        var TCCountry = $('#ddTalentConnectionRegistrationCountryOfSchool');
        $('#ddTalentConnectionRegistrationCountryOfSchool').on("change", function () {
            TalentConnectionCountryOnChange($(TCCountry));
        });

        var FormID = $('#formID').val();
        $(FormID).bootstrapValidator({
            fields: {
                CareersRegistration_EmailAddress: {
                    validMessage: 'The username looks great',
                    trigger: 'none',
                    validators: {
                        emailAddress: {
                            message: $('#EmailAddNotValid').val()
                        },
                        notEmpty: {
                            message: $('#EmailRequired').val()
                        },
                        callback: {
                            message: ''
                        }
                    }

                },
                CareersRegistration_Password: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#CreatePasswordlRequired').val()
                        },
                        callback: {
                            message: $('#InvalidPassword').val(),
                            callback: function (value, validator, $field) {
                                var retypePassword = $('#CareersRegistration_RetypePassword').val();
                                if (value == '') {
                                    //trap if retype password is previously validated correctly; trigger identical validator invalid
                                    if (retypePassword != '') {
                                        validator.updateStatus('CareersRegistration_RetypePassword', validator.STATUS_INVALID, 'identical');
                                    }
                                    return true
                                }
                                else {
                                    //if create password is not valid
                                    if (!IsPasswordValid(value) && retypePassword != '') {
                                        //trap if retype password is previously validated correctly; trigger identical validator invalid
                                        validator.updateStatus('CareersRegistration_RetypePassword', validator.STATUS_INVALID, 'identical');
                                        return false;
                                    }
                                    else if (IsPasswordValid(value)) {
                                        //if create password is valid									
                                        if (retypePassword != '') {
                                            //trigger identical validator of re-type password
                                            validator.updateStatus('CareersRegistration_RetypePassword', retypePassword == value ? validator.STATUS_VALID :

                                                validator.STATUS_INVALID, 'identical');
                                        }
                                        return true;
                                    }
                                }
                            }
                        },
                        stringLength: {
                            max: RetypePasswordMaxLengthValue,
                            message: $('#PasswordMaxLength').val()
                        }
                    }
                },
                CareersRegistration_RetypePassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#RetypePasswordlRequired').val()
                        },
                        callback: {
                            message: $('#InvalidPassword').val(),
                            callback: function (value, validator, $field) {
                                var createPassword = $('#CareersRegistration_Password').val();
                                var valid = IsPasswordValid(value);
                                if (createPassword != '' && value != '' && !valid) {
                                    //only identical validation is on
                                    validator.updateStatus('CareersRegistration_RetypePassword', validator.STATUS_INVALID, 'identical');
                                    return true;
                                }
                                if (value == '') {
                                    //force off identical validation, only notEmpty validator is on
                                    validator.updateStatus('CareersRegistration_RetypePassword', validator.STATUS_VALID, 'identical');
                                    // return true
                                }
                                return true
                            }
                        },
                        identical: {
                            field: 'CareersRegistration_Password',
                            message: $('#PasswordIdentical').val()
                        },
                        stringLength: {
                            max: RetypePasswordMaxLengthValue,
                            message: $('#RetypePasswordMaxLength').val()
                        }
                    }
                },
                CareerRegistration_FirstName: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#FirstNameRequired').val()
                        },
                        callback: {
                            message: $('#FirstNameAlphaOnly').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return IsValidInput(value, true, false, ['\\p{Pd}'])
                                }
                            }
                        },
                        stringLength: {
                            max: 50,
                            message: $('#FirstNameMaxLength').val()
                        }
                    }
                },
                CareerRegistration_LastName: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#LastNameRequired').val()
                        },
                        callback: {
                            message: $('#LastNameAlphaOnly').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return IsValidInput(value, true, false, ['\\p{Pd}'])
                                }
                            }
                        },
                        stringLength: {
                            max: 50,
                            message: $('#LastNameMaxLength').val()
                        }
                    }
                },
                ddBoxRegistrationCountryRegion: {
                    validators: {
                        notEmpty: {
                            message: $('#CountryRegion').val()
                        }
                    }
                },
                ddlPreferredCountryRegion: {
                    validators: {
                        notEmpty: {
                            message: $('#PreferredCountryRegion').val()
                        }
                    }
                },
                ddPreferredExperience: {
                    validators: {
                        notEmpty: {
                            message: $('#PreferredExperience').val()
                        }
                    }
                },
                ddPreferredIndustryMobile: {
                    validators: {
                        notEmpty: {
                            message: $('#PreferredIndustryMobile').val()
                        }
                    }
                },
                ddBoxRegistrationStateProvince: {
                    validators: {
                        notEmpty: {
                            message: $('#StateProvince').val()
                        }
                    }
                },
                CareerRegistration_City: {
                    validators: {
                        stringLength: {
                            max: 50,
                            message: $('#CityMaxLength').val()
                        },
                        callback: {
                            message: $('#CityAlphaOnly').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return IsValidInput(value, true, false, [])
                                }
                            }
                        }
                    }
                },
                captchaInput: {
                    trigger: 'submit',
                    validators: {
                        notEmpty: {
                            message: $('#CaptchaRequired').val()
                        },
                        callback: {
                            message: $('#IncorrectCaptcha').val()
                        }
                    }
                },
                ddTalentConnectionRegistrationDegreeEarned: {
                    validators: {
                        callback: {
                            message: $('#HighestDegreeEarnedRequired').val(),
                            callback: function (value, validator, $field) {
                                var status = $('.Status:radio:checked').val();
                                var checkBox = $('#chkJoinTalentConnection').filter(":checked").val();
                                if ((checkBox == "on") && (status == "isProfessional")) {
                                    if (value == "" || value == "Select") {
                                        return false;
                                    }
                                    else return true;
                                }
                                else return true;
                            }
                        }
                    }
                },
                TalentConnection_RelevantWorkExperience: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#RelevantWorkExperienceRequired').val()
                        },
                    }
                },
            }

        }).on('blur', '[name="CareersRegistration_EmailAddress"]', function (e, data) {
            var cnjaforms = $(this).closest("form");
            var $BootStrap = $(cnjaforms).data('bootstrapValidator');
            $BootStrap.updateStatus('CareersRegistration_EmailAddress', 'NOT_VALIDATED');
            $BootStrap.validateField('CareersRegistration_EmailAddress');

        });

        $('#btnUploadResume').on("click", function (e) {
            var emailValue = $('#CareersRegistration_EmailAddress').val();
            if (!IsEmailValid(emailValue) || emailValue == '') {
                $('#UploadErrorMessage').show();
            }
            else {
                $.ajax({
                    url: "/api/sitecore/RegistrationModule/GetUploadLink",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({ email: emailValue }),
                    contentType: "application/json",
                    success: function (data) {
                        uploadResume(data);
                    },
                    error: function (res) {
                        alert("EMAIL VALIDATION ERROR");
                    }
                })
            }
        });

        function uploadResume(data) {
            if (data == undefined || data == '') {
                {
                    alert('Email address is required');
                }
            } else {
                window.open(data, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=200,left=300,width=700,height=500");
            }
        }

        $('#btnRegister').on("click", function (event) {
            var careersRegistrationforms = $(this).closest("form");
            var captInput = $('input[name="captchaInput"]').val();

            if (captInput !== "") {
                var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', false);
            }
            else {
                var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
                $formBootStrap.enableFieldValidators('captchaInput', true);
            }

            var checkBox = $('#chkJoinTalentConnection').filter(":checked").val();
            var blogSubscription = $('#chkSubscribeToCareerBlog');
            var isSubscribedToBlog = false;
            if (typeof blogSubscription !== undefined) isSubscribedToBlog = blogSubscription.prop("checked") ? true : false;
            if (checkBox == undefined) { $("#ddTalentConnectionRegistrationDegreeEarned").removeClass('form-control validate-excluded-field'); }
            $formBootStrap.validate();
            var hasIndustryPrimaryJob = hasIndustry() & hasPrimaryJob();
            if (hasIndustryPrimaryJob) {
                if (hasIndustryPrimaryJob && $formBootStrap.isValid()) {
                    var objReg = {};
                    objReg.City = $('#CareerRegistration_City').val();
                    objReg.CountryRegionItemId = $('#ddBoxRegistrationCountryRegion').val();
                    objReg.EmailAddress = $('#CareersRegistration_EmailAddress').val();
                    objReg.FirstName = $('#CareerRegistration_FirstName').val();
                    objReg.LastName = $('#CareerRegistration_LastName').val();
                    objReg.Address1 = "";
                    objReg.Address2 = "";
                    objReg.HasAccentureAlertSubscription = false;
                    objReg.HasLocalNewsletterSubscription = $('#chkCareersNewsLetter').prop('checked');
                    objReg.HasJobEmailAlertSubscription = $('#chkJobAlert').prop('checked');
                    objReg.HasPrivacyAgreement = false;
                    objReg.IsProcessed = false;
                    objReg.JobPreferenceCityItemIds = GetRegistrationPreferredSelectedCities();
                    objReg.JobPreferenceCountryRegionItemId = $('#ddlPreferredCountryRegion').val();
                    objReg.JobPreferenceIndustryItemIds = GetRegistrationPreferredSelectedIndustries();
                    objReg.JobPreferenceYearsOfExperienceItemId = $('#ddPreferredExperience').val();
                    objReg.RegistrationId = "{00000000-0000-0000-0000-000000000000}";
                    objReg.SalutationItemId = $('#ddBoxRegistrationSalutation').val();
                    objReg.StateProvinceItemId = $('#ddBoxRegistrationStateProvince').val();
                    objReg.UniversityItemId = $('#ddBoxRegistrationUniversity').val();
                    objReg.Password = $('#CareersRegistration_Password').val();
                    objReg.JobPortalUrl = $("#CareersRegistration_JobPortalUrl").val();
                    objReg.PreferredLanguage = $('#SiteLanguage').val();
                    var objRegPrimaryJobs = {};
                    objRegPrimaryJobs.SkillValue = GetRegistrationPreferredSelectedPrimaryJob();
                    var objRegSpecializationSkills = {};
                    objRegSpecializationSkills.SkillValue = GetRegistrationPreferredSelectedSpecializationSkills();
                    var objRegTravelPercentage = {};
                    var travelPercentage = $('#ddPreferredTravel').val();
                    objRegTravelPercentage.SkillValue = travelPercentage ? travelPercentage.match(/\d+/)[0] : travelPercentage;
                    var CountrySite = $('#CountrySite').val();
                    var SiteLanguage = $('#SiteLanguage').val();
                    var dataToPass;
                    var urlString;
                    var captInput = $('input[name="captchaInput"]').val();
                    var captId = $('#CaptchaID').val();
                    var captInstance = $('#CaptInstance').val();
                    var captInputId = $('#UserInputID').val();

                    if ($('#chkJoinTalentConnection').is(':checked')) {
                        var talentConnectionVal = GetTalentConnectionValues();
                        dataToPass = JSON.stringify({ RegistrationValues: objReg, RegistrationTravelPercentageValue: objRegTravelPercentage, RegistrationSpecializationSkillValues: objRegSpecializationSkills, RegistrationPrimaryJobValues: objRegPrimaryJobs, TalentConnectionValues: talentConnectionVal, countrySite: CountrySite, siteLanguage: SiteLanguage, captInput: captInput, captId: captId, captInstance: captInstance, isSubscribedToBlog: isSubscribedToBlog });
                        urlString = "/api/sitecore/RegistrationModule/SaveRegistrationWithTalentConnection";
                    } else {
                        dataToPass = JSON.stringify({ RegistrationValues: objReg, RegistrationTravelPercentageValue: objRegTravelPercentage, RegistrationSpecializationSkillValues: objRegSpecializationSkills, RegistrationPrimaryJobValues: objRegPrimaryJobs, countrySite: CountrySite, siteLanguage: SiteLanguage, captInput: captInput, captId: captId, captInstance: captInstance, isSubscribedToBlog: isSubscribedToBlog });
                        urlString = "/api/sitecore/RegistrationModule/SaveRegistration";
                    }

                    $.ajax({
                        url: urlString,
                        async: false,
                        type: "POST",
                        data: dataToPass,
                        contentType: "application/json",
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log(jqXHR);
                            consoe.log(textStatus);
                            console.log(errorThrown);
                            if (typeof acncm !== 'undefined') {
                                acncm.Forms.detectedRegistrationFormError();
                            }
                            jQuery("body").trigger("analytics-form-error");
                        },
                        success: function (jsonOutput, textStatus, jqXHR) {
                            if (typeof acncm !== 'undefined') {
                                acncm.Forms.detectedRegistrationFormComplete();
                            }
                            if (jsonOutput[0].EmailSending == true && jsonOutput[0].RegistrationSaving == true) {
                                isFormSubmitted = true;
                                jQuery("body").trigger("analytics-form-success");
                                window.location.assign(jsonOutput[0].RedirectTo);
                                event.preventDefault();
                            }
                            else if (jsonOutput[0].IsCaptchaValid == false) {
                                $('#' + captInputId).get(0).Captcha.ReloadImage();
                                $formBootStrap.updateStatus('captchaInput', 'INVALID', 'callback');
                                jQuery("body").trigger("analytics-form-error");
                            }
                            else {
                                console.log("Error Saving Registration");
                                event.preventDefault();
                                jQuery("body").trigger("analytics-form-error");
                            }
                        }
                    });
                }
                else {
                    jQuery("body").trigger("analytics-form-error");
                    var cityTextboxValue = $.trim($('#CareerRegistration_City').val());
                    if (cityTextboxValue == "") {
                        $('#CareerRegistration_City').siblings().hide();
                    }
                    if (typeof acncm !== 'undefined') {
                        acncm.Forms.detectedRegistrationFormError();
                    }
                }
            }
            else {
                if ($formBootStrap.isValid() == false) {
                    jQuery("body").trigger("analytics-form-error");
                }
            }
            event.preventDefault();

        })


        function IsPasswordValid(PasswordCharacters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsPasswordValid",
                type: "POST",
                data: JSON.stringify({ Password: PasswordCharacters }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert("PASSWORD VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.ValidatedPassword;
                }
            });
            return returnVal;
        }
        function AlphaOnly(characters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsAlphaCharacters",
                type: "POST",
                data: JSON.stringify({ AlphaCharacters: characters }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert("ALPHA VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.AlphaOnly;
                }
            });
            return returnVal;
        }
        function IsValidInput(characters, includeLetters, includeNumbers, selectedSpecialCharacters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsValidDataInput",
                type: "POST",
                data: JSON.stringify({ data: characters, includeLetters: includeLetters, includeNumbers: includeNumbers, selectedSpecialCharacters: selectedSpecialCharacters }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert("ALPHA VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.IsValidInput;
                }
            });
            return returnVal;
        }
        function AlphanumericOnly(characters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsAlphanumericCharacters",
                type: "POST",
                data: JSON.stringify({ AlphanumericCharacters: characters }),
                contentType: "application/json",
                async: true,
                error: function (res) {
                    alert("ALPHANUMERIC VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.AlphanumericOnly;
                }
            });
            return returnVal;
        }
        function IsEmailValid(EmailCharacters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsEmailValid",
                type: "POST",
                data: JSON.stringify({ EmailCharacters: EmailCharacters }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert("EMAIL VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.ValidatedEmail;
                }
            });
            return returnVal;
        }
        function IsEmailUsed(EmailCharacters) {
            var returnVal = false;
            var validator = $('.validatorMessage span[data-bv-validator="callback"][data-bv-validator-for="CareersRegistration_EmailAddress"]');
            var validatorDiv = validator.closest("div.form-group");
            validatorDiv.find("i.form-control-feedback").removeClass("glyphicon-warning-sign");

            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsEmailUsed",
                type: "POST",
                data: JSON.stringify({ EmailCharacters: EmailCharacters }),
                contentType: "application/json",
                async: true,
                error: function (res) {
                    alert("EMAIL VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.ValidatedEmail;

                    if (EmailCharacters == '') { $('#UploadErrorMessage').hide(); }

                    validatorDiv.find("i.form-control-feedback").css({ 'display': 'inline-block' });
                    if (returnVal) {
                        validator.css({ 'display': 'inline-block' });
                        validator.parent().css({ 'display': 'inline-block' });
                        validator.closest("div.form-group").removeClass("has-success").addClass("has-error");
                        validator.closest("div.form-group").find("i.form-control-feedback").removeClass("glyphicon-ok").addClass("glyphicon-remove");

                        if (!returnVal) {
                            if (EmailCharacters.length > EmailMaxLengthValue) {
                                validator.text($('#EmailMaxLength').val());
                            }
                            else {
                                validator.text($('#ValidEmail').val());
                            }
                        }
                        else if (returnVal && IsLinkedUser(EmailCharacters)) {
                            validator.closest("div.form-group").removeClass("has-success").addClass("has-warning");
                            validator.closest("div.form-group").find("i.form-control-feedback").removeClass("glyphicon-ok").addClass("glyphicon-warning-sign");
                            validator.text($('#Warning').val());
                        }
                        else {
                            validator.text($('#UsedEmail').val());
                        }
                    }
                    else {
                        validator.css({ 'display': 'inline-block' });
                        validator.parent().css({ 'display': 'inline-block' });
                        validator.text($('#ValidEmail').val());
                        validatorDiv.find("i.form-control-feedback").removeClass("glyphicon-warning-sign").addClass('glyphicon-ok');
                    }
                }
            });
            return returnVal;
        }

        function IsLinkedUser(emailCharacters) {
            var returnVal = false;
            $.ajax({
                url: "/api/sitecore/RegistrationModule/IsLinkedUser",
                type: "POST",
                data: JSON.stringify({ emailCharacters: emailCharacters }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert("EMAIL VALIDATION ERROR");
                },
                success: function (res) {
                    returnVal = res.ValidatedEmail;
                    var ddlMobile = $('#ddPreferredIndustryMobile');
                    var industriesGuid = res.Industry;
                    var listOfIndustries = [];

                    if (industriesGuid !== undefined) {
                        $('#CareerRegistration_FirstName').val(res.FirstName);
                        $('#CareerRegistration_LastName').val(res.Lastname);
                        $('select#ddBoxRegistrationCountryRegion').selectpicker('val', res.CountryRegion);

                        if (industriesGuid.indexOf("|") > -1) {
                            listOfIndustries = industriesGuid.split("|");
                        } else {
                            listOfIndustries[0] = industriesGuid;
                        }

                        if (ddlMobile.val() === undefined) {
                            $('#selectedIndustries').empty();
                            for (var i = 0; i < listOfIndustries.length; i++) {
                                PopulateIndustry(listOfIndustries[i]);
                            }
                            hasIndustry();
                            rebindUndoableIndustryReg();
                        } else {
                            ddlMobile.selectpicker('val', listOfIndustries[0]);
                        }
                        var careersRegistrationforms = $('#CareerRegistration_FirstName').closest("form");
                        var $BootStrap = $(careersRegistrationforms).data('bootstrapValidator');
                        $BootStrap.updateStatus('CareerRegistration_FirstName', 'NOT_VALIDATED');
                        $BootStrap.validateField('CareerRegistration_FirstName');
                        $BootStrap.updateStatus('CareerRegistration_LastName', 'NOT_VALIDATED');
                        $BootStrap.validateField('CareerRegistration_LastName');
                    }
                }
            });
            return returnVal;
        }

        function PopulateIndustry(industryGuid) {
            var modalRegIndustries = $("#ModalRegIndustries input[value='" + industryGuid + "']");
            modalRegIndustries.prop("checked", true);
            $('#selectedIndustries').append("<span class='target comment'><a href='#' class='remove-selected-filter'>X</a>" + modalRegIndustries[0].name + "<label hidden guid=" +
                industryGuid + " value=" + modalRegIndustries[0].name + "> " + modalRegIndustries[0].name + "</label></span>");
        }

        function PopulatePrimaryJob(primaryJobGuid) {
            var modalRegPrimaryJob = $("#ModalRegPrimaryJob input[value='" + primaryJobGuid + "']");
            ModalRegPrimaryJob.prop("checked", true);
            $('#selectedPrimaryJob').append("<span class='target comment'><a href='#' class='remove-selected-filter'>X</a>" + modalRegPrimaryJob[0].name + "<label hidden guid=" +
                primaryJobGuid + " value=" + modalRegPrimaryJob[0].name + "> " + modalRegPrimaryJob[0].name + "</label></span>");
        }

        function GetTalentConnectionValues() {

            var talentConnectionVal = {};
            talentConnectionVal.TalentConnectionId;
            talentConnectionVal.UserId;
            talentConnectionVal.PhoneNumber = $('#TalentConnectionRegistration_PhoneNumber').val();
            talentConnectionVal.RelevantExperience = $('#ddPreferredExperience').val();
            var status = $('.Status:radio:checked').val();
            if (status == "isProfessional") {
                talentConnectionVal.HighestDegreeEarned = $('#ddTalentConnectionRegistrationDegreeEarned').val();
                talentConnectionVal.ChangeJobIn = $('#ddTalentConnectionRegistrationInterestedJobs').val();
            }

            if (status == "isStudent") {
                talentConnectionVal.CountryOfSchool = $('#ddTalentConnectionRegistrationCountryOfSchool').val();
                //fields with other
                var degreeMajor = $('#ddTalentConnectionRegistrationMajor :selected').val();
                var otherDegreeMajorValue = $("#DegreeMajor-other").val();
                var degreeMajorText = $('#ddTalentConnectionRegistrationMajor :selected').text();
                var degreeMajorDefaultValue = $('#degreeMajorDefaultValue').val();
                if (degreeMajor == otherDegreeMajorValue) {
                    talentConnectionVal.DegreeMajor = PrependOther($('#degreeMajor-textBox').val());
                } else {
                    if (degreeMajorText != degreeMajorDefaultValue) {
                        talentConnectionVal.DegreeMajor = degreeMajorText;
                    }
                    else talentConnectionVal.DegreeMajor = null;
                }

                var currentProgramOfStudy = $('#ddTalentConnectionRegistrationCurrentStudy :selected').val();
                var otherCurrentProgramOfStudy = $("#CurrentProgram-other").val();
                var currentProgramOfStudyText = $('#ddTalentConnectionRegistrationCurrentStudy :selected').text();
                var currentProgramDefaultValue = $('#currentProgramDefaultValue').val();
                if (currentProgramOfStudy == otherCurrentProgramOfStudy) {
                    talentConnectionVal.CurrentProgramOfStudy = PrependOther($('#currentProgram-textBox').val());
                } else {
                    if (currentProgramOfStudyText != currentProgramDefaultValue) {
                        talentConnectionVal.CurrentProgramOfStudy = currentProgramOfStudyText;
                    }
                    else talentConnectionVal.CurrentProgramOfStudy = null;
                }

                var school = $('#ddTalentConnectionRegistrationSchool :selected').val();
                var otherschool = $("#School-other").val();
                var schoolText = $('#ddTalentConnectionRegistrationSchool :selected').text();
                var schoolDefaultValue = $('#schoolDefaultValue').val();
                if (school == otherschool) {
                    talentConnectionVal.School = PrependOther($('#school-textBox').val());
                } else {
                    if (schoolText != schoolDefaultValue) {
                        talentConnectionVal.School = schoolText;
                    }
                    else talentConnectionVal.School = null;
                }

                var startDateStr = $('#startDateVal').val();
                if (startDateStr != '') {
                    talentConnectionVal.DegreeStartDate = FormatDate(startDateStr);
                }
                var expectedGradDateStr = $('#gradDateVal').val();
                if (expectedGradDateStr != '') {
                    talentConnectionVal.ExpectedGraduationDate = FormatDate(expectedGradDateStr);
                }
            }
            talentConnectionVal.LinkedInProfileUrl = $('#TalentConnectionRegistration_LinkedIn').val();
            talentConnectionVal.IsResumeUploaded = $('#').val();//check if the button is clicked and a resume was uploaded
            talentConnectionVal.AvatureId = $('#').val(); //no value yet
            talentConnectionVal.IsPreviouslyEmployed = $('#ddTalentConnectionRegistrationPreviouslyEmployed').val();
            talentConnectionVal.AreaOfInterest = $('#ddAreaOfInterest').val();

            return talentConnectionVal;
        }
        function FormatDate(date) {
            var formattedDate;
            //yyyy-dd-mm DB
            //dd/mm/yyyy val
            var type = $('.dtp-date').attr('type');
            if (type == "text") {
                formattedDate = date.substr(6, 4) + '-' + date.substr(3, 2) + '-' + date.substr(0, 2);
            }
            else {
                formattedDate = date;
            }
            return formattedDate;
        }
        function PrependOther(stringValue) {
            //to be updated when the 'Other' string source is identified
            return 'Other - ' + stringValue;
        }
    });

    function CountryRegionOnChange(selectedVal) {
        var dropdownval = '';
        if (selectedVal.value != undefined) { dropdownval = selectedVal.value; }
        else if (selectedVal.val() != undefined) { dropdownval = selectedVal.val(); }

        var RegStateProvince = $("#ddBoxRegistrationStateProvince");
        var RegUniversity = $('#ddBoxRegistrationUniversity');

        if (dropdownval != "") {
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetStateProvinceByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ CountryRegion: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    if (typeof data === "undefined" || data[0].Id == "") {
                        var ddlValues = ' <option value="NotApplicable">' + $('#NotApplicable').val() + '</option>';
                        RegStateProvince.prop("disabled", true);



                        if (RegStateProvince.closest('.form-group').hasClass('has-success')) {
                            var careersRegistrationforms = $("#ddBoxRegistrationStateProvince").closest("form");
                            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator').updateStatus('ddBoxRegistrationStateProvince', 'VALID', 'notEmpty');
                            RegStateProvince.closest('div.has-success').removeClass('has-success');
                            RegStateProvince.parent().find('i.glyphicon-ok').removeClass('glyphicon glyphicon-ok').css('display', 'none');
                        }

                        if (RegStateProvince.closest('.form-group').hasClass('has-error')) {
                            var careersRegistrationforms = $("#ddBoxRegistrationStateProvince").closest("form");
                            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator').updateStatus('ddBoxRegistrationStateProvince', 'VALID', 'notEmpty');
                            RegStateProvince.closest('div.has-error').removeClass('has-error');
                            RegStateProvince.parent().find('i.glyphicon-remove').removeClass('glyphicon glyphicon-remove').css('display', 'none');
                        }



                    }
                    else {

                        var ddlValues = ' <option value="">Select</option>';
                        RegStateProvince.prop("disabled", false);
                        $.each(data, function (key, value) {
                            ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                        });

                        var careersRegistrationforms = $("#ddBoxRegistrationStateProvince").closest("form");

                        if (RegStateProvince.closest('.form-group').hasClass('has-success')) {
                            RegStateProvince.closest('div.has-success').removeClass('has-success');
                            RegStateProvince.parent().find('i.glyphicon-ok').removeClass('glyphicon glyphicon-ok').css('display', 'none');

                        }
                        if (RegStateProvince.closest('.form-group').hasClass('has-error')) {
                            RegStateProvince.closest('div.has-error').removeClass('has-error');
                            RegStateProvince.parent().find('i.glyphicon-remove').removeClass('glyphicon glyphicon-remove').css('display', 'none');
                        }

                        var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator').updateStatus('ddBoxRegistrationStateProvince', 'NOT_VALIDATED', 'notEmpty');


                    }
                    RegStateProvince
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            RegStateProvince.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
            var careersRegistrationforms = $("#ddBoxRegistrationStateProvince").closest("form");
            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator').updateStatus('ddBoxRegistrationStateProvince', 'VALID', 'notEmpty');
            RegStateProvince.closest('div.has-error').removeClass('has-error');
            RegStateProvince.parent().find('i.glyphicon-remove').removeClass('glyphicon glyphicon-remove').css('display', 'none');
            RegUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }

    function StateOnChange(selectedVal) {
        var dropdownval = selectedVal.value;
        var RegUniversity = $('#ddBoxRegistrationUniversity');
        if (dropdownval != "") {
            var SiteLanguage = $('#SiteLanguage').val();
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetUniversities",
                async: false,
                type: "POST",
                data: JSON.stringify({ StateProvince: dropdownval, siteLanguage: SiteLanguage }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    RegUniversity.prop("disabled", false);
                    var ddlValues = '<option value="">Select</option>';
                    $('#ddBoxRegistrationUniversity').empty();
                    $.each(data, function (key, value) {
                        ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                    });
                    RegUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            RegUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }



    function TalentConnectionCountryOnChange(selectedVal) {
        var dropdownval = selectedVal.val();
        var TCUniversity = $('#ddTalentConnectionRegistrationSchool');
        var SchoolOther = $('#School-other');
        schoolFields.hide();
        if (dropdownval != "") {
            var SiteLanguage = $('#SiteLanguage').val();
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetUniversityByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ countryId: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    TCUniversity.prop("disabled", false);
                    var ddlValues = '<option value="">Select</option>';
                    $('#ddTalentConnectionRegistrationSchool').empty();
                    $.each(data, function (key, value) {
                        ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                    });

                    ddlValues = ddlValues + "<option value=" + SchoolOther.prop('value') + ">" + SchoolOther.prop('name') + "</option>";
                    TCUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            TCUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }

    $('button.filter-option').on("keydown", function (e) {
        if (e.which == 13) {
            $(this).trigger("click");
        }
    });

    $(".module-body.selection-reseter.cta").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });

    //$(".form-control.validate-excluded-field").on("keypress", function (event) {
    //    if (event.keyCode == 13) {
    //        $(this).trigger("click");
    //    }
    //});

    $("#ddlPreferredCountryRegion").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });

    $('#ddlPreferredCountryRegion').on('keydown', function (e) {
        if (event.keyCode == 13) {
            $(this).trigger("click");
        }
    });

    //$(".btn-default").on("keypress", function (event) {
    //    if (event.keyCode == 13) {
    //        $(this).trigger("click");
    //    }
    //});

    $('.btn-default').on('keydown', function (e) {
        if ($(this).is(":focus")) {
            $('#ddlPreferredCountryRegion').trigger("focus");
            if (event.keyCode == 13) {
                $(this).trigger("click");
            }
        }
    });

    //RMT 5237
    var forms = $(".captchaVal,#CareersRegistration_EmailAddress,#CareersRegistration_Password,#CareersRegistration_RetypePassword,#CareerRegistration_FirstName,#CareerRegistration_LastName");

    forms.on('keydown', function (e) {
        var tabcounter = 0;
        if (e.keyCode == 9 && tabcounter <= 0) {
            eval($(this).trigger("blur"));
            e.preventDefault();
            var formParent = $(this).parentsUntil(".form-group");
            var messageFocus = formParent.find(".validatorMessage");
            messageFocus.trigger("focus");
        }
    });

    $(function () {
        var errormsg = $(".validatorMessage");
        errormsg.on('keydown', function (e) {
            if (e.keyCode == 9) {
                var errorcheck = $(this).closest('div.has-error');
                if (errorcheck.attr('class')) {
                    var inputID = $(':focus').find('[data-bv-visible="true"]').attr("data-bv-validator-for");
                    e.preventDefault();
                    $("[name=" + inputID + "]").trigger("focus");
                }
            }
        });
    });

    //RMT 5947 SubHeader Margin
    var hasSubHeader = $(".hero-title-wrapper").find(".careers-subheader");
    if (hasSubHeader) {
        $(".top-block-spacing").css('margin-top', function (index, curValue) {
            return parseInt(curValue, 10) + 80 + 'px';
        });
    }
}

if (ComponentRegistry.JobPreference) {
    $(function () {
        rebindUndoablePrimaryJob();
        rebindUndoableCityReg();
        rebindUndoableIndustryReg();
        rebindUndoableSkills();

        var PreferredCountryRegion = $('#ddlPreferredCountryRegion');
        if (PreferredCountryRegion.val() != '') {
            GetCitiesByCountry($(PreferredCountryRegion));
        }
        $('#btnCityUpdate').on("click", function () {
            $('#selectedCities').empty();
            for (var ctr = 0; ctr < primaryCityList.items.length; ctr++) {
                if (primaryCityList.items[ctr].isPending === true) {
                    primaryCityList.items.splice(ctr, 1);
                    ctr--;
                } else {
                    $('#selectedCities').append(
                        '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + primaryCityList.items[ctr].name + '<label hidden guid="' +
                        primaryCityList.items[ctr].value + '" value="' + primaryCityList.items[ctr].name + '">' + primaryCityList.items[ctr].name + '/></span>'
                    );
                }
            }
            rebindUndoableCityReg();
            $('#RegCitiesLink').text($('#SelectCitiesLink').val());
        });

        $('#ModalRegCities .modal-footer .selection-reseter').on("click", function () {
            $('#ModalRegCities input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
            $('#ModalRegCities input[type=checkbox]').prop("disabled", false);
            for (var i = 0; i < primaryCityList.items.length; i++) {
                primaryCityList.items[i].isPending = true;
            }
        });
        $('#btnIndustryUpdate').on("click", function () {
            $('#selectedIndustries').empty();
            $('#selectIndustry .checkbox label input[type=checkbox]:checked').each(function () {
                $('#selectedIndustries').append(
                    '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + $(this).attr('name') + '<label hidden guid="' +
                    $(this).attr('value') + '" value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</label></span>'
                );
            });
            hasIndustry();
            rebindUndoableIndustryReg();
            setTimeout(function () { $('#industryErrorMessage').trigger("focus"); }, 1000);
        });
        $('#ModalRegIndustries .modal-footer .selection-reseter').on("click", function () {
            $('#ModalRegIndustries input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
        });

        $('button.filter-option').attr("role", "combobox");

        $('#btnPrimaryJobUpdateReg').on("click", function () {
            $('#selectedPrimaryJob').empty();
            for (var ctr = 0; ctr < primaryJobSelected.items.length; ctr++) {
                if (primaryJobSelected.items[ctr].isPending === true) {
                    primaryJobSelected.items.splice(ctr, 1);
                    ctr--;
                } else {
                    $('#selectedPrimaryJob').append(
                        '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + primaryJobSelected.items[ctr].name + '<label hidden guid="' +
                        primaryJobSelected.items[ctr].value + '" value="' + primaryJobSelected.items[ctr].name + '">' + primaryJobSelected.items[ctr].name + '</label></span>'
                    );
                }
            }
            hasPrimaryJob();
            rebindUndoablePrimaryJob();
            setTimeout(function () { $('#primaryJobErrorMessage').trigger("focus"); }, 0);
        });

        $('#ModalRegPrimaryJob .modal-footer .selection-reseter').on("click", function () {
            $('#ModalRegPrimaryJob input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
            $('#ModalRegPrimaryJob input[type=checkbox]').prop("disabled", false);
            checkedPrimaryJobCount = 0;
            for (var i = 0; i < primaryJobSelected.items.length; i++) {
                primaryJobSelected.items[i].isPending = true;
            }
        });



        //ADO 1083170 - Ticked checkboxes are based on selected Primary Jobs when displayed
        $('#ModalRegPrimaryJob .modal-header .close').on("click", function () {
            //reset Modal
            $('#ModalRegPrimaryJob input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
            //apply selected primaryjob(s) on Modal
            $('#ModalRegPrimaryJob input[type=checkbox]').each(function () {
                var selectedPrimaryJobSpanReg = $("#selectedPrimaryJob [class='target comment']");
                var checkboxText = $(this).attr('name');
                var selectedPrimaryJob = "";
                for (i = 0; i < selectedPrimaryJobSpanReg.length; i++) {
                    if ($(selectedPrimaryJobSpanReg[i]).css('display') != "none") {
                        selectedPrimaryJob = $(selectedPrimaryJobSpanReg[i]).children('label').attr('value');
                        if (checkboxText == selectedPrimaryJob) {
                            $(this).prop("checked", true);
                            checkMaxPrimary(jobSelector);
                            break;
                        }
                        else {
                            $(this).prop("checked", false);
                        }
                    }
                }
                setTimeout(
                    function () {
                        checkMaxPrimary(checkboxPrimaryJob);
                    }, 100);
            });
            for (var ctr = 0; ctr < primaryJobSelected.items.length; ctr++) {
                if (!$("#ModalRegPrimaryJob input[type=checkbox][value='" + primaryJobSelected.items[ctr].value + "']").prop('checked')) {
                    primaryJobSelected.items.splice(ctr, 1);
                    ctr--;
                } else {
                    primaryJobSelected.items[ctr].isPending = false;
                }
            }
        });

        //For Skills Specialization
        var skillsSpecializationValues = GetAllSkillSpecialization();
        var predictiveSkills = [];
        var specializationWarningMaximum = $('#ss-maximum-message');
        var specializationWarningDuplicate = $('#ss-duplicated-message');
        var specializationWarningNotAvailable = $('#ss-not-available-message');
        var divSpecializationWarningMessage = $('#specialization-warning-message');
        var inputedSkill = $("#skillsSpecialization");
        var skillSelected = $("#selected-skills");
        var dropDownList = $("#ddSkillSpecializationList");
        var newskillsSpecializationValues = [];


        if (skillsSpecializationValues) {
            for (var i = 0; i < skillsSpecializationValues.length; i++) {
                newskillsSpecializationValues.push(skillsSpecializationValues[i].skillName);
            }
            if (newskillsSpecializationValues) {
                searchDropdown(document.getElementById("skillsSpecialization"), newskillsSpecializationValues);
                if (specializationWarningMaximum || specializationWarningDuplicate || specializationWarningNotAvailable || specializationWarningNotAvailable || divSpecializationWarningMessage) {
                    $(".cta-arrow").on('click', function () {
                        var skills = [];
                        for (var i = 0; i < newskillsSpecializationValues.length; i++) {
                            skills.push(newskillsSpecializationValues[i].toLowerCase());
                        }
                        if (inputedSkill && skills && skillSelected) {
                            skills.sort(function (a, b) {
                                return a.toLowerCase().localeCompare(b.toLowerCase());
                            });
                            var skillIndex = skills.indexOf(inputedSkill.val().toLowerCase());
                            var skillValue = newskillsSpecializationValues[skillIndex];
                            var selectedSkills = skillSelected.children();
                            if (inputedSkill.val() !== "") {
                                if (skillIndex > -1) {
                                    if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                        if (predictiveSkills.length < 5) {
                                            if (skillValue) {

                                                var selectedSkillId = skillsSpecializationValues.filter(function (x) {
                                                    return x.skillName === skillValue
                                                })[0].skillId;

                                                skillSelected.append(
                                                    '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + skillValue + '<label hidden value="' + skillValue + '" id="' + selectedSkillId + '" /></span>'
                                                );
                                                selectedSkills.children().closest('.undoable.target.comment').remove();
                                                if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                    predictiveSkills.push(skillValue.toLowerCase());
                                                }
                                            }
                                        }
                                        else {
                                            divSpecializationWarningMessage.show();
                                            specializationWarningMaximum.show();
                                        }
                                    }
                                    else {
                                        divSpecializationWarningMessage.show();
                                        specializationWarningDuplicate.show();
                                    }
                                }
                                else {
                                    divSpecializationWarningMessage.show();
                                    specializationWarningNotAvailable.show();
                                }
                            }
                            inputedSkill.val("");
                            rebindUndoableSkills(predictiveSkills);
                            dropDownList.hide();
                        }
                    });

                    inputedSkill.on('keydown', function (e) {
                        if (specializationWarningMaximum || specializationWarningDuplicate || specializationWarningNotAvailable || specializationWarningNotAvailable || divSpecializationWarningMessage) {
                            specializationWarningMaximum.hide();
                            specializationWarningDuplicate.hide();
                            specializationWarningNotAvailable.hide();
                            divSpecializationWarningMessage.hide();
                            if (e.which === 13) {
                                e.preventDefault();
                                var skills = [];
                                for (var i = 0; i < newskillsSpecializationValues.length; i++) {
                                    skills.push(newskillsSpecializationValues[i].toLowerCase());
                                }
                                if (inputedSkill && skills && skillSelected) {
                                    skills.sort(function (a, b) {
                                        return a.toLowerCase().localeCompare(b.toLowerCase());
                                    });
                                    var skillIndex = skills.indexOf(inputedSkill.val().toLowerCase());
                                    var skillValue = newskillsSpecializationValues[skillIndex];
                                    var selectedSkills = skillSelected.children();
                                    if (inputedSkill.val() !== "") {
                                        if (skillIndex > -1) {
                                            if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                if (predictiveSkills.length < 5) {
                                                    if (skillValue) {

                                                        var selectedSkillId = skillsSpecializationValues.filter(function (x) {
                                                            return x.skillName === skillValue
                                                        })[0].skillId;

                                                        skillSelected.append(
                                                            '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + skillValue + '<label hidden value="' + skillValue + '" id="' + selectedSkillId + '" /></span>'
                                                        );
                                                        selectedSkills.children().closest('.undoable.target.comment').remove();
                                                        if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                            predictiveSkills.push(skillValue.toLowerCase());
                                                        }
                                                    }
                                                }
                                                else {
                                                    divSpecializationWarningMessage.show();
                                                    specializationWarningMaximum.show();
                                                }
                                            }
                                            else {
                                                divSpecializationWarningMessage.show();
                                                specializationWarningDuplicate.show();
                                            }
                                        }
                                        else {
                                            divSpecializationWarningMessage.show();
                                            specializationWarningNotAvailable.show();
                                        }
                                    }
                                    inputedSkill.val("");
                                    rebindUndoableSkills(predictiveSkills);
                                    dropDownList.hide();
                                }
                            }
                        }
                    });
                }
            }
        }
    });

    function hasIndustry() {
        var ddlMobile = $('#ddPreferredIndustryMobile').val(); //exist only in mobile view
        if (ddlMobile != undefined) return true;

        //desktop validation
        var industryVal = $('#selectedIndustries .target.comment'); //exist only in desktop view
        if (industryVal != undefined) {
            var hasTarget = false;
            var currentStyle;
            $(industryVal).each(function () {
                currentStyle = $(this).attr("style");
                if (currentStyle == undefined) {
                    hasTarget = true;
                    return false;
                }
                else if ((currentStyle.indexOf("display: block") >= 0) && $(this).hasClass("undoable") == false) {
                    hasTarget = true;
                }
            })

            if (hasTarget) {
                $('#industryId').removeClass("has-feedback").removeClass("has-error");
                $('#industryErrorMessage').hide();
                return true;
            } else {
                $('#industryId').addClass("has-feedback").addClass("has-error");
                $('#industryErrorMessage').show();
                $('#industryErrorMessage').trigger("focus");
                return false;
            }
        }
        else {
            $('#industryErrorMessage').show();
            return false;
        }
    }

    function hasPrimaryJob() {
        var ddlMobile = $('#ddPreferredPrimaryJobMobile').val(); //exist only in mobile view
        if (ddlMobile != undefined) return true;

        //desktop validation
        var primaryJobVal = $('#selectedPrimaryJob .target.comment'); //exist only in desktop view
        if (primaryJobVal != undefined) {
            var hasTarget = false;
            var currentStyle;
            $(primaryJobVal).each(function () {
                currentStyle = $(this).attr("style");
                if (currentStyle == undefined) {
                    hasTarget = true;
                    return false;
                }
                else if ((currentStyle.indexOf("display: block") >= 0) && $(this).hasClass("undoable") == false) {
                    hasTarget = true;
                }
            })

            if (hasTarget) {
                $('#primaryJobId').removeClass("has-feedback").removeClass("has-error");
                $('#primaryJobErrorMessage').hide();
                return true;
            } else {
                $('#primaryJobId').addClass("has-feedback").addClass("has-error");
                $('#primaryJobErrorMessage').show();
                setTimeout(function () { $("#RegPrimaryJob").trigger("focus") }, 0);
                return false;
            }
        }
        else {
            $('#primaryJobErrorMessage').show();
            return false;
        }
    }
    //ADO 1083170 - Max Primary Job Checker function
    function checkMaxPrimary(checkbox) {
        var chk = $(checkbox);
        var selectedCheckbox = $(checkbox + ":checked").length;
        for (i = 0; i < chk.length; i++) {

            if (selectedCheckbox >= 3) {
                if (!chk[i].checked) {
                    chk[i].disabled = true;
                }
            } else {
                if (!chk[i].checked) {
                    chk[i].disabled = false;
                }
            }
        }
    }

    function OrderSelection(elm, storedItems, checkbox) {
        var currentCheckBox = elm;
        checkboxIsCheckedReg(currentCheckBox[0], checkbox, currentCheckBox.parents().eq(3).attr('id'));
        if (currentCheckBox.prop("checked")) {
            if (storedItems.length > 0) {
                if (storedItems.filter(function (x) { return x.value === currentCheckBox[0].value }).length === 0) {
                    storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
                } else {
                    for (var i = 0; i < storedItems.length; i++) {
                        if (storedItems[i].name === currentCheckBox[0].name) {
                            storedItems.splice(i, 1);
                            storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
                        }
                    }
                }
            } else {
                storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
            }
        } else {
            for (var i = 0; i < storedItems.length; i++) {
                if (storedItems[i].name === currentCheckBox[0].name)
                    storedItems[i].isPending = true;
            }
        }
    }

    //ADO 1083170 - Call Max Primary SKill Checker per checkbox tick
    function checkboxIsCheckedReg(elem, checkbox, selectModal) {
        if (elem.checked)
            counter++;
        else
            counter--;
        setTimeout(
            function () {
                checkMaxPrimary(checkbox);
            }, 100);
    }
    function GetCitiesByCountry(selectedVal) {
        var dropdownval = '';
        if (selectedVal.value != undefined) { dropdownval = selectedVal.value; }
        else if (selectedVal.val() != undefined) { dropdownval = selectedVal.val(); }

        var CityCheckboxes = '';
        var CityItems = '';
        $('#selectedCities').empty();
        $('#RegCitiesLink').text($('#SelectCitiesLink').val());
        if (dropdownval != "") {
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetCitiesByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ CountryRegion: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    if (data == 0) {
                        if (CityItems == 0) {
                            $('#RegCitiesLink').addClass("disable-pointers");
                            if (IsIE()) {
                                $('#RegCitiesLink').replaceWith("<span class='col-sm-12 disable-pointers' id='RegCitiesLink'>" + $('#RegCitiesLink').text() + "</span>");
                            }
                        }
                    }
                    else {
                        if (IsIE()) {
                            $('#RegCitiesLink').replaceWith("<a href='#' id='RegCitiesLink' class='cta col-sm-12' data-target='#cities' data-toggle='modal'>" + $('#RegCitiesLink').text() + "</a>");
                        }
                        else {
                            $('#RegCitiesLink').removeClass("disable-pointers");
                        }
                    }
                    last = $(data).length;
                    rows = 18;
                    $('#RegCitiesLink').attr('data-toggle', 'modal');
                    $('#selectCity').empty();
                    $.each(data, function (key, value) {
                        CityCheckboxes = "<div class='checkbox'>" +
                            "<label>" +
                            "<input type='checkbox' name='" + value.Name + "' value='" + value.Id + "' />" + value.Name +
                            "</label>" +
                            "</div>"

                        if (((key + 1) % rows) == 1) { CityItems += '<div class="col-sm-4">' + CityCheckboxes; }
                        else if ((key + 1) == last || ((key + 1) % rows) == 0) { CityItems += CityCheckboxes + '</div>'; }
                        else { CityItems += CityCheckboxes; }
                    });
                }
            });
            primaryCityList.items = [];
            $('#selectCity').append(CityItems);
            checkboxPrimaryCity = $(citySelector);
            checkboxPrimaryCity.on("click", function () {
                OrderSelection($(this), primaryCityList.items, citySelector);
            });
        }
        else {
            $('#RegCitiesLink').removeAttr('data-toggle');
        }
    }
    function GetCitiesByCountryForMobile(selectedVal) {
        var dropdownval = selectedVal.value;
        var RegPrefCity = $('#ddPreferredCity');
        if (dropdownval != "") {
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetCitiesByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ CountryRegion: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    var ddlValues = ' <option value="">Select</option>';
                    RegPrefCity.prop("disabled", false);
                    RegPrefCity.empty();
                    $.each(data, function (key, value) {
                        ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                    });
                    RegPrefCity
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            RegPrefCity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }
    function GetRegistrationPreferredSelectedCities() {
        var selectedGuids = '';
        var PreferredCities = $('#selectedCities .target.comment');
        if (PreferredCities.length > 0) {
            PreferredCities.each(function () {
                if ($(this).css('display') != "none") { selectedGuids += $(this).children('label').attr('guid') + '|'; }
            });
        }
        else {
            selectedGuids = $('#ddPreferredCity').val();
        }
        return selectedGuids;
    }
    function GetRegistrationPreferredSelectedIndustries() {
        var selectedGuids = [];
        var concatGuids = "";

        var $PreferredIndustries = $('#selectedIndustries .target.comment');
        if ($PreferredIndustries.length > 0) {
            $PreferredIndustries.each(function () {
                var $industry = $(this);
                if ($industry.css('display') !== "none") {
                    var industryGuid = $industry.children('label').attr('guid');
                    if (industryGuid && industryGuid !== "")
                        selectedGuids.push(industryGuid)
                }
            });
        } else {
            concatGuids = $('#ddPreferredIndustry').val();
        }

        if (selectedGuids.length > 0)
            concatGuids = selectedGuids.join('|');

        return concatGuids;
    }

    function GetRegistrationPreferredSelectedPrimaryJob() {
        var selectedGuids = [];
        var concatGuids = "";

        var $PreferredPrimaryJob = $('#selectedPrimaryJob .target.comment');
        $PreferredPrimaryJob.each(function () {
            var $primaryJob = $(this);
            if ($primaryJob.css('display') !== "none") {
                var primaryJobGuid = $primaryJob.children('label').attr('guid');
                if (primaryJobGuid && primaryJobGuid !== "")
                    selectedGuids.push(primaryJobGuid)
            }
        });

        if (selectedGuids.length > 0)
            concatGuids = selectedGuids.join('|');

        return concatGuids;
    }
    function rebindUndoableCityReg() {
        $('#selectedCities a.remove-selected-filter').off();
        $('#selectedCities a.remove-selected-filter').undoable();
        $('#selectedCities .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegCities input[value=' + undoableValue + ']:checked').each(function () {
                $(this).prop('checked', false);
                for (var i = 0; i < primaryCityList.items.length; i++) {
                    if (primaryCityList.items[i].name === $(this)[0].name) {
                        primaryCityList.items.splice(i, 1);
                        i--;
                    }
                }
                checkMaxPrimary(citySelector);
            });

            $('#selectedCities .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegCities input[value=' + undoValue + ']:not(:checked)').each(function () {
                    $(this).prop('checked', true);
                    primaryCityList.items.push({ name: $(this)[0].name, value: $(this)[0].value, isPending: false });
                    checkMaxPrimary(citySelector);
                });
            });
        });
    }
    function rebindUndoableIndustryReg() {
        $('#selectedIndustries a.remove-selected-filter').off();
        $('#selectedIndustries a.remove-selected-filter').undoable();
        $('#selectedIndustries .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegIndustries input[value=' + undoableValue + ']:checked').each(function () {
                $(this).prop('checked', false);
            });
            hasIndustry();
            $('#selectedIndustries .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegIndustries input[value=' + undoValue + ']:not(:checked)').each(function () {
                    $(this).prop('checked', true);
                });
                hasIndustry();
            });
        });
    }

    function rebindUndoablePrimaryJob() {
        $('#selectedPrimaryJob a.remove-selected-filter').off();
        $('#selectedPrimaryJob a.remove-selected-filter').undoable();
        $('#selectedPrimaryJob .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegPrimaryJob input[value=' + undoableValue + ']:checked').each(function () {
                $(this).prop('checked', false);
                for (var i = 0; i < primaryJobSelected.items.length; i++) {
                    if (primaryJobSelected.items[i].name === $(this)[0].name) {
                        primaryJobSelected.items.splice(i, 1);
                        i--;
                    }
                }
                checkMaxPrimary(jobSelector);
            });
            hasPrimaryJob();
            $('#selectedPrimaryJob .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegPrimaryJob input[value=' + undoValue + ']:not(:checked)').each(function () {
                    $(this).prop('checked', true);
                    primaryJobSelected.items.push({ name: $(this)[0].name, value: $(this)[0].value, isPending: false });
                    checkMaxPrimary(jobSelector);
                });
                hasPrimaryJob();
            });
        });
    }
    $('#RegIndustryLink').on('keydown', function (e) {
        if (e.which == 9 && ($('.modal.fade.row').hasClass('in'))) {
            e.preventDefault();
            if ($(this).is(":focus")) {
                $('#industries').trigger("focus");
            }
        }
    });

    $('#RegPrimaryJob').on('keydown', function (e) {
        if (e.which == 9 && ($('.modal.fade.row').hasClass('in'))) {
            e.preventDefault();
            if ($(this).is(":focus")) {
                $('#primary-job').trigger("focus");
            }
        }
    });
    //For Skills Specialization
    function GetAllSkillSpecialization() {
        var responseValues = [];
        var skillSpecializationArray = [];
        var newResponseValues = [];
        var skillSpecializationVal = acncm.CacheManager.readSession("SkillsSpecialization");

        if (typeof skillSpecializationVal != 'undefined') {
            skillSpecializationVal = JSON.parse(skillSpecializationVal);
        } else {
            $.ajax({
                url: "/api/sitecore/RegistrationModule/GetAllSkillSpecialization",
                type: "POST",
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (!response) {
                        responseValues = null;
                        return responseValues;
                    } else {
                        var responseKeys = Object.keys(response);
                        responseValues = Object.keys(response).map(function (value) {
                            return response[value];
                        });

                        for (var countSkill = 0; countSkill < responseKeys.length; countSkill++) {
                            if (responseKeys && responseValues) {
                                var objSkillSpec = { skillId: responseKeys[countSkill], skillName: responseValues[countSkill] };
                                if (objSkillSpec) {
                                    newResponseValues.push(objSkillSpec);
                                }
                            }
                        }

                        if (newResponseValues) {
                            newResponseValues.sort(function (a, b) {
                                return a.skillName.toLowerCase().localeCompare(b.skillName.toLowerCase());
                            });
                            acncm.CacheManager.writeSession("SkillsSpecialization", JSON.stringify(newResponseValues));

                            skillSpecializationArray = acncm.CacheManager.readSession("SkillsSpecialization");

                            if (typeof skillSpecializationArray != 'undefined') {
                                skillSpecializationVal = JSON.parse(skillSpecializationArray);
                            }
                        }
                    }
                },
                error: function () {
                    newResponseValues = null;
                }
            });
            return skillSpecializationVal;
        }
        return skillSpecializationVal;
    }

    function searchDropdown(inputSearch, skillsItemArray) {
        var currentFocus;
        if (inputSearch) {
            inputSearch.addEventListener("input", function () {
                $this = $(this);
                var searchDropDownList, searchDropDownListItem, searchItemIndex, searchValue = $this.val();
                closeAllLists();
                if (!searchValue) {
                    return false;
                }
                currentFocus = -1;
                searchDropDownList = $("#ddSkillSpecializationList");
                if (searchDropDownList) {
                    searchDropDownList.addClass("search-dropdown-items");
                    searchDropDownList.show();
                }
                if (skillsItemArray) {
                    for (searchItemIndex = 0; searchItemIndex < skillsItemArray.length; searchItemIndex++) {
                        if (skillsItemArray[searchItemIndex].substr(0, searchValue.length).toUpperCase() === searchValue.toUpperCase()) {
                            searchDropDownListItem = document.createElement("DIV");
                            searchDropDownListItem.innerHTML = "<strong>" + skillsItemArray[searchItemIndex].substr(0, searchValue.length) + "</strong>";
                            searchDropDownListItem.innerHTML += skillsItemArray[searchItemIndex].substr(searchValue.length);
                            searchDropDownListItem.innerHTML += "<input type='hidden' value='" + skillsItemArray[searchItemIndex] + "'>";
                            searchDropDownListItem.addEventListener("click", function (e) {
                                inputSearch.value = this.innerText;
                                $("#skillsSpecialization").trigger("focus");
                                closeAllLists();
                            });
                            searchDropDownList.append(searchDropDownListItem);

                            if (searchDropDownList.children().length === 5) {
                                break;
                            }
                        }
                    }
                    if (!searchDropDownListItem) {
                        $(searchDropDownList).hide();
                    }
                }
            });
            inputSearch.addEventListener("keydown", function (e) {
                var searchDropDownList = $("#ddSkillSpecializationList");
                if (searchDropDownList) {
                    searchDropDownList = searchDropDownList.children();
                    if (e.keyCode == 40) {
                        e.preventDefault();
                        currentFocus++;
                        addActive(searchDropDownList);
                    } else if (e.keyCode == 38) {
                        e.preventDefault();
                        currentFocus--;
                        addActive(searchDropDownList);
                    } else if (e.keyCode == 13) {
                        e.preventDefault();
                        if (currentFocus > -1) {
                            if (searchDropDownList[currentFocus]) {
                                searchDropDownList[currentFocus].click();
                            }
                        }
                    }
                }
            });
        }

        function addActive(searchDropDownList) {
            if (searchDropDownList) {
                removeActive(searchDropDownList);
                if (currentFocus >= searchDropDownList.length) {
                    currentFocus = 0;
                }
                if (currentFocus < 0) {
                    currentFocus = (searchDropDownList.length - 1);
                }
                if (searchDropDownList[currentFocus]) {
                    searchDropDownList[currentFocus].classList.add("search-dropdown-active");
                }
            }
        }
        function removeActive(searchDropDownList) {
            if (searchDropDownList) {
                for (var searchItemIndex = 0; searchItemIndex < searchDropDownList.length; searchItemIndex++) {
                    if (searchDropDownList[searchItemIndex]) {
                        searchDropDownList[searchItemIndex].classList.remove("search-dropdown-active");
                    }
                }
            }
        }
        function closeAllLists(elmnt) {
            var searchDropDownListItem = $(".search-dropdown-items");
            if (searchDropDownListItem) {
                for (var searchItemIndex = 0; searchItemIndex < searchDropDownListItem.length; searchItemIndex++) {
                    var ddSearchListItem = searchDropDownListItem[searchItemIndex];
                    if (elmnt != ddSearchListItem && elmnt != inputSearch) {
                        if (ddSearchListItem) {
                            $(ddSearchListItem).children().remove();
                            $(ddSearchListItem).hide();
                        }
                    }
                }
            }
        }
        document.addEventListener("click", function (e) {
            closeAllLists(e.target);
        });
    }
    var selectedSkillsArray = [];
    function rebindUndoableSkills(selectedSkillsArray) {
        $('#selected-skills a.remove-selected-filter').off();
        $('#selected-skills a.remove-selected-filter').undoable();
        $('#selected-skills .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoText = $(this).parent().next().find('.undo-changes').find('i').text().trim().toLowerCase();
            for (var i = 0; i < selectedSkillsArray.length; i++) {
                if (selectedSkillsArray[i] === undoText) {
                    selectedSkillsArray.splice(i, 1);
                }
            }

            $('#selected-skills .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('value');
                var undoItem = $('#selected-skills').children().closest('.undoable.target.comment');
                if (selectedSkillsArray.length < 5) {
                    if (selectedSkillsArray.indexOf(undoValue.toLowerCase()) == -1) {
                        selectedSkillsArray.push(undoValue.toLowerCase());
                    }
                } else {
                    undoItem.remove();
                }

                if (selectedSkillsArray.length === 5) {
                    undoItem.remove();
                }
            });
        });
        $(this).prop("disabled", false);
    }

    function GetRegistrationPreferredSelectedSpecializationSkills() {
        var selectedSpecializationSkill = [];
        var concatSpecializationSkill = "";

        var $PreferredSpecializationSkill = $('#selected-skills .target.comment');
        $PreferredSpecializationSkill.each(function () {
            var $specializationSkill = $(this);
            if ($specializationSkill.css('display') !== "none") {
                var specializationSkillId = $specializationSkill.children('label').attr('id');
                if (specializationSkillId && specializationSkillId !== "")
                    selectedSpecializationSkill.push(specializationSkillId)
            }
        });

        if (selectedSpecializationSkill.length > 0)
            concatSpecializationSkill = selectedSpecializationSkill.join('|');

        return concatSpecializationSkill;
    }
}

if (ComponentRegistry.RegistrationComplete) {
    $(function () {


        $('#btnStartToday').on("click", function () {
            window.location.href = $('#startToday').val();
        });
        $('#btnJoin').on("click", function () {
            window.location.href = $('#Join').val();
        });
        $('#btnSignIn').on("click", function () {
            window.location.href = $('#signIn').val();
        });
        $("#resendEmailForm").bootstrapValidator({
            fields: {
                CaptchaInput: {
                    trigger: 'submit',
                    validators: {
                        notEmpty: {
                            message: $('#CaptchaRequired').val()
                        },
                        callback: {
                            message: $('#IncorrectCaptcha').val()
                        }
                    }
                }
            }
        });

        $('#btnResendEmail').on("click", function () {
            var RegEmail = $('#RegEmail').val();
            var RegStrID = $('#RegStrID').val();
            var RegCountry = $('#RegCountry').val();
            var SiteLanguage = $('#SiteLanguage').val();
            var captInput = $('input[name="CaptchaInput"]').val();
            var captId = $('#CaptchaID').val();
            var captInstance = $('#CaptInstance').val();
            var captInputId = $('#UserInputID').val();
            isFormDisabled = false;

            if (captInput !== "") {
                isFormDisabled = true;
                var $theForm = $('#resendEmailForm').data('bootstrapValidator');
                $theForm.enableFieldValidators('CaptchaInput', false);
            }
            else {
                isFormDisabled = false;
                var $theForm = $('#resendEmailForm').data('bootstrapValidator');
                $theForm.enableFieldValidators('CaptchaInput', true);
                $theForm.validate();
                jQuery("body").trigger("analytics-form-error");
            }
            if (isFormDisabled) {
                $.ajax({
                    url: "/api/sitecore/RegistrationModule/ResendEmail",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({ RegistrationID: RegStrID, countrySite: RegCountry, siteLanguage: SiteLanguage, captInput: captInput, captId: captId, captInstance: captInstance }),
                    dataType: "json",
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                    },
                    success: function (jsonOutput, textStatus, jqXHR) {
                        if (jsonOutput.IsEmailSent == true) {
                            acncm.CacheManager.write("_ss_fa_resend", true);
                            alert('RESENDING EMAIL SUCCESSFULL');
                            jQuery("body").trigger("analytics-form-success");
                        }
                        else if (jsonOutput.IsCaptchaValid == false) {
                            $('#' + captInputId).get(0).Captcha.ReloadImage();
                            $theForm.updateStatus('CaptchaInput', 'INVALID', 'callback');
                            jQuery("body").trigger("analytics-form-error");
                        }
                        else {
                            alert('RESENDING EMAIL FAILED');
                        }
                    }
                });
            }
        });
    })
}

if (ComponentRegistry.customforms) {
    var getStatus = $(".getStatus");

    //RMT 5947 Radio button Toggling
    $(".Status").each(function () {
        var instance = $(this);
        ToggleExperienceLevel(instance);
        $(instance).on("click", function () {
            ToggleExperienceLevel($(this));
        });
    });
    function ToggleExperienceLevel(radioButton) {
        var currentStatus = $(radioButton).val();
        if ($(radioButton).is(':checked')) {
            getStatus.hide();
            if (currentStatus == "isStudent") {
                $("#ddTalentConnectionRegistrationDegreeEarned").removeClass('form-control validate-excluded-field');
            }
            else $("#ddTalentConnectionRegistrationDegreeEarned").addClass('form-control validate-excluded-field');
            $("#" + currentStatus).show();
        }
    }

    var currentProgramFields = $("#CurrentProgram-fields")
    currentProgramFields.hide();

    $('#ddTalentConnectionRegistrationCurrentStudy').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#CurrentProgram-other").val();
        if (ddValue == otherValue) {
            currentProgramFields.show();
        } else {
            currentProgramFields.hide();
        }
    });

    var degreeMajorFields = $("#DegreeMajor-fields")
    degreeMajorFields.hide();

    $('#ddTalentConnectionRegistrationMajor').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#DegreeMajor-other").val();
        if (ddValue == otherValue) {
            degreeMajorFields.show();
        } else {
            degreeMajorFields.hide();
        }
    });



    $('#ddTalentConnectionRegistrationSchool').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#School-other").val();
        if (ddValue == otherValue) {
            schoolFields.show();
        } else {
            schoolFields.hide();
        }
    });

    //Bug fix 519767 - datepicker white spaces
    function ReadOnlyDatepicker() {
        if ($('.dtp-date').attr('type') == "text") {
            $('#startDateVal').attr("readonly", true);
            $('#gradDateVal').attr("readonly", true);
        }
    }
    $(function () {
        $('i').addClass('col-xs-1').addClass("col-sm-1");
    });

    $(".BDC_CaptchaDiv").css("height", "auto");

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CareersEditProfile.js
/* version="41" */
if (ComponentRegistry.EditProfile) {
    var primaryJobSelected = { items: [] };
    var primaryCityListEdit = { items: [] };
    var checkedPrimaryJobEditCount = 0;
    var jobSelector = '#selectPrimaryJobEdit .checkbox label input[type=checkbox]';
    var citySelector = '#selectCity .checkbox label input[type=checkbox]';
    var checkboxPrimaryJobEdit = $(jobSelector);
    var checkboxPrimaryCityEdit = $(citySelector);
    //For Others
    var currentProgramFields = $("#CurrentProgram-fields");
    currentProgramFields.hide();
    var counter = 0;

    $('#ddTalentConnectionRegistrationCurrentStudy').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#CurrentProgram-other").val();
        if (ddValue == otherValue) {
            currentProgramFields.show();
        } else {
            currentProgramFields.hide();
        }
    });

    var degreeMajorFields = $("#DegreeMajor-fields");
    degreeMajorFields.hide();

    $('#ddTalentConnectionRegistrationMajor').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#DegreeMajor-other").val();
        if (ddValue == otherValue) {
            degreeMajorFields.show();
        } else {
            degreeMajorFields.hide();
        }
    });

    var TCCountry = $('#ddTalentConnectionRegistrationCountryOfSchool');
    $('#ddTalentConnectionRegistrationCountryOfSchool').on("change", function () {
        TalentConnectionCountryOnChange($(TCCountry));
    });

    var schoolFields = $("#School-fields");
    schoolFields.hide();

    $('#ddTalentConnectionRegistrationSchool').on("change", function () {
        var ddValue = $(this).val();
        var otherValue = $("#School-other").val();
        if (ddValue == otherValue) {
            schoolFields.show();
        } else {
            schoolFields.hide();
        }
    });


    //$(window).on("unload", function () {
    //    //clear social session
    //    $.post("/api/sitecore/SocialSignInModule/ClearSocialSessionUnmerged");
    //});

    $(function () {
        ReadOnlyDatepickerEditProfile();

        if (typeof $('#IsSucceedingPageLoad') === 'object' && $('#IsSucceedingPageLoad').length > 0 && $('#IsSucceedingPageLoad').val() === "True") {
            $('#ProfileUpdatesConfirmation').show();
        }
        else $('#ProfileUpdatesConfirmation').hide();

        if ($('#ddTalentConnectionRegistrationCurrentStudy').val() == $("#CurrentProgram-other").val()) {
            $('#currentProgram-textBox').val($('#currentProgramOtherText').val());
            $("#CurrentProgram-fields").show();
        }

        if ($('#ddTalentConnectionRegistrationMajor').val() == $("#DegreeMajor-other").val()) {
            $('#degreeMajor-textBox').val($('#degreeMajorOtherText').val());
            $("#DegreeMajor-fields").show();
        }

        var countryOfSchool = $('#ddTalentConnectionRegistrationCountryOfSchool').val();
        if ((countryOfSchool == "") || (countryOfSchool == undefined)) {

            $('#ddTalentConnectionRegistrationSchool').prop("disabled", true);
        } else {
            var TCUniversity = $('#ddTalentConnectionRegistrationSchool');
            var SchoolOther = $('#School-other');
            var selectedSchool = $.trim(TCUniversity.text());

            $.ajax({
                url: "/api/sitecore/EditProfileModule/GetUniversityByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ countryId: $('#ddTalentConnectionRegistrationCountryOfSchool').val() }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    TCUniversity.prop("disabled", false);
                    var ddlValues = '<option value="">Select</option>';
                    $('#ddTalentConnectionRegistrationSchool').empty();
                    $.each(data, function (key, value) {
                        ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                    });

                    ddlValues = ddlValues + "<option value=" + SchoolOther.prop('value') + ">" + SchoolOther.prop('name') + "</option>";
                    TCUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');

                    $('#ddTalentConnectionRegistrationSchool option').each(function () {
                        var reselectedSchool = $.trim($(this).text());
                        if (selectedSchool.length > 0) {
                            if (reselectedSchool.toLowerCase() == selectedSchool.toLowerCase()) {

                                TCUniversity.selectpicker('val', $(this).val()).selectpicker('refresh');
                                return false;
                            }
                        } else {
                            schoolFields.hide();
                            return false;
                        }

                        var otherValue = $("#School-other").val();
                        TCUniversity.selectpicker('val', otherValue).selectpicker('refresh');
                        schoolFields.show();
                        $("#school-textBox").val(selectedSchool);


                    });
                }
            });

        }


        var FormID = $('#formID').val();
        $(FormID).bootstrapValidator({
            fields: {
                EditProfileOldPassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#OldPasswordlRequired').val()
                        },
                        callback: {
                            message: $('#InvalidPassword').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    if (!IsOldPasswordValid(value)) {
                                        $('#EditProfileOldPassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#OldPasswordIncorrect').val());
                                        return false
                                    }
                                }
                                return true
                            }
                        }
                    }
                },
                EditProfileCreatePassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#CreatePasswordlRequired').val()
                        },
                        callback: {
                            message: $('#InvalidPassword').val(),
                            callback: function (value, validator, $field) {
                                var retypePassword = $('#EditProfileRetypePassword').val();
                                if (value == '') {
                                    if (retypePassword != '') {
                                        validator.updateStatus('EditProfileRetypePassword', validator.STATUS_INVALID, 'identical');
                                    }
                                    return true
                                }
                                else {
                                    if (!IsPasswordValid(value) && retypePassword != '') {
                                        //trap if retype password is previously validated correctly; trigger identical validator invalid
                                        validator.updateStatus('EditProfileRetypePassword', validator.STATUS_INVALID, 'identical');
                                        return false;
                                    }
                                    else if (IsPasswordValid(value)) {
                                        //if create password is valid	
                                        if (IsOldPasswordValid(value)) {
                                            //if the password is same as the previous
                                            $('#EditProfileCreatePassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#PasswordSameAsPrevious').val());
                                            return false;
                                        }

                                        if (retypePassword != '') {
                                            //trigger identical validator of re-type password
                                            validator.updateStatus('EditProfileRetypePassword', retypePassword == value ? validator.STATUS_VALID : validator.STATUS_INVALID, 'identical');
                                        }
                                        return true;
                                    }
                                    else {
                                        $('#EditProfileCreatePassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#InvalidPassword').val());
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                },
                EditProfileRetypePassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#RetypePasswordlRequired').val()
                        },
                        callback: {
                            message: $('#InvalidPassword').val(),
                            callback: function (value, validator, $field) {
                                var createPassword = $('#EditProfileCreatePassword').val();
                                var valid = IsPasswordValid(value);
                                if (createPassword != '' && value != '' && !valid) {
                                    if (createPassword === value) {
                                        $('#EditProfileRetypePassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#InvalidPassword').val());
                                        return false;
                                    }
                                    if (createPassword !== value) {
                                        //only identical validation is on
                                        validator.updateStatus('EditProfileRetypePassword', validator.STATUS_INVALID, 'identical');
                                        return true;
                                    }
                                }
                                if (value == '') {
                                    //force off identical validation, only notEmpty validator is on
                                    validator.updateStatus('EditProfileRetypePassword', validator.STATUS_VALID, 'identical');
                                    // return true
                                }
                                return true
                            }
                        },
                        identical: {
                            field: 'EditProfileCreatePassword',
                            message: $('#PasswordIdentical').val()
                        }
                    }
                },
                EditProfileFirstName: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#FirstNameRequired').val()
                        },
                        callback: {
                            message: $('#FirstNameAlphaOnly').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return IsValidInput(value, true, false, ['\\p{Pd}'])
                                }
                            }
                        }
                    }
                },
                EditProfileLastName: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#LastNameRequired').val()
                        },
                        callback: {
                            message: $('#LastNameAlphaOnly').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return IsValidInput(value, true, false, ['\\p{Pd}'])
                                }
                            }
                        }
                    }
                },
                ddBoxEditProfileCountryRegion: {
                    validators: {
                        notEmpty: {
                            message: $('#CountryRegion').val()
                        }
                    }
                },
                ddBoxEditProfilePrefCountryRegion: {
                    validators: {
                        notEmpty: {
                            message: $('#CountryRegion').val()
                        }
                    }
                },
                captchaInput: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#CaptchaRequired').val()
                        },
                        callback: {
                            message: $('#IncorrectCaptcha').val(),
                            callback: function () {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    return isCaptchaCorrect()
                                }
                            }
                        }
                    }
                },
                ddTalentConnectionRegistrationDegreeEarnedTC: {
                    validators: {
                        callback: {
                            message: $('#HighestDegreeEarnedRequired').val(),
                            callback: function (value, validator, $field) {
                                if (value == "" || value == "Select") {
                                    return false;
                                }
                                else return true;
                            }
                        }
                    }
                }
            }
        });

        rebindUndoableCity();
        rebindUndoableIndustry();
        rebindUndoableSkills(GetRegisteredSkillSpecializationList());
        rebindUndoablePrimaryJobEdit();
        var EditProfilePassword;
        var EditProfileOldPassword;
        var EditProfileEmailAddress;

        ResizeHorizontal();

        storeSelectedValues();
        updateCityIndustryPrimaryJobModal();

        hasPrimaryJobEdit();

        //For Edit Profile Talent Connection
        var getStatusTC = $(".getStatusTC");
        $(".Status").each(function () {
            var instance = $(this);
            ToggleExperienceLevelTC(instance);
            $(instance).on("click", function () {
                ToggleExperienceLevelTC($(this));
            });
        });

        function ToggleExperienceLevelTC(radioButton) {
            var currentStatus = $(radioButton).val();
            if ($(radioButton).is(':checked')) {
                getStatusTC.hide();
                if (currentStatus == "isStudent") {
                    $("#ddTalentConnectionRegistrationDegreeEarnedTC").removeClass('form-control validate-excluded-field');
                }
                else $("#ddTalentConnectionRegistrationDegreeEarnedTC").addClass('form-control validate-excluded-field');
                $("#" + currentStatus).show();
            }
        }

        //For Skills Specialization
        var skillsSpecializationValues = GetAllSkillSpecialization();
        var predictiveSkills = GetRegisteredSkillSpecializationList();
        var specializationWarningMaximum = $('#ss-maximum-message');
        var specializationWarningDuplicate = $('#ss-duplicated-message');
        var specializationWarningNotAvailable = $('#ss-not-available-message');
        var divSpecializationWarningMessage = $('#specialization-warning-message');
        var inputedSkill = $("#skillsSpecialization");
        var skillSelected = $("#selected-skills");
        var dropDownList = $("#ddSkillSpecializationList");
        var newskillsSpecializationValues = [];

        if (skillsSpecializationValues) {
            for (var i = 0; i < skillsSpecializationValues.length; i++) {
                newskillsSpecializationValues.push(skillsSpecializationValues[i].skillName);
            }
            if (newskillsSpecializationValues) {
                searchDropdown(document.getElementById("skillsSpecialization"), newskillsSpecializationValues);
                if (specializationWarningMaximum || specializationWarningDuplicate || specializationWarningNotAvailable || specializationWarningNotAvailable || divSpecializationWarningMessage) {
                    $(".cta-arrow").on('click', function () {
                        var skills = [];
                        storeSelectedValues();
                        predictiveSkills = GetRegisteredSkillSpecializationList();

                        for (var i = 0; i < newskillsSpecializationValues.length; i++) {
                            skills.push(newskillsSpecializationValues[i].toLowerCase());
                        }
                        if (inputedSkill && skills && skillSelected) {
                            skills.sort(function (a, b) {
                                return a.toLowerCase().localeCompare(b.toLowerCase());
                            });
                            var skillIndex = skills.indexOf(inputedSkill.val().toLowerCase());
                            var skillValue = newskillsSpecializationValues[skillIndex];
                            var selectedSkills = skillSelected.children();
                            if (inputedSkill.val() !== "") {
                                if (skillIndex > -1) {
                                    if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                        if (predictiveSkills.length < 5) {
                                            if (skillValue) {
                                                var selectedSkillId = skillsSpecializationValues.filter(function (x) {
                                                    return x.skillName === skillValue
                                                })[0].skillId;
                                                skillSelected.append(
                                                    '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + skillValue + '<label hidden value="' + skillValue + '" id="' + selectedSkillId + '" /></span>'
                                                );
                                                selectedSkills.children().closest('.undoable.target.comment').remove();
                                                if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                    predictiveSkills.push(skillValue.toLowerCase());
                                                }
                                            }
                                        }
                                        else {
                                            divSpecializationWarningMessage.show();
                                            specializationWarningMaximum.show();
                                        }
                                    }
                                    else {
                                        divSpecializationWarningMessage.show();
                                        specializationWarningDuplicate.show();
                                    }
                                }
                                else {
                                    divSpecializationWarningMessage.show();
                                    specializationWarningNotAvailable.show();
                                }
                            }
                            inputedSkill.val("");
                            rebindUndoableSkills(predictiveSkills);
                            dropDownList.hide();
                        }
                    });

                    inputedSkill.on('keydown', function (e) {
                        if (specializationWarningMaximum || specializationWarningDuplicate || specializationWarningNotAvailable || specializationWarningNotAvailable || divSpecializationWarningMessage) {
                            specializationWarningMaximum.hide();
                            specializationWarningDuplicate.hide();
                            specializationWarningNotAvailable.hide();
                            divSpecializationWarningMessage.hide();
                            if (e.which === 13) {
                                e.preventDefault();
                                var skills = [];
                                storeSelectedValues();
                                predictiveSkills = GetRegisteredSkillSpecializationList();

                                for (var i = 0; i < newskillsSpecializationValues.length; i++) {
                                    skills.push(newskillsSpecializationValues[i].toLowerCase());
                                }
                                if (inputedSkill && skills && skillSelected) {
                                    skills.sort(function (a, b) {
                                        return a.toLowerCase().localeCompare(b.toLowerCase());
                                    });
                                    var skillIndex = skills.indexOf(inputedSkill.val().toLowerCase());
                                    var skillValue = newskillsSpecializationValues[skillIndex];
                                    var selectedSkills = skillSelected.children();
                                    if (inputedSkill.val() !== "") {
                                        if (skillIndex > -1) {
                                            if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                if (predictiveSkills.length < 5) {
                                                    if (skillValue) {
                                                        var selectedSkillId = skillsSpecializationValues.filter(function (x) {
                                                            return x.skillName === skillValue
                                                        })[0].skillId;
                                                        skillSelected.append(
                                                            '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + skillValue + '<label hidden value="' + skillValue + '" id="' + selectedSkillId + '" /></span>'
                                                        );
                                                        selectedSkills.children().closest('.undoable.target.comment').remove();
                                                        if (predictiveSkills.indexOf(inputedSkill.val().toLowerCase()) === -1) {
                                                            predictiveSkills.push(skillValue.toLowerCase());
                                                        }
                                                    }
                                                }
                                                else {
                                                    divSpecializationWarningMessage.show();
                                                    specializationWarningMaximum.show();
                                                }
                                            }
                                            else {
                                                divSpecializationWarningMessage.show();
                                                specializationWarningDuplicate.show();
                                            }
                                        }
                                        else {
                                            divSpecializationWarningMessage.show();
                                            specializationWarningNotAvailable.show();
                                        }
                                    }
                                    inputedSkill.val("");
                                    rebindUndoableSkills(predictiveSkills);
                                    dropDownList.hide();
                                }
                            }
                        }
                    });
                }
            }
        }
    });

    function storeSelectedValues() {
        var storeSelectedCities = [];
        var storeSelectedIndustries = [];
        var storeSelectedSkillSpecialization = [];
        var storeSelectedPrimaryJobs = [];
        primaryJobSelected.items = [];
        primaryCityListEdit.items = [];

        $('#selectedCities .target.comment').each(function () {
            if ($(this).css('display') != "none") {
                storeSelectedCities.push($(this).children('label').attr('guid'));
                primaryCityListEdit.items.push({ name: $(this).clone().find('a').remove().end().text(), value: $(this).children('label').attr('guid') });
            }
        });

        $('#selectedIndustries .target.comment').each(function () {
            if ($(this).css('display') != "none") {
                storeSelectedIndustries.push($(this).children('label').attr('guid'))
            }
        });

        $('#selectedPrimaryJobEdit .target.comment').each(function () {
            if ($(this).css('display') != "none") {
                storeSelectedPrimaryJobs.push($(this).children('label').attr('guid'));
                primaryJobSelected.items.push({ name: $(this).children('label').attr('value'), value: $(this).children('label').attr('guid') });
            }
        });

        $('#selected-skills .target.comment').each(function () {
            if ($(this).css('display') != "none" && !($(this).hasClass('undoable target comment'))) {
                storeSelectedSkillSpecialization.push($(this).children('label').attr('value'));
            }
        });

        var selectedValues = {
            cacheCities: storeSelectedCities,
            cacheIndustries: storeSelectedIndustries,
            cacheSkillSpecialization: storeSelectedSkillSpecialization,
            cachePrimaryJobs: storeSelectedPrimaryJobs
        }
        acncm.CacheManager.write("SelectedValues", JSON.stringify(selectedValues));
    }

    function updateCityIndustryPrimaryJobModal() {
        var selectedPrefValues = acncm.CacheManager.read("SelectedValues");

        if (typeof selectedPrefValues != 'undefined') {
            var selectedPrefValuesJSON = JSON.parse(selectedPrefValues);
            cacheCities = selectedPrefValuesJSON.cacheCities;
            cacheIndustries = selectedPrefValuesJSON.cacheIndustries;
            cachePrimaryJobs = selectedPrefValuesJSON.cachePrimaryJobs;
            var noOfValues;

            for (noOfValues = 0; noOfValues <= cacheCities.length - 1; noOfValues++) {
                $("#selectCity .checkbox label input:checkbox[value='" + cacheCities[noOfValues].toLowerCase() + "']").prop("checked", true);
                checkMaxEdit(citySelector);
            }

            for (noOfValues = 0; noOfValues <= cacheIndustries.length - 1; noOfValues++) {
                $("#selectIndustry .checkbox label input:checkbox[value='" + cacheIndustries[noOfValues].toLowerCase() + "']").prop("checked", true);
            }
            checkedPrimaryJobEditCount = 0;
            for (noOfValues = 0; noOfValues <= cachePrimaryJobs.length - 1; noOfValues++) {
                $("#selectPrimaryJobEdit .checkbox label input:checkbox[value='" + cachePrimaryJobs[noOfValues].toLowerCase() + "']").prop("checked", true);
                $('#selectedPrimaryJobEdit .target.comment').css('display', 'block');
                checkMaxEdit(jobSelector);
            }
        }
    }
    function GetRegisteredSkillSpecializationList() {
        var selectedPrefValues = acncm.CacheManager.read("SelectedValues");
        var registeredSkillSpecList = [];
        if (typeof selectedPrefValues != 'undefined') {
            var selectedPrefValuesJSON = JSON.parse(selectedPrefValues);
            cacheSkillSpecialization = selectedPrefValuesJSON.cacheSkillSpecialization;
            var noOfValues;

            if (cacheSkillSpecialization) {
                for (noOfValues = 0; noOfValues < cacheSkillSpecialization.length; noOfValues++) {
                    registeredSkillSpecList.push(cacheSkillSpecialization[noOfValues].toLowerCase());
                }
            }
        }

        return registeredSkillSpecList;
    }

    $('#btnUploadResumeEdit').on("click", function (e) {
        var emailValue = $('#EditProfileEmailAddress').val();
        $.ajax({
            url: "/api/sitecore/EditProfileModule/GetUploadLink",
            async: false,
            type: "POST",
            data: JSON.stringify({ email: emailValue }),
            contentType: "application/json",
            success: function (data) {
                uploadResume(data);
            },
            error: function (res) {
                alert("EMAIL VALIDATION ERROR");
            }
        })
    });

    function uploadResume(data) {
        if (data == undefined || data == '') {
            {
                alert('Email address is required');
            }
        } else {
            window.open(data, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=200,left=300,width=700,height=500");
        }
    }

    $('#EditProfileUpdateBtn').on("click", function (event) {
        if (hasPrimaryJobEdit() && hasPrimaryJobEdit() !== undefined) {
            var objProfile = {};
            var careersRegistrationforms = $(this).closest("form");
            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
            $formBootStrap.$submitButton = this;
            $formBootStrap.validate();

            if ($formBootStrap.isValid()) {
                objProfile.UserProfileId = $('#ProfileID').val();
                objProfile.SalutationItemId = $('#ddBoxEditProfileSalutation').val();
                objProfile.FirstName = $('#EditProfileFirstName').val();
                objProfile.LastName = $('#EditProfileLastName').val();
                objProfile.Address1 = $('#EditProfileAddress1').val();
                objProfile.Address2 = $('#EditProfileAddress2').val();
                objProfile.CountryRegionItemId = $('#ddBoxEditProfileCountryRegion').val();
                objProfile.StateProvinceItemId = $('#ddBoxEditProfileStateProvince').val();
                objProfile.City = removeTags($('#EditProfileCity').val());
                objProfile.UniversityItemId = $('#ddBoxEditProfileUniversity').val();
                objProfile.JobPreferenceCountryRegionItemId = $('#ddBoxEditProfilePrefCountryRegion').val();
                objProfile.JobPreferenceCityItemIds = GetPreferredSelectedCities();
                objProfile.JobPreferenceIndustryItemIds = GetPreferredSelectedIndustries();
                objProfile.JobPreferenceYearsOfExperienceItemId = $('#EditProfileExperienceDd').val();
                EditProfilePassword = $('#EditProfileCreatePassword').val();
                EditProfileOldPassword = $('#EditProfileOldPassword').val();
                var objProfileSkill = GetPreferredPrimaryJobs();
                var objSkillSpecialization = GetPreferredSkillSpecialization();
                var objRegTravelPercentage = {};
                var travelPercentage = $('#ddPreferredTravel').val();
                objRegTravelPercentage.SkillValue = travelPercentage ? travelPercentage.match(/\d+/)[0] : travelPercentage;
                var UserEmailAddress = $('#UserEmailAddress').val();
                var dataToPass;
                var urlString;

                if (!document.getElementById("divTalentConnection")) {
                    dataToPass = JSON.stringify({ Profile: objProfile, emailAddress: UserEmailAddress, oldPassword: EditProfileOldPassword, newPassword: EditProfilePassword, profileSkillSpecializationList: objSkillSpecialization, profilePrimaryJobList: objProfileSkill, travelPercentage: objRegTravelPercentage.SkillValue });
                    urlString = "/api/sitecore/EditProfileModule/UpdateProfile";
                } else {
                    var objProfileTalentConnection = GetProfileTalentConnectionValues();

                    dataToPass = JSON.stringify({ Profile: objProfile, ProfileTalentConnection: objProfileTalentConnection, emailAddress: UserEmailAddress, oldPassword: EditProfileOldPassword, newPassword: EditProfilePassword, profileSkillSpecializationList: objSkillSpecialization, profilePrimaryJobList: objProfileSkill, travelPercentage: objRegTravelPercentage.SkillValue });
                    urlString = "/api/sitecore/EditProfileModule/UpdateProfileWithTalentConnection";
                }

                $.ajax({
                    url: urlString,
                    async: false,
                    type: "POST",
                    data: dataToPass,
                    dataType: "json",
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                        if (typeof acncm !== 'undefined') {
                            acncm.Forms.detectedRegistrationFormError();
                        }
                    },
                    success: function (jsonOutput, textStatus, jqXHR) {
                        if (typeof acncm !== 'undefined') {
                            jQuery("body").trigger("analytics-form-success");
                            acncm.Forms.detectedRegistrationFormComplete();

                            if (jQuery('#EditProfileChangePassword').data('clicked')) {
                                window.location.href = "/Authentication/SignOut/SignOut";
                            }

                        }

                        if (jsonOutput == false) {
                            $('#ProfileUpdatesConfirmation').hide();
                            jQuery("body").trigger("analytics-form-error");
                            alert('ERROR SAVING');
                        }
                    }
                });
                event.preventDefault();

            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        }
        else {
            jQuery("body").trigger("analytics-form-error");
        }
        event.preventDefault();
    });

    $('#EditProfileChangeEmail').on("click", function () {
        window.location = $('#ChangeEmailLink').val();
        event.preventDefault();
    });

    function IsPasswordValid(InputtedPassword) {
        var returnVal = false;
        $.ajax({
            url: "/api/sitecore/EditProfileModule/IsPasswordValid",
            type: "POST",
            data: JSON.stringify({ Password: InputtedPassword }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("PASSWORD VALIDATION ERROR");
            },
            success: function (res) {
                returnVal = res.ValidatedPassword;
            }
        });
        return returnVal;
    }

    function IsOldPasswordValid(InputtedPassword) {
        var returnVal = false;
        $.ajax({
            url: "/api/sitecore/EditProfileModule/IsOldPasswordCorrect",
            type: "POST",
            data: JSON.stringify({ oldPassword: InputtedPassword, emailAddress: $('#EditProfileEmailAddress').val() }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("OLD PASSWORD VALIDATION ERROR");
            },
            success: function (res) {
                returnVal = res.isOldPasswordValidated;
            }
        });
        return returnVal;
    }

    function AlphaOnly(characters) {
        var returnVal = false;
        $.ajax({
            url: "/api/sitecore/EditProfileModule/IsAlphaCharacters",
            type: "POST",
            data: JSON.stringify({ AlphaCharacters: characters }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("ALPHA VALIDATION ERROR");
            },
            success: function (res) {
                returnVal = res.AlphaOnly;
            }
        });
        return returnVal;
    }

    function IsValidInput(characters, includeLetters, includeNumbers, selectedSpecialCharacters) {
        var returnVal = false;
        $.ajax({
            url: "/api/sitecore/EditProfileModule/IsValidDataInput",
            type: "POST",
            data: JSON.stringify({ data: characters, includeLetters: includeLetters, includeNumbers: includeNumbers, selectedSpecialCharacters: selectedSpecialCharacters }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("ALPHA VALIDATION ERROR");
            },
            success: function (res) {
                returnVal = res.IsValidInput;
            }
        });
        return returnVal;
    }

    $('#EditProfileChangePassword').on("click", function () {
        var divPassword = $(".col-xs-12.col-sm-6");
        divPassword.each(function () {
            $(this).attr({ "style": "z-index:1;" });
        });
        var divOutline = $(".col-sm-5.validatorMessage");
        divOutline.each(function () {
            $(this).attr({ "style": "outline-style:none;" });
        });
        var contentId = document.getElementById("EditProfilePasswordContainer");
        contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block";
        $(this).hide();
        $(this).data('clicked', true);

    });
    $('#btnCityUpdate').on("click", function () {
        $('#selectedCities').empty();
        var iCount = 0;

        for (var ctr = 0; ctr < primaryCityListEdit.items.length; ctr++) {
            if (primaryCityListEdit.items[ctr].isPending === true) {
                primaryCityListEdit.items.splice(ctr, 1);
                ctr--;
            } else {
                $('#selectedCities').append('<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + primaryCityListEdit.items[ctr].name + '<label hidden guid="' +
                    primaryCityListEdit.items[ctr].value + '" value="' + primaryCityListEdit.items[ctr].name + '">' + primaryCityListEdit.items[ctr].name + '</label></span>');
                iCount = iCount + 1;
            }
        }

        rebindUndoableCity();
        if (iCount > 0) {
            $('#modalCities').text($('#RefineResultsByCityLabel').val());
        }
        else {
            $('#modalCities').text($('#SelectCitiesLinkLabel').val());
        }
    });
    $('#ModalRegCities .modal-footer .selection-reseter').on("click", function () {
        $('#ModalRegCities input[type=checkbox]:checked').each(function () {
            $(this).prop('checked', false);
        });
        $('#ModalRegCities input[type=checkbox]').prop("disabled", false);
        for (var i = 0; i < primaryCityListEdit.items.length; i++) {
            primaryCityListEdit.items[i].isPending = true;
        }
    });
    $('#btnIndustryUpdate').on("click", function () {
        $('#selectedIndustries').empty();
        $('#selectIndustry .checkbox input[type=checkbox]:checked').each(function () {
            $('#selectedIndustries').append(
                '<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + $(this).attr('name') + '<label hidden guid="' +
                $(this).attr('value') + '" value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</label></span>'
            );
        });
        rebindUndoableIndustry();
    });
    $('#ModalRegIndustries .modal-footer .selection-reseter').on("click", function () {
        $('#ModalRegIndustries input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
    });

    //ADO 1083170 
    $('#btnPrimaryJobUpdate').on("click", function () {
        $('#selectedPrimaryJobEdit').empty();
        for (var ctr = 0; ctr < primaryJobSelected.items.length; ctr++) {
            if (primaryJobSelected.items[ctr].isPending === true) {
                primaryJobSelected.items.splice(ctr, 1);
                ctr--;
            } else {
                $('#selectedPrimaryJobEdit').append('<span class="target comment"><a href="#" class="remove-selected-filter">X</a>' + primaryJobSelected.items[ctr].name + '<label hidden guid="' +
                    primaryJobSelected.items[ctr].value + '" value="' + primaryJobSelected.items[ctr].name + '">' + primaryJobSelected.items[ctr].name + '</label></span>'
                );
            }
        }
        hasPrimaryJobEdit();
        rebindUndoablePrimaryJobEdit();
        setTimeout(function () { $('#primaryJobEditErrorMessage').trigger("focus"); }, 0);
    });
    $('#ModalRegPrimaryJobs .modal-footer .selection-reseter').on("click", function () {
        $('#ModalRegPrimaryJobs input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
        $('#ModalRegPrimaryJobs input[type=checkbox]').prop("disabled", false);
        for (var i = 0; i < primaryJobSelected.items.length; i++) {
            primaryJobSelected.items[i].isPending = true;
        }
    });


    checkboxPrimaryJobEdit.on("click", function () {
        OrderSelection($(this), primaryJobSelected.items, jobSelector);
    });

    checkboxPrimaryCityEdit.on("click", function () {
        OrderSelection($(this), primaryCityListEdit.items, citySelector);
    });

    $('#ModalRegCities .modal-header .close').on("click", function () {
        var selectedCities = $("#selectedCities .target.comment");
        var ModalCities = $('#ModalRegCities input[type=checkbox]');

        $('#ModalRegCities input[type=checkbox]:checked').each(function () {
            $(this).prop('checked', false);
        });

        $(selectedCities).each(function () {
            var cityName = $(this).children('label').attr('guid');
            if ($(this).css('display') !== "none") {
                for (i = 0; i < ModalCities.length; i++) {
                    if (cityName === $(ModalCities[i]).attr('value')) {
                        $(ModalCities[i]).prop('checked', true);
                        break;
                    }
                }
            }
        });

        for (var ctr = 0; ctr < primaryCityListEdit.items.length; ctr++) {
            if (!$("#ModalRegCities input[type=checkbox][value='" + primaryCityListEdit.items[ctr].value + "']").prop('checked')) {
                primaryCityListEdit.items.splice(ctr, 1);
                ctr--;
            } else {
                primaryCityListEdit.items[ctr].isPending = false;
            }
        }
        checkMaxEdit(citySelector);
    });


    $('#ModalRegPrimaryJobs .modal-header .close').on("click", function () {
        checkMaxEdit(jobSelector);
        $('#ModalRegPrimaryJobs input[type=checkbox]:checked').each(function () { $(this).prop('checked', false); });
        $('#ModalRegPrimaryJobs input[type=checkbox]').each(function () {
            var selectedPrimaryJobSpan = $("#selectedPrimaryJobEdit [class='target comment']");
            var checkboxText = $(this).attr('name');
            var selectedPrimaryJobEdit = "";
            for (i = 0; i < selectedPrimaryJobSpan.length; i++) {
                if ($(selectedPrimaryJobSpan[i]).css('display') !== "none") {
                    selectedPrimaryJobEdit = $(selectedPrimaryJobSpan[i]).children('label').attr('value');
                    if (checkboxText == selectedPrimaryJobEdit) {
                        $(this).prop("checked", true);
                        checkMaxEdit(jobSelector);
                        break;
                    }
                    else {
                        $(this).prop("checked", false);
                    }
                }
            }
            setTimeout(
                function () {
                    checkMaxEdit(jobSelector);
                }, 50);
        });

        for (var ctr = 0; ctr < primaryJobSelected.items.length; ctr++) {
            if (!$("#ModalRegPrimaryJobs input[type=checkbox][value='" + primaryJobSelected.items[ctr].value + "']").prop('checked')) {
                primaryJobSelected.items.splice(ctr, 1);
                ctr--;
            } else {
                primaryJobSelected.items[ctr].isPending = false;
            }
        }
    });

    $('button.filter-option').attr("role", "combobox");

    function hasPrimaryJobEdit() {
        var primaryJobEditErrorMessage = $('#primaryJobEditErrorMessage');
        var primaryJobVal = $('#selectedPrimaryJobEdit .target.comment');
        if (primaryJobVal != undefined) {
            var hasTarget = false;
            var currentStyle;
            $(primaryJobVal).each(function () {
                currentStyle = $(this).attr("style");
                if (currentStyle == undefined) {
                    hasTarget = true;
                    return false;
                }
                else if ((currentStyle.indexOf("display: block") >= 0) && $(this).hasClass("undoable") == false) {
                    hasTarget = true;
                }
            })

            if (hasTarget) {
                $('#primaryJobId').removeClass("has-feedback").removeClass("has-error");
                primaryJobEditErrorMessage.hide();
                return true;
            } else {
                $('#primaryJobId').addClass("has-feedback").addClass("has-error");
                primaryJobEditErrorMessage.show();
                setTimeout(function () { $("#RegPrimaryJobEdit").trigger("focus") }, 0);
                return false;
            }
        }
        else {
            primaryJobEditErrorMessage.show();
            return false;
        }
    }

    function EditCountryRegionOnChange(selectedVal) {
        var dropdownval = selectedVal.value;
        var EditStateProvince = $("#ddBoxEditProfileStateProvince");
        var EditUniversity = $('#ddBoxEditProfileUniversity');

        if (dropdownval != "") {
            $.ajax({
                url: "/api/sitecore/EditProfileModule/GetStateProvinceByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ CountryRegion: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    if (typeof data === "undefined" || data[0].Id == "") {
                        var ddlValues = ' <option value="NotApplicable">' + $('#NotApplicable').val() + '</option>';
                        EditStateProvince.prop("disabled", true);
                    }
                    else {
                        var ddlValues = ' <option value="">Select</option>';
                        EditStateProvince.prop("disabled", false);
                        $.each(data, function (key, value) {
                            ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                        });
                    }
                    EditStateProvince
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            EditStateProvince.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
            EditUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }

    function EditStateOnChange(selectedVal) {
        var dropdownval = selectedVal.value;
        var EditUniversity = $('#ddBoxEditProfileUniversity');
        if (dropdownval != "") {
            $.ajax({
                url: "/api/sitecore/EditProfileModule/GetUniversities",
                async: false,
                type: "POST",
                data: JSON.stringify({ StateProvince: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    EditUniversity.prop("disabled", false);
                    var ddlValues = '<option value="">Select</option>';
                    EditUniversity.empty();
                    $.each(data, function (key, value) {
                        ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                    });
                    EditUniversity
                        .html(ddlValues)
                        .selectpicker('refresh');
                }
            });
        }
        else {
            EditUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
        }
    }
    function checkboxIsCheckedReg(elem, checkbox, selectModal) {
        if (elem.checked)
            counter++;
        else
            counter--;
        setTimeout(
            function () {
                checkMaxEdit(checkbox);
            }, 100);
    }

    function OrderSelection(elm, storedItems, checkbox) {

        var currentCheckBox = elm;
        checkboxIsCheckedReg(currentCheckBox[0], checkbox, currentCheckBox.parents().eq(3).attr('id'));

        if (currentCheckBox.prop("checked")) {
            if (storedItems.length > 0) {
                if (storedItems.filter(function (x) { return x.value === currentCheckBox[0].value }).length === 0) {
                    storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
                } else {
                    for (var i = 0; i < storedItems.length; i++) {
                        if (storedItems[i].value === currentCheckBox[0].value) {
                            storedItems.splice(i, 1);
                            storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
                        }
                    }
                }
            } else {
                storedItems.push({ name: currentCheckBox[0].name, value: currentCheckBox[0].value, isPending: false });
            }
        } else {
            for (var i = 0; i < storedItems.length; i++) {
                if (storedItems[i].value === currentCheckBox[0].value)
                    storedItems[i].isPending = true;
            }
        }
    }

    function GetEditProfileCitiesByCountry(selectedVal) {
        var CityCheckboxes = '';
        var CityItems = '';
        var CityList = $('#selectCity');
        CityList.empty();
        $('#selectedCities').empty();
        $('#modalCities').text($('#SelectCitiesLinkLabel').val());
        var dropdownval = selectedVal.value;
        if (dropdownval != '') {
            $.ajax({
                url: "/api/sitecore/EditProfileModule/GetCitiesByCountry",
                async: false,
                type: "POST",
                data: JSON.stringify({ CountryRegion: dropdownval }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    if (data == 0) {
                        if (CityItems == 0) {
                            $('#modalCities').addClass("disable-pointers");
                            if (IsIE()) {
                                $('#modalCities').replaceWith("<span class='col-sm-12 disable-pointers' id='modalCities'>" + $('#modalCities').text() + "</span>");
                            }
                        }
                    }
                    else {
                        if (IsIE()) {
                            $('#modalCities').replaceWith("<a href='#' id='modalCities' class='cta col-sm-12' data-target='#cities' data-toggle='modal'>" + $('#modalCities').text() + "</a>");
                        }
                        else {
                            $('#modalCities').removeClass("disable-pointers");
                        }
                    }
                    last = $(data).length;
                    rows = 18;

                    $.each(data, function (key, value) {
                        CityCheckboxes = "<div class='checkbox'>" +
                            "<label>" +
                            "<input type='checkbox' name='" + value.Name + "' value='" + value.Id + "' />" + value.Name +
                            "</label>" +
                            "</div>"

                        if (((key + 1) % rows) == 1) { CityItems += '<div class="col-sm-4">' + CityCheckboxes; }
                        else if ((key + 1) == last || ((key + 1) % rows) == 0) { CityItems += CityCheckboxes + '</div>'; }
                        else { CityItems += CityCheckboxes; }
                    });
                }
            });
        }
        primaryCityListEdit.items = [];
        CityList.append(CityItems);
        checkboxPrimaryCityEdit = $('#selectCity .checkbox label input[type=checkbox]');
        checkboxPrimaryCityEdit.on("click", function () {
            OrderSelection($(this), primaryCityListEdit.items, citySelector);
        });
    }

    function GetPreferredSelectedCities() {
        var selectedGuids = [];
        $('#selectedCities .target.comment').each(function () {
            if ($(this).css('display') != "none") {
                selectedGuids.push($(this).children('label').attr('guid'));
            }
        });

        var concatGuids = "";

        if (selectedGuids.length > 0)
            concatGuids = selectedGuids.join('|');

        return concatGuids;
    }
    function GetPreferredSelectedIndustries() {
        var selectedGuids = [];

        $('#selectedIndustries .target.comment').each(function () {
            var $industryItem = $(this);
            if ($industryItem.css('display') !== "none") {
                var industryGuid = $industryItem.children('label').attr('guid');

                if (industryGuid && industryGuid !== "")
                    selectedGuids.push(industryGuid);
            }
        });

        var concatGuids = "";

        if (selectedGuids.length > 0)
            concatGuids = selectedGuids.join('|');

        return concatGuids;
    }

    function GetPreferredPrimaryJobs() {
        var selectedGuids = [];
        var concatGuids = "";

        $('#selectedPrimaryJobEdit .target.comment').each(function () {
            var $primaryJobEditItem = $(this);
            if ($primaryJobEditItem.css('display') !== "none") {
                var primaryJobEditGuid = $primaryJobEditItem.children('label').attr('guid');

                if (primaryJobEditGuid && primaryJobEditGuid !== "")
                    selectedGuids.push(primaryJobEditGuid);
            }
        });

        if (selectedGuids.length > 0)
            concatGuids = selectedGuids.join('|');

        return concatGuids;
    }
    function rebindUndoableCity() {
        $('#selectedCities a.remove-selected-filter').off();
        $('#selectedCities a.remove-selected-filter').undoable();
        $('#selectedCities .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegCities input[value=' + undoableValue + ']:checked').each(function () {
                $(this).prop('checked', false);
                for (var i = 0; i < primaryCityListEdit.items.length; i++) {
                    if (primaryCityListEdit.items[i].name === $(this)[0].name) {
                        primaryCityListEdit.items.splice(i, 1);
                        i--;
                    }
                }
                checkMaxEdit(citySelector);
            });

            $('#selectedCities .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegCities input[value=' + undoValue + ']:not(:checked)').each(function () {
                    $(this).prop('checked', true);
                    primaryJobSelected.items.push({ name: $(this)[0].name, value: $(this)[0].value, isPending: false });
                    checkMaxEdit(citySelector);
                });
            });
        });
    }
    function rebindUndoableIndustry() {
        $('#selectedIndustries a.remove-selected-filter').off();
        $('#selectedIndustries a.remove-selected-filter').undoable();
        $('#selectedIndustries .remove-selected-filter').on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegIndustries input[value=' + undoableValue + ']:checked').each(function () { $(this).prop('checked', false); });

            $('#selectedIndustries .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegIndustries input[value=' + undoValue + ']:not(:checked)').each(function () { $(this).prop('checked', true); });
            });
        });
    }

    function rebindUndoablePrimaryJobEdit() {
        var selectedPrimaryJobEdit = $('#selectedPrimaryJobEdit a.remove-selected-filter');
        selectedPrimaryJobEdit.off();
        selectedPrimaryJobEdit.undoable();
        selectedPrimaryJobEdit.on("click", function () {
            $('.undoable.target.comment').css('display', 'inline-block');
            $('.undo').css('padding-right', '10px');
            var undoableValue = $(this).parent().find('label').attr('guid');
            $('#ModalRegPrimaryJobs input[value=' + undoableValue + ']:checked').each(function () {
                $(this).prop('checked', false);
                for (var i = 0; i < primaryJobSelected.items.length; i++) {
                    if (primaryJobSelected.items[i].name === $(this)[0].name) {
                        primaryJobSelected.items.splice(i, 1);
                        i--;
                    }
                }
                checkMaxEdit(jobSelector);
            });
            hasPrimaryJobEdit();
            $('#selectedPrimaryJobEdit .undo a').on("click", function () {
                var undoText = $(this).closest('.undo-changes').find('i').text().trim();
                var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('guid');
                $('#ModalRegPrimaryJobs input[value=' + undoValue + ']:not(:checked)').each(function () {
                    $(this).prop('checked', true);
                    primaryJobSelected.items.push({ name: $(this)[0].name, value: $(this)[0].value, isPending: false });
                    checkMaxEdit(jobSelector);
                });
                hasPrimaryJobEdit();
            });

        });
    }

    //For Skills Specialization
    function GetAllSkillSpecialization() {
        var responseValues = [];
        var skillSpecializationArray = [];
        var newResponseValues = [];
        var skillSpecializationVal = acncm.CacheManager.readSession("SkillsSpecialization");

        if (typeof skillSpecializationVal != 'undefined') {
            skillSpecializationVal = JSON.parse(skillSpecializationVal);
        } else {
            $.ajax({
                url: "/api/sitecore/EditProfileModule/GetAllSkillSpecialization",
                type: "POST",
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (!response) {
                        responseValues = null;
                        return responseValues;
                    } else {
                        var responseKeys = Object.keys(response);
                        responseValues = Object.keys(response).map(function (value) {
                            return response[value];
                        });

                        for (var countSkill = 0; countSkill < responseKeys.length; countSkill++) {
                            if (responseKeys && responseValues) {
                                var objSkillSpec = { skillId: responseKeys[countSkill], skillName: responseValues[countSkill] };
                                if (objSkillSpec) {
                                    newResponseValues.push(objSkillSpec);
                                }
                            }
                        }

                        if (newResponseValues) {
                            newResponseValues.sort(function (a, b) {
                                return a.skillName.toLowerCase().localeCompare(b.skillName.toLowerCase());
                            });
                            acncm.CacheManager.writeSession("SkillsSpecialization", JSON.stringify(newResponseValues));

                            skillSpecializationArray = acncm.CacheManager.readSession("SkillsSpecialization");

                            if (typeof skillSpecializationArray != 'undefined') {
                                skillSpecializationVal = JSON.parse(skillSpecializationArray);
                            }
                        }
                    }
                },
                error: function () {
                    newResponseValues = null;
                }
            });
            return skillSpecializationVal;
        }
        return skillSpecializationVal;
    }

    function searchDropdown(inputSearch, skillsItemArray) {
        var currentFocus;
        if (inputSearch) {
            inputSearch.addEventListener("input", function () {
                $this = $(this);
                var searchDropDownList, searchDropDownListItem, searchItemIndex, searchValue = $this.val();
                closeAllLists();
                if (!searchValue) {
                    return false;
                }
                currentFocus = -1;
                searchDropDownList = $("#ddSkillSpecializationList");
                if (searchDropDownList) {
                    searchDropDownList.addClass("search-dropdown-items");
                    searchDropDownList.show();
                }
                if (skillsItemArray) {
                    for (searchItemIndex = 0; searchItemIndex < skillsItemArray.length; searchItemIndex++) {
                        if (skillsItemArray[searchItemIndex].substr(0, searchValue.length).toUpperCase() === searchValue.toUpperCase()) {
                            searchDropDownListItem = document.createElement("DIV");
                            searchDropDownListItem.innerHTML = "<strong>" + skillsItemArray[searchItemIndex].substr(0, searchValue.length) + "</strong>";
                            searchDropDownListItem.innerHTML += skillsItemArray[searchItemIndex].substr(searchValue.length);
                            searchDropDownListItem.innerHTML += "<input type='hidden' value='" + skillsItemArray[searchItemIndex] + "'>";
                            searchDropDownListItem.addEventListener("click", function (e) {
                                inputSearch.value = this.innerText;
                                $("#skillsSpecialization").trigger("focus");
                                closeAllLists();
                            });
                            searchDropDownList.append(searchDropDownListItem);

                            if (searchDropDownList.children().length === 5) {
                                break;
                            }
                        }
                    }
                    if (!searchDropDownListItem) {
                        $(searchDropDownList).hide();
                    }
                }
            });
            inputSearch.addEventListener("keydown", function (e) {
                var searchDropDownList = $("#ddSkillSpecializationList");
                if (searchDropDownList) {
                    searchDropDownList = searchDropDownList.children();
                    if (e.keyCode == 40) {
                        e.preventDefault();
                        currentFocus++;
                        addActive(searchDropDownList);
                    } else if (e.keyCode == 38) {
                        e.preventDefault();
                        currentFocus--;
                        addActive(searchDropDownList);
                    } else if (e.keyCode == 13) {
                        e.preventDefault();
                        if (currentFocus > -1) {
                            if (searchDropDownList[currentFocus]) {
                                searchDropDownList[currentFocus].click();
                            }
                        }
                    }
                }
            });
        }

        function addActive(searchDropDownList) {
            if (searchDropDownList) {
                removeActive(searchDropDownList);
                if (currentFocus >= searchDropDownList.length) {
                    currentFocus = 0;
                }
                if (currentFocus < 0) {
                    currentFocus = (searchDropDownList.length - 1);
                }
                if (searchDropDownList[currentFocus]) {
                    searchDropDownList[currentFocus].classList.add("search-dropdown-active");
                }
            }
        }
        function removeActive(searchDropDownList) {
            if (searchDropDownList) {
                for (var searchItemIndex = 0; searchItemIndex < searchDropDownList.length; searchItemIndex++) {
                    if (searchDropDownList[searchItemIndex]) {
                        searchDropDownList[searchItemIndex].classList.remove("search-dropdown-active");
                    }
                }
            }
        }
        function closeAllLists(elmnt) {
            var searchDropDownListItem = $(".search-dropdown-items");
            if (searchDropDownListItem) {
                for (var searchItemIndex = 0; searchItemIndex < searchDropDownListItem.length; searchItemIndex++) {
                    var ddSearchListItem = searchDropDownListItem[searchItemIndex];
                    if (elmnt != ddSearchListItem && elmnt != inputSearch) {
                        if (ddSearchListItem) {
                            $(ddSearchListItem).children().remove();
                            $(ddSearchListItem).hide();
                        }
                    }
                }
            }
        }
        document.addEventListener("click", function (e) {
            closeAllLists(e.target);
        });
    }
}

function rebindUndoableSkills(selectedSkillsArray) {
    $('#selected-skills a.remove-selected-filter').off();
    $('#selected-skills a.remove-selected-filter').undoable();
    $('#selected-skills .remove-selected-filter').on("click", function () {
        var undoText = $(this).parent().next().find('.undo-changes').find('i').text().trim().toLowerCase();
        for (var i = 0; i < selectedSkillsArray.length; i++) {
            if (selectedSkillsArray[i] === undoText) {
                selectedSkillsArray.splice(i, 1);
            }
        }
        storeSelectedValues();

        $('#selected-skills .undo a').on("click", function () {
            var undoText = $(this).closest('.undo-changes').find('i').text().trim();
            var undoValue = $('.selected-filter-container').children('span').find('label[value*="' + undoText + '"]').attr('value');
            var undoItem = $('#selected-skills').children().closest('.undoable.target.comment');
            if (selectedSkillsArray.length < 5) {
                if (selectedSkillsArray.indexOf(undoValue.toLowerCase()) == -1) {
                    selectedSkillsArray.push(undoValue.toLowerCase());
                }
            } else {
                undoItem.remove();
            }

            if (selectedSkillsArray.length === 5) {
                undoItem.remove();
            }
            storeSelectedValues();
        });
    });
    $(this).prop("disabled", false);
}

function GetPreferredSkillSpecialization() {
    var selectedGuids = [];
    var concatGuids = "";

    $('#selected-skills .target.comment').each(function () {
        var $skillSpecializationEditItem = $(this);
        if ($skillSpecializationEditItem.css('display') !== "none") {
            var skillSpecializationEditId = $skillSpecializationEditItem.children('label').attr('id');

            if (skillSpecializationEditId && skillSpecializationEditId !== "")
                selectedGuids.push(skillSpecializationEditId);
        }
    });

    if (selectedGuids.length > 0)
        concatGuids = selectedGuids.join('|');

    return concatGuids;
}

$(".module-body.selection-reseter.cta").on("keyup", function (event) {
    if (event.keyCode == 13) {
        $(this).trigger("click");
    }
});

$('#link-modal-industries').on('keydown', function (e) {
    if (e.which == 9 && ($('.modal.fade.row').hasClass('in'))) {
        e.preventDefault();
        if ($(this).is(":focus")) {
            $('#industries').trigger("focus");
        }
    }
});

$('#RegPrimaryJobEdit').on('keydown', function (e) {
    if (e.which == 9 && ($('.modal.fade.row').hasClass('in'))) {
        e.preventDefault();
        if ($(this).is(":focus")) {
            $('#primary-jobedit').trigger("focus");
        }
    }
});

if (ComponentRegistry.SignIn) {
    var SocialEmail = $('#SignInEmailAdd').val();
    if (SocialEmail != '') {
        $('#CareersRegistration_EmailAddress').val(SocialEmail);
        $("#CareersRegistration_EmailAddress").attr("readonly", "readonly");
    }
    else {
        $("#CareersRegistration_EmailAddress").prop("readonly", false);
    }
}

function ResizeHorizontal() {
    if ($("div").hasClass("profile-edit")) {

        var el = $(".ui-content-box.dock-shadow-box");
        var myLeftUI = $(".ui-content-box.dock-shadow-box").offset().left + 10;
        if ($(window).width() >= 1000) {
            $("#horizontalline").width($(".ui-content-box.dock-shadow-box").width());
            $("#horizontalline").offset({ left: myLeftUI });
            $("#horizontalline").css({ "margin-right": "-20px" });
        }
        else
            $("#horizontalline").removeAttr("style");
    }
}

function TalentConnectionCountryOnChange(selectedVal) {
    var dropdownval = selectedVal.val();
    var TCUniversity = $('#ddTalentConnectionRegistrationSchool');
    var SchoolOther = $('#School-other');
    schoolFields.hide();
    if (dropdownval != "") {
        var SiteLanguage = $('#SiteLanguage').val();
        $.ajax({
            url: "/api/sitecore/EditProfileModule/GetUniversityByCountry",
            async: false,
            type: "POST",
            data: JSON.stringify({ countryId: dropdownval }),
            dataType: "json",
            contentType: "application/json",
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            },
            success: function (data) {
                TCUniversity.prop("disabled", false);
                var ddlValues = '<option value="">Select</option>';
                $('#ddTalentConnectionRegistrationSchool').empty();
                $.each(data, function (key, value) {
                    ddlValues = ddlValues + "<option value=" + value.Id + ">" + value.Name + "</option>";
                });

                ddlValues = ddlValues + "<option value=" + SchoolOther.prop('value') + ">" + SchoolOther.prop('name') + "</option>";
                TCUniversity
                    .html(ddlValues)
                    .selectpicker('refresh');
            }
        });
    }
    else {
        TCUniversity.prop("disabled", true).selectpicker('val', '').selectpicker('refresh');
    }
}

$(window).on("resize", function () {
    ResizeHorizontal();
});

function FormatDateTalentConnection(date) {
    var formattedDate;
    //yyyy-dd-mm DB
    //dd/mm/yyyy val
    var type = $('.dtp-date').attr('type');
    if (type == "text") {
        formattedDate = date.substr(6, 4) + '/' + date.substr(3, 2) + '/' + date.substr(0, 2);
    }
    else {
        formattedDate = date;
    }
    return formattedDate;
}

function PrependOther(stringValue) {
    //to be updated when the 'Other' string source is identified
    return 'Other - ' + stringValue;
}

function GetProfileTalentConnectionValues() {
    var profileTalentConnectionValue = {};

    var status = $('.Status:radio:checked').val();

    if (status == 'isStudent') {
        // For Current Program Of Study Dropdown
        var currentProgramOfStudy = $('#ddTalentConnectionRegistrationCurrentStudy :selected').val();
        var otherCurrentProgramOfStudy = $("#CurrentProgram-other").val();
        var currentProgramOfStudyText = $('#ddTalentConnectionRegistrationCurrentStudy :selected').text();
        var currentProgramDefaultValue = $('#currentProgramDefaultValue').val();
        if (currentProgramOfStudy == otherCurrentProgramOfStudy) {
            profileTalentConnectionValue.CurrentProgramOfStudy = PrependOther($('#currentProgram-textBox').val());
        } else {
            if (currentProgramOfStudyText != currentProgramDefaultValue) {
                profileTalentConnectionValue.CurrentProgramOfStudy = currentProgramOfStudyText;
            }
            else {
                profileTalentConnectionValue.CurrentProgramOfStudy = null;
            }
        }

        // For School/University Dropdown
        var CountryOfSchool = $('#ddTalentConnectionRegistrationCountryOfSchool :selected').val();
        var school = $('#ddTalentConnectionRegistrationSchool :selected').val();
        var otherschool = $("#School-other").val();
        var schoolText = $('#ddTalentConnectionRegistrationSchool :selected').text();
        var schoolDefaultValue = $('#schoolDefaultValue').val();
        if (school == otherschool) {
            profileTalentConnectionValue.School = PrependOther($('#school-textBox').val());
        } else {
            if (schoolText != schoolDefaultValue) {
                profileTalentConnectionValue.School = schoolText;
            }
            else {
                profileTalentConnectionValue.School = null;
            }
        }
        profileTalentConnectionValue.CountryOfSchool = CountryOfSchool;

        // For Degree Major
        var degreeMajor = $('#ddTalentConnectionRegistrationMajor :selected').val();
        var otherDegreeMajorValue = $("#DegreeMajor-other").val();
        var degreeMajorText = $('#ddTalentConnectionRegistrationMajor :selected').text();
        var degreeMajorDefaultValue = $('#degreeMajorDefaultValue').val();
        if (degreeMajor == otherDegreeMajorValue) {
            profileTalentConnectionValue.DegreeMajor = PrependOther($('#degreeMajor-textBox').val());
        } else {
            if (degreeMajorText != degreeMajorDefaultValue) {
                profileTalentConnectionValue.DegreeMajor = degreeMajorText;
            }
            else profileTalentConnectionValue.DegreeMajor = null;
        }

        var startDateStr = $('#startDateVal').val();
        if (startDateStr != '') {
            profileTalentConnectionValue.DegreeStartDate = FormatDateTalentConnection(startDateStr);
        }
        var expectedGradDateStr = $('#gradDateVal').val();
        if (expectedGradDateStr != '') {
            profileTalentConnectionValue.ExpectedGraduationDate = FormatDateTalentConnection(expectedGradDateStr);
        }
        profileTalentConnectionValue.HighestDegreeEarned = null;
    }
    else {
        profileTalentConnectionValue.HighestDegreeEarned = $('#ddTalentConnectionRegistrationDegreeEarnedTC').val();

        // For Current Program Of Study Dropdown
        profileTalentConnectionValue.currentProgramOfStudy = null;
        profileTalentConnectionValue.otherCurrentProgramOfStudy = null;
        profileTalentConnectionValue.currentProgramOfStudyText = null;
        profileTalentConnectionValue.currentProgramDefaultValue = null;

        // For School/University Dropdown
        profileTalentConnectionValue.countryOfSchool = null;
        profileTalentConnectionValue.school = null;
        profileTalentConnectionValue.otherschool = null;
        profileTalentConnectionValue.schoolText = null;
        profileTalentConnectionValue.schoolDefaultValue = null;

        // For Degree Major
        profileTalentConnectionValue.degreeMajor = null;
        profileTalentConnectionValue.otherDegreeMajorValue = null;
        profileTalentConnectionValue.degreeMajorText = null;
        profileTalentConnectionValue.degreeMajorDefaultValue = null;

        profileTalentConnectionValue.startDateStr = null;
        profileTalentConnectionValue.expectedGradDateStr = null;
    }

    profileTalentConnectionValue.PhoneNumber = $('#EditProfilePhoneNumber').val();
    profileTalentConnectionValue.LinkedInProfileUrl = $('#TalentConnectionRegistration_LinkedIn').val();

    return profileTalentConnectionValue;
}

function ReadOnlyDatepickerEditProfile() {
    var type = $('.dtp-date').attr('type');
    if (type == "text") {
        $('#startDateVal').val($('#startDateTC').val());
        $('#gradDateVal').val($('#gradDateTC').val());
        $('#startDateVal').attr("readonly", true);
        $('#gradDateVal').attr("readonly", true);
    }
    else if (type == "date") {
        $('#startDateVal').val($('#degreeDateVal').val());
        $('#gradDateVal').val($('#expDateVal').val());
        $('#startDateVal').prop("readonly", false);
        $('#gradDateVal').prop("readonly", false);
    }
}

//ADO 1083170 - Max Primary Job Edit Checker function
function checkMaxEdit(checkbox) {
    var chk = $(checkbox);
    var selectedCheckbox = $(checkbox + ":checked").length;
    for (i = 0; i < chk.length; i++) {

        if (selectedCheckbox >= 3) {
            if (!chk[i].checked) {
                chk[i].disabled = true;

            }

        } else {

            if (!chk[i].checked) {
                chk[i].disabled = false;
            }

        }
    }

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CareersNavigationTab.js
//Version 4.0
if (ComponentRegistry.CareersNav) {
    $(function () {
        $(window).scrollTop(0);
        var myProfileTab = window.location.hash;
        var activeLink = "";

        updateTopNavBar(myProfileTab);

        //Bug 410080: Updated functionality to only take effect on CareersNavigationTab elements.
        $(document).on('click', ".profile-edit h2 a[data-toggle='tab']", function (e) {
            var thisSpan = $(".profile-edit h2 span[data-toggle='tab']");
            var navLink = thisSpan.data('href');

            thisSpan.replaceWith("<a data-toggle='tab' analytics-no-content-click='true' data-analytics-link-name='" + thisSpan.text() + "' data-analytics-content-type='cta' href='" + navLink + "' id='" + thisSpan.attr('id') + "'>" + thisSpan.text() + "</a>");
            $(this).replaceWith("<span data-toggle='tab' data-href='" + $(this).attr('href') + "' id='" + $(this).attr('id') + "'>" + $(this).text() + "</span>");

            myProfileTab = e.target.hash;
            if (myProfileTab != null && myProfileTab != "") {
                window.location.replace(myProfileTab);
            }
            $(window).scrollTop(0);

            updateTopNavBar(myProfileTab);
        });

        SelectTab(myProfileTab);
    });

    function SelectTab(myProfileTab) {
        if (myProfileTab != null && myProfileTab != "") {
            myProfileTab = myProfileTab.replace("#", "");
            myProfileTab = "#Nav" + myProfileTab;
        } else { myProfileTab = "#NavJobs"; }

        if ($(myProfileTab).length <= 0) { myProfileTab = "#NavJobs"; }

        var selectedMarkUp = $(myProfileTab)[0].outerHTML;
        selectedMarkUp = selectedMarkUp.replace(/<a/g, "<span");
        selectedMarkUp = selectedMarkUp.replace(/\/a>/g, "/span>");
        $(myProfileTab)[0].outerHTML = selectedMarkUp;

        $(myProfileTab).trigger("click");
    }

    function updateTopNavBar(activeLink) {
        var jobsLink = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(1) a, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(1) a");
        var editProfileLink = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(2) a, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(2) a");
        var subscriptionAlertsLink = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(3) a, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(3) a");

        var jobsSpan = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(1) span, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(1) span");
        var editProfileSpan = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(2) span, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(2) span");
        var subscriptionAlertsSpan = $("#loginPopoverContainer #loginPopoverContent .authenticated ul li:nth-child(3) span, #LoginPopoverTriggerContainer .popover .popover-content .authenticated ul li:nth-child(3) span");

        if (activeLink == "#Jobs") {
            jobsLink = jobsLink.replaceWith("<span data-href='" + jobsLink.attr('href') + "'>" + jobsLink.html() + "</span>");
            editProfileSpan = editProfileSpan.replaceWith("<a class='user-link' href=" + editProfileSpan.data('href') + ">" + editProfileSpan.html() + "</a>");
            subscriptionAlertsSpan = subscriptionAlertsSpan.replaceWith("<a class='user-link' href=" + subscriptionAlertsSpan.data('href') + ">" + subscriptionAlertsSpan.html() + "</a>");
            //jobsLink.css("display", "none");
            //editProfileLink.removeAttr('style');
            //subscriptionAlertsLink.removeAttr('style');
        }
        else if (activeLink == "#EditProfile") {
            editProfileLink = editProfileLink.replaceWith("<span data-href='" + editProfileLink.attr('href') + "'>" + editProfileLink.html() + "</span>");
            subscriptionAlertsSpan = subscriptionAlertsSpan.replaceWith("<a class='user-link' href=" + subscriptionAlertsSpan.data('href') + ">" + subscriptionAlertsSpan.html() + "</a>");
            jobsSpan = jobsSpan.replaceWith("<a class='user-link' href=" + jobsSpan.data('href') + ">" + jobsSpan.html() + "</a>");
            //editProfileLink.css("display", "none");
            //jobsLink.removeAttr('style');
            //subscriptionAlertsLink.removeAttr('style');
        }
        else if (activeLink == "#Subscription") {
            subscriptionAlertsLink = subscriptionAlertsLink.replaceWith("<span data-href='" + subscriptionAlertsLink.attr('href') + "'>" + subscriptionAlertsLink.html() + "</span>");
            editProfileSpan = editProfileSpan.replaceWith("<a class='user-link' href=" + editProfileSpan.data('href') + ">" + editProfileSpan.html() + "</a>");
            jobsSpan = jobsSpan.replaceWith("<a class='user-link' href=" + jobsSpan.data('href') + ">" + jobsSpan.html() + "</a>");
            //subscriptionAlertsLink.css("display", "none");
            //jobsLink.removeAttr('style');
            //editProfileLink.removeAttr('style');
        }
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\changeEmailModule.js
/* version="6" */
if (ComponentRegistry.changeEmailModule) {
    $(function () {
        var FormID = $('#changeEmailForm');

        $(FormID).bootstrapValidator({
            fields: {
                newEmail: {
                    trigger: 'blur',
                    validators: {
                        emailAddress: {
                            message: $('#invalidNewEmailFormat').val()
                        },
                        notEmpty: {
                            message: $('#requiredNewEmail').val()
                        },
                        different: {
                            field: 'oldEmail',
                            message: $('#identicalNewOldEmail').val()
                        },
                        callback: {
                            message: $('#checkNewEmailExist').val(),
                            callback: function (value, validator, $field) {
                                if ((value == '') || (value != '' && (value == $('#oldEmail').val()))) //covered by notEmpty, different
                                {
                                    return true;
                                }
                                else {
                                    return !ChangeEmailEmailExists();
                                }
                            }
                        }
                    }
                },
                captchaInput: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#requiredCaptcha').val()
                        },
                        callback: {
                            message: $('#invalidCaptcha').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }
                                else {
                                    ChangeEmailCaptVal = isCaptchaValid();
                                    return ChangeEmailCaptVal;
                                }
                            }
                        }
                    }
                }
            }
        });
    });
    $('#ChangeEmailButton').on("click", function () {
        var $custForm = $('#changeEmailForm').data('bootstrapValidator');
        var CaptInput = $('input[name="captchaInput"]').val();
        $custForm.$submitButton = this;
        $custForm.validate();

        if ($custForm.isValid() && ChangeEmailCaptVal) {
            $('#changeEmailForm input, #changeEmailForm select').each
                (
                   function (index) {
                       var input = $(this);

                       if (input.attr('name') == 'oldEmail') {
                           oEmail = input.val();
                       }
                       if (input.attr('name') == 'newEmail') {
                           nEmail = input.val();
                       }
                   }
                )
            $.ajax({
                url: "/api/sitecore/ChangeEmailModule/ChangeEmailPost",
                type: "POST",
                data: JSON.stringify({
                    oldEmail: oEmail,
                    newEmail: nEmail,
                    _captchaInput: CaptInput,
                    _captchaInstanceId: InstanceCaptId
                }),
                contentType: "application/json",
                async: false,
                error: function (res) {
                    alert(res);
                    jQuery("body").trigger("analytics-form-error");
                },
                success: function (res) {
                    if (!isNaN(parseFloat(res)) && isFinite(res)) {
                        jQuery("body").trigger("analytics-form-success");
                        window.location.assign("/Authentication/SignOut/SignOut?returnUrl=" + $("#changeEmailForm").attr("data-by-success-change"));
                    }
                    else {
                        alert(res);
                    }
                }
            });
        }
        else {
            jQuery("body").trigger("analytics-form-error");
        }
        return "no data";
    });

    $('#CancelButton').on("click", function () {
        window.history.go(-1);
    });

    function isCaptchaValid() {
        var CaptInput = $('input[name="captchaInput"]').val();
        var CaptchaID = $('#CaptchaID').val();
        var CaptInstance = $('#CaptInstance').val();
        var oldEmailAddress = $('#oldEmail').val();
        var returnVal = false;

        $.ajax({
            url: "/api/sitecore/ChangeEmailModule/isCaptchaValid",
            type: "POST",
            data: JSON.stringify({
                oldEmail: oldEmailAddress,
                _captchaInput: CaptInput,
                _captchaInstanceId: InstanceCaptId
            }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("Captcha Error");
            },
            success: function (res) {
                returnVal = res.CorrectCaptcha;

                if (!returnVal) {
                    CEmailCID.ReloadImage();
                }
            }
        });
        return returnVal;
    }

    function ChangeEmailEmailExists() {
        var emailAddress = $('#newEmail').val();
        var oldEmailAddress = $('#oldEmail').val();
        var returnVal = false;

        $.ajax({
            url: "/api/sitecore/ChangeEmailModule/IsEmailExists",
            type: "POST",
            data: JSON.stringify({
                oldEmail: oldEmailAddress,
                emailAddress: emailAddress
            }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                alert("Error in IsEmailExists.");
            },
            success: function (res) {
                returnVal = res.blnExists;
            }
        });
        return returnVal;
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\ClientAccount.js
/* version="4"*/
if (ComponentRegistry.ClientAccount) {
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $(function () {
        var FormId = $('#createPassword');

        $(FormId).bootstrapValidator({
            fields: {
                emailAddress: {
                    trigger: 'blur',
                    validators: {
                        emailAddress: {
                            message: $('#invalidEmailAdd').val()
                        },
                        notEmpty: {
                            message: $('#emailRequired').val()
                        },
                        callback: {
                            message: $('#ClientAccountSetupEmailAlreadyRegistered').val(),
                            callback: function (value, validator) {
                                if (value == '') {
                                    return true;
                                }
                                else {
                                    return !ClientAccountSetupIsEmailRegistered();
                                }
                            }
                        }

                    }
                },
                inputPassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#passwordRequired').val()
                        },
                        callback: {
                            message: $('#passwordMessage').val(),
                            callback: function (value, validator) {
                                if (value == '') {
                                    return true;
                                }
                                if (value != '' && value.length >= 8) {
                                    var isPasswordCorrect = IsInputPasswordValid();
                                    return isPasswordCorrect;
                                }
                            }
                        }
                    }
                },
                confirmPassword: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: $('#retypeRequired').val()
                        },
                        //stringLength: {
                        //    min: 8,
                        //    message: $('#passwordLength').val()
                        //},
                        identical: {
                            field: 'inputPassword',
                            message: $('#notSamePassword').val()
                        },
                        callback: {
                            message: $('#retypeMessage').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }
                                //if (value.length < 8 && value != '') {
                                //validator.updateStatus('confirmPassword', 'INVALID');
                                //return {
                                //    message: $('#passwordLength').val(),
                                //    valid: true
                                //};
                                //}
                                if (value.length >= 8 && value != '') {
                                    var isRetypePasswordCorrect = IsRetypePasswordValid();
                                    return isRetypePasswordCorrect;
                                }
                            }
                        }
                    }
                }
            }
        })
    });

    $('#btnclientcreatePassword').on("click", function (event) {
        var $formBootStrap = $('#createPassword').data('bootstrapValidator');

        $formBootStrap.$submitButton = this;
        $formBootStrap.validate();

        if ($formBootStrap.isValid()) {
            $('#createPassword input, #createPassword select').each
                (
                    function (index) {
                        var input = $(this);

                        if (input.attr('name') == 'inputPassword') {
                            InputPwd = input.val();
                        }
                        //if (input.attr('name') == 'confirmPassword') {
                        //    RetypPwd = input.val();
                        //}
                        if (input.attr('name') == 'emailAddress') {
                            emailAdd = input.val();
                        }
                    }
                )
            var queryString = getParameterByName("invite");
            var invitationID = $('input[name="invitationID"]').val();
            if (queryString.length > 0) {
                $.ajax(
                    {
                        url: "/api/sitecore/ClientAccountSetup/ClientAccountPost",
                        type: "POST",
                        data: JSON.stringify({
                            inputPassword: InputPwd,
                            //confirmPassword: RetypPwd,
                            emailAddress: emailAdd,
                            invitationId: invitationID
                        }),
                        contentType: "application/json",
                        async: false,
                        dataType: 'json',
                        //traditional: true,
                        success: function (result) {
                            var returnValue = result.returnPasswordCreated;
                            //alert(returnValue);

                            if (returnValue) {
                                window.location = ClientIndexRedirect;
                                jQuery("body").trigger("analytics-form-success");
                                event.preventDefault();
                            }
                            else {
                                alert("Failed to create password");
                                returnValue = "no data";
                            }
                        },
                        error: function (result) {
                            jQuery("body").trigger("analytics-form-error");
                            window.location.assign('https://www.accenture.com/');
                            event.preventDefault();
                        }
                    });
            }
            else {
                var resultValue = "no data";
                var newPwd = $("input[name=inputPassword]").val();
                $.ajax(
                    {
                        url: "/api/sitecore/ClientAccountSetup/UpdatePassword",
                        type: "POST",
                        data: JSON.stringify({
                            emailAddress: emailAdd,
                            newPassword: newPwd,
                            invitationId: invitationID
                        }),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        async: false,
                        success: function (data) {
                            if (data)
                                window.location.href = ClientIndexRedirect;
                            else
                                resultValue = "No data";
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            resultValue = errorThrown;
                            jQuery("body").trigger("analytics-form-error");
                        }
                    });
                //return resultValue;
            }
        }
        else {
            jQuery("body").trigger("analytics-form-error");
        }
        return "Error";
    });

    function IsInputPasswordValid() {
        var PasswordInput = $('input[name="inputPassword"]').val();
        var returnValue = false;

        $.ajax({
            url: "/api/sitecore/ClientAccountSetup/IsPasswordValid",
            type: "POST",
            data: JSON.stringify({ newPassword: PasswordInput }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.returnInputPassword;
                return returnValue;
            },
            error: function (result) {
                alert("Input Password Error Validation");
            }
        });
        return returnValue;
    }

    function IsRetypePasswordValid() {
        var ConfirmPasswordInput = $('input[name="confirmPassword"]').val();
        var returnValue = false;

        $.ajax({
            url: "/api/sitecore/ClientAccountSetup/IsPasswordValid",
            type: "POST",
            data: JSON.stringify({ newPassword: ConfirmPasswordInput }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.returnInputPassword;
                return returnValue;
            },
            error: function (result) {
                alert("Retype Password Error Validation");
            }
        });
        return returnValue;
    }

    function ClientAccountSetupIsEmailRegistered() {
        var EmailInput = $('input[name="emailAddress"]').val();
        var returnValue = true;
        var requestType = "request";
        if (getParameterByName("invite").length > 0) { requestType = "invite"; }

        $.ajax({
            url: "/api/sitecore/ClientAccountSetup/IsEmailRegistered",
            type: "POST",
            data: JSON.stringify({
                emailAddress: EmailInput,
                requestType: requestType,
                InvitationId: $('input[name="invitationID"]').val()
            }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.blnIsRegistered;
                return returnValue;
            },
            error: function (result) {
                alert("Email Input Error Validation");
            }
        });
        return returnValue;
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\clientEditProfile.js
/* version="11" */
if (ComponentRegistry.ClientEditProfile) {
    var EditProfilePassword;
    var EditProfileOldPassword;
    var EditProfileEmailAddress;

    function editProfile_visibility(id, show) {
        var e = document.getElementById(id);
        if (show == 'hide')
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
    
    //Intial load
    editProfile_visibility("clientProfileLeftNav", "hide");
    editProfile_visibility("head_editprofilepage", "hide");
    editProfile_visibility("head_subscriptionpage", "hide");

    //$(window).unload(function () {
    //    //clear social session
    //    $.post("/api/sitecore/SocialSignInModule/ClearSocialSessionUnmerged");
    //});

    //adjust mobile view
    function SetCookie(name, value, path, days, domain, secure) {
        var expires = null;
        if (days != null) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = date.toGMTString();
        }

        document.cookie = name + "=" + escape(value) +
            ((expires) ? ";expires=" + expires : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    }

    function GetCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }
    $(window).on('load resize', function () {
        
        if (isMobile()) {
            editProfile_visibility("head_editprofilepage", "show");
            editProfile_visibility("head_subscriptionpage", "show");
        }
        else {
            editProfile_visibility("clientProfileLeftNav", "show");
        }
    });

   
    function editProfile_updateNavUser() {
        var recachecookie = "triggerRecache";
        if (GetCookie(recachecookie) === undefined)
            SetCookie(recachecookie, "1", null, "1", null, null);
        else
            document.cookie = recachecookie + "=" + (GetCookie(recachecookie) + 1);
        profileFirstName = document.getElementById("EditProfileFirstName").value; //$('#EditProfileFirstName').val();
        profileLastName = document.getElementById("EditProfileLastName").value; //$('#EditProfileLastName').val();

        if (!profileFirstName || profileFirstName.length === 0) {
            varUserDisplayName = '';
        }
        else {
            varUserDisplayName = profileFirstName + " " + profileLastName;
        }
        
        if (!varUserDisplayName || varUserDisplayName.length === 0) {
            //no modification
        }
        else {
            if (document.getElementById('navUserDisplayUserName') == undefined) {
                //navigation setting is undefined for "navUserDisplayUserName"

                if (document.getElementById('navsignInLink') == undefined) {
                    //navigation setting is undefined for "navsignInLink"
                }
                else {
                    document.getElementById('navsignInLink').innerHTML = varUserDisplayName;

                }
            }
            else if (document.getElementById('block-header-new')) {
                document.getElementById('navUserDisplayUserName').innerHTML = "";
            }
            else {
                document.getElementById('navUserDisplayUserName').innerHTML = varUserDisplayName;
            }
        }
    }



    $(function () {

        var FormId = $('#defaultForm');
        $(window).scrollTop(0);		 
        var myProfileTab = window.location.hash;
        var activeLink = "";

        $(document).on('click', ".client h2 a[data-toggle='tab']", function (e) {
			
            var thisSpan = $(".client h2 span[data-toggle='tab']");
            var navLink = thisSpan.data('href');

            thisSpan.replaceWith("<a data-toggle='tab' href='" + navLink + "' id='" + thisSpan.attr('id') + "'>" + thisSpan.text() + "</a>");
            $(this).replaceWith("<span data-toggle='tab' data-href='" + $(this).attr('href') + "' id='" + $(this).attr('id') + "'>" + $(this).text() + "</span>");

            myProfileTab = e.target.hash;
            if (myProfileTab != null && myProfileTab != "") {
                window.location.replace(myProfileTab);
            }
            $(window).scrollTop(0);
         
        });
        SelectNav(myProfileTab);

        $(FormId).bootstrapValidator({
            fields: {
                EditProfileOldPassword: {
                    trigger: 'blur',
                    validators: {
                        callback: {
                            message: $('#ClientEditOldPasswordIncorrectValidation').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }
                                if (value != '' && value.length >= 8) {
                                    return ClientEditProfileIsInputOldPasswordValid(false);
                                }
                            }
                        }
                    }
                },
                EditProfileCreatePassword: {
                    trigger: 'blur',
                    validators: {
                        callback: {
                            message: $('#ClientEditPasswordRequirementValidation').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }

                                if (value != '' && value.length >= 8) {
                                    if (ClientEditProfileIsInputOldPasswordValid(true)) {
                                        $('#EditProfileCreatePassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#ClientEditPasswordSameAsPrevious').val());
                                        return false;
                                    }
                                    return ClientEditProfileIsInputNewPasswordValid();
                                }
                                else {
                                    $('#EditProfileCreatePassword').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#ClientEditPasswordRequirementValidation').val());
                                    return false;
                                }
                            }
                        }
                    }
                },
                EditProfileRetypePassword: {
                    trigger: 'blur',
                    validators: {
                        callback: {
                            message: $('#ClientEditPasswordRequirementValidation').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }
                                if (value != '' && value.length >= 8) {
                                    return ClientEditProfileIsInputNewRetypePasswordValid();
                                }
                            }
                        }
                    }
                }
            }
        })


        editProfile_updateNavUser();

        // Change Email Link Placement - START
        var changeEmailLink = $('#change-email-link');
        var changeEmailLinkContainer = $('#change-email-link-container');

        if (changeEmailLink.find('a').text() != "") {
            changeEmailLinkContainer.html(changeEmailLink.html());
            changeEmailLinkContainer.find('a').addClass('cta visible-xs hover-underline');
        }
        // Change Email Link Placement - END

        // Change Mobile Number Link Placement - START
        var changePhoneNumberLink = $('#change-mobile-number-link');
        var changePhoneNumberLinkContainer = $('#change-mobile-number-link-container');

        if (changePhoneNumberLink.find('a').text() != "") {
            changePhoneNumberLinkContainer.html(changePhoneNumberLink.html());
            changePhoneNumberLinkContainer.find('a').addClass('cta visible-xs hover-underline');
        }


        // Change Mobile Number Link Placement - END
    });

    $('#EditProfileUpdateBtn').on("click", function (e) {
        var objProfile = {};
        var careersRegistrationforms = $(this).closest("form");
        var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
        $formBootStrap.$submitButton = this;
        $formBootStrap.validate();

        $(".validatorMessage .outer-message").removeAttr("style");
        
        if ($formBootStrap.isValid()) {



            //objProfile.UserProfileId = ProfileID;
            objProfile.FirstName = $('#EditProfileFirstName').val();
            objProfile.LastName = $('#EditProfileLastName').val();            
            
            $("#message-container").empty();
            $.ajax({
                url: "/api/sitecore/ClientEditProfileModule/UpdateProfile",
                async: false,
                type: "POST",
                data: JSON.stringify({ Profile: objProfile}),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                    jQuery("body").trigger("analytics-form-error");
                },
                success: function (jsonOutput, textStatus, jqXHR) {
                    var html = "<div><b>";
                    $(jsonOutput).each(function () {
                        html += this.message;
                    });
                    html += "</b></div>";
                    $("#message-container").append(html);
                    jQuery("body").trigger("analytics-form-success");


                }
            });
        }
        else {
            jQuery("body").trigger("analytics-form-error");
        }

            e.preventDefault();
    });
    

    $("#updatePasswordBtn").on("click", function () {

        EditProfilePassword = $('#EditProfileCreatePassword').val();
        EditProfileOldPassword = $('#EditProfileOldPassword').val();
        $.ajax({
            url: "/api/sitecore/ClientEditProfileModule/ChangePassword",
            async: false,
            type: "POST",
            data: JSON.stringify({ oldPassword: EditProfileOldPassword, newPassword: EditProfilePassword }),
            dataType: "json",
            contentType: "application/json",
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            },
            success: function (jsonOutput, textStatus, jqXHR) {
                if (jsonOutput == true) {
                    alert('Successfully changed password');
                    $(".modal").modal('hide');
                }
                else {
                    alert('Invalid password');
                }
            }
        });
    });    
    
    //Bug #384085 - remove text-decoration of navigation
    $('div.client.profile-edit .form-section .nav a').removeAttr('style class').css('text-decoration', 'none');

    
}
function SelectNav(myProfileTab) {
    if (myProfileTab != null && myProfileTab != "") {
        myProfileTab = myProfileTab.replace("#", "");
        myProfileTab = "#Nav" + myProfileTab;
    } else { myProfileTab = "#Naveditprofilepane"; }

    if ($(myProfileTab).length <= 0) { myProfileTab = "#Naveditprofilepane"; }

    var selectedMarkUp = $(myProfileTab)[0].outerHTML;
    selectedMarkUp = selectedMarkUp.replace(/<a/g, "<span");
    selectedMarkUp = selectedMarkUp.replace(/\/a>/g, "/span>");
    $(myProfileTab)[0].outerHTML = selectedMarkUp;

    $(myProfileTab).trigger("click");
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\resetpassword.js
/*version="13"*/
function isAccountLockout(emailAddress) {
    var result = true;
    $.ajax({
        url: '/api/sitecore/ResetPassword/IsAccountLockout',
        data: JSON.stringify({
            emailAddress: emailAddress
        }),
        dataType: "json",
        context: this,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        async: false,
        success: function (data) {
            result = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            result = false;
        }
    });
    return result;
}

if (ComponentRegistry.ResetPassword) {

$(function () {
        var resetPasswordContentData = $('#reset-password-module-content-data');
        var captchaInput;
        var isCaptchaValid = true;

        $("#resetPasswordForm").bootstrapValidator({
            fields: {
                CaptchaInput: {
                    trigger: 'submit',
                    validators: {
                        notEmpty: {
                            message: resetPasswordContentData.data('required-captcha')
                        },
                        callback: {
                            message: resetPasswordContentData.data('incorrect-captcha')
                        }
                    }
                }
            }
        });

        function sendEmail() {
            var emailAddress = $('input[name="emailAdd"]').val();
            var createPage = $('input[name="createPasswordPage"]').val();
            var countryLanguage = resetPasswordContentData.data('country-site');
            var captchaInpudId = resetPasswordContentData.data('captcha-id')
            captchaInput = $('#' + captchaInpudId);
            var captchaInstance = captchaInput.data("captcha-instance");
            var captchaId = captchaInput.data("captcha-id");
            var captchaInputValue = captchaInput.val();
            var $result = true;
            $.ajax({
                url: '/api/sitecore/ResetPassword/SendResetEmail',
                data: JSON.stringify({
                    emailAddress: emailAddress,
                    pagePath: pageContext,
                    currentLanguage: countryLanguage,
                    captchaId: captchaId,
                    captInput: captchaInputValue,
                    captInstance: captchaInstance
                }),
                dataType: "json",
                context: this,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                async: false,
                success: function (data) {
                    if (data == "InvalidCaptcha") {
                        $(".error-summary").hide();
                        $(captchaInput).get(0).Captcha.ReloadImage();
                        $('#resetPasswordForm').data('bootstrapValidator').updateStatus('CaptchaInput', 'INVALID', 'callback');
                        isCaptchaValid = false;
                        $result = false;
                        jQuery("body").trigger("analytics-form-error");
                    }
                    else if (data) {
                        isCaptchaValid = true;
                        $result = true;
                    }
                    else {
                        $result = false;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $result = false;
                    jQuery("body").trigger("analytics-form-error");
                }
            });
            return $result;
        }

        function validateEmailAddress(emailAddress, methodName) {
            var result = true;
			$.ajax({
				url: '/api/sitecore/ResetPassword/' + methodName,
                data: JSON.stringify({
                    emailAddress: emailAddress
                }),
                dataType: "json",
                context: this,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                async: false,
                success: function (data) {
                    result = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    result = false;
                }
            });
            return result;
		}

        $('#btnResetPassword').on("click", function () {
            var captchaInputId = resetPasswordContentData.data('captcha-id')
            captchaInput = $('#' + captchaInputId);
            var captInput = captchaInput.val();

            if (captInput !== "") {
                var $theForm = $('#resetPasswordForm').data('bootstrapValidator');
                $theForm.enableFieldValidators('CaptchaInput', false);
            }
            else {
                var $theForm = $('#resetPasswordForm').data('bootstrapValidator');
                $theForm.enableFieldValidators('CaptchaInput', true);
            }

            var emailAddress = $('input[name="emailAdd"]').val();
            $theForm.validate();
            if ($theForm.isValid()) {
                var $result = true;
                $(".error-summary").hide();

                if (validateEmailAddress(emailAddress, 'ValidateEmailAddressInMembership')) {
                    if (isAccountLockout(emailAddress)) {
                        $(".account-lockout-error").removeClass("hidden");
                        $(".email-not-found-error").addClass("hidden");
                        $result = false;
                        $(captchaInput).get(0).Captcha.ReloadImage();
                        $theForm.resetForm();
                    }
                    else if (validateEmailAddress(emailAddress, 'ValidateIfLinkedInUser')) {
                        $(".account-lockout-error").addClass("hidden");
                        $(".email-not-found-error").addClass("hidden");
                        $(".unregistered-account-error").removeClass("hidden");
                        $result = false;
                    }
                    else {
                        $result = sendEmail();
                    }
                }
                else {
                    $(".account-lockout-error").addClass("hidden");
                    $(".email-not-found-error").removeClass("hidden");
                    $(".unregistered-account-error").addClass("hidden");

                    $result = false;
                }

                if ($result) {
                    var emailAddress = $('input[name="emailAdd"]').val();
                    $("#resetPasswordForm").hide();
                    var successMsg = $('#sectionSuccess').find('#success-message');
                    successMsg.html(successMsg.html().replace('<email_address>', emailAddress).replace('<EMAIL_ADDRESS>', emailAddress));
                    $("#sectionSuccess").show();
                    jQuery("body").trigger("analytics-form-success", true);
                }
                else {
                    if (!isCaptchaValid) {
                        $(".error-summary").hide();
                    }
                    else {
                        isCaptchaValid = true;
                        $(".error-summary").show();
                    }
                }
            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        });
    });
}

if (ComponentRegistry.CreatePassword) {

$(function () {
        var FormId = $('#createPasswordForm');
        $(FormId).bootstrapValidator({
            fields: {
                UserPassword: {
                    trigger: 'blur',
                    validators: {
                        callback: {
                            message: $('#passwordMessage').val(),
                            callback: function (value, validator) {
                                if ($("input[name='RetypePassword']").val().length > 0) {
                                    ArePasswordsIdentical();
                                }
                                if (value == '') {
                                    return true;
                                }

                                if (value != '' && value.length > 8) {
                                    if (IsSameAsPreviousPassword()) {
                                        $('input[name="UserPassword"]').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#PasswordSameAsPrevious').val());
                                        return false;
                                    }
                                    return CreatePasswordIsInputPasswordValid();
                                }
                                else {
                                    $('input[name="UserPassword"]').data('bv.messages').find('.help-block[data-bv-validator="callback"]').html($('#passwordMessage').val());
                                    return false;
                                }

                            }
                        }
                    }
                },
                RetypePassword: {
                    trigger: 'blur',
                    validators: {
                        callback: {
                            message: $('#passwordMessage').val(),
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true;
                                }
                                if (value.length > 8 && value != '') {
                                    return CreatePasswordIsRetypePasswordValid();
                                }
                            }
                        }
                    }
                }
            }
        })
    });
    function ArePasswordsIdentical() {
        var retypePasswordField = $("#reTypePasswordTxtbox");
        var retypePasswordValidatorIcon = retypePasswordField.find($("i[data-bv-field='RetypePassword']"));
        var retypePasswordValidator = $("#reTypePasswordTxtbox .validatorMessage").find("span[data-bv-validator='identical']");
        if ($("input[name='RetypePassword']").val() !== $('input[name="UserPassword"]').val()) {
            if (!retypePasswordField.hasClass("has-error")) {
                retypePasswordField.removeClass("has-success");
                retypePasswordField.addClass("has-error");
            }
            if (retypePasswordValidatorIcon.hasClass("glyphicon-ok")) {
                retypePasswordValidatorIcon.removeClass("glyphicon-ok");
                retypePasswordValidatorIcon.addClass("glyphicon-remove");
            }
            retypePasswordValidator.css("display", "inline-block");
            retypePasswordValidator.attr("data-bv-visible", "true");
            retypePasswordValidator.parent().css("display", "inline-block");
        }
    }
    function IsSameAsPreviousPassword() {
        var emailAddress = $('input[name="emailAddress"]').val();
        var PasswordInput = $('input[name="UserPassword"]').val();
        var returnValue = false;

        $.ajax({
            url: "/api/sitecore/ResetPassword/ValidatePreviousPassword",
            type: "POST",
            data: JSON.stringify({
                emailAddress: emailAddress,
                newPassword: PasswordInput
            }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.isPasswordValidated;
                return returnValue;
            },
            error: function (result) {
                alert("Input Password Error Validation");
            }
        });
        return returnValue;
    }

    function CreatePasswordIsInputPasswordValid() {
        var PasswordInput = $('input[name="UserPassword"]').val();
        var returnValue = false;

        $.ajax({
            url: "/api/sitecore/ResetPassword/ValidatePassword",
            type: "POST",
            data: JSON.stringify({ newPassword: PasswordInput }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.isPasswordValidated;               
                return returnValue;
            },
            error: function (result) {
                alert("Input Password Error Validation");
            }
        });
        return returnValue;
    }

    function CreatePasswordIsRetypePasswordValid() {
        var ConfirmPasswordInput = $('input[name="RetypePassword"]').val();
        var returnValue = false;

        $.ajax({
            url: "/api/sitecore/ResetPassword/ValidatePassword",
            type: "POST",
            data: JSON.stringify({ newPassword: ConfirmPasswordInput }),
            contentType: "application/json",
            async: false,
            success: function (result) {
                returnValue = result.isPasswordValidated;
                return returnValue;
            },
            error: function (result) {
                alert("Retype Password Error Validation");
            }
        });
        return returnValue;
    }

    function updatePassword(emailAddress) {
        var newPass = $('input[name="UserPassword"]').val();
        var resetPasswordID = $('input[name="resetPasswordID"]').val();
        var result = true;
        $.ajax({
            url: '/api/sitecore/ResetPassword/UpdatePassword',
            data: JSON.stringify({
                emailAddress: emailAddress,
                newPassword: newPass,
                resetPasswordID: resetPasswordID
            }),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: false,
            success: function (data) {
                if (data) {
                    $result = true;
                }
                else {
                    $result = false;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                result = false;
            }
        });       
        return result;
    }

    $('#btnCreatePassword').on("click", function (event) {
        var $theForm = $('#createPasswordForm').data('bootstrapValidator');
        var emailAddress = $('input[name="emailAddress"]').val();
        //$theForm.$submitButton = this;
        $theForm.validate();
        if ($theForm.isValid()) {
            var $result = true;
            $(".error-summary").hide();

            if (isAccountLockout(emailAddress)) {
                $(".account-lockout-error").removeClass("hidden");
                $result = false;
            } else {
                $(".account-lockout-error").addClass("hidden");
				$result = updatePassword(emailAddress);
				if (!$result) {
					$(".network-error").removeClass("hidden");
				}
            }

            if ($result) {
                jQuery("body").trigger("analytics-form-success", true);
                $("#divCreate").hide();
                $("#sectSuccess").show();
            }
            else {
                $(".error-summary").show();
            }
        
            event.preventDefault();
        }
    });
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\RemoveProfile.js
//version="9"
if (ComponentRegistry.RemoveProfile) {
    $(function () {
        var FormID = $('#formID').val();

        $(FormID).bootstrapValidator({
                fields: {
                removeProfileCaptchaInput: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: 'Required Captcha'
                        },
                        callback: {
                            message: 'Incorrect Captcha!',
                            callback: function (value, validator, $field) {
                                if (value == '') {
                                    return true
                                }
                                else {
                                    RemoveProfCaptVal = isRemoveProfileCaptchaCorrect();
                                    return RemoveProfCaptVal;
                                }
                            }
                        }
                    }
                }
            }
        });

        $('#btnRemoveProfileSubmit').on("click",function (e) {
            var careersRegistrationforms = $(this).closest("form");
            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
            //$formBootStrap.$submitButton = this;
            $formBootStrap.validate();

            if ($formBootStrap.isValid() && RemoveProfCaptVal) {
                $(this).attr("disabled", "disabled");

                var objReg = {};
                objReg.EmailAddress = removeProfileEmailAddress;
                objReg.FirstName = FirstName;
                objReg.Comments = removeTags($('#removeprofile_comments').val());
                objReg.CountrySite = removeProfileCountrySite;
                $.ajax({
                    url: "/api/sitecore/RemoveProfileModule/RemoveProfile",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({
                        usersDeletedDomain: objReg,
                        countrySite: removeProfileCountrySite,
                        siteLanguage: removeProfileSiteLanguage,
                        userProfileIdGuid: removeProfileUserProfileId
                    }),
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrown);
                        jQuery("body").trigger("analytics-form-error");
                    },
                    success: function (jsonOutput, textStatus, jqXHR) {
                        if (jsonOutput.RequestSuccess == true && jsonOutput.DeletionSuccess == true) {
                            var ConfirmationLink = $('#RemoveProfileConfirmation').val();
                            e.preventDefault();
                            window.location = "/Authentication/SignOut/SignOut?returnUrl=" + encodeURI(window.location.hostname + ConfirmationLink);
                            jQuery("body").trigger("analytics-form-success");
                        }
                        else {
                            console.log("Remove profile request failed");
                        }
                    }
                });
            }
            else {
                jQuery("body").trigger("analytics-form-error");
            }
        });

        $('#btnRemoveProfileCancel').on("click",function () {
            window.location = $('#RemoveProfileCancel').val();
        });
    });

    function isRemoveProfileCaptchaCorrect() {
        var CaptInput = $('input[name="removeProfileCaptchaInput"]').val();
        var returnVal = false;
        $.ajax({
            url: "/api/sitecore/RemoveProfileModule/IsWordCorrect",
            type: "POST",
            data: JSON.stringify({
                input: CaptInput,
                instance: InstanceCaptId
            }),
            contentType: "application/json",
            async: false,
            error: function (res) {
                console.log("isCaptchaCorrect() encountered error");
            },
            success: function (res) {
                if (res == 'True') {
                    returnVal = true;
                }
                else {
                    RegCID.ReloadImage();
                }
            }
        });
        return returnVal;
    }

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\SavedJobsModule.js
//version=*2*

if (ComponentRegistry.SavedJobsModule) {
    var viewJobsLink = $("#storedViewJobsLink").val();
    var nosavedJobsContainer = '#no-saved-jobs';
    $(nosavedJobsContainer).hide();

    $(window).on("load", function () {
        savedJobsModuleHelper.GetSavedJobs();
    });

    $(document).ajaxComplete(function () {
        var $divs = $(".saved-job");
        if (totalSavedJobs != undefined) {
            if ($divs.length == totalSavedJobs) {
                var numericallyOrderedDivs = $divs.sort(function (a, b) {
                    var c = ($(a).attr("id").replace("job-", "").trim());
                    var d = ($(b).attr("id").replace("job-", "").trim());

                    if (parseInt(c) > parseInt(d))
                        return -1;
                    if (parseInt(c) < parseInt(d))
                        return 1;
                    return 0;
                });

                $(".form-section .saved-jobs").first().html(numericallyOrderedDivs);
                $(".form-section .saved-jobs").first().prepend("<h2 class='corporate-black' id='saved-jobs-header'>Saved Job Postings</h2>");
            }
        }
    });

    $.ajax({ async: false });
    $.getJSON('/api/sitecore/savedjobsmodule/getcurrentdate', {}, function (currentdt) {
        currentdate = new Date(parseInt(currentdt.substr(6)));;
    });
    $.ajax({ async: true });

    var currentdate = undefined;
    var totalSavedJobs;

    var savedJobsModuleHelper = {
        DeleteJob: function (SavedJobInformationId, jobId) {
            $.ajax({
                url: '/api/sitecore/savedjobsmodule/deletejob',
                data: { SavedJobInformationId: SavedJobInformationId },
                traditional: true,
                cache: false,
                method: 'post',
                success: function (res) {
                    $('#job-' + SavedJobInformationId).remove();

                    var savedJobsSections = $(".saved-jobs > div.saved-job");
                    savedJobsModuleHelper.CheckSavedRecommendedJobs(jobId);
                    if (savedJobsSections.length <= 0) {
                        $(nosavedJobsContainer).show();
                        $("#horizontalline").addClass("hr-no-jobs");
                    }
                }
            });
        },

        CheckSavedRecommendedJobs: function (jobId) {
            var recommendedJobsSections = $(".saved-jobs > div.recommended-job");
            if (recommendedJobsSections.length > 0) {
                for (var i = 0; i < recommendedJobsSections.length; i++) {
                    var html = recommendedJobsSections[i];
                    var jobNumber = html.getElementsByClassName("cta")[1].dataset['jobId'];
                    if (jobNumber.indexOf(jobId) >= 0) {
                        $("#save-job-" + jobId).text("Save Job");
                        $("#save-job-" + jobId).removeClass("saved");
                        $("#save-job-" + jobId).addClass("save-job");
                        $("#save-job-" + jobId).on(this);
                        console.log("#save-job-" + jobId);
                    }
                }
            }
        },

        GetDetails: function (JobId, SavedJobInformationId) {
            var savedJobsHeader = '#saved-jobs-header';
            var removeJobText = $("#RemoveJob").val();
            var removeJobTextLinkName = (removeJobText !== null && removeJobText !== undefined) ? removeJobText.toLowerCase() : "";

            if (removeJobText == "" || removeJobText == undefined) {
                removeJobText = "Remove Job";
            }

            $.ajax({
                url: '/api/sitecore/savedjobsmodule/getjobdetails',
                data: { jobId: JobId },
                traditional: true,
                cache: false,
                method: 'post',
                error: function () {
                    remove = '<a class="cta" href="#" onClick="savedJobsModuleHelper.DeleteJob(' + SavedJobInformationId + ',' + "'" + JobId + "'" + ')"' + 'data-analytics-content-type="cta" data-analytics-link-name="'+ removeJobTextLinkName + '">' + removeJobText + '</a>';
                    $('<div class="sections" id="job-' + SavedJobInformationId + '">' +
                        '<p>There is an error with job id: ' + SavedJobInformationId + '.</p>' +
                        remove +
                        '</div>').insertAfter($(savedJobsHeader));
                },
                success: function (detail) {
                    detail = JSON.parse(detail);
                    if (detail.jobDetails == "null") {
                        $("#saved-jobs-error-message").removeClass("hidden")
                    }
                    else {
                        $("#saved-jobs-error-message").addClass("hidden");
                        var date = detail.postedDate;
                        if (date != undefined) {
                            var jobdate = new Date(date);
                            var parsedDate = savedJobsModuleHelper.ParseTime(jobdate, currentdate);

                            var jobLink = viewJobsLink + "?id=" + detail.id;

                            var detailTitleLinkName = (detail.title !== null && detail.title !== undefined) ? detail.title.toLowerCase() : "";
                            var title = '<h2 class="module-headline"><a href="' + jobLink + '"' + ' data-analytics-content-type="cta" data-analytics-link-name="' + detailTitleLinkName + '">' + detail.title + '</a></h2>';

                            var location = detail.location;
                            if (location == "" || location.length == 0 || typeof location == "undefined") {
                                location = $("#LocationNegotiable").val();
                            }
                            var loc = '<h3 class="corporate-black">' + location + '</h3>';
                            var description = '<p class="module-body">' + detail.jobDescription.substr(0, 250) + "... " + '</p>';
                            var requisitionId = '<p class="job-number">Job #' + detail.requisitionId + '</p>';
                            var talentSegment = '<p class="job-type">' + detail.talentSegment + '</p>';
                            var postedDate = '<p class="posting-date">' + 'Posted - ' + parsedDate + '</p>';
                            var view = '<a class="cta" href="' + jobLink + '"' + 'data-analytics-content-type="cta" data-analytics-link-name="view job"'+ '>' + 'VIEW JOB' + '</a>';
                            var remove = '<a class="cta" href="#" onClick="savedJobsModuleHelper.DeleteJob(' + SavedJobInformationId + ',' + "'" + JobId + "'" + ')"' + 'data-analytics-content-type="cta" data-analytics-link-name="' + removeJobTextLinkName +'">' + removeJobText + '</a>';

                            $('<div class="saved-job sections" id="job-' + SavedJobInformationId + '">' +
                                title +
                                loc +
                                description +
                                requisitionId +
                                talentSegment +
                                postedDate +
                                view +
                                remove +
                                '</div>').insertAfter($(savedJobsHeader));
                        }
                    }
                }
            });
        },

        ParseTime: function (date, serverDate) {
            var seconds = Math.floor((serverDate - date) / 1000);

            var interval = Math.floor(seconds / 31536000);

            if (interval > 1) { return interval + " years ago"; }

            interval = Math.floor(seconds / 2592000);

            if (interval > 1) { return interval + " months ago"; }

            interval = Math.floor(seconds / 86400);

            if (interval > 1) {
                return interval + " days ago";
            }
            interval = Math.floor(seconds / 3600);
            if (interval > 1) {
                return interval + " hours ago";
            }
            interval = Math.floor(seconds / 60);
            if (interval > 1) {
                return interval + " minutes ago";
            }
            return Math.floor(seconds) + " seconds ago";
        },

        GetSavedJobs: function () {
            $.ajax({
                url: '/api/sitecore/savedjobsmodule/getsavedjobs',
                traditional: true,
                cache: false,
                method: 'post',
                error: function () {
                    $(nosavedJobsContainer).show();
                    $("#horizontalline").addClass("hr-no-jobs");
                },
                success: function (res) {
                    if (res.length > 0) {
                        totalSavedJobs = res.length;
                        $(nosavedJobsContainer).hide();
                        $("#horizontalline").removeClass("hr-no-jobs");
                        $(res).each(function (i) {
                            savedJobsModuleHelper.GetDetails(this.JobId, this.SavedJobInformationId)
                        });
                    }
                }
            });
        },

        GetSavedJob: function (jobId) {
            var data = {
                jobId: jobId
            }
            $.ajax({
                url: '/api/sitecore/savedjobsmodule/GetSavedJob',
                data: data,
                traditional: true,
                cache: false,
                method: 'post',
                error: function () { $(nosavedJobsContainer).show(); },
                success: function (res) {
                    if (res.length > 0) {
                        $(nosavedJobsContainer).hide();
                        $(res).each(function (i) {
                            savedJobsModuleHelper.GetDetails(this.JobId, this.SavedJobInformationId)
                        });
                    }
                }
            });
        }
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BlockAnnouncement.js
//version 2

if (ComponentRegistry.BlockAnnouncement) {
    function closeAnnouncement() {
        $('#announcement-carousel').parent().parent().remove();

        //Cookies Alignment
        $('#ui-wrapper').removeClass('has-announcement-module');

    }


    function ClampAnnouncement() {
        var totalRow = 8;
        var anc = $('.carousel-inner').hasClass('single-announcement');

        if (isTablet()) {
            if (anc == true) {
                totalRow = 3;
            }
            else {
                totalRow = 2;
            }
        } else {
            if (anc == true) {
                totalRow = 8;
            }
            else {
                totalRow = 7;
            }
        }

        var announcementText = $('.announcement-content p');
        var announcementHeader = $('.announcement-header');

        announcementText.css('display', 'block');

        $('.announcement-content p').each(function (index) {
            var $this = $(this);
            var titleHeight = $this.closest('.item').find('.announcement-header').height();

            var hiddenItem = $this.closest('.item').css('display');

            if (hiddenItem == 'none') {
                $this.closest('.item').css({ 'position': 'absolute', 'visibility': 'hidden', 'display': 'block' });
                titleHeight = $this.closest('.item').find('.announcement-header').height();
                $this.closest('.item').css({ 'position': '', 'visibility': '', 'display': '' });
            }

            var lineHeight = $this.closest('.item').find('.announcement-header').css('line-height').replace("px", "");
            var lines = Math.round(titleHeight / parseInt(lineHeight));
            var bodyRowCount = totalRow - lines;

            var headline = announcementHeader[index];
            var ptag = announcementText[index];

            if (lines > 2) {
                $clamp(headline, { clamp: 2 });
            }

            $clamp(ptag, { clamp: bodyRowCount });
        });
    }

    //set the new data attributes for the play pause button
    var setDataPlayPauseButton = function () {
        var announcementButton = $('.announcement-block .acn-icon');
        if(announcementButton && announcementButton.length)
        (announcementButton).on("click", function () {
            if ($(announcementButton).hasClass('icon-play')){
                announcementButton.attr('data-analytics-link-name', 'icon-pause');
            }
            else {
                announcementButton.attr('data-analytics-link-name', 'icon-play');
            }

        });
    }

    $(function () {

        ClampAnnouncement();
        setDataPlayPauseButton();

        var ctr = 1;
        $("#content-wrapper > div.ui-container > div.block-title").each(function () {
            if (ctr == 1) {
                $(this).removeClass("first");
            }
            else if (ctr == 2) {
                $(this).addClass("first");
            }
            ctr++;
        });

        $('#announcement-carousel').on('slid', function (e) {
            ClampAnnouncement();
        });

        $(window).on('resize', function () {
            var announcementHeader = $('.announcement-header');
            var announcementContent = $('.announcement-content p');

            announcementHeader.removeAttr('style').removeClass('clamp');
            announcementContent.removeAttr('style').removeClass('clamp');

            ClampAnnouncement();
        });

    });
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CommentsModule.js
/* version="17" */
if (ComponentRegistry.CommentsModule) {
    var readMoreText = $('.comment-display-section').data("read-more-text");

    $(function () {
        jQuery.support.cors = true;

        // OMNI FORM ANALYSIS - FORM START
        if (typeof acncm !== 'undefined') {
            acncm.Forms.detectedFormStart();
        }

        $('.without-account-button').on("click", function () {
            $('#without-account-form').css('display', 'block');
            $('#comment-social').css('display', 'block');
            $('#with-account').css('display', 'none');
            $('#sign-in-social').css('display', 'none');

        });


        $('.sign-in-label').on("click", function () {
            $('#with-account').css('display', 'block');
            $('#sign-in-social').css('display', 'block');
            $('#without-account-form').css('display', 'none');
            $('#comment-social').css('display', 'none');
        });

        $("form#submitCommentsForm, form#submitUnauthenticated").on("submit", function (event) {
            var commentContentVal = $("#commentContent").val();
            var userNameVal = $("#userNameInput").val();
            var emailAddVal = $("#emailAddInput").val();
            var userId = $("#userNameInput").attr('id');
            var emailAddId = $("#emailAddInput").attr('id');
            var commentContentId = $("#commentContent").attr('id');
            var captchaId = $('.captchaVal').attr('id');

            var jsonObj = {
                commentContent: commentContentVal,
                contextPage: "ctpage",
                contextItemId: vItemContextID,
                commentsModuleItemPath: vmodelPath,
                captchaId: commentsModuleCaptchaId,
                captchaInput: $("#commentsModuleCaptcha input[name=captchaInput]").val(),
                captchaInstance: commentsModuleCaptchaInstance,
                userName: userNameVal,
                emailAddress: emailAddVal,
                userNameId: userId,
                emailId: emailAddId,
                commentId: commentContentId,
                language: acnPage.Language

            };

            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                async: true,
                url: "/api/sitecore/ProcessCommentsModule/PostComment",
                data: JSON.stringify(jsonObj),
                success: function (data) {
                    if (typeof data != undefined && data != null) {
                        if (data.Success) {
                            //fix for 410097--start
                            //alert(confirmationMessage);
                            //location.reload(true);
                            $('#comment-modal').modal('show');
                            $(".form-section").remove();
                            //--end
                        }
                        else {
                            if (data.Result != null || data.Result != undefined) {
                                $(".comments .form-section").remove();
                                var text = "<div class='form-section'><ul class = 'Val has-error'>"
                                for (var i = 0; i < Object.keys(data.Result).length; i++) {
                                    text = text + "<li class='ErrorList glyphicon' data-bv-field=" + Object.keys(data.Result)[i] + ">" + data.Result[Object.keys(data.Result)[i]] + "</li>";
                                }
                                text = text + "</ul></div>";
                                $("#commentContent").after(text);
                            }
                            if (data.Errors != null || data.Errors != undefined) {
                                $(".form-section").remove();
                                var text = "<div class='form-section'><ul class = 'Val has-error'>"
                                for (var i = 0; i < Object.keys(data.Errors).length; i++) {
                                    text = text + "<li class='ErrorList glyphicon' data-bv-field=" + Object.keys(data.Errors)[i] + ">" + data.Errors[Object.keys(data.Errors)[i]] + "</li>";
                                }
                                text = text + "</ul></div>";
                                $("#emailAddInput").after(text);
                            }
                            if (data.CaptchaError != null || data.CaptchaError != undefined)
                            {
                                $(".form-section").remove();
                                if (data.CaptchaStatus == false) {
                                    var text = "<div class='col-xs-6 form-section'><ul class = 'Val has-error'><li class='validatorMessage glyphicon' data-bv-field=" + captchaId + ">" + data.CaptchaError + "</li></ul></div>";
                                    $("#without-account-form .postcomment-box").before(text);
                                }
                            }
                            RefreshCaptcha(jsonObj.captchaId);
                        }
                    }

                    // OMNI FORM ANALYSIS - FORM COMPLETE
                    if (typeof acncm !== 'undefined') {
                        acncm.Forms.detectedFormComplete();
                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // OMNI FORM ANALYSIS - FORM ERROR
                    if (typeof acncm !== 'undefined') {
                        acncm.Forms.detectedFormError();
                    }
                }
            });

            event.preventDefault();
        });

        Comments = {
            ContextItem: vmodelPath,
            DefaultNumberOfComments: vDefaultNumOfCommentsToDisp + 0,
            TotalNumberOfComments: vTotalNumOfComments + 0,
            LimitNumberOfComments: vLimitNumOfComments + 0,
            MaxDays: vMaxDays + 0,
            NextCommentIndex: vNextCommentIndex,

            RenderHtmlAjax:
                     function (elm, ctx) {
                         $.ajax({
                             url: elm.data('url'),
                             type: 'POST',
                             data: {
                                 path: Comments.ContextItem,
                                 pageCount: (this.NextCommentIndex + Comments.DefaultNumberOfComments),
                                 defaultNumberOfComments: Comments.TotalNumberOfComments,
                                 limitNumberOfComments: Comments.LimitNumberOfComments,
                                 maxDays: Comments.MaxDays
                             },
                             cache: false,
                             context: ctx,
                             success: function (result) {
                                 this.append(result);

                                 var commentDesc = $('.comment-description');
                                 var commentDescHeight = parseInt(commentDesc.css('line-height'), 10);

                                 commentDesc.each(function (index) {
                                     if (index > 2) {
                                         if ($(window).width() < 767) {

                                             $(this).dotdotdot({
                                                 watch: 'window',
                                                 height: commentDescHeight * 5,
                                                 wrap: 'letter'
                                             });

                                         } else {

                                             $(this).dotdotdot({
                                                 watch: 'window',
                                                 height: commentDescHeight * 2,
                                                 wrap: 'letter'
                                             });
                                         }
                                         var isTruncated = $(this).triggerHandler("isTruncated");
                                         if (isTruncated) {
                                             $(this).after('<div class="read-more"><a class="content-txt-cta themeColor cta" href="javascript:void(0)" data-analytics-link-name="' + readMoreText.toLowerCase() + '" data-analytics-content-type="cta">' + readMoreText + '</a></div>');
                                         }
                                     }
                                 });

                                 $('.read-more').on("click", function () {
                                     if (!$(this).prev().hasClass("firstLoad")) {
                                         var content = $(this).prev().triggerHandler("originalContent");
                                         $(this).prev().trigger("destroy");
                                         $(this).prev().text("");
                                         $(this).prev().append(content);
                                         $(this).attr('style', 'display: none !important');
                                     }
                                 });

                                 Comments.NextCommentIndex += Comments.TotalNumberOfComments;
                                 if (Comments.DefaultNumberOfComments >= (Comments.TotalNumberOfComments - Comments.NextCommentIndex)
                                     || Comments.TotalNumberOfComments >= (Comments.LimitNumberOfComments - Comments.NextCommentIndex)) {
                                     $('#displayMoreComments').attr('style', 'display: none !important');
                                     $('#displayLoadMore').attr('style', 'display: none !important');
                                 }
                             }
                         });
                     },

            OnAjaxClick: function (e) {
                var myLink = $('#displayMoreComments');
                var myCtx = $('#commentSection');
                this.RenderHtmlAjax(myLink, myCtx);

                $('.comment-div').eq(2).css('margin-bottom', '10px');
            }
        };


        if ($("#submitCommentsForm").length > 0) {
            // reset form on page load
            $('#submitCommentsForm')[0].reset();
        }
        reloadPageOnModalHide();
    });


    $(window).on("load", function () {

        var commentCont = $(".comment-dots");
        var commentContHeight = parseInt(commentCont.css('line-height'), 10);
        // executes when complete page is fully loaded, including all frames, objects and images
        $('.comment-description').each(function (index) {
            if ($(window).width() < 767) {

                $(this).dotdotdot({
                    watch: 'window',
                    height: commentContHeight * 5,
                    wrap: 'letter'
                });

            } else {

                $(this).dotdotdot({
                    watch: 'window',
                    height: commentContHeight * 2,
                    wrap: 'letter'
                });

            }

        });

        $('.comment-description').each(function () {
            var isTruncated = $(this).triggerHandler("isTruncated");
            $(this).addClass("firstLoad");
            if (isTruncated) {
                $(this).after('<div class="read-more"><a class="content-txt-cta themeColor cta" href="javascript:void(0)" data-analytics-link-name="' + readMoreText.toLowerCase() + '" data-analytics-content-type="cta">' + readMoreText + '</a></div>');
            }
        });

        $('.read-more').on("click", function () {
            var content = $(this).prev().triggerHandler("originalContent");
            $(this).prev().trigger("destroy");
            $(this).prev().text("");
            $(this).prev().append(content);
            $(this).attr('style', 'display: none !important');
        });

    });

    $commentSection = $(".comment-display-section");


    $commentSection.on("click", ".comment-delete-yes", function (event) {
        $this = $(this);
        var commentItemId = $this.data('comment-id');

        var jsonObj = {
            contextPage: "ctpage",
            contextItemId: commentItemId,
            commentsModuleItemPath: vmodelPath,
            language: acnPage.Language
        };

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            async: false,
            url: "/api/sitecore/ProcessCommentsModule/DeleteComment",
            data: JSON.stringify(jsonObj),
            success: function (data) {
                if (typeof data != undefined && data != null) {
                    if (data.Success) {
                        //location.reload();
                        history.go(0);
                    }
                    else {
                        alert(data.Result);
                    }
                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                // OMNI FORM ANALYSIS - FORM ERROR
                if (typeof acncm !== 'undefined') {
                    acncm.Forms.detectedFormError();
                }
            }
        });
        $parentDiv.remove();

        event.preventDefault();
    });



    $commentSection.on("click", ".comment-delete", function (event) {
        $this = $(this);
        $parentDiv = $this.closest('.comment-div');
        $commentDesc = $parentDiv.find('.comment-description');
        $commentDesc.css('opacity', '0.1');
        $parentDiv.find('.comment-id').css('opacity', '0.1');
        $parentDiv.find('.dropdown.pull-right').css('opacity', '0.1');
        $parentDiv.find('.read-more').css('display', 'none');
        $deleteQuestion = $parentDiv.find('.comment-delete-question');
        $deleteQuestion.css('display', 'block');

        if ($(window).width() <= 767) {
            if ($commentDesc.height() > 60) {
                $deletePosition = "-" + (($commentDesc.height() / 2) + ($deleteQuestion.height() / 2)) + "px";
                $deleteQuestion.css('top', $deletePosition);
            }
        }
        else {
            $deletePosition = "-" + (($commentDesc.height() / 2) + ($deleteQuestion.height() / 2)) + "px";
            $deleteQuestion.css('top', $deletePosition);
            $parentDivHeight = $parentDiv.height() - $deleteQuestion.height() + "px";
            $parentDiv.css('height', $parentDivHeight);
        }
        event.preventDefault();
    });


    $commentSection.on("click", ".comment-delete-no", function (event) {
        $this = $(this);
        $parentDiv = $this.closest('.comment-div')
        $commentDesc = $parentDiv.find('.comment-description');
        $parentDiv.find('.comment-delete-question').css('display', 'none');
        $commentDesc.css('display', 'block');
        $readMore = $parentDiv.find('.read-more');
        if ($commentDesc.height() < 50 && $(window).width() > 767) {
            $readMore.css('display', 'block');
        }
        else if ($commentDesc.height() < 90 && $(window).width() < 767) {
            $readMore.css('display', 'block');
        }
        else {
            $readMore.css('display', 'none');
        }
        $commentDesc.css('opacity', '1');
        $parentDiv.find('.comment-id').css('opacity', '1');
        $parentDiv.find('.dropdown.pull-right').css('opacity', '1');
        $parentDiv.css('height', '');
        event.preventDefault();
    });



    $commentSection.on("click", ".comment-edit", function (event) {
        $this = $(this);
        $parentDiv = $this.closest('.comment-div')
        $parentDiv.find('.comment-description').css('display', 'none');
        $parentDiv.find('.read-more').css('visibility', 'hidden');
        $parentDiv.find('.comment-update').css('display', 'block');
        $textarea = $parentDiv.find('textarea');
        $textareaHeight = $textarea[0].scrollHeight;
        if ($textareaHeight <= 100) {
            $textarea.css('height', $textareaHeight);
        }
        else {
            $textarea.css('height', '100px');
        }
        event.preventDefault();
    });

    $("#editcommentOk,#btnEditModalClose").on("click", function (event) {
        $('#edit-comment-modal').modal('hide');
    });

    $commentSection.on("click", ".cancel-comment-update", function (event) {
        $this = $(this);
        $parentDiv = $this.closest('.comment-div')

        $parentDiv.find('textarea').val($.trim($parentDiv.find('.comment-description').text()));
        $parentDiv.find('.comment-update').css('display', 'none');
        $parentDiv.find('.comment-description').css('display', 'block');
        $parentDiv.find('.read-more').css('visibility', 'visible');
        $parentDiv.find(".form-section").remove();
        event.preventDefault();
    });

    $commentSection.on("click", ".comment-save", function (event) {

        $this = $(this);
        $parentDiv = $this.closest('.comment-div');

        var commentContentVal = $parentDiv.find('textarea').val();
        var commentItemId = $this.data('comment-id');
        var commentUpdateId = $parentDiv.find('textarea').attr('id');

        var jsonObj = {
            commentContent: commentContentVal,
            contextPage: "ctpage",
            contextItemId: commentItemId,
            commentsModuleItemPath: vmodelPath,
            commentId: commentUpdateId,
            language: acnPage.Language

        };

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            async: true,
            url: "/api/sitecore/ProcessCommentsModule/UpdateComment",
            data: JSON.stringify(jsonObj),
            success: function (data) {
                if (typeof data != undefined && data != null) {
                    if (data.Success) {
                        $(".form-section").remove();
                        $('#edit-comment-modal').modal('show');
                        $parentDiv.find('textarea').val($.trim($parentDiv.find('.comment-description').text()));
                        $parentDiv.find('.comment-update').css('display', 'none');
                        $parentDiv.find('.comment-description').css('display', 'block');
                        $parentDiv.find('.read-more').css('visibility', 'visible');
                    }
                    else {
                        $parentDiv.find(".form-section").remove();
                        if (data.Result != null) {
                            var text = "<div class='form-section'><ul class = 'Val has-error'>"
                            for (var i = 0; i < Object.keys(data.Result).length; i++) {
                                text = text + "<li class='ErrorList glyphicon' data-bv-field=" + Object.keys(data.Result)[i] + ">" + data.Result[Object.keys(data.Result)[i]] + "</li>";
                            }
                            text = text + "</ul></div>";
                            $parentDiv.find(".comment-update textarea").after(text);
                        }
                    }
                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                // OMNI FORM ANALYSIS - FORM ERROR
                if (typeof acncm !== 'undefined') {
                    acncm.Forms.detectedFormError();
                }
            }
        });

        event.preventDefault();
    });


    $(document).on('input', '.comments-module textarea', function () {
        if (this.scrollHeight <= 100) {
            this.style.height = '42px';
            this.style.height = (this.scrollHeight) + 'px';
        }
    });

    function RefreshCaptcha(captchaId) {
        $('#' + captchaId + '_ReloadLink').trigger("click");
    }
    var reloadPageOnModalHide = function () {
        $('#comment-modal').on('hidden.bs.modal', function () {
            history.go(0);
        });
    }
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BlogPostViewSubscribe.js
if (ComponentRegistry.BlogPostViewSubscribe) {
    //[AJS 12/15 trasfer inline scripts from BlogPostViewSubscribe.cshtml] - start
    function LoadButtonLink(btn) {
        var btnUrl = btn.getAttribute("href");
        window.open(btnUrl, '_self', false);
    }
    //-end
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\SiteAnalytics.js
// version="5" 

$(function () {

    if (typeof digitalData != 'undefined') {
        digitalData.page.pageInfo.destinationUrl = document.location;
        digitalData.page.pageInfo.referringUrl = document.referrer;

    }
});

/////////////////////
//  PRODUCTS      // 
///////////////////

this.AddProductAssetsToDigitalData = function (_productCategory, _productId) {

    if (digitalData.product === null) {
        digitalData.product = [];
    }

    var productItem = '{'
        + '"category":{"primaryCategory":"' + _productCategory + '"}'
        + '"productInfo":{"productID":"' + _productId + '"}'
        + '}';

    var productItemObj = JSON.parse(productItem);

    digitalData.product.push(productItemObj);
}; 

/////////////////////
//  USER          // 
///////////////////

this.SetDefaultProfileIfAnonymousUser = function () {

    if (digitalData.user[0].profile[0].profileInfo.profileID === "anonymous") {

        digitalData.user[0].profile[0].profileInfo.profileID = "VisitoryID will be placed here...";
        digitalData.user[0].profile[0].profileInfo.jobLevel = "";
    }

}; 

/////////////////////
//   EVENTS       // 
///////////////////

this.SiteAnalyticsEventTracking = function () {

    if (typeof digitalData === 'undefined') {
        return;
    }

    $("a").on("click", function () {

        AddTriggeredEventToDigitalData("click", "MouseEvent");
    });

}; 

this.AddTriggeredEventToDigitalData = function (_eventInfoType, _eventInfoName) {

    if (digitalData.events === null) {
        digitalData.events = [];
    }

    var eventInfo = '{"type":"' + _eventInfoType + '",' +
        '"eventName":"' + _eventInfoName + '"' +
        '}';

    var eventInfoObj = JSON.parse('{"eventInfo":' + eventInfo + '}');

    digitalData.events.push(eventInfoObj);

}; 



/////////////////////
//   UTILITIES    // 
///////////////////

this.UpdateComponentsAnalyticsID = function () {

    $.ajax({

        url: "/api/sitecore/SiteAnalytics/UpdateComponentsAnalyticsId",
        type: "POST",
        datatype: "json",
        contentType: "application/json",
        success: function (data) {
            var Components = data;

            return Components;
        }

    });
}; 

this.UpdateMetadataAnalyticsID = function () {

    $.ajax({

        url: "/api/sitecore/SiteAnalytics/UpdateMetadataAnalyticsId",
        type: "POST",
        datatype: "json",
        contentType: "application/json",
        success: function (data) {
            var Components = data;

            return Components;
        }

    });
}; 
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\podcasts.js
/*
if (ComponentRegistry.Podcast) {
    var $podcastElement = $('.podcast-audio');
    if ($podcastElement.length) {
        var vid, podcastPlayerId;
        $('.podcast-audio').parent().find('.media-container').addClass("podcast-audio-media-container");
        $(".podcast-audio .podcast-play-pause").click(function () {
            //Get the parent container...
            var $this = $(this);
            var $podcastAudio = $this.closest("div.podcast-audio");
            podcastPlayerId = $this.parent().data('podcast-video-player-id');

            //prepend h_
            if ($('#' + podcastPlayerId).length <= 0) {
                podcastPlayerId = "h_" + podcastPlayerId;
            }

            $('#' + podcastPlayerId).find('param[name="state"]').val("isPlaying");
            vid = document.getElementById(podcastPlayerId);
            var state = vid.doGetCurrentPlayState();
            if ($podcastAudio.hasClass("playing")) {
                $podcastAudio.removeClass("playing");
                vid.doPause();
            }
            else {
                $podcastAudio.addClass("playing");
                vid.doPlay();
            }

            try {
                var mobileVideoAutoPlay = document.getElementById(podcastPlayerId).getElementsByTagName('video')[0];
                if ($podcastAudio.hasClass("playing")) {
                    $podcastAudio.removeClass("playing");
                    mobileVideoAutoPlay.pause();
                } else {
                    $podcastAudio.addClass("playing");
                    mobileVideoAutoPlay.play();
                }
            } catch (e) {
            }

            //Bug 437929 Collection of R1.1 requirements that's in scope for R1.2 & Tracking of scope changes: Podcast module - Podcast icon is not consistent with the spec design
            var $podcastSlider = $this.next().find('.podcast-slider');
            $podcastSlider.find("a.ui-slider-handle").bind('touchend mouseup', function () {
                vid.doSeekToSecond(convertToSeconds($podcastSlider.slider("value")));
            });
            $podcastSlider.bind('touchend mouseup', function () {
                vid.doSeekToSecond(convertToSeconds($podcastSlider.slider("value")));
            });
        });

        function sliderTimer(currentDuration) {
            var totalSec = currentDuration / 1000,
                hours = parseInt(totalSec / 3600) % 24,
                minutes = parseInt(totalSec / 60) % 60,
                seconds = totalSec % 60;
            seconds = Math.round(seconds);
            //With Hours
            //result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
            var result = (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
            return result;
        }
        function convertToSeconds(currentDuration) {
            var seconds = currentDuration / 1000;
            return Math.round(seconds) + 1;
        }
    }
}
*/
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\RecommendedJobModule.js
//version=*2*

if (ComponentRegistry.RecommendedJobModule) {
    var userID = $("#storedUserId").val();
    $(function () {
        $(".save-job").on("click", function () {
            var jobNumber = $(this).data('job-id');

            $.get("/api/sitecore/savedjobsmodule/savejob",
            {
                UserId: userID,
                JobId: jobNumber,
                CreateUserId: userID
            },
            function () {
                unbindSaveLink(jobNumber);
                savedJobsModuleHelper.GetSavedJob(jobNumber);
            });
        });

        $("#edit-profile-tab").on("click", function () {
            javascript: $("#NavEditProfile").trigger("click");
        });
    });

    function unbindSaveLink(jobNumber) {
        $("#save-job-" + jobNumber).text("Saved");
        $("#save-job-" + jobNumber).removeClass("save-job");
        $("#save-job-" + jobNumber).addClass("saved");
        $("#save-job-" + jobNumber).off();
    }
}


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\ClientIndex.js
/* version="2" */
if (ComponentRegistry.ClientIndex) {

$(function () {
        
        window.setTimeout(function () {
            $(window).on("resize", function () {
                if (window.innerWidth<="768") {
                    $('#overflow-docking').find('.inner').addClass('parallax');
                    $('#overflow-controller').find('.inner').addClass('parallax');
                }
                else {
                    $('#overflow-docking').find('.inner').removeClass('parallax');
                    $('#overflow-controller').find('.inner').removeClass('parallax');
                }
            });
        }, 200);

        //check if  id="recommended-for-you-module"  
        if ($('#recommended-for-you-module').length > 0) {
            //recommended-for-you-module
            //get data value
            var artCount = $('#recommended-for-you-module').attr('data-total-count');
            if ((artCount === "") || (artCount === "0")) {
                //remove nearest colored container
                $('#recommended-for-you-module').closest('.colored-container').remove();
            }
        }
        else if ($('#related-content-module').length > 0) {
            //related-content-module
            //get data value
            var artCount = $('#related-content-module').attr('data-total-count');
            if ((artCount === "") || (artCount === "0")) {
                //remove nearest colored container
                $('#related-content-module').closest('.colored-container').remove();
            }
        }

        $("#overflow-docking").remove();
        $("#overflow-controller").empty();

        window.setTimeout(function () {
            CreateLayout();
            AdjustLayout();

            $('.ui-container').each(function () {
                var bckgroundImage = $(this).find('.hidden').attr('data-background-image');
                var containerId = ($(this).attr('id'));
                $("div[data-content-id=" + containerId + "]").find('.inner').css({ "background-image": "url('" + bckgroundImage + "')", "background-size": "cover" });
            });

            if (isMobile()) {
                $('#overflow-docking').find('.inner').addClass('parallax');
                $('#overflow-controller').find('.inner').addClass('parallax');
            }
            else {
                $('#overflow-docking').find('.inner').removeClass('parallax');
                $('#overflow-controller').find('.inner').removeClass('parallax');
            }

        }, 0);

        /*Jumplink Functionality*/
        $("#block-jumplink").hide();
        var totalnav = $('#jumplink-dropdown li').length - 1;
        $("#total-navigation").html(totalnav);

        var blockTitles = [];
        $(".ui-container .block-title h2").each(function () {
            var blockTitle = $(this).text();
            blockTitles.push(blockTitle);
        });

        $('#jumplink-dropdown li a').each(function (ctr) {

            if (ctr > 0) {
                var blockId = $(this).attr('href');
                var title = $(blockId + ' .block-title h2').text();
                $(this).children('span').text(title);
            }

        });
        /*End*/

        $('.article-title a h2').each(function () {
            $clamp(this, { clamp: 2 });
        });


    });

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\SocialSignin.js
// version="5"
if (ComponentRegistry.SocialSignIn) {
    $(function () {
        $('#btnContinueProfile').on("click", function () {
            if (window.location.hash == '') {
                if (ComponentRegistry.EditProfile)
                    window.location.href += '#EditProfile';
                else if (ComponentRegistry.ClientEditProfile)
                    window.location.href += '#editprofilepane';
                window.location.reload();
            }
            else
                $('#SocialMediaModal').modal('hide');
        });

        $('#SocialMediaModal button.close').on("click", function () {
            if (window.location.hash == '') {
                if (ComponentRegistry.EditProfile)
                    window.location.href += '#EditProfile';
                else if (ComponentRegistry.ClientEditProfile)
                    window.location.href += '#editprofilepane';
                window.location.reload();
            }
            else
                $('#SocialMediaModal').modal('hide');
        });

        $('#btnContinueRegistration').on("click", function () {
            var RegistrationLink = $('#loginPopoverContainer').find('#DefaultRegistrationLink').val();
            if (RegistrationLink != undefined || RegistrationLink != "")
                window.location.assign(RegistrationLink);
        });

        $('#ClientEditButton').on("click", function () {
            var PasswordParam = $('#modal_password').val();
            var URL = $('#URL').val();
            URL = URL + "?Create_Password=" + PasswordParam;
            var careersRegistrationforms = $(this).closest("form");
            var $formBootStrap = $(careersRegistrationforms).data('bootstrapValidator');
            $formBootStrap.validate();
            if ($formBootStrap.isValid()) {
                window.location.assign(URL);
            }
        });

        $('#SocialEmailModal button.close').on("click", function () {
            $('#SocialEmailModal').modal('hide');
        });

        function IEOldBrowser() {
            if (navigator.userAgent.indexOf("MSIE") != -1) {
                var version = parseInt(navigator.appVersion.match(/MSIE ([\d.]+)/)[1])
                if (version < 10)
                    return true;
                else
                    return false;
            }
        }

        $('#showClientEditModal').on("click", function (event) {
            var objData = {};
            var Item = $('#PageItemGuid').val();
            $.ajax({
                url: "/api/sitecore/SocialSignInModule/SignOutProfile",
                async: false,
                type: "POST",
                data: JSON.stringify({ ItemGuid: Item }),
                dataType: "json",
                contentType: "application/json",
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);
                },
                success: function (jsonOutput, textStatus, jqXHR) {
                    if (jsonOutput[0].ShowCreatePassword == true) {
                        $("#disconnectSocialSite").modal("hide");
                        $("#client-edit-modal").modal("show");
                    }
                    else {
                        if (IsIE())
                            window.location.reload(true);
                        else
                            window.location.assign(jsonOutput[0].RedirectPath);
                        $("#client-edit-modal").modal("hide");
                    }
                }
            });
            event.preventDefault;
        });

        var suggestedLink = $(".social-general-suggested .suggested-link");
        var suggestedLinkUrl = $(".social-general-suggested").data("socialurl");

        suggestedLink.attr("href", suggestedLinkUrl);
        if (suggestedLink.length > 0) {
            if (suggestedLink.attr("href")) {
                if (suggestedLinkUrl.indexOf("LinkedIn") > -1) {
                    suggestedLink.attr({
                        "data-linkaction": "Connect LinkedIn",
                        "data-linktype": "LinkedIn"
                    });
                }
                else if (suggestedLinkUrl.indexOf("Xing") > -1) {
                    suggestedLink.attr({
                        "data-linkaction": "Connect Xing",
                        "data-linktype": "Xing"
                    });
                }
            }
        }

        $(".social-general-suggested .social-suggested-text").attr("title", suggestedLink.text());

        $(".empty-tag").each(function () {
            if ($.trim($(this).text()).length == 0) {
                $(this).append("<p style= visibility: hidden>" + "WA Content" + "</p>");
            }
        });
    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CareersJobFeedsXmlModule.js
//Version 2

if (ComponentRegistry.CareersJobFeedsXmlModule) {
    var $this;
    $(function () {
        //list view
        var viewMore = $('a.view-more-link');
        var listJob = $('ul.jobfeed-list');

        viewMore.each(CareersJobFeedsXmlModule.AddIndexAndIdsForListView);
        listJob.each(CareersJobFeedsXmlModule.ToggleViewMoreLinkVisibility);
        //view more jobs
        viewMore.on("click", CareersJobFeedsXmlModule.ViewMoreClick);
        //remove horizontal line
        CareersJobFeedsXmlModule.RemoveHorizontalLine();

        var bar = $(".jobfeed-stat-bar span.align-right a");
        bar.addClass("color-primary");

        CareersJobFeedsXmlModule.CarouselSlide();

        var carouselItem = $("div.carousel-inner div.item:first-child");
        var carouselIndicator = $(".jobfeeds .carousel-indicators li:first-child");
        carouselItem.addClass("active");
        carouselIndicator.addClass("active");

        //ellipsis for headline and body
        $('.carousel ol.carousel-indicators li').on("click", CareersJobFeedsXmlModule.JobFeedModuleEllipsis);

        setTimeout(function () { CareersJobFeedsXmlModule.JobFeedModuleEllipsis(); }, 100);
        CareersJobFeedsXmlModule.JobFeedModuleEllipsis();

        //add current domain to job-url
        var jobURL = $('a.job-url');
        jobURL.each(CareersJobFeedsXmlModule.AddDomainToJobUrl);


        var shareButtonContainer = $('.social-likes__button');
        var socialIconsContainer = $('.social-likes.social-likes_single.socialSharePopover');
        var carouselInner = $('.carousel-inner');
        var body = $(document);

        function setShareContainerVisible($element) {
            $this = $($element);
            $this.closest(carouselInner).css('overflow', 'visible');

            var carouselId = $this.closest(carouselInner).parent().attr("id");
            var carouselContainer = "#" + carouselId;

            $(carouselContainer).addClass('do-not-rotate');
            $(carouselContainer).carousel('pause');
            $('.social-likes_opened').show();
            $('.social-likes.social-likes_single.socialSharePopover').removeClass('hidden');
        }


        shareButtonContainer.on("click tap touchstart", function () {

            setShareContainerVisible(this);

        });
        socialIconsContainer.on("click touchstart tap", function () {

            setShareContainerVisible(this);
        });
        body.on("click tap swipe", function () {

            $('.jobfeeds .carousel-inner').css('overflow', 'hidden');
            $('.social-likes.social-likes_single.socialSharePopover').addClass('hidden');
            $('.jobfeeds .carousel').removeClass('do-not-rotate');
            $('.jobfeeds .carousel').carousel('cycle');
        });

    });

    var CareersJobFeedsXmlModule = (function () {
        //private variables and methods
        CurrentDomain = function () {
            return window.location.protocol + "//" + window.location.hostname;
        };

        //public methods
        var CareersJobFeeds = {
            AddIndexAndIdsForListView: function (index) {
                $this = $(this);
                $this.attr('id', 'view-more-id-' + index);
                $this.attr('indx', index);
                $this.parent().siblings(".jobfeed-list-container").children("ul").attr('indx', index);
                $this.parent().siblings(".jobfeed-list-container").children("ul").addClass('jobfeed-ul-' + index);
            },
            RemoveHorizontalLine: function () {
                var horizontalLine = $('ul.jobfeed-list');
                horizontalLine.each(function (index) {
                    $this = $(this);
                    $this.attr('id', 'jobfeed-list-id-' + index);
                    var num = $('ul#jobfeed-list-id-' + index + ' li:not(".hidden")').length;

                    var totalLi = $('ul#jobfeed-list-id-' + index + ' > li').length;
                    $('ul#jobfeed-list-id-' + index + ' > li)').not(':nth-child(' + totalLi - 1 + ')').find('div hr').show();
                    $('ul#jobfeed-list-id-' + index + ' > li:nth-child(' + num + ') div hr').hide();
                });
            },
            ViewMoreClick: function () {
                $this = $(this);
                var indx = $this.attr("indx");
                var viewMoreSelector = jQuery('a#view-more-id-' + indx);
                var cntr = 1;
                var selhidden = $(".jobfeed-ul-" + indx + " li.hidden");
                if (selhidden.length == 0) {
                    viewMoreSelector.addClass("hidden");
                } else {
                    var first = selhidden.first();
                    var thisItem = first;
                    first.removeClass("hidden");
                    first.nextAll().slice(0, 4).removeClass("hidden");
                    CareersJobFeeds.RemoveHorizontalLine();
                    var moduleHeadlineList = $("li[class='jobfeed-li'] .module-headline");
                    var modulebodylist = $("ul.jobfeed-list li .module-body.dot-ellipsis");

                    EllipsisConfigFunction(moduleHeadlineList);
                    EllipsisConfigFunction(modulebodylist);
                    if ($(".jobfeed-ul-" + indx + " li.hidden").length == 0) {
                        viewMoreSelector.addClass("hidden");
                    }
                }
            },
            ToggleViewMoreLinkVisibility: function () {
                var defaultJobcnt = 5;
                var jobcnt = 1;
                $this = $(this);
                var indx = $this.attr("indx");
                var sel = $(".jobfeed-ul-" + indx + " li");
                var viewMoreSelector = $('a#view-more-id-' + indx);

                sel.each(function () {
                    $(this).attr('id', 'jobfeed-li-' + jobcnt);
                    if (jobcnt <= defaultJobcnt) {
                        viewMoreSelector.addClass("hidden");
                    } else {
                        viewMoreSelector.removeClass("hidden");
                    }
                    if (jobcnt > defaultJobcnt) {
                        $(this).addClass("hidden");
                    }

                    jobcnt++;
                });
            },
            CarouselSlide: function () {
                $this = $('.jobfeeds .carousel');
                $this.on('slid', function () {
                    var $jobfeed = $(this).closest('.jobfeeds .carousel');
                    var moduleBody = $jobfeed.find(".module-body.dot-ellipsis");
                    var moduleHeadline = $jobfeed.find(".module-headline.dot-ellipsis");
                    var modulebodylist = $jobfeed.find("ul.jobfeed-list li .module-body.dot-ellipsis");

                    EllipsisConfigFunction(moduleBody);
                    EllipsisConfigFunction(moduleHeadline);
                    EllipsisConfigFunction(modulebodylist);

                    var carouselId = $this.closest($('.jobfeeds .carousel-inner')).parent().attr("id");
                    var carouConcat = "#" + carouselId;

                    if (!$(carouConcat).hasClass('do-not-rotate')) {

                        $('.jobfeeds .carousel-inner').css('overflow', 'hidden');

                    }

                });
            },

            JobFeedModuleEllipsis: function () {
                $this = $(this).closest('.jobfeeds');
                var moduleBody = $this.find(".module-body.dot-ellipsis");
                var moduleHeadline = $this.find(".module-headline");
                var moduleHeadlineList = $("li[class='jobfeed-li'] .module-headline");
                var modulebodylist = $("ul.jobfeed-list li .module-body.dot-ellipsis");

                EllipsisConfigFunction(moduleBody);
                EllipsisConfigFunction(moduleHeadline);
                EllipsisConfigFunction(moduleHeadlineList);
                EllipsisConfigFunction(modulebodylist);
            },
            AddDomainToJobUrl: function () {
                $this = $(this);
                var jobUrl = $this.attr('href');
                var domain = CurrentDomain();
                if (jobUrl && jobUrl.indexOf(domain) === -1) {
                    $this.attr('href', domain + jobUrl);
                }
            }
        };

        return CareersJobFeeds;
    })();
}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\featured-leadership.js
/*version = "3"*/

if (ComponentRegistry.FeaturedLeadershipModule) {

    $(".icon-jump-links-arrow-up").on("click", function () {
        leadersNavigate("+=100");
    });

    $(".icon-jump-links-arrow-down").on("click", function () {
        leadersNavigate("-=100");
    });

    if ($(".js-animate-leaders li").length > 6) {
        $(".icon-jump-links-arrow-down").removeClass("hidden");
    }

    var list = $(".leadership-tab li");

    list.on("click", function () {
        $this = $(this);
        list.removeClass("bg-color-" + $this.parents(".leadership-tab").data("highlight"));
        $this.addClass("bg-color-" + $this.parents(".leadership-tab").data("highlight"));
    });

    $("#leadership_accordion div.accordion_icon").on("click", function () {
        var $panelHeading = jQuery(this).parent();
		var $accordionIcon = jQuery(this);
        var isCollapsed = $panelHeading.hasClass("collapsed");
        var linktype;
        if (isCollapsed)
        { linktype = "close"; }
        else { linktype = "open";
		}
        var nextType = $accordionIcon.data("linkprefix") + linktype;
        $accordionIcon.attr("data-linkaction", nextType);
        $accordionIcon.attr("data-linktype", nextType);
		$accordionIcon.attr("data-analytics-link-name", nextType.toLowerCase());
        $accordionIcon.attr("data-analytics-content-type", nextType.toLowerCase());
    });

    function leadersNavigate(amountLeadersMoves) {
        var currentTopValue = $(".js-animate-leaders").css("top");
        currentTopValue = currentTopValue ? currentTopValue.replace(/[^-\d\.]/g, "") : 0;
        var amountMovingNumber = amountLeadersMoves.replace(/[^0-9-]/g, "");
        var negamountMovingNumber = "-" + amountMovingNumber.replace(/[^0-9]/g, "");
        var leaderLength = $(".js-animate-leaders li").length - 6;
        if (amountMovingNumber < 0 && currentTopValue > amountMovingNumber * leaderLength || amountMovingNumber > 0 && currentTopValue < 0) {
            $(".js-animate-leaders").filter(":not(:animated)").animate({
                top: amountLeadersMoves
            }, "fast", function () {

                var arrowUp = $(".interactive-leadership-tab .icon-jump-links-arrow-up");
                var arrowDown = $(".interactive-leadership-tab .icon-jump-links-arrow-down");
                var aferAnimationTopValue = $(".js-animate-leaders").css("top");
                aferAnimationTopValue = aferAnimationTopValue ? aferAnimationTopValue.replace(/[^-\d\.]/g, "") : 0;

                if (aferAnimationTopValue >= 0) {
                    $(arrowUp).addClass("hidden");
                } else {
                    $(arrowUp).removeClass("hidden");
                }

                if (aferAnimationTopValue <= negamountMovingNumber * leaderLength) {
                    $(arrowDown).addClass("hidden");
                } else {
                    $(arrowDown).removeClass("hidden");
                }
            });
        }
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\TabSectionModule.js
/* version="7" */
if (ComponentRegistry.TabSectionModule) {
    $(function () {
        //navTab elm selector
        var $navTabs = $(tabControl.tabPageElmSelector);
        var $defaultActiveNavTabs = $($navTabs.closest('li.active'));
        //by the numbers shapeColor active-arrow-up, and dropdown-menu        
        var $getTabControlArrowUp = $("span.active-arrow-up");
        var $tabDropdownMenu = $("ul.dropdown-menu");
        //set tab-wrapper to InclusionAndDiversityTab and CorporateCitizenshipTab
        var $tabInclusionAndDiversity = $('div#InclusionAndDiversityTab.tab-pane');
        var $tabCorporateCitizenship = $('div#CorporateCitizenshipTab.tab-pane');
        var $tabPage = $('.tab-open-dropdown-wrapper ul.nav-tabs li > a');
        //initialize tabControl module
        tabControl.init($navTabs, $defaultActiveNavTabs, $getTabControlArrowUp, $tabDropdownMenu, $tabInclusionAndDiversity, $tabCorporateCitizenship, $tabPage);
    });

    //handle device orientation change
    $(window).on("orientationchange", function (event) {
        tabControl.handleOrientationChangeAndResize();
    });
    //handles zoom in
    $(window).on("resize", function (event) {
        tabControl.handleOrientationChangeAndResize();
    });
}

var tabControl = (function () {
    //private methods
    var _setDefaultActiveTabPageColor = function ($defaultActiveNavTabs) {
        $defaultActiveNavTabs.each(function () {
            var $this = $(this);
            var tabPageClass = '';
            //get class for tabPage
            tabPageClass = _getTabPageClass($this);
            //add classes to active tab
            $this.find('a').attr('class', tabPageClass);
        });
    }
    var _toggleActiveTabPage = function () {
        var $this = $(this);
        var tabPageClass = '';
        //clear all classes for each tab        
        _clearTabPageClasses($this);
        //get class for tabPage
        tabPageClass = _getTabPageClass($this);
        //add classes to active tab
        $this.attr('class', tabPageClass);

        //set currentTabName
        var currentTabName = $(".tab-control ul.nav-tabs li a.active").text();
        $(mobileDropdownMenu).text(currentTabName);

        //get and sets background image for tabBackgroundImg
        $tabBackgroundImg = $this.data('bg');
        $tabBackgroundColor = $this.data('bg-color');
        _setBackgroundTabBg($this, $tabBackgroundImg, $tabBackgroundColor);
    }
    var _clearTabPageClasses = function ($this) {
        //get parent
        var $tabControlParent = $this.closest('.tab-control');
        //clear tab pages of current tab control
        $tabControlParent.find('.nav.nav-tabs.row li[role="presentation"] > a').each(function () {
            $(this).attr('class', '');
        });
    }
    var _getTabPageClass = function ($this) {
        var tabPageClass = '';
        //color container and image container, active tab is white, pipeline and inactive tab is washed-out white
        if ($this.closest('.color-container, .image-container').length > 0) {
            tabPageClass = 'active';
        }
            //block is white, active tab is primary color, pipeline and inactive tab is black
        else {
            tabPageClass = 'active color-primary';
        }
        return tabPageClass;
    }

    var _setArrowUpColor = function ($getTabControlArrowUp) {
        $getTabControlArrowUp.css("cssText", "border-bottom: solid " + _darkenColor(blockInnerColor, 0.85) + " 15px");
    }

    var _setDropdownMenuColor = function ($tabDropdownMenu) {
        $tabDropdownMenu.css("background-color", _darkenColor(blockInnerColor, 0.85));
    }

    var _getBlockColor = function ($elm) {
        var parentUiContainerID = $elm.closest('.ui-container').attr('id');
        return blockInnerColor = $('div[data-content-id="' + parentUiContainerID + '"] > div').css('background-color');
    }
    //darken and change color opacity of the Dropdown-menu to 85%
    var _darkenColor = function (color, opacity) {
        if ($(tabPageElmSelector).length > 0) {
            var regexColor = color.replace(/[^\d,.]/g, '').split(',');

            if (color != "rgb(255, 255, 255)") { //check if the color is !white 
                regexColor[0] *= .785;
                regexColor[1] *= .415;
                regexColor[2] *= .475;
                return "rgba(" + parseInt(regexColor[0]) + ", " + parseInt(regexColor[1]) + ", " + parseInt(regexColor[2]) + ", " + opacity + ")";
            }
            else {
                return "rgba(" + parseInt(regexColor[0]) + ", " + parseInt(regexColor[1]) + ", " + parseInt(regexColor[2]) + ", " + opacity + ")";
            }
        }
    }

    //enable the dropdown overlay for mobile and tablet portrait
    var _setTabDropDown = function () {
        $(mobileDropdownMenu + ',' + dropdownArrow).on("click", function (e) {
            e.preventDefault();
            $(blockHowWeLead + ' ' + navTabsElmSelector).toggleClass("sub-menu-active");
            $(blockHowWeLead + dropDownMobileEnabled + ' ' + dropdownArrow).toggleClass("dropdown-arrow-down dropdown-arrow-up");
        })
    }

    //get width and height of current viewport/screen
    var _getViewPort = function () {
        var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
        return { width: w, height: h }
    }

    //public api    
    var checkDeviceIfMobileTabletPortrait = function () {
        var screen = _getViewPort();
        var screenWidth = screen.width;
        var enableMobileTabletPortrait = false;

        //laptop, tablet iPadMini width 1024 (landscape), tablet landscape
        if (screenWidth >= 1024) {
            enableMobileTabletPortrait = false;
        }
            //tablet portrait
        else if (screenWidth >= 768) {
            enableMobileTabletPortrait = true;
        }
            //mobile 
        else if (screenWidth >= 360) {
            enableMobileTabletPortrait = true;
        }
            //mobile iphone
        else {
            enableMobileTabletPortrait = true;
        }
        return enableMobileTabletPortrait;
    }

    var handleMobileAndTabletPortrait = function () {
        $(mobileDropdownMenu).css("background-color", _darkenColor(blockInnerColor, 1));

        $(blockHowWeLead).addClass('open-dropdown');
        $(blockHowWeLead + ' ' + mobileDropdownMenu).removeClass('hide');
        $(blockHowWeLead + ' ' + dropdownArrow).removeClass('hide');
        $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + pipelineElmSelector).addClass('hide');
        $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownMenuCloseBtn).addClass('hide');
        $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownToggle).addClass('hide');
        $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownToggleMobile).removeClass('hide');

        //handles transition from tablet landscape to portrait
        if ($(blockHowWeLead + ' ' + dropdownMenuOverlay).hasClass('sub-menu-active')) {
            // set the arrow to up if dropdown-menu is opened from landscape
            $(blockHowWeLead + ' ' + dropdownArrow).removeClass('dropdown-arrow-down').addClass('dropdown-arrow-up');
            // set the dropdown-menu overlay to enable if opened from landscape
            $(blockHowWeLead + ' ' + navTabsElmSelector).addClass('sub-menu-active');
            // set the icon to minus (-) if the dropdown-menu is opened from the landscape view
            $(blockHowWeLead + ' ' + dropdownToggleMobile).removeClass('ui-icon-plus').addClass('ui-icon-minus');
        } else {
            $(blockHowWeLead + ' ' + dropdownToggleMobile).addClass('ui-icon-plus').removeClass('ui-icon-minus');
        }
    }

    var handleOrientationChangeAndResize = function () {
        //check if mobile and tablet portrait        
        if (tabControl.checkDeviceIfMobileTabletPortrait()) {
            //disable hamburger, enable dropdown menu
            tabControl.handleMobileAndTabletPortrait();
        }
            //disable dropdown (tablet portrait and mobile version)
        else {
            $(tabControl.blockHowWeLead).removeClass('open-dropdown');
            $(tabControl.blockHowWeLead + ' ' + tabControl.mobileDropdownMenu).addClass('hide');
            $(tabControl.blockHowWeLead + ' ' + tabControl.dropdownArrow).addClass('hide');
            $(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector + ' ' + tabControl.pipelineElmSelector).removeClass('hide');
            $(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector + ' ' + tabControl.dropdownMenuCloseBtn).removeClass('hide');
            $(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector + ' ' + tabControl.dropdownToggle).removeClass('hide');
            $(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector + ' ' + tabControl.dropdownToggleMobile).addClass('hide');

            //handles transition from tablet portrait to landscape
            if ($(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector).hasClass('sub-menu-active')) {
                //resets the z-index of the drop-down overlay
                $(tabControl.blockHowWeLead + ' ' + tabControl.navTabsElmSelector).removeClass('sub-menu-active');
                //toggles the arrow properly during transition 
                $(tabControl.blockHowWeLead + ' ' + tabControl.dropdownArrow).toggleClass('dropdown-arrow-down dropdown-arrow-up');
            }
            //check and set if dropdown-menu overlay is opened from portrait
            if ($(tabControl.blockHowWeLead + ' ' + tabControl.dropdownMenuOverlay).hasClass('sub-menu-active')) {
                $(tabControl.blockHowWeLead + ' ' + tabControl.dropdownToggle).addClass('open-dropdown-menu');
                $(tabControl.blockHowWeLead + ' ' + tabControl.dropdownMenuOverlay).addClass('sub-menu-active');
            }
            else {
                $(tabControl.blockHowWeLead + ' ' + tabControl.dropdownToggle).removeClass('open-dropdown-menu');
            }
        }
    }

    //check and set if tab page has ContentBackgroundImage or ContentBackgroundColor
    var _setBackgroundTabBg = function ($this, tabBackgroundImg, tabBackgroundColor) {
        if (tabBackgroundImg != undefined || tabBackgroundColor != undefined) {
            //reverts background color of tab
            $($this.attr('href')).css('cssText', 'background-color: transparent');

            var tabBgImgContainer = $this.closest('.tab-control').find('.tab-content');
            var tabBgColor = $($this.attr('href') + '.bg-color-' + tabBackgroundColor).css('background-color');
            $(tabBgImgContainer).css({
                "margin-bottom": "-1px",
                "background-color": tabBgColor,
                "background-size": "cover",
                "background-image": "url('" + tabBackgroundImg + "')",
                "width": "100%",
                "display": "inline-block"
            });

            //sets background color of tab to transparent
            $($this.attr('href')).css('cssText', 'background-color: transparent !important');

        }
    }

    var _setTabWrapper = function ($tabInclusionAndDiversity, $tabCorporateCitizenship) {
        $tabInclusionAndDiversity.find('.row').removeClass('row').addClass('tab-wrapper');
        $tabCorporateCitizenship.find('.row').removeClass('row').addClass('tab-wrapper');
    }

    var tabPageElmSelector = '.tab-control .nav.nav-tabs.row li[role="presentation"] > a';

    var blockHowWeLead = '#block-how-we-lead .tab-control';
    var dropDownMobileEnabled = '.open-dropdown';

    var mobileDropdownMenu = '.tab-open-dropdown-wrapper .tab-control-dropdown';
    var dropdownArrow = '.tab-open-dropdown-wrapper span.icon-arrow-dropdown-jobs';
    var navTabsElmSelector = '.tab-open-dropdown-wrapper .nav-tabs';

    var pipelineElmSelector = 'li.pipeline';
    var dropdownToggle = '.dropdown .dropdown-toggle';
    var dropdownToggleMobile = '.dropdown .dropdown-toggle-mobile';
    var dropdownMenuOverlay = '.dropdown .dropdown-menu';
    var dropdownMenuCloseBtn = '.dropdown .dropdown-menu-close'

    var blockInnerColor = "";
    var maximumNumberOfTabsDisplayed = 5;

    var init = function ($navTabs, $defaultActiveNavTabs, $getTabControlArrowUp, $tabDropdownMenu, $tabInclusionAndDiversity, $tabCorporateCitizenship, $tabPage) {
        blockInnerColor = _getBlockColor($navTabs);
        //handle mobile and tablet portrait (enable dropdown for tabs)      
        if (checkDeviceIfMobileTabletPortrait()) {
            handleMobileAndTabletPortrait();
        }
            //for laptop - hide dropdown, remove dropdown classes
        else {
            $(blockHowWeLead).removeClass('open-dropdown');
            $(blockHowWeLead + ' ' + mobileDropdownMenu).addClass('hide');
            $(blockHowWeLead + ' ' + dropdownArrow).addClass('hide');
            $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + pipelineElmSelector).removeClass('hide');
            $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownMenuCloseBtn).removeClass('hide');
            $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownToggle).removeClass('hide');
            $(blockHowWeLead + ' ' + navTabsElmSelector + ' ' + dropdownToggleMobile).addClass('hide');
        }
        //set padding 0 
        $(blockHowWeLead).closest('.ui-content-box').css('cssText', 'padding: 0 !important');
        //sets DropdownMenu color same as shapeColor
        _setDropdownMenuColor($tabDropdownMenu);
        //sets active-arrow-up color same as shapeColor     
        _setArrowUpColor($getTabControlArrowUp);
        //toggle primary color for default active tabPage - non-color and non-image container
        _setDefaultActiveTabPageColor($defaultActiveNavTabs);
        //set tabPage click event handler
        $navTabs.on("click", _toggleActiveTabPage);
        _setTabDropDown();

        //Handles click events for laptop and tablet landscape
        $(dropdownToggle + ',' + dropdownMenuCloseBtn).on("click", function () {
            $(dropdownMenuOverlay).toggleClass('sub-menu-active');
            $(dropdownToggle).toggleClass('open-dropdown-menu');
        });
        //Handles click events for mobile and tablet portrait
        $(dropdownToggleMobile).on("click", function () {
            $(this).toggleClass('ui-icon-plus ui-icon-minus');
            $(dropdownMenuOverlay).toggleClass('sub-menu-active');
            $(this).toggleClass('open-dropdown-menu');
        });
        $(tabPageElmSelector).on("click", function () {
            $(blockHowWeLead + dropDownMobileEnabled + ' ' + navTabsElmSelector).toggleClass("sub-menu-active");
            $(blockHowWeLead + dropDownMobileEnabled + ' ' + dropdownArrow).toggleClass("dropdown-arrow-down dropdown-arrow-up");
        });
        //counts number of tab page and hides hamburger
        if ($tabPage && $tabPage.length < this.maximumNumberOfTabsDisplayed) {
            $(dropdownToggle).addClass('hide');
        }
        _setTabWrapper($tabInclusionAndDiversity, $tabCorporateCitizenship);
    }

    return {
        init: init,
        tabPageElmSelector: tabPageElmSelector,
        checkDeviceIfMobileTabletPortrait: checkDeviceIfMobileTabletPortrait,
        handleMobileAndTabletPortrait: handleMobileAndTabletPortrait,
        handleOrientationChangeAndResize: handleOrientationChangeAndResize,
        blockHowWeLead: blockHowWeLead,
        dropDownMobileEnabled: dropDownMobileEnabled,
        mobileDropdownMenu: mobileDropdownMenu,
        dropdownArrow: dropdownArrow,
        navTabsElmSelector: navTabsElmSelector,
        pipelineElmSelector: pipelineElmSelector,
        dropdownToggle: dropdownToggle,
        dropdownToggleMobile: dropdownToggleMobile,
        dropdownMenuOverlay: dropdownMenuOverlay,
        dropdownMenuCloseBtn: dropdownMenuCloseBtn,
        blockInnerColor: blockInnerColor,
        maximumNumberOfTabsDisplayed: maximumNumberOfTabsDisplayed
    }

})();
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CardCarouselModule.js
//version 2

if (ComponentRegistry.CardCarouselModule) {
    var $tileContainer = $('.tile-container');
    var $tiles = $('.by-the-numbers .tile-container .tile');
    var $tabPane = $('.by-the-numbers').closest('.col-sm-12');

    if ($('.by-the-numbers').closest('.tab-control').length > 0) {
        $tabPane = $('.tab-control .tab-pane .row');
    }

    $(function () {
        //prepare card carousel jquery objects
        var $arrowRight = $('.by-the-numbers .arrow-right .icon-arrowright2arrow-right2');
        var $arrowLeft = $('.by-the-numbers .arrow-left .icon-arrowright2arrow-right2');
        var cardsLength = $('.by-the-numbers .tile').length;
        var $directToBlockAddClass = true;

        if ($('.by-the-numbers').closest('.tab-control').length > 0) {
            $arrowRight = $('.tab-control .tab-pane .arrow-right .icon-arrowright2arrow-right2');
            $arrowLeft = $('.tab-control .tab-pane .arrow-left .icon-arrowright2arrow-right2');
            $directToBlockAddClass = false;
        }

        //initialize CardCarouselModule
        cardCarouselModule.init($tileContainer, $tiles, $tabPane, $arrowRight, $arrowLeft, $directToBlockAddClass, cardsLength);
    });

    //handle device orientation change
    $(window).on("orientationchange", function (event) {
        cardCarouselModule.handleOrientationChange($tileContainer, $tabPane, $tiles);
    });

    //handles zoom in
    $(window).on("resize", function () {
        cardCarouselModule.handleOrientationChange($tileContainer, $tabPane, $tiles);
    });
}

var cardCarouselModule = (function () {
    //private methods
    var _setLastTileBorder = function () {
        var screenWidth = cardCarouselModule.currentScreen.width;
        //laptop
        if (screenWidth > 1024) {
            cardCarouselModule.lastTileIndex = 4;
        }
        //tablet iPadMini width 1024
        else if (screenWidth >= 1000) {
            cardCarouselModule.lastTileIndex = 4;
        }
        //tablet portrait
        else if (screenWidth >= 768) {
            cardCarouselModule.lastTileIndex = 2;
        }
        //mobile
        else {
            cardCarouselModule.lastTileIndex = 1;
        }

        var $tiles = $('.by-the-numbers .tile');
        if ($tiles.length > 0) {
            //set all border right
            $tiles.css('border-right', '1px solid #949494');
            //remove border to current last tile
            $($tiles[cardCarouselModule.lastTileIndex]).css('border-right', 'none');
        }
    }
    //event handler for clicking right arrow icon
    var _slideToRight = function () {
        cardCarouselModule.slideCount++;
        cardCarouselModule.lastTileIndex++;
        var screenWidth = cardCarouselModule.currentScreen.width;
        var subtractor = 0;
        //laptop
        if (screenWidth >= 1000) {
            subtractor = 4;
        }
        //tablet portrait
        else if (screenWidth >= 768) {
            subtractor = 2;
        }
        //mobile
        else {
            subtractor = 1;
        }

        if (cardCarouselModule.slideCount >= (cardCarouselModule.cardsLength - subtractor)) {
            cardCarouselModule.slideCount = cardCarouselModule.cardsLength - subtractor;
            cardCarouselModule.$arrowRight.closest('.arrow-right').addClass('hidden');
        }
        if (cardCarouselModule.lastTileIndex > (cardCarouselModule.cardsLength - 1)) {
            cardCarouselModule.lastTileIndex = cardCarouselModule.cardsLength - 1;
        }

        cardCarouselModule.$arrowLeft.closest('.arrow-left').removeClass('hidden');
        var leftVal = cardCarouselModule.dimensions.cardWidth * (cardCarouselModule.slideCount - 1);
        cardCarouselModule.$tileContainer.css('transform', 'translate(-' + leftVal + 'px, 0px)');

        var $tiles = $('.by-the-numbers .tile');
        if ($tiles.length > 0) {
            //set all border right
            $tiles.css('border-right', '1px solid #949494');
            //remove border to current last tile
            $($tiles[cardCarouselModule.lastTileIndex]).css('border-right', 'none');
        }
    }
    //event handler for clicking left arrow icon
    var _slideToLeft = function () {
        cardCarouselModule.slideCount--;
        cardCarouselModule.lastTileIndex--;
        if (cardCarouselModule.slideCount <= 1) {
            cardCarouselModule.slideCount = 1;
            cardCarouselModule.$arrowLeft.closest('.arrow-left').addClass('hidden');
        }
        if (cardCarouselModule.lastTileIndex < 0) {
            cardCarouselModule.lastTileIndex = 0;
        }
        cardCarouselModule.$arrowRight.closest('.arrow-right').removeClass('hidden');
        var rightVal = cardCarouselModule.dimensions.cardWidth * (cardCarouselModule.slideCount - 1);
        cardCarouselModule.$tileContainer.css('transform', 'translate(-' + rightVal + 'px, 0px)');

        var $tiles = $('.by-the-numbers .tile');
        if ($tiles.length > 0) {
            //set all border right
            $tiles.css('border-right', '1px solid #949494');
            //remove border to current last tile
            $($tiles[cardCarouselModule.lastTileIndex]).css('border-right', 'none');
        }
    }
    //add background color to current card
    var _cardHover = function () {
        var $this = $(this);
        var color = $this.data("bgcolor")
        $this.addClass("bg-color-" + color).addClass("card-hover");
    }
    //remove background color to current card
    var _cardUnhover = function () {
        var $this = $(this);
        var color = $this.data("bgcolor")
        $this.removeClass("bg-color-" + color).removeClass("card-hover");
    }

    //public api
    //height and width of current viewport/screen   
    var currentScreen = {
        width: '',
        heigh: ''
    }
    //dimension of CardCarouselModule: tiles or card width and tile container width
    var dimensions = {
        cardWidth: 0,
        tileContainerCardWidth: 0
    }
    //cardwith specs for CardCarouselModule for each viewport/screen
    var settings = {
        laptop: {
            cardWidth: 200,
            tileContainerCardWidth: 999
        },
        tablet: {
            portrait: {
                cardWidth: 225,
                tileContainerCardWidth: 675
            },
            iPadMiniLandscape: {
                cardWidth: 180,
                tileContainerCardWidth: 900
            }
        },
        mobile: {
            portrait: {
                cardWidth: 154,
                tileContainerCardWidth: 308
            },
            iPhonePortrait: {
                cardWidth: 137,
                tileContainerCardWidth: 274
            }
        }
    }
    //total no. of cards
    var cardsLength = 0;
    //cards slide counter/cursor
    var slideCount = 1;
    //jQuery object arrow right
    var $arrowRight = null;
    //jQuery object arrow left
    var $arrowLeft = null;
    //jQuery object tile container
    var $tileContainer = null;
    //last visible tile in container
    var lastTileIndex = 0;

    //initialize   
    var init = function ($tileContainer, $tiles, $tabPane, $arrowRight, $arrowLeft, $directToBlockAddClass, cardsLength) {
        //set current screen
        //determine viewport/screen
        var curScreen = this.getViewPort();
        this.currentScreen.width = curScreen.width;
        this.currentScreen.height = curScreen.height;
        //calculate width of cards according to viewport
        this.setModuleDimensions();
        //bind click events for right and left arrow icons       
        this.cardsLength = cardsLength;
        this.$arrowRight = $arrowRight;
        this.$arrowLeft = $arrowLeft;
        this.$tileContainer = $tileContainer;
        this.$arrowRight.on("click", _slideToRight);
        this.$arrowLeft.on("click", _slideToLeft);
        //set last tile index
        _setLastTileBorder();
        //bind hover and unhover events to cards
        if ((cardCarouselModule.currentScreen.width <= 800 && cardCarouselModule.currentScreen.height <= 1024) ||
            (cardCarouselModule.currentScreen.height <= 800 && cardCarouselModule.currentScreen.width <= 1024)) {
            //for mobile
            $tiles.on("touchstart", _cardHover);
            $tiles.on("touchend", _cardUnhover);
        }
        else {
            //for laptop
            $tiles.on("mouseenter", _cardHover).on("mouseleave", _cardUnhover);
        }
        //set inline styles               
        $tileContainer.css('width', this.dimensions.cardWidth * this.cardsLength);
        $tabPane.css('width', this.dimensions.tileContainerCardWidth);
        $tileContainer.css('height', '100%');
        $tiles.css('width', this.dimensions.cardWidth);

        //set data-analytics-link-name for each card carousel
        cardCarouselHeadlineLinkName();

        if (cardCarouselModule.currentScreen.width >= 1000 && cardCarouselModule.cardsLength <= 5) {
            $arrowRight.addClass('hidden');
        }

        if ($directToBlockAddClass || cardCarouselModule.currentScreen.width < 768) {
            $tabPane.addClass('tab-pane-custom');
        }
    }

    //handle orientation change for tablet and mobile
    var handleOrientationChange = function ($tileContainer, $tabPane, $tiles) {
        //get slidecount
        //identify viewport
        var curScreen = cardCarouselModule.getViewPort();
        cardCarouselModule.currentScreen.width = curScreen.width;
        cardCarouselModule.currentScreen.height = curScreen.height;
        //re calculate cardwidth and container width based from viewport
        cardCarouselModule.setModuleDimensions();
        //reset counters
        cardCarouselModule.slideCount = 1;
        cardCarouselModule.lastTileIndex = 0;
        //set new cardwith and container width
        //set inline styles               
        $tileContainer.css('width', cardCarouselModule.dimensions.cardWidth * cardCarouselModule.cardsLength);
        $tabPane.css('width', cardCarouselModule.dimensions.tileContainerCardWidth);
        $tileContainer.css('height', '100%');
        $tiles.css('width', cardCarouselModule.dimensions.cardWidth)
        //reset transition      
        $tileContainer.css('transform', 'translate( 0px, 0px)');
        //re calculate last tile index        
        //remove border of last tile
        _setLastTileBorder();
        //make sure cards are positioned correctly
        var $arrowRight = $('.tab-control .tab-pane .arrow-right .icon-arrowright2arrow-right2');
        cardCarouselModule.$arrowLeft.closest('.arrow-left').addClass('hidden');
        if (cardCarouselModule.currentScreen.width >= 1000 && cardCarouselModule.cardsLength <= 5) {
            cardCarouselModule.$arrowRight.closest('.arrow-right').addClass('hidden');
        }
        else {
            cardCarouselModule.$arrowRight.closest('.arrow-right').removeClass('hidden');
        }
        if (cardCarouselModule.currentScreen.width < 768) {
            $tabPane.addClass('tab-pane-custom');
        }
    }

    //get width and height of current viewport/screen
    var getViewPort = function () {
        var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
        return { width: w, height: h }
    }
    //set dimensions of card and tile container (width)
    var setModuleDimensions = function () {
        var screenWidth = this.currentScreen.width;
        var cardWidth = 0;
        var tileContainerCardWidth = 0;
        //laptop
        if (screenWidth > 1150) {
            cardWidth = this.settings.laptop.cardWidth;
            tileContainerCardWidth = this.settings.laptop.tileContainerCardWidth;
        }
        //tablet iPadMini width 1024
        else if (screenWidth >= 1024) {
            cardWidth = this.settings.tablet.iPadMiniLandscape.cardWidth;
            tileContainerCardWidth = this.settings.tablet.iPadMiniLandscape.tileContainerCardWidth;
        }
        //tablet portrait
        else if (screenWidth >= 768) {
            cardWidth = this.settings.tablet.portrait.cardWidth;
            tileContainerCardWidth = this.settings.tablet.portrait.tileContainerCardWidth;
        }
        //mobile 
        else if (screenWidth >= 360) {
            cardWidth = this.settings.mobile.portrait.cardWidth;
            tileContainerCardWidth = this.settings.mobile.portrait.tileContainerCardWidth;
        }
        else { //mobile iphone
            cardWidth = this.settings.mobile.iPhonePortrait.cardWidth;
            tileContainerCardWidth = this.settings.mobile.iPhonePortrait.tileContainerCardWidth;
        }

        this.dimensions.tileContainerCardWidth = tileContainerCardWidth;
        this.dimensions.cardWidth = cardWidth;
    }
    var cardCarouselHeadlineLinkName = function () {
        var $targetLinks = jQuery(".overflow-container .tile-container a.tile");

        for (var i = 0; i < $targetLinks.length; i++) {
            var $targetLink = jQuery($targetLinks[i]);
            var linkText = $targetLink.prop("innerText");
            if ($targetLink.has("style") !== null || typeof $targetLink.has("style") !== 'undefined') {
                var targetLinkInnerHtml = $targetLink.prop("innerHTML");
                var wrapped = jQuery("<div>" + targetLinkInnerHtml + "</div>");
                wrapped.find("style").remove();
                linkText = wrapped.prop("innerText");
            }

            linkText = (linkText !== null && typeof linkText !== 'undefined') ? linkText.trim().replace(/\s+/g, " ").toLowerCase() : "";

            if (linkText)
                $targetLink.attr("data-analytics-link-name", linkText);
        }
    }
    return {
        currentScreen: currentScreen,
        dimensions: dimensions,
        settings: settings,
        cardsLength: cardsLength,
        slideCount: slideCount,
        $arrowRight: $arrowRight,
        $arrowLeft: $arrowLeft,
        $tileContainer: $tileContainer,
        lastTileIndex: lastTileIndex,
        init: init,
        handleOrientationChange: handleOrientationChange,
        getViewPort: getViewPort,
        setModuleDimensions: setModuleDimensions,
        cardCarouselHeadlineLinkName: cardCarouselHeadlineLinkName,
    };
})();

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\AdjacentTiles.js
//version 16
if (ComponentRegistry.AdjacentTilesModule) {
    $(function () {
        if (window.performance) {
            if (performance.navigation.type == 1) {
                sessionStorage.removeItem("loadedRowsCache");
            }
        }
        $(window).on('load resize orientationchange', function () {
            //initialize adjacentTileControl module
            adjacentTileControl.init();

        });

        //View More Adjacent Tiles
        $('.adjacent-tiles-container').each(function () {
            var isViewMoreEnabled = $(this).data("enable-view-more");
            var loadedRows;
            var cacheLoadedRows = sessionStorage.getItem("loadedRowsCache");

            if (cacheLoadedRows !== null) {
                loadedRows = cacheLoadedRows;
                $(this).find('.view-more-button').attr('data-incremental-variable', cacheLoadedRows);
            }
            else {
                loadedRows = $(this).data("loaded-rows-count") !== "" ? $(this).data("loaded-rows-count") : 0;
            }

            var tileRows = $(this).children('.col-sm-12');
            var totalRows = tileRows.length;

            //Only hide tiles when on preview mode
            if ($('#webedit').length === 0) {
                tileRows.hide();

                if (loadedRows !== 0) {
                    $(this).children('.col-sm-12').slice(0,loadedRows).show();
                    if (loadedRows < totalRows && typeof isViewMoreEnabled !== "undefined" && isViewMoreEnabled) {
                        $(this).find('.view-more-button').show();
                    }
                }
            }
        });

        $('.view-more-button').on("click", function () {
            var $adjacentTilesContainer = $(this).closest('.adjacent-tiles-container');
            var tileRows = $adjacentTilesContainer.children('.col-sm-12');
            var loadedRows = $adjacentTilesContainer.data("loaded-rows-count") !== "" ? $adjacentTilesContainer.data("loaded-rows-count") : 0;

            if (typeof tileRows !== "undefined" && tileRows.length) {
                var incrementalVariable = Number($(this).attr("data-incremental-variable"));
                var isLessThanTotalRows = incrementalVariable + loadedRows < tileRows.length;
                incrementalVariable = isLessThanTotalRows ? incrementalVariable + loadedRows : tileRows.length;
                $(this).attr('data-incremental-variable', incrementalVariable);

                $adjacentTilesContainer.children('.col-sm-12').slice(0,incrementalVariable).show();

                sessionStorage.setItem('loadedRowsCache', incrementalVariable);

                if (!isLessThanTotalRows) {
                    $(this).hide();
                }
            }

            //refreshing the loaded tiles
            //adjacentTileControl.init();
        });

        adjacentContainerDistance = $(".adjacent-tiles-container");
        if (isTablet()) {
            adjacentContainerDistance.closest(".ui-content-box").attr('style', "margin-top : 8px !important; margin-bottom : 6px !important; padding-bottom : 0 !important");
        }
        else if (isMobile()) {
            adjacentContainerDistance.closest(".ui-content-box").attr('style', "margin-top : 8px !important; margin-bottom : -2px !important; padding-bottom : 0 !important");
        }
        else {
            adjacentContainerDistance.closest(".ui-content-box").attr('style', "margin-top : 10px !important; margin-bottom : 8px !important; padding-bottom : 0 !important");
        }
    });
}

var adjacentTileControl = (function () {
    //public api
    var init = function () {

        //Animation for iOS Mobile
        $("*").on('touchstart', function () {
            $(this).trigger('hover');
        }).on('touchend', function () {
            $(this).trigger('hover');
        });

        var tiles = $('.adjacent-tiles');
        if (isMobile() || window.matchMedia("(max-width: 767px)").matches) {
            tiles.removeClass('zoom-onhover');
        }

        var slicer = $('.adjacent-tiles').parent('div');
        slicer.css('overflow', 'hidden');

        slicer.each(function (index) {
            var $adjTiles = $(this).find(".adjacent-tiles");
            $adjTiles.attr("data-position", index);
            $adjTiles.attr("data-analytics-module-name", "tile " + ++index);
        });

        //Tiles Height
        var articles = $('.adjacent-tiles .articles');
        setTimeout(function () {
            articles.each(function () {
                var $this = $(this);
                var tileHeight = $this.data('tile-height');
                if (tileHeight != "") {
                    $this.css('height', tileHeight);
                }
                var mobileTile = $this.find(".image-box");
                var mobileCard = $this.find(".card");
                var mobileBanner = $this.find(".banner-background");
                var mobileCardHeight = mobileCard.height();
                var mobileTileHeight = mobileTile.height();
                var cardTileType = mobileTile.data('card-type');
                var bannerTileType = mobileBanner.data('card-type');

                if (isMobile()) {

                    if (!mobileCard.hasClass('full-width')) {
                        if (mobileCardHeight >= 260) {
                            $this.css('height', mobileCardHeight + 40);
                        }
                        else {
                            $this.css('height', '260px');
                            var extraSpace = 260 - mobileCardHeight;
                            if (extraSpace < 40) {
                                var addSpace = 40 - extraSpace;
                                var withExactSpace = 260 + addSpace;
                                $this.css('height', withExactSpace);
                            }
                        }
                    }

                    if (bannerTileType == "Banner") {
                        $this.css('height', '375px');
                        $this.find(".banner-container").append($this.find('.cta-container'));
                    }
                }
                else if (isTablet() && window.matchMedia("(orientation: portrait)").matches || window.matchMedia("(max-width: 999px)").matches) {
                    if (bannerTileType == "Banner") {
                        $this.css('height', '375px');
                        $this.find(".banner-container").append($this.find('.cta-container'));
                    }
                }
                else {
                    if (bannerTileType == "Banner") {
                        $this.find(".banner-text").append($this.find('.cta-container'));
                    }
                }
            });
        }, 500);

        //Tiles Background
        var imagebox = $('.adjacent-tiles .image-box');
        var imageboxMp4 = $('.adjacent-tiles .image-box video');
        imagebox.each(function () {
            var $this = $(this);
            var bgColor = $this.data('color-bg');
            var bgLaptop = $this.data('laptop-bg');
            var bgMobile = $this.data('bgmobiles');
            var bgCardType = $this.data('card-type');

            if (typeof bgLaptop === "undefined")
                bgLaptop = "";
            if (typeof bgMobile === "undefined")
                bgMobile = "";

            if (bgCardType == "Profile") {
                $this.attr('style', 'background-image: linear-gradient(#dfdfdf 0%, #dfdfdf 100%)');
            }

            if (bgColor != "") {
                $this.attr('style', 'background-image: linear-gradient(' + bgColor + ')');
            }
            if (bgLaptop != "") {
                $this.attr('style', 'background-image: url(' + bgLaptop + ')');
            }
            if (isMobile() && bgMobile != "") {
                $this.attr('style', 'background-image: url(' + bgMobile + ')');
                $this.children('video').addClass('hidden').prop('muted', true);
            } else {
                $this.children('video').removeClass('hidden').prop('muted', false);
            }
        });

        //Tiles Card
        var card = $('.adjacent-tiles .card');
        card.each(function () {
            var $this = $(this);
            var cardType = $this.parent().find('.image-box').data('card-type');
            var cardContent = $this.find(".card-wrapper");
            var profileContent = $this.find(".profile-content");
            var cardWidth = $this.data('card-width');
            var profileImg = $this.find(".profile-image");
            var topAlign = $this.hasClass('cardv-top')
            var bottomAlign = $this.hasClass('cardv-bottom')
            var topVertical = $('.card.cardv-top');
            var bottomVertical = $('.card.cardv-bottom');
            var cardBGcolor = $this.data('cardcolor');

            if (topAlign == true) {
                topVertical.addClass('hover-top');
            }
            if (bottomAlign == true) {
                bottomVertical.addClass('hover-bottom');
            }
            if (cardBGcolor != "") {
                $this.attr('style', 'background-image: linear-gradient(' + cardBGcolor + ')');
            }

            if (cardType == "Profile") {
                if (profileImg.length == 0) {
                    $(".profile-content").css('top', '0');
                }
            }
            //if (isMobile() || window.matchMedia("(max-width: 767px)").matches) {
            //    cardContent.append($this.find('.cta-container'));
            //    profileContent.append($this.find('.cta-container'));
            //}
            //else {
            //    $this.removeClass('fixed-width');
            //    if (cardType == "Profile") {
            //        $this.addClass("full-width");
            //        $this.append($this.find('.cta-container'));
            //    }
            //    else {
            //        $this.addClass(cardWidth);
            //        if (cardWidth == "full-width") {
            //            $this.append($this.find('.cta-container'));
            //        }
            //    }
            //}
        });

        //Video
        var videoPlayer = $(".ytPlayer");

        videoPlayer.each(function () {
            var $this = $(this);
            var src = $this.data("url-orig");
            $this.attr("src", src);
        });

        function StopAllVideos(src) {
            var youtube = $(".ytPlayer");
            youtube.attr("src", src);
        }

        var playVideo = $("span.icon-play-2");

        playVideo.on("click", function (e) {
            var $this = $(this);
            var videoContainer = $(".video-container");
            var card = $(".card");
            var noCard = $(".no-card");

            var videoUrl = $this.closest(".articles").find(".ytPlayer").data("url");
            var videoSrc = $this.closest(".articles").find(".ytPlayer").data("url-orig");

            videoContainer.addClass("hidden");
            card.removeClass("hidden");
            noCard.removeClass("hidden");

            $this.closest(".articles").find(".video-container").removeClass("hidden");
            $this.closest(".card").addClass("hidden");
            $this.closest(".no-card").addClass("hidden");

            StopAllVideos(videoSrc);

            if (videoUrl) {
                $this.closest(".articles").find("iframe").attr("src", videoUrl);
            }
        });

        //Banner
        var tiles = $('.adjacent-tiles');
        var banner = tiles.find(".banner-background");
        var bannerText = tiles.find(".banner-text");
        var bannerCTA = tiles.find(".banner-container .cta-container");
        setTimeout(function () {

            if (isDesktop()) { //desktop & tablet landscape
                tiles.each(function () {
                    var $this = $(this);
                    var hoverState = $this.find(".banner-background:hover").length;
                    //initial display
                    banner.addClass('initial');
                    banner.removeClass('hover unhover');

                    var bannerImg = $this.find(".banner-container");
                    var laptopBanner = bannerImg.children().eq(0);
                    var hoverBanner = bannerImg.children().eq(1);
                    var mobileBanner = bannerImg.children().eq(2);

                    mobileBanner.addClass("hidden");

                    if (hoverState == 0) {
                        var color = $this.find(".banner-background").data("bg-color-orig");
                        var img = $this.find(".banner-background").data("image-orig");
                        if (img) {
                            laptopBanner.removeClass("hidden");
                            hoverBanner.addClass("hidden");
                        }
                        $this.find(".banner-container .banner-text p").css({ "animation": "", "animation-delay": "" });
                        $this.find(".banner-container .cta-container").css({ "animation": "", "animation-delay": "" });
                    }
                    else {
                        var color = $this.find(".banner-background").data("bg-color-hover");
                        var img = $this.find(".banner-background").data("image-hover");
                        if (img) {
                            laptopBanner.addClass("hidden");
                            hoverBanner.removeClass("hidden");
                        }
                        $this.find(".banner-container .banner-text p").css({ "animation": "fadeInText .4s forwards", "animation-delay": "50ms" });
                        $this.find(".banner-container .cta-container").css({ "animation": "fadeInText .4s forwards", "animation-delay": "50ms" });
                    }

                    if (color) {
                        $this.find(".banner-background").css("background-image", "linear-gradient(" + color + ")");
                    }
                    if (bannerText.hasClass('align-right')) {
                        laptopBanner.attr('style', "top: ");
                        hoverBanner.attr('style', "top: ");
                    }
                    else if (bannerText.hasClass('align-left')) {
                        laptopBanner.attr('style', "top: ");
                        hoverBanner.attr('style', "top: ");
                    }

                    //banner hover
                    $this.on("mouseenter",
                        function () { //onmouseenter
                            var enablehover = $(this).find('.banner-background').data('enablehover');
                            if (enablehover) {
                                var $this = $(this);
                                banner.removeClass('initial unhover');
                                banner.addClass('hover');
                                var color = $this.find(".banner-background").data("bg-color-hover");
                                var img = $this.find(".banner-background").data("image-hover");
                                if (color) {
                                    $this.find(".banner-background").css("background-image", "linear-gradient(" + color + ")");
                                }
                                if (img) {
                                    laptopBanner.addClass("hidden");
                                    hoverBanner.removeClass("hidden");
                                }
                                $this.find(".banner-container .banner-text p").css({ "animation": "fadeInText .4s forwards", "animation-delay": "50ms" });
                                $this.find(".banner-container .cta-container").css({ "animation": "fadeInText .4s forwards", "animation-delay": "50ms" });
                            }
                        })

                        .on("mouseleave", function () { //onmouseleave
                            var $this = $(this);
                            banner.removeClass('initial hover');
                            banner.addClass('unhover');
                            var color = $this.find(".banner-background").data("bg-color-orig");
                            var img = $this.find(".banner-background").data("image-orig");
                            if (color) {
                                $this.find(".banner-background").css("background-image", "linear-gradient(" + color + ")");
                            }
                            if (img) {
                                laptopBanner.removeClass("hidden");
                                hoverBanner.addClass("hidden");
                            }
                            $this.find(".banner-container .banner-text p").css({ "animation": "", "animation-delay": "" });
                            $this.find(".banner-container .cta-container").css({ "animation": "", "animation-delay": "" });
                        })
                })

                var footer = $("#block-footer.ui-container.color-container.row.c-right.c-ui-square");
                footer.on("mouseenter",
                    function () { //onmouseenter
                        var $this = $(this);
                        var bannerImg = $this.find(".banner-container");
                        var laptopBanner = bannerImg.children().eq(0);
                        var hoverBanner = bannerImg.children().eq(1);
                        banner.removeClass('initial hover');
                        banner.addClass('unhover');
                        var color = $this.find(".banner-background").data("bg-color-orig");
                        var img = $this.find(".banner-background").data("image-orig");
                        if (color) {
                            $this.find(".banner-background").css("background-image", "linear-gradient(" + color + ")");
                        }
                        if (img) {
                            laptopBanner.removeClass("hidden");
                            hoverBanner.addClass("hidden");
                        }
                    })
            }
            else { //mobile & tablet portrait
                tiles.each(function () {
                    var $this = $(this);
                    var bannerMobileBG = $this.find(".banner-background");
                    var bannerImg = $this.find(".banner-container");
                    var laptopBanner = bannerImg.children().eq(0);
                    var hoverBanner = bannerImg.children().eq(1);
                    var mobileBanner = bannerImg.children().eq(2);
                    var bannerText = $this.find(".banner-text");
                    var colorOnHover = bannerMobileBG.data("bg-color-hover");
                    var color = bannerMobileBG.data("bg-color-orig");
                    if (colorOnHover != "") {
                        bannerMobileBG.css("background-image", "linear-gradient(" + colorOnHover + ")");
                    }
                    else {
                        bannerMobileBG.css("background-image", "linear-gradient(" + color + ")");
                    }
                    laptopBanner.addClass("hidden");
                    hoverBanner.addClass("hidden");
                    mobileBanner.removeClass("hidden");
                    if (bannerText.hasClass('align-right')) {
                        mobileBanner.attr('style', "top: 35%");
                    }
                    else if (bannerText.hasClass('align-left')) {
                        mobileBanner.attr('style', "top: 55%");
                    }
                    $this.off('mouseenter mouseleave');
                })
            }

        }, 500);

        //RMT 7047 Accessibility of contents on Hovered Banner
        $(window).on("keyup", function (e) {

            //Styling Variables for Banner Accesibility
            var bannerBg = $(".banner-background");
            var bannerBgImage = $('.banner-container').children().eq(0);
            var bannerBgImageHover = $('.banner-container').children().eq(1);
            var bannerText = $(".banner-container .banner-text > p");
            var bannerCta = $(".banner-container .banner-text > .cta-container");

            var code = (e.keyCode ? e.keyCode : e.which);
            var focusedOnBanner = $('.banner-text > .cta-container > a:focus');

            //Hovered State
            var hoveredColor = focusedOnBanner.closest(".banner-background").data("bg-color-hover");
            var hoveredImg = focusedOnBanner.closest(".banner-background").data("image-hover");

            //Upon mouse leave
            var hoverLeaveColor = $(".banner-background").data("bg-color-orig");
            var hoverLeaveImg = $(".banner-background").data("image-orig");

            if (code == 9 && focusedOnBanner.length) {
                if (hoveredColor) {
                    bannerBg.css("background-image", "linear-gradient(" + hoveredColor + ")");

                    if (hoveredImg) {
                        bannerBgImage.addClass("hidden");
                        bannerBgImageHover.removeClass("hidden");
                    }

                    bannerText.addClass("hovered-banner-text");
                    bannerCta.addClass("hovered-cta-link");

                }
            }

            else {
                if (hoverLeaveColor) {
                    bannerBg.css("background-image", "linear-gradient(" + hoverLeaveColor + ")");

                    if (hoverLeaveImg) {
                        bannerBgImage.removeClass("hidden");
                        bannerBgImageHover.addClass("hidden");
                    }

                    if (bannerText.hasClass("hovered-banner-text")) {

                        bannerText.removeClass("hovered-banner-text");
                    }

                    if (bannerCta.hasClass("hovered-cta-link")) {

                        bannerCta.removeClass("hovered-cta-link");
                    }
                }
            }
        });
    }
    return {
        init: init,
    }
})();


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\BioModule.js
/*  version="5.0" */

if (ComponentRegistry.BioModule) {
    function BioModuleFunc() {
        var $windowJs = $(window);
        var bioPersons = $(".bio-persons");
        var bioPersonsTile = $(".bio-persons-tile");
        var personDetailsHeight = $windowJs.width() * 0.6 + 'px';
        var tabletPersonDetailsHeight = $windowJs.width() * 0.56 * 2 + 'px';
        var mobilePersonDetailsHeight = $windowJs.width() * 0.868 * 2 + 'px';
        var mobilePersonDetailsContentHeight = $windowJs.width() * 0.595 * 2 + 'px';
        var mobilePersonDetailsHeightLandscape = $windowJs.width() * 0.64 * 2 + 'px';
        var mobilePersonDetailsContentHeightLandscape = $windowJs.width() * 0.4 * 2 + 'px';
        var $bioPersonsAnchor = $(".bio-persons-anchor");
        var $bioPersonsDetails = $(".bio-persons-details");
        var $bioPersonsDetailsContents = $(".bio-persons-details-content");
        var $bioPersonsDetailsText = $('.bio-persons-details-text');
        var $bioTileCaption = $(".bio-tile-caption");
        var $backToBio = $(".back-to-bio-tiles");
        var viewMoreButton = $(".bio-persons-view-more");
        var changeOpacity = function (color, opacity) {
            this.$color = color.replace("rgb", "rgba");

            if (opacity) {
                return this.$color.replace(")", "," + opacity + ")");
            } else {
                return color;
            }
        };
        var bioModule = {
            init: function () {
                this.windowResize();
                this.tileControl();
                this.tileHover();
                this.backToTileView();
                this.tileCaptionDetect();
                this.viewMore();
                this.detailsScrollBarOnWindowResize();
            },
            updateTileHeight: function () {
                var $height = bioPersonsTile.width();
                if (this.isMobile() || this.isTabletPortrait() || this.isTabletLandscape() && $height <= 100) {
                    switch ($height) {
                        case 25:
                            $height = $windowJs.outerWidth(true) / 4;
                            break;
                        case 50:
                            $height = $windowJs.outerWidth(true) / 2;
                            break;
                    }
                    if (Math.floor($height) == 33) {
                        $height = $windowJs.outerWidth(true) / 3;
                    }
                }
                else if ($height == 25) {
                    $height = $windowJs.outerWidth(true) / 4;
                }
                $bioPersonsAnchor.css("height", $height + "px");
                bioPersonsTile.css("height", $height + "px");
            },
            updateDetailsHeight: function () {
                if ($(window).width() > 999) {
                    $bioPersonsDetails.css({ 'height': personDetailsHeight });
                    $bioPersonsDetailsContents.css({ 'height': personDetailsHeight });
                }
                else if ($(window).width() > 767) {
                    $bioPersonsDetails.css({ 'height': tabletPersonDetailsHeight });
                    $bioPersonsDetailsContents.css({ 'height': personDetailsHeight });
                }
                else {
                    if ($(window).height() > $(window).width()) {
                        $bioPersonsDetails.css({ 'height': mobilePersonDetailsHeight });
                        $bioPersonsDetailsContents.css({ 'height': mobilePersonDetailsContentHeight });
                    } else {
                        $bioPersonsDetails.css({ 'height': mobilePersonDetailsHeightLandscape });
                        $bioPersonsDetailsContents.css({ 'height': mobilePersonDetailsContentHeightLandscape });
                    }
                }
            },
            windowResize: function () {
                if (bioPersonsTile.length > 0) {
                    this.updateTileHeight();
                    this.updateDetailsHeight();
                }
            },
            tileHover: function () {
                if (!bioModule.isTabletPortrait() && !bioModule.isMobile()) {
                    bioPersonsTile.on("hover", function () {
                        var $fontColor = $(this).find($bioTileCaption).data('bg-color');
                        var $bioTileCaptionSpan = $(this).find(".bio-tile-caption > span");
                        $(this).find($bioTileCaption).toggleClass("bg-color-white");
                        $(this).find($bioTileCaptionSpan).toggleClass("color-" + $fontColor);
                    });
                }
                else {
                    bioPersonsTile.on("touchstart", function () {
                        var $fontColor = $(this).find($bioTileCaption).data('bg-color');
                        var $bioTileCaptionSpan = $(this).find(".bio-tile-caption > span");
                        $(this).find($bioTileCaption).toggleClass("bg-color-white");
                        $(this).find($bioTileCaptionSpan).toggleClass("color-" + $fontColor);
                    });
                    bioPersonsTile.on("touchend", function () {
                        var $fontColor = $(this).find($bioTileCaption).data('bg-color');
                        var $bioTileCaptionSpan = $(this).find(".bio-tile-caption > span");
                        $(this).find($bioTileCaption).toggleClass("bg-color-white");
                        $(this).find($bioTileCaptionSpan).toggleClass("color-" + $fontColor);
                    });
                }
            },
            backToTileView: function () {
                bioPersons.each(function () {
                    var $this = $(this);
                    $this.find($backToBio).on("click", function ($event) {
                        $event.preventDefault();
                        var contPosition = $this.offset().top;
                        var headerTopNavDis = $("#header-topnav").outerHeight();
                        $(this).closest($bioPersonsDetails).addClass("hidden");
                        $this.find(viewMoreButton).removeClass("hidden-twice");
                        $this.find($bioPersonsAnchor).removeClass("hidden");
                        if (!bioModule.isMobile() && !bioModule.isTabletPortrait() && !bioModule.isTabletLandscape()) {
                            setTimeout(function () {
                                $('html, body').animate({ scrollTop: contPosition - headerTopNavDis }, 100)
                            }, 100);
                        }
                    });
                });
            },
            tileCaptionDetect: function () {
                bioPersons.each(function () {
                    $(this).find(bioPersonsTile).each(function () {
                        var $bioTileCaptionSpanFrstChild = $(".bio-tile-caption > span:first-child");
                        var $bioTileCaptionSpanLastChild = $(".bio-tile-caption > span:last-child");
                        if ($(this).find($bioTileCaptionSpanLastChild).text() == "") {
                            $(this).find($bioTileCaptionSpanFrstChild).css('padding-top', '8px');
                        };
                    });
                });
            },
            tileControl: function () {
                bioPersons.each(function () {
                    var $this = $(this);
                    var bioPersonsBgColor = $this.css("background-color");
                    var $uiContentBox = $this.closest('.ui-content-box.inline');
                    var $lastSquareBlock = $this.closest('.ui-container.row-wide.clear-float').next('#block-footer');
                    var $tabControl = $(".tab-control");

                    if (($this.closest($tabControl).length < 1)) {
                        $uiContentBox.css("cssText",
                            'margin-top: 0 !important; padding-bottom: 0px !important');
                    }

                    $this.find($bioTileCaption).css("background-color", changeOpacity(bioPersonsBgColor, 0.7));
                    $this.find(bioPersonsTile).each(function () {
                        var attrImgSrc = $(this).attr("data-image-src");

                        if (typeof attrImgSrc !== typeof undefined && attrImgSrc !== false) {
                            $(this).css('background', 'url(' + attrImgSrc + ')');
                            $(this).parent(this.$bioPersonsAnchor)
                            .next($bioPersonsDetails)
                            .css('background', 'url(' + attrImgSrc + ')');
                        }

                        $(this).parent($bioPersonsAnchor).on("click", function ($event) {
                            $event.preventDefault();
                            var contPosition = $this.offset().top;
                            var headerTopNavDis = $("#header-topnav").outerHeight();
                            $this.find($bioPersonsAnchor).addClass("hidden")
                            $this.find(viewMoreButton).addClass("hidden-twice");
                            $(this).next($bioPersonsDetails).removeClass("hidden");
                            if (!bioModule.isMobile() && !bioModule.isTabletLandscape() && !bioModule.isTabletPortrait()) {
                                $('html, body').animate({ scrollTop: contPosition - headerTopNavDis }, 500);
                            }
                            if ($(this).next($bioPersonsDetails).find($bioPersonsDetailsText).find("p").parent().is(".overview")) {
                                $(this).next($bioPersonsDetails).find($bioPersonsDetailsText).find("p").unwrap();
                            }
                            $(this).next($bioPersonsDetails).find(".scroll-bar.vertical").remove();
                            $(this).next($bioPersonsDetails).find($bioPersonsDetailsText)
                            .customScrollbar({
                                hScroll: false,
                                vScroll: true,
                                animationSpeed: 5000,
                                wheelSpeed: 25
                            });
                        });
                    });
                });
            },
            detailsScrollBarOnWindowResize: function () {
                bioPersons.each(function () {
                    $(this).find($bioPersonsDetails).each(function () {
                        if (!$(this).hasClass("hidden")) {
                            $(this).find($bioPersonsDetailsText).find("p").unwrap();
                            $(this).find($bioPersonsDetailsText).find(".scroll-bar.vertical").remove();
                            $(this).find($bioPersonsDetailsText).customScrollbar({
                                hScroll: false,
                                vScroll: true,
                                animationSpeed: 5000,
                                wheelSpeed: 25
                            });
                        }
                    });
                });
            },
            isMobile: function () {
                var isMobile = false;
                var windowWidth = $(window).width();
                var mobileBreakpoint = 767;
                if (windowWidth <= mobileBreakpoint) {
                    isMobile = true;
                }
                return isMobile;
            },
            isTabletLandscape: function () {
                var isTablet = false;
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();
                var mobileBreakpoint = 767;
                var tabletBreakPoint = 1367;
                if (windowWidth > mobileBreakpoint && windowWidth < tabletBreakPoint && windowWidth > windowHeight) {
                    isTablet = true;
                }
                return isTablet;
            },
            isTabletPortrait: function () {
                var isTablet = false;
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();
                var mobileBreakpoint = 767;
                var tabletBreakPoint = 1025;
                if (windowWidth > mobileBreakpoint && windowWidth < tabletBreakPoint && windowHeight > windowWidth) {
                    isTablet = true;
                }
                return isTablet;
            },
            viewMore: function () {
                bioPersons.each(function () {
                    var $this = $(this);
                    $this.find(viewMoreButton).on("click", function () {
                        $this.find(bioPersonsTile).removeClass("hidden");
                        $this.css('overflow', 'auto');
                        $(this).addClass("hidden");
                    });
                });
            }
        };
        bioModule.init();
    };
    function HideModulesFuncInMobile() {
        var bioPersons = $(".bio-persons");
        var bioPersonsTile = $(".bio-persons-tile");
        var viewMoreButton = $(".bio-persons-view-more");
        var HideModules = {
            isMobile: function () {
                var isMobile = false;
                var windowWidth = $(window).width();
                var mobileBreakpoint = 767;
                if (windowWidth <= mobileBreakpoint) {
                    isMobile = true;
                }
                return isMobile;
            },
            hideBioModules: function () {
                if (isMobile()) {
                    bioPersons.each(function () {
                        var $this = $(this);
                        if (!($(this).find(bioPersonsTile).slice(4).first().hasClass("hidden"))) {
                            var $bioPersonsTile = $this.find(bioPersonsTile);
                            $this.find(bioPersonsTile).slice(4).addClass("hidden");
                            if ($bioPersonsTile.length > 4) {
                                $this.css('overflow', 'hidden');
                                $this.find(viewMoreButton).removeClass("hidden");
                            } else {
                                $this.css('overflow', 'auto');
                            }
                        }
                    });
                } else {
                    viewMoreButton.addClass("hidden");
                }
            }
        }
        HideModules.hideBioModules();
    };
    $(function () { BioModuleFunc(); HideModulesFuncInMobile(); });
    $(window).on("resize", function () { BioModuleFunc(); });
    $(window).on("orientationchange", function () { BioModuleFunc(); });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\WhyAccenture.js
/*  version="2" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.WhyAccentureModule = factory(jquery));
        };
    }
    else {
        root.WhyAccentureModule = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.WhyAccentureModule) {
$(function () {
                WhyAccentureModule.AddAnalyticsLinkTrackingAttribute();

            });

        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var AddAnalyticsLinkTrackingAttribute = function () {

        var clickableLinks = $("#why-accenture-carousel").find("a");
        var blockTitle = $.trim($('#why-accenture-carousel').parents(".ui-container").children('.block-title').text());
        var moduleArticleButton = $("#why-accenture-carousel").find("button");
        moduleArticleButton.attr({
            'data-analytics-link-name': moduleArticleButton.text().toLowerCase(),
            'data-analytics-content-type': 'cta'
        });

        for (var i = 0; i < clickableLinks.length; i++) {

            $(clickableLinks[i]).attr({
                "data-analytics-link-name": $(clickableLinks[i]).text(),
                'data-analytics-content-type': 'cta'
            });
        }
    };

    return {
        AddAnalyticsLinkTrackingAttribute: AddAnalyticsLinkTrackingAttribute
    };
}));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\PullQuote.js
/*  version="3" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.PullQuote = factory(jquery));
        }
    }
    else {
        root.PullQuote = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.PullQuote) {
            $(function () {
                PullQuote.setPullQuote();

            });

        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var setPullQuote = function () {

        var $pullQuote = $("div.component.pull-quote-margin");
        var $anchors = $pullQuote.find("a");
        for (i = 0; i < $anchors.length; i++) {
            if ($($anchors[i]).children("span").hasClass("DownloadItemTitle")) {
                $($anchors[i]).attr({ "data-linktype": "engagement", "data-analytics-link-name": $($anchors[i]).text().toLowerCase(), "data-analytics-content-type": "engagement" });
            }
            else if (!$($anchors[i]).children("span").hasClass("social-likes__icon")) {
                $($anchors[i]).attr({ "data-analytics-link-name": $($anchors[i]).text().toLowerCase(), "data-analytics-content-type": "cta" });
            }
        }
    };

    return {
        setPullQuote: setPullQuote
    };
}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\OptInModule.js
/*  version="2" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.OptInModule = factory(jquery));
        }
    }
    else {
        root.OptInModule = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.OptInModule) {
$(function () {
                OptInModule.setOptIn();

            });

 
        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var setOptIn = function () {

        var linkName = $("#module-email-alerts-optin").find("a").text().trim().toLowerCase();

        $("#module-email-alerts-optin").find("a").attr({ "data-analytics-link-name": linkName, "data-analytics-content-type": "cta"});
        
    };

    return {
        setOptIn: setOptIn
    };
}));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\SelfSelectionModule.js
/*  version="2" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.SelfSelectionModule = factory(jquery));
        }
    }
    else {
        root.SelfSelectionModule = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.SelfSelection) {
$(function () {
                SelfSelectionModule.setSelfSelection();
            });
        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var setSelfSelection = function () {

         var careersPackery = $('#careers_packery').find('.packery-component .module-article');
            for (var i = 1; i < careersPackery.length; i++) {
                if ($(careersPackery[i])[0].getElementsByClassName('self-selection').length) {
				   var tilePosition = i+1;
			    }
		     }

            var selfSelection = $('#careers_packery').find('.packery-component .module-article .self-selection');
            var contentType = selfSelection.find('p').text().toLowerCase() + '~' + tilePosition;
            selfSelection.find("button").attr('data-analytics-content-type', contentType);
            selfSelection.find("li > a").attr('data-analytics-content-type', contentType);
    };

    return {
        setSelfSelection: setSelfSelection
    };
}));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\CareersSignUpModule.js
/*  version="3" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.CareersSignUpModule = factory(jquery));
        }
    }
    else {
        root.CareersSignUpModule = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.CareersSignUpModule) {
            $(function () {
                CareersSignUpModule.setCareersSignUpModule();
            });

        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var setCareersSignUpModule = function () {

        //Adds data-analytics-template-zone to the CareersSignUp Block
        var $templateZone = $("#block-block");
        if ($templateZone.length > 0) {
            $templateZone.attr("data-analytics-template-zone", $templateZone.attr("id").toLowerCase());
        }

        //Adds data attributes to register and sign buttons in CareersSignUp Block
        var $moduleLinks = $(".sign-in-register-module a");
        for (var i = 0; i < $moduleLinks.length; i++) {
            if ($moduleLinks.length > 0) {
                $moduleLinks.eq(i).attr({ "data-analytics-link-name": $moduleLinks.eq(i).text().trim().toLowerCase(), "data-analytics-content-type": "call to action", "analytics-no-content-click": "true" });
                if ($moduleLinks.eq(i).text().toLowerCase().replace(/[^a-zA-Z0-9+]/g, "").indexOf("signin") >= 0) {
                    $moduleLinks.eq(i).attr("data-analytics-content-type", "sign in/out");
                }
            }
        }
    };

    return {
        setCareersSignUpModule: setCareersSignUpModule
    };
}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\reinvent-location.js
/*  version="73" */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], function (jquery) {
            return (root.ReinventLocation = factory(jquery));
        });
    }
    else {
        root.ReinventLocation = factory(root.jQuery, root.jsUtility);
    }
}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {
    var $reinventLocationModule = $('.reinvent-locations-hero-module');
    var $reinventLocationForm = $('.reinvent-location-hero-content-container');
    var $reinventLocationKeyword = $('.reinvent-locations-hero-module .reinvent-location-keywords');
    var $reinventLocationButton = $('.reinvent-locations-hero-module .reinvent-location-button');
    var $locationResultBlock = $(".reinvent-location-result-area");
    var $noResultsBlock = $locationResultBlock.find('.no-result-block');
    var $resultLocationHeader = $locationResultBlock.find(".country-header");
    var $locationResultText = $locationResultBlock.find(".location-result-text");
    var $regionTagHref = $resultLocationHeader.find('.region-tag-link');
    var $officeLocationResultsArea = $('.office-location-results-area');
    var keyword = "";
    var SearchQuery = "";
    var queryString = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
    var urlParams = "";
    var lastKeyword = "";
    var officeLocationResultArea = "";
    var isWithHeader = true;
    var redirectionQuery = "";
    var $locationSearchForKeyword = $('.reinvent-location-result-area .reinvent-location-search-for-keyword');

    var isKeywordCountryWithState = false;
    var isKeywordCountryWithoutState = false;
    var isKeywordState = false;
    var isKeywordRegion = false;

    // Collection of loaded locations
    var model = {
        region: [],
        country: [],
        results: []
    };

    //Alt Txt for office location
    var altTxtInternal = "Internal office image for";
    var altTxtExternal = "External office image for";
    var altTxtMap = "map";

    var duplicateLocations = [];

    // Lazy-Loading Variables
    var lazyLoadOfficeLocations;
    var returnSize = 150;
    var enableLazyLoad = false;
    var totalHits = 0;
    var totalResultsRetrieved = 0;
    var currentResultsRetrieved = 0;
    var searchTypeEnum = {
        Office: 0,
        Geo: 1
    };
    var locationHeight = 0;

    //Map & GetDirection Variables
    var bingMapGenericLink = "https://www.bing.com/maps?cp=@lat~@lon&amp;lvl=18&amp;style=r&amp;sp=point.@lat_@lon_@locationName";
    var getDirectionsLink = "https://www.bing.com/maps?rtp=~pos.@lat_@lon_@locationName&amp;cp=@lat~@lon&amp;lvl=18&amp;style=r&amp;sp=point.@lat_@lon";
    var mapEmbedImageLinkGroupList = "https://dev.virtualearth.net/REST/v1/Imagery/Map/Road/@query?ms=335,190&amp;zl=3&amp;&amp;c=en-US&amp;he=1&amp;key=Av8n4HG3gyMUjosR2nE-4lvj9nhmbb5Ntw6AzCKWIaTwLHJwPsDXN1Ny4crU6IFT";
    var mapLink = '/{0}/about/locations/office-location-map?lat=@lat&lon=@lon';
    var getDirectionMobileLink = '/{0}/about/locations/office-location-map?lat=@lat&lon=@lon&da=@da';
    var resultDetails = {};

    $reinventLocationForm.on('submit', function () {
        event.preventDefault();
        AppendToQuery($reinventLocationKeyword.typeahead('val'));
    });

    $reinventLocationKeyword.on('keyup', function (event) {
        var $suggestionDropdown = $('.reinvent-locations-hero-module .tt-dataset-keywordSuggestions .tt-suggestions');

        if (!$locationResultBlock.is(':visible')) {
            $reinventLocationButton.attr('href', $reinventLocationModule.attr('data-attribute-hero-home-link').replace('{0}', siteName));
            $reinventLocationButton.attr('href', $reinventLocationButton.attr('href'));
        }

        if (event.keyCode === 27) {
            $suggestionDropdown.hide();
        }

        if (event.keyCode === 38 || event.keyCode === 40) {
            $suggestionDropdown.show();
        }
    });

    $(window).on("scroll", function () {

        if (enableLazyLoad === true) {
            var locationContainerTop, locationScrollTop;
            var scrolledFromTop, visibleHeight;

            locationContainerTop = $(".office-location-details-container").offset().top;
            locationScrollTop = $(window).scrollTop();
            locationHeight = $(".office-location-details-container").height();
            scrolledFromTop = locationScrollTop - locationContainerTop;
            visibleHeight = document.documentElement.clientHeight;

            if (visibleHeight + scrolledFromTop >= locationHeight) {
                enableLazyLoad = false;
                if (lazyLoadOfficeLocations === true) {

                    GetOfficeLocations();
                }
            }
        }
    });

    $(window).on("resize", function () {
        var $officeDetails = $(".reinvent-location-result-area .office-locations-details");
        var $groupList = $(".reinvent-location-result-area .office-group-list .office-locations-details");
        var $officeWebsiteHeader = $(".reinvent-location-result-area .visit-website-header-container");
        var $regionTagLink = $resultLocationHeader.find('.region-tag-link');
        var $officeDetailsCard = $(".reinvent-location-result-area .office-locations-details-card");
        var index = 0;

        if ($locationResultBlock.length !== 0) {
            AdjustResultsContainerPadding();

            if ($regionTagLink) {
                $regionTagLink.each(function () {
                    if (jsUtility.isMobile()) {
                        $(this).css("padding-bottom", "0");
                    } else {
                        $(this).removeAttr("style");
                    }
                });
            }

            if ($officeDetailsCard && $groupList.length === 0) {
                $officeDetailsCard.each(function () {
                    var $mapsContainer = $(this).find(".maps-container");
                    var $officeDetailsContainer = $(this).find(".office-locations-details");
                    //For Maps LG|MD|SM
                    var bingMapGenericLinkWithDetails = bingMapGenericLink.replace(/@lat/g, resultDetails[index].latitude).replace(/@lon/g, resultDetails[index].longitude).replace("@locationName", resultDetails[index].locationname);
                    //For Maps XS
                    var mapContainerLink = mapLink.replace("{0}", GetGeo()).replace(/@lat/g, resultDetails[index].latitude).replace(/@lon/g, resultDetails[index].longitude);
                    if (jsUtility.isMobile()) {
                        if (resultDetails[index].latitude && resultDetails[index].longitude) {
                            $mapsContainer.find('a').attr('href', mapContainerLink);
                        }
                        $mapsContainer.after($officeDetailsContainer);
                    } else {
                        if (resultDetails[index].latitude && resultDetails[index].longitude) {
                            $mapsContainer.find('a').attr('href', bingMapGenericLinkWithDetails);
                        }
                        $mapsContainer.before($officeDetailsContainer);
                    }
                    index += 1;
                });
                index = 0;
            }


            if ($officeDetails && $groupList.length == 0) {
                $officeDetails.each(function () {
                    var $addressContainer = $(this).find(".address-container");
                    var $contactContainer = $(this).find(".contact-container");
                    var $officeDetailsLink = $(this).find(".office-details-link");
                    var $getDirectionLink = $(this).find(".get-directions-container");
                    var $visitWebsiteLink = $(this).find(".website-link-container");
                    //For GetDirection LG|MD|SM
                    var getDirectionsLinkWithDetails = getDirectionsLink.replace(/@lat/g, resultDetails[index].latitude).replace(/@lon/g, resultDetails[index].longitude).replace("@locationName", resultDetails[index].locationname);
                    //For GetDirection XS
                    var cleanedOfficeName = resultDetails[index].locationname !== "" ? (resultDetails[index].locationname).replace(/^Accenture\s/i, '') : "";
                    var getDirectionContainerLink = getDirectionMobileLink.replace("{0}", GetGeo()).replace(/@lat/g, resultDetails[index].latitude).replace(/@lon/g, resultDetails[index].longitude).replace(/@da/g, cleanedOfficeName);

                    if (resultDetails[index].latitude && resultDetails[index].longitude) {
                        $getDirectionLink.find('a').attr('href', getDirectionsLinkWithDetails)
                    }

                    if (!jsUtility.isTablet() && !jsUtility.isMobile()) {
                        $getDirectionLink.appendTo($officeDetailsLink);
                        $visitWebsiteLink.appendTo($officeDetailsLink);
                    } else {
                        if (jsUtility.isMobile() && (resultDetails[index].latitude && resultDetails[index].longitude)) {
                            $getDirectionLink.find('a').attr('href', getDirectionContainerLink)
                        }
                        $getDirectionLink.appendTo($addressContainer);
                        $visitWebsiteLink.appendTo($contactContainer);
                    }
                    index += 1;
                });
                index = 0;
            }

            if (jsUtility.isMobile() || jsUtility.isTablet()) {
                $(".reinvent-location-result-area .website-link-container").each(function () {
                    var $currentWebsiteLinkContainer = $(this);
                    var $phoneContainer = $currentWebsiteLinkContainer.siblings(".phone-container");
                    var $faxContainer = $currentWebsiteLinkContainer.siblings(".fax-container");
                    if ($phoneContainer.css("display") == "none" && $faxContainer.css("display") == "none") {
                        $currentWebsiteLinkContainer.css("padding-top", "0");
                    }
                });
            } else {
                $(".reinvent-location-result-area .website-link-container").each(function () {
                    var $currentWebsiteLinkContainer = $(this);
                    $attr = $currentWebsiteLinkContainer.attr("style");
                    if (typeof attr !== typeof undefined && attr !== false) {
                        $attr.removeAttr("style");
                    }
                });
            }
        }

    });

    $reinventLocationKeyword.on('typeahead:selected', function (e, datum) {
        var key = event.keyCode;
        if (key === 9) {
            $reinventLocationButton.trigger("focus");
        } else {
            AppendToQuery(datum.value);
        }
    });

    $reinventLocationButton.on('click', function () {
        if ($locationResultBlock.length === 0) {
            window.location.href = $reinventLocationButton.attr('href');
        }
    });

    var AppendToQuery = function (keyword) {
        redirectionQuery = keyword.trim() !== "" ? AddParameterURL(redirectionQuery, 'loc', jsUtility.ReplaceEncodedKeyword(RemoveKeywordTags(keyword))) : '';

        if ($locationResultBlock.length !== 0) {
            PreventDuplicateSearch();
        } else {
            window.location.href = $reinventLocationModule.attr('data-attribute-hero-home-link').replace('{0}', siteName) + redirectionQuery;

        }
        $reinventLocationKeyword.trigger("blur");
        CleanInputKeyword($reinventLocationKeyword.typeahead('val'));
    };

    $(document).on('click', '.reinvent-location-result-area .region-tag-link', function (event) {
        if (!($regionTagHref.text().indexOf('Location Home') >= 0)) {
            $reinventLocationKeyword.typeahead('val', $(this).text());
            PreventDuplicateSearch();
        }
    });

    $(document).on('keyup', '.reinvent-location-result-area .region-tag-link', function (event) {
        if (!($regionTagHref.text().indexOf('Location Home') >= 0)) {
            if (event.keyCode === 13) {
                $reinventLocationKeyword.typeahead('val', $(this).text());
                PreventDuplicateSearch();
            }
        }
    });

    var GetGeo = function () {
        var path = window.location.pathname;
        if (path) {
            var pathArray = path.split('/');
            path = pathArray[1];
        } else {
            path = "";
        }

        return path;
    };

    var PreventDuplicateSearch = function () {
        var locKeyword = RemoveKeywordTags($reinventLocationKeyword.val());
        $locationSearchForKeyword.html("Search for " + locKeyword + " is completed.");
        if (lastKeyword !== $reinventLocationKeyword.typeahead('val') && $locationResultBlock.length !== 0) {
            EmptyAndSpacesInput();
            DisplayLocationResults();
        }
    };

    var CleanInputKeyword = function (keyword) {
        keyword = RemoveKeywordTags(keyword);
        $("input.reinvent-location-keywords:text").val(keyword);
    };

    var EmptyAndSpacesInput = function () {
        if ($reinventLocationKeyword.typeahead('val').trim() !== "") {
            AppendToURL('loc', jsUtility.ReplaceEncodedKeyword(RemoveKeywordTags($reinventLocationKeyword.typeahead('val'))));
        } else {
            AppendToURL('', '');
        }
    };

    var RemoveParam = function (key, sourceURL) {
        var queryParams = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }
            queryParams = queryParams + "?" + params_arr.join("&");
        }
        return queryParams;
    };

    var AppendToURL = function (parameter, keyword) {
        keyword = RemoveKeywordTags(keyword);
        if (parameter === "" && keyword === "") {
            queryString = window.location.protocol + "//" + window.location.host + window.location.pathname + RemoveParam('loc', window.location.search);
            if (queryString.substr(-1) === '?') {
                queryString = queryString.replace('?', '');
            }
        } else {
            queryString = AddParameterURL(queryString, parameter, keyword);
        }
        window.history.pushState({ path: queryString }, '', queryString);
    };

    var AddParameterURL = function (url, param, value) {
        param = RemoveKeywordTags(param);
        var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
            qstring = /\?.+$/;

        // Check if the parameter exists
        if (val.test(url)) {
            return url.replace(val, '$1' + param + '=' + value);
        }
        else if (qstring.test(url)) {
            return url + '&' + param + '=' + value;
        } else {
            return url + '?' + param + '=' + value;
        }
    };

    var URLSearchParamsForIE = function () {
        (function (w) {

            w.URLSearchParams = w.URLSearchParams || function (searchString) {
                var self = this;
                self.searchString = searchString;
                self.get = function (name) {
                    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
                    if (results === null) {
                        return null;
                    }
                    else {
                        return decodeURIComponent(results[1]) || 0;
                    }
                };
            };

        })(window);
    };

    var IconHoverForOtherBrowsers = function (index) {
        if (IsIE()) {
            $(".office-details-link-" + index + " .get-directions-container a").removeClass("cta");
            $(".office-details-link-" + index + " .website-link-container a").removeClass("cta");
        }
    };

    //display location results through search
    var DisplayLocationResults = function () {
        var tabTitle = $('meta[property="og:title"]').attr('content');
        lastKeyword = RemoveKeywordTags($reinventLocationKeyword.typeahead('val'));
        if (lastKeyword === '<') {
            SearchQuery = lastKeyword;
        } else {
            SearchQuery = jsUtility.removeTags($reinventLocationKeyword.typeahead('val'));
        }
        totalResultsRetrieved = 0;
        if (SearchQuery.length >= 2) {
            keyword = SearchQuery;
            lazyLoadOfficeLocations = false;
            model = {
                region: [],
                country: [],
                results: []
            };
            GetOfficeLocations();
            $locationSearchForKeyword.removeAttr('aria-live');
        } else if (SearchQuery.length === 1) {
            ClearHeaderContent();
            NoResultsFound();
            $officeLocationResultsArea.empty();
            $noResultsBlock.removeClass("hide");
        } else {
            window.document.title = tabTitle;
            $officeLocationResultsArea.empty();
            ClearHeaderContent();
            $locationSearchForKeyword.attr('aria-live', 'off');
            $resultLocationHeader.find('.country-name-text').html("Country Name");
            $noResultsBlock.addClass("hide");
            $locationResultText.removeClass("hide");
            if ($locationResultText.is(':visible')) {
                $locationResultText.attr('tabindex', '0');
                if (IsIE() || jsUtility.isFirefox()) {
                    $locationResultText.on("focus", function () {
                        $locationResultText.css("outline", "none");
                    });
                }
                $locationResultText.trigger("focus");
                $locationResultText.removeAttr('tabindex');
            }
        }
    };

    // Gets locations
    var GetOfficeLocations = function () {

        if (jsUtility.removeTags($reinventLocationKeyword.typeahead('val')) !== keyword) {
            return;
        }

        $.ajax({
            url: '/api/sitecore/LocationsHeroModule/GetLocation',
            data: {
                query: RemoveKeywordTags(keyword),
                from: totalResultsRetrieved,
                size: returnSize,
                language: language
            },
            contentType: "application/json; charset=utf-8",
            type: "GET",
            dataType: "json",
            cache: false,
            error: function () {

            },
            success: function (data) {
                var results = model.results;

                if (lazyLoadOfficeLocations === true) {
                    results[0].documents = results[0].documents.concat(data.documents);
                } else {
                    results.push(data);
                }

                DisplayLocations(results[0].documents);
                FocusElement();

                if (lazyLoadOfficeLocations === true) {
                    $(window).scrollTop(locationHeight);
                }

                if (data && data.documents.length > 0) {
                    ProcessLazyLoadingVariables(data.documents.length, data.total, searchTypeEnum.Office);
                }
            }
        });
    };

    var FocusElement = function () {
        var $officeLocationDetails = $officeLocationResultsArea.find('.office-details-0');

        if ($noResultsBlock.is(':visible')) {
            $noResultsBlock.attr('tabindex', '0');
            if (IsIE() || jsUtility.isFirefox()) {
                $noResultsBlock.on("focus", function () {
                    $noResultsBlock.css("outline", "none");
                });
            }
            $noResultsBlock.trigger("focus");
            $noResultsBlock.removeAttr('tabindex');
        } else if ($resultLocationHeader.is(':visible')) {
            $resultLocationHeader.attr('tabindex', '0');
            if (IsIE() || jsUtility.isFirefox()) {
                $resultLocationHeader.on("focus", function () {
                    $resultLocationHeader.css("outline", "none");
                });
            }
            $resultLocationHeader.trigger("focus");
            $resultLocationHeader.removeAttr('tabindex');
        } else if ($officeLocationDetails.is(':visible')) {
            $officeLocationDetails.attr('tabindex', '0');
            if (IsIE() || jsUtility.isFirefox()) {
                $officeLocationDetails.on("focus", function () {
                    $officeLocationDetails.css("outline", "none");
                });
            }
            $officeLocationDetails.trigger("focus");
            $officeLocationDetails.removeAttr('tabindex');
        }
    };

    var ProcessLazyLoadingVariables = function (numberOfDocumentsReceived, totalNumberOfHits, searchType) {
        lazyLoadOfficeLocations = false;

        totalHits = totalNumberOfHits;
        currentResultsRetrieved = numberOfDocumentsReceived;
        totalResultsRetrieved += currentResultsRetrieved;
        if (totalResultsRetrieved > 0 && totalResultsRetrieved < totalHits) {
            enableLazyLoad = true;

            if (searchType === searchTypeEnum.Office) {
                lazyLoadOfficeLocations = true;
            }
        }
        else {
            enableLazyLoad = false;
        }
    };

    var CapitalizeKeyword = function (keyword) {
        keyword = RemoveKeywordTags($('.reinvent-location-keywords').val()).toLowerCase();
        var orginalKeyword = keyword.split(' ');
        var capKeyword = [];
        for (var x = 0; x < orginalKeyword.length; x++) {
            capKeyword.push(orginalKeyword[x].charAt(0).toUpperCase() + orginalKeyword[x].slice(1));
            newKeyword = capKeyword.join(' ');
        }
        return newKeyword;
    };

    function dynamicSort(property) {
        var sortOrder = 1;

        if (property[0] === "-") {
            sortOrder = -1;
            property = property.substr(1);
        }

        return function (a, b) {
            if (a[property] != null && b[property] != null) {
                if (sortOrder == -1) {
                    return b[property].localeCompare(a[property]);
                } else {
                    return a[property].localeCompare(b[property]);
                }
            }
        }
    };

    var DisplayLocations = function (data) {
        var isExactSearch = false;
        var tabTitle = $('meta[property="og:title"]').attr('content');
        var appendKeyword = CapitalizeKeyword(keyword);

        if (data) {
            data = data.filter(function (item) {
                return item.ReinventRegion !== null && item.ReinventRegion !== "";
            });
        }

        if (data && data.length > 0) {
            window.document.title = appendKeyword + " " + tabTitle;

            ClearHeaderContent();
            $officeLocationResultsArea.empty();

            if (data.length === 1) {
                isExactSearch = IsExactSearch(data[0]);
            }

            isKeywordRegion = IsKeywordRegion(data);
            isKeywordCountryWithState = IsKeywordCountryWithState(data);
            isKeywordCountryWithoutState = IsKeywordCountryWithoutState(data);
            isKeywordState = IsKeywordState(data);

            if (isExactSearch === true || (isKeywordRegion === false && isKeywordCountryWithState === false && isKeywordState === false && isKeywordCountryWithoutState === false)) {
                isWithHeader = false;
                $resultLocationHeader.find('.country-name-text').html("Country Name");
                if ((isKeywordRegion === true || isKeywordCountryWithState === true || isKeywordState === true || isKeywordCountryWithoutState === true)) {
                    isWithHeader = true;
                }
            } else {
                isWithHeader = true;
            }


            if (!isKeywordRegion) {
                $regionTagHref.removeAttr('href');
            }

            if ((isKeywordRegion === true)) {
                officeLocationResultArea = document.createElement("div");
                $(officeLocationResultArea).addClass("office-group-list col-xs-12");
                $(".office-location-results-area").append(officeLocationResultArea);

                data.sort(dynamicSort("Country"));

                for (var index = 0; index < data.length; index++) {
                    var tempRegion = data[index].ReinventRegion;

                    if (tempRegion !== null && tempRegion !== "" && tempRegion == appendKeyword) {
                        if ($.inArray(data[index].Country, duplicateLocations) == -1) {
                            if (isWithHeader === true) {
                                ShowHeaderContent();
                                LocationBlockHeader(data[index], data[index].Country, data[index].ReinventRegion, data[index].CountryURL, data[index].ContactUsURL);
                            }
                            duplicateLocations.push(data[index].Country);
                            CountryList(data[index], index);
                        }
                    }
                }
            }
            else if ((isKeywordCountryWithState === true)) {
                officeLocationResultArea = document.createElement("div");
                $(officeLocationResultArea).addClass("office-group-list col-xs-12");
                $(".office-location-results-area").append(officeLocationResultArea);

                data.sort(dynamicSort("StateProvince"));

                for (index = 0; index < data.length; index++) {
                    tempRegion = data[index].Country;

                    if (tempRegion !== null && tempRegion !== "" && appendKeyword) {
                        if ($.inArray(data[index].StateProvince, duplicateLocations) == -1) {
                            if (isWithHeader === true) {
                                ShowHeaderContent();
                                LocationBlockHeader(data[index], data[index].Country, data[index].ReinventRegion, data[index].CountryURL, data[index].ContactUsURL);
                            }
                            StateList(data[index], index);
                            duplicateLocations.push(data[index].StateProvince);
                        }
                    }
                }
            }
            else if ((isKeywordCountryWithoutState === true)) {
                officeLocationResultArea = document.createElement("div");
                $(officeLocationResultArea).addClass("office-location-details-container col-xs-12");
                $(".office-location-results-area").append(officeLocationResultArea);


                for (index = 0; index < data.length; index++) {
                    tempRegion = data[index].Country;

                    if (tempRegion !== null && tempRegion !== "" && appendKeyword) {
                        if (tempRegion.toLowerCase() == appendKeyword.toLowerCase()) {
                            if ($.inArray(data[index].StateProvince, duplicateLocations) == -1) {
                                if (isWithHeader === true) {
                                    ShowHeaderContent();
                                    LocationBlockHeader(data[index], data[index].Country, data[index].ReinventRegion, data[index].CountryURL, data[index].ContactUsURL);
                                }
                                LocationDetails(data[index], index);
                                duplicateLocations.push(idstate + "-" + idcity + "-" + data[index].LocationName + "-" + data[index].Address);
                            }
                        }

                    }
                }
            }

            else if ((isKeywordState === true)) {
                officeLocationResultArea = document.createElement("div");
                $(officeLocationResultArea).addClass("office-location-details-container col-xs-12");
                $(".office-location-results-area").append(officeLocationResultArea);


                for (index = 0; index < data.length; index++) {
                    tempRegion = data[index].StateProvince;

                    if (tempRegion !== null && tempRegion !== "" && appendKeyword) {
                        if (tempRegion.toLowerCase() == appendKeyword.toLowerCase()) {
                            if ($.inArray(data[index].StateProvince, duplicateLocations) == -1) {
                                if (isWithHeader === true) {
                                    ShowHeaderContent();
                                    LocationBlockHeader(data[index], data[index].Country, data[index].ReinventRegion, data[index].CountryURL, data[index].ContactUsURL);
                                }
                                LocationDetails(data[index], index);
                                duplicateLocations.push(idstate + "-" + idcity + "-" + data[index].LocationName + "-" + data[index].Address);
                            }
                        }

                    }
                }
            }

            else {
                officeLocationResultArea = document.createElement("div");
                $(officeLocationResultArea).addClass("office-location-details-container col-xs-12");
                $(".office-location-results-area").append(officeLocationResultArea);


                for (index = 0; index < data.length; index++) {
                    tempRegion = data[index].ReinventRegion;
                    var idstate = (data[index].StateProvince != null) ? data[index].StateProvince.replace(/\s+/g, '') : "nostate";
                    var idcity = (data[index].CityName) ? data[index].CityName.replace(/\s+/g, '') : "";

                    if (tempRegion !== null && tempRegion !== "") {
                        if ($.inArray(idstate + "-" + idcity + "-" + data[index].LocationName + "-" + data[index].Address, duplicateLocations) == -1) {
                            if (isWithHeader === true) {
                                ShowHeaderContent();
                                LocationBlockHeader(data[index], data[index].Country, data[index].ReinventRegion, data[index].CountryURL, data[index].ContactUsURL);
                            }
                            LocationDetails(data[index], index);
                            duplicateLocations.push(idstate + "-" + idcity + "-" + data[index].LocationName + "-" + data[index].Address);
                        }
                    }
                }
            }
            if (isWithHeader === true) {
                UpateLocationHeader();
            } else {
                $(".reinvent-location-result-area .office-location-results-block-container-0").css("margin-top", "0");
            }
        }
        else {
            window.document.title = tabTitle;
            ClearHeaderContent();
            $officeLocationResultsArea.empty();
            NoResultsFound();
        }
        duplicateLocations = [];
    };

    var UpateLocationHeader = function () {
        $(".office-location-results-area .office-name").each(function () {
            var currentClassValue = this.attributes[0].value;
            $(this).replaceWith("<h3 class='" + currentClassValue + "'>" + $(this).html() + "</h3>");
        });
    };

    var IsExactSearch = function (data) {

        var compiledResult = data.Address + data.CityName + data.LocationName + data.ContactFax + data.ContactTel;
        var keywordFound = compiledResult.replace(/ +/g, "").toLowerCase().indexOf(SearchQuery.replace(/ +/g, "").toLowerCase());
        var dataCountry = data.Country;

        if (dataCountry.toLowerCase() !== SearchQuery.toLowerCase()) {
            if (isKeywordState === false && IsKeywordCountryWithState === false && isKeywordRegion === false) {
                ClearHeaderContent();
                return true;
            } else if (keywordFound >= 0) {
                ClearHeaderContent();
                return true;
            }
        }

        return false;
    };

    var IsKeywordCountryWithState = function (data) {

        var localModel = {
            country: [],
            state: []
        };

        for (var index = 0; index < data.length; index++) {
            var currentCountry = data[index].Country;
            var currentState = data[index].StateProvince;
            if ($.inArray(currentCountry, localModel.country) === -1) {
                localModel.country.push(currentCountry);
            }
            if (currentState) {
                if ($.inArray(currentState, localModel.state) === -1) {
                    localModel.state.push(currentCountry);
                }
            }
        }

        if (localModel.country.length === 1 && localModel.state.length > 0) {
            if (SearchQuery.toLowerCase() === localModel.country[0].toLowerCase()) {
                return true;
            }
        }

        return false;

    };

    var IsKeywordCountryWithoutState = function (data) {

        var localModel = {
            country: [],
            state: []
        };

        for (var index = 0; index < data.length; index++) {
            var currentCountry = data[index].Country;
            var currentState = data[index].StateProvince;

            if (lastKeyword === currentCountry || lastKeyword.toLowerCase() === currentCountry.toLowerCase()) {
                if ($.inArray(currentCountry, localModel.country) === -1) {
                    localModel.country.push(currentCountry);
                }
                if (currentState) {
                    if ($.inArray(currentState, localModel.state) === -1) {
                        localModel.state.push(currentState);
                    }
                }
            }
        }

        if (localModel.country.length === 1 && localModel.state.length === 0) {
            if (SearchQuery.toLowerCase() === localModel.country[0].toLowerCase()) {
                return true;
            }
        }

        return false;

    };
    var IsKeywordState = function (data) {

        var localModel = {
            country: [],
            state: []
        };

        for (var index = 0; index < data.length; index++) {
            var currentCountry = data[index].Country;
            var currentState = data[index].StateProvince;

            if (currentState && lastKeyword.toLowerCase() === currentState.toLowerCase()) {
                if (currentCountry) {
                    if ($.inArray(currentCountry, localModel.country) === -1) {
                        localModel.country.push(currentCountry);
                    }
                }

                if (currentState) {
                    if ($.inArray(currentState, localModel.state) === -1) {
                        localModel.state.push(currentState);
                    }
                }
            }
        }

        if (localModel.state.length === 1 && localModel.country.length === 1) {
            if (SearchQuery.toLowerCase() === localModel.state[0].toLowerCase()) {
                return true;
            }
        }

        return false;
    };

    var IsKeywordRegion = function (data) {

        var isRegion = false;
        var excludeRegionIndex = [];

        for (var index = 0; index < data.length; index++) {
            var currentRegion = data[index].ReinventRegion;
            if (currentRegion && SearchQuery.toLowerCase()) {
                if (SearchQuery.toLowerCase() === currentRegion.toLowerCase()) {
                    isRegion = true;
                } else {
                    excludeRegionIndex.push(index);
                }
            }
        }

        if (isRegion === true) {
            for (var i = 0; i < excludeRegionIndex.length; i++) {
                data[i].ReinventRegion = "";
            }
        }

        return isRegion;

    };

    var LocationBlockHeader = function (state, country, reinventregion, countryurl, contactusurl) {
        var countryName = country;
        var regionTag = reinventregion;
        var stateTag = state.StateProvince;
        var countryURL = countryurl;
        var contactusURL = contactusurl;
        var countryHome = "";
        var $countryNameText = $resultLocationHeader.find('.country-name-text');
        var $regionTagLink = $resultLocationHeader.find('.region-tag-link');
        var $visitWebsiteLink = $resultLocationHeader.find('.visit-website-header-container');
        var $contactUsLink = $resultLocationHeader.find('.contact-us-header-container');
        var dictionaryLocationsHome = $(".office-location-results-translations").attr('data-attribute-location-home');
        var regionTagElement = document.createElement("a");
        var regionTagDivider = document.createElement("span");

        countryHome = $resultLocationHeader.attr('data-attribute-home-link').replace("{0}", GetGeo());

        CreateContactUs(countryName, contactusURL);
        CreateVisitWebsite(countryName, countryURL);

        $countryNameText.html(countryName);
        $regionTagLink.html(regionTag);
        $regionTagLink.attr("tabindex", 0);
        $regionTagLink.attr('data-analytics-content-type', 'engagement');
        $regionTagLink.attr('data-linktype', 'engagement');
        $regionTagLink.attr('data-analytics-link-name', regionTag);
        $regionTagLink.attr("role", 'button');
        $regionTagLink.attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", countryName));

        $(".region-tag-divider").remove();
        $(".region-tag2").remove();

        $resultLocationHeader.find('#visitWebsite').css("display", "none");

        if (isKeywordRegion === true) {
            $countryNameText.text(regionTag);
            $regionTagLink.empty().text(dictionaryLocationsHome);
            $regionTagLink.attr('data-analytics-link-name', dictionaryLocationsHome.toLowerCase());
            $regionTagLink.attr("href", countryHome);
            $regionTagLink.attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", dictionaryLocationsHome));
            $contactUsLink.hide();
            $visitWebsiteLink.hide();
        } else if (isKeywordState === true) {
            $(regionTagDivider).attr("class", "region-tag-divider");
            $(regionTagElement).attr("class", "corporate-semibold topic-link region-tag-link region-tag2");
            $(regionTagElement).attr("tabindex", 0);
            $(regionTagElement).attr('data-analytics-content-type', 'engagement');
            $(regionTagElement).attr('data-linktype', 'engagement');
            $(regionTagElement).attr('data-analytics-link-name', regionTag);
            $(regionTagElement).attr('role', 'button');
            $(regionTagElement).attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", regionTag));

            $regionTagLink.removeAttr("href");
            $countryNameText.text(stateTag);
            $regionTagLink.text(countryName);
            $regionTagLink.attr('data-analytics-link-name', countryName);
            $(regionTagElement).text(regionTag);
            $(regionTagDivider).append("&nbsp;•&nbsp;");
            $(regionTagDivider).insertAfter(".region-tag-link");
            $(regionTagElement).insertAfter(".region-tag-divider");
            $contactUsLink.show();
            $visitWebsiteLink.show();
            if (jsUtility.isMobile()) {
                $resultLocationHeader.find('.region-tag-link').each(function () {
                    $(this).css("padding-bottom", "0");
                });
            }
        } else if (isKeywordCountryWithState === true || isKeywordCountryWithoutState === true) {
            $regionTagLink.attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", regionTag));
            $regionTagLink.removeAttr("href");
            $countryNameText.text(countryName);
            $regionTagLink.text(regionTag);
            $regionTagLink.attr('data-analytics-link-name', regionTag);
            $contactUsLink.show();
            $visitWebsiteLink.show();
        } else {
            $contactUsLink.hide();
            $visitWebsiteLink.hide();
        }
    };

    var CreateContactUs = function (countryName, contactusURL) {

        var $headerContactUsText = $resultLocationHeader.attr('data-attribute-contact-us').replace('{0}', countryName);

        $resultLocationHeader.find('.contact-us').html($headerContactUsText);
        $resultLocationHeader.find('.contact-us-link').attr("href", contactusURL);
        $resultLocationHeader.find('.contact-us-link').attr('data-analytics-content-type', 'engagement');
        $resultLocationHeader.find('.contact-us-link').attr('data-linktype', 'engagement');
        $resultLocationHeader.find('.contact-us-link').attr('data-analytics-link-name', $headerContactUsText.toLowerCase());
    };

    var CreateVisitWebsite = function (countryName, countryURL) {

        var $headerVisitWebsiteText = $resultLocationHeader.attr('data-attribute-visit-website').replace('{0}', countryName);

        $resultLocationHeader.find('.visit-website').html($headerVisitWebsiteText);
        $resultLocationHeader.find('.visit-website-link').attr("href", countryURL);
        $resultLocationHeader.find('.visit-website-link').attr('data-analytics-content-type', 'engagement');
        $resultLocationHeader.find('.visit-website-link').attr('data-linktype', 'engagement');
        $resultLocationHeader.find('.visit-website-link').attr('data-analytics-link-name', $headerVisitWebsiteText.toLowerCase());
    };

    var $officeLocationResultsTranslations = $(".office-location-results-translations");

    var dictionaryOfficeLocationGrouplistAriaLabel = $officeLocationResultsTranslations.attr('data-attribute-location-office-group-list-aria-label');
    var dictionaryOfficeLocationImageGroupListAriaLabel = $officeLocationResultsTranslations.attr('data-attribute-location-office-image-group-list-aria-label');

    var LocationDetails = function (location, index) {

        var countryLink = $resultLocationHeader.attr('data-attribute-visit-website-link');
        var countryName = location.Country;
        var countryState = location.StateProvince;
        var countryStateCode = location.StateCode;
        var officeZipCode = location.PostalZipCode;
        var countryRegion = location.ReinventRegion;
        var officeContact = location.ContactTel;
        var officeFax = location.ContactFax;
        var locationURL = location.LocationURL;
        var _state = "";

        if (countryStateCode !== null) {
            if (countryName === "United States") {
                _state = ", " + countryStateCode + " ";
            } else if (countryName === "Canada" || countryName === "Australia") {
                _state = ", " + countryName + ", " + countryStateCode + ", ";
            } else {
                if (officeZipCode === null) {
                    officeZipCode = " ";
                    _state = ", " + countryName;
                } else {
                    _state = ", " + countryName;
                    officeZipCode = ", " + officeZipCode;
                }
            }
        } else {
            _state = " " + countryName;
        }
        if (countryState === null) {
            countryState = "";
        } else {
            countryState = countryState;
        }
        if (location.Address === null) {
            location.Address = "";
        }
        if (officeContact === null) {
            officeContact = "";
            lblPhone = "";
        }
        if (officeFax === null) {
            officeFax = "";
            lblFax = "";
        }
        if (location.LocationName === null) {
            location.LocationName = "";
        }
        if (location.Latitude === null) {
            location.Latitude = "";
        }
        if (location.Longitude === null) {
            location.Longitude = "";
        }
        if (location.CityName === null) {
            location.CityName = "";
        }
        if (location.InternalImageURL === null) {
            location.InternalImageURL = "";
        }
        if (location.ExternalImageURL === null) {
            location.ExternalImageURL = "";
        }
        if (location.ExternalImageAltTxt === null) {
            location.ExternalImageAltTxt = "";
        }
        if (location.InternallImageAltTxt === null) {
            location.InternallImageAltTxt = "";
        }
        resultDetails[index] = {
            longitude: location.Longitude,
            latitude: location.Latitude,
            locationname: location.LocationName
        };

        var dictionaryOfficeLocationAddress = $officeLocationResultsTranslations.attr('data-attribute-location-address');
        var dictionaryOfficeLocationContact = $officeLocationResultsTranslations.attr('data-attribute-location-contact');
        var dictionaryLocationGetDirection = $officeLocationResultsTranslations.attr('data-attribute-location-get-direction');
        var dictionaryOfficeLocationVisitWebsite = $officeLocationResultsTranslations.attr('data-attribute-location-visit-website');
        var dictionaryOfficeLocationVisitWebsiteAriaLabel = $officeLocationResultsTranslations.attr('data-attribute-location-visit-website-aria');
        var visitWebsiteAria = "";
        var officeLocationResultsBlockContainerIndex = '.office-location-results-block-container-' + (index);
        var officeLocationTagsContainer = '.office-location-tags-container-' + (index);
        var officeName = '.office-name-content-' + (index);
        var address = '.office-location-address-content-' + (index);
        var contactTel = '.office-location-contact-tel-content-' + (index);
        var contactFax = '.office-location-contact-fax-content-' + (index);
        var OfficeCountryContentValue = '.office-country-content-' + (index);
        var OfficeRegionContentValue = '.office-region-content-' + (index);
        var officeLocationContactContainer = ".office-location-contact-container-" + (index);
        var officeLocationResultsBlockContainer = ".office-location-results-block-container";
        var officeLocationAddressHeader = "<span class='address-header-text corporate-semibold'>";
        var getDirectionLinkAnalytics = "data-analytics-link-name='" + dictionaryLocationGetDirection.toLowerCase() + "' data-analytics-content-type='engagement' data-linktype='engagement'";
        var WebsiteLinkAnalytics = "data-analytics-link-name='" + dictionaryOfficeLocationVisitWebsite.toLowerCase() + "' data-analytics-content-type='engagement' data-linktype='engagement'";
        var MapAnalytics = "data-analytics-link-name='" + location.LocationName.toLowerCase() + " map' data-analytics-content-type='engagement' data-linktype='engagement'";
        var getDirectionIconAndLink = "<div class='get-directions-container col-md-6 col-lg-6'><a " + getDirectionLinkAnalytics + " aria-describedby ='instructionsForGetDirection-" + (index) + "' class='cta get-directions-cta'target='_blank'><i class='ion-ios-location'></i><span class='address-link-text corporate-regular'>";
        if (dictionaryOfficeLocationVisitWebsiteAriaLabel.length !== 0) {
            visitWebsiteAria = dictionaryOfficeLocationVisitWebsiteAriaLabel.replace("{0}", countryName);
        }
        var visitWebsiteIconAndLink = "<div class='website-link-container visit-website-link col-md-6 col-lg-6'><a aria-label = '" + visitWebsiteAria + "' class='cta visit-website-cta'" + WebsiteLinkAnalytics + " href=" + locationURL + "><i class='ion-android-desktop'></i><span class='website-link-text visit-website corporate-regular'>";
        var officeLocationPhoneContainer = "<a class='office-location-phone'><i class='ion-android-call'></i><span class='phone-basic-text contact-us corporate-regular'>";
        var officeLocationFaxContainer = "<a class='office-location-fax'><i class='ion-ios-paper'></i><span class='fax-basic-text corporate-regular'>";
        var officeLocationMapContentIndex = ".office-location-map-content-" + (index);
        var officeLocationAltTxt = dictionaryOfficeLocationAddress + ": " + location.Address;
        var ariaLabelGroup = dictionaryOfficeLocationImageGroupListAriaLabel.replace("{0}", location.LocationName);


        var officeLocationMapValue = "<a " + MapAnalytics + "aria-describedby='imageForMaps-" + (index) + "'target='_blank' class='maps-container col-xs-12 col-sm-6 office-location-map-content-" + (index) + " office-location-map-content' href='";
        var officeLocationDetails = ".office-details-" + (index);
        var officeLocationGetDirections = officeLocationDetails + " .get-directions-container a";

        jQuery('<div/>', {
            class: 'office-locations-details-card col-xs-12 office-location-results-block-container-' + (index)
        }).appendTo(officeLocationResultArea);

        if (jsUtility.isMobile()) {

            jQuery('<div/>', {
                class: "office-locations-details col-xs-12 col-sm-6 office-details-" + (index)
            }).appendTo(officeLocationResultsBlockContainerIndex);
        }
        else {

            jQuery('<div/>', {
                class: "office-locations-details col-xs-12 col-sm-6 office-details-" + (index)
            }).appendTo(officeLocationResultsBlockContainerIndex);

        }

        jQuery('<h2/>', {
            class: 'office-name corporate-semibold office-name-content-' + (index)
        }).appendTo(officeLocationDetails);

        jQuery('<div/>', {
            class: 'region-tag-container office-location-tags-container-' + (index)
        }).appendTo(officeLocationDetails);

        jQuery('<a/>', {
            class: 'region-tag corporate-semibold topic-link office-country-content-' + (index)
        }).appendTo(officeLocationTagsContainer);

        $(officeLocationTagsContainer).append("<span class='office-region-tag-divider region-divider-" + (index) + "'> • </span>");

        jQuery('<a/>', {
            class: 'region-tag corporate-semibold topic-link office-region-content-' + (index)
        }).appendTo(officeLocationTagsContainer);

        $(document).on('click', '.office-location-results-area .office-location-tags-container-' + (index) + ' a', function () {
            $reinventLocationKeyword.typeahead('val', $(this).text());
            PreventDuplicateSearch();
        });

        $(document).on('keyup', '.office-location-results-area .office-location-tags-container-' + (index) + ' a', function (event) {
            if (event.keyCode === 13) {
                $reinventLocationKeyword.typeahead('val', $(this).text());
                PreventDuplicateSearch();
            }
        });

        $(document).on('keyup', '.office-location-results-area .office-location-tags-container-' + (index) + ' a', function (event) {
            if (event.keyCode === 13) {
                $reinventLocationKeyword.typeahead('val', $(this).text());
                PreventDuplicateSearch();
            }
        });

        $(OfficeCountryContentValue).attr('data-analytics-content-type', 'engagement');
        $(OfficeCountryContentValue).attr('data-linktype', 'engagement');

        $(OfficeRegionContentValue).attr('data-analytics-content-type', 'engagement');
        $(OfficeRegionContentValue).attr('data-linktype', 'engagement');



        if (dictionaryOfficeLocationGrouplistAriaLabel.length !== 0) {
            countryNameAriaLabel = dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", countryName);
            countryRegionAriaLabel = dictionaryOfficeLocationGrouplistAriaLabel.replace("{0}", countryRegion);
        }

        if (isKeywordCountryWithState) {
            $(".region-divider-" + (index)).empty();
            $(OfficeCountryContentValue).text(countryState);
            $(OfficeCountryContentValue).attr('data-analytics-link-name', countryState);
            $(OfficeRegionContentValue).empty();
        } else if (isKeywordRegion) {
            if (!countryState || !countryName) {
                $(".region-divider-" + (index)).empty();
            }
            $(OfficeCountryContentValue).text(countryState);
            $(OfficeCountryContentValue).attr('data-analytics-link-name', countryState);
            $(OfficeRegionContentValue).text(countryName);
            $(OfficeRegionContentValue).attr('data-analytics-link-name', countryName);
        } else {
            if (!countryRegion || !countryName) {
                $(".region-divider-" + (index)).empty();
            }
            $(OfficeCountryContentValue).text(countryName);
            $(OfficeCountryContentValue).attr('data-analytics-link-name', countryName);
            $(OfficeRegionContentValue).text(countryRegion);
            $(OfficeRegionContentValue).attr('data-analytics-link-name', countryRegion);
        }
        $(OfficeCountryContentValue).attr('aria-label', countryNameAriaLabel);
        $(OfficeRegionContentValue).attr('aria-label', countryRegionAriaLabel);
        if ($(OfficeCountryContentValue).text().length !== 0 && $(OfficeRegionContentValue).text().length !== 0) {
            $(OfficeCountryContentValue).attr('tabindex', '0');
            $(OfficeCountryContentValue).attr('role', 'button');
            $(OfficeRegionContentValue).attr('tabindex', '0');
            $(OfficeRegionContentValue).attr('role', 'button');
        } else if ($(OfficeCountryContentValue).text().length !== 0 && $(OfficeRegionContentValue).text().length === 0) {
            $(OfficeCountryContentValue).attr('tabindex', '0');
            $(OfficeCountryContentValue).attr('role', 'button');
            $(OfficeRegionContentValue).removeAttr('tabindex');
            $(OfficeRegionContentValue).removeAttr('role', 'button');
        } else if ($(OfficeRegionContentValue).text().length !== 0 && $(OfficeCountryContentValue).text().length === 0) {
            $(OfficeRegionContentValue).attr('tabindex', '0');
            $(OfficeRegionContentValue).attr('role', 'button');
            $(OfficeCountryContentValue).removeAttr('tabindex');
            $(OfficeCountryContentValue).removeAttr('role', 'button');
        }

        jQuery('<div/>', {
            class: 'address-container col-sm-12 col-xs-12 col-md-6 col-lg-6 office-location-address-content-' + (index)
        }).appendTo(officeLocationDetails);

        $(address).append(officeLocationAddressHeader + dictionaryOfficeLocationAddress + "</span>");

        $(address).append("<div class='address'>" + location.Address + ", " + location.CityName + _state + officeZipCode + "</div>");


        $(officeLocationResultsBlockContainer).append(officeLocationAddressHeader + dictionaryOfficeLocationContact + "</div>");

        jQuery('<div/>', {
            class: 'contact-container col-sm-12 col-xs-12 col-md-6 col-lg-6 office-location-contact-container-' + (index)
        }).appendTo(officeLocationDetails);

        jQuery('<div/>', {
            class: "office-details-link col-md-12 col-lg-12 office-details-link-" + (index)
        }).appendTo(officeLocationDetails);

        if (officeContact || officeFax) {
            $(officeLocationContactContainer).append("<span class='contact-header-text corporate-semibold'>" + dictionaryOfficeLocationContact + "</span>");
        } else {
            if (jsUtility.isMobile() || jsUtility.isTablet()) {
                $(officeLocationContactContainer).find(".website-link-container").css("padding-top", "0");
            }
        }

        jQuery('<div/>', {
            class: 'phone-container contact-us-link office-location-contact-tel-content-' + (index),
            'data-analytics-link-name': officeContact,
            'data-analytics-content-type': 'engagement',
            'data-linktype': 'engagement'
        }).appendTo(officeLocationContactContainer);

        if (officeContact) {
            $(contactTel).append(officeLocationPhoneContainer + officeContact + "</span></a>");
        } else {
            $(contactTel).hide();
        }

        jQuery('<div/>', {
            class: 'fax-container office-location-contact-fax-content-' + (index),
            'data-analytics-link-name': officeFax,
            'data-analytics-content-type': 'engagement',
            'data-linktype': 'engagement'
        }).appendTo(officeLocationContactContainer);

        if (officeFax) {
            $(contactFax).append(officeLocationFaxContainer + officeFax + "</span></a>");
        } else {
            $(contactFax).hide();
        }

        if (!jsUtility.isTablet() && !jsUtility.isMobile()) {
            $(".office-details-link-" + (index)).append(getDirectionIconAndLink + dictionaryLocationGetDirection + "</span></a></div>");
            $(".office-details-link-" + (index)).append(visitWebsiteIconAndLink + dictionaryOfficeLocationVisitWebsite + "</span></a></div>");
        } else {
            $(address).append(getDirectionIconAndLink + dictionaryLocationGetDirection + "</span></a></div>");
            if (location.Country) {
                $(officeLocationContactContainer).append(visitWebsiteIconAndLink + dictionaryOfficeLocationVisitWebsite + "</span></a></div>");
            }
        }

        IconHoverForOtherBrowsers(index);
        $(officeName).text(location.LocationName);

        var mapEmbedImageLink = "https://dev.virtualearth.net/REST/V1/Imagery/Map/Road/@lat%2C@long/15?mapSize=520,220&amp;format=png&amp;pushpin=@lat,@long;37;&amp;key=Av8n4HG3gyMUjosR2nE-4lvj9nhmbb5Ntw6AzCKWIaTwLHJwPsDXN1Ny4crU6IFT";
        var mapEmbedImageLinkWithDetails = mapEmbedImageLink.replace(/@lat/g, location.Latitude).replace(/@long/g, location.Longitude);
        //For LG|MD|SM
        var bingMapGenericLinkWithDetails = bingMapGenericLink.replace(/@lat/g, location.Latitude).replace(/@lon/g, location.Longitude).replace("@locationName", location.LocationName);
        var getDirectionsLinkWithDetails = getDirectionsLink.replace(/@lat/g, location.Latitude).replace(/@lon/g, location.Longitude).replace("@locationName", location.LocationName);
        //For XS
        var mapContainerLink = mapLink.replace("{0}", GetGeo()).replace(/@lat/g, location.Latitude).replace(/@lon/g, location.Longitude);
        var cleanedOfficeName = (location.LocationName).replace(/^Accenture\s/i, '');
        var getDirectionContainerLink = getDirectionMobileLink.replace("{0}", GetGeo()).replace(/@lat/g, location.Latitude).replace(/@lon/g, location.Longitude).replace(/@da/g, cleanedOfficeName);

        jQuery('<span/>', {
            class: 'sr-only',
            id: 'instructionsForGetDirection-' + (index),
            html: 'this will open the map to ' + location.LocationName + ', ' + dictionaryOfficeLocationAddress + ': ' + location.Address + ' in a new window',
            style: 'display: none'
        }).appendTo($(officeLocationGetDirections));


        function displaySingleImage() {
            var imgType = location.ExternalImageURL !== "" ? "Internal" : location.InternalImageURL !== "" ? "External" : "Map";
            var altTxt = location.ExternalImageURL !== "" ? location.ExternalImageAltTxt : location.InternalImageURL !== "" ? location.InternalImageAltTxt : officeLocationAltTxt + " " + altTxtMap;

            if (imgType !== "Map") {

                var imgSrc = location.ExternalImageURL !== "" ? location.ExternalImageURL : location.InternalImageURL !== "" ? location.InternalImageURL : mapEmbedImageLinkWithDetails;
                var imgInternalExternalClass = location.ExternalImageURL !== "" ? "office-locations-external-img-only" : location.InternalImageURL !== "" ? "office-locations-internal-img-only" : "";

                $(officeLocationResultsBlockContainerIndex).append(officeLocationMapValue + bingMapGenericLinkWithDetails + "'>" + "<div role='group' aria-label='" + ariaLabelGroup + "' class='" + 'image-group-list-' + index + "'>" + "<img src='" + mapEmbedImageLinkWithDetails + "' class='office-locations-map-internal-external-image hidden-xs'></img> </div> </a>");
                $('.image-group-list-' + index + ' .office-locations-map-internal-external-image').attr('alt', officeLocationAltTxt + " " + altTxtMap);

                var OfficeLocationMapImage = $(officeLocationResultsBlockContainerIndex).find(".image-group-list-" + (index));
                $('.office-location-results-block-container-' + index + ' .maps-container').css('height', cardHeight + "px");

                $('.office-location-results-block-container-' + index + ' .image-group-list-' + index).css('height', cardHeight + "px");

                OfficeLocationMapImage.append("<img src='" + imgSrc + "' role='presentation' class='" + imgInternalExternalClass + "' alt ='" + altTxt + "' ></img>");

            }
            else {

                $(officeLocationResultsBlockContainerIndex).append(officeLocationMapValue + bingMapGenericLinkWithDetails + "'>" + "<img src='" + mapEmbedImageLinkWithDetails + "' class='office-locations-map-image' alt ='" + location.LocationName + ", " + officeLocationAltTxt + " " + altTxtMap + "'></img></a>");
            }
        };

        var cardHeight = $(".office-location-results-block-container-" + (index)).height();
        if (mapEmbedImageLinkWithDetails || getDirectionsLinkWithDetails) {
            if (location.Latitude && location.Longitude) {
                if (!jsUtility.isMobile()) {

                    if (jsUtility.isTablet()) {
                        if (location.ExternalImageURL !== "" && location.InternalImageURL !== "") {
                            $(officeLocationResultsBlockContainerIndex).append(officeLocationMapValue + bingMapGenericLinkWithDetails + "'>" + "<div role='group'  aria-label='" + ariaLabelGroup + "' class='" + 'image-group-list-' + index + "'>" + "<img src='" + mapEmbedImageLinkWithDetails + "' class='office-locations-map-internal-external-image'></img> </div> </a>");
                            $('.image-group-list-' + index + ' .office-locations-map-internal-external-image').attr('alt', officeLocationAltTxt + " " + altTxtMap);

                            var OfficeLocationMapImage = $(officeLocationResultsBlockContainerIndex).find(".image-group-list-" + (index));

                            OfficeLocationMapImage.append("<img src='" + location.InternalImageURL + "' class='office-locations-internal-image' role='presentation' alt ='" + location.InternalImageAltTxt + "' > </img>");
                            OfficeLocationMapImage.append("<img src='" + location.ExternalImageURL + "' class='office-locations-external-image' role='presentation' alt ='" + location.ExternalImageAltTxt + "' > </img>");
                            $('.office-location-results-block-container-' + index + ' .maps-container').css('height', cardHeight + "px");

                            $('.office-location-results-block-container-' + index + ' .image-group-list-' + index).css('height', cardHeight + "px");

                        }
                        else if (location.ExternalImageURL == "" || location.InternalImageURL == "") {
                            displaySingleImage();
                        }
                    }
                    else {
                        if (location.ExternalImageURL !== "" && location.InternalImageURL !== "") {

                            $(officeLocationResultsBlockContainerIndex).append(officeLocationMapValue + bingMapGenericLinkWithDetails + "'>" + "<div role='group'  aria-label='" + ariaLabelGroup + "' class='" + 'image-group-list-' + index + "'>" + "<img src='" + mapEmbedImageLinkWithDetails + "' class='office-locations-map-internal-external-image hidden-xs'></img> </div> </a>");
                            $('.image-group-list-' + index + ' .office-locations-map-internal-external-image').attr('alt', officeLocationAltTxt + " " + altTxtMap);

                            var OfficeLocationMapImage = $(officeLocationResultsBlockContainerIndex).find(".image-group-list-" + (index));

                            OfficeLocationMapImage.append("<img src='" + location.ExternalImageURL + "' class='office-locations-external-image' role='presentation' alt ='" + location.ExternalImageAltTxt + "' > </img>");
                            OfficeLocationMapImage.append("<img src='" + location.InternalImageURL + "' class='office-locations-internal-image hidden-xs' role='presentation' alt ='" + location.InternalImageAltTxt + "' > </img>");

                            $('.office-location-results-block-container-' + index + ' .maps-container').css('height', cardHeight + "px");

                            $('.office-location-results-block-container-' + index + ' .image-group-list-' + index).css('height', cardHeight + "px");


                        }
                        else if (location.ExternalImageURL == "" || location.InternalImageURL == "") {
                            displaySingleImage();
                        }

                    }
                }
                else {

                    var imgSrc = location.ExternalImageURL !== "" ? location.ExternalImageURL : location.InternalImageURL !== "" ? location.InternalImageURL : mapEmbedImageLinkWithDetails;
                    var altTxt = location.ExternalImageURL !== "" ? altTxtExternal + " " + ariaLabelGroup + " " + officeLocationAltTxt : location.InternalImageURL !== "" ? altTxtInternal + " " + ariaLabelGroup + " " + officeLocationAltTxt : ariaLabelGroup + " " + officeLocationAltTxt + " " + altTxtMap;

                    $(officeLocationResultsBlockContainerIndex).prepend(officeLocationMapValue + bingMapGenericLinkWithDetails + "'>" + "<img src='" + imgSrc + "' class='office-locations-map-image'></img></a>");
                    $('.office-location-results-block-container-' + (index) + ' .office-locations-map-image').attr('alt', altTxt);

                }

                jQuery('<span/>', {
                    class: 'sr-only',
                    id: 'imageForMaps-' + (index),
                    html: 'this will open the map in a new window'
                }).appendTo($('.office-location-results-area .office-location-results-block-container-' + (index)));

                if (jsUtility.isMobile()) {
                    $(officeLocationGetDirections).attr('href', getDirectionContainerLink);
                } else {
                    $(officeLocationGetDirections).attr('href', getDirectionsLinkWithDetails);
                }
            }

            if (jsUtility.isMobile()) {
                var $bingMapMobileLink = $('.office-location-results-area .office-location-map-content');
                if ($bingMapMobileLink) {
                    $(officeLocationMapContentIndex).find($bingMapMobileLink).attr('href', mapContainerLink);
                }
            }
        }

        if (officeContact !== null) {
            LocationDetailsContactTelForMobiles(officeContact, index);
        }

        if (officeFax !== null) {
            LocationDetailsContactFaxForMobiles(officeFax, index);
        }
    };

    var CountryList = function (location, index) {

        var countryName = location.Country;

        var officeLocationResultsBlockContainerIndex = '.office-location-results-block-container-' + (index);
        var officeLocationTagsContainer = '.office-location-tags-container-' + (index);
        var OfficeCountryContentValue = '.office-country-content-' + (index);
        var mapOfficeLocation = ".office-location-map-content-" + (index);
        var mapEmbedImageLinkGroupListWithDetails = mapEmbedImageLinkGroupList.replace(/@query/g, encodeURIComponent(countryName));
        var cardLinkContainer = ".country-tag-container-" + (index);

        if (countryName == "Argentina") {
            mapEmbedImageLinkGroupListWithDetails = mapEmbedImageLinkGroupList.replace(/@query/g, "Argentina,Brazil");
        }

        if (countryName !== null) {
            jQuery('<div/>', {
                class: 'office-locations-details-card col-xs-12 col-sm-6 col-md-4 office-location-results-block-container-' + (index)
            }).appendTo(officeLocationResultArea);

            if (jsUtility.isMobile()) {

                jQuery('<a/>', {
                    class: 'office-group-list-link country-tag-container-' + (index)
                }).appendTo(officeLocationResultsBlockContainerIndex);

            }
            else {

                jQuery('<a/>', {
                    class: 'office-group-list-link country-tag-container-' + (index),
                    href: 'javascript:void(0)'

                }).appendTo(officeLocationResultsBlockContainerIndex);

                jQuery('<span/>', {
                    class: 'maps-container  hidden-xs office-location-map-content-' + (index)
                }).appendTo(cardLinkContainer);
                $(mapOfficeLocation).append("<img src='" + mapEmbedImageLinkGroupListWithDetails + "'></img>");
                var imageCountryMaps = $(mapOfficeLocation).find("img");
                imageCountryMaps.attr('alt', countryName + ' Map');
            }


            jQuery('<div/>', {
                class: 'region-tag-container office-location-tags-container-' + (index)
            }).appendTo(cardLinkContainer);

            if (!$('html').hasClass("ie")) {
                jQuery('<span/>', {
                    class: 'sr-only hidden',
                    id: 'country' + (index)
                }).appendTo(cardLinkContainer);
            }

            jQuery('<h3/>', {
                class: 'region-tag corporate-semibold office-country-content-' + (index)
            }).appendTo(officeLocationTagsContainer);

            $(document).on('click', '.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index), function () {
                var countryTagLink = $('.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index)).find('.office-location-tags-container-' + (index));
                $reinventLocationKeyword.typeahead('val', $(countryTagLink).text());
                PreventDuplicateSearch();
            });

            $(document).on('keyup', '.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index), function (event) {
                if (event.keyCode === 13) {
                    var countryTagLink = $('.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index)).find('.office-location-tags-container-' + (index));
                    $reinventLocationKeyword.typeahead('val', $(countryTagLink).text());
                    PreventDuplicateSearch();
                }
            });



            $(mapOfficeLocation).attr('data-analytics-content-type', 'engagement');
            $(mapOfficeLocation).attr('data-linktype', 'engagement');
            $(OfficeCountryContentValue).attr('data-analytics-content-type', 'engagement');
            $(OfficeCountryContentValue).attr('data-linktype', 'engagement');

            if ($('html').hasClass("ie")) {

                $('.office-group-list-link.country-tag-container-' + (index)).attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace('{0}', countryName));

            } else {
                $OfficeCountryViewLocation = $('#country' + (index));
                $(OfficeCountryContentValue).attr('aria-labelledby', 'country' + (index));
                $OfficeCountryViewLocation.text(dictionaryOfficeLocationGrouplistAriaLabel.replace('{0}', countryName));
            }
            $(OfficeCountryContentValue).text(countryName);
            $(OfficeCountryContentValue).attr('data-analytics-link-name', countryName);

            $(cardLinkContainer).attr('data-analytics-content-type', 'engagement');
            $(cardLinkContainer).attr('data-linktype', 'engagement');
            $(cardLinkContainer).attr('data-analytics-link-name', countryName);

            IconHoverForOtherBrowsers(index);
        }

    };

    var StateList = function (location, index) {

        var stateName = location.StateProvince;

        var officeLocationResultsBlockContainerIndex = '.office-location-results-block-container-' + (index);
        var officeLocationTagsContainer = '.office-location-tags-container-' + (index);
        var OfficeCountryContentValue = '.office-country-content-' + (index);
        var mapOfficeLocation = ".office-location-map-content-" + (index);
        var mapEmbedImageLinkGroupListWithDetails = mapEmbedImageLinkGroupList.replace(/@query/g, encodeURIComponent(stateName));
        var cardLinkContainer = ".country-tag-container-" + (index);


        if (stateName !== null) {
            jQuery('<div/>', {
                class: 'office-locations-details-card col-xs-12 col-sm-6 col-md-4 office-location-results-block-container-' + (index)
            }).appendTo(officeLocationResultArea);

            if (jsUtility.isMobile()) {

                jQuery('<a/>', {
                    class: 'office-group-list-link country-tag-container-' + (index)
                }).appendTo(officeLocationResultsBlockContainerIndex);

            }
            else {

                jQuery('<a/>', {
                    class: 'office-group-list-link country-tag-container-' + (index),
                    href: 'javascript:void(0)'

                }).appendTo(officeLocationResultsBlockContainerIndex);

                jQuery('<span/>', {
                    class: 'maps-container  hidden-xs office-location-map-content-' + (index)
                }).appendTo(cardLinkContainer);
                $(mapOfficeLocation).append("<img src='" + mapEmbedImageLinkGroupListWithDetails + "'></img>");
                var imageStateMaps = $(mapOfficeLocation).find("img");
                imageStateMaps.attr('alt', stateName + ' Map');
            }


            jQuery('<div/>', {
                class: 'region-tag-container office-location-tags-container-' + (index)
            }).appendTo(cardLinkContainer);

            if (!$('html').hasClass("ie")) {
                jQuery('<span/>', {
                    class: 'sr-only hidden',
                    id: 'state' + (index)
                }).appendTo(cardLinkContainer);
            }

            jQuery('<h3/>', {
                class: 'region-tag corporate-semibold office-country-content-' + (index)
            }).appendTo(officeLocationTagsContainer);


            $(document).on('click', '.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index), function () {
                var countryTagLink = $('.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index)).find('.office-location-tags-container-' + (index));
                $reinventLocationKeyword.typeahead('val', $(countryTagLink).text());
                PreventDuplicateSearch();
            });

            $(document).on('keyup', '.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index), function (event) {
                if (event.keyCode === 13) {
                    var countryTagLink = $('.office-location-results-area .office-group-list .office-locations-details-card .country-tag-container-' + (index)).find('.office-location-tags-container-' + (index));
                    $reinventLocationKeyword.typeahead('val', $(countryTagLink).text());
                    PreventDuplicateSearch();
                }
            });

            $(mapOfficeLocation).attr('data-analytics-content-type', 'engagement');
            $(mapOfficeLocation).attr('data-linktype', 'engagement');
            $(OfficeCountryContentValue).attr('data-analytics-content-type', 'engagement');
            $(OfficeCountryContentValue).attr('data-linktype', 'engagement');

            $(OfficeCountryContentValue).text(stateName);
            $(OfficeCountryContentValue).attr('data-analytics-link-name', stateName);

            if ($('html').hasClass("ie")) {
                $('.office-group-list-link.country-tag-container-' + (index)).attr('aria-label', dictionaryOfficeLocationGrouplistAriaLabel.replace('{0}', stateName));
            }
            else {
                $OfficeCountryViewLocation = $('#state' + (index));
                $(OfficeCountryContentValue).attr('aria-labelledby', 'state' + (index));
                $OfficeCountryViewLocation.text(dictionaryOfficeLocationGrouplistAriaLabel.replace('{0}', stateName));
            }
            $(cardLinkContainer).attr('data-analytics-content-type', 'engagement');
            $(cardLinkContainer).attr('data-linktype', 'engagement');
            $(cardLinkContainer).attr('data-analytics-link-name', stateName);


            IconHoverForOtherBrowsers(index);
        }



    };

    var ClearHeaderContent = function () {
        $resultLocationHeader.find('.country-name-text').html("");
        $resultLocationHeader.find('.region-tag-link').html("");
        $resultLocationHeader.find('.contact-us').html("");
        $resultLocationHeader.find('.visit-website').html("");
        $resultLocationHeader.addClass("hide");
        $locationResultText.addClass("hide");
        $noResultsBlock.addClass("hide");
        $resultLocationHeader.find('.contact-us-link').removeAttr("href");
        $resultLocationHeader.find('.visit-website-link').removeAttr("href");

    };

    var ShowHeaderContent = function () {
        $resultLocationHeader.removeClass("hide");
    };

    var NoResultsFound = function () {

        var noResultsLabel = $noResultsBlock.attr('data-attribute-no-results-label');
        var noResultsText = $noResultsBlock.attr('data-attribute-no-results-text');

        $locationSearchForKeyword.attr('aria-live', 'off');
        $locationResultText.addClass("hide");
        $resultLocationHeader.find('.country-name-text').html("Country Name");
        $noResultsBlock.find('.no-result-label').html(noResultsLabel);
        $noResultsBlock.find('.no-result-text').html(noResultsText);
        $noResultsBlock.removeClass("hide");
    };

    var LocationDetailsContactTelForMobiles = function (contactTelNumber, index) {
        var officeLocationPhoneContainer = "<i class='ion-android-call'></i><span class='phone-basic-text contact-us corporate-regular' style='color: #004DFF;'>";
        var $officeLocationTelForMobile = $(".office-location-contact-tel-content-" + index).find(".office-location-phone");

        if (jsUtility.isMobileBrowser()) {
            $officeLocationTelForMobile.empty();
            $officeLocationTelForMobile.prepend('<a class="mobileContactTel-' + index + '" href="tel:' + contactTelNumber + '">' + officeLocationPhoneContainer + contactTelNumber + '</a>');
        }
    };

    var LocationDetailsContactFaxForMobiles = function (contactFaxNumber, index) {
        var officeLocationFaxContainer = "<i class='ion-ios-paper'></i><span class='fax-basic-text corporate-regular' style='color: #004DFF;'>";
        var $officeLocationFaxForMobile = $(".office-location-contact-fax-content-" + index).find(".office-location-fax");

        if (jsUtility.isMobileBrowser()) {
            $officeLocationFaxForMobile.empty();
            $officeLocationFaxForMobile.prepend('<a class="mobileContactFax-' + index + '" href="tel:' + contactFaxNumber + '">' + officeLocationFaxContainer + contactFaxNumber + '</a>');
        }
    };

    var AdjustResultsContainerPadding = function () {
        var blockContainerPadding = parseFloat($locationResultBlock.parents(".block-content").css("padding-left"));
        var blockContainerMargin = parseInt($locationResultBlock.parents(".row").css("margin-left"));
        var lgMinWidth = 1200;

        if (window.innerWidth >= (lgMinWidth + blockContainerPadding)) {
            if (!IsIE() && (window.innerWidth === 1280 && (blockContainerMargin < 15))) {
                $locationResultBlock.css({ "padding": ("0 " + ((15 - blockContainerMargin) + "px")) });
            }
            else {
                $locationResultBlock.css({ "padding": "0" });
            }
        }
        else {
            $locationResultBlock.removeAttr("style");
        }
    };

    var RemoveKeywordTags = function (keyword) {
        var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
        var tagOrComment = new RegExp('\\s*<(?:' + '!--(?:(?:-*[^->])*--+|-?)' + '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' + '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' + '|/?[a-z]' + tagBody + ')>', 'gi');
        var excludedCharacters = /[`%$^*()_+\=\[\]{}\\|<>\/~]/;
        var isKeywordUnclean;

        if (keyword) {
            var oldKeyword;
            do {
                oldKeyword = keyword;
                keyword = keyword.replace(tagOrComment, '').trim();
                isKeywordUnclean = excludedCharacters.test(keyword);
                if (isKeywordUnclean) {
                    keyword = keyword.replace(/[`%$^*()_+\=\[\]{}\\|<>\/~]/g, '');
                    return keyword;
                }
            } while (keyword !== oldKeyword);
            return keyword.replace(/&nbsp;|'&nbsp;'|'&nbsp'|"&nbsp;"|"&nbsp"|&nbsp|/g, '').trim();
        }
        return "";
    };

    $reinventLocationKeyword.typeahead({
        hint: false,
        highlight: true,
        minLength: 2
    },
        {
            name: 'keywordSuggestions',
            displayKey: 'value',
            source: function (query, response) {
                return $.getJSON(
                    '/api/sitecore/LocationsHeroModule/GetLocationSuggestion',
                    {
                        query: RemoveKeywordTags(query),
                        language: language,
                        size: maxAutocompleteItems
                    },
                    function (data) {
                        for (var i = 0; i < data.length; i++) {
                            data[i] = data[i].replace(/ *\[^]*\) */g, "");
                        }

                        var output = $.map(data, function (string) { return { value: string }; });

                        response(output.slice(0, 5));
                    });
            }
        });

    $(function () {
        AdjustResultsContainerPadding();
        if ($reinventLocationKeyword.length !== 0) {
            URLSearchParamsForIE();
            urlParams = new URLSearchParams(window.location.search);

            if (window.location.search !== "" && window.location.search.indexOf("loc=") !== -1) {
                var urlKey = RemoveKeywordTags(urlParams.get('loc'));
                $reinventLocationKeyword.typeahead('val', urlKey);
                AppendToQuery(urlKey);
                ClearHeaderContent();
                DisplayLocationResults();
            } else {
                $locationResultText.removeClass('hide');
            }

            if ($locationResultBlock.length === 0 && $reinventLocationModule.attr('data-attribute-hero-home-link') !== "") {
                $reinventLocationButton.attr('href', $reinventLocationModule.attr('data-attribute-hero-home-link').replace('{0}', siteName));
                if ($reinventLocationModule !== 0)
                    $reinventLocationButton.attr('aria-describedby', 'instructions-index');
            }

            else {
                $reinventLocationButton.removeAttr('aria-describedby');
            }

            var $locationsDropdownMenu = $('.reinvent-location-hero-content-container .tt-dropdown-menu');

            $locationsDropdownMenu.addClass('col-xs-12 col-lg-11');
        }
    });
}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\ctaBlogPost.js
//version=*7*
if (ComponentRegistry.CTABlogPostModule) {
    $(function () {
        var carouselIndicator = $('.carousel-indicators li');
        var contentRead = $('.carousel-inner .item');

        if (typeof acncCTABlogPost === "undefined") {
            acncCTABlogPost = new CTABlogPostObject();
            acncCTABlogPost.CTABlogPost.Init();
        }

        $('.blogPostCallToActionLink').on("keypress", function (e) {
            if (e.which == 13) {
                $(this).trigger("click");
                //autofocus
                var attrdatatoggle = $(this).attr('data-toggle');
                if (typeof attrdatatoggle !== typeof undefined && attrdatatoggle !== false && attrdatatoggle == "modal") {
                    var datatarget = $(this).attr('data-target');
                    setTimeout(function () {
                        $(datatarget).focus();
                    }, 400);

                }
            }
        });

        $('.blogPostCallToActionLink').on("click", function (e) {
            var attrdatatoggle = $(this).attr('data-toggle');
            if (typeof attrdatatoggle !== typeof undefined && attrdatatoggle !== false && attrdatatoggle == "modal") {
                var datatarget = $(this).attr('data-target');
                setTimeout(function () {
                    $(datatarget).focus();
                }, 400);
            }

        });
        $('.carousel-indicators li').on("keypress", function (e) {
            if (e.which == 13) {
                $(this).trigger("click");
            }
        });

        //lost focus
        $(".carousel-indicators li:last-child").focusout(function () {
            $(".btnModalClose").focus();
        });

        $('.content-area p:nth-child(2) span').wrap("<h3></h3>");
        
        //SPACE AND ENTER
        carouselIndicator.each(function () {
            if ($(this).hasClass("active")) {
                $(this).attr('aria-selected', 'true');
                    } else {
                        $(this).attr('aria-selected', 'false');
            }

            $(this).on("keypress", function (e) {
                var charCode = e.which || e.keycode;
				//enter
                if (charCode == 13) {
                    carouselIndicator.each(function () {
                        $(this).attr('aria-selected', 'false');
                    });
                    $(this).attr('aria-selected', 'true');
					//content reading
                    setTimeout(function () {
                        contentRead.each(function () {
                            if ($(this).hasClass('next left') || $(this).hasClass('prev right')) {
                                $(this).attr('aria-hidden', 'false');
                            } else {
                                $(this).attr('aria-hidden', 'true');
                            }
                        });
		            }, 4);
	            }
            });
            //tab
            $(this).on("keyup", function (e) {
                var charCode = e.which || e.keycode;
                if (charCode == 9) {
                    if ($(this).hasClass("active")) {
                        $(this).attr('aria-selected', 'true');
                    } else {
                        $(this).attr('aria-selected', 'false');
                    }
                }
            });

			//onclick
            $(this).on("click", function () {
				carouselIndicator.each(function () {
                    $(this).attr('aria-selected', 'false');
			});
				$(this).attr('aria-selected', 'true');
				setTimeout(function () {
					contentRead.each(function () {
                        if ($(this).hasClass('next left') || $(this).hasClass('prev right')) {
                            $(this).attr('aria-hidden', 'false');
                        } else {
                            $(this).attr('aria-hidden', 'true');
                        }
                    });
                }, 4);
			});
        });    
	});
}

function CTABlogPostObject() {
    var acncComponent = this;

    acncComponent.CTABlogPost = {
        Init: function () {
            acncComponent.CTABlogPost.Render();
        },
        Data: {

        },
        Render: function () {
            //Associate Modal to each Blog Post Component
            var ctaBlogPost = $(".blog-article-module,.module-article.a-countdown");
            var ctaBlogPostCount = 1;

            if (ctaBlogPost.length > 0) {
                var callToActionLinkSelector = $('.blogPostCallToActionLink');
                var ctaBlogPostModalSelector = $('.modal');
                var ctaBlogPostCarouselModalSelector = $('.modal #carousel-modal');
                var ctaBlogPostCarouselModalIndicatorsSelector = $('.modal #carousel-modal .carousel-indicators li');
                var callToActionLink = "";
                var ctaBlogPostModal = "";
                var ctaBlogPostCarouselModal = "";
                var ctaBlogPostCarouselModalIndicator = "";

                ctaBlogPost.each(function () {
                    //Distinct modal ID for CallToActionLink
                    callToActionLink = $(this).find(callToActionLinkSelector);
                    if ((typeof callToActionLink !== "undefined") && (callToActionLink != null)) {
                        callToActionLink.attr("data-target", "#ctaBlogPostModal" + ctaBlogPostCount);
                    }

                    //Distinct ID for modal
                    ctaBlogPostModal = $(this).find(ctaBlogPostModalSelector);
                    if ((typeof ctaBlogPostModal !== "undefined") && (ctaBlogPostModal != null)) {
                        ctaBlogPostModal.attr("id", "ctaBlogPostModal" + ctaBlogPostCount);
                    }

                    //Distinct ID for carousel-modal and pagination data-target
                    ctaBlogPostCarouselModal = $(this).find(ctaBlogPostCarouselModalSelector);
                    if ((typeof ctaBlogPostCarouselModal !== "undefined") && (ctaBlogPostCarouselModal != null)) {
                        ctaBlogPostCarouselModal.attr("id", "carousel-modal" + ctaBlogPostCount);

                        //Distinct ID for carousel-modal and pagination data-target				
                        ctaBlogPostCarouselModalIndicator = $(this).find(ctaBlogPostCarouselModalIndicatorsSelector);
                        if ((typeof ctaBlogPostCarouselModalIndicator !== "undefined") && (ctaBlogPostCarouselModalIndicator != null)) {
                            ctaBlogPostCarouselModalIndicator.each(function () {
                                $(this).attr("data-target", "#carousel-modal" + ctaBlogPostCount);
                            });
                        }
                    }

                    //Distinct modal ID no. for Modal
                    ctaBlogPostCount++;
                });

                //Transfer all CTA Blog Post Modal to Body
                if (ctaBlogPost.find(ctaBlogPostModalSelector).length > 0) {
                    ctaBlogPost.find(ctaBlogPostModalSelector).each(function () {
                        $(this).appendTo('body');
                    });
                }
            }
        }
    }

}

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\ctaMobileAlert.js
// version=”3”
var CTAMobileAlert = (function (window, $) {
    var _settings = {
        signUpBtn: $("#btnMobileAlertSignUp"),
        goBackBtn: $("#btnMobileAlertGoBack"),
        signUpSection: $("#sectionMobileAlertSignUp"),
        thankYouSection: $("#sectionMobileAlertThankYou"),
        pageHeaderBody: $(".hero-article .header-body")
    };

    var me = {};

    function setupBindings() {
        //do UI bindings
        _settings.goBackBtn.on("click", function () {
            var targetUrl = $(this).attr("data-targetUrl");
            window.location = targetUrl;
        });
    }

    function renderMobileAlert() {
        //hides Page subtitle in mobile
        if (($("#sectionMobileAlertSignUp").length > 0) && ($("#sectionMobileAlertThankYou").length > 0)) {
            if (_settings.pageHeaderBody.length > 0) {
                $(".hero-article .header-body").addClass("hidden-xs");
            }
        }
    }

    function loadMobileAlertPage() {

            $(document).ready(function () {
                validateMobileAlert();
            });       
    }


    function validateMobileAlert() {
        $('#mobileAlertsForm').bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                phone_number: {
                    validators: {
                        callback: {
                            message: '',
                            callback: function (value, validator, $field) {
                                var validationResult = IsMobileNumberValid(value, validator);
                                if (!validationResult.valid) {
                                    var validatorContainer = $('.validatorMessage [data-bv-validator-for="phone_number"]');
                                    validator.updateStatus('phone_number', validator.STATUS_INVALID, 'identical');
                                    $(validatorContainer).text(validationResult.message);
                                }
                                else {
                                    $(validatorContainer).text("");
                                    validator.updateStatus('phone_number', validator.STATUS_VALID, 'identical');
                                }
                                return validationResult.valid;
                            }
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
                // Use Ajax to submit form data
                $.ajax({
                    url: "/api/sitecore/CTAMobileAlertModule/SaveOptInSubscription",
                    async: false,
                    type: "POST",
                    data: JSON.stringify({ mobileNumber: $("#countryCode").val() + $("#mobileNumber").val() }),
                    contentType: "application/json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log("error encountered");
                    },
                    success: function (jsonOutput, textStatus, jqXHR) {
                        if (jsonOutput[0].OptInResult == true) {
                            if (($("#sectionMobileAlertSignUp").length > 0) && ($("#sectionMobileAlertThankYou").length > 0)) {
                                $("#sectionMobileAlertSignUp").hide();
                                $("#sectionMobileAlertThankYou").show();
                            }
                        }
                    }
                });
            }
        }).on('success.form.fv', function (e) {

        });
    }

    // Validates if the number provided is valid
    function IsMobileNumberValid(value, validator) {
        var validationResult = { valid: false, message: '' };
        var regExpValidator = new RegExp("^[0-9]*$");

        if (value == '') {
            validationResult.message = $("#validationTranslations").attr("data-blank");
            return validationResult;
        }

        if (!regExpValidator.test(value)) {
            validationResult.message = $("#validationTranslations").attr("data-format");;
            return validationResult;
        }

        if (value.length > 10) {
            validationResult.message = $("#validationTranslations").attr("data-length");;
            return validationResult;
        }

        $.ajax({
            url: "/api/sitecore/CTAMobileAlertModule/IsMobileNumberValid",
            async: false,
            type: "POST",
            data: JSON.stringify({ mobileNumber: $("#countryCode").val() + value }),
            contentType: "application/json",
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("error encountered");
            },
            success: function (jsonOutput, textStatus, jqXHR) {
                if (jsonOutput[0].ValidationSuccess == false) {
                    validationResult.valid = false;
                    validationResult.message = "Validation Failed";
                }
                else {
                    validationResult.valid = jsonOutput[0].IsNumberValid;
                    validationResult.message = jsonOutput[0].ErrorMessage;
                }
            }
        });

        return validationResult;
    }

    me.init = function () {
        setupBindings();
        renderMobileAlert();
        loadMobileAlertPage();
    }

    return me;
}(window, jQuery));

if (ComponentRegistry.CTAMobileAlertModule) {
    CTAMobileAlert.init();
}


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.dotdotdot.js
/* version="1" */
/*
 *	jQuery dotdotdot 1.7.5
 *
 *	Copyright (c) Fred Heusschen
 *	www.frebsite.nl
 *
 *	Plugin website:
 *	dotdotdot.frebsite.nl
 *
 *	Licensed under the MIT license.
 *	http://en.wikipedia.org/wiki/MIT_License
 */

(function( $, undef )
{
	if ( $.fn.dotdotdot )
	{
		return;
	}

	$.fn.dotdotdot = function( o )
	{
		if ( this.length == 0 )
		{
			$.fn.dotdotdot.debug( 'No element found for "' + this.selector + '".' );
			return this;
		}
		if ( this.length > 1 )
		{
			return this.each(
				function()
				{
					$(this).dotdotdot( o );
				}
			);
		}


		var $dot = this;
		var orgContent	= $dot.contents();

		if ( $dot.data( 'dotdotdot' ) )
		{
			$dot.trigger( 'destroy.dot' );
		}

		$dot.data( 'dotdotdot-style', $dot.attr( 'style' ) || '' );
		$dot.css( 'word-wrap', 'break-word' );
		if ($dot.css( 'white-space' ) === 'nowrap')
		{
			$dot.css( 'white-space', 'normal' );
		}

		$dot.bind_events = function()
		{
			$dot.on(
				'update.dot',
				function( e, c )
				{
					$dot.removeClass("is-truncated");
					e.preventDefault();
					e.stopPropagation();

					switch( typeof opts.height )
					{
						case 'number':
							opts.maxHeight = opts.height;
							break;

						case 'function':
							opts.maxHeight = opts.height.call( $dot[ 0 ] );
							break;

						default:
							opts.maxHeight = getTrueInnerHeight( $dot );
							break;
					}

					opts.maxHeight += opts.tolerance;

					if ( typeof c != 'undefined' )
					{
						if ( typeof c == 'string' || ('nodeType' in c && c.nodeType === 1) )
						{
					 		c = $('<div />').append( c ).contents();
						}
						if ( c instanceof $ )
						{
							orgContent = c;
						}
					}

					$inr = $dot.wrapInner( '<div class="dotdotdot" />' ).children();
					$inr.contents()
						.detach()
						.end()
						.append( orgContent.clone( true ) )
						.find( 'br' )
						.replaceWith( '  <br />  ' )
						.end()
						.css({
							'height'	: 'auto',
							'width'		: 'auto',
							'border'	: 'none',
							'padding'	: 0,
							'margin'	: 0
						});

					var after = false,
						trunc = false;

					if ( conf.afterElement )
					{
						after = conf.afterElement.clone( true );
					    after.show();
						conf.afterElement.detach();
					}

					if ( test( $inr, opts ) )
					{
						if ( opts.wrap == 'children' )
						{
							trunc = children( $inr, opts, after );
						}
						else
						{
							trunc = ellipsis( $inr, $dot, $inr, opts, after );
						}
					}
					$inr.replaceWith( $inr.contents() );
					$inr = null;

                    if (typeof opts.callback === "function")
					{
						opts.callback.call( $dot[ 0 ], trunc, orgContent );
					}

					conf.isTruncated = trunc;
					return trunc;
				}

			).on(
				'isTruncated.dot',
				function( e, fn )
				{
					e.preventDefault();
					e.stopPropagation();

					if ( typeof fn == 'function' )
					{
						fn.call( $dot[ 0 ], conf.isTruncated );
					}
					return conf.isTruncated;
				}

			).on(
				'originalContent.dot',
				function( e, fn )
				{
					e.preventDefault();
					e.stopPropagation();

					if ( typeof fn == 'function' )
					{
						fn.call( $dot[ 0 ], orgContent );
					}
					return orgContent;
				}

			).on(
				'destroy.dot',
				function( e )
				{
					e.preventDefault();
					e.stopPropagation();

					$dot.unwatch()
						.unbind_events()
						.contents()
						.detach()
						.end()
						.append( orgContent )
						.attr( 'style', $dot.data( 'dotdotdot-style' ) || '' )
						.data( 'dotdotdot', false );
				}
			);
			return $dot;
		};	//	/bind_events

		$dot.unbind_events = function()
		{
			$dot.off('.dot');
			return $dot;
		};	//	/unbind_events

		$dot.watch = function()
		{
			$dot.unwatch();
			if ( opts.watch == 'window' )
			{
				var $window = $(window),
					_wWidth = $window.width(),
					_wHeight = $window.height();

				$window.on(
					'resize.dot' + conf.dotId,
					function()
					{
						if ( _wWidth != $window.width() || _wHeight != $window.height() || !opts.windowResizeFix )
						{
							_wWidth = $window.width();
							_wHeight = $window.height();

							if ( watchInt )
							{
								clearInterval( watchInt );
							}
							watchInt = setTimeout(
								function()
								{
									$dot.trigger( 'update.dot' );
								}, 100
							);
						}
					}
				);
			}
			else
			{
				watchOrg = getSizes( $dot );
				watchInt = setInterval(
					function()
					{
						if ( $dot.is( ':visible' ) )
						{
							var watchNew = getSizes( $dot );
							if ( watchOrg.width  != watchNew.width ||
								 watchOrg.height != watchNew.height )
							{
								$dot.trigger( 'update.dot' );
								watchOrg = watchNew;
							}
						}
					}, 500
				);
			}
			return $dot;
		};
		$dot.unwatch = function()
		{
			$(window).off( 'resize.dot' + conf.dotId );
			if ( watchInt )
			{
				clearInterval( watchInt );
			}
			return $dot;
		};

		var	opts 		= $.extend( true, {}, $.fn.dotdotdot.defaults, o ),
			conf		= {},
			watchOrg	= {},
			watchInt	= null,
			$inr		= null;


		if ( !( opts.lastCharacter.remove instanceof Array ) )
		{
			opts.lastCharacter.remove = $.fn.dotdotdot.defaultArrays.lastCharacter.remove;
		}
		if ( !( opts.lastCharacter.noEllipsis instanceof Array ) )
		{
			opts.lastCharacter.noEllipsis = $.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis;
		}


		conf.afterElement	= getElement( opts.after, $dot );
		conf.isTruncated	= false;
		conf.dotId			= dotId++;


		$dot.data( 'dotdotdot', true )
			.bind_events()
			.trigger( 'update.dot' );

		if ( opts.watch )
		{
			$dot.watch();
		}

		return $dot;
	};


	//	public
	$.fn.dotdotdot.defaults = {
		'ellipsis'			: '... ',
		'wrap'				: 'word',
		'fallbackToLetter'	: true,
		'lastCharacter'		: {},
		'tolerance'			: 0,
		'callback'			: null,
		'after'				: null,
		'height'			: null,
		'watch'				: false,
		'windowResizeFix'	: true
	};
	$.fn.dotdotdot.defaultArrays = {
		'lastCharacter'		: {
			'remove'			: [ ' ', '\u3000', ',', ';', '.', '!', '?' ],
			'noEllipsis'		: []
		}
	};
	$.fn.dotdotdot.debug = function( msg ) {};


	//	private
	var dotId = 1;

	function children( $elem, o, after )
	{
		var $elements 	= $elem.children(),
			isTruncated	= false;

		$elem.empty();

		for ( var a = 0, l = $elements.length; a < l; a++ )
		{
			var $e = $elements.eq( a );
			$elem.append( $e );
			if ( after )
			{
				$elem.append( after );
			}
			if ( test( $elem, o ) )
			{
				$e.remove();
				isTruncated = true;
				break;
			}
			else
			{
				if ( after )
				{
					after.detach();
				}
			}
		}
		return isTruncated;
	}
	function ellipsis( $elem, $d, $i, o, after )
	{
		var isTruncated	= false;

		//	Don't put the ellipsis directly inside these elements
		var notx = 'a, table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style';

		//	Don't remove these elements even if they are after the ellipsis
		var noty = 'script, .dotdotdot-keep';

		$elem
			.contents()
			.detach()
			.each(
				function()
				{

					var e	= this,
						$e	= $(e);

					if ( typeof e == 'undefined' )
					{
						return true;
					}
					else if ( $e.is( noty ) )
					{
						$elem.append( $e );
					}
					else if ( isTruncated )
					{
						return true;
					}
					else
					{
						$elem.append( $e );
						if ( after && !$e.is( o.after ) && !$e.find( o.after ).length  )
						{
							$elem[ $elem.is( notx ) ? 'after' : 'append' ]( after );
						}
						if ( test( $i, o ) )
						{
							if ( e.nodeType == 3 ) // node is TEXT
							{
								isTruncated = ellipsisElement( $e, $d, $i, o, after );
							}
							else
							{
								isTruncated = ellipsis( $e, $d, $i, o, after );
							}
						}

						if ( !isTruncated )
						{
							if ( after )
							{
								after.detach();
							}
						}
					}
				}
			);
		$d.addClass("is-truncated");
		return isTruncated;
	}
	function ellipsisElement( $e, $d, $i, o, after )
	{
		var e = $e[ 0 ];

		if ( !e )
		{
			return false;
		}

		var txt			= getTextContent( e ),
			space		= ( txt.indexOf(' ') !== -1 ) ? ' ' : '\u3000',
			separator	= ( o.wrap == 'letter' ) ? '' : space,
			textArr		= txt.split( separator ),
			position 	= -1,
			midPos		= -1,
			startPos	= 0,
			endPos		= textArr.length - 1;


		//	Only one word
		if ( o.fallbackToLetter && startPos == 0 && endPos == 0 )
		{
			separator	= '';
			textArr		= txt.split( separator );
			endPos		= textArr.length - 1;
		}

		while ( startPos <= endPos && !( startPos == 0 && endPos == 0 ) )
		{
			var m = Math.floor( ( startPos + endPos ) / 2 );
			if ( m == midPos )
			{
				break;
			}
			midPos = m;

			setTextContent( e, textArr.slice( 0, midPos + 1 ).join( separator ) + o.ellipsis );
			$i.children()
				.each(
					function()
					{
						$(this).toggle().toggle();
					}
				);

			if ( !test( $i, o ) )
			{
				position = midPos;
				startPos = midPos;
			}
			else
			{
				endPos = midPos;

				//	Fallback to letter
				if (o.fallbackToLetter && startPos == 0 && endPos == 0 )
				{
					separator	= '';
					textArr		= textArr[ 0 ].split( separator );
					position	= -1;
					midPos		= -1;
					startPos	= 0;
					endPos		= textArr.length - 1;
				}
			}
		}

		if ( position != -1 && !( textArr.length == 1 && textArr[ 0 ].length == 0 ) )
		{
			txt = addEllipsis( textArr.slice( 0, position + 1 ).join( separator ), o );
			setTextContent( e, txt );
		}
		else
		{
			var $w = $e.parent();
			$e.detach();

			var afterLength = ( after && after.closest($w).length ) ? after.length : 0;

			if ( $w.contents().length > afterLength )
			{
				e = findLastTextNode( $w.contents().eq( -1 - afterLength ), $d );
			}
			else
			{
				e = findLastTextNode( $w, $d, true );
				if ( !afterLength )
				{
					$w.detach();
				}
			}
			if ( e )
			{
				txt = addEllipsis( getTextContent( e ), o );
				setTextContent( e, txt );
				if ( afterLength && after )
				{
					$(e).parent().append( after );
				}
			}
		}

		return true;
	}
	function test( $i, o )
	{
		return $i.innerHeight() > o.maxHeight;
	}
	function addEllipsis( txt, o )
	{
		while( $.inArray( txt.slice( -1 ), o.lastCharacter.remove ) > -1 )
		{
			txt = txt.slice( 0, -1 );
		}
		if ( $.inArray( txt.slice( -1 ), o.lastCharacter.noEllipsis ) < 0 )
		{
			txt += o.ellipsis;
		}
		return txt;
	}
	function getSizes( $d )
	{
		return {
			'width'	: $d.innerWidth(),
			'height': $d.innerHeight()
		};
	}
	function setTextContent( e, content )
	{
		if ( e.innerText )
		{
			e.innerText = content;
		}
		else if ( e.nodeValue )
		{
			e.nodeValue = content;
		}
		else if (e.textContent)
		{
			e.textContent = content;
		}

	}
	function getTextContent( e )
	{
		if ( e.innerText )
		{
			return e.innerText;
		}
		else if ( e.nodeValue )
		{
			return e.nodeValue;
		}
		else if ( e.textContent )
		{
			return e.textContent;
		}
		else
		{
			return "";
		}
	}
	function getPrevNode( n )
	{
		do
		{
			n = n.previousSibling;
		}
		while ( n && n.nodeType !== 1 && n.nodeType !== 3 );

		return n;
	}
	function findLastTextNode( $el, $top, excludeCurrent )
	{
		var e = $el && $el[ 0 ], p;
		if ( e )
		{
			if ( !excludeCurrent )
			{
				if ( e.nodeType === 3 )
				{
					return e;
				}
				if ( $.trim( $el.text() ) )
				{
					return findLastTextNode( $el.contents().last(), $top );
				}
			}
			p = getPrevNode( e );
			while ( !p )
			{
				$el = $el.parent();
				if ( $el.is( $top ) || !$el.length )
				{
					return false;
				}
				p = getPrevNode( $el[0] );
			}
			if ( p )
			{
				return findLastTextNode( $(p), $top );
			}
		}
		return false;
	}
	function getElement( e, $i )
	{
		if ( !e )
		{
			return false;
		}
		if ( typeof e === 'string' )
		{
			e = $(e, $i);
			return ( e.length )
				? e
				: false;
		}
		return !e.jquery
			? false
			: e;
	}
	function getTrueInnerHeight( $el )
	{
		var h = $el.innerHeight(),
			a = [ 'paddingTop', 'paddingBottom' ];

		for ( var z = 0, l = a.length; z < l; z++ )
		{
			var m = parseInt( $el.css( a[ z ] ), 10 );
			if ( isNaN( m ) )
			{
				m = 0;
			}
			h -= m;
		}
		return h;
	}


	//	override jQuery.html
	var _orgHtml = $.fn.html;
	$.fn.html = function( str )
	{
		if ( str != undef && typeof str !== "function" && this.data( 'dotdotdot' ) )
		{
			return this.trigger( 'update', [ str ] );
		}
		return _orgHtml.apply( this, arguments );
	};


	//	override jQuery.text
	var _orgText = $.fn.text;
	$.fn.text = function( str )
	{
		if ( str != undef && typeof str !== "function" && this.data( 'dotdotdot' ) )
		{
			str = $( '<div />' ).text( str ).html();
			return this.trigger( 'update', [ str ] );
		}
		return _orgText.apply( this, arguments );
	};


})( jQuery );

/*
## Automatic parsing for CSS classes
Contributed by [Ramil Valitov](https://github.com/rvalitov)
### The idea
You can add one or several CSS classes to HTML elements to automatically invoke "jQuery.dotdotdot functionality" and some extra features. It allows to use jQuery.dotdotdot only by adding appropriate CSS classes without JS programming.
### Available classes and their description
* dot-ellipsis - automatically invoke jQuery.dotdotdot to this element. This class must be included if you plan to use other classes below.
* dot-resize-update - automatically update if window resize event occurs. It's equivalent to option `watch:'window'`.
* dot-timer-update - automatically update if window resize event occurs. It's equivalent to option `watch:true`.
* dot-load-update - automatically update after the window has beem completely rendered. Can be useful if your content is generated dynamically using using JS and, hence, jQuery.dotdotdot can't correctly detect the height of the element before it's rendered completely.
* dot-height-XXX - available height of content area in pixels, where XXX is a number, e.g. can be `dot-height-35` if you want to set maximum height for 35 pixels. It's equivalent to option `height:'XXX'`.
### Usage examples
*Adding jQuery.dotdotdot to element*
    
	<div class="dot-ellipsis">
	<p>Lorem Ipsum is simply dummy text.</p>
	</div>
	
*Adding jQuery.dotdotdot to element with update on window resize*
    
	<div class="dot-ellipsis dot-resize-update">
	<p>Lorem Ipsum is simply dummy text.</p>
	</div>
	
*Adding jQuery.dotdotdot to element with predefined height of 50px*
    
	<div class="dot-ellipsis dot-height-50">
	<p>Lorem Ipsum is simply dummy text.</p>
	</div>
	
*/

jQuery(function($) {
	//We only invoke jQuery.dotdotdot on elements that have dot-ellipsis class
	$(".dot-ellipsis").each(function(){
		//Checking if update on window resize required
		var watch_window=$(this).hasClass("dot-resize-update");
		
		//Checking if update on timer required
		var watch_timer=$(this).hasClass("dot-timer-update");
		
		//Checking if height set
		var height=0;		
		var classList = $(this).attr('class').split(/\s+/);
		$.each(classList, function(index, item) {
			if (!item.match('/^dot\-height\-\d+$/')) {
				height=Number(item.substr(item.indexOf('-',-1)+1));
			}
		});
		
		//Invoking jQuery.dotdotdot
		var x = new Object();
		if (watch_timer)
			x.watch=true;
		if (watch_window)
			x.watch='window';
		if (height>0)
			x.height=height;
		$(this).dotdotdot(x);
	});
		
});

//Updating elements (if any) on window.load event
jQuery(window).on("load", function(){
	jQuery(".dot-ellipsis.dot-load-update").trigger("update.dot");
});

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\utility.js
/*  version="103" */
$(function () {
    jsUtility.init();

    //Tooltip  
    if (jsUtility.isMobileBrowser() == false) {
        dataOriginalTitle.tooltip();
    }
});

//on page load 
$(window).on("load", function () {
    jsUtility.updateThirdPartyLinks();
    jsUtility.onHoverDetails();
});

$(window).on('resize', resize);
function resize() {
    jsUtility.setFeaturedImage(),
        jsUtility.progressiveSetup();
    jsUtility.setDynamicBackground();
    jsUtility.setHeroImage();
    jsUtility.resizeHeroImage();
    jsUtility.setGapWidth();

    clearTimeout(this.id);
    this.id = setTimeout(jsUtility.updatePaddingBottom(), 500);
};

//On exit
$(window).on("beforeunload", function () {
    jsUtility.setLocationResult();
});

var dataOriginalTitle = $('[data-original-title]'); //Calling enhanced Tooltip

//Tooltip Dismissal Mechanism

dataOriginalTitle.on("keydown", function (e) {
    if (e.keyCode == 27) {
        dataOriginalTitle.tooltip("hide");
        dataOriginalTitle.trigger("blur");
    }
});

//For items that require enter key to trigger a mouse click
var OnEnterTrigger = $(".coe");
OnEnterTrigger.on("keypress", function (e) {
    if (e.which == 13) {
        this.trigger("click");
    }
});

var aspectRatio = 0.5625; // 16:9 default aspect ratio

var jsUtility = (function () {
    var init = function () {
        progressiveSetup();
        viewLessCards();
        onHoverDetails();
        viewAllCards();
        viewMoreCards();
        viewIncLessCards();
        setFeaturedImage();
        redirectBlockProfileOnLoad();
        checkBrowser();
        setBackgroundImage();
        addEllipsis();
        adjustHeaderOnLoadEditor();
        lazyLoading();
        isMobile();
        isTablet();
        isMobileBrowser();
        isFirefox();
        setDynamicBackground();
        setDataInlineLink();
        setDataProfiles();
        accessBarAdjustment();
        setHeroImage();
        resizeHeroImage();
        setGapWidth();
        setTableDisplay();
        pauseVideoInTabModule();
        pauseAudioInTabModule();
        skipLinksFocus();
        updatePaddingBottom();
        removeEmailInURL();
        removeFocusIndicatorOnClick();
        adjustContenMarginForMultinavBar();
        interactiveAnimationCache();
        brandpurposeAccessibilityUpdate();
        hideHeaderAndCookie();
    }
    var smMin = 768;
    var smMax = 999;
    var lgMin = 1200;

    var isMobile = function () {
        if ($(window).width() < smMin) {
            return true;
        } else {
            return false;
        }
    }

    var isTablet = function (landscape) {
        landscape = (landscape == undefined || landscape == '') ? false : landscape;
        if ($(window).width() >= smMin && $(window).width() <= smMax && !landscape) {
            return true;
        } else if ($(window).width() >= smMin && $(window).width() < lgMin && landscape) {
            return true;
        } else {
            return false;
        }
    }

    var tabTitleLink = $(".tab-title-container div li");
    var tabModule = $(".tab-container");

    if (isMobile() || isTablet()) {
        tabTitleLink = $("div.tabs-mobile li");
    }

    var onHoverDetails = function () {
        var onHoverModule = $('.audio-background-hover , .hover-details-background');
        onHoverModule.each(function () {
            var $this = $(this);

            var dataAttributeOpacity = $this.attr('data-attribute-opacity');
            var opacity = dataAttributeOpacity / 100;

            $this.css("opacity", opacity);
        });
    }

    var pauseVideoInTabModule = function () {
        var videoPlayerModule = $(".tab-content-container .video-player-module");
        var videoPlayer = document.querySelectorAll(".tab-content-container .video-player-youtube"), i;
        if (tabModule) {
            if (videoPlayerModule) {
                tabTitleLink.on('mousedown', function () {
                    if (isMobile() || isTablet()) {
                        videoPlayer = document.querySelectorAll(".tabs-mobile .video-player-youtube"), i;
                        for (i = 0; i < videoPlayer.length; i++) {
                            videoPlayer[i].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
                        }
                    }
                    if ($(this).hasClass("inactive")) {
                        for (i = 0; i < videoPlayer.length; i++) {
                            videoPlayer[i].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
                        }
                    }
                });
            }
        };
    }

    var adjustContenMarginForMultinavBar = function () {
        var multinavbar = $(".multipage-navigation-bar").length;

        if (multinavbar >= 1) {
            $("#redesign-main").addClass("multipage-margin");
        }
    }
    var interactiveAnimationCache = function () {
        var animationSwitch = $('#ai-animation-toggle');
        var animationValue;

        //ON and Off State
        if (((localStorage.getItem("isAnimation") === "true" || localStorage.getItem("isAnimation") === null) && !animationSwitch.is(':checked'))
            || (localStorage.getItem("isAnimation") === "false" && animationSwitch.is(':checked'))) {
            $(".ai-animation-switch-toggle").trigger("click");
        }
        $(".ai-animation-switch-toggle").on("click", function () {
            if (animationSwitch.is(':checked')) {
                animationValue = "true";
            } else {
                animationValue = "false";
            }
            localStorage.setItem("isAnimation", animationValue);
            $('.ai-animation-slider').addClass('transition');
        });
    };

    var pauseAudioInTabModule = function () {
        var audioPlayerModule = $("audio-module");
        var audioPlayer = $(".tab-content-container .playPause");
        if (tabModule) {
            if (audioPlayerModule) {
                tabTitleLink.on('mousedown', function () {
                    if (isMobile() || isTablet()) {
                        audioPlayer = $(".tabs-mobile .playPause");
                        if (audioPlayer.hasClass("ion-ios-pause")) {
                            audioPlayer.trigger("click");
                        }
                    }
                    if ($(this).hasClass("inactive")) {
                        if (audioPlayer.hasClass("ion-ios-pause")) {
                            audioPlayer.trigger("click");
                        }
                    }
                });
            }
        }
    }

    var setTableDisplay = function () {
        var blockContent = $(".table-display table");
        var tableContainer = $(".table-display");

        if (blockContent.hasClass('table')) {
            tableContainer.parent().css('display', "grid");
            tableContainer.closest(".block-content").css('padding-top', "1.25em");
            tableContainer.closest(".ui-container").find(".pagezone-description").css('margin-top', "0.63em");
            tableContainer.closest(".block-content").siblings().find("h2").addClass("module-title");

            if (jsUtility.isMobile()) {
                tableContainer.closest(".block-content").css('padding-top', "0.63em");
            }

            var currentCell = $('td').first();

            $('td').on("keydown", function () {
                currentCell = $(this);
            });

            $('.table tbody tr td').on("keydown", function (e) {
                var c = "";
                var kc = e.which || e.keyCode;
                if (kc === 39) {
                    c = currentCell.next();
                    currentCell.next().attr("tabindex", "0");
                    currentCell.attr("tabindex", "-1");

                    var rightLimit = $(this).siblings().length;
                    if (($(this).index() + 1) > rightLimit) {
                        currentCell.attr("tabindex", "0");
                    }
                    e.preventDefault();
                } else if (kc === 37) {
                    c = currentCell.prev();
                    currentCell.attr("tabindex", "-1");
                    currentCell.prev().attr("tabindex", "0");

                    if (($(this).index() - 1) < 0) {
                        currentCell.attr("tabindex", "0");
                    }
                    e.preventDefault();
                } else if (kc === 38) {
                    c = currentCell.closest('tr').prev().find('td').eq(currentCell).index();
                    currentCell.closest('tr').prev().find('td').eq(currentCell).index().attr("tabindex", "0");
                    currentCell.attr("tabindex", "-1");

                    if (($(this).parent('tr').index() - 1) < 0) {
                        currentCell.attr("tabindex", "0");
                    }
                    e.preventDefault();
                } else if (kc === 40) {
                    c = currentCell.closest('tr').next().find('td').eq(currentCell).index();
                    currentCell.attr("tabindex", "-1");
                    currentCell.closest('tr').next().find('td').eq(currentCell).index().attr("tabindex", "0");

                    var downLimit = $(this).parent('tr').siblings().length;
                    if (($(this).parent('tr').index() + 1) > downLimit) {
                        currentCell.attr("tabindex", "0");
                    }
                    e.preventDefault();
                }

                if (c.length > 0) {
                    currentCell = c;
                    currentCell.trigger("focus");
                }
            });
        }
    }

    var isMobileBrowser = function () {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            var $html = $('html');
            $html.addClass('isTouch');
            return true;
        } else {
            return false;
        }
    }

    var removeTags = function (keyword) {
        var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
        var tagOrComment = new RegExp('<(?:' + '!--(?:(?:-*[^->])*--+|-?)' + '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' + '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' + '|/?[a-z]' + tagBody + ')>', 'gi');

        if (keyword) {
            var oldKeyword;
            do {
                oldKeyword = keyword;
                keyword = keyword.replace(tagOrComment, '').trim();
            } while (keyword !== oldKeyword);
            return keyword.replace(/&nbsp;|</g, '').trim();
        }
        return "";
    };

    var sitecoreCrossPiece = $('#scCrossPiece');
    var adjustHeaderOnLoadEditor = function () {
        var scFieldValues = $('#scFieldValues');
        if (sitecoreCrossPiece.length > 0 && scFieldValues.length <= 0) {
            setTimeout(adjustHeaderOnLoadEditor);
        }
        else {
            setTimeout(adjustHeaderOnLoadEditor, 200);
        }

        hideRibbon();
    }

    var hideRibbon = function () {

        if (window.location.search.substring(1).indexOf('sc_mode=preview') >= 0) {
            $('#scWebEditRibbon').addClass('hidden');
            $('#scCrossPiece').addClass('hidden');
            if (window.location.href.toLowerCase().indexOf("tlaapp") === -1) {
                $('#header-topnav').css('top', '0px');
            }

        }
    }

    var setLocationResult = function () {
        if (OptanonActiveGroups.indexOf("3") !== -1) {
            navigator.permissions.query({ name: 'geolocation' }).then(function (result) {
                var locationResult = result.state;
                var cookieKey = "locationEnabled";
                acncm.CacheManager.writeFlagCookie(cookieKey, locationResult);
            })
        }
    }
    
    var checkBrowser = function () {
        var $html = $('html');
        var ua = navigator.userAgent.toLowerCase();
        var appName = navigator.appName.toLowerCase();

        if (ua.indexOf("firefox") > -1) {
            $html.addClass('firefox');
        }

        //RMT 7441 US002 Edge 200% alignment fix
        if (ua.indexOf("edge") > -1) {
            $html.addClass('ie-edge');
        }
        if (ua.indexOf("trident/7.0") != -1 && appName == "netscape") {
            $html.addClass('ie');
        }

        //RMT 8203 BUG 734964
        if (ua.indexOf("chrome") < 0 && ua.indexOf("safari") > -1) {
            $html.addClass("safari");
        }
    }

    var isFirefox = function () {
        if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
            return true;
        } else {
            return false;
        }
    }

    var setBackgroundImage = function () {
        var blockContainer = $("#hero-carousel .item, .ui-container");

        blockContainer.each(function () {
            var $this = $(this);
            var image = $this.data("src");
            if (image != undefined && image != "") {
                $this.css('background-image', "url(" + image + ")");
            }
        });
    }
    var addEllipsis = function () {
        var ellipsis = $('.dot-ellipsis');
        var htmlLang = $("html").attr("lang");
        var isJapanese = htmlLang.match("ja");
        var isChinese = htmlLang.match("zh");
        var truncateBy = 'word';
        var isHeight = '100%';
        setMaxHeight();

        if (isJapanese !== null || isChinese !== null) {
            truncateBy = 'letter';
        }

        ellipsis.dotdotdot({
            ellipsis: '... ',
            /*	Whether to update the ellipsis: true/'window' */
            watch: window,
            truncate: truncateBy,
            height: isHeight
        });
    }

    var ellipsisFunction = function (element, language) {
        var htmlLang = $("html").attr("lang");
        var isJapanese = htmlLang.match("ja");
        var isChinese = htmlLang.match("zh");
        var truncateBy = 'word'

        if (isJapanese !== null || isChinese !== null) {
            truncateBy = 'letter';
        };

        if (language !== undefined) {
            language = language.toLowerCase();
            if (language !== null || language !== "") {
                truncateBy = 'word';
            }

            if (language === "ja" || language === "zh-cn") {
                truncateBy = 'letter';
            }
        }

        element.dotdotdot({
            watch: 'window',
            height: 'auto',
            truncate: truncateBy
        });
    }

    var setMaxHeight = function () {
        var dccLinkVariant = $(".dynamic-card-link");
        dccLinkVariant.each(function () {
            if ($(this).has(".module-title.dot-ellipsis").length > 0) {
                var elem = $(this).find(".module-title.dot-ellipsis");
                titleFontsize = parseFloat($(elem).css("font-size"));

                if (titleFontsize >= 24) {
                    $(elem).css("max-height", 5.00 + "rem");
                }
                else {
                    $(elem).css("max-height", 3.00 + "rem");
                }
            }
        });
    }

    var lazyLoading = function () {
        var lazyLoading = $('.lazy');
        lazyLoading.lazy({
            effect: "fadeIn",
            effectTime: 270,
            threshold: 200
        });
    }

    var lazyLoadModule = function (element) {
        var lazyLoading = $(element).find('.lazy');
        lazyLoading.lazy();
    }

    var redirectBlockProfileOnLoad = function () {
        var anchorBlockId = window.location.hash;

        var profileCard = $(anchorBlockId);

        if (profileCard.hasClass("feature-profile-block-container")) {
            window.location.hash = "";
            var overallOffset = 20;

            //scroll to profile card
            $(window).on("load", function () {
                if (window.location.href.toLowerCase().indexOf("tlaapp") === -1) {
                    var globalHeaderOffset = $("#header-topnav").height();
                    overallOffset += globalHeaderOffset;
                    var isMultiPageNav = $("#multipage-nav").length > 0;
                    if (isMultiPageNav) {
                        if ($(".ie").length > 0 || $(".firefox").length > 0) {
                            $("#block-multipagenavigationsection").height($("#multipage-nav").height());
                        }
                        overallOffset += $("#multipage-nav").height();
                    }

                    $('html, body').animate({
                        scrollTop: profileCard.offset().top - overallOffset
                    }, 1000);
                }
            });

        }
    }

    //RMT7949 US011.A start
    var setFeaturedImage = function () {
        var featuredImage = $('.adaptive-img');
        var anchorBlockId = window.location.hash;
        var isScrollRedirectEnabled = $(".jumplink").length > 0 || $(anchorBlockId).hasClass("feature-profile-block-container");
        featuredImage.each(function () {
            var $this = $(this);
            var image = $this.data("imagexs");
            var imageParallax = $this.is(".fixed-parallax-standard, .fixed-parallax-partial");

            var isHeroParent = $this.closest(".hero-module").length > 0;
            if (typeof $this !== "undefined" && $this !== "") {
                if (!jsUtility.isMobile() && !jsUtility.isTablet()) {
                    image = $this.data("imagelg");
                    if ((!isScrollRedirectEnabled || (isHeroParent && $this.is("div"))) && $this.hasClass('lazy')) {
                        $this.attr("data-src", image);
                    }
                    else if (imageParallax) {
                        $this.css('background-image', "url(" + image + ")");
                    }
                    else {
                        $this.attr("src", image);
                    }
                }
                else if (jsUtility.isTablet()) {
                    image = $this.data("imagesm");
                    if ((!isScrollRedirectEnabled || (isHeroParent && $this.is("div"))) && $this.hasClass('lazy')) {
                        $this.attr("data-src", image);
                    }
                    else if (imageParallax) {
                        $this.css('background-image', "url(" + image + ")");
                    }
                    else {
                        $this.attr("src", image);
                    }
                }
                else {
                    if ((!isScrollRedirectEnabled || (isHeroParent && $this.is("div"))) && $this.hasClass('lazy')) {
                        $this.attr("data-src", image);
                    }
                    else if (imageParallax) {
                        $this.css('background-image', "url(" + image + ")");
                    }
                    else {
                        $this.attr("src", image);
                    }
                }
            }
        });

    };
    //RMT7949 US011.A end

    //Added during RMT 9756 for image functionality of Hero Block
    var setHeroImage = function () {

        var $heroImageContainer = $(".append-hero-block .append-image-container");
        var src = "";

        if ($heroImageContainer) {
            if (jsUtility.isMobile()) {
                src = $heroImageContainer.data("imagexs");
            }
            else if (jsUtility.isTablet()) {
                src = $heroImageContainer.data("imagesm");
            }
            else {
                src = $heroImageContainer.data("imagelg");
            }

            var $heroImage = $(".append-hero-block .marquee-image");

            if ($heroImage) {
                $heroImage.remove();
            }

            if (src) {
                $heroImageContainer.append("<img src='" + src + "' class='marquee-image' alt=' '>");
            }
        }
    }

    var resizeHeroImage = function () {
        var $contentHeight = $(".append-hero-block .marquee-image");
        var getHeight = $(".append-hero-block .item").height();

        if (jsUtility.isMobile()) {
            $contentHeight.css("height", "auto");
        }
        else {
            $contentHeight.css("height", getHeight);
        }
    }

    //end 

    //RMT 9756 and 9757. Functionality to fill the gap between 2 components

    var setGapWidth = function () {
        var screenWidth = $("#redesign-main");
        var contentWidth = $(".base-width");
        if (contentWidth) {
            var mainWidth = screenWidth.width();
            var blockWidth = contentWidth.width();
            var result = mainWidth - blockWidth;
            var marginDiff = (result / 2) / 3;
            var maxContent = $(".maximize-content");
            if (maxContent) {
                maxContent.removeAttr("style");
                if (!jsUtility.isMobile() && !jsUtility.isTablet()) {
                    var bodyContent = maxContent.outerWidth();
                    maxContent.css("width", "calc(" + bodyContent + "px + " + marginDiff + "px)");
                }
            }
        }
    }
    //end

    var setDynamicBackground = function () {
        var bgImage = $('.dynamic-bg');
        bgImage.each(function () {
            var $this = $(this);
            image = getViewportImage($this);

            if (image) {
                $this.css('background-image', "url(" + image + ")");
            }
        });
    };

    var getViewportImage = function (elm) {
        var image = "";

        if (typeof elm == "undefined" && elm == "") {
            return image;
        }

        if (jsUtility.isMobile()) {
            image = elm.data("imagexs")
        }
        else if (jsUtility.isTablet()) {
            image = elm.data("imagesm")
        }
        else {
            image = elm.data("imagelg")
        }

        return image;
    }

    //RMT8363 Progressive Display - start
    var progressiveSetup = function (isFilterEnabled) {
        /*filtering of cards is enabled*/
        var enableFilter = isFilterEnabled === undefined ? false : isFilterEnabled;

        var blockCardCounter = $('.progressive');
        blockCardCounter.each(function () {
            var cardsInBlock = enableFilter ? $(this).find('.progressive-card.filtered') : $(this).find('.progressive-card');
            var cardsCounter = cardsInBlock.length;
            $(this).attr('data-card-count', cardsCounter);
        });

        progressiveDisplay(enableFilter);
    }

    var progressiveDisplay = function (enableFilter) {

        var progressiveDisplay = enableFilter ? $('.progressive.enable-filter') : $('.progressive');
        var progressiveDisplayLength = progressiveDisplay.length;
        var viewLess = $(".view-less-cards");
        var viewAll = $(".view-all-cards");
        var viewMore = $(".view-more-cards");
        var incLess = $(".view-incless-cards");
        var cardCounter = 0;
        var blockCounter = 0;


        if (enableFilter) {
            viewLess.attr('tabindex', '0').removeClass('screenReaderOnly').removeClass('adjustive-margin-left').removeClass('adjustive-margin-right');
            viewMore.attr('tabindex', '0').removeClass('screenReaderOnly').removeClass('adjustive-margin-left').removeClass('adjustive-margin-right');
            incLess.attr('tabindex', '0').removeClass('screenReaderOnly').removeClass('adjustive-margin-left').removeClass('adjustive-margin-right');
        }
        // 'first-load' class - fix for BUG 817099

        progressiveDisplay.each(function () {

            if ($(this).hasClass('first-load') === false || enableFilter) {
                $(this).addClass('first-load');
                var cards = enableFilter ? $(this).find('.progressive-card.filtered') : $(this).find('.progressive-card');
                var cardsInBlock = $(this).attr('data-card-count');

                if (blockCounter < progressiveDisplayLength) {
                    // condition to disable progressive functionality in page editor
                    var isEditor = $('code').attr('type');
                    if (isEditor === "text/sitecore") {
                        cards.show();
                        disableProgressive($(this));
                    } else {
                        var initialCards;
                        if (isMobile()) {
                            initialCards = $(this).data('cards-xs');
                        } else if (isTablet()) {
                            initialCards = $(this).data('cards-sm');
                        } else {
                            initialCards = $(this).data('cards-lm');
                        }

                        if (initialCards == 'undefined' || initialCards == 0) {
                            disableProgressive($(this));
                        } else {
                            if (cardsInBlock <= initialCards) {
                                disableProgressive($(this));
                            } else {
                                cards.hide();
                                cards.each(function () {
                                    if (cardCounter < initialCards) {
                                        cards.eq(cardCounter).show();
                                    }
                                    cardCounter = cardCounter + 1;
                                });

                                enableProgressive($(this));
                                removeLinkCardPadding($(this));
                            }
                        }
                    }
                }

                cardCounter = 0;
                blockCounter = blockCounter + 1;
            }
        });
    }

    var removeLinkCardPadding = function (thisBlock) {
        var viewAllButton = thisBlock.find('.view-all-cards');
        var viewLessButton = thisBlock.find('.view-less-cards');
        var viewMoreButton = thisBlock.find('.view-more-cards');
        var incLessButton = thisBlock.find('.view-incless-cards');
        $(window).on('load resize', function () {
            if (((viewMoreButton.css('display') != 'none') || (viewLessButton.css('display') != 'none')) && isTablet()) {
                thisBlock.children(".link-cards").css('padding-bottom', '0');
            }
        });

        if (thisBlock.hasClass("view-more")) {

            viewAllButton.hide();
            viewMoreButton.show();
        }
        else {
            viewMoreButton.hide();
            viewAllButton.show();
        }
        viewLessButton.hide();
        incLessButton.hide();
    }

    var enableProgressive = function (thisBlock) {
        var lessButton = thisBlock.find('.view-less-cards');
        var moreButton = thisBlock.find('.view-more-cards');
        var incLessButton = thisBlock.find('.view-incless-cards');
        var viewAllButton = thisBlock.find('.view-all-cards');

        lessButton.attr('tabindex', '-1').addClass('screenReaderOnly');
        lessButton.children("span:nth-last-child(1)").attr('aria-hidden', 'true');

        if (thisBlock.hasClass("view-more")) {
            viewAllButton.hide();
            moreButton.show();

        }
        else {
            viewAllButton.show();
            moreButton.hide();
        }

        incLessButton.hide();
    }

    var disableProgressive = function (thisBlock) {
        var allButton = thisBlock.find('.view-all-cards');
        var lessButton = thisBlock.find('.view-less-cards');
        var moreButton = thisBlock.find('.view-more-cards');
        var incLessButton = thisBlock.find('.view-incless-cards');

        allButton.attr('aria-hidden', 'true');
        lessButton.attr('aria-hidden', 'true');
        moreButton.attr('aria-hidden', 'true');
        incLessButton.attr('aria-hidden', 'true');

        allButton.hide();
        lessButton.hide();
        moreButton.hide();
        incLessButton.hide();

    }
    // To focus on the first set of added cards
    var focusFirstCard = function (parent) {
        var cardIncrement = 0;
        if (isMobile()) {
            cardIncrement = parent.attr('data-cards-xs');
            scrollValue = 550;
        } else if (isTablet()) {
            cardIncrement = parent.attr('data-cards-sm');
            scrollValue = 350;
        } else {
            cardIncrement = parent.attr('data-cards-lm');
            scrollValue = 480;
        }

        var firstCard = parent.find(".progressive-card:visible").eq(cardIncrement);
        var cardLinks = firstCard.find(":tabbable").first();
        cardLinks.each(function (index, card) {
            if (card.tabIndex == 0) {
                card.focus();
                return false;
            }
        });
    }
    // To focus on the first card of the block
    var focusFirstCardHA = function (parent) {
        var firstCard = parent.find(".progressive-card:visible").first();
        var cardLinks = firstCard.find(":tabbable").first();
        cardLinks.each(function (index, card) {
            if (card.tabIndex == 0) {
                card.focus();
                return false;
            }
        });
    }
    //To focus on the very last card of the added set on shift tab
    var focusLastCardST = function (parent) {
        var firstCard = parent.find(".progressive-card:visible").last();
        var cardLinks = firstCard.find(":tabbable").last();
        cardLinks.each(function (index, card) {
            if (card.tabIndex == 0) {
                card.focus();
                return false;
            }
        });
    }

    var viewLess = $(".view-less-cards");
    var viewAll = $(".view-all-cards");
    var viewMore = $(".view-more-cards");
    var incLess = $(".view-incless-cards");

    var viewAllCards = function () {

        viewAll.on('click', function () {
            var viewAllBlock = $(this).closest('.progressive');
            var cardCounter = 0;
            addEllipsis();
            var initialLoad;
            if (isMobile()) {
                initialLoad = $(this).closest('.progressive').attr('data-cards-xs');
            } else if (isTablet()) {
                initialLoad = $(this).closest('.progressive').attr('data-cards-sm');
            } else {
                initialLoad = $(this).closest('.progressive').attr('data-cards-lm');
            }

            var allButton = viewAllBlock.find('.view-all-cards');
            var lessButton = viewAllBlock.find('.view-less-cards');

            viewAllBlock.each(function () {
                var cards = $(this).hasClass("enable-filter") ? $(this).find('.progressive-card.filtered') : $(this).find('.progressive-card');
                cards.each(function () {
                    if (cardCounter >= (initialLoad)) {
                        cards.eq(cardCounter).hide().slideDown();
                    }
                    cardCounter = cardCounter + 1;
                });
            });
            allButton.attr('tabindex', '-1').addClass('screenReaderOnly');
            allButton.attr('aria-hidden', 'true');
            lessButton.attr('tabindex', '0').removeClass('screenReaderOnly').removeClass('adjustive-margin-left').removeClass('adjustive-margin-right');
            lessButton.attr('aria-hidden', 'false');
            lessButton.show();
            lessButton.trigger("focus");
        });

        viewAll.on('keydown', function (e) {
            $this = $(this);
            var keyCode = e.which;
            var viewAllBlock = $(this).closest('.progressive');
            var lessButton = viewAllBlock.find('.view-less-cards');

            var visibleCard = viewAllBlock.find(".progressive-card:visible").first();
            var hasLink = visibleCard.find(":focusable").first();

            if ($this && $this.trigger("focus")) {
                if (keyCode == 13 || keyCode == 32) {
                    $this.addClass("keyed");
                    $this.trigger("click");
                    lessButton.addClass("keyed");
                }
                else if (keyCode == 27) {
                    $this.tooltip("hide");
                    $this.trigger("blur");
                }

                if (keyCode == 9) {
                    if ($this.hasClass("keyed") && hasLink.length !== 0) {
                        e.preventDefault();
                        $this.removeClass("keyed");
                        if (!e.shiftKey) {
                            focusFirstCardHA(viewAllBlock);
                        }
                        else if (e.shiftKey) {
                            focusLastCardST(viewAllBlock);
                        }
                    }
                }
            }
        });
    }

    var viewLessCards = function () {
        viewLess.on('click', function () {
            var viewLessBlock = $(this).closest('.progressive');
            var cardCounter = 0;
            addEllipsis();
            var initialLoad;
            if (isMobile()) {
                initialLoad = $(this).closest('.progressive').attr('data-cards-xs');
            } else if (isTablet()) {
                initialLoad = $(this).closest('.progressive').attr('data-cards-sm');
            } else {
                initialLoad = $(this).closest('.progressive').attr('data-cards-lm');
            }

            var allButton = viewLessBlock.find('.view-all-cards');
            var lessButton = viewLessBlock.find('.view-less-cards');
            var moreButton = viewLessBlock.find('.view-more-cards');
            var inclessButton = viewLessBlock.find('.view-incless-cards');

            viewLessBlock.each(function () {
                var cards = $(this).hasClass("enable-filter") ? $(this).find('.progressive-card.filtered') : $(this).find('.progressive-card');
                cards.each(function () {
                    if (cardCounter >= (initialLoad)) {
                        cards.eq(cardCounter).show().slideUp('slow');
                    }
                    cardCounter = cardCounter + 1;
                });
            });
            moreButton.attr('tabindex', '0').removeClass('screenReaderOnly');
            moreButton.attr('aria-hidden', 'false');
            allButton.attr('tabindex', '0').removeClass('screenReaderOnly');
            allButton.attr('aria-hidden', 'false');
            lessButton.attr('tabindex', '-1').addClass('screenReaderOnly');
            lessButton.attr('aria-hidden', 'true');
            inclessButton.attr('tabindex', '0').removeClass('screenReaderOnly');
            inclessButton.attr('aria-hidden', 'false');

            if (viewLessBlock.hasClass("view-more")) {
                moreButton.attr('tabindex', '0').removeClass('adjustive-margin-right');
                moreButton.show();
                inclessButton.hide();
                moreButton.addClass("LessKeyed");
                moreButton.trigger("focus");
            }
            else {
                allButton.show();
                lessButton.hide();
                allButton.trigger("focus");
            }
        });
        viewLess.on('keydown', function (e) {
            $this = $(this);
            var keyCode = e.which;
            var viewLessBlock = $(this).closest('.progressive');

            var visibleCard = viewLessBlock.find(".progressive-card:visible").first();
            var hasLink = visibleCard.find(":focusable").first();

            if ($this && $this.trigger("focus")) {
                if (keyCode == 13 || keyCode == 32) {
                    $this.trigger("click");
                    $this.addClass("keyed");
                }
                else if (keyCode == 27) {
                    $this.tooltip("hide");
                    $this.trigger("blur");
                }
            }
            var viewLessBlock = $this.closest('.progressive');
            if (keyCode == 9 && !e.shiftKey) {
                if ($this.hasClass("keyed") && hasLink.length !== 0) {
                    e.preventDefault();
                    $this.removeClass("keyed");
                    focusFirstCard(viewLessBlock); //prfilesblock hide all
                }
            }
            else if (keyCode == 9 && e.shiftKey) {
                if ($this.hasClass("keyed") && hasLink.length !== 0) {
                    e.preventDefault();
                    $this.removeClass("keyed");
                    focusLastCardST(viewLessBlock);
                }
            }

        });

    }

    var viewMoreCards = function () {
        var cardIncrement = 0;
        var currentCards = 0;
        var scrollValue = 0;

        viewMore.on('click', function () {

            var viewMoreBlock = $(this).closest('.progressive');
            var cardCounter = 0;
            var ctr = 0;
            addEllipsis();

            var moreButton = viewMoreBlock.find('.view-more-cards');
            var lessButton = viewMoreBlock.find('.view-less-cards');
            var incLessButton = viewMoreBlock.find('.view-incless-cards');

            if (isMobile()) {
                cardIncrement = $('.related-leadership').attr('incr-cards-xs');
                scrollValue = 550;
            } else if (isTablet()) {
                cardIncrement = $('.related-leadership ').attr('incr-cards-sm');
                scrollValue = 350;
            } else {
                cardIncrement = $('.related-leadership ').attr('incr-cards-lm');
                scrollValue = 480;
            }

            currentCards = $(".progressive-card.filtered:visible").length;
            cardIncrement = parseInt(cardIncrement);

            viewMoreBlock.each(function () {
                var vcards = $(this).hasClass("enable-filter") ? $(this).find('.progressive-card.filtered') : $(this).find('.progressive-card');

                vcards.each(function () {
                    if (cardCounter >= (currentCards) && (ctr < cardIncrement)) {

                        vcards.eq(cardCounter).hide().slideDown();
                        ctr++;
                    }

                    cardCounter++;
                });
            });

            var visibleCards = $(".progressive-card.filtered:visible");
            currentCards = visibleCards.length;

            if (cardCounter == currentCards) {
                moreButton.attr('tabindex', '-1').addClass('screenReaderOnly');
                moreButton.attr('aria-hidden', 'true');
                lessButton.attr('tabindex', '0').removeClass('screenReaderOnly').addClass('adjustive-margin-left');
                lessButton.attr('aria-hidden', 'false');
                incLessButton.attr('tabindex', '0').removeClass('adjustive-margin-left').addClass('adjustive-margin-right');
                lessButton.show();
                incLessButton.trigger("focus");
                incLessButton.addClass("hkeyed");
                moreButton.hide();
                if (!incLessButton.is(':visible')) {
                    lessButton.attr('tabindex', '0').removeClass('adjustive-margin-right').removeClass('adjustive-margin-left');
                }
            }
            else {
                moreButton.attr('tabindex', '0').addClass('adjustive-margin-right');
                incLessButton.attr('tabindex', '0').addClass('adjustive-margin-left').removeClass('screenReaderOnly').removeClass('adjustive-margin-right');
                incLessButton.attr('aria-hidden', 'false');
                incLessButton.show();
            }

            firstCardnew = visibleCards.eq(currentCards - ctr).find(':focusable');
            window.scroll(0, (visibleCards.eq(currentCards - ctr).position().top) + scrollValue);

            return firstCardnew;
        });

        var firstCardnew;

        viewMore.on('keydown', function (e) {
            $this = $(this);
            var keyCode = e.which;
            if ($this && $this.trigger("focus")) {
                if (keyCode == 13 || keyCode == 32) {
                    $this.trigger("click");
                    $this.addClass("keyed");
                }
                else if (keyCode == 27) {
                    $this.tooltip("hide");
                    $this.trigger("blur");
                }
            }
            var viewIncLessBlock = $(this).closest('.progressive');
            var visibleCard = viewIncLessBlock.find(".progressive-card:visible").first();
            var hasLink = visibleCard.find(":focusable").first();

            if (keyCode == 9 && !e.shiftKey) {
                if ($this.hasClass("keyed")) {
                    e.preventDefault();
                    firstCardnew.trigger("focus");
                    $this.removeClass("keyed");

                }
                if ($this.hasClass("LessKeyed") && hasLink.length !== 0) {
                    e.preventDefault();
                    $this.removeClass("LessKeyed");
                    focusFirstCardHA(viewIncLessBlock);
                }

            }
            else if (keyCode == 9 && e.shiftKey) {
                if ($this.hasClass("LessKeyed") && hasLink.length !== 0) {
                    e.preventDefault();
                    $this.removeClass("LessKeyed");
                    focusLastCardST(viewIncLessBlock);

                }
                if ($this.hasClass("keyed") && hasLink.length !== 0) {
                    e.preventDefault();
                    $this.removeClass("keyed");
                    focusLastCardST(viewIncLessBlock);

                }
            }

        });
    }

    var viewIncLessCards = function () {
        var initialCardCount = 0;
        var cardIncrement = 0;
        var currentCards = 0;
        var visibleCards;
        var scrollValue = 0;

        incLess.on('click', function () {
            var ctr = 0;

            var viewIncLessBlock = $(this).closest('.progressive');
            addEllipsis();

            var moreButton = viewIncLessBlock.find('.view-more-cards');
            var incLessButton = viewIncLessBlock.find('.view-incless-cards');
            var lessButton = viewIncLessBlock.find('.view-less-cards');

            if (isMobile()) {
                cardIncrement = $('.related-leadership').attr('incr-cards-xs');
                initialCardCount = $('.related-leadership ').attr('data-cards-xs');
                scrollValue = 550;
            } else if (isTablet()) {
                cardIncrement = $('.related-leadership ').attr('incr-cards-sm');
                initialCardCount = $('.related-leadership ').attr('data-cards-sm');
                scrollValue = 350;
            } else {
                cardIncrement = $('.related-leadership ').attr('incr-cards-lm');
                initialCardCount = $('.related-leadership ').attr('data-cards-lm');
                scrollValue = 480;
            }

            cardIncrement = parseInt(cardIncrement);
            initialCardCount = parseInt(initialCardCount);

            viewIncLessBlock.each(function () {
                visibleCards = $(".progressive-card.filtered:visible");
                var length = visibleCards.length - 1;
                visibleCards.each(function () {
                    if (length >= (initialCardCount) && (ctr < cardIncrement)) {

                        visibleCards.eq(length).hide().slideUp();
                        ctr++;
                    }

                    length--;
                });
            });

            visibleCards = $(".progressive-card.filtered:visible");
            currentCards = visibleCards.length;

            if (initialCardCount === currentCards) {
                moreButton.attr('tabindex', '0').removeClass('screenReaderOnly').removeClass('adjustive-margin-left').removeClass('adjustive-margin-right');
                moreButton.attr('aria-hidden', 'false');
                incLessButton.attr('tabindex', '1').addClass('screenReaderOnly');
                incLessButton.attr('aria-hidden', 'true');
                incLessButton.hide();
                moreButton.show();
                moreButton.addClass("LessKeyed");
                moreButton.trigger("focus");
            }
            else {
                moreButton.attr('tabindex', '0').removeClass('screenReaderOnly');
                moreButton.attr('aria-hidden', 'false');
                lessButton.attr('tabindex', '-1').addClass('screenReaderOnly');
                lessButton.attr('aria-hidden', 'true');
                incLessButton.attr('tabindex', '0').removeClass('adjustive-margin-right').addClass('adjustive-margin-left');

                moreButton.show();
                moreButton.trigger("focus");
                lessButton.hide();
            }
            LessCardNew = visibleCards.eq(currentCards - cardIncrement).find(':focusable');

            window.scroll(0, (visibleCards.eq(currentCards - cardIncrement).position().top) + scrollValue);

            return LessCardNew;
        });
        var LessCardNew;

        //focus to the first card of the last added set of cards ,RLB only
        var focusLastCard = function (parent) {
            var cardIncrement = 0;
            var visibleCards = 0;
            var currentCards = 0;
            if (isMobile()) {
                cardIncrement = $('.related-leadership').attr('incr-cards-xs');
                scrollValue = 550;
            } else if (isTablet()) {
                cardIncrement = $('.related-leadership ').attr('incr-cards-sm');
                scrollValue = 350;
            } else {
                cardIncrement = $('.related-leadership ').attr('incr-cards-lm');
                scrollValue = 480;
            }
            visibleCards = $(".progressive-card.filtered:visible");
            currentCards = visibleCards.length;
            var firstCard = parent.find(".progressive-card:visible").eq(currentCards - cardIncrement); // backup
            var cardLinks = firstCard.find(":focusable").first();
            cardLinks.each(function (index, card) {
                if (card.tabIndex == 0) {
                    card.focus();
                    return false;
                }
            });
        }

        incLess.on('keydown', function (e) {
            $this = $(this);
            var keyCode = e.which;
            if ($this && $this.trigger("focus")) {
                if (keyCode == 13 || keyCode == 32) {
                    $this.addClass("keyed");
                    $this.trigger("click");
                    $this.trigger("focus");
                }
                else if (keyCode == 27) {
                    $this.tooltip("hide");
                    $this.trigger("blur");
                }
            }
            var viewIncLessBlock = $this.closest('.progressive');
            var visibleCard = viewIncLessBlock.find(".progressive-card:visible").first();
            var hasLink = visibleCard.find(":focusable").first();

            if ($this.hasClass("keyed")) {
                if (keyCode == 9 && !e.shiftKey) {
                    e.preventDefault();
                    $this.removeClass("keyed");
                    LessCardNew.trigger("focus");
                }
                else if (keyCode == 9 && e.shiftKey) {
                    e.preventDefault();
                    $this.removeClass("keyed");
                    focusLastCardST(viewIncLessBlock);

                }

            }

            if ($this.hasClass("hkeyed") && hasLink.length !== 0) {

                if (keyCode == 9 && !e.shiftKey) {
                    e.preventDefault();
                    focusLastCard(viewIncLessBlock);
                    $this.removeClass("hkeyed");
                }
                if (keyCode == 9 && e.shiftKey) {
                    e.preventDefault();
                    $this.removeClass("hkeyed");
                    focusLastCardST(viewIncLessBlock);

                }
            }

        });
    }
    //RMT8363 Progressive Display - end

    //RMT9081
    var setDataInlineLink = function () {
        var InlineLink = $('#redesign-main .richtext a, #redesign-main .content-module a, #interactive-main .richtext a, #interactive-main .content-module a');

        InlineLink.attr('data-linkcomponentname', 'inline link');
        InlineLink.attr('data-linktype', 'engagement');
    }

    var setDataProfiles = function () {
        var profileLink = $('.speaker-bio a');

        profileLink.attr('data-analytics-link-name', 'profiles');
        profileLink.attr('data-analytics-content-type', 'engagement');
        profileLink.attr('data-linkcomponentname', 'profiles');
        profileLink.attr('data-linktype', 'engagement');
    }

    var ReplaceEncodedKeyword = function (keyword) {
        if (keyword.indexOf("/") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "/", "%2F");
        if (keyword.indexOf("?") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "\\?", "%3F");
        if (keyword.indexOf(":") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, ":", "%3A");
        if (keyword.indexOf("@") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "@", "%40");
        if (keyword.indexOf("=") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "=", "%3D");
        if (keyword.indexOf("&") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "&", "%26");
        if (keyword.indexOf("#") > -1)
            keyword = ReplaceAllReservedCharacter(keyword, "#", "%23");

        return keyword;
    };

    var ReplaceAllReservedCharacter = function (str, find, replace) {
        return str.replace(new RegExp(find, 'g'), replace);
    };

    //ADO1149194 - PII redaction
    var removeEmailInURL = function () {
        var currUrl = window.location.href;
        var regexExp = new RegExp('[?|&][a-zA-Z0-9+._-]+=[a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+[a-z0-9](?:[a-z0-9-]*[a-z0-9])&?');

        if (currUrl.match(regexExp)) {
            if (currUrl.match(regexExp).indexOf('?')) {
                currUrl = currUrl.replace(regexExp, "?");
            }

            while (currUrl.match(regexExp)) {
                currUrl = currUrl.replace(regexExp, "&");
            }

            currUrl = currUrl.match('[&|?]$') ? currUrl.substring(0, currUrl.length - 1) : currUrl;

            history.pushState({}, "", currUrl);
        }
    };

    //ADO 1083474
    var updatePaddingBottom = function () {

        var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
        var ih = (iOS) ? document.documentElement.clientHeight : window.innerHeight;

        var bodyHeight = parseInt($('body').css('height'), 10);
        var lastBlock = $('#footer-block').prev().children().last();
        var differenceInHeight = ih - bodyHeight;
        var lastBlockPadding = lastBlock.css('padding-bottom');


        if (lastBlock.hasClass('block-ribbon')) {
            lastBlock = lastBlock.prev().last();
        }

        if (differenceInHeight < 0) {
            lastBlock.css('padding-bottom', 0);
            differenceInHeight = ih - bodyHeight;
            lastBlock.css('padding-bottom', parseInt(lastBlockPadding, 10) + differenceInHeight);
        }
        if (ih > bodyHeight) { //if the screen is bigger than the body -> less contents

            if (lastBlockPadding !== undefined) {
                lastBlock.css('padding-bottom', parseInt(lastBlockPadding, 10) + differenceInHeight);
            }
            else {
                lastBlock.css('padding-bottom', differenceInHeight);
            }

        }
    }

    var removeFocusIndicatorOnClick = function () {
        var focusableElements = $("a, button, div[role='tab'], div[role='button'], div[role*='link'], div[class='ion'], div[class*='gh-item'], li[role='tab'], div[role='listitem'], input[class*='progressbar']");
        var $modal = $('.modal');
        var $contentWrapper = $('.content-wrapper');
        var $skipLink = $('.skip-link');

        if ($contentWrapper.hasClass('focus-indicator')) {
            $modal.addClass('focus-indicator');
            $contentWrapper.addClass('focus-indicator');
            $skipLink.addClass('focus-indicator');

            focusableElements.on('mousedown', function () {
                var $this = $(this);
                if (!$this.hasClass('nav-submenu-label')) {
                    setTimeout(function () {
                        $this.trigger("blur");
                    }, 0);
                }
            });
        }

        if ($contentWrapper.hasClass('focus-indicator-interactive')) {
            $modal.addClass('focus-indicator');
            $contentWrapper.addClass('focus-indicator');
            $skipLink.addClass('focus-indicator');

            focusableElements.on('mousedown', function () {
                var $this = $(this);
                if (!$this.hasClass('nav-submenu-label')) {
                    setTimeout(function () {
                        $this.trigger("blur");
                    }, 0);
                }
            });
        }
    };

    //ADO1207614
    var updateThirdPartyLinks = function () {
        $('a[target$="_blank"]').each(function () {
            var relAttr = $(this).attr('rel');

            if (typeof relAttr === typeof undefined || relAttr === false) {
                $(this)[0].setAttribute("rel", "noopener");
            }
        });
    };
    //remove role=link for Brandpurpose page footer
    var brandpurposeAccessibilityUpdate = function () {
        $('#brandpurpose-main').siblings('#footer-block').find('.footer-links a, .social-icons a').removeAttr('role');
        $('#brandpurpose-main').siblings('#footer-block').find('.footer-links a, .social-icons a').attr("data-container","#footer-block");

    };

    //TLA App
    var hideHeaderAndCookie = function () {
        var currentUrl = window.location.href.toLowerCase();
        if (currentUrl.indexOf("tlaapp") !== -1 || currentUrl.indexOf("tlaappcb") !== -1) {
            var $elem = $("a").not("[class^='ion-social'] ,.anchor-custom-link");
            var tlaParam = currentUrl.indexOf("tlaappcb") > -1 ? "tlaAppCB" : "tlaApp";
            $elem.each(function () {
                var $this = $(this);
                var hashLoc = "";
                var firstUrl = "";
                var lastUrl = "";
                var delimiter = $this.attr("href").indexOf("?") > -1 ? "&" : "?";
                var anchorUrl = $this.attr("href");
                if ((anchorUrl !== undefined) && (anchorUrl !== "" || anchorUrl !== "#") && anchorUrl.indexOf(".pdf") === -1) {

                    if (anchorUrl.indexOf("#") > -1) {
                        hashLoc = anchorUrl.indexOf("#");
                        firstUrl = anchorUrl.substring(0, hashLoc);
                        lastUrl = anchorUrl.substring(hashLoc, anchorUrl.length);
                        $this.attr("href", firstUrl + delimiter + tlaParam + lastUrl);
                    }
                    else {
                        $this.attr("href", anchorUrl + delimiter + tlaParam);
                    }

                }
            });

            //fix for added navigation bars through content
            if ($('.navbar-light .row.itn-nav').length > 0) {
                if (isMobile()) {
                    $('.navbar-light').css('top', '-8px');
                } else {
                    $('.navbar-light').css('top', 0);
                }
            }
            if ($('#redesign-main .progress-nav-bar').length > 0) 
                $('#redesign-main .progress-nav-bar').css('top', 0);
            
            if ($('#redesign-main nav.navbar.navbar-light.bg-light').length > 0) 
                $('#redesign-main nav.navbar.navbar-light.bg-light').css({ 'margin-top': 0, 'top': 0 });
        }

    };

    return {
        init: init,
        isTablet: isTablet,
        isMobile: isMobile,
        isFirefox: isFirefox,
        lazyLoadModule: lazyLoadModule,
        redirectBlockProfileOnLoad: redirectBlockProfileOnLoad,
        setFeaturedImage: setFeaturedImage,
        isMobileBrowser: isMobileBrowser,
        viewLessCards: viewLessCards,
        viewAllCards: viewAllCards,
        viewMoreCards: viewMoreCards,
        viewIncLessCards: viewIncLessCards,
        progressiveSetup: progressiveSetup,
        setDynamicBackground: setDynamicBackground,
        setHeroImage: setHeroImage,
        resizeHeroImage: resizeHeroImage,
        setGapWidth: setGapWidth,
        ellipsisFunction: ellipsisFunction,
        removeTags: removeTags,
        ReplaceEncodedKeyword: ReplaceEncodedKeyword,
        updatePaddingBottom: updatePaddingBottom,
        removeEmailInURL: removeEmailInURL,
        removeFocusIndicatorOnClick: removeFocusIndicatorOnClick,
        setLocationResult: setLocationResult,
        updateThirdPartyLinks: updateThirdPartyLinks,
        onHoverDetails: onHoverDetails
    }
})();

//Will be removed once SERP functionality for Redesign is done
function Bootstraploader() {
    var validatorExists = $('head').find("script[src*='bootstrapValidator.js']").length > 0;

    if (!validatorExists) {
        var bootstrapScript = document.createElement('script'), d = false;
        bootstrapScript.async = true;
        bootstrapScript.src = "/Scripts/lib/bootstrapValidator.js";
        bootstrapScript.type = "text/javascript";
        bootstrapScript.onload = bootstrapScript.onreadystatechange = function () {
            var bootstrapReadyState = this.readyState;
            //Validate if script is downloaded successfully.
            if (!d && bootstrapReadyState == "complete" || bootstrapReadyState == "loaded") {
                d = true;
                InitializeBootstrapValidator(); //Callback
            }
        };
        $('head').append(bootstrapScript);
    }
};

var smallMin = 768;
var smallMax = 999;

function IsIE() {
    if ($('html').hasClass('ie')) {
        return true;
    } else {
        return false;
    }
};

var skipLinksFocus = function () {
    if (IsIE()) {
        var mainContent = $('#redesign-main');
        var footerContent = $('#footer-block');

        mainContent.attr('tabindex', '-1');
        footerContent.attr('tabindex', '-1');
    }
};
function isMobile() {
    if ($(window).width() < smallMin) {
        return true;
    } else {
        return false;
    }
};
function isTablet() {
    if ($(window).width() >= smallMin && $(window).width() <= smallMax) {
        return true;
    } else {
        return false;
    }
};

function accessBarAdjustment() {
    // Select the node to observe
    var targetNode = document.getElementsByTagName("BODY")[0];

    // If the targetNode exists on our page
    if (targetNode) {

        // Watch when nodes are added to targetNode, or its descendants
        var config = {
            childList: true,
            subtree: true
        };

        // When mutation is observed
        var callback = function (mutationsList) {

            var stickyAccessBar = $('.sticky-access-bar');
            var stickyHeight = stickyAccessBar.height();

            for (var mutation in mutationsList) {
                // If Sticky Access Bar is enabled, apply bottom spacing on content-wrapper and cookie
                if (stickyAccessBar.length > 0) {
                    stickyAccessBar.closest('.content-wrapper').css('padding-bottom', stickyHeight);
                    $('.optanon-alert-box-wrapper,.optanon-toggle-display').css('margin-bottom', stickyHeight);
                } else {
                    // Stop observing, we did what we needed
                    observer.disconnect();
                }
            }
        };

        // Create a new observer
        var observer = new MutationObserver(callback);

        // Start observing
        observer.observe(targetNode, config);
    }
};

//Will be removed once SERP functionality for Redesign is done
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\global-header.js
/*  version="114" */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['utility'], function (utility) {
            root.GlobalHeader = factory(utility);
        });
    } else {
        /* NOTES: Purpose of .off() jquery native function
        is to prevent multiple fired event during orientation change */
        root.GlobalHeader = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.GlobalHeaderSettings) {

            /* Adjust Header in Preview */
            function adjustHeaderForPreview() {
                if ($('#scCrossPiece').length > 0 && $('#scFieldValues').length <= 0) {
                    $('.navbar-fixed-top').css('top', $('#scCrossPiece').height());
                }
                else { setTimeout(adjustHeaderForPreview, 2500); }
            };

            $(window).on("load", function () {
                root.GlobalHeader.addBodyId();
                root.GlobalHeader.elements.$tertiaryNav.css('display', 'none');
                var frameParent = $('#scWebEditRibbon');
                if (frameParent.length > 0 && $('#scFieldValues').length <= 0) {
                    adjustHeaderForPreview();
                    //add event handler
                    var siteCoreButton = $("a[data-sc-id='QuickRibbon']", frameParent.contents());
                    siteCoreButton.on('click dblclick', function () {
                        setTimeout(adjustHeaderForPreview, 50);
                    });
                }
            });

            $(function () {
                if ($("html").hasClass("ie")) {
                    root.GlobalHeader.elements.$navMenu.attr("role", "tablist");
                    root.GlobalHeader.elements.$navLabel.attr("role", "tab");
                }
                root.GlobalHeader.elements.$viewPortWidth = $(document).width();
                root.GlobalHeader.elements.$deviceHeight = $(window).height();
                root.GlobalHeader.init();
                $(document).on('touchmove', function (e) {
                    var navContent = root.GlobalHeader.elements.$navContent
                    if (navContent.has($(e.target)).length && jsUtility.isMobile() && !(navContent.outerHeight() < navContent.get(0).scrollHeight)) {
                        e.preventDefault();
                    }
                });

                /* Remove Duplicate Signout IDs */
                $(function () {
                    var isSecondMenuSignOut = $("#second-contact-link div.signin-links ul").find("li").last();
                    var isMenuFooterSignOut = $("#menuFooter div.signin-links ul").find("li").last();
                    var isPopOverSignOut = $("div.popover-content div.signin-links ul").find("li").last();
                    var isAuthUser = $("#navUserDisplayUserName").parents(".gh-item.signin-container");
                    var menuFooterParent = isMenuFooterSignOut.prop('parentElement');
                    var secondMenuParent = isSecondMenuSignOut.prop('parentElement');
                    var popOverParent = isPopOverSignOut.prop('parentElement');
                    var menuFooterSib = isMenuFooterSignOut.prop('previousSibling');
                    var secondMenuSib = isSecondMenuSignOut.prop('previousSibling');
                    var popOverSib = isPopOverSignOut.prop('previousSibling');
                    $("a#signout").attr('data-analytics-link-name', 'sign out');

                    if ($(".popover").length > 0) {
                        isSecondMenuSignOut.detach();
                        isMenuFooterSignOut.detach();

                        $(".nav-icon-container").on("click", function (e) {
                            if (menuFooterSib !== undefined) {
                                isMenuFooterSignOut.appendTo(menuFooterParent);
                            }
                            menuFooterSib = menuFooterParent = undefined;
                        });

                        $("li.col-sm-12.secondary-item").on("click", function (e) {
                            if (secondMenuSib !== undefined) {
                                isSecondMenuSignOut.appendTo(secondMenuParent);
                            }
                            secondMenuSib = secondMenuParent = undefined;
                        });
                    }

                    isAuthUser.on("click", function (e) {
                        var $this = $(this);
                        var isPopOverSignOutPresent = $("div.popover-content div.signin-links ul li a#signout").length > 0;
                        if (isPopOverSignOutPresent === 0) {
                            if (popOverSib !== undefined) {
                                isPopOverSignOut.appendTo(popOverParent);
                            }
                        }
                    });

                });

                /* Adjust Global Header when using No Squint */
                var $logoListener = document.getElementsByClassName('gh-item acn-logo');
                var observer = new MutationObserver(function (mutations) {
                    var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
                    var $layoutColumn = $(".layout-column");
                    var $secondaryNavs = $(".secondary-navs.panel-collapse");
                    var $countryForm = $('.country-form');
                    var $countryList = $('#location-recommendation ul > li');
                    var $body = $('body');
                    var $navSubmenu = $('.secondary-nav-menu');
                    var $signInContainer = $(".signin-container");
                    var $signInText = $(".signin.ucase");
                    var $signInTextSize = parseInt($signInText.css("font-size"));
                    var $ulitlityNav = $(".utility-nav");
                    var $authenticated = $(".popover.show");
                    var $width = $(document).width() - ($('.acn-logo.gh-item').width() + parseInt($('.primary-nav').css('padding-left')) + $('.utility-nav').width());

                    if ($("#wave_sidebar_container").length == 0 && !jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                        if (root.GlobalHeader.elements.$baseFontsize != 0 && (root.GlobalHeader.elements.$baseFontsize < $currentFontSize)) {
                            root.GlobalHeader.elements.$tertiaryItem.css({ "min-width": " auto" });
                            root.GlobalHeader.elements.$secondaryItem.css({ "word-break": " break-word" });
                            root.GlobalHeader.elements.$primaryNav.css({ "width": $width });
                            $countryForm.css({ 'z-index': '3', 'height': 'auto', "margin-top": "3.13em" });
                            $countryList.css({ 'height': 'auto' });
                            $authenticated.css({ "word-break": " break-word" });
                        }

                        if ($signInText.outerHeight() > $signInContainer.height()) {
                            $signInText.removeAttr("style");
                            $signInContainer.removeAttr("style");
                        } else if ($signInTextSize == root.GlobalHeader.elements.$baseFontsize) {
                            $signInText.css({ 'line-height': '4.38em' });
                        }

                        if ($currentFontSize >= (root.GlobalHeader.elements.$baseFontsize * 1.50)) {
                            root.GlobalHeader.elements.$primaryNav.css({ "width": $width });
                            $layoutColumn.find(".multiple-l3").children().last().css({ "word-break": " break-word" });
                            $body.css('padding-top', '0');
                            $ulitlityNav.css({ "z-index": "999" });
                            $secondaryNavs.css({ "padding-top": "3.13em", "height": "auto" });
                            root.GlobalHeader.elements.$divContainer.css({ "margin-top": "4.38em;" });
                            $countryForm.css({ 'z-index': '3', 'height': 'auto', "margin-top": "3.13em" });
                        }

                        else if ($currentFontSize >= (root.GlobalHeader.elements.$baseFontsize * 1.40)) {
                            $layoutColumn.find(".multiple-l3").children().last().css({ "word-break": " break-word" });
                            root.GlobalHeader.elements.$tertiaryItem.css({ "min-width": " auto" });
                            root.GlobalHeader.elements.$secondaryItem.css({ "word-break": " break-word" });
                            $ulitlityNav.css({ "z-index": "999" });
                            $countryForm.css({ 'z-index': '3' });
                        }

                        else {
                            root.GlobalHeader.elements.$primaryNav.css({ "width": "auto" });
                            $layoutColumn.find(".multiple-l3").children().last().css({ "word-break": "" });
                            $body.css('padding-top', "");
                            $signInText.css({ "line-height": "" });
                            $signInContainer.css({ "line-height": "" });
                            $secondaryNavs.css({ "padding-top": "0", "height": "", "top": "" });
                            root.GlobalHeader.elements.$divContainer.css({ "margin-top": '0' });
                            $countryForm.css({ 'z-index': '1' });
                            $navSubmenu.css({ 'height': 'auto' });
                            $authenticated.css({ "word-break": "" });
                        }
                    }
                });

                if ($logoListener != null && $logoListener.length > 0) {
                    observer.observe($logoListener[0], { attributes: true });
                }

                $('.acn-logo.gh-item').css('z-index', 'auto');
                if ($('div .signin-links').length > 0)
                    $('div .signin-links a').attr('data-linkcomponentname', 'top nav')

                var zoomLevel = function () {
                    var estWindowZoom = Math.round((window.devicePixelRatio) * 100);
                    return estWindowZoom;
                }

                if (zoomLevel() > 100 || jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                    var isPrimaryLinkPresent = $('#nav-icon').parents(".primary-nav").length > 0;
                    var hamburgerIconContainer = $(".nav-icon-container");

                    if (isPrimaryLinkPresent) {
                        hamburgerIconContainer.attr({ 'tabindex': 0, 'aria-label': 'menu' });
                    }
                }

            });

            window.addEventListener("orientationchange", function () {
                root.GlobalHeader.elements.$divContainer.css({ 'top': '', 'opacity': '' });
                setTimeout(function () {
                    root.GlobalHeader.elements.$viewPortWidth = $(document).width();
                    root.GlobalHeader.elements.$deviceHeight = $(window).height();
                    if (!jsUtility.isTablet() && !jsUtility.isMobile()) {
                        var utilitywidth = parseInt($('.utility-nav').width());
                        var padding = parseInt(root.GlobalHeader.elements.$primaryNav.css('padding-left'));
                        var newWidth = root.GlobalHeader.elements.$viewPortWidth - (padding + utilitywidth)-1;
                        root.GlobalHeader.menuControl.closeTabletMenu();
                        root.GlobalHeader.menuControl.closeTertiaryMenu();
                        root.GlobalHeader.elements.$primaryNav.css('width', newWidth);
                        root.GlobalHeader.elements.$navMenu.parent().removeClass('hidden');
                    } else {
                        root.GlobalHeader.elements.$primaryNav.css('width', "");
                    }
                }, 300);
                root.GlobalHeader.menuControl.initializeMenu();
                root.GlobalHeader.menuControl.initializeAnalytics();
            }, false);

            $(window).on("resize", function () {
                var zoomLevel = function () {
                    var estWindowZoom = Math.round((window.devicePixelRatio) * 100);
                    return estWindowZoom;
                }
                var isInternetExplorer = (navigator.appName == 'Microsoft Internet Explorer' || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)));
                var isSafari = (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1);

                /* MOBILE */
                if (jsUtility.isMobile() && !jsUtility.isTablet()) {
                    if (isInternetExplorer || isSafari) {
                        if (zoomLevel() >= 200) {
                            root.GlobalHeader.menuControl.initializeAccessibleHamburgerIcon();
                            root.GlobalHeader.menuControl.initializeAccessibleNavSubMenu();
                        }
                        root.GlobalHeader.menuControl.initializeAccessibleHamburgerIcon();
                        root.GlobalHeader.menuControl.initializeAccessibleNavSubMenu();
                    }
                }

                /* TABLET */
                if (!jsUtility.isMobile() && jsUtility.isTablet()) {
                    root.GlobalHeader.menuControl.closeTabletMenu();
                    if (root.GlobalHeader.elements.$countrySelectorCont.hasClass(root.GlobalHeader.elements.$toggleCountryList)) {
                        root.GlobalHeader.elements.$countrySelectorCont.removeClass(root.GlobalHeader.elements.$toggleCountryList);
                    }

                    if ($("html").hasClass("safari")) {
                        root.GlobalHeader.elements.$primaryNav.css('width', '');
                    }

                    root.GlobalHeader.elements.$acnLogoContainer.removeClass('hidden');
                    root.GlobalHeader.menuControl.initializeAccessibleHamburgerIcon();
                    root.GlobalHeader.menuControl.initializeAccessibleNavSubMenu();
                }
                /* DESKTOP */
                if (!jsUtility.isMobile() && !jsUtility.isTablet()) {
                    $grid = $('.layout-column .multiple-l3').packery({ itemSelector: '.secondary-item', percentPosition: true });
                    root.GlobalHeader.menuControl.closeTabletMenu();
                    root.GlobalHeader.menuControl.closeMobileMenu();
                    root.GlobalHeader.menuControl.closeTertiaryMenu();
                    root.GlobalHeader.showHideSecondaryNav.hideSubNav();

                    if ($("html").hasClass("safari") && $('.nav-icon-container').css('display') == 'none') {
                        var utilitywidth = parseInt($('.utility-nav').width());
                        var padding = parseInt(root.GlobalHeader.elements.$primaryNav.css('padding-left'));

                        var newWidth = $(window).width() - (padding + utilitywidth);
                        root.GlobalHeader.menuControl.closeTabletMenu();
                        root.GlobalHeader.menuControl.closeTertiaryMenu();
                        root.GlobalHeader.elements.$primaryNav.css('width', newWidth);
                        root.GlobalHeader.elements.$navMenu.parent().removeClass('hidden');
                    }
                    if (isSafari) {
                        root.GlobalHeader.menuControl.removeAccessibleHamburgerIcon();
                        root.GlobalHeader.menuControl.removeAccessibleNavSubMenu();
                    }
                    root.GlobalHeader.elements.$navContent.removeClass('hidden');
                    //function for pagezoom 
                    root.GlobalHeader.NavMenuScrollOnZoom();
                    root.GlobalHeader.menuControl.removeAccessibleNavSubMenu();
                }
                root.GlobalHeader.menuControl.initializeMenu();
                root.GlobalHeader.menuControl.initializeAnalytics();
                root.GlobalHeader.destroyPackery('.layout-column .multiple-l3');
            });
        }
    }

})(typeof self !== 'undefined' ? self : this, function () {

    /* GLOBAL VARIABLES */
    var $baseFontsize = 16;
    var $viewPortWidth, $deviceHeight;
    var $backDropTablet = $(".back-drop-tablet");
    var $countrySelectorCont = $('.utility-nav .country-form');
    var $mobileShowToggle = 'show-sub-menu';
    var $nav = $(".nav-content .nav-submenu");
    var $navContainer = $('.nav-content');
    var $navIcon = $('#nav-icon');
    var $navIconContainer = $("div.nav-icon-container.hidden-lg");
    var $navLabel = $('div.nav-submenu-label[data-parent= "#navigation-menu"]');
    var $navLabelKeyPressed = $('div.nav-submenu-label');
    var $toggleCountryList = 'show-country-list';
    var $varSearchBody = $('#search-body .search-body-wrapper');
    var $divContainer = $(".secondary-navs");
    var $acnLogoContainer = $('.acn-logo-container');
    var $documentClick = $(document);
    var $navMenu = $('#navigation-menu');
    var $menuFooter = $('#menuFooter');
    var $tertiaryContainer = $('.secondary-item[data-tertiary]');
    var $groupTitle = $('li.col-sm-12.secondary-item');
    var $tertiaryClose = $('.nav-submenu-label-L3');
    var $tertiaryNav = $('#tertiaryNav');
    var $primaryNav = $('.primary-nav');
    var $secondContactLink = $('#second-contact-link');
    var $tertiaryListContainer = $('#tertiaryListContainer')
    var $subMenuLabel = $('.nav-submenu-label');
    var $isTertiaryMenuClosed = false;
    var $userLinks = $(".signin-container");
    var $isHidingSubMenu = false; //true when animation for hiding the desktop submenu is going on
    var $isShowingSubMenu = false;  //true when animation for showing the desktop submenu is going on
    var $isShowingBackdrop = false;
    var $isHidingBackdrop = false;
    var $navContent = $('#nav-content-menu');
    var $tabElements = $('.gh-item'); //Global Header top level items (Acn logo - Primary Links - Utility Navs)
    var $isKeyboard = false;
    var $countrySelect = $('.country-select-cont');
    var $secondaryItem = $(".secondary-item");
    var $headerTopNav = $("#header-topnav");
    var $tertiaryItem = $(".tertiary-item");
    var $navBarDefault = $('.navbar.navbar-default');

    var geoGroupStoredData = "";
    var ACN_COUNTRY_SELECTOR_CAREERS = "CountryLanguageSelectorData_Careers";
    var ACN_COUNTRY_SELECTOR_DOTCOM = "CountryLanguageSelectorData_Dotcom";
    var $grid;
    function addBodyId() {
        $('body').attr('id', 'body-id');
    };

    var init = function () {
        globalHeaderNavigation();
        secondaryLinksContainerAdjustment();
        pollOptanonConsentCookie();
        removeCachedKeywordSearchSession();
        if ($('.search-icon-container.search-trigger').length == 0) {
            globalHeaderSearch();
        }
        globalCountrySelector();
        globalHeaderMap();
        return "init done - all functions invoked";
    };
    /* GLOBAL HEADER CONTROL */

    /* NAVIGATION LINKS */
    var globalHeaderNavigation = function () {
        var prevSubmenu = null;
        var headerSecondaryNav = $(".ie .nav-content .secondary-navs");
        var headerPrimaryNav = $(".ie #block-header-new .primary-nav");
        var headerUtilityNav = $(".ie #block-header-new .utility-nav");
        var headerNavbarBackground = $(".ie #block-header-new .navbar-background");
        var ieSubMenu = $(".ie .nav-content .nav-submenu.panel");
        var ieCookieCloseBtn = $(".ie .cookie-nav .disclaimer-close-btn.close");
        var isKeyPressDown = false;
        var isPackery = false;
        $userLinks.on("keydown", function (e) {
            var code = e.which;
            if (code == 40 || code == 38)
                isKeyPressDown = true;

        });

        $secondContactLink.html($menuFooter.children().clone());
        menuControl.initializeMenu();
        menuControl.initializeAnalytics();

        $documentClick.on("click touchstart", function (event) {
            if (!jsUtility.isMobile() && !jsUtility.isTablet()) {
                if (!$(event.target).closest($navMenu).length && !$navLabel.is(event.target) && !$navIcon.hasClass('open') && !$isHidingSubMenu) {
                    showHideSecondaryNav.hideSubNav();
                }
            }
        });

        /* TABLET */
        if (jsUtility.isTablet() && !jsUtility.isMobile()) {
            $divContainer.removeClass('hidden');
            $navContainer.addClass('hidden');
        }

        /* DESKTOP */
        if (!jsUtility.isTablet() && !jsUtility.isMobile()) {
            $divContainer.addClass('hidden');
            $navContainer.removeClass('hidden');
        }

        /* MOBILE */
        if (jsUtility.isMobile()) { //Mobile Only
            $navContainer.removeClass('hidden');
        }

        $(document).on("click", function (e) {
            if ($('.popover').hasClass('show')) {
                if ($(e.target).closest('#block-header').length === 0) {
                    $('.popover').removeClass("show");
                }
            }
        });

        ieSubMenu.on("click", function () {
            var cookieNav = $(".cookie-nav");
            if (headerSecondaryNav.length > 0) {
                if (cookieNav.length > 0) {
                    headerSecondaryNav.css("padding-top", cookieNav.height() + "px");
                    headerPrimaryNav.css("border-bottom", "1px solid #e3e3e3");
                    headerUtilityNav.css("border-bottom", "1px solid #e3e3e3");
                    headerNavbarBackground.css({ "border-bottom": "1px solid #e3e3e3", "height": "70px" });
                }
            }

        });

        ieCookieCloseBtn.on("click", function () {
            if (headerSecondaryNav.length > 0) {
                headerSecondaryNav.css("padding-top", "");
                headerPrimaryNav.css("border-bottom", "");
                headerUtilityNav.css("border-bottom", "");
                headerNavbarBackground.css({ "border-bottom": "", "height": "" });
            }

        });

        /* AUTHENTICATED USER CLICK */
        $userLinks.on('click', function (e) {
            var $this = $(this);
            var signedIn = $(".ion-ios-contact-outline");
            if (!isKeyPressDown) {
                if (signedIn.length > 0) {
                    var linkPopOver = $('.popover');
                    if (!linkPopOver.is(':visible')) {
                        linkPopOver.addClass("show");
                    } else {
                        linkPopOver.removeClass("show");
                    }

                    $(document.body).on('click.signin-container', function () {
                        var $body = $(this);

                        linkPopOver.hide();
                        $body.off('click.signin-container');
                    });
                }
                else {
                    e.preventDefault();
                    var loginUrl = $this.find("a").attr("href");
                    var loginUrlTarget = $this.find("a").attr("target");
                    loginUrlTarget = loginUrlTarget === undefined || loginUrlTarget === "" ? "_self" : loginUrlTarget;
                    window.open(loginUrl, loginUrlTarget);
                }
            }
            isKeyPressDown = false;
        });

        /* AUTHENTICATED KEYPRESS */
        $userLinks.on('keydown', function (e) {
            var $this = $(this);
            var code = e.which;
            if (code === 13 || code === 32) {
                if ($('div.popover').hasClass("show")) {
                    $this.attr("aria-expanded", "false");
                } else {
                    $this.attr("aria-expanded", "true");
                }
                e.preventDefault();
            }
        });
        /* HAMBURGER MENU */
        $navIconContainer.off('click').on("click", function (e) {
            menuControl.closeTertiaryMenu();
            $('body').toggleClass('o-hidden');

            if (jsUtility.isTablet(true) || jsUtility.isTablet() || jsUtility.isMobile()) { //TABLET & MOBILE
                if (!$tertiaryNav.attr('display', 'none')) {
                    menuControl.closeTertiaryMenu();
                }
                if ($navIcon.hasClass("open")) {
                    $navIconContainer.attr('role', 'button');
                    $navIconContainer.attr({ 'aria-expanded': 'false','aria-label': 'menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menuclose', 'data-analytics-link-name': 'menu', 'tabindex': 0 });
                    jsUtility.isMobile() ? menuControl.closeMobileMenu() : menuControl.closeTabletMenu();
                    if (jsUtility.isFirefox()) {
                        $navIconContainer.attr('role', 'button');
                        $navIconContainer.attr({ 'aria-expanded': 'true', 'aria-label': 'close menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menu', 'data-analytics-link-name': 'menuclose', 'tabindex': 0 });
                        menuControl.closeTabletMenu();
                        menuControl.closeMobileMenu();
                    }

                } else {
                    $navIconContainer.attr('role', 'button');
                    $navIconContainer.attr({ 'aria-expanded': 'true', 'aria-label': 'close menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menu', 'data-analytics-link-name': 'menuclose', 'tabindex': 0 });
                    jsUtility.isMobile() ? menuControl.openMobileMenu() : menuControl.openTabletMenu();

                    if (jsUtility.isFirefox()) {
                        $navIconContainer.attr('role', 'button');
                        $navIconContainer.attr({ 'aria-expanded': 'true', 'aria-label': 'close menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menu', 'data-analytics-link-name': 'menuclose', 'tabindex': 0 });
                        menuControl.openTabletMenu();
                        menuControl.openMobileMenu();
                    }
                }
            }
            $nav.removeClass($mobileShowToggle);
            $divContainer.removeClass('in').addClass('collapse');
            countrySelectorControl.closeCountrySelector();
            prevSubmenu = null;

            //append data analytics attribute
            var $authenticatedLinks = $('.signin-links ul li');
            if ($authenticatedLinks.length > 0) {
                for (var i = 0; i < $authenticatedLinks.length; i++) {
                    var parent = $authenticatedLinks[i];
                    var text = $(parent).find('a')[0].innerText;
                    if (text !== "") {
                        parent.setAttribute('data-analytics-link-name', text.toLowerCase());
                        parent.setAttribute('data-analytics-content-type', 'engagement');
                        if (parent.querySelector('a#signout'))
                        {
                            parent.setAttribute('data-analytics-content-type', 'sign out');
                        }
                    }
                }
            }
            e.preventDefault();
        });

        /* PRIMARY LINKS */
        $navLabel.on("click", function (event) {
            //event.preventDefault();
            var $this = $(this);
            var newNav = $this.closest('.nav-submenu');
            var subMenu = $(this).next();
            var newDivContainer = $this.siblings('.secondary-navs');
            var fifthL2Child = $('.layout-column .multiple-l3 .secondary-item').eq(4);
            var isColumnLayout = $('.layout-column .multiple-l3');
            var isColumnSecondaryMenu = $('.layout-column .secondary-nav-menu');
            if ($isKeyboard == true) {
                $isKeyboard = false;
            }
            else {
                document.activeElement.blur();
            }
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                $divContainer.removeClass('hidden');

                if (newNav.hasClass($mobileShowToggle)) {
                    setTimeout(function () {
                        newNav.removeClass($mobileShowToggle);
                    }, 10);
                } else {
                    if (newNav.attr('id') != 'tertiary-block') {
                        $nav.delay(1400).removeClass($mobileShowToggle);
                    }
                    setTimeout(function () {
                        newNav.delay(2800).addClass($mobileShowToggle);
                    }, 10);
                    if (isLandscape() && ($isTertiaryMenuClosed)) {
                        var title = $('.tertiary-title').text();
                        subMenu = $("div").find("[data-id='" + title + "']");

                    }
                }
                $('.layout-column .multiple-l3 .secondary-item').removeAttr('style')
                $this.siblings().find('.secondary-nav-menu').removeAttr('style')
                destroyPackery('.layout-column .multiple-l3');
            }
            else {
                if (hasClass(newDivContainer, 'hidden')) {
                    $divContainer.addClass('hidden');
                    $headerTopNav.addClass("navbar-fixed-top");
                    if (IsIE()) {
                        $(".secondary-navs").removeClass("secondary-navs-zoom");
                    }
                    if (!$isShowingSubMenu) {
                        $isShowingSubMenu = true;
                        setTimeout(function () {
                            showHideSecondaryNav.showNav(newNav);
                            $isShowingSubMenu = false;
                            isColumnLayout.css('padding', '0');
                            var percentWidth = window.outerWidth <= 1024 ? '24.8%' : (window.innerWidth < 1366 ? (window.innerWidth <= 1138 && window.innerWidth != 1051 && window.innerWidth != 1047 ? '24.6%' : '24.8%') : '24%');
                            isColumnLayout.find('.secondary-item').css('width', percentWidth);
                            isColumnLayout.find('.secondary-item').css('padding-left', '1.225em');
                            var pckry = Packery.data($('.multiple-l3')[0])
                            if ((pckry == undefined && !(jsUtility.isMobile() || jsUtility.isTablet())) || pckry != undefined && (pckry.maxY == 0 || pckry.maxX == 0)) {
                                $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                isPackery = true;
                                gridMapping($this);
                            }
                            else {
                                if ((isPackery == false) && !(jsUtility.isMobile() || jsUtility.isTablet())) {
                                    $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                    isPackery = true;
                                    gridMapping($this);
                                }
                                if (pckry.maxY != 0) {
                                    var menuheight = (pckry.maxY + 50);
                                    isColumnSecondaryMenu.css('height', (menuheight / 16).toFixed(2) + 'em');
                                    isColumnSecondaryMenu.css('padding-bottom', 3.13 + 'em');
                                }
                            }
                            NavMenuScrollOnZoom();

                        }, 100);
                    }
                } else {
                    showHideSecondaryNav.clickHideNav(newNav);
                }
            }
            careersHomeLocalVersionLinkAnalytics();
        });

        /*WEB ACCESSIBILITY - PRIMARY LINKS ON KEYPRESS*/
        $navLabelKeyPressed.on("keydown", function (e) {
            var code = e.which;
            var $this = $(this);
            var newNavKeypressed = $this.closest('.nav-submenu');
            var subMenu = $(this).next();
            var newDivContainer = $this.siblings('.secondary-navs');
            var fifthL2Child = $('.layout-column .multiple-l3 .secondary-item').eq(4);
            var isColumnLayout = $('.layout-column .multiple-l3');
            var isColumnSecondaryMenu = $('.layout-column .secondary-nav-menu');

            if (code === 13 || code === 32 || code === 40) {

                if ($isKeyboard == true) {
                    $isKeyboard = false;
                }

                if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                    $divContainer.removeClass('hidden');

                    if (newNavKeypressed.hasClass($mobileShowToggle)) {
                        setTimeout(function () {
                            newNavKeypressed.removeClass($mobileShowToggle);
                        }, 10);
                        $this.attr("aria-expanded", "false");
                    } else {
                        if (newNavKeypressed.attr('id') != 'tertiary-block') {
                            $nav.delay(1400).removeClass($mobileShowToggle);
                        }
                        setTimeout(function () {
                            newNavKeypressed.delay(2800).addClass($mobileShowToggle);
                        }, 10);
                        if (isLandscape() && ($isTertiaryMenuClosed)) {
                            var title = $('.tertiary-title').text();
                            subMenu = $("div").find("[data-id='" + title + "']");

                        }
                        $this.attr("aria-expanded", "true");
                    }
                    $('.layout-column .multiple-l3 .secondary-item').removeAttr('style')
                    $this.siblings().find('.secondary-nav-menu').removeAttr('style')
                    destroyPackery('.layout-column .multiple-l3');
                }
                else {
                    if (hasClass(newDivContainer, 'hidden')) {
                        $divContainer.addClass('hidden');
                        $headerTopNav.addClass("navbar-fixed-top");
                        if (IsIE()) {
                            $(".secondary-navs").removeClass("secondary-navs-zoom");
                        }
                        if (!$isShowingSubMenu) {
                            $isShowingSubMenu = true;
                            setTimeout(function () {
                                showHideSecondaryNav.showNavKeyPressedFirstItem(newNavKeypressed);
                                $isShowingSubMenu = false;
                                isColumnLayout.css('padding', '0');
                                var percentWidth = window.outerWidth <= 1024 ? '24.8%' : (window.innerWidth < 1366 ? (window.innerWidth <= 1138 && window.innerWidth != 1051 && window.innerWidth != 1047 ? '24.6%' : '24.8%') : '24%');
                                isColumnLayout.find('.secondary-item').css('width', percentWidth);
                                isColumnLayout.find('.secondary-item').css('padding-left', '1.225em');
                                var pckry = Packery.data($('.multiple-l3')[0])
                                if ((pckry == undefined && !(jsUtility.isMobile() || jsUtility.isTablet())) || pckry != undefined && (pckry.maxY == 0 || pckry.maxX == 0)) {
                                    $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                    isPackery = true;
                                    gridMapping($this);
                                }
                                else {
                                    if ((isPackery == false) && !(jsUtility.isMobile() || jsUtility.isTablet())) {
                                        $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                        isPackery = true;
                                        gridMapping($this);
                                    }
                                    if (pckry.maxY != 0) {
                                        var menuheight = (pckry.maxY + 50);
                                        isColumnSecondaryMenu.css('height', (menuheight / 16).toFixed(2) + 'em');
                                        isColumnSecondaryMenu.css('padding-bottom', 3.13 + 'em');
                                    }
                                }
                                NavMenuScrollOnZoom();

                            }, 100);
                        }
                    } else {
                        showHideSecondaryNav.clickHideNav(newNavKeypressed);
                    }
                }

            }
            else if (code === 38) {

                if ($isKeyboard == true) {
                    $isKeyboard = false;
                }

                if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                    $divContainer.removeClass('hidden');

                    if (newNavKeypressed.hasClass($mobileShowToggle)) {
                        setTimeout(function () {
                            newNavKeypressed.removeClass($mobileShowToggle);
                        }, 10);
                    } else {
                        if (newNavKeypressed.attr('id') != 'tertiary-block') {
                            $nav.delay(1400).removeClass($mobileShowToggle);
                        }
                        setTimeout(function () {
                            newNavKeypressed.delay(2800).addClass($mobileShowToggle);
                        }, 10);
                        if (isLandscape() && ($isTertiaryMenuClosed)) {
                            var title = $('.tertiary-title').text();
                            subMenu = $("div").find("[data-id='" + title + "']");

                        }
                    }
                    $('.layout-column .multiple-l3 .secondary-item').removeAttr('style')
                    $this.siblings().find('.secondary-nav-menu').removeAttr('style')
                    destroyPackery('.layout-column .multiple-l3');
                }
                else {
                    if (hasClass(newDivContainer, 'hidden')) {
                        $divContainer.addClass('hidden');
                        $headerTopNav.addClass("navbar-fixed-top");
                        if (IsIE()) {
                            $(".secondary-navs").removeClass("secondary-navs-zoom");
                        }
                        if (!$isShowingSubMenu) {
                            $isShowingSubMenu = true;
                            setTimeout(function () {
                                showHideSecondaryNav.showNavKeyPressedLastItem(newNavKeypressed);
                                $isShowingSubMenu = false;
                                isColumnLayout.css('padding', '0');
                                var percentWidth = window.outerWidth <= 1024 ? '24.8%' : (window.innerWidth < 1366 ? (window.innerWidth <= 1138 && window.innerWidth != 1051 && window.innerWidth != 1047 ? '24.6%' : '24.8%') : '24%');
                                isColumnLayout.find('.secondary-item').css('width', percentWidth);
                                isColumnLayout.find('.secondary-item').css('padding-left', '1.225em');
                                var pckry = Packery.data($('.multiple-l3')[0])
                                if ((pckry == undefined && !(jsUtility.isMobile() || jsUtility.isTablet())) || pckry != undefined && (pckry.maxY == 0 || pckry.maxX == 0)) {
                                    $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                    isPackery = true;
                                    gridMapping($this);
                                }
                                else {
                                    if ((isPackery == false) && !(jsUtility.isMobile() || jsUtility.isTablet())) {
                                        $grid = isColumnLayout.packery({ itemSelector: '.secondary-item', percentPosition: true, transitionDuration: 0 });
                                        isPackery = true;
                                        gridMapping($this);
                                    }
                                    if (pckry.maxY != 0) {
                                        var menuheight = (pckry.maxY + 50);
                                        isColumnSecondaryMenu.css('height', (menuheight / 16).toFixed(2) + 'em');
                                        isColumnSecondaryMenu.css('padding-bottom', 3.13 + 'em');
                                    }
                                }
                                NavMenuScrollOnZoom();

                            }, 100);
                        }
                    } else {
                        showHideSecondaryNav.clickHideNav(newNavKeypressed);
                    }
                }

            }
        });

        var $contentWrapper = $(".content-wrapper");
        if ($contentWrapper.hasClass("focus-indicator")) {
            $navLabel.on("focus", function (event) {
                var $this = $(this);
                $this.parent('.nav-submenu').addClass('focus-indicator-enh');
                $this.parent('.nav-submenu').siblings().removeClass('focus-indicator-enh');
                setTimeout(function () {
                    var isNavIconOpen = $("#nav-icon").hasClass("open");
                    if ($this.parent('.nav-submenu').siblings(".focus-indicator-enh").length == 0 && isNavIconOpen === false) {
                        showHideSecondaryNav.hideSubNav();
                    }
                }, 100);
            });

            $navLabel.on("focusout", function (event) {
                var $this = $(this);
                $this.parent('.nav-submenu').removeClass('focus-indicator-enh');
            });
        } else {
            $navLabel.on("focus", function () {
                var $this = $(this);
                setTimeout(function () {
                    var isNavIconOpen = $("#nav-icon").hasClass("open");
                    if ($this.parent('.nav-submenu').siblings().children(":focus").length == 0 && isNavIconOpen === false) {
                        showHideSecondaryNav.hideSubNav();
                    }
                }, 100);
            });
        }
     
        if ($(".gh-item.search-icon-container").length == 0) {
            $('.utility-nav').addClass('show-country-select');
        } else {
            $('.utility-nav').removeClass('show-country-select');
        }

        /* OPEN TERTIARY MENU */
        $tertiaryContainer.on("click", function L3() {
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                if ($navIcon.hasClass("open")) {
                    $navContent.children().attr('style', 'display:none !important;');
                    $isTertiaryMenuClosed = false;
                    if ($(this).parent().attr('id') != 'no-l3') {
                        var tertiary = $(this).data("tertiary");
                        $tertiaryNav.css({ 'opacity': '0', 'left': '-530px' });
                        $tertiaryNav.css("display", "flex").animate({
                            opacity: '1',
                            left: '0px',
                        }, 100); 

                        $('.tertiary-title').html($(this).parents('.nav-submenu').find('.nav-submenu-label-text').text().trim());
                        $subMenuLabel.addClass('tertiaryLevel3');
                        $tertiaryListContainer.html($(this).children('ul').clone());
                        $tertiaryListContainer.children('ul').removeClass('hidden-xs hidden-sm hidden-md');
                        $('div.nav-content.panel-group.tertiary-nav-container.hidden.crawl-down').removeClass('hidden');
                    }
                }
            }
        });
        /* OPEN TERTIARY MENU - WEB ACCESSIBILITY*/
        $tertiaryContainer.on("keypress", function L3(e) {
            var code = e.which;
            if (code === 13 || code === 32) {
                if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                    if ($navIcon.hasClass("open")) {
                        $navContent.children().attr('style', 'display:none !important;');
                        $isTertiaryMenuClosed = false;
                        if ($(this).parent().attr('id') != 'no-l3') {
                            var tertiary = $(this).data("tertiary");
                            $tertiaryNav.css({ 'opacity': '0', 'left': '-530px' });
                            $tertiaryNav.css("display", "flex").animate({
                                opacity: '1',
                                left: '0px',
                            }, 100);
                            $('.tertiary-title').html($(this).parents('.nav-submenu').find('.nav-submenu-label-text').text().trim());
                            $subMenuLabel.addClass('tertiaryLevel3');
                            $tertiaryListContainer.html($(this).children('ul').clone());
                            $tertiaryListContainer.children('ul').removeClass('hidden-xs hidden-sm hidden-md');
                            $('div.nav-content.panel-group.tertiary-nav-container.hidden.crawl-down').removeClass('hidden');
                        }
                    }
                    if (code === 9 && !e.shiftKey) {
                        $('#menuFooter').find("a").first().trigger("focus");
                        e.preventDefault();
                    }
                }
            }

        });
        /* TERTIARY BACK BUTTON */
        $tertiaryClose.on("click", function () {
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                menuControl.closeTertiaryMenu();
                $navContent.children().css('display', '');
            }
        });

        /* TERTIARY BACK BUTTON - WEB ACCESSIBILITY */
        $tertiaryClose.on("keypress", function (e) {
            var code = e.which;
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                if (code === 13 || code === 32) {
                    menuControl.closeTertiaryMenu();
                    $navContent.children().css('display', '');
                }
            }
        });

        /* CLICK OUTSIDE MENU - TABLET */
        $backDropTablet.on("click", function () {
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                menuControl.closeTabletMenu();
            }
        });
    };

    /* SECONDARY LINKS HEIGHT ADJUSTMENT */
    var secondaryLinksContainerAdjustment = function () {

        var $searchJobLink = $('.secondary-nav-menu .first-secondary-item').find('.search-jobslink');
        var $cnzhMenu = $('.secondary-nav-menu .first-secondary-item .secondary-hyperlink');
        var $careersHomeLocalVersionLink = $("#careershome-localversion");
        var $checkLegacy = $(".ui-content-wrapper").length;

        if ($checkLegacy > 0) {
            //Checking if Search Job & careershome local version is exisitng and if it is on Legacy page
            if ($searchJobLink.length > 0 && $careersHomeLocalVersionLink.length > 0) {
                $searchJobLink.parent().css('height', 8.33 + 'em');
            }
            //Checking if Search Job is exisitng and if it is on Legacy page
            else if ($searchJobLink.length > 0) {
                $searchJobLink.parent().css('height', 5.43 + 'em');
            }
        }
        else {
                $searchJobLink.parent().css('height', 6.43 + 'em');
        }

            if (pageContext.split('/')[3] === "cn-zh") {
                $cnzhMenu.css('margin-right', 0 + 'em');
            }

    };


    /* SEARCH */
    var globalHeaderSearch = function () {
        var headerId = '#header-topnav';
        var searchBody = $('#search-body');
        var searchIcon = $(headerId + ' .search-icon-container');
        var searchInput = $(headerId + ' .search-textbox');
        var clearInput = $(headerId + ' .ion-ios-close');
        var countrySelector = $('.utility-nav .country-select-cont');
        var showSearchClass = 'show-search';
        var signInCont = $('.utility-nav .signin-container');
        var textboxSearchIcon = $(headerId + ' .ion-ios-search');

        searchIcon.off('click').on("click", function () {

            if (!$(textboxSearchIcon).hasClass('serp')) {
                $(this).toggleClass(showSearchClass);
                $varSearchBody.css('height', deviceHeight + 'px');
                $('body').toggleClass('modal-open');
                $acnLogoContainer.toggleClass('hidden');
                $navIcon.toggleClass('hidden-xs hidden-sm');
                countrySelector.css('visibility', 'hidden');
                searchBody.toggleClass('slide-down');
                signInCont.css('visibility', 'hidden');
                $navLabel.css('visibility', 'hidden');

                searchInput.val('');
                clearInput.addClass('hidden');

                if (!hasClass($(this), showSearchClass)) {
                    $varSearchBody.css('height', 0);
                    countrySelector.removeAttr('style');
                    signInCont.removeAttr('style');
                    $navLabel.removeAttr('style');
                }
            }
        });

        searchInput.on("keyup", function () {
            if (viewPortWidth <= 999) {
                if ($(this).val() != '') {
                    clearInput.removeClass('hidden');
                } else {
                    clearInput.addClass('hidden');
                }
            }
        });

        clearInput.on("click", function (e) {
            e.preventDefault();
            searchInput.val('');
            clearInput.addClass('hidden');
            $('#search-recommendation').removeClass('in')
                .addClass('collapse');
        });
    };

    /* COUNTRY SELECTOR */
    var globalCountrySelector = function () {
        var countryIcon = $('.country-select-cont');
        var isKeyPressDown = false;
        var isCountrySelectorClicked = false;
        countryIcon.on("keydown", function (e) {
            var code = e.which;
            if (code == 13 || code == 32 || code == 40 || code == 38) {
                if (!isCountrySelectorClicked) {
                    isKeyPressDown = true;
                    isCountrySelectorClicked = true;
                    GetCountrySelectorData();
                }
                isKeyPressDown = true;
                $countrySelectorCont.toggleClass($toggleCountryList);
                isCountryListExpanded();
            }
        })

        countryIcon.off('click').on("click", function () {
            if (!isKeyPressDown) {
                if (!isCountrySelectorClicked) {
                    isCountrySelectorClicked = true;
                    GetCountrySelectorData();
                }
                $countrySelectorCont.toggleClass($toggleCountryList);
                isCountryListExpanded();
            }
            isKeyPressDown = false;
        })

        $(document).on("mouseup touchend", function (e) {
            if (!e) e = window.event;
            var targetElement = e.target || e.srcElement;

            if ($('.show-country-list').length && $(targetElement).attr('class') !== 'country-select-cont' && $(targetElement).attr('class') !== 'show-country-list'
                && !$(targetElement).closest('.country-select-cont').length && !$(targetElement).closest('.show-country-list').length) {
                $countrySelectorCont.toggleClass($toggleCountryList);
                isCountryListExpanded();
            }
        });
    };
    function checkMembershipData() {
        $.ajax({
            url: "/api/sitecore/ReinventRegistration/B2CCheck",
            async: true,
            type: "POST",
            data: JSON.stringify({ uri: window.location.href }),
            contentType: "application/json",
            error: function () {
                console.error("Error in checking membership.", "error");
            },
            success: function (msg) {
                if (msg.redirecturl != "/") {
                    window.location.href = msg.redirecturl;
                }
            }
        });
    };

    $(document).on('click', "#navUserDisplayUserName", function (e) {
        checkMembershipData();
    }); 

    function GetCountrySelectorData() {
        var geoGroupStoredData = CheckCountrySelectorLocalStorage();
        var pageLocation = document.location.href.toLowerCase();
        var countries = [];
        if (geoGroupStoredData != 'null' && geoGroupStoredData != null && typeof geoGroupStoredData != 'undefined' && geoGroupStoredData.length > 0) { //check value condition for different type of browser.
            var geoObj = JSON.parse(geoGroupStoredData);

            for (var i = 0; i < geoObj.GeoGroup.length; i++) {
                for (var j = 0; j < geoObj.GeoGroup[i].CountryGroup.length; j++) {
                    for (var k = 0; k < geoObj.GeoGroup[i].CountryGroup[j].CountryList.length; k++) {
                        countries.push(geoObj.GeoGroup[i].CountryGroup[j].CountryList[k]);
                    }
                }
            }
            //RMT 8948 - countries with multiple languages will follow reverse order
            countries.sort(function (a, b) {
                var country1 = a.CountryName, country2 = b.CountryName;
                if (country1 == country2) {
                    var site1 = a.Sites, site2 = b.Sites;
                    return site1 > site2 ? -1 : 1;
                } else {
                    return country1 > country2 ? 1 : -1;
                }
            });
            CountrySelectorTemplate(countries);
        } else {
            var serviceURL = '/api/sitecore/CountrySelectorModule/GetCountrySelectorData';
            $.ajax({
                type: 'GET',
                url: serviceURL,
                contentType: "application/json; charset=utf-8",
                data: { pageContext: pageContext }, //pulled from the country selector view variable.
                dataType: "json",
                async: true,
                cache: true,
                error: function () {
                    console.error("Error while trying to get Geo Group List.");
                },
                success: function (data, status) {
                    if (data.GeoGroup != null && data.GeoGroup != "") {
                        if (data.GeoGroup.length > 0) {
                            if (typeof (Storage) !== "undefined") {
                                var dataObject = { GeoGroup: data.GeoGroup, DateCreated: new Date().getTime() }

                                if (pageLocation.indexOf("/careers") >= 0) {
                                    localStorage.setItem(ACN_COUNTRY_SELECTOR_CAREERS, JSON.stringify(dataObject));
                                }
                                else {
                                    localStorage.setItem(ACN_COUNTRY_SELECTOR_DOTCOM, JSON.stringify(dataObject));
                                }
                            }

                            for (var i = 0; i < data.GeoGroup.length; i++) {
                                for (var j = 0; j < data.GeoGroup[i].CountryGroup.length; j++) {
                                    for (var k = 0; k < data.GeoGroup[i].CountryGroup[j].CountryList.length; k++) {
                                        countries.push(data.GeoGroup[i].CountryGroup[j].CountryList[k]);
                                    }
                                }
                            }
                            //RMT 8948 - countries with multiple languages will follow reverse order
                            countries.sort(function (a, b) {
                                var country1 = a.CountryName, country2 = b.CountryName;
                                if (country1 == country2) {
                                    var site1 = a.Sites, site2 = b.Sites;
                                    return site1 > site2 ? -1 : 1;
                                } else {
                                    return country1 > country2 ? 1 : -1;
                                }
                            });
                            CountrySelectorTemplate(countries);
                        }
                    } else {
                        console.error("Page Context is not set.");
                    }
                }
            })

        }
    };
    function CheckCountrySelectorLocalStorage() {
        var pageLocation = document.location.href.toLowerCase();

        if (typeof (Storage) !== "undefined") {
            if (pageLocation.indexOf("/careers") >= 0) {
                geoGroupStoredData = localStorage.getItem(ACN_COUNTRY_SELECTOR_CAREERS);
            }
            else {
                geoGroupStoredData = localStorage.getItem(ACN_COUNTRY_SELECTOR_DOTCOM);
            }

            //If local Storage is more than 1 day, remove localStorage and return null
            if (geoGroupStoredData != null) {
                if ((Date.now() - JSON.parse(geoGroupStoredData).DateCreated) > 86400000) {
                    if (pageLocation.indexOf("/careers") >= 0) {
                        localStorage.removeItem(ACN_COUNTRY_SELECTOR_CAREERS);
                    }
                    else {
                        localStorage.removeItem(ACN_COUNTRY_SELECTOR_DOTCOM);
                    }
                    return null;
                }
            }
        }
        return geoGroupStoredData;
    };

    function CountrySelectorTemplate(countries) {
        var locationContainerId = "#location-recommendation";
        var locationSelectorMarkup = "";
        var countrySite = "/" + window.location.pathname.split("/")[1];
        var defaultHeader = "";
        var pageLocation = document.location.href.toLowerCase();
        var currentDomainSubs = document.location.host.split(".");
        var currentCountry = $("p#current-country");

        //Compare countrysite of the URL to the list of countries displayed in the Language Selector
        for (var i = 0; i < countries.length; i++) {
            var countryUrl = countries[i].CountryDotcomUrl;
            var countryLanguage = countries[i].LanguageTitle;

            //If countrysite is the same as the URL of the country, End the comparison
            //Display the corresponding language of the country as Default Language
            if (countrySite == countryUrl) {
                defaultHeader = '<li class="default">Default (' + countryLanguage + ') </li > ';
                break;
            }
            //Else, if countrysite is not among the list, set "English" as default
            else {
                defaultHeader = '<li class="default">Default (English) </li > ';
            }
        }

        if (currentCountry.text().indexOf(countryLanguage) === -1) {
            currentCountry.append("(" + countryLanguage + ")");
        }
        var allCountriesHeader = '<li class="dropdown-header ucase">All COUNTRIES &amp; LANGUAGES</li>';

        locationSelectorMarkup = '<ul role="menu" aria-labelledby="country-language-selector">';
        locationSelectorMarkup += defaultHeader;
        locationSelectorMarkup += allCountriesHeader;

        if (pageLocation.indexOf("/careers") >= 0) {
            var careersURL = "/careers";
        } else {
            var careersURL = "";
        }

        for (var i = 0; i < countries.length; i++) {
            var countryName = countries[i].CountryName;
            var countryDotComUrl = countries[i].CountryDotcomUrl + careersURL;
            var countryUrl = countries[i].CountryDotcomUrl + careersURL;
            var countrySiteCode = countrySite + careersURL;
            var subDomain = currentDomainSubs[0];
            var currentSecondLD = currentDomainSubs[1];
            var chinaCacheURL = document.location.protocol + "//" + subDomain + "." + currentSecondLD + ".cn/cn-zh" + careersURL;
            var chinaCacheURLLowerEnvi = document.location.protocol + "//Accenture-cn.cdnsvc.com/cn-zh" + careersURL;
            var countryLanguage = countries[i].LanguageTitle;

            if (countryLanguage == "Chinese")
            {
                if (subDomain === "www")
                {
                    locationSelectorMarkup += '<li role="none"><a href="' + chinaCacheURL + '" data-linktype="language" data-analytics-content-type="language" data-linkcomponentname="top nav" data-analytics-link-name=" ' + countryName + '" role="menuitem">' + countryName + " (" + countryLanguage + ")" + '</a></li>';
                }
                else
                {
                    locationSelectorMarkup += '<li role="none"><a href="' + chinaCacheURLLowerEnvi + '" data-linktype="language" data-analytics-content-type="language" data-linkcomponentname="top nav" data-analytics-link-name=" ' + countryName + '" role="menuitem">' + countryName + " (" + countryLanguage + ")" + '</a></li>';
                }

            }
            else
            {
                locationSelectorMarkup += '<li role="none"><a href="' + countryUrl + '" data-linktype="language" data-analytics-content-type="language" data-linkcomponentname="top nav" data-analytics-link-name=" ' + countryName + '" role="menuitem">' + countryName + " (" + countryLanguage + ")" + '</a></li>';
            }


        }
        locationSelectorMarkup += '</ul>';

        $(locationContainerId).html(locationSelectorMarkup);
    };

    var destroyPackery = function (element) {
        var pckry = Packery.data($(element)[0])
        if (pckry != undefined) {
            $(element).packery('destroy');
            isPackery = false;
        }
    };
    /* WEB ACCESSIBILITY MAPPING */
    var globalHeaderMap = function () {
        mapTopLevel();
        /* ADD MAPPING TO SUBMENUS */
        var subMenu = $('.nav-submenu');
        var isLayoutVertical = $('.layout-vertical');
        for (var h = 0; h < subMenu.length; h++) {
            if ($(subMenu[h]).hasClass("layout-vertical") && $(subMenu[h]).find("ul").hasClass("multiple-l3")) {
                mapLayoutVertical(h, subMenu);

            }
            else if ($(subMenu[h]).find('ul').hasClass("multiple-l3") || $(subMenu[h]).find('ul').hasClass("single-l2")) {
                mapTertiaryLayoutRow(h, subMenu);
            }
            else if ($(subMenu[h]).find('ul').hasClass("no-l3")) {
                mapSecondaryLayoutRow(h, subMenu);
            }
        }

        function mapTopLevel() {
            for (var i = 0; i < $tabElements.length; i++) {
                $($tabElements[i]).attr('data-cell', 'GH' + i);
            }
        }

        function mapLayoutVertical(ctr, subMenu) {
            var row = -1;
            var tertiaryCounter = 0;
            var col = '@';
            var id = $(subMenu[ctr]).find('.secondary-navs').attr('id');
            var secondaryLinks = $("#" + id + '> div .nav-item-links > ul').children("li");
            for (var i = 0; i < secondaryLinks.length; i++) {
                tertiaryCounter = 0;
                col = 'A';
                tertiaryLinks = $(secondaryLinks[i]).find('ul').children();
                if (i == 2) {
                    if (col == "A") {
                        row = 0;
                    }
                    if (col == "B") {
                        row = 0;
                    }
                }
                for (var j = 0; j < tertiaryLinks.length; j++) {
                    if (i == 2) {
                        if (col == "A") {
                            col = 'C';
                        }
                        if (col == "B") {
                            col = 'D';
                        }
                    }
                    $(tertiaryLinks[j]).find('a').attr('data-cell', col + row);
                    row = row++;
                    col = nextChar(col);
                    if (tertiaryCounter == 1) {
                        col = 'A';
                        row++;
                        tertiaryCounter = 0;
                    }
                    else {
                        tertiaryCounter++;
                    }
                }
                row++;
            }
            $("#" + id + '> div .nav-item-links > ul').attr('data-lastrow', row - 1);
        }

        function mapTertiaryLayoutRow(ctr, subMenu) {
            var row = 0;
            var tertiaryCounter = 0;
            var col = '@';
            var id = $(subMenu[ctr]).find('.secondary-navs').attr('id');
            var secondaryLinks = $("#" + id + '> div .nav-item-links > ul').children("li");
            for (var i = 0; i < secondaryLinks.length; i++) {
                tertiaryCounter = 0;
                col = 'A';
                tertiaryLinks = $(secondaryLinks[i]).find('ul').children();
                for (var j = 0; j < tertiaryLinks.length; j++) {
                    $(tertiaryLinks[j]).find('a').attr('data-cell', col + row);
                    row = row++;
                    col = nextChar(col);
                    if (tertiaryCounter == 3) {
                        col = 'A';
                        row++;
                        tertiaryCounter = 0;
                    }
                    else {
                        tertiaryCounter++;
                    }
                }
                row++;
            }
            $("#" + id + '> div .nav-item-links > ul').attr('data-lastrow', row - 1);
        }
        function mapLayoutColumn(ctr, subMenu) {
            var row = 0;
            var tertiaryCounter = 0;
            var col = 'A';
            var id = $(subMenu[ctr]).find('.secondary-navs').attr('id');
            var secondaryLinks = $("#" + id + '> div .nav-item-links > ul').children("li");
            col = 'A';
            for (var i = 0; i < secondaryLinks.length; i++) {
                tertiaryCounter = 0;
                tertiaryLinks = $(secondaryLinks[i]).find('ul').children();
                for (var j = 0; j < tertiaryLinks.length; j++) {
                    if (i == 4) {
                        col = 'A';
                        var lastChild = parseInt($(secondaryLinks[0]).children().find("a").last().data("cell")[1]) + 1;
                        var newNum = j + lastChild;
                        $(tertiaryLinks[j]).find('a').attr('data-cell', col + newNum);
                    }
                    else {
                        $(tertiaryLinks[j]).find('a').attr('data-cell', col + j);
                        row = row++;
                        tertiaryCounter++;
                    }
                }
                col = nextChar(col);
                row++;
            }
            $("#" + id + '> div .nav-item-links > ul').attr('data-lastrow', row - 1);

        }
        function mapSecondaryLayoutRow(ctr, subMenu) {
            var secondaryLinkRow = -1;
            var secondaryLinkCol = '@';
            var id = $(subMenu[ctr]).find('.secondary-navs').attr('id');
            var secondaryLinks = $("#" + id + '> div .nav-item-links > ul').children("li");
            for (var i = 0; i < secondaryLinks.length; i++) {
                if (!$(secondaryLinks[i]).find('a').hasClass('overview-link')) {
                    if (secondaryLinkCol == '@') {
                        secondaryLinkRow++;
                    }
                    secondaryLinkCol = nextChar(secondaryLinkCol);
                    $(secondaryLinks[i]).find('a').attr('data-cell', secondaryLinkCol + secondaryLinkRow);
                    secondaryLinkCol = secondaryLinkCol == 'D' ? '@' : secondaryLinkCol;
                }
            }
            $("#" + id + '> div .nav-item-links > ul').attr('data-lastrow', secondaryLinkRow);
        }
        function nextChar(c) {
            return String.fromCharCode(c.charCodeAt(0) + 1);
        }
    };

    var gridMapping = function ($this) {
        var lists = $("div#Businesses .multiple-l3").children('li')
        var grid = Packery.data($('.multiple-l3')[0])
        if (grid === undefined) {
            return;
        }
        var colAPosition = 0, colBPosition = 0, colCPosition = 0, colDPosition = 0;
        for (var i = 1; i < 4; i++) {
            for (var j = 0; j < grid.items.length; j++) {
                //highest 'x' position. column D
                if (grid.items[j].position.x > colDPosition && i == 1) {
                    colDPosition = grid.items[j].position.x;
                }
                //second highest 'x' position. column C
                else if (grid.items[j].position.x > colCPosition && grid.items[j].position.x < colDPosition && i == 2) {
                    colCPosition = grid.items[j].position.x;
                }
                //second lowest 'x' position. column B
                else if (grid.items[j].position.x > colBPosition && grid.items[j].position.x < colCPosition && i == 3) {
                    colBPosition = grid.items[j].position.x
                }
            }
        }
        var ah = 0, bh = 0, ch = 0, dh = 0;
        for (j = 0; j < grid.items.length; j++) {
            if (grid.items[j].position.x == colAPosition) {
                $(grid.items[j].element).children().find('a').attr('data-cell', 'A')
            }
            else if (grid.items[j].position.x == colBPosition) {
                $(grid.items[j].element).children().find('a').attr('data-cell', 'B')
            }
            else if (grid.items[j].position.x == colCPosition) {
                $(grid.items[j].element).children().find('a').attr('data-cell', 'C')
            }
            else if (grid.items[j].position.x == colDPosition) {
                $(grid.items[j].element).children().find('a').attr('data-cell', 'D')
            }
        }
        var columns = ['A', 'B', 'C', 'D'];
        var highestHeight = 0;
        for (var j = 0; j < columns.length; j++) {
            var dk = $("a[data-cell= " + columns[j] + "]");
            for (var i = 0; i < dk.length; i++) {
                $(dk[i]).attr('data-cell', columns[j] + i);
            }
        }
        var menuheight = (grid.maxY + 50);
        $('.layout-column .secondary-nav-menu').css('height', (menuheight / 16).toFixed(2) + 'em');
        $('.layout-column .secondary-nav-menu').css('padding-bottom', 3.13 + 'em');
    };
    //approximated zoom level
    var zoomLevel = function () {

        var estWindowZoom = Math.round((window.devicePixelRatio) * 100);
        return estWindowZoom;

    };

    //return to top
    var goTop = function () {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    };

    //allow scroll GlobalHeader menu 
    var NavMenuScrollOnZoom = function () {
        var pckry = Packery.data($('.multiple-l3')[0]);
        setTimeout(function () {
            if (zoomLevel() > 100 && ($('.secondary-navs').not(".hidden").height() + $(".navbar-background").height()) > $(window).height()) {
                $('body').css('padding-top', '0');
                $("#header-topnav").removeClass("navbar-fixed-top");
                $navBarDefault.not('.interactive-navigation-bar').css({ "z-index": "1031" });
                goTop();
                if (IsIE()) {
                    $(".secondary-navs").addClass("secondary-navs-zoom");
                }
            }
        }, 500);

    };

    /* HIDE OR SHOW SECONDARY NAVIGATION CONTROL */
    var showHideSecondaryNav = {
        showNav: function (navlinks) {
            $isShowingSubMenu = true;
            var $this = navlinks;
            var subMenu = $("#" + $this.data("id"));
            $navLabel.removeClass('active').closest('.nav-submenu').removeClass('border-bottom');
            $navLabel.attr("aria-expanded", "false");
            subMenu.siblings('.nav-submenu-label').addClass('active');
            subMenu.siblings('.nav-submenu-label').attr("aria-expanded", "true");
            subMenu.parent('.nav-submenu').addClass('border-bottom');
            subMenu.css({ 'opacity': '0', 'top': '-530px' });
            subMenu.removeClass("hidden").animate({
                opacity: '1',
                top: '70px'
            }, 400);

            var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
            var $body = $('body');
            var $layoutColumn = $(".layout-column");
            if (!jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                if ($baseFontsize != 0 && ($baseFontsize < $currentFontSize)) {
                    if (($('.secondary-navs').not(".hidden").height() + $(".navbar-background").height()) > $(window).height()) {
                        $layoutColumn.find(".multiple-l3").children().last().css({ "font-size": "" });
                        $headerTopNav.removeClass("navbar-fixed-top");
                        $navBarDefault.css({ "z-index": "1031" });
                        $body.css('padding-top', '0');
                        goTop();
                    }
                    $('.gh-item').not('.signin-container, .acn-logo').css({ "position": "relative", "z-index": "11" });
                    $tertiaryItem.css({ "min-width": " auto" });
                    $secondaryItem.css({ "word-break": " break-word" });
                }
            }
            $isShowingSubMenu = false;

        },
        hideSubNav: function () {
            if (!$isHidingSubMenu && !$isShowingSubMenu) {
                $isHidingSubMenu = true;
                var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
                var subMenu = $('div.secondary-navs:not(.hidden)');
                var $body = $('body');
                subMenu.removeClass('active').closest('.nav-submenu').removeClass('border-bottom');
                $navLabel.removeClass('active');
                $navLabel.attr("aria-expanded", "false");
                subMenu.css({ 'top': '0', 'opacity': '1' });
                subMenu.animate({
                    top: (jsUtility.isTablet() ? 0 : '-530px'),
                    opacity: '1'
                }, 400);
                setTimeout(function () {
                    subMenu.addClass("hidden");
                    if (!jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                        if ($baseFontsize != 0 && ($baseFontsize < $currentFontSize)) {
                            $('.gh-item').css({ "z-index": "auto" });
                            $('.gh-item').not('.search-icon-container').css({ "position": "static" });
                        }
                        $('.gh-item').not('.signin-container, .acn-logo').css({ "position": "", "z-index": "" });
                        $tertiaryItem.css({ "min-width": "" });
                        $secondaryItem.css({ "word-break": "" });
                        $headerTopNav.addClass("navbar-fixed-top");
                        $headerTopNav.css({ "margin-top": "" });
                        $divContainer.css({ "z-index": "" });
                        $navBarDefault.css({ "z-index": "" });
                        $body.css('padding-top', "");
                    }

                    $isHidingSubMenu = false;
                }, 400);

            }
        },
        clickHideNav: function (navlinks) {
            var $this = navlinks;
            var subMenu = $("#" + $this.data("id"));
            var primaryLink = $('div.secondary-navs:not(.hidden)');
            var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
            var $body = $('body');
            if (!$isHidingSubMenu) {
                $('div.nav-submenu-label.active').removeClass('active');
                $('div.nav-submenu').removeClass('border-bottom');
                $navLabel.attr("aria-expanded", "false");
                $isHidingSubMenu = true;
                subMenu.css({ 'top': '0', 'opacity': '1' });
                subMenu.animate({
                    top: '-530px',
                    opacity: '0'
                }, 300);
                setTimeout(function () {
                    subMenu.addClass("hidden");
                    if (!jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                        if ($baseFontsize != 0 && ($baseFontsize < $currentFontSize)) {
                            $('.gh-item').css({ "z-index": "auto" });
                            $('.gh-item').not('.search-icon-container').css({ "position": "static" });
                        }
                        $('.gh-item').not('.signin-container, .acn-logo').css({ "position": "", "z-index": "" });
                        $tertiaryItem.css({ "min-width": "" });
                        $secondaryItem.css({ "word-break": "" });
                        $headerTopNav.addClass("navbar-fixed-top");
                        $headerTopNav.css({ "margin-top": "" });
                        $divContainer.css({ "z-index": "" });
                        $navBarDefault.css({ "z-index": "" });
                        $body.css('padding-top', "");
                    }
                    $isHidingSubMenu = false;
                }, 300);

            }
            destroyPackery('.layout-column .multiple-l3');
        },
        showBackDrop: function () {
            if (!$isShowingBackdrop) {
                $isShowingBackdrop = true;
                $("html").css({ 'overflow': 'hidden' });
                $(".back-drop-tablet").css("position", "fixed");
                $navContent = $('#nav-content-menu');
                $navContent.css({ 'margin-top': ' 50px' });
                $backDropTablet.css({ 'opacity': '0', 'z-index': '11', 'top': '0' });
                $backDropTablet.removeClass("hidden").animate({
                    opacity: '0.6',
                    zIndex: '11'
                }, 100);
                $isShowingBackdrop = false;

                $(document).on('touchmove', function (e) {
                    var isInNavSubmenu = $('.nav-submenu-label').has($(e.target)).length;
                    var isInPrimaryLinks = $(".primary-link-container").has($(e.target)).length;
                    var isBackDropHidden = $backDropTablet.hasClass('hidden');
                    var isOverflow = $("#nav-content-menu").height() < $(".primary-link-container").height() + $menuFooter.height() + 50;
                    var isInLangSelect = $("#location-recommendation").has($(e.target)).length;
                    var searchModal = $('#myModal').has($(e.target)).length;
                    var isTertiaryNav = $('#tertiaryNav').has($(e.target)).length;
                    var isTertiaryOverflow = $('#tertiaryNav').height() < ($('#second-contact-link').height() + $('#tertiaryListContainer .tertiary-nav-container').height() + $('.primary-nav').height() + $('#tertiary-block > .tertiaryLevel3').height());
                    if ((!isInNavSubmenu || isInPrimaryLinks || isTertiaryNav) && !isBackDropHidden && !isOverflow && !isInLangSelect && !searchModal && !isTertiaryOverflow) {
                        e.preventDefault();
                    }
                    if ($(event.target).hasClass('back-drop-tablet')) {
                        e.preventDefault();
                    }
                });


            }

        },
        hideBackDrop: function () {
            if (!$isHidingBackdrop) {
                $isHidingBackdrop = true;
                $("html").css({ 'overflow': '' });
                $backDropTablet.css({ 'opacity': '0.6', 'z-index': '11' });
                $backDropTablet.animate({
                    opacity: '0',
                    zIndex: '11'
                }, 10);
                setTimeout(function () {
                    $backDropTablet.addClass('hidden');
                    $isHidingBackdrop = false;
                }, 100);
            }

        },
        showNavKeyPressedFirstItem: function (navlinks) {
            $isShowingSubMenu = true;
            var $this = navlinks;
            var subMenu = $("#" + $this.data("id"));
            $navLabel.removeClass('active').closest('.nav-submenu').removeClass('border-bottom');
            $navLabel.attr("aria-expanded", "false");
            subMenu.siblings('.nav-submenu-label').addClass('active');
            subMenu.siblings('.nav-submenu-label').attr("aria-expanded", "true");
            subMenu.parent('.nav-submenu').addClass('border-bottom');
            subMenu.css({ 'opacity': '0', 'top': '-530px' });
            subMenu.removeClass("hidden").animate({
                opacity: '1',
                top: '70px'
            }, 400);

            var focusSecondaryItem = subMenu.find('a').first();
            var lastFocusSecondaryItem = subMenu.find('a').last();

            setTimeout(function () {
                focusSecondaryItem.trigger("focus");
            }, 600);

            document.addEventListener('keydown', function (e) {
                var code = e.which;
                if (code === 36) {
                    focusSecondaryItem.trigger("focus");
                }
                else if (code === 35) {
                    lastFocusSecondaryItem.trigger("focus");
                }
            });

            var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
            var $body = $('body');
            var $layoutColumn = $(".layout-column");
            if (!jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                if ($baseFontsize != 0 && ($baseFontsize < $currentFontSize)) {
                    if (($('.secondary-navs').not(".hidden").height() + $(".navbar-background").height()) > $(window).height()) {
                        $layoutColumn.find(".multiple-l3").children().last().css({ "font-size": "" });
                        $headerTopNav.removeClass("navbar-fixed-top");
                        $navBarDefault.css({ "z-index": "1031" });
                        $body.css('padding-top', '0');
                        goTop();
                    }
                    $('.gh-item').not('.signin-container, .acn-logo').css({ "position": "relative", "z-index": "11" });
                    $tertiaryItem.css({ "min-width": " auto" });
                    $secondaryItem.css({ "word-break": " break-word" });
                }
            }
            $isShowingSubMenu = false;

        },
        showNavKeyPressedLastItem: function (navlinks) {
            $isShowingSubMenu = true;
            var $this = navlinks;
            var subMenu = $("#" + $this.data("id"));
            $navLabel.removeClass('active').closest('.nav-submenu').removeClass('border-bottom');
            $navLabel.attr("aria-expanded", "false");
            subMenu.siblings('.nav-submenu-label').addClass('active');
            subMenu.siblings('.nav-submenu-label').attr("aria-expanded", "true");
            subMenu.parent('.nav-submenu').addClass('border-bottom');
            subMenu.css({ 'opacity': '0', 'top': '-530px' });
            subMenu.removeClass("hidden").animate({
                opacity: '1',
                top: '70px'
            }, 400);

            var focusSecondaryItem = subMenu.find('a').first();
            var lastFocusSecondaryItem = subMenu.find('a').last();

            setTimeout(function () {
                lastFocusSecondaryItem.trigger("focus");
            }, 600);

            document.addEventListener('keydown', function (e) {
                var code = e.which;
                if (code === 36) {
                    focusSecondaryItem.trigger("focus");
                }
                else if (code === 35) {
                    lastFocusSecondaryItem.trigger("focus");
                }
            });

            var $currentFontSize = parseInt($(".nav-submenu-label-text").css("font-size"));
            var $body = $('body');
            var $layoutColumn = $(".layout-column");
            if (!jsUtility.isMobileBrowser() && !jsUtility.isMobile() && !jsUtility.isTablet()) {
                if ($baseFontsize != 0 && ($baseFontsize < $currentFontSize)) {
                    if (($('.secondary-navs').not(".hidden").height() + $(".navbar-background").height()) > $(window).height()) {
                        $layoutColumn.find(".multiple-l3").children().last().css({ "font-size": "" });
                        $headerTopNav.removeClass("navbar-fixed-top");
                        $navBarDefault.css({ "z-index": "1031" });
                        $body.css('padding-top', '0');
                        goTop();
                    }
                    $('.gh-item').not('.signin-container, .acn-logo').css({ "position": "relative", "z-index": "11" });
                    $tertiaryItem.css({ "min-width": " auto" });
                    $secondaryItem.css({ "word-break": " break-word" });
                }
            }
            $isShowingSubMenu = false;

        }
    };

    /* COUNTRY SELECTOR CONTROL */
    var countrySelectorControl = {
        closeCountrySelector: function () {
            if (hasClass($countrySelectorCont, $toggleCountryList)) {
                $countrySelectorCont.removeClass($toggleCountryList);
                $countrySelect.attr("aria-expanded", "false");
            }
        }
    };

    /* MENU CONTROL */
    var menuControl = {
        closeTabletMenu: function () {
            showHideSecondaryNav.hideBackDrop();
            $navContainer.removeClass('crawl-right');
            setTimeout(function () {
                $navIcon.removeClass("open");
                if (jsUtility.isTablet()) {
                    $navContainer.addClass('hidden');
                }
            }, 210);
            $navContent.children().css('display', '');
            var subMenu = $('div.secondary-navs');
            subMenu.removeClass('active').closest('.nav-submenu').removeClass('border-bottom');
            $navLabel.removeClass('active');
        },
        openTabletMenu: function () {
            showHideSecondaryNav.showBackDrop();
            $navContainer.removeClass('hidden');
            setTimeout(function () {
                $navIcon.addClass("open");
                $navContainer.addClass('crawl-right');
            }, 100);
        },
        closeTertiaryMenu: function () {
            $isTertiaryMenuClosed = true;
            $navMenu.parent().removeClass('hidden');
            $tertiaryNav.css("display", "none");
            $tertiaryListContainer.html("");
            $subMenuLabel.removeClass('tertiaryLevel3');
        },
        openMobileMenu: function () {
            $("html").css({ 'overflow': 'hidden' });
            $navIcon.addClass("open");
            $navContainer.addClass('crawl-down');
            $acnLogoContainer.addClass('hidden');
            $countrySelect.addClass('absolute-fade');
        },
        closeMobileMenu: function () {
            $("html").css({ 'overflow': '' });
            $navContent.children().css('display', '');
            $navIcon.removeClass("open");
            $navContainer.removeClass('crawl-down');
            $acnLogoContainer.removeClass('hidden');
            $countrySelect.removeClass('absolute-fade');
        },
        initializeMenu: function () {
            if (jsUtility.isTablet(true) || jsUtility.isMobile() || jsUtility.isTablet()) {
                if (!hasClass($divContainer, 'collapse')) {
                    $divContainer.addClass('collapse');
                    $navLabel.attr('data-toggle', 'collapse');
                }
            } else {
                $divContainer.removeClass('collapse');
                $navLabel.removeAttr('data-toggle');
            }
        },
        initializeAnalytics: function () {
            /* TERTIARY LINKS - ANALYTICS */
            if (!jsUtility.isMobile() && !jsUtility.isTablet()) {
                $groupTitle.removeAttr("data-linktype data-analytics-link-name data-analytics-module-name data-analytics-content-type data-linkaction data-componentname");
            } else {

                if ($groupTitle && $groupTitle.length) {
                    for (var i = 0; i < $groupTitle.length; i++) {
                        var linkValue = $($groupTitle[i]).children("span").text()
                        if (linkValue) {
                            $($groupTitle[i]).attr("data-analytics-link-name", linkValue.toLowerCase());
                        }

                    }
                    $groupTitle.attr({ 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-analytics-module-name': 'top nav', 'data-linkaction': linkValue.toLowerCase(), 'data-linkcomponentname':'top/nav' });
                }
            }
        },
        initializeAccessibleNavSubMenu: function () { //RMT10134	
            var secondaryLinkItem = $("li.col-sm-12.secondary-item");
            var backButton = $(".back-menu-container-gh ");
            var isSecondaryLinkPresent = $("li.col-sm-12.secondary-item").length > 0;
            var isBackButtonPresent = $(".back-menu-container-gh ").length > 0;
            var secondaryItemText = $("li.col-sm-12.secondary-item span.secondary-item-text");
            var isSecondaryItemPresent = secondaryItemText.length > 0;

            if (isSecondaryLinkPresent) {
                secondaryLinkItem.attr({ 'tabindex': 0 });
            }
            if (isBackButtonPresent) {
                backButton.attr({ 'tabindex': 0 });
            }
            if (isSecondaryItemPresent) {
                secondaryItemText.removeAttr('tabindex');
            }
        },
        initializeAccessibleHamburgerIcon: function () { //RMT10134
            var isPrimaryLinkPresent = $('#nav-icon').parents(".primary-nav").length > 0;
            var hamburgerIconContainer = $(".nav-icon-container");
            if (isPrimaryLinkPresent) {
                hamburgerIconContainer.attr({ 'tabindex': 0, 'aria-label': 'menu' });
                isHamburgerExpanded();
            }
        },
        removeAccessibleHamburgerIcon: function () { //RMT10134
            var isPrimaryLinkPresent = $('#nav-icon').parents(".primary-nav").length > 0;
            var hamburgerIconContainer = $(".nav-icon-container");
            if (isPrimaryLinkPresent) {
                hamburgerIconContainer.removeAttr('tabindex');
            }
        },
        removeAccessibleNavSubMenu: function () { //RMT10134
            var isNavIconOpen = $("#nav-icon").hasClass("open");
            var secondaryLinkItem = $("li.col-sm-12.secondary-item");
            var backButton = $(".back-menu-container-gh ");
            var isSecondaryLinkPresent = $("li.col-sm-12.secondary-item").length > 0;
            var isBackButtonPresent = $(".back-menu-container-gh ").length > 0;
            var secondaryItemText = $("li.col-sm-12.secondary-item span.secondary-item-text");
            var isSecondaryItemPresent = secondaryItemText.length > 0;

            if (isNavIconOpen == false) {
                if (isSecondaryLinkPresent) {
                    secondaryLinkItem.removeAttr('tabindex');
                }
                if (isBackButtonPresent) {
                    backButton.removeAttr('tabindex');
                }
                if (isSecondaryItemPresent) {
                    secondaryItemText.attr({ 'tabindex': 0 });
                }
            }
        },
        closeHamburgerIcon: function () { //RMT10134
            var isNavIconOpen = $("#nav-icon").hasClass("open");
            var secondaryLinkItem = $("li.col-sm-12.secondary-item");
            var backButton = $(".back-menu-container-gh ");
            var isSecondaryLinkPresent = $("li.col-sm-12.secondary-item").length > 0;
            var isBackButtonPresent = $(".back-menu-container-gh ").length > 0;
            var clickedSecondaryItem = $("li.col-sm-12.secondary-item.escClass");

            if (isNavIconOpen) {
                if (isSecondaryLinkPresent) {
                    secondaryLinkItem.attr({ 'tabindex': 0 });
                }
                if (isBackButtonPresent) {
                    backButton.attr({ 'tabindex': 0 });
                }
            }
            if (isNavIconOpen == false) {  //RMT10134
                if (isSecondaryLinkPresent) {
                    secondaryLinkItem.removeAttr('tabindex');
                    clickedSecondaryItem.removeClass("escClass");
                }
                if (isBackButtonPresent) {
                    backButton.removeAttr('tabindex');
                    clickedSecondaryItem.removeClass("escClass");
                }
            }
        }
    };

    /* GLOBAL FUNCTIONS */

    /* Overrides native jquery function hasClass() */
    function hasClass($thisElement, $class) {
        var classArray = $thisElement.attr('class');
        if (classArray) {
            classArray = classArray.split(" ");
        }

        if ($.inArray($class, classArray) > 0) {
            return true;
        } else {
            return false;
        }
    };

    /* Landscape && Portrait Functions */
    function isLandscape() {
        if ($(window).width() > $(window).height()) {
            return true;
        }
        else {
            return false;
        }
    };

    function isCountryListExpanded() {
        if ($countrySelectorCont.hasClass($toggleCountryList)) {
            $countrySelect.attr("aria-expanded", "true");
        }
        else {
            $countrySelect.attr("aria-expanded", "false");
        }
    };

    function isHamburgerExpanded() {
        /* Tablet */
        if ($navIcon.hasClass("open")) {
            $navIconContainer.attr('role', 'button');
            $navIconContainer.attr({ 'aria-expanded': 'false', 'aria-label': 'menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menuclose', 'data-analytics-link-name': 'menu', 'tabindex': 0 });
        } else {
            $navIconContainer.attr('role', 'button');
            $navIconContainer.attr({ 'aria-expanded': 'true', 'aria-label': 'close menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menu', 'data-analytics-link-name': 'menuclose', 'tabindex': 0 });
        }
        /* Mobile or Firefox */
        if ((!jsUtility.isTablet() && jsUtility.isMobile()) || jsUtility.isFirefox()) {
            if ($navIcon.hasClass("open")) {
                $navIconContainer.attr('role', 'button');
                $navIconContainer.attr({ 'aria-expanded': 'true', 'aria-label': 'close menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menu', 'data-analytics-link-name': 'menuclose', 'tabindex': 0 });
            } else {
                $navIconContainer.attr('role', 'button');
                $navIconContainer.attr({ 'aria-expanded': 'false', 'aria-label': 'menu', 'data-linktype': 'nav/paginate', 'data-analytics-content-type': 'nav/paginate', 'data-linkaction': 'menuclose', 'data-analytics-link-name': 'menu', 'tabindex': 0 });
            }
        }
    };

    /* WEB ACCESSIBILITY - KEYBOARD FUCNTIONALITY */
    document.onkeydown = function (e) {
        var code = e.which;
        var currentMenu = $($subMenuLabel).parent().find(".active");
        var isCountrySelector = $(document.activeElement).hasClass('country-select-cont');
        var isAuthUserMenu = $(document.activeElement).parents('div .signin-links').length > 0;
        var isMultipleL3 = $(document.activeElement).parents(".multiple-l3").length;
        var isLayoutColumn = $(document.activeElement).parents().hasClass("layout-column");
        var authUserMenu = $(".popover");
        var isMapped = $(document.activeElement).data('cell');
        var isOverviewLink = $(document.activeElement).hasClass('overview-link');
        var parentId = $(document.activeElement).parents('.secondary-navs').attr('id');
        var isSignInContainer = $(document.activeElement).hasClass("signin-container");
        var isNavSubMenuLabel = $(document.activeElement).hasClass("nav-submenu-label");
        var isSearchContainer = $(document.activeElement).hasClass("search-icon-container");
        var isInCountrySelector = $(document.activeElement).parents("#location-recommendation").length > 0;
        var isTertiaryItem = $(document.activeElement).parent().hasClass("tertiary-item");
        var isSecondaryItem = $(document.activeElement).parent().hasClass("secondary-item");
        var isOverviewItem = $(document.activeElement).parent().hasClass("first-secondary-item");
        var isAcnLogo = $(document.activeElement).hasClass("gh-item acn-logo");
        var isTopLevelElement = $(document.activeElement).hasClass('gh-item');
        var hasMultiPageNavigation = $(document.activeElement).parents('#multipage-nav').length > 0;
        var countrySelectorLastItem = $("#location-recommendation").find("a").last();
        var countrySelectorFirstItem = $("#location-recommendation").find("ul li:nth-child(3) a");
        var isHamburgerIcon = $(document.activeElement).hasClass("nav-icon-container hidden-lg");
        var isSecondaryMenu = $(document.activeElement).hasClass("col-sm-12 secondary-item");
        var isBackButton = $(document.activeElement).hasClass("back-menu-container-gh");
        var isMenuDropdownOpen = $("div#nav-content-menu.nav-content.panel-group.crawl-right").length > 0 || $("div#nav-content-menu.nav-content.panel-group.crawl-down").length > 0;
        var isNavIconOpen = $("#nav-icon").hasClass("open");
        var clickedSecondaryItem = $("li.col-sm-12.secondary-item.escClass");
        var hamburgerButton = $("div.nav-icon-container.hidden-lg");
        var backButton = $("div.back-menu-container-gh ");
        var accentureLogo = $("a.gh-item.acn-logo");
        var socialIconItem = $("#menuFooter").find("a").last();
        var socialIconSecondary = $("#second-contact-link").find("a").last();
        var subMenuFirstItem = $("#navigation-menu").find("div.gh-item.nav-submenu-label").first();
        var isSubMenuFirst = subMenuFirstItem.is(':focus');
        var lastItemGH5 = $("ul.tertiary-nav-container.col-sm-12.hidden-xs.hidden-sm.hidden-md").find("a").last();
        var accentureLogoXs = $("a.acn-logo");
        var signOutItem = $("div.popover-content div.signin-links ul li a#signout");
        var isSignOut = signOutItem.is(":focus");
        var popOVerJobs = $("div.popover-content div.signin-links ul li").find("a").first();
        var fullWidthVideoHeroVariant = $("div.hero-homepage-full-width-video-enabled");
        var isRegisterContainer = $(document.activeElement).hasClass("register-container");

        /*Last Item Nav Checker*/
        if (document.activeElement === countrySelectorLastItem[0]) {
            if (code === 9) {
                if ($countrySelectorCont.hasClass($toggleCountryList)) {
                    $countrySelectorCont.toggleClass($toggleCountryList);
                    isCountryListExpanded();
                    if ($('#redesign-main').hasClass('.body-content')) {
                        $('#redesign-main.body-content').next().find(':focusable').first().trigger("focus");
                    }

                    //BUG1344635
                    if ((fullWidthVideoHeroVariant !== null || typeof fullWidthVideoHeroVariant !== 'undefined') && fullWidthVideoHeroVariant.length > 0) {
                        var heroButtonFullWidth = $(".hero-btn-wrapper").eq(0);
                        var qatFirst = $(".quick-access-tab").find('a').first();
                        var breadCrumb = $(".about-hero-parent-bcrumb a");
                        var careersHomePageKeywordSearch = $("#about-hero .job-search-enabled #job-search-hero-bar");

                        if (qatFirst.length > 0) {
                            e.preventDefault();
                            qatFirst.trigger("focus");
                        }else if (breadCrumb.length > 0) {
                            e.preventDefault();
                            breadCrumb.first().trigger("focus");
                        } else if (careersHomePageKeywordSearch.length > 0) {
                            e.preventDefault();
                            careersHomePageKeywordSearch.trigger("focus");
						}
                        else if (heroButtonFullWidth.length > 0) {
                            e.preventDefault();
                            heroButtonFullWidth.trigger("focus");
                        }
                        else {
                            $('#redesign-main.body-content').find(':focusable').first().trigger("focus");
                        }
                    }
                }
            }
            if (e.shiftKey && code === 9) {
                $countrySelectorCont.toggleClass($toggleCountryList);
                $(document.activeElement).parent().prev().children().trigger("focus");
                e.preventDefault();
            }
        }

        if (document.activeElement === countrySelectorFirstItem[0]) {
            if (e.shiftKey && code === 9) {
                if ($countrySelectorCont.hasClass($toggleCountryList)) {
                    $countrySelectorCont.toggleClass($toggleCountryList);
                    isCountryListExpanded();
                    $countrySelect.trigger("focus");
                    e.preventDefault();
                }
            }
        }

        /* Country Selector Activate Keys */
        if (isCountrySelector) {
            if (code === 13) {
                $(document.activeElement).trigger("click");
                setTimeout(function () {
                    countrySelectorFirstItem.trigger("focus");
                }, 700);
                e.preventDefault();
            }
            if (code === 32) {
                if (jsUtility.isFirefox()) {
                    $(document.activeElement).trigger("click");
                    countrySelectorFirstItem.trigger("focus");
                    e.preventDefault();
                }
                $(document.activeElement).trigger("click");
                setTimeout(function () {
                    countrySelectorFirstItem.trigger("focus");
                }, 2000);
                e.preventDefault();
            }
        }
        if (isHamburgerIcon) {
            if (code === 32) {
                if (jsUtility.isFirefox()) {
                    isHamburgerExpanded();
                    if (isNavIconOpen) {
                        $(document.activeElement).attr("aria-expanded", "true");
                    } else {
                        $(document.activeElement).attr("aria-expanded", "false");
                    }
                }
            }
        }
        /* tab key */
        if (code === 9 && !e.shiftKey) {
            /*Order of Tab Navigation in Global Header when Zoomed*/
            if ($(document.activeElement).text() == "Skip to footer") {
                GetCountrySelectorData();
                accentureLogo.trigger("focus");
                e.preventDefault();
                if ((jsUtility.isTablet() || jsUtility.isMobile())) {
                    hamburgerButton.trigger("focus");
                    e.preventDefault();
                }
                if (zoomLevel() >= 150) {
                    hamburgerButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isHamburgerIcon && isNavIconOpen == false) {
                if ($acnLogoContainer.hasClass('hidden-sm') || $acnLogoContainer.hasClass('hidden-xs')) {
                    accentureLogo.trigger("focus");
                    menuControl.closeHamburgerIcon();
                    menuControl.removeAccessibleNavSubMenu();
                    menuControl.closeTabletMenu();
                    menuControl.closeMobileMenu();
                    e.preventDefault();
                }
                if ($acnLogoContainer.hasClass('hidden-lg') || $acnLogoContainer.hasClass('hidden-md')) {
                    accentureLogoXs.trigger("focus");
                    menuControl.closeHamburgerIcon();
                    menuControl.removeAccessibleNavSubMenu();
                    menuControl.closeTabletMenu();
                    menuControl.closeMobileMenu();
                    e.preventDefault();
                }
            }
            else if (document.activeElement === socialIconItem[0] || document.activeElement === socialIconSecondary[0]) {
                if ($acnLogoContainer.hasClass('hidden-sm') || $acnLogoContainer.hasClass('hidden-xs')) {
                    menuControl.closeHamburgerIcon();
                    menuControl.removeAccessibleNavSubMenu();
                    menuControl.closeTabletMenu();
                    menuControl.closeMobileMenu();
                    hamburgerButton.attr({ 'aria-expanded': 'false', 'aria-label': 'menu' });
                    accentureLogo.trigger("focus");
                    e.preventDefault();
                }
                if ($acnLogoContainer.hasClass('hidden-lg') || $acnLogoContainer.hasClass('hidden-md')) {
                    menuControl.closeHamburgerIcon();
                    menuControl.removeAccessibleNavSubMenu();
                    menuControl.closeTabletMenu();
                    menuControl.closeMobileMenu();
                    hamburgerButton.attr({ 'aria-expanded': 'false', 'aria-label': 'menu' });
                    setTimeout(function () {
                        accentureLogoXs.trigger("focus");
                    }, 500);
                    e.preventDefault();
                }
            }
            else if (isHamburgerIcon && isNavIconOpen) {
                subMenuFirstItem.trigger("focus");
                e.preventDefault();
                if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                    $countrySelect.trigger("focus");
                    e.preventDefault();
                }
                if ($navLabel.hasClass('tertiaryLevel3') && !jsUtility.isMobile()) {
                    backButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isCountrySelector && isNavIconOpen) {
                subMenuFirstItem.trigger("focus");
                e.preventDefault();
                if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                    subMenuFirstItem.trigger("focus");
                    e.preventDefault();
                }
                if ($('.nav-submenu-label').hasClass('tertiaryLevel3')) {
                    backButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (document.activeElement === countrySelectorLastItem[0] && isNavIconOpen) {
                if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                    subMenuFirstItem.trigger("focus");
                    e.preventDefault();
                }
                if ($('.nav-submenu-label').hasClass('tertiaryLevel3')) {
                    backButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isAcnLogo && isNavIconOpen == false) {
                if (jsUtility.isTablet(true) || jsUtility.isTablet() || jsUtility.isMobile()) {
                    $('.ion-ios-search.serp').trigger("focus");
                    e.preventDefault();
                }
            }
            else if ((lastItemGH5.is(":focus"))) {
                if (isNavIconOpen == false) {
                    showHideSecondaryNav.hideSubNav();
                    $('.ion-ios-search.serp').trigger("focus");
                    e.preventDefault();
                } else {
                    $('#menuFooter').find("a").first().trigger("focus");
                    e.preventDefault();
                }
            }
            else if ($(document.activeElement).hasClass("serp") && isNavIconOpen == false) {
                if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                    $countrySelect.attr('tabindex', -1);
                }
                else {
                    $countrySelect.removeAttr('tabindex');
                }
            }

            else if (isSignOut) {
                $(".popover").removeClass("show");
                $userLinks.attr("aria-expanded", "false");
                $("#country-language-selector").trigger("focus");
                e.preventDefault();
            }
        }

        /* shift + tab key */
        if (e.shiftKey && code === 9) {
            if (isHamburgerIcon) {
                $("a.skip-link.skip-link-focusable.focus-indicator").trigger("focus");
                menuControl.closeHamburgerIcon();
                menuControl.removeAccessibleNavSubMenu();
                menuControl.closeTabletMenu();
                menuControl.closeMobileMenu();
                hamburgerButton.attr({ 'aria-expanded': 'false', 'aria-label': 'menu' });
                e.preventDefault();
                if (!$('.ui-wrapper').hasClass('focus-indicator')) {
                    $("a.skip-link.skip-link-focusable").trigger("focus");
                    menuControl.closeHamburgerIcon();
                    menuControl.removeAccessibleNavSubMenu();
                    menuControl.closeTabletMenu();
                    menuControl.closeMobileMenu();
                    hamburgerButton.attr({ 'aria-expanded': 'false', 'aria-label': 'menu' });
                    e.preventDefault();
                }
            }
            else if (isSubMenuFirst || isBackButton) {
                accentureLogo.trigger("focus");
                e.preventDefault();
                if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                    $countrySelect.trigger("focus");
                    e.preventDefault();
                } else {
                    hamburgerButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isCountrySelector && isNavIconOpen) {
                hamburgerButton.trigger("focus");
                e.preventDefault();
            }
            else if ($(document.activeElement).hasClass("serp")) {
                if (jsUtility.isTablet(true) || jsUtility.isMobile()) {
                    if ($acnLogoContainer.hasClass('hidden-sm') || $acnLogoContainer.hasClass('hidden-xs')) {
                        accentureLogo.trigger("focus");
                        e.preventDefault();
                    }
                    if ($acnLogoContainer.hasClass('hidden-lg') || $acnLogoContainer.hasClass('hidden-md')) {
                        accentureLogoXs.trigger("focus");
                        e.preventDefault();
                    }
                }
            }
            else if (!jsUtility.isTablet() && jsUtility.isMobile()) {
                if (accentureLogoXs.is(':focus')) {
                    hamburgerButton.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (countrySelectorFirstItem.is(':focus')) {
                if ($countrySelectorCont.hasClass($toggleCountryList)) {
                    $countrySelectorCont.toggleClass($toggleCountryList);
                    isCountryListExpanded();
                    $countrySelect.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (countrySelectorLastItem.is(':focus')) {
                $countrySelectorCont.toggleClass($toggleCountryList);
                $(document.activeElement).parent().prev().children().trigger("focus");
                e.preventDefault();
            }
            else if (popOVerJobs.is(":focus")) {
                $(".popover").removeClass("show");
                $userLinks.attr("aria-expanded", "false");
                $userLinks.trigger("focus");
                e.preventDefault();
            }
        }

        /* escape key */
        if (code === 27) {
            if ($countrySelectorCont.hasClass($toggleCountryList)) {
                $countrySelectorCont.toggleClass($toggleCountryList);
                isCountryListExpanded();
                $countrySelect.trigger("focus");
                if (jsUtility.isTablet(true) || jsUtility.isMobile()) {
                    setTimeout(function () {
                        $countrySelect.trigger("focus");
                    }, 10);
                }
                e.preventDefault();
            }
            if ($subMenuLabel.hasClass("active")) {
                var currentSubmenuLabel = $subMenuLabel.parent().find(".active");
                $subMenuLabel.parent().find(".active").trigger("click");
                setTimeout(function () {
                    currentSubmenuLabel.trigger("focus");
                }, 400);
                e.preventDefault();
            }

            if (isSignInContainer || isAuthUserMenu) {
                linkPopOver.removeClass("show");
                $userLinks.trigger("focus");
                $userLinks.attr("aria-expanded", "false");
                e.preventDefault();
            }

            if (isNavIconOpen) {
                $(document.activeElement).parents().find("div.nav-icon-container.hidden-md.hidden-lg").trigger("click");
                menuControl.closeHamburgerIcon();
                menuControl.removeAccessibleNavSubMenu();
                hamburgerButton.trigger("focus");
                clickedSecondaryItem.removeClass("escClass");
                e.preventDefault();
            }
        }
        /* enter or space key - simulates click */
        else if ((code === 13) || (code === 32)) {
            if (isSignInContainer) {
                if (authUserMenu.length > 0) {
                    authUserMenu.trigger("click");
                }
                else {
                    $(document.activeElement).trigger("click");
                }
            }
            else if (isInCountrySelector) {
                $(document.activeElement)[0].click();
                e.preventDefault();
            }
            else if (isAcnLogo) {
                $(document.activeElement).children("img").trigger("click");
            }
            else if (isNavSubMenuLabel) {
                $isKeyboard = true;
                $(document.activeElement).trigger("click");
                e.preventDefault();
            }
            else if (isSearchContainer) {
                $(".search-icon-container").trigger("click");
                e.preventDefault();
            }
            else if (isTertiaryItem || isSecondaryItem || isOverviewItem) {
                e.preventDefault();
                $(document.activeElement)[0].click();
            }
            else if (hasMultiPageNavigation) {
                $(document.activeElement)[0].click();
            }
            else if (isHamburgerIcon) {
                $isKeyboard = true;
                $(document.activeElement).trigger("click");
                menuControl.initializeAccessibleHamburgerIcon();
                menuControl.initializeAccessibleNavSubMenu();
                clickedSecondaryItem.removeClass("escClass");
                $(document.activeElement).trigger("focus");
                isHamburgerExpanded();
                e.preventDefault();
            }

            else if (isSecondaryMenu) {
                $isKeyboard = true;
                $(document.activeElement).addClass("escClass");
                $(document.activeElement).trigger("click");
                backButton.trigger("focus");
                e.preventDefault();
            }

            else if (isBackButton) {
                $isKeyboard = true;
                $(document.activeElement).trigger("click");
                clickedSecondaryItem.trigger("focus");
                clickedSecondaryItem.removeClass("escClass");
                $(document.activeElement).trigger("focus");
                e.preventDefault();
            }
            else if (isRegisterContainer && code === 32) {
                e.preventDefault();
            }
        }
        /* right arrow key */
        else if (code === 39) {
            if (isNavSubMenuLabel) {
                $isKeyboard = true
                if (isMenuDropdownOpen) {
                    $(document.activeElement).trigger("click");
                    $(document.activeElement).trigger("focus");
                    e.preventDefault();
                }
            }
            if (isSecondaryMenu) {
                $isKeyboard = true;
                $(document.activeElement).addClass("escClass");
                $(document.activeElement).trigger("click");
                backButton.trigger("focus");
                e.preventDefault();
            }

            if (isTopLevelElement) {
                e.preventDefault();
                if (isMenuDropdownOpen == false) {
                    itemMoveRight();
                }
            }
            else if (isMapped && isMapped.length == 2) {
                if (isLayoutColumn && isMultipleL3 > 0) {
                    if (!($(document.activeElement).parents(".secondary-item").children("ul").find("a").attr("data-cell")[0] == "D")) {
                        $(document.activeElement).parents(".secondary-item").next().children("ul").find("a")[0].trigger('focus');
                    }
                }
                else {
                    e.preventDefault();
                    moveRight();
                }
            }

        }
        /* left arrow */
        else if (code === 37) {
            if (isBackButton) {
                $isKeyboard = true;
                $(document.activeElement).trigger("click");
                clickedSecondaryItem.trigger("focus");
                clickedSecondaryItem.removeClass("escClass");
                $(document.activeElement).trigger("focus");
                e.preventDefault();
            }
            if (isNavSubMenuLabel) {
                $isKeyboard = true
                if (isMenuDropdownOpen) {
                    $(document.activeElement).trigger("click");
                    isNavSubMenuLabel.siblings().removeClass('hidden');
                    $(document.activeElement).trigger("focus");
                    e.preventDefault();
                }
            }
            if (isTopLevelElement) {
                if (isMenuDropdownOpen == false) {
                    itemMoveLeft();
                }
            }
            if (isMapped && isMapped.length == 2) {
                if (isLayoutColumn && isMultipleL3 > 0) {
                    if (!($(document.activeElement).parents(".secondary-item").prev().children("ul").find("a").attr("data-cell")[0] == "D")) {
                        $(document.activeElement).parents(".secondary-item").prev().children("ul").find("a")[0].trigger('focus');
                    }
                }
                else {
                    e.preventDefault();
                    moveLeft();
                }
            }

        }
        /* down arrow key */
        else if (code === 40) {
            var isPrimaryLinkMenuOpen = $(document.activeElement).parent().children('.active').length;
            var overviewLink = $(document.activeElement).parent().children('.secondary-navs').find('.overview-link');
            var firstLink = $(document.activeElement).parent().siblings('li').find('a').first();

            if (isSignInContainer) {
                authUserMenu.children(".popover-content").find("a").first().trigger("focus");
                e.preventDefault();
            }
            if (isAuthUserMenu) {
                $(document.activeElement).parent().next().children().trigger("focus");
                e.preventDefault();
            }
            if (isPrimaryLinkMenuOpen > 0) {
                if (overviewLink.length > 0) {
                    overviewLink.trigger("focus");
                    e.preventDefault();
                } else {
                    firstLink = $(document.activeElement).parent().children().find('a').first();
                    firstLink.trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isOverviewLink) {
                firstLink = $(document.activeElement).parent().siblings('li').find('a').first();
                firstLink.trigger("focus");
                e.preventDefault();
            }
            else if (isMapped && isMapped.length == 2) {
                moveDown();
                e.preventDefault();
            }
            else if (isCountrySelector) {
                $(document.activeElement).trigger("click");
                setTimeout(function () {
                    countrySelectorFirstItem.trigger("focus");
                }, 700);
                e.preventDefault();
            }
            if (isInCountrySelector) {
                if (document.activeElement === countrySelectorLastItem[0]) {
                    countrySelectorFirstItem.trigger("focus");
                    e.preventDefault();
                } else {
                    $(document.activeElement).parent().next().children().trigger("focus");
                    e.preventDefault();
                }
            }
        }
        /* up arrow key */
        else if (code === 38) {
            var hasOverviewLink = $(document.activeElement).parents('.nav-submenu').find('.overview-link');

            if (isAuthUserMenu) {
                if ($(document.activeElement).parent().prev().length == 0) {
                    $userLinks.trigger("focus");
                    e.preventDefault();
                } else {
                    $(document.activeElement).parent().prev().children().trigger("focus");
                    e.preventDefault();
                }
            }
            if (isMapped) {
                if (isMapped.length == 2 && isMapped[1] == 0) {
                    if (hasOverviewLink.length > 0) {
                        $(document.activeElement).parents().siblings('li').children('a.overview-link').trigger("focus");
                        e.preventDefault();
                    } else {
                        $(document.activeElement).parents('.nav-submenu').find('.gh-item').trigger("focus");
                        e.preventDefault();
                    }
                }
                else if (isMapped.length == 2 && isMapped[1] > 0) {
                    moveUp();
                    e.preventDefault();
                }
                else if (isOverviewLink) {
                    $(document.activeElement).parents('.nav-submenu.panel').find('.gh-item').trigger("focus");
                    e.preventDefault();
                }
            }
            else if (isOverviewLink) {
                $(document.activeElement).parents('.nav-submenu.panel').find('.gh-item').trigger("focus");
                e.preventDefault();
            }
            if (isInCountrySelector) {
                if (document.activeElement === countrySelectorFirstItem[0]) {
                    countrySelectorLastItem.trigger("focus");
                    e.preventDefault();
                } else {
                    $(document.activeElement).parent().prev().children().trigger("focus");
                    e.preventDefault();
                }
            }
            if (isCountrySelector) {
                $(document.activeElement).trigger("click");
                setTimeout(function () {
                    countrySelectorLastItem.trigger("focus");
                }, 700);
                e.preventDefault();
            }
        }
        /* home key */
        else if (code === 36) {
            if (isInCountrySelector) {
                countrySelectorFirstItem.trigger("focus");
                e.preventDefault();
            }
        }
        /* end key */
        else if (code === 35) {
            if (isInCountrySelector) {
                countrySelectorLastItem.trigger("focus");
                e.preventDefault();
            }
        }

        /* Top Level Controls */
        function itemMoveRight() {
            var cell = $(document.activeElement).data('cell');
            newLocator = '[data-cell=GH' + nextInt(cell[2], $tabElements.length) + ']';
            $(newLocator).trigger("focus");
        };
        function itemMoveLeft() {
            var cell = $(document.activeElement).data('cell');
            newLocator = '[data-cell=GH' + previousInt(cell[2]) + ']';
            $(newLocator).trigger("focus");
        };

        /* Secondary Nav Controls */
        function moveDown() {
            var newCell = String($(document.activeElement).attr('data-cell')[0]) + '' + String(nextInt($(document.activeElement).attr('data-cell')[1]));
            var newLocator = '#' + parentId + ' ' + '[data-cell=' + newCell + ']';
            if ($(newLocator).length == 0) {
                newLocator = getNearestCell(parentId, newCell, code)
            }
            $(newLocator).trigger("focus");

        };
        function moveUp() {
            var newCell = String($(document.activeElement).attr('data-cell')[0]) + '' + String(previousInt($(document.activeElement).attr('data-cell')[1]));
            var newLocator = '#' + parentId + ' ' + '[data-cell=' + newCell + ']';
            $(newLocator).trigger("focus");
        };
        function moveRight() {
            var newCell = nextChar($(document.activeElement).attr('data-cell')[0]) + '' + String($(document.activeElement).attr('data-cell')[1]);
            var newLocator = '#' + parentId + ' ' + '[data-cell=' + newCell + ']';
            if ($(newLocator).length == 0) {
                newLocator = getNearestCell(parentId, newCell, code)
            }
            $(newLocator).trigger("focus");
        };
        function moveLeft() {
            var newCell = previousChar($(document.activeElement).attr('data-cell')[0]) + '' + String($(document.activeElement).attr('data-cell')[1]);
            var newLocator = '#' + parentId + ' ' + '[data-cell=' + newCell + ']';
            if ($(newLocator).length == 0) {
                newLocator = getNearestCell(parentId, newCell, code)
            }
            $(newLocator).trigger("focus");
        };

        /* Data Grid Functions */
        function nextChar(c) {
            if (isLayoutColumn && isMultipleL3 > 0) {
                return ((c.charCodeAt(0) + 1) > 68) ? 'E' : String.fromCharCode(c.charCodeAt(0) + 1);
            }
            else {
                return ((c.charCodeAt(0) + 1) > 67) ? 'D' : String.fromCharCode(c.charCodeAt(0) + 1);
            }
        };
        function previousChar(c) {
            return ((c.charCodeAt(0) - 1) < 65) ? 'A' : String.fromCharCode(c.charCodeAt(0) - 1);
        };
        function nextInt(i, lastRow) {
            return (parseInt(i) + 1) > lastRow ? lastRow + 1 : parseInt(i) + 1;
        };
        function previousInt(i) {
            return (parseInt(i) - 1) < 0 ? 0 : parseInt(i) - 1;
        };
        function getNearestCell(parentId, cell, key) {
            var locator = '';
            if (key == 40) { //arrow down
                var lastRow = $("#" + parentId + '> div .nav-item-links > ul').data('lastrow');
                for (var i = parseInt(cell[1]); i <= lastRow && $(locator).length == 0; i = nextInt(i, lastRow)) {
                    locator = '#' + parentId + ' ' + '[data-cell=' + cell[0] + String(i) + ']';
                }
            } else if (key == 38) { //arrow up
                for (var i = parseInt(cell[1]); i != 0 && $(locator).length == 0; i = previousInt(i)) {
                    locator = '#' + parentId + ' ' + '[data-cell=' + cell[0] + String(i) + ']';
                }
            } else if (key == 37) { //arrow left
                var subMenu = $('.nav-submenu');
                if (isLayoutColumn && isMultipleL3 > 0) {
                    $(document.activeElement).parents(".secondary-item").prev().children("ul").find("a")[0].trigger('focus');
                }
                else {
                    for (var i = cell[0]; $(locator).length == 0; i = previousChar(i)) {
                        locator = '#' + parentId + ' ' + '[data-cell=' + i + cell[1] + ']';
                    }
                }

            } else if (key == 39) { //arrow right
                if (isLayoutColumn && isMultipleL3 > 0) {
                    for (var i = cell[0]; i != 'E' && $(locator).length == 0; i = nextChar(i)) {
                        locator = '#' + parentId + ' ' + '[data-cell=' + i + '0' + ']';
                    }
                }
                else {
                    for (var i = cell[0]; i != 'D' && $(locator).length == 0; i = nextChar(i)) {
                        locator = '#' + parentId + ' ' + '[data-cell=' + i + cell[1] + ']';
                    }
                }
            }
            return locator;
        };
    };

    // function to verify if all cookie settings are enabled
    var areCookieSettingsEnabled = function () {
        var enabled = false;
        var optanonCookie = acncm.CacheManager.read('OptanonConsent');

        // if value of cookie is not null (means cookies are enabled in browser)
        if (optanonCookie) {
            var optanonCookieVars = optanonCookie.split('&');

            var optanonGroupsIndex = -1;
            optanonCookieVars.forEach(function (key) {
                if (key.includes('groups')) {
                    optanonGroupsIndex = optanonCookieVars.indexOf(key);
                }
            });

            if (optanonGroupsIndex !== -1) {
                var cookieSettingsString = optanonCookieVars[optanonGroupsIndex];
                cookieSettingsString = cookieSettingsString.split('=')[1].split(',');

                // verify if all cookie settings in site are enabled or not
                enabled = true;
                cookieSettingsString.forEach(function (key) {
                    if (key.split(':')[1] === '0') {
                        enabled = false;
                    }
                });
            }

        }
        return enabled;
    }

    var displayCareersHomeLocalVersionLink = function () {

        var careersHomeLocalVersionLink = $(".careershome-localversion");
        var workdayDomain = careersHomeLocalVersionLink.data("wddomain") ? careersHomeLocalVersionLink.data("wddomain") : "";
        var workdayCareersPath = "/AccentureCareers";
        var cookiesEnabled = areCookieSettingsEnabled();
        var previousPage = document.referrer;
        var visitedWorkday = "";
        var careersHomeLocalVersionLinkId = $("#careershome-localversion");
        if (cookiesEnabled) {
            visitedWorkday = acncm.CacheManager.read("VisitedWorkdayPortal");
        }


        // display access application button via referrer link
        if (previousPage && workdayDomain &&
            previousPage.includes(workdayDomain) &&
            previousPage.includes(workdayCareersPath) &&
            cookiesEnabled) {
                careersHomeLocalVersionLink.removeClass("hide");
                careersHomeLocalVersionLinkId.parent().css('height', 9.64 + 'em');
                acncm.CacheManager.writeFlagCookie("VisitedWorkdayPortal", "True", "");
        }
        // display access application buttons via cookie value
        else if (visitedWorkday && visitedWorkday === "True") { 
            careersHomeLocalVersionLink.removeClass("hide");
            careersHomeLocalVersionLinkId.parent().css('height', 9.64 + 'em');
        }
        else if (cookiesEnabled) {
            acncm.CacheManager.writeFlagCookie("VisitedWorkdayPortal", "False", "");
        }

    };

    var pollOptanonConsentCookie = function () {
        var pollCookie = setInterval(() => {
            var optanonCookie = acncm.CacheManager.read("OptanonConsent");
            if (typeof optanonCookie !== "undefined") {
                displayCareersHomeLocalVersionLink();
                clearInterval(pollCookie);
            }
        }, 1000);
    };

    var careersHomeLocalVersionLinkAnalytics = function () {
        $(".careershome-localversion").attr("data-analytics-link-name", "visit local careers page");
        $("#careershome-localversion a").attr("data-analytics-link-name", "visit local careers page");
    };

    //Keyword Search Cache  - About Hero
    var removeCachedKeywordSearchSession = function () {
        var isCareersLandingPage = $("#about-hero-button-container").data("is-careers-landing")
            ? $("#about-hero-button-container").data("is-careers-landing")
            : "";
        var currentPageUrl = window.location.href;
        var isJobSearchPage = currentPageUrl.indexOf("jobsearch") > -1 ? currentPageUrl.indexOf("jobsearch") > -1 : "";

        //remove session storage key when page is not careers home and jobsearch
        if (sessionStorage.getItem("VisitedJobSearch") !== null && sessionStorage.getItem("VisitedJobSearch").length > 1 && !isCareersLandingPage && !isJobSearchPage)
        {
            sessionStorage.removeItem("VisitedJobSearch");
        }

    };

    return {
        init: init,
        addBodyId: addBodyId,
        menuControl: menuControl,
        showHideSecondaryNav: showHideSecondaryNav,
        destroyPackery: destroyPackery,
        NavMenuScrollOnZoom: NavMenuScrollOnZoom,
        elements: {
            $viewPortWidth: $viewPortWidth,
            $deviceHeight: $deviceHeight,
            $backDropTablet: $backDropTablet,
            $countrySelectorCont: $countrySelectorCont,
            $mobileShowToggle: $mobileShowToggle,
            $nav: $nav,
            $navContainer: $navContainer,
            $navIcon: $navIcon,
            $navIconContainer: $navIconContainer,
            $navLabel: $navLabel,
            $toggleCountryList: $toggleCountryList,
            $varSearchBody: $varSearchBody,
            $divContainer: $divContainer,
            $acnLogoContainer: $acnLogoContainer,
            $documentClick: $documentClick,
            $navMenu: $navMenu,
            $menuFooter: $menuFooter,
            $tertiaryContainer: $tertiaryContainer,
            $groupTitle: $groupTitle,
            $tertiaryClose: $tertiaryClose,
            $tertiaryNav: $tertiaryNav,
            $primaryNav: $primaryNav,
            $secondContactLink: $secondContactLink,
            $tertiaryListContainer: $tertiaryListContainer,
            $subMenuLabel: $subMenuLabel,
            $isTertiaryMenuClosed: $isTertiaryMenuClosed,
            $userLinks: $userLinks,
            $isHidingSubMenu: $isHidingSubMenu,
            $isShowingSubMenu: $isShowingSubMenu,
            $isShowingBackdrop: $isShowingBackdrop,
            $isHidingBackdrop: $isHidingBackdrop,
            $navContent: $navContent,
            $tabElements: $tabElements,
            $isKeyboard: $isKeyboard,
            $countrySelect: $countrySelect,
            $headerTopNav: $headerTopNav,
            $secondaryItem: $secondaryItem,
            $tertiaryItem: $tertiaryItem,
            $baseFontsize: $baseFontsize,
            $grid: $grid
        }

    }

})

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\AnalyticsOverride.js
/*version 2*/
$(window).on("load", function () {
    if (typeof (inos) != 'undefined') {
        var s = inos;
        console.log('s variable overriden by inos');
    }
});
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\hero-block.js
/*  version="5" */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define['jquery'], function (jquery) {
            return (root.HeroBlock = factory(jquery));
        }
    }
    else {
        root.HeroBlock = factory(root.jQuery, root.jsUtility);

        if (ComponentRegistry.HeroBlock) {
            $(function () {
                HeroBlock.setHeroImage();
                HeroBlock.setFeatureBackgroundImage();
            });

            root.jQuery(window).on("resize", function () {
                HeroBlock.setHeroImage();
                HeroBlock.setFeatureBackgroundImage();
            });
        }
    }

}(typeof self !== 'undefined' ? self : this, function ($, jsUtility) {

    var setHeroImage = function () {

        var $heroImageContainer = $("#hero-carousel .hero-image-container");

        if ($heroImageContainer) {
            var alignment = $heroImageContainer.data("alignment");
            var src = alt = "";

            if (jsUtility.isMobile()) {
                src = $heroImageContainer.data("imagexs");
                alt = $heroImageContainer.data("imagexsalt");
            }
            else if (jsUtility.isTablet()) {
                src = $heroImageContainer.data("imagesm");
                alt = $heroImageContainer.data("imagesmalt");
            }
            else {
                src = $heroImageContainer.data("imagelg");
                alt = $heroImageContainer.data("imagelgalt");
            }

            var $heroImage = $("#hero-carousel .hero-item-image .dynamic-bg");

            if ($heroImage) {
                $heroImage.remove();
            }

            if (src) {
                var tempAlt = (alt) ? alt : " ";
                $heroImageContainer.append("<img src='" + src + "' alt='" + tempAlt + "' class='col-xs-12 col-sm-4 dynamic-bg " + alignment + "'>");
            }
        }
    }; 

    var setFeatureBackgroundImage = function () {
        var $backgroundContainer = $("#hero-carousel .hero-item-featureoverview");

        if ($backgroundContainer) {
            var src = "";
            var $mobileBackgroundImage = $("#hero-carousel .hero-item-featureoverview .hero-wrapper > img");

            if ($mobileBackgroundImage) {
                $mobileBackgroundImage.remove();
            }
            $backgroundContainer.css('background-image', "");

            if (jsUtility.isMobile()) {
                var $heroWrapper = $("#hero-carousel .hero-item-featureoverview .hero-wrapper");

                src = $backgroundContainer.data("imagexs");

                if (src && $heroWrapper) {
                    $heroWrapper.append("<img src='" + src + "' alt=' ' class='col-xs-12'>");
                }
            }
            else {

                if (jsUtility.isTablet()) {
                    src = $backgroundContainer.data("imagesm");
                }
                else {
                    src = $backgroundContainer.data("imagelg");
                }

                if (src) {
                    $backgroundContainer.css('background-image', "url(" + src + ")");
                }
            }
        }
    }; 

    return {
        setHeroImage: setHeroImage,
        setFeatureBackgroundImage: setFeatureBackgroundImage
    }
}));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\analytics-link-tracking-attributes.js
/* version 76.0 */
//This script will inject link tracking attributes to the
//page according to the defined list of criteria.
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], function (jquery) {
            return (root.AnalyticsLinkTrackingAttributes = factory(jquery));
        });
    }
    else {
        root.AnalyticsLinkTrackingAttributes = factory(root.jQuery);
        root.jQuery(window).on("load", function () {
            if ((typeof _satellite !== "undefined") && (_satellite.getVar("TrackingPlatform") === "adobelaunch"))
                AnalyticsLinkTrackingAttributes.init();
        });
    }
}(typeof self !== 'undefined' ? self : this, function ($) {

    var linkTrackingAttributes = {
        linkName: "data-analytics-link-name", //data-name || data-linkaction
        linkType: "data-linktype",
        contentType: "data-analytics-content-type", //data-linktype
        templateZone: "data-analytics-template-zone", //data-linkpagesection
        moduleName: "data-analytics-module-name" //data-linkcomponentname
    };

    //DOM_LinkTypesElementMapping
    var linkTypeMapping = [{
        //Footer links Contact Numbers 
        "elmSelector": "#block-footer a.phone-LocalPhoneNumber, #block-footer a.phone-TollFreeHotLine",
        "parentSelector": "#block-footer",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        // blog Subscribe button
        "elmSelector": "button:contains('SUBSCRIBE'), button:contains('Subscribe')",
        "parentSelector": "",
        "linkType": "cta",
        "dataName": "subscribe",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Multi Page Nav
        "elmSelector": "#multipage-nav .nav-articles li.nav-item a",
        "parentSelector": "#multipage-nav",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Profile Block
        "elmSelector": ".feature-profile-block-container.module .featured-profile-session-link, .feature-profile-block-container.module .featured-profile-link-arrow",
        "parentSelector": ".feature-profile-block-container.module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Calendar Details: Register Button
        "elmSelector": ".calendar-details.module .calendar-buttons .btn.calendar-register, .calendar-details.module .calendar-buttons a.add-to-calendar-link, .calendar-details.module .get-direction-container a",
        "parentSelector": ".calendar-details.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Job Listing Right Rail: View More Jobs
        "elmSelector": ".job-listing-right-rail.module .view-more-jobs a",
        "parentSelector": ".job-listing-right-rail.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Event Agenda: Save to Calendar: Multiple Day Agenda
        "elmSelector": ".event-agenda.multi-day-event.module .session-details a.session-calendar",
        "parentSelector": ".event-agenda.multi-day-event.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Event Agenda: Save to Calendar: Single Day Agenda
        "elmSelector": ".event-agenda.single-day-event.for-single-event.module .session-details a.session-calendar",
        "parentSelector": ".single-day-event.for-single-event.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Video cards and players (Multi-video)
        "elmSelector": ".video-player-module .video-playlist .playlist-item",
        "parentSelector": ".video-player-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Expertise Heroes: Case Study
        "elmSelector": ".hero-carousel-wrapper .expertise-hero-content .case-study-block .expertise-hero-related-tag-container a.topic-link",
        "parentSelector": ".hero-carousel-wrapper .expertise-hero-content .case-study-block",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Social Feeds: View on Instagram
        "elmSelector": ".social-feed-module.social-feed-ig.module .view-on-link a",
        "parentSelector": ".social-feed-module.social-feed-ig.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Social Feeds: Twitter Feed - Retweet Button
        "elmSelector": ".social-feed-module.module .retweet .btn.twitter-btn.corporate-regular",
        "parentSelector": ".social-feed-module.module",
        "linkType": "share intent",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Social Feeds: Twitter Feed - Twitter Handle
        "elmSelector": ".social-feed-module.module a.cta",
        "parentSelector": ".social-feed-module.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Share Tools: Border Below/Above and Social Media Icon
        "elmSelector": ".share-tools.module .share-icons-container .social-likes div[role^='link']",
        "parentSelector": ".share-tools.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Share Module vertical
        "elmSelector": ".vertical.share-tools .share-icons-container .social-likes div[role^='link'] ",
        "parentSelector": ".vertical.share-tools",
        "linkType": "share intent",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Share Module horizontal
        "elmSelector": ".width.share-tools .share-icons-container .social-likes div[role^='link'] ",
        "parentSelector": ".width.share-tools",
        "linkType": "share intent",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Share Tools: Social Media Icon Print
        "elmSelector": ".share-tools.module .share-icons-container div[role^='link'].print",
        "parentSelector": ".share-tools.module",
        "linkType": "engagement",
        "dataName": "print",
        "dataRel": "",
        "isInternal": ""
    }, {

        //Social Feeds: View on Twitter
        "elmSelector": ".social-feed-module.social-feed-twitter .view-on-link a",
        "parentSelector": ".social-feed-module.social-feed-twitter",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Icon bar section: Social icon - twitter, linkedin
        "elmSelector": ".icon-bar-section .social-icon .social-icon-trigger",
        "parentSelector": ".icon-bar-section",
        "linkType": "share intent",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Share: tv-social
        "elmSelector": ".tv-share .tv-share__icons .tv-social a",
        "parentSelector": ".richtext",
        "linkType": "share intent",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Anchor Links
        "elmSelector": ".jumplink .anchor-link",
        "parentSelector": ".jumplink",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".icon-pause, .icon-play",
        "parentSelector": "li",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".menu-btn",
        "parentSelector": "li",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "a#sign-in-link",
        "parentSelector": "li",
        "linkType": "sign in",
        "dataName": "asset",
        "dataRel": "productGuid",
        "isInternal": ""
    }, {
        "elmSelector": "a.color-primary.ui-link[data-rel][data-name]",
        "parentSelector": "div#Tab-LatestJobs.tab-pane",
        "linkType": "latest jobs",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".footer-textlink a, #disclaimer-cookiestatement a",
        "parentSelector": "#block-footer",
        "linkType": "footer",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".track-careers-register-link",
        "parentSelector": ".sign-in-register-module",
        "linkType": "careers registration",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "span.acn-icon-for-login.icon-linkedin",
        "parentSelector": "div.input-group.linkedin-signin ",
        "linkType": "sign in",
        "dataName": "asset",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#refine-filter-by-city",
        "parentSelector": "#filter-container",
        "linkType": "careers job search",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#refine-filter-by-skill",
        "parentSelector": "#filter-container",
        "linkType": "careers job search",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "a.cta",
        "parentSelector": "div.people-gallery.packery div[class*='mop']",
        "linkType": "employee profile",
        "dataName": "asset",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "span.acn-icon.acn-icon-for-login",
        "parentSelector": "span.social-media-signin-section",
        "linkType": "exit",
        "dataName": "asset",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "a.disclaimer-close-btn.close",
        "parentSelector": "div.cookie-nav",
        "linkType": "call to action",
        "dataName": "asset",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "input#update-subscription",
        "parentSelector": "div.manage-alert.profile-subscriptions",
        "linkType": "engagement",
        "dataName": "update",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "a#btnMainMenu.menu-btn span",
        "parentSelector": "nav#header-topnav.navbar ul#rightTopSection li",
        "linkType": "nav/paginate",
        "dataName": "asset",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#DownloadModule a",
        "parentSelector": "#DownloadModule",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".list-group-item[href]",
        "parentSelector": "#main-menu",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#scroll-button",
        "parentSelector": "",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": "div.btn.convertible.btn-cta",
        "parentSelector": "",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "#find-jobs-form button",
        "parentSelector": ".component.find-job-module",
        "linkType": "careers job search",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "#ADFSLoginPage input[type='submit']",
        "parentSelector": "",
        "linkType": "sign in/out",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "button[onclick*='findAJob']",
        "parentSelector": "form",
        "linkType": "careers job search",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": ".IN-widget a",
        "parentSelector": "#paddingbox",
        "linkType": "linkedin match",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#smartbyte-linkedinmatch",
        "parentSelector": "",
        "linkType": "linkedin match",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": ".jobfeeds.tile .view-all-link",
        "parentSelector": "",
        "linkType": "view all",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "div.footer-textlink span.country-language-trigger",
        "parentSelector": "div.footer-textlink span.country-language-trigger",
        "linkType": "footer",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": "div.btnviewgallery.bg-color-primary.ucase",
        "parentSelector": "div.btnviewgallery.bg-color-primary.ucase",
        "linkType": "image gallery",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": "a.btnclose-gallery",
        "parentSelector": "a.btnclose-gallery",
        "linkType": "x|image gallery",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": "div#subs-main-modal",
        "parentSelector": "div#subs-main-modal",
        "linkType": "unsubscribe email",
        "dataName": "",
        "dataRel": "",
        "isInternal": "false"
    }, {
        "elmSelector": "button.btn.btn-primary.recommended-jobs",
        "parentSelector": "div.job-container-footer",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "div.job-arrow a.no-underline.icon-arrowright2arrow-right2.color-full-black",
        "parentSelector": "div.component.career-recommended-jobs",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": "h2.subheader1.color-full-black span a",
        "parentSelector": "div.component.career-recommended-jobs",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": "true"
    }, {
        "elmSelector": ".icon-chevron_thin",
        "parentSelector": "#video-accordion .container-claster",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".close-video-accordion",
        "parentSelector": "#video-accordion .container-claster",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.component.richtext div.card-carousel-bottom-richtext",
        "parentSelector": "#block-by-the-numbers",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".icon-chevronthin.icon-chevron_thin.color-white",
        "parentSelector": "#block-how-we-lead",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div#navigation-menu div.nav-submenu-label",
        "parentSelector": "#block-header",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.nav-item-links li.first-secondary-item a",
        "parentSelector": "#block-header",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "ul.no-l3 li.secondary-item a",
        "parentSelector": "#block-header",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.nav-item-links li.tertiary-item a",
        "parentSelector": "#block-header",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.nav-content div.nav-submenu-label-L3",
        "parentSelector": "#block-header",
        "linkType": "nav/paginate",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.calendar-details div.description-container a",
        "parentSelector": "div.calendar-details div.description-container",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.link-cards div.dynamic-card-link a",
        "parentSelector": "div.link-cards",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.icon-card-text a.icon-info-cta",
        "parentSelector": "div.icon-card-text",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.video-player-module div.modal-play",
        "parentSelector": "div.video-player-module",
        "linkType": "engagement",
        "dataName": "Video Play",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "div.video-player-module div.playlist-transcript a",
        "parentSelector": "div.video-player-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {//Featured Insight - title
        "elmSelector": ".featured-insight.module .module-title-wrapper a",
        "parentSelector": ".featured-insight.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Insight  - CTA
        "elmSelector": ".featured-insight.module .description-container .cta-container a",
        "parentSelector": ".featured-insight.module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Related Leadership Block
        "elmSelector": ".related-leadership .cta-button-container a",
        "parentSelector": ".related-leadership.flex-container",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Topic Block
        "elmSelector": ".topic-module .topic-container .topic-color-bar .cta-container a",
        "parentSelector": ".topic-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Theme Narrative Block
        "elmSelector": ".theme-narrative-utility-container.module .theme-narrative-download-container .theme-narative-download a",
        "parentSelector": ".theme-narrative-utility-container.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Split Content Block
        "elmSelector": ".split-content-block-container.module .split-content-container .split-content-bar .split-image-text .content .split-link-arrow a",
        "parentSelector": ".split-content-block-container.module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".split-content-block-container.module .split-content-container .split-content-bar .split-image-text-link .content .split-link-arrow a",
        "parentSelector": ".split-content-block-container.module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Image
        "elmSelector": ".image-module.module .full-16x9 a",
        "parentSelector": ".image-module.module",
        "linkType": "image",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".image-module.module .full-3x1 a",
        "parentSelector": ".image-module.module",
        "linkType": "image",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Alliance and Partners
        "elmSelector": ".section-pagezone-cta a",
        "parentSelector": ".section-pagezone-cta",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Insights Heroes feature - article breadcrumb
        "elmSelector": ".ui-container.hero-module .carousel-inner .hero-breadcrumblink a",
        "parentSelector": ".ui-container.hero-module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Insights Heroes feature - topic
        "elmSelector": ".ui-container.hero-module .carousel-inner a.topic-link",
        "parentSelector": ".ui-container.hero-module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Business Unit, Innov, LowerLevel
        "elmSelector": ".ui-container.hero-module .about-hero-wrapper .about-hero-parent-bcrumb a",
        "parentSelector": ".ui-container.hero-module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Progressive Display
        "elmSelector": ".progressive-display.view-all-cards",
        "parentSelector": ".progressive-display.view-all-cards",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".progressive-display.view-less-cards",
        "parentSelector": ".progressive-display.view-less-cards",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Video Cards
        "elmSelector": ".video-player-module .video-modal .thumbnail-container .modal-play",
        "parentSelector": ".video-player-module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Audio - progress and background + progress
        "elmSelector": ".audio-module .audio-player-container .audioplayer .playPause",
        "parentSelector": ".audio-module",
        "linkType": "engagement",
        "dataName": "audio play",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Audio = sticky audio
        "elmSelector": ".audio-module .audio-player-container.audio-sticky-player .sticky-audioplayer .sticky-playPause",
        "parentSelector": ".audio-module",
        "linkType": "engagement",
        "dataName": "audio play",
        "dataRel": "",
        "isInternal": ""
    }, {
        //GlobalHeader logo
        "elmSelector": "nav#header-topnav div.primary-nav div.acn-logo-container a.acn-logo",
        "parentSelector": "nav#header-topnav div.primary-nav",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Global Header Search
        "elmSelector": "nav#header-topnav div.utility-nav div.search-trigger",
        "parentSelector": "nav#header-topnav div.utility-nav",
        "linkType": "search activity",
        "dataName": "initiated search - click/tap",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Global Header Sign In
        "elmSelector": "nav#header-topnav div.utility-nav div.signin-container",
        "parentSelector": "nav#header-topnav div.utility-nav",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Global Header country list
        "elmSelector": "nav#header-topnav div.utility-nav div.country-form div#location-recommendation a",
        "parentSelector": "div.country-form div#location-recommendation",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Global header Profile Sign Out Link
        "elmSelector": "div.signin-container div.signin-links a#signout",
        "parentSelector": "div.signin-container div.signin-links",
        "linkType": "sign out",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Global header Profile Links
        "elmSelector": "div.signin-container div.signin-links a:not(#signout)",
        "parentSelector": "div.signin-container div.signin-links",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Footer footer-links, legal-links
        "elmSelector": "div.footer-links a,  div.legal-links a",
        "parentSelector": "footer#footer-block div.footer-links",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Footer legal-statements
        "elmSelector": "footer#footer-block div.legal-statements a",
        "parentSelector": "footer#footer-block div.legal-statements",
        "linkType": "footer",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Legacy Footer 
        "elmSelector": "div#block-footer div.social a.acn-spr",
        "parentSelector": "div#block-footer div.social",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //downloads base module
        "elmSelector": "div.downloads-base-container > a, div.downloads-info a",
        "parentSelector": "div.downloads-base-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //accordion
        "elmSelector": "div.reinvent-accordion-parent div.reinvent-accordion-module a.reinvent-accordion-link",
        "parentSelector": "div.reinvent-accordion-parent div.reinvent-accordion-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //ribbon block
        "elmSelector": "div.themes-ribbon a, div.event-ribbon a, div.join-ribbon a, div.article-ribbon div.container-left a ",
        "parentSelector": "div.block-ribbon",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Mixed Media Block Full Image Card
        "elmSelector": "article.mixed-media-block div.full-image-container a.cta-button",
        "parentSelector": "article.mixed-media-block div.full-image-container",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Mixed Media Block Quote Video Transcript
        "elmSelector": "div.video-player-module div.video-content.align-right a",
        "parentSelector": "div.video-player-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Mixed Media Block 3 Media Block Video
        "elmSelector": "div.media-items-block div.media-item div.modal-play.video-item",
        "parentSelector": "div.media-items-block div.media-item",
        "linkType": "engagement",
        "dataName": "video modal",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Event Hero - breadcrumb, hashtag
        "elmSelector": "div.event-hero-bcrumb-wrapper div.event-hero-bcrumb a, div.hero-details-wrapper a.event-hashtag",
        "parentSelector": "div.event-hero-wrapper",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Homepage A,Hompage B, About Landing Page
        "elmSelector": "div.homepage-a a.cta-button div.btn-primary, div.homepage-b a.cta-button, div.about-landing-page a.cta-button div.btn-primary ",
        "parentSelector": "div#landing-page-hero",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Insight Card Module 8 card variant
        "elmSelector": "div.insight-card-block div.cta-serp-container a",
        "parentSelector": "div.insight-card-block",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Newsletter Intruder
        "elmSelector": ".module.newsletter-intruder-module .newsletter-intruder-cta a ",
        "parentSelector": ".module.newsletter-intruder-module",
        "linkType": "",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Tabs 
        "elmSelector": ".tab-container li",
        "parentSelector": ".tab-container",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Author Profile Module Profile View: Author Name
        "elmSelector": ".module.author-profile .author-information .module-title a",
        "parentSelector": ".module.author-profile",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Author Profile Module List View: Author Name
        "elmSelector": ".module.many-author-profile .many-author-container .eyebrow-title a",
        "parentSelector": ".module.many-author-profile",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        // SignInDetailsModule
        "elmSelector": ".sign-in-module .input-group.social-single #linkedinButton",
        "parentSelector": ".sign-in-module",
        "linkType": "linkedin",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //register Module Captcha icons
        "elmSelector": ".stay-connected-module .privacy-policy .form-group #captchaimg .BDC_CaptchaIconsDiv a",
        "parentSelector": ".stay-connected-module",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //register Module Captcha Image
        "elmSelector": ".stay-connected-module .privacy-policy .form-group #captchaimg .BDC_CaptchaImageDiv a",
        "parentSelector": ".stay-connected-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Confirmation-thankyou Module Captcha Image
        "elmSelector": " #captchaimg .BDC_CaptchaImageDiv a",
        "parentSelector": ".registration-thankyou-confirmation-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Confirmation-thankyou Module Captcha Image
        "elmSelector": " #captchaimg .BDC_CaptchaIconsDiv a",
        "parentSelector": ".registration-thankyou-confirmation-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Comments Module Captcha Image
        "elmSelector": ".comments-module .post-a-comment-form .privacy-policy .BDC_CaptchaDiv .BDC_CaptchaImageDiv a",
        "parentSelector": ".comments-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Comments Module Captcha Reload Icon
        "elmSelector": ".comments-module .post-a-comment-form .privacy-policy .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a.BDC_ReloadLink",
        "parentSelector": ".comments-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Comments Module Captcha Sound Link Icon
        "elmSelector": ".comments-module .post-a-comment-form .privacy-policy .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a.BDC_SoundLink",
        "parentSelector": ".comments-module",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Section Module Pagination
        "elmSelector": ".featured-section-module-carousel ol.carousel-indicators li",
        "parentSelector": ".featured-section-module-carousel",
        "linkType": "nav/paginate",
        "dataName": "nav/paginate",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Article CTA
        "elmSelector": ".module-article.featured-article-item a",
        "parentSelector": ".module-article.featured-article-item",
        "linkType": "featuredarticlemodule",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Jobseekers Module captcha image
        "elmSelector": "#jSeekCaptcha #captchaimg .BDC_CaptchaImageDiv a",
        "parentSelector": "#jSeekCaptcha",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Jobseekers Module change captcha
        "elmSelector": "#jSeekCaptcha #captchaimg .BDC_CaptchaIconsDiv .BDC_ReloadLink",
        "parentSelector": "#jSeekCaptcha",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Jobseekers Module speak captcha
        "elmSelector": "#jSeekCaptcha #captchaimg .BDC_CaptchaIconsDiv .BDC_SoundLink",
        "parentSelector": "#jSeekCaptcha",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Section Module Article Category
        "elmSelector": ".featured-section-module-carousel .featured-section-module a.articleCategoryLink",
        "parentSelector": ".featured-section-module-carousel",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Featured Section Module Article Title
        "elmSelector": ".featured-section-module-carousel .featured-section-module a.article-title",
        "parentSelector": ".featured-section-module-carousel",
        "linkType": "headline",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Dynamic Featured Article Module Article Category
        "elmSelector": ".packery-container.clamp .packery-item .module-article .articlecategory a.articleCategory",
        "parentSelector": ".packery-container.clamp",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Dynamic Featured Article Module Article Title
        "elmSelector": ".packery-container.clamp .packery-item .module-article a.articleHeadline",
        "parentSelector": ".packery-container.clamp",
        "linkType": "headline",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Remove Profile Module captcha image
        "elmSelector": ".profile-remove .BDC_CaptchaDiv .BDC_CaptchaImageDiv a",
        "parentSelector": ".profile-remove",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Remove Profile Module change captcha and speak captcha
        "elmSelector": ".profile-remove .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a",
        "parentSelector": ".profile-remove",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Change Email Module captcha image
        "elmSelector": "#ChangeEmailBodyModule #captchaimg .BDC_CaptchaDiv .BDC_CaptchaImageDiv a",
        "parentSelector": "#ChangeEmailBodyModule",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Change Email Module change captcha and speak captcha
        "elmSelector": "#ChangeEmailBodyModule #captchaimg .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a",
        "parentSelector": "#ChangeEmailBodyModule",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Submit Module Captcha Image, Refresh, and Sound
        "elmSelector": ".panel-body .form-horizontal.acn-form .form-group #captchaimg .BDC_CaptchaDiv a",
        "parentSelector": ".panel-body",
        "linkType": "cta",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Forms module feedback message
        "elmSelector": ".customform ~ #sectionSuccess a",
        "parentSelector": "#sectionSuccess",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Careers event registration form module captcha
        "elmSelector": ".customform .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a",
        "parentSelector": ".customform",
        "linkType": "form",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        //Forgot Password form module captcha
        "elmSelector": ".forgotpassword .BDC_CaptchaDiv .BDC_CaptchaIconsDiv a",
        "parentSelector": ".forgotpassword",
        "linkType": "form",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".resetpassword ~ #sectionSuccess a",
        "parentSelector": "#sectionSuccess",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#networkError a",
        "parentSelector": "#networkError",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": "#expired-disabled-link a",
        "parentSelector": "#expired-disabled-link",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }, {
        "elmSelector": ".forgotpassword ~ #sectionSuccess a",
        "parentSelector": "#sectionSuccess",
        "linkType": "engagement",
        "dataName": "",
        "dataRel": "",
        "isInternal": ""
    }];

    //LinkAnalysisFilter_LinkPageSectionLocation
    var templateZone = [{
        LocationSelector: "nav#header-topnav",
        Name: "navigation header",
        Location: "global header",
        LocationMobile: ""
    }, {
        LocationSelector: "div.hero-header h2.page-identifier",
        Name: "hero header strategy links",
        Location: "top nav",
        LocationMobile: ""
    }, {
        LocationSelector: "div#myModal.modal.search-page",
        Name: "search modal",
        Location: "global header",
        LocationMobile: ""
    }, {
        LocationSelector: "div#countryLanguageSelectorModal.modal.location-selector",
        Name: "country language selector modal",
        Location: "global header",
        LocationMobile: "side nav"
    }, {
        LocationSelector: "div#ui-wrapper div.custom-banner",
        Name: "landing page custom banner",
        Location: "top nav",
        LocationMobile: ""
    }, {
        LocationSelector: "div#block-hero",
        Name: "top page locator",
        Location: "marquee",
        LocationMobile: ""
    }, {
        LocationSelector: "div#block-footer.ui-container",
        Name: "footer block",
        Location: "footer",
        LocationMobile: "footer"
    }, {
        LocationSelector: "footer#footer-block.ui-container",
        Name: "reinvent footer block",
        Location: "footer",
        LocationMobile: "footer"
    }, {
        LocationSelector: "div#main-menu.sidr",
        Name: "side menu navigation",
        Location: "side nav",
        LocationMobile: ""
    }, {
        LocationSelector: "span#scroll-button.icon-circle",
        Name: "scroll swipe",
        Location: "page nav",
        LocationMobile: ""
    }, {
        LocationSelector: "div.component.career-recommended-jobs h2 span a",
        Name: "jobs",
        Location: "jobs",
        LocationMobile: ""
    }, {
        LocationSelector: "div#block-latest-jobs",
        Name: "recommended jobs",
        Location: "recommended jobs",
        LocationMobile: ""
    }, {
        LocationSelector: "div.secondary-nav-item",
        Name: "primary menu sublinks",
        Location: "secondary nav",
        LocationMobile: ""
    }, {
        LocationSelector: "div#hero-carousel, div#about-hero, div#bio-hero, div.event-hero-wrapper,div#landing-page-hero",
        Name: "base heroes",
        Location: "hero",
        LocationMobile: ""
    }, {
        LocationSelector: "div.block-ribbon.ui-container",
        Name: "block ribbon",
        Location: "block-ribbon",
        LocationMobile: ""
    }, {
        LocationSelector: "div.quick-access-tab",
        Name: "quick access tab",
        Location: "quick access tab",
        LocationMobile: ""
    }, {
        LocationSelector: ".jumplink",
        Name: "jumplink",
        Location: "anchor links",
        LocationMobile: ""
    }, {
        LocationSelector: "div.optanon-alert-box-button-middle",
        Name: "Onetrust Link Analysis - Cookie Settings button",
        Location: "consent manager",
        LocationMobile: ""
    }, {
        LocationSelector: "div.optanon-alert-box-corner-close",
        Name: "Onetrust Link Analysis - Close Cookie Settings",
        Location: "consent manager",
        LocationMobile: ""
    }, {
        LocationSelector: "div.optanon-white-button-middle",
        Name: "Onetrust Link Analysis - Save and Allow Cookie Settings",
        Location: "consent manager",
        LocationMobile: ""
    }, {
        LocationSelector: "div#optanon-popup-top",
        Name: "Onetrust Link Analysis - Close Pop-Up Cookie Setting",
        Location: "consent manager",
        LocationMobile: ""
    }, {
        LocationSelector: "div[id^='block-'].ui-container",
        Name: "page blocks",
        Location: "customblock",
        LocationMobile: ""
    }, {
        LocationSelector: "div.sticky-access-bar",
        Name: "careers sticky access",
        Location: "careers sticky access",
        LocationMobile: ""
    }, {
        LocationSelector: ".module.author-profile, .module.many-author-profile",
        Name: "Author Profile",
        Location: "right rail",
        LocationMobile: ""

    }, {
        LocationSelector: "div.block-ribbon",
        Name: "ribbon block module",
        Location: "ribbon",
        LocationMobile: ""
    }, {
        LocationSelector: "div#eventSmartByte",
        Name: "event calendar smart byte",
        Location: "event calendar smart byte",
        LocationMobile: ""
    }, {
        LocationSelector: "div#EventsLinkModule",
        Name: "event link",
        Location: "event link",
        LocationMobile: ""
    }];

    //LinkAnalysisFilter_OverlayLinkPageSection
    var templateZoneModals = [{
        "Name": "Country Selector",
        "ParentSelector": "div#block-footer",
        "OverlaySelector": "div#countryLanguageSelectorModal",
        "OverrideSelector": ""
    }, {
        "Name": "City Modal",
        "ParentSelector": "div.job-preference .form-group.has-feedback",
        "OverlaySelector": "div#cities.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Industry Modal",
        "ParentSelector": "div.job-preference .form-group",
        "OverlaySelector": "div#industries.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Author Bio",
        "ParentSelector": "div.item.blogpost.active",
        "OverlaySelector": "div.modal.fade#main-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Job Search:Refined by City",
        "ParentSelector": "div.panel-body #refine-filter-by-city",
        "OverlaySelector": "div#cities.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Job Search:Refined by Skill",
        "ParentSelector": "div.panel-body #refine-filter-by-skill",
        "OverlaySelector": "div#industries.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Job Search:Refined by Area of Business",
        "ParentSelector": "div.panel-body #refine-filter-by-area-of-business",
        "OverlaySelector": "div#area-of-business.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Job Search:Refined by Area of Expertise",
        "ParentSelector": "div.panel-body #refine-filter-by-area-of-expertise",
        "OverlaySelector": "div#area-of-expertise.modal.fade.row",
        "OverrideSelector": ""
    }, {
        "Name": "Email Subscription",
        "ParentSelector": "input#update-subscription",
        "OverlaySelector": "div#subs-main-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Video Overlay\t",
        "ParentSelector": "div[id^=hero-slide].item.video-back",
        "OverlaySelector": "div[id^=hero-slide].item.video-back p.popupvid-x-button-container",
        "OverrideSelector": ".popupvid-x-button-container"
    }, {
        "Name": "Image Gallery",
        "ParentSelector": "div.btnviewgallery.bg-color-primary.ucase",
        "OverlaySelector": "div.modal.galleryModal",
        "OverrideSelector": ""
    }, {
        "Name": "Image Gallery - Mobile",
        "ParentSelector": "div.image-gallery-folder",
        "OverlaySelector": "div.modal.galleryModal",
        "OverrideSelector": ""
    }, {
        "Name": "Download Overlay",
        "ParentSelector": "div#DownloadModule",
        "OverlaySelector": "div#download-module-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Unsubscribe Email",
        "ParentSelector": "div.block-title",
        "OverlaySelector": "div#subs-main-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Accenture in your Day",
        "ParentSelector": "div.module-blog-authors.single.component .carousel.slide .item.active",
        "OverlaySelector": "div.modal.fade#main-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Careers-Email",
        "ParentSelector": "div#SectionModule_Investor div.panel-body section.contact-info.contact-card div.contact-info-item div.contact-info-item-envelope",
        "OverlaySelector": "div.modal#contact-main-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Type to Search Block",
        "ParentSelector": "div.featured-section-module-carousel div.featured-section-viewall",
        "OverlaySelector": "div#myModal.modal.search-page",
        "OverrideSelector": ""
    }, {
        "Name": "Not Found",
        "ParentSelector": "div.page-not-found .search-trigger",
        "OverlaySelector": "div#myModal.modal.search-page",
        "OverrideSelector": ""
    }, {
        "Name": "Authors - View All",
        "ParentSelector": "a.ctaViewAll",
        "OverlaySelector": "div.modal-content",
        "OverrideSelector": ""
    }, {
        "Name": "Post Comment Deletion",
        "ParentSelector": "div#postacomment",
        "OverlaySelector": "div.comment-div",
        "OverrideSelector": ""
    }, {
        "Name": "Youtube Video Overlay",
        "ParentSelector": "span.employeename a table.connect",
        "OverlaySelector": "div#cboxWrapper div#cboxContent",
        "OverrideSelector": ""
    }, {
        "Name": "Share Popover",
        "ParentSelector": "div.popover.fade.bottom.in",
        "OverlaySelector": ".popover-content .social-likes.social-likes_vertical",
        "OverrideSelector": ""
    }, {
        "Name": "Reinvent - BioModal Module",
        "ParentSelector": "a.bio-modal-trigger",
        "OverlaySelector": "div.bio-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Reinvent - Text Modal",
        "ParentSelector": "a.text-modal-link",
        "OverlaySelector": "div#text-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Reinvent - Audio Modal",
        "ParentSelector": "a.audio-modal-trigger, div.audio-modal-trigger",
        "OverlaySelector": "div.modal.media-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Reinvent - Video Modal",
        "ParentSelector": "div.modal-play",
        "OverlaySelector": "div.modal.media-modal",
        "OverrideSelector": ""
    }, {
        "Name": "Reinvent - Slideshare Modal",
        "ParentSelector": "a.slideshare-modal-trigger, div.slideshare-modal-trigger",
        "OverlaySelector": "div.modal.media-modal",
        "OverrideSelector": ""
    }];

    //LinkAnalysisFilter_LinkComponents
    var moduleNames = [{
        "LinkComponentName": "Case Study Hero Block",
        "ParentComponentSelector": ".hero-carousel-wrapper .expertise-hero-content .case-study-block",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "case-study-hero",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Marquee Component",
        "ParentComponentSelector": "div[id^='hero-slide']",
        "ComponentTitleSelector": "div.page-title",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Marquee Component - Find Button",
        "ParentComponentSelector": "div[id^='hero-slide']",
        "ComponentTitleSelector": "button#btn-find",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Dynamic Featured Section Component",
        "ParentComponentSelector": "div.component.packery-item .module-article",
        "ComponentTitleSelector": "h3.articlecategory",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Featured Section Component",
        "ParentComponentSelector": "div.featured-section-module.module-article.component",
        "ComponentTitleSelector": "h3",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Navigation arrow",
        "ParentComponentSelector": "div.job-arrow",
        "ComponentTitleSelector": "a",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Carousel Components",
        "ParentComponentSelector": "div.component .carousel-inner div.module-article.item.active",
        "ComponentTitleSelector": "h3",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "About Accenture - How We Lead Components",
        "ParentComponentSelector": ".hwl-persons-item__card-closed",
        "ComponentTitleSelector": ".hwl-caption span:first-of-type",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "About Accenture - How We Lead Components - Expanded",
        "ParentComponentSelector": ".col-xs-12.hwl-persons-item__card-expanded",
        "ComponentTitleSelector": ".bio-header p span.name",
        "ComponentTitleOverride": "",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Author Profile Module",
        "ParentComponentSelector": ".module.author-profile",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "author",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Author Profile Module - Many",
        "ParentComponentSelector": "article.module.many-author-profile",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "author",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Quick Summary Module",
        "ParentComponentSelector": "article.quick-summary-container",
        "ComponentTitleSelector": "a.text-underline",
        "ComponentTitleOverride": "quick summary",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Follow Us Module",
        "ParentComponentSelector": "div.block-content div.follow-us-module",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "connect/social",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Follow Us Module Ribbon",
        "ParentComponentSelector": "div.follow-us-ribbon div.follow-us-module",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "ribbon",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Dynamic Content Cards Image Block",
        "ParentComponentSelector": "div.dynamic-content-card-image-block div.related-content-block",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "related content",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Reinvent - Calendar Details Link on Description",
        "ParentComponentSelector": "div.calendar-details div.description-container a",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "calendar-description",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "GDPR  Onetrust Link Analysis - Cookie Settings button",
        "ParentComponentSelector": "div.optanon-alert-box-button-middle",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "consent manager",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "GDPR  Onetrust Link Analysis - Close Cookie Settings",
        "ParentComponentSelector": "div.optanon-alert-box-corner-close",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "consent manager",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "GDPR  Onetrust Link Analysis - Save and Allow Cookie Settings",
        "ParentComponentSelector": "div.optanon-white-button-middle",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "consent manager",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "GDPR  Onetrust Link Analysis - Close Pop-Up Cookie Settings",
        "ParentComponentSelector": "div#optanon-popup-top",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "consent manager",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Footer Legal Statements",
        "ParentComponentSelector": "footer#footer-block div.legal-statements a",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "footer",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Interactive Progressive Display Card Text Module",
        "ParentComponentSelector": ".card-text-module-block .progressive-display.view-all-cards, .card-text-module-block .view-less-cards",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "card text module",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Interactive Progressive Display Module",
        "ParentComponentSelector": ".matrix-module-block .progressive-display.view-all-cards, .matrix-module-block .progressive-display.view-less-cards",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "matrix module",
        "NonDescendantOf": ""

    }, {
        "LinkComponentName": "Interactive Progressive Display Card Image Module ",
        "ParentComponentSelector": ".card-image-module-block .progressive-display.view-all-cards, .card-image-module-block .view-less-cards",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "card image module",
        "NonDescendantOf": ""
    },
    //Progressive Display
    {
        "LinkComponentName": "Progressive Display Module",
        "ParentComponentSelector": ".progressive-display.view-all-cards, .view-less-cards",
        "ComponentTitleSelector": "",
        "ComponentTitleOverride": "related services",
        "NonDescendantOf": ""
    }, {
        "LinkComponentName": "Filter Results Button - Meet Our People Block",
        "ParentComponentSelector": ".rlb-filter-btn",
        "ComponentTitleSelector": "button.drop-down-btn",
        "ComponentTitleOverride": "filter",
        "NonDescendantOf": ""
    }];

    var getArticleObjects = function () {
        var baseObj = $('.ui-container .block-content .col-lg-8 .content-module').first();
        var summaryObjList = baseObj.prevAll().children();
        var bodyObjList = baseObj.parent().parent().siblings();
        var bottomObjList = $('.row .block-content .col-lg-8.col-md-8.col-sm-12.col-xs-12').closest('.ui-container').nextAll();
        var rightRailList = $('.ui-container .block-content .col-lg-8').siblings('.col-lg-4');
        var arr = [];
        if (baseObj.length > 0) {
            arr.push({
                Name: "body-" + baseObj[0].classList[0],
                LocationSelector: baseObj.parent().parent(),
                Location: "body"
            });
        }

        if (summaryObjList.length > 0) {
            for (var i = 0; i < summaryObjList.length; i++) {
                var item = {
                    Name: "summary-" + $(summaryObjList[i])[0].classList[0],
                    LocationSelector: $(summaryObjList[i]),
                    Location: "summary"
                };
                arr.push(item);
            }
        }

        if (bodyObjList.length > 0) {
            for (var i = 0; i < bodyObjList.length; i++) {
                var item = {
                    Name: "body-" + $(bodyObjList[i])[0].classList[0],
                    LocationSelector: $(bodyObjList[i]),
                    Location: "body"
                };
                arr.push(item);
            }
        }

        if (bottomObjList.length > 0) {
            for (var i = 0; i < bottomObjList.length; i++) {
                if (!$(bottomObjList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "bottom-" + $(bottomObjList[i])[0].classList[0],
                        LocationSelector: $(bottomObjList[i]),
                        Location: "article bottom"
                    };
                    arr.push(item);
                }
            }
        }

        if (rightRailList.length > 0) {
            for (var i = 0; i < rightRailList.length; i++) {
                if (!$(rightRailList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "right-" + $(rightRailList[i])[0].classList[0],
                        LocationSelector: $(rightRailList[i]),
                        Location: "right rail"
                    };
                    arr.push(item);
                    //override any existing data analytics template zone
                    var children = $(rightRailList[i]).find("[data-analytics-template-zone]");
                    for (var j = 0; j < children.length; j++) {
                        var item = {
                            Name: "right-" + $(children[j])[0].classList[0],
                            LocationSelector: $(children[j]),
                            Location: "right rail"
                        };
                        arr.push(item);
                    }
                }
            }
        }
        return arr;
    };

    var getAIObjects = function () {
        var $bodyList = jQuery('.ui-container.hero-module').nextAll();
        var $bottomObjList = $bodyList.last();
        var cardTextModuleList = $('.ui-container .card-text-module-block');
        var arr = [];

        if ($bodyList.length > 0) {
            for (var i = 0; i < $bodyList.length; i++) {
                var item = {
                    Name: "body-" + jQuery($bodyList[i])[0].classList[0],
                    LocationSelector: jQuery($bodyList[i]),
                    Location: "body"
                };
                arr.push(item);
            }
        }

        if ($bottomObjList.length > 0) {
            for (var j = 0; j < $bottomObjList.length; j++) {
                var bottomItem = {
                    Name: "bottom-" + jQuery($bottomObjList[j])[0].classList[0],
                    LocationSelector: jQuery($bottomObjList[j]),
                    Location: "article bottom"
                };
                arr.push(bottomItem);
            }
        }

        //interactive card text module
        if (cardTextModuleList.length > 0) {
            for (var i = 0; i < cardTextModuleList.length; i++) {
                var location = "article bottom";
                if ($(cardTextModuleList[i]).closest('.ui-container').find('.author-module').length > 0) {
                    location = "body";
                }
                var item = {
                    Name: "body-article-bottom-" + $(cardTextModuleList[i])[0].classList[0],
                    LocationSelector: $(cardTextModuleList[i]),
                    Location: location
                };
                arr.push(item);
            }
        }

        //interactive author module
        var $authorModuleList = $(".author-module .author-article");
        if ($authorModuleList.length > 0) {
            for (var i = 0; i < $authorModuleList.length; i++) {
                var item = {
                    Name: "body-" + jQuery($authorModuleList[i])[0].classList[0],
                    LocationSelector: jQuery($authorModuleList[i]),
                    Location: "body"
                };
                arr.push(item);
            }
        }

        return arr;
    };

    var getCaseStudyObject = function () {
        var capabilityBlock = $('.row .block-content .capability-block').closest('.ui-container');
        var bodyList = $('.ui-container.hero-module').nextAll();
        var rightRailList = $('.ui-container .block-content .col-lg-8').siblings('.col-lg-4');
        var arr = [];
        if (capabilityBlock.length > 0) {
            arr.push({
                Name: "summary-" + capabilityBlock[0].classList[0],
                LocationSelector: capabilityBlock,
                Location: "article bottom"
            })
        }

        var bottomObjList = capabilityBlock.nextAll();
        if (bodyList.length > 0) {
            for (var i = 0; i < bodyList.length; i++) {
                if ($(bodyList[i])[0] == capabilityBlock[0])
                    break;
                if (!$(bodyList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "summary-" + $(bodyList[i])[0].classList[0],
                        LocationSelector: $(bodyList[i]),
                        Location: "body"
                    };
                    arr.push(item);
                }
            }
        }
        if (bottomObjList.length > 0) {
            for (var i = 0; i < bottomObjList.length; i++) {
                if (!$(bottomObjList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "summary-" + $(bottomObjList[i])[0].classList[0],
                        LocationSelector: $(bottomObjList[i]),
                        Location: "article bottom"
                    };
                    arr.push(item);
                }
            }
        }
        if (rightRailList.length > 0) {
            for (var i = 0; i < rightRailList.length; i++) {
                if (!$(rightRailList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "right-" + $(rightRailList[i])[0].classList[0],
                        LocationSelector: $(rightRailList[i]),
                        Location: "right rail"
                    };
                    arr.push(item);
                    //override any existing data analytics template zone
                    var children = $(rightRailList[i]).find("[data-analytics-template-zone]");
                    for (var j = 0; j < children.length; j++) {
                        var item = {
                            Name: "right-" + $(children[j])[0].classList[0],
                            LocationSelector: $(children[j]),
                            Location: "right rail"
                        };
                        arr.push(item);
                    }
                }
            }

        }
        return arr;
    };
    var getBlogPostPageObject = function () {
        var baseObjBlogPostPage = $('.ui-container .block-content .col-lg-8 .blog-content-module').first();
        var summaryObjListBlogPostPage = baseObjBlogPostPage.parent().parent().find(".quick-summary-container");
        var bodyObjListBlogPostPage = baseObjBlogPostPage.parent().parent().parent().siblings();
        var bottomObjList = $('.row .block-content .col-lg-8.col-md-8.col-sm-12.col-xs-12').closest('.ui-container').nextAll();
        var rightRailList = $('.ui-container .block-content .col-lg-8').siblings('.col-lg-4');
        var arr = [];

        if (baseObjBlogPostPage.length > 0) {
            arr.push({
                Name: "body-" + baseObjBlogPostPage[0].classList[0],
                LocationSelector: baseObjBlogPostPage.parent().parent().parent(),
                Location: "body"
            });
        }
        if (summaryObjListBlogPostPage.length == 0) {
            summaryObjListBlogPostPage = baseObjBlogPostPage.parent().parent().find(".share-tools.module");
        }
        if (summaryObjListBlogPostPage.length > 0) {
            for (var i = 0; i < summaryObjListBlogPostPage.length; i++) {
                var item = {
                    Name: "summary-" + $(summaryObjListBlogPostPage[i])[0].classList[0],
                    LocationSelector: $(summaryObjListBlogPostPage[i]),
                    Location: "summary"
                };
                arr.push(item);
            }
        }

        if (bodyObjListBlogPostPage.length > 0) {
            for (var i = 0; i < bodyObjListBlogPostPage.length; i++) {
                var item = {
                    Name: "body-" + $(bodyObjListBlogPostPage[i])[0].classList[0],
                    LocationSelector: $(bodyObjListBlogPostPage[i]),
                    Location: "body"
                };
                arr.push(item);
            }
        }
        if (bottomObjList.length > 0) {
            for (var i = 0; i < bottomObjList.length; i++) {
                if (!$(bottomObjList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "bottom-" + $(bottomObjList[i])[0].classList[0],
                        LocationSelector: $(bottomObjList[i]),
                        Location: "article bottom"
                    };
                    arr.push(item);
                }
            }
        }

        if (rightRailList.length > 0) {
            for (var i = 0; i < rightRailList.length; i++) {
                if (!$(rightRailList[i]).hasClass('block-ribbon')) {
                    var item = {
                        Name: "right-" + $(rightRailList[i])[0].classList[0],
                        LocationSelector: $(rightRailList[i]),
                        Location: "right rail"
                    };
                    arr.push(item);
                    //override any existing data analytics template zone
                    var children = $(rightRailList[i]).find("[data-analytics-template-zone]");
                    for (var j = 0; j < children.length; j++) {
                        var item = {
                            Name: "right-" + $(children[j])[0].classList[0],
                            LocationSelector: $(children[j]),
                            Location: "right rail"
                        };
                        arr.push(item);
                    }
                }
            }
        }
        return arr;
    };
    var branchTemplateZone = [
        //standard article
        {
            BranchTemplate: "{20401DC1-4890-404F-AB10-895A5731FE3E}",
            TemplateZone: getArticleObjects()
        },
        //FAI
        {
            BranchTemplate: "{2323DED5-44D9-4D00-9460-19762A3A6DCA}",
            TemplateZone: getArticleObjects()
        },
        //FAO
        {
            BranchTemplate: "{6F20947A-9657-484C-8151-9D1C2B447FA4}",
            TemplateZone: getArticleObjects()
        },
        //TLA
        {
            BranchTemplate: "{ED78BFDD-16FC-4D31-8CD8-4EEEBBB2C414}",
            TemplateZone: getAIObjects()
        },
        //WorkDetail
        {
            BranchTemplate: "{04EFC50A-C891-46FF-A79F-E187649A3D00}",
            TemplateZone: getAIObjects()
        },
        //CaseStudy
        {
            BranchTemplate: "{E913586E-1024-4333-8B59-7456038F7BD8}",
            TemplateZone: getCaseStudyObject()
        },
        //BlogPostPage
        {
            BranchTemplate: "{AC2C368C-9364-4145-BA5B-BDAB581BD783}",
            TemplateZone: getBlogPostPageObject()
        }
    ];

    //list of richText like modules
    var richTextLinks = [{
        "elmSelector": ".richtext a"
    }, {
        "elmSelector": "#DownloadModule a"
    }, {
        "elmSelector": ".pull-quote-margin a:not(.social-likes__button.social-likes__button_single)"
    }, {
        "elmSelector": ".carousel.slide.social-media a"
    }, {
        "elmSelector": ".videoWrapper iframe"
    }, {
        "elmSelector": ".btn-stock-container button.btn-stock-widget"
    }, {
        "elmSelector": "#stock-widget a"
    }, {
        "elmSelector": ".form-group p a"
    }, {
        "elmSelector": ".module-body #textContent a"
    }, {
        "elmSelector": "#block-blogpost .component p a"
    }, {
        "elmSelector": ".richtext button"
    }, {
        "elmSelector": "#blogpost-module .blogpost-content a"
    }, {
        "elmSelector": "div.page-not-found .navigation-links a"
    }, {
        "elmSelector": ".accordionModule a"
    }, {
        "elmSelector": "#collapse-accordionmodule-accordioncontentmodule a"
    }, {
        "elmSelector": ".adjacent-tiles a"
    }, {
        "elmSelector": ".privacy-policy a"
    }, {
        "elmSelector": ".sign-in-register-module a"
    }, {
        "elmSelector": ".profile-remove a"
    }, {
        "elmSelector": ".form-section a"
    }, {
        "elmSelector": ".module-article .article-content a"
    }, {
        "elmSelector": ".cardShare li"
    }, {
        "elmSelector": ".quick-access-tab a"
    }, {
        "elmSelector": ".partner-logo-card a"
    }, {
        "elmSelector": ".rte-inline a"
    }, {
        "elmSelector": ".icon-card-container .icon-card-text .card-content-details a"
    }, {
        "elmSelector": "a[href*='.pdf'],a[href*='.tekpdf'],a[href*='.PDF'],a[href*='.TEKPDF']"
    }, {
        "elmSelector": ".blog-content-module a"
    }, {
        "elmSelector": ".author-module .author-article a"
    }, {
        "elmSelector": ".rte-inline-eng a"
    }];

    var init = function () {

        enforceLinkType();
        mapTemplateZones();
        mapModalTemplateZone();
        applyModuleNames();
        setDataAttributesByPageTemplate();
        setRichTextNewLinkAttributes();
    };

    var enforceLinkType = function () {
        var updatedElements = [];
        $.each(linkTypeMapping, function (i, v) {
            var foundTarget = false;
            var $elmSel = $(v.elmSelector);
            var parentSel = v.parentSelector;
            var $parentSel;
            if (parentSel) {
                $parentSel = $(parentSel);
                if ($parentSel.length > 0) {
                    if ($elmSel.length > 0 && $elmSel.closest(parentSel).length > 0) {
                        foundTarget = true;
                    }
                }
            } else {
                if ($elmSel.length > 0) {
                    foundTarget = true;
                }
            }
            if (foundTarget) {

                var holdDataName = $elmSel.attr("data-name");
                var holdLinkAction = $elmSel.attr("data-linkaction");
                var holdLinkType = $elmSel.attr("data-linktype");
                var holdDataLinkName = $elmSel.attr("data-analytics-link-name");
                var holdDataContentType = $elmSel.attr("data-analytics-content-type");

                if (v.dataName.length > 0) {
                    if (!holdDataName) {
                        if (!holdLinkAction && !holdDataLinkName) {
                            $elmSel.attr(linkTrackingAttributes.linkName, v.dataName);
                        }
                    }
                }
                else {
                    if (!holdLinkAction && !holdDataLinkName) {
                        for (var x = 0; x < $elmSel.length; x++) {
                            var $currentElm = $($elmSel[x]);
                            var linkText = "";

                            if ($currentElm.text() && $currentElm.text().trim().length > 0)
                                linkText = $currentElm.text();
                            else if ($currentElm.prop('text') && $currentElm.prop('text').trim().length > 0)
                                linkText = $currentElm.prop('text');
                            else if ($currentElm.prop('innerText') && $currentElm.prop('innerText').trim().length > 0)
                                linkText = $currentElm.prop('innerText');
                            else if ($currentElm.attr('title') && $currentElm.attr('title').trim().length > 0)
                                linkText = $currentElm.attr('title');
                            else if ($currentElm.find('img').attr('alt') && $currentElm.find('img').attr('alt').trim().length > 0)
                                linkText = $currentElm.find('img').attr('alt');
                            else if ($currentElm.attr('value'))
                                linkText = $currentElm.attr('value');
                            else if ($currentElm.attr('data-network') && $currentElm.attr('data-network').trim().length > 0)
                                linkText = $currentElm.attr('data-network');
                            else if ($currentElm.attr('aria-label') && $currentElm.attr('aria-label').trim().length > 0)
                                linkText = $currentElm.attr('aria-label');
                            else if ($currentElm.hasClass('social-likes__widget_email'))
                                linkText = 'email';

                            if (linkText)
                                $currentElm.attr(linkTrackingAttributes.linkName, linkText.trim().toLowerCase());
                        }
                    }
                }

                if (v.linkType.length > 0) {
                    if (!holdLinkType && !holdDataContentType)
                        $elmSel.attr(linkTrackingAttributes.contentType, v.linkType);
                }

                updatedElements.push($elmSel);
            }
        });
    };

    var mapTemplateZones = function () {
        $.each(templateZone, applyTemplateZone);
    };

    var mapBranchTemplateZoneAttrs = function (modules) {
        if (modules != undefined && modules.length > 0) {
            $.each(modules, applyBranchTemplateZoneAttr);
        }
    };

    var applyTemplateZone = function (index, item) {

        if (item.Location === "customblock") {
            customBlockTemplateZone(item);
            return;
        }

        var $container = $(item.LocationSelector);

        if ($container && $container.length) {
            var holdTemplateZone = $container.attr(linkTrackingAttributes.templateZone);
            var holdLinkPageSection = $container.attr("data-linkpagesection");

            if (holdTemplateZone || holdLinkPageSection)
                return;

            $container.attr(linkTrackingAttributes.templateZone, item.Location);
        }
    };

    var applyBranchTemplateZoneAttr = function (index, item) {
        BranchTemplateZoneAttr(item);
        return;
    };

    var customBlockTemplateZone = function (templateZoneData) {

        var $blocks = $(templateZoneData.LocationSelector);

        //Skip if the block is empty.
        if (!$blocks)
            return;

        for (var indx = 0; indx < $blocks.length; indx++) {

            var templateZoneValue = "";
            var $currentBlock = $($blocks[indx]);
            var $sectionTitle = $currentBlock.find("h2.section-title"); //Redesign block title

            if (typeof $sectionTitle === "undefined")
                $sectionTitle = $currentBlock.find("div.block-title h2"); //Legacy block title           

            if ($sectionTitle && $sectionTitle.length)
                templateZoneValue = 'block-' + $sectionTitle.text().trim().toLowerCase().replace(/\s+/g, '-');
            else
                templateZoneValue = $currentBlock.attr("id");

            $currentBlock.attr(linkTrackingAttributes.templateZone, templateZoneValue);

        }
    };


    var BranchTemplateZoneAttr = function (templateZoneData) {
        var $blocks;
        if (typeof templateZoneData.LocationSelector == "string") {
            $blocks = $(templateZoneData.LocationSelector);
        }
        else {
            $blocks = templateZoneData.LocationSelector;
        }
        //Skip if the block is empty.
        if (!$blocks)
            return;

        for (var indx = 0; indx < $blocks.length; indx++) {
            var templateZoneValue = "";
            var $currentBlock = $($blocks[indx]);
            $($currentBlock).attr('data-analytics-template-zone', templateZoneData.Location);
        }
    };

    var mapModalTemplateZone = function () {

        $("[" + linkTrackingAttributes.linkType + "], [" + linkTrackingAttributes.contentType + "]").on("click", applyModalTemplateZone);
    };

    var applyModalTemplateZone = function () {

        var $targetElement = $(this);
        $.each(templateZoneModals, function (index, item) {

            var $parentNode = $targetElement.closest(item.ParentSelector);

            if (!$parentNode && $parentNode.length === 0)
                return;

            var $currentTemplateZone = $targetElement.closest("[" + linkTrackingAttributes.templateZone + "]");
            var templateZoneValue = $currentTemplateZone.attr(linkTrackingAttributes.templateZone);

            if (templateZoneValue && templateZoneValue.length)
                $(item.OverlaySelector).attr(linkTrackingAttributes.templateZone, templateZoneValue);
        });
    };

    var applyModuleNames = function () {

        for (var i = 0; i < moduleNames.length; i++) {
            var componentInfo = moduleNames[i];
            var $componentParent = $(componentInfo.ParentComponentSelector);
            var holdDataModuleName = $componentParent.attr('data-analytics-module-name');
            var holdLinkComponentName = $componentParent.attr('data-linkcomponentname');

            if (holdDataModuleName || holdLinkComponentName) {
                continue;
            }
            var $nonDescendantOf = $componentParent.closest(componentInfo.NonDescendantOf);

            if ($nonDescendantOf && $nonDescendantOf.length) {
                continue;
            }

            if ($componentParent && $componentParent.length) {

                var componentName = "";

                if (componentInfo.ComponentTitleOverride.length) {
                    componentName = componentInfo.ComponentTitleOverride.toLowerCase();
                }
                else if (componentInfo.ComponentTitleSelector.length) {

                    var $componentNameSource = $(componentInfo.ParentComponentSelector + ' ' + componentInfo.ComponentTitleSelector);
                    $componentNameSource.each(function (i, v) {

                        var sourceText = "";

                        if ($componentParent.eq(i).attr('id')) {
                            sourceText = $componentParent.eq(i).attr('id');
                        }
                        else {
                            sourceText = v.textContent.trim().toLowerCase();
                        }

                        jQuery($componentParent[i]).attr(linkTrackingAttributes.moduleName, sourceText);
                    });
                }

                if (componentName.length)
                    $componentParent.attr(linkTrackingAttributes.moduleName, componentName);
            }
        };
    };

    var setDataAttributesByPageTemplate = function () {
        if (typeof dataModel === "undefined") {
            return;
        }

        var pageTemplate = dataModel.page.pageInfo.branchTemplate.toUpperCase();
        var branchTemplateZoneSettings = {};

        if (!pageTemplate || pageTemplate === "default") {
            //Default Settings
            branchTemplateZoneSettings = branchTemplateZone[0];
        } else {
            for (var indx = 0; indx < branchTemplateZone.length; indx++) {
                var branchTemplateZoneItem = branchTemplateZone[indx];
                if (branchTemplateZoneItem.BranchTemplate.indexOf(pageTemplate) > -1) {
                    branchTemplateZoneSettings = branchTemplateZoneItem;
                    break;
                }
            }
        }
        mapBranchTemplateZoneAttrs(branchTemplateZoneSettings.TemplateZone);
    };

    var setRichTextNewLinkAttributes = function () {

        var addNewLinkAttributes = function (index, item) {

            var links = $(item.elmSelector);

            if (links.length > 0) {

                for (i = 0; i < links.length; i++) {

                    var $elmLink = $(links[i]);
                    var holdDataName = $elmLink.attr("data-name");
                    var holdLinkAction = $elmLink.attr("data-linkaction");
                    var holdLinkType = $elmLink.attr("data-linktype");
                    var holdDataLinkName = $elmLink.attr("data-analytics-link-name");
                    var holdDataContentType = $elmLink.attr("data-analytics-content-type");
                    var transcriptLink = $elmLink.find("> span#icon-downloadID");

                    //don't add new attributes if already existing.
                    if (holdDataLinkName != undefined && holdDataContentType != undefined) {
                        continue;
                    }

                    //data-analytics-link-name
                    if (holdDataName != undefined) {
                        $elmLink.attr(linkTrackingAttributes.linkName, holdDataName);
                    }
                    else {
                        if (holdLinkAction != undefined) {
                            $elmLink.attr(linkTrackingAttributes.linkName, holdLinkAction);
                        }
                        else {
                            var linkText = "";

                            if ($elmLink.text() && $elmLink.text().trim().length > 0) {
                                linkText = $elmLink.text();

                                if ($elmLink["0"].innerText.indexOf("\n") > -1) {
                                    linkText = $elmLink["0"].innerText.split("\n")[0];
                                }
                            }
                            else if ($elmLink.prop('text') && $elmLink.prop('text').trim().length > 0)
                                linkText = $elmLink.prop('text');
                            else if ($elmLink.prop('innerText') && $elmLink.prop('innerText').trim().length > 0)
                                linkText = $elmLink.prop('innerText');
                            else if ($elmLink.attr('title') && $elmLink.attr('title').trim().length > 0)
                                linkText = $elmLink.attr('title');
                            else if ($elmLink.find('img').attr('alt') && $elmLink.find('img').attr('alt').trim().length > 0)
                                linkText = $elmLink.find('img').attr('alt');
                            else if ($elmLink.attr('value'))
                                linkText = $elmLink.attr('value');
                            else if ($elmLink.attr('aria-label') && $elmLink.attr('aria-label').trim().length > 0)
                                linkText = $elmLink.attr('aria-label');

                            if (linkText)
                                $elmLink.attr(linkTrackingAttributes.linkName, linkText.trim().toLowerCase());
                        }
                    }

                    //data-analytics-content-type
                    if (holdLinkType != undefined) {
                        $elmLink.attr(linkTrackingAttributes.contentType, holdLinkType);
                    }
                    else if (holdDataContentType != undefined) {
                        continue;
                    }
                    else if (transcriptLink.length > 0) {
                        $elmLink.attr(linkTrackingAttributes.contentType, "engagement");
                    }
                    else if ($elmLink.closest("[class='author-module']").length > 0) {
                        $elmLink.attr(linkTrackingAttributes.contentType, "engagement");
                        $elmLink.attr("data-analytics-link-type", "engagement");
                    }
                    else if (item.elmSelector === ".rte-inline-eng a") {
                        $elmLink.attr(linkTrackingAttributes.contentType, "engagement");
                    }
                    else {
                        $elmLink.attr(linkTrackingAttributes.contentType, "cta");
                    }
                }
            }
        };

        var applyLinkAttributes = function () {
            $.each(richTextLinks, addNewLinkAttributes);
        };

        applyLinkAttributes();
    };



    return {
        init: init
    };
}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\reinvent\reinvent-consent-manager.js
/*  version="2" */
function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
}; 

var minimizeBanner = getCookie('OptanonAlertBoxClosed');
var configLocalStorageName = $("#configLocalStorageName")
var localStorageName = configLocalStorageName.attr("value");
var isNewBanner = $("#isNewBanner").attr("value");
var isIE = $('html').hasClass('ie')

//localStorageName Value 
if (configLocalStorageName.length > 0) {
    //check if the banner has been closed already
    if (isNewBanner == "True") {
        localStorageName = "https://cdn.cookielaw.org/scripttemplates/otSDKStub.js";
        $(document).on("click", ".optanon-toggle-display", function () {
            Optanon.ToggleInfoDisplay();
        });
    }

    var substringStart = localStorageName.lastIndexOf("/") + 1;
    var substringEnd = localStorageName.lastIndexOf(".");
    localStorageName = localStorageName.substr(substringStart, substringEnd);
    localStorageName = localStorageName.replace(/-/g, '');
    var minimizeButtonKey = localStorageName;
    //if not closed yet delegate event to the buttons
    if (minimizeBanner === undefined) {
        $(document).one("click", "button[onclick*=\"Optanon.TriggerGoogleAnalyticsEvent(\'OneTrust Cookie Consent\'\"], button[class*='save-preference'], button[id*='accept'], [class*='banner-close']", function (event) {
            var minimizeButtonText = isNewBanner == "True" ? $('button#onetrust-pc-btn-handler').text() : $('button.optanon-toggle-display.cookie-settings-button').text();
            localStorage.setItem(minimizeButtonKey, minimizeButtonText);
            $("body").append("<div id=\"optanon-minimize-wrapper\" data-analytics-template-zone=\"consent manager\" data-analytics-module-name=\"consent manager\" class=\"optanon-toggle-display\"><button id=\"optanon-minimize-button\" title=\"" + minimizeButtonText + "\" data-analytics-link-name=\"" + minimizeButtonText.toLowerCase() + "\" data-analytics-content-type=\"cta\" aria-label=\"" + minimizeButtonText + "\" >" + minimizeButtonText + "</button></div>");
        });
    }//show the minimized button if the banner is closed already
    else {
        var oldBannerKey = isNewBanner != "True" ? minimizeButtonKey : "otSDKStub.js";
        var replacedKey = (localStorage.getItem("otSDKStub.js") == null) ? "otSDKStub.js" : oldBannerKey;
        if (isIE) {
            $.cookie('OptanonAlertBoxClosed', '', { expires: -1, path: clientGeoLocation });
            $.cookie('OptanonAlertBoxClosed', '', { expires: -1, path: '/' });
        }
        if (typeof $.cookie('OptanonAlertBoxClosed') != 'undefined'
            && (localStorage.getItem(replacedKey) == null || localStorage.getItem(replacedKey) == "")
            && typeof localStorage.getItem(replacedKey) != 'undefined') {
            localStorage.setItem(replacedKey, "Cookie Settings")
        }
        $(function () {
            var optanondatalink = (localStorage.getItem(minimizeButtonKey) != null) ? localStorage.getItem(minimizeButtonKey) : "";
            $("body").append("<div id=\"optanon-minimize-wrapper\" data-analytics-template-zone=\"consent manager\" data-analytics-module-name=\"consent manager\" class=\"optanon-toggle-display\"><button id=\"optanon-minimize-button\" title=\"" + optanondatalink + "\" data-analytics-link-name=\"" + optanondatalink.toLowerCase() + "\" data-analytics-content-type=\"cta\" aria-label=\"" + optanondatalink + "\" >" + optanondatalink + "</button></div>");
        });
    }
}

