/***********************************************************************
 *
 Copyright © 1995 - 1998, 3Com Corporation or its subsidiaries ("3Com").  
 All rights reserved.
   
 This software may be copied and used solely for developing products for 
 the Palm Computing platform and for archival and backup purposes.  Except 
 for the foregoing, no part of this software may be reproduced or transmitted 
 in any form or by any means or used to make any derivative work (such as 
 translation, transformation or adaptation) without express written consent 
 from 3Com.

 3Com reserves the right to revise this software and to make changes in content 
 from time to time without obligation on the part of 3Com to provide notification 
 of such revision or changes.  
 3COM MAKES NO REPRESENTATIONS OR WARRANTIES THAT THE SOFTWARE IS FREE OF ERRORS 
 OR THAT THE SOFTWARE IS SUITABLE FOR YOUR USE.  THE SOFTWARE IS PROVIDED ON AN 
 "AS IS" BASIS.  3COM MAKES NO WARRANTIES, TERMS OR CONDITIONS, EXPRESS OR IMPLIED, 
 EITHER IN FACT OR BY OPERATION OF LAW, STATUTORY OR OTHERWISE, INCLUDING WARRANTIES, 
 TERMS, OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND 
 SATISFACTORY QUALITY.

 TO THE FULL EXTENT ALLOWED BY LAW, 3COM ALSO EXCLUDES FOR ITSELF AND ITS SUPPLIERS 
 ANY LIABILITY, WHETHER BASED IN CONTRACT OR TORT (INCLUDING NEGLIGENCE), FOR 
 DIRECT, INCIDENTAL, CONSEQUENTIAL, INDIRECT, SPECIAL, OR PUNITIVE DAMAGES OF 
 ANY KIND, OR FOR LOSS OF REVENUE OR PROFITS, LOSS OF BUSINESS, LOSS OF INFORMATION 
 OR DATA, OR OTHER FINANCIAL LOSS ARISING OUT OF OR IN CONNECTION WITH THIS SOFTWARE, 
 EVEN IF 3COM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

 3Com, HotSync, Palm Computing, and Graffiti are registered trademarks, and 
 Palm III and Palm OS are trademarks of 3Com Corporation or its subsidiaries.

 IF THIS SOFTWARE IS PROVIDED ON A COMPACT DISK, THE OTHER SOFTWARE AND 
 DOCUMENTATION ON THE COMPACT DISK ARE SUBJECT TO THE LICENSE AGREEMENT 
 ACCOMPANYING THE COMPACT DISK.
 
 *****************************************************************************
 *
 * PROJECT:  Pilot
 * FILE:     DateMonth.c
 * AUTHOR:	 Art Lamb: April 8, 1996
 *
 * DECLARER: Datebook
 *
 * DESCRIPTION:
 *	  This is the Datebook application's month view module.
 *
 **********************************************************************/

#include <Pilot.h>
#include "Datebook.h"

// zzz Testing
extern void PrintApptRecord (DmOpenRef dbP, UInt index);



/***********************************************************************
 *
 *	Internal Constants
 *
 ***********************************************************************/
#define linesInMonthPlusTitle			7
#define maxWeeksInMonth					6

// Day number's margins
#define textLeftMargin					3
#define textTopMargin					1


// Event indicators
#define lunchStartTime					0x0b1e		// 11:30 am
#define lunchMidTime						0x0c0f		// 12:15 pm
#define lunchEndTime						0xd00			//  1:00 pm

#define timeIndicatorWidth				2
#define timeIndicatorTopMargin		3
#define timeIndicatorRightMargin		2

#define untimeIndicatorTopMargin		13
#define untimeIndicatorRightMargin	5

#define repeatIndicatorBottomMargin	2


#define morningHeight					4
#define lunchHeight						3
#define afternoonHeight					4


/***********************************************************************
 *
 *	Internal Structutes
 *
 ***********************************************************************/
typedef struct {
	RectangleType			bounds;
	SWord						month;			// month displayed
	SWord						year;				// year displayed
	DateTimeType			selected;
} MonthType;

typedef MonthType * MonthPtr;



