<%@ page contentType="text/html"%>
<%@ page
	import="javax.xml.parsers.DocumentBuilderFactory,javax.xml.parsers.DocumentBuilder,org.w3c.dom.*"%>
<%@page import="ibase.dashboard.umpl.bean.MSRTerritoryWiseCallAvgBean"%>
<%@page import="ibase.utility.CommonConstants"%>
<%@ page import="javax.naming.InitialContext"%>
<%@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.text.SimpleDateFormat"%>
<jsp:useBean id="msrTerritoryWiseCallAvgBean" scope="request" class="ibase.dashboard.umpl.bean.MSRTerritoryWiseCallAvgBean" />
<%!GenericUtility genericUtility = GenericUtility.getInstance();

	SimpleDateFormat simpleDateFormat=null;
	Calendar calendar = null;
	int month = 0;
	int preyear = 0;
	int  preyearVal = 0;
	int year = 0;
	int  curryearVal =0;
	String[] seclectYear = null;
	String[] seclectMonth = null;
	int lastDayOfMonth = 0;
	int todaysDay = 0;
	int day=1;
	Document dom = null;
	NodeList dtlList = null;
	Node parentNode = null;
	NodeList childNodeList = null;
	String fldValue = "";
    String descr="";
   
	String xmlString = "";
	String objName = "";	
	StringBuffer xmlData = null;	
	NodeList detailList = null;
	
	NodeList territoryList = null;
	Node territoryNode = null;
	String territoryNodeName="";
	
	NodeList spCodeList = null;
	Node spCodeNode = null;
	String spCodeNodeName = "";
	
	NodeList spCodeChildList= null;
	Node spCodeChildNode = null;
	String spCodeChildNodeName = "";
	
	double TerrFldWrkngDays=0.0;
	double TerrDoctorCall=0.0;
	double territoryCallAvg=0.0;
	String msrName="";
	double MSRFldWrkngDays=0.0;
	double MSRDoctorCall=0.0;
	double MSRCallAvg=0.0;
	String[] territory_loc = null;
	String checkTerrLoc = "";
	
	String rptTitle = "";
	String srcJSPath = "";
	String srcImagesPath = "";	
	String frmDate = "";
	String toDate = "";
	String terrLocCodeXml = "";
	
	List<String> terrLocList = new ArrayList<String>();
	List<Double> callAvgList = new ArrayList<Double>();
	List<Double> doctCallList = new ArrayList<Double>();
	
%>
<%
	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");
	
%>
<%
	String userAgent = request.getHeader("user-agent");
	System.out.println("userAgent ==" + userAgent);
	if (userAgent.indexOf("Android") > 0 || userAgent.indexOf("iPhone") > 0 || userAgent.indexOf("iPad") > 0)
	{
		srcJSPath     = "/ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "/ibase/FusionChart/images/Column3D.swf";
             System.out.println("call when,calling like ipad,iPhone and Tab");
  
	} else
	{
		srcJSPath = "/ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "/ibase/FusionChart/images/Column3D.swf";
		System.out.println("srcJSPath =="+srcJSPath);
		System.out.println("srcImagesPath ==" +srcImagesPath);

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

<style type="text/css">
.dropdown {
	border-radius: 5px;
	width: 1000px;
	align: center;
	background-color: #CEECF5;
}
.headerTable {
	height: 50px;
	width: 825px;
	border: 1;
	align: center;
}
.headerTr {
	background-color:2471C4;
	height: 30px;
	font-size: 10pt;
}
.detailTr {
	background-color: E0E9EB;
	height: 20px;
	font-size: 10pt;
}

</style>

<script type="text/javascript">

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

function getData(territoryLoc)
{
	
	var elementForm  = document.getElementById("territory_loc");
	
     var unitForm     =territoryLoc.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;
  				  }
  		       }
        }
       
     
       var curryearList   = document.getElementById("acct_year");
        
        for (var m = 0; m < curryearList.options.length; m++) 
            	 {
        	     var checkyear = curryearList.options[m].value;
        		   if(checkyear==curryear)
    				  {
        			   curryearList.options[m].selected = true;
    				  }
    		       }
         
         var currmonthList   = document.getElementById("acct_month");
                 
          	for (var n = 0; n < currmonthList.options.length; n++) 
              	 {
          	      var checkmonth = currmonthList.options[n].value;
          		   if(checkmonth==currmonth)
      				  {
          			   currmonthList.options[n].selected = true;
      				  }
      		       }
}

