/**
 * application component, all event will be dispatched in this class 
 * */
(function(){
	var app = jQuery.extend( new Component("app"), {
		mainComponentDivId : "mainContent", //div id of main content
		mainComponent : null, //current component that show in main content	
		selectDateValue : "", //this selectDateValue is for the position detail and movement page
		selectBpKey : "",     //this selectBpKey is for the mainPage's nvg's selectByKey div
		components : {},      //a cache object to hold loaded component
		user : null,
		doAjaxRequest : false,
		autoCompleteBpkeys : [],
		componentRoles:{
			//client
			"hasAnyRole('WMD_Clients')" : ["initialMainContent","estatementDownload","rhs", "quickAccessLink"],
			//RM
			"hasAnyRole('WMD_RMs','WMD_CSOs','WMD_BADTs','WMD_Super','WMD_RTBs')" : [	"nonClientInitialMainContent",
			                                                 	"estatementDownload",
			                                                 	"rmBpKeySelectMenu",
			                                                 	"rhs",
			                                                 	"quickAccessLink"
			                                                 ],
			//admin
			"hasRole('WMD_Admin1') or hasRole('WMD_Admin2')" : ["quickAccessLink","rhs"]
		},
		/**
		 * a object saving latest ticket no (version no) of render request for every div, 
		 * component.render can check it to discard the response which isn't from latest render request
		 * */
		counts : {
			getCount: function(divId){
				return this[divId] || 0;
			}, 
			increaseCount: function(divId){
				var count = this.getCount(divId);
				this[divId] = count + 1;
				return this[divId];
				
			}
		},
		EPWEB_CONTEXT_ROOT : "/WMD/ePlatform/",
		EPRESTAPI_CONTEXT_ROOT : "/WMD/ePlatform/restapi/",
		MANAGER_USERID_URL : "&&&MANAGER_USERID_URL&&&",
		ANNOUNCEMENT_PAGESIZE : 10,
		ANNOUNCEMENT_TOPNUM : 4,
		CLIENT_SETUP_PAGESIZE : 500,
		QUICK_ACCESS_LINK_PAGESIZE : 4,
		TIMEOUT_INTERVAL : 420,
		LANGUAGE_COOKIE_NAME : "lang_language",
		EXT_LANGUAGE_COOKIE_NAME : "NMRPREFLANG",
		COOKIES_DOMAIN : ".nomuranow.com",
		
		getComponent : function(componentId){
			return this.components[componentId];	
		},
		registerComponent : function(component){
			this.components[component.id] = component;
		},
		/**
		 * load javascript file and return a deferred object 
		 * */
		loadScriptsById : function(){
			 var id = arguments[0],
			     urls = ["scripts/" + id + ".js"];
			 
			 if (!this.components[id]){
				 return loadScript (urls).done( function(){
					 //if user logout on another page, any requests will return the context of /IDM/LoginHome
					 //so component will cannot be loaded, program cannot know if it is raised by js error or user logout out 
					 if (!app.components[id]) {
						 app.user.logout();
					 }
				 });
			 } else {
				 var dtd = $.Deferred();
				 dtd.resolve();
				 return dtd;
			 }
		},
		/**
		 * load the javascript file of the component and trigger the "load" event
		 * */
		renderComponent : function(){
			 var self = this,
			     id = arguments[0],
			     dtd = $.Deferred();
			 
			 Array.prototype.splice.call(arguments, 0, 1, "load");
			 var args = arguments;
			     
			 this.loadScriptsById (id).done(function(){
				 var component = self.getComponent(id);
				 component.trigger.apply(component,args).done(function() {
					 dtd.resolve.apply(null, arguments); 
				 })
				 .fail(function() {
					 dtd.reject.apply(null, arguments);
				 });
			 });
			 
			 return dtd;
		},
	    getLangCookieName: function(){
	    	var cookieName = "";
	    	if(!(this.user.role&&this.user.role.checkRole)||this.user.role.checkRole("hasRole('WMD_Intranet')")){
	    		cookieName = this.LANGUAGE_COOKIE_NAME;
	    	} else {
	    		cookieName = this.EXT_LANGUAGE_COOKIE_NAME + this.user.env;
	    	}
	    	console.log("lang C Name=" + cookieName);
	    	return cookieName;
	    },
		user: {
			//outstanding function
			logout : function(){
				var timeoutArg = arguments[0] || false;
				if(!app.user.role.checkRole("hasRole('WMD_Intranet')")){
					addLogoutRecord(true);
					window.open("/IDM/UI/Logout", "_self");
				}else{
					ajaxCall({url:app.EPRESTAPI_CONTEXT_ROOT + "access/logout", dataType: "json"}).always( function(){
						
						if(app.user.role.checkRole("hasRole('WMD_Intranet')")){
							addLogoutRecord(false);
							window.location = app.EPRESTAPI_CONTEXT_ROOT + "login.jsp?timeout=" + timeoutArg;	
						}
					});		
				}
			},
			intranetTimeout : function(){
				ajaxCall({url:app.EPRESTAPI_CONTEXT_ROOT + "access/logout", dataType: "json"}).done( function(){
					addLogoutRecord(false);
					window.location = app.EPRESTAPI_CONTEXT_ROOT + "login.jsp";
				});		
			}
		},
		initUser : function(){
	        $("#mainLoadingDiv").show();
	        var self = this;
	        var role = window.location.search;
	        
	        var dtd = $.Deferred();
	        var ajax = ajaxCall({
	        	url: this.EPRESTAPI_CONTEXT_ROOT + "user/profile/" + role, 
	        	type: "get",
	        	dataType: "json"
	        }).done( function(data){
	            self.autoCompleteBpkeys = data.data.bpKey ;
	        	$.extend( self.user, data.data);

	            $.extend( self.user.role, roleHelper);
	            
	            if(self.user.role.checkRole("hasAnyRole('WMD_Clients')")){
	            	self.user.bpKey = self.user.bpKey[0];
	            }
	            self.user.lang = getCookie(self.getLangCookieName()) || self.user.lang;
		    	console.log("lang=" + self.user.lang);
		    	if (!lang.langVars[self.user.lang]){
		    		self.user.lang = lang.EN;
		    	}
		    	
	            if (self.user.acceptTC !== undefined && !self.user.acceptTC){
	            	window.open("termCondition.html?ask=1", "_self");
	            	dtd.reject();
	            } else {
	            	dtd.resolve.apply(null, arguments);
	            }
	            
	        }).fail( function() {
	        	dtd.reject.apply(null, arguments);	        
	        });
	        return dtd;
		},
		init : function(){
	        var self = this;
		    this.initUser()
		    .done(function(data){
		    	app.uiLoadingStatus.setIsLoading(true);
		    	//self.user.portfolioNumber= data.data.portfolioList;
	            //call setLang method for in181
	    		lang.currentLang = self.user.lang;		    		
	            //set the first Date in selectDateValue param
		    	if( data.data.asOfDate){
		    		self.selectDateValue = data.data.asOfDate[data.data.asOfDate.length-1];
		    	}else{
		    		self.selectDateValue="01/01/01";
		    	}
	            //set the first bpKey in selectBpKey param
		    	if( data.data.bpKey){		    	    
		    	    if (self.user.role.checkRole("hasAnyRole('WMD_Clients')")){
		    	        self.selectBpKey = data.data.bpKey[0];
		    	    }
		    	    else{
		    	        self.selectBpKey = "";
		    	    }
		    	}else{
		    		self.selectBpKey="";
		    	}
	            
	            var portfolioRoleAjax = function(){
	            	if (self.user.role.checkRole("hasAnyRole('WMD_Clients','WMD_RMs','WMD_CSOs','WMD_BADTs','WMD_Super')")){
	    	            if (self.selectBpKey != ""){
    	            	    var url = "businessPartners/menu/" +  self.selectBpKey + "?asOfDate=" + self.selectDateValue;
    	            		return ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url, dataType: "json"}, false);
	    	            }
	    	            else{
	    	                return [[]];
	    	            }
	            	}
	            	else{
	            		return [[]];
	            	}
	            };
	            var url = "businessPartners/menu/" +  self.selectBpKey + "?asOfDate=" + self.selectDateValue;
	            
	            $.when(
	            	lang.getLangMessages(lang.currentLang),
		            self.renderComponent("header").done( function () {lang.updateLangMenu(app.user.lang);}),
		            self.renderComponent("footer"),
		            portfolioRoleAjax()
	            ).done(function(){
	            	self.portfolioRole = arguments[arguments.length-1][0];	      
	            }).pipe(function(){
	            	return $.when(app.initRoleControl(), app.renderComponent("navigator"));
	            }).done( function(){
	        	    
	        	    //app.trigger('menuClick', firstMenu.find("a").attr("cid"), firstMenu, "load");	
	        	    
	            	
	        	    
	            	//lang.updateUIMessages();
	            	//app.reLoadComponents();
	            	//app.trigger("bpKeyChange");
	            	$("[actionName]").die().live("click", function(){
	            		trackAction($(this).attr("actionName"));
	            	});
	            	$('#mainContentLoadingOnHomePage').hide();
		            $('.mainContentOnHomePage').show();
		            if($("#adminHome").is(":visible")&& $("#helpManualAsHome").is(":visible")){
	        			 $("#helpManualAsHome").hide().trigger("reject");
	        		}
	        		if($("#helpManualAsHome").is(":visible") && $("#helpManual").is(":visible") ){
	        			//$("#helpManual").hide().trigger("reject");
	        			if (self.user.role.checkRole("hasAnyRole('WMD_Reports')")){
	        				$("#helpManualAsHome").hide().trigger("reject");
	        			} else {
	        				$("#helpManual").hide().trigger("reject");
	        			}
	        		}
        			
	        		var newRole = self.user.role;
	        		var newRole2 = new Array();
	        		for(var i = 0; i < newRole.length; i++) {
	        			if(newRole[i] == "WMD_Intranet" || newRole[i] == "WMD_Extranet") {
	        				
	        			}else {
	        				newRole2.push(newRole[i]);
	        			}
	        		}
        			if (self.user.role.checkRole("hasAnyRole('WMD_Reports')") && newRole2.length == 1){
        				$("#ePlatformOptions").hide().trigger("reject");
        				app.trigger("load", "helpManual");
        				myNavigator.select($("#helpManual"));
        				
        			} else {
		        		if($(".menu dt:has(a[cid]):visible").first() && $(".menu dt:has(a[cid]):visible >a ").first().attr("cid")=='helpManual'){
		        			//WMD_Reports, WMD_Client_Setup 
		        			
		        			app.trigger("load", "helpManual");
		        			myNavigator.select($(".menu dt:has(a[cid]):visible").first());
		        		}else if($(".menu dt:has(a[cid]):visible").first() && $(".menu dt:has(a[cid]):visible >a ").first().attr("cid")=='nonClientInitialMainContent'){
		            		//WMD_Admin1, WMD_Admin2
		        			app.trigger("load", "nonClientInitialMainContent");
		            		myNavigator.select($(".menu dt:has(a[cid]):visible").first());
		        		}else{
		        			myNavigator.select($(".menu dt:has(a[cid]):visible").first());
		        		}
        			}
	        		lang.updateUIMessageWithOutGetData();
	            }).always(function(){
	            	
	            	app.uiLoadingStatus.setIsLoading(false);
	            });
	        });
		},
		reLoadComponents : function(){
			if (!(app.user.role && app.user.role.checkRole)) {
				return;
			}
			
			if (app.user.role.checkRole("hasAnyRole('WMD_Clients','WMD_RMs','WMD_CSOs','WMD_BADTs','WMD_Super','WMD_Admin1','WMD_Admin2')")){
				app.trigger("load", "quickAccessLink");
			}

		    if( this.mainComponent && this.mainComponent.id == "faq") {
		    	app.trigger("load", this.mainComponent.id);
		    } else if ( this.mainComponent &&( this.mainComponent.id == "initialMainContent" ||
		    		this.mainComponent.id == "nonClientInitialMainContent") ){
		    	app.trigger("load", "announcement");
		    } else if ($("#announcementListNow").val() == 1){
		        app.trigger("call", "announcement", "loadList");
		    } else if ($("#announcementDetailPageFlag").val() == 1){
                app.trigger("load", "announcement");
            }
		    
		},
		/**
		 * hide or show menu item by current user role, also load component by current user role.
		 * In page, I have defined a customized attribute of html object which are named "role".
		 */
		initRoleControl : function(){
			var self = this;
			return self.user.role.checkComponents(self.componentRoles).done(function(){				
				self.user.role.checkHtmlElements();
			});
		},
		autoTimeout: function(){
			//var timeout = 50;
			var count = 0,
				interval = 0;
				
			interval = startTimer();
			$("body").die().live("click mouseover", function(){
				interval = startTimer();
			});
			
			function startTimer(){
				clearTimeout(interval);
				interval = setTimeout(function(){
					clearTimeout(interval);
					
					dialog
					.set({autoHideTime: 3 * 60 * 1000, autoHideAction: "No",height: "190px",width: "430px"})
					.show( $("#autoLogoutTemplate").html(), "Ok").done( function (btnName) {
						if (btnName == "No"){
							app.user.logout(true);
						}
						startTimer();
					});
//					showModalDialog(app.EPWEB_CONTEXT_ROOT + 'template/timeout.html',[window],'dialogwidth:400px; dialogheight:230px; location:no; status:no; help:no; resizable:no; toolbar:no');
					
				}, app.TIMEOUT_INTERVAL * 1000);//
				return interval;
			}
//			app.resetTimeout = function(){
//				interval = startTimer();
//			};
		}
	});
	
	app.uiLoadingStatus = (function() {
		var isLoading = false;
		return {
			getIsLoading: function() { return isLoading;},
			setIsLoading: function(val){
				if (val){
					window.rmBpKeySelectMenu && rmBpKeySelectMenu.bpKeyInput.prop("disabled",true);//attr("readonly", "true");
				}
				else{
					window.rmBpKeySelectMenu && rmBpKeySelectMenu.bpKeyInput.prop("disabled",false);//.removeAttr("readonly");
				}
				isLoading = val;
			}
		}
	})();
	
	var roleHelper = {
			checkRole : function(roleValue){
				
    			var check=function(exp){
    				var result = exp.indexOf("hasAnyRole") != -1? false : true;  
    				var roles = exp.split(",");
    				//console.log(roles + " --- roles");
//    				console.log(roles.length + " --- roles");
    				
    				for(var i =0; i<roles.length ; i++) {
//    					roles[i] = roles[i].replace( '(hasAnyRole|hasRole)\(', '' );
    					roles[i] = result ? roles[i].replace('hasRole(', '') : roles[i].replace( 'hasAnyRole(', '' );
    					roles[i] = "" + roles[i].replace(')', '');
    					var roleWithQuote = roles[i].substring(1, roles[i].length-1);
    					//console.log(roleWithQuote+"   ---");
    					if("hasAnyRole" == exp.substring(0,10) && app.user.role.indexOf(roleWithQuote) != -1) {
    						result = true;
							break;
    					} else if ("hasRole" == exp.substring(0,7) && app.user.role.indexOf(roleWithQuote) == -1) {
    						result = false;
							break;
    					}
    				}
    				return result;
    				
    			};
    			var finalResult = false;
    			//console.log(roleValue+" ---value");
    			if(roleValue.indexOf(" or ") != -1){
    				var parts = roleValue.split(" or ");
    				for(var i = 0; i < parts.length ; i++){
    					//var roles = parts[i].split(",");
    					if(check(parts[i]) === true){
    						finalResult = true;
    						break;
    					}					
    				}
    			}else{
    				finalResult = check(roleValue);
    			}
    			return finalResult;
        	},
        	checkComponents : function(mapping){
        		var dtdRequestList = [];
        		for (var roleKey in mapping){
    				if(app.user.role.checkRole(roleKey)){
    					var componentIds = mapping[roleKey];
    					for(var i = 0; i < componentIds.length; i++){
    						dtdRequestList.push(app.trigger("load", componentIds[i]));
    					}
    				}
    			}
        		return $.when.apply(null, dtdRequestList);
        		
        	},
        	checkHtmlElements : function(){
        		$("[WMD_Role]").each(function(i, d){
    				var roleValue = $(d).attr("WMD_Role");
    				
    				if(app.user.role.checkRole(roleValue) === true){
    					$(d).show().trigger("resolve");
    				} else {
    					$(d).hide().trigger("reject");
    				}
    				   				
    			});
        		app.user.role.checkPortfolioRole();
        		
        		if($("#adminHome").is(":visible")&& $("#helpManualAsHome").is(":visible")){
        			 $("#helpManualAsHome").hide().trigger("reject");
        		}
        		if($("#helpManualAsHome").is(":visible") && $("#helpManual").is(":visible") ){
        			//$("#helpManual").hide().trigger("reject");
        			if (self.user.role.checkRole("hasAnyRole('WMD_Reports')")){
        				$("#helpManualAsHome").hide().trigger("reject");
        			} else {
        				$("#helpManual").hide().trigger("reject");
        			}
        		}
        		
        		 
        		
        	},
        	checkPortfolioRole : function(){
        		$("#psubmenu dt").each(function(){
        			$(this).hide(); 
        		});   
    		    
		        $("#psubmenu dt").each(function(i,d){
		        	if (app.portfolioRole && app.portfolioRole.data && app.portfolioRole.data.result){
			            //var text = $(d).find("div[class=linktext]").text(),
			            var text = $(d).attr("pid"),
			                role = $(d).attr("WMD_Role");
	
			            if($.isArray(app.portfolioRole.data.result) && app.portfolioRole.data.result.indexOf(text)!= -1 && app.user.role.checkRole(role)){
			               $(d).show();  
			            } 
			            //to display Portfolio List
			            if($(d).attr('class')=='subactived'&& app.user.role.checkRole(role)){
			            	$(d).show();
			            }
		        	}
		        });
		        
		        
        	},
        	isAdmin1 : function(){
        		return this.checkRole.call(this, "hasAnyRole('WMD_Admin1','WMD_Super')");
        	},
        	isAdmin2 : function(){
        		return this.checkRole.call(this, "hasAnyRole('WMD_Admin2','WMD_Super')");
        	},
        	checkAdminRole : function(){
        		if(this.checkRole("hasRole('WMD_Admin2','WMD_Admin1')") || this.checkRole("hasRole('WMD_Super')")){
        			return "both";
        		} else if (this.isAdmin1()) {
        			return "admin1";
        		} else  if(this.isAdmin2()) {
        			return "admin2";
        		} else {
        			return "NOTADMIN";
        		}
        	}
	};
	
	window.app  = app;
})();