/***********************************************************************
 *
 * FUNCTION:    FirstDayOfMonth
 *
 * DESCRIPTION: This routine returns the day-of-the-week, adjusted by the 
 *              preference setting that specifies the first day-of-
 *              the-week.  If the date passed is a Tuesday and the 
 *              start day of week is Monday, this routine will return
 *              a value of one.
 *
 * PARAMETERS:  monthP     - pointer to MontnType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/8/96	Initial Revision
 *
 ***********************************************************************/
static Word FirstDayOfMonth (MonthPtr monthP)
	{
	return (DayOfWeek (monthP->month, 1, monthP->year) - 
			StartDayOfWeek + daysInWeek) % daysInWeek;
	}


/***********************************************************************
 *
 * FUNCTION: 	 DrawMonth
 *
 * DESCRIPTION: Draw the month object.
 *
 * PARAMETERS:  monthP  - pointer to month object to draw
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			roger	4/8/96	Initial Revision
 *
 ***********************************************************************/
static void DrawMonth (MonthPtr monthP)
	{
	Short				drawX, drawY;
	Short				cellWidth, cellHeight;
	Short				charWidth;
	Short				lastDay;
	Short				day;
	FontID			currFont;
	Handle			dayOfWeekStringsH;
	CharPtr			dayOfWeekText;	// array of day of week letters
	Char				dayOfWeekLetter;
	Char				dayInAscii[3];
	Word				dow;
	Word				i;
	Short				x, y;
	DateTimeType	today;
	RectangleType	r;
	

	cellWidth = monthP->bounds.extent.x / daysInWeek;
	cellHeight = monthP->bounds.extent.y / linesInMonthPlusTitle;

	currFont = FntSetFont (boldFont);

	// Draw the days of the week labels right justified to the number columns
	//
	// Get the resource the contains "Sun Mon Tue Wed Thu Fri Sat "
	dayOfWeekStringsH = DmGetResource (strRsc, daysOfWeekStrID);
	dayOfWeekText = MemHandleLock (dayOfWeekStringsH);

	drawY = 	monthP->bounds.topLeft.y + (cellHeight - FntLineHeight()) / 2;
	for (i = 0; i < daysInWeek; i++)
		{
		dayOfWeekLetter = dayOfWeekText[((i + StartDayOfWeek) % daysInWeek) * 4];
		drawX = monthP->bounds.topLeft.x + (cellWidth * i) +
			((cellWidth - FntCharWidth (dayOfWeekLetter)) / 2);
		WinDrawChars (&dayOfWeekLetter, 1, drawX, drawY);
		}
	MemHandleUnlock(dayOfWeekStringsH);


	// Draw the grid.
	x = monthP->bounds.topLeft.x;
	y = monthP->bounds.topLeft.y + cellHeight;
	for (i = 0; i < daysInWeek + 1; i++)
		{
		WinDrawLine (x, y, x, y + (cellHeight * maxWeeksInMonth));
		x += cellWidth;
		}

	x = monthP->bounds.topLeft.x;
	for (i = 0; i < maxWeeksInMonth + 1; i++)
		{
		WinDrawLine (x, y, x + (cellWidth * daysInWeek) , y);
		y += cellHeight;
		}


	// Draw the days of the month
	FntSetFont (stdFont);
	charWidth = FntCharWidth('0');
	
	dow = FirstDayOfMonth (monthP);
	drawX = monthP->bounds.topLeft.x + (dow * cellWidth) + textLeftMargin;
	drawY = monthP->bounds.topLeft.y + cellHeight + textTopMargin;
	lastDay = DaysInMonth(monthP->month, monthP->year);
	for (i=1; i <= lastDay; i++, dow++)
		{
		if (dow == daysInWeek)
			{
			drawX = monthP->bounds.topLeft.x + textLeftMargin;
			drawY += cellHeight;
			dow = 0;
			}
		StrIToA (dayInAscii, i);
		WinDrawChars (dayInAscii, 
						  (i < 10) ? 1 : 2, 
//						  (i < 10) ? drawX + charWidth : drawX,
						  drawX,
						  drawY);
		drawX += cellWidth;
		}


	// Display a rectangle around today's day if it's visible.
	TimSecondsToDateTime(TimGetSeconds(), &today);
	if (monthP->month == today.month &&
		 monthP->year == today.year)
		{
		day = today.day - 1 + FirstDayOfMonth (monthP);
		r.topLeft.x = monthP->bounds.topLeft.x + (day % daysInWeek) * cellWidth;
		r.topLeft.y = monthP->bounds.topLeft.y + ((day / daysInWeek) + 1) * cellHeight;
		r.extent.x = ((today.day < 10) ? charWidth : charWidth * 2) + (textLeftMargin * 2);
		r.extent.y = FntLineHeight () + (textTopMargin * 2);
		RctInsetRectangle (&r, 1);
		WinInvertRectangle (&r, 0);
		}

	FntSetFont (currFont);
	}


