<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page buffer = "50kb"%>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "com.egurkha.ini.*"%>
<%@ page import = "com.egurkha.util.*"%>
<%@ page import = "com.egurkha.monitor.alarms.*"%>
<%@ page import = "com.egurkha.EgConstants" %>
<%@ page import = "egurkha.ConfigSiteBean"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "com.eg.EgMemInfo"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgDateInfo"%>
<%@ page import = "com.eg.EgServicesInfo"%>
<%@ page import = "com.eg.EgDbInfo"%>
<%@ page import ="com.egurkha.util.EgSorter"%>
<%@ page import = "com.eg.EgMemCheck"%>
<%@ page import = "java.sql.*"%>
<%@ page import = "java.util.*"%>
<%@ page import = "java.text.*"%>
<%@ page import = "com.egurkha.User"%>
<%@ page import = "com.egurkha.UserRegistry"%>
<%@ page import="com.egurkha.monitor.OneClickDashboardModel"%>
<%@ page import = "com.egurkha.EgUserRole"%>
<%@ page import = "egurkha.config.EcUserData"%>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "net.sf.json.*"%>
<jsp:useBean id = "chnuserpro" scope = "page" class = "egurkha.TransactionBean"/>

<%!
	ResultSet rs = null;
	String str_conn = "";
	String s_qry = "";
	String str_query = "";
	String str_query1 = "";
	String str_utype = "";
	String usertype = "";
	String site = "";
	String str_urole = "";
	String str_ualarmpref = "";
	String str_ualarmmode = "";
	String qctr = "";
	String s_flag = "";
	String s_validdate = "";
	Vector v_sites  = new Vector();
	Vector v_siteslist = new Vector();
	java.sql.Date d_validtill;
	String s_validtill = "";
	String s_current_date = "";
	boolean b_state = false;
	boolean show = true;
	String [] utype = new String[2];
	ArrayList allrolenamesarr = null;
	ArrayList a_all_segs = new ArrayList();
	ArrayList a_user_segs = new ArrayList();
	Vector users = new Vector();
	Vector ausers = new Vector();
	String userStr = "";
	String rptTimeline = "";

	public boolean isValidDomainUser(String l_user)
	{
		IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_authenticate.ini");
		if (iniFile != null && l_user != null && l_user.indexOf("/") != -1)
		{
			l_user = l_user.substring(0,l_user.indexOf("/")).trim();
			String subjs[]=iniFile.getSubjects();
			if (subjs!=null && subjs.length>0)
			{
				for (int i=0;i<subjs.length ; i++)
				{
					String domainDisName = subjs[i];
					if (domainDisName != null && domainDisName.equalsIgnoreCase(l_user))
					{
						return true;
					}
				}
			}
		}
		return false;
	}
%>

