/** 
 * Set to false the value of whether or not the current window contains
 * a popup calendar.
 */
window.popupCalendar = "false";

/**
 * Set the HTML control to which the value of the date selected from the 
 * calendar will be written.
 */ 
function setDestinationField(textfieldName) {
   var targetTextField = document.getElementById("datefield");
   targetTextField.value = textfieldName;
}

/**
 * Open the calendar in a popup window.
 */ 
function selectDate(destinationField) {
   setDestinationField(destinationField);
   openCalendar('../functions/calendar.htm', 620,200);
}

/**
 * Set the value of the date HTML control to that selected from the popup calendar
 * if it (the date) is selected from the calendar.
 */
function showDate(dateValue) {
	if (window.popupCalendar == "true") {
	   var fieldName = opener.document.getElementById("datefield").value;
		
	   // Set the value of the date HTMl control to the date passed to this function.	
	   opener.document.getElementById(fieldName).value = dateValue;
	   // Close the popup window containing the calendar.
	   opener.document.getElementById(fieldName).focus();
	   window.close();

	} else {
	   // Do nothing.
	}
}

/**
 * Show the dates of the month containing today's date and set the value of the
 * HTML control to today's date.
 */
function pickDate(datetoday, haslinks){
  var datearray = datetoday.split('/');
  window.selecteddate = new Date(datearray[2],(datearray[0]-1),datearray[1]);
  
  showDate(datetoday); 
  // if current view is timesheet, then maintain that view
  if (getView() == 'timesheet') {
	    SetView('timesheet', true, haslinks);
  } else {
	 SetView('day', true, haslinks);
  }

}

/**
 * Display dates for other months other than the present month.
 */
function pickDateInWeek(datetoday, haslinks){
  var datearray = datetoday.split('/');
  window.selecteddate = new Date(datearray[2],(datearray[0]-1),datearray[1]);  
  showDate(datetoday);
  SetView('week', true, haslinks);
}

/**
 * Fomart and return today's date.
 */
function getFomarttedToday(infunction){
   // Set the current date to today's date if it is not already set.
   window.currdate = (window.currdate != null ? window.currdate : new Date());
  
   // Set temporary date attributes to the current date attributes.
   var tempdate = new Date(window.currdate.getFullYear(),window.currdate.getMonth(),window.currdate.getDate());

   if (tempdate.getMonth() == 2) {
       tempdate.setDate(28);   
   } else if(tempdate.getDate() == 31){
       tempdate.setDate(30);   
   }

   // Check where this function is called and fomart accordingly.
   if (infunction == 'getpreviousmonth') {
      // Fomart today's date for use in the 'getPreviousMonth' function.
      if (tempdate.getMonth() == 0){
          tempdate.setMonth(11);
          var year = tempdate.getFullYear()-1;
          tempdate.setFullYear(year);
      } else{
          tempdate.setMonth(tempdate.getMonth()-1);
      }
	  
   } else if (infunction == 'getnextmonth'){
      // Fomart today's date for use in the 'getNextMonth' function.
      if (tempdate.getMonth() == 11){
         tempdate.setMonth(0);
         tempdate.setFullYear(tempdate.getFullYear()+1);
      } else{
         tempdate.setMonth(window.currdate.getMonth()+1);
      }
	  
   } else if (infunction == 'gettodaylongdate'){
      // Fomart today's date for use in the 'getTodayLongDate' function.
      var tempdate = new Date();
      var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
      tempdate = months[tempdate.getMonth()] + " "+tempdate.getDate() +", "+tempdate.getFullYear();
	  
   } else if (infunction == 'gettodayshortdate'){
      // Fomart today's date for use in the 'getTodayLongDate' function.
      var tempdate = new Date();	
	  tempdate = tempdate.getMonth()+1 +"/" + tempdate.getDate() + "/" + tempdate.getFullYear();
   }
   
   fomartteddate = tempdate;
   return fomartteddate;
}

/**
 * Get the previous month and write the dates in that month.
 */
