<%@page contentType="text/html"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory,javax.xml.parsers.DocumentBuilder,org.w3c.dom.*"%>
<%@page import="ibase.dashboard.mfg.bean.*"%>
<%@page import="javax.naming.Context"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="ibase.webitm.utility.GenericUtility"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.Enumeration"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.HashMap"%>
<%@page errorPage="error.jsp"%>
<%@ page import="java.io.File,ibase.utility.CommonConstants" %>
<%@page import="java.text.SimpleDateFormat"%>
<jsp:useBean id="productionVsBudgetBean" scope="request"	class="ibase.dashboard.mfg.bean.ProductionVsBudgetReportBean" />

<%!GenericUtility genericUtility = GenericUtility.getInstance();
	String objName = "";
	Document dom = null;
	NodeList dtlList = null;
	Node parentNode = null;
	NodeList childNodeList = null;
	Node currDetail = null;
	ArrayList<String> chartDataList = null;
	List<String> geoLocList = null;
	List<String> unitFormList = null;
	String childNodeName = "";
	String period = "";
	String netsales = "";
	String amount = "";
	String fin_entity = "";
	StringBuffer chartData = null;
	String selectedEntity = "";
	String entity = "", descr = "";
	String user = "TA821";
	String rptTitle = "";
	String srcJSPath = "";
	String srcImagesPath = "";	
	Calendar calendar = null;
	String frmDate = "";
	String toDate = "", unitForm = "";
	String dayQty = "", fldValue = "";
       String fldDescr="",unitDescr="";
	NodeList locationList = null;
	NodeList detailList = null;
	NodeList unitList = null;
	NodeList dateList = null;
	NodeList dayQtyList = null;
	Node locationNode = null;
	NodeList foreCastList = null;
	Node unitNode = null;
	Node dateNode = null;
	Node dayNode = null;
	Node foreCastNode = null;
	String date = "";
	int lastDayOfMonth = 0;      
	int todaysDay = 0;
	int month = 0;
	int  preyear = 0;
	int  preyearVal = 0;
	int  year = 0;
	int  curryearVal =0;
	int currmonthVal =0;
	String[] geo_loc = null;
	String[] unit_form = null;
	String unitFrmXml = "";
	String geoLocCodeXml = "";
       String xmlDataString ="";
	String checkGeoLoc = "";
	String checkUnitForm = "";
	List<String> sumDayPro   = null;
	List<String> cumLstYear  = null;
	List<Double> cumuQty     = null;
	List<String> LBEList     = null;
	SimpleDateFormat simpleDateFormat = null;
	Double cumulativePro = 0.0;
	Double cumuQtyInDoubl = 0.0;
	Double cumLstYearInDouble = 0.0;
	Double lbeInDouble = 0.0;
	String cumulativeProStr = "";
	String cumuQtyStr = "";
	String cumLstYearStr = "";
	String lbeValStr = "";	
	String[] seclectYear = null;
	String[] seclectMonth = null;
	String monthStr="";
	int day=1;	
   //28/11/2013
   int  deviceDisplay=0;
   int  deviceFilter=0;
   //07/01/2014
  int    chartDivId = 0;
  String preyearMonth="";
  String exportPDFPath ="";
  String exportImagePath="";
  HashMap <String, List<String>> grdDataMap  =null;
  List gridDataList=null;  
  String userID="";


%>
<%
	response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
	response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	response.setHeader("Pragma", "no-cache");
	CommonConstants.setAPPLICATION_CONTEXT(config.getServletContext().getRealPath("/"));
	
%>
<%
	String userAgent = request.getHeader("user-agent");
	
	if (userAgent.indexOf("Android") > 0 || userAgent.indexOf("iPhone") > 0 )
	{
		srcJSPath     = "/ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "/ibase/FusionChart/images/MSColumnLine3D.swf";
		System.out.println("userAgent for iPhone==" + userAgent);
		deviceDisplay   =1;
		deviceFilter    =3;
  
	} 
	else if (userAgent.indexOf("Android") > 0 || userAgent.indexOf("iPad") > 0)
	{
		System.out.println("userAgent For iPad==" + userAgent);
		deviceDisplay   =2;
		deviceFilter    =3;
		
	}
	else
	{
		srcJSPath     = "/ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "/ibase/FusionChart/images/MSColumnLine3D.swf";
		System.out.println("userAgent for PC ==" + userAgent);
		deviceDisplay   =3;
		deviceFilter    =1;
		System.out.println("srcJSPath =="+srcJSPath+"srcImagesPath==="+srcImagesPath);
	}	
%>

