/**
 * 拉至底翻页刷新通用接口，
 * 适用于同样情况不同请求的场景
 *
 * @param curPage(Number)       刚开始默认从第几页开始刷新，默认为1
 * @param nextid(string)        存放于topnext的DOM id
 * @param method(string)        请求方式，最终以"type=method"方式请求
 * @param subjectId(string)     刷新列表的DOM id
 * @param url(string)           请求地址
 * @param sort(boolean)         是否以时间归类，并显示时间栏
 */
;(function($, window){
	"use strict";

    var XGScrollRefresh = function(options, success){
        options = options || {};
        this.curPage = options.curPage || 1;
        this.isAllLoaded = false;
        this.refreshId = options.refreshid || "refresh";
        this.nextId = options.nextid || "topnext";
        this.method = options.method || "get";
        this.subjectId = options.subjectid || "user-records";
        this.url = options.url || "viewlrlist.htm";
        this.sort = (undefined == options.sort ? true : options.sort);

        this.lastDatetime = undefined;
        var self = this;
        window.onload = function(){
            self.nextDiv = $("#" + self.nextId);
            self.subjectDiv = $("#" + self.subjectId);
            self.refreshDiv = self.createRefresh(self.refreshid);
            self.initBody();
            self.startRefresh();
        }

        $(window).bind("scroll", function(){ self.startRefresh(); });
    };

    XGScrollRefresh.prototype.initBody = function(){
        var doc = $(document.body);
        var win = $(window);
        if(doc.height() < win.height()){
            doc.height(win.height());
        }
    };

    XGScrollRefresh.prototype.createRefresh = function(id){
        id = id || "refresh";
        var div = "" +
            "<div class='refreshing' id='" + id + "'>" +
                "<i class='fa fa-fw fa-spinner fa-spin large'></i>" +
            "</div>";
        return $(div).appendTo("body");
    };

    XGScrollRefresh.prototype.createPanel = function(datetime){
        var self = this;
        if(self.lastDatetime === datetime || undefined === datetime){
            return null;
        }
        var panel = "" +
            "<div class='datetime yellow bg small' style='" +
            "display: block;" +
            "font-size: 0.7rem;" +
            "width: 100%;" +
            "z-index: 101;" +
            "padding: 0.1rem 0.3rem;" +
            "'>" + datetime + "</div>";
        self.lastDatetime = datetime;
        return panel;
    };

    XGScrollRefresh.prototype.startRefresh = function(){
        if(this.isAllLoaded)
            return false;

        var self = this;
        var documentHeight = $(document).height();
        var windowHeight = $(window).height();
        var screenOffsetHeight = $(window).scrollTop();
        if(documentHeight <= windowHeight + screenOffsetHeight){

            self.refreshDiv.show();
            var url = self.url;
            if(self.method === self.nextDiv.val()){
                url += "?type=" + self.method;
                url += "&";
            }
            else{
                url += "?";
            }
            url += "pageNumber=" + self.curPage;

            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/html; charset=utf-8",
                dataType: "html",
                cache: false,
                success: function(data){
                    var data = data.split("||||");

                    var html = $.trim(data[0]);
                    self.nextDiv.val($.trim(data[1]));
                    if("" == html){
                        self.isAllLoaded = true;
                    }
                    else{
                    	html = html.split("%%");
                        var length = html.length;
                        for(var i = 0; i < length; i += 2){
                            if(self.sort){
                                var panel = self.createPanel(html[i + 1]);
                                self.subjectDiv.append(panel);
                            }
                            self.subjectDiv.append(html[i]);
                        }
                        ++self.curPage;
                        $(document.body).height($(document.body).height() + 30 + "px");
                    }
                    self.refreshDiv.hide();
                },
                error: function(xhr, statusText, err){
                    self.refreshDiv.hide();
                    alert(decodeURI(xhr.statusText));
                }
            });
        }
    };

    $.extend($, {
        ScrollRefresh: function(method, success){
            return new XGScrollRefresh(method, success);
        }
    });
})(window.Zepto || window.jQuery, window);
