/*
 * 2009.2.12
 * 改自 Fpi.SearchIterator
 * 修改：
 *  1, 取消　headers 参数, 由 options 的 getHeadersMethod()方法取代，每次绑定都重新获取 headers
 * 	2, 参数recordCount无需传递
 *  3, onResize 更名为 callback
 *  4, render 方法改为由用户调用
 */

/*
2009.7.14
	添加参数 autoRender,实例化 PagerIterator后是否自动展示，默认为false
*/
Fpi.PageIterator = function(options, doc){
		/* OPTIONS
		 * getRecordsMethod 获取记录方法(该方法必须）
		 * getRecordCountMethod 获取记录条数方法，重新显示（调用reload 方法）时需要该参数，如果该参数不存在，则 reload 方法被调用时页面不会有改变
		 * getHeadersMethod
		 * recordCount 记录总条数
		 * pageSize 一页显示条数
		 * noDatasFound 没有记录时显示
		 * callback 
		 * 
		 * showException
		 * 
		 * parentDiv
		 * showMessage
		 * showException
		 * showOneRecordMessage
		 * showCheckbox
		 * 
		 * firstMessage
		 * previousMessage
		 * nextMessage
		 * lastMessage
		 */
		doc = doc || document;
		
		this.options = options || {};
		
		this.pageDatas=[];
		this.pageSize = this.options.pageSize || 20;
		//this.recordCount = this.options.recordCount ? parseInt(this.options.recordCount) : 0;
		this.getRecordsMethod = this.options.getRecordsMethod || null;
		this.getRecordCountMethod = this.options.getRecordCountMethod || null;
		this.getHeadersMethod = this.options.getHeadersMethod || null;
		this.alwaysReloadHeaders = this.options.alwaysReloadHeaders || false;
		this.autoRender	= this.options.autoRender || false;
		
		this.callback = this.options.callback;
		
		this.showCheckbox = this.options.showCheckbox || false;
		
		this.showException = this.options.showException;
		this.noMessage ='';
		
		this.pager = new Fpi.Pager(this.pageSize, 0, this.options.pageDiv, this.options);
		this.pager.attachOnPageChange(this.showRecords.bind(this));
		
		this.currentPage = 1;
		
		this.divWrap = this.options.parentDiv || doc.createElement('div');
		// 加载动画
		var loadingAnimation = doc.createElement('div');
		loadingAnimation.className = 'loading-animation';
		loadingAnimation.style.display = 'none';
		this.divWrap.appendChild(loadingAnimation);
		this.loadingAnimation = loadingAnimation;
		
		// results table
		var resultsTable = doc.createElement('table');
		resultsTable.className = 'taglib-search-iterator';
		resultsTable.valign = 'top';
		resultsTable.appendChild(doc.createElement('tbody'));
		this.resultsTable = resultsTable;
		
		this.divWrap.appendChild(resultsTable);
		
		// 去掉 float属性 (分页信息里有 float 属性,如果不去掉,则该分页控件下的所有html元素都会浮动在该分页控件的右边)
		this.divWrap.appendChild(jQuery('<div style="clear:both"></div>')[0]);
		
		this.tableList = new TableList(this.resultsTable, [], this.options.noDatasFound || '\u627e\u4e0d\u5230\u8bb0\u5f55', this.showCheckbox, (options && options.tableStyles));
		
		if(this.autoRender) {
			this.render();
		}
}

