/* Minification failed. Returning unminified contents.
(513,16-17): run-time error JS1014: Invalid character: `
(513,17-18): run-time error JS1195: Expected expression: <
(513,55-56): run-time error JS1195: Expected expression: <
(513,62-63): run-time error JS1014: Invalid character: `
(514,5-6): run-time error JS1002: Syntax error: }
(516,70-71): run-time error JS1004: Expected ';': {
(519,6-7): run-time error JS1195: Expected expression: )
(521,77-78): run-time error JS1004: Expected ';': {
(524,48-49): run-time error JS1014: Invalid character: `
(524,57-58): run-time error JS1193: Expected ',' or ')': $
(524,87-88): run-time error JS1004: Expected ';': {
(524,115-116): run-time error JS1004: Expected ';': $
(524,160-161): run-time error JS1014: Invalid character: `
(524,161-162): run-time error JS1195: Expected expression: )
(526,6-7): run-time error JS1195: Expected expression: )
(528,59-60): run-time error JS1195: Expected expression: )
(528,61-62): run-time error JS1004: Expected ';': {
(532,6-7): run-time error JS1195: Expected expression: )
(535,1-2): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
 */
// Angular JS App
var app = angular.module('AccApp', ['xeditable', 'ui.bootstrap', 'ngSanitize'])

app.directive('autoComplete', function ($timeout) {
    return function (scope, iElement, iAttrs) {
        iElement.autocomplete({
            minLength: 2,
            source: scope[iAttrs.uiItems],
            select: function () {
                $timeout(function () {
                    iElement.trigger('input');
                }, 0);
            }
        });
    };
});

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

app.directive('onLastRepeat', function () {
    return function (scope, element, attrs) {
        if (scope.$last) setTimeout(function () {
            toggleTermsLists(".topics-list", "a");
            toggleTermsLists(".keywords-list", "i");
        }, 1);
    };
});

app.filter('LibItemTopicsFilter', function () {
    return function (list, searchobj) {
        return list.filter(function (item) {
            var passes_filters = false,
                any_filter_set = false;

            for (topic in searchobj) {
                any_filter_set = any_filter_set || searchobj[topic];
                passes_filters = passes_filters || (searchobj[topic] && item.SelTopicsToString !== null && item.SelTopicsToString.length > 0 && item.SelTopicsToString.toLowerCase().indexOf(searchobj[topic].toLowerCase()) !== -1);
            }
            return !any_filter_set || passes_filters;
        });
    };
});

app.filter('LibItemTypeFilter', function () {
    return function (list, searchobj) {
        return list.filter(function (item) {
            var passes_filters = false,
                any_filter_set = false;

            for (type in searchobj) {
                any_filter_set = any_filter_set || searchobj[type];
                passes_filters = passes_filters || (searchobj[type] && item.Type === type);
            }
            return !any_filter_set || passes_filters;
        });
    };
});

app.filter('LibItemTagsFilter', function () {
    return function (list, searchobj) {
        return list.filter(function (item) {
            var passes_filters = false,
                any_filter_set = false;
            var selTags = JSON.parse(item.SelTagsJsonString);

            for (tag in searchobj) {
                any_filter_set = any_filter_set || searchobj[tag];
                passes_filters = passes_filters || (searchobj[tag] && selTags[tag]);
            }
            return !any_filter_set || passes_filters;
        });
    };
});

app.filter('LibItemTypeIdFilter', function () {
    return function (list, searchobj) {
        return list.filter(function (item) {       

            return !searchobj || item.Type === searchobj;
        });
    };
});

app.filter('LibItemTagIdFilter', function () {
    return function (list, searchobj) {
        return list.filter(function (item) {

            var selTags = JSON.parse(item.SelTagsJsonString);

            return !searchobj || selTags[searchobj];
        });
    };
});


