/***********************************************************************
 *
 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:     Datebook.c
 * AUTHOR:	 Art Lamb: June 12, 1995
 *
 * DECLARER: Datebook
 *
 * DESCRIPTION:
 *	  This is the Datebook application's week view module.
 *
 **********************************************************************/

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



/***********************************************************************
 *
 *	Global variables
 *
 ***********************************************************************/

//	WeekView globals:
static VoidHand			WeekObjectH;					//	The currently active
																	//	week

static CustomPatternType	regAppt = {0xaa55, 0xaa55, 0xaa55, 0xaa55};
										//	50% gray pattern
static CustomPatternType	overLapAppt = {0x8844, 0x2211, 0x8844, 0x2211};
										//	Diagonal stripes
static FontID				OrigFont;


/***********************************************************************
 *
 *	Internal Constants
 *
 ***********************************************************************/


//	WeekView/Day object constants
#define weekViewDayHMargin					4		//	This is the horizontal space
 															//	between the edge of the day's
 															//	bounds and the visible event
 															//	bar.

#define weekViewTimeDisplayWidth			25		//	Width of column of times
#define timeHMargin							2		//	Horiz margin between times
															//	& first day bar.
#define weekHMargin							2		//	Horiz margin between days
															//	and right edge of screen.
#define weekViewDayDisplayHeight			12		//	Height of day labels at top
															//	of view.
#define weekViewDateDisplayHeight		13		//	Height of date labels under
															//	day labels at top of view.
#define weekViewEventFrameWidth			3		//	Width of frame around

#define weekViewScrollInterval			4		//	Scroll interval, in hours.
															//	Must be >= 1.
#define weekViewNumDispHours				11		//	Number of hours that we display
															//	on one screenful of data.
#define weekViewHourDisplayInterval		2		//	Used for displaying the time
															//	bar.
															
#define dataMarkHMargin						4		//	Horizontal margins around
															//	data indicators.
#define dataMarkVMargin						2
#define outOfRangeDay						0		//	illegal date.
 
#define weekDescMarginX						3		// Margin in popup desc
#define weekDescMarginY						2		// Margin in popup desc

#define moveThreshold						8		// Number of pixels to drag an 
															// event before it starts moving

#define weekDescDisplayTicks				200	// number of tick to display the
															// description popup 

/***********************************************************************
 *
 *	Internal Structutes
 *
 ***********************************************************************/

//	These structures are used by the WeekView of the DateBook
typedef struct
	{
	RectangleType			bounds;
	DateType					date;					//	If the 'day' field is set to
														//	'outOfRangeDay', this day is
														//	outside the allowable system range
														//	and should not be drawn.
	unsigned char			dayOfWeek;
	VoidHand					apptsH;				//	Use ApptInfoPtr to examine
	Word						numAppts;
	Word						firstEventHour;
	Word						lastEventHour;		//	The limits of the events which
														//	exist on this day.  Meaningless
														//	if there are no appts.
	} DayType;
	
typedef struct
	{
	RectangleType			bounds;
	Word						startHour;			//	first currently displayed hour
	Word						endHour;				//	last currently displayed hour
	DayType					days[daysInWeek];
	DateType					startDate;			//	Start date of week
	Word						firstEventHour;	//	Hour of earliest event
														//	during the current week.
	Word						lastEventHour;		//	Hour of latest event
														//	during the current week.
	Word						hourHeight;			//	Height, in pixels, of one
														//	hour of time in a day bar.
	SDWord					descTick;			// tick count when the popup 
														// description was displayed.
	WinHandle				behindDesc;			// bits behind popup description.
	WinHandle				behindHighlight;	// bits behind selection highlighting

	} WeekType;
	
typedef WeekType * WeekPtr;

/***********************************************************************
 *
 *	Internal Functions
 *
 ***********************************************************************/
static void WeekViewDrawTimes (short startYPos, Word startHour, Word endHour,
										 Word hourHeight);
static void WeekViewFree (void);
static void WeekViewInit (FormPtr frm);
static void WeekViewInitDays (FormPtr frm);
static void WeekViewDrawDays (void);
static void WeekViewDraw (FormPtr frm);
static void WeekEraseDescription (Boolean eraseIt);
 
// zzz move to time manager.
/***********************************************************************
 *
 * FUNCTION:    TimeDifference
 *
 * DESCRIPTION: Subtract pTime2 from pTime1 and place the result in
 *					 pTimeDiff.
 *
 *					 Note that TimeType is now unsigned so this doesn't
 *					 work for negative times (which no longer exist!).
 *
 * PARAMETERS:  pTime1   - pointer to HMSTime
 *              pTime2   - pointer to HMSTime
 *              pTimeDiff- pointer to HMSTime
 *
 * RETURNED:	 pTimeDiff is set to pTime1 - pTime2.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			roger	12/2/94	Initial Revision
 *
 ***********************************************************************/

static void TimeDifference (TimePtr pTime1, TimePtr pTime2, TimePtr pTimeDiff)
	{
	pTimeDiff->hours = pTime1->hours - pTime2->hours;

	if (pTime1->minutes < pTime2->minutes)
		{
		pTimeDiff->minutes = pTime1->minutes + hoursInMinutes - pTime2->minutes;
		pTimeDiff->hours--;
		}
	else
		pTimeDiff->minutes = pTime1->minutes - pTime2->minutes;
	
	}

/***********************************************************************
 *
 * FUNCTION:    FirstDayOfYear
 *
 * DESCRIPTION: Return the number of day from 1/1/1904 of the first day 
 *              of the year passed.
 *
 *					 The first day of the year is always a Monday.  The rule 
 *					 for determining the first day of the year is:
 *				
 *					 New Years Day	First Day of the Year
 *					 ------------	---------------------
 *					 Monday			Monday Jan 1
 *					 Tuesday			Monday Dec 31
 *					 Wednesday		Monday Dec 30
 *					 Thursday		Monday Dec 29
 *					 Friday			Monday Jan 4 
 *					 Saturday		Monday Jan 3 
 *					 Sunday			Monday Jan 2
 *
 * PARAMETERS:	 year  - year (1904-2031)
 *
 * RETURNED:	 number of days since 1/1/1904
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/4/96	Initial Revision
 *
 ***********************************************************************/
static ULong FirstDayOfYear (Word year)
{
	ULong days;
	Word dayOfWeek;
	DateType date;
	
	// Get days to January 1st of the year passed.
	date.day = 1;
	date.month = 1;
	date.year = year - firstYear;
	days = DateToDays (date);
	
	dayOfWeek = DayOfWeek (1, 1, year);

	// Move to monday.
	days++;
	days -= dayOfWeek;

	
	if (dayOfWeek >= friday)
		days += daysInWeek;
		
	return (days);
}


/***********************************************************************
 *
 * FUNCTION:    GetWeekNumber
 *
 * DESCRIPTION: Calculate the week number of the specified date.
 *
 * PARAMETERS:	 month - month (1-12)
 *              day   - day (1-31)
 *              year  - year (1904-2031)
 *
 * RETURNED:	 week number (1-53)
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/4/96	Initial Revision
 *
 ***********************************************************************/
static Word GetWeekNumber (Word month, Word day, Word year)
	{
	Word dow;
	Word week;
	ULong days;
	ULong firstOfYear;
	ULong firstOfNextYear;
	DateType date;

	// Calculate the julian date of Monday in the same week as the 
	// specified date.
	date.day = day;
	date.month = month;
	date.year = year - firstYear;
	days = DateToDays (date);

	// Adjust the day of the week by the preference setting for the first day
	// of the week.
	dow = (DayOfWeek (month, day, year) - StartDayOfWeek + daysInWeek) 
				% daysInWeek;

	if (monday < StartDayOfWeek)
		days -= (Short)dow - (monday + daysInWeek - StartDayOfWeek);
	else		
		days -= (Short)dow - (monday - (Short)StartDayOfWeek);


	firstOfYear = FirstDayOfYear (year);
	
	if (days < firstOfYear)
		{
		// The date passed is in a week that is part of the prior 
		//	year, so get the start of the prior year.
		if (year > firstYear)
			firstOfYear = FirstDayOfYear (--year);
		}
	else
		{
		// Make sure the date passed is not in a week that in part
		// of next year.
		if (year < lastYear)
			{  
			firstOfNextYear = FirstDayOfYear (year + 1);
			if (days == firstOfNextYear)
				firstOfYear = firstOfNextYear;
			}
		}
	
	week = ((Short)(days - firstOfYear)) / daysInWeek + 1;		// one base
	
	return (week);
	}
	

/***********************************************************************
 *
 * FUNCTION:    WeekViewNewAppointment
 *
 * DESCRIPTION:	This routine create a new apointment.  It's called
 *                when the user selects an empty time slot.
 *
 * PARAMETERS:		startTime - start time of the new appointment
 *                endTime   - end time of the new appointment
 *
 * RETURNED:		nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/25/95	Initial Revision
 *
 ***********************************************************************/
static void WeekViewNewAppointment (TimePtr startTime, TimePtr endTime)
{
	Err error;
	Word recordNum;
	ApptDBRecordType newAppt;
	ApptDateTimeType when;
	
	// Create a new appointment on the current day.
	MemSet (&newAppt, sizeof (newAppt), 0);

	when.startTime = *startTime;
	when.endTime = *endTime;
	if (TimeToInt(when.endTime) > apptMaxEndTime)
		TimeToInt (when.endTime) = apptMaxEndTime;
	when.date = Date;
	newAppt.when = &when;
	newAppt.description = "";
	if (AlarmPreset.advance != apptNoAlarm)
		newAppt.alarm = &AlarmPreset;		

	error = ApptNewRecordFar (ApptDB, &newAppt, &recordNum);
	
	if (! error)
		{
		CurrentRecord = recordNum;
		ItemSelected = true;
		}

	// Display an alert that indicates that the new record could 
	// not be created.
	if (error)
		{
		// zzz Add alert here
		}
}


/***********************************************************************
 *
 * FUNCTION:    WeekViewUpdateScrollers
 *
 * DESCRIPTION:	This routine draws or erases the Week View scroll arrow
 *						buttons depending on whether there is more data to be
 *						displayed in either direction.
 *
 * PARAMETERS:		frm - pointer to the Week View form.
 *
 * RETURNED:		nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	7/31/95	Initial Revision
 *			kcr	9/20/95	convert to use FrmUpdateScrollers
 *
 ***********************************************************************/
static void WeekViewUpdateScrollers (FormPtr frm)
	{
	WeekType		*week;
	Word upIndex;
	Word downIndex;
	Boolean scrollableUp;
	Boolean scrollableDown;
	
	week = MemHandleLock (WeekObjectH);

	scrollableUp = (week->startHour > week->firstEventHour);
	scrollableDown = (week->endHour < week->lastEventHour);
	upIndex = FrmGetObjectIndex (frm, WeekUpButton);
	downIndex = FrmGetObjectIndex (frm,WeekDownButton);
	FrmUpdateScrollers (frm, upIndex, downIndex, scrollableUp, scrollableDown);
		
	MemPtrUnlock(week);
	}	//	end of WeekViewUpdateScrollers
	
/***********************************************************************
 *
 * FUNCTION:    DrawTopDataMark
 *
 * DESCRIPTION:	This routine draws a little mark above a given day's
 *						event bar.
 *
 * PARAMETERS:		r - the bounds of the day
 *               scrool - true of the view can be scrolled up
 *               noTime - true of the day has untimed events.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	4/19/95	initial version
 *
 ***********************************************************************/
static void DrawTopDataMark (RectanglePtr r, Boolean scroll, Boolean untimed)
	{
	Short x1, x2, y;
	
	x1 = r->topLeft.x + dataMarkHMargin;
	x2 = r->topLeft.x + r->extent.x - dataMarkHMargin;
	y = r->topLeft.y + weekViewDayDisplayHeight +
		weekViewDateDisplayHeight - dataMarkVMargin;

	if (scroll)
		{
		// Draw the scroll indicators.
		WinDrawLine (x1, y, x2, y);
		if (untimed)
			{
			// Draw the no-time indicators.
			WinDrawLine (x1, y-1, x1+1, y-1);
			}
		else
			{
			// Erase the no-time indicators.
			WinEraseLine (x1, y-1, x1+1, y-1);
			}
		}
	
	else
		{
		// Draw the no-time indicators and erase the scroll indicators.
		if (untimed)
			{
			WinDrawLine (x1, y-1, x1+1, y-1);
			WinDrawLine (x1, y, x1+1, y);
			WinEraseLine (x1+2, y, x2, y);
			}

		// Erase both the scroll and no-time indicators.
		else
			{
			WinEraseLine (x1, y-1, x1+1, y-1);
			WinEraseLine (x1, y, x2, y);
			}
		}
	}	//	end of DrawTopDataMark