/***********************************************************************
 *
 * FUNCTION:    DrawAppointment
 *
 * DESCRIPTION: This routine draw an appointment indicator.
 *
 * PARAMETERS:  dayR  - bounds of the day's drawing region
 *              start - appointment's start time
 *              end   - appointment's end time
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/8/96	Initial Revision
 *
 ***********************************************************************/
static void DrawAppointment (RectanglePtr dayR, TimeType start, TimeType end)
{
	Short x, y;
	RectangleType r;
	
	// Draw the indicator for an untimed appointment.
	if (TimeToInt(start) == apptNoTime)
		{
		x = dayR->topLeft.x + untimeIndicatorRightMargin;
		y = dayR->topLeft.y + untimeIndicatorTopMargin;
		
		WinDrawLine (x - 1, y, x + 1, y);
		WinDrawLine (x, y - 1, x, y + 1);
		return;
		}
		

	// Draw the indicator for an timed appointment.
	x = dayR->topLeft.x + dayR->extent.x - timeIndicatorWidth - 
		timeIndicatorRightMargin;
	y = dayR->topLeft.y + timeIndicatorTopMargin;

	// Draw indicator for a morning appointment.
	if (TimeToInt(start) < lunchStartTime)
		{
		r.topLeft.x = x;
		r.topLeft.y = y;
		r.extent.x = timeIndicatorWidth;
		r.extent.y = morningHeight;
		WinDrawRectangle (&r, 0);
		}

	// Draw indicator for a lunch appointment.
	if ((TimeToInt(start) >= lunchStartTime && TimeToInt(start) < lunchEndTime) ||
		 (TimeToInt(start) < lunchStartTime && TimeToInt(end) > lunchMidTime))
		{
		r.topLeft.x = x;
		r.topLeft.y = y + morningHeight  + 1;
		r.extent.x = timeIndicatorWidth;
		r.extent.y = lunchHeight;
		WinDrawRectangle (&r, 0);
		}

	// Draw indicator for a afternoon appointment.
	if (TimeToInt(start) >= lunchEndTime ||
		(TimeToInt(start) < lunchEndTime && TimeToInt(end) > lunchEndTime))
		{
		r.topLeft.x = x;
		r.topLeft.y = y + morningHeight + lunchHeight + 2;
		r.extent.x = timeIndicatorWidth;
		r.extent.y = afternoonHeight;
		WinDrawRectangle (&r, 0);
		}
}

/***********************************************************************
 *
 * FUNCTION:    GetDayBounds
 *
 * DESCRIPTION: This routine returns the bounds of the specified day
 *
 * PARAMETERS:  monthP  - pointer to month object
 *              day     - day of month
 *              r       - returned: bounds of the day     
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/10/96	Initial Revision
 *
 ***********************************************************************/
static void GetDayBounds (MonthPtr monthP, Word day, RectanglePtr r)
	{
	Word cell;
	Short	cellWidth;
	Short cellHeight;

	cell = day - 1 + FirstDayOfMonth (monthP);
	cellWidth = monthP->bounds.extent.x / daysInWeek;
	cellHeight = monthP->bounds.extent.y / linesInMonthPlusTitle;
	r->topLeft.x = monthP->bounds.topLeft.x + (cell % daysInWeek) * cellWidth;
	r->topLeft.y = monthP->bounds.topLeft.y + ((cell / daysInWeek) + 1) * cellHeight;
	r->extent.x = cellWidth;
	r->extent.y = cellHeight;
	}
	

