/**
   * jpage for  jQuery分頁插件
   * 功能:
   * 1.指定頁數內靜態分頁
   * 2.超過指定頁數後ajax請求下一組靜態分頁
   * 3.支持cookie記錄當前頁碼和分組大小
   * 4.支持瀏覽器前進後退
   * 5.搜索引擎抓取
   * @author 陳健
   * @version 3.0
   * @date 2015-06-25
   * @param config 插件配置
   */
(function(){
	var i18n = {
		'zh-cn' : {
			noRecord: '沒有檢索到任何記錄!',
			error: '請求失敗或超時,請稍後再試!'
		},
		'zh-tw' : {
			noRecord: '沒有檢索到任何記錄!',
			error: '請求失敗或超時,請稍後再試!'
		}
	}
	function getLang(langType) {
		return i18n[langType];
	}
	jQuery.fn.jpage = function(config){
		var canPushState = Boolean(window.history.pushState);//是否支持pushState
		var containerId = this.attr("id");
		init("#"+containerId,config);//初始化
		
		/**
		   * 初始化,主程序
		   * @param t 容器的ID,帶#號
		   * @param config 插件配置
		   */
		function init(t,config){
			//公有變量
			if(!t)
				return;
			var initStore = config.dataStore;			//初始數據
			var xmlStore = $(createXMLDocument(initStore));
			var dataStore = new Array();
			xmlStore.find('record').each(
				function(){
					dataStore.push($(this).text());
				}
			);
			var lang = typeof zh_choose != 'undefined' && zh_choose == 't' ? getLang('zh-tw') : getLang('zh-cn');
			var openCookies = config.openCookies != null ? config.openCookies : true;
			var configPage = config.perPage > 0 ? config.perPage : 10;
			var perPage = !openCookies || $.cookie(t+"_perPage") == null ? configPage : parseInt($.cookie(t+"_perPage"));	//每頁顯示記錄數
			var totalRecord = config.totalRecord;																			//總記錄數
			if(totalRecord==undefined)
				totalRecord = 0;
			else{
				totalRecord = config.totalRecord > 0 ? config.totalRecord : 0;	
				if(totalRecord == 0){
					$(t).css("text-align","center");
					$(t).css("line-height","50px");
					$(t).html(lang.noRecord);
					return;
				}
			}	
			var proxyUrl = config.proxyUrl != null ? config.proxyUrl : 'dataproxy.jsp';									//數據代理地址
			var groupSize = config.groupSize != null ? config.groupSize : 1;											//組大小
			var barPosition = config.barPosition == null || config.barPosition == ""? 'bottom' : config.barPosition;	//工具條位置
			var ajaxParam = config.ajaxParam;	
			//ajax的請求參數
			var searchstart = config.ajaxParam.searchstart;
			var showMode = config.showMode == null || config.showMode == '' ? 'full' : config.showMode;					//顯示模式
			var allowChangePerPage = config.allowChangePerPage == null || config.allowChangePerPage ? true : false;		//是否允許切換每頁顯示數
			var themeName = config.themeName == null || config.themeName == '' ? 'default' : config.themeName;			//主題名稱
			var dataBefore = config.dataBefore == null ? '' : config.dataBefore;
			var dataAfter = config.dataAfter == null ? '' : config.dataAfter;
			var callBack = config.callBack == null ? function(){} : config.callBack;
		
			//私有變量
			var totalPage = Math.ceil(totalRecord/perPage);																//總頁數
			var currentPage = !openCookies || $.cookie(t+"_currentPage") == null ? 1 : parseInt($.cookie(t+"_currentPage"));//當前頁碼
			var uid = getUrlParam('uid');
			if (uid == containerId) {
				currentPage = parseInt(getUrlParam('pageNum'));
			}
			if(currentPage>totalPage){
				currentPage=totalPage;
			}
			if(searchstart*1==1){
				currentPage = 1;
			}
			var startRecord;																							//每頁起始記錄,相對於當前組
			var endRecord;	 																							//每頁結束記錄,相對於當前組
			var gpStartPage;																							//組開始頁
			var gpEndPage;																								//組結束頁
			var gpStartRecord = 1;																						//組開始記錄
			var gpEndRecord = perPage * groupSize;
		
			//數據容器
			var container = '
';
		
			//添加工具條
			var toolbar = '';
		
			if(configPagegroupSize)
				getRemoteData();
			else{
				getStartEnd();
				loadData();
				refresh();
			}
			//瀏覽器前進後退
			function browserChangePage() {
				uid = getUrlParam('uid');
				var targetPage;
				if (uid == containerId) {
					targetPage = parseInt(getUrlParam('pageNum'));
				} else {
					targetPage = 1;
				}
				if(!dataStore || (targetPage > currentPage && currentPage == gpEndPage) || (targetPage < currentPage && currentPage == gpStartPage)){
					currentPage = targetPage;
					getGroupStartEnd();
					getStartEnd();
					getRemoteData();
				}else{
					currentPage = targetPage;
					getStartEnd();
					loadData();
					refresh();
				}
			}
			if (canPushState) {//HTML5支持pushSate
				window.addEventListener('popstate', browserChangePage);
			} else {
				window.onhashchange = browserChangePage;
			}
		
			//刷新按钮监听
			btnRefresh.bind("mousedown",pressHandler).bind("mouseup",unpressHandler).bind("mouseout",unpressHandler);
			//按钮链接
			modifyBtnLink({
				uid: containerId,
				pageNum: currentPage
			});
		
			//刷新工具栏
			refresh();
			//按钮监听
			btn.click(
				function() {
					if ($(this).is('[disabled]')) {
						return false;
					}
					
					btn.removeAttr('href');
				}
			);
			
			btnNext.click(
				function(){
					if(currentPage < totalPage){
						if(!dataStore || currentPage == gpEndPage){
							currentPage += 1;
							getGroupStartEnd();
							getStartEnd();
							getRemoteData();
						}else{
							currentPage += 1;
							getStartEnd();
							loadData();
							refresh();
						}
					}
					var hashParams = {uid: containerId};
					hashParams.pageNum = currentPage;
					pushState(hashParams);
					modifyBtnLink(hashParams);
					return false;
				}
			);	
			btnPrev.click(
				function(){
					if(currentPage > 1){
						if(!dataStore || currentPage == gpStartPage){
							currentPage -= 1;
							getGroupStartEnd();
							getStartEnd();
							getRemoteData();
						}else{
							currentPage -= 1;
							getStartEnd();
							loadData();
							refresh();
						}
					}
					var hashParams = {uid: containerId};
					hashParams.pageNum = currentPage;
					pushState(hashParams);
					modifyBtnLink(hashParams);
					return false;
				}
			);
			btnFirst.click(
				function(){
					if(!dataStore || currentPage > 1){
						if(gpStartPage > 1){
							currentPage = 1;
							getGroupStartEnd();
							getStartEnd();
							getRemoteData();
						}else{
							currentPage = 1;
							getStartEnd();
							loadData();
							refresh();
						}
					}
					var hashParams = {uid: containerId};
					hashParams.pageNum = currentPage;
					pushState(hashParams);
					modifyBtnLink(hashParams);
					return false;
				}
			);
			btnLast.click(
				function(){
					if(!dataStore || currentPage < totalPage){
						if(gpEndPage > 0 && gpEndPage < totalPage){
							currentPage = totalPage;
							getGroupStartEnd();
							getStartEnd();
							getRemoteData();
						}else{
							currentPage = totalPage;
							getStartEnd();
							loadData();
							refresh();
						}
					}
					var hashParams = {uid: containerId};
					hashParams.pageNum = currentPage;
					pushState(hashParams);
					modifyBtnLink(hashParams);
					return false;
				}
			);
			btnRefresh.click(
				function(){
					getGroupStartEnd();
					getStartEnd();
					getRemoteData();
				}
			);
			
			//页码输入框监听
			valCurrentPage.keydown(
				function(event){
					var targetPage = parseInt($(this).val());
					if(event.keyCode==13 && targetPage>=1 && targetPage<=totalPage){
						if(!dataStore || gpStartPage > targetPage || (gpEndPage > 0 && gpEndPage < targetPage)){
							currentPage = targetPage;
							getGroupStartEnd();
							getStartEnd();
							getRemoteData();
						}else{
							currentPage = targetPage;
							getStartEnd();
							loadData();
							refresh();
						}
					}
					var hashParams = {uid: containerId};
					hashParams.pageNum = currentPage;
					pushState(hashParams);
					modifyBtnLink(hashParams);
				}
			);
			
			valPerPage.change(
				function(){
					valPerPage.val($(this).val());
					perPage = parseInt($(this).val());
					currentPage = 1;
					totalPage = Math.ceil(totalRecord/perPage);
					if(groupSize){
						getGroupStartEnd();
						getStartEnd();
						getRemoteData();
					}else{
						getStartEnd();
						loadData();
						refresh();				
					}			
				}
			);
			if (typeof zh_choose != 'undefined' && zh_choose == 't') {//转繁体
				zh_tran('t');
			}
			
			/*********************************init私有函数***************************************************/
			/**
			   * 置为正在检索状态
			   */
			function startLoad(){
				$(t).addClass(themeName+"_container");
				mask = document.createElement('div');
				$(mask).addClass(themeName+"_mask");
				$(mask).css("height",$(t).height());
				$(t).append(mask);
				$(t+" ."+themeName+"_pgRefresh").addClass(themeName+"_pgLoad");
				//$(t+" ."+themeName+"_pgSearchInfo").html("正在检索中,请稍后...");
			}
			
			/**
			   * 置为结束检索状态
			   */
			function overLoad(){
				$(t+" ."+themeName+"_pgRefresh").removeClass(themeName+"_pgLoad");
				$(t+" ."+themeName+"_pgTotalRecord").text(totalRecord);
				$(t+" ."+themeName+"_pgStartRecord").text(startRecord+gpStartRecord-1);
				$(t+" ."+themeName+"_pgEndRecord").text(endRecord+gpStartRecord-1);
				$(mask).remove();
				$(t).removeClass(themeName+"_container");
				valStartRecord = $(t+" ."+themeName+"_pgStartRecord");
				valEndRecord =$(t+" ."+themeName+"_pgEndRecord");
			}
		
			/**
			   * 获得远程数据
			   */
			function getRemoteData(){
				startLoad();
				$.ajax(
					{
						type: "POST",
						url: proxyUrl + "?startrecord="+gpStartRecord+"&endrecord="+gpEndRecord+"&perpage="+perPage,
						cache: false,
						data: ajaxParam,
						dataType: "xml",
						timeout: 30000,
						success: function(xml){
							xmlStore = $(xml);
							totalRecord = xmlStore.find('totalrecord').text();
							totalPage = xmlStore.find('totalpage').text();
							dataStore = null;
							dataStore = new Array();
							xmlStore.find('record').each(
								function(){
									dataStore.push($(this).text());
								}
							);
							
							if(totalRecord==0)
								$('.'+themeName+'_pgToolbar').remove();
							getStartEnd();
							loadData();
							refresh();
							overLoad();
						},
						error: function(){
							alert(lang.error);
							overLoad();
							return;
						}
					}
				);
			}
			/**
			   * 获得当前页开始结束记录
			   */
			function getStartEnd(){
				if(groupSize){
					startRecord = (currentPage-1)*perPage+1 - gpStartRecord + 1;
					endRecord = Math.min(currentPage*perPage,totalRecord) - gpStartRecord + 1;
				}else{
					startRecord = (currentPage-1)*perPage+1;
					endRecord = Math.min(currentPage*perPage,totalRecord);
				}
			}
		
			/**
			   * 获得当前组开始结束页码
			   */
			function getGroupStartEnd(){
				if(groupSize==null){
					return;
				}
				var groupId = groupSize > 0 ? Math.ceil(currentPage/groupSize) : 0;
				gpStartPage = (groupId-1)*groupSize+1;
				if(totalRecord > 0){
					gpEndPage = Math.min(groupId*groupSize,totalPage);
				}
				
				gpStartRecord = (gpStartPage-1)*perPage+1;
				if(totalRecord > 0){
					gpEndRecord = Math.min(gpEndPage*perPage,totalRecord);
				}
			}
		
			/**
			   * 刷新數據容器
			   */
			function loadData(){
				if(dataStore==null||dataStore.length==0){
					valContainer.css("text-align","left");
					valContainer.css("line-height","22px");
					valContainer.html(lang.noRecord);
					return;
				}
				
				var view = "";
				for(var i=startRecord-1;i<=endRecord-1 && i < dataStore.length;i++){
					view += dataStore[i].replace("{id}",gpStartRecord+i);
				}
				valContainer.html(dataBefore + view + dataAfter);
				
				//翻頁回調函數
				callBack();
			}
		
			/**
			   * 刷新工具欄狀態
			   */
			function refresh(){
				if(openCookies){
					//當前頁碼寫入cookie
					$.cookie(t+'_currentPage', currentPage);
					$.cookie(t+'_perPage', perPage);
				}
		
				valCurrentPage.val(currentPage);
				valStartRecord.html(startRecord+gpStartRecord-1);
				valEndRecord.html(endRecord+gpStartRecord-1);
				valTotalPage.html(totalPage);
				
				btn.unbind("mousedown",pressHandler);
				btn.bind("mouseup",unpressHandler);
				btn.bind("mouseout",unpressHandler);
				
				if(currentPage == 1 && currentPage != totalPage){
					enabled();
					btnGo.bind("mousedown",pressHandler);
					btnPrev.addClass(themeName+"_pgPrevDisabled").attr('disabled', 'disabled');
					btnFirst.addClass(themeName+"_pgFirstDisabled").attr('disabled', 'disabled');
				}else if(currentPage != 1 && currentPage == totalPage){
					enabled();
					btnBack.bind("mousedown",pressHandler);
					btnNext.addClass(themeName+"_pgNextDisabled").attr('disabled', 'disabled');
					btnLast.addClass(themeName+"_pgLastDisabled").attr('disabled', 'disabled');
				}else if(currentPage == 1 && currentPage == totalPage){
					disabled();
				}else{
					enabled();
					btnBack.bind("mousedown",pressHandler);
					btnGo.bind("mousedown",pressHandler);
					btnNext.addClass(themeName+"_pgNext");
					btnPrev.addClass(themeName+"_pgPrev");
					btnFirst.addClass(themeName+"_pgFirst");
					btnLast.addClass(themeName+"_pgLast");
				}
				
			}
			
			/**
			   * 移除按鈕disabled狀態樣式
			   */
			function enabled(){
					btnNext.removeClass(themeName+"_pgNextDisabled").removeAttr('disabled');
					btnPrev.removeClass(themeName+"_pgPrevDisabled").removeAttr('disabled');
					btnFirst.removeClass(themeName+"_pgFirstDisabled").removeAttr('disabled');
					btnLast.removeClass(themeName+"_pgLastDisabled").removeAttr('disabled');
			}
			
			/**
			   * 添加按鈕disabled狀態樣式
			   */
			function disabled(){
					btnNext.addClass(themeName+"_pgNextDisabled").attr('disabled', 'disabled');
					btnPrev.addClass(themeName+"_pgPrevDisabled").attr('disabled', 'disabled');
					btnFirst.addClass(themeName+"_pgFirstDisabled").attr('disabled', 'disabled');
					btnLast.addClass(themeName+"_pgLastDisabled").attr('disabled', 'disabled');
			}
		
			/**
			   * 添加按鈕按下狀態樣式
			   */
			function pressHandler(){
				$(this).addClass(themeName+"_pgPress");
			}
		
			/**
			   * 移除按鈕按下狀態樣式
			   */
			function unpressHandler(){
				$(this).removeClass(themeName+"_pgPress");
			}
			
			/**
			 * 修改按鈕鏈接
			 */
			function modifyBtnLink(hashParams) {
				var pageNum = hashParams.pageNum;
				hashParams.pageNum = pageNum + 1;
				btnNext.attr('href', getUrl(hashParams));
				hashParams.pageNum = totalPage;
				btnLast.attr('href', getUrl(hashParams));
				hashParams.pageNum = pageNum - 1;
				btnPrev.attr('href', getUrl(hashParams));
				hashParams.pageNum = 1;
				btnFirst.attr('href', getUrl(hashParams));
			}
		}
		
		/**
		 * 創建XML文檔
		 */
		function createXMLDocument(text) {
			var xmlDoc = null;
			try{// Internet Explorer
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = "false";
				xmlDoc.loadXML(text);
			}catch (e){
				try{// Firefox, Mozilla, Opera, etc.
					parser = new DOMParser();
					xmlDoc = parser.parseFromString(text, "text/xml");
				}catch (e) {
				}
			}
			return xmlDoc;
		}
		
		/**
		 * 組裝頁面路徑
		 */
		function getUrl(hashParams) {
			var pageUrl = location.pathname;
			var pageParams = getPageParams(hashParams);
			
			if (canPushState) {
				pageUrl += '?' + $.param($.extend(pageParams, hashParams));
			} else {
				if (pageParams) {
					pageUrl += '?' + $.param(pageParams);
				}
				pageUrl += '#!' + $.param(hashParams);
			}
			return pageUrl;
		}
		/**
		 * 獲取url中原查詢參數json
		 */
		function getPageParams(hashParams) {
			var pageUrl = location.href;
			var pageQueryStr = pageUrl.split(/\?/)[1];
			var pageParams = null;
			if (pageQueryStr) {
				pageParams = {};
				var hashIndex = pageQueryStr.indexOf('#!');
				if (hashIndex != -1) {
					pageQueryStr = pageQueryStr.substr(0, hashIndex);
				}
				var pageParamsArray = pageQueryStr.split('&');
				for (var i in pageParamsArray) {
					if(hashParams && hashParams[i]){
						continue;
					}
					var pageParam = pageParamsArray[i].split('=');
					pageParams[pageParam[0]] = unescape(pageParam[1]);
				}
			}
			return pageParams;
		}
		
		/**
		 * 獲取當前頁面參數
		 * @param name
		 * @returns
		 */
		function getUrlParam(name, url) {
			url = url ? url : location.href;
            var reg = new RegExp("(#!|&|\\?)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象
            var r = url.substr(1).match(reg);  //匹配目標參數
            if (r != null) return unescape(r[2]); return null; //返回參數值
        }
		function pushState(hashParams) {
			var separate = canPushState ? '?' : '#'
			if (canPushState) {
				window.history.pushState(null, null, getUrl(hashParams));
			} else {
				window.location.hash = '#!' + $.param(hashParams);
			}
		}
	};
})(jQuery);