#if 0
/***********************************************************************
 *
 * FUNCTION:    DrawTopDataMark
 *
 * DESCRIPTION:	This routine draws a little mark above a given day's
 *						event bar.
 *
 * PARAMETERS:		RectanglePtr				r - the bounds of the day
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	10/3/95	initial version
 *
 ***********************************************************************/
static void DrawTopDataMark (RectanglePtr r)
	{
	WinDrawLine (r->topLeft.x + dataMarkHMargin,
					 r->topLeft.y +
					 	weekViewDayDisplayHeight +
					 	weekViewDateDisplayHeight - dataMarkVMargin,
					 r->topLeft.x + r->extent.x - dataMarkHMargin,
					 r->topLeft.y + 
					 	weekViewDayDisplayHeight +
					 	weekViewDateDisplayHeight - dataMarkVMargin);
	}	//	end of DrawTopDataMark


/***********************************************************************
 *
 * FUNCTION:    EraseTopDataMark
 *
 * DESCRIPTION:	This routine erases a little mark above a given day's
 *						event bar.
 *
 * PARAMETERS:		RectanglePtr				r - the bounds of the day
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	10/3/95	initial version
 *
 ***********************************************************************/
static void EraseTopDataMark (RectanglePtr r)
	{
	WinEraseLine (r->topLeft.x + dataMarkHMargin,
					 r->topLeft.y +
					 	weekViewDayDisplayHeight +
					 	weekViewDateDisplayHeight - dataMarkVMargin,
					 r->topLeft.x + r->extent.x - dataMarkHMargin,
					 r->topLeft.y + 
					 	weekViewDayDisplayHeight +
					 	weekViewDateDisplayHeight - dataMarkVMargin);
	}	//	end of EraseTopDataMark
#endif

/***********************************************************************
 *
 * FUNCTION:    DrawBottomDataMark
 *
 * DESCRIPTION:	This routine draws a little mark below a given day's
 *						event bar.
 *
 * PARAMETERS:		RectanglePtr				r - the bounds of the day
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	10/3/95	initial version
 *
 ***********************************************************************/
static void DrawBottomDataMark (RectanglePtr r)
	{
	WinDrawLine (r->topLeft.x + dataMarkHMargin,
					 r->topLeft.y + r->extent.y + dataMarkVMargin,
					 r->topLeft.x + r->extent.x - dataMarkHMargin,
					 r->topLeft.y + r->extent.y + dataMarkVMargin);
	}	//	end of DrawBottomDataMark


/***********************************************************************
 *
 * FUNCTION:    EraseBottomDataMark
 *
 * DESCRIPTION:	This routine erases a little mark below a given day's
 *						event bar.
 *
 * PARAMETERS:		RectanglePtr				r - the bounds of the day
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	10/3/95	initial version
 *
 ***********************************************************************/
static void EraseBottomDataMark (RectanglePtr r)
	{
	WinEraseLine (r->topLeft.x + dataMarkHMargin,
					 r->topLeft.y + r->extent.y + dataMarkVMargin,
					 r->topLeft.x + r->extent.x - dataMarkHMargin,
					 r->topLeft.y + r->extent.y + dataMarkVMargin);
	}	//	end of EraseBottomDataMark


/***********************************************************************
 *
 * FUNCTION:    WeekViewDrawDataMarks
 *
 * DESCRIPTION:	This routine draws little marks above and below each
 *						day's event bar to show that there are more events
 *						in either direction for a given day.
 *
 *						This routine must be broken out separately from the
 *						standard draw routine, because it must function even
 *						when a clip region is set for drawing while scrolling.
 *
 * PARAMETERS:		nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	10/3/95	initial version
 *
 ***********************************************************************/
static void WeekViewDrawDataMarks (void)
	{
	int					i;
	Boolean				untimed;
	WeekType				*week;
 	ApptInfoPtr			appts;

	week = MemHandleLock (WeekObjectH);
	
	for (i = 0; i < daysInWeek; i++)
		{
		// Check if the are any untimed apppoints.  They'll be first in list
		// of appointment if they exist.
		untimed = false;
		if (week->days[i].numAppts)
			{
			appts = MemHandleLock (week->days[i].apptsH);
			untimed = (TimeToInt (appts[0].startTime) == apptNoTime);
	 		MemPtrUnlock(appts);
			}

		DrawTopDataMark (&(week->days[i].bounds),
							  week->days[i].firstEventHour < week->startHour,
							  untimed);
		
//		if (week->days[i].firstEventHour < week->startHour)
//			DrawTopDataMark (&(week->days[i].bounds));
//		else
//			EraseTopDataMark (&(week->days[i].bounds));

		if (week->days[i].lastEventHour > week->endHour)
			DrawBottomDataMark (&(week->days[i].bounds));
		else
			EraseBottomDataMark (&(week->days[i].bounds));
		}

	MemPtrUnlock(week);
	}	//	end of WeekViewDrawDataMarks


/***********************************************************************
 *
 * FUNCTION:    WeekViewDrawDescription
 *
 * DESCRIPTION:	This routine
 *
 * PARAMETERS:		
 *
 * RETURNED:    	handle of a window that contains the bits obscured 
 *                by the description.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	3/28/96	Initial Revision
 *
 ***********************************************************************/
static WinHandle WeekViewDrawDescription (TimePtr startTime, TimePtr endTime,
	DatePtr date, CharPtr desc, Boolean saveBits)
{
	Char ch;
	Word error;
	Word len;
	Word charsToDraw;
	Word charsToErase;
	Char str [20];
	Short descWidth;
	Short maxDescWidth;
	CharPtr ptr;
	Short x, y;
	FontID curFont;
	WinHandle winH = 0;
	RectangleType r;	
	RectangleType eraseR;	
	
	curFont = FntSetFont (stdFont);
	
	// Compute the bounds of the drawing region for the description.
	WinGetWindowExtent (&r.extent.x, &r.extent.y);
	r.topLeft.x = 0;
	r.topLeft.y = 0;
	r.extent.y = (FntLineHeight () * 2) + (weekDescMarginY * 3) + 3;
	
	// Save the region that we're going to draw over.
	if (saveBits)
		{
		winH = WinSaveBits (&r, &error);
		if (! winH) return (0);
		
		// Erase and frame the drawing region with a 3D frame.
		WinEraseRectangle (&r, 0);
		r.topLeft.x++;
		r.topLeft.y++;
		r.extent.x -= 3;
		r.extent.y -= 3;
		WinDrawRectangleFrame (popupFrame , &r);
		}
	else
		{
		r.topLeft.x++;
		r.topLeft.y++;
		r.extent.x -= 3;
		r.extent.y -= 3;
		}
	

	// Format and draw the appointments date.
	if (date)
		{
		DateToDOWDMFormat (date->month, date->day, date->year + firstYear,
			ShortDateFormat, str);
	
		x = r.topLeft.x + weekDescMarginX;
		y = r.topLeft.y + weekDescMarginY;
		WinDrawChars (str, StrLen (str), x, y);

		charsToErase = 0;
		if (date->month >= 1 && date->month <= 9)
			charsToErase++;

		if (date->day >= 1 && date->day <= 9)
			charsToErase++;

		// I don't know how mush wider the old day-name was than 
		// day-name just drawn, so I'll erase the width of two chatacter
		// just to be save.
		eraseR.topLeft.x = x + FntCharsWidth (str, StrLen (str));
		eraseR.topLeft.y = y;
		eraseR.extent.x = FntAverageCharWidth () * 2 + 
								FntCharWidth ('1') * charsToErase;
		eraseR.extent.y = FntLineHeight ();
		WinEraseRectangle (&eraseR, 0);
		}


	// Format and draw the appointments start and end times
	if (startTime && endTime)
		{
		TimeToAscii (startTime->hours, startTime->minutes,
			TimeFormat, str);
		len = StrLen (str);
		str[len++] = spaceChr;
		str[len++] = '-';
		str[len++] = spaceChr;
		TimeToAscii (endTime->hours, endTime->minutes,
			TimeFormat, &str[len]);
			
		x = r.topLeft.x + (r.extent.x - weekDescMarginX - 
			FntCharsWidth (str, StrLen (str)));
		y = r.topLeft.y + weekDescMarginY;
		
		charsToErase = 0;
		if ((startTime->hours >= 1 && startTime->hours <= 9) ||
			(startTime->hours >= 13 && startTime->hours <= 21))
			charsToErase++;

		if ((endTime->hours >= 1 && endTime->hours <= 9) ||
			(endTime->hours  >= 13 && endTime->hours <= 21))
			charsToErase++;
			
		if (charsToErase)
			{
			eraseR.topLeft.x = x - (FntCharWidth ('1') * charsToErase);
			eraseR.topLeft.y = y;
			eraseR.extent.x = x - eraseR.topLeft.x;
			eraseR.extent.y = FntLineHeight ();
			WinEraseRectangle (&eraseR, 0);
			}
			
		
		WinDrawChars (str, StrLen (str), x, y);
		}



	// Draw the appointment's desciption.
	if (desc)
		{
		x = r.topLeft.x + weekDescMarginX;
		y = r.topLeft.y + (weekDescMarginY << 1) + FntLineHeight();
		maxDescWidth = r.extent.x - x - weekDescMarginX;
	
		ptr = StrChr (desc, linefeedChr);
		if (ptr)
			{
			charsToDraw = (Word) (ptr - desc);
			descWidth = FntCharsWidth (desc, charsToDraw);
			if (descWidth <= maxDescWidth)
				WinDrawChars (desc, charsToDraw, x, y);
			else
				{
				maxDescWidth -= FntCharWidth (horizEllipsisChr);
				while (descWidth > maxDescWidth)
					descWidth -= FntCharWidth (desc[charsToDraw--]);
				WinDrawChars (desc, charsToDraw, x, y);
				ch = horizEllipsisChr;
				WinDrawChars (&ch, 1, x + descWidth, y);
				}
			}
		else
			{
			maxDescWidth -= FntCharWidth (horizEllipsisChr);
			charsToDraw = 0;
			while (true)
				{
				if ( ! desc[charsToDraw]) break;
				maxDescWidth -= FntCharWidth (desc[charsToDraw]);
				if (maxDescWidth >= 0)
					charsToDraw++;
				else
					break;
				}
				
			WinDrawChars (desc, charsToDraw, x, y);
			if (maxDescWidth < 0)
				{
				descWidth = FntCharsWidth (desc, charsToDraw);
				ch = horizEllipsisChr;
				WinDrawChars (&ch, 1, x + descWidth, y);
				}
			}
		}

	FntSetFont (curFont);
	
	return (winH);
}


/***********************************************************************
 *
 * FUNCTION:    WeekViewScroll
 *
 * DESCRIPTION:	This routine scrolls the Week View in the direction 
 *						specified.  It is assumed that there is room to scroll
 *						in the specified direction.  If there is not, the 
 *						scroll operation will just redraw the screen in place.
 *
 *						The screen is scrolled on weekViewScrollInterval if
 *						byPage is FALSE, and by weekViewNumDispHours if
 *						byPage is TRUE, in the specified direction.
 *
 * PARAMETERS:	DirectionType			direction - up or dowm
 *					Boolean					byPage - TRUE if scrolling by page, FALSE
 *													if scrolling by weekViewScrollInterval
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	8/7/95	Initial Revision
 *			kcr	8/8/95	added page scrolling
 *			kcr	8/21/95	scroll to even intervals when not scrolling byPage
 *
 ***********************************************************************/