//************** Library *****************
app.controller('LibraryCtrl', ['$scope', '$uibModal', '$http', '$filter', 'orderByFilter', 'limitToFilter', function ($scope, $uibModal, $http, $filter, orderByFilter, limitToFilter) {
    $scope.itemsSortField = '-DateAdded';
    $scope.myTagsLimit = 5;
    $scope.myItemsLimit = 10;

    //instantiate for better performance
    $scope.myTags = [];
    $scope.myItems = [];


    $scope.searchTags = {};
    $scope.searchType = {};
    $scope.searchTopics = [];

    $scope.selectedItemsForDelete = [];


    $scope.topics = ["Acute Coronary Syndromes", "Arrhythmias and Clinical EP", "Cardiac Biomarkers", "Cardiothoracic Surgery", "Congenital Heart Disease and Pediatric Cardiology", "Geriatric", "Heart Failure and Cardiomyopathies", "Noninvasive Imaging", "Anticoagulation Management", "Invasive CV Angio and Interventions", "Pericardial Disease", "Prevention", "Pulmonary Hypertension and Venous Thromboembolic", "Sleep Apnea", "Sports and Exercise", "Stable Ischemic Heart Disease", "Standard ECG and Stress Testing", "Valvular Heart Disease", "Vascular Medicine", "Atrial Fibrillation", "Catheter Ablation", "Electrocardiogram", "Cardiac Rhythm Management", "Cardiometabolic", "Dyslipidemia", "Chronic Angina"];


    $scope.isEmpty = function (obj) {
        for (var i in obj) if (obj.hasOwnProperty(i)) return false;
        return true;
    };

    $scope.retrieveLibraryTags = function () {
        $http.get("/api/library/member/tags")
            .then(function (res) {
                $scope.myTags = angular.fromJson(res.data);
            });
    };
    $scope.retrieveLibraryItems = function () {
		
        $http.get("/api/library/member/items")
            .then(function (res) {
                $scope.myItems = angular.fromJson(res.data);
                if ($scope.myItems.length === 0)
                { $(notfoundmsg).show(); }
                $(loading).hide();
            });
       

    };

    
    $scope.retrieveLibraryTags();
    $scope.retrieveLibraryItems();
    
    $scope.addSearchTopic = function () {
        if ($scope.searchTopics.indexOf($scope.sTopic) === -1) {
            $scope.searchTopics.push($scope.sTopic);
        }
        $scope.sTopic = '';
    };

    $scope.removeSearchTopic = function (topic) {
        var index = $scope.searchTopics.indexOf(topic);
        if (index > -1) {
            $scope.searchTopics.splice(index, 1);
        }
    };

    $scope.toggleSelectionForDelete = function (itemId) {
        var idx = $scope.selectedItemsForDelete.indexOf(itemId);

        if (idx > -1) {
            $scope.selectedItemsForDelete.splice(idx, 1);
            $scope.selectAll = false;
        }
        else {
            $scope.selectedItemsForDelete.push(itemId);
        }
    };

    $scope.selectDeselectAll = function () {
        var fItems = limitToFilter(orderByFilter($filter('LibItemTopicsFilter')($filter('LibItemTypeFilter')($filter('LibItemTagsFilter')($scope.myItems, $scope.searchTags), $scope.searchType), $scope.searchTopics), $scope.itemsSortField), $scope.myItemsLimit);
        $scope.selectedItemsForDelete = [];

        if ($scope.selectAll === true) {
            fItems.forEach(function (elem) {
                if(!elem.IsExternal)
                    $scope.selectedItemsForDelete.push(elem.Id);
            });
        }
      
    };

    $scope.orderFn = function (tag) {
        var fItems = $filter('LibItemTopicsFilter')($filter('LibItemTypeFilter')($filter('LibItemTagIdFilter')($scope.myItems, tag.Id), $scope.searchType), $scope.searchTopics);
        return fItems.length;
    }

    $scope.deleteSelected = function () {
        var index;

        $scope.selectedItemsForDelete.forEach(function (itemIndex) {
            for (var i = 0; i < $scope.myItems.length; i++) {

                if ($scope.myItems[i]["Id"] === itemIndex) {
                    index = i;
                    //ws delete
                    var item = {
                        Id: itemIndex
                        //SelTags: $scope.selTags
                    };
                    var delObj = JSON.stringify(item);

                    $http.post("/api/library/item/delete", delObj)
                    .then(function (data) {
                        if (data.statusText === 'OK') {
                            //$('#assign-tags-msg').show();
                            $scope.myItems.splice(index, 1);
                        } else {
                            //        $scope.messages = 'Oops, we received your request, but there was an error.';
                            console.log('Request received, but with errors (data): ' + data);
                        }
                    });
                }
            }
        });

        $scope.selectedItemsForDelete = [];
    };

    $scope.deleteAllSelected = function () {
        var delObj = JSON.stringify($scope.selectedItemsForDelete);

        $http.post("/api/library/items/delete", delObj)
            .then(function (res) {
            if (res.data === true) {
                $scope.selectedItemsForDelete = [];
                $scope.retrieveLibraryItems();
                $scope.selectAll = false;
            } else {
                console.log('Request received, but with errors (data): ' + data);
            }
        });
    };

    $scope.editMyTags = function () {
        $uibModal.open({
            templateUrl: 'tagsModalContent.html',
            backdrop: true,
            windowClass: 'modal',
            resolve: {
                jsonObj: function () {
                    return $scope;
                }
            },
            controller: 'ModalEditTagsInstanceCtrl'
        }).result.then(
            function () { $scope.retrieveLibraryItems(); $scope.retrieveLibraryTags(); },
            function () { $scope.retrieveLibraryItems(); $scope.retrieveLibraryTags(); });
    };

    $scope.assignTags = function (itemId, sel, isExternal) {
        var selTags = JSON.parse(sel);

        $uibModal.open({
            templateUrl: 'assignTagsModalContent.html',
            backdrop: true,
            windowClass: 'modal',
            resolve: {
                jsonObj: function () {
                    $scope.itemId = itemId;
                    $scope.selTags = selTags;
                    $scope.isExternal = isExternal;
                    return $scope;
                }
            },
            controller: 'ModalAssignTagsInstanceCtrl'
        }).result.then(
            function () { $scope.retrieveLibraryItems(); },
            function () { $scope.retrieveLibraryItems(); });

    };
}]);