<html>
<head>
<script type="text/javascript" src="<%=srcJSPath%>"></script>
<link rel="stylesheet" type="text/css"	   href="/ibase/dashboard/mfg/css/ui.dropdownchecklist.standalone.css" />
<link rel="stylesheet" type="text/css"	   href="/ibase/dashboard/mfg/css/mfg.css" />
<script type="text/javascript"	           src="/ibase/dashboard/mfg/jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript"	           src="/ibase/dashboard/mfg/jquery/jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript"	           src="/ibase/dashboard/mfg/jquery/ui.dropdownchecklist-1.4-min.js"></script>
</head>
<script type="text/javascript">

$(document).ready(function(){
	 
	$("#geo_loc").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 100 ,emptyText: "Select ..."});
 });
 
$(document).ready(function(){
	$("#unit_form").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 100,emptyText: "Select ..."});
 });
$(document).ready(function(){
	$("#acct_year").dropdownchecklist({emptyText: "For previous." });
 });
$(document).ready(function(){
	$("#acct_month").dropdownchecklist({emptyText: "For previous." });
 });

 //function for validation on change 27/11/2013
function isLocationSelected()
 {
	 if (document.getElementById("geo_loc").selectedIndex == -1 )
	{
		 alert("Please select at least one Location code");
		 return false;
	}
	
	
		
	else if(document.getElementById("unit_form").selectedIndex==-1)
       {
	        alert("Please select at least one Unit Form");
	        return false;
	 }
	 return true;
  }

</script>

<body>