static void WeekViewScroll (DirectionType direction, Boolean byPage)
	{
	int					interval;
	RectangleType		r, vacated, origClip;
	short					lineYPos;
	WeekType				*week;
	Word					scrollDist;
	Word					dispStartHour;
	
	week = MemHandleLock (WeekObjectH);
	
	if (byPage)
		interval = weekViewNumDispHours;
	else
		interval = weekViewScrollInterval;
		
	//	Adjust week's displayed hour range in the proper direction
	if (direction == up)
		{
		if (byPage)
			scrollDist = weekViewNumDispHours;
		else
			scrollDist = week->startHour -
							 ((((week->startHour - interval - 1) / interval) + 1) *
							  interval);
		if ((week->startHour - week->firstEventHour) < scrollDist)
			scrollDist = week->startHour - week->firstEventHour;

		week->startHour -= scrollDist;
		week->endHour -= scrollDist;
		}
	else	//	down
		{
		if (byPage)
			scrollDist = weekViewNumDispHours;
		else
			scrollDist = (((week->startHour / interval) + 1) * interval) - 
							 week->startHour;
		if ((week->lastEventHour - week->endHour) < scrollDist)
			scrollDist = week->lastEventHour - week->endHour;

		week->startHour += scrollDist;
		week->endHour += scrollDist;
		}

	//	Redraw the hour markers:
	//	Determine where start of backround is:	
 	lineYPos = week->bounds.topLeft.y +
 						 weekViewDayDisplayHeight +
 						 weekViewDateDisplayHeight;
 	dispStartHour = week->startHour;

 	while ((dispStartHour % weekViewHourDisplayInterval) != 0)
 		{	//	Display starts on an odd hour
 		lineYPos += week->hourHeight;
 		dispStartHour++;
 		}

 	//	Draw times - vertically centered on background lines; 
 	//	horizontally centered in space between left edge of view and
 	//	left end of lines.  Erase background first.
	r = week->bounds;
	r.extent.x = weekViewTimeDisplayWidth;
	WinEraseRectangle (&r, 0);
 	WeekViewDrawTimes (lineYPos, dispStartHour, week->endHour, week->hourHeight);	

	//	We only want to scroll the 'event bar' area of the screen.
	//	Shrink the vertical size by 1 pix on top to keep the frame
	//	edges intact.
	r = week->bounds;
	r.topLeft.y += (weekViewDayDisplayHeight + weekViewDateDisplayHeight +1);
	r.extent.y = week->hourHeight*weekViewNumDispHours -1;
	r.topLeft.x += weekViewTimeDisplayWidth + 1;
	r.extent.x = r.extent.x - weekViewTimeDisplayWidth - 2;

	//	The actual scrolling dirty-work:
	if (direction == up)
		WinScrollRectangle (&r, down, scrollDist*week->hourHeight, &vacated);
	else
		WinScrollRectangle (&r, up, scrollDist*week->hourHeight, &vacated);
	WinEraseRectangle (&vacated, 0);
	WinGetClip (&origClip);
	WinSetClip (&vacated);
	WeekViewDraw (FrmGetActiveForm ());
	WeekViewDrawDays ();
	WinSetClip (&origClip);
	WeekViewDrawDataMarks ();

	WeekViewUpdateScrollers (FrmGetActiveForm());

	MemPtrUnlock(week);
	}	//	end of WeekViewScroll


/***********************************************************************
 *
 * FUNCTION:    WeekViewGoToWeek
 *
 * DESCRIPTION:	This routine moves the Week View to the week
 *						including the current setting of Date.  It is assumed
 *						that the week view is already up; it must be erased,
 *						reinitialized, and redrawn.
 *
 * PARAMETERS:  	nothing
 *
 * RETURNED:    	nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	8/21/95	Initial Revision
 *			kcr	9/19/95	removed date calc.  Must be done by caller.
 *
 ***********************************************************************/
static void WeekViewGoToWeek (void)
	{
	WeekType				*week;

	WeekViewFree ();
	WeekViewInit (FrmGetActiveForm ());

	//	Erase the old week view before drawing the new one.
	week = MemHandleLock (WeekObjectH);
	WinEraseRectangle (&(week->bounds), 0);
	WeekViewDraw (FrmGetActiveForm ());

	WeekViewInitDays (FrmGetActiveForm ());
	WeekViewDrawDays ();
	WeekViewDrawDataMarks ();

	MemPtrUnlock(week);
	}	//	end of WeekViewGoToWeek
	

/***********************************************************************
 *
 * FUNCTION:    WeekViewDayInit
 *
 * DESCRIPTION:	This routine initializes a passed DayType structure.
 *						All fields of the DayType struct are filled in and
 *						the week->firstEventHour and week->lastEventHour vars are
 *						maintained.
 *
 * PARAMETERS:		DayType				*day - the structure to init.
 *						unsigned char		dayOfWeek - matches date
 *						RectanglePtr		bounds
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	7/28/95		Initial Revision
 *			kcr	10/3/95		calc day's event range, as well as week's.
 *			kcr	10/12/95		don't calc data if date is out of range.
 *			kcr	11/13/95		remove date param; dates are set during week init
 *
 ***********************************************************************/
 static void WeekViewDayInit (DayType *day, unsigned char dayOfWeek,
 										RectanglePtr bounds,
 										Word *firstEventHour, Word *lastEventHour,
 										VoidHand apptsH, Word numAppts)
 	{
 	ApptInfoPtr				appts;
 	int						i;

 	//	Load day bounds
 	day->bounds = *bounds;

 	//	Load the appt list
 	if (day->date.day != outOfRangeDay)
 		{
	 	day->apptsH = apptsH;
	 	day->numAppts = numAppts;
	 	day->dayOfWeek = dayOfWeek;
	 	}
	else	//	Non-displayable date.
		{
		day->apptsH = 0;
		day->numAppts = 0;
		day->dayOfWeek = 0;
		}
 	day->firstEventHour = 24;
 	day->lastEventHour = 0;

 	//	Stretch the bounds of the scrolling range if there are any events
 	//	outside the current range.  This must be performed for both
 	//	the day and the week.
	if (day->numAppts != 0)
		appts = MemHandleLock (day->apptsH);
 	for (i = 0; i < day->numAppts; i++)
 		{
 		if ((appts[i].startTime.hours != (unsigned char) apptNoTime) &&
 			 (appts[i].startTime.hours < (*firstEventHour)))
 			{
 			//	Round down to the nearest hour <= start of appt.
 			(*firstEventHour) = appts[i].startTime.hours;
 			day->firstEventHour = appts[i].startTime.hours;
 			}
 		else if ((appts[i].startTime.hours != (unsigned char) apptNoTime) &&
					(appts[i].startTime.hours < day->firstEventHour))
 			day->firstEventHour = appts[i].startTime.hours;


 		if ((appts[i].endTime.hours != (unsigned char) apptNoTime) &&
 			 (appts[i].endTime.hours > (*lastEventHour) ||
 			  (appts[i].endTime.hours == (*lastEventHour) &&
 			   appts[i].endTime.minutes != 0)))
 			{
 			//	Round up to the next hour >= end of the appt.
 			(*lastEventHour) = appts[i].endTime.hours;
 			if (appts[i].endTime.minutes != 0)
 				(*lastEventHour)++;
 			day->lastEventHour = appts[i].endTime.hours;
 			if (appts[i].endTime.minutes != 0)
 				day->lastEventHour++;
 			}

 		else if ((appts[i].endTime.hours != (unsigned char) apptNoTime) &&
 					(appts[i].endTime.hours > day->lastEventHour ||
 					 (appts[i].endTime.hours == day->lastEventHour &&
 					  appts[i].endTime.minutes != 0)))
 			{
 			//	Round up to the next hour >= end of the appt.
 			day->lastEventHour = appts[i].endTime.hours;
 			if (appts[i].endTime.minutes != 0)
 				day->lastEventHour++;
 			}
 		}
 	if (day->numAppts != 0)
 		MemPtrUnlock(appts);

 	}	//	end of WeekViewDayInit


/***********************************************************************
 *
 * FUNCTION:    WeekViewDayClose
 *
 * DESCRIPTION:	This routine frees all allocatd memory involved in
 *						a DayType structure.  It is generally called when a week
 *						is being torn down.
 *
 * PARAMETERS:		DayType				*day
 *
 * RETURNED:    	nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/9/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewDayClose (DayType *day)
 	{
 	if (day->numAppts != 0)
 		{
 		MemHandleFree (day->apptsH);
 		day->apptsH = 0;
 		}
 	}	//	end of WeekViewDayClose
 	

/***********************************************************************
 *
 * FUNCTION:    	WeekViewHoursToCoords
 *
 * DESCRIPTION:	Convert a time to a y-coordinate position, based on
 *						a starting hour.  'time' is assumed to be within the
 *						current hour display range.
 *
 * PARAMETERS:		TimeType				time - the time to convert
 *						Word					startHour - baseline of time to use
 *												as the zero-coordinate.
 *						Word					hourHeight - vertical size of an hour-long
 *												event.
 *
 * RETURNED:		Word					yPos - the difference, in y-coords,
 *												between startHour and time, based on
 *												week->hourHeight.
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/3/95		Initial Revision
 *
 ***********************************************************************/
static Word WeekViewHoursToCoords(TimeType time, Word startHour,
											 Word hourHeight)
	{
	Word				yPos;
	
	yPos = (time.hours - startHour) * hourHeight;
	yPos += (time.minutes * hourHeight) / 60;
	return (yPos);
	}	//	end of WeekViewHoursToCoords


/***********************************************************************
 *
 * FUNCTION:    	WeekViewGetEventBounds
 *
 * DESCRIPTION:	Determine the top & bottom bounds of an event.
 *
 * PARAMETERS:		TimeType				startTime
 *						TimeType				endTime
 *						Word					startHour - start of time display
 *						Word					endHour - end of time display
 *						RectanglePtr		r - points to rectangle holding whole
 *													event bar's coords, including top &
 *													bottom of frame.
 *						Word					hourHeight - height, in pix, of an hour-
 *													long event.
 *
 * RETURNED:		nothing				y-coords of r have been adjusted so that
 *													frame around event (top & bottom) will
 *													include start & end times.
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/8/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewGetEventBounds(TimeType startTime, TimeType endTime,
											  Word startHour, Word endHour,
											  RectanglePtr r, Word hourHeight)
	{
	short				startYOffset = 0;
	short				endYOffset;
	
	//	Determine start y coord, relative to top of r, inclusive of the
	//	startTime:
	if (startTime.hours > startHour ||
		 (startTime.hours == startHour &&
		  startTime.minutes != 0))
			{	//	Need to adjust start y coord.
			startYOffset = WeekViewHoursToCoords(startTime, startHour, hourHeight);
			r->topLeft.y += startYOffset;
			}
			
	//	Determine ending coord, relative to the top of the event bar,
	//	inclusive of the endTime:
	endYOffset = r->extent.y;
	if (endTime.hours < endHour)
		{	//	Need to shorten up end y-coord
		endYOffset = WeekViewHoursToCoords(endTime, startHour, hourHeight);
		endYOffset++;										//	Make the range inclusive
																//	of the endTime
		}

	r->extent.y = endYOffset - startYOffset;

	r->topLeft.y++;								//	Allow for top & bottom of frame
	r->extent.y -= 2;
	}	//	end of WeekViewGetEventBounds


/***********************************************************************
 *
 * FUNCTION:    	AdjustEventRight
 *
 * DESCRIPTION:	Shifts a full-width appt rect to the right side of 
 *						the event bar.  If the event bar is odd-width, we
 *						will put the smaller portion on the right.
 *
 * PARAMETERS:		RectanglePtr	event
 *
 * RETURNED:		Nothing; event is adjusted.
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	10/5/95		initial version
 *
 ***********************************************************************/
static void AdjustEventRight (RectanglePtr event)
	{
	short				oldWidth;

	//	Make the bar an extra pix narrower to accomodate it's frame.
	oldWidth = event->extent.x;
	event->extent.x = oldWidth / 2 - 1;
	event->topLeft.x += (oldWidth - event->extent.x);
	}	//	end of AdjustEventRight


/***********************************************************************
 *
 * FUNCTION:    	AdjustEventLeft
 *
 * DESCRIPTION:	Shifts a full-width appt rect to the left side of 
 *						the event bar.  If the event bar is odd-width, the
 *						smaller half of the bar goes on the right.
 *
 * PARAMETERS:		RectanglePtr	event
 *
 * RETURNED:		Nothing; event is adjusted.
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	10/5/95		initial version
 *
 ***********************************************************************/
static void AdjustEventLeft (RectanglePtr event)
	{
	//	Make the bar an extra pix narrower to accomodate the frame.
	event->extent.x = event->extent.x - (event->extent.x / 2) - 1;
	}	//	end of AdjustEventLeft