Fpi.PageIterator.prototype = {
	render	:	function(){
		
		jQuery(this.loadingAnimation).show();
		
		this.getRecordCountMethod(this.getRecordCountMethodComplete.bind(this));
		
		return this.divWrap;
	},
	// 隐藏动画
	hideAnimation	:	function(){
		jQuery(this.loadingAnimation).hide();
	},
	// 列表显示记录
	showRecords	:	function(){
		jQuery(this.loadingAnimation).show();
		this.getRecordsMethod(this.pager.getStart(), this.pager.getEnd(), this.getRecordsMethodComplete.bind(this));
	},
	/*
	 * 重新显示当前页(记录数，或记录有改动时调用该方法）
	 */
	reload		:	function(){
		jQuery(this.loadingAnimation).show();
		
		this.getRecordCountMethod(this.getRecordCountMethodComplete.bind(this));
	},
	getRecordCountMethodComplete	:	function(count){
		
		this.hideAnimation();
		
		if(count.exception){
			// 用户自定义错误显示
			if(this.showException){
				// 获取记录条数失败
				this.showException('\u83b7\u53d6\u8bb0\u5f55\u6570\u5931\u8d25');
			}else{
				alert('\u83b7\u53d6\u8bb0\u5f55\u6570\u5931\u8d25');
			}
			
			this.callback && this.callback();
			
			return;
		}
		
		this.pager.recordCount = parseInt(count) || (count && count['returnValue']);
		
		if(this.pager.loaded) {
			this.pager.updatePage(false);
		}else {
			this.pager.render();
			this.divWrap.appendChild(this.pager.pageDiv);
		}
		
		if(this.pager.recordCount) {
			this.showRecords();
		} else {
			this.getRecordsMethodComplete();
		}
	},
	getRecordsMethodComplete	:	function(records){
		jQuery(this.loadingAnimation).hide();
		
		if(!records){
			records = [];
		}
		
		if(records.exception){
			this.hideAnimation();
			
			jQuery(this.resultsTable).find('tr').remove();
			
			if(this.showException){
				this.showException(records.exception);
			}else{
				jQuery('<tr class="portlet-section-body">' + '\u83b7\u53d6\u8bb0\u5f55\u5931\u8d25' + '</tr>').appendTo(this.resultsTable);
			}
			
			this.callback && this.callback();
			
			return;
		}
		
		// 列表头信息
		if(!this.headers || this.alwaysReloadHeaders) {
			this.headers = this.getHeadersMethod && this.getHeadersMethod(bindToTableList.bind(this));
		}
		
		if(this.headers || !this.getHeadersMethod) {
			bindToTableList.bind(this)();
		} 
		
		function bindToTableList(headers) {
			if(headers) {
				this.headers = headers;
			}
			records.headers = this.headers;
		
			this.tableList.datas = records;
			this.tableList.render();
			//Fpi.Util.createTableList.bind(this)(this.resultsTable, records, this.options.noDatasFound || '\u627e\u4e0d\u5230\u8bb0\u5f55', this.showCheckbox);
			
			//Fpi.Util.createTableList(this.resultsTable, records, this.options.noDatasFound || '\u627e\u4e0d\u5230\u8bb0\u5f55', this.showCheckbox);
			
			this.callback && this.callback(records);
			//this.pageDatas = Fpi.Util.getPageDatas();
		}
		/*
		records.headers = this.headers;
		
		this.tableList.datas = records;
		this.tableList.render();
		//Fpi.Util.createTableList.bind(this)(this.resultsTable, records, this.options.noDatasFound || '\u627e\u4e0d\u5230\u8bb0\u5f55', this.showCheckbox);
		
		//Fpi.Util.createTableList(this.resultsTable, records, this.options.noDatasFound || '\u627e\u4e0d\u5230\u8bb0\u5f55', this.showCheckbox);
		
		this.callback && this.callback(records);
		//this.pageDatas = Fpi.Util.getPageDatas();
		*/
	}
};

// 事件
jQuery.extend(Fpi.PageIterator.prototype, {
	attachOnRowClickEvents	:	function(eHandler) {
		this.tableList.attachOnRowClickEvents(eHandler);
	},
	detachOnRowClickEvents	:	function(eHandler) {
		this.tableList.detachOnRowClickEvents(eHandler);
	},
	clearOnRowClickEvents	:	function() {
		this.tableList.clearOnRowClickEvents();
	}
});

Fpi.Pager = function(pageSize, recordCount, pageDiv, options){
		
		this.loaded = false;
		
		this.currentPage = 1;
		
		this.pageSize = (pageSize ? parseInt(pageSize) : 20 );
		
		this.recordCount = recordCount || 0;
		this.pageDiv = pageDiv;
		
		this.firstMessage = options.firstMessage || '\u9996\u9875';
		this.previousMessage = options.previousMessage || '\u4e0a\u4e00\u9875';
		this.nextMessage = options.nextMessage || '\u4e0b\u4e00\u9875';
		this.lastMessage = options.lastMessage || '\u672b\u9875';
		this.showMessage = options.showMessage || 'showing-{0}-{1}-of-{2}-results';
		this.showOneRecordMessage = options.showOneRecordMessage || 'showing-{0}-record-of-{1}-results';
		this.className = options.pagerClassName;
		
		// 最多允许显示的页数选择
		this.showSelectPageCount = options.showSelectPageCount || 20;
};