/**
 * load a component 
 * */
app.on("load", function(){
	return this.renderComponent.apply(this, arguments);
});

app.on("menuClick", function( id, menu, eventId ){
	if (!id) return;
	if (!app.uiLoadingStatus.getIsLoading()){//!myNavigator.isClicking && !app.changeChecked) {
		app.uiLoadingStatus.setIsLoading(true);
		//myNavigator.isClicking = true;
		
		//$(this).removeClass("standard");
		myNavigator.select(menu);
		//$(menu).find("a").toggleClass("selected");
		//myNavigator.selected = $(menu);
		//console.log("cid=" + $(menu).find("a").attr("cid"));

		return app.trigger('call', id, eventId)
			.done(function() {
				app.uiLoadingStatus.setIsLoading(false);
				//myNavigator.isClicking = false;
			});
	
	} else {
		var dtd = $.Deferred();
		dtd.reject();
		return dtd;
	}
});

/**
 * trigger a event of the component  
 * */
app.on("call", function(){
	var self = this,
	    targetComponentId = arguments[0];
	
	Array.prototype.splice.call(arguments, 0, 1);
	var args = arguments;
	return self.loadScriptsById(targetComponentId).pipe(function(){
		var targetComponent = self.getComponent(targetComponentId);
		return targetComponent.trigger.apply(targetComponent, args);		
	});
	 
});

