/*{{{
 * 标签控制相关
 * 09-09-16 10:10:23 by wangxb07
 * }}}
 */

var TagLimiter = Class.create({
	initialize : function(inputId) {
		this.objMain = $(inputId);

		Event.stopObserving(this.objMain, "keyup");
		Event.stopObserving(this.objMain, "keydown");

		this.objMain.observe('keyup',this.exec.bind(this));
		this.objMain.observe('keydown',this.updateOldValue.bind(this));
		this.objMain.observe('blur',this.clearBlank.bind(this));

		this.limitTagNum = 10;//tag数量
		this.limitTagLength = 10;//tag内容中文长度
		this.zh_en_exchange = 5;//tag内容中英文等价比
		
		this.oldValue = "";
		this.keydownCount = 0;
	},
	/**
	 * 失去焦点清楚空白
	 */
	clearBlank : function(){
		var _valArr = this.objMain.value.split(',');
		var _resArr = [];
		var j = 0;
		for(var i=0; i < _valArr.length; ++i){
			if(!_valArr[i].blank()){
				_resArr[j] = _valArr[i];
				j++;
			}
		}
		this.objMain.value = _resArr.join(",");
	},

	updateOldValue : function(){
		this.keydownCount++;
		if(this.keydownCount==1){
			this.oldValue = this.objMain.value;
		}
	},

	exec : function(){
		this.checkQj(this.objMain);
		this.trunTagNum();
		this.trunTagLength();
		this.keydownCount = 0;
	},

	/**
	 * 标签数量不能操过制定个数
	 */
	trunTagNum : function(){
		var _valArr = this.objMain.value.split(',');
		var _newVal = '';
		if(_valArr.length > this.limitTagNum){
			this.objMain.value = this.oldValue;
		}
	},

	/**
	 * 标签能容不能操过制定长度
	 */
	trunTagLength : function(){
		var _valArr = this.objMain.value.split(',');

		for(var i=0; i < _valArr.length; i++){
			var _string = _valArr[i];
			if(this.isOutStrLen(_string)){
				this.objMain.value = this.oldValue;
				return false;
			}
		}
	//	_valArr.push(_string);
	//	if(this.objMain.value != this.oldValue)
	//		this.objMain.value = _valArr.join(",");
	},

	/**
	 * private
	 * 返回字符串中英文字符是否超过截取长度
	 * 
	 * @param		string		str		字符串
	 *
	 * @return		bool			
	 */
	isOutStrLen : function(str){
		var _arrStr = str.split('');
		var _length = 0;
		var _enStrLength = 0;
		var _zhStrLength = 0;
		for(var i=0; i < _arrStr.length; ++i){
			if(_arrStr[i].match(/[^\u4e00-\u9fa5]/g)){
				_enStrLength ++;
				_length = _length + 1;
			}else{
				_zhStrLength ++;
				_length = _length + this.zh_en_exchange;
			}
		}
		
		if((this.limitTagLength * this.zh_en_exchange) < (_enStrLength + _zhStrLength * this.zh_en_exchange)){
			return true;
		}else{
			return false;
		}
	},

	/**
	 * private
	 * 全角逗号转半角
	 * 
	 * @param 		dom_input	obj		输入框对象
	 *
	 */
	checkQj : function(obj) {
		var objValue = obj.value;
		var p1 = /(，+)|(\s+)|(\|+)|(\.+)|(。+)|(、+)|(\\+)|(`+)|(\/+)|(\{+)|(\}+)|(\"+)|(\'+)/g;
		if(p1.test(objValue)){
			obj.value = objValue.replace(p1,",");
		}
	}
});
