AE.namespace('AE.app');

AE.app.current = function(config){
	this.config = {
		// 是否重置当前URL
		currentURL : null,
		
		// 是否找最长规则
		onlyOneMatch : false,
		
		// 规则Map
		rules	:	{
			/*
			"we.aliui.com" : {"menu-1":{
																				css:"current",
																				text:"<a href="x">x</a>",
																				call:function(o){
																					alert(o.id);
																				}
																			}
														},
			"aliui.com" : {"menu-1":{css:"current"}}
			*/
		}
	};
	
	this.temp = {
		remainRuleIds : []		// 筛选过后剩余规则
	};

	// 返回对象
	return this;
};


AE.app.current.prototype =  {
	
	// 得到最终能匹配到的规则索引
	getremainRuleIds : function(rules){
		
		var _self = this;var config = this.config;
		var remainRuleIds = [];
		var currentRuleKey = "";
		
		for(key in config.rules){
			
			// 匹配正则
			var regx = new RegExp(key,"gi");

			if(config.onlyOneMatch){
				if(regx.test(location.href) && key.length > currentRuleKey.length){
					remainRuleIds = [];
					remainRuleIds.push(key);
					currentRuleKey = key;
				}
			}else{
				// 如果匹配成功 而且规则是最长的则认为是最终规则
				if(regx.test(location.href)){
					 currentRuleKey = key;
					 remainRuleIds.push(key);
				}
			}
			
		}
		
		return remainRuleIds;
	},
	
	// 设置当前项
	setCurrentItem : function(ruleId){
		var _self = this;var config = this.config;
		var rule = config.rules[ruleId];
		
		for(key in rule){
			var dom = key;
			
			if(rule[key].css){
				YUD.addClass(key,rule[key].css);
			}

			if(rule[key].text != undefined){
				get(key).innerHTML = rule[key].text;
			}

			if(rule[key].call){
				rule[key].call(get(key));
			}

		}
	},
	
	// 初始化
	init : function(customConfig){
			// 合并配置
			this.config = YL.merge(this.config,customConfig||{});
			// 定义_self
			var _self = this;var config = this.config;
			
			if(!config.currentURL){
				config.currentURL = location.href;
			}
			
			// 获取当前最终匹配路径规则
			var remainRuleIds = _self.temp.remainRuleIds = _self.getremainRuleIds(config.rules);
			
			for(var i=0;i<remainRuleIds.length;i++){
				var remainRuleId = remainRuleIds[i];
				_self.setCurrentItem(remainRuleId);
			};

			// 回收内存
			if(AE.bom.isIE){ CollectGarbage(); }
			
			// 返回对象
			return _self;
			
	}	
	
}
