﻿(function ($) {
    // The jQuery.matchcentreui namespace will automatically be created if it doesn't exist
    $.widget("matchcentreui.pagerii", {
        // These options will be used as defaults
        options: {
            duration: 'normal',
            page: 1,
            countPerPage: 0,
            _pages: [],
            _pagecount: 0,
            _animating: 0,
            routerURL: '',
            fullClassName: '',
            pageMethodName: 'Page',
            additionalParams: []
        },
        _createPagerWrapper: function () {
            var widget = this;
            var element = this.element[0];
            // Relatively position main element and hide overflowing content.
            // The main element will be the view port.
            $(element).css({ 'overflow': 'hidden' });
            $(element).addClass('mc-ui-posrel');

            // NOTE: All divs that are direct children of the main element are 
            // considered individual pages.

            // - Wrap the list of items to page in a pageable container.
            var pagerElements =
                $(element).children('div')
                    .wrapAll('<div class="mc-ui-pager-container" />');

            // - Add previous and next buttons to the widget.
            $('div.mc-ui-pager-container', element)
                .after('<span class="mc-ui-pager-next">&nbsp;</span>')
                .after('<span class="mc-ui-pager-prev">&nbsp;</span>');
        },
        _initPager: function () {
            var widget = this;
            var element = this.element[0];

            // Reset cached pages.
            widget.options._pages = [];
            widget.options._pagecount = 0;

            // - Mark the list of items to page with a class "mc-ui-pager-item-container". 
            var pagerElements =
                $('.mc-ui-pager-container', element).children('div')
                    .addClass('mc-ui-pager-item-container')
                    .each(function () {
                        widget.options._pages[++widget.options._pagecount] = $(this);
                    });

            // - Setup interaction states
            $(element).unbind('mouseenter').mouseenter(function () { $(this).addClass('ui-state-hover') });
            $(element).unbind('mouseleave').mouseleave(function () { $(this).removeClass('ui-state-hover') });
        },
        _initHorizontalPager: function () {
            var widget = this;
            var element = this.element[0];

            // - Setup all pager items to float next to each other.
            // - Adjust pageable container width for horizontal viewing.
            var pagerContainerWidth = 0;
            $('div.mc-ui-pager-container div.mc-ui-pager-item-container', element)
                .addClass('mc-ui-float-l')
                .each(function () {
                    pagerContainerWidth += $(this).outerWidth(true);
                });
            $('div.mc-ui-pager-container', element).css('width', pagerContainerWidth + 'px');

            // - Position pageable container for displaying selected page.
            var selectedPage = widget.options._pages[widget.options.page];
            var selectedPageLeft = $(selectedPage).position().left;
            $('div.mc-ui-pager-container', element).addClass('mc-ui-posabs');
            $('div.mc-ui-pager-container', element).css('left', '-' + selectedPageLeft);

            // - Adjust height of main element according to first page.
            var displayHeight = $('div.mc-ui-pager-item-container:nth-child(' + widget.options.page + ')', element).outerHeight(true);
            $(element).css('height', displayHeight + 'px');

            // - Setup previous and next clickable elements.
            $('span.mc-ui-pager-prev', element).addClass('mc-ui-posabs-tl').unbind('click').click(function (event) { event.preventDefault(); widget._prevClick() });
            $('span.mc-ui-pager-next', element).addClass('mc-ui-posabs-tr').unbind('click').click(function (event) { event.preventDefault(); widget._nextClick() });

            // - Initialize display of previous and next buttons.
            if ($(selectedPage).hasClass('mc-ui-final')) {
                $('span.mc-ui-pager-next', element).hide();
            }
            else {
                // - Cache next page so long if possible.
                widget._cacheNext();
            }

            if (widget.options.page <= 1) {
                $('span.mc-ui-pager-prev', element).hide();
            }
        },
        _cacheNext: function () {
            var widget = this;
            var element = this.element[0];

            if (undefined != widget.options._pages[widget.options.page + 1])
                return;

            widget.options._animating++;
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: widget.options.routerURL,
                data:
            "{" +
            "fullClassName:'" + widget.options.fullClassName + "'," +
            "methodName:'" + widget.options.pageMethodName + "'," +
            "parameters:['" + (widget.options.page + 1) + "','" + widget.options.countPerPage + (widget.options.additionalParams.length > 0 ? "','" : "") + widget.options.additionalParams.join("','") + "']}",
                success: function (result, textStatus, jqXHR) {
                    // Receive new contents.
                    var newElement = $(result.d)
                .addClass('mc-ui-pager-item-container')
                .addClass('mc-ui-float-l')
                .each(function () {
                    widget.options._pages[++widget.options._pagecount] = $(this);
                });

                    var currentPage = widget.options._pages[widget.options.page];

                    // Insert new contents in DOM.
                    $(currentPage).after($(newElement));

                    var pagerContainerWidth = $('div.mc-ui-pager-container', element).outerWidth(true);

                    $(newElement)
                .each(function () {
                    pagerContainerWidth += $(this).outerWidth(true);
                });

                    $('div.mc-ui-pager-container', element).css('width', pagerContainerWidth + 'px');

                    if (widget.options.success) {
                        widget.options.success($(newElement), result, textStatus, jqXHR);
                    }
                },
                complete: function (jqXHR, textStatus) {
                    widget.options._animating--;
                }
            });
        },
        _nextClick: function () {
            var widget = this;
            var element = this.element[0];

            if (widget.options._animating > 0)
                return false;

            widget.options._animating++;

            widget._slideLeft();

            widget.options._animating--;

            // - Load the next page with AJAX if necessary
            widget._cacheNext();
        },
        _slideLeft: function () {
            var widget = this;
            var element = this.element[0];

            // - Get current left offset.
            var currentOffset = $('div.mc-ui-pager-container', element).position().left;
            // - Get current left offset slide delta.
            var currentPage = widget.options._pages[widget.options.page];
            var currentPageWidth = $(currentPage).outerWidth(true);
            var slideDelta = currentPageWidth;

            // Adjust display height of main element according to the next page to display.
            var displayHeight = $('div.mc-ui-pager-item-container:nth-child(' + (widget.options.page + 1) + ')', element).outerHeight(true);
            widget.options._animating++;
            $(element).animate({ 'height': displayHeight + 'px' }, widget.options.duration, function () { widget.options._animating--; });
            // Slide pageable container left.
            widget.options._animating++;
            $('div.mc-ui-pager-container', element).animate({ 'left': (currentOffset - slideDelta) + 'px' }, widget.options.duration, function () { widget.options._animating--; });

            // - Adjust display index for one page right.
            widget.options.page++;

            var nextPage = widget.options._pages[widget.options.page];

            // - Adjust the paging buttons.
            if ($(nextPage).hasClass('mc-ui-final')) {
                $('span.mc-ui-pager-next', element).fadeOut(widget.options.duration);
            }
            if (widget.options.page > 1) {
                $('span.mc-ui-pager-prev', element).fadeIn(widget.options.duration);
            }
        },
        _prevClick: function () {
            var widget = this;
            var element = this.element[0];

            if (widget.options._animating > 0)
                return false;

            widget.options._animating++;

            widget._slideRight();

            widget.options._animating--;

            // - Load the next page with AJAX if necessary
            //if (undefined == widget.options._pages[widget.options.page + 1])
            //{
            //    widget._cacheNext();
            //}
        },
        _slideRight: function () {
            var widget = this;
            var element = this.element[0];

            // - Get current left offset.
            var currentOffset = $('div.mc-ui-pager-container', element).position().left;
            // - Get current left offset slide delta.
            var currentPage = widget.options._pages[widget.options.page];
            var currentPageWidth = $(currentPage).outerWidth(true);
            var slideDelta = currentPageWidth;


            // Adjust display height of main element according to the next page to display.
            var displayHeight = $('div.mc-ui-pager-item-container:nth-child(' + (widget.options.page - 1) + ')', element).outerHeight(true);
            widget.options._animating++;
            $(element).animate({ 'height': displayHeight + 'px' }, widget.options.duration, function () { widget.options._animating--; });
            // Slide pageable container left.
            widget.options._animating++;
            $('div.mc-ui-pager-container', element).animate({ 'left': (currentOffset + slideDelta) + 'px' }, widget.options.duration, function () { widget.options._animating--; });

            // - Adjust display index for one page left.
            widget.options.page--;

            var nextPage = widget.options._pages[widget.options.page];

            // - Adjust the paging buttons.
            if (!$(nextPage).hasClass('mc-ui-final')) {
                $('span.mc-ui-pager-next', element).fadeIn(widget.options.duration);
            }
            if (widget.options.page <= 1) {
                $('span.mc-ui-pager-prev', element).fadeOut(widget.options.duration);
            }
        },
        _create: function () {
            // The _create method is where you set up the widget
            var widget = this;
            var element = this.element[0];

            widget._createPagerWrapper();
            /*
            switch (widget.options.animation) {
            case 'leftToRightSlide':
            default:
            widget._createLeftToRightSlide();
            break;
            }
            */
        },
        _init: function () {
            // The _init method is where you initialise or re-initialise the widget
            var widget = this;
            var element = this.element[0];

            widget._initPager();
            widget._initHorizontalPager();
        },
        _setOption: function (key, value) {
            // Use the _setOption method to respond to changes to options
            $.Widget.prototype._setOption.apply(this, arguments)
        },
        destroy: function () {
            // Use the destroy method to reverse everything your plugin has applied
            $.Widget.prototype.destroy.call(this);
            // do something
        }
    });
})(jQuery);


(function ($) {
    $(document).bind('afterClose.facebox', function () {
        $('#facebox .content').empty();
    });
})(jQuery);