app.on("getMenuAndCheckRole", function(){
    $("#masterMenu2").hide();
    $("#masterMenuLoading_sidebarheader").show();
    $("#masterMenuLoading").css("height","50px");
    myNavigator.showLoading("masterMenuLoading");
    var url = "businessPartners/menu/" +  app.selectBpKey + "?asOfDate=" + app.selectDateValue;
    return ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url, dataType: "json"}, false).done(function(){
    	myNavigator.select($("#psubmenu dt:has(a[cid='initialMainContent'])").first());
    	app.portfolioRole = arguments[0];   
        app.user.role.checkPortfolioRole();
        $("#loadingDiv").empty().remove();
        $("#masterMenuLoading_sidebarheader").hide();
        $("#masterMenuLoading").css("height","0px");
        $("#masterMenu2").show();
        if($("#adminHome").is(":visible")&& $("#helpManualAsHome").is(":visible")){
        	$("#helpManualAsHome").hide().trigger("reject");
   		}
   		if($("#helpManualAsHome").is(":visible") && $("#helpManual").is(":visible") ){
   			//$("#helpManual").hide().trigger("reject");
   			if (self.user.role.checkRole("hasAnyRole('WMD_Reports')")){
				$("#helpManualAsHome").hide().trigger("reject");
			} else {
				$("#helpManual").hide().trigger("reject");
			}
   		}
    });
});
app.on("bpKeyChange", function(){
	var	sourceComponentId = arguments[0],
	    bpKey = app.selectBpKey,
	    isRedirect = arguments[2] || false;
	 $("#wmdBpkNum").prop("disabled",true);
	if (!app.uiLoadingStatus.getIsLoading()){
        bpKey = arguments[1];
        app.uiLoadingStatus.setIsLoading(true);
        app.selectBpKey = bpKey;
        var dtdList = [];
        if(sourceComponentId){
            dtdList.push(app.trigger("load", sourceComponentId));
        }
        dtdList.push(app.trigger("call", "estatementDownload", "reloadDownloadList"));
        if(!isRedirect){
            dtdList.push(app.trigger("load", "initialMainContent"));                
        }       
        dtdList.push(app.trigger("getMenuAndCheckRole"));
        return $.when.apply(null, dtdList).done(function(){
    	   // myNavigator.select($("#psubmenu dt:has(a[cid='initialMainContent'])").first());
            app.uiLoadingStatus.setIsLoading(false);
            $("#wmdBpkNum").prop("disabled",false);
        });
    } else {
        rmBpKeySelectMenu.bpKeyInput.val(app.selectBpKey);
        var dtd = $.Deferred();
        dtd.reject();
        return dtd;
    }
	/*if (!app.uiLoadingStatus.getIsLoading()){
	    bpKey = arguments[1];
	    app.uiLoadingStatus.setIsLoading(true);
		app.selectBpKey = bpKey;
		var url = "businessPartners/menu/" +  app.selectBpKey + "?asOfDate=" + app.selectDateValue;
		return ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url, dataType: "json"}, false).pipe(function(){
			var dtdList = [];
			app.portfolioRole = arguments[0];	
			dtdList.push(app.trigger("load", sourceComponentId));
			dtdList.push(app.user.role.checkPortfolioRole());
			dtdList.push(app.trigger("call", "estatementDownload", "reloadDownloadList"));
			if(!isRedirect){
				dtdList.push(app.trigger("load", "initialMainContent"));				
			}		
			return $.when.apply(null, dtdList);
		}).done(function(){
			app.uiLoadingStatus.setIsLoading(false);
		});
	} else {
		rmBpKeySelectMenu.bpKeyInput.val(app.selectBpKey);
		var dtd = $.Deferred();
		dtd.reject();
		return dtd;
	}*/
});