<%
	JSONObject rootObj = new JSONObject();
	JSONObject hiddenFields = new JSONObject();
	response.setHeader("Cache-Control", "no-store");
	response.setHeader("Pragma", "no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

	boolean isDouble=EgDbInfo.doubleByteEnabled;
	ResultSet rs = null;
	ResultSet rs_uname = null;
	boolean b_state = false;
	Vector users = new Vector();
	Vector usersexist = new Vector();
	Vector all_Users = new Vector();
	IniUI iniUI = IniUI.getInstance();
	ArrayList dateFormats;
	List temp_dateFormats;
	String format="";
	User user = registry.getUser(session.getId());
	
	String servicesDir = EgInstallInfo.getInstallDir()+"/manager/config/";
	IniFile ServicesIni = new IniFile(servicesDir+"eg_services.ini");

	String eGMgrModel = ServicesIni.getValue("MISC_ARGS","eGMgrModel");

	IniFile eguuid = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_uuid.ini");
	
	EgUserRole usrRole = _user.getUserRole();
	Vector getAllRoles = EgUserRole.getAllRoles();
	boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();
	String userId = _user.getLoginID();

	EgUuidInfo egUuidInfo = new EgUuidInfo();

	//String org = request.getParameter("org");

	EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
	str_conn = egDb.setConnection();
	if (str_conn.equals("CONNECTED"))
	{
		try
		{
			str_query = "SELECT user_id,user_type FROM user_info ORDER BY user_id";
			rs_uname = egDb.SelectExec(str_query);
			Hashtable roles = new Hashtable();
			Hashtable allComps = new Hashtable();
			while(rs_uname.next())
			{
				String str_uname=rs_uname.getString("user_id");
				String str_uid_uname=str_uname;

				String str_utype=rs_uname.getString("user_type");
				boolean isdefuser = User.isDefaultUser(str_uname);
				if (str_uname.indexOf("/Grp/") != -1)
				{
					String grpDelimiter = "/Grp/";
					int idx = str_uname.indexOf(grpDelimiter);
					String str_uname_A = str_uname.substring(0,idx);
					int nextIdx = idx + grpDelimiter.length();
					String str_uname_B = str_uname.substring(nextIdx);
					str_uname = str_uname_A + "/" + str_uname_B + " (Group)";
				}
				if (!isdefuser)
				{
					//if (eGMgrModel.equalsIgnoreCase("enterprise"))
					//{
						//TreeSet userSet = egUuidInfo.getAllUsersUnderOrg("egenterprise");
						//if (userSet.contains(str_uname))
						//{
							//all_Users.add(str_uname);
						//}
					//}
					//else
					{
						boolean isdefaultuser = User.isDefaultUser(userId);
						if (userId.equalsIgnoreCase("egenterprise"))
						{
							isdefaultuser = false;
						}
						if(!isdefaultuser)
						{
							String orgName = "";
							boolean isSuperOrg = egUuidInfo.isSuperOrg(userId);
							boolean isOrg = egUuidInfo.isOrg(userId);
							if (isSuperOrg)
							{
								orgName = userId;
							}
							else if (isOrg)
							{
								orgName = userId;
							}
							else
							{
								orgName = egUuidInfo.getDirectDependentOU(userId);
							}
							TreeSet userSet = egUuidInfo.getAllUsersUnderOrg(orgName);
							if (userSet.contains(str_uname))
							{
								all_Users.add(str_uname);
							}
						}
						else
						{
							all_Users.add(str_uname);
						}
					}
				}
				usersexist.add(str_uname);
				EgUserRole userRole=(EgUserRole)roles.get(str_utype);
				Boolean allComp = (Boolean) allComps.get(str_utype);
				boolean allCompAccess = false;
				if (userRole == null || allComp == null)
				{
					userRole = EgUserRole.getRoleObject(str_utype,getAllRoles);
					if(userRole == null)
						continue;
					roles.put(str_utype,userRole);
					allCompAccess = userRole.hasAllComponentAccess();
					allComps.put(str_utype,new Boolean(allCompAccess));
				}
				else
				{
					allCompAccess = allComp.booleanValue();
				}
				boolean isUserForAutoAssociate = egUuidInfo.isUser(str_uname);
				boolean isShareRole = false;
				
				String orgNameOfUser = egUuidInfo.getDirectDependentOU(str_uname);
				String selecteduname = request.getParameter("username");
				String org = "";
				if (selecteduname != null && selecteduname.trim().length() > 0)
				{
					org = egUuidInfo.getDirectDependentOU(selecteduname);
				}
				if (org != null && !org.equalsIgnoreCase("egenterprise"))
				{
					isShareRole = egUuidInfo.isShareRole(str_utype,getAllRoles);
				}
				if(!allCompAccess && isUserForAutoAssociate && !isShareRole && org != null && org.equalsIgnoreCase(orgNameOfUser))
				{
					if (!selecteduname.equalsIgnoreCase(str_uname))
					{
						users.add(str_uname);
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				egDb.releaseConnection(false);
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
			}
		}
	}
	EgDbAdapterTypeUI.releaseObject(egDb);
	rootObj.put("isUsersCreated",new Boolean(true));
	if (all_Users.size() == 0)
	{
		rootObj.put("isUsersCreated",new Boolean(false));
		out.println(rootObj);
		return;
	}
	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT", "selectedDateFormat");
	String currentDateFormat_script = currentDateFormat; // MMM dd, yyyy
	String currentDateFormat_script_later = null;
	
	String pwdLength = egUI.getValue("MISC_ARGS","PwdMinLen");
	rootObj.put("pwdLength",pwdLength);

	/*
	 * password complexity check - STARTS
	 * by Meena.V
	 */
	String pwdComplexity = egUI.getValue("MISC_ARGS","PwdComplexity");
	if(pwdComplexity == null || pwdComplexity.length()==0)
	{
		pwdComplexity = "LC";
	}
	StringTokenizer pwdComplexStrTknzr = new StringTokenizer(pwdComplexity,",");
	rootObj.put("pwdComplexity",pwdComplexity);
	rootObj.put("pwdComplexityCount",pwdComplexStrTknzr.countTokens());
	/*
	 * password complexity check - ENDS
	 */

	String actDomain=request.getParameter("domain");
	String actSso=request.getParameter("SAML");
	String prevDomain="";
	String strSelect2="";
	IniFile userMappinginiFile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_ui.ini");

	// For find Service Health enabled or disabled
	// By Saravanan.A on 28-2-2012
	String enableServiceHealth = egUI.getValue("SERVICE_HEALTH","enable_services_health");
	enableServiceHealth=(enableServiceHealth==null || enableServiceHealth.trim().length()==0)?"false":enableServiceHealth.toLowerCase();

	boolean isEnableServiceHealth=false;
	if(enableServiceHealth!=null && (enableServiceHealth.equalsIgnoreCase("yes") || enableServiceHealth.equalsIgnoreCase("true")))
		isEnableServiceHealth=true;
	//---end---

	String installdir = EgInstallInfo.getInstallDir();
	IniFile endUserINI = new IniFile(installdir+"/manager/config/eg_endUserDetails.ini");
	String enableEndUserDashboard = endUserINI.getValue("END_USER_DASHBOARD_SETTINGS","EnableEndUserDashboard");
	enableEndUserDashboard=(enableEndUserDashboard==null || enableEndUserDashboard.trim().length()==0)?"false":enableEndUserDashboard.toLowerCase();

	boolean isEnableEndUserDashboard=false;
	if(enableEndUserDashboard!=null && (enableEndUserDashboard.equalsIgnoreCase("yes") || enableEndUserDashboard.equalsIgnoreCase("true")))
		isEnableEndUserDashboard=true;

	String noOfShifts = ServicesIni.getValue("MISC_ARGS","NoOfShiftPeriods");
	Integer intObj = null;
	if (!com.egurkha.util.StringUtils.isNull(noOfShifts) && noOfShifts.length()>0)
	{
		intObj = new Integer(noOfShifts);
	}
	else 
	{
		intObj = new Integer("1");
	}
	int noOfShiftPeriods = intObj.intValue();
	if (noOfShiftPeriods > 10)
	{
		noOfShiftPeriods = 10;
	}
	else if (noOfShiftPeriods < 1)
	{
		noOfShiftPeriods = 1;
	}

	//if(currentDateFormat.indexOf("MMM") >= 0)
	//{
		//for(int i=0; i < currentDateFormat.length();i++)
		//{
			//if(String.valueOf(currentDateFormat.charAt(i)).equals("M"))
			//{
				//currentDateFormat_script = currentDateFormat.replace('M','N');
			//}
		//}
	//}

	IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir() +"/manager/config/eg_authenticate.ini");
	IniFile ssoIniObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_samlsso.ini");
	
	boolean hasSsoLoginEnabled = false;
	String enableSSOLogin = ssoIniObj.getValue("SAML_SSO","SSO_ENABLED");
	if(enableSSOLogin!=null && (enableSSOLogin.equalsIgnoreCase("yes") || enableSSOLogin.equalsIgnoreCase("true")))
	{
		hasSsoLoginEnabled = true;
	}
	rootObj.put("isSAMLLoginEnabled",hasSsoLoginEnabled);

	String[] alldomains=iniFile.getSubjects();
	boolean multipledomains=false;
	int countdomains=0;
	for (int i=0;i<alldomains.length;i++)
	{
		String parent=iniFile.getValue(alldomains[i],"parent_domain_name");
		if (parent.equalsIgnoreCase("none"))
			countdomains++;
	}
	if (countdomains > 1)
		multipledomains=true;
	int validuser=-1;
	boolean validuser1=false;
	String searchBase="";
	String dispDate = null;
	String comFormat = null;
	String deleteAlarm = "false";
	String deleteAcknowledgement = "false";
	String timeZone = "";
	String mailSender = "";
	String str_monitorhomepage = "";
	String allowUserToCreateDashboard = "yes";

	//auditlog
	String previous = "";
	String prevpwd = "";
	String strSalt = "";
	String e_role = "";
	String usertemp = "";
	String ec="";
	String rc="";
	String to = "To:", cc = "cc:", bcc = "bcc:", esc = "Esc",scrpt="cmd:";
	StringBuffer tomail = new StringBuffer();
	StringBuffer ccmail = new StringBuffer();
	StringBuffer bccmail = new StringBuffer();
	StringBuffer escmail = new StringBuffer();
	StringBuffer scriptBuff=new StringBuffer();//add by sunder
	String mailToken = null, comma = ",", tomailStr = "", ccmailStr = "", bccmailStr = "", escmailStr = "",customScript="";;
	int tolen = to.length();
	Hashtable ht = new Hashtable();
	String escMail = "";

	int level = 0;
	int existLevel = 0;
	int size=0;
	String urname =  request.getParameter("qctr");
	String reqFrom = request.getParameter("reqfrom");
	reqFrom = (reqFrom !=null && reqFrom.length()>0)?reqFrom:"";
	String selectedMailSender = "";
	String selectedTimeZone = "";

	ArrayList mailShiftPeriodsList = new ArrayList();
	ArrayList smsShiftPeriodsList = new ArrayList();
	ArrayList escShiftPeriodsList = new ArrayList();
	ArrayList execShiftPeriodList = new ArrayList();

	boolean td=false;
	//auditlog
	String previous1 = "";
	String ala1 = "";
	String ala2 = "";
	String ala3 = "";
	String rc1 = "";
	String m1 = "";
	String sdate = "";
	String t1 = "";
	String t2 = "";
	String t3 = "";
	String p1 = "";
	Vector vecesc = new Vector();
	String escextra = "";

	String alarm_n_type = "";
	String alarm_h = "";
	String alarm_m = "";
	String alarm_l = "";
	String type1 = "";
	String type2 = "";
	String str_ualarmtype = "";
	boolean alarmtype = false;
	String type3 = "";
	String pref1 = "";
	String pref2 = "";
	String mode1 = "";
	String mode2 = "";
	String mode3 = "";
	String modeForDDInMailYes = "";
	String modeForDDInMailNo = "";
	String str_upass = "";
	String str_umailid = "";
	boolean b_recordpresent = false;
	boolean noexpiryflag = false;
	//CONTROL ACTION
	String remotecontrol1 = "";
	String remotecontrol2 = "";
	String userrole = "";
	String uname = "";
	boolean hasmonitoraccess = false;
	boolean hasallcompaccess = false;
	String str_uid = "";
	Vector v_zones = new Vector();
	Vector sess_vec = new Vector();
	EgUserPreferences eg_pref = null;


	String mailShiftPeriod = "";
	String smsShiftPeriod = "";
	String escShiftPeriod = "";
	String measureInMailMode = "";
	String ddInMailMode = "";
	String execShiftPeriod="";
	String userLogo[];
	String loginLogo="default";
	String monitorLogo="default";
	String reporterLogo="default";
	String configLogo="default";
	String defaultLogo="same";

	EgDateInfo datehandler = new EgDateInfo();
	String s_date = datehandler.egetDate();
	String s_day = s_date.substring(0, s_date.indexOf("/"));
	String s_month = s_date.substring(s_date.indexOf("/") + 1, s_date.lastIndexOf("/"));
	String s_year = s_date.substring(s_date.lastIndexOf("/") + 1, s_date.indexOf(" "));
	s_current_date = s_month + "/" + s_day + "/" + s_year;

	String needLanguageEntires = request.getParameter("needLanguageEntires");
	if (needLanguageEntires == null) needLanguageEntires = "";

	IniFile egMgrMisc = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
	String selecteduname = request.getParameter("username");
	String userStatus = request.getParameter("userStatus");
	if (selecteduname != null && selecteduname.trim().length() > 0)
	{
		rootObj.put("userStatus","active");
		String temp_userName = com.egurkha.util.StringUtils.decodeSecurityChar(selecteduname);
		String uvalidtill = egUuidInfo.getExpiryDateOfUser(temp_userName);

		if (uvalidtill != null)
		{
			if (uvalidtill.indexOf("9999-12-12 23:59:59") == -1)
			{
				uvalidtill = uvalidtill.substring(0,10);
				uvalidtill = com.egurkha.util.DateUtil.changeDateFormat(uvalidtill,"yyyy-MM-dd","MM/dd/yyyy");
			}
			else
			{
				uvalidtill = "12/12/9999";
			}

			java.util.Date today = new java.util.Date();
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
			java.util.Date uvalidtilldate = new java.util.Date();
			
			try
			{
				uvalidtilldate = formatter.parse(uvalidtill+" 23:59:59");
			}
			catch(Exception e){}

			if (!uvalidtill.equalsIgnoreCase("12/12/9999") && uvalidtilldate.compareTo(today) < 0)
			{
				userStatus = "expired";
				rootObj.put("userStatus","expired");
			}
		}
	}
	String changePwd = egMgrMisc.getValue("CHANGE_PASSWORD",selecteduname);
	if (changePwd == null || changePwd.trim().length() == 0)
	{
		changePwd = "true";
	}
	rootObj.put("changePwd",changePwd);

	JSONObject langEntries = new JSONObject();
	if (needLanguageEntires.equalsIgnoreCase("yes"))
	{
		langEntries.put("utype",_mapping.getTextDescription("admin.user.Role"));
		langEntries.put("userAuth",_mapping.getTextDescription("admin.user.User authentication"));
		langEntries.put("domainAuth",_mapping.getTextDescription("admin.common.Domain"));
		langEntries.put("eGAuth",_mapping.getTextDescription("admin.common.Local"));
		langEntries.put("eGAuth",_mapping.getTextDescription("admin.common.Local"));
		langEntries.put("rdoOperation",_mapping.getTextDescription("admin.user.Operation"));
		langEntries.put("radioOperation1",_mapping.getTextDescription("admin.common.User"));
		langEntries.put("radioOperation2",_mapping.getTextDescription("admin.common.Group"));
		langEntries.put("uname",_mapping.getTextDescription("admin.user.ID"));
		langEntries.put("grpnameCon",_mapping.getTextDescription("admin.user.Group Name"));
		//langEntries.put("upass",_mapping.getTextDescription("admin.user.Password"));
		langEntries.put("pasCont",_mapping.getTextDescription("admin.user.Password"));
		langEntries.put("confpasswd",_mapping.getTextDescription("admin.user.Retype Password"));
		langEntries.put("userExpFieldContainer",_mapping.getTextDescription("admin.user.Expiry date"));
		langEntries.put("Never",_mapping.getTextDescription("admin.user.No expiry"));
		langEntries.put("timeZone",_mapping.getTextDescription("admin.user.Time Zone"));
		langEntries.put("userDataFormat",_mapping.getTextDescription("admin.ui.Date format to be used"));
		langEntries.put("tmpAlarmGroup",_mapping.getTextDescription("admin.user.Alarms by mail / SMS"));
		langEntries.put("mailSenders",_mapping.getTextDescription("admin.user.Mail Sender"));
		langEntries.put("mailIDsContainer",_mapping.getTextDescription("admin.user.Mail ID/Mobile number"));
		langEntries.put("tomailid",_mapping.getTextDescription("admin.user.To"));
		langEntries.put("ccmailid",_mapping.getTextDescription("admin.user.Cc"));
		langEntries.put("bccmailid",_mapping.getTextDescription("admin.user.Bcc"));
		langEntries.put("customScript",_mapping.getTextDescription("admin.user.Command to be executed for alerts "));
		langEntries.put("escMailIDsContainer",_mapping.getTextDescription("admin.user.Escalation mail ID/Mobile number"));
		langEntries.put("alarmNotify",_mapping.getTextDescription("admin.user.Type of notification"));
		langEntries.put("alarmMsgMode",_mapping.getTextDescription("admin.user.Message mode"));
		langEntries.put("measure_in_mail_mode",_mapping.getTextDescription("admin.user.Include measure details in mail alerts"));
		langEntries.put("detailsDiagnosisAlerts",_mapping.getTextDescription("admin.mail.Include detailed diagnosis in mail alerts"));
		langEntries.put("mailshift",_mapping.getTextDescription("admin.user.Email alerts only during shift periods"));
		langEntries.put("Execshift",_mapping.getTextDescription("admin.user.Execute command only during shift periods"));
		langEntries.put("smsshift",_mapping.getTextDescription("admin.user.SMS alerts only during shift periods"));
		langEntries.put("escshift",_mapping.getTextDescription("admin.user.Escalation alerts only during shift periods"));
		langEntries.put("displayAlamGroup",_mapping.getTextDescription("admin.user.Alarm display"));
		langEntries.put("eGRemoteExec",_mapping.getTextDescription("admin.user.Remote control"));
		langEntries.put("eGRemoteExec",_mapping.getTextDescription("admin.user.Remote control"));
		langEntries.put("userDashboardCreationPrivilege",_mapping.getTextDescription("admin.user.Allow user to create mydashboard"));
		langEntries.put("execcommands",_mapping.getTextDescription("admin.user.Remote command execution"));
		langEntries.put("alrmDeletion",_mapping.getTextDescription("admin.user.Allow alarm deletion"));
		langEntries.put("alrmAck",_mapping.getTextDescription("admin.user.Allow alarm acknowledgement"));
		//langEntries.put("monitorHomePage",_mapping.getTextDescription("admin.profile.Monitor home page"));
		langEntries.put("timeOpt",_mapping.getTextDescription("admin.user.Maximum timeline for reports"));
		langEntries.put("personalizedLogo",_mapping.getTextDescription("admin.user.Personalize Logo for "));
		langEntries.put("imgLoginPage",_mapping.getTextDescription("admin.user.Logo preference for Login page"));
		langEntries.put("imgAdminPage",_mapping.getTextDescription("admin.user.Logo preference for Admin/Monitor"));
		langEntries.put("imgRepPage",_mapping.getTextDescription("admin.user.Logo preference for Reporter"));
		langEntries.put("imgConfigPage",_mapping.getTextDescription("admin.user.Logo preference for Configuration"));
	}
	rootObj.put("langEntries",langEntries);


	String orgName = request.getParameter("org");
	orgName = com.egurkha.util.StringUtils.decodeSecurityChar(orgName);
	String userNameStr = request.getParameter("username");
	User selecteduser = registry.getUser(session.getId());
	
	if (userNameStr != null && userNameStr.trim().length() > 0)
	{
		EcUserData ecusr = new EcUserData(userNameStr,false);
		selecteduser = ecusr.getUser(userNameStr);
	}

	int usrLicStatus = 0;
	if (orgName != null && orgName.trim().length() > 0)
	{
		List orgList = egUuidInfo.getOrgNames(orgName);

		int orgListLen = (orgList != null) ? orgList.size() : 0;
		for (int y=0; y<orgListLen; y++)
		{
			String org_id = orgList.get(y).toString().trim();
			GroupCertValidator grpCert = new GroupCertValidator(org_id);
			usrLicStatus = grpCert.checkUser(org_id,orgName,userNameStr);
			
			if (usrLicStatus != 1)
			{
				JSONObject errorObj = new JSONObject();
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.error.Add user"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You have exceeded the number of users allowed by your license"));
				errorObj.put("message2",_mapping.getTextDescription("admin.error.To support additional users")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b class='font_bold'>license@eginnovations.com</b>");
				rootObj.put("errors",errorObj);
				out.println(rootObj.toString());
				return;
			}
		}
	}
	
	egDb = EgDbAdapterTypeUI.getObject();
	str_conn = egDb.setConnection();
	if (str_conn.equals("CONNECTED"))
	{
		try
		{
			//str_query = "SELECT user_id FROM user_info";
			String userName = request.getParameter("username");
			userName = com.egurkha.util.StringUtils.decodeSecurityChar(userName);
			if (userName != null && !userName.equalsIgnoreCase("null") && !userName.equals("-1"))
			{
				if (userName.indexOf("(Group)") != -1)
				{
					int idx = userName.indexOf("/");
					int nextIdx = userName.indexOf("(Group)");
					String strtempuname = userName.substring(0,idx);
					strtempuname = strtempuname + "/Grp/";
					String strtempuname_A = userName.substring(idx + 1 ,nextIdx);
					userName = strtempuname + strtempuname_A;
					userName = userName.trim();
				}
				str_query = "SELECT alarm_delete,alarm_acknowledgement,timezone,mail_sender,mail_shift_period,sms_shift_period,esc_shift_period,monitor_home,measure_in_mail,dd_in_mail,exec_shift_period,logo FROM user_pref where user_id='" + userName + "'";
				ResultSet rSet = egDb.dbselect(str_query);
				if (rSet.next())
				{
					deleteAlarm = rSet.getString("alarm_delete");
					deleteAcknowledgement = rSet.getString("alarm_acknowledgement");
					timeZone = rSet.getString("timezone");
					mailSender= rSet.getString("mail_sender");
					mailShiftPeriod = rSet.getString("mail_shift_period");
					smsShiftPeriod = rSet.getString("sms_shift_period");
					escShiftPeriod = rSet.getString("esc_shift_period");
					str_monitorhomepage = rSet.getString("monitor_home");
					measureInMailMode = rSet.getString("measure_in_mail");
					ddInMailMode = rSet.getString("dd_in_mail");
					execShiftPeriod= rSet.getString("exec_shift_period");
					String tempLogo=rSet.getString("logo");
					userLogo= StringUtils.getTokens(tempLogo,"\\");
					if(userLogo!=null && userLogo.length==5)
					{
						String temp="";
						temp=userLogo[0];
						if(temp.equals("c"))
						{
							loginLogo="custom";
						}
						temp=userLogo[1];
						
						if(temp.equals("c"))
						{
							monitorLogo="custom";
						}
						temp=userLogo[2];
						if(temp.equals("c"))
						{
							reporterLogo="custom";
						}
						
						temp=userLogo[3];
						if(temp.equals("c"))
						{
							configLogo="custom";
						}
						temp=userLogo[4];
						if(temp.equals("d"))
						{
							defaultLogo="different";
						}
					}
				}
			}

			/* Added by Prakash.K starts */
			String dateFormat = "MMM dd, yyyy";
			if(timeZone != null && timeZone.length() > 0 && timeZone.indexOf("$@$") > -1)
			{
				ArrayList aListTokens = StringUtils.egTokenizer(timeZone,"$@$");

				if(aListTokens!=null)
				{
					timeZone=(String)aListTokens.get(0);
					dateFormat=(String)aListTokens.get(1);
				}
			}

			/* Added by Prakash.K finish */

			JSONArray clubAvailableUsers = new JSONArray();
			if (all_Users.size() != 0)
			{
				uname = request.getParameter("username");
				uname = com.egurkha.util.StringUtils.decodeSecurityChar(uname);
				String authenticationType=request.getParameter("authentication");

				String tempUser = "";
				JSONObject tmpUserObj = new JSONObject();
				tmpUserObj.put("displayField",_mapping.getTextDescription("admin.user.Choose user"));
				tmpUserObj.put("valueField","-1");
				tmpUserObj.put("groupField","");
				clubAvailableUsers.add(tmpUserObj);
				ArrayList localUsers = new ArrayList();
				ArrayList domainUsers = new ArrayList();
				ArrayList domainGroups = new ArrayList();
				ArrayList SAMLUsers = new ArrayList();
				ArrayList orgUsers = new ArrayList();

				String orgs [] = eguuid.getVariables("ORGANIZATION_DETAILS");
				ArrayList orgList = orgs==null?new ArrayList():new ArrayList(Arrays.asList(orgs));

				for (int i = 0; i < all_Users.size(); i++)
				{
					str_uid = (String) all_Users.get(i);
					tempUser = str_uid;

					if (((String)session.getAttribute("sess_userid")).equalsIgnoreCase(str_uid))
					{
						continue;
					}

					if (tempUser.indexOf("samlsso/") != -1 && !hasSsoLoginEnabled)
					{
						continue;
					}
					if (eGMgrModel.equalsIgnoreCase("msp") && orgList.contains(tempUser))
					{
						orgUsers.add(tempUser);
					}
					else if (tempUser.startsWith("samlsso/"))
					{
						SAMLUsers.add(tempUser);
					}
					else if (tempUser.indexOf("/") != -1)
					{
						if (tempUser.indexOf("(Group)") != -1)
						{
							domainGroups.add(tempUser);
						}
						else
						{
							domainUsers.add(tempUser);
						}
					}
					else
					{
						localUsers.add(tempUser);
					}
					String tmp = str_uid;
				}

				if (localUsers != null && localUsers.size() > 0)
				{
					for (int l=0;l<localUsers.size();l++)
					{
						JSONObject localUserObj = new JSONObject();
						String strLocalUser = (String) localUsers.get(l);
						if (!com.egurkha.util.StringUtils.isNull(strLocalUser))
						{
							localUserObj.put("groupField","Local");
							localUserObj.put("displayField",strLocalUser);
							localUserObj.put("valueField",strLocalUser);
							clubAvailableUsers.add(localUserObj);
						}

					}
				}

				if (domainUsers != null && domainUsers.size() > 0)
				{
					for (int d=0;d<domainUsers.size();d++)
					{
						JSONObject domUserObj = new JSONObject();
						String strDomUser = (String) domainUsers.get(d);
						String tempDomUser = strDomUser;
						if (!com.egurkha.util.StringUtils.isNull(strDomUser))
						{
							String temp = userMappinginiFile.getValue("DBUSER_USER_MAP",strDomUser);
							if (temp != null && !temp.equals("") && temp.length() > 0)
							{
								tempDomUser = temp;
							}

							tempDomUser = StringUtils.replace(tempDomUser,"<","&lt;");
							tempDomUser = StringUtils.replace(tempDomUser,">","&gt;");
							
							domUserObj.put("groupField","Domain Users");
							domUserObj.put("displayField",tempDomUser);
							domUserObj.put("valueField",strDomUser);
							clubAvailableUsers.add(domUserObj);
						}

					}
				}
				if (domainGroups != null && domainGroups.size() > 0)
				{
					for (int d=0;d<domainGroups.size();d++)
					{
						JSONObject domUserObj = new JSONObject();
						String strDomUser = (String) domainGroups.get(d);
						String tempDomUser = strDomUser;
						if (!com.egurkha.util.StringUtils.isNull(strDomUser))
						{
							if (strDomUser.indexOf("(Group)") != -1)
							{
								String tmp = strDomUser;
								int idx = tmp.indexOf("/");
								int nextIdx = tmp.indexOf("(Group)");
								String strtempuname = tmp.substring(0,idx);
								strtempuname = strtempuname + "/Grp/";
								String strtempuname_A = tmp.substring(idx + 1 ,nextIdx);
								tmp = strtempuname + strtempuname_A;
								tmp = tmp.trim();
								String temp = userMappinginiFile.getValue("DBUSER_USER_MAP",tmp);
								if (temp != null && !temp.equals("") && temp.length() > 0)
								{
									tmp = temp;
								}

								String grpDelimiter = "/Grp/";
								idx = tmp.indexOf(grpDelimiter);
								String str_uname_A = tmp.substring(0,idx);
								nextIdx = idx + grpDelimiter.length();
								String str_uname_B = tmp.substring(nextIdx);
								tempDomUser = str_uname_A + "/" + str_uname_B ;
								strDomUser = tmp;


								temp = userMappinginiFile.getValue("DBUSER_USER_MAP",strDomUser);
								if (temp != null && !temp.equals("") && temp.length() > 0)
								{
									tempDomUser = temp;
								}

								tempDomUser = StringUtils.replace(tempDomUser,"<","&lt;");
								tempDomUser = StringUtils.replace(tempDomUser,">","&gt;");
								
								domUserObj.put("groupField","Domain Groups");
								domUserObj.put("displayField",tempDomUser);
								domUserObj.put("valueField",strDomUser);
								clubAvailableUsers.add(domUserObj);
							}
						}
					}
				}
				
				if (SAMLUsers != null && SAMLUsers.size() > 0)
				{
					for (int s=0;s<SAMLUsers.size();s++)
					{
						JSONObject samlUserObj = new JSONObject();
						String strSAMLUser = (String) SAMLUsers.get(s);
						if (!com.egurkha.util.StringUtils.isNull(strSAMLUser))
						{
							String tmp = strSAMLUser;
							int idx = tmp.indexOf("/");
							String str_uname_A = tmp.substring(idx+1);

							samlUserObj.put("groupField","SAML");
							samlUserObj.put("displayField",str_uname_A);
							samlUserObj.put("valueField",strSAMLUser);
							clubAvailableUsers.add(samlUserObj);
						}

					}
				}

				if (orgUsers != null && orgUsers.size() > 0)
				{
					for (int o=0;o<orgUsers.size();o++)
					{
						JSONObject orgUserObj = new JSONObject();
						String strOrgUser = (String) orgUsers.get(o);
						if (!com.egurkha.util.StringUtils.isNull(strOrgUser))
						{
							orgUserObj.put("groupField","Organization");
							orgUserObj.put("displayField",strOrgUser);
							orgUserObj.put("valueField",strOrgUser);
							clubAvailableUsers.add(orgUserObj);
						}
					}
				}
				rootObj.put("availableUsers",clubAvailableUsers);

				// availableUsersTree - start
				IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
				String managerModel = inifile.getValue("MISC_ARGS","eGMgrModel");
				String session_userid = (String)session.getAttribute("sess_userid");
				if (userStatus == null || userStatus.trim().length() == 0)
				{
					userStatus = "active";
				}

				rootObj.put("initialUserStatus",userStatus);
				if (hasAllComponentAccess)
				{
					if(managerModel != null && managerModel.equalsIgnoreCase("msp"))
					{
						IniFile inifile1 = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_uuid.ini");
						String topLevelOrgs[] = inifile1.getVariables("ORG_UUID");

						ArrayList superOrgs = new ArrayList();
						if(topLevelOrgs != null && topLevelOrgs.length>0)
						{
							superOrgs.addAll(Arrays.asList(topLevelOrgs));
						}
						JSONArray exportDataArr = new JSONArray();
						for(int i=0;i<superOrgs.size();i++)
						{
							JSONObject exportDataObj = new JSONObject();
							String optVar = "";
							String optVal = "";

							String strDbChild = "";

							String orgname = (String)superOrgs.get(i);
							String uvalidtill = egUuidInfo.getExpiryDateOfUser(orgname);

							boolean isDisabled = false;

							if (uvalidtill != null)
							{
								if (uvalidtill.trim().length() == 0)
								{
									continue;
								}
								if (uvalidtill.indexOf("9999-12-12 23:59:59") == -1)
								{
									uvalidtill = uvalidtill.substring(0,10);
									uvalidtill = com.egurkha.util.DateUtil.changeDateFormat(uvalidtill,"yyyy-MM-dd","MM/dd/yyyy");
								}
								else
								{
									uvalidtill = "12/12/9999";
								}

								java.util.Date today = new java.util.Date();
								SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
								java.util.Date uvalidtilldate = new java.util.Date();
								
								try
								{
									uvalidtilldate = formatter.parse(uvalidtill+" 23:59:59");
								}
								catch(Exception e){}

								if (userStatus.equalsIgnoreCase("active"))
								{
									if (!uvalidtill.equalsIgnoreCase("12/12/9999") && uvalidtilldate.compareTo(today) < 0)
									{
										continue;
									}
								}
								else if (userStatus.equalsIgnoreCase("expired"))
								{
									if (uvalidtill.equalsIgnoreCase("12/12/9999") || uvalidtilldate.compareTo(today) > 0)
									{
										isDisabled = true;
										exportDataObj.put("cls","disabledNode");
									}
								}
							}
							else
							{
								if (userStatus.equalsIgnoreCase("expired"))
								{
									isDisabled = true;
									exportDataObj.put("cls","disabledNode");
								}
							}

							optVar = (String)superOrgs.get(i);
							optVal = (String)superOrgs.get(i);

							JSONArray rootUserObjectArray = new JSONArray();
							if (userStatus.equalsIgnoreCase("expired"))
							{
								TreeSet expiredUserSet = egUuidInfo.getAllExpiredUsers();
								if (expiredUserSet != null && !expiredUserSet.isEmpty())
								{
									rootUserObjectArray = egUuidInfo.buildTreeJsonForExpiredUsers(orgname,false,expiredUserSet);
								}
							}
							else
							{
								rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers(orgname,session_userid,false,userStatus);
							}

							if (orgname.equalsIgnoreCase("egenterprise"))
							{
								if (!rootUserObjectArray.isEmpty())
								{
									exportDataObj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
									exportDataObj.put("id",optVar);
									exportDataObj.put("iconCls","iconDomain");
									exportDataObj.put("expanded",true);
									exportDataObj.put("children",rootUserObjectArray);
									exportDataArr.add(exportDataObj);
								}
							}
							else
							{
								if (userStatus.equalsIgnoreCase("expired") && isDisabled)
								{
									if (rootUserObjectArray.isEmpty())
									{
										continue;
									}
								}
								exportDataObj.put("text",optVal);
								exportDataObj.put("id",optVar);
								exportDataObj.put("iconCls","iconDomain");
								exportDataObj.put("expanded",true);
								exportDataObj.put("children",rootUserObjectArray);
								exportDataArr.add(exportDataObj);
							}
						}
						rootObj.put("exportDataArr",exportDataArr);
						rootObj.put("RootNodeText","Choose Organization / Organizational Unit / User");

						if (exportDataArr.isEmpty())
						{
							rootObj.put("isUsersCreated",new Boolean(false));
							out.println(rootObj);
							return;
						}
					}
					else
					{
						JSONArray exportDataArr = new JSONArray();
						JSONObject exportDataObj = new JSONObject();

						if (userStatus.equalsIgnoreCase("expired"))
						{
							exportDataObj.put("cls","disabledNode");
						}

						exportDataObj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
						exportDataObj.put("id","egenterprise");
						exportDataObj.put("iconCls","iconDomain");
						exportDataObj.put("expanded",true);

						JSONArray rootUserObjectArray = new JSONArray();
						if (userStatus.equalsIgnoreCase("expired"))
						{
							TreeSet expiredUserSet = egUuidInfo.getAllExpiredUsers();
							if (expiredUserSet != null && !expiredUserSet.isEmpty())
							{
								rootUserObjectArray = egUuidInfo.buildTreeJsonForExpiredUsers("egenterprise",false,expiredUserSet);
							}
						}
						else
						{
							rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers("egenterprise",session_userid,false,userStatus);
						}

						exportDataObj.put("children",rootUserObjectArray);
						exportDataArr.add(exportDataObj);

						if (rootUserObjectArray.isEmpty())
						{
							rootObj.put("isUsersCreated",new Boolean(false));
							out.println(rootObj);
							return;
						}
						else
						{
							rootObj.put("exportDataArr",exportDataArr);
							rootObj.put("RootNodeText","Choose Organizational Unit / User");
						}
					}
				}
				else
				{
					String orgname = "";
					boolean isSuperOrg = egUuidInfo.isSuperOrg(session_userid);
					boolean isOrg = egUuidInfo.isOrg(session_userid);
					if (isSuperOrg)
					{
						orgname = session_userid;
					}
					else if (isOrg)
					{
						orgname = session_userid;
					}
					else
					{
						orgname = egUuidInfo.getDirectDependentOU(session_userid);
					}

					JSONArray rootUserObjectArray = new JSONArray();
					if (userStatus.equalsIgnoreCase("expired"))
					{
						TreeSet expiredUserSet = egUuidInfo.getAllExpiredUsers();
						if (expiredUserSet != null && !expiredUserSet.isEmpty())
						{
							rootUserObjectArray = egUuidInfo.buildTreeJsonForExpiredUsers(orgname,false,expiredUserSet);
						}
					}
					else
					{
						rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers(orgname,session_userid,false,userStatus);
					}

					rootObj.put("exportDataArr",rootUserObjectArray);
					rootObj.put("RootNodeText","Choose Organizational Unit / User");

					if (rootUserObjectArray.isEmpty())
					{
						rootObj.put("isUsersCreated",new Boolean(false));
						out.println(rootObj);
						return;
					}
				}

				// availableUsersTree - end

				if (authenticationType == null)
				{
					authenticationType = "Eg";
					if (uname != null && uname.indexOf("/")>-1 && isValidDomainUser(uname))
					{
						authenticationType = "domain";
						actDomain = uname.substring(0,uname.indexOf("/"));
					}
					else if(uname != null && uname.indexOf("samlsso") != -1)
					{
						StringTokenizer token1 = new StringTokenizer(uname, "/");
						String tmpSAML = (String) token1.nextElement();
						String IdpName = (String) token1.nextElement();
						authenticationType = "SAML";
						actSso = IdpName;
					}
					rootObj.put("authenticationType",authenticationType);
				}
				else
				{
					rootObj.put("authenticationType",authenticationType);
				}

				JSONArray domainsList = new JSONArray();
				String[] domains=iniFile.getSubjects();
				if(domains!=null)
				{
					for(int i=0;i<domains.length;i++)
					{
						JSONObject tmpObj = new JSONObject();
						String domain = domains[i];
						if(domain.equalsIgnoreCase(actDomain))
						{
							rootObj.put("selectedDomain",actDomain);
						}
						tmpObj.put("displayField",domain);
						tmpObj.put("valueField",domain);
						domainsList.add(tmpObj);
					}
				}
				rootObj.put("domainsList",domainsList);


				JSONArray ssoList = new JSONArray();
				String[] idps=ssoIniObj.getSubjects();
				if(idps!=null)
				{
					for(int i=0;i<idps.length;i++)
					{
						String idp = idps[i];
						if (!com.egurkha.util.StringUtils.isNull(idps[i]) && (idps[i].equals("SAML_SSO") || idps[i].startsWith("SECONDARY_")))
						{
							continue;
						}

						JSONObject tmpObj = new JSONObject();
						if(idp.equalsIgnoreCase(actSso))
						{
							rootObj.put("selectedSso",actSso);
						}
						tmpObj.put("displayField",idp);
						tmpObj.put("valueField",idp);
						ssoList.add(tmpObj);
					}
				}
				rootObj.put("ssoList",ssoList);
				
				if(validuser1 || authenticationType.equalsIgnoreCase("Eg") || uname.indexOf("/") != -1 || uname.indexOf("samlsso") != -1)
				{
					qctr = request.getParameter("qctr");
					if (qctr != null && qctr.equals("1"))
					{
						if (uname != null)
						{
							if (uname.indexOf("(Group)") != -1)
							{
								int idx = uname.indexOf("/");
								int nextIdx = uname.indexOf("(Group)");
								String strtempuname = uname.substring(0,idx);
								strtempuname = strtempuname + "/Grp/";
								String strtempuname_A = uname.substring(idx + 1 ,nextIdx);
								uname = strtempuname + strtempuname_A;
								uname = uname.trim();
							}

							str_query1 = "SELECT * FROM user_info WHERE user_id='" + uname + "'";
							rs = egDb.dbselect(str_query1);

							while (rs.next())
							{
								str_utype = rs.getString("user_type");
								str_upass = rs.getString("user_pass");
								str_upass = EgCrypt.decrypt(str_upass);
								str_umailid = rs.getString("user_mailid");
								d_validtill = rs.getDate("user_valid_till");
								strSalt = "~EG~";
								str_upass += strSalt;
								prevpwd = EgCrypt.encrypt(str_upass); //auditlog
								
								rptTimeline = rs.getString("rept_timeline");

								if (str_umailid == null)
									str_umailid = "";

								str_ualarmtype = rs.getString("user_alarm_type");

								if (str_ualarmtype == null)
								{
									str_ualarmtype = "";
									alarmtype = false;
								}

								if (str_ualarmtype.indexOf("H") > -1)
								{
									type1 = "checked";
									alarmtype = true;
								}

								if (str_ualarmtype.indexOf("I") > -1)
								{
									type2 = "checked";
									alarmtype = true;
								}

								if (str_ualarmtype.indexOf("L") > -1)
								{
									type3 = "checked";
									alarmtype = true;
								}

								str_ualarmpref = rs.getString("user_alarm_pref");

								if (str_ualarmpref == null)
									str_ualarmpref = "";
								else if (str_ualarmpref.equals("N"))
									pref1 = "checked";
								else if (str_ualarmpref.equals("C"))
									pref2 = "checked";
								str_ualarmmode = rs.getString("user_alarm_mode");
								if (str_ualarmmode == null)
									str_ualarmmode = "";
								else if (str_ualarmmode.equals("H"))
									mode1 = "checked";
								else if (str_ualarmmode.equals("T"))
									mode2 = "checked";
								String ca = rs.getString("ca_enabled");

								if (ca == null)
								{
									remotecontrol1 = "";
									remotecontrol2 = "";
								}
								else
								{
									if (ca.indexOf("#")>-1)
									{
										ec=ca.substring(ca.indexOf("#")+1);
										rc=ca.substring(0,ca.indexOf("#"));
									}
									if (rc.equalsIgnoreCase("true"))
									{
										remotecontrol1 = "checked";
									}
									else
									{
										remotecontrol2 = "checked";
									}
								}
								if(rptTimeline == null)
								{
									rptTimeline = "1 month";
								}
							}

							if (d_validtill == null)
							{
								noexpiryflag = true;
								b_recordpresent = false;
							}
							else
							{
								b_recordpresent = true;
							}

							if (b_recordpresent == true)
							{
								String s_validtill = d_validtill.toString();
								s_validdate = s_validtill.substring(s_validtill.indexOf("-") + 1, s_validtill.length());
								s_validdate = s_validdate + "-" + s_validtill.substring(0, s_validtill.indexOf("-"));
								s_validdate = s_validdate.replace('-', '/');
							}
						}

						eg_pref = EgUserPreferences.getUserPreferences(uname);
						alarm_n_type = eg_pref.getUIAlarms();

						if (alarm_n_type == null)
							alarm_n_type = "";

						if (alarm_n_type.indexOf('H') > -1)
							alarm_h = "checked";

						if (alarm_n_type.indexOf('I') > -1)
							alarm_m = "checked";

						if (alarm_n_type.indexOf('L') > -1)
							alarm_l = "checked";

						str_urole = request.getParameter("usertype");
						ArrayList userroles = new ArrayList();
						userroles = EgUserRole.getAllRoleNames();
						String each_role = "";

						boolean isConfigEnabled = EgInstallInfo.isConfigSupported;
						ArrayList aListPredefinedRoles = new ArrayList();
						ArrayList aListUserdefinedRoles = new ArrayList();
						for (int i=0;i<userroles.size();i++)
						{
							String rolename = (String)userroles.get(i);
							if (rolename.equalsIgnoreCase("egsm"))
							{
								continue;
							}

							if (!isConfigEnabled && (rolename.equals("MonitorNoConfig") || rolename.equals("SupermonitorNoConfig")))
							{
								continue;
							}

							boolean isRoleNotDefault = EgUserRole.isRoleNotDefault(rolename);
							if (isRoleNotDefault)
							{
								aListUserdefinedRoles.add(rolename);
							}
							else
							{
								aListPredefinedRoles.add(rolename);
							}
						}

						String chk = "";
						if (str_urole == null)
						{
							str_urole = str_utype;
						}

						EgUserRole eg = EgUserRole.getRoleObject(str_urole,getAllRoles);
						hasmonitoraccess = eg.hasMonitorAccess();
						hasallcompaccess = eg.hasAllComponentAccess();
						rootObj.put("hasallcompaccess",new Boolean(hasallcompaccess));

						JSONArray userRolesArr = new JSONArray();
						JSONObject tmpRoleObj = new JSONObject();

						tmpRoleObj.put("displayField",_mapping.getTextDescription("admin.user.Choose a role"));
						tmpRoleObj.put("groupField","");
						tmpRoleObj.put("valueField","none");
						tmpRoleObj.put("hasallcompaccess",false);
						tmpRoleObj.put("isShareRole",true);
						userRolesArr.add(tmpRoleObj);

						for (int i=0;i<aListPredefinedRoles.size();i++)
						{
							each_role = (String)aListPredefinedRoles.get(i);
							String tips = egUI.getValue("TOOLTIPS_FOR_ROLES",each_role);
							EgUserRole eg1 = EgUserRole.getRoleObject(each_role,getAllRoles);
							tmpRoleObj.put("displayField",each_role);
							tmpRoleObj.put("groupField","Pre-defined roles");
							tmpRoleObj.put("valueField",each_role);
							tmpRoleObj.put("hasallcompaccess",eg1.hasAllComponentAccess());
							tmpRoleObj.put("tips",tips);
							tmpRoleObj.put("isShareRole",egUuidInfo.isShareRole(each_role,eg1));
							userRolesArr.add(tmpRoleObj);
							if(each_role.equalsIgnoreCase(str_urole))
							{
								e_role=each_role;
							}
						}

						boolean isdefuser = User.isDefaultUser(userId);
						if (userId.equalsIgnoreCase("egenterprise"))
						{
							isdefuser = false;
						}
						
						if(eGMgrModel != null && eGMgrModel.equalsIgnoreCase("msp"))
						{
							String sess_userid = (String)session.getAttribute("sess_userid");
							String orgForRoles = sess_userid;
							if (uname != null && uname.trim().length() > 0)
							{
								orgForRoles = uname;
							}
							else if (orgName != null && orgName.trim().length() > 0)
							{
								orgForRoles = orgName;
							}
							String orgname = "";
							if (egUuidInfo.isSuperOrg(orgForRoles))
							{
								orgname = orgForRoles;
							}
							else
							{
								orgname = egUuidInfo.getSuperOU(orgForRoles);
							}
							if (!orgname.equalsIgnoreCase("egenterprise"))
							{
								String userRoles = eguuid.getValue("ORG_ROLE_MAPPINGS",orgname);
								List userRoleList = java.util.Arrays.asList(StringUtils.getTokens(userRoles,","));
								aListUserdefinedRoles.retainAll(userRoleList);
							}
						}

						for (int i=0;i<aListUserdefinedRoles.size();i++)
						{
							tmpRoleObj = new JSONObject();
							each_role = (String)aListUserdefinedRoles.get(i);
							EgUserRole eg1 = EgUserRole.getRoleObject(each_role,getAllRoles);
							tmpRoleObj.put("displayField",each_role);
							tmpRoleObj.put("groupField","User defined roles");
							tmpRoleObj.put("valueField",each_role);
							tmpRoleObj.put("hasallcompaccess",eg1.hasAllComponentAccess());
							tmpRoleObj.put("isShareRole",egUuidInfo.isShareRole(each_role,eg1));
							userRolesArr.add(tmpRoleObj);
							if(each_role.equalsIgnoreCase(str_urole))
							{
								e_role = each_role;
							}
						}
						rootObj.put("userRolesArr",userRolesArr);
						rootObj.put("utype",e_role);

						if (str_urole != null && uname != null && qctr.equals("1"))
						{
							if (authenticationType.equalsIgnoreCase("Eg"))
							{
								rootObj.put("changeObj",prevpwd);//str_upass
							}
							try
							{
								if (b_recordpresent == true)
								{
									if (s_validdate != null && s_validdate.equals("12/12/9999"))
									{
										sdate = "Never";
										rootObj.put("validtill",sdate);
										hiddenFields.put("validtill_h",sdate);
									}
									else
									{
										sdate = s_validdate;
										if (DateUtil.isDate(s_validdate, "MM/dd/yyyy"))
										{
											comFormat = "MM/dd/yyyy";
										}
										else
										{
											comFormat = currentDateFormat;
										}
										dispDate = DateUtil.changeDateFormat(s_validdate, comFormat, currentDateFormat);

										EgTimeZoneConverter egtc = new EgTimeZoneConverter(dispDate+" 23:59:59", _user);
										String userDateFormat = user.getUserDateFormat();

										if(!StringUtils.isNull(userDateFormat) && userDateFormat.equalsIgnoreCase("default"))
										{
											userDateFormat = currentDateFormat;
										}
										//if(userDateFormat.indexOf("MMM") >= 0)
										//{
											//currentDateFormat_script = StringUtils.replace(userDateFormat, "M", "N");
										//}
										currentDateFormat_script_later = currentDateFormat_script;
										rootObj.put("validtill",egtc.getDateTime());
										rootObj.put("validtill_h_pre",dispDate);
										hiddenFields.put("validtill_h",dispDate);
									}
								}
								else
								{
									if (noexpiryflag == true)
									{
										rootObj.put("validtill","Never");
										hiddenFields.put("validtill_h","Never");
									}
									else
									{
										rootObj.put("validtill",s_validdate);
									}
								}
							}
							catch(Exception e)
							{
								e.printStackTrace();
							}

							JSONArray timeZoneArr = new JSONArray();
							JSONObject tmpZoneObj = new JSONObject();
							TimeZone tz = TimeZone.getDefault();
							timeZone = (timeZone!=null && !timeZone.equalsIgnoreCase("null"))?timeZone:"default";

							TimeZoneUtil tzu = new TimeZoneUtil();
							ArrayList timeZoneList = tzu.getAllTimeZones();
							if (timeZoneList!=null && timeZoneList.size()>0)
							{
								String isTZoneSelected = "";
								if (timeZone.equals("default"))
								{
									isTZoneSelected = "selected";
									selectedTimeZone = tz.getID();
								}
								for (int i=0;i<timeZoneList.size();i++)
								{
									String timeZoneValue = (String)timeZoneList.get(i);
									StringTokenizer st = new StringTokenizer(timeZoneValue,"@");
									String offset = st.nextToken();
									String timeZoneId = st.nextToken();
									isTZoneSelected = "";
									if(!timeZoneId.equals("Singapore"))
									{
										if (timeZone.trim().equals(timeZoneId))
										{
											isTZoneSelected = "selected";
											selectedTimeZone = timeZoneId;
										}
										tmpZoneObj.put("displayField",offset+" "+timeZoneId.replace('_',' '));
										tmpZoneObj.put("valueField",timeZoneId);
										timeZoneArr.add(tmpZoneObj);
										if (selectedTimeZone == null || selectedTimeZone.trim().length() == 0)
										{
											if(timeZoneId.equals(tzu.getID()))
											{
												selectedTimeZone = timeZoneId;
											}
										}
									}
								}
							}
							rootObj.put("selectedTimeZone",selectedTimeZone);
							rootObj.put("timeZone",timeZoneArr);

							String selectedDateFormat = iniUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
							if (StringUtils.isNull(selectedDateFormat))
							{
								selectedDateFormat = EgConstants.BLANK_STRING;
							}
							rootObj.put("selectedDateFormat",dateFormat);
							hiddenFields.put("$_CURRENT_DATE_FORMAT$selectedDateFormat","Date format to be used$"+selectedDateFormat);
							hiddenFields.put("previousDateFormat",selectedDateFormat);

							JSONArray userDataFormatArr = new JSONArray();
							dateFormats = iniUI.getAvailableDateFormats();
							dateFormats = iniUI.getAvailableDateFormats();
							if(dateFormats != null && dateFormats.size() > 0)
							{
								EgSorter esort = new EgSorter(dateFormats, 1);
								temp_dateFormats = esort.sort(1, "String", "asc");
								dateFormats.clear();
								dateFormats.addAll(temp_dateFormats);
							}
							if (dateFormats != null && dateFormats.size() > 0)
							{
								for(int i=0;i<dateFormats.size();i++)
								{
									format=(String)dateFormats.get(i);
									if (format != null && format.indexOf("NNN") != -1)
									{
										continue;
									}
									JSONObject dataObj = new JSONObject();
									dataObj.put("displayField",format);
									dataObj.put("valueField",format);
									userDataFormatArr.add(dataObj);
								}
							}
							else
							{
								JSONObject dataObj = new JSONObject();
								dataObj.put("displayField",dateFormat);
								dataObj.put("valueField",dateFormat);
								userDataFormatArr.add(dataObj);
							}
							rootObj.put("userDataFormat",userDataFormatArr);

							/*Description Field- start*/
							String isDescEnabled = egMgrMisc.getValue("MISC_ARGS","ShowUserDescription");
							if(isDescEnabled != null && isDescEnabled.equalsIgnoreCase("yes"))
							{
								String userDescription = egMgrMisc.getValue("USER_DESCRIPTION",uname);
								rootObj.put("description",userDescription);
							}
							rootObj.put("isDescEnabled",isDescEnabled);
							/*Description Field- end*/

							try
							{
								StringTokenizer stoken = new StringTokenizer(str_umailid, ",");
								int count = stoken.countTokens();

								for (int i = 0; i < count; i++)
								{
									mailToken = stoken.nextToken();
									if (mailToken.startsWith(to))
									{
										tomail.append(mailToken.substring(tolen));
										tomail.append(comma);
									}
									else if (mailToken.startsWith(cc))
									{
										ccmail.append(mailToken.substring(cc.length()));
										ccmail.append(comma);
									}
									else if (mailToken.startsWith(bcc))
									{
										bccmail.append(mailToken.substring(bcc.length()));
										bccmail.append(comma);
									}
									else if (mailToken.startsWith(esc))
									{
										escmail.append(mailToken.substring(esc.length()));
										escmail.append(comma);
									}
									else if(mailToken.startsWith(scrpt))
									{
										scriptBuff.append(mailToken.substring(scrpt.length()));
										scriptBuff.append(comma);
									}
									else
									{
										tomail.append(mailToken);
										tomail.append(comma);
									}
								}
								if (count > 0)
								{
									tomailStr = tomail.toString();
									if (tomailStr.length() > 0)
										tomailStr = tomailStr.substring(0, tomailStr.length() - 1);

									ccmailStr = ccmail.toString();
									if (ccmailStr.length() > 0)
										ccmailStr = ccmailStr.substring(0, ccmailStr.length() - 1);

									bccmailStr = bccmail.toString();

									if (bccmailStr.length() > 0)
										bccmailStr = bccmailStr.substring(0, bccmailStr.length() - 1);

									escmailStr = escmail.toString();

									if (escmailStr.length() > 0)
										escmailStr = escmailStr.substring(0, escmailStr.length() - 1);
									customScript=scriptBuff.toString();
										if(customScript.length()>0)
											customScript=customScript.substring(0,customScript.length()-1);
										if(customScript!=null && customScript.endsWith("NA"))
											customScript="";
								}

								if (escmailStr.lastIndexOf(",") > 0)
								{
									String tmp  = escmailStr.substring(escmailStr.lastIndexOf(",") + 1, escmailStr.length());
									String temp = tmp.substring(0, tmp.indexOf(":"));

									if (!temp.equals(""))
										level = Integer.parseInt(temp);
								}
								rootObj.put("level",new Integer(level));

								StringTokenizer st = new StringTokenizer(escmailStr, ",");
								StringBuffer sb = new StringBuffer();

								while (st.hasMoreTokens())
								{
									//escmailStr 1:l1@y.com,1:l11@y.com,2:l2@y.com,2:l21@y.com
									mailToken = st.nextToken();
									StringTokenizer tok = new StringTokenizer(mailToken, ":");
									int cnt = tok.countTokens();

								//try{
								/*if(cnt<2)
								{
									for (int i=0;tok.hasMoreTokens(); i++)
									{
										sb.append(tok.nextToken());
										sb.append (",");
									}
								}
								else
								{
								*/
									while (tok.hasMoreTokens())
									{
										try
										{
											String tok1 = tok.nextToken();
											String tok2 = tok.nextToken();
											if (!ht.containsKey(tok1))
											{
												ht.put(tok1, tok2);
											}
											else
											{
												String val   = (String) ht.get(tok1);
												String value = val + "," + tok2;
												ht.put(tok1, value);
											}
										}
										catch (Exception ex)
										{
										}
									}
									//}
								}

								String esc1 = sb.toString();
								if (esc1.lastIndexOf(",") > 0)
									escMail = esc1.substring(0, esc1.lastIndexOf(","));
								else
								{
									esc1 = (String) ht.get((Object) ("1"));
									ht.remove((Object) ("1"));

									if (esc1 != null)
									{
										escMail = esc1;
									}
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}

							JSONObject mailAlertSettings = new JSONObject();
							IniUI ui = (com.egurkha.ini.IniUI) IniUI.getInstance();
							rootObj.put("hasmonitoraccess",new Boolean(false));

							chnuserpro.createFile("eg_services.ini");
							String defaultMailSender = chnuserpro.getStrValue("MISC_ARGS","MailSender");
							String selected = "";
							if (mailSender !=null && mailSender.length()>0 && mailSender.equals("default"))
							{
								if (!StringUtils.isNull(defaultMailSender))
								{
									selectedMailSender = defaultMailSender;
								}
								else
								{
									selectedMailSender = mailSender;
								}
								mailAlertSettings.put("selectedMailSender",mailSender);
							}
							JSONArray mailSendersArr = new JSONArray();
							JSONObject mailSenderObj = new JSONObject();
							mailSenderObj.put("displayField",defaultMailSender+"("+_mapping.getTextDescription("admin.usre.Default")+")");
							mailSenderObj.put("valueField","default");
							mailSendersArr.add(mailSenderObj);

							String[] mailIDs = chnuserpro.getVariables("MAIL_SENDERS");
							if (mailIDs !=null && mailIDs.length>0)
							{
								for(int i=0;i<mailIDs.length;i++)
								{
									mailSenderObj = new JSONObject();
									selected = "";
									mailIDs[i]= mailIDs[i].trim();
									if (mailIDs[i].equals(mailSender.trim()))
									{
										selected = "selected";
										selectedMailSender = mailIDs[i];
										mailAlertSettings.put("selectedMailSender",selectedMailSender);
									}
									mailSenderObj.put("displayField",mailIDs[i]);
									mailSenderObj.put("valueField",mailIDs[i]);
									mailSendersArr.add(mailSenderObj);
								}
							}
							mailAlertSettings.put("mailSenders",mailSendersArr);
							mailAlertSettings.put("tomailid",tomailStr);
							mailAlertSettings.put("ccmailid",ccmailStr);
							mailAlertSettings.put("bccmailid",bccmailStr);
							rootObj.put("mailAlertSettings",mailAlertSettings);


							if (hasmonitoraccess)
							{
								rootObj.put("hasmonitoraccess",new Boolean(true));
								mailAlertSettings.put("high",type1);
								mailAlertSettings.put("medium",type2);
								mailAlertSettings.put("low",type3);
								mailAlertSettings.put("hasAlramList",new Boolean(true));
								if (str_ualarmtype == null || str_ualarmtype.length() == 0 || str_ualarmtype.equalsIgnoreCase("null"))
								{
									mailAlertSettings.put("hasAlramList",new Boolean(false));
								}
								//chnuserpro.createFile("eg_services.ini");
								//String defaultMailSender = chnuserpro.getStrValue("MISC_ARGS","MailSender");
								//String selected = "";
								//if (mailSender !=null && mailSender.length()>0 && mailSender.equals("default"))
								//{
									//if (!StringUtils.isNull(defaultMailSender))
									//{
										//selectedMailSender = defaultMailSender;
									//}
									//else
									//{
										//selectedMailSender = mailSender;
									//}
									//mailAlertSettings.put("selectedMailSender",mailSender);
								//}
								//JSONArray mailSendersArr = new JSONArray();
								//JSONObject mailSenderObj = new JSONObject();
								//mailSenderObj.put("displayField",defaultMailSender+"("+_mapping.getTextDescription("admin.usre.Default")+")");
								//mailSenderObj.put("valueField","default");
								//mailSendersArr.add(mailSenderObj);

								//String[] mailIDs = chnuserpro.getVariables("MAIL_SENDERS");
								//if (mailIDs !=null && mailIDs.length>0)
								//{
									//for(int i=0;i<mailIDs.length;i++)
									//{
										//mailSenderObj = new JSONObject();
										//selected = "";
										//mailIDs[i]= mailIDs[i].trim();
										//if (mailIDs[i].equals(mailSender.trim()))
										//{
											//selected = "selected";
											//selectedMailSender = mailIDs[i];
											//mailAlertSettings.put("selectedMailSender",selectedMailSender);
										//}
										//mailSenderObj.put("displayField",mailIDs[i]);
										//mailSenderObj.put("valueField",mailIDs[i]);
										//mailSendersArr.add(mailSenderObj);
									//}
								//}
								//mailAlertSettings.put("mailSenders",mailSendersArr);
								//mailAlertSettings.put("tomailid",tomailStr);
								//mailAlertSettings.put("ccmailid",ccmailStr);
								//mailAlertSettings.put("bccmailid",bccmailStr);

								mailAlertSettings.put("customScript",customScript);

								mailAlertSettings.put("escmailid",escMail);
								JSONArray escMailIDs = new JSONArray();
								if (ht != null && ht.size() > 0)
								{
									size = ht.size();
									Iterator it = (new TreeMap(ht)).keySet().iterator();
									while (it.hasNext())
									{
										String skey = (String) it.next();
										String val = (String) ht.get(skey);
										existLevel++;
										vecesc.add(val);
										escMailIDs.add(val);
									}
								}
								rootObj.put("existLevel",new Integer(existLevel));
								mailAlertSettings.put("escmailids",escMailIDs);
								if (hasmonitoraccess)
								{
									if (pref1.equalsIgnoreCase("checked"))
									{
										mailAlertSettings.put("notify","New");
									}
									else
									{
										mailAlertSettings.put("notify","Complete list");
									}

									if (mode1.equalsIgnoreCase("checked"))
									{
										mailAlertSettings.put("msgmode","Html");
									}
									else
									{
										mailAlertSettings.put("msgmode","Text");
									}
								}

								JSONArray measure_in_mail_modeArr = new JSONArray();
								JSONObject tmpMeasureObj = new JSONObject();

								tmpMeasureObj.put("valueField","NO");
								tmpMeasureObj.put("displayField",_mapping.getTextDescription("admin.user.No"));
								measure_in_mail_modeArr.add(tmpMeasureObj);

								tmpMeasureObj = new JSONObject();
								tmpMeasureObj.put("valueField","DATA");
								tmpMeasureObj.put("displayField",_mapping.getTextDescription("admin.user.Data"));
								measure_in_mail_modeArr.add(tmpMeasureObj);

								tmpMeasureObj = new JSONObject();
								tmpMeasureObj.put("valueField","GRAPH");
								tmpMeasureObj.put("displayField",_mapping.getTextDescription("admin.user.GRAPH"));
								measure_in_mail_modeArr.add(tmpMeasureObj);
								
								mailAlertSettings.put("measure_in_mail_mode",measure_in_mail_modeArr);
								mailAlertSettings.put("selectedMailMode",measureInMailMode);

								if (ddInMailMode.equalsIgnoreCase("YES"))
								{
									mailAlertSettings.put("dd_in_mail_mode",new Boolean(true));
								}
								else
								{
									mailAlertSettings.put("dd_in_mail_mode",new Boolean(false));
								}

								//Mail shift Periods
								mailAlertSettings.put("isShiftPeriodsEnabled",new Boolean(false));
								EgServicesInfo servicesInfo = new EgServicesInfo("manager");
								if (servicesInfo.isShiftPeriodsEnabled())
								{
									mailAlertSettings.put("isShiftPeriodsEnabled",new Boolean(true));
									if (mailShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("mailshift","No");
									}
									else
									{
										mailAlertSettings.put("mailshift","Yes");
									}

									String mailStyle = "";
									StringTokenizer daySt = null;

									mailAlertSettings.put("mailShiftPeriodsList","yes");
									if (mailShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("mailShiftPeriodsList","no");
									}
									else
									{
										StringTokenizer stt = new StringTokenizer(mailShiftPeriod,"|");
										while (stt.hasMoreTokens())
										{
											mailShiftPeriodsList.add(stt.nextToken());
										}
									}

									JSONArray mailShiftPeriodsListArr = new JSONArray();
									for (int m=0;m<mailShiftPeriodsList.size();m++)
									{
										JSONObject mailShiftPeriodsListObj = new JSONObject();
										String dayAndShift = (String)mailShiftPeriodsList.get(m);
										String day = dayAndShift.substring(0,dayAndShift.indexOf("#"));
										String shift = dayAndShift.substring(dayAndShift.indexOf("#")+1);
										daySt = new StringTokenizer(day,",");
										String weekDay = "";
										while(daySt.hasMoreTokens())
										{
											String tmpDay = daySt.nextToken();

											if (tmpDay.equals("1"))
											{
												weekDay = "Sun";
											}else if (tmpDay.equals("2"))
											{
												weekDay += ",Mon";
											}else if (tmpDay.equals("3"))
											{
												weekDay += ",Tue";
											}else if (tmpDay.equals("4"))
											{
												weekDay += ",Wed";
											}else if (tmpDay.equals("5"))
											{
												weekDay += ",Thu";
											}else if (tmpDay.equals("6"))
											{
												weekDay += ",Fri";
											}else if (tmpDay.equals("7"))
											{
												weekDay += ",Sat";
											}
										}
										if (weekDay.startsWith(","))
											weekDay = weekDay.substring(1);

										mailShiftPeriodsListObj.put("mailday"+m,weekDay);
										mailShiftPeriodsListObj.put("mailshift"+m,shift);
										mailShiftPeriodsListArr.add(mailShiftPeriodsListObj);

									}
									mailAlertSettings.put("mailList",mailShiftPeriodsListArr);

									// Exec Shift Period
									if (execShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("Execshift","No");
									}
									else
									{
										mailAlertSettings.put("Execshift","Yes");
									}

									String execStyle = "";
									StringTokenizer dayStr = null;
									mailAlertSettings.put("execShiftPeriodList","yes");
									if (execShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("execShiftPeriodList","no");
									}
									else
									{
										StringTokenizer stt = new StringTokenizer(execShiftPeriod,"|");
										while (stt.hasMoreTokens())
										{
											execShiftPeriodList.add(stt.nextToken());
										}
									}

									JSONArray execShiftPeriodListArr = new JSONArray();
									for (int m=0;m<execShiftPeriodList.size();m++)
									{
										JSONObject execShiftPeriodListObj = new JSONObject();
										String dayAndShift = (String)execShiftPeriodList.get(m);
										String day = dayAndShift.substring(0,dayAndShift.indexOf("#"));
										String shift = dayAndShift.substring(dayAndShift.indexOf("#")+1);
										dayStr = new StringTokenizer(day,",");
										String weekDay = "";
										while(dayStr.hasMoreTokens())
										{
											String tmpDay = dayStr.nextToken();

											if (tmpDay.equals("1"))
											{
												weekDay = "Sun";
											}else if (tmpDay.equals("2"))
											{
												weekDay += ",Mon";
											}else if (tmpDay.equals("3"))
											{
												weekDay += ",Tue";
											}else if (tmpDay.equals("4"))
											{
												weekDay += ",Wed";
											}else if (tmpDay.equals("5"))
											{
												weekDay += ",Thu";
											}else if (tmpDay.equals("6"))
											{
												weekDay += ",Fri";
											}else if (tmpDay.equals("7"))
											{
												weekDay += ",Sat";
											}
										}
										if (weekDay.startsWith(","))
											weekDay = weekDay.substring(1);

										execShiftPeriodListObj.put("Execday"+m,weekDay);
										execShiftPeriodListObj.put("ExecShift"+m,shift);
										execShiftPeriodListArr.add(execShiftPeriodListObj);
									}
									mailAlertSettings.put("ExeComList",execShiftPeriodListArr);

									//  SMS Shift Periods
									if (smsShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("smsshift","No");
									}
									else
									{
										mailAlertSettings.put("smsshift","Yes");
									}

									String smsStyle = "";
									mailAlertSettings.put("smsShiftPeriodsList","yes");
									if (smsShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("smsShiftPeriodsList","no");
									}
									else
									{
										StringTokenizer stt = new StringTokenizer(smsShiftPeriod,"|");
										while (stt.hasMoreTokens())
										{
											smsShiftPeriodsList.add(stt.nextToken());
										}
									}

									JSONArray smsShiftPeriodsListArr = new JSONArray();
									for (int m=0;m<smsShiftPeriodsList.size();m++)
									{
										JSONObject smsShiftPeriodsListObj = new JSONObject();
										String dayAndShift = (String)smsShiftPeriodsList.get(m);
										String day = dayAndShift.substring(0,dayAndShift.indexOf("#"));
										String shift = dayAndShift.substring(dayAndShift.indexOf("#")+1);
										daySt = new StringTokenizer(day,",");
										String weekDay = "";
										while(daySt.hasMoreTokens())
										{
											String tmpDay = daySt.nextToken();
											
											if (tmpDay.equals("1"))
											{
												weekDay = "Sun";
											}else if (tmpDay.equals("2"))
											{
												weekDay += ",Mon";
											}else if (tmpDay.equals("3"))
											{
												weekDay += ",Tue";
											}else if (tmpDay.equals("4"))
											{
												weekDay += ",Wed";
											}else if (tmpDay.equals("5"))
											{
												weekDay += ",Thu";
											}else if (tmpDay.equals("6"))
											{
												weekDay += ",Fri";
											}else if (tmpDay.equals("7"))
											{
												weekDay += ",Sat";
											}			 
										}
										if (weekDay.startsWith(","))
											weekDay = weekDay.substring(1);

										smsShiftPeriodsListObj.put("smsday"+m,weekDay);
										smsShiftPeriodsListObj.put("smsShift"+m,shift);
										smsShiftPeriodsListArr.add(smsShiftPeriodsListObj);
									}
									mailAlertSettings.put("SmsList",smsShiftPeriodsListArr);

									// Esc Shift Period
									if (escShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("escshift","No");
									}
									else
									{
										mailAlertSettings.put("escshift","Yes");
									}

									String escStyle = "";
									mailAlertSettings.put("escShiftPeriodsList","yes");
									if (escShiftPeriod.equalsIgnoreCase("default"))
									{
										mailAlertSettings.put("escShiftPeriodsList","no");
									}
									else
									{
										StringTokenizer stt = new StringTokenizer(escShiftPeriod,"|");
										while (stt.hasMoreTokens())
										{
											escShiftPeriodsList.add(stt.nextToken());
										}
									}

									JSONArray escShiftPeriodListArr = new JSONArray();
									for (int m=0;m<escShiftPeriodsList.size();m++)
									{
										JSONObject escShiftPeriodsListObj = new JSONObject();
										String dayAndShift = (String)escShiftPeriodsList.get(m);
										String day = dayAndShift.substring(0,dayAndShift.indexOf("#"));
										String shift = dayAndShift.substring(dayAndShift.indexOf("#")+1);
										daySt = new StringTokenizer(day,",");
										String weekDay = "";
										while(daySt.hasMoreTokens())
										{
											String tmpDay = daySt.nextToken();
											
											if (tmpDay.equals("1"))
											{
												weekDay = "Sun";
											}else if (tmpDay.equals("2"))
											{
												weekDay += ",Mon";
											}else if (tmpDay.equals("3"))
											{
												weekDay += ",Tue";
											}else if (tmpDay.equals("4"))
											{
												weekDay += ",Wed";
											}else if (tmpDay.equals("5"))
											{
												weekDay += ",Thu";
											}else if (tmpDay.equals("6"))
											{
												weekDay += ",Fri";
											}else if (tmpDay.equals("7"))
											{
												weekDay += ",Sat";
											}			 
										}
										if (weekDay.startsWith(","))
											weekDay = weekDay.substring(1);

										escShiftPeriodsListObj.put("escday"+m,weekDay);
										escShiftPeriodsListObj.put("escShift"+m,shift);
										escShiftPeriodListArr.add(escShiftPeriodsListObj);
									}
									mailAlertSettings.put("EscList",escShiftPeriodListArr);
									rootObj.put("mailShiftPeriodsCount",mailShiftPeriodsList.size());
									rootObj.put("smsShiftPeriodsCount",smsShiftPeriodsList.size());
									rootObj.put("escShiftPeriodsCount",escShiftPeriodsList.size());
									rootObj.put("execShiftPeriodCount",execShiftPeriodList.size());	
									
								} // isShiftEnabled

								String strShowMailFiltersOption = ServicesIni.getValue("MISC_ARGS","showMailFiltersOption");
								strShowMailFiltersOption=(strShowMailFiltersOption==null || strShowMailFiltersOption.trim().length()==0)?"no":strShowMailFiltersOption.toLowerCase();

								boolean isEnableShowMailFiltersOption=false;
								if(strShowMailFiltersOption!=null && (strShowMailFiltersOption.equalsIgnoreCase("yes") || strShowMailFiltersOption.equalsIgnoreCase("true")))
									isEnableShowMailFiltersOption=true;

								IniFile egMAIL = new IniFile(s_iniFile_dir + "eg_mailalert.ini");

								String loginId=uname;
								loginId=(loginId==null || loginId.trim().length()==0)?"":loginId;
								String strMailFilterOption = egMAIL.getValue("MailFilter_Option",loginId);
								strMailFilterOption=(strMailFilterOption==null || strMailFilterOption.trim().length()==0)?"All_Elements":strMailFilterOption.toLowerCase();

								rootObj.put("isFilterControlEnabled",new Boolean(false));
								hiddenFields.put("previousisfiltercontrolenabled",new Boolean(false));

								if(isEnableShowMailFiltersOption)
								{
									rootObj.put("isFilterControlEnabled",new Boolean(true));
									rootObj.put("filterControlDefaultSelection","All_Elements");
									hiddenFields.put("previousisfiltercontroldefaultselection","All_Elements");

									if (strMailFilterOption != null && 
										strMailFilterOption.equalsIgnoreCase("Descriptors_Only"))
									{
										rootObj.put("filterControlDefaultSelection","Descriptors_Only");
										hiddenFields.put("previousisfiltercontroldefaultselection","Descriptors_Only");

									}
								}

								rootObj.put("mailAlertSettings",mailAlertSettings);
								rootObj.put("alarm_h",alarm_h);
								rootObj.put("alarm_m",alarm_m);
								rootObj.put("alarm_l",alarm_l);
								//rootObj.put("remoteEnabled",new Boolean(false));
								boolean remoteEnabled = EgMemInfo.remoteEnabled;
								if (uname != null && (remoteEnabled))
								{
									//rootObj.put("remoteEnabled",new Boolean(true));
									if (remotecontrol1.equalsIgnoreCase("checked"))
									{
										rootObj.put("remotecontrol",new Boolean(true));
									}
									else
									{
										rootObj.put("remotecontrol",new Boolean(false));
									}

									String anycommand="";
									String othercommand="";
									if (ec.equalsIgnoreCase("true"))
										anycommand="selected";
									if (ec.equalsIgnoreCase("false"))
										othercommand="selected";

									JSONArray remoteCommandArr = new JSONArray();
									JSONObject remoteCommandObj = new JSONObject();

									remoteCommandObj.put("displayField",_mapping.getTextDescription("admin.user.Any commands"));
									remoteCommandObj.put("valueField","true");
									remoteCommandArr.add(remoteCommandObj);
									remoteCommandObj = new JSONObject();
									remoteCommandObj.put("displayField",_mapping.getTextDescription("admin.user.Configured commands only"));
									remoteCommandObj.put("valueField","false");
									remoteCommandArr.add(remoteCommandObj);
									rootObj.put("execcommands",remoteCommandArr);
									if (anycommand.equalsIgnoreCase("selected"))
									{
										rootObj.put("selectedCommandMode","true");
									}
									else if (othercommand.equalsIgnoreCase("selected"))
									{
										rootObj.put("selectedCommandMode","false");
									}
									else
									{
										rootObj.put("selectedCommandMode","true");
									}
									hiddenFields.put("previousexeccommands",(anycommand.equals("selected"))?"true":"false");
								}

								if (deleteAlarm.equalsIgnoreCase("true"))
								{
									rootObj.put("alarmdelete",new Boolean(true));
								}
								else
								{
									rootObj.put("alarmdelete",new Boolean(false));
								}

								if (deleteAcknowledgement.equalsIgnoreCase("true"))
								{
									rootObj.put("acknowledgment",new Boolean(true));
								}
								else
								{
									rootObj.put("acknowledgment",new Boolean(false));
								}
								if (!hasallcompaccess && users.size() > 0)
								{
									td = true;
								}

								//**Create dashboard privilege permission--starts**//

								IniFile customDashboardIni = new IniFile(s_iniFile_dir + "eg_customdashboard.ini");

								allowUserToCreateDashboard = customDashboardIni.getValue("USER_DASHBOARD_CREATION_PRIVILEGE",uname);

								if (allowUserToCreateDashboard.equalsIgnoreCase("no"))
								{
									rootObj.put("dashboardCreationPrivilege",new Boolean(false));
								}
								else
								{
									rootObj.put("dashboardCreationPrivilege",new Boolean(true));
								} 
								customDashboardIni = null;

								//**Create dashboard privilege permission--ends**//

								EgMemCheck memCheck = new EgMemCheck();
								
						
								JSONObject hiddenParams = new JSONObject();
								JSONObject screenLabels = new JSONObject();
								EgUserRole userRole1 = EgUserRole.getRoleObject(str_urole,getAllRoles);
								JSONArray monhomear = new JSONArray();
								JSONObject monhomeob = new JSONObject();
								String user_role_name = userRole1.getRoleName();
								if (user_role_name != null && !user_role_name.equals("AlarmViewer") && !user_role_name.equals("SuperAlarmViewer"))
									rootObj.put("remoteEnabled",remoteEnabled);

								if (userRole1.getReporterPerm() < 0)
								{
									if (userRole1.getMonitorPerm() > 0)
									{
										screenLabels.put("admin.profile.Monitor Home Page", _mapping.getTextDescription("admin.profile.Monitor Home Page"));
										String monHomePage = selecteduser.getMonitorHomePage();
										if(monHomePage!=null && monHomePage.equals("Monitor Dashboard"))
										{
											monHomePage = "Infrastructure Overview";
										}
										else if(monHomePage.equals("Virtual"))
											monHomePage = "Virtual Dashboard";
										else if(monHomePage.equals("Alarm History"))
											monHomePage = "History of Alarms";
										else if(monHomePage.equals("Acknowledgement History"))
											monHomePage = "History of Acknowledgements";
										else if(monHomePage.equals("Deletion History"))
											monHomePage = "History of Deletions";

										String tempMonHomePage = monHomePage;
										String currentMonitorHomePageURL = request.getParameter("currentMonitorHomePageURL");
										currentMonitorHomePageURL = (currentMonitorHomePageURL == null) ? "" : currentMonitorHomePageURL;
										currentMonitorHomePageURL = com.egurkha.util.StringUtils.replace(currentMonitorHomePageURL, "|amp|", "&");
										//String user_role_name = userRole1.getRoleName();
										String strDisable = "";
										if (user_role_name != null && (user_role_name.equals("AlarmViewer") || user_role_name.equals("SuperAlarmViewer")))
										{
											strDisable = "disabled";
										}
										rootObj.put("monitorHomeDisable",strDisable);

										// this following code check the userRole1 permission for a user.
										ArrayList aListUserRolePerm = new ArrayList();
										ArrayList aListMonPerm = new ArrayList();
										boolean hasallcompaccess1 = userRole1.hasAllComponentAccess();
										if (!hasallcompaccess1)
										{
											EgUserPermission userPerm = EgUserPermission.getInstance();
											String[][] gg = userPerm.getMonitorDesc();
											long mon = userRole1.getMonitorPerm();
											for (int j = 0; j < gg.length; j++)
											{
												for (int k = 1; k < gg[j].length; k = +2)
												{
													long perm_long = 0;
													try
													{
														perm_long = Long.parseLong(gg[j][k]);
													} catch (Exception e)
													{
														e.printStackTrace();
													}
													if ((mon & perm_long) == perm_long)
														aListUserRolePerm.add(gg[j][k - 1].trim());
													aListMonPerm.add(gg[j][k - 1].trim());
												}
											}
										}
										//--end--
										if (userRole1.getRoleName().equals("AlarmViewer") || userRole1.getRoleName().equals("SuperAlarmViewer"))
										{
											tempMonHomePage = "AlarmViewer";
											screenLabels.put("admin.profile.Current Alarms", _mapping.getTextDescription("admin.profile.Current Alarms"));
										}
										else
										{
											Object monitorHomePages[] = egUI.getVariables("MONITOR_HOME_PAGE");
											List monitorHomePagesList = new LinkedList();
											if (monitorHomePages != null && monitorHomePages.length > 0)
											{
												for (int i = 0; i < monitorHomePages.length; i++)
												{
													String homePageName = (String) monitorHomePages[i];
													if (homePageName != null && homePageName.trim().length() > 0)
													{
														if (!hasallcompaccess1)
														{
															if (aListMonPerm != null && aListMonPerm.size() > 0 && aListMonPerm.contains(homePageName.trim()))
															{
																if (aListUserRolePerm != null && aListUserRolePerm.size() > 0 && aListUserRolePerm.contains(homePageName))
																{
																	monitorHomePagesList.add(homePageName);
																	monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
																}
															}
															else
															{
																monitorHomePagesList.add(homePageName);
																monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
															}
														}
														else
														{
															monitorHomePagesList.add(homePageName);
															monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
														}
													}
												}
												if (!EgInstallInfo.isAggregationSupported())
												{
													//monitorHomePagesList.remove("Aggregates");
													int aggIndex = monitorHomePagesList.indexOf("Aggregates");
													if (aggIndex >= 0)
													{
														monitorHomePagesList.remove(aggIndex + 1);
														monitorHomePagesList.remove(aggIndex);
													}
												}
												// for remove Service Health if its not enabled
												// By Saravanan.A on 28-2-2012
												if (!isEnableServiceHealth)
												{
													int shIndex = monitorHomePagesList.indexOf("Service Health");
													if (shIndex >= 0)
													{
														monitorHomePagesList.remove(shIndex + 1);
														monitorHomePagesList.remove(shIndex);
													}
												}

												if (!isEnableEndUserDashboard)
												{
													int shIndex = monitorHomePagesList.indexOf("End User Dashboard");
													if (shIndex >= 0)
													{
														monitorHomePagesList.remove(shIndex + 1);
														monitorHomePagesList.remove(shIndex);
													}
												}

												//--end--
												// sort the Home page list
												if (monitorHomePagesList != null && monitorHomePagesList.size() > 0)
												{
													EgSorter esort = new EgSorter(monitorHomePagesList, 2);
													monitorHomePagesList = esort.sort(2, "String", "asc");
												}
											}
											if (monitorHomePagesList != null && monitorHomePagesList.size() > 0)
											{
												for (int i = 0; i < monitorHomePagesList.size(); i += 2)
												{
													String homePageName = (String) monitorHomePagesList.get(i);
													String homePageDisplayName = (String) monitorHomePagesList.get(i + 1);
													String url_for_home = "";
													if (homePageName != null && homePageName.trim().length() > 0)
													{
														String monitor_home_page_value = egUI.getValue("MONITOR_HOME_PAGE", homePageName);
														if (monitor_home_page_value != null && monitor_home_page_value.trim().length() > 0)
														{
															url_for_home = monitor_home_page_value;
														}
														else if (homePageName.trim().equalsIgnoreCase("AlarmViewer"))
														{
															url_for_home = "/final/monitor/EgAlarms.jsp";
														}
														else
														{
															url_for_home = "/final/servlet/com.eg.EgMonitorController?monCmd=dashboard";
														}
													}
													else
													{
														url_for_home = "/final/servlet/com.eg.EgMonitorController?monCmd=dashboard";
													}
													if (monHomePage != null && homePageName != null && (monHomePage.equalsIgnoreCase(homePageName) || currentMonitorHomePageURL.equalsIgnoreCase(url_for_home)))
													{
														rootObj.put("homePageName", homePageName);
														rootObj.put("homePageDisplayName", homePageDisplayName);
													}
													else
													{
														rootObj.put("homePageName", homePageName);
														rootObj.put("homePageDisplayName", homePageDisplayName);
													}
												}
											}
										}
										hiddenParams.put("$_monitorHomePage", tempMonHomePage);
									}
								}
								else if (userRole1.getAdminPerm() > 0 || userRole1.getMonitorPerm() > 0)
								{
									if (userRole1.getMonitorPerm() > 0)
									{
										screenLabels.put("admin.profile.Monitor Home Page", _mapping.getTextDescription("admin.profile.Monitor Home Page"));
										String monHomePage = selecteduser.getMonitorHomePage();
										if(monHomePage!=null && monHomePage.equals("Monitor Dashboard"))
										{
											monHomePage = "Infrastructure Overview";
										}
										else if(monHomePage.equals("Virtual"))
											monHomePage = "Virtual Dashboard";
										else if(monHomePage.equals("Alarm History"))
											monHomePage = "History of Alarms";
										else if(monHomePage.equals("Acknowledgement History"))
											monHomePage = "History of Acknowledgements";
										else if(monHomePage.equals("Deletion History"))
											monHomePage = "History of Deletions";

										String tempMonHomePage = monHomePage;
										String currentMonitorHomePageURL = request.getParameter("currentMonitorHomePageURL");
										currentMonitorHomePageURL = (currentMonitorHomePageURL == null) ? "" : currentMonitorHomePageURL;
										currentMonitorHomePageURL = com.egurkha.util.StringUtils.replace(currentMonitorHomePageURL, "|amp|", "&");
										//String user_role_name = userRole1.getRoleName();
										String strDisable = "";
										if (user_role_name != null && (user_role_name.equals("AlarmViewer") || user_role_name.equals("SuperAlarmViewer")))
										{
											strDisable = "disabled";
										}
										rootObj.put("monitorHomeDisable",strDisable);
										ArrayList aListUserRolePerm = new ArrayList();
										ArrayList aListMonPerm = new ArrayList();
										boolean hasallcompaccess1 = userRole1.hasAllComponentAccess();
										if (!hasallcompaccess1)
										{
											EgUserPermission userPerm = EgUserPermission.getInstance();
											String[][] gg = userPerm.getMonitorDesc();
											long mon = userRole1.getMonitorPerm();
											for (int j = 0; j < gg.length; j++)
											{
												for (int k = 1; k < gg[j].length; k = +2)
												{
													long perm_long = 0;
													try
													{
														perm_long = Long.parseLong(gg[j][k]);
													} catch (Exception e)
													{
														e.printStackTrace();
													}
													if ((mon & perm_long) == perm_long)
														aListUserRolePerm.add(gg[j][k - 1].trim());
													aListMonPerm.add(gg[j][k - 1].trim());
												}
											}
										}
										if (userRole1.getRoleName().equals("AlarmViewer") || userRole1.getRoleName().equals("SuperAlarmViewer"))
										{
											tempMonHomePage = "AlarmViewer";
											rootObj.put("isAlarmViewerUser","true");
											Object monitorHomePages[] = egUI.getVariables("MONITOR_HOME_PAGE");
											List monitorHomePagesList = new LinkedList();
											if (monitorHomePages != null && monitorHomePages.length > 0)
											{
												for (int i = 0; i < monitorHomePages.length; i++)
												{
													String homePageName=(String)monitorHomePages[i];
													if (homePageName != null && homePageName.trim().length() > 0)
													{
														monhomeob.put("displayField", homePageName);
														monhomeob.put("valueField", homePageName);
														monhomear.add(monhomeob);
													}
												}
												rootObj.put("monhomearray", monhomear);
											}
											rootObj.put("monHomePage", "Current Alarms");
											screenLabels.put("admin.profile.Current Alarms", _mapping.getTextDescription("admin.profile.Current Alarms"));
										}
										else
										{
											Object monitorHomePages[] = egUI.getVariables("MONITOR_HOME_PAGE");
											List monitorHomePagesList = new LinkedList();
											if (monitorHomePages != null && monitorHomePages.length > 0)
											{
												for (int i = 0; i < monitorHomePages.length; i++)
												{
													String homePageName = (String) monitorHomePages[i];
													if (homePageName != null && homePageName.trim().length() > 0)
													{
														if(EgInstallInfo.isSuperManager)
														{
															if(homePageName.equals("Live Graph") || homePageName.equals("Quick Insight") || 
																homePageName.equals("Virtual Dashboard") || homePageName.equals("My Dashboard"))
															{
																continue;
															}
														}
														//monitorHomePagesList.add(homePageName);
														if (!hasallcompaccess1)
														{
															if (aListMonPerm != null && aListMonPerm.size() > 0 && aListMonPerm.contains(homePageName.trim()))
															{
																if (aListUserRolePerm != null && aListUserRolePerm.size() > 0 && aListUserRolePerm.contains(homePageName))
																{
																	monitorHomePagesList.add(homePageName);
																	monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
																}
															}
															else
															{
																monitorHomePagesList.add(homePageName);
																monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
															}
														}
														else
														{
															monitorHomePagesList.add(homePageName);
															monitorHomePagesList.add(_mapping.getTextDescription("monitor.menu." + homePageName));
														}
													}
												}
												if (!EgInstallInfo.isAggregationSupported())
												{
													//monitorHomePagesList.remove("Aggregates");
													int aggIndex = monitorHomePagesList.indexOf("Aggregates");
													if (aggIndex >= 0)
													{
														monitorHomePagesList.remove(aggIndex + 1);
														monitorHomePagesList.remove(aggIndex);
													}
												}
												// for remove Service Health if its not enabled
												// By Saravanan.A on 28-2-2012
												if (!isEnableServiceHealth)
												{
													int shIndex = monitorHomePagesList.indexOf("Service Health");
													if (shIndex >= 0)
													{
														monitorHomePagesList.remove(shIndex + 1);
														monitorHomePagesList.remove(shIndex);
													}
												}
												//--end--

												if (!isEnableEndUserDashboard)
												{
													int shIndex = monitorHomePagesList.indexOf("End User Dashboard");
													if (shIndex >= 0)
													{
														monitorHomePagesList.remove(shIndex + 1);
														monitorHomePagesList.remove(shIndex);
													}
												}

												if (monitorHomePagesList != null && monitorHomePagesList.size() > 0)
												{
													EgSorter esort = new EgSorter(monitorHomePagesList, 2);
													monitorHomePagesList = esort.sort(2, "String", "asc");
												}
											}
											if (monitorHomePagesList != null && monitorHomePagesList.size() > 0)
											{
												for (int i = 0; i < monitorHomePagesList.size(); i += 2)
												{
													String homePageName = (String) monitorHomePagesList.get(i);
													String homePageDisplayName = (String) monitorHomePagesList.get(i + 1);
													String url_for_home = "";
													if (homePageName != null && homePageName.trim().length() > 0)
													{
														String monitor_home_page_value = egUI.getValue("MONITOR_HOME_PAGE", homePageName);
														if (monitor_home_page_value != null && monitor_home_page_value.trim().length() > 0)
														{
															url_for_home = monitor_home_page_value;
														}
														else if (homePageName.trim().equalsIgnoreCase("AlarmViewer"))
														{
															url_for_home = "/final/monitor/EgAlarms.jsp";
														}
														else
														{
															url_for_home = "/final/servlet/com.eg.EgMonitorController?monCmd=dashboard";
														}
													}
													else
													{
														url_for_home = "/final/servlet/com.eg.EgMonitorController?monCmd=dashboard";
													}
													if (monHomePage != null && homePageName != null && (monHomePage.equalsIgnoreCase(homePageName) || currentMonitorHomePageURL.equalsIgnoreCase(url_for_home)))
													{
														rootObj.put("monHomePage",homePageDisplayName);
													}
													else
													{
														monhomeob = new JSONObject();
														monhomeob.put("displayField", homePageDisplayName);
														monhomeob.put("valueField", homePageName);
														monhomear.add(monhomeob);
													}
												}
												rootObj.put("monhomearray", monhomear);
											}
										}
										hiddenParams.put("$_monitorHomePage", tempMonHomePage);
										
										OneClickDashboardModel oneClickModel=new OneClickDashboardModel(uname);
										JSONArray monDomainsOpt=oneClickModel.getMonitoringDomains();
										if(monDomainsOpt!=null && monDomainsOpt.isEmpty())
										{
											JSONObject jOpt=new JSONObject();
											jOpt.put("displayField","Not Applicable");
											jOpt.put("valueField","-1");
											monDomainsOpt.add(jOpt);
										}
										IniFile customIniObj=new IniFile(EgInstallInfo.getInstallDir()+ "/manager/config/eg_customdashboard.ini");
										String selectedMonitorDomain=customIniObj.getValue("USER_DOMAIN_MAPPING",uname);
										if(StringUtils.isNull(selectedMonitorDomain))
										{
											if(monDomainsOpt!=null && !monDomainsOpt.isEmpty())
											{
												JSONObject jOpt=(JSONObject)monDomainsOpt.get(0);
												selectedMonitorDomain=(String)jOpt.get("valueField");
											}
											else
											{
												selectedMonitorDomain="-1";
											}
										}
										rootObj.put("selectedMonitorDomain",selectedMonitorDomain);
										rootObj.put("monitoringDomains",monDomainsOpt);

										String monitorHomePageSelection = null;
										rs_uname = null;
										try
										{
											str_query = "SELECT monitor_home_option,monitor_home FROM user_pref where USER_ID='" + uname + "'";
											rs_uname = egDb.SelectExec(str_query);
											while(rs_uname.next())
											{
												monitorHomePageSelection = rs_uname.getString(1);
												monHomePage = rs_uname.getString(2);
											}
										}
										catch (Exception e)
										{
											e.printStackTrace();
										}
										rootObj.put("monitorHomePageSelection",monitorHomePageSelection);
										if(monitorHomePageSelection != null)
										{
											if(monHomePage == null || monHomePage.equalsIgnoreCase("Monitor Dashboard") || monHomePage.equalsIgnoreCase("AlarmViewer"))
											{
												monHomePage = "Infrastructure Overview";
											}
											rootObj.put("monHomePage",monHomePage);
										}
										rootObj.put("td",new Boolean(td));
										rootObj.put("hasAllCompAccess",new Boolean(hasallcompaccess));
									}
								}

								if (!hasallcompaccess)
								{
									JSONObject generalSettings = new JSONObject();
									String interestedDomains = eguuid.getValue("COMPONENT_TYPE_PREFERENCES",uname);
									ArrayList interestedDomainList = new ArrayList();
									if (interestedDomains != null && interestedDomains.trim().length() > 0)
									{
										interestedDomainList = StringUtils.egTokenizer(interestedDomains,",",true,true,true);
									}
									JSONArray tmpList = new JSONArray();
									JSONObject tmpObject = new JSONObject();
									String userLanguage = _user.getLanguage();
									if (userLanguage == null)
										userLanguage = iniUI.getDefaultLanguage();

									MappingNameSorter sorter = new MappingNameSorter(userLanguage);
									interestedDomainList = sorter.getSortedCompTypeList(interestedDomainList);
									
									JSONObject availSrvrObj = new JSONObject();
									JSONArray discSrvrArray = new JSONArray();
									int colCount = 0;

									for (int i = 0;i<interestedDomainList.size();i++)
									{
										colCount++;
										EgName nameObj = (EgName)interestedDomainList.get(i);
										String tmpVal = nameObj.getActualName();
										String tmpDis = nameObj.getLocalName();
										
										if (colCount == 3)
										{
											tmpObject.put("col_"+colCount , tmpDis);
											tmpObject.put("valueField_"+colCount , tmpVal);
											tmpList.add(tmpObject);
											tmpObject = new JSONObject();
											colCount = 0;
										}
										else
										{
											tmpObject.put("col_"+colCount , tmpDis);
											tmpObject.put("valueField_"+colCount , tmpVal);
										}
									}
									if (colCount == 1)
									{
										tmpObject.put("col_2","");
										tmpObject.put("col_3","");
										tmpObject.put("valueField_2" , "");
										tmpObject.put("valueField_3" , "");
										tmpList.add(tmpObject);
									}
									if (colCount == 2)
									{
										tmpObject.put("col_3","");
										tmpObject.put("valueField_3" , "");
										tmpList.add(tmpObject);
									}
									generalSettings.put("configuredServersList",tmpList);
									generalSettings.put("configuredServersCount",interestedDomainList.size());
									rootObj.put("generalSettings",generalSettings);

									boolean isAlarmViewer = (str_urole.equals("AlarmViewer") || str_urole.equals("SuperAlarmViewer"));
									if(str_urole !=null)
									{
										EgUserRole userRoleName = EgUserRole.getRoleObject(str_urole,getAllRoles);
										boolean hasReporterTab  = userRoleName.hasAnyReporterRole(EgUserPermission.REPORTER);
										boolean  hasMemReporterChek = memCheck.isReportEnabled();
									}

									ResultSet rs_uname1 = null;
									boolean b_state1 = false;
									Vector users1    = new Vector();
									ArrayList allrolenamesarr1 = null;
									String str_conn1 = "";
									String str_query1 = "";
									ausers.clear();
									try
									{
										str_query1 = "SELECT RELATED_USERS FROM user_relation where USER_ID='" + uname + "'";
										rs_uname1 = egDb.SelectExec(str_query1);
										b_state1 = egDb.getState();

										while (rs_uname1.next())
										{
											String str_utype1 = rs_uname1.getString(1);
											ausers.add(str_utype1);
											if (str_utype1 != null && str_utype1.indexOf("~,~") != -1)
											{
												userStr = userStr + str_utype1 + "~,~";
											}
											else if (str_utype1 != null && str_utype1.indexOf(",") != -1)
											{
												String tempAUser = str_utype1.substring(0,str_utype1.indexOf(","));
												if (users.contains(tempAUser))
												{
													str_utype1 = StringUtils.replace(str_utype1,",","~,~");
													userStr = userStr + str_utype1 + "~,~";
												}
												else
												{
													userStr = userStr + str_utype1 + "~,~";
												}
											}
											else
											{
												userStr = userStr + str_utype1 + "~,~";
											}
										}
										if (userStr != null && userStr.endsWith("~,~"))
											userStr = userStr.substring(0, userStr.length() - 3);
									}
									catch (Exception e1)
									{
										e1.printStackTrace();
									}
									if (users.contains(uname))
									{
										users.remove(uname);
									}

									JSONArray availusersArr = new JSONArray();
									String realUser = "";
									String dispData = "";
									for (int i = 0; i < users.size(); i++)
									{
										JSONObject tmpUserObj1 = new JSONObject();
										String temp_user = (String) users.get(i);
										if (temp_user.indexOf("(Group)") != -1)
										{
											int idx = temp_user.indexOf("/");
											int nextIdx = temp_user.indexOf("(Group)");
											String strtempuname = temp_user.substring(0,idx);
											strtempuname = strtempuname + "/Grp/";
											String strtempuname_A = temp_user.substring(idx + 1 ,nextIdx);
											realUser = strtempuname + strtempuname_A;
											realUser = realUser.trim();
										}
										else
										{
											realUser = temp_user;
										}
										dispData = realUser;
										if (dispData.indexOf("/Grp/") != -1)
										{
											String grpDelimiter = "/Grp/";
											int idx = dispData.indexOf(grpDelimiter);
											String str_uname_A = dispData.substring(0,idx);
											int nextIdx = idx + grpDelimiter.length();
											String str_uname_B = dispData.substring(nextIdx);
											dispData = str_uname_A + "/" + str_uname_B + " (Group)";
										}
										else if (dispData.startsWith("samlsso/"))
										{
											String tmp = dispData;
											int idx = tmp.indexOf("/");
											dispData = tmp.substring(idx+1);
											dispData = dispData + " (SAML)";
										}

										dispData = StringUtils.replace(dispData,"<","&lt;");
										dispData = StringUtils.replace(dispData,">","&gt;");
										String tmpData = egUI.getValue("DBUSER_USER_MAP",dispData);
										if (tmpData != null && tmpData.length() > 0)
										{
											dispData = tmpData;
										}
										tmpUserObj1.put("displayField",dispData);
										tmpUserObj1.put("valueField",realUser);
										availusersArr.add(tmpUserObj1);
									}
									usertemp = userStr;
									users.clear();
									rootObj.put("AutoAssociated",new Boolean(false));
									hiddenFields.put("prevautoassociated",new Boolean(false));
									if (userStr.length() > 0)
									{
										rootObj.put("AutoAssociated",new Boolean(true));
										hiddenFields.put("prevautoassociated",new Boolean(true));
									}
									rootObj.put("userStr",userStr);
									rootObj.put("availusers",availusersArr);
									hiddenFields.put("prevassousers",userStr);
									userStr = ""; //resets its length into 0
								}
							}

							JSONArray timeLineReports = new JSONArray();
							//User Allowed Maximun timeline for Reports
							Vector v_timeOption = new Vector();
							String[] timeLiineOpt = new String[] {"1 day", "2 days", "3 days", "4 days",
								"5 days", "6 days","1 week","2 weeks","3 weeks","4 weeks","1 month"};
							v_timeOption.addAll(Arrays.asList(timeLiineOpt));

							String optTime = request.getParameter("timeOpt");
							if(rptTimeline != null && rptTimeline.length()>0) {
								optTime = rptTimeline;
							}
							if (optTime == null || optTime.equals("") || optTime.equalsIgnoreCase("NULL"))
							{
								if(v_timeOption != null) {
									optTime = (String)v_timeOption.get(v_timeOption.size()-1);
								}
							}
							EgMemCheck memCheck = new EgMemCheck();
							if(str_urole !=null)
							{
								EgUserRole userRoleName = EgUserRole.getRoleObject(str_urole,getAllRoles);
								boolean hasReporterTab  = userRoleName.hasAnyReporterRole(EgUserPermission.REPORTER);
								boolean hasMemReporterChek = memCheck.isReportEnabled();

								rootObj.put("hasReporterTab",new Boolean(hasReporterTab));
								rootObj.put("hasMemReporterChek",new Boolean(hasMemReporterChek));
								if(hasReporterTab == true && hasMemReporterChek == true)
								{
									JSONObject tmLineObj = new JSONObject();
									for(int n=0;n<v_timeOption.size();n++)
									{
										tmLineObj = new JSONObject();
										String s=(String)v_timeOption.get(n);
										if(optTime!=null && optTime.equalsIgnoreCase(s))
										{
											tmLineObj.put("displayField",optTime);
											tmLineObj.put("valueField",optTime);
											timeLineReports.add(tmLineObj);
											rootObj.put("chgTimeOptSeleted",optTime);
										}
										else
										{
											tmLineObj.put("displayField",_mapping.getTextDescription("admin.common."+s));
											tmLineObj.put("valueField",s);
											timeLineReports.add(tmLineObj);
										}
									}

									if(optTime!=null && optTime.equalsIgnoreCase("-1"))
									{
										tmLineObj = new JSONObject();
										tmLineObj.put("displayField",_mapping.getTextDescription("admin.common.Unlimited"));
										tmLineObj.put("valueField","-1");
										timeLineReports.add(tmLineObj);
										rootObj.put("chgTimeOptSeleted","-1");
									}
									else
									{
										tmLineObj = new JSONObject();
										tmLineObj.put("displayField",_mapping.getTextDescription("admin.common.Unlimited"));
										tmLineObj.put("valueField","-1");
										timeLineReports.add(tmLineObj);
									}
									rootObj.put("chgTimeOpt",timeLineReports);
								}
							}

							// Login Home
							JSONArray LogoArr = new JSONArray();
							JSONObject logoObj = new JSONObject();
							logoObj.put("displayField",_mapping.getTextDescription("admin.common.Default"));
							logoObj.put("valueField","hide");
							LogoArr.add(logoObj);

							logoObj = new JSONObject();
							logoObj.put("displayField",_mapping.getTextDescription("admin.common.Custom"));
							logoObj.put("valueField","show");
							LogoArr.add(logoObj);
							rootObj.put("logoArr",LogoArr);

							
							rootObj.put("selectedLoginPageLogo","hide");
							if (loginLogo.equals("custom"))
							{
								rootObj.put("selectedLoginPageLogo","show");
							}

							// Admin / Monitor
							rootObj.put("selectedAdminPageLogo","hide");
							if (monitorLogo.equals("custom"))
							{
								rootObj.put("selectedAdminPageLogo","show");
							}

							JSONObject otherModules = new JSONObject();
							if(str_urole!=null && !str_urole.equals("AlarmViewer") && !str_urole.equals("SuperAlarmViewer"))
							{
								rootObj.put("logoCheck",new Boolean(true));
								if (defaultLogo.equalsIgnoreCase("different"))
								{
									rootObj.put("logoCheck",new Boolean(false));
								}

								boolean configPres=false;
								boolean isConfigEnabled1= EgInstallInfo.isConfigSupported;
								rootObj.put("isConfigSupported",new Boolean(false));
								if(isConfigEnabled1 && str_urole!=null && !str_urole.equals("MonitorNoConfig") && !str_urole.equals("SupermonitorNoConfig"))
								{
									configPres = true;
									rootObj.put("isConfigSupported",new Boolean(true));
								}

								// Reporter
								rootObj.put("selectedRepPageLogo","hide");
								if (reporterLogo.equals("custom"))
								{
									rootObj.put("selectedRepPageLogo","show");
								}

								if(configPres)
								{
									rootObj.put("selectedConfigPageLogo","hide");
									if (configLogo.equals("custom"))
									{
										rootObj.put("selectedConfigPageLogo","show");
									}
								}
							}
						}
					}
				}
			} // check all users
			String unameCached = request.getParameter("username");
			unameCached = com.egurkha.util.StringUtils.decodeSecurityChar(unameCached);
			if (unameCached != null && !unameCached.equals("-1"))
			{
				if (unameCached.indexOf("(Group)") != -1)
				{
					int idx = unameCached.indexOf("/");
					int nextIdx = unameCached.indexOf("(Group)");
					String strtempuname = unameCached.substring(0,idx);
					strtempuname = strtempuname + "/Grp/";
					String strtempuname_A = unameCached.substring(idx + 1 ,nextIdx);
					String unameCached2 = strtempuname + strtempuname_A;
					unameCached2 = unameCached2.trim();
					rootObj.put(unameCached,unameCached2);
				}
				else
				{
					rootObj.put(unameCached,unameCached);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				egDb.releaseConnection(false);
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
			}
		}
	}
	EgDbAdapterTypeUI.releaseObject(egDb);
	s_flag = request.getParameter("flag");
	v_sites.removeAllElements();
	v_siteslist.removeAllElements();
	a_user_segs.clear();
	s_validtill = "";
	s_validdate = "";
	b_recordpresent = false; 

	for (int i = 0; i <vecesc.size(); i++)
	{
		if (escextra == null || escextra.equals(""))
		{
			escextra = (String) vecesc.get(i);
		}
		else
		{
			escextra = escextra + " # " + (String) vecesc.get(i);
		}
	}

	if (type1 != null && type1.equals("checked"))
		t1 = "high";
	else
		t1 = "-";

	if (type2 != null && type2.equals("checked"))
		t2 = "medium";
	else
		t2 = "-";

	if (type3 != null && type3.equals("checked"))
		t3 = "low";
	else
		t3 = "-";

	if (!(pref1 == null) && pref1.equals("checked"))
		p1 = "New";
	else if (pref2 != null && pref2.equals("checked"))
		p1 = "Complete";

	if (mode1 != null && mode1.equals("checked"))
		m1 = "HTML";
	else if (mode2 != null && mode2.equals("checked"))
		m1 = "TEXT";

	if (remotecontrol1 != null && remotecontrol1.equals("checked"))
		rc1 = "Enabled";
	else if (remotecontrol2 != null && remotecontrol2.equals("checked"))
		rc1 = "Disabled";

	if (alarm_h != null && alarm_h.equals("checked"))
	{
		//ala1 = "Critical";
		ala1="True";
	}
	else
	{
		//ala1 = "-";
		ala1="False";
	}
	if (alarm_m != null && alarm_m.equals("checked"))
	{
		//ala2 = "Major";
		ala2="True";
	}
	else
	{
		//ala2 = "-";
		ala2="False";
	}
	if (alarm_l != null && alarm_l.equals("checked"))
	{
		ala3="True";
		//ala3 = "Minor";
	}
	else
	{
		//ala3 = "-";
		ala3="False";
	}

	if(tomailStr==null || tomailStr.trim().equals("null") || tomailStr.trim().equals(""))
	{
		tomailStr="-";
	}

	if(ccmailStr==null || ccmailStr.trim().equals("null") || ccmailStr.trim().equals(""))
	{
		ccmailStr="-";
	}

	if(bccmailStr==null || bccmailStr.trim().equals("null") || bccmailStr.trim().equals(""))
	{
		bccmailStr="-";
	}

	if(escMail==null || escMail.equals("null") || escMail.equals(""))
	{
		escMail="-";
	}

	if(escextra==null || escextra.equals("null") || escextra.equals(""))
	{
		escextra="-";
	}

	//previous = "User Role|" + e_role + " # Password|" + prevpwd + " # Valid Till|" + sdate +"#";
	if(e_role!=null && !e_role.equals("null") && !e_role.equals("") && e_role.equals("limitedadmin") || e_role.equals("config"))
	{
		previous = "User Role|" + e_role + " # Password|" + prevpwd + " # Valid Till|" + sdate +"#"+" Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement+ " # Monitor Home Page|"+str_monitorhomepage;
	}
	else
	{
		previous = "User Role|" + e_role + " # Password|" + prevpwd + " # Valid Till|" + sdate +"#"+"  Alarms| critical " + t1 + ", major " + t2 + ", minor " + t3 + " # To|" + StringUtils.replaceCharacter(tomailStr, ':', '|') + " # Cc|" + StringUtils.replaceCharacter(ccmailStr, ':', '|') + " # Bcc|" + StringUtils.replaceCharacter(bccmailStr, ':', '|');
		if(escMail!=null && !escMail.equals("null") && !escMail.equals(""))
		{
			previous =previous+" # ESCMail|"+StringUtils.replaceCharacter(escMail,':','|'); 
		}
		if(escextra!=null && !escextra.equals("null") && !escextra.equals(""))
		{
			previous =previous+ " # ESCMail|" + StringUtils.replaceCharacter(escextra, ':', '|');
		}
		previous =previous+" # Notification Type|" + p1 + " # MsgMode|" + m1 + " # Remote Control|" + rc1 +"#"+"  Alarm Display| critical " + ala1 + ", major " + ala2 + ", minor " + ala3+" #"+" Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement+" #"+" Monitor Home Page|"+str_monitorhomepage+"#";
	}
	//previous =previous+"  Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement;

	if(e_role!=null && !e_role.equals("null") && !e_role.equals("") && e_role.equals("limitedadmin") || e_role.equals("config"))
	{
		previous1 = "User Role|" + e_role + " # Password|" + prevpwd + " # Valid Till|" + sdate +"#"+" Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement+" # Monitor Home Page|"+str_monitorhomepage;
	}
	else
	{
		previous1 = "User Role|" + e_role + " # Password|" + prevpwd + " # Valid Till|" + sdate +"#"+"  Alarms| critical " + t1 + ", major " + t2 + ", minor " + t3 + " # To" + StringUtils.replaceCharacter(tomailStr, ':', '|') + " # Cc|" + StringUtils.replaceCharacter(ccmailStr, ':', '|') + " # Bcc|"+ StringUtils.replaceCharacter(bccmailStr, ':', '|');
		if(escMail!=null && !escMail.equals("null") && !escMail.equals(""))
		{
			previous1 =previous1+ " # ESC Level 1|" + StringUtils.replaceCharacter(escMail, ':', '|') ;
		}
		if(escextra!=null && !escextra.equals("null") && !escextra.equals(""))
		{
			previous1 =previous1+ " # ESC Level 2|" + StringUtils.replaceCharacter(escextra, ':', '|');
		}
		// previous1 =previous1+ " # Notification Type|" + p1 + " # MsgMode|" + m1 + " # Remote Control|" + rc1 + " # Alarm Display| critical " + ala1 + ", major " + ala2 + ", minor " + ala3 + " # Other Users|" + usertemp+"#"+"  Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement;
		previous1 =previous1+" # Notification Type|" + p1 + " # MsgMode|" + m1 + " # Remote Control|" + rc1 +"#"+"  Alarm Display| critical " + ala1 + ", major " + ala2 + ", minor " + ala3+" #"+" Allow Alaram Delete|"+deleteAlarm+" # Allow Alaram Acknowledegement|"+deleteAcknowledgement+" #"+" Monitor Home Page|"+str_monitorhomepage;
	}

	String previousRemoteControlValue = (remotecontrol1 !=null && remotecontrol1.equalsIgnoreCase("checked"))?"true":"false";

	hiddenFields.put("strUserRole",str_urole);
	hiddenFields.put("str_utype",str_utype);
	hiddenFields.put("currentdate",s_current_date);
	hiddenFields.put("startHr","00");
	hiddenFields.put("startMin","00");
	hiddenFields.put("endHr","00");
	hiddenFields.put("endMin","00");
	hiddenFields.put("prevDomain",prevDomain);
	//hiddenFields.put("username1",usersexist);
	hiddenFields.put("size",size);
	hiddenFields.put("previousremotecontrol",previousRemoteControlValue);
	hiddenFields.put("previousmailsenders",selectedMailSender);
	hiddenFields.put("currentmailsenders",selectedMailSender);
	hiddenFields.put("previoustimezone",selectedTimeZone);
	hiddenFields.put("currenttimezone",selectedTimeZone);
	hiddenFields.put("previous",previous);
	hiddenFields.put("previous1",previous1);
	rootObj.put("hiddenFields",hiddenFields);

	JSONArray daysPickerArr = new JSONArray();
	JSONObject daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Sunday"));
	daysPickerObj.put("valueField","Sun");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Monday"));
	daysPickerObj.put("valueField","Mon");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Tuesday"));
	daysPickerObj.put("valueField","Tue");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Wednesday"));
	daysPickerObj.put("valueField","Wed");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Thursday"));
	daysPickerObj.put("valueField","Thu");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Friday"));
	daysPickerObj.put("valueField","Fri");
	daysPickerArr.add(daysPickerObj);

	daysPickerObj = new JSONObject();
	daysPickerObj.put("displayField",_mapping.getTextDescription("admin.common.Saturday"));
	daysPickerObj.put("valueField","Sat");
	daysPickerArr.add(daysPickerObj);
	rootObj.put("daysPicker",daysPickerArr);

	JSONArray shiftsHourPickerArr = new JSONArray();
	for (int i=0;i<24;i++)
	{
		JSONObject shiftsPickerObj = new JSONObject();
		String num = i+"";
		if (i < 10)
		{
			num = "0"+num;
		}
		shiftsPickerObj.put("displayField",num);
		shiftsPickerObj.put("valueField",num);
		shiftsHourPickerArr.add(shiftsPickerObj);
	}
	rootObj.put("shiftsPickerHour",shiftsHourPickerArr);
	JSONArray shiftsMiPickerArr = new JSONArray();
	for (int i=0;i<60;i++)
	{
		JSONObject shiftsPickerObj = new JSONObject();
		String num = i+"";
		if (i < 10)
		{
			num = "0"+num;
		}
		shiftsPickerObj.put("displayField",num);
		shiftsPickerObj.put("valueField",num);
		shiftsMiPickerArr.add(shiftsPickerObj);
	}
	rootObj.put("shiftsPickerMi",shiftsMiPickerArr);

	/* code for 2fa starts here */

	IniFile egMFAIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mfa.ini");

	String is2FAEnabled = egMFAIniFile.getValue("2FA_SETTINGS","Is2FAEnabled");

	if (is2FAEnabled != null && (is2FAEnabled.equalsIgnoreCase("yes") || is2FAEnabled.equalsIgnoreCase("true")))
	{
		String twoFAOptionFlag = egMFAIniFile.getValue("2FA_SETTINGS","TwoFAOptionFlag");

		if (twoFAOptionFlag != null && twoFAOptionFlag.equalsIgnoreCase("c"))
		{
			rootObj.put("is2FACFlagEnabled","yes");
		}
		else
		{
			rootObj.put("is2FACFlagEnabled","no");
		}
	}

	/* code for 2fa ends here */

	String userName = request.getParameter("username");
	userName = com.egurkha.util.StringUtils.decodeSecurityChar(userName);
	String sess_userid = (String)session.getAttribute("sess_userid");

	JSONArray jArray = new JSONArray();
	JSONArray jMainArray = new JSONArray();

	if (hasAllComponentAccess)
	{
		String superOrgName = "";
		boolean isSuperOrg = egUuidInfo.isSuperOrg(userName);
		boolean isOrg = egUuidInfo.isOrg(userName);
		if (isSuperOrg)
		{
			superOrgName = userName;
		}
		else if (isOrg)
		{
			superOrgName = egUuidInfo.getSuperOU(userName);
		}
		else
		{
			superOrgName = egUuidInfo.getSuperOU(userName);
		}

		jArray = egUuidInfo.buildTreeJson(superOrgName,true);
		JSONObject obj = new JSONObject();
		obj.put("id",superOrgName);
		if (superOrgName.equalsIgnoreCase("egenterprise"))
		{
			obj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
		}
		else
		{
			obj.put("text",superOrgName);
		}
		obj.put("name",superOrgName);
		obj.put("uvalidtill",egUuidInfo.getExpiryDateForOU(superOrgName));
		obj.put("expanded", true);
		obj.put("iconCls", "iconDomain");
		obj.put("children", jArray);
		jMainArray.add(obj);
		rootObj.put("organization", jMainArray);
	}
	else
	{
		String userStr = _user.getLoginID();
		String ouName = "";
		boolean isSuperOrg = egUuidInfo.isSuperOrg(userStr);
		boolean isOrg = egUuidInfo.isOrg(userStr);
		if (isSuperOrg)
		{
			ouName = userStr;
		}
		else if (isOrg)
		{
			ouName = userStr;
		}
		else
		{
			ouName = egUuidInfo.getDirectDependentOU(userStr);
		}

		jArray = egUuidInfo.buildTreeJson(ouName,true);
		JSONObject obj = new JSONObject();
		obj.put("id",ouName);
		if (ouName.equalsIgnoreCase("egenterprise"))
		{
			obj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
		}
		else
		{
			obj.put("text",ouName);
		}
		obj.put("name",ouName);
		obj.put("uvalidtill",egUuidInfo.getExpiryDateForOU(ouName));
		obj.put("expanded", true);
		obj.put("iconCls", "iconOtherUsers");
		obj.put("children", jArray);
		jMainArray.add(obj);
		rootObj.put("organization", jMainArray);
	}
	
	boolean isSelectedUserSuperOrg = egUuidInfo.isSuperOrg(userName);
	boolean isSelectedUserOrg = egUuidInfo.isOrg(userName);

	if (isSelectedUserSuperOrg)
	{
		rootObj.put("hideOrganization",true);
		rootObj.put("userModel","Organization");
	}
	else
	{
		if (isSelectedUserOrg)
		{
			rootObj.put("userModel","SubOrganization");
		}
		else
		{
			rootObj.put("userModel","User");
		}
		rootObj.put("hideOrganization",false);
		String org = egUuidInfo.getDirectDependentOU(userName);
		rootObj.put("organizationValue",org);
	}
	
	String usrType = request.getParameter("usertype");

	if (!isSelectedUserOrg)
	{
		boolean hasOURole = egUuidInfo.hasOURole(userName);
		rootObj.put("isShareRole",hasOURole);

		if (usrType != null)
		{
			boolean isShareRole = false;
			String org = egUuidInfo.getDirectDependentOU(userName);
			if (org != null && !org.equalsIgnoreCase("egenterprise"))
			{
				isShareRole = egUuidInfo.isShareRole(usrType,getAllRoles);
			}
			rootObj.put("isShareRole",isShareRole);
		}
	}

	String ShareCompsAcrossOU = egMgrMisc.getValue("MISC_ARGS","ShareCompsAcrossOU");
	if (ShareCompsAcrossOU != null && ShareCompsAcrossOU.trim().length() > 0)
	{
		rootObj.put("ShareCompsAcrossOU",ShareCompsAcrossOU);
	}
	else
	{
		rootObj.put("ShareCompsAcrossOU","false");
	}

	/* To show organization type for egenterprise monitor user - Starts */
	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean shareNickAcrossOU = EgUuidInfo.shareNickAcrossOU();
	boolean showOrgType = false;
	String usr_dependentOU = egUuidInfo.getDirectDependentOU(userName);
	if (isMspModel && shareNickAcrossOU && ((egUuidInfo.isUser(userName) && usr_dependentOU != null && usr_dependentOU.equalsIgnoreCase("egenterprise")) || (egUuidInfo.isSuperOrg(userName))))
	{
		showOrgType = true;
	}
	rootObj.put("showOrgType",showOrgType);

	/* To show organization type for egenterprise monitor user - Ends */
	
	//if(request.getQueryString() !=null )
	//{
	//	session.setAttribute("adminLastAccessedURL","/final/admin/EgChangeUserProfile.jsp?"+request.getQueryString());
	//}
	out.println(rootObj.toString());
%>





