﻿(function($) {
    $.widget("cimbrian.pagedlist", {
        _init: function() {
            var self = this;
            self._search();
        },
        _renderPager: function(pageIndex, pageCount, self) {
            if (self.options.pagerControl && self.options.searchObject) {
                var ctrl = $("#" + self.options.pagerControl);
                var pageSize = self.options.searchObject.PageSize;
                ctrl.empty();
                if (pageCount > 0) {
                    var first = $("<a />")
                    .attr("href", "#")
                    .addClass("pagedList-pageNumber hideThis")
                    .text("<<|")
                    .click(function() {
                        self.page(0);
                        return false;
                    })
                    .appendTo(ctrl);
                    var previous = $("<a />")
                    .attr("href", "#")
                    .addClass("pagedList-pageNumber hideThis")
                    .text("<")
                    .click(function() {
                        self.page((pageIndex > 0) ? pageIndex - 1 : 0);
                        return false;
                    })
                    .appendTo(ctrl);
                    var startIndex = 0;
                    var endIndex = 0;
                    if (pageCount <= 10) {
                        endIndex = (pageCount - 1);
                    } else {
                        if (pageIndex < 10) {
                            endIndex = 9;
                        } else if ((pageCount - pageIndex) <= 10) {
                            startIndex = (pageCount - 11);
                            endIndex = (pageCount - 1);
                        } else {
                            startIndex = (pageIndex - 5);
                            endIndex = (pageIndex + 5);
                        }
                    }
                    for (var i = startIndex; i <= endIndex; i++) {
                        var lnk = $("<a />")
                                    .attr({
                                        "href": "#",
                                        "pageNumber": i
                                    })
                                    .addClass((i == pageIndex ? " pagedList-selectedPage" : "pagedList-pageNumber"))
                                    .text(i + 1)
                                    .click(function() {
                                        self.page(parseInt($(this).attr("pageNumber")));
                                        return false;
                                    })
                                    .appendTo(ctrl);
                    }
                    var next = $("<a />")
                    .attr("href", "#")
                    .addClass("pagedList-pageNumber hideThis")
                    .text(">")
                    .click(function() {
                        self.page((pageIndex < (pageCount - 1)) ? pageIndex + 1 : pageIndex);
                        return false;
                    })
                    .appendTo(ctrl);
                    var last = $("<a />")
                    .attr("href", "#")
                    .addClass("pagedList-pageNumber hideThis")
                    .text("|>>")
                    .click(function() {
                        self.page(pageCount - 1);
                        return false;
                    })
                    .appendTo(ctrl);
                }
            }
        },
        _render: function(response, self, pageNum, prevPageNum) {
            self.options.pageCount = response.PageCount;
            //only want to check for previous search terms on initial load
            self.options.isFirstQuery = false;
            self.options.searchObject.IsFirstQuery = false;
            var goingBack = (pageNum < prevPageNum);
            //add the new page
            var offsetClass = (goingBack ? "pagedList-offRight" : "pagedList-offLeft");
            var newPage = $("<div />")
                .html(response.HTML)
                .attr("pageNumber", pageNum)
                .addClass("pagedList-page " + offsetClass)
                .css('opacity', 0.1)
                .appendTo(self.element);
            //move new page into viewport
            newPage
                .animate({ left: "0px" }, 500)
                .animate({ opacity: 1 }, 500, function() {
                    if ($.browser.msie) {
                        this.style.removeAttribute("filter");
                    }
                })
                .removeClass(offsetClass)
                .addClass("pagedList-center");
            self._renderPager(pageNum, response.PageCount, self);
            if (prevPageNum != -1 && self.options.autoScroll) {
                var targetOffset = self.element.offset().top - 30;
                $('html,body').animate({ scrollTop: targetOffset }, 1000);
            }
            self._trigger("onLoadComplete");
        },
        _search: function(prevPageNum) {
            var self = this;
            if (self.options.url != null && self.options.searchObject != null) {
                $.ajax({
                    url: self.options.url,
                    async: self.options.async,
                    data: $.toJSON(self.options.searchObject),
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    success: function($response, $status) {
                        self.options.searchObject.PageIndex = $response.PageIndex;
                        self._render($response, self, self.options.searchObject.PageIndex, prevPageNum);
                    },
                    error: function($error, $message) {
                        //alert($error + " " + $message);
                    }
                });
            }
        },
        search: function(searchTerms, sortFld, sortDir) {
            var self = this;
            var searchObject = new Object();
            searchObject.PageIndex = 0;
            searchObject.PageSize = self.options.pageSize;
            searchObject.SearchTerms = searchTerms;
            searchObject.SortField = sortFld;
            searchObject.SortDirection = sortDir;
            searchObject.IsFirstQuery = self.options.isFirstQuery;
            self.options.searchObject = searchObject;
            var prevPage = $(".pagedList-center");
            if (prevPage.length > 0) {
                prevPage
                    .animate({ opacity: 0.1 }, 500)
                    .animate({ left: (self.element.width() + 10) + "px" }, 500, function() {
                        self.element.empty();
                        self._search();
                    });
            } else {
                self.element.empty();
                self._search(-1);
            }
        },
        page: function(pageNum) {
            var self = this;
            if (pageNum <= self.options.pageCount) {
                //we haven't yet loaded this page
                var prevPage = $(".pagedList-center");
                var prevPageNumber = parseInt(prevPage.attr("pageNumber"));
                if (prevPage.length > 0 && prevPageNumber != pageNum) {
                    var move = (self.element.width() + 10) + "px";
                    if (pageNum < prevPageNumber) {
                        //going back to a lower page, slide to the left
                        move = "-300px";
                    }
                    prevPage
                    .animate({ opacity: 0.1 }, 500)
                    .animate({ left: move }, 500, function() {
                        prevPage.remove();
                        var searchObj = self.options.searchObject;
                        searchObj.PageIndex = pageNum;
                        self.options.searchObject = searchObj;
                        self._search(prevPageNumber);
                    });
                }
            }
        }
    });

    $.extend($.cimbrian.pagedlist, {
        version: "1.7.2",
        defaults: {
            searchObject: null,
            async: true,
            url: null,
            pagerControl: null,
            pageSize: 5,
            pageCount: 0,
            autoScroll: true,
            isFirstQuery: true
        }
    });
})(jQuery);
