/*
 * scrollLoad 1.0 - Extremely Scroll Load Content for jQuery
 * http://code.haohailuo.com/
 *
 * Copyright (c) 2011 Laurence.xu code.haohailuo.com
 * Author Laurence.xu (haohailuo@163.com)
 */
/*
 * use demo
 * $.scrollLoad({'loadurl':'test.php', 'objid':'mypage', 'appendid':'body', 'loadtype':'post'}); ,默认为get加载
*/
(function($) {
	var run_num = 2, requesting = false, request_obj = null, run_interval;
	$.scrollLoad = function(options) {
		var opts = $.extend({}, $.scrollLoad.defaults, options);
		if(opts.loadurl == null || opts.loadurl == '') {
			return false;
		}
		
		if(opts.appendid == null || opts.appendid == '') {
			return false;
		}
		
		if(opts.objid != null && opts.objid != '') {
			$('#'+opts.objid).click(function(){
				//调用加载
				showContent(opts);
			});
		}
		
		run_interval = setInterval(function(){
			cando(opts);
		}, 1000);//每隔2秒钟调用一次cando函数来判断当前滚动条位置。
	};
	var nn=1;
	var n0=0;
	function showContent(opts) {
		
		if(requesting) {
			/*request_obj.abort();
			requesting = false;
			request_obj = null;*/
			return false;
		}

	     if(nn>4) {
			clearInterval(run_interval);
			return false;
		}
		
		requesting = true;
         n0=0;
		var old_content = $('#'+opts.objid).html();
		if(opts.loadtype == 'GET' || opts.loadtype == 'get') {
			$('#'+opts.objid).html('数据加载中...');
			
			var loadmoreurl=opts.loadurl.replace("{page}",run_num);			
			var hTag = document.createElement("script");
			hTag.type = "text/javascript";
			hTag.src = "/d.aspx?=http://www.9ku.com"+loadmoreurl;
			document.getElementsByTagName("head")[0].appendChild(hTag);			
			
			request_obj = $.get(loadmoreurl, function(data) {
				requesting = false;
				request_obj = null;
				if(data.indexOf("class")==-1){if(nn<5){n0=1;nn=nn+1;setTimeout(function(){showContent(opts);},5000);} $("#mypage").hide();return false;}//判断请求数据为空时候隐藏加载按钮
				
				if(n0==0)
		{
		run_num++;
		}
				$('#'+opts.appendid).append(data);
				$('#'+opts.objid).html(old_content);
			});
		}else {
			$('#'+opts.objid).html('数据加载中...');
			request_obj = $.post(opts.loadurl, function(data) {
				requesting = false;
				request_obj = null;
					if(n0==0)
		{
		run_num++;
		}
				$('#'+opts.appendid).append(data);
				$('#'+opts.objid).html(old_content);
			});
		}
	
		
	}

	function cando(opts){
		if(opts.loadnum > 0 && opts.loadnum <= run_num) {
			clearInterval(run_interval);
			return false;
		}
		
		var heights = $(window).height() + document.documentElement.scrollTop;
	
	      
		if(heights > $('#'+opts.objid).offset().top) {
			var nnn=$('#'+opts.objid).html();
			if(nnn.indexOf("数据加载中")==-1)
			{
             //alert(heights+"----"+$('#'+opts.objid).offset().top);
             showContent(opts);//如果是，调用showContent函数加载内容。
			}
			
		}
	}
	
	//默认参数
	$.scrollLoad.defaults = {
		objid: null,			//点击触发加载的目标元素
		appendid: null,			//加载的内容添加到的目标元素
		loadnum: 5,				//加载次数
		loadurl: null,			//加载的url地址
		loadtype: 'GET'			//ajax加载方式
	};
}(jQuery));