/***********************************************************************
 *
 * FUNCTION:    	UpdateEndTime
 *
 * DESCRIPTION:	Compares the passed time with the passed endTime.  If the
 *						time is later than the endTime, the endTime will be
 *						advanced to the earlier of either the time or the 
 *						timeLimit.
 *
 * PARAMETERS:		TimeType				*time - time to compare
 *						TimeType				*endTime - time to update
 *						Word					timeLimit - cannot advance *endTime
 *												past this hour value.
 *
 * RETURNED:		Nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	10/5/95		initial version
 *
 ***********************************************************************/
static void UpdateEndTime (TimeType *time, TimeType *endTime,
									Word timeLimit)
	{
	if (TimeToInt(*time) > TimeToInt (*endTime))
		{
		if (time->hours >= timeLimit)
			{
			endTime->hours = timeLimit;
			endTime->minutes = 0;
			}
		else
			{
			endTime->hours = time->hours;
			endTime->minutes = time->minutes;
			}
		}
	}	//	end of UpdateEndTime


/***********************************************************************
 *
 * FUNCTION:    	WeekViewDayDrawAppts
 *
 * DESCRIPTION:	Draws the passed appt list within the passed 
 *						RectangleType.  This should only be called when there
 *						is a non-0 number of events and a non-0 apptsH handle.
 *
 * PARAMETERS:		VoidHand				apptsH - handle of mem chunk containing
 *												the ApptInfoPtr (list).
 *						Word					numAppts - number of entries in apptsH.
 *						RectanglePtr		r - the day's current event bar; this
 *													includes the top & bottom frame area.
 *													The width is set correctly for frame
 *													drawing over the existing frame, or
 *													rect-filling within the existing frame.
 *						Word					startHour - first displayed hour of the
 *												event bar.
 *						Word					endHour - end of the event bar.
 *						Word					hourHeight - vertical size of an hour-long
 *													event.
 *
 * RETURNED:		Nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/4/95		Initial Revision
 *			kcr	10/4/95		Draw overlapped events side-by-side
 *
 ***********************************************************************/
static void WeekViewDayDrawAppts (VoidHand apptsH, Word numAppts,
											 RectanglePtr r, Word startHour,
											 Word endHour, Word hourHeight)
	{
	ApptInfoPtr				appts;
	Boolean					overlapOnLeft;
	CustomPatternType		origPattern;
 	int						i;
 	RectangleType			apptRect;
 	TimeType					lastEndTimeLeft, lastEndTimeRight;

	appts = MemHandleLock (apptsH); 
	lastEndTimeLeft.hours = 0;
	lastEndTimeLeft.minutes = 0;
	lastEndTimeRight.hours = 0;
	lastEndTimeRight.minutes = 0;
	WinGetPattern(origPattern);
	WinSetPattern(regAppt);

	for (i = 0; i < numAppts; i++)
		{
		//	Only display timed appts.
		if (appts[i].startTime.hours == (unsigned char) apptNoTime)
			continue;
		//	Don't display events which end <= startHour
		if (appts[i].endTime.hours < startHour ||
			 (appts[i].endTime.hours == startHour &&
			  appts[i].endTime.minutes == 0))
			continue;
		//	Don't display events which start >= endHour
		if (appts[i].startTime.hours >= endHour)
			continue;

		//	Check for overlap with previous appts on both sides:
		if (((appts[i].startTime.hours < lastEndTimeLeft.hours) ||
			  ((appts[i].startTime.hours == lastEndTimeLeft.hours) &&
			   (appts[i].startTime.minutes < lastEndTimeLeft.minutes))) &&
			 ((appts[i].startTime.hours < lastEndTimeRight.hours) ||
			  ((appts[i].startTime.hours == lastEndTimeRight.hours) &&
			   (appts[i].startTime.minutes < lastEndTimeRight.minutes))))
			{
			//	Overlapping appts need to be drawn in two parts - the overlapping
			//	part and the non-overlapping part, if any.
			apptRect = *r;

			//	Select side on which to overlap the bars:
			if (TimeToInt (lastEndTimeLeft) > TimeToInt (lastEndTimeRight))
				overlapOnLeft = false;
			else
				overlapOnLeft = true;

			//	The overlap area ends at the earlier of the appropriate
			//	lastEndTime or the appt's endTime.
			if (overlapOnLeft &&
				 (TimeToInt(appts[i].endTime) > TimeToInt (lastEndTimeLeft)))
				WeekViewGetEventBounds (appts[i].startTime, lastEndTimeLeft,
												startHour, endHour, &apptRect,
												hourHeight);
			else if (!overlapOnLeft &&
						(TimeToInt(appts[i].endTime) > TimeToInt (lastEndTimeRight)))
				WeekViewGetEventBounds (appts[i].startTime, lastEndTimeRight,
												startHour, endHour, &apptRect,
												hourHeight);
			else
				WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
												startHour, endHour, &apptRect,
												hourHeight);

			//	Select side to overlap
			if (!overlapOnLeft)
				AdjustEventRight (&apptRect);
			else
				AdjustEventLeft (&apptRect);

			WinSetPattern(overLapAppt);
			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			WinSetPattern(regAppt);
			
			//	Now do the non-overlapping part.
			if ((overlapOnLeft &&
				  TimeToInt(appts[i].endTime) <= TimeToInt (lastEndTimeLeft)) ||
				 (!overlapOnLeft &&
				  TimeToInt(appts[i].endTime) <= TimeToInt (lastEndTimeRight)))
				continue;			//	No non-overlapping part
			apptRect = *r;
			if (overlapOnLeft)
				{
				WeekViewGetEventBounds (lastEndTimeLeft, appts[i].endTime,
												startHour, endHour, &apptRect,
												hourHeight);
				AdjustEventLeft (&apptRect);
				UpdateEndTime (&(appts[i].endTime), &lastEndTimeLeft, endHour);
				}
			else
				{
				WeekViewGetEventBounds (lastEndTimeRight, appts[i].endTime,
												startHour, endHour, &apptRect,
												hourHeight);
				AdjustEventRight (&apptRect);
				UpdateEndTime (&(appts[i].endTime), &lastEndTimeRight, endHour);
				}

			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			
			}	//	end of if <overlapping appt>

		//	Check for overlap with left side only:
		else if ((appts[i].startTime.hours < lastEndTimeLeft.hours) ||
					((appts[i].startTime.hours == lastEndTimeLeft.hours) &&
					 (appts[i].startTime.minutes < lastEndTimeLeft.minutes)))
			{	//	draw non-overlapping appt on right side; update right end time
			apptRect = *r;							//	Use pre-calculated x & y coords.
			WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
											startHour, endHour, &apptRect,
											hourHeight);
			AdjustEventRight (&apptRect);

			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			UpdateEndTime (&(appts[i].endTime), &lastEndTimeRight, endHour);
			}
			   
		//	Check for overlap with right side only:
		else if ((appts[i].startTime.hours < lastEndTimeRight.hours) ||
					((appts[i].startTime.hours == lastEndTimeRight.hours) &&
					 (appts[i].startTime.minutes < lastEndTimeRight.minutes)))
			{	//	draw non-overlapping appt on left side; update left end time
			apptRect = *r;							//	Use pre-calculated x & y coords.
			WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
											startHour, endHour, &apptRect,
											hourHeight);
			AdjustEventLeft (&apptRect);

			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			UpdateEndTime (&(appts[i].endTime), &lastEndTimeLeft, endHour);
			}

		//	Appt does not overlap previous appt - check for overlap with
		//	next appt.
		else if (((i + 1) < numAppts) &&
					((appts[i+1].startTime.hours < appts[i].endTime.hours) ||
					 ((appts[i+1].startTime.hours == appts[i].endTime.hours) &&
					  (appts[i+1].startTime.minutes < appts[i].endTime.minutes))))
			{	//	draw non-overlapping appt on left side; update left end time.
			apptRect = *r;							//	Use pre-calculated x & y coords.
			WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
											startHour, endHour, &apptRect,
											hourHeight);
			AdjustEventLeft (&apptRect);

			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			UpdateEndTime (&(appts[i].endTime), &lastEndTimeLeft, endHour);
			}	//	end of if <overlapping next appt>

		else	//	Appt does not overlap previous appts:
			{	//	Draw full width appt; update both left & right end times.
			apptRect = *r;							//	Use pre-calculated x & y coords.
			WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
											startHour, endHour, &apptRect,
											hourHeight);

			WinFillRectangle(&apptRect, 0);
			WinDrawRectangleFrame(simpleFrame, &apptRect);
			UpdateEndTime (&(appts[i].endTime), &lastEndTimeLeft, endHour);
			UpdateEndTime (&(appts[i].endTime), &lastEndTimeRight, endHour);
			}	//	end of if <non-overlapping appt>

		}	//	end of for <each appt in day>
		

	//	Clean up after drawing events
	MemPtrUnlock(appts);
	WinSetPattern(origPattern);
	
	}	//	end of WeekViewDayDrawAppts
		

/***********************************************************************
 *
 * FUNCTION:    WeekViewCreateEventBar
 *
 * DESCRIPTION:	This routine calculates the area of a given day's
 *						event bar.
 *
 * PARAMETERS:		RectanglePtr		day - full day's bounds
 *						RectanglePtr		r - points to rect to be filled with
 *													event bar's coords.  The resulting
 *													bar does not include the frame around
 *													it.  The top & bottom of the frame
 *													should be added before this is passed
 *													to GetEventBounds
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/10/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewCreateEventBar (RectanglePtr day, RectanglePtr r)
	{
 	//	NOTE: since this is a framed event bar, the bounds of the bar must
 	//	be shrunk 1 pix on top & sides to keep the frame (drawn outside of passed
 	//	rect) within the bounds.  This is only nesc because we are using 
 	//	a frame around the event bar.
 	r->topLeft.x = day->topLeft.x + weekViewDayHMargin + 1;
 	r->topLeft.y = day->topLeft.y +
 						weekViewDayDisplayHeight +
 						weekViewDateDisplayHeight + 1;
 	r->extent.x = day->extent.x - 2*weekViewDayHMargin - 1;
 	r->extent.y = day->extent.y -
 						weekViewDayDisplayHeight -
 						weekViewDateDisplayHeight - 1;
 	}	//	end of WeekViewCreateEventBar
 					

/***********************************************************************
 *
 * FUNCTION:    WeekViewDayDraw
 *
 * DESCRIPTION:	This routine draws a passed DayObject structure.
 *
 * PARAMETERS:		DayType				*day - the day to draw
 *						Word					startHour - first displayed hour of the
 *												day
 *						Word					endHour - end of event bar display
 *						Word					hourHeight - vertical size of hour-long
 *													event
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	7/31/95		Initial Revision
 *			kcr	10/3/95		remove frame around whole day.
 *			kcr	10/13/95		don't draw days which are outside of date range
 *
 ***********************************************************************/
static void WeekViewDayDraw (DayType *day, Word startHour, Word endHour,
									  Word hourHeight)
 	{
 	RectangleType			r;

	//	Only draw days which are in range.
	if (day->date.day == outOfRangeDay)
		return;

 	//	Use day bounds to create event bar bounds
 	WeekViewCreateEventBar (&(day->bounds), &r);

 	//	Draw the appointments - including overlaps.  The current appointment
 	//	is highlighted specially.  Only show portions of events which fall
 	//	between startHour & endHour.
	if (day->numAppts != 0)
		{
		//	Pass event bar to the event drawing routine, including the top &
		//	bottom frame areas.
		r.topLeft.y--;
		r.extent.y += 2;
		WeekViewDayDrawAppts (day->apptsH, day->numAppts, &r, startHour,
									 endHour, hourHeight);
 		}
  	}	//	end of WeekViewDayDraw