function getPreviousMonth(haslinks){
   var fomartteddate = getFomarttedToday('getpreviousmonth');
   // Set the attributes of the date to be displayed to the fomartted date
   // attributes. 
   window.selecteddate = fomartteddate;

   // Write the calendar with or without links.
   if (haslinks == true){
	  writeCalendarWithLinks(fomartteddate);
   } else if(haslinks == false){
      writeCalendarWithoutLinks(fomartteddate);
   } else {
	  writeCalendarWithoutLinks(fomartteddate);
   }
}

/**
 * Get the next month and write the dates in that month.
 */
function getNextMonth(haslinks){
   var fomartteddate = getFomarttedToday('getnextmonth');
   // Set the attributes of the date to be displayed to the fomartted date
   // attributes. 
   window.selecteddate = fomartteddate;

   if (haslinks == true){
	  // Write the calendar with links.
      writeCalendarWithLinks(fomartteddate);
   } else if(haslinks == false){
	  // Write calendar without links.
      writeCalendarWithoutLinks(fomartteddate);
   } else {
      writeCalendarWithoutLinks(fomartteddate);
   }
}

/**
 * Get today's date in the formart 'month dd, yyyy'.
 */
function getTodayLongDate(){
   var fomartteddate = getFomarttedToday('gettodaylongdate');
   return fomartteddate;
}

/**
 * Get today's date in the formart 'mm/dd/yyyy'.
 */
function getTodayShortDate(){
   var fomartteddate = getFomarttedToday('gettodayshortdate');
   return fomartteddate;
}

/**
 * Get the current view of the calendar.
 */
function getView(){
    var view = window.view;
    return (view != null ? view : 'day');
}

/**
 * Set the current view of the calendar and write the appropriate calendar.
 */
function SetView(view, init, haslinks){
	// Get the temp date from the window if the calendar is in a popup
	if (view == "week") {
		var tempdate = (window.selecteddate != null ? window.selecteddate : new Date());
	// Get temp date from hidden field "selecteddate" if the calendar is in a timesheet
	} else {
		var datetoday = document.getElementById("selecteddate").value;
		var datearray = datetoday.split('/');
    	var currentdate = new Date(datearray[2],(datearray[0]-1),datearray[1]); 
		var tempdate;
		if (datetoday == "") {
			tempdate = new Date();
		} else {
			tempdate = currentdate;
		}
	}
	
    var datestring = (tempdate.getMonth()+1)+'/'+tempdate.getDate()+'/'+tempdate.getFullYear();
    window.view = view;
	
	// Write the calendar with or without links.
	if (haslinks == true){
		
	   writeCalendarWithLinks(tempdate);
	} else if(haslinks == false){
       writeCalendarWithoutLinks(tempdate);
	} else {
	   writeCalendarWithoutLinks(tempdate);
	}
}

/**
 * Change the appearance of today to make it stand out.
 */
function markToday(today,date){
   if (today == date) {
      // Return a bold date.
      return "<b><i>"+date+"</i></b>" ;
   } else {
      // Return the date in the fomart it was passed.
      return date;
   }
}

/**
 * Write the calendar HTML.
 */