function isTerritorySelected()
 {
	 if(document.getElementById("territory_loc").selectedIndex==-1)
     {
	        alert("Please select at least one Territory Location");
	        return false;
	 }
	 return true;
  }
</script>
</head>
<body>

	<%
		
	try
	{
		simpleDateFormat = new SimpleDateFormat("dd-MMM-yy");
		calendar         = Calendar.getInstance();
		preyear          = calendar.get(Calendar.YEAR) - 1;
		preyearVal       = preyear;
		year             = calendar.get(Calendar.YEAR);	
		curryearVal      = year;
		month            = calendar.get(Calendar.MONTH)+1 ;
		
		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);
		
		//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]);	
			 
			//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());
		     
		   //End of -------1St of month and last of month
		     			
			currDate =seclectMonth[0]+"-"+seclectYear[0];
		  // out.println("frmDate:"+frmDate+" toDate:"+toDate);
		}
		
		rptTitle      = "MSR Territory Wise Call Average Report For " + currDate;
		terrLocCodeXml = msrTerritoryWiseCallAvgBean.getTerritoryLocXmlData();
		
  %>
 <form method="post" action="MSRTWiseCallAverageReport.jsp"	name="MSRTWiseCallAverageReport">
 <table align="center">
	<tr>
		<td class="title"><%=rptTitle%></td>
	</tr>
</table>
<table class="dropdown">
	<tr>
		<td>Territory: 
		<select id="territory_loc" name="territory_loc" multiple="multiple" size="15">
			<%
			dom = genericUtility.parseString(terrLocCodeXml);

			 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>	
		Year: <select id="acct_year" name="acct_year" size="5">
            <option value="<%=curryearVal%>"><%=curryearVal%></option>
            <option value="<%=preyearVal%>"><%=preyearVal%></option>
           
            </select>
		Month: <select id="acct_month" name="acct_month" size="5">
            <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 Report" onclick="return isTerritorySelected();"/>
		</td>
	</tr>
