String.prototype.parseBool = function() {
	var t = this.toLowerCase();
	return t === "on" || t === "yes" || t === "true";
};

String.prototype.normalize = function () {
    return this.replace(/\s+/g, ' ').replace(/^\s+|\s+/g, '');
};

String.prototype.isEmpty = function () {
    return this.normalize().length == 0;
};

(function ($) {
    // shop item animation decorator
    $.fn.extend({
        attachShopItemAnimation: function (params) {
            var p = $.extend({}, $.fn.attachShopItemAnimation.defaults, params);
            return this.each(function () {
                var cart = $(".sidebar>article.shopping-cart");
                var form = $(this).find("form");
                var img = $(this).find("img:first");
                form.submit(function () {
                    img.clone().appendTo("body").css({
                        position: "absolute",
                        top: img.offset().top + "px",
                        left: img.offset().left + "px"
                    }).animate({
                        top: cart.offset().top + (cart.outerHeight() - img.height()) / 2 + "px",
                        left: cart.offset().left + (cart.outerWidth() - img.width()) / 2 + "px",
                        opacity: 0.4
                    }, 1000, "easeInOutCubic").queue(function () { $(this).remove() });
                });
            });
        }
    });

    $.fn.attachShopItemAnimation.defaults = {
        animationLength: 1000
    };


    // notification box
    $.extend({
        notify: function (message, type) {
            var box = $('<div class="popup-message"/>').html(message);
            switch (type) {
                case "error":
                case "warning":
                    box.addClass(type);
                    break;
                default:
                    break;
            }
            box.appendTo("body").hide().fadeIn(500);
            setTimeout(function () {
                box.fadeOut(2000).queue(function () {
                    box.remove();
                    box = null;
                });
            }, 5000);
        }
    });


    $(function () {
        // featured articles widget
        $("article.widget-feature").each(function () {
            var widget = $(this);
            var articles = widget.find(">article");
            var articleContainer = $('<div class="article-container"/>').appendTo(widget);
            articles.remove().appendTo(articleContainer).css({ position: "absolute", top: 0, left: 0 }).hide().eq(0).show();
            var delay = Number(widget.attr("data-delay")) || 4000;
            var animationLength = Number(widget.attr("data-anim-length")) || 1000;
            var autoScroll = widget.attr("data-anim-auto").parseBool();
            var articleList = $('<ul class="widget-feature-navigation"/>').appendTo(widget);

            articles.children("article").hide();

            var currentArticle = 0;
            var switchToArticle = function (i) {
                i = i % articles.length;
                i = i < 0 ? i + articles.length - 1 : i;
                /*
                articleContainer.stop().animate({ scrollTop: i * 400 + "px" }, animationLength, "easeInOutCubic");
                articleList.find(">li").removeClass("active").eq(i).addClass("active");
                */
                articles.stop().fadeOut(animationLength).eq(i).stop().fadeIn(animationLength);
                articleList.children("li").removeClass("active").eq(i).addClass("active");
                currentArticle = i;
            };

            articles.each(function (idx) {
                $('<li><img src="' + $(this).find("img").attr("src") + '" alt="" /><p>' + $(this).find("header").text() + '</p></li>').click(function () {
                    autoScroll = false;
                    switchToArticle(idx);
                }).appendTo(articleList);
            });

            articleList.find(">li:first").addClass("active");

            setInterval(function () {
                if (autoScroll)
                    switchToArticle(currentArticle + 1);
            }, delay);
        });


        // front page shop widget
        $(".widget-frontpage-shop").each(function () {
            var widget = $(this);
            var scrollContainer = widget.find(".container");
            var pager = widget.find(".pager");
            var items = scrollContainer.find("li");
            var pages = Math.ceil(items.length / 3);
            var scrollWidth = items.outerWidth(true) * 3;
            var currentPage = 0;

            var autoscroll = widget.attr("data-autoscroll").parseBool();
            var autoscrollDelay = isNaN(Number(widget.attr("data-autoscroll-delay"))) ? 5000 : Number(widget.attr("data-autoscroll-delay"));
            var animationLength = isNaN(Number(widget.attr("data-animation-length"))) ? 500 : Number(widget.attr("data-animation-length"));

            // function to scroll to a specific page
            var scrollToPage = function (page) {
                currentPage = page;
                scrollContainer.stop().animate({ scrollLeft: page * scrollWidth + "px" }, animationLength, "easeInOutCubic").queue(function () {
                    pager.children("a:not(.back,.forward)").removeClass("current").eq(page).addClass("current");
                });
            };

            // enlarge the container
            scrollContainer.children("ul").width(pages * scrollWidth + 10);

            // autoscroll functions
            setInterval(function () {
                if (autoscroll) {
                    scrollToPage((currentPage + 1) % pages);
                }
            }, autoscrollDelay);

            // generate the pager
            for (var i = 0; i < pages; i++) {
                var pageItem = $('&nbsp;<a href="#">' + (i + 1) + '</a>&nbsp;').appendTo(pager);
                if (i == currentPage) pageItem.addClass("current");
            }

            // attach pager functionality
            var pagerItems = pager.find("a:not(.back,.forward)");
            pager.delegate('a', 'click', function () {
                autoscroll = false;
                var $t = $(this);
                if ($t.is(".back")) scrollToPage(Math.max(currentPage - 1, 0));
                else if ($t.is(".forward")) scrollToPage(Math.min(currentPage + 1, pages - 1));
                else scrollToPage(pagerItems.index(this));
                return false;
            });
        });


        // search results widget
        $(".widget-search-results-browser").each(function () {
            var widget = $(this);
            var list = widget.find("ol");
            var results = list.children();
            var itemsPerPage = Number(widget.attr("data-items-per-page")) || 10;
            var animationLength = Number(widget.attr("data-animation-length")) || 500;
            var container = $('<div class="container"><div class="scroller clearfix">').insertBefore(list);
            var pager = widget.find(".pager");
            var pageList, currentPage = 0, pages = Math.ceil(results.length / itemsPerPage), pageWidth = container.width();

            var scroller = container.children(".scroller").width(container.width() * pages);

            for (var i = 0; i < results.length; i++) {
                if (i % itemsPerPage == 0) {
                    pageList = $('<ol/>').appendTo(scroller).width(pageWidth);
                }
                results.eq(i).remove().appendTo(pageList);
            }

            list.remove();

            var scrollToPage = function (n) {
                currentPage = Math.max(Math.min(n, pages - 1), 0);
                container.stop().animate({ scrollLeft: currentPage * pageWidth + "px" }, animationLength, "easeInOutQuart").queue(updatePager);
            };

            // generate pager
            for (var i = 0; i < pages; i++) {
                var pageItem = $('&nbsp; <a href="#">' + (i + 1) + '</a> &nbsp;').appendTo(pager);
                if (i == currentPage) pageItem.addClass("current");
            }

            var pagerItems = pager.children("a:not(.back,.forward)");

            var updatePager = function () {
                pager.find("a:not(.back,.forward)").removeClass("current").eq(currentPage).addClass("current");
            };

            pager.delegate("a.back", "click", function () {
                scrollToPage(currentPage - 1);
                return false;
            });

            pager.delegate("a.forward", "click", function () {
                scrollToPage(currentPage + 1);
                return false;
            });

            pager.delegate("a:not(.back,.forward)", "click", function () {
                scrollToPage(pagerItems.index(this));
                return false;
            });
        });


        // postcard selector widget
        $(".widget-postcard-selector,.shop-category-list,.widget-image-gallery").each(function () {
            var widget = $(this);
            var list = widget.find("ul");
            var cards = list.children();
            var wrapper = $('<div class="wrapper"/>').insertBefore(list);
            var scroller = $('<div class="scroller clearfix"/>').appendTo(wrapper);
            var itemsPerPage = Number(widget.attr("data-items-per-page")) || 9;
            var animationLength = Number(widget.attr("data-animation-length")) || 500;
            var pager = widget.find(".pager");
            var pages = Math.ceil(cards.length / itemsPerPage);
            var pageList, currentPage = 0, pageWidth = wrapper.width();
            var cart = $(".sidebar>article.shopping-cart");

            scroller.width(pages * wrapper.width());
            for (var i = 0; i < cards.length; i++) {
                if (i % itemsPerPage == 0) {
                    pageList = $('<ul class="clearfix"/>').appendTo(scroller);
                }
                cards.eq(i).remove().appendTo(pageList);
            }
            list.remove();

            var scrollToPage = function (n) {
                currentPage = Math.max(Math.min(n, pages - 1), 0);
                wrapper.stop().animate({ scrollLeft: currentPage * pageWidth + "px" }, animationLength, "easeInOutQuart").queue(updatePager);
            };

            // generate pager
            for (var i = 0; i < pages; i++) {
                var pageItem = $('&nbsp; <a href="#">' + (i + 1) + '</a> &nbsp;').appendTo(pager);
                if (i == currentPage) pageItem.addClass("current");
            }

            var pagerItems = pager.children("a:not(.back,.forward)");

            var updatePager = function () {
                pager.find("a:not(.back,.forward)").removeClass("current").eq(currentPage).addClass("current");
            };

            pager.delegate("a.back", "click", function () {
                scrollToPage(currentPage - 1);
                return false;
            });

            pager.delegate("a.forward", "click", function () {
                scrollToPage(currentPage + 1);
                return false;
            });

            pager.delegate("a:not(.back,.forward)", "click", function () {
                scrollToPage(pagerItems.index(this));
                return false;
            });
        });

        // image browser
        var createImageBrowser = function (idx) {
            var widget = $(this),
                list = widget.find("ul"),
                items = list.children(),
                viewer = $('<div class="viewer"/>').insertBefore(list),
                pager = $('<div class="pager"/>').insertAfter(viewer),
                animationLength = Number(widget.attr("data-animation-length")) || 300;

            idx = idx || 0;

            list.wrap('<div class="wrapper"/>');

            var wrapper = widget.find(".wrapper"),
                itemsPerPage = Math.floor(wrapper.width() / items.eq(0).outerWidth()),
                maxPage = Math.ceil(items.length / itemsPerPage) - 1,
                currentPage = 0,
                pageStep = wrapper.width();

            if (widget.is(".video")) {
                viewer.css("min-height", "360px");
            } else {
                // prefetch images
                items.each(function () {
                    var tmp = new Image();
                    tmp.src = $(this).attr("data-lightbox-image");
                });
            }

            var switchImage = function (idx) {
                viewer.children().remove();
                var selectedImage = items.eq(idx).find("img");

                if (widget.is(".video")) {
                    var id = "youtube-video-" + Math.floor(Math.random() * 10e8);
                    var youtubeUrl = "http://www.youtube.com/v/{0}?fs=1&amp;hl=en_US&amp;rel=0&amp;color1=0x006699&amp;color2=0x54abd6".split("{0}").join(selectedImage.attr("data-youtube"));

                    $('<div id="' + id + '"/>').appendTo(viewer);
                    swfobject.embedSWF(
                        youtubeUrl, id, "480", "295", "10", null, {},
                        { movie: youtubeUrl, allowFullScreen: "true", allowscriptaccess: "always" },
                        { width: 480, height: 295 }
                    );
                } else {
                    if (selectedImage.is("[data-lightbox-image]") && widget.parent().is(".lightbox")) {
                        viewer.append('<img src="' + selectedImage.attr("data-lightbox-image") + '"/>');
                    } else {
                        viewer.append(selectedImage.clone());
                    }
                }
                viewer.append('<p>' + selectedImage.attr("data-description") + '</p>');
                items.removeClass("active").eq(idx).addClass("active");
            };

            list.delegate("li,img,a", "click", function (ev) {
                var $t = $(this);
                $t = !$t.is("li") ? $t.closest("li") : $t;
                switchImage(items.index($t));
                return false;
            });

            if (!widget.is(".video") && !widget.parent().is(".lightbox")) {
                viewer.delegate("img", "click", function (ev) {
                    convertBrowserToLightbox.apply(widget.get(0), [items.index(items.filter(".active"))]);
                    ev.preventDefault();
                }).css("cursor", "pointer");
            }

            pager.append('<a href="#" class="prev"><img src="/Content/images/content/left-pager-arrow.png" alt="Nazaj"/></a><a href="#" class="next"><img src="/Content/images/content/right-pager-arrow.png" alt="Naprej"/></a>');

            var switchToPage = function (idx) {
                idx = Math.min(Math.max(0, idx), maxPage);
                wrapper.stop().animate({ scrollLeft: idx * pageStep + "px" }, animationLength, "easeInOutQuart");
                currentPage = idx;
            };

            pager.delegate("a", "click", function (ev) {
                var $t = $(this);
                if ($t.is(".next")) {
                    switchToPage(currentPage + 1);
                } else if ($t.is(".prev")) {
                    switchToPage(currentPage - 1);
                }
                return false;
            });

            switchImage(idx);
        };

        var deepClone = function (node) {
            if (node.jquery) node = node.get(0);
            var clone = node.nodeType == 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(true);
            var child = node.firstChild;
            while (child) {
                clone.appendChild(deepClone(child));
                child = child.nextSibling;
            }
            return clone;
        };

        var convertBrowserToLightbox = function (idx) {
            var original = $(this),
                clone = $('<div class="widget-image-browser"/>'),
                list = $('<ul class="clearfix"/>').appendTo(clone),
                lightbox = $('<div class="lightbox"/>').appendTo("body").append(clone).hide();

            /*@cc_on
            /*@if(@_jscript_version >= 5)
            // workaround because of IE not supporting cloning HTML5 elements
            original.find("ul>li img").each(function () {
                var img = $(this);
                list.append(
                        '<li><img src="' + (img.is("[data-lightbox-image]") ? img.attr("data-lightbox-image") : img.attr("src")) +
                        '" alt="' + img.attr("alt") +
                        '" title="' + img.attr("title") +
                        '" data-description="' + img.attr("data-description") +
                        '"/>');
            });
            @else @*/
                    list.append(original.find("ul>li").clone());
                /*@end
            @*/

            createImageBrowser.apply(clone.get(0), [idx]);
            $('<a href="#" class="close">Zapri</a>').appendTo(lightbox).click(function () {
                lightbox.fadeOut().queue(function () { lightbox.remove(); });
                return false;
            });
            var prefetch = new Image();
            prefetch.src = clone.find("ul>li>img").eq(idx).attr("src");
            lightbox.css({
                left: original.offset().left + (original.outerWidth() - lightbox.width()) / 2 + "px",
                top: original.offset().top + (original.outerHeight() - lightbox.height()) / 2 + "px"
            }).fadeIn();
        };

        $(".widget-image-browser").each(createImageBrowser);

        // decorate add item operations with animations
        $(".widget-frontpage-shop ul li, .shop-item-detail").attachShopItemAnimation();

        // FAQ widget
        $("section.faq").each(function () {
            $(this).delegate("header", "click", function () {
                var animatable = $(this).siblings("section");
                if (animatable.height() == 0) {
                    animatable.animate({ height: animatable.data("original-height") + "px" }, 500, "easeInOutCubic");
                } else {
                    animatable.animate({ height: 0 }, 500, "easeInOutCubic");
                }
                return false;
            });
            // measure elements
            $(this).find("article>section").each(function () {
                var animatable = $(this);
                animatable.data("original-height", animatable.outerHeight(true) + 20).css({ overflow: "hidden" }).height(0);
            });
        });
    });
})(jQuery);