/***********************************************************************
 *
 * FUNCTION:    DrawTimedAppointments
 *
 * DESCRIPTION: This routine draws appointment indicators for all the 
 *              appointment in a month.
 *
 * PARAMETERS:  monthP  - month object
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/10/96	Initial Revision
 *
 ***********************************************************************/
static void DrawTimedAppointments (MonthPtr monthP)
{
	UInt	count = 0;
	UInt	recordNum;
	DateType temp;
	DateType date;
	Boolean untimed;
	Boolean sameMonth;
	VoidHand recordH;
	RectangleType dayR;
	ApptDBRecordType apptRec;


	date.day = 1;
	date.month = monthP->month;
	date.year = monthP->year - firstYear;
	
	// Find the first non-repeating appointment of the day.
	ApptFindFirstFar (ApptDB, date, &recordNum);
	while (true)
		{
		recordH = DmQueryNextInCategory (ApptDB, &recordNum, dmAllCategories);
		if (! recordH) break;

		ApptGetRecordFar (ApptDB, recordNum, &apptRec, &recordH);

		// Check if the appointment is on the same month
		sameMonth = (apptRec.when->date.month == monthP->month) && 
						(apptRec.when->date.year == monthP->year - firstYear);

		untimed = TimeToInt(apptRec.when->startTime) == apptNoTime;

		if (sameMonth && 
			 ((ShowUntimedAppts && untimed) || (ShowTimedAppts && (! untimed))))
			{
			GetDayBounds (monthP, apptRec.when->date.day, &dayR);
			DrawAppointment (&dayR, apptRec.when->startTime,
				apptRec.when->endTime);
			}
		MemHandleUnlock (recordH);
		if (! sameMonth) break;

		// Get the next record.
		 recordNum++;
		}


	// Add the repeating appointments to the list.  Repeating appointments
	// are stored at the beginning of the database.
	recordNum = 0;
	while (true)
		{
		recordH = DmQueryNextInCategory (ApptDB, &recordNum, dmAllCategories);
		if (! recordH) break;
		
		ApptGetRecordFar (ApptDB, recordNum, &apptRec, &recordH);
		
		untimed = TimeToInt(apptRec.when->startTime) == apptNoTime;

		if (apptRec.repeat && 
			 ((ShowUntimedAppts && untimed) || (ShowTimedAppts && (! untimed))))
			{
			date.day = 1;
			date.month = monthP->month;
			date.year = monthP->year - firstYear;

		 	while (ApptNextRepeatFar (&apptRec, &date))
				{
				if ((date.month != monthP->month) || 
					(date.year != monthP->year - firstYear))
					break;
				
				GetDayBounds (monthP, date.day, &dayR);
				DrawAppointment (&dayR, apptRec.when->startTime, 
					apptRec.when->endTime);

				temp = date;
				DateAdjust (&date, 1);
				if (DateToInt (temp) == DateToInt (date)) break;
				}
			}
		MemHandleUnlock (recordH);

		// If the record has no repeating info we've reached the end of the 
		// repeating appointments.
		if (! apptRec.repeat) break;
		
		 recordNum++;
		}
}


/***********************************************************************
 *
 * FUNCTION:    DrawRepeatingAppointments
 *
 * DESCRIPTION: This routine draws appointment indicators for all the 
 *              daily repeating appointments in a month.
 *
 * PARAMETERS:  monthP  - month object
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/16/96	Initial Revision
 *
 ***********************************************************************/
