<%@ include file = "ErReporterTracker.jsp" %>
<%@ page import = "com.eg.EgDateInfo" %>
<%@ page import = "egurkha.reporter.*" %>
<%@ page import = "com.eg.EgGroupInfo" %>
<%@ page import = "com.eg.EgDiscInfo" %>
<%@ page import = "com.eg.EgTopoInfo" %>
<%@ page import = "com.eg.EgServicesInfo" %>
<%@ page import = "com.eg.EgDbInfo" %>
<%@ page import = "com.eg.EgTablesInfo" %>
<%@ page import = "com.eg.EgTesterInfo" %>
<%@ page import = "com.eg.EgURLEncoder" %>
<%@ page import = "com.eg.EgURLDecoder" %>
<%@ page import = "com.egurkha.util.DateTimeTokenizer" %>
<%@ page import = "com.egurkha.util.DateUtil" %>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.EgMappingInfo" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.egurkha.pdfmaker.*" %>
<%@ page import = "com.eg.EgConfigInfo"%>
<%@ page import = "java.util.ListIterator"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import ="com.egurkha.util.StringUtils"%>
<%@ page import = "com.eg.EgTestInfo"%>
<%@ page import = "com.eg.MappingNameSorter"%>
<%@ page import = "com.eg.EgName" %>
<%@ page import = "java.util.Date" %>


<%@ taglib prefix = "egui" uri = "../WEB-INF/eg-taglib.tld" %>
<%@ page language = "java" contentType = "text/html; charset=UTF-8" pageEncoding = "UTF-8" %>

<%
	String titleToDisplay=request.getParameter("er_RmDispName");
	String serverTable_view = request.getParameter("serverTable_view");
	if(serverTable_view == null)
		serverTable_view="summary";
	boolean bottleneck = true;
	int cnt=0;
	boolean isBasedCpu=false;
	boolean isBasedMemory=false;
	boolean hasAllComponentAccess = false;
	EgUserRole userRole    = thisuser.getUserRole();
	hasAllComponentAccess = userRole.hasAllComponentAccess();
	String bottleneckField = "";
	JSONObject rootJson = new JSONObject();
	JSONObject selectedObj = new JSONObject();
	JSONObject hiddens = new JSONObject();
	JSONObject selectionDetails = new JSONObject();
	JSONObject screenLabels = new JSONObject();
	JSONObject backgroundResultObj = new JSONObject();
	JSONObject resultsObj = new JSONObject();
	String skinColor = "";
	skinColor = thisuser.getReporterSkin();

	//Back Button - Start
	String bggroundStr = (String)request.getAttribute("bggroundStr");
	String status = (String)request.getAttribute("status");	
	HashMap backreqMap = (HashMap)session.getAttribute("backQuery");
	String backQnumber = request.getParameter("backQnumber");
	String servlet2 = request.getParameter("backServletName");
	String er_option = request.getParameter("er_option");
	String er_site = request.getParameter("er_site");
	String er_includeZones = request.getParameter("er_includezones");
	ErHelperUtils erhelputils = null;
	if( servlet2!=null && !servlet2.equals(""))
		erhelputils = new ErHelperUtils(backreqMap,backQnumber,servlet2);
	else
		erhelputils = new ErHelperUtils(backreqMap,backQnumber);
	boolean enableBack=erhelputils.isBackButtonEnable();
	String queryString="";
	String backButtonEnable = request.getParameter("back");
	rootJson.put("ID","backQnumber="+erhelputils.getBackID()+"&"+erhelputils.getQueryString());
	if(backButtonEnable != null && backButtonEnable.equalsIgnoreCase("True"))
	{
		status = (String)request.getParameter("status");
		bggroundStr = (String)request.getParameter("bggroundStr");
		request.setAttribute("VcCapacity_REPORT_RESULT", null);
	}
	String noOfDays="";
	//Back Button - End
%>

<%!
	private static final String BLANK_SPACE = " ";
	private static final String COMA = ",";
	private static final String COLON = ":";
	private static final String UTF_8 = "UTF-8";
	private static final String DD_MM_YYYY = "dd/MM/yyyy";
	private static final String DD_MM_YYYY_HH_MM_SS = DD_MM_YYYY + " HH:mm:ss";
%>