</table>  
  
  <%		
  		territory_loc = request.getParameterValues("territory_loc");
		String terryLoc = "";
		checkTerrLoc="";
		if (territory_loc != null && territory_loc.length != 0)
			{
				for (int i = 0; i < territory_loc.length; i++)
					{
						if (!territory_loc[i].equals("0"))
							{
								if (i == territory_loc.length - 1)
								checkTerrLoc += "'" +territory_loc[i].trim()+ "'";
								else
								checkTerrLoc += "'" +territory_loc[i].trim()+ "',";
							}
					}
			}
		
		if(checkTerrLoc!=null && checkTerrLoc.trim().length()>0)
		{
			xmlString = msrTerritoryWiseCallAvgBean.getMSRWiseCallAvgDetail(frmDate,toDate,this.checkTerrLoc);
		}
		System.out.println("xmlString  in jsp ==>" + xmlString);
		
		xmlData = new StringBuffer("<chart caption='");	
		xmlData.append(rptTitle);
		xmlData.append("'  rotateValues='1' xaxisname='Territories' yaxisname='Call Average' numdivlines='9' showSum='1'  useRoundEdges='1' showLabels='1'>" );
		if (xmlString != null && xmlString.trim().length() > 0)
		{
		
			dom = genericUtility.parseString(xmlString);
			if(dom !=null )
			{	
				//territoryList     =new ArrayList<String>();				
				detailList = dom.getElementsByTagName("Detail");
				if(detailList.item(0).getFirstChild() != null)
				{
					
					territoryList = dom.getElementsByTagName("territory");
					 // start of to set set tag for Territory wise call average report
					for (int cntr = 0; cntr < territoryList.getLength(); cntr++)
					{
						territoryNode = territoryList.item(cntr);
						territoryNodeName=territoryNode.getAttributes().item(0).getNodeValue();
						
						terrLocList.add(territoryNodeName);
						
						spCodeList = territoryNode.getChildNodes();
						TerrFldWrkngDays=0.0;
						TerrDoctorCall=0.0;
						for (int nodCtr = 0; nodCtr < spCodeList.getLength(); nodCtr++)
						{
							spCodeNode = spCodeList.item(nodCtr);
							spCodeNodeName = spCodeNode.getNodeName();
							spCodeChildList = spCodeNode.getChildNodes();
						    for(int chldNodCtr = 0; chldNodCtr < spCodeChildList.getLength(); chldNodCtr++)
						    {
								spCodeChildNode = spCodeChildList.item(chldNodCtr);
								spCodeChildNodeName=spCodeChildNode.getNodeName();
								if(spCodeChildNodeName.equals("fld_working_days"))
								{
									TerrFldWrkngDays=TerrFldWrkngDays+Double.parseDouble(spCodeChildNode.getTextContent());
								}
								if(spCodeChildNodeName.equals("doctor_call"))
								{
									TerrDoctorCall=TerrDoctorCall+Double.parseDouble(spCodeChildNode.getTextContent());
								}																
							}																					
						}
						territoryCallAvg=(TerrDoctorCall/TerrFldWrkngDays);
						callAvgList.add(territoryCallAvg);
						doctCallList.add(TerrDoctorCall);
					    xmlData.append("<set font='Arial' label='"+territoryNodeName.trim()+"' color='2590E1' value='"+String.format("%.2f", territoryCallAvg)+"' link='newchart-xml-"+territoryNodeName.trim()+"' />");
			            // start of to set linkeddata tag for MSR wise call average report
			            
							xmlData.append("<linkeddata id='"+territoryNodeName.trim()+"'>");
							xmlData.append("<chart caption='MSR wise Call Average' subcaption='Territory:"+territoryNodeName.trim()+"' rotateValues='1' placeValuesInside='1' xAxisName='MSR' yAxisName='Call Average' >");
							xmlData.append("<categories>");
				            for (int nodCtr = 0; nodCtr < spCodeList.getLength(); nodCtr++)
							{
								spCodeNode = spCodeList.item(nodCtr);
								spCodeNodeName = spCodeNode.getNodeName();
								spCodeChildList = spCodeNode.getChildNodes();
								
								for(int chldNodCtr = 0; chldNodCtr < spCodeChildList.getLength(); chldNodCtr++)
								{
									spCodeChildNode = spCodeChildList.item(chldNodCtr);
									spCodeChildNodeName=spCodeChildNode.getNodeName();
									if(spCodeChildNodeName.equals("msr_name"))
									{
										msrName=(spCodeChildNode.getTextContent());
									}
									if(spCodeChildNodeName.equals("fld_working_days"))
									{
										MSRFldWrkngDays=Double.parseDouble(spCodeChildNode.getTextContent());
									}
									if(spCodeChildNodeName.equals("doctor_call"))
									{
										MSRDoctorCall=Double.parseDouble(spCodeChildNode.getTextContent());
									}	
									
								}
								xmlData.append(" <category label='"+msrName+"'/>");																			
							}
				            xmlData.append("</categories>");
				            
				            xmlData.append("<dataset seriesName='MSR' color='2590E1'>");
				            for (int nodCtr = 0; nodCtr < spCodeList.getLength(); nodCtr++)
							{
								spCodeNode = spCodeList.item(nodCtr);
								spCodeNodeName = spCodeNode.getNodeName();
								spCodeChildList = spCodeNode.getChildNodes();
								
								for(int chldNodCtr = 0; chldNodCtr < spCodeChildList.getLength(); chldNodCtr++)
								{
									spCodeChildNode = spCodeChildList.item(chldNodCtr);
									spCodeChildNodeName=spCodeChildNode.getNodeName();
									if(spCodeChildNodeName.equals("msr_name"))
									{
										msrName=(spCodeChildNode.getTextContent());
									}
									if(spCodeChildNodeName.equals("fld_working_days"))
									{
										MSRFldWrkngDays=Double.parseDouble(spCodeChildNode.getTextContent());
									}
									if(spCodeChildNodeName.equals("doctor_call"))
									{
										MSRDoctorCall=Double.parseDouble(spCodeChildNode.getTextContent());
									}	
									if(spCodeChildNodeName.equals("call_avg"))
									{
										MSRCallAvg=Double.parseDouble(spCodeChildNode.getTextContent());
									}	
										
								}
								xmlData.append("<set value='"+String.format("%.2f", MSRCallAvg)+"'/> ");
								
							}
				            xmlData.append("</dataset>");
				            xmlData.append("<dataset seriesName='Target' renderAs='Line' color='00cc00'>");
				            for (int nodCtr = 0; nodCtr < spCodeList.getLength(); nodCtr++)
							{
				            	xmlData.append("<set value='12' /> ");
							}
				            xmlData.append("</dataset>");
				            xmlData.append("</chart></linkeddata>");
				       // end of to set linkeddata tag 
					}
				   // end of to set set tag 				   				   
				} 
				else
				{
%>
					<table cellspacing="1" cellpadding="2" align="center">
						<tr>
							<td><h4>No data found !</h4></td>
						</tr>
					</table>
					
<%
			    }				
			}			
		}
		xmlData.append("</chart>");
		System.out.println("xmlDataString----->"+xmlData.toString());
		xmlString=xmlData.toString();