static void DrawRepeatingAppointments (MonthPtr monthP)
{
	UInt	count = 0;
	UInt	recordNum;
	Short x1, x2, y;
	DateType temp;
	DateType date;
	Boolean first;
	Boolean last;
	VoidHand recordH;
	RectangleType dayR;
	ApptDBRecordType apptRec;


	// Loop through the repeating event looking for daily repeating events.
	// Repeating appointments are stored at the beginning of the database.
	recordNum = 0;
	while (true)
		{
		recordH = DmQueryNextInCategory (ApptDB, &recordNum, dmAllCategories);
		if (! recordH) break;
		
		ApptGetRecordFar (ApptDB, recordNum, &apptRec, &recordH);
		
		if (apptRec.repeat && 
			 apptRec.repeat->repeatType == repeatDaily &&
			 apptRec.repeat->repeatFrequency == 1)
			{
			date.day = 1;
			date.month = monthP->month;
			date.year = monthP->year - firstYear;

			first = true;

		 	while (ApptNextRepeatFar (&apptRec, &date))
		 		{
		 		if ((date.month != monthP->month) ||
				 	 (date.year != monthP->year - firstYear))
					break;
		
				GetDayBounds (monthP, date.day, &dayR);
				y = dayR.topLeft.y + dayR.extent.y - repeatIndicatorBottomMargin;
				x1 = dayR.topLeft.x;
				x2 = dayR.topLeft.x + dayR.extent.x;
				
				last = (DateToInt (date) == DateToInt (apptRec.repeat->repeatEndDate));

				if (first)
					{
					first = false;
					WinDrawLine (x1+1, y-1, x1+1, y+1);
					x1 += 2;
					}
				
				if (last)
					{
					WinDrawLine (x2-1, y-1, x2-1, y+1);
					x2 -= 2;
					}

				WinDrawGrayLine (x1, y, x2, y);

				temp = date;
				DateAdjust (&date, 1);
				if (DateToInt (temp) == DateToInt (date)) break;
				}
			}
		MemHandleUnlock (recordH);

		// If the record has no repeating info we've reached the end of the 
		// repeating appointments.
		if (! apptRec.repeat) break;
		
		 recordNum++;
		}
}

/***********************************************************************
 *
 * FUNCTION:    DrawAppointmentsInMonth
 *
 * DESCRIPTION: This routine draws appointment indicators for all the 
 *              appointment in a month.
 *
 * PARAMETERS:  monthP  - month object
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/16/96	Initial Revision
 *
 ***********************************************************************/
static void DrawAppointmentsInMonth (MonthPtr monthP)
{

	if (ShowTimedAppts || ShowUntimedAppts)
		DrawTimedAppointments (monthP);

	if (ShowDailyRepeatingAppts)
	DrawRepeatingAppointments (monthP);
}

/***********************************************************************
 *
 * FUNCTION: 	 MapPointToItem
 *
 * DESCRIPTION: Return return the item at x, y.
 *
 * PARAMETERS:  x, y - coordinate
 *              r - the bounds of the item area (not the MTWTFSS area)
 *
 * RETURNED:	 item number (doesn't check for invalid bounds!)
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			roger	11/15/94	Initial Revision
 *
 ***********************************************************************/
static Short MapPointToItem (Short x, Short y, RectanglePtr r)
	{
	Short itemNumber;

	itemNumber = daysInWeek * (((y - r->topLeft.y) /
		(r->extent.y / linesInMonthPlusTitle)) - 1);
	itemNumber += ((x - r->topLeft.x) / (r->extent.x / daysInWeek));
	return itemNumber;
	}


/***********************************************************************
 *
 * FUNCTION:    MonthViewGetMonthPtr
 *
 * DESCRIPTION: This routine returns a pointer to the month object.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:	 pointer to a MonthType structure
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/10/96	Initial Revision
 *
 ***********************************************************************/
static MonthPtr MonthViewGetMonthPtr (void)
	{
	FormPtr frm;
	
	frm = FrmGetActiveForm ();
	return (FrmGetGadgetData (frm, FrmGetObjectIndex (frm, MonthGadget)));
	}


/***********************************************************************
 *
 * FUNCTION:    MonthSelectDay
 *
 * DESCRIPTION: This routine selects a day in the month object.
 *
 * PARAMETERS:	 monthP  - pointer to control object (ControlType)
 *              eventP  - pointer to an EventType structure.
 *              dateP   - returned: pointer to the date selected
 *
 * RETURNED:	true if the event was handle or false if it was not.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/9/96	Initial Revision
 *
 ***********************************************************************/