app.controller('ModalEditTagsInstanceCtrl', ['$scope', '$uibModalInstance', '$http', 'jsonObj', function ($scope, $uibModalInstance, $http, jsonObj) {

    $scope.myTags = jsonObj.myTags;

  
    
    $scope.checkName = function (data, id) {
        if (data === '') {
            return "Tag name is required!";
        }
    };

    $scope.saveTag = function (data, id) {
        var tag = {
            id: id,
            name: data.name
        };
        var saveObj = JSON.stringify(tag);

        $('.update-mytags-spinner-' + id).show();
        $http.post("/api/library/member/tag/update", saveObj).then(function (res) {
            var resTagId = angular.fromJson(res.data.d);
           

            $http.get("/api/library/member/tags")
            .then(function (res) {
                var myTags = angular.fromJson(res.data);
                $scope.myTags = myTags;
            });
            
            $('.update-mytags-spinner-' + id).hide();
            return resTagId !== 0;
        });
    };


    $scope.removeTag = function (index, id) {
        var tag = {
            id: id
        };
        var delObj = JSON.stringify(tag);

        $('.update-mytags-spinner-' + id).show();
        $http.post("/api/library/member/tag/delete", delObj).then(function (res) { 
            for (var i = 0; i < $scope.myTags.length; i++) {
                if ($scope.myTags[i].Id === id) {
                    $scope.myTags.splice(i, 1);
                    break;
                }
            }
            $('.update-mytags-spinner-' + id).hide();
        });
    };


    $scope.addTag = function () {
        $scope.inserted = {
            id: '0',
            Name: ''
        };

        $scope.myTags.push($scope.inserted);
    };


    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
}]);


