<%
/*******************************************************************************
*	File name		:	ErTopNReports.jsp
*	Purpose			:	Fetches Top N Descriptors based on Sortby option for Test ,Measure and 
*							Components and selected TimeFrame
*	Version			:	4.3
*	Author			:	Alagu sundaram. MR 
*	Creation Date	:	13/05/2003 - (dd/mm/yyyy)
*******************************************************************************/
%>

<%@ include file = "ErReporterTracker.jsp" %>
<%@ page import = "egurkha.reporter.*" %>
<%@ page import = "java.util.*"%>
<%@ page import = "egurkha.TransactionBean"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "java.sql.*"%>
<%@ page import = "com.eg.EgDbInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo,com.eg.EgTopoInfo,com.eg.EgSpecsInfo" %>
<%@ page import = "egurkha.EgCrawler" %>
<%@ page import = "com.eg.EgTopoInfo" %>
<%@ page import = "com.eg.EgTablesInfo" %>
<%@ page import = "com.eg.EgMappingInfo" %>
<%@ page import = "com.eg.EgReportInfo" %>
<%@ page import = "com.eg.EgDateInfo"%>
<%@ page import = "com.eg.EgServicesInfo" %>
<%@ page import = "com.eg.EgGroupInfo" %>
<%@ page import = "com.eg.MappingNameSorter" %>
<%@ page import = "egurkha.EgCrawler" %>
<%@ page import = "com.eg.EgViewInfo" %>
<%@ page import	= "com.eg.EgURLEncoder" %>
<%@ page import = "java.net.URLEncoder" %>
<%@ page import = "java.net.URLDecoder" %>
<%@ page import = "com.eg.MappingNameSorter"%>
<%@ page import = "com.eg.EgName"%>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "com.egurkha.util.DateTimeTokenizer" %>
<%@ page import = "com.egurkha.util.DateUtil" %>
<%@ page import = "com.egurkha.util.*" %>
<%@ page import = "java.text.*" %>
<%@ page import = "com.eg.EgConfigInfo"%>
<%@ page import = "com.egurkha.util.ListUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="egui" uri="../WEB-INF/eg-taglib.tld" %>
<%@ page import = "net.sf.json.*" %>
<%@ page import="com.egurkha.util.StringUtils"%>

