﻿/**
 * 项目名称：[js工具库]
 * 程序作者：李宁<liningftp@163.com>
 * 创建时间：2008-08-20
 * 修改记录：2008-09-19 00:05 修正lee.cssTextToJsNameJSON函数，支持styleFloat(IE)、支持形如border-right-width的属性
 * 当前版本：2009-01-08
 */

//==================================================================================================命名空间
var lee = lee || {};//命名空间

//==================================================================================================工具函数
/**
 * document.getElementById的简洁形式
 */
lee.$ = function(id){
    return typeof(id) == "object" ? id : document.getElementById(id);
};

/**
 * 检测浏览器是否为IE
 * @return {Boolean} }如果是IE，返回true；否则，返回false。
 */
lee.isIE = (function(){return navigator.appName.indexOf("Microsoft") > -1})();

/**
 * @return {String} 返回时间戳
 */
lee.timestamp = function(){return new Date().getTime();};

/**
 * @return {String} 返回形如：2008-08-30格式的日期时间
 */
lee.gettime = function(){
    function addstart(s){
        return s.length == 2 ? s : "0"+s;
    }
    var time = new Date();
    return time.getFullYear() + 
        "-" + addstart(time.getMonth().toString()) + 
        "-" + addstart(time.getDay().toString()) + 
        " " + addstart(time.getHours().toString()) + 
        ":" + addstart(time.getMinutes().toString()) + 
        ":" + addstart(time.getSeconds().toString());
};

//==================================================================================================Cookie
/**
 * 设置cookie值
 * @name {String} 新项的名称
 * @value {String} 新项的值
 * @hours {Int} 持续存在多少个小时
 * @return {void}
 */
lee.setCookie = function(name, value, hours){
    var expires = "";
    if(hours){
        expires = new Date(new Date().getTime() + hours*3600000);
        expires = ";expires=" + expires.toGMTString();
    }
    document.cookie = name + "=" + encodeURIComponent(value) + expires;
};

/**
 * 获取制定name的cookie值
 * @name {String} 获取项的名称
 * @return {String} 获取项的值
 */
lee.getCookie = function(name){
    var value = "";
    var cookies = document.cookie;
    cookies = cookies.split(';');
    
    for(var i = 0; i < cookies.length; ++i){
        if(cookies[i].length > 1){
            cookies[i] = cookies[i].split('=');
            if(cookies[i][0] == name) 
                value = decodeURIComponent(cookies[i][1]);
        }
    }
    
    return value;
};

//==================================================================================================动态载入资源
////////////////////////////////////////////////////////////////////////////////Script载入
/**
 * “动态脚本标签”导入js文件（如果不是必须，不要使用，因为这种方式在IE下是异步的，而在FireFox下是同步的）
 * @src {String} js文件的url地址
 */
var Script = function(src){
    this.head = document.getElementsByTagName("head").item(0);
	this.scriptObj = document.createElement("script");
    this.src = src;
	this.timestamp = '&timestamp=' + (new Date()).getTime();
};

/**
 * @return {void}
 */
Script.prototype.add = function(){
	this.scriptObj.setAttribute("type","text/javascript");
	this.scriptObj.setAttribute("charset", "gb2312");
	//请求非js文件
	//this.scriptObj.setAttribute("src", this.src + this.timestamp);
	//请求js文件
	this.scriptObj.setAttribute("src", this.src);
	this.head.appendChild(this.scriptObj);
};

/**
 * @return {void} 
 */
Script.prototype.remove = function(){
    this.head.removeChild(this.scriptObj);
};

////////////////////////////////////////////////////////////////////////////////动态添加Css样式
var Css = function(txt){
    this.head = document.getElementsByTagName("head").item(0);
    this.cssObj = document.createElement("style");
    this.cssTxt = txt;
};

Css.prototype.add = function(){
    this.cssObj.setAttribute("type","text/css");
    try{
        this.cssObj.innerHTML = this.cssTxt;
    }catch(e){
        this.cssObj.styleSheet.cssText = this.cssTxt;
    }
    this.head.appendChild(this.cssObj);
};

Css.prototype.remove = function(){
    this.head.removeChild(this.cssObj);
};

//==================================================================================================Css文本解析
/*
 * 将css文本转成JSON对象
 * @cssTxt {String}
 * @return {JSON}
 */