app.controller('ModalAssignTagsInstanceCtrl', ['$scope', '$uibModalInstance', '$http', 'jsonObj', function ($scope, $uibModalInstance, $http, jsonObj) {

    $scope.myTags = jsonObj.myTags;
    $scope.itemId = jsonObj.itemId;
    $scope.selTags = jsonObj.selTags;
    $scope.isExternal = jsonObj.isExternal;

    $scope.ok = $scope.submit = function () {
        var tags = {
            Id: $scope.itemId,
            SelTags: $scope.selTags,
            IsExternal: $scope.isExternal
        };
        var saveObj = JSON.stringify(tags);

        $http.post("/api/library/item/update-tags", saveObj )
            .then(function (data) {
                if (data.statusText === 'OK') {
                    

                    $('#assign-tags-msg').show();
                    $uibModalInstance.dismiss('cancel');
                } else {
                    console.log('Request received, but with errors (data): ' + data);
                }
            });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
}]);


;
// iOS 7 hack: Add an optgroup to every select in order to avoid truncating the content
//$(document).ready(function () {
//    if (navigator.userAgent.match(/(iPad|iPhone|iPod touch);.*CPU.*OS 7_\d/i)) {
//        var selects = document.querySelectorAll("select");
//        for (var i = 0; i < selects.length; i++) {
//            selects[i].appendChild(document.createElement("optgroup"));
//        }
//    }
//});


//jquery UI helpers
// on window resize run function
$(window).resize(function () {
    fluidDialog();
});
// catch dialog if opened within a viewport smaller than the dialog width
$(document).on("dialogopen", ".ui-dialog", function (event, ui) {
    fluidDialog();
});
function fluidDialog() {
    var $visible = $(".ui-dialog:visible");
    // each open dialog
    $visible.each(function () {
        var $this = $(this);
        var dialog = $this.find(".ui-dialog-content").data("ui-dialog");
        // if fluid option == true
        if (dialog.options.fluid) {
            var wWidth = $(window).width();
            // check window width against dialog width
            if (wWidth < (parseInt(dialog.options.maxWidth) + 50)) {
                // keep dialog from filling entire screen
                $this.css("max-width", "100%");
            } else {
                // fix maxWidth bug
                $this.css("max-width", dialog.options.maxWidth + "px");
            }
            //reposition dialog
            dialog.option("position", dialog.options.position);
        }
    });

}

function RearrangeSearchFacet() {
    $(".coveo-facet-search").each(function () {
        var parent = $(this).parent();
        var values = $(parent).find(".coveo-facet-values");
        $(this).after(values);

        $(values).find(".coveo-facet-value").each(function (i, v) {
            var selected = $(v).hasClass("coveo-selected");
            console.log($(v).attr("data-value") + ": " + selected);
            if (!selected) {
                console.log($(v).attr("data-value") + " is good to be removed");
                $(v).remove();
            }
            if ($(v).hasClass("coveo-no-state")) {
                UpdateFacetSearch(parent);
            }
        });

    });
}

function UpdateFacetSearch(facet) {
    var href = location.href;
    location.hash = "";
    location.href = href;
}

$(document).ready(function () {
    $(".CoveoSearchInterface").on('beforeInitialization', function () {
    });

    $(".CoveoSearchInterface").on("afterInitialization", function () {
        RearrangeSearchFacet();

        $(this).on("deferredQuerySuccess", function () {
            RearrangeSearchFacet();
        });
    });
    $(".CoveoSearchInterface").on("noResults", function () {
        $(".coveo-summary-section").hide();
        $(".coveo-sort-section").hide();
        $(".coveo-results-header").append("<span class='custom-message'>Your query did not match any documents.</span>");
    });
    $(".CoveoSearchInterface").on("preprocessResults", function () {
        $(".coveo-summary-section").show();
        $(".coveo-sort-section").show();
        $(".custom-message").remove();
        $("[data-title='Filter by Topic'] input").attr("placeholder", "Search in Filter by Topic");

        $(".coveo-dynamic-facet-header-btn.coveo-dynamic-facet-header-clear").each(function (i, ctl) {
            $(ctl).html("show all");
        });

        $(".CoveoDynamicFacet").each(function (i, ctl) {
            var numOfValues = $(ctl).attr("data-number-of-values");
            var isMoreLessEnabled = $(ctl).attr("data-enable-more-less");
            var enabledFacetSearch = $(ctl).attr("data-enable-facet-search");
            if (numOfValues === "1" && isMoreLessEnabled === "false" && enabledFacetSearch === "true") {
                $(ctl).addClass("enabled-facet-search");
            }
        });

        //Move count along with facet label 
        setTimeout(function () {
            $(".coveo-checkbox-label").each(function () {
                var label = $(this).find(".coveo-checkbox-span-label");
                $(this).find(".coveo-checkbox-span-label-suffix").appendTo(label);
            });
        }, 100);
       
    });

    var queryFirstResult = 1;
    var totalResultCount = 0;

    function getSpan(value) {
        return `<span class='coveo-highlight'>${value}</span>`;
    }

    $(".CoveoSearchInterface").on("querySuccess", function (e, args) {
        totalResultCount = args.results.totalCount;
        queryFirstResult = args.query.firstResult + 1;
    });

    $(".CoveoSearchInterface").on('newResultsDisplayed', function (e, args) {
        if (Coveo.$(".CoveoPager").length === 0) {
            var result = e.target.lastChild.children;
            Coveo.$(".CoveoQuerySummary").html(`Results ${getSpan(queryFirstResult)}-${getSpan(result.length)} of ${getSpan(totalResultCount.toLocaleString())}`);
        }
    });

    $('.CustomFacet .facet-toggle').on('click', function () {
        var $customFacet = $(this).closest('.CustomFacet');
        $customFacet.toggleClass('facet-collapsed');
        $customFacet.find('.facet-toggle').toggle();
    });

});
;
//tooltips
$(document).ready(function () {
    if ($(".question-circle").length > 0) {
        $(".question-circle").tooltip({
            trigger: 'click focus'
        });
    }
    $(".nav-tooltip").tooltip({
        trigger: 'hover'
    });
    $('body').on('click touchstart', function (e) {
        $('[data-toggle="tooltip"]').each(function () {
            //the 'is' for buttons that trigger popups
            //the 'has' for icons within a button that triggers a popup
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.tooltip').has(e.target).length === 0) {
                $(this).tooltip('hide');
            }
        });
    });
});

