/*
 * Toastr
 * Copyright 2012-2014 
 * Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * ARIA Support: Greta Krafsig
 *
 * Project: https://github.com/CodeSeven/toastr
 */
; (function (define) {
    define(['jquery'], function ($) {
        return (function () {
            var $container;
            var listener;
            var toastId = 0;
            var toastType = {
                error: 'error',
                info: 'info',
                success: 'success',
                warning: 'warning'
            };

            var toastr = {
                clear: clear,
                remove: remove,
                error: error,
                getContainer: getContainer,
                info: info,
                options: {},
                subscribe: subscribe,
                success: success,
                version: '2.1.0',
                warning: warning
            };

            var previousToast;

            return toastr;

            //#region Accessible Methods
            function error(message, title, optionsOverride) {
                return notify({
                    type: toastType.error,
                    iconClass: getOptions().iconClasses.error,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function getContainer(options, create) {
                if (!options) { options = getOptions(); }
                $container = $('#' + options.containerId);
                if ($container.length) {
                    return $container;
                }
                if (create) {
                    $container = createContainer(options);
                }
                return $container;
            }

            function info(message, title, optionsOverride) {
                return notify({
                    type: toastType.info,
                    iconClass: getOptions().iconClasses.info,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function subscribe(callback) {
                listener = callback;
            }

            function success(message, title, optionsOverride) {
                return notify({
                    type: toastType.success,
                    iconClass: getOptions().iconClasses.success,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function warning(message, title, optionsOverride) {
                return notify({
                    type: toastType.warning,
                    iconClass: getOptions().iconClasses.warning,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function clear($toastElement) {
                var options = getOptions();
                if (!$container) { getContainer(options); }
                if (!clearToast($toastElement, options)) {
                    clearContainer(options);
                }
            }

            function remove($toastElement) {
                var options = getOptions();
                if (!$container) { getContainer(options); }
                if ($toastElement && $(':focus', $toastElement).length === 0) {
                    removeToast($toastElement);
                    return;
                }
                if ($container.children().length) {
                    $container.remove();
                }
            }
            //#endregion

            //#region Internal Methods

            function clearContainer (options) {
                var toastsToClear = $container.children();
                for (var i = toastsToClear.length - 1; i >= 0; i--) {
                    clearToast($(toastsToClear[i]), options);
                }
            }

            function clearToast ($toastElement, options) {
                if ($toastElement && $(':focus', $toastElement).length === 0) {
                    $toastElement[options.hideMethod]({
                        duration: options.hideDuration,
                        easing: options.hideEasing,
                        complete: function () { removeToast($toastElement); }
                    });
                    return true;
                }
                return false;
            }

            function createContainer(options) {
                $container = $('<div/>')
                    .attr('id', options.containerId)
                    .addClass(options.positionClass)
                    .attr('aria-live', 'polite')
                    .attr('role', 'alert');

                $container.appendTo($(options.target));
                return $container;
            }

            function getDefaults() {
                return {
                    tapToDismiss: true,
                    toastClass: 'toast',
                    containerId: 'toast-container',
                    debug: false,

                    showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
                    showDuration: 300,
                    showEasing: 'swing', //swing and linear are built into jQuery
                    onShown: undefined,
                    hideMethod: 'fadeOut',
                    hideDuration: 1000,
                    hideEasing: 'swing',
                    onHidden: undefined,

                    extendedTimeOut: 1000,
                    iconClasses: {
                        error: 'toast-error',
                        info: 'toast-info',
                        success: 'toast-success',
                        warning: 'toast-warning'
                    },
                    iconClass: 'toast-info',
                    positionClass: 'toast-top-right',
                    timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
                    titleClass: 'toast-title',
                    messageClass: 'toast-message',
                    target: 'body',
                    closeHtml: '<button type="button">&times;</button>',
                    newestOnTop: true,
                    preventDuplicates: false,
                    progressBar: false
                };
            }

            function publish(args) {
                if (!listener) { return; }
                listener(args);
            }

            function notify(map) {
                var options = getOptions(),
                    iconClass = map.iconClass || options.iconClass;

                if (options.preventDuplicates) {
                    if (map.message === previousToast) {
                        return;
                    } else {
                        previousToast = map.message;
                    }
                }

                if (typeof (map.optionsOverride) !== 'undefined') {
                    options = $.extend(options, map.optionsOverride);
                    iconClass = map.optionsOverride.iconClass || iconClass;
                }

                toastId++;

                $container = getContainer(options, true);
                var intervalId = null,
                    $toastElement = $('<div/>'),
                    $titleElement = $('<div/>'),
                    $messageElement = $('<div/>'),
                    $progressElement = $('<div/>'),
                    $closeElement = $(options.closeHtml),
                    progressBar = {
                        intervalId: null,
                        hideEta: null,
                        maxHideTime: null
                    },
                    response = {
                        toastId: toastId,
                        state: 'visible',
                        startTime: new Date(),
                        options: options,
                        map: map
                    };

                if (map.iconClass) {
                    $toastElement.addClass(options.toastClass).addClass(iconClass);
                }

                if (map.title) {
                    $titleElement.append(map.title).addClass(options.titleClass);
                    $toastElement.append($titleElement);
                }

                if (map.message) {
                    $messageElement.append(map.message).addClass(options.messageClass);
                    $toastElement.append($messageElement);
                }

                if (options.closeButton) {
                    $closeElement.addClass('toast-close-button').attr('role', 'button');
                    $toastElement.prepend($closeElement);
                }

                if (options.progressBar) {
                    $progressElement.addClass('toast-progress');
                    $toastElement.prepend($progressElement);
                }

                $toastElement.hide();
                if (options.newestOnTop) {
                    $container.prepend($toastElement);
                } else {
                    $container.append($toastElement);
                }
                $toastElement[options.showMethod](
                    {duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
                );

                if (options.timeOut > 0) {
                    intervalId = setTimeout(hideToast, options.timeOut);
                    progressBar.maxHideTime = parseFloat(options.timeOut);
                    progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
                    if (options.progressBar) {
                        progressBar.intervalId = setInterval(updateProgress, 10);
                    }
                }

                $toastElement.hover(stickAround, delayedHideToast);
                if (!options.onclick && options.tapToDismiss) {
                    $toastElement.click(hideToast);
                }

                if (options.closeButton && $closeElement) {
                    $closeElement.click(function (event) {
                        if (event.stopPropagation) {
                            event.stopPropagation();
                        } else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
                            event.cancelBubble = true;
                        }
                        hideToast(true);
                    });
                }

                if (options.onclick) {
                    $toastElement.click(function () {
                        options.onclick();
                        hideToast();
                    });
                }

                publish(response);

                if (options.debug && console) {
                    console.log(response);
                }

                return $toastElement;

                function hideToast(override) {
                    if ($(':focus', $toastElement).length && !override) {
                        return;
                    }
                    clearTimeout(progressBar.intervalId);
                    return $toastElement[options.hideMethod]({
                        duration: options.hideDuration,
                        easing: options.hideEasing,
                        complete: function () {
                            removeToast($toastElement);
                            if (options.onHidden && response.state !== 'hidden') {
                                options.onHidden();
                            }
                            response.state = 'hidden';
                            response.endTime = new Date();
                            publish(response);
                        }
                    });
                }

                function delayedHideToast() {
                    if (options.timeOut > 0 || options.extendedTimeOut > 0) {
                        intervalId = setTimeout(hideToast, options.extendedTimeOut);
                        progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
                        progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
                    }
                }

                function stickAround() {
                    clearTimeout(intervalId);
                    progressBar.hideEta = 0;
                    $toastElement.stop(true, true)[options.showMethod](
                        {duration: options.showDuration, easing: options.showEasing}
                    );
                }

                function updateProgress() {
                    var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
                    $progressElement.width(percentage + '%');
                }
            }

            function getOptions() {
                return $.extend({}, getDefaults(), toastr.options);
            }

            function removeToast($toastElement) {
                if (!$container) { $container = getContainer(); }
                if ($toastElement.is(':visible')) {
                    return;
                }
                $toastElement.remove();
                $toastElement = null;
                if ($container.children().length === 0) {
                    $container.remove();
                }
            }
            //#endregion

        })();
    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) { //Node
        module.exports = factory(require('jquery'));
    } else {
        window['toastr'] = factory(window['jQuery']);
    }
}));

//declare Namespace
var ppeproNS = ppeproNS || {};

ppeproNS.DataService = function () {

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    //When a form is submited intercept the postback and perform and ajax request.
    //Populate the target with the data returned from the ajax request
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _ajaxSubmit = function (action, method, data) {

        var options = {
            url: action,
            type: method,
            data: data
        };
        return $.ajax(options);

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    //When a value is selected form the autocomplete drop down list submit form the input
    //field was attached to.
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _submitAutoCompleteForm = function (event, ui) {

        ppeproNS.PageService.$searchBox.val(ui.item.label);
        var $form = ppeproNS.PageService.$searchForm; 
        $form.submit();
    };


    return {
        AjaxSubmit: _ajaxSubmit,
        SubmitAutoCompleteForm: _submitAutoCompleteForm
    };

} ();
//declare Namespace
var ppeproNS = ppeproNS || {};

//on DOM ready
$(document).ready(function () {

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    //Wire up events
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    var pageObj = ppeproNS.PageService;
        pageObj.$searchBox = $("#ppeproSearchBox");
        pageObj.$searchForm = $("#standardSearchForm");

    //If form is marked for ajax, wire up submit event
    $("form[data-ppepro-ajax='true']").submit(pageObj.AjaxSubmital);

    //Autosize text areas
    $("textarea[data-autogrow='true']").autosize({ append: "\n" });
    document.body.offsetWidth; // trigger a reflow before the class is changed
    $("textarea[data-autogrow='true']").addClass('textarea-transition');

    //If input field is marked for autocomplete, wire up autocomplete event
    $("input[data-ppepro-autocomplete]").each(pageObj.InitAutoComplete);    

    //Wire paged list links to retrieve the page clicked on
    $("#results").on("click", ".pagedList a", pageObj.Paging);    
    pageObj.InitPagingTitleAttr();

    //Initialize Toastr
    pageObj.InitToastr();

});    //end DOM ready function


//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Page class
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
ppeproNS.PageService = function () {

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Div containing the loading message
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    var $loadIndicator = $("#ajax-loading-container"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // The input used for searach terms
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $searchBox = $("#ppeproSearchBox"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // The form containing searchBox and other search fields such as filters
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $searchForm = $("#standardSearchForm"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // The button that submits the search form
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $searchButton = $("#ppeproSearchButton"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // The container that holds help information for it's page
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $helpContainer = $("#searchHelpContainer"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // The button that opens the help container
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $helpButton = $("#searchHelpBtn"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Recaptcha form variables
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $feedbackFormRecaptcha = $("#feedback_recaptcha_element"),
    $feedbackFormRecaptchaWarning = $("#feedback_recaptcha_warning"),
    $standardFeedbackFormRecaptcha = $("#standard_feedback_recaptcha_element"),
    $standardFeedbackFormRecaptchaWarning = $("#standard_feedback_recaptcha_warning"),
    $productFeedbackFormRecaptcha = $("#product_feedback_recaptcha_element"),
    $productFeedbackFormRecaptchaWarning = $("#product_feedback_recaptcha_warning"),
    $productSubmissionFormRecaptcha = $("#product_submission_recaptcha_element"),
    $productSubmissionFormRecaptchaWarning = $("#product_submission_recaptcha_warning"),

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Terms that are excluded froma  search
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    $excludedTerms = ["a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all",
                        "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "amoungst", "amount", "an", "and", "another",
                        "any", "anyhow", "anyone", "anything", "anyway", "anywhere", "are", "around", "as", "at", "back", "be", "became", "because", "become",
                        "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both",
                        "bottom", "but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done",
                        "down", "due", "during", "each", "eg", "eight", "either", "eleven", "else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every",
                        "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "first", "five", "for", "former",
                        "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence",
                        "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie",
                        "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd",
                        "made", "many", "may", "me", "meanwhile", "might", "mill", "more", "moreover", "most", "mostly", "move", "much", "must", "my",
                        "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing",
                        "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves",
                        "out", "over", "own", "part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems",
                        "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something",
                        "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then",
                        "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thickv", "thin", "third", "this", "those",
                        "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two",
                        "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "when", "whence", "whenever",
                        "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever",
                        "whole", "whom", "whose", "why", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the"],

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize toast notifications
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initToastr = function () {

        toastr.options = {
            "closeButton": false,
            "debug": false,
            "progressBar": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "600",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Show loading indicator
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _showLoadingIndicator = function () {
        $loadIndicator.show();
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Hide loading indicator
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _hideLoadingIndicator = function () {
        $loadIndicator.hide();
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Gather form information and submit to DataService.AjaxSubmit, highlight terms and
    // fix links
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _ajaxSubmital = function () {
        $loadIndicator.show();

        var $form = $(this);
        var $target = $($form.attr("data-ppepro-target"));

        ppeproNS.DataService.AjaxSubmit($form.attr("action"), $form.attr("method"), $form.serialize())
            .then(function (data) {
                $target.replaceWith(data); //update page                

                //if any results exist, then highlight
                var resultCount = $("#standardResults").attr("data-result-count");
                if (resultCount > 0) {

                    //get terms to highlight
                    var searchTerm = $searchBox.val();
                    var isMatch = $("#standardResults").attr("data-exact-match");

                    _highlightTerms(searchTerm, '#' + $target.attr('id'), isMatch);
                }
                else //no results
                {
                    $("#standardResults ul.standard-list").hide();
                }

                try {

                    //Fix anchors (add external link icon and document types icon)
                    CDC.Policy.External.init();
                    CDC.Policy.Documents.init();

                    //Apply standard reference popovers
                    _initPopoverTooltip();

                    //Hide search result options
                    _hideSearchResultOptions();                    

                } catch (err) { }

                $loadIndicator.hide();

            }, function (jqXHR, message, err) {
                toastr.error("Internal Server Error");
                $loadIndicator.hide();
            });

        return false; //intercept the full postback
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize autocomplete for search input
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initAutoComplete = function () {

        var $input = $(this);
        var options = {
            source: $input.attr("data-ppepro-autocomplete"),
            select: ppeproNS.DataService.SubmitAutoCompleteForm //submitAutoCompleteForm
        };

        //Retrieves the autocomplete results
        $input.autocomplete(options);

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Adjust title attribute for pagedList navigation buttons for 508 compliance
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initPagingTitleAttr = function () {

        //Skip to first page
        $("#results .PagedList-skipToFirst:not('.disabled') a").attr('title', 'Skip to first page');
        $("#results .PagedList-skipToFirst.disabled a").attr('title', 'Skip to first page (Disabled)');

        //Previous Page
        $("#results .PagedList-skipToPrevious:not('.disabled') a").attr('title', 'Previous Page');
        $("#results .PagedList-skipToPrevious.disabled a").attr('title', 'Previous Page (Disabled)');

        //Skip to last page
        $("#results .PagedList-skipToLast:not('.disabled') a").attr('title', 'Skip to last page');
        $("#results .PagedList-skipToLast.disabled a").attr('title', 'Skip to last page (Disabled)');

        //Next page
        $("#results .PagedList-skipToNext:not('.disabled') a").attr('title', 'Next page');
        $("#results .PagedList-skipToNext.disabled a").attr('title', 'Next page (Disabled)');
        
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize tooltip popovers
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initPopoverTooltip = function () {
        $('[data-toggle="popover"]').popover({ trigger: "hover focus" });
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Retrieve the next page of results and update the page with those results
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _paging = function () {

        $loadIndicator.show();
        var $a = $(this);
        var $target = $($a.parents("div.pagedList").attr("data-ppepro-target"));

        //Append the newSearch parameter with a value of false since paging was used to avoid duplicate search log entries
        //If this is not done, the server side paging will register as a new search to be logged
        ppeproNS.DataService.AjaxSubmit($a.attr("href"), "GET", $searchForm.serialize() + '&' + $.param({ newSearch: false }))
            .then(function (data) {
                $target.replaceWith(data); //update page

                //Get terms to highlight
                var searchTerm = $searchBox.val();
                var isMatch = $("#standardResults").attr("data-exact-match");
                _highlightTerms(searchTerm, '#' + $target.attr('id'), isMatch);

                //Fix anchors (add external link icon and document types icon)
                CDC.Policy.External.init();
                CDC.Policy.Documents.init();

                //Hide search result options
                _hideSearchResultOptions();

                //Adjust pager navigation titles
                _initPagingTitleAttr();

                //Apply standard reference popovers
               //_initPopoverTooltip();

                $loadIndicator.hide();

                //Scroll back to the top of the results
                _scrollToTop('#' + $searchForm.attr('id'));

            }, function (jqXHR, message, err) {
                toastr.error("Internal Server Error");
                $loadIndicator.hide();
            });

        return false; //intercept the full postback                

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Change what fields to search by and update autocomplete
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _setSearchBy = function (searchBy, fullTextSearch) {

        //Check if searchby is set to Full Text, if so disable autocomplete
        if (searchBy.val() == fullTextSearch) {
            $searchBox.autocomplete("option", "disabled", true);
        }

        //Whenever the search by field changes, update the autocomplete widget
        searchBy.change(function () {
            if ($(this).val() != fullTextSearch) //if not full text, enable autocomplete
            {
                $searchBox.autocomplete("option", "source", baseUrl + "/Home/Autocomplete?searchBy=" + $(this).val());
                $searchBox.autocomplete("option", "disabled", false);
            }
            else // full text, disable autocomplete 
            {
                $searchBox.autocomplete("option", "disabled", true);
            }
        });
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize help section options for the page
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initHelpOptions = function () {

        $helpContainer.hide(); //Initially hide the help section

        //Toggle search help container
        $helpButton.bind("keypress", function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (e.which == 13) {
                //prevent form submittal and invoke help button click                
                $(this).click();                
            }
            return false;
        });

        $helpButton.bind("click", function () {
            var cont = $(this);
            var $helpspan = cont.children("span:first");
            //If help section is visible, then change to up arrow
            if ($helpContainer.is(":visible")) {
                cont.removeClass("advanced-filter-help-active").addClass("advanced-filter-help");
                $helpspan.removeClass("glyphicon glyphicon-backward search-help-collapse").addClass("glyphicon glyphicon-forward search-help-expand");
                $helpspan.removeAttr("style").css({ "position": "absolute", "top": ".60em", "right": ".5em" });
            }
            else //help section is hidden, change to down arrow
            {
                cont.removeClass("advanced-filter-help").addClass("advanced-filter-help-active");
                $helpspan.removeClass("glyphicon glyphicon-forward search-help-expand").addClass("glyphicon glyphicon-backward search-help-collapse");
                $helpspan.removeAttr("style").css({ "position": "absolute", "top": ".40em", "right": ".5em" });
            }

            $helpContainer.slideToggle(400);

        }); //end bind
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize search result for the target
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initSearchResultOptions = function (target) {

        _hideSearchResultOptions();

        $(target).on("click", ".result-options", function (event) {
            event.stopPropagation();
            var $btn = $(this);
            $thisResult = $btn.nextUntil('div.result-options-list').first().next();

            if ($thisResult.is(":visible")) {
                $btn.removeClass("result-options-active");
            }
            else //options are hidden
            {
                $btn.addClass("result-options-active");
            }

            $thisResult.slideToggle(200);
        });

        $('html').click(function () {

            //Hide the menus if visible
            var $resultLists = $("div.result-options-list");
            $resultLists.each(function () {
                var $option = $(this);
                if ($option.is(":visible")) {
                    $option.slideToggle(300);
                    setTimeout(function () {
                        $option.siblings(".result-options").removeClass("result-options-active");
                    }, 275);

                }
            });
        });
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize result section options for the target
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initResultOptions = function (target) {

        //upon entering results, show option buttons
        target.on("mouseenter", "div.search-result, div.altsearch-result", function (e) {
            $(this).find(".detailed-info-button").addClass("detailed-info-button-visible");
        }) //upon exiting results, hide option buttons
        .on("mouseleave", "div.search-result, div.altsearch-result", function (e) {
            $(this).find(".detailed-info-button").removeClass("detailed-info-button-visible");
        });

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Hides result section options for the target
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _hideSearchResultOptions = function () {
        $(".result-options-list").hide();
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Wire a keypress handler to the search form
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initKeyPressHandler = function () {
        $searchForm.keypress(_keyPressHandler);
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Keypress handler that checks if the enter key was hit, if so submit form
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _keyPressHandler = function (e) {

        //If the enter key was hit, submit the form
        if (e.which == 13) {
            $searchBox.blur();
            $searchForm.submit();
            return false;
        }
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize search box effects
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initSearchEffects = function () {

        //When the search box becomes focus, add interactive styles
        $searchBox.bind("focus blur", function () {
            $(this).toggleClass("search-box-active");
        });

        //Wire search button to form
        $searchButton.bind("click", function () {
            $searchForm.submit();
        });

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize an image carousel
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initImageCarousel = function () {

        //set up unslider
        $(".ppepro-slider").unslider({
            speed: 400,
            delay: 10000,
            keys: true,
            dots: true,
            fluid: true
        });

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Highlight search terms entered by the user
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _highlightTerms = function (searchterm, target, isObject) {

        // remove any old highlighted terms
        $(target).removeHighlight();

        // disable highlighting if empty
        if (searchterm) {

            var termArray = [];

            //If search term is not a lab, standard, or organization parse search terms   
            if (isObject != "True") {
                var rx = /[^\s"]+|"([^"]*)"/gi;

                do {
                    var terms = rx.exec(searchterm);
                    if (terms != null) {
                        //Index 1 in the array is the captured group if it exists --> "([^"]*)" 
                        //Index 0 is the matched text, which we use if no captured group exists
                        termArray.push(terms[1] ? terms[1] : terms[0]);
                    }
                } while (terms != null)
            }
            else { //is a lab, standard number, or standard organization, do not parse search term

                //remove quotes from the begining and end of string if they exist
                termArray.push(searchterm.replace(/^"(.+(?="$))"$/, '$1'));
            }

            //Remove excluded search terms
            termArray = termArray.filter(function (exclude) {
                return $excludedTerms.indexOf(exclude) < 0;
            });

            $.each(termArray, function (_, term) {
                // highlight the new term                    
                if (term != "")
                    $(target).highlight(term);
            });

        } //end if searchterms is not empty
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize email form validation
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initWebMailValidation = function () {

        //Validate feedback form
        //$('#feedback_form').validate({
        //    rules: {
        //        To: {
        //            required: true,
        //            email: true,
        //        },
        //        From: {
        //            required: true,
        //            email: true,
        //        },
        //        Subject: {
        //            minLength: 1,
        //            required: true
        //        },
        //        Message: {
        //            minlength: 1,
        //            required: true
        //        }
        //    },
        //    messages: {
        //        To: "Please enter a valid email address.",
        //        From: "Please enter a valid email address.",
        //        Subject: {
        //            required: "Subject is a required field.",
        //            minlength: "The subject line must be at least 2 characters long."
        //        },
        //        Message: {
        //            required: "Message is a required field.",
        //            minlength: "Message must be at least 2 characters long."
        //        },
        //    }
        //});      


        //*** USE THIS METHOD UNTIL THE CDC TEMPLATE HAS BEEN UPDATED TO MORE CURRENT LIBRARIES ***       
        $('input.required, textarea.required').bind('input propertychange', function () {

            var inputVal = $(this).val();
            if (inputVal.length) {
                $(this).removeClass("input-validation-error").addClass("input-validation-pass");
                $(this).siblings(".message-block").removeClass("invalid").addClass("validated").hide();
            } else {
                $(this).removeClass("input-validation-pass").addClass("input-validation-error");
                $(this).siblings(".message-block").addClass("invalid").removeClass("validated").show();
            }
        });

        var testEmail = /^[ ]*([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[ ]*$/i;
        $('input.validate-email').bind('input propertychange', function () {

            var inputVal = $(this).val();
            if (inputVal.length) {
                if (testEmail.test(inputVal)) {
                    $(this).removeClass("input-validation-error").addClass("input-validation-pass");
                    $(this).siblings(".message-block").removeClass("invalid").addClass("validated").hide();
                } else {
                    $(this).removeClass("input-validation-pass").addClass("input-validation-error");
                    $(this).siblings(".message-block").removeClass("validated").addClass("invalid").show();
                }
            }
            else {
                //hide error message blocks initially
                $("div.message-block").hide();
            }
        });

        //hide error message blocks initially
        $("div.message-block").hide();

    },    

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize email dialog forms for Postal
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initWebMail = function () {

        //Determine dialog box size based on browswer window width
        var winW = $(window).width();
        if (winW > 770) {
            var dialogW = 700;
        }
        else {
            var dialogW = winW * .96;
        }

        //Initialize form validation
        _initWebMailValidation();

        //Get email forms
        var $feedbackform = $("div#FeedbackForm");
        var $feedback_form = $("#feedback_form");
        var $standardFeedbackform = $("div#StandardFeedbackForm");
        var $standard_feedback_form = $("#standard_feedback_form");
        var $productFeedbackform = $("div#ProductFeedbackForm");
        var $product_feedback_form = $("#product_feedback_form");
        var $linkform = $("div#LinkForm");
        var $link_form = $("#link_form");
        var $productform = $("div#ProductForm");
        var $product_form = $("#product_form");

        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        // Feedback Form
        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $("#FeedbackForm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: dialogW,
            buttons: {
                "Send Feedback": function () {

                    var invalidFields = $feedback_form.find("div.invalid");

                    //Check that email form has valid entries
                    if ($feedback_form.valid() && invalidFields.length <= 0) {

                        //if reCaptcha validated user
                        if (grecaptcha.getResponse(feedbackCaptchaElement).length) {

                            //Send email
                            $.ajax({
                                url: baseFolder + 'Base/SendFeedback',
                                type: "POST",
                                data: {
                                    to: $feedbackform.find("input#To").val(),
                                    from: $feedbackform.find("input#From").val(),
                                    subject: $feedbackform.find("input#Subject").val(),
                                    message: $feedbackform.find("textarea#Message").val(),
                                }
                            });

                            $(this).dialog("close");
                            toastr.success("Thank you for your feedback!");
                        }
                        else { //recaptcha failed to validate user                            
                            $feedbackFormRecaptchaWarning.show(); //$("#feedback_recaptcha_warning").show(); //show reCaptcha warning
                        }
                    }
                    else {
                        //show error message blocks
                        $("div.message-block").show();
                        $("div.message-block.validated").hide();
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");                    
                }
            },
            create: function () {
                //Add custom classes and send icon to dialog buttons
                $(this).closest(".ui-dialog")
                    .find(".ui-button")
                    .eq(0).addClass("dialog-button").button({ icons: { primary: 'fa fa-send' } })
                    .eq(1).addClass("dialog-button-secondary");

                $(".ui-dialog-titlebar").hide(); //hide the dialog title bar   
            },
            open: function (event, ui) {

                //Reset email form and clear validation
                var validator = $feedback_form.validate();
                validator.resetForm();

                $feedback_form.find("[data-valmsg-replace]")
                .removeClass("field-validation-error")
                .addClass("field-validation-valid")
                .empty();


                //Prepare clean form
                $feedbackform.find("input#From").val("");
                $feedbackform.find("textarea#Message").val("");
                $feedbackform.find("input").removeClass("input-validation-error input-validation-pass");
                $feedbackform.find("textarea").removeClass("input-validation-error input-validation-pass");
                $feedbackform.find("div.message-block").removeClass("invalid validated").hide();
                $feedbackform.find("div.message-block").removeClass("invalid validated").hide();
                $feedbackFormRecaptchaWarning.hide(); //$("#feedback_recaptcha_warning").hide();
            }
        }); //end FeedbackForm Dialog Init

        //Wire click event for feedback form buttons from search results
        //$("#results, #product-results-wrapper").on("click", "div[data-feedbackform], button[data-feedbackform], span[data-feedbackform]", function () {
        //    $feedbackform.find("input#Subject").val("Feedback regarding " + $(this).attr("data-feedback-number"));
        //    $feedbackform.dialog("open");
        //});

        $("#contentArea").on("click", "#feedbackformlink", function (e) {
            e.preventDefault();
            $feedbackform.find("input#Subject").val("PPE-Info Feedback");
            $feedbackform.dialog("open");
        });

        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        // Standard Feedback Form
        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $("#StandardFeedbackForm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: dialogW,
            buttons: {
                "Send Feedback": function () {

                    var invalidFields = $standard_feedback_form.find("div.invalid");

                    //Check that email form has valid entries
                    if ($standard_feedback_form.valid($standardFeedbackFormRecaptcha) && invalidFields.length <= 0) {

                        //if reCaptcha validated user
                        if (grecaptcha.getResponse(standardFeedbackCaptchaElement).length) {

                            //Send email
                            $.ajax({
                                url: baseFolder + 'Base/SendFeedback',
                                type: "POST",
                                data: {
                                    to: $standardFeedbackform.find("input#To").val(),
                                    from: $standardFeedbackform.find("input#From").val(),
                                    subject: $standardFeedbackform.find("input#Subject").val(),
                                    message: $standardFeedbackform.find("textarea#Message").val(),
                                }
                            });

                            $(this).dialog("close");
                            toastr.success("Thank you for your feedback!");
                        }
                        else { //recaptcha failed to validate user                            
                            $standardFeedbackFormRecaptchaWarning.show(); //$("#standard_feedback_recaptcha_warning").show(); //show reCaptcha warning
                        }
                    }
                    else {
                        //show error message blocks
                        $("div.message-block").show();
                        $("div.message-block.validated").hide();
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            create: function () {
                //Add custom classes and send icon to dialog buttons
                $(this).closest(".ui-dialog")
                    .find(".ui-button")
                    .eq(0).addClass("dialog-button").button({ icons: { primary: 'fa fa-send' } })
                    .eq(1).addClass("dialog-button-secondary");

                $(".ui-dialog-titlebar").hide(); //hide the dialog title bar   
            },
            open: function (event, ui) {

                //Reset email form and clear validation
                var validator = $standard_feedback_form.validate();
                validator.resetForm();

                $standard_feedback_form.find("[data-valmsg-replace]")
                .removeClass("field-validation-error")
                .addClass("field-validation-valid")
                .empty();


                //Prepare clean form
                $standardFeedbackform.find("input#From").val("");
                $standardFeedbackform.find("textarea#Message").val("");
                $standardFeedbackform.find("input").removeClass("input-validation-error input-validation-pass");
                $standardFeedbackform.find("textarea").removeClass("input-validation-error input-validation-pass");
                $standardFeedbackform.find("div.message-block").removeClass("invalid validated").hide();
                $standardFeedbackFormRecaptchaWarning.hide(); //$("#standard_feedback_recaptcha_warning").hide();
            }
        }); //end FeedbackForm Dialog Init

        //Wire click event for feedback form buttons from search results
        $("#results").on("click", "div[data-feedbackform], button[data-feedbackform], span[data-feedbackform]", function () {
            $standardFeedbackform.find("input#Subject").val("Feedback regarding " + $(this).attr("data-feedback-number"));
            $standardFeedbackform.dialog("open");
        });
        $("#results").on("keypress", "div[data-feedbackform], button[data-feedbackform], span[data-feedbackform]", function (e) {
            if (e.which == 13) {
                $(this).click();
            }
        });


        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        // Product Feedback Form
        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $("#ProductFeedbackForm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: dialogW,
            buttons: {
                "Send Feedback": function () {

                    var invalidFields = $product_feedback_form.find("div.invalid");

                    //Check that email form has valid entries
                    if ($product_feedback_form.valid() && invalidFields.length <= 0) {

                        //if reCaptcha validated user
                        if (grecaptcha.getResponse(productFeedbackCaptchaElement).length) {

                            //Send email
                            $.ajax({
                                url: baseFolder + 'Base/SendFeedback',
                                type: "POST",
                                data: {
                                    to: $productFeedbackform.find("input#To").val(),
                                    from: $productFeedbackform.find("input#From").val(),
                                    subject: $productFeedbackform.find("input#Subject").val(),
                                    message: $productFeedbackform.find("textarea#Message").val(),
                                }
                            });

                            $(this).dialog("close");
                            toastr.success("Thank you for your feedback!");
                        }
                        else { //recaptcha failed to validate user                            
                            $productFeedbackFormRecaptchaWarning.show(); //$("#product_feedback_recaptcha_warning").show(); //show reCaptcha warning
                        }
                    }
                    else {
                        //show error message blocks
                        $("div.message-block").show();
                        $("div.message-block.validated").hide();
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            create: function () {
                //Add custom classes and send icon to dialog buttons
                $(this).closest(".ui-dialog")
                    .find(".ui-button")
                    .eq(0).addClass("dialog-button").button({ icons: { primary: 'fa fa-send' } })
                    .eq(1).addClass("dialog-button-secondary");

                $(".ui-dialog-titlebar").hide(); //hide the dialog title bar   
            },
            open: function (event, ui) {

                //Reset email form and clear validation
                var validator = $product_feedback_form.validate();
                validator.resetForm();

                $product_feedback_form.find("[data-valmsg-replace]")
                .removeClass("field-validation-error")
                .addClass("field-validation-valid")
                .empty();


                //Prepare clean form
                $productFeedbackform.find("input#From").val("");
                $productFeedbackform.find("textarea#Message").val("");
                $productFeedbackform.find("input").removeClass("input-validation-error input-validation-pass");
                $productFeedbackform.find("textarea").removeClass("input-validation-error input-validation-pass");
                $productFeedbackform.find("div.message-block").removeClass("invalid validated").hide();
                $productFeedbackFormRecaptchaWarning.hide(); //$("#product_feedback_recaptcha_warning").hide();
            }
        }); //end FeedbackForm Dialog Init

        //Wire click event for feedback form buttons from search results
        $("#product-results-wrapper").on("click", "div[data-feedbackform], button[data-feedbackform], span[data-feedbackform]", function () {
            $productFeedbackform.find("input#Subject").val("Feedback regarding " + $(this).attr("data-feedback-number"));
            $productFeedbackform.dialog("open");
        });
        $("#product-results-wrapper").on("keypress", "div[data-feedbackform], button[data-feedbackform], span[data-feedbackform]", function (e) {
            if (e.which == 13) {
                $(this).click();
            }
        });

        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        // Link Form *** CURRENTLY NOT IN USE DUE TO CONCERNS OF BECOMING A SPAM BOT ***
        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $("#LinkForm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: dialogW,
            buttons: {
                "Send": function () {

                    var invalidFields = link_form.find("div.invalid");

                    //Check that email form has valid entries
                    if ($link_form.valid() && invalidFields.length <= 0) {

                        //Send email
                        $.ajax({
                            url: baseFolder + 'Base/SendLink',
                            type: "POST",
                            data: {
                                to: $linkform.find("input#To").val(),
                                from: $linkform.find("input#From").val(),
                                subject: $linkform.find("input#Subject").val(),
                                message: $linkform.find("textarea#Message").val(),
                            }
                        });

                        $(this).dialog("close");                                            
                    }
                    else {
                        //show error message blocks
                        $("div.message-block").show();
                        $("div.message-block.validated").hide();
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            create: function () {
                //Add custom classes and send icon to dialog buttons
                $(this).closest(".ui-dialog")
                    .find(".ui-button")
                    .eq(0).addClass("dialog-button").button({ icons: { primary: 'fa fa-send' } })
                    .eq(1).addClass("dialog-button-secondary");

                $(".ui-dialog-titlebar").hide(); //hide the dialog title bar   
            },
            open: function (event, ui) {

                //Reset email form and clear validation
                var validator = $link_form.validate();
                validator.resetForm();

                $link_form.find("[data-valmsg-replace]")
                .removeClass("field-validation-error")
                .addClass("field-validation-valid")
                .empty();

                //prepare clean form
                $linkform.find("input#To").val("");
                $linkform.find("input#From").val("")
                $linkform.find("textarea#Message").val(link);
                $linkform.find("input").removeClass("input-validation-error input-validation-pass");
                $linkform.find("textarea").removeClass("input-validation-error input-validation-pass");
                $linkform.find("div.message-block").removeClass("invalid validated").hide();
                $("#product_feedback_recaptcha_warning").hide();
            }
        }); //end LinkForm Dialog Init 

        //Wire click event for link form buttons from search results
        $("#results, #product-results-wrapper").on("click", "div[data-linkform], button[data-linkform], span[data-linkform]", function () {
            $linkform.find("input#Subject").val("PPE-Info link for " + $(this).attr("data-link-number"));

            //Determine web address
            if (!window.location.origin) {
                window.location.origin = baseUrl;
            }

            //Get link for the selected standard
            var link = baseUrl + "Standards/Info/" + $(this).attr("data-link-number").replace(/[\-\.\:\s]*/gi, '');

            $linkform.dialog("open");
        });


        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        // Product Form
        //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $("#ProductForm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: dialogW,
            buttons: {
                "Send": function () {

                    var invalidFields = $product_form.find("div.invalid");

                    //Check that email form has valid entries
                    if ($product_form.valid() && invalidFields.length <= 0) {

                        //if reCaptcha validated user
                        if (grecaptcha.getResponse(productSubmissionCaptchaElement).length) {

                            //Send email
                            $.ajax({
                                url: baseFolder + 'Base/ProductSubmission',
                                type: "POST",
                                data: {
                                    manufacturer: $productform.find("input#Manufacturer").val(),
                                    contactName: $productform.find("input#ContactName").val(),
                                    contactEmailAddress: $productform.find("input#ContactEmailAddress").val(),
                                    contactPhoneNumber: $productform.find("input#ContactPhoneNumber").val(),
                                    subject: $productform.find("input#Subject").val(),
                                    message: $productform.find("textarea#Message").val(),
                                }
                            });

                            $(this).dialog("close");
                            toastr.success("Thank you for your submission!");
                        }
                        else { //recaptcha failed to validate user                            
                            $productSubmissionFormRecaptchaWarning.show(); //$("#product_submission_recaptcha_warning").show(); //show reCaptcha warning
                        }
                    }
                    else {
                        //show error message blocks
                        $("div.message-block").show();
                        $("div.message-block.validated").hide();
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            create: function () {
                //Add custom classes and send icon to dialog buttons
                $(this).closest(".ui-dialog")
                    .find(".ui-button")
                    .eq(0).addClass("dialog-button").button({ icons: { primary: 'fa fa-send' } })
                    .eq(1).addClass("dialog-button-secondary");

                $(".ui-dialog-titlebar").hide(); //hide the dialog title bar   
            },
            open: function (event, ui) {

                //Reset email form and clear validation
                var validator = $product_form.validate();
                validator.resetForm();

                $product_form.find("[data-valmsg-replace]")
                .removeClass("field-validation-error")
                .addClass("field-validation-valid")
                .empty();

                //prepare clean form
                $productform.find("input#Manufacturer").val("");
                $productform.find("input#ContactName").val("");
                $productform.find("input#ContactEmailAddress").val("");
                $productform.find("input#ContactPhoneNumber").val("");
                $productform.find("textarea#Message").val("");
                $productform.find("input").removeClass("input-validation-error input-validation-pass");
                $productform.find("textarea").removeClass("input-validation-error input-validation-pass");
                $productform.find("div.message-block").removeClass("invalid validated").hide();
                $productSubmissionFormRecaptchaWarning.hide(); //$("#product_submission_recaptcha_warning").hide();
            }
        }); //end LinkForm Dialog Init 

        //Wire click event for product form buttons 
        $("#erg-menu-buttons").on("click", "span[data-productform]", function () {

            //Determine web address
            if (!window.location.origin) {
                window.location.origin = baseUrl;
            }

            $productform.dialog("open");
        });
        $("#erg-menu-buttons").on("keypress", "span[data-productform]", function (e) {
            if (e.which == 13) {
                $(this).click();
            }
        });

        //Resize the dialog box when the browswer window changes size
        $(window).resize(function () {
            $feedbackform.dialog("option", "position", "center");
            $linkform.dialog("option", "position", "center");
            $productform.dialog("option", "position", "center");
            $("#help-dialog").dialog("option", "width", $(window).width() * .90);
        });

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Initialize the help dialog
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _initHelpDialog = function () {

        var windowH = $(window).height();

        $("#help-dialog").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            height: "auto",
            maxHeight: $(window).height() * .80,
            overflow: scroll,
            title: "Search Help",
            width: $(window).width() * .90,
            show: {
                effect: "drop",
                duration: 500
            },
            hide: {
                effect: "drop",
                duration: 500
            },
            open: function (event, ui) {

                var $dialog = $(this);
                $dialog.css({ 'max-height': windowH * .80, 'overflow-y': 'auto' });
                $("html, body").css({ overflow: 'hidden' }); //prevent body from scrolling   
                $("#help-dialog").parents(".ui-dialog").css({ background: '#F0F4FE' });

            },
            beforeClose: function (event, ui) {
                $("html, body").css({ overflow: 'auto' }); //re-enable scrolling
            }
        }); //end Help Dialog Init

        $("#help-glyph").bind("click", function () {
            $("#help-dialog").dialog("open");
        });

        $("#help-glyph").bind("keypress", function (e) {
            e.preventDefault();
            if (e.which == 13) {
                $(this).click();
            }
            return false;
        });
    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Scroll back to the top of the results with a default animation time of 600 ms
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _scrollToTop = function (target) {

        $('body,html').animate({ scrollTop: $(target).offset().top - 5 }, 600);

    },

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Scroll back to the top of the results with a user provided animation period
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    _scrollToTopDelayed = function (target, delay) {

        $('body,html').animate({ scrollTop: $(target).offset().top - 5 }, delay);

    };

    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    // Reveal public methods
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    return {
        InitToastr: _initToastr,
        ShowLoadingIndicator: _showLoadingIndicator,
        HideLoadingIndicator: _hideLoadingIndicator,
        AjaxSubmital: _ajaxSubmital,
        InitAutoComplete: _initAutoComplete,
        SetSearchBy: _setSearchBy,
        InitHelpOptions: _initHelpOptions,
        InitSearchResultOptions: _initSearchResultOptions,
        InitResultOptions: _initResultOptions,
        InitKeyPressHandler: _initKeyPressHandler,
        InitSearchEffects: _initSearchEffects,
        InitImageCarousel: _initImageCarousel,
        HighlightTerms: _highlightTerms,
        InitWebMail: _initWebMail,
        InitHelpDialog: _initHelpDialog,
        InitPagingTitleAttr: _initPagingTitleAttr,
        InitPopoverTooltip: _initPopoverTooltip,
        Paging: _paging,
        ScrollToTop: _scrollToTop,
        ScrollToTopDelayed: _scrollToTopDelayed
    };

} ();

jQuery.fn.highlight=function(pat){function innerHighlight(node,pat){var skip=0;if(node.nodeType==3){var pos=node.data.toUpperCase().indexOf(pat);if(pos>=0){var spannode=document.createElement('span');spannode.className='highlight';var middlebit=node.splitText(pos);var endbit=middlebit.splitText(pat.length);var middleclone=middlebit.cloneNode(true);spannode.appendChild(middleclone);middlebit.parentNode.replaceChild(spannode,middlebit);skip=1;}}
else if(node.nodeType==1&&node.childNodes&&!/(script|style)/i.test(node.tagName)){for(var i=0;i<node.childNodes.length;++i){i+=innerHighlight(node.childNodes[i],pat);}}
return skip;}
return this.each(function(){innerHighlight(this,pat.toUpperCase());});};jQuery.fn.removeHighlight=function(){function newNormalize(node){for(var i=0,children=node.childNodes,nodeCount=children.length;i<nodeCount;i++){var child=children[i];if(child.nodeType==1){newNormalize(child);continue;}
if(child.nodeType!=3){continue;}
var next=child.nextSibling;if(next==null||next.nodeType!=3){continue;}
var combined_text=child.nodeValue+next.nodeValue;new_node=node.ownerDocument.createTextNode(combined_text);node.insertBefore(new_node,child);node.removeChild(child);node.removeChild(next);i--;nodeCount--;}}
return this.find("span.highlight").each(function(){var thisParent=this.parentNode;thisParent.replaceChild(this.firstChild,this);newNormalize(thisParent);}).end();};
/**
 *   Unslider by @idiot
 */
 
(function($, f) {
	//  If there's no jQuery, Unslider can't work, so kill the operation.
	if(!$) return f;
	
	var Unslider = function() {
		//  Set up our elements
		this.el = f;
		this.items = f;
		
		//  Dimensions
		this.sizes = [];
		this.max = [0,0];
		
		//  Current inded
		this.current = 0;
		
		//  Start/stop timer
		this.interval = f;
				
		//  Set some options
		this.opts = {
			speed: 500,
			delay: 3000, // f for no autoplay
			complete: f, // when a slide's finished
			keys: !f, // keyboard shortcuts - disable if it breaks things
			dots: f, // display ••••o• pagination
			fluid: f // is it a percentage width?,
		};
		
		//  Create a deep clone for methods where context changes
		var _ = this;

		this.init = function(el, opts) {
			this.el = el;
			this.ul = el.children('ul');
			this.max = [el.outerWidth(), el.outerHeight()];			
			this.items = this.ul.children('li').each(this.calculate);
			
			//  Check whether we're passing any options in to Unslider
			this.opts = $.extend(this.opts, opts);
			
			//  Set up the Unslider
			this.setup();
			
			return this;
		};
		
		//  Get the width for an element
		//  Pass a jQuery element as the context with .call(), and the index as a parameter: Unslider.calculate.call($('li:first'), 0)
		this.calculate = function(index) {
			var me = $(this),
				width = me.outerWidth(), height = me.outerHeight();
			
			//  Add it to the sizes list
			_.sizes[index] = [width, height];
			
			//  Set the max values
			if(width > _.max[0]) _.max[0] = width;
			if(height > _.max[1]) _.max[1] = height;
		};
		
		//  Work out what methods need calling
		this.setup = function() {
			//  Set the main element
			this.el.css({
				overflow: 'hidden',
				width: _.max[0],
				height: this.items.first().outerHeight()
			});
			
			//  Set the relative widths
			this.ul.css({width: (this.items.length * 100) + '%', position: 'relative'});
			this.items.css('width', (100 / this.items.length) + '%');
			
			if(this.opts.delay !== f) {
				this.start();
				this.el.hover(this.stop, this.start);
			}
			
			//  Custom keyboard support
			this.opts.keys && $(document).keydown(this.keys);
			
			//  Dot pagination
			this.opts.dots && this.dots();
			
			//  Little patch for fluid-width sliders. Screw those guys.
			if(this.opts.fluid) {
				var resize = function() {
					_.el.css('width', Math.min(Math.round((_.el.outerWidth() / _.el.parent().outerWidth()) * 100), 100) + '%');
				};
				
				resize();
				$(window).resize(resize);
			}
			
			if(this.opts.arrows) {
				this.el.parent().append('<p class="arrows"><span class="prev">←</span><span class="next">→</span></p>')
					.find('.arrows span').click(function() {
						$.isFunction(_[this.className]) && _[this.className]();
					});
			};
			
			//  Swipe support
			if($.event.swipe) {
				this.el.on('swipeleft', _.prev).on('swiperight', _.next);
			}
		};
		
		//  Move Unslider to a slide index
		this.move = function(index, cb) {
			//  If it's out of bounds, go to the first slide
			if(!this.items.eq(index).length) index = 0;
			if(index < 0) index = (this.items.length - 1);
			
			var target = this.items.eq(index);
			var obj = {height: target.outerHeight()};
			var speed = cb ? 5 : this.opts.speed;
			
			if(!this.ul.is(':animated')) {			
				//  Handle those pesky dots
				_.el.find('.dot:eq(' + index + ')').addClass('active').siblings().removeClass('active');

				this.el.animate(obj, speed) && this.ul.animate($.extend({left: '-' + index + '00%'}, obj), speed, function(data) {
					_.current = index;
					$.isFunction(_.opts.complete) && !cb && _.opts.complete(_.el);
				});
			}
		};
		
		//  Autoplay functionality
		this.start = function() {
			_.interval = setInterval(function() {
				_.move(_.current + 1);
			}, _.opts.delay);
		};
		
		//  Stop autoplay
		this.stop = function() {
			_.interval = clearInterval(_.interval);
			return _;
		};
		
		//  Keypresses
		this.keys = function(e) {
			var key = e.which;
			var map = {
				//  Prev/next
				37: _.prev,
				39: _.next,
				
				//  Esc
				27: _.stop
			};
			
			if($.isFunction(map[key])) {
				map[key]();
			}
		};
		
		//  Arrow navigation
		this.next = function() { return _.stop().move(_.current + 1) };
		this.prev = function() { return _.stop().move(_.current - 1) };
		
		this.dots = function() {
			//  Create the HTML
			var html = '<ol class="dots">';
				$.each(this.items, function(index) { html += '<li class="dot' + (index < 1 ? ' active' : '') + '">' + (index + 1) + '</li>'; });
				html += '</ol>';
			
			//  Add it to the Unslider
			this.el.addClass('has-dots').append(html).find('.dot').click(function() {
				_.move($(this).index());
			});
		};
	};
	
	//  Create a jQuery plugin
	$.fn.unslider = function(o) {
		var len = this.length;
		
		//  Enable multiple-slider support
		return this.each(function(index) {
			//  Cache a copy of $(this), so it 
			var me = $(this);
			var instance = (new Unslider).init(me, o);
			
			//  Invoke an Unslider instance
			me.data('unslider' + (len > 1 ? '-' + (index + 1) : ''), instance);
		});
	};
})(window.jQuery, false);