app.on("changeAsOfDate", function(){
    $("#masterMenu2").hide();
    $("#masterMenuLoading_sidebarheader").show();
    $("#masterMenuLoading").css("height","50px");
    myNavigator.showLoading("masterMenuLoading");
	var sourceComponentId = arguments[0];
	var dtdList = [];
	if (!app.uiLoadingStatus.getIsLoading()) {
		app.uiLoadingStatus.setIsLoading(true);
		app.selectDateValue = arguments[1] || app.selectDateValue;
		if(app.selectBpKey){
		      var url = "businessPartners/menu/" +  app.selectBpKey + "?asOfDate=" + app.selectDateValue; 
		      dtdList.push(ajaxCall({ url: app.EPRESTAPI_CONTEXT_ROOT + url, dataType: "json"}, false));
		}
		if (sourceComponentId) {
			dtdList.push(app.trigger("load", sourceComponentId));				
		}
		return $.when.apply(null, dtdList).done(function(){
			if( dtdList.length == 1 ){
				app.portfolioRole = arguments[0];				
			} else if(dtdList.length > 1){
				app.portfolioRole = arguments[0][0];				
			}
		}).done(function(){
			app.uiLoadingStatus.setIsLoading(false);
			dtdList.push(app.user.role.checkPortfolioRole());
			$("#loadingDiv").empty().remove();
			$("#masterMenuLoading_sidebarheader").hide();
	        $("#masterMenuLoading").css("height","0px");
	        $("#masterMenu2").show();
	        
		});
	} else {
		$(".AsOfDate").val(app.selectDateValue);
		var dtd = $.Deferred();
		dtd.reject();
		return dtd;
	}
});