lee.cssTextToJSON = function(cssTxt){
    var s = cssTxt.replace(/[{}]/g, "");        
    var arr = s.split(";");
    var o = {};
    for(var i = 0; i < arr.length; i++){
        if(arr[i].length > 2){
            var arr2 = arr[i].split(':');
            o[arr2[0]] = arr2[1].toString();
        }
    }
    return o;
};

/**
 * 将css样式名转成js中style的属性名
 * @name {String} css样式名
 * @return {String} style属性名
 */
lee.cssStyleNameToJsName = function(name){
    if(name.indexOf('-') > -1){
        var i = name.indexOf('-');
        name = name.substring(0, i) + name.substr(i+1, 1).toUpperCase() + name.substring(i+2);
        return lee.cssStyleNameToJsName(name);
    }
    else{
        return name;
    }
};

/**
 * 将cSS文本转成js中style的属性名对象
 * @name {String} css样式名
 * @return {JSON} style属性名对象
 */
lee.cssTextToJsNameJSON = function(cssTxt){
    var s = cssTxt.replace(/[{}]/g, "");        
    var arr = s.split(";");
    var o = {};
    for(var i = 0; i < arr.length; i++){
        if(arr[i].length > 2){
            var arr2 = arr[i].split(':');
            var name = lee.cssStyleNameToJsName(arr2[0]);
            o[name] = arr2[1].toString();
        }
    }
    
    if(o.float){
        o.cssFloat = o.float;
        o.styleFloat = o.float;
        delete(o.float);  
    }
    return o;
};

//==================================================================================================资源清理
lee.gc = {
	purge : function(d){
	    var a = d.attributes, i, l, n;
	    if(a){
		    l = a.length;
		    for(i = 0; i < l; ++i){
			    n = a[i].name;
			    if(typeof d[n] === 'function'){
				    d[n] = null;
			    }
		    }
	    }
	    a = d.childNodes;
	    if(a){
		    l = a.length;
		    for(i = 0; i < l; ++i){
			    lee.gc.purge(d.childNodes[i]);
		    }
	    }
	}
};

//==================================================================================================Div类
function Div(o){        
    this.div = o || document.createElement("div");
    this.x = null;
    this.y = null;
    this.width = null;
    this.height = null;
}

/**
 * 添加样式
 * @cssTxt {String} css风格的样式文本（不支持一键多值的形式，如："border:solid 1px red"）
 * @return {void}
 */
Div.prototype.addStyle = function(cssTxt){
    var o = lee.cssTextToJsNameJSON(cssTxt);
    for(var n in o)
        this.div.style[n] = o[n];
    if(o.left && typeof o.left == 'string')
        this.x = parseInt((o.left).match(/\d+/)[0]);
    if(o.top && typeof o.top == 'string')
        this.y = parseInt((o.top).match(/\d+/)[0]);
    
    if(o.width) this.width = o.width;
    if(o.height) this.height = o.height;
};

/**
 * 给div Dom元素添加文本内容
 * @txt {String} 文本内容
 * @return {void}
 */
Div.prototype.addText = function(txt){
    this.div.innerHTML = txt;
};

/**
 * 将this.div添加到指定dom中
 * @parent {HTMLElement}
 * @return {void}
 */
Div.prototype.appendParent = function(parent){
    this.parent = parent;
    this.parent.appendChild(this.div);
};

/**
 * 将this.div的对象绑定清空，并从父节点中删除
 * @return {void}
 */
Div.prototype.removeSelf = function(){
    lee.gc.purge(this.div);
    if(this.parent)
        this.parent.removeChild(this.div);
};

/**
 * 移除所有字节点
 */
Div.prototype.removeAllChild = function(){
    while(true){
        if(this.div.childNodes[0]){
            this.div.removeChild(this.div.childNodes[0]);
        }
        else break;
    }
};

/**
 * 向this.div添加事件绑定
 * @return {void}
 */
Div.prototype.addEvent = function(type, func){
    if(this.div.attachEvent)
        this.div.attachEvent("on" + type, func);
    else if(this.div.addEventListener)
        this.div.addEventListener(type, func, false);
};

//==================================================================================================Element方法
var Element = {};
/**
 * 只保留Element的第一个节点，剩余都删除
 */