static Boolean MonthSelectDay (MonthPtr monthP, EventPtr eventP, DatePtr dateP)
	{
	Short				x, y;
	Short       	item;
	Short       	daysInMonth;
	Short       	firstDayInMonth;
	Short				cellWidth, cellHeight;
	Boolean			penDown;
	Boolean			selected;
	RectangleType	r;
	

	firstDayInMonth = FirstDayOfMonth (monthP);
	daysInMonth = DaysInMonth (monthP->month, monthP->year);

	// Restrict the selection bounds.  The top should be moved down
	// to exclude selecting the day of week titles.  The bottom should
	// be moved up to the last week with a day in it.
	RctCopyRectangle (&(monthP->bounds), &r);
	r.topLeft.y += r.extent.y / linesInMonthPlusTitle;
	r.extent.y = (r.extent.y / linesInMonthPlusTitle) *
		(((firstDayInMonth + daysInMonth - 1) / 7) + 1);

	if (! RctPtInRectangle (eventP->screenX, eventP->screenY, &r))
		return false;


	// Compute the bounds of the day the pen is on.
	item = MapPointToItem (eventP->screenX, eventP->screenY, &monthP->bounds);

	cellWidth = monthP->bounds.extent.x / daysInWeek;
	cellHeight = monthP->bounds.extent.y / linesInMonthPlusTitle;
	r.topLeft.x = monthP->bounds.topLeft.x + (item % daysInWeek) * cellWidth + 1;
	r.topLeft.y = monthP->bounds.topLeft.y + ((item / daysInWeek) + 1) * cellHeight + 1;
	r.extent.x = cellWidth - 1;
	r.extent.y = cellHeight - 1;

	// Invert the selected day.
	WinInvertRectangle (&r, 0);
	selected	= true;


	// Track the pen until it's released, highlight or unhighlight the
	// item as the pen move in and out of it.
	do 
		{
		PenGetPoint (&x, &y, &penDown);

		if (RctPtInRectangle (x, y, &r))
			{
			if (! selected)
				{
				WinInvertRectangle (&r, 0);
				selected = true;
				}
			}

		else if (selected)
			{
			WinInvertRectangle (&r, 0);
			selected = false;
			}

		} while (penDown);


	// Exit if the pen was released outside the item.
	if (! selected)
		return (false);

	WinInvertRectangle (&r, 0);

	dateP->month = monthP->month;
	dateP->year = monthP->year - firstYear;

	// Is the selection is outside of the month?
	if ((unsigned) (item - firstDayInMonth) >= (unsigned) daysInMonth)
		{
		// Move to the month before or after the current month.
		dateP->day = 1;
		DateAdjust (dateP, (item - firstDayInMonth));
		}
	else
		{
		dateP->day = item - firstDayInMonth + 1;
		}

	return true;
	}