<%
	try
	{
         exportPDFPath      = CommonConstants.APPLICATION_CONTEXT + "dashboard" + File.separator + "mfg"+ File.separator + "Scheduler"+File.separator +"ExportExample"+ File.separator + "ExportPDF"+File.separator;
         
         exportImagePath    = CommonConstants.APPLICATION_CONTEXT + "dashboard" + File.separator + "mfg"+ File.separator + "Scheduler"+ File.separator +"ExportExample"+ File.separator + "ExportImages"+File.separator;
    	        
         //out.println("exportImagePath========"+exportImagePath);
         userID              =request.getParameter("userID");	
		//ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)session.getAttribute("USER_INFO"); 		
					
		simpleDateFormat = new SimpleDateFormat("dd-MMM-yy");
		calendar         = Calendar.getInstance();
		preyear          = calendar.get(Calendar.YEAR) - 1;
		preyearVal       = calendar.get(Calendar.YEAR) - 1;					
		month            = calendar.get(Calendar.MONTH)+1 ;
		currmonthVal     = calendar.get(Calendar.MONTH)+1;
		year             = calendar.get(Calendar.YEAR);		
		curryearVal      = calendar.get(Calendar.YEAR);
		String currDate  = simpleDateFormat.format(calendar.getTime());
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		toDate           = simpleDateFormat.format(calendar.getTime());	
		
		calendar         = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		frmDate          = simpleDateFormat.format(calendar.getTime());
		todaysDay        = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		lastDayOfMonth   = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
		//frmDate = "01-jan-14";
		//toDate  = "30-jan-14";		
		//new code added by Birendra Pandey It is VIMP
		seclectYear      = request.getParameterValues("acct_year");
		seclectMonth     = request.getParameterValues("acct_month");		
		
		if(seclectYear!=null && seclectMonth!=null)
		{
			
			
			 year         = Integer.parseInt(seclectYear[0]);
			 month        = Integer.parseInt(seclectMonth[0]);
			  preyear     = year - 1;			 
			 if(month==1)
			     monthStr="Jan";  
			 else if(month==2)
			     monthStr="Feb"; 
			 else if(month==3)
			     monthStr="Mar"; 
             else if(month==4)
			     monthStr="Apr"; 
             else if(month==5)
			     monthStr="May"; 
             else if(month==6)
			     monthStr="Jun"; 
             else if(month==7)
			     monthStr="Jul"; 
             else if(month==8)
			     monthStr="Aug"; 
             else if(month==9)
			     monthStr="Sep"; 
             else if(month==10)
			     monthStr="Oct"; 
             else if(month==11)
			     monthStr="Nov"; 
             else if(month==12)
			     monthStr="Dec";    				 
			 
			//ADD-------1St of month and last of month				  
			  calendar       =Calendar.getInstance();
		      calendar.set(year, month-1, day);
		      frmDate        = simpleDateFormat.format(calendar.getTime());			     
		      calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		      toDate         = simpleDateFormat.format(calendar.getTime());			      
		      lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                 
		      
		   //End of -------1St of month and last of month		     			
			currDate =todaysDay+"-"+monthStr+"-"+seclectYear[0];
			//out.println("frmDate===="+frmDate+"To Date====="+toDate);
			//out.println("lastDayOfMonth for selected  "+lastDayOfMonth);
		}
		
		//End by Birendra Pandey		
		
		rptTitle           = "Production Vs Budget Report For : " + currDate;
		preyearMonth       =""+preyearVal+"/"+month;		 
		unitFrmXml         = productionVsBudgetBean.getUnitFormXmlData();
		geoLocCodeXml      = productionVsBudgetBean.getGeoLoCodeXmlData();
		System.out.println("rptTitle=====" + rptTitle);
		
%>
<form method="post" action="ProductionVsBudgetReportExport.jsp"	name="ProductionVsBudgetReport">
<br>
<table class="dropdown">
	<tr>
		<td class="tdLabel">
		 Location : <select id="geo_loc" name="geo_loc"	multiple="multiple" size="5">
		
           <%
			dom = genericUtility.parseString(geoLocCodeXml);

			 if (dom != null)
					{
			%>
			<option value="0">All</option>
			<%
				            dtlList = dom.getElementsByTagName("Detail");
						for (int cntr = 0; cntr < dtlList.getLength(); cntr++)
						{
							parentNode = dtlList.item(cntr);

							childNodeList = parentNode.getChildNodes();
							if (childNodeList.getLength() > 0)
							{
								fldValue = childNodeList.item(0).getTextContent();
								descr = childNodeList.item(1).getTextContent();
			%>
			<option value="<%=fldValue%>"><%=descr%></option>
			<%
				}

						}
					}
			%>
		</select>
		Product Form : 
		<select id="unit_form" name="unit_form" 	multiple="multiple" size="5">
              
			<%
				dom = genericUtility.parseString(unitFrmXml);

					if (dom != null)
					{
			%>
			<option value="0">All</option>
			<%
				dtlList = dom.getElementsByTagName("Detail");
						for (int cntr = 0; cntr < dtlList.getLength(); cntr++)
						{
							parentNode = dtlList.item(cntr);

							childNodeList = parentNode.getChildNodes();

							if (childNodeList.getLength() > 0)
							{
								unitForm = childNodeList.item(0).getTextContent();
                                unitDescr = childNodeList.item(1).getTextContent();

			%>
			<option value="<%=unitForm%>"><%=unitDescr%></option>
			<%
				}

						}
					}
			%>
		</select>		
		Year : <select id="acct_year" name="acct_year" size="3">
            <option value="<%=curryearVal%>"><%=curryearVal%></option>
            <option value="<%=preyearVal%>"><%=preyearVal%></option>           
            </select>
		
          Month : <select id="acct_month" name="acct_month" size="3">
            <option value="1">JAN</option>
            <option value="2">FEB</option>
            <option value="3">MAR</option>
            <option value="4">APR</option>
            <option value="5">MAY</option>
            <option value="6">JUN</option>
            <option value="7">JUL</option>
            <option value="8">AUG</option>
            <option value="9">SEP</option>
            <option value="10">OCT</option>
            <option value="11">NOV</option>
            <option value="12">DEC</option>
            
            </select>						
		    <input type="submit" name="showChart" value="View"	onclick="return isLocationSelected();"/>			
		</td>
	</tr>
</table>
<br>

<%
	    geo_loc          =request.getParameterValues("geo_loc");
	    unit_form        =request.getParameterValues("unit_form");	
		
		String geoLoc = "", unitFrm = "";
		if (geo_loc == null)
		{
			geoLoc = request.getParameter("geoLocation");
			if (geoLoc != null && geoLoc.trim().length() != 0)
			{
				geo_loc = geoLoc.trim().split(",");
			}
		}

		if (unit_form == null)
		{
			unitFrm = request.getParameter("unitForm");
			if (unitFrm != null && unitFrm.trim().length() != 0)
			{
				unit_form = unitFrm.trim().split(",");
			}
		}

		checkGeoLoc = "";
		if (geo_loc != null && geo_loc.length != 0)
		{
			for (int i = 0; i < geo_loc.length; i++)
			{
				if (!geo_loc[i].equals("0"))
				{

					if (i == geo_loc.length - 1)

						checkGeoLoc += "'" + geo_loc[i] + "'";

					else
						checkGeoLoc += "'" + geo_loc[i] + "',";

				}

			}
		}
		checkUnitForm = "";
		if (unit_form != null && unit_form.length != 0)
		{
			for (int i = 0; i < unit_form.length; i++)
			{
				if (!unit_form[i].equals("0"))
				{
					if (i == unit_form.length - 1)
						checkUnitForm += "'" + unit_form[i] + "'";

					else
						checkUnitForm += "'" + unit_form[i] + "',";
				}
			}
		}
              
            System.out.println("checkGeoLoc ==="+checkGeoLoc +"checkUnitForm ="+checkUnitForm );
		//here set selected value of geoLocation and unitForm for  final report output 
		
		if((checkGeoLoc!=null && checkGeoLoc.trim().length() != 0 ) && (checkUnitForm!=null && checkUnitForm.trim().length() != 0) ){
		   xmlDataString = productionVsBudgetBean.getProductionBudget(frmDate, toDate, this.checkGeoLoc, this.checkUnitForm);
		}
					
		System.out.print("Final xmlDataString ,which make charts= " + xmlDataString);
		//parse xml
		dom = genericUtility.parseString(xmlDataString);
		if (dom != null)
		{
            //Initilization of all variable on dated 28/10/2013			
			chartDataList    = new ArrayList<String>();
			geoLocList       =new ArrayList<String>();
			unitFormList     =new ArrayList<String>();
			//***************BIrendra Pandey*************************
		 sumDayPro        = new ArrayList<String>();
	        cumLstYear       = new ArrayList<String>();
	        cumuQty          = new ArrayList<Double>();
	        LBEList          = new ArrayList<String>(); 						
		 detailList       = dom.getElementsByTagName("Detail");

			if (detailList.item(0).getFirstChild() != null)
			{
				locationList = dom.getElementsByTagName("geo_loc");
				for (int cntr = 0; cntr < locationList.getLength(); cntr++)
				{

					locationNode = locationList.item(cntr);
					//start  of the Lable setting 1			
					geoLocList.add(locationNode.getAttributes().getNamedItem("glocdescr").getNodeValue());
					chartData = new StringBuffer("<chart caption='");
					chartData.append("' palette='1' showValues='0' yAxisValuesPadding='10' numberPrefix='' chartOrder='line,area,column' startAngX='8' startAngY='-32' endAngX='8' endAngY='-32' zdepth='50' zgapPlot='10' showPlotBorder='0' dynamicShading='1' showAlternateHGridColor='1' labelDisplay='Stagger' legendNumColumns='2' showBorder='0' exportEnabled='1'  exportAtClient='0' exportHandler='FCExporter' exportAction='save'>");
					
					chartData.append("<categories>");

					unitList = locationNode.getChildNodes();
					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						unitNode = unitList.item(nodCtr);
						//Add unit form in unitForm List
						unitFormList.add(unitNode.getAttributes().getNamedItem("unitdescr").getNodeValue());
						//geoLocList.add(locationNode.getAttributes().getNamedItem("glocdescr").getNodeValue());
						dateList = unitNode.getChildNodes();
						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{

							dateNode = dateList.item(dateCtr);
							date = dateNode.getAttributes().item(0).getNodeValue();
							chartData.append("<category label='" + date + "'/>");
						}
					}

					chartData.append("<category label='" + "fc" + "'/>");
					chartData.append("</categories>");
					//1.End of  Lable  setting 1		
					
			           
                    //2. start dataset for Day Production
			       chartData.append("<dataset seriesName='Day Production' color='FF8533'>");

					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						unitNode = unitList.item(nodCtr);
						dateList = unitNode.getChildNodes();

						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{
							dateNode   = dateList.item(dateCtr);
							int day    = Integer.parseInt(dateNode.getAttributes().item(0).getNodeValue());
							dayQtyList = dateNode.getChildNodes();
							
							//add new code for previous report as on dated 14/11/2013
							if(currmonthVal==month && curryearVal==year)
							{
								if (day <= todaysDay)
								{
									for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
									{
										dayNode = dayQtyList.item(dayCtr);
										dayQty = dayNode.getAttributes().item(0).getNodeValue();
										chartData.append("<set value='" + dayQty + "'/>");
									}
								} 
								
								
								else
								{
									for (int p = todaysDay + 1; p <= lastDayOfMonth; p++)
									{
										chartData.append("<set value='0'/>");
									}
								}
							}
							
							else
							{   if (day <= lastDayOfMonth)
								{
								for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
								{
									dayNode  = dayQtyList.item(dayCtr);
									dayQty   = dayNode.getAttributes().item(0).getNodeValue();
									chartData.append("<set value='" + dayQty + "'/>");
								}
							  }	
							}
							//end on dated 14/11/2013														
							
						}

					}
					chartData.append("</dataset>");
					//2. End dataset for Day Production
					//3. Start dataset for Cumulative Production
					chartData.append("<dataset seriesName='Cumulative Production' color='00cc00'>");
					String curCumQtyTem = "";
					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						unitNode = unitList.item(nodCtr);
						dateList = unitNode.getChildNodes();

						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{
							dateNode = dateList.item(dateCtr);
							int day = Integer.parseInt(dateNode.getAttributes().item(0).getNodeValue());
							dayQtyList = dateNode.getChildNodes();
							//add new code for previous report as on dated 14/11/2013
							if(currmonthVal==month && curryearVal==year)
							{
								if (day <= todaysDay)
								{
									for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
									{
										dayNode = dayQtyList.item(dayCtr);
										NodeList curCumQtyList = dayNode.getChildNodes();

										for (int curCumCtr = 0; curCumCtr < curCumQtyList.getLength(); curCumCtr++)
										{
											Node curCumQtyNode = curCumQtyList.item(curCumCtr);
											if (curCumQtyNode.getNodeName().equals("cur_cumqty"))
											{

												curCumQtyTem = curCumQtyNode.getTextContent();
												chartData.append("<set value='" + curCumQtyNode.getTextContent() + "'/>");
											}
										}
									}
								} else
								{
									for (int p = todaysDay + 1; p <= lastDayOfMonth; p++)
									{
										chartData.append("<set value='0'/>");
									}
								}
							}
							else
							{
								if (day <= lastDayOfMonth)
								{
								for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
								{
									dayNode = dayQtyList.item(dayCtr);
									NodeList curCumQtyList = dayNode.getChildNodes();
									for (int curCumCtr = 0; curCumCtr < curCumQtyList.getLength(); curCumCtr++)
									{
										Node curCumQtyNode = curCumQtyList.item(curCumCtr);
										if (curCumQtyNode.getNodeName().equals("cur_cumqty"))
										{
                                                                           
											curCumQtyTem = curCumQtyNode.getTextContent();
											chartData.append("<set value='" + curCumQtyNode.getTextContent() + "'/>");
										}
									}
								}
							  }
							}
						//end of previous report on dated 14/11/2013					
						}
					}
					sumDayPro.add(curCumQtyTem);					
					chartData.append("</dataset>");
					//3. End dataset for Cumulative Production						
					//4. Start dataset for Forecasting	
					chartData.append("<dataset seriesName='Forecast' color='F5F907' >");

					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						double cumulativeQty = 0.0;
						unitNode = unitList.item(nodCtr);
						dateList = unitNode.getChildNodes();
						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{
							dateNode   = dateList.item(dateCtr);
							dayQtyList = dateNode.getChildNodes();
							int day    = Integer.parseInt(dateNode.getAttributes().item(0).getNodeValue());

							for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
							{
								dayNode = dayQtyList.item(dayCtr);
								foreCastList = dayNode.getChildNodes();

								for (int prevCtr = 0; prevCtr < foreCastList.getLength(); prevCtr++)
								{
									foreCastNode = foreCastList.item(prevCtr);

									if (foreCastNode.getNodeName().equals("cur_cumqty"))
									{
										//out.println("day:"+day+"--todaysDay"+todaysDay);
										
										if(currmonthVal==month && curryearVal==year)
										{	
											if (day == todaysDay)
											{
												cumulativeQty = Double.parseDouble(foreCastNode.getTextContent());

												cumulativeQty = Math.round(cumulativeQty * lastDayOfMonth) / day;
												cumuQty.add(cumulativeQty);

												for (int dayOfMonth = 1; dayOfMonth <= lastDayOfMonth; dayOfMonth++)
												{
													chartData.append("<set value='0'/>");
												}
												chartData.append("<set value='" + cumulativeQty + "'/>");

											}
										}
										else
										{
											if(day == lastDayOfMonth)//added if condition on 16 nov2013 
											{
											  cumulativeQty = Double.parseDouble(foreCastNode.getTextContent());
											
											  cumulativeQty = Math.round(cumulativeQty * lastDayOfMonth) / day;
											  cumuQty.add(cumulativeQty);
											
											  for (int dayOfMonth = 1; dayOfMonth <= lastDayOfMonth; dayOfMonth++)
											  {
												chartData.append("<set value='0'/>");
											  }
											  chartData.append("<set value='" + cumulativeQty + "'/>");
											}
										}
										
										

									}

								}
							}
						}
					}

					chartData.append("</dataset>");
					//4. End dataset for Forecasting	
					
					//5. start dataset for Last year Quantity

					chartData.append("<dataset seriesName='Cumulative Last Year' color='1E86A8' renderAs='Line'>");
					String prevYearQtyTemp = "";
					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						unitNode = unitList.item(nodCtr);
						dateList = unitNode.getChildNodes();
						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{
							dateNode = dateList.item(dateCtr);
							dayQtyList = dateNode.getChildNodes();

							for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
							{
								//dayNode = dayQtyList.item(dateCtr);
								dayNode = dayQtyList.item(dayCtr);
								NodeList prevYearQtyList = dayNode.getChildNodes();

								for (int prevCtr = 0; prevCtr < prevYearQtyList.getLength(); prevCtr++)
								{
									Node prevYearQtyNode = prevYearQtyList.item(prevCtr);

									if (prevYearQtyNode.getNodeName().equals("pyr_cumqty"))
									{
										prevYearQtyTemp = (prevYearQtyNode.getTextContent());
                                                                     
										if(prevYearQtyTemp=="")
										prevYearQtyTemp="0.0";									     
										chartData.append("<set value='" + prevYearQtyNode.getTextContent() + "'/>");
									}
								}
							}
						}
					}
					cumLstYear.add(prevYearQtyTemp);
					chartData.append("</dataset>");
					//5. End dataset for Last year Quantity
					//6. Start dataset for Daily Budget Quantity				
					chartData.append("<dataset seriesName='Cumulative Budget' color='660426' renderAs='Line'>");
					String LBETEMP = "";
					for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
					{
						unitNode = unitList.item(nodCtr);
						dateList = unitNode.getChildNodes();
						for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
						{
							dateNode = dateList.item(dateCtr);
							dayQtyList = dateNode.getChildNodes();

							for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
							{
								dayNode = dayQtyList.item(dayCtr);
								NodeList dailyBdgtList = dayNode.getChildNodes();

								for (int dBdgtCtr = 0; dBdgtCtr < dailyBdgtList.getLength(); dBdgtCtr++)
								{
									Node dailyBdgtNode = dailyBdgtList.item(dBdgtCtr);

									if (dailyBdgtNode.getNodeName().equals("cum_budqty"))
									{
										LBETEMP = dailyBdgtNode.getTextContent();										
										chartData.append("<set value='" + LBETEMP + "'/>");
									}
								}
							}
						}
					}
					LBEList.add(LBETEMP);
					chartData.append("</dataset>");
					//6. End dataset for Daily Budget Quantity

					chartData.append("</chart>");
					chartDataList.add(chartData.toString());					
					chartData.setLength(0);

				}
			} else
			{
%>
<table cellspacing="1" cellpadding="2" align="center">
	<tr>
		<td>
		<h4>No data found !</h4>
		</td>
	</tr>
</table>
<%
	}
		}

   
	int countChart = 0;
	int tablId = 0;
	Double actLBE = 0.0;
	Double cumuQtyLBE = 0.0;
	


		