//toggles search filters open and closed in tablet and smaller viewports
//after they are responsively hidden at top of main content area
function toggleFilters(parentContainer) {
    $("#filter-toggle").on("click", function (e) {
        var facetContainer = $(this).parents(parentContainer);
        if (facetContainer.hasClass('show-filters')) {
            facetContainer.removeClass('show-filters');
        } else {
            facetContainer.addClass('show-filters');
        }
    });
}

//toggles keyword and terms lists in articles if more than 4 exist
//in listings and on homepage featured journal article
function toggleTermsLists(parentContainer, itemWrapper, moreLabel) {
    topicCountTarget = 4;
    parentContainer = typeof parentContainer !== 'undefined' ? parentContainer : '.topics-list';
    itemWrapper = typeof itemWrapper !== 'undefined' ? itemWrapper : 'a';
    moreLabel = typeof moreLabel !== 'undefined' ? moreLabel : 'more';
    $(parentContainer).each(function () {
        var topicCount = $(this).find(itemWrapper).length;
        //count the number of authors (wrapped in whatever) and add a "more-link if there are more than 4
        if (topicCount >= topicCountTarget) {
            if (!$(this).hasClass('more-toggle-active')) {
                $(this).addClass('more-toggle-active');
                $(this).append('<button class="button-as-link more-link">' + moreLabel + '</button>');
                $(".more-link").on('click touchstart', function (e) {
                    e.preventDefault();
                    $(this).parents(parentContainer).addClass('show-all');
                });
            }
        }
    });
}

//select/deslect all checkboxes within a common parent
function toggleSelectAllResults(trigger, targetParent) {
    $(trigger).on('click touchstart', function (event) {
        event.preventDefault();
        // find all the checkboxes and select them
        $(this).parents(targetParent).find('input:checkbox').attr('checked', 'checked');
    });
}

//back to listing
$(document).ready(function () {
    var pghistorylen = history.length - 1; // page load history length
    $(".back-to-listing").each(function () {
        if (document.referrer.indexOf(location.protocol + "//" + location.host) === 0) {
            //retain filters on go back to listing
            $(this).on('click', function () {
                history.go(pghistorylen - history.length);
                return false;
            })
        }
        else {
            $(this).addClass('hide-element');//hide back to listing link
            //check if anythign else exists in lvl2-masthead and hide if not.
            var siblingElements = $(this).siblings();
            //console.log("elements" + siblingElements);
            if (siblingElements.length == 0) {
                $(this).parent('#lvl2-masthead').addClass('masthead-empty');
            }
        }
    })
});

$(document).ready(function () {
    $('#print-page').on('click touchstart', function (event) {
        window.print();
    });
});

function iCalLink(id) {
    //alert("id : " + id);
    //$.get("/api/Calendar/Index/"+id, function(data){alert('success!');});
    window.location = "/wapi/Calendar/Index/" + id;
}