/***********************************************************************
 *
 * FUNCTION:    MonthViewSetTitle
 *
 * DESCRIPTION: This routine set the title of the Month View
 *
 * PARAMETERS:  monthP  - pointer to month object (MonthType)
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/10/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewSetTitle (MonthPtr monthP)
	{
	Char title [longDateStrLength];
	
	DateToAscii (monthP->month, 1, monthP->year, dfDMYLongNoDay, title);
	FrmCopyTitle (FrmGetActiveForm (), title);
	TimeDisplayed = false;
	}

	
/***********************************************************************
 *
 * FUNCTION:    MonthViewShowTime
 *
 * DESCRIPTION: This routine display the current time in the title of the
 *              month view.
 *
 * PARAMETERS:  frm - pointer to the day view form.
 *
 * RETURNED:    nothing
 *
 * NOTE:        The global variable TimeDisplayed is set to true by this
 *              routine.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/15/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewShowTime (void)
{
	Char				title[timeStringLength];
	DateTimeType 	dateTime;

	TimSecondsToDateTime (TimGetSeconds (), &dateTime);
	TimeToAscii (dateTime.hour, dateTime.minute, TimeFormat, title);
	FrmCopyTitle (FrmGetActiveForm (), title);
	
	TimeDisplayed = true;
	TimeDisplayTick = TimGetTicks () + timeDisplayTicks;
	EvtSetNullEventTick (TimeDisplayTick);
}


/***********************************************************************
 *
 * FUNCTION:    MonthViewHideTime
 *
 * DESCRIPTION: If the title of the Day View is displaying the current 
 *              time, this routine will change the title to the standard
 *					 title (the current date).
 *
 * PARAMETERS:  nothing
 *
 * PARAMETERS:  hide - true to always hide, false hide only if
 *                     to time has been display for the require
 *                      length of time.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/14/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewHideTime (Boolean hide)
{
	MonthPtr 	monthP;
	if (TimeDisplayed)
		{
		if (hide || (TimGetTicks () >= TimeDisplayTick))
			{
			monthP = MonthViewGetMonthPtr ();
			MonthViewSetTitle (monthP);
			}
		else
			{
			EvtSetNullEventTick (TimeDisplayTick);
			}
		}
}


/***********************************************************************
 *
 * FUNCTION:		MonthViewGotoDate
 *
 * DESCRIPTION:	This routine displays the date picker so that the 
 *						user can select a month to navigate to.  If the date
 *						picker is confirmed, the month selected month is 
 *                confirmed
 *
 *						This routine is called when a "go to" button is pressed.
 *              
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/20/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewGotoDate (void)
	{
	CharPtr		title;
	VoidHand		titleH;
	MonthPtr 	monthP;
	SWord 		day;

	// Get the title for the date picker dialog box.
	titleH = DmGetResource (strRsc, goToDateTitleStrID);
	title = MemHandleLock (titleH);

	monthP = MonthViewGetMonthPtr ();

	// Display the date picker.
	day = 1;
	if (SelectDay (selectDayByMonth, &monthP->month, &day, &monthP->year, title))
		{
		WinEraseRectangle (&monthP->bounds, 0);
	
		MonthViewSetTitle (monthP);
		DrawMonth (monthP);
		DrawAppointmentsInMonth (monthP);
		}

	MemHandleUnlock (titleH);
	}



/***********************************************************************
 *
 * FUNCTION:    MonthViewScroll
 *
 * DESCRIPTION: This routine scrolls the month view foreward or backwards
 *              by a month.
 *
 * PARAMETERS:  monthP  - pointer to month object (MonthType)
 *              direction - up (backwards) or down (foreward)
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/8/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewScroll (MonthPtr monthP, DirectionType direction)
{
	// Move backward one month.
	if (direction == up)
		{
		if (monthP->month > january)
			monthP->month--;
		else if (monthP->year > firstYear)
			{
			monthP->month = december;
			monthP->year--;
			}
		else
			return;
		}
		
	// Move foreward one month.
	else
		{
		if (monthP->month < december)
			monthP->month++;
		else if (monthP->year < lastYear)
			{
			monthP->month = january;
			monthP->year++;
			}
		else
			return;
		}
	
	WinEraseRectangle (&monthP->bounds, 0);

	MonthViewSetTitle (monthP);
	DrawMonth (monthP);
	DrawAppointmentsInMonth (monthP);
}


/***********************************************************************
 *
 * FUNCTION:    MonthViewDoCommand
 *
 * DESCRIPTION: This routine preforms the menu command specified.
 *
 * PARAMETERS:  command  - menu item id
 *
 * RETURNED:    true if 
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/17/96	Initial Revision
 *
 ***********************************************************************/
static Boolean MonthViewDoCommand (Word command)
{
	Boolean 		handled = true;
	
	// Preferences
	if (command == MonthPreferencesCmd)
		FrmPopupForm (PreferencesDialog);

	// Display Options
	else if (command == MonthDisplayOptionsCmd)
		FrmPopupForm (DisplayDialog);

	// About
	else if (command == MonthGetInfoCmd)
		AbtShowAbout (sysFileCDatebook);

	return (handled);
}


/***********************************************************************
 *
 * FUNCTION:    MonthViewInit
 *
 * DESCRIPTION: This routine initialize the month view.
 *
 * PARAMETERS:  frm - pointer of the Month View form
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/8/96	Initial Revision
 *
 ***********************************************************************/
static void MonthViewInit (FormPtr frm)
{
	Word objIndex;
	Short width;
	MonthPtr monthP;

	// Create a month object, initialize it, and store a pointer to it in the 
	// month gadget of the Month View.
	monthP = MemPtrNew (sizeof (MonthType));
	if (monthP)
		{
		objIndex = FrmGetObjectIndex (frm, MonthGadget);

		FrmGetObjectBounds (frm, objIndex, &monthP->bounds);
		width = monthP->bounds.extent.x;
		monthP->bounds.extent.x = (width / daysInWeek * daysInWeek) + 1;
		monthP->bounds.topLeft.x = (width - monthP->bounds.extent.x) / 2;

		monthP->month = Date.month;
		monthP->year = Date.year + firstYear;

		FrmSetGadgetData (frm, objIndex, monthP);

		MonthViewSetTitle (monthP);

		// Highlight the Month View push button.
		FrmSetControlGroupSelection (frm, DayViewGroup, MonthMonthViewButton);
		}

	TimeDisplayed = false;
}


