(function($) {
    
    $.fn.disableSelection = function() { 
        this.each(function() { 
            this.onselectstart = function() { return false; }; 
            this.unselectable = "on"; 
            $(this).css('-moz-user-select', 'none'); 
        });
    }
    
    $.fn.equalizeHeights = function() {
        var maxHeight = 0;
        $(this).each(function() {
            var item = $(this);
            if (item.length > 0) {
                maxHeight = Math.max(item.height(), maxHeight);
            }
        }).height(maxHeight);
    }
    
    $.fn.banner = function() {
        $(this).each(function() {
            var banner = $(this);
            banner.disableSelection();
            var slides = $(".carousel-item", banner).css("left", "940px");
            if (slides.length > 0) {
                // Activate the slideshow.
                slides.eq(0).css("left", "0");
                var frame = 0;
                var height = 1;
                function nextSlide() {
                    slides.eq(frame % slides.length).animate({
                        "left": "-941px"
                    });
                    frame += 1;
                    slides.eq(frame % slides.length).css("left", "940px").animate({
                        "left": "0"
                    });
                }
                function prevSlide() {
                    slides.eq(frame % slides.length).animate({
                        "left": "940px"
                    });
                    frame -= 1;
                    slides.eq(frame % slides.length).css("left", "-940px").animate({
                        "left": "0"
                    });
                }
                var timer = setInterval(nextSlide, 6000);
                // Enable the buttons.
                var leftButton = $('<span id="carousel-left"></span>').click(function() {
                    clearInterval(timer);
                    prevSlide();
                });
                var rightButton = $('<span id="carousel-right"></span>').click(function() {
                    clearInterval(timer);
                    nextSlide();
                });
                banner.append(leftButton).append(rightButton);
            }
        });
    }
    
    $.fn.gallery = function() {
        $(this).each(function() {
            var gallery = $(this);
            gallery.disableSelection();
            var items = $(".gallery-item", gallery).css("z-index", 1);
            var pages = Math.ceil(items.length / 8);
            // Add the thumbnails.
            var thumbnailContainer = $('<div id="gallery-thumbnails"></div>');
            gallery.append(thumbnailContainer);
            items.each(function() {
                var item = $(this);
                if (item.is("img")) {
                    var thumbnail = item.clone();
                    thumbnail.removeClass("gallery-item").addClass("gallery-thumbnail");
                } else {
                    var thumbnail = $('<span class="gallery-thumbnail gallery-video-thumbnail"></span>').attr("title", item.attr("title"));
                }
                thumbnailContainer.append(thumbnail);
            });
            var thumbnails = $(".gallery-thumbnail", thumbnailContainer);
            thumbnails.slice(8).hide();
            thumbnails.eq(0).addClass("here");
            // Initialize the first image.
            var frame = 2;
            var currentItem = items.eq(0).css("z-index", frame);
            // Enable the transitions.
            function pageOf(item) {
                return Math.floor(item.index() / 8);
            }
            function activateThumbnail(thumbnail) {
                thumbnails.removeClass("here");
                thumbnail.addClass("here");
                if (thumbnail.is(":hidden")) {
                    var thumbnailIndex = (pageOf(thumbnail) * 8)
                    thumbnails.hide().slice(thumbnailIndex, thumbnailIndex + 8).show();
                }
                $("#gallery-pagination-current", gallery).html(pageOf(currentItem) + 1);
            }
            function show(item) {
                if (item.attr("data-index") != currentItem.attr("data-index")) {
                    frame += 1;
                    item.hide().css("z-index", frame).fadeIn();
                    currentItem = item;
                    activateThumbnail(thumbnails.eq(item.index()));
                    title.html(item.attr("title"));
                }
            }
            // Add the media title.
            var title = $('<span id="gallery-title"></span>').html(currentItem.attr("title"));
            gallery.append(title);
            // Make the thumbnail buttons clickable.
            thumbnails.click(function() {
                show(items.eq($(this).index()));
            });
            // Add the left and right buttons.
            var leftButton = $('<span id="gallery-left"><span></span></span>');
            gallery.append(leftButton);
            var rightButton = $('<span id="gallery-right"><span></span></span>');
            gallery.append(rightButton);
            leftButton.click(function() {
                if (currentItem.index() == 0) {
                    show(items.eq(items.length - 1));
                } else {
                    show(currentItem.prev());
                }
            });
            rightButton.click(function() {
                if (currentItem.index() == items.length - 1) {
                    show(items.eq(0));
                } else {
                    show(currentItem.next());
                }
            });
            // Add the pagination.
            if (pages > 1) {
                var pagination = $('<span id="gallery-pagination"></span>');
                var paginationNext = $('<span id="gallery-pagination-next">Next</span>');
                var paginationPrev = $('<span id="gallery-pagination-prev">Prev</span>');
                pagination.append(paginationPrev);
                pagination.append("Page ");
                var paginationCurrent = $('<span id="gallery-pagination-current"></span>').html(pageOf(currentItem) + 1);
                pagination.append(paginationCurrent);
                pagination.append(" of " + pages);
                pagination.append(paginationNext);
                gallery.append(pagination);
                paginationNext.click(function() {
                    var currentPage = pageOf(currentItem);
                    if (currentPage + 1 == pages) {
                        var nextPage = 0;
                    } else {
                        var nextPage = currentPage + 1;
                    }
                    show(items.eq((nextPage * 8)));
                });
                paginationPrev.click(function() {
                    var currentPage = pageOf(currentItem);
                    if (currentPage == 0) {
                        var nextPage = pages - 1;
                    } else {
                        var nextPage = currentPage - 1;
                    }
                    show(items.eq((nextPage * 8)));
                });
            }
        });
    }
    
    $.fn.feedSelector = function() {
        $(this).each(function() {
            var container = $(this);
            var feeds = $(".feed-instance", container);
            var tabs = $(".mini-feed-tabs a", container).each(function() {
                var tab = $(this);
                var feed = $(tab.attr("href"));
                tab.click(function() {
                    feeds.hide()
                    tabs.removeClass("here");
                    tab.addClass("here");
                    feed.show()
                    return false;
                });
            });
            tabs.filter(".here").click();
        });
    }
    
    /**
     * Creates a placeholder on the matched inputs.
     */
    $.fn.placeholder = function() {
        return this.each(function() {
            var input = $(this);
            var placeholder = input.attr("placeholder");
            if (input.val() == "") {
                input.val(placeholder);
                input.addClass("placeholder");
            }
            // Add the behaviours.
            input.focus(function() {
                if (input.val() == placeholder) {
                    input.val("");
                    input.removeClass("placeholder");
                }
            });
            input.blur(function() {
                if (input.val() == "") {
                    input.val(placeholder);
                    input.addClass("placeholder");
                }
            });
            input.parents("form").submit(function() {
                if (input.val() == placeholder) {
                    input.val("");
                    input.removeClass("placeholder");
                }
            });
        });
    }
    
    $(function() {
        $("#carousel .container").banner();
        $("#gallery").gallery();
        $("#mini-feed").feedSelector();
        // Equalize the content heights.
        $("#content-primary, #content-secondary, #content-tertiary").equalizeHeights();
        // Force IE to render the damn body overlays.
        $(window).load(function() {
            $("#body").css("height", $("content-primary").outerHeight());
            $("#body .overlay-top").width();
            $("#body .overlay").css("height", $("#body").innerHeight() - 64 + "px").width();
            $("#body .overlay-bottom").css("top", $("#body").innerHeight() - 32 + "px").width();
            $("#suppliers-of").width();
            $("#back-to-top").css("bottom", $("#back-to-top").css("bottom"));
        });
        // Add in placeholders.
        $("input[placeholder]").placeholder();
    });
}(jQuery));
