<%@ include file="/includes.jsp" %>
<%@ page import="java.util.Date" %>
<%@ page import ="java.text.SimpleDateFormat" %>
<%@ page import ="java.util.Calendar" %>
<%@ page import ="java.util.GregorianCalendar" %>


<script language="javascript">


//Trimming functions
function ltrim ( s )
{
   return s.replace( /^\s*/, "" );
}

function rtrim ( s )
{
   return s.replace( /\s*$/, "" );
}

function trim ( s )
{
   return rtrim(ltrim(s));
}
//Validation Functions
function validate()
    {
        //Check Empty From Date Field
        if(trim(document.CWTReportForm.fromDate.value)=="")
        {
            alert("Please enter From Date.");
            document.CWTReportForm.fromDate.focus();
            return false;
        }
			

        //Check occurences of '/' symbol
        var checkOK = "0123456789/";
        var checkStr = document.CWTReportForm.fromDate.value;                    
        var allValid_f = true;                                                    

        for (i = 0; i < checkStr.length; i++) 
        { 
                ch = checkStr.charAt(i); 
                for (j = 0; j < checkOK.length; j++)
                 if (ch == checkOK.charAt(j))
                 break;
                 if (j == checkOK.length)
                 { 
                allValid_f = false; break; 
                } 
        }
         
        if (!allValid_f) 
        { 
                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }                                                           
        
        var k;
        var l=0;
        
        for(k = 0; k < checkStr.length; k++) { ch = checkStr.charAt(k); if(ch=='/') l++;}
            if (l!=2) 
                { 
                        alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                        document.CWTReportForm.fromDate.select();
                        document.CWTReportForm.fromDate.focus();
                        return (false); 
                 } 

        //Checks for Invalid Date formats
        a=document.CWTReportForm.fromDate.value.indexOf('/')
        b=document.CWTReportForm.fromDate.value.indexOf('/',a+1)
        fs_date=document.CWTReportForm.fromDate.value.substring(0,a)
        fs_month=document.CWTReportForm.fromDate.value.substring(a+1,b)
        fs_year=document.CWTReportForm.fromDate.value.substring(b+1,10)

        
        if(document.CWTReportForm.fromDate.value.substring(b+1,10).length !=4)
            {

                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
            }

        if((document.CWTReportForm.fromDate.value.substring(a+1,b).length < 1) || (document.CWTReportForm.fromDate.value.substring(a+1,b).length > 2))
        {
                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
        
        if((document.CWTReportForm.fromDate.value.substring(0,a).length < 1) || (document.CWTReportForm.fromDate.value.substring(0,a).length > 2))
        {
                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
        
        if(fs_month>12 || fs_month<1)
        {
                alert("Invalid From Date.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
         }
        
        if(fs_date>31 || fs_date<1)
        {
                alert("Invalid From Date.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
        
        if(fs_month==4 || fs_month==6 || fs_month==9 || fs_month==11)
        if(fs_date>30)
        {
                alert("Invalid From Date.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
        
        if(fs_month==2)
        if(fs_date>29)
        {
                alert("Invalid From Date.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
        

        if((fs_year%4)!=0)
        if(fs_month==2)
        if(fs_date>28)
        {
                alert("Invalid From Date.");
                document.CWTReportForm.fromDate.select();
                document.CWTReportForm.fromDate.focus();
                return (false); 
        }
                            
        //Check Empty To Date Field
        if(trim(document.CWTReportForm.toDate.value)=="")
        {
                alert("Please enter To Date.");
                document.CWTReportForm.toDate.focus();
                return false;
        }
	
	//Check occurences of '/' symbol	
        var checkStr1 = document.CWTReportForm.toDate.value;                    
	var allValid_r = true;                                                    
	 
	for (i = 0; i < checkStr1.length; i++) 
	{ 
		ch = checkStr1.charAt(i); 
		for (j = 0; j < checkOK.length; j++)
                if (ch == checkOK.charAt(j))
		break;
		
                if (j == checkOK.length)
                { 
                    allValid_r = false; break; 
                } 
                }
                if (!allValid_r) 
                { 
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                 }

		var l1=0;         
		for(k = 0; k < checkStr1.length; k++) { ch = checkStr1.charAt(k); if(ch=='/') l1++;}
		if (l1!=2) 
		{ 
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }                                                           

                c=document.CWTReportForm.toDate.value.indexOf('/')
                d=document.CWTReportForm.toDate.value.indexOf('/',c+1)
                r_date=document.CWTReportForm.toDate.value.substring(0,c)
                r_month=document.CWTReportForm.toDate.value.substring(c+1,d)
                r_year=document.CWTReportForm.toDate.value.substring(d+1,10)

                //Checks for Invalid Date Formats
                if(document.CWTReportForm.toDate.value.substring(d+1,10).length !=4)
                {
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }

                if((document.CWTReportForm.toDate.value.substring(c+1,d).length < 1) || (document.CWTReportForm.toDate.value.substring(c+1,d).length > 2))
                {
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                
                if((document.CWTReportForm.toDate.value.substring(0,c).length < 1) || (document.CWTReportForm.toDate.value.substring(0,c).length > 2))
                {
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                    
                if(r_month>12 || r_month<1)
                {
                    alert("Invalid To Date.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                
                if(r_date>31 || r_date<1)
                {
                    alert("Invalid To Date.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                
                if(r_month==4 || r_month==6 || r_month==9 || r_month==11)
                if(r_date>30)
                {
                    alert("Invalid To Date.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                
                if(r_month==2)
                if(r_date>29)
                {
                    alert("Invalid To Date.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                
                if((r_year%4)!=0)
                if(r_month==2)
                if(r_date>28)
                {
                    alert("Invalid To Date.");
                    document.CWTReportForm.toDate.select();
                    document.CWTReportForm.toDate.focus();
                    return (false); 
                }
                var date1,date2,dateT1,dateT2;
                var vDateSplit = document.CWTReportForm.fromDate.value.split("/");
				date1 = vDateSplit[1] + "/" + vDateSplit[0] + "/" + vDateSplit[2];
				var vDateSplit1 = document.CWTReportForm.toDate.value.split("/");
				date2 = vDateSplit1[1] + "/" + vDateSplit1[0] + "/" + vDateSplit1[2];
				
				//Check for the Order of the Dates

                dateT1=   new Date(date1).getTime();
                dateT2 =  new Date(date2).getTime();

				//alert(new Date(date1).getMonth())	;
                if(dateT1>dateT2)
                {
                        alert("From Date cannot be less than To Date.");
                        document.CWTReportForm.fromDate.select();
                        document.CWTReportForm.fromDate.focus();
                        return false;
                }
		var strCheck =  checkDupSelect();
if(strCheck==false)
{
	return false;
}
//alert( strCheck );
	
                return true;
}
//End Validation




function expandIt(whichEl, Check)
{
	
	if (Check == 'FALSE')
	{
		whichEl.style.display = "none";
	}
	else
	{
		whichEl.style.display = "";
	}
}
function summaryCheck()
{
	if(document.CWTReportForm.reportType[0].checked!=true)
	{
	//document.frmVehicle.btncollection.disabled = true;
	expandIt(ExpOne, 'FALSE');
	expandIt(ExpTwo, 'FALSE');
	}
	else
	{
	//alert("test");
	document.CWTReportForm.elements["sortingDate"].value="";
	document.CWTReportForm.elements["sortingPatient"].value="";
	document.CWTReportForm.elements["waitingTime"].value="";
	document.CWTReportForm.elements["exclude"].checked=false;	
//	alert(document.CWTReportForm.elements["sortingDate"].value);
//	alert(document.CWTReportForm.elements["sortingPatient"].value);
//	alert(document.CWTReportForm.elements["waitingTime"].value);
//	alert(document.CWTReportForm.elements["exclude"].value);
	expandIt(ExpOne, 'TRUE');
	expandIt(ExpTwo, 'TRUE');
	//document.frmVehicle.btncollection.disabled = false;
	}
if(document.CWTReportForm.reportType[1].checked==true)
	{
	//document.frmVehicle.btncollection.disabled = true;
	expandIt(ExpOne, 'TRUE');
	expandIt(ExpTwo, 'TRUE');
	}
	else
	{
	expandIt(ExpOne, 'FALSE');
	expandIt(ExpTwo, 'FALSE');
	//document.frmVehicle.btncollection.disabled = false;
	}
return;
}



//Function to check the duplicate sorting order selected 

function checkDupSelect()
{ 
var strSortingDate = document.CWTReportForm.elements["sortingDate"]; 
var strSortingPatient = document.CWTReportForm.elements["sortingPatient"];
var strwaitingTime = document.CWTReportForm.elements["waitingTime"];
var selectedPatient = getSelections(strSortingPatient);
var selectedDate = getSelections(strSortingDate);
var selectedWaitingTime = getSelections(strwaitingTime); 
for(var k=0;k<selectedPatient.length;k++) 
{
for(var m=0;m<selectedDate.length;m++)
{
for(var l=0;l<selectedWaitingTime.length;l++)
{
if (selectedDate[m].value == selectedPatient[k].value && selectedDate[m].value !="" && selectedPatient[k].value !="")
{
alert("Sorting criteria should be distinct."); 
document.CWTReportForm.sortingDate.focus();
return false; 
}
else if(selectedDate[m].value == selectedWaitingTime[l].value && selectedDate[m].value !="" && selectedWaitingTime[l].value !="") 
{
alert("Sorting criteria should be distinct.");
document.CWTReportForm.sortingDate.focus();
return false; 
}else if(selectedPatient[k].value == selectedWaitingTime[l].value && selectedPatient[m].value !="" && selectedWaitingTime[l].value !="") 
{
alert("Sorting criteria should be distinct.");
document.CWTReportForm.sortingDate.focus();
return false; 
}

}
}
}
}

function getSelections(select) 
{ 
var options = select.options; 
sOptions = []; 
var opt, k=0; 
while(opt = options[k++]) 
if(opt.selected) 
sOptions[sOptions.length] = opt;
return sOptions ;
}






var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(0, null, flatSelected);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);
  // ... we can show it here.
  cal.show();
}


</script>

<s:form action="/emdt/CWTReportAction.do" onsubmit="return validate();">
<table cellpadding=0 cellspacing=0 border=0><tr>
<td width=40></td>
<tr>

<% 
// Initialise the contents of the From and To date boxes
String strToDate= new String();
String strFromDate = new String();
java.text.SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new Date();
if (session.getAttribute("cwtReportToDate") == null)	{
	strToDate = sdf.format(date);
}
else
{
//	 ...set to last entered value
	strToDate = session.getAttribute("cwtReportToDate").toString();
}

if (session.getAttribute("cwtReportFromDate") == null)	{
	// then set the default 'from' date string to one month before today
	sdf.setCalendar(Calendar.getInstance());
	Date d = sdf.parse(strToDate);
	Calendar calendar = new GregorianCalendar();
	calendar.setTime(d);
	calendar.add(Calendar.MONTH, -1);
	int m = calendar.get(Calendar.MONTH);
	m = m + 1 ;
	int dt = calendar.get(Calendar.DATE);
	String lMon = null;
	String lDay = null;
	if ( m < 10 ) {
	    lMon = "0" + m;
	} else {
	    lMon = String.valueOf(m);
	}
	if ( dt < 10 ) {
	    lDay = "0" + dt;
	} else {
	    lDay = String.valueOf(dt);
	}
	strFromDate = lDay +"/"+ lMon +"/"+calendar.get(Calendar.YEAR);
}	
else
{
	// ...set to last entered value
	strFromDate = session.getAttribute("cwtReportFromDate").toString();
}

%>

</tr></table>

<table><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr></table>
<table width="50%" cellpadding=0 cellspacing=0 border=0>
<tr>
	<td class="input" width="60%">
		<input type="hidden" name="reportName" value="<%=request.getParameter("reportId")%>">
	</td>
</tr>
<tr><td height=4></td></tr>
</table>
<table cellpadding=0 cellspacing=0 border=0 width="56%" >

<tr>
	<td>
		<table cellpadding=0 cellspacing=0 border=0 class="dialogBox" width="100%">
<tr><td class="dialogTitle"><b>

<%if(request.getParameter("reportId") !=null && request.getParameter("reportId").equalsIgnoreCase("firstseen")){%>
	<s:text name="title.report.indexpage"/>
<%}else{%>	
	<s:text name="title.report.indexpagedefinitive"/>
<%}%>

</b>
</td></tr>
		<tr>
			<td>
			<table cellpadding=10 cellspacing=0 border=0 width="100%" >

				<tr>
					<td>
						<table cellpadding=0 cellspacing=0 border=0 width="100%">
							<tr><td class="label" width="41%">
							<%if(request.getParameter("reportId") !=null && request.getParameter("reportId").equalsIgnoreCase("firstseen")){%>
							<b><s:text name="title.report.date"/></b>
							<%}else{%>
							<b><<s:text name="title.report.dateDefinitive"/></b>
							<%}%>
							
							</td>
								<td class="input"><s:text name="title.report.date.from"/></td>
								<td class="input" width="29%">

<html:text property="fromDate" styleId="sel1" value ="<%=strFromDate%>"  size="12" maxlength="10"/><img src="tiles/skins/date.png"
onclick="return showCalendar('sel1', '%d/%m/%Y');"> 
</td>
<td  class="label" width="12" colspan="2"><s:text name="title.report.date.to"/></td>

<td class="input" align="right" width="29%">
<html:text property="toDate" value="<%=strToDate%>" styleId="sel2" size="12"  maxlength="10"/><img src="tiles/skins/date.png"
onclick="return showCalendar('sel2', '%d/%m/%Y');"></td> 
							</tr>
					</table>
						<br><br>
						<table cellpadding=0 cellspacing=0 border=0>
							<tr><td class="label"><b><s:text name="title.report.reporttype"/></b></td>
								<td width=18></td>
								<td class="input"><s:text name="title.report.reporttype.summary"/></td>
								<td width=6></td>
								<td class="input"><input type="radio" name="reportType" value="summary" onClick="summaryCheck();"></td>
								
								<td class="label" valign="bottom"><s:text name="title.report.reporttype.detail" property="selected"/></td>
								<td width=6></td>
								<td class="input"><input type="radio" checked="checked" name="reportType" value="detail" onClick="summaryCheck();"></td>
							</tr>
						</table>
						<br><br>
					<table width="50%" cellpadding=0 cellspacing=0 border=0 id="ExpOne" style="display:block;">
						<tr>
							<td width="35%" class="label"><b><s:text name="title.report.reporttype.SortOrder"/></b></td>
							<td width=8>&nbsp;</td>
							<td class="label"><s:text name="title.report.reporttype.SortOrder.date"/></td>
							
							<td class="input"><select name="sortingDate" >
							<option value=""></option>
							<option value="1">1</option>
							<option value="2">2</option>
							<option value="3">3</option>
							</select></td>
						</tr>

					<tr><td height=4></td></tr>
					<tr><td class="label"></td>
						<td width=8>&nbsp;</td>
						<td class="label"><s:text name="title.report.reporttype.SortOrder.patient"/></td>
						<td class="input"><select name="sortingPatient" >
						<option value=""></option>
						<option value="1">1</option>
						<option value="2">2</option>
						<option value="3">3</option>
						</select></td></tr>
					<tr><td height=4></td></tr>
					<tr><td class=inputLabel></td>
						<td width=8>&nbsp;</td>
						<td class="label"><s:text name="title.report.reporttype.SortOrder.waitingtime"/></td>
						<td class="input"><select name="waitingTime" >
						<option value=""></option>
						<option value="1">1</option>
						<option value="2">2</option>
						<option value="3">3</option>
						</select>
					</td>
				</tr>
		</table>
<br><br>

<table cellpadding=0 cellspacing=0 border=0 id="ExpTwo" style="display:block;"> 
<tr><td class="label">
<%if(request.getParameter("reportId") !=null && request.getParameter("reportId").equalsIgnoreCase("firstseen")){%>
<b><s:text name="title.report.reporttype.SortOrder.exclude"/></b>
<%}else{%>	
	<b><s:text name="title.report.reporttype.SortOrder.excludeDefinitive"/></b>
<%}%>

</td>
    <td width=10></td>
    <td class="input"><html:checkbox property="exclude" value="true"></html:checkbox></td><td class="label"><s:text name="title.report.exclude.yes"/>

</td></tr></table>
<table cellpadding=0 cellspacing=0 border=0>
<tr><td width=2></td>
    <td class="input">
<html:submit ></html:submit>
<td class="input">
<html:button property="" value="Cancel" onclick="cancelWindow();"></html:button>
</td></tr>
</table>
</td></tr></table>
</td></tr><tr><td colspan = '2' class="dialogSpacer"></td></tr>
<tr><td colspan = '2' class="dialogFooter"></td></tr>
</table>
</td></tr>
 </table>
<input type="hidden" name="userName" value="<c:out value="${webapp.currentUser.username}"/>" />
<input type="hidden" name="pageUrl" value="" >
</s:form>
<script language="javascript">
function onLoad()
{
	document.CWTReportForm.fromDate.focus();
	document.CWTReportForm.reportType[1].checked=true;
	document.CWTReportForm.pageUrl.value=document.location;
}

  </script><%
   String adPath = request.getHeader("Referer");
   int lastIndex = adPath.lastIndexOf("/");
   int lastIndex1 = adPath.lastIndexOf("/",lastIndex-1);
   int lastIndex2 = adPath.lastIndexOf("/",lastIndex1-1);
   String adPath2 = adPath.substring(lastIndex2,lastIndex1);
   String path = "\""+adPath2+"/emdt/CWTCancelAction.do"+"\"";
   %><script language="javascript">
 function cancelWindow(){
document.CWTReportForm.action =<%=path%>;
document.CWTReportForm.submit();
}
</script>