<%
try
{
	response.setContentType("application/json");

	JSONObject combo=new JSONObject();
	JSONObject urlFields=new JSONObject();
	JSONObject displayFields=new JSONObject();
    JSONObject hiddenFields = new JSONObject();
	JSONObject selectedFields = new JSONObject();
	JSONObject selectionDetails = new JSONObject(); 
	JSONObject rootJson = new JSONObject();
  	JSONObject loopJsonObj = new JSONObject();

	String bggroundStr = (String)request.getAttribute("bggroundStr");
	String status = (String)request.getAttribute("status");

	//Back Button - Start

	HashMap backreqMap = (HashMap)session.getAttribute("backQuery");
	String backQnumber = request.getParameter("backQnumber");
	String servlet2 = request.getParameter("backServletName");
	String chartIndex = request.getParameter("chartIndex");
	rootJson.put("chartIndex",chartIndex);
	String strtitle="";
	ErHelperUtils erhelputils = null;
	String userid = UBean.getUserId();

	ErUserData user=new ErUserData(userid,false);


	if(servlet2!=null && !servlet2.equals(""))
		erhelputils = new ErHelperUtils(backreqMap,backQnumber,servlet2);
	else
		erhelputils = new ErHelperUtils(backreqMap,backQnumber);

	boolean enableBack=erhelputils.isBackButtonEnable();
	String backButtonEnable = request.getParameter("back");
	rootJson.put("ID","backQnumber="+erhelputils.getBackID()+"&"+erhelputils.getQueryString());
	if(backButtonEnable != null && backButtonEnable.equalsIgnoreCase("True"))
	{
		status = (String)request.getParameter("status");
		request.setAttribute("TopNReportData",null);
		bggroundStr = (String)request.getParameter("bggroundStr");
	}
	//Back Button - End

	EgServicesInfo si = new EgServicesInfo("manager");
	EgViewInfo egviewinfo = new EgViewInfo("manager");
	EgDbInfo dbInfo = new EgDbInfo("manager");
	EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
	ErInfo erInfo = new ErInfo();
	EgTablesInfo tablesInfo = new EgTablesInfo("manager");
	ErReqData erd = new ErReqData(request);
	ErReportHelper er_helper = new ErReportHelper();
	ErUtils erUtils = new ErUtils();
	EgDateInfo egDt = new EgDateInfo();
	EgGroupInfo gpinfo = new EgGroupInfo();
	EgReportInfo reportinfo = new EgReportInfo("manager");
	String confrimation = reportinfo.getValue("BACKGROUND_PROCESS","NeedConfirmation");
	String strbgrepportName = reportinfo.getValue("BACKGROUND_PROCESS","EnableBackgroundReport");
	String limitforbg = reportinfo.getValue("BACKGROUND_PROCESS","MinDurationForReport");

	IniUI ui = IniUI.getInstance();
	UserRegistry tregistry = UserRegistry.getInstance();
	User tuser = tregistry.getUser(session.getId());
	String thisLanguage = ui.getDefaultLanguage();
	MappingNameSorter sorter = new MappingNameSorter(thisLanguage);
	if (tuser!=null)
	{
		String userLang = tuser.getLanguage();
		if (userLang!=null && !userLang.equalsIgnoreCase("NULL"))
		{
			thisLanguage=userLang;
		}
	}
	ErRemoteScriptingBean remoteAsLocalbean = new ErRemoteScriptingBean(UBean);
	EgMappingInfo intlmap = new EgMappingInfo(thisuser.getLanguage());
	User usr = UserRegistry.getInstance().getUser(session.getId());
	ErComponentsUtils compUtils = new ErComponentsUtils(usr.getLoginID());
	IniFile iniObj;
	iniObj=new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_report.ini");
	String mngrIProc = new IniFile(new EgConfigInfo("manager").getDbFile()).getValue("DB_PROPERTIES","ManagerUrl");

	//For Sorting
	ArrayList serverList = new ArrayList();
	//MappingNameSorter sorter = new MappingNameSorter(thisLanguage);

	java.util.Date local_date = new java.util.Date(egDt.egetUTCDate());
	Calendar cal = Calendar.getInstance();

	String varCompaTemplate[];
	String selTempl="" ;
	Vector v_template=new Vector();
	Vector v_templateValue=new Vector();
	boolean templateEnable=false;
	boolean valueFound=false;

	String show_timeinuse = request.getParameter("sh_timeinuse");
	String s_template=request.getParameter("er_template");
	String er_templateEnable=request.getParameter("er_templateEnable");

	if (s_template==null)
		s_template=iniObj.getValue("REPORT_TEMPLATES","UseTemplates");
	String s_site = request.getParameter("er_site");
	String s_test = request.getParameter("er_test");
	String st_dataFrom = request.getParameter("er_dataFrom");
	String isForceSubmit = request.getParameter("isForceSubmit");
	String rmComponentType = request.getParameter("rmComponentType");

	if(st_dataFrom==null || (st_dataFrom!=null && st_dataFrom.equals("")))
	{
		st_dataFrom="Component";
	}

	//added by srinivasulu p
	String starttimeformat = "";
	String endtimeformat = "";
	String s_tit = new String();
	List lst = new LinkedList();
	List lst_dat = new LinkedList();
	Vector vec=new Vector();
	Vector vec1=new Vector();
	Hashtable ht = new Hashtable();
	Hashtable ht1 = new Hashtable();
	//until this
	String sel_comp="";
	String sel_service="";
	Vector v_service=null;
	String s_service="";
	s_service = request.getParameter("er_service");
	String trendQuery="";
	if(request.getParameter("er_trenddata")!=null)
		trendQuery = request.getParameter("er_trenddata");
	String includezone=request.getParameter("er_dataZone");
	String s_meas = request.getParameter("er_measure");
	String arr_comp[] = request.getParameterValues("er_component");
	String arr_info[] =  request.getParameterValues("er_info_list");
	String s_combination = request.getParameter("er_combination");
	String arr_selection[] = request.getParameterValues("er_selection");
	String reqFromSchedule = request.getParameter("fromSchedule");
	String fromScheduleModify = request.getParameter("fromScheduleModify");
	String er_favorite = request.getParameter("er_favorite");
	String fromFavoriteModify = request.getParameter("fromFavoriteModify");
	String favorite_id = request.getParameter("id");
	String schedule_id = request.getParameter("schedule_id");
	String s_comp=request.getParameter("er_component");
	String isSubmitForDesc=request.getParameter("isSubmit");
	String divStatus = request.getParameter("divStatus");
	String srcForImg="";
	String treeCompType=request.getParameter("treeCompType");

	String s_treeParam = request.getParameter("treeParam");

	if(arr_info!=null && arr_info.length>0)
	{
		for(int cnt=0;cnt<arr_info.length;cnt++)
		{
			String str = arr_info[cnt];
			str = erUtils.specialCharDecode(str);
			arr_info[cnt] = str;
		}
	}
	if(includezone == null || includezone.length() == 0)
		includezone = "yes";
	if(divStatus==null)
	{
	divStatus="none";
	}
	if(divStatus.equals("none"))
	{
		srcForImg="../images/moreoption.png";
	}
	else if(divStatus.equals("block"))
	{
		srcForImg="../images/lessoption.png";
	}
	Hashtable chart=null;
	String repTypeGraph="",repTypeData="";
	String qryString="";

	String reportType=request.getParameter("er_reportType");
	if (reportType==null || (reportType!=null && reportType.equals("")))
		reportType="graph";
	String sortby = request.getParameter("er_sortby");
	if (sortby==null || sortby.equals(""))
		sortby="Avg";
	String excludeweekend = request.getParameter("er_excwe");
	if (excludeweekend==null || excludeweekend.equals(""))
		excludeweekend="No";
	String showInfo=request.getParameter("er_showinfo");

	String er_groupby=request.getParameter("er_groupby");
	if (er_groupby==null || er_groupby.equals(""))
		er_groupby="Component_Descriptor";
	if(showInfo!=null && showInfo.length()>0)
	{
		if(showInfo.equalsIgnoreCase("Yes"))
		{
			er_groupby="Component_Descriptor";
		}
		else
		{
			er_groupby="Component";
		}
	}

	Vector v_sortby = new Vector();
	v_sortby.add("Avg");
	v_sortby.add("Max");
	v_sortby.add("Min");

	Vector v_test = er_helper.getAllMetaTests();
	String tests ="";
	if(rmComponentType!=null)
	{
		v_test = new Vector();
		tests=remoteAsLocalbean.getTestsForComponent("dummy:" + rmComponentType);
		StringTokenizer strz = new StringTokenizer(tests, "*");
		while(strz.hasMoreTokens())
		{
			String tempTest = strz.nextToken();
			v_test.add(tempTest);
		}
	}
	Vector filteredTests =(Vector)v_test.clone();
	if(rmComponentType != null && !rmComponentType.trim().equals("")) 
	{
		v_test = new Vector();
		for(int u=0; u < filteredTests.size(); u++)
		{
			String testToFilter = (String)filteredTests.get(u);
			if(specsInfo.isTestRelevantForServer(rmComponentType,testToFilter))
				v_test.add(testToFilter);
		}
	}
	v_template = er_helper.getMetaTemplateForSite(s_site);
	Vector userTests = (Vector)v_test.clone();
	Map usrTest = usr.getTests();
	v_test = new Vector();
	if(userTests!=null)
	{
		if(usrTest!=null)
		{
			for(int u=0; u < userTests.size(); u++)
			{
				if(usrTest.containsKey((String)userTests.get(u)))
				{
					String strUserTest=(String)userTests.get(u);
					if (!com.eg.EgInstallInfo.isConfigTest(strUserTest))
						v_test.add(strUserTest);
				}
			}
		}
	}
	if(!templateEnable)
	{
		serverList = sorter.getSortedTestList(v_test);
		if(s_test == null && serverList != null && serverList.size() > 0)
		{
			EgName nameObj = (EgName)serverList.get(0);
			String tmpVal = nameObj.getActualName();
			s_test = tmpVal;
		}
	}
	Vector v_compare=new Vector();
	v_compare.addElement("Zone");
	v_compare.addElement("Service");
	v_compare.addElement("Segment");
	v_compare.addElement("Component");

	Vector v_comp=new Vector();
	Vector v_infos=new Vector();
	Vector v_temp=new Vector();
	List servComponentList = null;

	Vector v_allcomp = compUtils.getAllUserComponents1();
	Vector vectestrelgroup=new Vector();
	List zoneList = compUtils.getUserZones();
	if(zoneList != null && zoneList.contains("--Default--"))
		zoneList.remove("--Default--");
	ArrayList listzonecomponents= new ArrayList();
	for (int z=0;z<zoneList.size();z++)
	{
		String zone = (String)zoneList.get(z);
		listzonecomponents.addAll(compUtils.getTypeModifyComponents(compUtils.getZoneComponents(zone,true),2));
	}
	if(isForceSubmit!=null && isForceSubmit.equals("true") && s_treeParam!=null && s_treeParam.trim().length()>0
		&& (st_dataFrom!=null &&(st_dataFrom.equalsIgnoreCase("Zone") ||st_dataFrom.equalsIgnoreCase("Service") || st_dataFrom.equalsIgnoreCase("Segment"))))
			s_service = s_treeParam;

	// get component for zone,service,segment
	if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Zone"))
	{
		if(s_service!=null && !s_service.equals("-1") && !s_service.equalsIgnoreCase("NULL"))
		{
			String s_service1 = "";
			if(s_service.indexOf("-view:")>-1)
				s_service1 = s_service.substring(0,s_service.indexOf("-view:")).trim();
			else
				s_service1 = s_service;

			if((includezone != null && includezone.equalsIgnoreCase("yes")) || s_service.indexOf("-view:")>-1)
				v_comp.addAll(compUtils.getTypeModifyComponents(compUtils.getZoneComponents(s_service1,true),2));
			else
				v_comp.addAll(compUtils.getTypeModifyComponents(compUtils.getZoneComponents(s_service1,false),2));

			Vector vecforview=new Vector();
			if(s_service.indexOf("-view:")>-1)
			{
				Vector v_incom = egviewinfo.getviewComponents(s_service.substring(s_service.indexOf("-view:")+"-view:".length()));
				for(int m=0;m<v_incom.size();m++)
				{
					if(v_comp.contains(v_incom.get(m).toString().trim()))
					{
						vecforview.add((String)v_incom.get(m));
					}
				}
				v_comp = new Vector();
				v_comp = vecforview;
			}
			if(isForceSubmit!=null && isForceSubmit.equals("true") && s_treeParam!=null && s_treeParam.trim().length()>0) 
			{
				if(includezone!=null && includezone.equalsIgnoreCase("yes"))
					servComponentList = new ArrayList(compUtils.getZoneComponents(s_service,true));
				else
					servComponentList = new ArrayList(compUtils.getZoneComponents(s_service,false));
			}
		}
	}
	else if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Service"))
	{
		if(isForceSubmit!=null && isForceSubmit.equals("true") && s_treeParam!=null && s_treeParam.trim().length()>0)
			servComponentList = new ArrayList(compUtils.getServiceComponents(s_service));
		if(s_service!=null && !s_service.equals("-1"))
			v_comp = compUtils.getTypeModifyComponents(compUtils.getServiceComponents(s_service),2);
	}
	else if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Segment"))
	{
		if(s_service!=null && !s_service.equals("-1"))
			v_comp = compUtils.getTypeModifyComponents(compUtils.getSegmentComponents(s_service),2);
		if(isForceSubmit!=null && isForceSubmit.equals("true") && s_treeParam!=null && s_treeParam.trim().length()>0)
			servComponentList = new ArrayList(compUtils.getSegmentComponents(s_service));
	}
	else
	{
		v_comp = compUtils.getAllUserComponents1();
	}
	//get test for zone,service and segment component
	if((st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Zone") || st_dataFrom.equalsIgnoreCase("Segment") || st_dataFrom.equalsIgnoreCase("Service"))|| (s_service!=null && !s_service.equals("")))
	{
		Vector vecTemplaterelgroup = new Vector();
		if(v_template!=null && v_comp!=null && v_comp.size()>0)
		{
			for(int i=0; i<v_template.size(); i++)
			{
				String strTemplateName = (String)v_template.get(i);
				String tempVal=iniObj.getValue("REPORT_TEMPLATES",strTemplateName);
				String strTest_temp =tempVal; 
				if(tempVal!=null && tempVal.indexOf(":")>-1)
					strTest_temp=tempVal.substring(0,tempVal.indexOf(":"));

				for(int a=0;a<v_comp.size();a++)
				{
					String compname=(String)v_comp.get(a);
					if(st_dataFrom!=null&& s_service!=null && !s_service.equalsIgnoreCase("--Default--"))
					{
						if(specsInfo.isTestRelevantForServer(compname.substring(0,compname.indexOf(":")),strTest_temp))
						{
							if(!vecTemplaterelgroup.contains(strTemplateName))
								vecTemplaterelgroup.add(strTemplateName);
						}
					}
					else
					{
						if(specsInfo.isTestRelevantForServer(compname.substring(compname.lastIndexOf(":")+1),strTest_temp))
						{
							if(!vecTemplaterelgroup.contains(strTemplateName))
								vecTemplaterelgroup.add(strTemplateName);
						}
					}
				}
			}
			v_template = new Vector();
			if(vecTemplaterelgroup!=null && vecTemplaterelgroup.size()>0)
				v_template.addAll(vecTemplaterelgroup);
		}
		if(v_test!=null && v_comp!=null && v_comp.size()>0){
		for(int t=0;t<v_test.size();t++)
		{
			for(int a=0;a<v_comp.size();a++)
			{
				String compname=(String)v_comp.get(a);
				if(st_dataFrom!=null&& s_service!=null && !s_service.equalsIgnoreCase("--Default--"))
				{
					if(specsInfo.isTestRelevantForServer(compname.substring(0,compname.indexOf(":")),(String)v_test.get(t)))
					{
						if(!vectestrelgroup.contains((String)v_test.get(t)))
							vectestrelgroup.add((String)v_test.get(t));
					}
				}
				else
				{
					if(specsInfo.isTestRelevantForServer(compname.substring(compname.lastIndexOf(":")+1),(String)v_test.get(t)))
					{
						if(!vectestrelgroup.contains((String)v_test.get(t)))
							vectestrelgroup.add((String)v_test.get(t));
					}
				}
			}
		}
			v_test=new Vector();
			v_test.addAll(vectestrelgroup);
		}
	}
	if(v_test!=null && v_test.size()>0 && !v_test.contains(s_test))
	{
		s_test=(String)v_test.get(0);
	}
	Vector v_meas = erInfo.getMeasuresForTest(1,s_test);
	if (v_meas != null)
	{
		Collections.sort(v_meas,String.CASE_INSENSITIVE_ORDER);
	}
	ArrayList testList = new ArrayList();

	testList = sorter.getSortedMeasureList(s_test,v_meas);
	Vector mappingMeasure = new Vector();
	v_meas = new Vector();
	for(int i=0;i<testList.size();i++)
	{
		EgName nameObj = (EgName)testList.get(i);
		String val = nameObj.getActualName();
		String dis = nameObj.getLocalName();
		v_meas.add(val);
		mappingMeasure.add(intlmap.getMeasureDescription(s_test,val));
	}
	if(s_meas == null && v_meas != null && v_meas.size() > 0)
	{
		s_meas = (String)v_meas.get(0);
	}
	if(st_dataFrom!=null && !st_dataFrom.equalsIgnoreCase("Component"))
	{
		if(s_service!=null && !s_service.equals("-1"))
		{
			if(!s_service.equalsIgnoreCase("--Default--"))
				if(v_comp==null)
					v_comp=new Vector();

				for(int i=0;i<v_comp.size();i++)
				{
					String s_tmp=(String)v_comp.elementAt(i);
					String str_comptype=s_tmp.substring(0,s_tmp.indexOf(":"));
					String str_compname=s_tmp.substring(s_tmp.indexOf(":")+1);
					String s_component = str_compname +":"+str_comptype;
					v_comp.setElementAt(s_component,i);
				}
		}
	}
	if(s_test != null && !s_test.equalsIgnoreCase("-1"))
	{
		Vector vecTemp = new Vector();
		for(int i=v_comp.size()-1;i>=0;i--)
		{
			String s_com = v_comp.get(i).toString();
			if(!specsInfo.isTestRelevantForServer(s_com.substring(s_com.lastIndexOf(":")+1),s_test) && st_dataFrom!=null && !st_dataFrom.equals("Segment") && !st_dataFrom.equals("Service"))
			{
				v_comp.removeElementAt(i);
			}
			else
			{
				if(treeCompType!=null && !treeCompType.equalsIgnoreCase("NULL"))
				{
					String strType = s_com.substring(s_com.lastIndexOf(":")+1);
					if(!treeCompType.equalsIgnoreCase(strType))
						vecTemp.add(v_comp.get(i));
				}
			}
		}
		if(vecTemp!=null && vecTemp.size()>0)
		{
			v_comp.removeAll(vecTemp);
		}
		arr_comp = erd.getComponents();
	}
	else
	{
		v_comp.removeAllElements();
	}
	Collections.sort(v_comp);

	Vector v_componetdisp=new Vector();
	for(int i=0;i<v_comp.size();i++)
	{
		String dispcomp=(String)v_comp.get(i);
		if(dispcomp.indexOf(":NULL")>-1)
		{
			v_componetdisp.add(dispcomp.substring(0,dispcomp.indexOf(":NULL"))+":"+dispcomp.substring(dispcomp.indexOf("NULL:")+5));
		}
		else
		{
			v_componetdisp.add(dispcomp);
		}
	}
	if (s_combination==null	|| s_combination.equals(""))
	{
		arr_comp = new String[v_comp.size()];
		for(int	i=0;i<arr_comp.length;i++)
			arr_comp[i]	= (String)v_comp.get(i);
	}
	String s_end_time="";
	String s_start_time="";
	String timefrm="";
	String time2="";
	long msecsPerHour = (long) 1000 * 60*60 ;
	if(s_comp!=null && !s_comp.equals("")&& arr_comp !=null)
	{
		if(s_site == null || s_site.equals("-1") || s_site.equals("null"))
			s_site=null;


		if(!user.hasAllComponentAccess())
		{
			for(int s=0;s<arr_comp.length;s++)
			{
				v_infos.addAll(erInfo.getInfosForTest(s_site,s_test,arr_comp[s]));
			}
		}else
			v_infos.addAll(erInfo.getInfosForTest(s_test));



		v_infos = ErUtils.formatString(v_infos,"$0+$1","$1");
		v_infos = ListUtils.removeDuplicates(v_infos,true);
		Collections.sort(v_infos,String.CASE_INSENSITIVE_ORDER);
	}
	else if(s_comp == null && s_test!=null && arr_comp != null)
	{
		if(s_site == null || s_site.equals("-1") || s_site.equals("null"))
			s_site=null;
		if(!user.hasAllComponentAccess())
		{
			for(int s=0;s<arr_comp.length;s++)
			{
				v_infos.addAll(erInfo.getInfosForTest(s_site,s_test,arr_comp[s]));
			}
		}else
			v_infos.addAll(erInfo.getInfosForTest(s_test));

		v_infos = ErUtils.formatString(v_infos,"$0+$1","$1");
		v_infos = ListUtils.removeDuplicates(v_infos,true);
		Collections.sort(v_infos,String.CASE_INSENSITIVE_ORDER);
	}
	Vector v_qry_string = (Vector) request.getAttribute("chartData");
	Vector v_pdf_qry = (Vector)request.getAttribute("pdfData");
	Hashtable ht_Data= (Hashtable)request.getAttribute("TopNReportData");
	boolean isFromDrillDown = ("y".equals(request.getParameter("isFromDrillDown")))? true : false;

	if(isFromDrillDown){
		session.setAttribute("drillDownData",ht_Data);
	}
	if(ht_Data!=null && ht_Data.size()>0)
	{
		if(ht_Data.containsKey("sampleValues_0"))
			reportType="graph";
		else
			reportType="data";
	}
	session.setAttribute("TopNReportData",ht_Data);

	int chartCount = -1;
	int compareLimit = er_helper.getCompareLimit();
	int count=0;
	int maxInfo = er_helper.getMaxInfos("INFOS","Showtop");
	String timefrom1=(er_helper.getTimeFrame("TIMEFRAME","From")==null) ? "00:00" :er_helper.getTimeFrame("TIMEFRAME","From");
	String timeto1=(er_helper.getTimeFrame("TIMEFRAME","To")==null) ? "23:59" :er_helper.getTimeFrame("TIMEFRAME","To");
	
	String timefrom="";
	String minfrom="";
	String timeto="";
	String minto="";
	StringTokenizer st=new StringTokenizer(timefrom1,":");
	if(st.hasMoreTokens())
	{
		timefrom=st.nextToken();
		minfrom=st.nextToken();
	}
	st=new StringTokenizer(timeto1,":");
	if(st.hasMoreTokens())
	{
		timeto=st.nextToken();
		minto=st.nextToken();
	}
	String Days=(er_helper.getExcludeWeekends("EXCLUDE_WEEKEND","Days")==null) ? "Saturday,Sunday" :er_helper.getExcludeWeekends("EXCLUDE_WEEKEND","Days");
	request.setAttribute("Weekends",Days);

	Vector v_show=new Vector();
	v_show.add("TOP  - " +maxInfo/4);
	v_show.add("TOP  - " +maxInfo/2);
	v_show.add("TOP  - " +maxInfo);
	v_show.add("ALL");
	v_show.add("LAST  - " +maxInfo);
	v_show.add("LAST  - " +maxInfo/2);
	v_show.add("LAST  - " +maxInfo/4);

	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 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;
	
	String priority=request.getParameter("er_priority");
	if(priority==null || priority.equals(""))
		priority="TOP  - " +maxInfo;

	String pdfStartDate = request.getParameter("startdate");
	String pdfStartHr = request.getParameter("starthr");
	String pdfEndDate=request.getParameter("enddate");
	String pdfEndHr = request.getParameter("endhr");
	
	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = strUserDateFormat;
	String comFormat = null;
	EgTimeZoneConverter converterStart=null;
	EgTimeZoneConverter converterEnd=null;
	
	String st_dateTime="";
	String en_dateTime="";
	if(pdfStartDate!=null)
	{
		if(DateUtil.isDate(pdfStartDate,"MM/dd/yyyy"))
		{
			comFormat = currentDateFormat;
			pdfStartDate = DateUtil.changeDateFormat(pdfStartDate,"MM/dd/yyyy",comFormat);
		}
		converterStart = new EgTimeZoneConverter(pdfStartDate+" "+pdfStartHr+":"+"00",tuser);
		st_dateTime = converterStart.getDateTime();
	}
	if(pdfEndDate!=null)
	{
		if(DateUtil.isDate(pdfEndDate,"MM/dd/yyyy"))
		{
			comFormat = currentDateFormat;
			pdfEndDate = DateUtil.changeDateFormat(pdfEndDate,"MM/dd/yyyy",comFormat);
		}
		converterEnd = new EgTimeZoneConverter(pdfEndDate+" "+pdfEndHr+":"+"00",tuser);
		en_dateTime = converterEnd.getDateTime();
	}
	String pdfTime = "From "+st_dateTime+" hrs "+""+" To "+ en_dateTime+"  hrs";
	Vector topNPdfData = new Vector();
	topNPdfData = (Vector)request.getAttribute("topNPdfData");
	if(topNPdfData!=null && !topNPdfData.isEmpty())
	{
		topNPdfData.removeElementAt(0);
		topNPdfData.insertElementAt(pdfTime,0);
	}	
	String opt=request.getParameter("er_trenddata");
	if(opt==null)
		opt="No";
	
	String detailval= iniObj.getValue("MISC","DetailedTime");	
	Vector v_listall =new Vector();
	v_listall.add("Zone");
	v_listall.add("Segment");
	v_listall.add("Service");
	v_listall.add("Component");
	String s_list=request.getParameter("er_dataFrom");
	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 er_timeline=request.getParameter("er_timeline");
	
	if(er_timeline==null  || er_timeline.equals(" "))
	{
		er_timeline="1 day";
	}
	//Date calculation according to time select
		
	String[] options=null;
	if(opt!=null && opt.equals("No"))
	{
		 options = new String[]{"Any","1 hour", "3 hours", "6 hours", "9 hours", "12 hours", "15 hours", "18 hours", "21 hours","1 day", "2 days", "3 days", "4 days", "5 days", "6 days","1 week","2 weeks","3 weeks","4 weeks","1 month"};
	}
	else 
	{
		if(er_timeline!=null && !er_timeline.equals("Any"))
		{
			String tmp=er_timeline.substring(er_timeline.indexOf(" ")+1,er_timeline.length());
			
			if(tmp.startsWith("h"))
			{
				er_timeline="1 day";
			}

		}
		options =new String[]{"Any","1 day", "2 days", "3 days", "4 days", "5 days", "6 days","1 week","2 weeks","3 weeks","4 weeks","1 month"};
	}
	String startDateTime="";
	String endDateTime="";
	String dispDate = null;
	String stmin = null;
	String enmin = null;
	String strEncodedUserID = urs;
	if(urs!=null )
		strEncodedUserID = EgURLEncoder.encode(urs,"UTF-8");
	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();
			if(opt!=null && opt.equals("No"))
			{
				endDateTime = sdf.format(today);
			}
			else
			{
				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"))
			{//weeks
				value *= (7 * 24 * 3600);
			}
			else if (unit.startsWith("mo"))
			{//months
				if(opt!=null && opt.equals("No"))
				{
					java.util.Date dt_temp = new java.util.Date(egDt.egetUTCDate());
					Calendar cal_temp = new GregorianCalendar();
					cal_temp.setTime(dt_temp);
					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");
				}
				else
				{
					java.util.Date dt_temp = new java.util.Date(endDateTime);
					Calendar cal_temp = new GregorianCalendar();
					cal_temp.setTime(dt_temp);
					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"))
			{
				java.util.Date start = egDt.egetRealDate();
				java.util.Date startTmp=new java.util.Date(endDateTime);
				start.setTime(startTmp.getTime() - (value * 1000));
				startDateTime = sdf.format(start);
			}
		}
		if ((startDateTime != null) && (endDateTime != null))
		{
			String shr = startDateTime.substring(startDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, startDateTime.indexOf(":"));  
			String en_hr = endDateTime.substring(endDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, endDateTime.indexOf(":"));
			stmin=startDateTime.substring(startDateTime.indexOf(":")+1);
			enmin=endDateTime.substring(endDateTime.indexOf(":")+1);
			s_en_time=endDateTime.substring(0, endDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
			s_st_time=startDateTime.substring(0, startDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE));
			if(opt!=null && opt.equals("No"))
			{
				s_st_hr = shr;
				s_en_hr = en_hr;
			}
		}
	}
	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;
		}
		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 st_date = request.getParameter("startdate");
	String en_date = request.getParameter("enddate");
	String tpnRpt = "Top N";
	StringBuffer printQString= new StringBuffer();
	printQString.append("er_gtype=Comparison");
	printQString.append("&er_rtype="+EgURLEncoder.encode(tpnRpt,"UTF-8"));
	printQString.append("&er_trgttype="+EgURLEncoder.encode(tpnRpt,"UTF-8"));
	printQString.append("&er_timeline="+EgURLEncoder.encode(request.getParameter("er_timeline"),"UTF-8"));
	if(st_date !=null && en_date !=null)
	{
		printQString.append("&startdate=" + EgURLEncoder.encode(st_date,"UTF-8"));
		printQString.append("&enddate=" + EgURLEncoder.encode(en_date,"UTF-8"));
	}
	else
	{
		printQString.append("&startdate=" + st_date);
		printQString.append("&enddate=" + en_date);
	}
	printQString.append("&starthr="+request.getParameter("starthr"));
	printQString.append("&startmin="+request.getParameter("startmin"));
	printQString.append("&endhr="+request.getParameter("endhr"));
	printQString.append("&endmin="+request.getParameter("endmin"));
	printQString.append("&er_mode="+request.getParameter("er_mode"));
	printQString.append("&er_excwe="+request.getParameter("er_excwe"));
	printQString.append("&er_test="+s_test);
	printQString.append("&er_trenddata="+request.getParameter("er_trenddata"));
	printQString.append("&er_measure="+s_meas);
	printQString.append("&er_sortby="+sortby);
	printQString.append("&timefrom="+timefrom2);
	printQString.append("&minfrom="+minfrom2);
	printQString.append("&timeto="+timeto2);
	printQString.append("&minto="+minto2);
	printQString.append("&userID="+strEncodedUserID);
	if(arr_selection!=null)
	{
		for(int k =0;k<arr_selection.length;k++)
			printQString.append("&er_selection="+ arr_selection[k]);
	}
	printQString.append("&option=data&printGraph=yes");
	printQString.append("&er_reportType="+reportType);
	String titleToDisplay = "";
	String er_RmDispName = request.getParameter("er_RmDispName");
	if(er_RmDispName!=null && er_RmDispName.length()>0) {
		titleToDisplay = er_RmDispName.trim();
		printQString.append("&er_RmDispName="+er_RmDispName);
	}else
		titleToDisplay = intlmap.getTextDescription("reporter.comparison.COMPARISON REPORTS")+"-"+intlmap.getTextDescription("reporter.operation.TOP N");

	rootJson.put("reportTitle",titleToDisplay);

	boolean compute= si.getAvgSumTrends();

	//hiddenFields.put("er_combination","");
	hiddenFields.put("er_rtype","Top N");
	hiddenFields.put("er_gtype","Comparison");
	hiddenFields.put("fromSchedule",reqFromSchedule);
	if(fromScheduleModify!=null)
		hiddenFields.put("fromScheduleModify",fromScheduleModify);

	if(fromFavoriteModify!=null)
		hiddenFields.put("fromFavoriteModify",fromFavoriteModify);

		hiddenFields.put("favorite_id", favorite_id);
		hiddenFields.put("er_favorite", er_favorite);

	String callFromReport = request.getParameter("callFromReport");
	String rmComponent = request.getParameter("rmComponent");
	List ls = null;
	if((rmComponentType!=null && !rmComponentType.equals("") && (rmComponent==null || rmComponent.equals("undefined"))) || ((st_dataFrom!=null &&(st_dataFrom.equalsIgnoreCase("Zone") ||st_dataFrom.equalsIgnoreCase("Service") || st_dataFrom.equalsIgnoreCase("Segment"))) &&s_treeParam!=null && !s_treeParam.equals("") && (rmComponent==null || rmComponent.equals("undefined")))) {
		ErComponentsUtils computils = new ErComponentsUtils(usr);
		if(s_treeParam!=null && s_treeParam.trim().length()>0 && servComponentList!=null && servComponentList.size()>0)
			ls = new ArrayList(servComponentList);
		else
			ls = computils.getServerForTypesRepMenu(v_comp,rmComponentType);
		String s_comps=ls.toString().substring(1);
		s_comps = s_comps.substring(0,s_comps.length()-1);
		if(s_comps!=null && !s_comps.equals("")){
			if(s_comps.indexOf(",")>-1)
				s_comps=s_comps.replaceAll(", ", ",");
			rmComponent = s_comps;
		}
	}
	hiddenFields.put("treeCompType", treeCompType);
	hiddenFields.put("isForceSubmit", isForceSubmit);
	hiddenFields.put("callFromReport", callFromReport);
	hiddenFields.put("rmComponentType", rmComponentType);
	hiddenFields.put("rmComponent", rmComponent);

	hiddenFields.put("schedule_id",schedule_id);
	hiddenFields.put("er_ViewName","ErTopNReports.jsp");
	hiddenFields.put("er_trgttype","Top N");
	hiddenFields.put("er_graphtype","");
	hiddenFields.put("pdfTime",pdfTime);
	hiddenFields.put("userID",urs);
	hiddenFields.put("detailtime",detailval);
	hiddenFields.put("getMaxDaysInMonth",String.valueOf(ErUtils.getMaxDaysInMonth()));
	hiddenFields.put("inidate",currentDateFormat);
	hiddenFields.put("reporttype",request.getParameter("reporttype"));
	hiddenFields.put("forwardto","ErTopNReportsJson");
	hiddenFields.put("er_bgreportfrom","Comparison_Top_N");
	hiddenFields.put("bgenabled",strbgrepportName);
	hiddenFields.put("limitforbg",limitforbg);
	hiddenFields.put("savereport","save");
	hiddenFields.put("servletName","com.eg.ErRepoLiteC");
	hiddenFields.put("divStatus",divStatus);
	hiddenFields.put("trendenable",String.valueOf(compute));

	rootJson.put("isSubmit",isSubmitForDesc);

	String strwidth = "90%";
	if(backreqMap == null || backreqMap != null && backreqMap.size() == 0)
		strwidth="100%";
	if (!StringUtils.isNull(titleToDisplay)){ 
		lst.add(titleToDisplay);
	}
	else
	{
		lst.add(intlmap.getTextDescription("reporter.comparison.COMPARISON REPORTS")+"-"+intlmap.getTextDescription("reporter.operation.TOP N"));
	}
	String csv_wk="";
	if(excludeweekend!=null && excludeweekend.equalsIgnoreCase("Yes"))
		csv_wk=intlmap.getTextDescription("reporter.common.Exclude weekends")+" : " +Days;
	lst.add(intlmap.getTextDescription("reporter.common.Time period")+":"+intlmap.getTextDescription("reporter.common.From")+" "+timefrom2+":"+minfrom2+intlmap.getTextDescription("reporter.common.Hrs")+" "+intlmap.getTextDescription("reporter.common.To")+" "+timeto2+":"+minto2+intlmap.getTextDescription("reporter.common.Hrs")+","+'"'+csv_wk+'"');

	displayFields.put("MappedExcludeDays",intlmap.getTextDescription("reporter.common.Excludes")+" " +Days);

	String fromFavSch = request.getParameter("fromFavSch");

	rootJson.put("fromFavSch",fromFavSch);

	if(backreqMap != null && backreqMap.size() > 0 &&  enableBack && request.getParameter("enableBack")!=null && request.getParameter("enableBack").equalsIgnoreCase("true") && (fromFavSch!=null && fromFavSch.equalsIgnoreCase("true")))
	{
		rootJson.put("ID","backQnumber="+erhelputils.getBackID()+"&"+erhelputils.getQueryString());
	}
	String detailed="",trend="";
	String datatype=request.getParameter("er_trenddata");
	if(!StringUtils.isNull(datatype))
	{
		if(datatype.equalsIgnoreCase("Yes"))
			trend = "checked";
		else
			detailed = "checked";
	}else
	{
		datatype="No";
		detailed = "checked";
	}
	if (ht_Data	!=null && !ht_Data.isEmpty())
	{
		if(reportType!=null && reportType.equalsIgnoreCase("graph"))
		{
			if(ht_Data.size()>0)
				valueFound=true;
		}
		else
		{
			Iterator itr1 = ht_Data.keySet().iterator();
			Vector v_tmp1 = (Vector)ht_Data.get(itr1.next());
			if (v_tmp1.size()>0)	
				valueFound=true;
		}
	}
	String align="right";
	String width="12";
	//v_template=iniObj.getVariables("REPORT_TEMPLATES",true);
	//v_template.removeElementAt(0);
	v_template=(Vector)v_template.clone();
	Collections.sort(v_template,String.CASE_INSENSITIVE_ORDER);
	
	displayFields.put("reporter.operation.Report for",intlmap.getTextDescription("reporter.uptime.Analyze by"));
	JSONArray reportForComboArray = new JSONArray();
	for(int g=0;g<v_listall.size();g++)
	{
		loopJsonObj = new JSONObject();
		//reportForComboArray.add( tmp_listObj );
		String select_event = (String)v_listall.get(g);
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.operation."+select_event));
		loopJsonObj.put("valueField", select_event);
		reportForComboArray.add(loopJsonObj);
		if(select_event.equals(st_dataFrom))
		{
			selectedFields.put("selectedreportFor",st_dataFrom);
		}
	}
	combo.put("reportForCombo",reportForComboArray);
	displayFields.put("reporter.comparison.Include SubZones", intlmap.getTextDescription("reporter.comparison.Include SubZones"));
	if(st_dataFrom==null || st_dataFrom.equals("Component"))
	{
		sel_comp="checked";
		sel_service="";
	}
	else
	{
		sel_comp="";
		sel_service="checked";
	}
	if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Zone"))
	{ 		
		/*if(includezone!=null && includezone.equalsIgnoreCase("yes"))
			selectedFields.put("selectedsubZone", "Yes");*/
		if(includezone!=null && includezone.equalsIgnoreCase("No"))
			selectedFields.put("selectedsubZone", "No");
		else
			selectedFields.put("selectedsubZone", "Yes");
			
			Vector v_include=new Vector();
			v_include.add("Yes");
			v_include.add("No");
			JSONArray subZoneComboArray = new JSONArray();
			Iterator subZone_itr = v_include.iterator();
			while ( subZone_itr.hasNext() )
			{
				loopJsonObj = new JSONObject();
				String option = (String) subZone_itr.next();
				loopJsonObj.put("displayField", intlmap.getTextDescription("reporter.common."+option));
				loopJsonObj.put("valueField", option);
				subZoneComboArray.add( loopJsonObj );
			}
			combo.put("subZoneCombo", subZoneComboArray);	
	}
	User currentuser = UserRegistry.getInstance().getUser(session.getId());
	Vector v_zones=new Vector();
	Vector view_zones=new Vector();
	Vector v_segment=new Vector();
	if(compUtils.getUserZones() != null)
		view_zones.addAll(compUtils.getUserZones());
	if(view_zones != null && view_zones.contains("--Default--"))
		view_zones.remove("--Default--");
	for(int z=0;z<view_zones.size();z++)
	{
		v_zones.add(view_zones.get(z).toString().trim());
		Vector view_s=egviewinfo.getviewsforzone(view_zones.get(z).toString().trim());
		for(int v=0;v<view_s.size();v++)
		{
			v_zones.add(view_zones.get(z).toString().trim()+"-view:"+(String)view_s.get(v));
		}
	}
	v_segment.addAll(Arrays.asList(compUtils.getUserSegments()));

	if(st_dataFrom!=null && !st_dataFrom.equalsIgnoreCase("-1") && !st_dataFrom.equalsIgnoreCase("component"))
	{
		if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Service"))
		{
			v_service = compUtils.getUserServices(true);
		}
		else if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Zone"))
		{
			Vector v_zcom=new Vector();
			if(listzonecomponents !=null)
			{
				for(int i=0;i<listzonecomponents.size();i++)
				{
					String s_tmp=(String)listzonecomponents.get(i);
					String str_comptype=s_tmp.substring(0,s_tmp.indexOf(":"));
					String str_compname=s_tmp.substring(s_tmp.indexOf(":")+1);
					String s_component = str_compname +":"+str_comptype;
					listzonecomponents.set(i,s_component);
				}
				for(int a=0;a< v_allcomp.size();a++)
				{
					if(!listzonecomponents.contains((String)v_allcomp.get(a)))
						v_zcom.add((String)v_allcomp.get(a));
				}
			}
			else
			{
				for(int a=0;a< v_allcomp.size();a++)
				{
						v_zcom.add((String)v_allcomp.get(a));
				}
			}
			if(v_zcom !=null && !v_zcom.isEmpty())
			{
				v_zones.insertElementAt("--Default--",0);
			}
			v_service=v_zones;
		}
		else if(st_dataFrom!=null && st_dataFrom.equalsIgnoreCase("Segment"))
		{
			v_service = compUtils.getUserSegments();
		}
		Collections.sort(v_service,String.CASE_INSENSITIVE_ORDER);

		displayFields.put("reporter.common.seg-ser-zone",intlmap.getTextDescription("reporter.common."+st_dataFrom));
		JSONArray elementsArray = new JSONArray();
		if(v_service!=null && !v_service.isEmpty())
		{
				loopJsonObj = new JSONObject();
				loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Please choose a "+st_dataFrom));
				loopJsonObj.put("valueField", "-1");
				elementsArray.add(loopJsonObj);

			for(int g=0;g<v_service.size();g++)
			{
				loopJsonObj = new JSONObject();
				String select_event = (String)v_service.get(g);
				loopJsonObj.put("displayField",select_event);
				loopJsonObj.put("valueField", select_event);
				elementsArray.add(loopJsonObj);
				if(select_event.equals(s_service))
				{
					selectedFields.put("selectedSeg-Ser-Zone",s_service);
				}
				if(isForceSubmit!=null && isForceSubmit.equals("true") && g==0)
					selectedFields.put("selectedSeg-Ser-Zone",select_event);
			}
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1");
			elementsArray.add(loopJsonObj);
		}
		combo.put("seg-ser-zoneCombo",elementsArray);
	}
	vec.add(intlmap.getTextDescription("reporter.operation.Report for")+":"+st_dataFrom);
	if(s_service!=null)
	{
		vec.add(st_dataFrom+":"+s_service);
	}
	if(includezone!=null)
	{
		vec.add(intlmap.getTextDescription("reporter.comparison.Include SubZones")+":"+includezone);
	}
	lst.add(vec);

	if(reportType!=null && reportType.equalsIgnoreCase("graph"))
	{
		repTypeGraph="checked";
		repTypeData="";
	}
	else
	{
		repTypeGraph="";
		repTypeData="checked";
	}
	if(v_template!=null)
	{
		for(int i=0; i<v_template.size(); i++)
		{
			String tempVal=iniObj.getValue("REPORT_TEMPLATES",(String)v_template.get(i));
			v_templateValue.add(tempVal);
			if(erd.s_test!=null)
			{
				if(tempVal.trim().equalsIgnoreCase((s_test+":"+erd.s_measure).trim()))
				selTempl=(String)v_template.get(i);
			}
		}
		String useTemplate="",useTest="";
		templateEnable=false;
		if(er_templateEnable!=null)
		{
			if(erd.s_template!=null)
				s_template=erd.s_template;
		}
		if(s_template!=null && s_template.equalsIgnoreCase("yes"))
		{
			useTemplate="checked";
			useTest=" ";
			templateEnable=true;
			selectedFields.put("selectedCriteria","yes");
		}
		else
		{
			useTemplate="";
			useTest="checked";
			selectedFields.put("selectedCriteria","no");
		}
		if(v_qry_string!=null)
		{
			qryString="er_gtype="+erd.s_gtype+"&er_timeline=1 day&er_tbound="+erd.s_tbound+"&er_graphtype="+erd.s_gtype;
		}
		else
		{
			if(request.getQueryString()==null)
			{
				qryString="er_gtype="+erd.s_gtype+"&er_timeline=1 day&er_tbound="+erd.s_tbound+"&er_graphtype="+erd.s_gtype;
			}
			else
				qryString=request.getQueryString();
		}
		
		displayFields.put("reporter.comparison.Select by Criteria",intlmap.getTextDescription("reporter.comparison.Select by Criteria"));
		JSONArray criteriaArray =  new JSONArray();

		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Metrics"));
		loopJsonObj.put("valueField", "yes");
		criteriaArray.add(loopJsonObj);		

		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.operation.Test"));
		loopJsonObj.put("valueField", "no");
		criteriaArray.add(loopJsonObj);
		combo.put("criteriaCombo",criteriaArray);
	}
	else
	{
		width="16";
		align="left";
	}
	if(reportType!=null && reportType.equalsIgnoreCase("graph"))
	{
		repTypeGraph="checked";
		repTypeData="";
	}
	else
	{
		repTypeGraph="";
		repTypeData="checked";
	}

		displayFields.put("reporter.comparison.Report Type",intlmap.getTextDescription("reporter.comparison.Report Type"));
		JSONArray reporttypeArray =  new JSONArray();

		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Graph"));
		loopJsonObj.put("valueField", "graph");
		reporttypeArray.add(loopJsonObj);

		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Data"));
		loopJsonObj.put("valueField", "data");
		reporttypeArray.add(loopJsonObj);	

		combo.put("reportTypeCombo",reporttypeArray);
		selectedFields.put("selectedreportType",reportType);


	rootJson.put("templateEnable",String.valueOf(templateEnable));
	if(!templateEnable)
	{
		JSONArray testArray = new JSONArray();
		serverList = sorter.getSortedTestList(v_test);

		if(v_test!=null && !v_test.isEmpty())
		{

			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Please  choose a Test"));
			loopJsonObj.put("valueField", "-1" );
			testArray.add(loopJsonObj);
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1");
			testArray.add(loopJsonObj);
		}
		for(int n=0;n<serverList.size();n++)
		{
			EgName nameObj = (EgName)serverList.get(n);
			String tmpVal = nameObj.getActualName();
			String tmpDis = nameObj.getLocalName();

			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTestDescription(tmpDis));
			loopJsonObj.put("valueField", tmpVal);
			testArray.add(loopJsonObj);
			if(s_test!=null && s_test.equalsIgnoreCase(tmpVal))
			{
				selectedFields.put("selectedTest",s_test);
			}
			else
			{
				if(n==0)
				{
					selectedFields.put("selectedTest",tmpVal);
				}
			}
		}
		JSONArray measureArray =  new JSONArray();
		if(v_meas!=null && !v_meas.isEmpty())
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Please choose a measure"));
			loopJsonObj.put("valueField", "-1" );
			measureArray.add(loopJsonObj);
			for( int k=0;v_meas.size()>k;k++)
			{
				if(	v_meas.get(k).equals(s_meas))
					selectedFields.put("selectedMeasure",s_meas);

				loopJsonObj = new JSONObject();
				loopJsonObj.put("displayField",mappingMeasure.get(k));
				loopJsonObj.put("valueField", v_meas.get(k) );
				measureArray.add(loopJsonObj);
			}
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1");
			measureArray.add(loopJsonObj);
		}
		displayFields.put("reporter.comparison.Test",intlmap.getTextDescription("reporter.comparison.Test"));
		displayFields.put("reporter.comparison.Measure",intlmap.getTextDescription("reporter.comparison.Measure"));
		displayFields.put("reporter.comparison.Metric",intlmap.getTextDescription("reporter.comparison.Metric"));
		displayFields.put("reporter.comparison.Component",intlmap.getTextDescription("reporter.comparison.Component"));

		combo.put("testCombo",testArray);
		combo.put("measureCombo",measureArray);
	}
	else
	{
		JSONArray metricsArray =  new JSONArray();
		if(v_template!=null && v_template.size()>0)
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Please  choose a Metric"));
			loopJsonObj.put("valueField", "-1" );
			metricsArray.add(loopJsonObj);
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1" );
			metricsArray.add(loopJsonObj);
		}
		for(int n=0;n<v_template.size();n++)
		{
			String s=(String)v_template.get(n);
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common."+s));
			loopJsonObj.put("valueField", intlmap.getTextDescription("reporter.common."+s));
			metricsArray.add(loopJsonObj);

			if(selTempl!=null && selTempl.equalsIgnoreCase(s))
			{
				selectedFields.put("selectedMetrics", intlmap.getTextDescription("reporter.common."+s));
			}
		}
		combo.put("metricsCombo",metricsArray);
	}
	if(st_dataFrom==null ||(!st_dataFrom.equalsIgnoreCase("Zone") || !st_dataFrom.equalsIgnoreCase("Service") || !st_dataFrom.equalsIgnoreCase("Segment"))){
		if(s_treeParam!=null && s_treeParam.length() > 0)
		{
			Vector v_tempComp = new Vector();
			for(int i=0; i < v_comp.size(); i++)
			{
				String s = (String)v_componetdisp.get(i);
				if(s.indexOf(s_treeParam)> -1)
				{
					arr_comp[0]=s;
					v_tempComp.add(s);
				}
			}
			v_comp = new Vector();
			v_comp.addAll(v_tempComp);
			v_componetdisp = new Vector();
			v_componetdisp.addAll(v_tempComp);
		}
	}
	if(ls!=null && ls.size()>0){
		v_comp= new Vector(Collections.synchronizedList(ls));
		v_componetdisp= new Vector(Collections.synchronizedList(ls));
	}
	Collections.sort(v_comp,String.CASE_INSENSITIVE_ORDER);
	Collections.sort(v_componetdisp,String.CASE_INSENSITIVE_ORDER);
	JSONArray componentArray =  new JSONArray();
	JSONObject componentMapping = new JSONObject();
	if(v_comp!=null && v_comp.size()==0)
	{
		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
		loopJsonObj.put("valueField", "-1" );
		componentArray.add(loopJsonObj);
		componentMapping.put("-1",intlmap.getTextDescription("reporter.common.Not Applicable"));
	}else
	{
		for(int n=0;n<v_comp.size();n++)
		{
			String s=(String)v_componetdisp.get(n);
			if(treeCompType!=null && !treeCompType.equalsIgnoreCase("NULL"))
			{
				String strType = s.substring(s.lastIndexOf(":")+1);
				if(!treeCompType.equalsIgnoreCase(strType))
					continue;
			}
			String s_compDisplay=s.substring(0,s.lastIndexOf(":")+1)+intlmap.getComponentTypeDescription(s.substring(s.lastIndexOf(":")+1));
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",s_compDisplay);
			loopJsonObj.put("valueField", v_comp.get(n));
			componentArray.add(loopJsonObj);
			componentMapping.put(v_comp.get(n),s_compDisplay);
		}
	}
	if(arr_comp!=null)
		selectedFields.put("selectedComps",arr_comp);

	if(componentArray!=null && componentArray.size()==0)
	{
		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
		loopJsonObj.put("valueField", "-1" );
		componentArray.add(loopJsonObj);
		componentMapping.put("-1",intlmap.getTextDescription("reporter.common.Not Applicable"));
	}
	combo.put("componentsCombo",componentArray);
	rootJson.put("combination",componentMapping);
	if(v_comp!=null)
	{
		for(int n=0;n<v_comp.size();n++)
		{
			String s=(String)v_componetdisp.get(n);
		}
	}
	JSONArray sortArray =  new JSONArray();
	for(int n=0;n<v_sortby.size();n++)
	{
		String s=(String)v_sortby.get(n);
		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common."+s));
		loopJsonObj.put("valueField",s);
		sortArray.add(loopJsonObj);
		if(sortby!=null && sortby.equalsIgnoreCase(s))
		{
			selectedFields.put("selectedSortBy",s);
		}
	}
	combo.put("sortByCombo",sortArray);
	//displayFields.put("reporter.comparison.Show Descriptors",intlmap.getTextDescription("reporter.comparison.Show Descriptors"));
	displayFields.put("reporter.comparison.Aggregate by",intlmap.getTextDescription("reporter.comparison.Aggregate by"));
	displayFields.put("reporter.comparison.Sort by",intlmap.getTextDescription("reporter.comparison.Sort by"));
	displayFields.put("reporter.comparison.Show Data",intlmap.getTextDescription("reporter.comparison.Show Data"));

	/*JSONArray showDescArray =  new JSONArray();
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Yes"));
	loopJsonObj.put("valueField","Yes");
	showDescArray.add(loopJsonObj);
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.No"));
	loopJsonObj.put("valueField","No");
	showDescArray.add(loopJsonObj);
	
	combo.put("showDescriptorCombo",showDescArray);
	//selectedFields.put("selectedDescriptor",showInfo);*/
	
	JSONArray showGroupArray =  new JSONArray();
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Component with Descriptor"));
	loopJsonObj.put("valueField","Component_Descriptor");
	showGroupArray.add(loopJsonObj);
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Component"));
	loopJsonObj.put("valueField","Component");
	showGroupArray.add(loopJsonObj);
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Descriptor"));
	loopJsonObj.put("valueField","Descriptor");
	showGroupArray.add(loopJsonObj);

	combo.put("showGroupbyCombo",showGroupArray);
	selectedFields.put("selectedGroupBy",er_groupby);
	rootJson.put("computeTrend",String.valueOf(compute));

	JSONArray showDataArray =  new JSONArray();
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Detailed"));
	loopJsonObj.put("valueField","No");
	showDataArray.add(loopJsonObj);
	if(compute)
	{
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Trend"));
	loopJsonObj.put("valueField","Yes");
	showDataArray.add(loopJsonObj);
	}
	combo.put("showDataCombo",showDataArray);
	selectedFields.put("selectedShowData",datatype);
	displayFields.put("reporter.common.Descriptor",intlmap.getTextDescription("reporter.common.Descriptor"));
	//if(showInfo.equalsIgnoreCase("Yes"))
	if(er_groupby.equalsIgnoreCase("Component_Descriptor"))
	{
		String aa = null;
		Vector mhost = new Vector();
		if(s_comp!=null && s_test!=null && !s_comp.equals("") && !s_comp.equals("-1")&& !s_test.equals("-1") && !s_test.equals("null") && !s_comp.equals("null"))
		{
			mhost = erInfo.getMsmtHostForTest(s_site,s_test,s_comp);
			Vector v_info = new Vector();
			if(mhost.size()>1)
			{
				if((v_infos.size())>0)
				{
					for(int j=0;j<v_infos.size();j++)
					{
						for(int i=0;i<mhost.size();i++)
						{
							aa = v_infos.get(j) + "(" + mhost.get(i) + ")";
							v_info.add(aa);
						}
					}
				}
				else
				{
					for(int i=0;i<mhost.size();i++)
					{
						aa = "(" + mhost.get(i) + ")";
						v_info.add(aa);
					}
				}
			}
			else
			{
				if((v_infos.size())>0)
				{
					for(int j=0;j<v_infos.size();j++)
					{
						aa =(String) v_infos.get(j);
						v_info.add(aa);
					}
				}
			}
			v_infos =(Vector)v_info.clone();
		}
		String arr_infoValue[]={"all_descriptor"};
		if(isForceSubmit!=null && isForceSubmit.equals("true"))
		{
			if(arr_info==null || arr_info.length==0)
				selectedFields.put("selectedInfo",arr_infoValue);
			else
				selectedFields.put("selectedInfo",arr_info);
		}else	if(arr_info==null || arr_info.length==0)
			selectedFields.put("selectedInfo",arr_infoValue);
		else
			selectedFields.put("selectedInfo",arr_info);

		
		String maxCountStr = reportinfo.getValue("MISC","NoOfDescriptorforChartTopN");
		if(maxCountStr==null || maxCountStr.length()==0)
		{
			maxCountStr = "500";
		}
		int maxCount = Integer.parseInt(maxCountStr);
		JSONArray infoArray = new JSONArray();
		if(v_infos!=null && !v_infos.isEmpty())
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField","All Descriptors");
			loopJsonObj.put("valueField","all_descriptor");
			infoArray.add(loopJsonObj);
			if(maxCount>v_infos.size())
			{
				for(int k=0;v_infos.size()>k;k++)
				{
					loopJsonObj = new JSONObject();
					loopJsonObj.put("displayField",v_infos.get(k));
					loopJsonObj.put("valueField",v_infos.get(k));
					infoArray.add(loopJsonObj);
				}
			}
			else
			{
				rootJson.put("disableInfoCombo", "yes");
				if(arr_info==null || arr_info.length==0)
				{
					rootJson.put("infoTextFieldValue", "*");
				}
				else
				{
					String info_str = "";
					for(int i=0;i<arr_info.length;i++)
					{
						info_str+=arr_info[i]+",";
					}
					info_str = info_str.substring(0,info_str.length()-1);
					rootJson.put("infoTextFieldValue", arr_info[0]);
				}
			}
		}
		else
		{
			loopJsonObj = new JSONObject();
			loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Not Applicable"));
			loopJsonObj.put("valueField", "-1" );
			infoArray.add(loopJsonObj);
			selectedFields.put("selectedInfo","-1");
		}
		combo.put("infoCombo",infoArray);
		String select_yes = "";
		String select_no = "";
		if(show_timeinuse != null && show_timeinuse.equalsIgnoreCase("Yes"))
		{
			select_yes = "checked";
			select_no="";
			selectedFields.put("weightedAvg","Yes");
		}
		else
		{
			select_yes="";
			select_no = "checked";
			selectedFields.put("weightedAvg","No");
		}
	}
	displayFields.put("reporter.comparison.Weighted Average",intlmap.getTextDescription("reporter.comparison.Weighted Average"));
	JSONArray WeightedAvgArray =  new JSONArray();
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.Yes"));
	loopJsonObj.put("valueField","Yes");
	WeightedAvgArray.add(loopJsonObj);
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.comparison.No"));
	loopJsonObj.put("valueField","No");
	WeightedAvgArray.add(loopJsonObj);

	combo.put("weightedAvgCombo",WeightedAvgArray);

	displayFields.put("reporter.common.Exclude weekends",intlmap.getTextDescription("reporter.common.Exclude weekends"));
	JSONArray exclweekArray  =  new JSONArray();

	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.Yes")+" ("+Days+") ");
	loopJsonObj.put("valueField", "Yes");
	exclweekArray.add(loopJsonObj);
	loopJsonObj = new JSONObject();
	loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common.No"));
	loopJsonObj.put("valueField", "No");
	exclweekArray.add(loopJsonObj);

	combo.put("excludeWeekCombo",exclweekArray);
	selectedFields.put("excludeWeek",excludeweekend);

	displayFields.put("reporter.comparison.Show",intlmap.getTextDescription("reporter.comparison.Show"));

	JSONArray priorityArray =  new JSONArray();

	for(int n=0;n<v_show.size();n++)
	{
		String s=(String)v_show.get(n);
		loopJsonObj = new JSONObject();
		loopJsonObj.put("displayField",intlmap.getTextDescription("reporter.common."+s));
		loopJsonObj.put("valueField", s);
		priorityArray.add(loopJsonObj);

		if(priority!=null && priority.equalsIgnoreCase(s))
		{
			selectedFields.put("selectedPriority",priority);
		}
	}
	combo.put("priorityCombo",priorityArray);

	displayFields.put("reporter.common.Time period", intlmap.getTextDescription("reporter.common.Time period"));
	displayFields.put("reporter.common.Hrs", intlmap.getTextDescription("reporter.common.Hrs"));
	displayFields.put("reporter.common.Mins", intlmap.getTextDescription("reporter.common.Mins"));
	selectedFields.put("selectedTimeFrom",timefrom);
	selectedFields.put("selectedMinsFrom",minfrom);
	selectedFields.put("selectedTimeTo",timeto);
	selectedFields.put("selectedMinsTo",minto);