/***********************************************************************
 *
 * FUNCTION:    WeekViewInitDays
 *
 * DESCRIPTION:	Check the data of the days in the current week and
 *						extend the week's time range if nesc.  Assumes the
 *						week has already been initialized.
 *
 *						This routine is performing all of the heavy data access
 *						work, so that the screen can be drawn quickly without
 *						the burden of the database.
 *
 * PARAMETERS:  FormPtr			frm - The currently active (WeekView) form
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	11/13/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewInitDays (FormPtr frm)
	{
 	int					i, skipFirstDays = 0, skipLastDays = 0;
 	RectangleType		dayBounds;
	short					dayWidth;
 	WeekType				*week;
	UInt 					counts[daysInWeek];
	VoidHand 			apptLists[daysInWeek];

 	ErrFatalDisplayIf(!WeekObjectH, "Unallocated Week View object");
	week = MemHandleLock (WeekObjectH);

 	//	Initialize the days:
 	dayWidth = (week->bounds.extent.x - weekViewTimeDisplayWidth) / daysInWeek;
 	dayBounds.topLeft.x = week->bounds.topLeft.x + weekViewTimeDisplayWidth;
 	dayBounds.topLeft.y = week->bounds.topLeft.y;
 	dayBounds.extent.x = dayWidth;
 	dayBounds.extent.y = week->hourHeight * weekViewNumDispHours +
 								weekViewDayDisplayHeight +
 								weekViewDateDisplayHeight;


	// Get all the appointments in the week.
	ApptGetAppointmentsFar (ApptDB, week->startDate, daysInWeek, 
		apptLists, counts);

 	for (i = 0; i < daysInWeek; i++)
 		{
 		WeekViewDayInit(&(week->days[i]),
 							 (i + StartDayOfWeek) % daysInWeek,
 							 &dayBounds,
 							 &(week->firstEventHour),
 							 &(week->lastEventHour),
 							 apptLists[i], counts[i]);

 		dayBounds.topLeft.x += dayWidth;					//	Next day bounds
 		}

 	//	Initailize scroll controls
	WeekViewUpdateScrollers(frm);

 	MemPtrUnlock (week);
	}	//	end of WeekViewInitDays


/***********************************************************************
 *
 * 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	7/15/96	Initial Revision
 *			scl	3/11/97	added dfMYMedNoPost for French 2.0 ROM
 *
 ***********************************************************************/
static void WeekViewSetTitle (WeekType * week)
{
	Int	i;
	Char	title[3*longDateStrLength];
	Char	tempTitle[longDateStrLength];;

 	//	Set the title of the form to be the non-localized month/year date of the
 	//	StartDayOfWeek.  The format shall be "Mmm 'YY - Mmm 'YY", or
 	//	"Mmm - Mmm 'YY" if the year is the same, or "Mmm 'YY" if the month
 	//	is the same.
#if COUNTRY == COUNTRY_FRANCE		// French folks don't like "'" ('97)
 	DateToAscii (week->startDate.month, week->startDate.day,
 					 week->startDate.year + firstYear, dfMYMedNoPost,  title);
#else
 	DateToAscii (week->startDate.month, week->startDate.day,
 					 week->startDate.year + firstYear, dfMYMed,  title);
#endif

 	if ((week->startDate.month != week->days[daysInWeek-1].date.month) &&
 		 (week->days[daysInWeek-1].date.day != outOfRangeDay))
 		{	//	If months of first & last days of week differ, and the
 			//	end of the date range was not encountered.
#if COUNTRY == COUNTRY_FRANCE		// French folks don't like "'" ('97)
 		DateToAscii (week->days[daysInWeek-1].date.month,
 						 week->days[daysInWeek-1].date.day,
 						 week->days[daysInWeek-1].date.year + firstYear,
 						 dfMYMedNoPost, tempTitle);
#else
 		DateToAscii (week->days[daysInWeek-1].date.month,
 						 week->days[daysInWeek-1].date.day,
 						 week->days[daysInWeek-1].date.year + firstYear,
 						 dfMYMed, tempTitle);
#endif
 		if (week->startDate.year == week->days[daysInWeek-1].date.year)
 			{	// "m - m 'yy" format instead of "m 'y - m 'y"
 			for (i = StrLen (title) - 1; title[i] != ' '; i--)
 				;
 			title[i] = '\0';
 			}
 		StrCat (title, " - ");
 		StrCat (title, tempTitle);
 		}
	FrmCopyTitle (FrmGetActiveForm (), title);

	TimeDisplayed = false;
}


/***********************************************************************
 *
 * FUNCTION:    WeekViewInit
 *
 * DESCRIPTION:	This routine initializes the structures used for the
 *						WeekView.  The start date will be set and the start
 *						and end of the display range will be set.
 *
 * PARAMETERS:  FormPtr			frm - The currently active (WeekView) form
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	7/27/95		Initial Revision
 *			kcr	10/4/95		New title date format
 *			kcr	10/9/95		Make sure lastEventHour does not get adjusted past
 *									midnight. Bug #260.
 *			kcr	10/12/95		handle beginning of date range & end of date
 *									range.
 *
 ***********************************************************************/
static void WeekViewInit (FormPtr frm)
 	{
 	int					i, skipFirstDays = 0, skipLastDays = 0;
 	DateType				tempDate;
 	WeekType				*week;
 	Word 					len;
	Word					index;
 	Word					startDay;
 	Word					weekNumber;
	CharPtr				weeekNumberStr;

 	//	Allocate currWeek object & day objects
 	WeekObjectH = MemHandleNew (sizeof (WeekType));
 	ErrFatalDisplayIf(!WeekObjectH, "Allocation error");
	week = MemHandleLock (WeekObjectH);

 	//	Set bounds of WeekView
	index  = FrmGetObjectIndex (frm, WeekDayDisplay);
	FrmGetObjectBounds (frm, index, &(week->bounds));
	week->bounds.extent.x -= weekHMargin;

 	//	Determine the start date for this week based on the current 'Date' and
 	//	the StartDayOfWeek
 	week->startDate.year = Date.year;
 	week->startDate.month = Date.month;
 	week->startDate.day = Date.day;

 	startDay = DayOfWeek (Date.month, Date.day, Date.year+firstYear);
 																//	Current day of week
 	//	Adjust startDate backwards to previous occurrance of StartDayOfWeek
 	if (startDay > StartDayOfWeek)
 		DateAdjust (&(week->startDate), - ((Long) (startDay - StartDayOfWeek)));
 	else if (StartDayOfWeek > startDay)
 		DateAdjust (&(week->startDate),
 								- ((Long)(startDay + daysInWeek - StartDayOfWeek)));


 	//	Make sure we have not run into the start of the legal date
 	//	range.  If this has happened, we will skip the
 	//	dates betweeen the StartDayOfWeek and the beginning of the legal
 	//	date range.
	if ((week->startDate.year == 0) &&
		 (week->startDate.month == 1) &&
		 (week->startDate.day == 1))
		{
		startDay = DayOfWeek (1, 1, firstYear);
		if (startDay > StartDayOfWeek)
			skipFirstDays = startDay - StartDayOfWeek;
		else if (StartDayOfWeek > startDay)
			skipFirstDays = daysInWeek + startDay - StartDayOfWeek;
		}
	//	Make sure we have not run into the end of the legal date
	//	range.  If this happens, we will skip the days between the
	//	end of the date range and the week->startDate+daysInWeek.
	else if ((week->startDate.year == numberOfYears - 1) &&
				(week->startDate.month == 12) &&
				(week->startDate.day > (31 - (daysInWeek - 1))))
		{
		startDay = DayOfWeek (1, 1, lastYear);
		if (startDay >= StartDayOfWeek)
			skipLastDays = daysInWeek - (startDay - StartDayOfWeek) - 1;
		else
			skipLastDays = daysInWeek - (startDay + daysInWeek - StartDayOfWeek)
								- 1;
		}


 	//	week->startDate is now the date of the first instance of 
 	//	StartDayOfWeek <= the current Date.  An exception occurs when
 	//	the beginning of the legal date range has been hit.  In this case,
 	//	week->startDate falls on StartDayOfWeek+skipFirstDays.

 	//	Determine the scrolling range, and the initial displayed time range:
 	//
 	//	These vars hold the elligible scrolling range for the current week.
 	//	The range will be expanded as necessary as the days' events are
 	//	examined.
 	week->firstEventHour = DayStartHour;
 	week->lastEventHour = DayEndHour;

 	//	If range is still less than a screenful, stretch it.  End of display
 	//	may not extend past midnight, however.
 	if ((week->lastEventHour - week->firstEventHour < weekViewNumDispHours) &&
 		 (week->firstEventHour + weekViewNumDispHours > 24))
 		{	//	Have to stretch range at both ends
 		week->lastEventHour = 24;
 		week->firstEventHour = week->lastEventHour - weekViewNumDispHours;
 		}
 	else if (week->lastEventHour - week->firstEventHour < weekViewNumDispHours)
 		week->lastEventHour = week->firstEventHour + weekViewNumDispHours;

 	week->hourHeight = (week->bounds.extent.y -
 								 weekViewDayDisplayHeight -
 								 weekViewDateDisplayHeight) / weekViewNumDispHours;
 	//	The display will initially show all events from the start of the
 	//	user's day range to the end of the vertical screen space.  If there
 	//	is room for more hours of data than the user's day range specified,
 	//	a full screenful will be shown anyway.
 	week->startHour = week->firstEventHour;
 	week->endHour = week->firstEventHour + weekViewNumDispHours;


	//	Set the dates of each day so they can be drawn before initializing the
	//	days.
 	tempDate = week->startDate;
	for (i = 0; i < daysInWeek; i++)
		{
 		if ((i < skipFirstDays) ||
 			 (i >= (daysInWeek - skipLastDays)))
 			{
 			week->days[i].date.day = outOfRangeDay;
 			}
 		else
 			{
			week->days[i].date = tempDate;
 			DateAdjust (&tempDate, 1);						//	Next date
			}
		}

 	//	Set the title of the form
 	WeekViewSetTitle (week);


	// Put the current week number in the week number label.
	weeekNumberStr = FrmGetLabel (frm, WeekNumberLabel);
	weekNumber = GetWeekNumber (Date.month, Date.day, Date.year+firstYear);
	len = StrLen(weeekNumberStr);

#if COUNTRY == COUNTRY_GERMANY	// number appears first

	if (weekNumber < 10) {
		weeekNumberStr [0] = numericSpaceChr;			// (" 5. Woche")
	} else {
		weeekNumberStr [0] = '0' + (weekNumber/10);		// ("14. Woche")
	}
	weeekNumberStr [1] = '0' + (weekNumber%10);

#else							// number appears last

	StrIToA (&weeekNumberStr [len - 2], weekNumber);	// ("Week 14")
	if (weekNumber < 10)
		weeekNumberStr [len - 1] = numericSpaceChr;		// ("Week  5")

#endif

	FrmCopyLabel (frm, WeekNumberLabel, weeekNumberStr);

	// Highlight the Week View push button.
	FrmSetControlGroupSelection (frm, DayViewGroup, WeekWeekViewButton);

 	week->behindDesc = NULL;
 	
 	MemPtrUnlock (week);
 	} //	end of WeekViewInit


/***********************************************************************
 *
 * FUNCTION:    WeekViewFree
 *
 * DESCRIPTION:	This routine is called when the WeekView is being torn
 *						down.  It's primary function is to free allocated
 *						memory.
 *
 * PARAMETERS:  	nothing
 *
 * RETURNED:		nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/9/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewFree (void)
 	{
 	int					i;
 	WeekType				*week;
 	
	WeekEraseDescription (true);

	week = MemHandleLock (WeekObjectH);
	//	Close each day structure
	for (i = 0; i < daysInWeek; i++)
		WeekViewDayClose (&(week->days[i]));
		
	//	Free WeekType obj.
	MemHandleFree (WeekObjectH);
 	}	//	end of WeekViewFree


/***********************************************************************
 *
 * FUNCTION:    WeekViewShowTime
 *
 * 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 WeekViewShowTime (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:    WeekViewHideTime
 *
 * DESCRIPTION: If the title of the Week 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 WeekViewHideTime (Boolean hide)
{
	WeekPtr 	week;

	if (TimeDisplayed)
		{
		if (hide || (TimGetTicks () >= TimeDisplayTick))
			{
			week = MemHandleLock (WeekObjectH);
			WeekViewSetTitle (week);
			MemPtrUnlock (week);
			
			}
		else
			{
			EvtSetNullEventTick (TimeDisplayTick);
			}
		}
}


/***********************************************************************
 *
 * FUNCTION:     WeekViewDayLabels
 *
 * DESCRIPTION:  Draw the day of week and day number labels along the 
 *					  top of the week view display.
 *
 * PARAMETERS:	  week - pointer the week object (WeekType)
 *
 * RETURNED:     nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			art	4/23/96		Initial Revision
 *
 ***********************************************************************/