/***********************************************************************
 *
 * FUNCTION:    MonthViewHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the Month View
 *              of the Datebook application.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event was handled and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/8/96	Initial Revision
 *
 ***********************************************************************/
 Boolean MonthViewHandleEvent (EventPtr event)
{
	UInt daysInMonth;
	FormPtr frm;
	DateType date;
	Boolean handled = false;
	MonthPtr monthP;

	if (event->eType == penDownEvent)
		{
		monthP = MonthViewGetMonthPtr ();
		if (MonthSelectDay (monthP, event, &date))
			{
			Date = date;
			FrmGotoForm (DayView);
			handled = true;
			}
		}


	else if (event->eType == keyDownEvent)
		{
		MonthViewHideTime (true);

		// Datebook key pressed? Only the Datebook button will reach this
		//	point.
		if (ChrIsHardKey(event->data.keyDown.chr))
			{	
			DateSecondsToDate (TimGetSeconds (), &date);
			Date = date;
			FrmGotoForm (DayView);
			handled = true;
			}
		else if (event->data.keyDown.chr == pageUpChr)
			{
			monthP = MonthViewGetMonthPtr ();
			MonthViewScroll (monthP, up);
			handled = true;
			}	
		else if (event->data.keyDown.chr == pageDownChr)
			{
			monthP = MonthViewGetMonthPtr ();
			MonthViewScroll (monthP, down);
			handled = true;
			}
		}


	else if (event->eType == ctlSelectEvent)
		{
		monthP = MonthViewGetMonthPtr ();
		switch (event->data.ctlSelect.controlID)
			{
			case MonthGoToButton:
				MonthViewGotoDate ();
				handled = true;
				break;

			case MonthDayViewButton:
				Date.year = monthP->year - firstYear;
				Date.month = monthP->month;
				daysInMonth = DaysInMonth (Date.month, Date.year + firstYear);
				Date.day = min (Date.day, daysInMonth);
				FrmGotoForm (DayView);
				handled = true;
				break;

			case MonthWeekViewButton:
				Date.year = monthP->year - firstYear;
				Date.month = monthP->month;
				daysInMonth = DaysInMonth (Date.month, Date.year + firstYear);
				Date.day = min (Date.day, daysInMonth);
				FrmGotoForm (WeekView);
				handled = true;
				break;
			}
		}


	else if (event->eType == ctlRepeatEvent)
		{
		switch (event->data.ctlRepeat.controlID)
			{
			case MonthPrevButton:
				monthP = MonthViewGetMonthPtr ();
				MonthViewScroll (monthP, up);
				break;
			
			case MonthNextButton:
				monthP = MonthViewGetMonthPtr ();
				MonthViewScroll (monthP, down);
				break;
			}
		}


	else if (event->eType == menuEvent)
		{
		handled = MonthViewDoCommand (event->data.menu.itemID);
		}
		

	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		MonthViewInit (frm);
		FrmDrawForm (frm);

		monthP = MonthViewGetMonthPtr ();
		DrawMonth (monthP);
		DrawAppointmentsInMonth (monthP);
		handled = true;
		}


	else if (event->eType == frmUpdateEvent)
		{
		monthP = MonthViewGetMonthPtr ();
		WinEraseRectangle (&monthP->bounds, 0);
		DrawMonth (monthP);
		DrawAppointmentsInMonth (monthP);
		handled = true;		
		}

	else if (event->eType == frmCloseEvent)
		{
		monthP = MonthViewGetMonthPtr ();
		if (monthP)
			MemPtrFree (monthP);
		}


	else if (event->eType == frmTitleEnterEvent)
		{
		// If the pen is in the title toggle between the current date
		// and the current time.
		if (TimeDisplayed)
			MonthViewHideTime (true);
		else
			MonthViewShowTime ();
		}


	else if (event->eType == nilEvent)
		{
		MonthViewHideTime (false);
		}



	return (handled);
}