﻿
jQuery.fn.jpage = function(config){
	init("#"+this.attr("id"),config);
}

function init(t,config){
    
    var initPage=true;
	var configPage = config.perPage > 0 ? config.perPage : 10;	
																				
	//var perPage = $.cookie(t+"_perPage") == null ? configPage : parseInt($.cookie(t+"_perPage"));				//每页显示记录数
	var perPage = configPage;
	var suffix = config.suffix==null ? '' : config.suffix;
	$.cookie(t+'_currentPage', 1);
	$.cookie(t+'_perPage', perPage);
	var proxyUrl = config.proxyUrl ;														                    //数据代理地址																															//组大小
	var barPosition = config.barPosition == null ? 'normal' : config.barPosition;								//工具条位置
	var ajaxParam = config.ajaxParam;																																//ajax的请求参数
	var showMode = config.showMode == null ? 'full' : config.showMode;											//显示模式
    var parm=config.parm;
    var additional=config.Additional;
    
	//私有变量
	var currentPage = $.cookie(t+"_currentPage") == null ? 1 : parseInt($.cookie(t+"_currentPage"));			//当前页码
	var startRecord = 0;																																								//每页起始记录
	var endRecord = 0;	 
																																								//每页结束记录
	var totalPage = 0;
	var totalRecord = $.cookie(t+"_totalRecord") == null ? 0 : parseInt($.cookie(t+"_totalRecord"));;	

	//数据容器
	var container = '<div class="pgContainer"></div>'

	//添加工具条
	var toolbar = '<table class="pgToolbar"><tr><td>';
	toolbar += '<table class="pgPanel"><tr>';
	if(additional!=null)
	{
	    toolbar+='<td class="addTD" style="text-align:left">'+additional+'</td>';
	}

	if (showMode == 'full') { //|| showMode == 'normal'){
	    toolbar += '<td><select class="pgPerPage">';
	    if (config.perPage > 0) {
	        for (var i = 0; i < config.pageCountType.length; i++) {
	            toolbar += '<option value=' + config.pageCountType[i] + '>' + config.pageCountType[i] + suffix + '</option>';
	        }
	        toolbar += '</select>&nbsp;&nbsp;</td>';
	        toolbar += '<td class="separator">&nbsp;</td>';
	    }
	}
	else if (showMode == 'normal') {
	    toolbar += '<td style=\'width:140px;\'>&nbsp;</td><td>&nbsp;</td>';
	}
	
	toolbar += '<td class="pgBtn pgFirst" title="首页">&nbsp;</td>';
	toolbar += '<td class="pgBtn pgPrev" title="上页">&nbsp;</td>';
	if(showMode != 'mini'){
		toolbar += '<td class="separator">&nbsp;</td>';
        toolbar += '<td>第 <input class="pgCurrentPage" type="text" value="0" title="页码" /> 页 / 共 <span class="pgTotalPage">0</span> 页</td>';
		toolbar += '<td class="separator">&nbsp;</td>';
	}
	toolbar += '<td class="pgBtn pgNext" title="下页">&nbsp;</td>';
	toolbar += '<td class="pgBtn pgLast" title="尾页">&nbsp;</td>';

    if(showMode != 'normal')
    {
	    toolbar += '<td class="separator">&nbsp;</td>';
	    toolbar += '<td class="pgBtn pgRefresh" title="刷新"></td>';
    }
	if(showMode == 'full'){
		toolbar += '<td class="separator">&nbsp;</td>';
		toolbar += '<td class="pgSearchInfo">共&nbsp;<span class="pgTotalRecord"></span>&nbsp;条,第&nbsp;<span class="pgStartRecord"></span>&nbsp;-&nbsp;<span class="pgEndRecord"></span>&nbsp;条</td>';
	}
	toolbar += '</tr></table>';
	toolbar += '</td></tr></table>';
	
	switch(barPosition){
	
		case 'top':
			$(t).html(toolbar+container);
			break;
		case 'bottom':
			$(t).html(container+toolbar);
			break;
		case 'normal':
			$(t).html(toolbar+container+toolbar);
			break;	
		case 'no':
			$(t).html(container);
			break;
		default:
			$(t).html(toolbar+container+toolbar);
	}
 
	var btnRefresh = $(t+" .pgRefresh");														//刷新按钮
	var btnNext =$(t+" .pgNext");																//下一页按钮
	var btnPrev = $(t+" .pgPrev");																//上一页按钮
	var btnFirst = $(t+" .pgFirst");															//首页按钮
	var btnLast = $(t+" .pgLast");																//末页按钮
	var btnGo = $(t+" .pgNext,"+t+" .pgLast");
	var btnBack = $(t+" .pgPrev,"+t+" .pgFirst");
	var btn = $(t+" .pgFirst,"+t+" .pgPrev,"+t+" .pgNext,"+t+" .pgLast");
		
	var valContainer = $(t+" .pgContainer");
    var btn = $(t+" .pgFirst,"+t+" .pgPrev,"+t+" .pgNext,"+t+" .pgLast");
	var mask;
	
	var valCurrentPage = $(t+" .pgCurrentPage");
	var valStartRecord = $(t+" .pgStartRecord");
	var valEndRecord =$(t+" .pgEndRecord");
	var valContainer = $(t+" .pgContainer");
	var valPerPage = $(t+" .pgPerPage");
	var valTotalPage = $(t+" .pgTotalPage");
	var valTotalRecord = $(t+" .pgTotalRecord");
	
	valPerPage.change(function(){
 	    var pageSize = this.value;
 	    $(valPerPage).each(function(){
 	        $(this).attr("value",pageSize);                  
        });
        
        perPage = parseInt($(this).val());
		currentPage = 1;
		totalPage = Math.ceil(totalRecord/perPage);
		getRemoteData();
			
		//$.historyLoad(Math.random());        
 	});	 
 	
 	//刷新按钮监听
	btnRefresh.bind("mousedown",pressHandler).bind("mouseup",unpressHandler).bind("mouseout",unpressHandler);
	
	//按钮监听
	btnNext.click(
		function(){
			if(currentPage < totalPage){
			    currentPage += 1;
			    getRemoteData();
			    //$.historyLoad(Math.random());
			}
		}
	);	
	btnPrev.click(
		function(){
			if(currentPage > 1){
			    currentPage -= 1;
			    getRemoteData();
			    //$.historyLoad(Math.random());
			}
		}
	);
	btnFirst.click(
		function(){
			if(currentPage > 1){
			    currentPage = 1;
			    getRemoteData();
			    //$.historyLoad(Math.random());
			}
		}
	);
	btnLast.click(
		function(){
			if(currentPage < totalPage){
			    currentPage = totalPage;
			    getRemoteData();
			    //$.historyLoad(Math.random());
			}
		}
	);
	btnRefresh.click(
		function(){
		    getRemoteData();
			//$.historyLoad(Math.random());
		}
	);
	
	//页码输入框监听
	valCurrentPage.keydown(
		function(e){
			var targetPage = parseInt(Number($(this).val()));

            

			if((window.event ? e.keyCode : e.which)==13 && targetPage>=1 && targetPage<=totalPage){
			    //startLoad();
			    currentPage = targetPage;
			    getRemoteData();
			    //$.historyLoad(Math.random());
			    overLoad();
			}
		}
	);	
	
	getRemoteData();
//	$.historyInit(getRemoteData);	
//  $.historyLoad(Math.random());
 	
 	/*
	 * 置为正在检索状态
	 */
	function startLoad(){
		$(t).addClass("container");
		mask = document.createElement('div');
		$(mask).addClass("mask");
		$(mask).css("height",$(t).height()+"px")
		       .css("width",$(t).width()+"px")
		       .css("left",$(t).offset().left+"px")
		       .css("top",$(t).offset().top+"px");
		$(t).append(mask);		
		$(t+" .pgRefresh").addClass("pgLoad");
//		$(t+" .pgRefresh").removeClass("pgRefresh");
		$(t+" .pgSearchInfo").html("正在检索中,请稍后...");
	}
	
	/*
       * 置为结束检索状态
       */
	function overLoad(){
		$(t+" .pgRefresh").removeClass("pgLoad");
		$(t+" .pgSearchInfo").html('共&nbsp;<span class="pgTotalRecord">'+totalRecord+'</span>&nbsp;条,第&nbsp;<span class="pgStartRecord">'+startRecord+'</span>&nbsp;-&nbsp;<span class="pgEndRecord">'+endRecord+'</span>&nbsp;条');
		$(mask).remove();
		try{Resize();}
		catch(e){}
	}
	
	
	
	/**
	   * 获得远程数据
	   */
	function getRemoteData(){
		    startLoad();

		    $.ajax(
			    {
    //				type: "POST",
				    url: proxyUrl + "?CurrentPage="+currentPage+"&PerPage="+perPage+"&parm="+parm,
				    cache: false,
				    data: ajaxParam,
				    dataType: "html",
				    timeout: 10000,
				    success: function(msg){
				   
				        var result = msg.split("|"); 
				        valContainer.html(result[0]);	
 
				        getStartEnd($(result[1]).text(),$(result[2]).text());
				        
				        if(result.length>3)
				        {
				            ExecutiveFunction($(result[3]).text());
				        }
				        
					    refresh();
					    overLoad();
				    },
				    error: function(){
    				
				        $.cookie(t+'_currentPage', 1);
				        $.cookie(t+'_perPage', configPage);
				        $.cookie(t+'_totalRecord', 0);
    				    
					    alert("请求失败或超时,请稍后再试!");
					    overLoad();
					    return;
				    }
			    }
		    );

	}
	
		/**
	   * 获得当前页开始结束记录
	   */
	function getStartEnd(paTotalRecord,paTotalPage){
	    totalPage=paTotalPage;
	    totalRecord=paTotalRecord;
	    startRecord = (currentPage-1)*perPage+1;
	    endRecord = Math.min(currentPage*perPage,totalRecord);
	}
	
	var getRemoteDataTimes=0;
		/**
	   * 刷新工具栏状态
	   */
	function refresh(){
		//当前页码写入cookie
		$.cookie(t+'_currentPage', currentPage);
		$.cookie(t+'_perPage', perPage);
		
		var temptotalRecord = $.cookie(t+"_totalRecord") == null ? 0 : parseInt($.cookie(t+"_totalRecord"));;	
		$.cookie(t+'_totalRecord', totalRecord);
		
		if(totalRecord != 0)
		{		
		    if(temptotalRecord != totalRecord && !initPage)
		    {
		        getRemoteDataTimes = parseInt(getRemoteDataTimes)+1;
		        overLoad();
		        if(getRemoteDataTimes==3)
		        {
		            alert('服务忙,请稍候再试...');
		            return;
		        }
		        else
		        {
		            tempTotalPage = Math.ceil(totalRecord/perPage);
		            if(tempTotalPage<currentPage)
		            {
		                currentPage=tempTotalPage;
		                getStartEnd();
		            }
		            getRemoteData();
		            return;
		        }
		    }
    		
		    initPage=false;
		    getRemoteDataTimes=0;
    
		    valCurrentPage.val(currentPage);
		    valStartRecord.html(startRecord);
		    valEndRecord.html(endRecord);
		    valTotalPage.html(totalPage);

		    btn.unbind("mousedown",pressHandler);
		    btn.bind("mouseup",unpressHandler);
		    btn.bind("mouseout",unpressHandler);

		    if(currentPage == totalPage && totalPage!=1){
			    enabled();
			    btnBack.bind("mousedown",pressHandler);
			    btnNext.addClass("pgNextDisabled");
			    btnLast.addClass("pgLastDisabled");
		    }else if(currentPage == 1 && totalPage!=1){
			    enabled();
			    btnGo.bind("mousedown",pressHandler);
			    btnPrev.addClass("pgPrevDisabled");
			    btnFirst.addClass("pgFirstDisabled");
		    }
		    else if(currentPage == 1 && totalPage == 1)
		    {
			    enabled();
			    btnGo.bind("mousedown",pressHandler);
			    btnNext.addClass("pgNextDisabled");
			    btnLast.addClass("pgLastDisabled");
			    btnPrev.addClass("pgPrevDisabled");
			    btnFirst.addClass("pgFirstDisabled");		    
		    }
		    else{
			    enabled();
			    btnBack.bind("mousedown",pressHandler);
			    btnGo.bind("mousedown",pressHandler);
			    btnNext.addClass("pgNext");
			    btnPrev.addClass("pgPrev");
			    btnFirst.addClass("pgFirst");
			    btnLast.addClass("pgLast");
		    }
		    //$(t).css("height", $(t).attr("scrollHeight"));
		}
		else
		{
		    NoRecord();
		}
	}
	
	function NoRecord()
	{	        
	    $(t).html("<div class='norecord'>很遗憾,没有检索到任何记录!</div>")
	        .css("top",$(t).offset().top+"px")
	        .css("left",$(t).offset().left+"px")
	    /*$(t).css("height","50px");*/
	}	
	
	/*
	 * 移除按钮disabled状态样式
	 */
	function enabled(){
			btnNext.removeClass("pgNextDisabled");
			btnPrev.removeClass("pgPrevDisabled");
			btnFirst.removeClass("pgFirstDisabled");
			btnLast.removeClass("pgLastDisabled");
	}
	
	
	/**
	   * 添加按钮按下状态样式
	   */
	function pressHandler(){
		$(this).addClass("pgPress");
	}

	/**
	   * 移除按钮按下状态样式
	   */
	function unpressHandler(){
		$(this).removeClass("pgPress");
	}
	
}