function removeEmpties(emptyElement) {
    $(emptyElement).each(function () {
        if (jQuery.trim($(this).text()) == "") $(this).remove();
    });
};
// JavaScript source code
$(document).ready(function () {//resize events
    $('body').removeClass('no-js');
    // set variables
    var resizeBrowserWidth;
    var resizeTimeout;
    // check width on load
    var resizeBrowserWidth = $(window).width();
    testWidth(resizeBrowserWidth);
    // test width on resize (timeout keeps browser from going crazy)
    $(window).resize(function () {
        var resizeBrowserWidth = $(window).width();
        resizeTimeout = setTimeout(function () {
            testWidth(resizeBrowserWidth);
        }, 200);
        //scrollFeaturedContent();
    });
    // add class to body based on viewport, move stuff around
    function testWidth(resizeBrowserWidth) {
        $('body').removeClass("small-viewport medium-viewport");
        $('#nav-utility').appendTo('#nav-utility-holder');
        if (resizeBrowserWidth <= 674) {//handheld
            $('body').addClass('small-viewport');
            $('#nav-utility').prependTo('#nav-utility-handheld');
            $('#sidebar .my-section-container').insertAfter('#main-content .feature-tabs');
            $('#sidebar .featured-article').insertAfter('#main-content .feature-tabs');
            $('#sidebar .find-guideline').insertAfter('#main-content .feature-tabs');
            $('#sidebar .recommended-for-you').prependTo('#sidebar');
            $('#my-library-layout #sidebar').prependTo('#my-library-layout');
            $('#my-notifications-layout #sidebar').prependTo('#my-notifications-layout');
        } else if (resizeBrowserWidth <= 980) {//tablet
            $('body').removeClass('small-viewport large-viewport');
            $('body').addClass('medium-viewport');
            $('#nav-utility').prependTo('#nav-utility-handheld');
            $('#sidebar .my-section-container').insertAfter('#main-content .feature-tabs');
            $('#sidebar .featured-article').insertAfter('#main-content .feature-tabs');
            $('#sidebar .find-guideline').insertAfter('#main-content .feature-tabs');
            $('#sidebar .recommended-for-you').prependTo('#sidebar');
            $('#my-library-layout #sidebar').prependTo('#my-library-layout');
            $('#my-notifications-layout #sidebar').prependTo('#my-notifications-layout');

        } else if (resizeBrowserWidth > 980) {// greater than tablet (undo the other stuff)
            $('body').addClass('large-viewport');
            $('body').removeClass('small-viewport');
            $('#nav-primary-holder li').removeClass("active");//we don't want navs to stay open here.
            $('#main-content .my-section-container').prependTo('#sidebar');
            $('#main-content .featured-article').prependTo('#sidebar');
            $('#main-content .find-guideline').prependTo('#sidebar');
            $('#my-library-layout #sidebar').insertAfter('#main-content');
            $('#my-notifications-layout #sidebar').insertAfter('#main-content');
        }
    }
});;
//Main Nagivation
var bfNav = {
    navItems: undefined,
    navObjects: [],
    activeObj: undefined,
    init: function () {
        var that = this;
        this.navItems = $('#nav-primary > li');
        this.buildNavObjects();
    },
    buildNavObjects: function () {
        var that = this;
        this.navItems.each(function () {
            that.navObjects.push(new NavObject($(this)));
        })
    }
}

function NavObject(el) {
    this.parent = bfNav;
    this.el = el;
    this.active = false;
    var that = this;
    this.el.hover(function () {
        $(this).addClass("bfHover");
    }, function () {
        $(this).removeClass("bfHover");
    })
    this.el.find("> a").on("touchstart", function (e) {
        if (!$('body').hasClass('nav-active')) {
            e.preventDefault();
            if (that.active) {
                var targetURL = $(this).attr('href');
                window.location = targetURL;
                that.toggleActive(false);
            } else {
                that.toggleActive(true);
            }
        }
    })
    this.el.find("a[href*='#theme']").on("touchstart click", function () {//this is just for the "Latest in Cardiology" subnavs which are really just search facet triggers
        console.log(this);
        if ($(this).parents('.header-latest.current').length != 0) {
            var clickedText = $(this).text();//get the label
            that.toggleActive(false);//close the subnav when subitem is clicked
            $("#lvl2-masthead > h1 span").remove();//remove label from page heading, if present
            $("#lvl2-masthead > h1").append("<span>: " + clickedText + "</span>");//append clicked title to page heading
        }
    })
    this.el.find(".panel-close").on("click", function () {
        that.toggleActive(false);
    })
}

