(function ($) {

    $.fn.alphaListOrganizer = function (options) {

        var defaults = {};
        var options = $.extend(defaults, options);

        return this.each(function () {

            var $list = $(this);
            var $itemsContainer = $(">.items", $list);
            var $alphaGroups = $(">.alpha-group", $itemsContainer);
            var $items = $(".item", $alphaGroups);

            var alphaCount = $alphaGroups.length;

            if (alphaCount > 1) {

                $itemsContainer.addClass("items-columned");
                // doing these entries separately because doing them together crashes IE9
                $itemsContainer.append("<div class='col col-1'/>");
                $itemsContainer.append("<div class='col col-2'/>");
                $itemsContainer.append("<div class='col col-3'/>");

                var remainder = alphaCount % 3;
                var perCol = parseInt(alphaCount / 3);

                $(">.col-1", $itemsContainer).append($alphaGroups.filter(":lt(" + (perCol + (remainder > 0 ? 1 : 0)) + ")"));
                $(">.col-2", $itemsContainer).append($alphaGroups.filter(":gt(" + ((perCol + (remainder > 0 ? 1 : 0)) - 1) + "):lt(" + (perCol + (remainder > 1 ? 1 : 0)) + ")"));
                $(">.col-3", $itemsContainer).append($alphaGroups.filter(":gt(" + ((perCol * 2) + remainder - 1) + ")"));

            }

        });

    };

    $.fn.dropDownList = function (options) {

        var defaults = {};
        var options = $.extend(defaults, options);

        return this.each(function () {

            var $list = $(this);
            var $itemsContainer = $(">.items", $list);
            var $items = $(">.item", $itemsContainer);

            $itemsContainer.css("visibility", "hidden").show();

            if (!$items.filter(".selected").length)
                $items.first().addClass("selected");

            $list.prepend($items.filter(".selected").clone());

            var $selectedItem = $(">.selected", $list);

            var maxWidth = 0;
            for (var i = 0; i < $items.length; i++) {

                if ($items.eq(i).width() > maxWidth)
                    maxWidth = $items.eq(i).outerWidth();

            }

            $list.width(maxWidth).data("drop-height", $itemsContainer.height());
            $itemsContainer.hide().css("visibility", "");

            if (!$list.is(".static")) {

                $(">a", $selectedItem).click(function () { return false; });

                $(">a", $items).click(function () {

                    var $link = $(this);
                    var $item = $link.parent(".item");

                    if (!$item.is(".selected")) {

                        $item.addClass("selected").siblings(".selected").removeClass("selected");
                        $selectedItem.remove();
                        $list.prepend($item.clone());
                        $selectedItem = $(">.selected", $list);

                        $list.trigger("mouseleave");

                    } else {

                        return false;

                    }

                });

            }

            $list.mouseenter(function () {

                if (!$itemsContainer.is(":visible"))
                    $itemsContainer.height(0).show();

                $itemsContainer.stop().animate({

                    height: parseInt($list.data("drop-height"))

                }, {

                    duration: 200

                });

            }).mouseleave(function () {

                $itemsContainer.stop().animate({

                    height: 0

                }, {

                    duration: 200,
                    complete: function () {

                        if ($itemsContainer.height() == 0)
                            $itemsContainer.hide();

                    }

                });

            });

        });

    };

    $.fn.relatedScroller = function (options) {

        var defaults = {};
        var options = $.extend(defaults, options);

        return this.each(function () {

            var $scroller = $(this);
            var $container = $(".items", $scroller);
            var $items = $(".item", $container);

            if ($items.length > 3) {

                var maxHeight = 0;
                var itemWidth = $items.first().outerWidth(true);

                for (var i = 0; i < $items.length; i++)
                    if ($items.eq(i).outerHeight() > maxHeight)
                        maxHeight = $items.eq(i).outerHeight();

                $scroller.height(maxHeight);

                $container.before("<div class='items-holder' />");

                $(".items-holder", $scroller).append($container);

                $container.css({

                    position: 'absolute',
                    left: 0,
                    top: 0

                }).height(maxHeight).width(itemWidth * $items.length);

                var numPages = Math.ceil($items.length / 3);

                //$scroller.append("<div class='pager'><strong>More</strong> <a href='javascript:;' class='previous'>Previous</a><span class='pages' /><a href='javascript:;' class='next'>&nbsp;</a></div>");
                $scroller.append("<div class='pager-container'><div class='pager'><a href='javascript:;' class='previous'>Previous</a><a href='javascript:;' class='next'>Next</a></div></div>");
                var $nav = $(".pager-container", $scroller);

                var $prev = $(".previous", $nav);
                var $next = $(".next", $nav);

                for (var i = 1; i <= numPages; i++)
                    $next.before("<a href='javascript:;' class='page' rel='" + i + "'>" + i + "</a>");

                $(".page", $nav).click(function () {

                    var $page = $(this);

                    $page.addClass("page-active").siblings(".page.page-active").removeClass("page-active");

                    var pageIdx = parseInt($page.attr("rel"));
                    var itemIdx = 3 * (pageIdx - 1);
                    var $item = $items.eq(itemIdx);

                    var newLeft = $items.length < itemIdx + 3 ? -$items.eq(itemIdx - (3 - ($items.length - itemIdx) % 3)).position().left : -$item.position().left;
                    var oldLeft = $container.position().left;
                    var leftDiff = Math.abs(newLeft - oldLeft);

                    $container.stop().animate({

                        left: newLeft

                    }, .8 * leftDiff);

                    $prev.stop().animate({
                        opacity: pageIdx == 1 ? .3 : 1
                    }, 200);

                    $next.stop().animate({
                        opacity: pageIdx == numPages ? .3 : 1
                    }, 200);

                    return false;

                }).first().addClass("page-active");

                $prev.css("opacity", .3);

                $(".previous,.next", $nav).click(function () {

                    var isNext = $(this).is(".next");
                    var $activePage = $(".page.page-active", $nav);

                    if (isNext)
                        $activePage.next(".page").click();
                    else
                        $activePage.prev(".page").click();

                    return false;

                });

            }

        });

    };

    $.fn.directory = function (options) {

        var defaults = {};
        var options = $.extend(defaults, options);

        return this.each(function () {

            var $directory = $(this);
            var $itemsContainer = $(">.items", $directory);
            var $items = $(">.item>.item-header>.link-bar", $itemsContainer).closest(".item");

            var activeItemId = location.hash.split("#")[1];

            $items.each(function () {

                var $item = $(this);
                var $itemContent = $(">.item-content", $item);

                $itemContent.data("height", $itemContent.height());

                if ($item.attr("id") != activeItemId)
                    $itemContent.height(0).hide();
                else {
                    $item.addClass("item-active");
                    $itemContent.show();
                }

            });

            $(">.item-header", $items).mouseenter(function () {

                var $itemHeader = $(this);

                if (!$itemHeader.is(".item-header-hover") && $itemHeader.children("a").length)
                    $itemHeader.addClass("item-header-hover");

            }).mouseleave(function () {

                var $itemHeader = $(this);
                $itemHeader.removeClass("item-header-hover");

            });

            $(">.item-header>.link-bar", $items).click(function () {

                var $itemHeader = $(this);
                var $item = $itemHeader.closest(".item");
                var $itemContent = $(">.item-content", $item);

                if (!$item.is(".item-active")) {

                    $item.addClass("item-active");

                    var $activeItem = $item.siblings(".item-active");
                    var $itemContentToHide = $(">.item-content", $activeItem);

                    $activeItem.removeClass("item-active");

                    $itemContentToHide.stop().animate({

                        height: 0

                    }, {

                        duration: 1000,
                        complete: function () {

                            if ($(this).height() == 0)
                                $(this).hide();

                        }

                    });

                    if (!$itemContent.is(":visible"))
                        $itemContent.height(0).show();

                    $itemContent.stop().animate({

                        height: $itemContent.data("height")

                    }, {

                        duration: 1000

                    });

                } else {

                    $item.removeClass("item-active");

                    $itemContent.stop().animate({

                        height: 0

                    }, {

                        duration: 1000,
                        complete: function () {

                            if ($(this).height() == 0)
                                $(this).hide();

                        }

                    });

                }

                return false;

            });

        });

    };

    $.fn.hilites = function (options) {

        var defaults = {};
        var options = $.extend(defaults, options);

        return this.each(function () {

            var $hilites = $(this);
            var $back = $(".item-content-background", $hilites);
            var $container = $(".items", $hilites);
            var $items = $(".item", $container);
            var maxHeight = 0;
            var maxPaddedHeight = 0;

            var minHeight = $container.height() + ($container.offset().top - $back.offset().top);

            $(".item-content", $items).css('min-height', minHeight).each(function () {

                if ($(this).height() > maxHeight)
                    maxHeight = $(this).height();

                if ($(this).outerHeight() > maxPaddedHeight)
                    maxPaddedHeight = $(this).outerHeight();

            });

            $hilites.closest(".content-container").css("margin-bottom", maxPaddedHeight + $back.position().top - $hilites.height());

            $back.height($items.first().children(".item-content").outerHeight());

            $items.first().addClass("item-active").children(".item-content").show();

            $(".item-selector", $items).append("<div class='status-bar'><div class='bar' /><div class='tip' /></div>");

            var startTimer = function ($item, $prevItem) {

                if ($prevItem && $prevItem.length) {

                    var $prevStatusBar = $(".item-selector>.status-bar", $prevItem);
                    var $prevBar = $(">.bar", $prevStatusBar);

                    $prevBar.stop();

                    $prevStatusBar.stop().animate({

                        opacity: 0

                    }, {

                        duration: 500,
                        complete: function () {

                            if (parseFloat($(this).css("opacity")) == 0)
                                $(this).hide().css("opacity", "");

                        }

                    });

                }


                var $statusBar = $(".item-selector>.status-bar", $item);
                var $bar = $(">.bar", $statusBar);

                $statusBar.show();

                $bar.stop().css({

                    opacity: 0,
                    width: ''

                }).animate({

                    opacity: 1,
                    complete: function () {

                        if (parseFloat($(this).css("opacity")) == 1)
                            $(this).css("opacity", "");

                    }

                }, {

                    duration: 500

                }).animate({

                    width: 5

                }, {

                    duration: 9000,
                    complete: function () {

                        if ($bar.width() == 5) {

                            var $nextItem = $item.next(".item");

                            if (!$nextItem.length)
                                $nextItem = $item.siblings(".item").first();

                            $statusBar.stop().animate({

                                opacity: 0

                            }, {

                                duration: 500,
                                complete: function () {

                                    if (parseFloat($(this).css("opacity")) == 0)
                                        $(this).hide().css("opacity", "");

                                }

                            });

                            $(".item-selector>a", $nextItem).trigger("click", [true]);

                        }

                    }

                });

            };

            var animateOut = function ($itemContent, callback) {

                $itemContent.stop().animate({

                    opacity: 0

                }, {

                    duration: 500,
                    complete: function () {

                        if (parseFloat($(this).css("opacity")) == 0)
                            $(this).hide().css("opacity", "");

                        if (callback)
                            callback();

                    }

                });

            };

            var animateIn = function ($itemContent, callback) {

                if (!$itemContent.is(":visible"))
                    $itemContent.css("opacity", 0).show();

                $itemContent.stop().animate({

                    opacity: 1

                }, {

                    duration: 500,
                    complete: function () {

                        if (parseFloat($(this).css("opacity")) == 1)
                            $(this).css("opacity", "");

                        if (callback)
                            callback();

                    }

                });

            };

            var animateBackground = function (newHeight, callback) {

                $back.stop().animate({

                    height: newHeight

                }, {

                    duration: 250,
                    complete: function () {

                        if (callback)
                            callback();

                    }

                });

            };

            $(".item-selector>a", $items).click(function (evt, isNotRealClick) {

                var $item = $(this).closest(".item");

                if (!$item.is(".item-active")) {

                    var $prevItem = $item.siblings(".item-active");

                    var $itemContent = $item.children(".item-content");
                    var $prevItemContent = $prevItem.children(".item-content");

                    $item.addClass("item-active");
                    $prevItem.removeClass("item-active");

                    var startHeight = $back.height();

                    $itemContent.css({

                        visibility: 'hidden',
                        opacity: 0

                    });

                    var itemContentHeight = $itemContent.outerHeight();

                    $itemContent.css({

                        visibility: '',
                        opacity: ''

                    });

                    if (startHeight < itemContentHeight) {

                        animateOut($prevItemContent, function () {

                            animateBackground(itemContentHeight, function () {

                                animateIn($itemContent);

                            });

                        });

                    } else {

                        animateOut($prevItemContent, function () {

                            animateIn($itemContent, function () {

                                animateBackground(itemContentHeight);

                            });

                        });

                    }

                    startTimer($item, isNotRealClick ? false : $prevItem);

                } else {

                    return true;

                }

                return false;

            });

            if ($items.length > 1)
                startTimer($items.first(), false);
            else if ($items.length == 1)
                $(".item-selector>.status-bar", $items.first()).show();

        });

    };

})(jQuery);
