<%@ include file= "ErReporterTracker.jsp" %>
<%@ page import = "java.util.Date"%>
<%@ page import = "java.util.Map"%>
<%@ page import = "java.text.SimpleDateFormat"%>
<%@ page import = "java.util.Enumeration"%>
<%@ page import = "net.sf.json.*" %>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "egurkha.reporter.ErUtils"%>
<%@ page import = "egurkha.reporter.builder.TemplateInfoBean"%>
<%@ page import = "egurkha.reporter.builder.ReportBuilderBean"%>
<%@ page import = "egurkha.reporter.builder.ReportBuilderCustomBean"%>
<%@ page import = "java.io.DataOutputStream"%>
<%@ page import = "java.io.FileNotFoundException"%>
<%@ page import = "java.io.FileOutputStream"%>
<%@ page import = "java.io.IOException"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "com.eg.EgConfigInfo"%>
<%@ page import = "com.eg.EgMappingInfo"%>
<%@ page import = "com.eg.EgDateInfo"%>
<%@ page import = "com.egurkha.util.DateUtil" %>
<%@ page import = "com.egurkha.util.DateTimeTokenizer" %>

 
<%
try
{
	JSONObject builderJson =new JSONObject();
	String method	=	request.getParameter("method");
	if(method != null && method.equals("timelineChange"))
	{
		String er_timeline=request.getParameter("er_timeline");
		String er_stdate = request.getParameter("er_stdate");
		String er_enddate = request.getParameter("er_enddate");
		String er_sthr = request.getParameter("er_sthr");
		String er_endhr = request.getParameter("er_endhr");
		String er_stmin = request.getParameter("er_stmin");
		String er_endmin = request.getParameter("er_endmin");
		ReportBuilderCustomBean builderBean=new ReportBuilderCustomBean(urs,session.getId());
		JSONObject combo=new JSONObject();
		combo.put("timeInterValCombo",builderBean.getTimeIntervalCombo(er_timeline,er_stdate,er_enddate,er_sthr,er_endhr,er_stmin,er_endmin));
		builderJson.put("combo", combo);
		builderJson.put("selectedFields", builderBean.getSelectedFields());
		//builderJson.put("getTimeIntervalCombo",builderBean.getTimeIntervalCombo(er_timeline));
	}
	else
	{
	String queryString =(String)ErUtils.prepareQueryString(request.getParameterMap());	
	EgMappingInfo intlmap=new EgMappingInfo(thisuser.getLanguage());
	String isCustomLayout=request.getParameter("isCustomLayout");

	ArrayList encodeParamList=new ArrayList();
	encodeParamList.add("er_measure");
	encodeParamList.add("recordInfo");
	encodeParamList.add("chartInfo");
	encodeParamList.add("er_timeline");
	encodeParamList.add("er_component");
	String Qstring = "";
	JSONObject selectionDetails=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");
	builderJson.put("chartIndex",chartIndex);
	String strtitle="";
	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 backButtonEnable = request.getParameter("back");
	builderJson.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
	ArrayList listbackvar = new  ArrayList();
	String mngrIProc = new IniFile(new EgConfigInfo("manager").getDbFile()).getValue("DB_PROPERTIES","ManagerUrl");
	String titleDisp=(String)request.getParameter("templateName");
	/*if(request.getParameter("isSubmit")!=null)
	{
		listbackvar.add("ReportBuilder.jsp");
		listbackvar.add("status="+status+"&bggroundStr="+bggroundStr+"&er_view=GRAPH&"+queryString);
		session.setAttribute("favSchBackDisplay","Yes");
	}
	else
	{
		listbackvar.add("ReportBuilder.jsp");
		listbackvar.add(queryString);
		session.setAttribute("favSchBackDisplay","No");
	}
	String backadded = erhelputils.getBackID();
	backreqMap = erhelputils.setBackQueryMap(backreqMap,backadded,listbackvar);
	session.setAttribute("backQuery",backreqMap);*/
	//..
	if(method != null && method.equalsIgnoreCase("submit"))
	{
		
		if(queryString!=null)
		{
			
			ArrayList strtok=ErUtils.egTokenizer(queryString,"&");
			for(int i=0;i<strtok.size();i++)
			{
				String param=(String)strtok.get(i);
				int ind = param.indexOf("=");
				if (ind < 0)
					continue;
				String reqparam = param.substring(0,ind);
				String reqvalue = param.substring(ind+1);
				//if(encodeParamList != null &&(encodeParamList.contains(reqparam)))
				//{
				//}

				/*
						This line is commented because of the reloading issue happened in the all builder reports
						Need to Check if any problems occurs throughout the Report builder Reports
				*/
					reqvalue=com.eg.EgURLEncoder.encode(reqvalue, "UTF-8");


				if(reqparam != null && reqparam.equalsIgnoreCase("er_component"))
				{
					continue;
				}
				Qstring = Qstring + reqparam + "=" + reqvalue + "&";
			}
			Qstring += "er_component=sessionComponent";
		}
		String fromReportBuilder=null;
		if(request.getParameter("fromReportBuilder") != null)
			fromReportBuilder=request.getParameter("fromReportBuilder");
		String user_dispName=(String)request.getParameter("user_dispName");
		if(user_dispName != null)
			user_dispName=com.eg.EgURLEncoder.encode(user_dispName, "UTF-8");
		if(titleDisp != null)
			titleDisp=com.eg.EgURLEncoder.encode(titleDisp, "UTF-8");
		if(user_dispName != null)
			titleDisp=user_dispName;
		Map tempNameMap=new HashMap();
		tempNameMap.put("fileName",titleDisp);
		session.setAttribute("parameters",tempNameMap);//..this is common attribute in reporter module
		session.setAttribute("reportLastAccessedURL","/final/reporter/ReportBuilder.jsp?isSubmit=true&"+Qstring);		
		//......ezhil
		listbackvar.add("ReportBuilder.jsp");
		listbackvar.add("isSubmit=true&status="+status+"&bggroundStr="+bggroundStr+"&er_view=GRAPH&"+Qstring/*+"&previousreportName=EXECUTIVE_REPORTS_COMPONENT"*/);
		session.setAttribute("favSchBackDisplay","Yes");
		
		if(isCustomLayout!=null && isCustomLayout.equals("yes")) 
		{
			session.setAttribute("PDF_URL",mngrIProc+"/final/reporter/ErPrintCustomReportBuilder.jsp");	
		}
		else
		{
			session.setAttribute("PDF_URL",mngrIProc+"/final/reporter/ErPrintReportBuilder.jsp");
		}
		
		String er_option=request.getParameter("er_option");
		String er_compType=request.getParameter("er_compType");
		String excludeweekend=request.getParameter("er_excwe");
		if (excludeweekend==null ||	excludeweekend.equals(""))
			excludeweekend="No";
		
		selectionDetails.put(intlmap.getTextDescription("reporter.common.Analysis By"),er_option);
		selectionDetails.put(intlmap.getTextDescription("reporter.common.Component Type"),intlmap.getComponentTypeDescription(er_compType));
		Object selectedComps=request.getParameterValues("er_component");
		if(selectedComps != null)
		{
			List selectedCompList=new ArrayList(Arrays.asList((String[])selectedComps));
			if(selectedCompList != null && !selectedCompList.isEmpty() && selectedCompList.size() == 1)
			{
				String firstComp=(String)selectedCompList.get(0);
				if(firstComp != null && !firstComp.equals("-1"))
				{
					firstComp=firstComp.indexOf(":") != -1 ? firstComp.substring(0,firstComp.lastIndexOf(":")) : firstComp;
					if(firstComp.indexOf(":") != -1)
					{
						String portNo=(String)firstComp.substring(firstComp.indexOf(":")+1);
						if(portNo == null || portNo.equalsIgnoreCase("NULL"))
							firstComp=firstComp.substring(0,firstComp.indexOf(":"));							
					}
					selectionDetails.put("Component",firstComp);
				}
			}
		}
		String[] options = {"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","2 months","3 months"};
		
		IniUI ui = IniUI.getInstance();
		EgDateInfo egDt = new EgDateInfo();
		String uiFile = "eg_ui.ini";
		String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
		IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
		String currentDateFormat = strUserDateFormat;
		long msecsPerHour = (long) 1000 * 60 * 60;
		String starttimeformat="";
		String endtimeformat="";
		String dispDate = null;
		String comFormat = null;
		String Hourfrom="";
		String Minfrom="";
		String Hourto="";
		String Minto="";
		String fromTime,toTime;
		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 timefrom2=request.getParameter("timefrom");
		String minfrom2=request.getParameter("minfrom");
		String timeto2=request.getParameter("timeto");
		String minto2=request.getParameter("minto");

		if (timefrom2!=null)
			Hourfrom=timefrom2;
		if (minfrom2!=null)
			Minfrom=minfrom2;
		if (timeto2!=null)
			Hourto=timeto2;
		if (minto2!=null)
			Minto=minto2;
		
		if(er_timeline==null  || er_timeline.equals(" "))
		{
			er_timeline="1 day";
		}
			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 = new java.util.Date(egDt.egetUTCDate());
						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 = egDt.egetRealDate();
					start.setTime(today.getTime() - (value * 1000));
					startDateTime = sdf.format(start);
				}else if (unit.endsWith("last")){
					String usrStartDateTime = startDateTime +" 00:00";
					String usrEndDateTime = endDateTime +" 23:59";
					System.out.println("ReportBuilderController User Start Date-->"+usrStartDateTime+ "    End Time-->"+usrEndDateTime);
					EgTimeZoneConverter timeZoneConverterStart = new EgTimeZoneConverter(usrStartDateTime, thisuser, true);
					startDateTime = DateUtil.changeDateFormat((String) timeZoneConverterStart.getDate(false), thisuser.getUserDateFormat(), "MM/dd/yyyy");
					startDateTime = startDateTime+" "+(String) timeZoneConverterStart.getHour()+":"+(String) timeZoneConverterStart.getMinute();
					EgTimeZoneConverter timeZoneConverterEnd = new EgTimeZoneConverter(usrEndDateTime, thisuser, true);
					endDateTime = DateUtil.changeDateFormat((String) timeZoneConverterEnd.getDate(false), thisuser.getUserDateFormat(), "MM/dd/yyyy");
					endDateTime = endDateTime +" "+(String) timeZoneConverterEnd.getHour()+":"+(String) timeZoneConverterEnd.getMinute();
		
				}
			
				if ((startDateTime != null) && (endDateTime != null))
				{
					int shr = Integer.parseInt(startDateTime.substring(startDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, startDateTime.indexOf(":")));
					strmin=startDateTime.substring(startDateTime.indexOf(":")+1);
					int en_hr = Integer.parseInt(endDateTime.substring(endDateTime.indexOf(DateTimeTokenizer.BLANK_SPACE)+1, endDateTime.indexOf(":")));
					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));
					s_st_hr = String.valueOf(shr);
					s_en_hr = String.valueOf(en_hr);
				}
			}
		}
		//..
		String	userDateFormat = thisuser.getUserDateFormat();
		s_st_time = DateUtil.changeDateFormat(s_st_time,"MM/dd/yyyy",userDateFormat);
		s_en_time = DateUtil.changeDateFormat(s_en_time,"MM/dd/yyyy",userDateFormat);
		if(request.getParameter("dateInMillisecs") != null)
		{
			String dateInMillisecs=request.getParameter("dateInMillisecs");
			try
			{
				Date date=new Date(Long.parseLong(dateInMillisecs));
				SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
				String selectedStartDateVal = df2.format(date);				
				String selectedStartDateDisp =DateUtil.changeDateFormat(selectedStartDateVal,"dd/MM/yyyy",userDateFormat);
				s_st_time=selectedStartDateDisp;
				s_en_time=selectedStartDateDisp;
			}
			catch (Exception e)
			{
			}
		
		}
		//..

		EgTimeZoneConverter usrTimeZoneStart = new EgTimeZoneConverter(s_st_time+" "+s_st_hr+":"+strmin, thisuser);
		EgTimeZoneConverter usrTimeZoneEnd = new EgTimeZoneConverter(s_en_time+" "+s_en_hr+":"+enmin, thisuser);
		String  pdfStartDate = usrTimeZoneStart.getDateTime();
		String  pdfEndDate   = usrTimeZoneEnd.getDateTime();
		String pdfTime = "From "+pdfStartDate+" hrs "+" "+" To "+pdfEndDate+" hrs";		
