(function() {
	Application = {};
	var startTime;
	var $navMenus;

	/* 初始化导航菜单 */
	Application.initNavMenu = function(nav, sideNav) {
		$navMenus = $(nav).find('a');
		var $childNavMenus = $(sideNav).find('ul.sideNavigation'); 
		/* 给横向菜单注册onclick方法 */
		$navMenus.each(function(i) {
			this._index=i;
			var myChildMenu = Zving.getDom('_Child' + this.id);
			if(myChildMenu){
				myChildMenu._index=this._index;
				this._childMenu = myChildMenu; // 给菜单添加childMenu属性
			}
			this.onHash = function() {
				var self = this;
				$childNavMenus.hide();
				var url = self.getAttribute('url');
				var myChildMenu = Zving.getDom('_Child' + self.id);
				$navMenus.removeClass('current');
				$(self).addClass('current');
				
				var iframes=$('#_framesWrap iframe:not(#_mainFrame_'+self._index+')');
				iframes.each(function(i){
					try {
						this.style.width = Zving.getDom('_framesWrap').clientWidth + 'px';
						this.style.height = Zving.getDom('_framesWrap').clientHeight + 'px';
					} catch (e) {
						//在ie下iframe不可见时，设置宽高会出错？？？（待证实）
					}
					this.style.position = 'absolute';
				});
				var $targetIframe=$('#_mainFrame_'+self._index);
				if(!$targetIframe.length){
					$targetIframe=$('<iframe id="_mainFrame_'+self._index+'" name="_mainFrame_'+self._index+'" frameborder="0" width="100%" height="100%" src="about:blank" scrolling="auto" style="position:absolute;left:-33in;top:-22in;" allowtransparency="true"></iframe>');
					$targetIframe.appendTo('#_framesWrap')
				}
				$targetIframe.css({
					width:'100%',
					height:'100%',
					position:'static'
				});
				
				if (!url) {
					$('#leftColumnWrap').show();
					self._childMenu = myChildMenu; // 给菜单添加childMenu属性
					myChildMenu.onHash();
				} else {
					$('#leftColumnWrap').hide();
					$G('splitter1')&& $('#splitter1').hide();
					$('#toggleLeftColumn').removeClass('toggleBtn-left');
					$('#toggleLeftColumn').addClass('toggleBtn-right');
				}
			};
			this.onclick = function(evt) {
				evt = evt||window.event;
				var self = this;
				var url = self.getAttribute('url');
				var menuid=self.getAttribute('menuid');
				var myChildMenu = Zving.getDom('_Child' + self.id);
				if (!url && myChildMenu) {
					self._childMenu = myChildMenu; // 给菜单添加childMenu属性
					myChildMenu.onShow();
				} else {
					if (!/^#/.test(url)) {
						window.location.hash = menuid;
					}
					Zving.preventEvent();
				}
				if(!Zving.isIE){//如果不是IE，来个涟漪效果
					Zving.Node.showRipples(evt, self);
				}
				//if(this.)$('#leftColumnWrap').show();
				//$G('splitter1')&& $('#splitter1').show();
				$('#toggleLeftColumn').removeClass('toggleBtn-right');
				$('#toggleLeftColumn').addClass('toggleBtn-left');
			};
		}); /* 给左侧菜单注册onclick方法 */
		$childNavMenus.each(function(i) {
			var childNavMenu=this;
			var $links = $(childNavMenu).find('a');
			childNavMenu.onHash = function() {
				$(childNavMenu).show();
			};
			childNavMenu.onShow = function() {
				$(childNavMenu).show();
				if (childNavMenu._activeMenu) {
					childNavMenu._activeMenu.onclick();
				} else {
					if ($links[0]) {
						$links[0].onclick();
					} else {
						window.location.hash = $navMenus[childNavMenu._index].getAttribute('menuid');
					}
				}
			}
			$links.each(function(j) {
				this.setAttribute('target','_mainFrame_'+childNavMenu._index)
				this._index=j;
				this.setActiveMenu = function() {
					$links.each(function() {
						$(this).removeClass('current');
					})
					$(this).addClass('current');
					childNavMenu._activeMenu = this;
				};
				this.onclick = function(evt) {
					evt = evt||window.event;
					var self = this;
					if(!Zving.isIE){//如果不是IE，来个涟漪效果
						Zving.Node.showRipples(evt, self);
					}
					window.location.hash = childNavMenu.id.substr("_Child_Menu_".length) + '/' + (this.getAttribute('menuid'));
					Zving.preventEvent(evt);

				}
			})
		})
	};

	//在hash值改变时
	Application._handleHashChange= function(h){
		if(!/^\w+/.test(h)){
			return;
		}
		var index = h.split('/');
		var navMenuId=index[0];
		var subNavMenuId = index[1];
		var query
		if(index.length==3){
			 query=index[2]
		}else if(index.length==2){
			if(index[1].indexOf('=')>-1){
				query=index[1];
				subNavMenuId=null;
			}
		}
		query=query?'?'+query:'';
		var navMenu = Zving.getDom('_Menu_' + navMenuId);
		if (!navMenu) {
			navMenu=$navMenus[0];
		}
		if(!navMenu) {
			return;
		}
		navMenu.onHash();
		var url = navMenu.getAttribute('url');
		var targetIframe=Zving.getDom('_mainFrame_'+navMenu._index);
		if(url){
			$('#leftColumnWrap').hide();
			$G('splitter1')&& $('#splitter1').hide();
			$('#toggleLeftColumn').removeClass('toggleBtn-left');
			$('#toggleLeftColumn').addClass('toggleBtn-right');
			
			if (!/^#/.test(url)) {
				if(!targetIframe.src.endsWith(url+query)){
					targetIframe.src = url+query;
					var menuid = navMenu.getAttribute('menuid');
					var dc = {"MenuID": menuid};
					Server.sendRequest("Application.changeMenuClickCount",dc,null);
				}
			}
		}

		if(subNavMenuId){
			var childNavMenu = Zving.getDom('_Child_Menu_' + navMenuId);
			if (!childNavMenu) {
				return;
			}
			$(childNavMenu).show();
			var $links = $(childNavMenu).find('a');
			var link;
			$links.each(function(){
				if(this.getAttribute('menuid') && this.getAttribute('menuid')==subNavMenuId){
					link=this;
					return false;
				}
			})
			if (link) {
				link.setActiveMenu();
				var url = link.getAttribute("href"),
				target = link.getAttribute("target");
				var targetIframe=Zving.getDom(target);
				if (!/^#/.test(url)) {
					if(!targetIframe.src.endsWith(url+query)){
						targetIframe.src = url+query;
						var dc = {"MenuID":subNavMenuId};
						Server.sendRequest("Application.changeMenuClickCount",dc,null);
					}
				}
				
				
			}
		}	
	};
	Application.setCurrentMenu = function(pathname) {
		if (Zving.getDom("_Navigation")) {
			$navMenus.each(function(i){
				var navMenuItem = this;
				var url = navMenuItem.getAttribute('href');
				if (url) {
					if (url.indexOf(pathname) > -1) {
						if (!$(navMenuItem).hasClass('current')) {
							navMenuItem.setActiveMenu();
							return false;
						}
					}
				}
				if (navMenuItem._childMenu) { // 查找与当前页面地址匹配的菜单，然后高亮
					var $links = $(navMenuItem._childMenu).find('a');
					$links.each(function(i){
						if (this.getAttribute('href').indexOf(pathname) > -1) {
							if (!$(this).hasClass('current')) {
								this.setActiveMenu();
								return false;
							}
						}
					});
				}
			});
		}
	};
	Application.setPrivParam = function(key,value){
		var win = Zving.rootWin;
		if (!win.Priv) {
			try{//测试发现在firefox下从其他域的页面跳转到ZCMS也存在opener
				if (window.opener && window.opener.Zving) {
					win = window.opener.Zving.rootWin;
				}
			}catch(e){
				win=Zving.rootWin;
			}
		}
		if (win.Priv) {
			if(!win.PrivParams){
				win.PrivParams = {};
			}
			var params = win.PrivParams;
			params[key] = value;
		}
	};
	Application.setAllPriv = function(elem) {
		var $buttons = $("a.z-btn",elem||document);
		$buttons.each(function() {
			if($(this).is('.z-toolbar-more')){$(this).enable();return;}
			var p = this.getAttribute("priv");
			if (p) {
				if (!Application.hasPriv(p)) {
					$(this).disable();
				}else{
					$(this).enable();
				}
			}
		});
	};
	Application.hasPriv = function(privID) {
		var win = Priv.getWin();
		if (win.Priv) {
			var arr = privID.split("||");
			var flag = false;
			if(win.Priv.AdminUserName==win.Priv.UserName){
				flag = true;	
			}else{
				for (var i = 0; i < arr.length; i++) {
					if(!arr[i]){
						continue;
					}
					var item = arr[i];
					if(win.PrivParams){
						for(var k in win.PrivParams){
							item = item.replace("${"+k+"}",win.PrivParams[k]);//替换变量
						}
					}
					if (win.PrivInstance.hasPriv(item)) {
						flag = true;
					}
				}
			}
			return flag;
		}
		return false;
	};
	
	
	Priv = {};
	Priv.getWin = function(){
		var win = Zving.rootWin;
		if (!win.Priv||!win.Priv.Init) {
			try{//测试发现在firefox下从其他域的页面跳转到ZCMS也存在opener
				if (win.opener && win.opener.Zving && win.opener.Zving.rootWin && win.opener.Zving.rootWin.Privilege) {
					win = win.opener.Zving.rootWin;
				}
			}catch(e){
				win=Zving.rootWin;
			}
		}
		return win;
	}
	
	Priv.init = function(obj) {
		if (!obj) {
			return;
		}
		var win = Priv.getWin();
		if (win != window) {
			win.obj = win.JSON.parse(JSON.stringify(obj));
		} else {
			win.obj = obj;
		}
		if (!win.PrivInstance) {
			win.PrivInstance = new Privilege(win.obj);
			win.Priv.Init = true;
		} else {
			win.PrivInstance.update(win.obj);
		}
	};


	Priv.charToFlag = function(flag) {
		var i = 0;
		if(flag==36||flag==37){
			i = flag;	
		}else	if (flag < 58) {
			i = flag - 48;
		} else if (flag < 91) {
			i = flag - 27;
		} else if (flag < 123) {
			i = flag - 87;
		}
		return i;
	}
	
	Privilege = function(obj){
		if(typeof(obj)==='string'){
			obj=JSON.parse(obj);
		}
		this.Data = obj;
	}
		
	Privilege.prototype.hasPriv = function(k){
		if(!k){
			return false;
		}
		var index = k.lastIndexOf('.');
		if (index > 0) {
			var id = k.substring(index + 1);
			if (id.isInt()) {
				k = k.substring(0, index);
				var flags = this.Data.ids[id];
				if (flags == null) {
					return false;
				}
				var order = this.Data.types[k];
				if ((order!==0 && !order) || order >= flags.length * 6) {
					return false;
				}
				var flag = flags.charCodeAt(order / 6);
				return (Priv.charToFlag(flag) & 1 << (5 - order % 6)) != 0;
			} else {
				return this.Data.keys[k];
			}
		} else {
			return this.Data.keys[k];
		}
	}
	Privilege.prototype.update=function(obj){
		if(!obj){
			return;
		}
		if(typeof(obj)==='string'){
			obj=JSON.parse(obj);
		}
		this.Data = obj;
	}
	
	Page.onReady(function() {
		var i;
		var nav = Zving.getDom('_Navigation'),
		sideNav = Zving.getDom('_sideNavigation');
		if (nav && sideNav) {
			$navMenus = $(nav).find('a');
			Application.initNavMenu(nav, sideNav); // 导航菜单初始化
			var h = window.location.hash || Cookie.get('lastNavStatus');
			h = h && h.replace(/^#*/,'');
			if (!h) {
				if($navMenus && $navMenus.length > 0) {
					h=$navMenus[0].getAttribute('menuid');
					if($navMenus[0]._childMenu){
						var firstSubMenu=$navMenus[0]._childMenu.getElementsByTagName('A')[0];
						if(firstSubMenu){
							h+='/'+firstSubMenu.getAttribute('menuid');
						}
					}
				}
			}
			Application._handleHashChange(h);
		}
		
		if (!Zving.restricted && window.frameElement && window.frameElement.id == "_MainArea") {
			parent.Application.setCurrentMenu(window.location.pathname);
		}
		
		Application.setAllPriv();
		$('div.ui-page-container').on('pagechange',function(e){
			Application.setAllPriv(this);
		})
	});

	if(window.location.pathname.indexOf('/application.')>=0){
		$window.on( "hashchange", function( e, triggered ) {
			Application._handleHashChange( location.hash.replace(/^#*/,'') );
		});
		$window.on('unload', function() {
			if (window.location.hash) {
				var initdata = location.hash.match(/([\w\.]+)(\/([\w\.]+))?/);
				if (initdata && initdata.length) {
					var navMenuId = initdata[1],
					subNavMenuId = initdata[3];
					Cookie.set('lastNavStatus', navMenuId + '/' + subNavMenuId);
				}
			}
		})
	}

})();