/**
 * 滚动加载js
 */
var pageIndex = 1;//分页
var AjaxObj = null;

//滚动加载
var scrollLoad = function(id, target, url, force) {
    var force = force || false;
	var offsetTop = $(id).offset().top;
	var clientHeight = document.documentElement.clientHeight;
	var scrollTop = $(window).scrollTop();
	var scrollStatus = $(target).data('scrollPagination');
    var keywords = $('input[name="keywords"]').val();

	if ((offsetTop < clientHeight + scrollTop && AjaxObj == null && scrollStatus == 'enabled') || force) {
		$('#loading').fadeIn();

		AjaxObj = $.getJSON(url, {page:pageIndex, keywords:keywords}, function(json) {
			$('#loading').fadeOut();
			$('#load-end').fadeOut();

			if (json.status == 1 && json.totalPage> 0) {
				if (pageIndex == 1) {
					$(target).html(json.content);
				} else {
					$(target).append(json.content);
				}

				if (pageIndex < json.totalPage) {
					pageIndex++;
					if (pageIndex % 3 == 1) {
						$('#load-end').fadeIn();
						$(target).data('scrollPagination', 'disabled');
					}
				} else {
					$(target).data('scrollPagination', 'disabled');
                    $(target).append('<p style="line-height:30px;text-align:center;">数据已全部加载完了...</p>');
				}
			} else {
				$(target).data('scrollPagination', 'disabled');
                $(target).html('<p style="line-height:30px;text-align:center;">还没有任何数据...</p>');
			}

			AjaxObj = null;
		})
	}
}

jQuery(function($) {
    var scrollPageUrl = $("#scroll-ul").data('pageUrl');

    //加载第一页
    scrollLoad('#load-top', '#scroll-ul', scrollPageUrl);

    //绑定滚动加载事件
	$(window).on('scroll', function() {
		scrollLoad('#load-top', '#scroll-ul', scrollPageUrl);
	})

    //每三次询问确认加载更多
    $('#load-end a').on('click', function() {
		$('#load-end').hide();
		$('#scroll-ul').data('scrollPagination', 'enabled');
        scrollLoad('#load-top', '#scroll-ul', scrollPageUrl);
	})

    //搜索
    $('input[name="keywords"]').on('keyup', function() {
        pageIndex = 1;
        $('#scroll-ul').data('scrollPagination', 'enabled');
        scrollLoad('#load-top', '#scroll-ul', scrollPageUrl, true);
    });

});