<%
	try
	{
		long t1 = System.currentTimeMillis();
		String isSubmit = request.getParameter("isSubmit");

		response.setHeader("Cache-Control","no-store");
		response.setHeader("Pragma","no-cache");
		response.setDateHeader("Expires", -1);
		
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		EgReportInfo reportInfo = new EgReportInfo("manager");
		EgTopoInfo topoInfo = new EgTopoInfo("manager");
		EgTablesInfo tablesInfo = new EgTablesInfo ("manager");
		EgTesterInfo testerInfo = new EgTesterInfo ("manager");
		UBean = new ErUserData(urs,false);
		ErUserData erdata = new ErUserData(UBean.getUserId(),false); //boolean arg given to check Ent or asplite
		User this_user = UserRegistry.getInstance().getUser(session.getId());
		com.egurkha.ini.IniUI ui = (com.egurkha.ini.IniUI)com.egurkha.ini.IniUI.getInstance();
		UserRegistry mregistry = UserRegistry.getInstance();
		User muser = mregistry.getUser(session.getId());
		EgDateInfo egDt = new EgDateInfo();
		ErUtils erUtils = new ErUtils();
		EgGroupInfo gpinfo = new EgGroupInfo();
		ErEsxVMutils erEsxUtils = new ErEsxVMutils();
		IniFile eg_report = new IniFile(EgInstallInfo.getInstallDir() +"/manager/config/eg_report.ini");
		String thisLanguage = ui.getDefaultLanguage();
		if (muser!=null)
		{
			String userLang = muser.getLanguage();
			if (userLang!=null && !userLang.equalsIgnoreCase("NULL"))
			{
				thisLanguage=userLang;
			}
		}
		EgMappingInfo intlmap = new EgMappingInfo(thisuser.getLanguage());
		String mngrIProc = new IniFile(new EgConfigInfo("manager").getDbFile()).getValue("DB_PROPERTIES","ManagerUrl");
		ErComponentsUtils compUtil = new ErComponentsUtils(thisuser.getLoginID());
		String font = ui.getFontName();
		String userid = UBean.getUserId();
		long msecsPerHour = (long) 1000 * 60 * 60;
		String uiFile = "eg_ui.ini";
		String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
		com.eg.IniFile egUI = new com.eg.IniFile(s_iniFile_dir + uiFile);
		String currentDateFormat = strUserDateFormat;
		SimpleDateFormat sd_currentDateFormat = new SimpleDateFormat(currentDateFormat + " HH:mm:ss");
		Map resultMap = (Map) session.getAttribute("CITRIX_CAPACITY_PLANNING_REPORT_RESULT");


		//Back Button - Start
		queryString = null;
		//Back Button - End
		String s_st_time  = request.getParameter("startdate");
		String s_en_time  = request.getParameter("enddate");
		String s_st_hr    = request.getParameter("starthr");
		String s_en_hr    = request.getParameter("endhr");
		String strmin     = request.getParameter("startmin");
		String enmin      = request.getParameter("endmin");
		String er_timeline = request.getParameter("er_timeline");
		String er_time     = request.getParameter("er_time");
		String s_inidate   = request.getParameter("inidate");
		String fromDash    = request.getParameter("isDash");
		String schedule_id = request.getParameter("schedule_id");
		String reqFromSchedule = request.getParameter("fromSchedule");	
		String fromScheduleModify = request.getParameter("fromScheduleModify");
		String fromFavoriteModify = request.getParameter("fromFavoriteModify");
		String favorite_id = request.getParameter("id");
		String er_favorite = request.getParameter("er_favorite");
		String divStatus = request.getParameter("divStatus");
		String srcForImg="";
		if(divStatus==null)
		{
		divStatus="none";
		}

		if(divStatus.equals("none"))
		{
			srcForImg="../images/moreoption.png";
		}
		else if(divStatus.equals("block"))
		{
			srcForImg="../images/lessoption.png";
		}
		String dispCsvStartDate = s_st_time+" "+s_st_hr+":"+strmin;
		String dispCsvEndDate = s_en_time+" "+s_en_hr+":"+enmin;
		
		String drillStartDate = s_st_time+" 00:00";
		String drillEndDate = s_en_time+" 00:00";
		EgTimeZoneConverter converterStart=null;
		EgTimeZoneConverter converterEnd=null;
		String dispDate = null;
		String comFormat = null;
		String st_dateTime="";
		String en_dateTime="";
		if(s_st_time!=null)
		{
			if(DateUtil.isDate(s_st_time,"MM/dd/yyyy"))
			{
				comFormat = "MM/dd/yyyy";
			}
			else
			{
				comFormat = currentDateFormat;
			}
			dispDate = 	DateUtil.changeDateFormat(s_st_time,comFormat,currentDateFormat);
			converterStart = new EgTimeZoneConverter(dispDate+" "+s_st_hr+":"+strmin,thisuser);
			st_dateTime=converterStart.getDateTime();
		}
		if(s_en_time!=null)
		{
			if(DateUtil.isDate(s_en_time,"MM/dd/yyyy"))
			{
				comFormat = "MM/dd/yyyy";
			}
			else
			{
				comFormat = currentDateFormat;
			}
			dispDate = 	DateUtil.changeDateFormat(s_en_time,comFormat,currentDateFormat);
			converterEnd = new EgTimeZoneConverter(dispDate+" "+s_en_hr+":"+enmin,thisuser);
			en_dateTime=converterEnd.getDateTime();
		}
		if(er_timeline!=null&&er_timeline.equals("Any"))
		{
			try {
				if(s_st_time!=null && s_en_time!=null&& currentDateFormat!=null)
				{
					SimpleDateFormat myFormat = new SimpleDateFormat(currentDateFormat);
					java.util.Date date1 = myFormat.parse(s_st_time);
					java.util.Date date2 = myFormat.parse(s_en_time);
					long diff = date2.getTime() - date1.getTime();
					int dayss= (int)( (date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24));
					if(dayss==0 || dayss==1)
						noOfDays=dayss+" day";
					else
						noOfDays=dayss+" days";
				}

			} catch (Exception e) {}
		}
		
		ErReportHelper erh = new ErReportHelper();	
		if(er_timeline == null)
		{
			String strUsrTimelines = erh.getUserTimeline(thisuser.getLoginID());
			if(strUsrTimelines.equals("-1"))
			{
				er_timeline="1 month";
			}
			else
			{
				er_timeline=strUsrTimelines;
			}
		}
		List v_site=new ArrayList();
		String datafrom = request.getParameter("er_datafrom");
		if(datafrom == null || datafrom.equals(""))
		{
			datafrom = "Component";
		}
		Vector v_component	= new Vector();
		Vector temp_component = new Vector();
		Vector v_comptype = new Vector();
		List compList = new ArrayList();
		Vector v_zones = new Vector();
		ArrayList listCompTypes =reportInfo.getComponent("CITRIX_CAPACITY_CPU_PLANNING",false);
		Vector v_componentName = new Vector();
		EgTestInfo tokInfo = new EgTestInfo("manager");
		MappingNameSorter sorter = new MappingNameSorter(thisLanguage);
		ErInfo erInfo = new ErInfo();
		String selectedComp[] = request.getParameterValues("er_component");
		String isFavorite = request.getParameter("isFavorite");
		EgCrawler crawlerBean = new EgCrawler(new IniFile(s_iniFile_dir + "eg_topology.ini"));
		String comp_type=request.getParameter("er_comptype");
		String comp_name=request.getParameter("er_component");
		String fromMenu = request.getParameter("fromMenu");
		String strcompname = "";
		Hashtable htAllGroups=erEsxUtils.getGroups(null,listCompTypes, thisuser, thisuser.getLoginID(), "Yes",true);
		ArrayList v_options = erEsxUtils.getOptions(htAllGroups);
		ArrayList aListComponentTemp = null;
		if(v_options!=null)
		{
			if(v_options.contains("Service"))
			{
				v_options.remove("Service");
			}
			if(v_options.contains("Segment"))
			{
				v_options.remove("Segment");
			}
			if(v_options.contains("Zone"))
			{
				if (er_option == null)
				{
					er_option = "Zone";
				}
			}
		}
		if (er_option == null)
			er_option = (String)v_options.get(0);

		ArrayList removeList = new ArrayList();
		JSONArray comboArray =  new JSONArray();
		JSONObject loopJsonObj = new JSONObject();
		comboArray =  new JSONArray();
		for ( int i=0; i<v_options.size();i++)
		{
			String tempStr = (String) v_options.get(i);
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common."+tempStr));
			loopJsonObj.put("valueField",tempStr);
			comboArray.add(loopJsonObj);
			if(er_option.equals(tempStr)){
				selectedObj.put("er_option",er_option);
			}
		}
		rootJson.put("anlyzeCombo",comboArray);
		if(er_option!=null && !er_option.equalsIgnoreCase("Component"))
		{
			v_site = erEsxUtils.getGroupsName(htAllGroups,er_option);
			if(er_option.equalsIgnoreCase("Zone"))
			{
				screenLabels.put("reporter.common.Zone",intlmap.getTextDescription("reporter.common.Zone"));
				ArrayList defaultZoneCompList = erEsxUtils.getComponentForGroup(htAllGroups,er_option,"--Default--");
				if(!hasAllComponentAccess)
				{
					defaultZoneCompList = null;
				}
				if(defaultZoneCompList==null || defaultZoneCompList.size()==0)
				{
					if(v_site!=null && v_site.contains("--Default--"))
					{
						v_site.remove("--Default--");
					}
				}
			}
			if(er_site==null || (er_site != null && er_site.equalsIgnoreCase("null")))
			{
				if(v_site!=null && v_site.size()>0)
				{
					er_site = (String)v_site.get(0);
				}
				else
				{
					er_site = "";
				}
			}
			comboArray =  new JSONArray();
			if (v_site!=null && v_site.size() > 0)
			{
				for (int i=0; i<v_site.size(); i++)
				{
					String tempStr = (String)v_site.get(i);
					loopJsonObj = new JSONObject();
					if(tempStr != null && tempStr.equalsIgnoreCase("--Default--"))
						loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common."+tempStr));
					else
						loopJsonObj.put("displayField",tempStr);
					loopJsonObj.put("valueField",tempStr);
					comboArray.add(loopJsonObj);
					if (tempStr.equalsIgnoreCase(er_site)){
						selectedObj.put("er_site", er_site);
					}
				}
			}
			else
			{
				loopJsonObj = new JSONObject();
				loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
				loopJsonObj.put("valueField", "-1");
				comboArray.add(loopJsonObj);
				selectedObj.put("er_site", "-1");
			}
			if(er_site!=null && er_site.length()>0)
			{
				aListComponentTemp = erEsxUtils.getComponentForGroup(htAllGroups,er_option,er_site);
			}
//			selectionDetails.put(intlmap.getTextDescription("reporter.thin."+er_option),er_site);
			rootJson.put("siteCombo",comboArray);
		}
		else
		{
			aListComponentTemp = erEsxUtils.getComponentForGroup(htAllGroups,er_option,null);
		}
		screenLabels.put("reporter.common.siteLabel",intlmap.getTextDescription("reporter.common."+er_option));
		comboArray =  new JSONArray();
		if(aListComponentTemp!=null)
		{
			for(int n=0;n<aListComponentTemp.size();n++)
			{
				String comp = (String)aListComponentTemp.get(n);
				int index=comp.lastIndexOf(":");
				if(index>-1)
				{ 
					String  v_componentType = comp.substring(index+1,comp.length()); 
					if(!v_comptype.contains(v_componentType))
					{
						v_comptype.add(v_componentType);
						if(comp_type == null || comp_type.equals("-1") || comp_type.equals("")) // it will comes very first time only
						{
							comp_type = (String) v_comptype.get(0);
						}
					}
					if(comp_type!=null && comp_type.equalsIgnoreCase(v_componentType))
					{
						compList.add(comp);
					}
				}
			}
		}
		if (v_comptype.size() > 0)
		{
			v_comptype=compUtil.getIntnlSupportCompType(v_comptype,"#");
			for (int i=0 ; i< v_comptype.size(); i++)
			{
				String s=(String)v_comptype.get(i);
				ArrayList aListData = tokInfo.egTokenizer(s,"#");
				String CompTypeDisp=(String)aListData.get(0);
				String CompTypeValue=(String)aListData.get(1);
				loopJsonObj = new JSONObject();
				loopJsonObj.put("displayField",CompTypeDisp);
				loopJsonObj.put("valueField",CompTypeValue);
				comboArray.add(loopJsonObj);
				if (!StringUtils.isNull(CompTypeValue) && CompTypeValue.equalsIgnoreCase(comp_type))
				{
					selectedObj.put("er_comptype", comp_type);
				}
			}
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1");
			selectedObj.put("er_comptype", "-1");
			comboArray.add(loopJsonObj);
		}
		rootJson.put("compTypeCombo",comboArray);
		comboArray =  new JSONArray();
		if (compList!=null && compList.size() > 0)
		{
			if(comp_name==null)
			{
				comp_name = (String)compList.get(0);
				if(comp_name != null && comp_name.indexOf(":") > -1)
					comp_name=comp_name.substring(0,comp_name.indexOf(":"));
			}
			for (int i=0; i<compList.size(); i++)
			{
				String tempStr = (String)compList.get(i);
				String dispStr = tempStr;
				if(dispStr.indexOf(":")>-1)
				{
					dispStr = dispStr.substring(0,dispStr.indexOf(":"));
				}
				loopJsonObj = new JSONObject();
				loopJsonObj.put("displayField",dispStr);
				loopJsonObj.put("valueField",dispStr);
//				loopJsonObj.put("valueField",tempStr);
				comboArray.add(loopJsonObj);
				if (dispStr.equalsIgnoreCase(comp_name))
				{
					selectedObj.put("er_componentname", comp_name);
				}
			}
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1");
			comboArray.add(loopJsonObj);
			selectedObj.put("er_componentname", "-1");
		}
		rootJson.put("componentCombo",comboArray);
		
		Vector v_time = new Vector();
		v_time.add("00");
		v_time.add("01");
		v_time.add("02");
		v_time.add("03");
		v_time.add("04");
		v_time.add("05");
		v_time.add("06");
		v_time.add("07");
		v_time.add("08");
		v_time.add("09");
		v_time.add("10");
		v_time.add("11");
		v_time.add("12");
		v_time.add("13");
		v_time.add("14");
		v_time.add("15");
		v_time.add("16");
		v_time.add("17");
		v_time.add("18");
		v_time.add("19");
		v_time.add("20");
		v_time.add("21");
		v_time.add("22");
		v_time.add("23");

		Vector v_min = new Vector();
		v_min.add("00");
		v_min.add("05");
		v_min.add("10");
		v_min.add("15");
		v_min.add("20");
		v_min.add("25");
		v_min.add("30");
		v_min.add("35");
		v_min.add("40");
		v_min.add("45");
		v_min.add("50");
		v_min.add("55");
		v_min.add("59");

		String timefrom1=(erh.getTimeFrame("TIMEFRAME","From")==null) ? "00:00" :erh.getTimeFrame("TIMEFRAME","From");
		String timeto1=(erh.getTimeFrame("TIMEFRAME","To")==null) ? "23:59" :erh.getTimeFrame("TIMEFRAME","To");
		timefrom1 = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING","startTime");
		timeto1 = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING","endTime");
		String timefrom="";
		String minfrom="";
		String timeto="";
		String minto="";
//		String pvsEnv="No";
		StringTokenizer st;
		if(timefrom1 != null)
		{
			st = new StringTokenizer(timefrom1,":");
			if(st.hasMoreTokens())
			{
				timefrom=st.nextToken();
				minfrom=st.nextToken();
			}
		}
		if(timeto1 != null)
		{
			st=new StringTokenizer(timeto1,":");
			if(st.hasMoreTokens())
			{
				timeto=st.nextToken();
				minto=st.nextToken();
			}
		}
		String timefrom2 = request.getParameter("timefrom");
		String minfrom2 = request.getParameter("minfrom");
		String timeto2 = request.getParameter("timeto");
		String minto2 = request.getParameter("minto");

		if (timefrom2!=null)
			timefrom = timefrom2;
		if (minfrom2!=null)
			minfrom = minfrom2;
		if (timeto2!=null)
			timeto = timeto2;
		if (minto2!=null)
			minto = minto2;

		//Date calculation according to time select
		String[] options = {"Any","1 week","2 weeks","3 weeks","4 weeks","1 month", "2 months",
					"3 months", "6 months", "12 months", "18 months", "24 months", "30 months", "36 months"};

		String startDateTime = "";
		String endDateTime = "";
		
		if(er_timeline!=null&&!er_timeline.equals("Any"))
		{
			int blankSpaceIndex = er_timeline.indexOf(DateTimeTokenizer.BLANK_SPACE);
			if (blankSpaceIndex > 0)
			{
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
				java.util.Date today =  egDt.egetRealDate();
				endDateTime = sdf.format(today);

				long value = Integer.parseInt(er_timeline.substring(0, blankSpaceIndex));
				String unit = er_timeline.substring(blankSpaceIndex+1).toLowerCase();
				if (unit.startsWith("h"))
				{//hours
					value *= 3600;
				}
				else if (unit.startsWith("d"))
				{//days
					value *= (24 * 3600);
				}
				else if (unit.startsWith("w"))
				{
					if(unit.endsWith("last")){
						//last week
						int weekCount = (int) value;
						SimpleDateFormat simpledf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
						java.util.Date currDateTime = egDt.egetRealDate();
						String currentDateTime = simpledf.format(currDateTime);
						String currentDate = currentDateTime.substring(0, currentDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
						String currentHr = currentDateTime.substring(currentDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, currentDateTime.indexOf(":"));
						String currentMin = currentDateTime.substring(currentDateTime.indexOf(":")+1, currentDateTime.lastIndexOf(":"));
						String userFormat = thisuser.getUserDateFormat();
						String curFormatDate = DateUtil.changeDateFormat(currentDate,"MM/dd/yyyy", userFormat); 
						EgTimeZoneConverter realDateTime = new EgTimeZoneConverter(curFormatDate+" "+currentHr+":"+currentMin,thisuser);
						java.util.Date realDate=new SimpleDateFormat(userFormat).parse((String) realDateTime.getDate(false));
						Calendar c = Calendar.getInstance();
						c.setTime(realDate);
						int i = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek() * weekCount;
						int startDayCount = 7 * weekCount + (1 * (weekCount - 1));
						int lastDayCount = 6 * weekCount + (1 * (weekCount - 1));
						c.add(Calendar.DATE, - i - startDayCount);
						c.set(Calendar.HOUR, 00);
						c.set(Calendar.MINUTE, 00);
						java.util.Date start = c.getTime();
						startDateTime = new SimpleDateFormat(userFormat).format(start);
						c.add(Calendar.DATE, lastDayCount);	
						c.set(Calendar.HOUR, 23);
						c.set(Calendar.MINUTE, 00);
						java.util.Date end = c.getTime();
						endDateTime = new SimpleDateFormat(userFormat).format(end);
					}else{
						//weeks
						value *= (7 * 24 * 3600);
					}
				}
				else if (unit.startsWith("mo"))
				{
					if(unit.endsWith("last"))
					{//last month
						int monthCount = (int) value;
						SimpleDateFormat simpledf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
						java.util.Date currDateTime = egDt.egetRealDate();
						String currentDateTime = simpledf.format(currDateTime);
						String currentDate = currentDateTime.substring(0, currentDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
						String currentHr = currentDateTime.substring(currentDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, currentDateTime.indexOf(":"));
						String currentMin = currentDateTime.substring(currentDateTime.indexOf(":")+1, currentDateTime.lastIndexOf(":"));
						String userFormat = thisuser.getUserDateFormat();
						String curFormatDate = DateUtil.changeDateFormat(currentDate,"MM/dd/yyyy", userFormat); 
						EgTimeZoneConverter realDateTime = new EgTimeZoneConverter(curFormatDate+" "+currentHr+":"+currentMin,thisuser);
						java.util.Date realDate=new SimpleDateFormat(userFormat).parse((String) realDateTime.getDate(false));
						Calendar c = Calendar.getInstance();
						c.setTime(realDate);
						c.add(Calendar.MONTH, -monthCount);
						c.set(Calendar.DATE, 1);
						c.set(Calendar.HOUR, 00);
						c.set(Calendar.MINUTE, 00);
						java.util.Date start = c.getTime();
						startDateTime = new SimpleDateFormat(userFormat).format(start);
						Calendar c1 = Calendar.getInstance();
						c1.setTime(realDate);
						c1.add(Calendar.MONTH, -1);
						c1.set(Calendar.DAY_OF_MONTH, c1.getActualMaximum(Calendar.DAY_OF_MONTH));
						c1.set(Calendar.HOUR, 23);
						c1.set(Calendar.MINUTE, 59);
						java.util.Date end = c1.getTime();
						endDateTime = new SimpleDateFormat(userFormat).format(end);
					}else{
						//months
						java.util.Date dt_temp = egDt.egetRealDate();
						Calendar cal_temp = new GregorianCalendar();
						cal_temp.setTime(dt_temp);
						//cal_temp.add(Calendar.DATE,-1);
						cal_temp.add(Calendar.HOUR_OF_DAY,0);
						java.util.Date dt_temp1 = cal_temp.getTime();
						long l_temp = dt_temp1.getTime();
						int  totalDays=24*(ErUtils.getMaxDaysInMonth());
						startDateTime = egDt.egetDate(l_temp -(long)( (value*totalDays * msecsPerHour)));
						startDateTime = DateUtil.changeDateFormat(startDateTime,"dd/MM/yyyy HH:mm","MM/dd/yyyy HH:mm");
					}
				}
				if (unit!=null&&!unit.startsWith("mo")&& !unit.endsWith("last"))
				{
					java.util.Date start = new java.util.Date();
					java.util.Date startTmp=new java.util.Date(endDateTime);
					start.setTime(startTmp.getTime() - (value * 1000));
					startDateTime = sdf.format(start);
				}
			}
			if ((startDateTime != null) && (endDateTime != null))
			{
				s_inidate="MM/dd/yyyy";
				try
				{
					int shr=Integer.parseInt(startDateTime.substring(startDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, startDateTime.indexOf(":")));
					int en_hr=Integer.parseInt(endDateTime.substring(endDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, endDateTime.indexOf(":")));
					s_en_time=endDateTime.substring(0, endDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
					s_st_time=startDateTime.substring(0, startDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
//					s_st_hr = String.valueOf(shr);
//					s_en_hr = String.valueOf(en_hr);
//					strmin=startDateTime.substring(startDateTime.indexOf(":")+1);
//					enmin=endDateTime.substring(endDateTime.indexOf(":")+1);
					s_st_hr = "0";
					s_en_hr = "0";
					strmin="0";
					enmin="0";
				}
				catch(Exception e)
				{
					System.out.println("Eception caught :"+e);
					e.printStackTrace();
				}
			}
		}

		String disable="";
		if(er_timeline!=null&&!er_timeline.equals("Any"))
		{
			disable ="disabled";
		}
		if(er_timeline!=null&&er_timeline.equals("Any"))
		{
			String StrDate="";
			try
			{
				java.text.SimpleDateFormat df=new java.text.SimpleDateFormat("MM/dd/yyyy k 'at' hh:mm");
				StrDate =df.format(new java.util.Date());
			}
			catch(Exception ee)
			{
				System.out.println("Exception is"+ee);
			}
			String SDate =StrDate.substring(0,StrDate.indexOf(" "));
			String shour =StrDate.substring(StrDate.indexOf(" "),StrDate.lastIndexOf(""));
			shour = shour.substring(0,3);
			if(s_st_time==null)
			{
				s_st_time=SDate;
				s_inidate="MM/dd/yyyy";
			}
			if(s_en_time==null)
			{
				s_en_time=SDate;
			}
			if(s_st_hr==null)
			{
				shour =shour.trim();
				int starthr = Integer.parseInt(shour);
				starthr = starthr-1;
				s_st_hr=String.valueOf(starthr);
			}
			if(s_en_hr==null)
			{
				shour =shour.trim();
				s_en_hr =shour;
			}
		}
		String s_title = "";	
		boolean noDataFound = true;
		if(resultMap != null && isSubmit != null && isSubmit.equalsIgnoreCase("true"))
		{
			Boolean noData = ((Boolean) resultMap.get("NO_DATA_FOUND"));
			if(noData != null)
				noDataFound = noData.booleanValue();
		}
		String confirmation = reportInfo.getValue("BACKGROUND_PROCESS","NeedConfirmation");
		String strbgrepportName = reportInfo.getValue("BACKGROUND_PROCESS","EnableBackgroundReport");
		String limitforbg = reportInfo.getValue("BACKGROUND_PROCESS","MinDurationForReport");
		boolean isBackgroundProcess = false;
		
		String er_type = request.getParameter("er_type");
		if(er_type == null) {
			er_type="Yes";
		}

		String excludeweekend = request.getParameter("er_excwe");
		if (excludeweekend == null || excludeweekend.equals("")) {
			excludeweekend = "Yes";
		}
//		pvsEnv = request.getParameter("ShowpvsEnvironment");
//		if (pvsEnv == null || pvsEnv.equals("")) {
//			pvsEnv = "No";
//		}
		String Days = (erh.getExcludeWeekends("EXCLUDE_WEEKEND","Days") == null) ? 
				"Saturday,Sunday" : erh.getExcludeWeekends("EXCLUDE_WEEKEND","Days");
		request.setAttribute("Weekends",Days);
		EgDbInfo dbInfo = new EgDbInfo("manager");
		String pdfPrint = request.getParameter("pdfPrint");
		String sample = request.getParameter("sample");
		hiddens.put("currTime", "");
		hiddens.put("er_rtype", "Citrix Server");
		hiddens.put("er_trgttype", "Citrix Capacity Planning");
		hiddens.put("font", font);
		hiddens.put("reporttype", request.getParameter("reporttype"));
		hiddens.put("eruserid", userid);
		hiddens.put("er_combination", "");
		hiddens.put("fromSchedule", reqFromSchedule);
		if(fromScheduleModify!=null)
			hiddens.put("fromScheduleModify",fromScheduleModify);
		else
			hiddens.put("fromScheduleModify","null");
		if(fromFavoriteModify!=null)
			hiddens.put("fromFavoriteModify",fromFavoriteModify);
		else
			hiddens.put("fromFavoriteModify","null");
		hiddens.put("favorite_id", favorite_id);
		hiddens.put("er_favorite", er_favorite);

		hiddens.put("schedule_id", schedule_id);
		hiddens.put("er_ViewName", "ErCitrixCapacityPlanningReport.jsp");
		hiddens.put("er_trenddata", "");
		hiddens.put("inidate", currentDateFormat);
		hiddens.put("er_datafrom", datafrom);
		hiddens.put("getMaxDaysInMonth", String.valueOf(ErUtils.getMaxDaysInMonth()));
		hiddens.put("isSchedule", "false");
		hiddens.put("isFavorite", "false");
		hiddens.put("er_flag", "true");
		hiddens.put("userID", urs);
		hiddens.put("forwardto", "ErCitrixCapacityPlanningReport");
		hiddens.put("er_bgreportfrom", "Citrix_CapacityPlanning");
		hiddens.put("bgenabled", strbgrepportName);
		hiddens.put("limitforbg", limitforbg);
		hiddens.put("savereport", "save");
		hiddens.put("servletName", "com.eg.ErCitrixCapacityPlanningReportC");
		hiddens.put("fromMenu", "false");
		hiddens.put("divStatus", divStatus);
		screenLabels.put("reporter.common.reportType", intlmap.getTextDescription("reporter.common.Report Type"));
		String strGraphChecked="";
		String strDataChecked="";
	
		JSONArray reportTypeArr = new JSONArray();
		JSONObject reportTypeObj = new JSONObject();
		reportTypeObj.put("displayField", intlmap.getTextDescription("reporter.common.Graph"));
		reportTypeObj.put("valueField", "Yes");
		reportTypeArr.add(reportTypeObj);
		reportTypeObj = new JSONObject();
		reportTypeObj.put("displayField", intlmap.getTextDescription("reporter.common.Data"));
		reportTypeObj.put("valueField", "No");
		reportTypeArr.add(reportTypeObj);
		rootJson.put("reportTypeCombo", reportTypeArr);

		if(er_type == null || er_type.equals("Yes"))
		{
			strGraphChecked = "checked";
			strDataChecked = "";
			selectedObj.put("reportTypeSelected", "Yes");
		}
		else
		{
			strGraphChecked = "";
			strDataChecked = "checked";
			selectedObj.put("reportTypeSelected", "No");
		}
		screenLabels.put("reporter.common.excludeweekends", intlmap.getTextDescription("reporter.common.Exclude weekends"));

		JSONArray excludeWeekArr = new JSONArray();
		JSONObject excludeWeekObj = new JSONObject();
		excludeWeekObj.put("valueField", "Yes");
		excludeWeekObj.put("displayField", intlmap.getTextDescription("reporter.common.Yes")+" ("+Days+") ");
		excludeWeekArr.add(excludeWeekObj);
		excludeWeekObj = new JSONObject();
		excludeWeekObj.put("valueField", "No");
		excludeWeekObj.put("displayField", intlmap.getTextDescription("reporter.common.No"));
		excludeWeekArr.add(excludeWeekObj);
		rootJson.put("excludeWeekCombo", excludeWeekArr);
		Vector v_selection = new Vector();	
		if(excludeweekend.equalsIgnoreCase("Yes") )
		{
			selectedObj.put("excludeWeekSelected", "Yes");
			rootJson.put("excludeWeekEndMsg",intlmap.getTextDescription("reporter.common.Excludes")+ " " +Days);
		}
		else
		{
			selectedObj.put("excludeWeekSelected", "No");
			rootJson.put("excludeWeekEndMsg",intlmap.getTextDescription("reporter.common.Excludes")+ " " +Days);
		}
		screenLabels.put("reporter.common.Timeperiod", intlmap.getTextDescription("reporter.common.Time period"));
		screenLabels.put("reporter.common.From", intlmap.getTextDescription("reporter.common.From"));
		screenLabels.put("reporter.common.To", intlmap.getTextDescription("reporter.common.To"));
		screenLabels.put("reporter.common.Hrs", intlmap.getTextDescription("reporter.common.Hrs"));
		screenLabels.put("reporter.common.Mins", intlmap.getTextDescription("reporter.common.Mins"));
		selectedObj.put("timePeriodFromHrSelected", timefrom);
		selectedObj.put("timePeriodFromMinSelected", minfrom);

		selectedObj.put("timePeriodToHrSelected", timeto);
		selectedObj.put("timePeriodToMinSelected", minto);
//		selectedObj.put("ShowpvsEnvironment", pvsEnv);

		screenLabels.put("reporter.common.Timeline", intlmap.getTextDescription("reporter.common.Timeline"));
	%>
	
	<%@include file ="ErTimeFormatJSON.jsp"%>
	
	<%
		screenLabels.put("timelineHr", intlmap.getTextDescription("reporter.common.Hr"));
		hiddens.put("er_usertimeline", strUsrTimeline);
		screenLabels.put("reporter.common.Timeline", intlmap.getTextDescription("reporter.common.Timeline"));
		screenLabels.put("reporter.common.From", intlmap.getTextDescription("reporter.common.From"));
		screenLabels.put("reporter.common.To", intlmap.getTextDescription("reporter.common.To"));
		screenLabels.put("reporter.common.Hr", intlmap.getTextDescription("reporter.common.Hr"));
		screenLabels.put("reporter.common.Graph", intlmap.getTextDescription("reporter.common.Graph"));
		rootJson.put("timelineCombo",timelineComboArray);
		rootJson.put("timelineHourCombo",timelineHourComboArray);
		selectedObj.put("selectedTimeline",er_timeline);
		selectedObj.put("startDate",startDateJSON);
		selectedObj.put("endDate",endDateJSON);
		selectedObj.put("startHour",startHourJSON);
		selectedObj.put("endHour",endHourJSON);
		selectedObj.put("startmin", strmin);
		selectedObj.put("endmin", enmin);
		selectedObj.put("selectedGraphMode",selectedGraphMode);

		//User TimeZone changes
		selectedObj.put("startDateForDisplay",startDateForDisplay);
		selectedObj.put("startHourForDisplay",startHourForDisplay);
		selectedObj.put("startMinForDisplay",startMinForDisplay);
		selectedObj.put("endDateForDisplay",endDateForDisplay);
		selectedObj.put("endHourForDisplay",endHourForDisplay);
		selectedObj.put("endMinForDisplay",endMinForDisplay);

		screenLabels.put("reporter.consolidated.reportGeneration", intlmap.getTextDescription("reporter.consolidated.Report Generation"));
		screenLabels.put("reporter.consolidated.reportName", intlmap.getTextDescription("reporter.consolidated.Report Name"));

		String er_reportgenration = request.getParameter("er_reportgenration");
		String er_background ="";
		String er_foreground ="";
		JSONArray reportGenArr = new JSONArray();
		JSONObject reportGenObj = new JSONObject();
		reportGenObj.put("valueField", "background");
		reportGenObj.put("displayField", strbackground);
		reportGenArr.add(reportGenObj);

		reportGenObj = new JSONObject();
		reportGenObj.put("valueField", "foreground");
		reportGenObj.put("displayField", strforeground);
		reportGenArr.add(reportGenObj);

		rootJson.put("reportGenCombo", reportGenArr);

		if (er_reportgenration != null && er_reportgenration.equals("background"))
		{
			er_background = "selected";
			er_foreground = "";
			selectedObj.put("reportGenSelected", "background");
		}
		else if (er_reportgenration != null && er_reportgenration.equals("background-csv"))
		{
			er_background = "selected";
			er_foreground = "";
			selectedObj.put("reportGenSelected", "background-csv");
		}
		else
		{
			er_background = "";
			er_foreground = "selected";
			selectedObj.put("reportGenSelected", "foreground");
		}
		String bg_reportname = request.getParameter("bg_reportname");
		if(bg_reportname == null)
		{
			bg_reportname = "";
		}
		if(strbgrepportName != null && strbgrepportName.equalsIgnoreCase("Yes"))
		{
			if (er_reportgenration != null && er_reportgenration.equals("background"))
			{
				selectedObj.put("reportName",bg_reportname); 
			}
		}
		if(fromScheduleModify!=null && fromScheduleModify.equalsIgnoreCase("Yes"))
		{
			screenLabels.put("reporter.common.SUBMIT", intlmap.getTextDescription("reporter.common.Save"));
		}
		else
		{
			screenLabels.put("reporter.common.SUBMIT", intlmap.getTextDescription("reporter.common.SUBMIT"));
		}
		if(bggroundStr != null && !bggroundStr.equals(""))
		{
			String strreportName = "Citrix_CapacityPlanning";
			isBackgroundProcess = true;
			backgroundResultObj.put("status", status);
			String bgroundResponseTxt=bggroundStr;
			if(status != null && !status.equalsIgnoreCase("exceedLimit"))
			{
				bgroundResponseTxt=erbgreport.getlangsupportedString(bggroundStr,bgString,urs);
			}
			if(status != null && (status.equalsIgnoreCase("duplicate") || status.equalsIgnoreCase("exceedLimit")))
			{
				strreportName ="All Report Types";
			}
			if(strreportName!=null && strreportName.indexOf(" ") > -1)
			{
				strreportName = com.eg.EgURLEncoder.encode(strreportName, "UTF-8");
			}
			backgroundResultObj.put("backgroundResponseText", bgroundResponseTxt);
			backgroundResultObj.put("backgroundResponseURLLink", "/final/servlet/com.eg.ErStartBackGroundReportC?back=true&er_bgreportfrom="+strreportName+"&userID="+com.eg.EgURLEncoder.encode(urs, "UTF-8")+"&savereport=search&er_filterby=Report_Name&forwardto=ErBackGoundProcess");
			backgroundResultObj.put("backgroundResponseURLText", intlmap.getTextDescription("reporter.common.Click here to see a list of generated and processing reports"));
		}
		if(isSubmit != null && isSubmit.equalsIgnoreCase("true") && !isBackgroundProcess ) {
			String componentName = "";
			rootJson.put("selectionDetailstitle", intlmap.getTextDescription("reporter.common.Selection Details for")+" "+componentName);
			if(er_option!=null)
				selectionDetails.put( intlmap.getTextDescription("reporter.common.Analyze By"), intlmap.getTextDescription("reporter.common."+er_option));
			if(er_option!=null && !er_option.equalsIgnoreCase("component")&& er_site!=null)
				selectionDetails.put( intlmap.getTextDescription("reporter.common."+er_option), er_site);
			if(comp_type!=null && comp_type.length()>0)
				selectionDetails.put( intlmap.getTextDescription("reporter.common.Component Type"), intlmap.getComponentTypeDescription(comp_type));
			else
				selectionDetails.put( intlmap.getTextDescription("reporter.common.Component Type"), comp_type);
			selectionDetails.put( intlmap.getTextDescription("reporter.common.Timeline"), "<span class='font_bold'> </span> "+st_dateTime +" "+intlmap.getTextDescription("reporter.common.hrs")+" <span class='font_bold'> "+intlmap.getTextDescription("reporter.common.to")+" </span> "+en_dateTime+" "+intlmap.getTextDescription("reporter.common.hrs"));

			String resultFor=null;
			if(!noDataFound)
			{
				HashMap serverDatas = (HashMap)resultMap.get("ServerWiseDatas");
				ArrayList idleServerList = (ArrayList)resultMap.get("idleServerList");
				CitrixCapacityPlannigDAO ctrxbean=new CitrixCapacityPlannigDAO();
				JSONObject active_session_graph=new JSONObject();
				JSONObject total_session_graph=new JSONObject();
				JSONObject cpu_memory_graph=new JSONObject();
				JSONObject disk_network_graph=new JSONObject();
				JSONObject datast=null;
				JSONObject details=null;
				JSONArray dataSet=new JSONArray();
				JSONArray dataSet1=new JSONArray();
				JSONArray dataSet2=new JSONArray();
				JSONArray dataSet3=new JSONArray();
				if(er_option != null && er_option.equalsIgnoreCase("component"))
					resultFor="ServerWise";
				if(idleServerList != null && idleServerList.size() > 0)
				{
					resultsObj.put("idleServers",idleServerList);
				}
				String coulmnList = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "componentwiseColumns");
				if(resultFor != null && resultFor.equalsIgnoreCase("ServerWise"))
				{
					ArrayList al=new ArrayList();
					JSONObject usageTable =null;
					String limitBy="";
					String limitByVal="-";
					Double sessns=0.0;
					ArrayList DetailsList=new ArrayList();
					JSONObject totSessnGraph=null;
					JSONObject actveSessnGraph=null;
					JSONObject cpuMemoryGraph=null;
					JSONObject diskNetworkGraph=null;
					JSONArray limitbyArray=null;
					Iterator itr=serverDatas.keySet().iterator();
					while(itr.hasNext())
					{
						datast=new JSONObject();
						JSONArray rowData=new JSONArray();
						String CompName = (String) itr.next();
						ArrayList value=(ArrayList)serverDatas.get(CompName);
						if(value != null && value.size() >0)
						{
							for(int i=0;i<value.size();i++)
							{
								HashMap h1=(HashMap)value.get(i); 
								if(h1 != null && h1.size() > 0)
								{
									CitrixInfoBean cib=new CitrixInfoBean(h1,coulmnList);
									DetailsList.add(cib);
									String posssibleCnt=cib.getPossibleSessnsCnt();
									if(cib.getBottleNeckresource() != null && !cib.getBottleNeckresource().equalsIgnoreCase(""))
										limitBy=cib.getBottleNeckresource();
									if(limitBy!= null && !limitBy.equalsIgnoreCase(""))
										al.add(new CustomSort(limitBy,posssibleCnt));
								}
							}
							JSONObject graphdataset=ctrxbean.getGraphDataset(DetailsList,CompName,currentDateFormat,intlmap);
							if(graphdataset != null && graphdataset.size() > 0){
								actveSessnGraph=(JSONObject)graphdataset.get("ActiveSession");
								cpuMemoryGraph=(JSONObject)graphdataset.get("CpuMemoryGraph");
								diskNetworkGraph=(JSONObject)graphdataset.get("DiskNetworkGraph");
							}
						}
						JSONObject tot_sessn_graph = (JSONObject)resultMap.get("totalSessionGraph");
						totSessnGraph=ctrxbean.getTotalSessionGraphData(tot_sessn_graph,CompName,currentDateFormat,st_dateTime,en_dateTime,intlmap);
					}
					if(al != null && al.size()>0)
					{
						CustomSort.orderby="asc";
						Collections.sort(al);
						int minCal = 0;
						int sInfoSize = al.size();
						if (sInfoSize > 0) 
						{
							String dataPointsForMinCal = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "DataPointsForMinCalinUI");
							double dataToBeConsidered = 5;
							if (dataPointsForMinCal != null) {
								dataPointsForMinCal = dataPointsForMinCal.trim();
								if (dataPointsForMinCal.endsWith("%")) 
									dataPointsForMinCal = dataPointsForMinCal.substring(0, dataPointsForMinCal.indexOf("%"));
								try {
									dataToBeConsidered = Integer.parseInt(dataPointsForMinCal);
								} catch (Exception e) {
									System.out.println("Error in data points specification in ini, using default");
								}
							}
							dataToBeConsidered /= 100;
//							minCal = (int) (sInfoSize * dataToBeConsidered);

							double maxVl=(sInfoSize)*(dataToBeConsidered);
							String strVal1=erUtils.round(maxVl,0);
							minCal=Integer.parseInt(strVal1);
							if(minCal > 0)
								minCal=minCal-1;
						}
						if (minCal <= 0)
							minCal = 0;

						CustomSort  cs = (CustomSort)al.get(minCal);
						if(cs != null)
						{
							limitByVal=(String)cs.col1;
							sessns=(Double)cs.col2;
						}
					}
					String limitByValue="";
					if(resultsObj != null && !resultsObj.containsKey("Overview"))
					{
						details=new JSONObject();
						limitbyArray=new JSONArray();
						limitbyArray.add(limitByVal);
						details.put("Possible_Sessions",sessns.intValue());
						details.put("Limit_By",limitbyArray);
						resultsObj.put("Overview",details);
					}
					usageTable=ctrxbean.getDetailedValues(DetailsList,er_timeline,"true",reporter_Skin,intlmap);
					if(usageTable != null){
						if(usageTable.containsKey("Table_Data"))
							resultsObj.put("Table1",usageTable.get("Table_Data"));
						if(usageTable.containsKey("Recommandatn"))
							resultsObj.put("Recommandatn",usageTable.get("Recommandatn"));
						if(usageTable.containsKey("RecommandatnBasedCalculatn"))
							resultsObj.put("SessnBasedCalculatn",usageTable.get("RecommandatnBasedCalculatn"));
						if(usageTable.containsKey("overview1")){
							resultsObj.put("Overview",usageTable.get("overview1"));
						}
						if(usageTable.containsKey("Usage"))
							resultsObj.put("Usage",usageTable.get("Usage"));
						if(usageTable.containsKey("CPUGraph"))
							resultsObj.put("CPUGraph",usageTable.get("CPUGraph"));
						if(usageTable.containsKey("MemoryGraph"))
							resultsObj.put("MemoryGraph",usageTable.get("MemoryGraph"));
						if(usageTable.containsKey("DiskGraph"))
							resultsObj.put("DiskGraph",usageTable.get("DiskGraph"));
						if(usageTable.containsKey("NetworkGraph"))
							resultsObj.put("NetworkGraph",usageTable.get("NetworkGraph"));
					}

					resultsObj.put("graph1",totSessnGraph);
					resultsObj.put("graph2",actveSessnGraph);
					resultsObj.put("graph3",cpuMemoryGraph);
					resultsObj.put("graph4",diskNetworkGraph);
					resultsObj.put("isServerwise",true);
				}
				else//zone wise data processing Starts
				{
					resultsObj.put("isServerwise",false);
					ArrayList zoneDatas = (ArrayList)resultMap.get("ZoneWiseDatas");
					String UniqueUserCnt = (String)resultMap.get("UniqueUsersCount");
					if(UniqueUserCnt == null)
						UniqueUserCnt="-";
					String zoneCols = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "zonewiseColumns");
					CitrixInfoBeanforZone ctrxZne=null;
					SimpleDateFormat ntesdf=new SimpleDateFormat(currentDateFormat);
					SimpleDateFormat dbformat=new SimpleDateFormat("yyyy-MM-dd");
					String dbdateFormat=ctrxbean.getChartlabelFormat(currentDateFormat);
					SimpleDateFormat uiformat=new SimpleDateFormat(dbdateFormat);
					JSONObject AnalysisDataObj=new JSONObject();
					String serversCount="0";
					double totalServersCount=0;
					int possibleSessionsbyZone=0;
					int peakValue=0;
					String strtDte="";
					String endDte="";
					try{
						Date dte=ntesdf.parse(st_dateTime);
						strtDte=ntesdf.format(dte);
						dte=ntesdf.parse(en_dateTime);
						endDte=ntesdf.format(dte);
					}
					catch(Exception ee){}


					if(zoneDatas != null && zoneDatas.size() > 0){
						AnalysisDataObj=ctrxbean.getZoneWiseGraphDatas(zoneDatas,zoneCols,dbformat,uiformat,strtDte,endDte,UniqueUserCnt,intlmap);
						serversCount=(String)AnalysisDataObj.get("TotalServers");
						String possibleSessnCnt=(String)AnalysisDataObj.get("AdditionalPossibleSessionsByZone");
						if(possibleSessnCnt != null )
							possibleSessionsbyZone=(int)Double.parseDouble(possibleSessnCnt);
						possibleSessnCnt=(String)AnalysisDataObj.get("PeakLoadByZone");
						if(possibleSessnCnt != null )
							peakValue=(int)Double.parseDouble(possibleSessnCnt);
					}
					if(serversCount != null )
						totalServersCount=Double.parseDouble(serversCount);
					String servrCols = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "componentwiseColumns");
					ArrayList compWisedatas=new ArrayList();
					ArrayList zoneWiseUsagedatas=new ArrayList();
					HashMap zoneWiseUsagedataObj=new HashMap();
					ArrayList tmpArray=null;
					JSONArray analysArr=null;
					CitrixInfoBean ctrxServrBean=null;
					HashMap tmpObjct=null;
					if(serverDatas != null && serverDatas.size() > 0){
						double dataToBeConsidered = 5;
						double dataToBeMaxConsidered = 95;
						try{
							String dataPointsForMinCal = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "DataPointsForMinCalinUI");
							if (dataPointsForMinCal != null) 
							{
								dataPointsForMinCal = dataPointsForMinCal.trim();
								if (dataPointsForMinCal.endsWith("%")) {
									dataPointsForMinCal = dataPointsForMinCal.substring(0, dataPointsForMinCal.indexOf("%"));
								}
								try {
									dataToBeConsidered = Integer.parseInt(dataPointsForMinCal);
								} catch (Exception e) {
									System.out.println("Error in data points specification in ini, using default");
								}
							}
							dataToBeConsidered /= 100;
							String dataPointsForMaxCal = reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING", "DataPointsForMaxCalinUI");
							if (dataPointsForMaxCal != null) 
							{
								dataPointsForMaxCal = dataPointsForMaxCal.trim();
								if (dataPointsForMaxCal.endsWith("%")) {
									dataPointsForMaxCal = dataPointsForMaxCal.substring(0, dataPointsForMaxCal.indexOf("%"));
								}
								try {
									dataToBeMaxConsidered = Integer.parseInt(dataPointsForMaxCal);
								} catch (Exception e) {
									System.out.println("Error in data points specification in ini, using default");
								}
							}
							dataToBeMaxConsidered /= 100;
						}catch(Exception ee){
							ee.printStackTrace();
						}
						int minCal = 0;
						int maxCal = 0;
						int possiblesessnCnt=0;
						Iterator itr=serverDatas.keySet().iterator();
						ArrayList all=new ArrayList();
						ArrayList ServCapacity=new ArrayList();
						ArrayList StstsList=new ArrayList();
						ArrayList pieval=null;

						ArrayList cpuLimitation=new ArrayList();
						ArrayList memoryLimitaion=new ArrayList();
						ArrayList diskLimitaion=new ArrayList();
						ArrayList networkLimitation=new ArrayList();
						int cpuCnt=0;
						int memoryCnt=0;
						int diskCnt=0;
						int networkCnt=0;
						int overallSessionCnt=0;
						while(itr.hasNext()){
							int totalSessnsCnt=0;
							compWisedatas=new ArrayList();
							pieval=new ArrayList();
							String compName=(String)itr.next();
							tmpArray=(ArrayList)serverDatas.get(compName);
							if(tmpArray != null && tmpArray.size() > 0){
								int sInfoSize=tmpArray.size();
//								minCal = (int) (sInfoSize * dataToBeConsidered);
//								maxCal = (int) (sInfoSize * dataToBeMaxConsidered);
								double maxVl=(sInfoSize)*(dataToBeConsidered);
								String strVal1=erUtils.round(maxVl,0);
								minCal=Integer.parseInt(strVal1);
								if(minCal > 0)
									minCal=minCal-1;
								maxVl=(sInfoSize)*(dataToBeMaxConsidered);
								strVal1=erUtils.round(maxVl,0);
								maxCal=Integer.parseInt(strVal1);
								if(maxCal > 0)
									maxCal=maxCal-1;

								if (minCal <= 0) {
									minCal = 0;
								}
								if (maxCal <= 0) {
									maxCal = 0;
								}
								for(int i=0;i<tmpArray.size();i++){
									tmpObjct=(HashMap)tmpArray.get(i);
									ctrxServrBean=new CitrixInfoBean(tmpObjct,servrCols);
									compWisedatas.add(ctrxServrBean);
									zoneWiseUsagedatas.add(ctrxServrBean);
									String limitBy=ctrxServrBean.getBottleNeckresource();
									String total_sessns=ctrxServrBean.getTotalSessions();
									int tmpVl=(int)Double.parseDouble(total_sessns);
									totalSessnsCnt+=tmpVl;
									overallSessionCnt+=tmpVl;
									if(!pieval.contains(limitBy))
										pieval.add(limitBy);
								}
				//for resourse limitation analysis
								if(pieval.contains("MEMORY") || pieval.contains("Memory") || pieval.contains("2.0000") ){
									memoryCnt+=1;
									if(!memoryLimitaion.contains(compName))
									memoryLimitaion.add(compName);
								}
								else if(pieval.contains("DISK") || pieval.contains("3.0000")){
									diskCnt+=1;
									if(!diskLimitaion.contains(compName))
									diskLimitaion.add(compName);
								}
								else if(pieval.contains("NETWORK") || pieval.contains("4.0000")){
									networkCnt+=1;
									if(!networkLimitation.contains(compName))
									networkLimitation.add(compName);
								}
								else if(pieval.contains("CPU") ||pieval.contains("Cpu") || pieval.contains("1.0000")){
									cpuCnt+=1;
									if(!cpuLimitation.contains(compName))
									cpuLimitation.add(compName);
								}

			//for find 95% of current active sessions
							Collections.sort(compWisedatas,
							new CitrixInfoBean() {
								public int compare(Object obj1, Object obj2) {
									CitrixInfoBean bean1 = (CitrixInfoBean) obj1;
									CitrixInfoBean bean2 = (CitrixInfoBean) obj2;
									if (bean1.getActiveSessions() == bean2.getActiveSessions()) {
										return 0;
									} else if (Double.parseDouble(bean1.getActiveSessions()) >	Double.parseDouble(bean2.getActiveSessions())) {
										return 1;
									} else {
										return -1;
									}
								}
							});
							CitrixInfoBean ctrx_activeSessn=(CitrixInfoBean)compWisedatas.get(maxCal);
							String actveSessions=ctrx_activeSessn.getActiveSessions();

			//for find 5% of additional possible sessions
								Collections.sort(compWisedatas,
								new CitrixInfoBean() {
									public int compare(Object obj1, Object obj2) {
										CitrixInfoBean bean1 = (CitrixInfoBean) obj1;
										CitrixInfoBean bean2 = (CitrixInfoBean) obj2;
										if (bean1.getPossibleSessnsCnt() == bean2.getPossibleSessnsCnt()) {
										return 0;
										} else if (Double.parseDouble(bean1.getPossibleSessnsCnt()) > Double.parseDouble(bean2.getPossibleSessnsCnt())) {
										return 1;
										} else {
										return -1;
										}
									}
								});
								CitrixInfoBean additnlSessn=(CitrixInfoBean)compWisedatas.get(minCal);
								String addtnlSessions=additnlSessn.getPossibleSessnsCnt();
								possiblesessnCnt+=(int)Double.parseDouble(addtnlSessions);
								all.add(new CustomSort(compName+"$"+addtnlSessions,actveSessions));
								
							//ServCapacity
								double xtraSessnVal=0;
								double curntSessnsVal=0;
								if(addtnlSessions != null)
									xtraSessnVal=Double.parseDouble(addtnlSessions);
								if(actveSessions != null)
									curntSessnsVal=Double.parseDouble(actveSessions);
								ServCapacity.add(new CustomSort((compName+"$"+curntSessnsVal+"#"+xtraSessnVal),String.valueOf(xtraSessnVal+curntSessnsVal)));
							//for server Loads Calculation
								StstsList.add(new CustomSort(compName,String.valueOf(totalSessnsCnt)));
							}
							zoneWiseUsagedataObj.put(compName,compWisedatas);
						}
//						analysArr=ctrxbean.getConsumptionAnalysisperSession(zoneWiseUsagedatas);
						AnalysisDataObj.put("usagePerSessionTitVal",intlmap.getTextDescription("reporter.common.Resource Consumption Per Session"));
//						AnalysisDataObj.put("UsagePerSession",analysArr);
						resultsObj.put("AnalysisDatas",AnalysisDataObj);


// Distribution panel Data Processing Starts Here
						JSONObject distrubutnObj=new JSONObject();
						JSONObject tmpObj2=null;
						int serverCount =serverDatas.size();
						distrubutnObj=ctrxbean.getDistributionGraphandTableperServers(all,possiblesessnCnt,serverCount,intlmap);
				//for server and capacity Graph
						CustomSort.orderby="desc";
						Collections.sort(ServCapacity);
						tmpObj2=ctrxbean.getServerCapacityGraph(ServCapacity,false,intlmap);
						distrubutnObj.put("ServrCapacityGraph",tmpObj2);
						tmpObj2=ctrxbean.getServerCapacityGraph(ServCapacity,true,intlmap);
						distrubutnObj.put("ServrCapacityGraph_Drill",tmpObj2);

						String limitVal=reportInfo.getValue("CITRIX_CAPACITY_CPU_PLANNING","ServerandCapacityGrpahLimit");
						String servCapactyTitle="";
						if(limitVal != null){
							double dd=Double.parseDouble(limitVal);
							if(dd > 1)
								servCapactyTitle=intlmap.getTextDescription("reporter.common.Top")+" "+limitVal+" "+intlmap.getTextDescription("reporter.common.Servers Based on Additional Capacity");
							else
								servCapactyTitle=intlmap.getTextDescription("reporter.common.Top")+" "+limitVal+" "+intlmap.getTextDescription("reporter.common.Server Based on Additional Capacity");
						}
						distrubutnObj.put("ServrCapacityGraphTitle",servCapactyTitle);
						distrubutnObj.put("possiblesessnCnt",possiblesessnCnt);
						double singlVal=(double)overallSessionCnt/StstsList.size();
						double low_Sessions=(singlVal-(singlVal/2));
						double high_Sessions=(singlVal+(singlVal/2));
						int lowConsumptn=0;
						int normalConsumptn=0;
						int highConsumption=0;
						int crntCapacity=overallSessionCnt+possiblesessnCnt;

						float normalVal=(float)overallSessionCnt/StstsList.size();
						CustomSort.orderby="asc";
						Collections.sort(StstsList);
						for(int i=0;i<StstsList.size();i++)
						{
							CustomSort cs =(CustomSort)StstsList.get(i);
							String col=(String)cs.col1;
							Double val=(Double)cs.col2;
							if(val.intValue() > 0 && val.intValue() <= low_Sessions){
								lowConsumptn+= 1;
							}
							if(val.intValue() > low_Sessions && val.intValue() <= high_Sessions){
								normalConsumptn+= 1;
							}
							if(val.intValue() > high_Sessions ){
								highConsumption+= 1;
							}
						}
						JSONArray tmpArr=new JSONArray();
						JSONObject obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Above normal Load"));
						obj.put("value",highConsumption+" "+intlmap.getTextDescription("reporter.common.Servers"));
						tmpArr.add(obj);
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Below normal Load"));
						obj.put("value",lowConsumptn+" "+intlmap.getTextDescription("reporter.common.Servers"));
						tmpArr.add(obj);
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Normal Load"));
						obj.put("value",normalConsumptn+" "+intlmap.getTextDescription("reporter.common.Servers"));
						tmpArr.add(obj);
						distrubutnObj.put("serverLoads",tmpArr);
						tmpArr=new JSONArray();
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Concurrent Sessions"));
//						int peakValue =0;
//						if(resultMap != null && resultMap.containsKey("PeakLoadDatas")){
//							ArrayList PeakLoadDataArr = (ArrayList)resultMap.get("PeakLoadDatas");
//							Collections.sort(PeakLoadDataArr);
//							double maxVl=(PeakLoadDataArr.size())*(dataToBeMaxConsidered);
//							String strVal1=erUtils.round(maxVl,0);
//							int peakVal=Integer.parseInt(strVal1);
//							if(peakVal  > 0)
//								peakVal=peakVal-1;
//							Double tmpVl=(Double)PeakLoadDataArr.get(peakVal);
//							peakValue = Integer.valueOf(tmpVl.intValue());
//						}
//						peakValue =(int) peakLoadbyZone;
						obj.put("value",peakValue+"");
						obj.put("iconclass","iconSessionsCompleted");
//						crntCapacity=possiblesessnCnt+peakValue;
						crntCapacity=possibleSessionsbyZone+peakValue;
						tmpArr.add(obj);
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Additional Sessions Possible"));
//						obj.put("value",possiblesessnCnt+"");
						obj.put("value",possibleSessionsbyZone+"");
						obj.put("iconclass","iconSessionsCompleted");
						tmpArr.add(obj);
						double usrSessnRatio=0;
						double totalCapcity=0;
						if(UniqueUserCnt != null && !UniqueUserCnt.equalsIgnoreCase("-")){
							try{
								Double unqUsr=Double.parseDouble(UniqueUserCnt);
								if(unqUsr > 0 && peakValue > 0){
									usrSessnRatio=unqUsr/peakValue;
									totalCapcity=usrSessnRatio*crntCapacity;
								}
							}
							catch(Exception ee){}
						}
						distrubutnObj.put("CapacityDemandTable",tmpArr);
						tmpArr=new JSONArray();
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Concurrent Sessions"));
						obj.put("value",crntCapacity+"");
						obj.put("iconclass","iconSessionsCompleted");
						tmpArr.add(obj);
						obj=new JSONObject();
						obj.put("name",intlmap.getTextDescription("reporter.common.Unique Users"));
						obj.put("value",erUtils.round(totalCapcity,0));
						obj.put("iconclass","iconLogonUser");
						tmpArr.add(obj);
						distrubutnObj.put("TotalCapacityTable",tmpArr);
						String distSummaryVal="During the period of "+strtDte+" - "+endDte+", peak load was at "+peakValue+" concurrent user sessions. Based on the resource consumption of the user sessions and the available resources on the "+serversCount+" servers, "+possibleSessionsbyZone+" additional sessions can be accommodated, which brings the total capacity to "+crntCapacity+" concurrent user sessions. Based on the User-to-Session ratio observered, "+crntCapacity+" concurrent user sessions roughly equates to "+erUtils.round(totalCapcity,0)+" unique users.";
						distSummaryVal="*Computed based on current user-to-session ratio";
						distrubutnObj.put("distributionSummary",distSummaryVal);
						resultsObj.put("DistributionDatas",distrubutnObj);


// Optimization panel Data Processing Starts Here
						JSONObject optimizatnObj=new JSONObject();
						JSONObject tmpObj=new JSONObject();
						int serverCnt=StstsList.size();
						obj=ctrxbean.getServerDetails(serverDatas,tmpObj,coulmnList,intlmap);
						optimizatnObj.put("ServerDetails",obj);
						JSONObject resourcelimitationMap=new JSONObject();
						if(obj != null && obj.containsKey("ResourcelimitatnMap"))
							resourcelimitationMap=(JSONObject)obj.get("ResourcelimitatnMap");
						ctrxbean.getOptimizationRecommendation(tmpObj,optimizatnObj,serverCnt,crntCapacity,usrSessnRatio,intlmap);
						//for Optimizing Capacity Datas
						ArrayList recm=new ArrayList();
						JSONArray Datastz=new JSONArray();
						JSONArray datasetArr=new JSONArray();
						JSONObject resourseTable=new JSONObject();
						JSONArray cpuLimitatnArr=new JSONArray();
						JSONArray memLimitatnArr=new JSONArray();
						JSONArray diskLimitatnArr=new JSONArray();
						JSONArray netwrkLimitatnArr=new JSONArray();
						if(resourcelimitationMap != null && resourcelimitationMap.size() > 0){
							Iterator resrceitr=resourcelimitationMap.keySet().iterator();
							while(resrceitr.hasNext()){
								String str=(String)resrceitr.next();
								String limtatnVal=(String)resourcelimitationMap.get(str);
								if(limtatnVal != null && limtatnVal.indexOf("CPU") >-1){
									if(cpuLimitatnArr != null && !cpuLimitatnArr.contains(str))
										cpuLimitatnArr.add(str);
								}
								else if(limtatnVal != null && limtatnVal.indexOf("Memory") >-1){
									if(memLimitatnArr != null && !memLimitatnArr.contains(str))
										memLimitatnArr.add(str);
								}
								else if(limtatnVal != null && limtatnVal.indexOf("Disk") >-1){
									if(diskLimitatnArr != null && !diskLimitatnArr.contains(str))
										diskLimitatnArr.add(str);
								}
								else if(limtatnVal != null && limtatnVal.indexOf("Network") >-1){
									if(netwrkLimitatnArr != null && !netwrkLimitatnArr.contains(str))
										netwrkLimitatnArr.add(str);
								}
							}
						}
						cpuCnt=cpuLimitatnArr.size();
						memoryCnt=memLimitatnArr.size();
						diskCnt=diskLimitatnArr.size();
						networkCnt=netwrkLimitatnArr.size();
						int maxLimitationVal = networkCnt;
						if(maxLimitationVal<cpuCnt)
						{
							maxLimitationVal = cpuCnt;
						}
						if(maxLimitationVal<memoryCnt)
						{
							maxLimitationVal = memoryCnt;
						}
						if(maxLimitationVal<diskCnt)
						{
							maxLimitationVal = diskCnt;
						}
						cpuLimitation=new ArrayList(cpuLimitatnArr);
						memoryLimitaion=new ArrayList(memLimitatnArr);
						diskLimitaion=new ArrayList(diskLimitatnArr);
						networkLimitation=new ArrayList(netwrkLimitatnArr);
						String queryStr="";
						String chartname=intlmap.getTextDescription("reporter.common.List of Servers Bottlenecked by ");
						if(memoryCnt > 0){
							String qstring="";
							if(memoryLimitaion != null && memoryLimitaion.size()>0)
							{
								for(int i=0;i<memoryLimitaion.size();i++){
									if (i == 0)
										qstring="ercomp="+(String)memoryLimitaion.get(i);
									else
										qstring=qstring+"&ercomp="+(String)memoryLimitaion.get(i);
								}
								queryStr=queryStr+qstring;
							}
							recm.add(new CustomSort("Memory",String.valueOf(memoryCnt)));
							obj=new JSONObject();
							obj.put("ServerCount",memoryCnt);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#FF7C78");
							obj.put("bottleneckParam","Memory");
							if(totalServersCount > 0)
								obj.put("percent",erUtils.round(((memoryCnt*100)/totalServersCount),0));
							obj.put("url","/final/reporter/ErCapacityPlanningDrillDownData.jsp?"+qstring+"&chartname="+erUtils.specialCharEncode(chartname)+" "+intlmap.getTextDescription("reporter.common.Memory"));
							resourseTable.put("Memory",obj);
							obj=new JSONObject();
							obj.put("name",intlmap.getTextDescription("reporter.common.Memory"));
							obj.put("y",new Double(memoryCnt));
							obj.put("color","#FF7C78");
							datasetArr.add(obj);
						}else{
							obj=new JSONObject();
							obj.put("ServerCount",0);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#FF7C78");
							resourseTable.put("Memory",obj);
						}
						if(diskCnt > 0){
							String qstring="";
							if(diskLimitaion != null && diskLimitaion.size()>0)
							{
								if(queryStr != null && !queryStr.equalsIgnoreCase(" "))
									queryStr+="&";
								for(int i=0;i<diskLimitaion.size();i++){
									if (i == 0)
										qstring="ercomp="+(String)diskLimitaion.get(i);
									else
										qstring=qstring+"&ercomp="+(String)diskLimitaion.get(i);
								}
								queryStr=queryStr+qstring;
							}
							recm.add(new CustomSort("Disk",String.valueOf(diskCnt)));
							obj=new JSONObject();
							obj.put("ServerCount",diskCnt);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#FFCD50");
							obj.put("bottleneckParam","Disk");
							obj.put("url","/final/reporter/ErCapacityPlanningDrillDownData.jsp?"+qstring+"&chartname="+erUtils.specialCharEncode(chartname)+" "+intlmap.getTextDescription("reporter.common.Disk"));
							if(totalServersCount > 0)
								obj.put("percent",erUtils.round(((diskCnt*100)/totalServersCount),0));
							resourseTable.put("Disk",obj);

							obj=new JSONObject();
							obj.put("name",intlmap.getTextDescription("reporter.common.Disk"));
							obj.put("y",new Double(diskCnt));
							obj.put("color","#FFCD50");
							datasetArr.add(obj);
						}
						else{
							obj=new JSONObject();
							obj.put("ServerCount",0);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#FFCD50");
							resourseTable.put("Disk",obj);
						}
						if(networkCnt > 0){
							if(queryStr != null && !queryStr.equalsIgnoreCase(" "))
									queryStr+="&";
							String qstring="";
							if(networkLimitation != null && networkLimitation.size()>0)
							{
								for(int i=0;i<networkLimitation.size();i++){
									if (i == 0)
										qstring="ercomp="+(String)networkLimitation.get(i);
									else
										qstring=qstring+"&ercomp="+(String)networkLimitation.get(i);
								}
								queryStr=queryStr+qstring;
							}
							recm.add(new CustomSort("Network",String.valueOf(networkCnt)));
							obj=new JSONObject();
							obj.put("ServerCount",networkCnt);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#99D3C5");
							obj.put("bottleneckParam","Network");
							obj.put("url","/final/reporter/ErCapacityPlanningDrillDownData.jsp?"+qstring+"&chartname="+erUtils.specialCharEncode(chartname)+" "+intlmap.getTextDescription("reporter.common.Network"));
							if(totalServersCount > 0)
								obj.put("percent",erUtils.round(((networkCnt*100)/totalServersCount),0));
							resourseTable.put("Network",obj);

							obj=new JSONObject();
							obj.put("name",intlmap.getTextDescription("reporter.common.Network"));
							obj.put("y",new Double(networkCnt));
							obj.put("color","#99D3C5");
							datasetArr.add(obj);
						}
						else{
							obj=new JSONObject();
							obj.put("ServerCount",0);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#99D3C5");
							resourseTable.put("Network",obj);
						}
						if(cpuCnt > 0){
							String qstring="";
							if(queryStr != null && !queryStr.equalsIgnoreCase(" "))
									queryStr+="&";
							if(cpuLimitation != null && cpuLimitation.size()>0)
							{
								for(int i=0;i<cpuLimitation.size();i++){
									if (i == 0)
										qstring="ercomp="+(String)cpuLimitation.get(i);
									else
										qstring=qstring+"&ercomp="+(String)cpuLimitation.get(i);
								}
								queryStr=queryStr+qstring;
							}
							recm.add(new CustomSort("CPU",String.valueOf(cpuCnt)));
							obj=new JSONObject();
							obj.put("ServerCount",cpuCnt);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#778AAA");
							obj.put("bottleneckParam","CPU");
							obj.put("url","/final/reporter/ErCapacityPlanningDrillDownData.jsp?"+qstring+"&chartname="+erUtils.specialCharEncode(chartname)+" "+intlmap.getTextDescription("reporter.common.CPU"));
							if(totalServersCount > 0)
								obj.put("percent",erUtils.round(((cpuCnt*100)/totalServersCount),0));
							resourseTable.put("CPU",obj);
							obj=new JSONObject();
							obj.put("name",intlmap.getTextDescription("reporter.common.CPU"));
							obj.put("y",new Double(cpuCnt));
							obj.put("color","#778AAA");
							datasetArr.add(obj);
						}else{
							obj=new JSONObject();
							obj.put("ServerCount",0);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#778AAA");
							resourseTable.put("CPU",obj);
						}
						double idleServerCnt=(totalServersCount-(cpuCnt+memoryCnt+diskCnt+networkCnt));
						if(idleServerCnt > 0){
							obj=new JSONObject();
							obj.put("ServerCount",idleServerCnt);
							obj.put("ServerMaxCount",maxLimitationVal);
							obj.put("color","#778AAA");
							obj.put("url","/final/reporter/ErCapacityPlanningDrillDownData.jsp?chartname="+erUtils.specialCharEncode(chartname)+" "+intlmap.getTextDescription("reporter.common.Idle"));
							resourseTable.put("Idle_Servers",obj);
						}
						JSONObject resourceLimitationGraph=new JSONObject();
						if(datasetArr != null && datasetArr.size() > 0){
							JSONArray breakdwnArr=new JSONArray();
							obj=new JSONObject();
							obj.put("data",datasetArr);
							breakdwnArr.add(obj);
							resourceLimitationGraph.put("DataSet",breakdwnArr);
						}
						resourceLimitationGraph.put("chartType","donut");
						resourceLimitationGraph.put("pieSize","180%");
						resourceLimitationGraph.put("innerSize","60%");
						resourceLimitationGraph.put("chartHeight","130");
						resourceLimitationGraph.put("chartWidth","130");
						resourceLimitationGraph.put("isShadowEnable",new Boolean(false));
						resourceLimitationGraph.put("enableTooltpPercent","true");
						optimizatnObj.put("limitingFactorTable",resourseTable);
						optimizatnObj.put("limitingFactorGraph",resourceLimitationGraph);
						if( er_site == null || (er_site != null && er_site.equalsIgnoreCase("null")))
							optimizatnObj.put("zoneName","--Dafault--");
						else
							optimizatnObj.put("zoneName",er_site);

						
						resultsObj.put("OptmizingCapacityDatas",optimizatnObj);
//						if(pvsEnv != null && pvsEnv.equalsIgnoreCase("Yes")){
//							resultsObj.put("showPvsData","Yes");
//							JSONObject pvsEnvDatas=ctrxbean.getPSVEnvDatas(overallSessionCnt,StstsList.size());
//							resultsObj.put("PVSEnvData",pvsEnvDatas);
//						}
//						else
//							resultsObj.put("showPvsData","no");
						if(serverTable_view  != null){
							resultsObj.put("servertableViewBy",serverTable_view);
						}
					}
					session.setAttribute("Capacity_Planning_Drilldown",serverDatas);
					JSONObject hrwiseData=null;
					HashMap dates=new HashMap();
					dates.put("StartDate",drillStartDate);
					dates.put("EndDate",drillEndDate);
					session.setAttribute("Capacity_Planning_Timeline",dates);
				}
			}// data found block
		}// er_submit block
		String strEncodeer_timeline = er_timeline;
		if(er_timeline != null)
			strEncodeer_timeline = EgURLEncoder.encode(er_timeline,"UTF-8");
		s_st_time  = request.getParameter("startdate");
		s_en_time  = request.getParameter("enddate");
		if(s_st_time != null && s_en_time != null && s_inidate != null)
		{
			s_st_time = EgURLEncoder.encode(s_st_time,"UTF-8");
			s_en_time = EgURLEncoder.encode(s_en_time,"UTF-8");
			s_inidate = EgURLEncoder.encode(s_inidate,"UTF-8");
		}
		String dataProcess = mngrIProc+"/final/reporter/ErCapacityPlanningReportPrint.jsp;jsessionid="+ session.getId()+"?er_comptype="+comp_type+"&er_datafrom="+datafrom+"&er_type="+er_type+"&startdate="+s_st_time+"&enddate="+s_en_time+"&timefrom="+timefrom2+"&minfrom="+minfrom2+"&timeto="+timeto2+"&minto="+minto2+"&starthr="+s_st_hr+"&endhr="+s_en_hr+"&er_timeline="+strEncodeer_timeline+"&startmin="+strmin+"&endmin="+enmin+"&inidate="+s_inidate+"&pageWidthProces=400"+"&er_option="+er_option+"&er_site="+er_site;
		String selcComp="";
		if(selectedComp != null) 
		{
			for(int l=0;l<selectedComp.length;l++)
				selcComp +="&er_component=" + EgURLEncoder.encode(selectedComp[l],"UTF-8");
		}
		session.setAttribute("MAIL_URL",dataProcess);
		session.setAttribute("PDF_URL", mngrIProc+"/final/reporter/ErCapacityPlanningReportPrint.jsp");
		rootJson.put("PDF_URL", "../reporter/ErHtmlToSavePdf.jsp?er_datafrom="+datafrom+"&er_type="+er_type+"&startdate="+request.getParameter("startdate")+"&enddate="+request.getParameter("enddate")+"&timefrom="+timefrom2+"&minfrom="+minfrom2+"&timeto="+timeto2+"&minto="+minto2+"&starthr="+s_st_hr+"&endhr="+s_en_hr+"&er_timeline="+er_timeline+"&startmin="+strmin+"&endmin="+enmin+"&inidate="+request.getParameter("inidate")+"&pageWidthProces=700&er_comptype="+comp_type+"&er_option="+er_option+"&er_site="+er_site+"&er_excwe="+excludeweekend+selcComp);
		queryString=(String)ErUtils.prepareQueryString(request.getParameterMap());
		String qString="";
		String qStringBackUrl = "";
		if(queryString!=null)
		{
			StringTokenizer strtok = new StringTokenizer(queryString,"&");
			while(strtok.hasMoreTokens())
			{
				String parameter = strtok.nextToken();
				int ind = parameter.indexOf("=");
				if (ind < 0)
					continue;
				String reqparam =parameter.substring(0,ind);
				String value = parameter.substring(ind+1);
				if(reqparam!=null) 
				{
					if ( reqparam.equals("call") )
					{
						continue;
					}
					if(reqparam.equals("er_component"))
					{
						value=com.eg.EgURLEncoder.encode(value, "UTF-8");
						//continue;
					} else if(reqparam.equals("startdate"))
					{
						value=com.eg.EgURLEncoder.encode(value, "UTF-8");
					} else if(reqparam.equals("enddate"))
					{
						value=com.eg.EgURLEncoder.encode(value, "UTF-8");
					} else if(reqparam.equals("inidate"))
					{
						value=com.eg.EgURLEncoder.encode(value, "UTF-8");
					} 
					qString += reqparam+"="+value+"&";
				}
			}
			if(request.getParameter("isSubmit")!=null)
			{
				session.setAttribute("reportLastAccessedURL","/final/reporter/ErCitrixCapacityPlanningReport.jsp?isSubmit=true&"+ qString);
			}
			else 
			{
				session.setAttribute("reportLastAccessedURL","/final/reporter/ErCitrixCapacityPlanningReport.jsp?" + qString);
			}
			rootJson.put("PRINT_URL", "/final/reporter/ErCapacityPlanningReportPrint.jsp?"+qString+"&pdfPrint=yes");
		}
	}
	catch(Throwable t)
	{
		t.printStackTrace();
	}
	//For Setting the PDf File Name
	HashMap paramVal =new HashMap();
	paramVal.put("fileName","CitrixCapacityPlanningReport");
	session.setAttribute("parameters", paramVal);
	//Back Button - Start
	ArrayList listbackvar = new  ArrayList();
	if(request.getParameter("isSubmit")!=null)
	{
		listbackvar.add("ErCitrixCapacityPlanningReport.jsp");
		listbackvar.add("status="+status+"&bggroundStr="+bggroundStr+"&"+queryString);
		session.setAttribute("favSchBackDisplay","Yes");
	}
	else 
	{
		listbackvar.add("ErCitrixCapacityPlanningReport.jsp");
		listbackvar.add(queryString);
		session.setAttribute("favSchBackDisplay","No");
	}
	String backadded = erhelputils.getBackID();
	backreqMap = erhelputils.setBackQueryMap(backreqMap,backadded,listbackvar);
	session.setAttribute("backQuery",backreqMap);
	//Back Button - End

	
	rootJson.put("selectedValues", selectedObj);
	rootJson.put("selectionDetails", selectionDetails);
	rootJson.put("screenLabels", screenLabels);
	rootJson.put("hiddens", hiddens);


	if ( !backgroundResultObj.isEmpty() )
	{
		rootJson.put("backgroundResults", backgroundResultObj);
	}
	if ( !resultsObj.isEmpty() )
	{
		rootJson.put("RESULTS", resultsObj);
	}
	out.println(rootJson.toString());
%>
