/* Minification failed. Returning unminified contents.
(123,16-17): run-time error JS1014: Invalid character: `
(123,17-18): run-time error JS1195: Expected expression: <
(123,55-56): run-time error JS1195: Expected expression: <
(123,62-63): run-time error JS1014: Invalid character: `
(124,5-6): run-time error JS1002: Syntax error: }
(126,70-71): run-time error JS1004: Expected ';': {
(129,6-7): run-time error JS1195: Expected expression: )
(131,77-78): run-time error JS1004: Expected ';': {
(134,48-49): run-time error JS1014: Invalid character: `
(134,57-58): run-time error JS1193: Expected ',' or ')': $
(134,87-88): run-time error JS1004: Expected ';': {
(134,115-116): run-time error JS1004: Expected ';': $
(134,160-161): run-time error JS1014: Invalid character: `
(134,161-162): run-time error JS1195: Expected expression: )
(136,6-7): run-time error JS1195: Expected expression: )
(138,59-60): run-time error JS1195: Expected expression: )
(138,61-62): run-time error JS1004: Expected ';': {
(142,6-7): run-time error JS1195: Expected expression: )
(145,1-2): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
 */
var app = angular.module('AccApp', ['xeditable', 'ui.bootstrap', 'ngSanitize'])

// 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();
});