%>
<script>
 var geoLocation    ="<%=this.checkGeoLoc%>";
 var unitform       ="<%=this.checkUnitForm%>";
 var curryear       ="<%=this.year%>";
 var currmonth      ="<%=this.month%>";
//window.onload      =getData(geoLocation.trim(),unitform,curryear,currmonth);
 window.onload      = new function() { 

 
 //1   
   var element   = document.getElementById("geo_loc");
   var location  =geoLocation.split(",");     
     for(i=0;i<location.length;i++)
     {
      
      	for (var j = 0; j < element.options.length; j++) 
        	 {
            
    	        var checkLoc= "'"+element.options[j].value+"'";                           
    		   if(checkLoc== location[i])
				   {
                    element.options[j].selected = true;
				   }
		       }
      }
     //2
     var elementForm  = document.getElementById("unit_form");
     var unitForm     = unitform.split(","); 
     
       for(k=0;k <unitForm.length;k++)
       {
      	for (var l = 0; l < elementForm.options.length; l++) 
          	 {
      	     var checkUnit= "'"+elementForm.options[l].value+"'";
      		   if(checkUnit== unitForm[k])
  				  {
      			     
      			   elementForm.options[l].selected = true;
  				  }
  		       }
        }

       //3 
       var curryearList   = document.getElementById("acct_year");
      // alert("curryear==="+curryear); 
        
        for (var m = 0; m < curryearList.options.length; m++) 
            	 {
        	     var checkyear = curryearList.options[m].value;
        		   if(checkyear==curryear)
    				  {
                        
        			   curryearList.options[m].selected = true;
    				  }
    		       }
         
    //4
         var currmonthList   = document.getElementById("acct_month");
                 
         //alert("currmonth================="+currmonth);  
          	for (var n = 0; n < currmonthList.options.length; n++) 
              	 {
          	         var checkmonth = currmonthList.options[n].value;
          		   if(checkmonth==currmonth)
      				  {
          			   currmonthList.options[n].selected = true;
      				  }
      		       }


};