%>

	<%@ include file ="ErTimeFormatJSON.jsp"%>

<%
	String sdate = request.getParameter("startdate");	
	String edate = request.getParameter("enddate");	
	String shr = request.getParameter("starthr");	
	String ehr = request.getParameter("endhr");	
	String smin = request.getParameter("startmin");	
	String emin = request.getParameter("endmin");

	if(sdate!=null)
	{
		if(DateUtil.isDate(sdate,"MM/dd/yyyy"))
		{
			comFormat = "MM/dd/yyyy";
		}
		else
		{
			comFormat = currentDateFormat;
		}
		dispDate = 	DateUtil.changeDateFormat(sdate,comFormat,currentDateFormat);
		converterStart = new EgTimeZoneConverter(dispDate+" "+shr+":"+smin,thisuser);
		starttimeformat=converterStart.getDateTime()+" "+"Hrs ";
	}
	if(edate!=null)
	{
		if(DateUtil.isDate(edate,"MM/dd/yyyy"))
		{
			comFormat = "MM/dd/yyyy";
		}
		else
		{
			comFormat = currentDateFormat;
		}
		dispDate = 	DateUtil.changeDateFormat(edate,comFormat,currentDateFormat);
		converterEnd = new EgTimeZoneConverter(dispDate+" "+ehr+":"+emin,thisuser);
		endtimeformat=converterEnd.getDateTime()+" "+"Hrs ";
	}	
	Vector dvec = new Vector();
	String stimefmt = "Start Date : "+starttimeformat;
	String etimefmt = "End Date : "+endtimeformat;
	dvec.add('"'+stimefmt+'"');
	dvec.add('"'+etimefmt+'"');
	lst.add(dvec);

	hiddenFields.put("userTimeline",strUsrTimeline);
	displayFields.put("reporter.common.Timeline", intlmap.getTextDescription("reporter.common.Timeline"));
	displayFields.put("reporter.common.From", intlmap.getTextDescription("reporter.common.From"));
	displayFields.put("reporter.common.To", intlmap.getTextDescription("reporter.common.To"));
	displayFields.put("reporter.common.Hr", intlmap.getTextDescription("reporter.common.Hr"));
	displayFields.put("reporter.common.Graph", intlmap.getTextDescription("reporter.common.Graph"));

	combo.put("timelineCombo",timelineComboArray);
	//rootJson.put("timelineHourCombo",timelineHourComboArray);
	selectedFields.put("selectedTimeline",er_timeline);
	selectedFields.put("startDate",startDateJSON);
	selectedFields.put("endDate",endDateJSON);
	selectedFields.put("startHour",startHourJSON);
	selectedFields.put("endHour",endHourJSON);
	selectedFields.put("startmin",startMin); 
	selectedFields.put("endmin",endMin);
	selectedFields.put("selectedGraphMode",selectedGraphMode);

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

	displayFields.put("reporter.consolidated.Report Generation", intlmap.getTextDescription("reporter.consolidated.Report Generation"));
	displayFields.put("reporter.consolidated.Report Name", intlmap.getTextDescription("reporter.consolidated.Report Name"));
	JSONArray reportGenerationComboArray =  new JSONArray();
	JSONObject tmpobj=new JSONObject();
	tmpobj.put("displayField", strbackground);
	tmpobj.put("valueField", "background");
	reportGenerationComboArray.add(tmpobj);
	tmpobj=new JSONObject();
	tmpobj.put("displayField", strforeground);
	tmpobj.put("valueField", "foreground");
	reportGenerationComboArray.add(tmpobj);
	combo.put("reportGenerationCombo",reportGenerationComboArray);

	String er_reportgenration = request.getParameter("er_reportgenration");
	String er_background ="";
	String er_foreground ="";
	if (er_reportgenration != null && er_reportgenration.equals("background"))
	{
		er_background = "selected";
		er_foreground = "";
		selectedFields.put("reportGeneration","background");
	}
	else
	{
		er_background = "";
		er_foreground = "selected";
		selectedFields.put("reportGeneration","foreground");
	}
	String bg_reportname = request.getParameter("bg_reportname");
	if(bg_reportname == null)
	{
		bg_reportname = "";
	}
	if(bggroundStr != null && !bggroundStr.equals(""))
	{
		displayFields.put("backgroundReportStatus",status);
		String strreportName ="Comparison_Top_N";
		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");
		}
		String bgroundResponseTxt=bggroundStr;
		if(status != null && !status.equalsIgnoreCase("exceedLimit"))
		{
			bgroundResponseTxt = erbgreport.getlangsupportedString(bggroundStr,bgString,urs);
		}
		displayFields.put("bgroundResponseTxt",bgroundResponseTxt);
		urlFields.put("bgroundReportsURL","/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");
		displayFields.put("backgroundAnchor", intlmap.getTextDescription("reporter.common.Click here to see a list of generated and processing reports"));
	}
	if(ht_Data!=null)
	{
		String s_reportType="";
		if(reportType!=null && reportType.equalsIgnoreCase("graph")) {
			s_reportType="Graph";
		} else {
			s_reportType="Data";
		}
//		JSONObject selectionDetails=new JSONObject();
 
		displayFields.put("selectionDetailtitle",intlmap.getTextDescription("reporter.common.Selection Details for")+" "+intlmap.getTextDescription("reporter.common."+s_list));

		if(s_service!=null && !s_service.equals("Component"))
		{
			displayFields.put("selectionDetailtitle",intlmap.getTextDescription("reporter.common.Selection Details for")+" "+intlmap.getTextDescription("reporter.common."+s_list)+" : "+intlmap.getTextDescription("reporter.common."+s_service));
		}
		if(s_template!=null && s_template.equalsIgnoreCase("yes")) {
			selectionDetails.put(intlmap.getTextDescription("reporter.comparison.Select by Criteria"),intlmap.getTextDescription("reporter.comparison.Metrics"));
		}
		else
		{
			selectionDetails.put(intlmap.getTextDescription("reporter.comparison.Select by Criteria"),intlmap.getTextDescription("reporter.operation.Test"));
		}
		//selectionDetails.put(intlmap.getTextDescription("reporter.comparison.Show Descriptors"),showInfo);
		if(er_groupby!=null && er_groupby.equalsIgnoreCase("Component_Descriptor"))
			selectionDetails.put(intlmap.getTextDescription("reporter.comparison.Aggregate by"),intlmap.getTextDescription("reporter.comparison.Component with Descriptor"));
		else
			selectionDetails.put(intlmap.getTextDescription("reporter.comparison.Aggregate by"),intlmap.getTextDescription("reporter.comparison."+er_groupby));
		if (compute)
		{
			String s_reportFor="";
			if(opt != null && opt.equals("Yes")) {
				s_reportFor = "Trend";
			} else {
				s_reportFor= "Detailed";
			}
			selectionDetails.put(intlmap.getTextDescription("reporter.common.Show Data"),intlmap.getTextDescription("reporter.comparison."+s_reportFor));
		}
		selectionDetails.put(intlmap.getTextDescription("reporter.common.Exclude weekends"),intlmap.getTextDescription("reporter.comparison."+excludeweekend));
		selectionDetails.put(intlmap.getTextDescription("reporter.common.Time Period"),timefrom+":"+minfrom+"<span class='font_bold'>  "+intlmap.getTextDescription("reporter.common.to")+" </span> "+timeto+":"+minto);
		
		String viewStartDateTime;
		String viewEndDateTime;

		viewStartDateTime=startDateForDisplay+" "+startHourForDisplay+":"+startMinForDisplay;
		viewEndDateTime=endDateForDisplay+" "+endHourForDisplay+":"+endMinForDisplay;

	selectionDetails.put((String)intlmap.getTextDescription("reporter.common.Timeline")," "+viewStartDateTime+
		" "+intlmap.getTextDescription("reporter.common.hrs")+
		"<span class='font_bold'>"+" "+intlmap.getTextDescription("reporter.common.to")+"</span>"+" "
		+" "+viewEndDateTime+" hrs");

		rootJson.put("selectionDetails",selectionDetails);
	}

	Vector data=new Vector();
	Hashtable htdata=new Hashtable();
	Hashtable repData=new Hashtable();
	String unit="";
	Map tmpMap = request.getParameterMap();
	HashMap mapTmp = new HashMap();
	mapTmp.putAll(tmpMap);
	if(mapTmp!=null && mapTmp.get("er_info_list")!=null)
	{
		Object obj = mapTmp.get("er_info_list");
		if(obj!=null && obj instanceof String[])
		{
			String[] strArr = (String[])obj;
			for(int cnt=0;cnt<strArr.length;cnt++)
			{
				String str = strArr[cnt];
				str = erUtils.specialCharEncode(str);
				strArr[cnt] = str;
			}
			mapTmp.put("er_info_list",strArr);
		}
		else if(obj!=null && obj instanceof String)
		{
			String str = (String)obj;
			str = erUtils.specialCharEncode(str);
			mapTmp.put("er_info_list",str);
		}
	}

	//String queryString=(String)ErUtils.prepareQueryString(request.getParameterMap());
	String queryString=(String)ErUtils.prepareQueryString(mapTmp);
	String Qstring="";
	if(queryString!=null)
	{
		StringTokenizer strtok = new StringTokenizer(queryString,"&");
		while(strtok.hasMoreTokens())
		{
			String parameter = strtok.nextToken();
			int ind = parameter.indexOf("=");
			//if (ind < 0 || parameter.indexOf("responseType")>-1)
			if (ind < 0)
				continue;

			String reqparam =parameter.substring(0,ind);
			String value = parameter.substring(ind+1);
			if(reqparam!=null&&reqparam.equals("er_component"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_service"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_combination"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("userID"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("startdate"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("enddate"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("inidate"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("pdfTime"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_timeline"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_priority"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_trgttype"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("er_rtype"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			if(reqparam!=null&&reqparam.equals("erTestMeasureCombination"))
			{
				value = erUtils.specialCharEncode(value);
			}
			if(reqparam!=null&&reqparam.equals("er_info_list"))
			{
				value=com.eg.EgURLEncoder.encode(value, "UTF-8");
			}
			Qstring=Qstring+reqparam+"="+value+"&";
		}
	}
	String dataProcess = mngrIProc+"/final/servlet/com.eg.ErRepoLiteC;jsessionid="+ session.getId()+"?"+printQString.toString();

	session.setAttribute("PDF_URL", mngrIProc+"/final/servlet/com.eg.ErRepoLiteC");
	session.setAttribute("DRILLDOWN_PDF_URL", mngrIProc+"/final/reporter/ErTopNReportsDrillDownPrint.jsp");
	
	urlFields.put("saveQString",printQString.toString());
	//s_qryString+"&er_reportType=<%=reportType"
	if(!isFromDrillDown)
	session.setAttribute("MAIL_URL",dataProcess);

	if (ht_Data!=null )
	{
		String colName = "reporter.comparison.Component";
		if (ht_Data.isEmpty())
		{
			lst.add(intlmap.getTextDescription("reporter.common.No measures available for the current selection"));	
		}
		else
		{
			String skey="";
			Iterator itr = ht_Data.keySet().iterator();
			if(reportType!=null && reportType.equals("data"))
			{
				while(itr.hasNext())
				{
					skey = (String)itr.next();
					Vector v_tmp = (Vector)ht_Data.get(skey);
					if (v_tmp.size()>0)
					{
						JSONObject resultData = new JSONObject();
						ArrayList dataArray =  new ArrayList();

						unit= tablesInfo.getUnitForMeasure(s_test,s_meas);
						String mapStr=s_test+":"+s_meas; 
						boolean isDescriptorChoosen = false;
						if(arr_info!=null && arr_info.length>0)
							isDescriptorChoosen = true;
						if(er_groupby!=null && er_groupby.equalsIgnoreCase("Descriptor") && v_infos!=null && !v_infos.isEmpty()&& isDescriptorChoosen )
						{
							colName = "reporter.comparison.Descriptor";
						}
						s_tit = intlmap.getTestDescription(s_test)+":"+intlmap.getMeasureDescription(s_test,s_meas)+"("+unit+")";
						vec1.add(intlmap.getTextDescription(colName));
						resultData.put("title",s_tit);
						vec1.add(intlmap.getTextDescription("reporter.common.Min"));
						vec1.add(intlmap.getTextDescription("reporter.common.Max"));
						vec1.add(intlmap.getTextDescription("reporter.common.Avg"));

						JSONArray tableHeadingsArray=new JSONArray();

						tableHeadingsArray.add(intlmap.getTextDescription(colName));
						tableHeadingsArray.add(intlmap.getTextDescription("reporter.common.Min"));
						tableHeadingsArray.add(intlmap.getTextDescription("reporter.common.Max"));
						tableHeadingsArray.add(intlmap.getTextDescription("reporter.common.Avg"));
						for (int k=0;k<v_tmp.size();k=k+2)
						{
							ArrayList DataSet =  new ArrayList();
							String server=(String)v_tmp.get(k);
							Vector v_val=(Vector)v_tmp.get(k+1);
							data.add(server);
							DataSet.add(server);
							lst_dat.add(server);
							for (int i=0; i<v_val.size();i=i+3)
							{
								for (int j=i; j<i+3; j++)
								{
									data.add(v_val.get(j));
									DataSet.add(v_val.get(j));
									lst_dat.add(v_val.get(j));
								}
							}
							dataArray.add(DataSet);
						}
						resultData.put("dataArray",dataArray);
						resultData.put("columnNames",tableHeadingsArray);

						ht.put(vec1,lst_dat);
						ht1.put(s_tit,ht);
						lst.add(ht1);
						vec1=new Vector();
						ht = new Hashtable();
						ht1 = new Hashtable();
						lst_dat = new LinkedList();
						rootJson.put("reportData",resultData);
					}
					else
					{
						lst.add(intlmap.getTextDescription("reporter.common.No measures available for the current selection"));	
					}
				}
			}
			else
			{
				JSONObject chartData =  new JSONObject();

				ErFusionChartBean chartbean = new ErFusionChartBean();
				String strLabels = (String)ht_Data.get("sampleLabels");
				StringTokenizer strTok = new StringTokenizer(strLabels,",");
				int countlabels = strTok.countTokens();
				int heightForapplet = chartbean.getbarHeightforCount(countlabels);
				if(heightForapplet>0)
				{
					heightForapplet = (heightForapplet - (countlabels*15));
				}
				String xmlStringForFusionBarChart = chartbean.getXmlDataforfusionbarchart(ht_Data);
				String er_mode = request.getParameter("er_mode");
				String dimension = "MSBar"+(er_mode != null && er_mode.equalsIgnoreCase("2D") ? "2" : "3" ) + "D";
				String swfpath = "/final/FusionCharts/swf/MSBar" +  (er_mode != null && er_mode.equalsIgnoreCase("2D") ? "2" : "3" ) + "D.swf";

				chartData.put("chartTitle",strtitle);
				chartData.put("swfpath",swfpath);
				chartData.put("XMLData",xmlStringForFusionBarChart);
				chartData.put("chartHeight",String.valueOf(heightForapplet));
					//
			chartData.put("xAxisLabel",chartbean.getXAxisDataLabel());
			chartData.put("yAxisLabel",chartbean.getYAxisLabel());
			JSONArray dataSet = new JSONArray();
			JSONObject s1=new JSONObject();
			s1.put("name","");
			s1.put("data",chartbean.getBarDataSet());
			s1.put("showInLegend", new Boolean(false));
			dataSet.add(s1);

			chartData.put("DataSet",dataSet);
			chartData.put("title","");
			chartData.put("chartType","bar");
			chartData.put("chartHeight",chartbean.getBarChartHeight());
			chartData.put("chartWidth",chartbean.getBarChartWidth());
			chartData.put("isTopNReport",new Boolean(true));
			rootJson.put("reportData",chartData);
		}
			String key=s_test +" : " +s_meas;
			htdata.put(key,data);
			repData.put("commandName","TopN");
			Vector data1=new Vector();
			String subTitle=intlmap.getTextDescription("reporter.common.From")+"  "+erd.s_stdate+" "+intlmap.getTextDescription("reporter.common.hrs")+" "+intlmap.getTextDescription("reporter.common.To")+" "+erd.s_enddate+" "+intlmap.getTextDescription("reporter.common.hrs");
			data1.add(subTitle);
			data1.add(htdata);
			HashMap param =new HashMap();
			if(reportType!=null && !reportType.equalsIgnoreCase("graph"))
			{
				repData.put("pdfData",topNPdfData);
				session.setAttribute("sessionVal",repData);
				param.put("REPORT_PARAM",ErUtils.parseQueryString(ErUtils.prepareQueryString(request.getParameterMap())));
				param.put("REPORT_DATA",topNPdfData);
				session.setAttribute("parameters", param);
			}
			else
			{
				//Map tempHash=request.getParameterMap();
				Map tempHash = ErUtils.parseQueryString(ErUtils.prepareQueryString(request.getParameterMap()));
				tempHash.remove("er_combination");
				tempHash.remove("er_graphtype");
				User this_user = UserRegistry.getInstance().getUser(session.getId());
				urs = this_user.getLoginID();
				tempHash.put("er_userid",urs);
				tempHash.put("er_view","image");
				param.put("REPORT_PARAM",ErUtils.parseQueryString(ErUtils.prepareQueryString(tempHash)));
				param.put("REPORT_DATA",ht_Data);
				session.setAttribute("parameters", param);
				session.setAttribute("chartDatas",ht_Data);
			}
		}
				String testDescription = intlmap.getTestDescription(s_test);
				unit= tablesInfo.getUnitForMeasure(s_test,s_meas);
				if (testDescription != null && testDescription.length() > 0)
					strtitle=intlmap.getTestDescription(s_test) +" : " +intlmap.getMeasureDescription(s_test,s_meas)+" ("+unit+") ";
				else
					strtitle = s_test + " : " + s_meas;
				//
				if(strtitle!=null)
				{
					strtitle = erUtils.specialCharEncode(strtitle);
				}
				
				session.setAttribute("DRILLDOWN_MAIL_URL", mngrIProc+"/final/reporter/ErTopNReportsDrillDownPrint.jsp;jsessionid="+ session.getId()+"?"+printQString.toString()+"&chartTitle="+strtitle);

				String Pstring="";
				if(printQString!=null)
				{
					StringTokenizer strtok = new StringTokenizer(printQString.toString(),"&");
					while(strtok.hasMoreTokens())
					{
						String parameter = strtok.nextToken();
						int ind = parameter.indexOf("=");
						//if (ind < 0 || parameter.indexOf("responseType")>-1)
						if (ind < 0)
							continue;

						String reqparam =parameter.substring(0,ind);
						String value = parameter.substring(ind+1);
						if(reqparam!=null&&reqparam.equals("er_RmDispName"))
						{
							value=com.eg.EgURLEncoder.encode(value, "UTF-8");
						}
						Pstring=Pstring+reqparam+"="+value+"&";
					}
				}
		ArrayList hm=(ArrayList)session.getAttribute("QueryStringMap");
		if(hm!=null)
		{
			Object[] objArr=new Object[6];
			objArr[0]=Pstring;
			objArr[1]=ht_Data;
			objArr[2]=strtitle;
			objArr[3]="";
			objArr[4]=chartIndex;
			objArr[5]=colName;
			if(chartIndex!=null&& chartIndex.length()>0)
			{
				Integer cIndx=new Integer(chartIndex);
				hm.set(cIndx,objArr);
			}
		}
		HashMap csvMap=(HashMap)session.getAttribute("CsvDataMapForTopN");
		HashMap csvTitleMap=(HashMap)session.getAttribute("csvTitleMapForTopN");
		if(csvMap!=null)
			csvMap.put(chartIndex,lst);
		if(csvTitleMap!=null)
			csvTitleMap.put(chartIndex,strtitle);
	}

	//Back Button - Start
	ArrayList listbackvar = new  ArrayList();
	if(request.getParameter("isSubmit")!=null)
	{
		session.setAttribute("reportLastAccessedURL","/final/reporter/ErTopNReports.jsp?"+Qstring);

		listbackvar.add("/servlet/com.eg.ErRepoLiteC?");
		listbackvar.add("status="+status+"&bggroundStr="+bggroundStr+"&"+queryString);
		session.setAttribute("favSchBackDisplay","Yes");
	}
	else
	{
		session.setAttribute("reportLastAccessedURL","/final/reporter/ErTopNReports.jsp?"+Qstring);

		listbackvar.add("ErTopNReports.jsp");
		listbackvar.add(queryString);
		session.setAttribute("favSchBackDisplay","No");
	}
	String backadded = erhelputils.getBackID();
	backreqMap = erhelputils.setBackQueryMap(backreqMap,backadded,listbackvar);
	session.setAttribute("backQuery",backreqMap);
	session.setAttribute("list",lst);
	//Back Button - End
	rootJson.put("selectedFields",selectedFields);
	rootJson.put("combo",combo);
	rootJson.put("displayFields",displayFields);
	rootJson.put("hiddenFields",hiddenFields); 
	rootJson.put("urlFields",urlFields); 

	out.println(rootJson.toString());
}
catch(Exception e)
{
	e.printStackTrace();
}
%>