NavObject.prototype.toggleActive = function (active) {
    this.active = active;
    if (active) {
        this.el.addClass("bfHover");
        $("#nav-primary").addClass("nav-active");
        if (this.parent.activeObj) {
            this.parent.activeObj.toggleActive(false);
        }
        this.parent.activeObj = this;
    } else {
        this.el.removeClass("bfHover");
        $("#nav-primary").removeClass("nav-active");
        this.parent.activeObj = undefined;
    }
}

$(document).ready(function () {
    if (!$('body').hasClass('small-viewport medium-viewport')) {
        bfNav.init();
    }
});
//end Main Navigation

//Toggle functions for nav buttons that appear only at smaller responsive screen sizes
var navToggle = {
    active: undefined,
    view: {
        body: 'body',
        holder: '#nav-primary-holder',
        mask: '#page-mask',
        toggles: [
			{
			    el: '#header-mobile-trigger',
			    activeClass: 'nav-active'
			},
			{
			    el: '#header-search-trigger',
			    activeClass: 'search-active'
			},
			{
			    el: '#nav-myacc .header-myacc',
			    activeClass: 'myacc-active'
			},
			{
			    el: '#nav-myacc .header-myacc-noti',
			    activeClass: 'notification-active'
			}
        ]
    },
    buildView: function () {
        for (var key in this.view) {
            if (key == "toggles") {
                for (var i = 0; i < this.view.toggles.length; i++) {
                    this.view.toggles[i].el = $(this.view.toggles[i].el);
                }
            } else {
                this.view[key] = $(this.view[key]);
            }
        }
    },
    setHandlers: function () {
        var that = this;
        for (var i = 0; i < this.view.toggles.length; i++) {
            (function (index) {
                that.view.toggles[index].el.on("click", function () {
                    that.toggleActive(index);
                    if ($(this).hasClass('header-myacc-noti')) {//Clear the MyACC notification flag on click, should also mark notifications as "read" in sitecore
                        $(this).addClass('clear-alert');
                    }
                })
            })(i)
        }
        this.view.mask.on("click", function () {
            that.toggleActive(that.active);
        })
    },
    toggleActive: function (which) {
        if (this.active !== undefined) {
            this.view.body.removeClass(this.view.toggles[this.active].activeClass);
        }
        if (which != this.active) {
            this.active = which;
            this.view.body.addClass(this.view.toggles[this.active].activeClass);
            this.view.body.addClass("mask-active");
        } else {
            this.active = undefined;
            this.view.body.removeClass("mask-active");
        }
    },
    init: function () {
        this.buildView();
        this.setHandlers();
    }
}

$(document).ready(function () {
    navToggle.init();
});

function addNavToggles(whatNav) {
    $(whatNav + ' li:has("ul")').prepend('<span class="toggler"></span>');//add toggle to any item having children
    $('#nav-secondary li.current').addClass('active');
    $(whatNav + ' li .toggler').on('click', function (e) {
        e.preventDefault();
        $(this).parent('li').toggleClass('active');
    });
    $(whatNav + ' > li > .toggler').on('click', function () {
        $('body').toggleClass('dyn-nav-height');
    });
}

$(document).ready(function () {//add manual toggle switches for nested nav items	
    addNavToggles('#nav-primary');
    addNavToggles('#nav-secondary');
});

$(document).ready(function () {//add manual toggle switches for nested nav items	
    if ($('#results-within-guidelines')) {
        $('#results-within-guidelines .article-content h1').prepend('<button class="toggler"></button>');
        $('#results-within-guidelines .article-content h1 button').on('click', function () {
            $(this).parents('.article-tease').toggleClass('active');
        });
    }
});

$(document).ready(function () {//topc select in site search
    $("#searchDropdownBox").change(function () {
        var displayText = $(this).find("option:selected").attr("title");
        $("#nav-search-in-content").text(displayText);
    });
});;
//These are the "+" content navs as seen on Clinical Topics landing page

$(document).ready(function () {
    MakePlainAccordions();
});

