<%@ 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">


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

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

function trim ( s )
{
   return rtrim(ltrim(s));
}

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

        //Check occurences of '/' symbol
        var checkOK = "0123456789/";
        var checkStr = document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.fromDate.select();
                        document.CWTCSVGeneratorForm.fromDate.focus();
                        return (false); 
                 } 

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

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

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

        if((document.CWTCSVGeneratorForm.fromDate.value.substring(a+1,b).length < 1) || (document.CWTCSVGeneratorForm.fromDate.value.substring(a+1,b).length > 2))
        {
                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
        }
        
        if((document.CWTCSVGeneratorForm.fromDate.value.substring(0,a).length < 1) || (document.CWTCSVGeneratorForm.fromDate.value.substring(0,a).length > 2))
        {
                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
        }
        
        if(fs_month>12 || fs_month<1)
        {
                alert("Invalid From Date.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
         }
        
        if(fs_date>31 || fs_date<1)
        {
                alert("Invalid From Date.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
        }
        
        if(fs_month==2)
        if(fs_date>29)
        {
                alert("Invalid From Date.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
        }
        

        if((fs_year%4)!=0)
        if(fs_month==2)
        if(fs_date>28)
        {
                alert("Invalid From Date.");
                document.CWTCSVGeneratorForm.fromDate.select();
                document.CWTCSVGeneratorForm.fromDate.focus();
                return (false); 
        }
                            
        //Check Empty To Date Field
        if(trim(document.CWTCSVGeneratorForm.toDate.value)=="")
        {
                alert("Please enter To Date.");
                document.CWTCSVGeneratorForm.toDate.focus();
                return false;
        }
	
	//Check occurences of '/' symbol	
        var checkStr1 = document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }                                                           

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

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

                if((document.CWTCSVGeneratorForm.toDate.value.substring(c+1,d).length < 1) || (document.CWTCSVGeneratorForm.toDate.value.substring(c+1,d).length > 2))
                {
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                
                if((document.CWTCSVGeneratorForm.toDate.value.substring(0,c).length < 1) || (document.CWTCSVGeneratorForm.toDate.value.substring(0,c).length > 2))
                {
                    alert("Invalid To Date.\nFormat accepted is dd/mm/yyyy.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                    
                if(r_month>12 || r_month<1)
                {
                    alert("Invalid To Date.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                
                if(r_date>31 || r_date<1)
                {
                    alert("Invalid To Date.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                
                if(r_month==2)
                if(r_date>29)
                {
                    alert("Invalid To Date.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                
                if((r_year%4)!=0)
                if(r_month==2)
                if(r_date>28)
                {
                    alert("Invalid To Date.");
                    document.CWTCSVGeneratorForm.toDate.select();
                    document.CWTCSVGeneratorForm.toDate.focus();
                    return (false); 
                }
                var date1,date2,dateT1,dateT2;
                var vDateSplit = document.CWTCSVGeneratorForm.fromDate.value.split("/");
				date1 = vDateSplit[1] + "/" + vDateSplit[0] + "/" + vDateSplit[2];
				var vDateSplit1 = document.CWTCSVGeneratorForm.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.CWTCSVGeneratorForm.fromDate.select();
                        document.CWTCSVGeneratorForm.fromDate.focus();
                        return false;
                }
				
	    return true;
}
//End Validation


/*function submitPage()
{
    var boolValidate;
   boolValidate=validate();
    alert(boolValidate);
	if(boolValidate)
	{
	}
} */


//Functions for the calendar..
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.
    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.  This we align the calendar bottom
  // of the text-box.
  _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");

  cal.create(parent);
  // ... we can show it here.
  cal.show();
}


function addDiv(fileName)
{
	var windowname;
	var strlink;
	strlink="DownloadCSV.jsp?name="+fileName;
	windowname="DownloadCSV"+fileName;
	topPos=(window.screen.availHeight-300)/2;
	leftPos=(window.screen.availWidth-330)/2;
	WindowProp="height=300,width=370,left=" + leftPos + ",top=" + topPos;
	window.open(strlink,windowname,WindowProp);
}


function openWindow()
{
	var fileName;
	document.CWTCSVGeneratorForm.submit();
	fileName = document.CWTCSVGeneratorForm.filePath.value;
	addDiv(fileName);
}


</script>
<s:form action="/emdt/CWTCSVGeneratorAction.do" onsubmit="return validate();">
<table cellpadding=0 cellspacing=0 border=0>
	<tr><td width=40>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
</table>
<% 
// 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();
}
%>

<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>

<tr>
	<td>
		<table cellpadding=0 width="400" cellspacing=0 border=0 class="dialogBox">
<tr><td class="dialogTitle"><b>
CSV Creation For NCWT Upload

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

				<tr>
					<td width="100%">
						<table cellpadding=0 cellspacing=0 border=0 width="100%">
							<tr><td class="label" colspan="4"></td></tr>
							<tr><td colspan="4"><b>Please select the dates :</b></td></tr>
							<tr><td class="label"  colspan="4">&nbsp;</td></tr>

							<tr>
								<td class="input" width="22%">Date From</td>
								<td class="input" width="19%">
								<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="19%">Date To</td>
								<td class="input" align="right" width="18%">
								<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 width=2></td>
								<td class="input">
									<html:submit value="Create CSV" ></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="filePath" value="" >
</s:form><%
   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.CWTCSVGeneratorForm.action =<%=path%>;
document.CWTCSVGeneratorForm.submit();
}
</script>
