var ambient = ambient || { };

(function($) {
    $(document).ready(function(event) {
        $('.marquee img').imgpreload({
            all: function() {
                $('.marquee').marquee({
                    maxWidthSelector: '.a-outer-wrapper'
                });
            }
        });
        $('.news-ticker').newsTicker();
        $('.a-nav-main.nav-depth-0').megaMenu();
        $('.a-slot.product img').imgZoom();

        var printButton = $('<a />')
            .attr('href', '#')
            .html(ambient.i18n.print)
            .addClass('print-button')
            .click(function(event) {
                event.preventDefault();
                window.print();
            });
        $('.a-default .a-content, .a-blog .a-content').append(printButton);
    });
})(jQuery);

(function($) {
    /**
     * Create a mega menu.
     *
     * @param {Object} options Settings hash.
     */
    $.fn.megaMenu = function(options) {
        var settings = $.extend({

        }, options || { });

        var mega = this;
        $('li', mega).removeClass('css-hover');
        mega.addClass('mega')
            .children()
            .children('ul')
            .wrap('<div class="menu-wrapper" />')
            .wrap('<div class="menu-wrapper-inner" />');
        var links = mega.children().children('a');
        var menus = mega.children().children('div');

        links.click(function(e) {
            var menu = $(this).next();
            if (menu.length > 0) {
                e.preventDefault();
                open(menu);

                var left = $(this).position().left + $(this).width() / 2 - 15;
                menu.find('.menu-wrapper-inner').css({
                    backgroundPosition: left + 'px 0'
                });
            }
        });

        var current = null;

        function close(menu, options) {
            menu.animate({
                height: 0
            }, $.extend({ }, options || { }));
            mega.animate({
                height: 40
            });
        };

        function open(menu) {
            if (current != null) {
                if (current[0] == menu[0]) {
                    close(current);
                } else {
                    close(current, {
                        complete: function() {
                            open(menu);
                        }
                    });
                }
                current = null;
                return;
            }

            current = menu;
            var height = menu.children().first().innerHeight();
            menu.animate({
                height: height
            });
            mega.animate({
                height: height + 40
            });
        }
    };

    /**
     * A changer for recent news headlines.
     *
     * @param {Object} options Settings hash.
     */
    $.fn.newsTicker = function(options) {
        var settings = $.extend({
            containerSelector: '.container',
            itemSelector: '.item',

            delay: 5000,
            transition: 'swing',
            duration: 400
        }, options || { });

        return this.each(function(index, element) {
            var ticker = $(element);
            var container = $(settings.containerSelector, ticker);
            var items = $(settings.itemSelector, container);

            var currentItem = 0;
            var advanceInterval = null;

            if (items.length > 0) {
                showItem(currentItem);
                startTicker();
            }

            function startTicker() {
                if (advanceInterval != null) {
                    clearInterval(advanceInterval);
                }

                advanceInterval = setInterval(function() {
                    showItem((currentItem + 1) % items.length);
                }, settings.delay);
            }

            function showItem(index) {
                currentItem = index;

                var item = $(items[index]);

                container.animate({
                    top: -item.position().top
                }, {
                    duration: settings.duration,
                    transition: settings.transition,
                    complete: settings.complete
                });
            }
        });
    }

    /**
     * Create an animated marquee.
     *
     * @param {Object} options Configuration hash.
     */
    $.fn.marquee = function(options) {
        var settings = $.extend({
            // selectors
            maxWidthSelector: '.outer-wrapper',
            wrapperSelector: '.panels-wrapper',
            frameSelector: '.panels-frame',
            containerSelector: '.panels',
            panelSelector: '.panel',
            navSelector: '.marquee-nav',
            navButtonSelector: 'li',

            // transition option
            duration: 400,
            easing: 'swing',
            autoadvance: true,
            delay: 5000,
            complete: null
        }, options || { });

        var maxWidth = $(settings.maxWidthSelector).width();

        return this.each(function(index, element) {
            var marquee = $(element);

            var wrapper = $(settings.wrapperSelector, marquee);
            var frame = $(settings.frameSelector, marquee);
            var panelContainer = $(settings.containerSelector, frame);
            var panels = $(settings.panelSelector, panelContainer);

            var nav = $(settings.navSelector, marquee);
            var buttons = $(settings.navButtonSelector, nav);

            var advanceInterval = null;
            var currentPanel = 0;

            wrapper.css({
                width: maxWidth,
                left: -(maxWidth - marquee.width()) / 2
            });

            doInitialPositioning();
            setupNavigation();
            showPanel(currentPanel);
            if (settings.autoadvance) {
                startAutoadvance();
            }

            /**
             * All the panels of the marquee need to be positioned horizontally
             * in one container so that later we can move the container to
             * show the selected panel.
             *
             * Also the image within the panel is to be centered
             * vertically if it's higher than the marquee.
             *
             */
            function doInitialPositioning() {
                var total = 0;
                panels.each(function(index, element) {
                    var img = $('img', element);

                    var width = img.width();
                    var height = img.height();

                    $(element).css({
                        left: total
                    });

                    img.css({
                        left: 0,
                        top: (marquee.height() - height) / 2
                    });

                    total += width;
                });
            }

            /**
             * Setup buttons of the navigation to change panels. The index of
             * the button is the same as the index of the panel to show.
             */
            function setupNavigation() {
                buttons.each(function(index, element) {
                    $(element).click(function(event) {
                        if (advanceInterval != null) {
                            clearInterval(advanceInterval);
                        }
                        showPanel(index);
                    });
                });
            }

            /**
             * Move the panel container to the correct place to show the panel
             * under the given index. Also the frame's width and position need
             * to be adjusted because we allow for variable width panels, and
             * navigation buttons need to be updated.
             *
             * @param {Number} index Index of the panel.
             */
            function showPanel(index) {
                currentPanel = index;

                var panel = $(panels[index]);
                var button = $(buttons[index]);

                var width = panel.width();

                var animationSettings = {
                    duration: settings.duration,
                    easing: settings.easing,
                    complete: settings.complete,
                    queue: false
                };

                panelContainer.animate({
                    left: -panel.position().left
                }, animationSettings);
                frame.animate({
                    left: (wrapper.width() - width) / 2,
                    width: width
                }, animationSettings);

                buttons.removeClass('active');
                button.addClass('active');
            }

            /**
             * Starts the interval that will automatically change the
             * displayed panel every settings.delay milliseconds.
             */
            function startAutoadvance() {
                if (advanceInterval != null) {
                    clearInterval(advanceInterval);
                }

                advanceInterval = setInterval(function() {
                    showPanel((currentPanel + 1) % panels.length);
                }, settings.delay);
            }
        });
    };

    $.fn.imgZoom = function(options) {
        var settings = $.extend({
            width: 260,
            height: 260
        }, options || { });

        function zoomImgSrc(src) {
            var pattern = /(\d+)\.(\d+)\.[sc]\.[a-z]{1,3}$/;
            var result = pattern.exec(src);

            if (result.length > 0) {
                src = src.replace(result[1], settings.width);
                src = src.replace(result[2], settings.height);
            }
            return src;
        }

        this.each(function(index, element) {
            var img = $(this);
            var parent = img.parent();
            var timeout = null;
            var zoom = $('<img />')
                .load(function(event) {
                    zoom.css({
                        position: 'absolute',
                        top: img.position().top -
                            (zoom.height() - img.height()) / 2,
                        left: img.position().left -
                            (zoom.width() - img.width()) / 2
                    });
                })
                .attr('src', zoomImgSrc(img.attr('src')))
                .hide()
                .appendTo(parent).
                mouseleave(function() {
                    zoom.fadeOut();
                });
            img.hover(function(event) {
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(function() {
                    zoom.fadeIn();
                }, 500);
            }, function(event) {
                if (timeout) clearTimeout(timeout);
            });
        });
    }
})(jQuery);