Element.remainFirst = function(node){
    //IE n=1,FF n=2
    var n = document.getElementsByClassName == null ? 1 : 2;
    while(node.childNodes.length > n){
            node.removeChild(node.childNodes[n]);
    }
};
//==================================================================================================事件方法
lee.addEvent = function(node, type, func){
    if(node.attachEvent)
        node.attachEvent("on" + type, func);
    else if(node.addEventListener)
        node.addEventListener(type, func, false);
};

lee.removeEvent = function(node, type, func){
    if(node.detachEvent)
        node.detachEvent("on" + type, func);
    else if(node.removeEventListener)
        node.removeEventListener(type, func, false);
};

lee.addStyle = function(el, cssText){
    if(el == null) return;
    var o = lee.cssTextToJsNameJSON(cssText);
    for(var n in o)
        el.style[n] = o[n];
};

lee.addStyleToHead = function(css) {
	var style = document.createElement('style');
	style.type = 'text/css';
	if(this.isIE){
		style.styleSheet.cssText = css;  
	}else{
		style.innerHTML = css;
	}
	document.getElementsByTagName('head')[0].appendChild(style);
};
//==================================================================================================获取位置坐标
/**
 * 位置坐标类
 * @e {Event} 鼠标事件
 * @param {Int} n 表示参考对象为“最近源对象”的n级父对象,n=0时表示自己
 */
function Position(e, n){
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;
    
    //IE--e.srcElement;FF--e.target
    this.target = e.srcElement || e.target;
    if(n > 0){
        for(var i = 0; i < n; ++i)
            this.target = this.target.parentNode;
    }
    this.targetTop = this.target.offsetTop;
    this.targetLeft = this.target.offsetLeft;
    this.targetWidth = this.target.offsetWidth;
    this.targetHeight = this.target.offsetHeight;
};

//==================================================================================================信息输出台
lee.console = {
    counter:0,        
    main:null,
    width:0,
    height:0,
    
    init:function(width, height){
        lee.console.width = width;
        lee.console.height = height;
        var div = new Div();
        div.addStyle("position:absolute;top:1px;right:1px;width:" + width + "px;height:" + height + "px;border-style:solid;border-width:2px;border-color:#99aaee;overflow-x:scroll;overflow-y:scroll;");
        div.appendParent(document.body);
        lee.console.main = div;
    },
    
    goBottom:function(){
        lee.console.main.div.scrollTop = lee.console.main.div.scrollHeight;
    },
    
    out:function(s){
        var div = new Div();
        div.addStyle("{width:" + (lee.console.width - 17) + "px;height:20px;padding-top:2px;font-size:14px;}");
        if(s != "\n" && s != "n"){
            if(++lee.console.counter%2 == 1)
                div.addStyle("{background-color:#99aaee;}");
            else    
                div.addStyle("{background-color:#ccd6ff;}");
            div.addText(s);
        }
        else{
            div.addStyle("{background-color:orange;}");
        }
        div.appendParent(lee.console.main.div);
        lee.console.goBottom();
    },
    
    clear:function(){
        
    }
};
//==================================================================================================Array工具
/**
 * 返回指定元素在数组中的索引
 * @arr {Array}
 * @o {Object} 指定元素
 * @return {Int} 元素的索引，不存在返回-1
 */
Array.indexOf = function(arr, o){/*return:int, ok:> -1, none:-1*/
    for(var i = 0; i < arr.length; i++){
        if(arr[i] == o)
            return i;
    }
    return -1;
};

Array.remove = function(arr, k){/*return:Array*/
	var res = [];
	for(var i = 0; i < arr.length; i++){
		if(i == k){
			while(i < arr.length - 1){
				res[i] = arr[++i];
			}
			break;
		}
		res[res.length] = arr[i];
	}
	return res;
}

/**
 * 交换索引i和j的对应的元素
 * @arr {Array}
 * @i {Int}
 * @j {Int}
 * @return {void}
 */
Array.exchange = function(arr, i, j){
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
};

/**
 * 移动数组元素
 * @arr {Array}
 * @i {Int} 移动起始位置
 * @j {Int} 移动终点位置
 * @return {void}
 */
Array.move = function(arr, i, j){
    var temp = arr[i];
    while(i < j){
        arr[i] = arr[++i];
    }
    arr[j] = temp;
};

