/**
 * Navigatable tabs
 */
$.fn.navTabs = function(options) {

    return this.each(function(index, el) {

        var selectedTab = $(el).find(".depth0:has(.selected)");

        if (selectedTab.length) {

            $(selectedTab).addClass("selected");
        }
        else if ($(el).find(".depth0.selected").length == 0) {

            $(el).find(".depth0").first().addClass("selected");
        }
    });
};

$(function(){

    // Show/hide download pop-up for links with "popMeUp-*" class (the "*" part is the target ID to load)

    var popupCache = [];

    // Yuk! Refactor this!

    $('a[class^="popMeUp-"]').click(function() {

        var href = this.href,
            splitOffset = this.className.indexOf(" "),
            idToInject = (splitOffset > 0) ? this.className.substring(8, splitOffset) : this.className.substring(8);  // 8 is the offset after "popMeUp-"

        var handleShowPopup = function() {

            $(popupCache[href]).find("a, input").first().focus();  // slightly more accessible
        };

        if (!popupCache[href]) {

            popupCache[href] = $('<div class="popup">');
            popupCache[href].load(href + " #" + idToInject, null, function() {

                popupCache[href].append('<button class="linkButton close">Lukk</button>');
                popupCache[href].appendTo('body');
                popupCache[href].lightbox_me({ centered: true, onLoad: handleShowPopup });
            });
        }
        else {

            popupCache[href].lightbox_me({ centered: true, onLoad: handleShowPopup });
        }

        return false;
    });

    // Nav tabs (non-jquery; better accessbility)

    $(".navTabs").navTabs();

    // Tabs (in DLR pages; kompetansemål lists)

    $(".tabs").tabs();

    // Remove trailing slash from faceted search breadcrumbs

    $("#block-faceted_search_ui-1_current span:last-child").remove();

    // Filtering widgets

    try {

        $(".exposed-widget-filter .filterTitle").replaceWith(function () {

            return("<button class='filterTitle linkButton'>" + $(this).text() + "</button>");
        });
    }
    catch (e) {

        // Strange jQuery bug? Matching window for replacement if no other match (i.e. not good)
    }

    $(".exposed-widget-filter .filterTitle").click(function() {


        $(".exposed-widget-filter .filterTitle.open").not(this).click();
        $(this).parent().find(".filterBy-content").slideToggle("fast");
        $(this).toggleClass("open");

        return false;
    });

    var checkChildNodes = function() {

        var $this = $(this);

        $this.
            parent().
            parent().
            find("input[type='checkbox']").
            not(this).
            attr("checked", $this.attr("checked")).
            attr("disabled", $this.attr("checked"));
    };

    $(".exposed-widget-filter input[type='checkbox']").click(checkChildNodes);
    $(".exposed-widget-filter input[type='checkbox']:checked").
        each(checkChildNodes).
        parents(".filterBy").
        siblings(".filterTitle").
        addClass("active");

    // Sort <button> maddness... this needs refactoring

    $(".sort_byWidget button[type='submit']").click(function() {

        $("input[type='hidden'][name='sort_by']").remove();

        if ($.browser.msie && ($.browser.version == "6.0" || $.browser.version == "7.0")) {

            // IE 6 & 7 don't submit <button>s correctly -- yep, this is atrocious

            $(this).val(($(this).val() == "Nyeste") ? "created" :
                            ($(this).val() == "Forlag") ? "title_1" : "title");

            this.style.visibility = "hidden";  // ... and jQuery doesn't work for this...!
        }
    });

    // Frontpage coverslide

    $(".slideshow").coverslide({ startAt: 1 }).each(function() {

        var $carousel = $(this),
            secondsLimit = 10,
            secondsGracePeriod = 4,
            secondsElapsed = 0,
            stopped = false,
            timer;

        timer = setInterval(function() {

            var $next;

            if (stopped) return;
            ++secondsElapsed;

            if (secondsElapsed >= secondsLimit) {

                $next = $carousel.children(".ui-coverslide-stack-active").next();

                if (!$next.length) {

                    $next = $carousel.children().first();
                }

                $next.click();
                secondsElapsed = 0;
            }

        }, 1000);

        $carousel.hover(function() {

            stopped = true;

        }, function() {

            stopped = false;

            if ((secondElapsed + secondsGracePeriod) >= secondsLimit) {

                secondsElapsed = secondsLimit - secondsGracePeriod;
            }
        });
    });
});