static void WeekViewDayLabels (WeekType *week)
	{
	Int				i;
 	Char				dateStr[3];				//	temp storage for string 
 													//	representing the date number.
	Byte 				dayOfWeek;
	Short				x, y;
	Short				dayWidth;
	Short				labelWidth;
	FontID 			origFont;
 	CharPtr			dayLabels;
	DayType 			*day;
 	DateTimeType	today;
	

	origFont = FntGetFont();

	// Get the resource that contains the first letter of each day.
 	dayLabels = MemHandleLock (DmGetResource (strRsc, daysOfWeekInitialsStrID));

	// Get today's date.
 	TimSecondsToDateTime(TimGetSeconds(), &today);

 	dayWidth = (week->bounds.extent.x - weekViewTimeDisplayWidth) / daysInWeek;
 	x = week->bounds.topLeft.x + weekViewTimeDisplayWidth;
 	y = week->bounds.topLeft.y;

 	for (i = 0; i < daysInWeek; i++)
 		{
		day = &(week->days[i]);

		//	Only draw days which are in range.
		if (day->date.day == outOfRangeDay)
			break;
			
	 	//	If this day's date matches the system date, then we will use
	 	//	boldFont to draw the day & date labels.
	 	if (day->date.year+firstYear == today.year &&
	 		 day->date.month == today.month &&
	 		 day->date.day == today.day)
	 		FntSetFont (boldFont);
	 	else
	 		FntSetFont (stdFont);
	 	
	 	//	Draw the day labels over the centers of the bars:
		dayOfWeek = (i + StartDayOfWeek) % daysInWeek;
	 	labelWidth = FntCharWidth (dayLabels[dayOfWeek]);
	 	WinDrawChars (&dayLabels[dayOfWeek],
	 					  1,
	 					  x + (dayWidth - labelWidth)/2+1,
	 					  y);
	 	
	 	//	Draw the date labels under the day labels:
	 	StrIToA (dateStr, day->date.day);
	 	labelWidth = FntCharsWidth (dateStr, StrLen(dateStr));
	 	WinDrawChars (dateStr,
	 					  StrLen(dateStr),
	 					  x + (dayWidth - labelWidth)/2+1,
	 					  y + weekViewDayDisplayHeight);

		x += dayWidth;
		}

	MemPtrUnlock (dayLabels);
	
 	//	Restore the original font
 	FntSetFont (origFont);
	}
	

/***********************************************************************
 *
 * FUNCTION:    WeekViewDrawTimes
 *
 * DESCRIPTION:	Draw the time markers down the left-hand edge of 
 *						the week view display.
 *
 * PARAMETERS:		short			startYPos - Y position of first hour marker
 *						Word			startHour - first hour marker to draw
 *						Word			endHour - end of display range; may or may not
 *											be the last visible marker.
 *						Word			hourHeight - vertical size of an hour-long event.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	8/8/95		Initial Revision
 *			kcr	10/3/95		include minutes in times; right justify times.
 *
 ***********************************************************************/
static void WeekViewDrawTimes (short startYPos, Word startHour, Word endHour,
										 Word hourHeight)
	{
 	char					hourStr[timeStringLength];	//	Holds string representing
 																//	hours.
	int					j;
 	short					hourWidth, hourYPos;
 	Word					nextHour;

 	hourYPos = startYPos - FntLineHeight() / 2;

	for (nextHour = startHour;
		  nextHour < endHour;
		  nextHour += weekViewHourDisplayInterval,
		  hourYPos += hourHeight*weekViewHourDisplayInterval)
		{
		TimeToAscii (nextHour, 0, TimeFormat, hourStr);
		if (!Use24HourFormat(TimeFormat))
			{	//	If we are using the 12-hour/Am/Pm format, strip off the
				//	trailing am/pm
			for (j = 0; hourStr[j] != ' ' && j < timeStringLength; j++)
				;
			hourStr[j] = '\0';
			}
		hourWidth = FntCharsWidth (hourStr, StrLen (hourStr));
		WinDrawChars (hourStr,
	 					  StrLen (hourStr),
	 					  weekViewTimeDisplayWidth - timeHMargin - hourWidth,
						  hourYPos);
		}	//	end of for <each hour marker>

	}	//	end of WeekViewDrawTimes


/***********************************************************************
 *
 * FUNCTION:    WeekViewDraw
 *
 * DESCRIPTION:	This routine draws the background for the WeekView - the
 *						dotted lines, the hour markers, and then draws each
 *						day.
 *
 * PARAMETERS:  FormPtr			frm - The currently active (WeekView) form
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	7/27/95		Initial Revision
 *			kcr	8/8/95		can draw starting on odd or even hours
 *			kcr	10/3/95		draw frame around all day bars; dividing lines
 *									between days.
 *			kcr	11/13/95		break out day-drawing to another routine
 *
 ***********************************************************************/
static void WeekViewDraw (FormPtr frm)
 	{
 	Int					i;
 	Short					x;
 	Short					dayWidth;
 	RectangleType		r;
 	short					lineYPos;
 	WeekType				*week;
 	Word					dispStartHour;

	week = MemHandleLock (WeekObjectH);

	//	Determine where start of backround is:
 	lineYPos = week->bounds.topLeft.y +
 						 weekViewDayDisplayHeight +
 						 weekViewDateDisplayHeight;
 	dispStartHour = week->startHour;
 	
	//	Draw frame around whole day-area.  Cut rect down by one pix on each
	//	side so frame will be in week area, not outside.
	r.topLeft.x = week->bounds.topLeft.x + weekViewTimeDisplayWidth + 1;
	r.topLeft.y = lineYPos + 1;		//	Want frame to be on line, not outside.
	r.extent.x = week->bounds.extent.x - weekViewTimeDisplayWidth - 2;
	r.extent.y = weekViewNumDispHours * week->hourHeight - 1;
	WinDrawRectangleFrame (simpleFrame, &r);

 	//	Draw background (solid lines).
 	x = week->bounds.topLeft.x + weekViewTimeDisplayWidth;
 	dayWidth = (week->bounds.extent.x - weekViewTimeDisplayWidth) / daysInWeek;
 	for (i = 1; i < daysInWeek; i++)
 		{
 		x += dayWidth;
 		WinDrawLine (x, r.topLeft.y, x, r.topLeft.y + r.extent.y);
		}

	//	Adjust start hour for times & lines to be on a display interval.
 	while ((dispStartHour % weekViewHourDisplayInterval) != 0)
 		{	//	Display starts on an odd hour
 		lineYPos += week->hourHeight;
 		dispStartHour++;
 		}

	// Draw the day numbers and doy of week labels.
	WeekViewDayLabels (week);

 	//	Draw times
 	WeekViewDrawTimes (lineYPos, dispStartHour, week->endHour, week->hourHeight);

 	//	Draw background (dotted lines).  The dotted lines are drawn at
 	//	specific hour intervals from the top of the bar area to the end of
 	//	the hour display.
 	//	Lines will not be drawn for the first & last hours - the frame should
 	//	include this.
 	if (week->startHour == dispStartHour)
 		{
 		lineYPos += week->hourHeight*weekViewHourDisplayInterval;
 		dispStartHour += weekViewHourDisplayInterval;
 		}
 	for (;
 		  dispStartHour < week->endHour;
 		  dispStartHour += weekViewHourDisplayInterval)
 		{
 		WinDrawGrayLine (week->bounds.topLeft.x + weekViewTimeDisplayWidth + 1,
 						 	  lineYPos,
 						 	  week->bounds.topLeft.x + week->bounds.extent.x - 2,
 						 	  lineYPos);

		//	Position of next line
 		lineYPos += week->hourHeight*weekViewHourDisplayInterval;
  		}	//	end of for <each hour interval>


 	MemPtrUnlock (week);
 	} //	end of WeekViewDraw
 	

/***********************************************************************
 *
 * FUNCTION:    WeekViewDrawDays
 *
 * DESCRIPTION:	This routine draws each
 *						day.  This should be called after WeekViewInitDays.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	11/13/95		Initial Revision
 *
 ***********************************************************************/
static void WeekViewDrawDays (void)
	{
	int	i;
 	WeekType				*week;
	
	week = MemHandleLock (WeekObjectH);

	for (i = 0; i < daysInWeek; i++)
 		{
		/*
 		if (i != 0)
 			WinDrawLine (week->days[i].bounds.topLeft.x,
 							 week->days[i].bounds.topLeft.y +
 						 		weekViewDayDisplayHeight +
 						 		weekViewDateDisplayHeight,
 							 week->days[i].bounds.topLeft.x,
 							 week->days[i].bounds.topLeft.y +
 							 	week->days[i].bounds.extent.y);
 		*/

 		WeekViewDayDraw(&(week->days[i]), week->startHour, week->endHour,
 						 week->hourHeight);
		}

 	MemPtrUnlock (week);
	}	//	end of WeekViewDrawDays


/***********************************************************************
 *
 * FUNCTION:    WeekViewEraseDay
 *
 * DESCRIPTION:  This routine erase the appointment on the specified day.
 *
 * PARAMETERS:  day  - day of the week
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			art	4/16/96		Initial Revision
 *
 ***********************************************************************/
static void WeekViewEraseDay (WeekType *week, Int dayOfWeek)
	{
	RectangleType dayR;
	
	dayR = week->days[dayOfWeek].bounds;
	dayR.topLeft.x += 1;
	dayR.extent.x -= 1;
	dayR.topLeft.y += weekViewDayDisplayHeight + weekViewDateDisplayHeight + 1;
	dayR.extent.y -= weekViewDayDisplayHeight + weekViewDateDisplayHeight + 1;
	WinEraseRectangle (&dayR, 0);
	}


/***********************************************************************
 *
 * FUNCTION:    WeekEraseDescription
 *
 * DESCRIPTION: This routine will will erase the description
 *              popup if been visible.
 *
 * PARAMETERS:  eraseIt - true to always erase, false erase only if
 *                        to popup has been display for the require
 *                        length of time.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/7/96	Initial Revision
 *
 ***********************************************************************/
static void WeekEraseDescription (Boolean eraseIt)
	{
 	WeekType	*week;
		
	week = MemHandleLock (WeekObjectH);
	
	if (week->behindDesc)
		{
		if ((eraseIt) || (TimGetTicks () >= week->descTick))
			{
			WinRestoreBits (week->behindDesc, 0, 0);
			week->behindDesc = NULL;
			}
		else
			{
			EvtSetNullEventTick (week->descTick);
			}
		}

 	MemPtrUnlock (week);
}

/***********************************************************************
 *
 * FUNCTION:    WeekEraseDescription
 *
 * DESCRIPTION: This routine returns true if the piont passed is within
 *              the bounds if an appointment description popup.
 *
 * PARAMETERS:  x, y - pen location
 *
 * RETURNED:    true if point is in description popup.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/15/96	Initial Revision
 *
 ***********************************************************************/
static Boolean WeekViewPointInDescription (Short x, Short y)
	{
 	WeekType	*week;
	Boolean inDesc = false;
	WinHandle win;
	RectangleType r;
	
	week = MemHandleLock (WeekObjectH);
	
	if (week->behindDesc)
		{
		win = WinSetDrawWindow (week->behindDesc);		
		r.topLeft.x = 0;
		r.topLeft.y = 0;
		WinGetWindowExtent (&r.extent.x, &r.extent.y);
		WinSetDrawWindow (win);

		inDesc = RctPtInRectangle (x, y, &r);
		}

 	MemPtrUnlock (week);

	return (inDesc);
	}


/***********************************************************************
 *
 * FUNCTION:    WeekViewSelectEvent
 *
 * DESCRIPTION:  This routine draws the selection highlight around and 
 *               move the event.
 *
 * PARAMETERS:  week
 *              dayOfWeek
 *              event
 *              recordNum
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			art	3/29/96		Initial Revision
 *
 ***********************************************************************/