/**
 * 查找指定元素在指定数组中存在的个数
 * @array {Arrray}指定的数组
 * @value {Object}指定的元素
 * @return {Int}存在的个数
 */
Array.hasValue = function(array, value){
    var counter = 0;
    for(var i = 0; i < array.length; ++i)
        if(array[i] == value)
            ++counter;
    return counter;
};

/**
 * 去除数组中重复的元素，相同的元素只保留一个
 * @array {Arrray} 指定的数组
 * @return {Array} 经过浓缩之后的新数组
 */
Array.trimRepeat = function(array){
    var arr = [];
    for(var i = 0; i < array.length; ++i)
        if(Array.hasValue(arr, array[i]) == 0)
            arr[arr.length] = array[i];
    return arr;
};

//==================================================================================================String
String.toJSON = function(txt){
	s = "[" + txt + "]";
	try{
		return eval(s)[0];
	}
	catch(e){
		return txt;
	}
};

/**
 * 去除字符串首尾空格，2008-09-20 09:03
 * @param {String} s --原字符串
 * @return {String} 新字符串
 */
String.trim = function(s){
    return s.replace(/(^\s*)|(\s*$)/g, '');
};

/**
 * 计算子字符串的个数，2008-11-22 11:50
 * @param {String} str --原字符串
 * @param {String} substr --子字符串
 * @return {Int} 返回值
 */
String.getCount = function(str, substr){
	var i = str.indexOf(substr), j = str.lastIndexOf(substr), count = 0;
	while(i){
		++count; if(i == j) break;
		i = str.indexOf(substr, i + 1);
	}		
	return count;
};

/**
 * 获取字符串的字节长度，中文一个字符按两个字节计算
 */
String.getByteLength = function(str){
    var i, sum = 0;
    for(i = 0; i < str.length; i++) {
        if ((str.charCodeAt(i) >= 0) && (str.charCodeAt(i) <= 255))  
            sum = sum + 1;
        else
            sum = sum + 2;
    }
    return sum;
};
//==================================================================================================Event
lee.event = {
    add : function(el, type, func){
        if(window.attachEvent){
            el.attachEvent('on'+type, func);
        }
        else if(window.addEventListener){
            el.addEventListener(type, func, false);
        }
    }
};