function MakePlainAccordions() {
    $(".collapse-box").each(function () {
        if (!$(this).children().hasClass("accordion-control")) {
            $(this).data("AccordionGroup", new AccordionGroup(this).toggleActive());
        }
    })
}

function AccordionGroup(container) {
    this.accordionControls = $(container).find(".collapse-box-heading");
    this.accordionContents = $(container).find(".collapse-box-content");
    this.active = undefined;
    var that = this;
    //only add a button if there are children to expose AND we have not added any previous triggers
    if (!(this.accordionContents.length == 0) && !(this.accordionControls.has('button.trigger').length)) {
        this.accordionControls.prepend("<button class='trigger'></button>");//need a button so top level text can still link
        this.accordionControls.find(".trigger").on("click", function () {
            that.toggleActive($(this).index());
        })
    }
}

AccordionGroup.prototype.toggleActive = function (active) {
    var controls = this.accordionControls;
    var contents = this.accordionContents;
    controls.eq(this.active).add(contents.eq(this.active)).add(controls.eq(active)).add(contents.eq(active)).toggleClass("active");
    this.active = active;
};
//HEROSPACE THREE-UP IMAGES
var heroCtrl = {
    position: undefined,
    view: {
        slides: [],
        wrapper: undefined,
        cont: undefined,
        dirNav: {
            next: undefined,
            prev: undefined
        }
    },
    transitionSupport: (function () {
        var s = document.createElement('div').style;
        return ('transition' in s || 'webkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s);
    })(),
    goTo: function (index) {
        this.position = index;
        this.view.cont.removeClass("active-slide-0 active-slide-1 active-slide-2").addClass("active-slide-" + index);
        this.showNav();
    },
    showNav: function () {
        this.position > 0 ? this.view.dirNav.prev.show() : this.view.dirNav.prev.hide();
        if (this.view.slideFull) {
            this.position < this.view.slides.length - 1 ? this.view.dirNav.next.show() : this.view.dirNav.next.hide();
        } else {
            this.position < this.view.slides.length - 2 ? this.view.dirNav.next.show() : this.view.dirNav.next.hide();
        }
    },
    next: function () {
        if (this.view.slideFull) {
            if (this.position == this.view.slides.length - 1) {
                return this.position;
            } else {
                return this.position + 1;
            }
        } else {
            if (this.position == this.view.slides.length - 2) {
                return this.position;
            } else {
                return this.position + 1;
            }
        }
    },
    prev: function () {
        if (this.view.slideFull) {
            if (!this.position) {
                return this.position;
            } else {
                return this.position - 1;
            }
        } else {
            if (!this.position) {
                return this.position;
            } else {
                return this.position - 1;
            }
        }
    },
    buildView: function () {
        this.view.wrapper = $("#featured-content-outerwrap");
        this.view.cont = this.view.wrapper.find("#featured-content-innerwrap");
        var dirNav = this.view.wrapper.find("#featured-content-controls");
        this.view.dirNav.next = dirNav.find("#featured-content-next");
        this.view.dirNav.prev = dirNav.find("#featured-content-prev");
        this.view.slides = this.view.cont.find(".featured-tease");
        this.getSlideSize();
    },
    getSlideSize: function () {
        //some smartphones are reporting the wrapper as 1px larger than first slide
        if (this.view.wrapper.outerWidth() - this.view.slides.first().outerWidth() <= 1) {
            this.view.slideFull = true;
        } else {
            this.view.slideFull = false;
        }
    },
    setHandlers: function () {
        var that = this;
        $(window).resize(function () {
            that.getSlideSize();
        });
        this.view.dirNav.next.on("click", function () {
            that.goTo(that.next());
        })
        this.view.dirNav.prev.on("click", function () {
            that.goTo(that.prev());
        })
        this.view.slides.each(function (index) {
            $(this).swipe({
                swipeLeft: function (e) {
                    e.preventDefault();
                    that.goTo(that.next());
                },
                swipeRight: function (e) {
                    e.preventDefault();
                    that.goTo(that.prev());
                },
                allowPageScroll: "vertical"
            })
        })
    },
    init: function () {
        this.buildView();
        this.setHandlers();
        this.goTo(0);
    }
}

$(function () {
    heroCtrl.init();
});
