/**
 * Baidu UE JavaScript Library
 * 
 * get-unique-id.js
 * @author UTer
 * @version $Revision: 1.1 $
 */


(function () {
	var uniqueIdMap = {};
	
	/**
	 * @param <Number> len 生成uniqueId的长度
	 * @owner window
	 */
	getUniqueId = function (len) {
		var l = len || 8;
		var uid = '';
		while (l--) {
			uid += getRandomChar();
		}
		if (!uniqueIdMap[uid]) {
			uniqueIdMap[uid] = 1;
			return uid;
		} else {
			return getUniqueId(l);
		}
	}
	
	var getRandomChar = function () {
		var charMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		var charMapLen = charMap.length;
		return charMap.charAt(Math.floor(Math.random() * charMapLen));
	}
})();
/**
 * Baidu UE JavaScript Library
 * 
 * class.js
 * @author UTer
 * @version $Revision: 1.3 $
 */


/**
 * 元类
 * @public
 * @param <object> props 类成员
 * @param <Class> superClass 父类
 * @return <Class> 创建的类
 */
function Class(props, superClass) {
	var con = props.constructor == Object ? undefined : props.constructor;
	if (superClass) {
		var superConstructor = function () {superClass.call(this)};
	}
	var clazz = con || superConstructor || new Function();
	if (superClass) {
		function s_(){};
		s_.prototype = superClass.prototype;
		clazz.prototype = new s_();
	}
	for (var k in props) {
		clazz.prototype[k] = props[k];
	}
	clazz.constructor = clazz;
	return clazz;
}
/**
 * Baidu UE JavaScript Library
 * 
 * element.js
 * @author UTer
 * @version $Revision: 1.5 $
 */



/**
 * Dom对象的扩展类
 * @public
 */
var Element = new Class({
	constructor: function (el) {
		if (!el) return;
			
		if (el.constructor == String) {
	        el = document.createElement(el);
	    }
	    return G(el);
	}
});
Element.prototype = {
	/**
     * 包装器版本信息
     * @private
     */
	wrapVersion: 1,
	
	/**
	 * Element的样式操作
	 * <pre>
	 * <b>设置css：</b>
	 * .css('width', '500px')
	 * .css({width : '500px', backgroundColor : '#ccc'})
	 * .css('width', '500px', 'backgroundColor', '#ccc')
	 * <b>获取css：</b>
	 * .css('width')
	 * </pre>
	 * 
	 * @public
	 * @return <Element> 当前元素
	 */
	css: function (arg) {
		var argLen = arguments.length;
		if (argLen > 1 && argLen % 2 == 0) {
			for (var i = 0; i < argLen; i += 2) {
				var a = arguments[i], a2 = arguments[i+1];
				if (typeof a == 'string' && typeof a2 == 'string') {
					this.style[a] = a2;
				}
			}
		} else if (argLen == 1) {
			if (typeof arg == 'string') {
				var sty = this.currentStyle || document.defaultView.getComputedStyle(this, null);
				return sty[arg]; 
			} else {
				for (var k in arg) {
					this.style[k] = arg[k];
				}
			}
		}
		return this;
	},
	
	/**
     * 设置Element可见
     * @public
     * @param display 新的显示样式:block|inline....,默认为""(有些情况下,style.display=''还不能显示元素,原因待查)
     * @return <Element> 当前元素
     */
    show: function (display) {
        this.style.display = display || '';
        return this;
    },
	
	/**
	 * 设置Element隐藏
	 * @public
	 * @return <Element> 当前元素
	 */
	hide: function () {
		this.style.display = "none";
		return this;
	},
	
	/**
	 * 为Element添加class
	 * @public
	 * @param <string> name class的名称
	 * @return <Element> 当前元素
	 */
	addClass: function (name) {
		var classArr = this.className.split(/\s+/);
		classArr.push(name);
		this.className = classArr.join(' ');
		return this;
	},
	
	/**
	 * 删除Element的class
	 * @public
	 * @param <string> name class的名称
	 * @return <Element> 当前元素
	 */
	removeClass: function (name) {
		var classArr = this.className.split(/\s+/);
		var len = classArr.length;
		while (len--) {
			if (classArr[len] == name) {
				classArr.splice(len, 1);
			}
		}
		this.className = classArr.join(' ');
		return this;
	},
	
	/**
	 * 添加子Element
	 * @public
	 * @param <HTMLElement> el 要添加的元素
	 * @return <Element> 当前元素
	 */
	append: function (el) {
		this.appendChild(el);
		return this;
	},
	
	/**
	 * 设置Element的innerHTML
	 * @public
	 * @param <string> html html字符串
	 * @return <Element> 当前元素
	 */
	setHTML: function (html) {
		this.innerHTML = html;
		return this;
	},
	
	/**
	 * 从页面中移除Element
	 * @public
	 * @return <Element> 当前元素
	 */
	remove: function () {
		if (this.parentNode) {
			this.parentNode.removeChild(this);
		}
		return this;
	},
	
	/**
	 * 移除Element内部的文本节点
	 * @public
	 * @return <Element> 当前元素
	 */
	clearEmptyNode: function () {
		var nodes = this.childNodes;
		var i = nodes.length;
		while (i--) {
			var node = nodes[i];
			if (node.nodeType != 1 && 
				(node.nodeType != 3 || node.nodeValue.trim().length == 0)) {
				this.removeChild(node);
			}
		}
		return this;
	},
	
	/**
     * 获得Element的绝对位置
     * @public
     * @return <K,V> 位置信息
     */
    getPosition : function() {
        var left = 0, top = 0;
        var el = this;
        do {
            left += el.offsetLeft || 0;
            top += el.offsetTop || 0;
            el = el.offsetParent;
        } while (el);
        return  {'left': left, 'top': top};
    },
	
	/**
	 * 设置Element的透明度
	 * @public
	 * @param <number> opacity 透明度，0-1
	 * @return <Element> 当前元素
	 */
	setOpacity: function (opacity) {
		this.style.visibility = opacity < 0.001 ? "hidden" : "visible";
		if (!this.currentStyle || !this.currentStyle.hasLayout)
			this.style.zoom = 1;
			
		if (window.ActiveXObject)
			this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")";
			
		this.style.opacity = opacity;
		return this;
	}
}

