// JavaScript Document
/*Author:Alan*/
(function(){
	var jq = window._jq = (function(){
		var jq;
		if(typeof $ != 'undefined')
			jq = $;
		else if(typeof jq2!='undefined')
			jq = jq2;
		else if(typeof jQ!='undefined')
			jq = jQ;
		return jq;
	}());
	
	window._$ = function(renderTo){
		return new Grid(renderTo);
	}
			  
	var Grid = function(renderTo){
		this.render = document.getElementById(renderTo);
		if(this.render.childNodes.length>0){
			this.render.removeChild(this.render.childNodes[0]);
		}
		this.render.className = 'render';
		this.wrap = $c('div');
		this.wrap.className = 'grid_wrap';
		this.title = $c('div');
		this.head = $c('div');
		this.content = $c('div');
		this.foot = $c('div');
		this.render.appendChild(this.wrap);
		this.wrap.appendChild(this.head);
		this.wrap.appendChild(this.content);
		this.wrap.appendChild(this.foot);
	}
	
	Grid.prototype = {
		init:function(){
			this.head.className = 'grid_head';
			this.content.className = 'grid_content';
			this.content.style.height = this.render.offsetHeight - 54+'px';
			this.foot.className = 'grid_foot';
		},
		
		initHeadData:function(){
			if(this.head.childNodes.length>0)
				return;
			var table = $c('table');
			var tbody = $c('tbody');
			var tr = $c('tr');
			for(index in this.columns){
				var column = this.columns[index];
				var td = $c('td');
					td.innerHTML = column.text;
					if(column.width)
						td.style.width = column.width;
				tr.appendChild(td);
			}
			if(this.requestParams.buttons){
				var td = $c('td');
				if(this.requestParams.buttons.text)
					td.innerHTML = this.requestParams.buttons.text;
				else
					td.innerHTML = '操作';
				if(this.requestParams.buttons.width)
					td.style.width = this.requestParams.buttons.width;
				
				tr.appendChild(td);
			}
			tbody.appendChild(tr);
			table.appendChild(tbody);
			this.head.appendChild(table);
		},
		
		setContent:function(jsonData){
			//总记录数
			this.total = jsonData.Total;
			//数据集合
			this.records = jsonData.Records;
		},
		
		initFootPage:function(){
			//总页数
			this.pageCount = this.total%this.limit ==0?this.total/this.limit:Math.floor(this.total/this.limit)+1;
			if(typeof this.currentPage=='undefined')
				this.currentPage = 1;
		},
		
		removeContent:function(){
			
			if(this.content.childNodes.length>0){
				this.content.removeChild(this.content.childNodes[0]);
			}
		},
		setFoot:function(){
			
		},
		//渲染数据到GRID中
		initContentDatas:function(){
			var table = $c('table');
			var tbody = $c('tbody');
			
			//遍历结果集,放到GRID中
			for(var row=0;row<this.records.length;row++){
				var rowMessage = this.records[row];
				
				var tr = $c('tr');
					 addHover(tr,'grid_content_rows_hover');
				for(var col=0;col<this.columns.length;col++){
					var columnParam = this.columns[col];
					var html = '';
					var td = $c('td');
					
					//组装回调函数的参数
					if(typeof columnParam.params!='undefined'){
						 var params = {};
						 for(var p=0;p<columnParam.params.length;p++){
							 var column = columnParam.params[p];
							 	  params[column] = rowMessage[column];
						}
					}
					//返回值为空时返回一个空字符串
					if(rowMessage[columnParam.name]==undefined){
						this.records[row][columnParam.name] = '';
						
				 	}
					//鼠标移动到TD时的title
					if(columnParam.title){
						if(columnParam.titleCallback)
							td.title = columnParam.titleCallback(params);
						else if(rowMessage[columnParam.name]!='')
							td.title = rowMessage[columnParam.name];
					}
				
					if(columnParam.className){
						td.className = columnParam.className+' grid_content_normal';
					}else{
						if(columnParam.center)
							td.className = 'grid_content_center';
						else
							td.className = 'grid_content_normal';
					}
					
					 //如果没有指定回调函数
					 if(typeof columnParam.callback=='undefined'){
					 	html = rowMessage[columnParam.name];
					}else{
						 //如果回调函数指定了需要传的参数
						 
						if(typeof columnParam.params!='undefined'){
							html = columnParam.callback(params);
						}else{
							html = columnParam.callback();
						}
					}
					
					if(columnParam.width){
						td.style.width = columnParam.width;
						
					}
					if(html==undefined)
						html = '';
					td.innerHTML = '<div style="width:'+columnParam.width+';">'+html+'</div>';
					tr.appendChild(td);
						 	
				}
				/*按钮列*/
				if(this.requestParams.buttons){
						tr.appendChild(this.createButtons(row));
				}
				
				
				tbody.appendChild(tr);
				table.appendChild(tbody);
			}
			this.content.appendChild(table);
		},
		
		/*创建按钮*/
		createButton:function(name,params,callback,textCallback){
			var button = $c('a');
				button.style.color = 'blue';
					button.href='javascript:void(0);';
					if(textCallback)
						button.innerHTML = textCallback(params);
					else
						button.innerHTML = name;
					button.onclick = function(){
							callback(params);
					}
			return button;
		},
		/*创建操作列按钮*/
		createButtons:function(row){
			var actions = this.requestParams.buttons.actions;
			var td = $c('td');
			var rowRecords = this.records[row];
			if(this.requestParams.buttons.width){
					td.style.width = this.requestParams.buttons.width;
			}
						
			for(var index=0;index<actions.length;index++){
					var reg_params = actions[index].params;
					var params = {};
					//如果回调函数配置了参数
					if(reg_params)
						for(var p=0;p<reg_params.length;p++){
							var column = reg_params[p];
							params[column] = rowRecords[column];
						}
					var callback = actions[index].callback;
					
					//显示条件
					var show = actions[index].show;
					if(show){
						if(!show(params))
							continue;
					}
					var name = actions[index].name;
					var textCallback = actions[index].textCallback;
					var button = this.createButton(name,params,callback,textCallback);
						 if(actions[index].className)
						 	button.className = actions[index].className;
						 else
						 	button.className = 'actionBt';
						td.appendChild(button);
						td.className = 'grid_actions';
					}
			return td;
		},
		
		/*
			设置分页按钮的数据
		*/
		initFootPageMessage:function(total){
			if(this.foot.childNodes.length>0){
				this.foot.removeChild(this.foot.childNodes[0]);
			}
			var start = this.start+1;
			var limit = this.limit;
			this.currentPage = start%limit ==0?Math.floor(start/limit):Math.floor(start/limit)+1;
			this.sumPage = total%this.limit!=0?Math.floor(total/this.limit)+1:total/this.limit;
			
			
			//跳页按钮内容
			this.pagesArray = new Array();
			for(var i=-5;i<=5;i++){
				if(i<=0){
					if(this.currentPage+i>0)
						this.pagesArray.push(this.currentPage+i);
				}else{
					if(this.currentPage+i<=this.sumPage){
						this.pagesArray.push(this.currentPage+i);
					}
				}
		
			}
			
		},
		
		/*
		 *	渲染分页按钮
		 */
		setFootDatas:function(){
			var pageDiv = $c('div');
			var _this = this;
			
			var totalBt = $c('input');
				totalBt.type = 'button';
				totalBt.className = 'disabledBt';
				totalBt.disabled = 'disabled';
				totalBt.value = '共'+this.sumPage+'页';
				pageDiv.appendChild(totalBt);
			var firstBt = $c('input');
				firstBt.type = 'button';
				firstBt.value = '|<首页';
				
				pageDiv.appendChild(firstBt);
				if(this.currentPage!=1){
					firstBt.className = 'firstBt';
					firstBt.onclick = function(){
							_this.requestParams.start = 0;
							_this.request(_this.requestParams);
					}
				}else{
					firstBt.className = 'disabledBt';
					firstBt.disabled = 'disabled';
				}
			var preBt = $c('input');
				preBt.type = 'button';
				preBt.value = '上一页';
				
				pageDiv.appendChild(preBt);
				if(this.currentPage!=1){
					preBt.className = 'preBt';
					preBt.onclick = function(){
							_this.requestParams.start =_this.start-(_this.limit);
							_this.request(_this.requestParams);
					}
				}else{
					preBt.className = 'disabledBt';
					preBt.disabled = 'disabled';
				}
			
			for(var index=0;index<this.pagesArray.length;index++){
				
				var bt = $c('input');
					bt.type = 'button';
					bt.value = this.pagesArray[index];
					if(this.pagesArray[index]==this.currentPage)
						bt.className = 'hoverBt';
					else
						bt.className = 'normalBt';
					bt.onclick = function(){
						var curpage = this.value;
						_this.requestParams.start = (curpage-1)*_this.limit;
						_this.request(_this.requestParams);
					}
				pageDiv.appendChild(bt);
			}
			
			
			var nextBt = $c('input');
				nextBt.type = 'button';
				nextBt.value = '下一页';
				
				pageDiv.appendChild(nextBt);
				if(this.currentPage<this.pageCount){
					nextBt.className = 'nextBt';
					nextBt.onclick = function(){
							_this.requestParams.start =_this.start+(_this.limit);
							_this.request(_this.requestParams);
					}
				}else{
					nextBt.className = 'disabledBt';
					nextBt.disabled = 'disabled';
				}
			
			var endBt = $c('input');
				endBt.type = 'button';
				endBt.value = '尾页>|';
				
				pageDiv.appendChild(endBt);
				if(this.currentPage<this.pageCount){
					endBt.className = 'endBt';
					endBt.onclick = function(){
							_this.requestParams.start = (_this.pageCount-1)*_this.limit;
						
							_this.request(_this.requestParams);
					}
				}else{
					endBt.className = 'disabledBt';
					endBt.disabled = 'disabled';
				}
			
			this.foot.appendChild(pageDiv);
		},
		
		
		//Ajax访问并渲染数据到GRID
		request:function(request){
			this.requestParams = request;
			this.start = request.start;
			this.limit = request.limit;
			this.columns = request.columns;
			this.loading = request.loading==false?false:true;
			var data = request.data;
			data.start = this.start;
			data.limit = this.limit;
			_this = this;
			this.showBg();
			jq.ajax({
				url:request.url,
				data:data,
				type:'POST',
				dataType:'json',
				success:function(results){
					_this.results = results;
					_this.renderGrid();
					_this.hideBg();
				},
				error:function(){
					_this.hideBg();
					alert('系统超时，请重新登录系统后尝试。如果还遇到该问题，请联系客服人员。');
				}
			});
			
		},
		showBg:function(){
			if(this.loading){
				this.bg = getBg();
				_jq(this.bg).fadeTo('slow',0.2);
				this.initFlontWin();
				this.wrap.appendChild(this.flont);
				
				//this.wrap.appendChild(this.bg);
			}
		},
		hideBg:function(){
			if(this.loading){
				//this.wrap.removeChild(this.bg);
				_jq(this.bg).fadeOut('slow',function(){
					  
				});
				_jq(this.flont).fadeOut('slow',function(){
												  
				});
			}
			//this.wrap.removeChild(this.flont);
		},
		initFlontWin:function(){
			this.flont = $c('div');
			this.bg.appendChild(this.flont);
			this.flont.className = 'loading_flont';
			
			var table = $c('table');
				 table.className = 'loading_flont_table';
			var tbody = $c('tbody');
				 var tr = $c('tr');
				 var mTd = $c('td');
				 
				 	  mTd.style.verticalAlign = 'middle';
				 	  var img = $c('img');
					  		img.className = 'loading_img';
					  		img.style.marginRight = '6px';
							img.src = $path()+'/imgs/loading.gif';
					  mTd.appendChild(img);
				 var text = $c('td');
				 	  text.innerHTML = '加载中...';
				tr.appendChild(mTd);
				tr.appendChild(text);
				tbody.appendChild(tr);
				table.appendChild(tbody);
			this.flont.style.width = '100px';
			this.flont.style.left = (this.render.offsetWidth-80)/2+'px';
			this.flont.style.top = (this.render.offsetHeight-50)/2+'px';
			this.flont.appendChild(table);
			this.flont.text = text;
		},
		//渲染GRID
		renderGrid:function(){
			
			//this.removeAll();
			//渲染GRID头部
			this.initHeadData();
			//移除GRID内容(准备刷新数据)
			this.removeContent();
			//GRID内容信息设置
			this.setContent(this.results);
			//GRID内容渲染
			this.initContentDatas();
			//总页数、当前页设置
			this.initFootPage();
			//分页按钮信息设置
			this.initFootPageMessage(this.results.Total);
			//分页按钮渲染
			this.setFootDatas();
			//GRID渲染
			this.init();
		}
	};
	
	var subResult = function(width,strParam){
		var str = new String(strParam);
		var w = width.replace('px','');
		var fontCount = Math.floor(parseInt(w)/12);
		if(getLength(str)>fontCount){
			return str.substr(0,fontCount-4)+'...';
		}
		return str;
	}
	
	/*添加类似hover伪类效果的样式，主要为了支持IE6(IE不支持a元素之外的hover伪类)*/
	var addHover = function(obj,className){
		var oldClass = obj.className;
		var newClass = className;
		obj.onmouseover = function(){
			this.className = oldClass+' '+newClass;
		}
		obj.onmouseout = function(){
			this.className = oldClass;
		}
	}
	
	var getLength = function(str){
		var length = 0;
		for(var i=0;i<str.length;i++){
			if(str.charCodeAt(i)>255)
				length+=2;
			else
				length+=1;
		}
		return length;
	}
	
	var $c = function(tagName){
		return document.createElement(tagName);
	}
	
	var getBg = function(){
		var winBg = $c('div');
			winBg.className = 'win_bg';
		return winBg;
	}
	var $path = function(){
		var path;
		var scripts = document.getElementsByTagName('script');
		for(var i=0;i<scripts.length;i++){
			var src = scripts[i].src;
			if(src.indexOf('gridv2/grid.js')!=-1){
				path = src.replace('grid.js','');
			}
		}

		return path;
	}
})();