//==================================================================================================Ajax
function Ajax(method, url, data, callback){
    var o = (function(){
		if(window.ActiveXObject){
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
		else if(window.XMLHttpRequest){
			return new XMLHttpRequest();
		}
	})();
	
	var head = function(){
		o.open("HEAD", url + "&timestamp=" + new Date().getTime().toString(), true);
		o.onreadystatechange = response;
		try{
		o.send(null);
		}catch(e){
		} 
	};
	
	var get = function(){
		o.open("GET", url + "&timestamp=" + new Date().getTime().toString(), true);
		o.onreadystatechange = response;
		o.send(null);
	};
	
	var post = function(data){
		o.open("POST", url, true);
		o.onreadystatechange = response;
		o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		o.send(data);
	};
	
	var response = function(){
		if(o.readyState == 4){
//		    try{
//		        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
//			}catch(e){}
		    if(o.status == 200){
			    callback(o.responseText);
		    }
		}
	};
	
	this.xhr = function(){
	    return o;
	};
	
	this.request = function(){
	    switch(method.toUpperCase()){
	        case "GET":
			    get();
	            break;
	        case "POST":
	            post(data);
	            break;
	        case "HEAD":
	            head();
	            break;
	    }
	};
}

//==================================================================================================JSON
if(!JSON) var JSON = {};
JSON.getEle = function(json, n){
    var i = -1;
    for(var key in json){
        if(++i == n)
            return json[key];                
    }
};

//==================================================================================================iframe-push
lee.push =  {
    connection   : false,
    iframediv    : false,
	
    //接收回调函数
    recv: null,
    
    initialize: function(src, recv) {
        lee.push.recv = recv;
        if(navigator.appVersion.indexOf("MSIE") != -1) {
            // For IE browsers
            lee.push.connection = new ActiveXObject("htmlfile");
            lee.push.connection.open();
            lee.push.connection.write("<html>");
            //lee.push.connection.write("<script>document.domain = '"+document.domain+"'");
            lee.push.connection.write("</html>");
            lee.push.connection.close();
            lee.push.iframediv = lee.push.connection.createElement("div");
            lee.push.connection.appendChild(lee.push.iframediv);
            lee.push.connection.parentWindow.recv = lee.push.recv;
            lee.push.iframediv.innerHTML = "<iframe id='lee.push_iframe' src=" + src + "></iframe>";
        } 
        else if (navigator.appVersion.indexOf("KHTML") != -1) {
            // for KHTML browsers.[i.e:(KDE)Konqueror/Safari(WebKit)]
            lee.push.connection = document.createElement('iframe');
            lee.push.connection.setAttribute('id', 'lee.push_iframe');
            lee.push.connection.setAttribute('src', src);
            with (lee.push.connection.style) {
                position   = "absolute";
                left       = top   = "-100px";
                height     = width = "1px";
                visibility = "hidden";
            }
            document.body.appendChild(lee.push.connection);
        }
        else{
            // For other browser (Firefox...)
            lee.push.connection = document.createElement('iframe');
            lee.push.connection.setAttribute('id', 'lee.push_iframe');
            with(lee.push.connection.style){
                left       = top   = "-100px";
                height     = width = "1px";
                visibility = "hidden";
                display    = 'none';
            }
            lee.push.iframediv = document.createElement('iframe');
            lee.push.iframediv.setAttribute('src', src);
            lee.push.connection.appendChild(lee.push.iframediv);
            document.body.appendChild(lee.push.connection);
        }
    },

    onUnload: function() {
        if (lee.push.connection) {
            lee.push.connection = false; 
        }
    }
};

//==================================================================================================dynamic script
//var dscript = function(src){
//    this.head = document.getElementsByTagName("head").item(0);
//	this.scriptObj = document.createElement("script");
//    this.src = src;
//	this.timestamp = '&timestamp=' + (new Date()).getTime();
//};
//			  
////需要重新定义
//dscript.prototype.callback = null;

//dscript.prototype.send = function(){
//	this.scriptObj.setAttribute("type","text/javascript");
//	this.scriptObj.setAttribute("charset", "gb2312");
//	this.scriptObj.setAttribute("src", this.src + "?callback=" + this.callback + "&timestamp=" + this.timestamp);
//	this.head.appendChild(this.scriptObj);
//};

//dscript.prototype.remove = function(){
//    this.head.removeChild(this.scriptObj);
//};
//==================================================================================================Html Encode/Decode
var HtmlCode = {
    /**
     * @param {HTMLString} html
     * @return {String}
     */
    encode:function(html){
        //替换小于号<
        html = html.replace(/</g, '$lt;');
        //替换大于号<
        html = html.replace(/>/g, '$gt;');
        //替换空白符
        html = html.replace(/ /g, '$nbsp;');
        return html;
    },
    
    /**
     * @param {String} str
     * @return {HTMLString} html
     */
    decode:function(str){        
        //替换<为&lt;
        str = str.replace(/\$lt;/g, '<');
        //替换<为&gt;
        str = str.replace(/\$gt;/g, '>');
        //替换&nbsp;为空白符
        str = str.replace(/\$nbsp;/g, ' ');
        return str;
    }
};

//==================================================================================================Control类
var Control = {
    /**
     * @param {HTMLElement} textarea
     */
    TextArea:function(textarea){
        var o = textarea;
        var start = 0;
        var end = 0;
        
        var savepos = function(){
            //如果是Firefox(1.5)的话，方法很简单
            if(typeof(o.selectionStart) == "number"){
                start = o.selectionStart;
                end = o.selectionEnd;
            }
            //下面是IE(6.0)的方法，麻烦得很，还要计算上'\n'
            else if(document.selection){
                var range = document.selection.createRange();
                if(range.parentElement().id == o.id){
                    // create a selection of the whole textarea
                    var range_all = document.body.createTextRange();
                    range_all.moveToElementText(o);
                    //两个range，一个是已经选择的text(range)，一个是整个textarea(range_all)
                    //range_all.compareEndPoints()比较两个端点，如果range_all比range更往左(further to the left)，则
                    //返回小于0的值，则range_all往右移一点，直到两个range的start相同。
                    // calculate selection start point by moving beginning of range_all to beginning of range
                    for(start=0; range_all.compareEndPoints("StartToStart", range) < 0; start++) range_all.moveStart('character', 1);
                    // get number of line breaks from textarea start to selection start and add them to start
                    // 计算一下\n
                    for(var i = 0; i <= start; i ++){
                        if (o.value.charAt(i) == '\n') start++;
                    }
                    // create a selection of the whole textarea
                    var range_all = document.body.createTextRange();
                    range_all.moveToElementText(o);
                    // calculate selection end point by moving beginning of range_all to end of range
                    for(end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end ++) range_all.moveStart('character', 1);
                    // get number of line breaks from textarea start to selection end and add them to end
                    for (var i = 0; i <= end; i ++){
                        if (o.value.charAt(i) == '\n') end ++;
                    }
                }
            }
        };
        
        lee.addEvent(o, 'keydown', savepos);
        lee.addEvent(o, 'keyup', savepos);
        lee.addEvent(o, 'mousedown', savepos);
        lee.addEvent(o, 'mouseup', savepos);
        lee.addEvent(o, 'focus', savepos);
        
        this.insert = function(text){
            var pre = o.value.substr(0, start);
            var post = o.value.substr(end);
            o.value = pre + text + post;
        };
    }    
};

//=================================================================================================>
/**
 * 网格控件 2008-09-18
 * @param {HTMLElement} parent 父对象
 * @param {Array} data 二维数组对象 [[v1,v2,...],...]
 * @param {Object} sizes -> {width:w, colsWidth:[w1,w2,...], rowHeight:h, rowsCount:c}
 * 修改记录：2008-09-22 10:00 修正单击索引内容不改变bug，增加Grid.removeSelf()方法
 *           2008-11-26 23:38 重新实现
 *           2009-01-08 09:42 更新实现 增加行集属性
 */
Control.Grid = function (parent, data, sizes){
	this.width = sizes.width;
	this.rowHeight = sizes.rowHeight;
	this.rowsCount = sizes.rowsCount;
	this.height = (this.rowHeight + 2) * this.rowsCount + 5;//考虑到边框占用的高度，加入了调整参数
	this.colsCount = sizes.colsWidth.length;
	this.colsWidth = sizes.colsWidth;
	
	//创建显示容器
	var table = document.createElement("div");
	lee.addStyle(table, '{width:' + this.width + 'px;height:' + this.height + 'px;border-style:solid;border-width:1px;border-color:#7f7f7f;}');
    parent.appendChild(table);
    
    this.board = document.createElement("div");
    lee.addStyle(this.board, '{}');
    table.appendChild(this.board);
    
    //创建表头
    this.header = document.createElement("div");
	lee.addStyle(this.header, '{width:' + this.width + 'px;height:' + this.rowHeight + 'px;}');
	lee.addStyle(this.header, '{background-color:#aaa;}');
	this.board.appendChild(this.header);
	
	//创建表头字段
	for(var j = 0; j < this.colsCount; ++j){
		var td = document.createElement("div");
		lee.addStyle(td, '{width:' + this.colsWidth[j] + 'px;height:' + this.rowHeight + 'px;line-height:' + this.rowHeight + 'px;float:left;font-size:12px;text-align:center;}');
		if(this.colsCount - j > 1)
			lee.addStyle(td, '{border-right-style:solid;border-right-width:1px;border-right-color:#cbcbcb;}');
		//插入单元格
		this.header.appendChild(td);
	}
	
	//创建行
	this.main = document.createElement("div");
	this.board.appendChild(this.main);
	this.rows = [];
	this.rowsColor = {normal0:'#ffffff', normal1:'#edf5ff', mouseover:'#b2d2ff'};
	
	this.render = function(n){
	    this.main.innerHTML = "";
	    var len = (this.rowsCount * n <= data.length ? this.rowsCount : data.length % this.rowsCount);
	    this.rows = [];
	    for(var i = this.rowsCount*(n-1), t = 0; t < len; ++i, ++t){
		    var row = document.createElement("div");
		    this.rows[this.rows.length] = row;
		    lee.addStyle(row, '{width:' + this.width + 'px;height:' + this.rowHeight + 'px;}');
		    if (i % 2 == 1)
			    lee.addStyle(row, '{background-color:' + this.rowsColor.normal0 + ';}');
		    else
			    lee.addStyle(row, '{background-color:' + this.rowsColor.normal1 + ';}');
		    //添加行
		    this.main.appendChild(row);
    		
		    //创建单元格
		    for(var j = 0; j < this.colsCount; ++j){
			    var td = document.createElement("div");
			    //添加数据
			    td.innerHTML = data[i][j];
			    lee.addStyle(td, '{width:' + this.colsWidth[j] + 'px;height:' + this.rowHeight + 'px;line-height:' + this.rowHeight + 'px;float:left;font-size:12px;text-align:center;}');
			    if(this.colsCount - j > 1)
				    lee.addStyle(td, '{border-right-style:solid;border-right-width:1px;border-right-color:#cbcbcb;}');
			    //插入单元格
			    row.appendChild(td);
		    }
	    }
	};
	
	//插入新数据
	//newdata->[[],[],[],...]
	this.insert = function(newdata){
	    for(var i = 0; i < newdata.length; ++i){
		    var row = document.createElement("div");
		    this.rows[this.rows.length] = row;
		    lee.addStyle(row, '{width:' + this.width + 'px;height:' + this.rowHeight + 'px;}');
		    if (i % 2 == 1)
			    lee.addStyle(row, '{background-color:' + this.rowsColor.normal0 + ';}');
		    else
			    lee.addStyle(row, '{background-color:' + this.rowsColor.normal1 + ';}');
		    //添加行
		    this.main.appendChild(row);
    		
		    //创建单元格
		    for(var j = 0; j < this.colsCount; ++j){
			    var td = document.createElement("div");
			    //添加数据
			    td.innerHTML = newdata[i][j];
			    lee.addStyle(td, '{width:' + this.colsWidth[j] + 'px;height:' + this.rowHeight + 'px;line-height:' + this.rowHeight + 'px;float:left;font-size:12px;text-align:center;}');
			    if(this.colsCount - j > 1)
				    lee.addStyle(td, '{border-right-style:solid;border-right-width:1px;border-right-color:#cbcbcb;}');
			    //插入单元格
			    row.appendChild(td);
		    } 
	    }	    
	    //最下面一行的下边框，使用红线
	    lee.addStyle(this.rows[this.rows.length - 1], 'border-bottom-style:solid;border-bottom-width:1px;border-bottom-color:#000;');

	};
};

/**
 * 分页控件
 * @param {int} total 总数量 
 * @param {int} per 单页数量
 * @param {HTMLEevent} clickEvent 单击分页索引事件方法
 * @param {String} name 实例名
 * @return void
 */
Control.Pagination = function(parent, total, per, clickEvent, name){
    this.parent = parent;
    this.total = total;
    this.per = per;
    this.name = name;
    
    this.indexN = (total%per == 0 ? total/per : (total-total%per)/per + 1);//页数
    this.pageN = (this.indexN%10 == 0 ? this.indexN/10 : (this.indexN-this.indexN%10)/10 + 1);
    
    this.current_id = 'index_1';//当前选中索引链接的ID
    this.current_page = 1;//当前页数
    
    /**
     * 单击索引
     * @param {string} id索引连接的ID，如：index_1
     * @param {int} n id中的数字，如：1
     */
    this.click = function(id, n){
        if(lee.$(id) == null || (id == this.current_id && lee.$(id).value == 1))
            return;
        lee.$(id).value = 1;
        
        lee.addStyle(lee.$(this.current_id), '{background-color:;color:#333;}');
        lee.addStyle(lee.$(id), '{background-color:#f00;color:#fff;}');
        lee.$(id).blur();
        this.current_id = id;
        //调用用户定义的方法
        clickEvent(n);
    };
    
    //改变页
    this.changepage = function(/*新页中第一个索引号*/start){
        var a_html = "<div style='width:70px;float:left;'><a href='javascript:" + this.name + ".gohead()'>最前</a><a href='javascript:" + this.name + ".goup()' style='margin:0px 10px 0px 5px;'>上页</a></div>";
        var len = ((this.indexN - start + 1) < 10 ? (this.indexN - start + 1) : 10);
        a_html += "<div style='width:250px;float:left;font-size:14px;'>";
        for(var i = start, j = 0; j < len; ++i, ++j){
            a_html += "<a id=\"index_" + i + "\" href=\"javascript:" + this.name + ".click('index_" + i + "'," + i + ");\" style=\"margin:0px 2px;\">" + i + "</a>";
        }
        a_html += "</div>";
        a_html += "<div style='width:70px;float:left;'><a href='javascript:" + this.name + ".godown()' style='margin:0px 5px 0px 10px;'>下页</a><a href='javascript:" + this.name + ".goend()'>最后</a></div>";
        
        this.parent.innerHTML = a_html;
        lee.$('current_page').innerHTML = this.current_page;
    };
     
    this.changepage(1);
    var s = this.name + ".click('index_1', 1)";
    setTimeout(function(){eval(s);}, 200);
    
    //翻到最前
    this.gohead = function(){
        if(this.current_page == 1)
            return;
        this.current_page = 1;
        this.changepage(1);
        
        var s = this.name + ".click('index_1', 1)";
        eval(s);
    };
    //翻到最后
    this.goend = function(){
        if(this.current_page == this.pageN)
            return;
        this.current_page = this.pageN;
        var start = (this.pageN - 1) * 10 + 1;
        this.changepage(start);
        
        var s = this.name + ".click('index_" + start + "', " + start + ")";
        eval(s);
    };
    //翻到下页
    this.godown = function(){
        if(this.current_page == this.pageN)
            return; 
        var start = (this.current_page++) * 10 + 1;
        this.changepage(start);    
            
        var s = this.name + ".click('index_" + start + "', " + start + ")";
        eval(s);
    };
    //翻到上页
    this.goup = function(){
        if(this.current_page == 1)
            return;
        var start = (--this.current_page - 1) * 10 + 1;
        this.changepage(start);
                
        var s = this.name + ".click('index_" + start + "', " + start + ")";
        eval(s);
    };
    
    //转向第n页（n从1开始）  
    this.go = function(n){
        if(n < 1 || n > this.indexN){
            alert('超出范围！');
            return;
        }
        
        this.current_page = (n%10 == 0 ? n / 10 : (n - n%10) / 10 + 1);
        var start = (n%10 == 0 ? n : (n - n%10 + 1));
        this.changepage(start);
                
        var s = this.name + ".click('index_" + n + "', " + n + ")";
        eval(s);
    };
};

//=================================================================================================>page技巧
//设为首页
lee.setIndex = function(a){
    lee.addEvent(a, 'click', function(){
        a.style.behavior = 'url(#default#homepage)';
        a.setHomePage(location.href);
        return false;
    });
};

//将url查询参数，转换成json对象
lee.convertUrlParam = function(url_param){
    var params = url_param.split('&');
    var paramJSON = {};
    for(var i = 0; i < params.length; ++i){
        var keyValue = params[i].split('=');
        if(keyValue == "") continue;
        var key = keyValue[0].match(/[a-zA-Z_-]{1}[0-9a-zA-Z_-]+$/)[0];
        paramJSON[key] = keyValue[1];
    }
    return paramJSON;
};

//=================================================================================================>格式化
//输出格式：2009-03-19 13:56:01的形式
Date.prototype.formatDateTime = function(){
    var year = this.getFullYear(), mon = this.getMonth(), day = this.getDate();
    var hour = this.getHours(), min = this.getMinutes(), sec = this.getSeconds();
    mon = mon.toString().length == 2 ? mon + 1 : "0" + (mon + 1);
    day = day.toString().length == 2 ? day : "0" + day;
    hour = hour.toString().length == 2 ? hour : "0" + hour;
    min = min.toString().length == 2 ? min : "0" + min;
    sec = sec.toString().length == 2 ? sec : "0" + sec;
    
    return year + "-" + mon + "-" + day + " " + hour + ":" + min + ":" + sec;
};

//将时间字符串格式化成：2009-03-19 14:11:40的形式
lee.formatDateTime = function(/*String*/str_dt){
    str_dt = str_dt.split(" ");
    var date = str_dt[0].split("-");
    var time = str_dt[1].split(":");
    
    for(var i = 0; i < date.length; ++i){
        var d = date[i];
        if(i == 0){
            if(d.length == 2) date[i] = "20" + d;
        }
        else{
            if(d.length == 1) date[i] = "0" + d;
        }
    }
    
    for(var i = 0; i < time.length; ++i){
        var t = time[i];
        if(t.length == 1){
            time[i] = "0" + t;
        }
    }
    
    return date.join("-") + " " + time.join(":");
};