function writeCalendar(currentdate, haslinks){

   // Months array.
   var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
   // Get current month and year.
   var curmonth=currentdate.getMonth()+1;
   var curyear = currentdate.getFullYear();

   // The HTML for the calendar table
   var tabletext = '';
   tabletext += "<table id='calendar' width='100%' border='0' cellspacing='0' cellpadding='0'>\n";
   tabletext += "<tr>\n";
   tabletext += "<td valign='top'>";
     
   tabletext += "<table width='100%' border='0' cellspacing='0' cellpadding='0'>";
   tabletext += "<tr class='portletlabel'>";
   tabletext += "<td nowrap class='smalltextb'  align='center' width='100%'><font color='#000000'>";

   // Table containing the month, year and navigation buttons
   tabletext += "<table width='100%' border=0 cellpadding=0 cellspacing=0 class='bgmd'><tr><td valign='top' align='left'><a href='javascript:getPreviousMonth("+haslinks+")'>";
   tabletext += "<img border='0' height='21' src='../images/portlet_endcap_l_narrow.gif' width='7'><img border='0' src='../images/leftarrow.gif'></a></td>";
   tabletext += "<td nowrap align='center' class='portletlabel'>  "+months[curmonth-1].substr(0,3)+" "+curyear+"  </td><td align='right' class='portletlabel'>";
   tabletext += "<a href='javascript:getNextMonth("+haslinks+")'><img border='0' src='../images/rightarrow.gif'><img border='0' height='21' src='../images/portlet_endcap_r_narrow.gif' width='7'></a></td></tr></table></font></td>";
   tabletext += "</tr><tr><td><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td align='center'>";

   // Table containing the border and the days-of-the-month table.
   tabletext += "<table width='100%' border='0' cellspacing='0' class='bgmd'><tr><td align='center'><table bgcolor='#FFFFFF' width='100%'><tr>";
   tabletext += "<td class='smalltext' align='center' nowrap>Today \n";
   tabletext += "is "+getTodayLongDate()+"</td>\n";
   tabletext += "</tr>\n";

   tabletext += "<tr> \n";
   tabletext += "<td> \n";   

   // Write HTML for the table containing the days of the month.
   tabletext += writeCalendarDays(currentdate,haslinks);
   
   tabletext += "</td></tr></table>";
   tabletext += "</td></tr></table>\n"; // End of border table

   tabletext += "</td></tr></table>";
   tabletext += "      </td>\n";
   tabletext += "    </tr>\n";
   tabletext += "</table>"
   <!-- end of wrapper for calendar table -->
	
   // Get the calendar table where the HTML will be written
   var tableobj =  (document.all ? document.all['calendar'] : document.getElementById('calendar'));
   // Specify the HTML for the calendar table
   tableobj.outerHTML = tabletext;
}

/**
 * Write HTML for the table containing the days of the month.
 */