</script>

<table class="chartTable">
	<%  
	       
            String chartId="";           
            String chartName="";
           //Add new code on dated 06/02/2014
           grdDataMap  = new HashMap<String, List<String>>();

       		for (String chartDatFrmList : chartDataList)
			{
				chartDivId++;                
				chartId    ="myChartId"+chartDivId+userID;                                                  
				chartName  ="myChartId"+chartDivId; 	
                            gridDataList =new ArrayList<String>();				
				
	%>
	<%
		if (tablId == 0 || (tablId % deviceDisplay == 0))
				{
	%>
	<tr>
		<%
			tablId = 0;
					}
		%>



		<td class="chartCell">			
		<div id="chartContainer<%=chartDivId%>">Chart will load here !</div>		
		<script type="text/javascript"> 
		         //FusionCharts.setCurrentRenderer('javascript');
		         
		         var myChart = new FusionCharts("<%=srcImagesPath%>", "<%=chartId%>", "400", "350", "0", "0");
		         myChart.setXMLData("<%=chartDatFrmList%>");          
		         myChart.setChartAttribute( "caption" , "<%=geoLocList.get(countChart)%>: <%=unitFormList.get(countChart)%>" );     
			  myChart.render("chartContainer<%=chartDivId%>"); 
		         //Add new code on dated 07/01/2014             
                      myChart.addEventListener("Rendered", function () 
					 { 
			 	 var cObject = getChartFromId('<%=chartId%>');
			     if( cObject.hasRendered() ) cObject.exportChart({exportFormat: 'png',exportFileName:'<%=chartId%>'});
			 	 
			 	 		 
			 		} );   
                
              //end

              </script>

           
		<table class="summaryTable" >
			<tr class="summaryTr">
				<td>Month</td>
				<td>Actual</td>
				<td>LBE</td>
				<td>Actual/LBE</td>
				<td>Pace(EOM)</td>
				<td>Pace(EOM)/LBE</td>
				<td><%=preyear%>/<%=monthStr%></td>
			</tr>
			<tr class="summaryDetail">
				<td><%=year%>/<%=monthStr%></td>

				<%
					            
							cumulativePro = Double.parseDouble(sumDayPro.get(countChart));
														
							if (cumulativePro >= 1000000)
							{

								cumulativePro = Math.round(cumulativePro / 1000000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumulativeProStr = cumulativePro.toString() + "M";

							} else
							{
								cumulativePro = Math.round(cumulativePro / 1000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumulativeProStr = cumulativePro.toString() + "K";

							}

							cumuQtyInDoubl = cumuQty.get(countChart);
							if (cumuQtyInDoubl >= 1000000)
							{
								cumuQtyInDoubl = Math.round(cumuQtyInDoubl / 1000000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumuQtyStr = cumuQtyInDoubl.toString() + "M";

							} else
							{
								cumuQtyInDoubl = Math.round(cumuQtyInDoubl / 1000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumuQtyStr = cumuQtyInDoubl.toString() + "K";

							}
							
							if (Double.parseDouble(LBEList.get(countChart)) == 0.0)
							{
								actLBE = 0.0;
								cumuQtyLBE = 0.0;

							}

							else
							{
								actLBE = ((Double.parseDouble(sumDayPro.get(countChart)) / Double.parseDouble(LBEList.get(countChart)) * 100));
								cumuQtyLBE = (cumuQty.get(countChart) / Double.parseDouble(LBEList.get(countChart)) * 100);
							}

							cumLstYearInDouble = Double.parseDouble(cumLstYear.get(countChart));
							if (cumLstYearInDouble >= 1000000)
							{

								cumLstYearInDouble = Math.round(cumLstYearInDouble / 1000000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumLstYearStr = cumLstYearInDouble.toString() + "M";

							} else
							{
								cumLstYearInDouble = Math.round(cumLstYearInDouble / 1000 * Math.pow(10, 2)) / Math.pow(10, 2);
								cumLstYearStr = cumLstYearInDouble.toString() + "K";

							}

							lbeInDouble = Double.parseDouble(LBEList.get(countChart));
							if (lbeInDouble >= 1000000)
							{

								lbeInDouble = Math.round(lbeInDouble / 1000000 * Math.pow(10, 2)) / Math.pow(10, 2);
								lbeValStr = lbeInDouble.toString() + "M";

							} else
							{
								lbeInDouble = Math.round(lbeInDouble / 1000 * Math.pow(10, 2)) / Math.pow(10, 2);
								lbeValStr = lbeInDouble.toString() + "K";

							}


                        //Add new code on dated 07/01/2014							
							
							gridDataList.add(""+year+"/"+month);
							gridDataList.add(cumulativeProStr);
							gridDataList.add(lbeValStr);
							gridDataList.add(String.format("%.2f", actLBE));
							gridDataList.add(cumuQtyStr);
							gridDataList.add(String.format("%.2f",cumuQtyLBE));
							gridDataList.add(cumLstYearStr);							
							grdDataMap.put(chartName, gridDataList);									
							//End of new code

						
				%>
				<td><%=cumulativeProStr%></td>
				<td><%=lbeValStr%></td>
				<td><%=String.format("%.2f", actLBE)%> %</td>
				<td><%=cumuQtyStr%></td>
				<td><%=String.format("%.2f",cumuQtyLBE)%> %</td>
				<td><%=cumLstYearStr%></td>
			</tr>
		</table>
		</td>

		<%
			if (tablId > 0 && tablId % deviceDisplay == 0)
					{
		%>
	</tr>
	<%
		}
	%>

	<%
	tablId++;
	countChart++;
	}//end of for loop
			
	chartDataList =null;
	geoLocList    = null;
	unitFormList  = null;	
	sumDayPro      = null;
	cumLstYear     = null;
	cumuQty        = null;
	LBEList        = null; 		
	countChart     = 0;
	tablId         = 0;
	unitFrmXml     ="";
	geoLocCodeXml  ="";
       xmlDataString  ="";	
	cumulativePro  = 0.0;
	cumuQtyInDoubl = 0.0;
	cumLstYearInDouble = 0.0;
	lbeInDouble    = 0.0;	
	actLBE         = 0.0;
       cumuQtyLBE     = 0.0;	
	cumulativeProStr = "";
	cumuQtyStr     = "";
	cumLstYearStr  = "";
	lbeValStr      = "";
	dom = null;
	//add on dated 07/01/2014
	session.setAttribute("gridDataMap", grdDataMap);
			
	%>
	
		
</table>

<%
 
	} catch (Exception ex)
	{
		System.out.println("Exception : ProductionVsBudgetReport.jsp :" + ex.getMessage());
	}
%>
   
<script>

var actualChart     ="<%=chartDivId%>";
//14/01/2014
var exportPDFPath   ="<%=exportPDFPath%>";
var exportImagePath ="<%=exportImagePath%>";
var preyearMonth    ="<%=preyearMonth%>";
var rptTitle        ="<%=rptTitle%>";
var userID          ="<%=userID%>";

function getXMLHttpRequest()
{  
	  var xmlHttpReq;  
	  // to create XMLHttpRequest object in non-Microsoft browsers  
	  if (window.XMLHttpRequest) {  
	    xmlHttpReq = new XMLHttpRequest();  
	  } else if (window.ActiveXObject) {  
	    try {  
	      //to create XMLHttpRequest object in later versions of Internet Explorer  
	      xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");  
	    } catch (exp1) {  
	      try {  
	        //to create XMLHttpRequest object in later versions of Internet Explorer  
	        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");  
	      } catch (exp2) {  
	        //xmlHttpReq = false;  
	        alert("Exception in getXMLHttpRequest()!");  
	      }  
	    }  
	  }  
	  return xmlHttpReq;  
	}  
	  
	/* 
	* AJAX call starts with this function 
	*/ 
	 
	function makeRequest(userID) 
	{  
	  
	  if(userID!=""&& userID.length>0)
	  {
	  var xmlHttpRequest = getXMLHttpRequest();  
	  xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);  
	  xmlHttpRequest.open("POST","/ibase/ProductionVsBudgetReportServlet?userID="+userID+"&exportPDFPath="+exportPDFPath+"&exportImagePath="+exportImagePath+"&preyearMonth="+preyearMonth+"&rptTitle="+rptTitle, true);    
	  xmlHttpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	  xmlHttpRequest.send(null);  
   	}  
	   	
  }

	
function getReadyStateHandler(xmlHttpRequest) 
{  
	  return function() 
	  {  
	    if (xmlHttpRequest.readyState == 4) 
		    {  
			
	      if (xmlHttpRequest.status == 200) 
		    {  
	      } 
	      else 
		      {  
	           alert("Http error " + xmlHttpRequest.status + ":" + xmlHttpRequest.statusText);  
	           }  
	    }  
	  };  
	}  


var chartCnt=0;
function FC_Exported(objRtn)
{
    if (objRtn.statusCode=="1")
    {
    	chartCnt++;		
    	if(chartCnt==actualChart)
    	{
    	makeRequest(userID);		
    	//window.open('', '_parent', '');         
       window.close();
    	}
    }
    else
    {
        alert("The chart with DOM Id " + objRtn.DOMId + " could not be saved on server. There was an error. Description : " + objRtn.statusMessage);
    }
}


</script>
</form>
<%
chartDivId=0;
%>	
</body>
</html>