app.on("ajaxError", function() {
	var errorType = arguments[1],
		xhr = arguments[0];
	
	if (xhr.status === "500") {
		xhr.errorId;
		//server side error, go to the error page
		//window.location = app.EPRESTAPI_CONTEXT_ROOT + "error/500";
		window.location = "error.html?errorId=" + xhr.errorId;
	} else if (xhr.status === "401" || xhr.status === "400") {
		if ((!(app.user.role && app.user.role.checkRole)) || app.user.role.checkRole("hasRole('WMD_Intranet')")){
			window.location = app.EPRESTAPI_CONTEXT_ROOT + "access/clean";
		} else {
			window.location = "/IDM/UI/Logout";
		}
	} else if (xhr.status === "403") {
		window.location = app.EPRESTAPI_CONTEXT_ROOT + "error/403";
	} else if (xhr.status === "600") {
		//server side validation failed
		if (errorType) {
			dialog.set({disableLanguage:true}).show(errorType);
		}
	}
	else{
//		if (errorType) {
//			dialog.set({disableLanguage:true}).show(errorType);
//		}
	}
});

app.changeErrorMessage = function() {
	$("label.error").each(function(){
		var errorContent = $(this).html();
		var self = $(this);
		
		$.each($.validator.messages, function(key, value){
			if(errorContent == value) {
				//console.log("value = " + key);
				self.attr("msgid", "msg" + key);
			}
		});
	});
};

app.on("langChanged", function() {
	var msg = lang.messages;
//	for ( id in $.validator.messages){
//		if (msg["msg" + id]){
//			$.validator.messages[id] = msg["msg" + id];
//		}
//	}
	app.changeErrorMessage();
});