function writeCalendarDays(currentdate,haslinks){
   
   window.currdate = currentdate;
   window.currdate.getDate();
   
   // Months array.
   var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
   // Get current month and year.
   var curmonth=currentdate.getMonth()+1;
   var curyear = currentdate.getFullYear();
   // Create new date given the current year and month.
   var recreateddate = new Date(curyear,curmonth-1,1);
   // The first day of the week.
   var firstdofw = recreateddate.getDay();
   recreateddate.setDate(0);
   // The last day of the month.
   var lastmonthday = recreateddate.getDate() - firstdofw+1;
   recreateddate = new Date(curyear,curmonth-1,1);
	
   // Reset the value of the month for the recreated date if it is the 12th month (i.e., date.getMonth == 11).
   if (recreateddate.getMonth() == 11){
       recreateddate.setMonth(0);
       recreateddate.setFullYear(recreateddate.getFullYear()+1);
   } else{
       recreateddate.setMonth(recreateddate.getMonth()+1);
   }
   // Reset the value of the day in the month for the selected date.
   recreateddate.setDate(0);

   var lastday = recreateddate.getDate();
   var week;
   var dofw;
   var day;
   var nextmonthday = 1;
   var now = currentdate;//new Date();
   var today;
   
   // Check whether the current date is today's date. If so, then today is assigned the value of
   // the day today (dd).	
   if (now.getFullYear() == currentdate.getFullYear() && now.getMonth() == currentdate.getMonth()){
      today = now.getDate();
   } else {
      today = 0;
   }
   
   // Check whether the selected date in the window is null. If so, assign it a new date. 	
   if (window.selecteddate == null) {
      window.selecteddate = new Date();
   }  
   
   // The HTML for the calendar table
   var tabletext = '';	
   // The the days-of-the-month table.
   tabletext += "<!--this is the 100% days table -->\n";
   tabletext += "<table border='0' cellspacing='0' cellpadding='2' width='100%'>\n";
   
   // The row containing the week days headers.
   tabletext += "<tr> \n";
   tabletext += "\n<td class='smalltext' nowrap align='center'>Su</td>\n<td class='smalltext' nowrap align='center'>Mo</td>\n<td class='smalltext' nowrap align='center'>Tu</td>\n<td class='smalltext' nowrap align='center'>We</td>\n<td class='smalltext' nowrap align='center'>Th</td>\n<td class='smalltext' nowrap align='center'>Fr</td>\n<td class='smalltext' nowrap align='center'>Sa</td>\n</tr>";
   tabletext += "\n<!-- start calendar-->\n";
   // The selected day of the month.
   var dayofthemonth = selecteddate.getDate();
   // The sunday before the selected day.
   var sundaybeforeselectedday = 1;
   
   if ((dayofthemonth - selecteddate.getDay()) > 0 ) {
      sundaybeforeselectedday = dayofthemonth - selecteddate.getDay();
   }
   // The Saturday after the selected day.
   var satafterselectedday = dayofthemonth+6-selecteddate.getDay();

   for (week=1,dofw=1,day=1;day<=lastday || dofw <= 7;){
      if (dofw == 1) {
	     // Start a row.
         tabletext += "<tr>\n";
      }
	  
      if (week==1 && dofw<firstdofw+1){
	     // Write the days for the previous month.
         tabletext += "<td class='previousandnextmonthdays' align='center' >"+lastmonthday+"</td>";
         lastmonthday++;
         dofw++;
		 
      }else if (day > lastday){
	     // Write the days for the next month.
         tabletext += "<td class='previousandnextmonthdays' align='center'>"+nextmonthday+"</td>";
         nextmonthday++;
         dofw++;
		 
      }else{
         var classname, style;

         if ((getView()=='week' && sundaybeforeselectedday <= day && day <= satafterselectedday) || (getView()=='day' && day == dayofthemonth) ) {
            style = 'smalltextlt nowrap';
         } else {
            style = 'smalltext';
		 }

         // Check whether the date should have links.
         if (haslinks){
		    // Write calendar with links.
            if ( getView()=='week' ) {
               tabletext += "<td class='"+style+"' align=center><a href='javascript:pickDateInWeek(\""+curmonth+"/"+day+"/"+curyear+"\", "+haslinks+");'>"+markToday(today,day)+"</a></td>\n";
            } else if (getView()=='timesheet') {
				tabletext += "<td class='"+style+"' align=center><a href='javascript:processTimesheetDate(\""+curmonth+"*"+day+"*"+curyear+"\", "+haslinks+");'>"+markToday(today,day)+"</a></td>\n";
			} else {
               tabletext += "<td class='"+style+"' align=center><a href='javascript:pickDateInWeek(\""+curmonth+"/"+day+"/"+curyear+"\", "+haslinks+");'>"+markToday(today,day)+"</a></td>\n";
            }
         } else {
		    // Write calendar without links.
            if ( getView()=='week' ) {
               tabletext += "<td class='"+style+"' align=center>"+markToday(today,day)+"</td>\n";
            } else {
               tabletext += "<td class='"+style+"' align=center>"+markToday(today,day)+"</td>\n";
            }
         }
		 
         day++;
		 
         if (dofw == 7){
		    // End the row.
            tabletext += "\n</tr>\n";
            week++;
			// Reset the day of the week.
            dofw = 1;
         } else {
            dofw++;
		 }
      }// End 'else'
   }// End 'for' loop
   
   // End calendar table if the day of the week is not zero.
   if ( dofw != 0 ) {
      tabletext += "</tr>";
      tabletext += "\n<!-- end calendar-->\n";
   }
   tabletext += "</table>\n";
   <!--  end of calendar core (dates)-->
			
   return tabletext;
}

/**
 * Open the calendar in a popup.
 */
function openCalendar(fileName, left, top) {  
   // The window features:
   // width - width of the window
   // height - height of the window
   // scrollbar - "yes" for scrollbars, "no" for no scrollbars
   // left - number of pixels from left of screen
   // top - number of pixels from top of screen
  
   features = "width=190,height=190" + "," + "left=" + left +"," + "top=" + top + "";
   childWindow = window.open(fileName,"calendarWindow", features);   
}

/**
 * Write the calendar without links. 
 */
function writeCalendarWithoutLinks(currentdate) {
   writeCalendar(currentdate, false);
}

/**
 * Write the calendar with links.
 */
function writeCalendarWithLinks(currentdate) {
   writeCalendar(currentdate, true);
}