/**
 * 获得dom对象的包装
 * @param <string||HTMLElement> el element或element的id
 * @return <Element> dom元素
 */
function G(el) {
	if (el.constructor == String) {
        el = document.getElementById(el);
    }
    if (!el) return null;
    var p = Element.prototype;
    if (el.wrapVersion == p.wrapVersion) {
        return el;
    }
    for (var n in p) {
        el[n] = p[n];
    }
    return el;
}

/**
 * Baidu UE JavaScript Library
 * 
 * string.js
 * @author UTer
 * @version $Revision: 1.5 $
 */


/**
 * 删除字符串中的首尾空白字符
 * 
 * @public
 * @return <String> 处理过的字符串
 */
String.prototype.trim = function () {
	return this.replace(/(^\s+|\s+$)/g, '');
}

/**
 * 编码字符串中的html敏感字符
 * 
 * @public
 * @return <String> 处理过的字符串
 */
String.prototype.escapeHTML = function () {
	return this.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/**
 * 反编码字符串中的html敏感字符
 * 
 * @public
 * @return <String> 处理过的字符串
 */
String.prototype.unescapeHTML = function () {
	return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
}

/**
 * 简单的字符串格式化
 * 
 * @public
 * @return <String> 格式化后的字符串
 */
String.prototype.format = function () {
	var argus = [];
	argus = Array.apply(argus, arguments);
	var reStr = this.replace(/\{([0-9]+)\}/g, function ($0, num) {
		var str = argus[parseInt(num, 10)];
		return  typeof(str) == 'undefined' ? '' : str;
	});
	return reStr;
}

/**
 * 判断字符串是否以某个字符串开始
 * 
 * @public
 * @param <String> str 开始的字符串
 * @return <Boolean> 是否以param string开始
 */
String.prototype.startWith = function (str) {
	return this.indexOf(str) == 0;
}

/**
 * 判断字符串是否以某个字符串结尾
 * 
 * @public
 * @param <String> str 开始的字符串
 * @return <Boolean> 是否以param string结尾
 */
String.prototype.endWith = function (str) {
	return this.lastIndexOf(str) == (this.length - str.length);
}
/**
 * Baidu UE JavaScript Library - Web Control
 * 
 * pager.js
 * @author UTer
 * @version $Revision: 1.4 $
 */


/**
 * 分页控件
 * <pre>
 * <h3>构造器参数说明：</h3>
 * current：当前页数，初始值为0
 * total：总页数
 * itemCount：显示的页数
 * 
 * firstPage：首页文字
 * lastPage：末页文字
 * previousPage：上一页文字
 * nextPage：下一页文字
 * 
 * onchange：日期选择变化时触发事件
 * 
 * <h3>示例：</h3>
 * var myPager = new Pager({
 * 	total:10,
 * 	current:1,
 * 	onchange:function(index) {
 * 		G('info').innerHTML = "你选择了第"+ (index+1) + "页";
 * 	}
 * });
 * myPager.appendTo(document.body);
 * </pre>
 * 
 * @param <Object> params 用于初始化控件的属性集合
 */
function Pager (params) {
	this.uniqueId = getUniqueId();
	params = params || {};
	
	this.current		= parseInt(params.current, 10) || 0;
	this.total			= parseInt(params.total, 10);
	this.itemCount		= parseInt(params.itemCount, 10) || 7;
	
	this.firstPage		= params.firstPage || "首页";
	this.lastPage		= params.lastPage || "末页";
	this.previousPage	= params.previousPage || "上一页";
	this.nextPage		= params.nextPage || "下一页";
	
	this.onchange = params.onchange || new Function();
}


Pager.prototype = {
	/**
	 * 将控件附加到页面容器
	 * 
	 * @public
	 * @param <HTMLElement> el 页面容器元素
	 */
	appendTo: function (el) {
		var container = new Element('div');
		container.id = this.uniqueId + 'Pager';
		container.className = 'pager-wrap';
		el.appendChild(container);
		this.renderPager(container);
		container.onclick = this.getChangeHandler();
		
		this.appendTo = new Function();
	},
	
	/**
	 * 设置当前页数
	 * 
	 * @public
	 * @param <Number> current 当前页数
	 */
	setCurrent: function (current) {
		this.current = current;
		this.renderPager(G(this.uniqueId + "Pager"));
	},
	
	/**
	 * 设置总页数
	 * 
	 * @public
	 * @param <Number> total 当前页数
	 */
	setTotal: function (total) {
		this.total = total;
		this.renderPager(G(this.uniqueId + "Pager"));
	},
	
	/**
	 * 绘制页码
	 * 
	 * @private
	 * @param <HTMLElement> container 控件自身容器元素
	 */
	renderPager: function (container) {
		var itemTpl = '<a index="{0}" class="{2}">{1}</a>';
		var html = [];
		
		//绘制首页和上一页
		if (this.current > 0) {
			html.push(itemTpl.format("0", this.firstPage, "pager-first"),
					itemTpl.format((this.current - 1), this.previousPage, "pager-prev"));
		}
		
		//计算起始页码和终止页码
		var start = this.current - Math.floor(this.itemCount / 2);
		if (start < 0) {
			start = 0;
		}
		var end = start + this.itemCount;
		if (end > this.total) {
			end = this.total;
			start = end > this.itemCount ? end - this.itemCount : 0;
		}
		
		//绘制页码
		for (;start < end; start++) {
			var itemClass = start == this.current ? "pager-current" : "pager-normal";
			html.push(itemTpl.format(start, "[" + (start+1) + "]", itemClass));
		}
		
		//绘制末页和下一页
		if (this.current < this.total - 1) {
			html.push(itemTpl.format((this.current + 1), this.nextPage, "pager-next"),
					itemTpl.format((this.total - 1), this.lastPage, "pager-last"));
		}
		
		container.innerHTML = html.join('');
	},
	
	/**
	 * 获取页码选择的事件句柄
	 * 
	 * @private
	 * @return <Function> 页码选择的事件句柄
	 */
	getChangeHandler: function () {
		var me = this;
		return function (e) {
			e = e || window.event;
			var tar = e.srcElement || e.target;
			
			var index = parseInt(tar.getAttribute('index'), 10);
			me.current = index;
			var reVal = me.onchange.call(me, index);
			if (!(reVal === false)) {
				me.renderPager(G(me.uniqueId + "Pager"));
			}
		}
	}
};