static void WeekViewSelectEvent (WeekType *week, Int dayOfWeek, 
	 EventPtr event, Word recordNum)

	{
	Int					i;
	Int					newDayOfWeek;
	Int					savedDayOfWeek;
	Word					error;
	Word					hourHeight;
	Short					x, y;
	Short 				posInDay;
	Short					posInAppt;
	Boolean 				moving = false;
	Boolean				penDown = true;
	Boolean				moved;
	Boolean				sameTime;
	Boolean				sameDate;
	TimeType 			newStart, timeDiff;
	TimeType	 			start, end;
	DateType				date;
	WinHandle 			savedBits;
	WinHandle			bitsBehindDesc;
	VoidHand				recordH;
	RectangleType		moveR, dayR, weekR, eventR;
	FrameBitsType		eventFrame;
	ApptDBRecordType	apptRec;

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

	start = apptRec.when->startTime;
	end = apptRec.when->endTime;
	date = week->days[dayOfWeek].date;
	TimeDifference (&end, &start, &timeDiff);

	moveR.topLeft.x = event->screenX - moveThreshold;
	moveR.topLeft.y = event->screenY - moveThreshold;
	moveR.extent.x = moveThreshold << 1;
	moveR.extent.y = moveThreshold << 1;
	
	dayR = week->days[dayOfWeek].bounds;
 	dayR.topLeft.y += weekViewDayDisplayHeight + weekViewDateDisplayHeight;
 	dayR.extent.y -= weekViewDayDisplayHeight + weekViewDateDisplayHeight;

	weekR = week->bounds;
	weekR.topLeft.x = week->days[0].bounds.topLeft.x;
	weekR.extent.x = week->days[0].bounds.extent.x * daysInWeek;
 	weekR.topLeft.y += weekViewDayDisplayHeight + weekViewDateDisplayHeight;
 	weekR.extent.y = week->hourHeight * weekViewNumDispHours;

	hourHeight = week->hourHeight;

	eventFrame.word = 0;
	eventFrame.bits.width = weekViewEventFrameWidth;

	newDayOfWeek = dayOfWeek;
	savedDayOfWeek = dayOfWeek;

	// Compute the bounds of the event.
	WeekViewCreateEventBar (&(week->days[dayOfWeek].bounds), &eventR);
	eventR.topLeft.y--;		//	Include the top & bottom of frame in bar
	eventR.extent.y += 2;
	WeekViewGetEventBounds (start, end, week->startHour, week->endHour, 
								   &eventR, hourHeight);
	// Highlight the event.
	RctInsetRectangle (&eventR, -weekViewEventFrameWidth);
	savedBits = WinSaveBits (&eventR, &error);
	RctInsetRectangle (&eventR, weekViewEventFrameWidth);
	WinDrawRectangleFrame (eventFrame.word, &eventR);

	// Draw the event description, time, and date.
	bitsBehindDesc = WeekViewDrawDescription (
									&apptRec.when->startTime,
									&apptRec.when->endTime,
									&date,
									apptRec.description,
									true);

	posInAppt = event->screenY - dayR.topLeft.y - 
					((start.hours - week->startHour) * hourHeight) -
					((start.minutes * hourHeight) / hoursInMinutes);		
	do 
		{
		PenGetPoint (&x, &y, &penDown);

		// The pen must be move pass a threshold before we will start
		// moving the event.  This threshold is greater than the distance
		// that would normally be traveled to move an event.
		if (! moving)
			{
			if (RctPtInRectangle (x, y, &moveR)) continue;
			moving = true;
			}
			
		// If we're moved outside the bound of the week, highlight to 
		// original event again.
		if (! RctPtInRectangle (x, y, &weekR))
			{
			if ((TimeToInt (start) == TimeToInt(apptRec.when->startTime)) && 
				 (DateToInt (date) == DateToInt(week->days[dayOfWeek].date)))
				continue;
			start = apptRec.when->startTime;
			end = apptRec.when->endTime;
			dayOfWeek = savedDayOfWeek;
			date = week->days[dayOfWeek].date;
			}
			
		// Have we moved the event to another day.
		else if (! RctPtInRectangle (x, y, &dayR))
			{
			for (newDayOfWeek = 0; newDayOfWeek < daysInWeek; newDayOfWeek++)
				{
				if (RctPtInRectangle (x, y, &week->days[newDayOfWeek].bounds))
					break;
				}
			dayR = week->days[newDayOfWeek].bounds;
		 	dayR.topLeft.y += weekViewDayDisplayHeight + weekViewDateDisplayHeight;
 			dayR.extent.y -= weekViewDayDisplayHeight + weekViewDateDisplayHeight;

			date = week->days[savedDayOfWeek].date;
			DateAdjust (&date, (long)newDayOfWeek - (long)savedDayOfWeek);
			}
		

		// Based on the position of the pen compute the time of the event.
		if (RctPtInRectangle (x, y, &weekR))
			{
			// Rounded the y coordinate to an even value,  this is done to
			// reduce the bounding of the selection highlight caused by 
			// digitizor.
			posInDay = week->startHour * hourHeight + 
				((y & (~1)) - dayR.topLeft.y - posInAppt);
			if (posInDay < 0) posInDay = 0;
			newStart.hours = (posInDay / hourHeight);
			newStart.minutes =  (2 * (posInDay % hourHeight) / 
				hourHeight) * (hoursInMinutes / 2);


			if (TimeToInt (start) == TimeToInt(newStart) && 
				 newDayOfWeek == dayOfWeek)
				continue;
			
			if (week->days[newDayOfWeek].date.day != outOfRangeDay)
				{
			dayOfWeek = newDayOfWeek;

			// The start time has changed so update the end time.
			start = newStart;
			end.hours = start.hours + timeDiff.hours;
			end.minutes = start.minutes + timeDiff.minutes;
			if (end.minutes >= hoursInMinutes)
				{
				end.hours++;
				end.minutes -= hoursInMinutes;
				}
			if (end.hours > maxHours)
				{
				end.hours = maxHours;
				end.minutes = maxMinutes;
				}
			}

			// We've move passed the last valid day (12/31/1931)
			else
				{
				if ((TimeToInt (start) == TimeToInt(apptRec.when->startTime)) && 
					 (DateToInt (date) == DateToInt(week->days[dayOfWeek].date)))
					continue;
				start = apptRec.when->startTime;
				end = apptRec.when->endTime;
				dayOfWeek = savedDayOfWeek;
				date = week->days[dayOfWeek].date;
				}
			}

		
		// Unhighlight the current selection.
		WinRestoreBits (savedBits, 
							 eventR.topLeft.x - weekViewEventFrameWidth,
							 eventR.topLeft.y - weekViewEventFrameWidth);
				
		WeekViewCreateEventBar (&(week->days[dayOfWeek].bounds), &eventR);
		eventR.topLeft.y--;		//	Include the top & bottom of frame in bar
		eventR.extent.y += 2;
		WeekViewGetEventBounds (start, end, week->startHour, week->endHour,
					                &eventR, hourHeight);
		// Highlight the event.
		RctInsetRectangle (&eventR, -weekViewEventFrameWidth);
		savedBits = WinSaveBits (&eventR, &error);
		RctInsetRectangle (&eventR, weekViewEventFrameWidth);
		WinDrawRectangleFrame (eventFrame.word, &eventR);
		
		// Draw the new date and time.
		WeekViewDrawDescription (&start, &end, &date, NULL, false);

		} while (penDown);

	WinRestoreBits (savedBits, 
						 eventR.topLeft.x - weekViewEventFrameWidth,
						 eventR.topLeft.y - weekViewEventFrameWidth);
						 


	// Check if the date or time of the appointment has been changed.
	sameTime = ((TimeToInt(start) == TimeToInt(apptRec.when->startTime)) &&
		         (TimeToInt(end) == TimeToInt(apptRec.when->endTime)));
	sameDate = (DateToInt(date) == DateToInt(week->days[savedDayOfWeek].date));

	MemHandleUnlock (recordH);
	

	// If the time hasn't been changed leave the description popup display
	// for a short period of time.
	if (sameTime && sameDate) 
		{
		week->descTick = TimGetTicks () + weekDescDisplayTicks;
		week->behindDesc = bitsBehindDesc;
		EvtSetNullEventTick (week->descTick);
		return;
		}

	WinRestoreBits (bitsBehindDesc, 0, 0);

	
	// If the date or time was changed move the appointment and redraw the view.
	// If only the time have changed then split the event into two event.
	MoveEventFar (&recordNum, start, end, date, sameDate, &moved);
	if (moved)
		{
		ApptGetRecordFar (ApptDB, recordNum, &apptRec, &recordH);
		MemHandleUnlock (recordH);

		if (apptRec.repeat)
			{
			for (i = 0; i < daysInWeek; i++)
				WeekViewEraseDay (week, i);
			}
		else
			{
			WeekViewEraseDay (week, dayOfWeek);
			WeekViewEraseDay (week, savedDayOfWeek);
			}
		WeekViewDraw (FrmGetActiveForm ());

		for (i = 0; i < daysInWeek; i++)
			WeekViewDayClose (&(week->days[i]));
		WeekViewInitDays (FrmGetActiveForm());
		WeekViewDrawDays ();
		WeekViewDrawDataMarks ();
		}
	}



/***********************************************************************
 *
 * FUNCTION:    WeekViewDayHandleSelection
 *
 * DESCRIPTION:	This routine is called when a pen down event occurs in
 *						a week object.  This routine will check to see if 
 *						the pen-down occurred within the passed day and track
 *						the pen until it is released.
 *
 * PARAMETERS:		DayType			*day
 *						EventPtr			event
 *						Word				startHour - current starting hour of event
 *												display.
 *						Word				endHour - current ending hour of event display
 *						Word				hourHeight - current vertical size of an hour
 *
 * RETURNED:    	Boolean			true if this day contained the passed
 *												event/point and handled it.  False if
 *												the event/point was outside this day.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	8/9/95	Initial Revision
 *			kcr	8/18/95	invert day/date area instead of framing
 *			kcr	10/13/95	don't handle points if day is out of date range.
 *
 ***********************************************************************/