Fpi.Pager.prototype = {
	/*
	 * 计算页数
	 */
	calculate	:	function(){
		this.pageCount = this.recordCount && Math.ceil(parseInt(this.recordCount) / parseInt(this.pageSize));		
		
	},
	/*
	 * 获取记录开始行
	 */
	getStart	:	function(){
		var start = (this.currentPage - 1) * this.pageSize;
		
		if(start >= this.recordCount && start > 0){
			start = this.recordCount - 1;
		}
		
		return start;
	},
	/*
	 * 获取记录结束行
	 */
	getEnd		:	function(){
		var end = this.getStart() + this.pageSize;
		if(end >= this.recordCount && end > 0){
			end = this.recordCount;
		}
		
		return end;
	},
	/*
	 * 获取分页显示信息（包括当前显示记录、记录总数）
	 */
	getShowResultMessage	:	function(){
		if(this.recordCount == 0){
			return '';
		}
		if(this.pageSize == 1){
			return this.showOneRecordMessage.replace('{0}', (this.getStart() + 1)).replace('{1}', this.recordCount);
		}else{
			return this.showMessage.replace('{0}',(this.getStart() + 1)).replace('{1}', this.getEnd()).replace('{2}', this.recordCount);
		}
	},
	/*
	 * 显示分页
	 */
	render		:	function(doc){
		doc = doc || document;
		
		this.calculate();
		
		this.loaded = true;
		
		this.pageDiv = this.pageDiv || doc.createElement('div');
		this.pageDiv.className = this.className || 'taglib-page-iterator';
		
		if(!(this.recordCount && this.pageCount > 0)){
			//return this.pageDiv;
		}
		
		// search div
		var searchDiv = jQuery('<div class="search-results">' + this.getShowResultMessage() + '</div>');
		searchDiv.appendTo(this.pageDiv);
		
		// search pages
		var searchPages = jQuery('<div class="search-pages"></div>');
		searchPages.appendTo(this.pageDiv);
		
		// page selector
		var pageSelector = jQuery('<div class="page-selector"></div>');
		pageSelector.appendTo(searchPages);
		var pageSelect = doc.createElement('select');
		this.pageSelect = pageSelect;
		pageSelect.onchange = this.onPageSelectChange.bind(this);
		
		this.createPageSelect();
		/*if(this.pageCount){
			for(var i = 1; i <= this.pageCount; i++){
				var option = new Option(i, i);
				pageSelect.options.add(option);
				if(i == this.currentPage){
					option.selected = true;
				}
			} 
		}else{
			var option = new Option('','');
			pageSelect.options.add(option);
		}*/
		
		jQuery(pageSelect).appendTo(pageSelector);
		
		// page links
		var pageLinks = jQuery('<div class="page-links"></div>');
		pageLinks.appendTo(searchPages);
		
		// 第一页
		var firstLink = jQuery('<a class="first" href="#">' + this.firstMessage + '</a>');
		//firstLink.bind('onclick', this.onFirstPageClick);
		firstLink[0].onclick = this.onFirstPageClick.bind(this);
		var firstSpan = jQuery('<span class="first">' + this.firstMessage + '</span>');
		// 上一页
		var preLink = jQuery('<a class="previous" href="javascript:;">' + this.previousMessage + '</a>');
		//preLink.bind('onclick', this.onPrePageClick);
		preLink[0].onclick = this.onPrePageClick.bind(this);
		var preSpan = jQuery('<span class="previous">' + this.previousMessage + '</span>');
		// 下一页
		var nextLink = jQuery('<a class="next" href="#">' + this.nextMessage + '</a>');
		//nextLink.bind('onclick', this.onNextPageClick);
		nextLink[0].onclick = this.onNextPageClick.bind(this);
		var nextSpan = jQuery('<span class="next">' + this.nextMessage + '</span>');;
		// 尾页
		var lastLink = jQuery('<a class="last" href="#">' + this.lastMessage + '</a>');
		//lastLink.bind('onclick', this.onLastPageClick);
		lastLink[0].onclick = this.onLastPageClick.bind(this);
		var lastSpan = jQuery('<span class="last">' + this.lastMessage + '</span>');
		
		//firstLink.appendTo(pageLink);
		firstLink.appendTo(pageLinks);
		firstSpan.appendTo(pageLinks);
		preLink.appendTo(pageLinks);
		preSpan.appendTo(pageLinks);
		nextLink.appendTo(pageLinks);
		nextSpan.appendTo(pageLinks);
		lastLink.appendTo(pageLinks);
		lastSpan.appendTo(pageLinks);
		
		firstLink.hide();
		preLink.hide();
		nextLink.hide();
		lastLink.hide();
		if(this.currentPage > 1){
			firstLink.show();
			preLink.show();
			firstSpan.hide();
			preSpan.hide();
		}
		
		if(this.pageCount && this.currentPage != this.pageCount){
			nextLink.show();
			lastLink.show();
			nextSpan.hide();
			lastSpan.hide();
		}
	},
	/*
	 * 单击首页
	 */
	onFirstPageClick	:	function(){
		this.currentPage = 1;
		this.updatePage();
	},
	onPrePageClick		:	function(){
		this.currentPage = (this.currentPage > 1 ? this.currentPage - 1 : this.currentPage);
		this.updatePage();
	},
	onNextPageClick		:	function(){
		this.currentPage = (this.currentPage < this.pageCount ? (this.currentPage + 1) : this.currentPage);
		this.updatePage();
	},
	onLastPageClick		:	function(){
		this.currentPage = this.pageCount;
		this.updatePage();
	},
	/*
	 * 页码改变时该方法被调用，重新显示页码信息及各按钮状态
	 */
	updatePage			:	function(fireEvent){
		this.calculate(); // 重新计算页数
		
		var firstLink = jQuery('a.first', this.pageDiv);
		var firstSpan = jQuery('span.first', this.pageDiv);
		
		var preLink = jQuery('a.previous', this.pageDiv);
		var preSpan = jQuery('span.previous', this.pageDiv);
		
		var nextLink = jQuery('a.next', this.pageDiv);
		var nextSpan = jQuery('span.next', this.pageDiv);
		
		var lastLink = jQuery('a.last', this.pageDiv);
		var lastSpan = jQuery('span.last', this.pageDiv);
		
		if(this.currentPage > this.pageCount){
			this.currentPage = (this.pageCount || 1);
		}
		if(this.currentPage <= 1){
			this.currentPage = 1;
			firstLink.hide();
			firstSpan.show();
			
			preLink.hide();
			preSpan.show();
		}else{
			firstLink.show();
			firstSpan.hide();
			
			preLink.show();
			preSpan.hide();
		}
		
		if(this.currentPage < this.pageCount){
			nextLink.show();
			lastLink.show();
			nextSpan.hide();
			lastSpan.hide();
		}else{
			this.currentPage = this.pageCount;
			nextLink.hide();
			lastLink.hide();
			nextSpan.show();
			lastSpan.show();
		}

		// 重新显示分页信息
		jQuery('div.search-results', this.pageDiv)[0].innerHTML = this.getShowResultMessage();
		/*
		if(this.pageCount<=1){
			jQuery('div.search-pages', this.pageDiv).hide();	  		  
      		jQuery('div.page-selector', this.pageDiv).hide();
			// return ;
		}else{
			jQuery('div.search-pages', this.pageDiv).show();	  		  
			jQuery('div.page-selector', this.pageDiv).show();			
		}
		*/
		this.createPageSelect();
		// 改变分页下拉列表为当前页
		jQuery('div.page-selector select', this.pageDiv).attr('value', this.currentPage);
		// 触发用户自定义事件
		if(fireEvent || fireEvent == undefined) {
			this.pageChange();
		}
	},
	createPageSelect	:	function(){
		var select = this.pageSelect;
		
		while(select.options.length > 0){
			select.options[select.options.length - 1] = null;
		}
		
		if(this.pageCount){
			// 开始页
			var startPage = this.currentPage - Math.ceil(this.showSelectPageCount / 2) + 1;
			
			// 结束页
			var endPage = startPage + this.showSelectPageCount - 1;
			
			// 校正开始、结束页
			if(startPage < 1 && endPage > this.pageCount){
				startPage = 1;
				endPage = this.pageCount;
			}else if(startPage < 1){
				endPage = endPage - startPage + 1;
				startPage = 1;
			}else if(endPage > this.pageCount){
				startPage = startPage - (endPage - this.pageCount)
				endPage = this.pageCount;
			}
			
			if(startPage < 1){
				startPage = 1;
			}
			
			if(endPage > this.pageCount){
				endPage = this.pageCount;
			}
			
			// 创建选择页
			for(var i = startPage; i <= endPage; i++){
		   		var option = new Option(i, i);
		   		select.options.add(option);
		   		if(i == this.currentPage){
		   			option.selected = true;
		   		}
		   }
		}else{
			var option = new Option('','');
			select.options.add(option);
		}
	},
	/*
	 * 页码下拉列表更新时动作
	 */
	onPageSelectChange	:	function(){
		var pageIndex = parseInt(this.pageSelect.value);
		
		this.goPage(pageIndex);
	},
	/*
	 * 转到指定页
	 */
	goPage				:	function(pageIndex){
		if(!pageIndex){
			return;
		}
		
		if(pageIndex < 1){
			pageIndex = 1;
		}
		if(pageIndex > this.pageCount){
			pageIndex = this.pageCount;
		}
		
		this.currentPage = pageIndex;
		
		this.updatePage();
	},
	// 改变当前页时触发的动作
	pageChange			:	function(){
		if(this.onPageChange){
			// 用户自定义事件
			for(var i = 0; i < this.onPageChange.length; i++){
				this.onPageChange[i]();
			}
		}
	},
	// 添加页码改变时动作
	attachOnPageChange	:	function(_eHandler){
		if(!this.onPageChange) this.onPageChange = [];
		this.onPageChange.push(_eHandler);
	}
}