﻿/**
 * @author prcvictim
 * Import: zXml.js
 */
var DataList = function () {this.initialize.apply(this, arguments);};
DataList.prototype = {
	initialize: function (arg) {
		this.xmlDoc 	= null;
		this.xmlHttp    = null;
		this.srcElement = arg.srcElement;
		this.LoadGIF    = null;
		this.funProcess = arg.funProcess || null;
		this.UI 		= this._initUI();
		this.isLoad		= false;
		this.isNullData = false;
		this.dataList 	= [];
		this.fieldName 	= [];
		this.xmlCount	= 0   // 记录XML的记录个数.
		this.Count		= 0;  // 记录筛选后的录数.
		this.orderBy	= true;
		this.PageSize   = 10; // 每页至多显示的行.
		this.PageCursor	= 0;
		this.loadNum    = 0;
		this.Filters	= [];
	},
	loadXML: function (source) {
	    this.abort();
		this.loadNum++;
        this.PageCursor = 0;
	    var thisObj = this;
		this.xmlHttp = (new zXmlHttp.Request(source, {onComplete: function (transport) {
		    if (transport.readyState == 4) {
		        thisObj.xmlDoc = zXmlDom.createDocument();
		        thisObj.xmlDoc.loadXML(transport.responseText);
		        //thisObj.xmlDoc = transport.responseXML;
		        //thisObj.xmlDoc.readyState = 4;
				thisObj.isLoad = true;
				if (thisObj.OnLoad() != false) {
					thisObj._initData();
					thisObj.OnLoaded(thisObj.dataList.length, thisObj.xmlCount);
					//thisObj.Next();
				}
		    } else {
		        thisObj.LoadGIFHidden();
		    }
			thisObj = null;
		} })).xmlHttp;
	
//		this.xmlDoc = zXmlDom.createDocument();
//		this.xmlDoc.async = true;
//		this.xmlDoc.load(source);
//		this.loadNum++;
//      this.PageCursor = 0;
//		var thisObj = this;
//		clearInterval(DataList.intervalID);
//		DataList.intervalID = setInterval(function () {
//			if (thisObj.xmlDoc.readyState == 4) {
//				clearInterval(DataList.intervalID);
//				thisObj.isLoad = true;
//				if (thisObj.OnLoad() != false) {
//					thisObj._initData();
//					thisObj.OnLoaded(thisObj.dataList.length, thisObj.xmlCount);
//				}
//				thisObj = null;
//			}
//		}, 60);
	},
	loadXMLObj: function (obj) {
	    this.abort();
	    //this.xmlDoc = obj;
		this.LoadGIFShow();
		this.loadNum++;
        this.PageCursor = 0;
		var thisObj = this;
		clearInterval(DataList.intervalID);
		if (zXml.useActiveX) {//IE
		    DataList.intervalID = setInterval(function () {
			    if (obj.readyState == "complete") {
		            clearInterval(DataList.intervalID);
		            thisObj.xmlDoc = zXmlDom.createDocument();
		            thisObj.xmlDoc.loadXML(obj.xml);
                    thisObj.isLoad = true;
		            if (thisObj.OnLoad() != false) {
			            thisObj._initData();
			            thisObj.OnLoaded(thisObj.dataList.length, thisObj.xmlCount);
		            }
		        }
		    }, 60);
		} else {//Firefox
		    new zXmlHttp.Request(obj.getAttribute("src"), {onComplete: function (transport) {
		        if (transport.readyState == 4) {
		            thisObj.xmlDoc = zXmlDom.createDocument();
		            thisObj.xmlDoc.loadXML(transport.responseText);
				    thisObj.isLoad = true;
				    if (thisObj.OnLoad() != false) {
					    thisObj._initData();
					    thisObj.OnLoaded(thisObj.dataList.length, thisObj.xmlCount);
				    }
		        } else {
		            thisObj.LoadGIFHidden();
		        }
			    thisObj = null;
		    } });
		
		
		
//            this.xmlDoc = zXmlDom.createDocument();
//            this.xmlDoc.load(obj.src);
//		    DataList.intervalID = setInterval(function () {
//			    if (obj.readyState == 4) {
//		            clearInterval(DataList.intervalID);
//                    thisObj.isLoad = true;
//		            if (thisObj.OnLoad() != false) {
//			            thisObj._initData();
//			            thisObj.OnLoaded(thisObj.dataList.length, thisObj.xmlCount);
//		            }
//		        }
//		    }, 60);
		}
	},
	abort: function () {
	    if (this.xmlHttp != null && this.xmlHttp.readyState != 4) { this.xmlHttp.abort(); }
	},
	isLoaded: function (arg) {
		this.isLoaded.caller([arg]);
					
//		if (!this.isLoad || this.dataList.length < 1 || this.dataList.length <1){
//			var thisObj = this;
//			var caller = this.isLoaded.caller;
//			var intervalID = setInterval(function () {
//				if (thisObj.xmlDoc.readyState == 4) {
//					clearInterval(intervalID);
//					caller.apply(thisObj, [arg]);
//				}
//				thisObj = null;
//			}, 60);	
//		} else {
//			return true;
//		}
	},
	Query: function (where) {
		var xmlNodes;
		if (where){
			xmlNodes = this._selectNodes(".//Row[" + where + "]");
		} else {
			if (zXml.useActiveX)
				xmlNodes = this.xmlDoc.documentElement.childNodes;
			else
				xmlNodes = this._selectNodes("*");
		}
		this.PageCursor = 0;
		if (xmlNodes.length > 0) {
			this.isNullData = false;
			this._initData(xmlNodes);
		} else {
			this.isNullData = true;
			this.PageCursor	= 0;
			this.Count = 0;
			this.OnNullResult();
			this.OnPageChange();
			this.LoadGIFHidden();
			return;
		}
		this.RefreshUI();
	},
	addFilters: function (arg) {
		this.Filters.push(arg);
	},
	Filter: function (arg, fieldName) {
		if (this.OnFilters(arg) != false) {
			var xpath = '1=1';
			for (var i = 0; i < this.Filters.length; i++) {
				if (this.Filters[i].Field == fieldName) this.Filters[i].arg = arg;
				xpath += ' and ' + this.Filters[i].doFilters(this.Filters[i].arg);
			}
			this.LoadGIFShow();
		    clearTimeout(this.QUERY_TIMEOUT);
		    var thisObj = this;
		    this.QUERY_TIMEOUT = setTimeout(function () {
			    thisObj.Query(xpath);
			    thisObj.OnFiltersed(thisObj.Count, thisObj.xmlCount);
				thisObj = null;
		    }, 1);
		}
	},
	Sort: function (field, orderBy) {
	    this.LoadGIFShow();
		clearTimeout(this.SORT_TIMEOUT);
		var thisObj = this;
		this.SORT_TIMEOUT = setTimeout(function () {
			thisObj.Arrangement(field, orderBy);
			thisObj = null;
		}, 1);
	},
	Arrangement: function (field, orderBy) {
	    var asc,p1,p2;
		for (var i = 0; i < this.dataList.length; i++) {
			for (var j = i + 1; j < this.dataList.length; j++) {
				if (this.funProcess && field != 'Nam') {
						p1 = this.funProcess.convertField(field, this.dataList[i][field])
						p2 = this.funProcess.convertField(field, this.dataList[j][field]);
						asc = p1 < p2;
				} else {
					// 对中文字符进行排序,写的好乱,有时间再整理.
					var s = [this.dataList[i][field], this.dataList[j][field]];
					s.sort(function(a,b){return a.localeCompare(b)});
					asc = (this.dataList[i][field] == s[0]);
				}
				//debugger;
				if (orderBy) {
					if (!asc) {
					var node = this.dataList[i];
					this.dataList[i] = this.dataList[j];
					this.dataList[j] = node;
					}
				} else {
					if (asc) {
					var node = this.dataList[i];
					this.dataList[i] = this.dataList[j];
					this.dataList[j] = node;
					}
				}
 			}
		}
		this.RefreshUI();
	},
	RefreshUI: function () {
		if (this.isNullData) return;
		if (this.UI) {
			while (this.UI.rows.length > 0) this.UI.deleteRow(this.UI.rows.length-1);
			var newCell,btnHead;
			var Row = this.UI.insertRow(-1);
			// 建立标头行.
			var thisObj = this;
			for (var i = 0; i < this.fieldName.length; i++) {
				if ( this.funProcess ) {
					this.funProcess.insertHead(this.fieldName[i], Row);
				} else {
					newCell = Row.insertCell(i);
					btnHead = document.createElement('button');
					btnHead.fieldID = i;
					btnHead.onclick = function () {
						thisObj.Arrangement(this.fieldID);
					}
					btnHead.innerHTML = this.fieldName[i].toLowerCase().replace(/_/,' ');
					newCell.appendChild(btnHead);
				}
				thisObj = null;
			}
			
			// 建立数据行.
			for (var i = this.PageCursor*this.PageSize; i < (this.PageCursor+1)*this.PageSize; i++) {
				if (this.dataList[i]) {	
					if ( this.funProcess ) {
						this.funProcess.insertRow(this.dataList[i], this.UI);
					} else {
						Row = this.UI.insertRow(-1);
						for (var j = 0; j < this.fieldName.length; j++) {
							newCell = Row.insertCell(j);
							newCell.innerHTML = htmlConvert( this.dataList[i][this.fieldName[j]] );
						}
					}
				}
			}
			
			this.LoadGIFHidden();
		}
	},
	Back: function () {
		if (--this.PageCursor < 0)
			this.PageCursor = 0;
			
		if (this.OnPageChange() != false)this.RefreshUI();
	},
	Next: function () {
		var max = Math.ceil(this.Count/this.PageSize) - 1;
		if (++this.PageCursor > max) {
			this.PageCursor = max;
		}
		if (this.OnPageChange() != false)this.RefreshUI();
	},
	LoadGIFShow: function () {
	    if (document.readyState=="uninitialized" || document.readyState=="loading" || document.readyState=="loaded" || document.readyState=="interactive"){ // || document.getElementById("ON_LOAD_EVENT") == null) {
//	        var thisObj = this;
//	        setTimeout(function () { thisObj.LoadGIFShow.call(thisObj); }, 10);
	        return;
	    }
        //try {
        if (!this.LoadGIF) {
            this.LoadGIF = document.createElement("div");
            this.LoadGIF.className = "loading";
            this.LoadGIF.style.position="absolute";
            this.LoadGIF.style.left=document.body.clientWidth/2 - 180 + "px";
            this.LoadGIF.style.top= "200px";
	        
            document.body.appendChild(this.LoadGIF);
        }
        var waitText = I18N.DataLoading;
        this.LoadGIF.innerHTML = "<img src='../images/iconsearch.gif' /> " + waitText + "...";
        this.LoadGIF.style.display = "block";
	    //} catch (e) { }
	},
	LoadGIFHidden: function () {
	    if (!this.LoadGIF) return;
		if (this.Count == 0) {
	        var waitText = I18N.NoResultsFound;
	        this.LoadGIF.innerHTML = waitText;
	    } else {
	        this.LoadGIF.style.display = "none";
	        //this.LoadGIF.style.visibility = "hidden";
	    }
	},
	OnLoad: function () { },
	OnToDataList: function (rows) { },
	OnLoaded: function (Result, Count) { },
	OnPageChange: function () { },
	OnFilters: function (e) { },
	OnFiltersed: function (Result, Count) { },
	OnNullResult: function () {},
	_initData: function (xmlNodes) {
		var rowNodes, rows, nodeName, nodeValue;
		this.fieldName = [];
		this.dataList = [];
		if (zXml.useActiveX) {
		    try {
		    
			xmlNodes = xmlNodes || this.xmlDoc.documentElement.childNodes; 
			for (var i = 0; i < xmlNodes.length; i++) {
				rowNodes = xmlNodes[i].childNodes;
				rows = {};
				for (var j = 0; j < rowNodes.length; j++) {
					nodeName = xmlEscape(rowNodes[j].nodeName);
					nodeValue = xmlEscape(rowNodes[j].text);
					rows[nodeName] = nodeValue;
					if (i==0) {
						this.fieldName.push(nodeName);
					}
				}
				if (this.OnToDataList(rows, this._initData.caller != this.Query) != false) 
					this.dataList.push(rows);
			}
			
			} catch (ex) {  }
		} else {
			xmlNodes = xmlNodes || this._selectNodes("*");
			this.fieldName = [];
			var rowNodes;
			if (xmlNodes[0] != undefined) {
			    rowNodes = xmlNodes[0].getElementsByTagName('*');
			
			    for (f = 0; f < rowNodes.length; f++){
				    this.fieldName.push(rowNodes[f].nodeName);
			    }
			    for (var i = 0; i < xmlNodes.length; i++) {
				    rowNodes = [];
				    for (var s = 0; s < this.fieldName.length; s++) {
					    rowNodes.push(xmlNodes[i].getElementsByTagName(this.fieldName[s])[0].textContent);
				    }
				    rows = {};
				    for (var j = 0; j < rowNodes.length; j++) {
					    nodeName = xmlEscape(this.fieldName[j]);
					    nodeValue = xmlEscape(rowNodes[j]);
    						
					    rows[nodeName] = nodeValue;
				    }
				    if (this.OnToDataList(rows, this._initData.caller != this.Query) != false) 
					    this.dataList.push(rows);
			    }
			}
		}
		
		if (this._initData.caller != this.Query) {
			this.xmlCount = this.dataList.length;
		}
		this.Count = this.dataList.length;
		this.OnPageChange();
	},
	_initUI: function () {
		var dataTable = document.createElement('table');
		dataTable.className = 'DataList';
		this.srcElement.appendChild(dataTable);
		return dataTable;
	},
	_selectNodes: function (xPath) {
		var xmlNodes;
		if (zXml.useActiveX)
				xmlNodes = this.xmlDoc.selectNodes(xPath);
		else{
			var oEvaluator = new XPathEvaluator();
			var oResult = oEvaluator.evaluate(xPath, this.xmlDoc.documentElement, null,
				XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

			var oElement;
			xmlNodes = [];
			while (oElement = oResult.iterateNext()) {
				  xmlNodes.push(oElement);
			}
		}
		
		return xmlNodes;
	}
};





////////////////////////
function xmlEscape(text)
{    
    text = text.replace(/&/g,"&amp;");
    text = text.replace(/</g,"&lt;");
    text = text.replace(/>/g,"&gt;");
    
    return text;
}
function xmlUnescape(text)
{
    text = text.replace(/&lt;/g,"<");
    text = text.replace(/&gt;/g,">");
    text = text.replace(/&amp;/g,"&");
    return text;
}

function htmlConvert(text)
{
	var reNumber = /^\d+$/; //数字.
	var reMail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; //EMail;
	var reLink = /.+\.\w+\?\w+\=\d+$/; //Links
	var reImage = /\.[gif|jpg|jpeg]/i;
	var reDate = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	if (reMail.exec(text)) text = "<a href='mailto:" + text + "'>" + text + "</a>";
	if (reLink.exec(text)) text = "<a href='" + text + "'>" + text + "</a>";
	if (reImage.exec(text)) text = "<img src='" + text + "' />";
	if (reDate.exec(text)) {var d=new Date(text); text=d.toLocaleDateString();};
	if (reNumber.exec(text)) text = Math.floor(text);
	if (text==null || text=='') text="&nbsp;";
	
	return text;
}


///////////////////////

var DataProcess = function () {this.initialize.apply(this, arguments);}
DataProcess.prototype = {
	initialize: function (fields) {
		this.fields = fields;
	},
	isNotPermit: function (fieldName) {
		return !this.isAuto;
	},
	insertHead: function (fieldName, Row) {
		
	},
	insertRow: function (data, table) {
		
	},
	convertField: function (fieldID, data) {

	}
};