static Boolean WeekViewDayHandleSelection (WeekType *week, Int dayOfWeek, 
	EventPtr event)

	{
	DayType *			day;
	Word					startHour;
	Word					endHour;
	Word					hourHeight;
	ApptInfoPtr			appts;
	Boolean				apptSelected;
	Boolean				invertHighlight = true;
	FrameBitsType		eventFrame;
	int					i;
	short					x, y;
	TimeType				newStart, newEnd;
	Word					error;
	Word					recordNum;
	WinHandle			savedBits;
	Boolean				newAppt = false;
	Boolean				penDown = true;
	Boolean				selected = true;
	RectangleType		pickR, saveR, highR;			//	pickR is the picking area,
																//	highR is the highlighted
																//		region
																//	saveR is the saved window
																//		(framed highlights only)

	day = &week->days[dayOfWeek];
	
	startHour = week->startHour;
	endHour = week->endHour;
	hourHeight = week->hourHeight;


	//	If this is the wrong day, give up
	if (! RctPtInRectangle (event->screenX, event->screenY, &(day->bounds)))
		return (false);
		
	//	If this day is out of the day range, and therefore inelligible for
	//	events, skip it:
	if (day->date.day == outOfRangeDay)
		return (true);
		
	//	Determine the part of the day that is selected:
	//	1.	Day/Date - go to day
	//	2.	single appt. - go to day, edit existing event
	//	3.	empty appt. slot - go to day edit new event

	//	NOTE: we are sometimes using different rectangles for picking &
	//	drawing highlights.  This is so that we can give the user as wide a
	//	margin for picking error as possible.
	
	apptSelected = false;
	Date = day->date;
	if (event->screenY <= (day->bounds.topLeft.y + weekViewDayDisplayHeight +
								  weekViewDateDisplayHeight))
		{	//	Day/Date is selected - highlight day/date
		pickR = day->bounds;
		pickR.extent.y = weekViewDayDisplayHeight + weekViewDateDisplayHeight;
		highR = pickR;
		highR.topLeft.x += weekViewDayHMargin-1;
		highR.extent.x -= 2*(weekViewDayHMargin-1);
		//	no saveR needed for this case
		}
	else
		{	//	Check through all appts
		if (day->numAppts != 0)
			appts = MemHandleLock (day->apptsH); 

		for (i = day->numAppts -1; i >= 0; i--)
			{
			//	Get the bounds of each appointment and check selected point
			//	against them.  We traverse the list from bottom to top
			//	so that we will find the event with the latest start time
			//	in the event of event overlap.
		 	WeekViewCreateEventBar (&(day->bounds), &highR);
			highR.topLeft.y--;		//	Include the top & bottom of frame in bar
			highR.extent.y += 2;
			WeekViewGetEventBounds (appts[i].startTime, appts[i].endTime,
											startHour, endHour,
											&highR, hourHeight);
			pickR = highR;
			pickR.topLeft.x = day->bounds.topLeft.x;
			pickR.extent.x = day->bounds.extent.x;
			pickR.topLeft.y--;
			pickR.extent.y += 2;			//	Include top & bottom of frame in pick
												//	area.
			if (RctPtInRectangle (event->screenX, event->screenY, &pickR))
				{
				apptSelected = true;
				recordNum = appts[i].recordNum;
				break;
				}
			}
		if (i >= day->numAppts)
			{	
			//	New appt has been selected.  Convert y-coord of pt to
			//	time of new appt & visible region of new appt.
			newStart.hours = (event->screenY -
									day->bounds.topLeft.y -
									weekViewDayDisplayHeight -
									weekViewDateDisplayHeight) / hourHeight;
			newStart.hours += startHour;
			newStart.minutes = 0;
			
			newEnd = newStart;
			newEnd.hours++;
			
		 	WeekViewCreateEventBar (&(day->bounds), &highR);
			highR.topLeft.y--;		//	Include the top & bottom of frame in bar
			highR.extent.y += 2;
			WeekViewGetEventBounds (newStart, newEnd,
											startHour, endHour,
											&highR, hourHeight);
			pickR = highR;
			pickR.topLeft.x = day->bounds.topLeft.x;
			pickR.extent.x = day->bounds.extent.x;
			pickR.topLeft.y--;
			pickR.extent.y += 2;			//	Include top & bottom of frame in pick
												//	area.
			
			newAppt = true;
			}

		if (day->numAppts != 0)
			MemPtrUnlock(appts);
		
		invertHighlight = false;
		}	//	end of else <pt in event bar>

	// Draw the date, time and description of the apointment.
	if (apptSelected)
		{
		WeekViewHideTime (true);
		WeekViewSelectEvent (week, dayOfWeek, event, recordNum);
		return (true);
		}


	//	Handle all of the fancy dragging & highlighting:
	//	If invertHighlight, then highlight the selection by inverting the
	//	rectangle; else, highlight by drawing a frame.
	saveR = highR;
	if (!invertHighlight)
		{
		eventFrame.word = 0;
		eventFrame.bits.width = weekViewEventFrameWidth;
		//	Expand the drawR to include the frame:
		saveR.topLeft.x -= weekViewEventFrameWidth;
		saveR.topLeft.y -= weekViewEventFrameWidth;
		saveR.extent.x += 2*weekViewEventFrameWidth;
		saveR.extent.y += 2*weekViewEventFrameWidth;

		savedBits = WinSaveBits (&saveR, &error);
		WinDrawRectangleFrame (eventFrame.word, &highR);
		}
	else	//	inverting
		{
		WinInvertRectangle (&highR, 0);
		}


	do 
		{
		PenGetPoint (&x, &y, &penDown);

		if (RctPtInRectangle (x, y, &pickR))
			{
			if (! selected)
				{
				if (! invertHighlight)
					{
					savedBits = WinSaveBits (&saveR, &error);
					WinDrawRectangleFrame (eventFrame.word, &highR);
					}
				else
					WinInvertRectangle (&highR, 0);

				selected = true;
				}
			}

		else if (selected)
			{
			if (! invertHighlight)
				WinRestoreBits (savedBits, saveR.topLeft.x, saveR.topLeft.y);
			else
				WinInvertRectangle (&highR, 0);
				
			selected = false;
			}

		} while (penDown);
		

	if (selected)
		{
		if (!invertHighlight)
			WinRestoreBits (savedBits, saveR.topLeft.x, saveR.topLeft.y);
		
		if (newAppt)
			WeekViewNewAppointment (&newStart, &newEnd);
		FrmGotoForm (DayView);
		}

	return (true);
	}	//	end of WeekViewDayHandleSelection
	

/***********************************************************************
 *
 * FUNCTION:		WeekViewGotoDate
 *
 * DESCRIPTION:	This routine dispay the date picker so that the 
 *						user can select a week to navigate to.  If the date
 *						picker is confirmed, the week containing the
 *						day selected is displayed.
 *
 *						This routine is called when a "go to" button is pressed.
 *              
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	9/19/95	Initial Revision
 *			kcr	9/19/95	navigates to a week instead of a day.
 *			kcr	10/5/95	preserve font around calls to DatePicker
 *
 ***********************************************************************/
static void WeekViewGotoDate (void)
	{
	CharPtr title;
	FontID	origFont;
	VoidHand titleH;
	SWord month, day, year;

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

	day = Date.day;
	month = Date.month;
	year = Date.year + firstYear;

	// Display the date picker.
	origFont = FntGetFont ();
	if (SelectDay (selectDayByWeek, &month, &day, &year, title))
		{
		FntSetFont (origFont);
		Date.day = day;
		Date.month = month;
		Date.year = year - firstYear;

		WeekViewGoToWeek ();
		}
	else
		FntSetFont (origFont);
	MemHandleUnlock (titleH);
	}


/***********************************************************************
 *
 * FUNCTION:    WeekViewGotoToday
 *
 * DESCRIPTION: This routine navigates to today in the day view.
 *
 *              This routine is called when a "go to" button is pressed.
 *              
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/15/95	Initial Revision
 *
 ***********************************************************************/
static void WeekViewGotoToday (void)
{
	DateTimeType dateTime;
	
	// Get today's date.
	TimSecondsToDateTime (TimGetSeconds (), &dateTime);
	Date.year = dateTime.year - firstYear;
	Date.month = dateTime.month;
	Date.day = dateTime.day;

	FrmGotoForm (DayView);
}


/***********************************************************************
 *
 * FUNCTION:    WeekViewDoCommand
 *
 * DESCRIPTION: This routine performs the menu command specified.
 *
 * PARAMETERS:  command  - menu item id
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/10/95	Initial Revision
 *
 ***********************************************************************/
static void WeekViewDoCommand (Word command)
{

	switch (command)
		{
		case WeekGetInfoCmd:
			AbtShowAbout (sysFileCDatebook);
			break;
						
		case WeekPreferencesCmd:			
			FrmPopupForm (PreferencesDialog);
			break;
		}
}


/***********************************************************************
 *
 * FUNCTION:    WeekViewHandleSelection
 *
 * DESCRIPTION: This routine is called when a pen down event occurs in
 *              a week object.  This routine will track
 *              the pen until it is released.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			kcr	8/9/95	Initial Revision
 *
 ***********************************************************************/
static Boolean WeekViewHandleSelection (EventPtr event)
	{
	int					i;
 	WeekType				*week;
		
	week = MemHandleLock (WeekObjectH);
	
	if (!RctPtInRectangle (event->screenX, event->screenY, &(week->bounds)))
		{
		MemPtrUnlock (week);
		return (false);
		}
		
	//	Let each day have a crack at the event until one handles it
	for (i = 0; i < daysInWeek; i++)
		{
		if (WeekViewDayHandleSelection (week, i, event))
			break;
		}
			
 	MemPtrUnlock (week);
	return (true);
}


/***********************************************************************
 *
 * FUNCTION:		WeekViewUpdateDisplay
 *
 * DESCRIPTION:	Update the Week View display according to the passed
 *						updateCode.
 *
 * PARAMETERS:		Word				updateCode - indicates which changes have
 *												been made to the view.
 *
 * RETURNED:		nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			kcr	10/9/95		initial version
 *
 ***********************************************************************/
static void WeekViewUpdateDisplay (Word updateCode)
	{
	if (updateCode & updateDisplayOptsChanged)
		{	//	Start & end times have changed
		WeekViewGoToWeek ();
		}
		
	else if (updateCode & frmRedrawUpdateCode)
		{
		FrmDrawForm (FrmGetActiveForm ());
		WeekViewDraw (FrmGetActiveForm ());
		WeekViewDrawDays ();
		WeekViewDrawDataMarks ();
		}

	}	//	end of WeekViewUpdateDisplay


/***********************************************************************
 *
 * FUNCTION:    WeekViewHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the "Week View"
 *              of the Datebook application.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handle and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			art	7/24/95		Initial Revision
 *			kcr	8/21/95		added prev & next week buttons
 *			kcr	9/19/95		added handler for 'Day' button
 *			kcr	10/2/95		changed prev & next week buttons to repeat.
 *
 ***********************************************************************/
Boolean WeekViewHandleEvent (EventPtr event)
	{
	FormPtr frm;
	DateType date;
	Boolean handled = false;

	if (event->eType == ctlSelectEvent)
		{
		switch (event->data.ctlSelect.controlID)
			{
			case WeekGoToButton:
				WeekViewGotoDate ();
				handled = true;
				break;

			case WeekDayViewButton:
				//	'Date' var should already be set.
				//	This can only happen when navigating from week to week,
				//	with prev/next arrows, or when navigating with the date
				//	picker.
				FrmGotoForm (DayView);
				handled = true;
				break;

			case WeekMonthViewButton:
				//	'Date' var should already be set.
				//	This can only happen when navigating from week to week,
				//	with prev/next arrows, or when navigating with the date
				//	picker.
				FrmGotoForm (MonthView);
				handled = true;
				break;

			}
		}

	// Handle the repeating scroll controls.  NOTE: it
	//	is important not to 'handle' repeating controls so
	//	that the next event will be generated correctly.
	else if (event->eType == ctlRepeatEvent)
		{
		switch (event->data.ctlRepeat.controlID)
			{
			case WeekUpButton:
				WeekViewScroll (up, false);
				break;
				
			case WeekDownButton:
				WeekViewScroll (down, false);
				break;

			case WeekPrevButton:
				DateAdjust (&Date, -daysInWeek);
				WeekViewGoToWeek ();
				break;
			
			case WeekNextButton:
				DateAdjust (&Date, daysInWeek);
				WeekViewGoToWeek ();
				break;

			}
		}


	else if (event->eType == penDownEvent)
		{
		handled = WeekViewPointInDescription (event->screenX, event->screenY);
		WeekEraseDescription (true);
		if (! handled)
			handled = WeekViewHandleSelection (event);
		EventInWeekView = true;
		}


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

		// Datebook key pressed? Only the Datebook button will reach this
		//	point.
		if (ChrIsHardKey(event->data.keyDown.chr))
			{	
			DateSecondsToDate (TimGetSeconds (), &date);
			Date = date;
			if (EventInWeekView ||
				(event->data.keyDown.modifiers & poweredOnKeyMask))
				FrmGotoForm (DayView);
			else
				FrmGotoForm (MonthView);				
			handled = true;
			}
		else if (event->data.keyDown.chr == pageUpChr)
			{
			DateAdjust (&Date, -daysInWeek);
			WeekViewGoToWeek ();
			handled = true;
			}	
		else if (event->data.keyDown.chr == pageDownChr)
			{
			DateAdjust (&Date, daysInWeek);
			WeekViewGoToWeek ();
			handled = true;
			}
		EventInWeekView = true;
		}


	else if (event->eType == menuEvent)
		{
		WeekViewDoCommand (event->data.menu.itemID);
		return (true);
		}


	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		OrigFont = FntSetFont (stdFont);
		WeekViewInit (frm);
		FrmDrawForm (frm);
		WeekViewDraw (frm);

		WeekViewInitDays (frm);
		WeekViewDrawDays ();
		WeekViewDrawDataMarks ();
		EventInWeekView = false;
		handled = true;
		}

	else if (event->eType == frmUpdateEvent)
		{
		WeekViewUpdateDisplay (event->data.frmUpdate.updateCode);
		handled = true;
		}

	else if (event->eType == frmCloseEvent)
		{
		WeekViewFree ();
		FntSetFont (OrigFont);
		}
		
	else if (event->eType == frmTitleEnterEvent)
		{
		// If the pen is in the title toggle between the current date
		// and the current time.
		if (TimeDisplayed)
			WeekViewHideTime (true);
		else
			WeekViewShowTime ();
		}

	else if (event->eType == frmTitleSelectEvent)
		{
		// Cause a null event to be sent in a few seconds so that we can
		// toggle back to displaying the date.
		if (TimeDisplayed)
			{
			TimeDisplayTick = TimGetTicks () + timeDisplayTicks;
			EvtSetNullEventTick (TimeDisplayTick);
			}
		}

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

	return (handled);
	}	//	end of WeekViewHandleEvent