%>
	<div id="chartContainer">Chart will load here !</div>		
		
		<script type="text/javascript"> 
		         FusionCharts.setCurrentRenderer('javascript');
		         var myChart = new FusionCharts("<%=srcImagesPath%>", "myChartId", "850", "850", "0", "1");
		         myChart.setXMLData("<%=xmlString%>");    
		         myChart.render("chartContainer");  
		         FusionCharts("myChartId").configureLink (
		        		  {
		        		    swfUrl : "/ibase/FusionChart/images/MSCombi3D.swf",
		        		    overlayButton:
		        		    {    
		        		      message: 'close',
		        		      fontColor : '880000',
		        		      bgColor:'FFEEEE',
		        		      borderColor: '660000'
		        		    }
		        		  }, 0);
        </script>
        <table class="headerTable" border="1">
        <tr class="headerTr">
           <td >Territory</td>
           <td>Call Average</td> 
           <td>Doctor Call</td>
                              
        </tr>
       
        <%
           double totAverage=0.0;
           double totAvg=0.0;
          for(int i=0;i<terrLocList.size();i++)
          {
			  totAverage=totAverage+callAvgList.get(i);
			  
        %>
        <tr class="detailTr">
			<td><%=terrLocList.get(i)%></td>
			<td><%=String.format("%.2f",callAvgList.get(i))%></td>
			<td><%=doctCallList.get(i)%></td>				
        </tr>
        <%
		  }
		  totAvg=(totAverage/terrLocList.size());
		  if(totAverage==0.0)
		   totAvg=0.0;
        %>
        <tr class="headerTr"> <td >Total Average</td> <td class="detailTr" colspan="2"><%=String.format("%.2f",totAvg)%></td></tr>
       
        </table>
<%
	} catch (Exception ex)
	{
		System.out.println("Exception : ITMWizardHandlerServlet sMessageArguments(String,wizardBean) :" + ex); //$NON-NLS-1$
	}
%>
</form>
<script>
var curryear  ="<%=this.year%>";
var currmonth ="<%=this.month%>";
var territoryLoc  ="<%=this.checkTerrLoc%>";
window.onload =getData(territoryLoc);

</script>
</body>
</html>