%>
	<%@  include file ="ErTimeFormatJSON.jsp"%>	
<%
	
	//selectionDetails.put(intlmap.getTextDescription("reporter.common.Exclude weekends"),excludeweekend);
	//selectionDetails.put(intlmap.getTextDescription("reporter.common.Time Period "),Hourfrom+":"+Minfrom+" <b>"+intlmap.getTextDescription("reporter.common.to")+" </b>"+Hourto+":"+Minto);
//	String tempName=request.getParameter("templateName");
	boolean timelineHidden=false;
	Map tRequestMap=(Map)session.getAttribute("tRequestMap"); 
	if(tRequestMap != null && tRequestMap.get("timelineHidden") != null)
	{
		String timelineHiddenStr=(String)tRequestMap.get("timelineHidden");
		if(timelineHiddenStr.equalsIgnoreCase("yes"))
			timelineHidden=true;
	}
	if(!timelineHidden)
		selectionDetails.put((String)intlmap.getTextDescription("reporter.common.Timeline"),pdfStartDate+" "+intlmap.getTextDescription("reporter.common.hrs")+" <b>  "+intlmap.getTextDescription("reporter.common.to")+" </b>"+pdfEndDate+" "+intlmap.getTextDescription("reporter.common.hrs"));
	
		
	}
	else if(method != null && !method.equalsIgnoreCase("setTitleDescription") && !method.equalsIgnoreCase("setWidgetHeaderFooter") && !method.equalsIgnoreCase("getWebApp"))
	{
		//..This condition for set LastAccessUrl other than submit method//..
		if(queryString!=null)
		{
			
			ArrayList strtok=ErUtils.egTokenizer(queryString,"&");
			for(int i=0;i<strtok.size();i++)
			{
				String param = (String)strtok.get(i);
				int ind = param.indexOf("=");
				if (ind < 0)
					continue;
				String reqparam = param.substring(0,ind);
				String reqvalue = param.substring(ind+1);
				//if(encodeParamList != null &&(encodeParamList.contains(reqparam)))
				//{
					reqvalue=com.eg.EgURLEncoder.encode(reqvalue, "UTF-8");
				//}
				if(reqparam != null && reqparam.equalsIgnoreCase("er_component"))
				{
					continue;
				}
				Qstring = Qstring + reqparam + "=" + reqvalue + "&";
			}
			Qstring += "er_component=sessionComponent";
		}
		session.setAttribute("reportLastAccessedURL","/final/reporter/ReportBuilder.jsp?"+Qstring);	
		//..ezhil
		listbackvar.add("ReportBuilder.jsp");
		listbackvar.add(Qstring);
		session.setAttribute("favSchBackDisplay","No");
		//..
		//session.setAttribute("reportLastAccessedURL","/final/reporter/ReportBuilder.jsp?isSubmit=true&"+Qstring);		
	}
	//ezhil
	String backadded = erhelputils.getBackID();
	backreqMap = erhelputils.setBackQueryMap(backreqMap,backadded,listbackvar);
	session.setAttribute("backQuery",backreqMap);
	//..
	String widget = request.getParameter("widget"); 
	boolean isHeaderFooterUpdate=false;
	request.setAttribute("userId",urs);
	request.setAttribute("sessionId",session.getId());

	if(method!=null)
	{
		 
		String fromReportBuilder = request.getParameter("fromReportBuilder"); 
		IniFile inifile; 
		if(fromReportBuilder != null && fromReportBuilder.equals("true"))
			inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_report.ini",true); 
		else
			inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_reportbuilder.ini",true); 
			int pageWidthProces=1024;
		if(isCustomLayout!=null && isCustomLayout.equals("yes")) 
		{
			if(method.equals("setWidgetHeaderFooter"))
			{
				// this is for both custom and normal layout
				isHeaderFooterUpdate=true;
				//IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_reportbuilder.ini",true); 
				String idDescription =(String) request.getParameter("idDescription");
				String widgetHeaderFooterInfo = (String)request.getParameter("widgetHeaderFooterInfo");
				//StringTokenizer token1 = new StringTokenizer(idDescription, "$~$");
				ArrayList token1=ErUtils.egTokenizer(idDescription, "$~$");
				String templateName=null;
				String widgetId=null;
				String descriptionType=null;
				/*while (token1.hasMoreElements())
				{
					templateName=(String) token1.nextElement();
					widgetId=(String) token1.nextElement();
					descriptionType=(String) token1.nextElement();
				}*/
				for(int i=0;i<token1.size();i=i+3)
				{
					templateName=(String) token1.get(i);
					widgetId=(String) token1.get(i+1);
					descriptionType=(String) token1.get(i+2);
				}
				if(templateName!=null)
				{
					//grid$~$widget$~$headerDescription
					//inifile.setValue(templateName+"_displayView",widgetId+"*~*"+descriptionType,widgetHeaderFooterInfo);
					JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
					if(resultJson!=null)
					{
						JSONObject widgetCollection=(JSONObject) resultJson.get(widgetId+"_detail");
						if(widgetCollection==null)
							 widgetCollection=(JSONObject) resultJson.get("widget");
						if(descriptionType.equalsIgnoreCase("headerDescription"))
							widgetCollection.put("widgetHeader",widgetHeaderFooterInfo);
						else
							widgetCollection.put("widgetFooter",widgetHeaderFooterInfo);
					}
				}
				//inifile.saveFile();
			}
			else if(method.equals("setTitleDescription"))
			{
				String templateTitle = request.getParameter("templateTitle");  
				if(templateTitle == null)
					templateTitle=request.getParameter("templateName");
				JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
				if(resultJson!=null)
				{
					resultJson.put("templateTitle",templateTitle);
				}
				
			}
			else if(method.equals("setWidgetDescription")) 
			{
				String templateName = request.getParameter("templateName");
				String widgetName = request.getParameter("widgetName");
				String headerDescription = request.getParameter("headerDescription");  
				String footerDescription = request.getParameter("footerDescription");  
				String widgetTitleInfo = request.getParameter("widgetTitleInfo"); 
				String widgetInfoStr=inifile.getValue(templateName+"_overview",widgetName);
				if(widgetTitleInfo==null)
					widgetTitleInfo="Tabel Title";

				JSONObject widgetInfoObj = (JSONObject) JSONSerializer.toJSON(widgetInfoStr);

				if(headerDescription!=null)
					widgetInfoObj.put("headerDescription",headerDescription);
				if(footerDescription!=null)
					widgetInfoObj.put("footerDescription",footerDescription);

				widgetInfoStr=widgetInfoObj.toString();
				JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
				if(resultJson!=null)
				{
					
					JSONObject widgetCollection=(JSONObject) resultJson.get(widgetName+"_detail");
					if(widgetCollection==null)
						widgetCollection=(JSONObject) resultJson.get("widget");
						widgetCollection.put("headerDescription",widgetTitleInfo);

					 
				}

				//inifile.setValue(templateName+"_overview",widgetName,widgetInfoStr);
				//inifile.saveFile();

				Map tRequestMap=(Map)session.getAttribute("tRequestMap"); 
				
				tRequestMap.put(widgetName,widgetInfoStr); 
			}
			else if(method.equals("clearSessionData"))
			{
				session.setAttribute("htdata",null);
				session.setAttribute("htdataDrillDown",null);
				session.setAttribute("distributedPieMap",null);
					JSONObject preLoadWidgetInfo = new JSONObject();
					String er_compType=request.getParameter("er_compType");
					String reportGenType=request.getParameter("reportGenType");
					String templateName=(String)request.getParameter("templateName");
					ArrayList selCompTypeList = null;
					JSONArray preLoadWidgetLst = new JSONArray();
					if(reportGenType==null || !reportGenType.equalsIgnoreCase("background"))
					{
						//if(er_compType!=null && er_compType.equalsIgnoreCase("all"))
						if(er_compType!=null) // if need all the configured widget..else part not use for this condition
						{
							String widgetLstStr = inifile.getValue(templateName+"_configureview","widgetOrder");
							preLoadWidgetLst = (JSONArray) JSONSerializer.toJSON(widgetLstStr);
						}
						else
						{
							ArrayList allWidgetCompLst = new ArrayList(Arrays.asList(inifile.getVariables(templateName+"_detailview")));
							Collections.sort(allWidgetCompLst);
							if(er_compType.indexOf(",")>-1)
							{
								selCompTypeList=new ArrayList(Arrays.asList(er_compType.split(",")));
							}
							else
							{
								selCompTypeList=new ArrayList();
								selCompTypeList.add(er_compType);
							}
							for(int i=0;i<selCompTypeList.size();i++)
							{
								String selCompType = (String)selCompTypeList.get(i);
								for(int j=0;j<allWidgetCompLst.size();j++)
								{
									String WidgetComp = (String)allWidgetCompLst.get(j);
									if(WidgetComp.contains(selCompType))
									{
										WidgetComp = WidgetComp.substring(0,WidgetComp.indexOf("$"));
										if(!preLoadWidgetLst.contains(WidgetComp))
										{
											preLoadWidgetLst.add(WidgetComp);
										}
									}
								}
							}
						}
					}
					if(preLoadWidgetLst.size()>0)
					{
						for(int i=0;i<preLoadWidgetLst.size();i++)
						{
							String widgetId = (String)preLoadWidgetLst.get(i);
							String widgetLstStr = inifile.getValue(templateName+"_overview",widgetId);
							JSONObject widgetInfoObj = (JSONObject) JSONSerializer.toJSON(widgetLstStr);
							if(fromReportBuilder != null && fromReportBuilder.equals("true") && widgetInfoObj != null && widgetInfoObj.get("headerDescription") != null)
							{
								String headerDesc=(String)widgetInfoObj.get("headerDescription");
								headerDesc=intlmap.getTextDescription("reporter.common."+headerDesc);
								widgetInfoObj.put("headerDescription",headerDesc);
							}
							preLoadWidgetInfo.put(widgetId,widgetInfoObj);
						}
						String widgetMerge = inifile.getValue(templateName+"_overview","widgetMerge");
						if(widgetMerge!=null && widgetMerge.equalsIgnoreCase("yes"))
						{
							String widgetMergeListStr = inifile.getValue(templateName+"_overview","widgetMergeList");
							JSONArray widgetMergeList = (JSONArray) JSONSerializer.toJSON(widgetMergeListStr);
							JSONArray widgetMergeOut = new JSONArray();
							for(int i=0;i<widgetMergeList.size();i++)
							{
								JSONArray widgetMergeAry = (JSONArray)widgetMergeList.get(i);
								JSONArray widgetMergeOutObj = new JSONArray();
								for(int j=0;j<widgetMergeAry.size();j++)
								{
									String widgetId = (String)widgetMergeAry.get(j);
									if(preLoadWidgetInfo.get(widgetId)!=null)
									{
										JSONObject widgetInfoObj = new JSONObject();
										widgetInfoObj.put(widgetId,preLoadWidgetInfo.get(widgetId));
										widgetMergeOutObj.add(widgetInfoObj);
									}
								}
								widgetMergeOut.add(widgetMergeOutObj);
							}
							builderJson.put("preLoadWidgetInfo", widgetMergeOut);
						}
						else
						{
							builderJson.put("preLoadWidgetInfo", preLoadWidgetInfo);
						}
					}
				builderJson.put("status", "success");
			}
			else if(method.equals("getWebApp"))
			{
				ReportBuilderCustomBean builderBean=new ReportBuilderCustomBean(request,null,urs,true);
				builderJson.put("status", "success");
				builderJson.put("combo", builderBean.getMyCustomInfo());
				builderJson.put("selectedFields", builderBean.getSelectedFields());
			}
			else
			{
				String bg_reportname=request.getParameter("bg_reportname");
				String dynamicRangesInfo=(String)request.getParameter("dynamicRangesInfo");
				if(dynamicRangesInfo!=null&&dynamicRangesInfo.length()>0)
				{
					//StringTokenizer tokens = new StringTokenizer(dynamicRangesInfo,",");
					ArrayList tokens=ErUtils.egTokenizer(dynamicRangesInfo,",");
					Map sessionrangeMap=new HashMap();
					/*while (tokens.hasMoreTokens())
					{  
						String eachToken=tokens.nextToken();
						StringTokenizer subTokens = new StringTokenizer(eachToken,"~");
						// 1st token Display name and next token valuesettings(eg: gt*10)
						sessionrangeMap.put(subTokens.nextToken(),subTokens.nextToken());
					}*/
					for(int i=0;i<tokens.size();i++)
					{
						String eachToken=(String)tokens.get(i);
						ArrayList subTokens=ErUtils.egTokenizer(eachToken,"~");
						// 1st token Display name and next token valuesettings(eg: gt*10)
						sessionrangeMap.put((String)subTokens.get(0),(String)subTokens.get(1));
					}
					session.setAttribute("sessionrangeMap",sessionrangeMap);
				}
				if(bg_reportname!=null)
				{
					String totalwidget=(String)request.getParameter("totalwidget");
					int totalCount=Integer.parseInt(totalwidget);
					for(int i=0;i<totalCount;i++)
					{
						ReportBuilderCustomBean builderBean=new ReportBuilderCustomBean(request,null,urs,"widgetInfo"+i);
						builderJson.put("status", "success");
						builderJson.put("combo", builderBean.getCombos());
						builderJson.put("selectedFields", builderBean.getSelectedFields());
						builderJson.put("displayFields", builderBean.getDisplayFields());
						JSONObject data=(JSONObject)builderBean.getData();
						builderJson.put("data",data);
						builderJson.put("hiddenFields", builderBean.getHiddenFields());
					}
				}
				else
				{
					ReportBuilderCustomBean builderBean=new ReportBuilderCustomBean(request,null,urs);
					builderJson.put("status", "success");
					builderJson.put("combo", builderBean.getCombos());
					builderJson.put("selectedFields", builderBean.getSelectedFields());
					builderJson.put("displayFields", builderBean.getDisplayFields());
					JSONObject data=(JSONObject)builderBean.getData();
					builderJson.put("data",data);
					builderJson.put("hiddenFields", builderBean.getHiddenFields());
					JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
					if(resultJson!=null)
					{
						String templateName=request.getParameter("templateName");
						String needNoMeasure=inifile.getValue(templateName+"_overview","needNoMeasure");
							String firstColWordBreakPrint=inifile.getValue(templateName+"_overview","firstColWordBreakPrint");
							resultJson.put("firstColWordBreakPrint",firstColWordBreakPrint);
							builderJson.put("firstColWordBreakPrint",firstColWordBreakPrint);
						resultJson.put("needNoMeasure",needNoMeasure);
						builderJson.put("needNoMeasure",needNoMeasure);
						if(resultJson.get("selectionDetails") == null)
						resultJson.put("selectionDetails",selectionDetails);
					}
				}
			}
		}
		else
		{
			if(method.equals("setTitleDescription"))
			{
				String templateTitle = request.getParameter("templateTitle");  
				if(templateTitle == null)
					templateTitle=request.getParameter("templateName");
				JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
				if(resultJson!=null)
				{
					resultJson.put("templateTitle",templateTitle);
				}
				
			}
			else if(method.equals("setHeaderDescription")){
				String templateName = request.getParameter("templateName");
				String headerDescription = request.getParameter("headerDescription");  
				String footerDescription = request.getParameter("footerDescription");  
				String componentType = request.getParameter("componentType");  
				String widgetTitleInfo = request.getParameter("widgetTitleInfo");  
				
				if(widgetTitleInfo==null)
					widgetTitleInfo="Tabel Title";
					
				//IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_reportbuilder.ini",true); //No need to apply eg_report.ini
				if(widgetTitleInfo!=null)
				{
					//inifile.setValue(templateName+"_displayView","widget*~*title",widgetTitleInfo);
					JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
			
					if(resultJson!=null)
					{
					
						JSONObject widgetCollection=(JSONObject) resultJson.get("widget");
						widgetCollection.put("headerDescription",widgetTitleInfo);				
	
					}
				}
				//inifile.saveFile();
				Map tRequestMap=(Map)session.getAttribute("tRequestMap"); 
				tRequestMap.put("headerDescription",headerDescription); 
			}
			else if(method.equals("setWidgetHeaderFooter"))
			{
				// this is for both custom and normal layout
				isHeaderFooterUpdate=true;
				//IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_reportbuilder.ini",true); 
				String idDescription =(String) request.getParameter("idDescription");
				String widgetHeaderFooterInfo = (String)request.getParameter("widgetHeaderFooterInfo");
				//StringTokenizer token1 = new StringTokenizer(idDescription, "$~$");
				ArrayList token1=ErUtils.egTokenizer(idDescription, "$~$");
				String templateName=null;
				String widgetId=null;
				String descriptionType=null;

			
				for(int i=0;i<token1.size();i=i+3)
				{
					templateName=(String) token1.get(i);
					widgetId=(String) token1.get(i+1);
					descriptionType=(String) token1.get(i+2);
				}
				if(templateName!=null)
				{
					//grid$~$widget$~$headerDescription
					//inifile.setValue(templateName+"_displayView",widgetId+"*~*"+descriptionType,widgetHeaderFooterInfo);
					JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
					if(resultJson!=null)
					{
					
						JSONObject widgetCollection=(JSONObject) resultJson.get(widgetId);
						if(widgetCollection==null)
							 widgetCollection=(JSONObject) resultJson.get("widget");

						if(descriptionType.equalsIgnoreCase("headerDescription"))
							widgetCollection.put("widgetHeader",widgetHeaderFooterInfo);
						else
							widgetCollection.put("widgetFooter",widgetHeaderFooterInfo);

			
					}
				
				}
				//inifile.saveFile();
			
			}
			else if(method.equals("graphHeaderFooter"))
			{
				isHeaderFooterUpdate=true;
				String idDescription =(String) request.getParameter("idDescription");
				String compName = (String)request.getParameter("compName");
				String templateName = (String)request.getParameter("templateName");
				String widgetHeaderFooterInfo = (String)request.getParameter("widgetHeaderFooterInfo");
				String chartTypeCollection = (String)request.getParameter("chartTypeCollection");
				String chartType = (String)request.getParameter("chartType");
				//StringTokenizer token1 = new StringTokenizer(idDescription, "$~$");
				ArrayList token1=ErUtils.egTokenizer(idDescription, "$~$");
				String graphIndex=null;
				String descriptionType=null;
				/*while (token1.hasMoreElements())
				{
					descriptionType=(String) token1.nextElement();
					graphIndex=(String) token1.nextElement();
				}*/
				for(int i=0;i<token1.size();i=i+2)
				{
					descriptionType=(String) token1.get(i);
					graphIndex=(String) token1.get(i+1);
				}
				if(templateName!=null)
				{
					JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
					if(resultJson!=null)
					{
						JSONObject widgetCollection=(JSONObject) resultJson.get("widget");
						JSONArray chartAry=(JSONArray)widgetCollection.get(chartType);
						JSONObject chartAryObj=(JSONObject)chartAry.get(0);
						JSONObject updateableObj=null;
						if(compName!=null && compName.length()>0)
						{
							JSONObject chartCollObj=(JSONObject)chartAryObj.get(chartTypeCollection);
							JSONArray chartCompAry=(JSONArray)chartCollObj.get(compName);
							updateableObj=(JSONObject)chartCompAry.get(Integer.parseInt(graphIndex));
						}
						else
						{
							JSONArray chartCollAry=(JSONArray)chartAryObj.get(chartTypeCollection);
							updateableObj=(JSONObject)chartCollAry.get(Integer.parseInt(graphIndex));
						}
						if(descriptionType.equalsIgnoreCase("footer"))
							updateableObj.put("graphFooter",widgetHeaderFooterInfo);
						else
							updateableObj.put("graphHeader",widgetHeaderFooterInfo);
					}
				}
			}
			else if(method.equals("clearSessionData"))
			{
				session.setAttribute("htdata",null);
				session.setAttribute("htdataDrillDown",null);
				session.setAttribute("distributedPieMap",null);
				builderJson.put("status", "success");
			}
			else
			{
				String dynamicRangesInfo=(String)request.getParameter("dynamicRangesInfo");
				if(dynamicRangesInfo!=null&&dynamicRangesInfo.length()>0)
				{
					//StringTokenizer tokens = new StringTokenizer(dynamicRangesInfo,",");
					ArrayList tokens=ErUtils.egTokenizer(dynamicRangesInfo,",");
					Map sessionrangeMap=new HashMap();
					/*while (tokens.hasMoreTokens())
					{  
						String eachToken=tokens.nextToken();
						StringTokenizer subTokens = new StringTokenizer(eachToken,"~");
						// 1st token Display name and next token valuesettings(eg: gt*10)
						sessionrangeMap.put(subTokens.nextToken(),subTokens.nextToken());
					}*/
					for(int i=0;i<tokens.size();i++)
					{
						String eachToken=(String)tokens.get(i);
						ArrayList subTokens=ErUtils.egTokenizer(eachToken,"~");
						// 1st token Display name and next token valuesettings(eg: gt*10)
						sessionrangeMap.put((String)subTokens.get(0),(String)subTokens.get(1));
					}
					session.setAttribute("sessionrangeMap",sessionrangeMap);
				}
				ReportBuilderBean builderBean=new ReportBuilderBean(request,null,urs);
				builderJson.put("status", "success");
				builderJson.put("combo", builderBean.getCombos());
				builderJson.put("selectedFields", builderBean.getSelectedFields());
				builderJson.put("displayFields", builderBean.getDisplayFields());
				builderJson.put("data", builderBean.getData());
				builderJson.put("hiddenFields", builderBean.getHiddenFields());
				JSONObject resultJson = (JSONObject) session.getAttribute("htdata");
				if(resultJson!=null)
				{
					if(resultJson.get("selectionDetails") == null)
					resultJson.put("selectionDetails",selectionDetails);
				}
			}			
		}
			if(method.equalsIgnoreCase("submit"))
			{
				//
				//String mngrIProc = new IniFile(new EgConfigInfo("manager").getDbFile()).getValue("DB_PROPERTIES","ManagerUrl");
				if(isCustomLayout!=null && isCustomLayout.equals("yes")) 
				{
					session.setAttribute("MAIL_URL",mngrIProc+"/final/reporter/ErPrintCustomReportBuilder.jsp;jsessionid="+session.getId()+"?isSubmit=true&"+Qstring+"&drilldownReport=no&titleDisp="+titleDisp);
	}
				else
				{
					session.setAttribute("MAIL_URL",mngrIProc+"/final/reporter/ErPrintReportBuilder.jsp;jsessionid="+session.getId()+"?isSubmit=true&"+Qstring+"&drilldownReport=no&titleDisp="+titleDisp);
				}
			}
		}
	if(isHeaderFooterUpdate)
	{
		builderJson.put("isHeaderFooterUpdate","yes");
	}
	builderJson.put("selectionDetails",selectionDetails);	
	
	}
	response.getWriter().write(builderJson.toString());
}
catch (Exception ex)
{
	ex.printStackTrace();
}
%>
