/***********************************************************************
 *
 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 main module.  This module
 *   starts the application, dispatches events, and stops
 *   the application.
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			???		????		Initial Revision
 *			frigino	970909	Added alarmSoundUniqueRecID to DatebookPreferenceType
 *									to remember the alarm sound to play. Moved
 *									DatebookPreferenceType out of this file.
 *
 **********************************************************************/

#include <Pilot.h>
#include <Graffiti.h>
#include <SysEvtMgr.h>

#define	NON_PORTABLE
#include <MemoryPrv.h>

#include "Datebook.h"

extern ECApptDBValidate (DmOpenRef dbP);


/***********************************************************************
 *
 *	Global variables, declarded in DateGlobals.c.  Because of a bug in
 *  the Metrowerks compiler, we must compile the globals separately with
 *	 PC-relative strings turned off.
 *
 ***********************************************************************/
extern	VoidHand				ApptsH;
extern	Word					NumAppts;
extern	VoidHand				ApptsOnlyH;
extern	Word					NumApptsOnly;

extern	Word					TopVisibleAppt;
extern	Boolean				HideSecretRecords;				// true if serect records are hidden
extern	Word					PendingUpdate;						// code of pending day view update


// The following global variables are used to keep track of the edit
// state of the application.
extern 	Word					CurrentRecord;						// record being edited
extern 	Boolean				ItemSelected;						// true if a day view item is selected
extern 	Word					DayEditPosition;					// position of the insertion point in the desc field
extern	Word					DayEditSelectionLength;			// length of the current selection.
extern	Boolean				RecordDirty;						// true if a record has been modified


// The following global variable are only valid while editng the detail
// of an appointment.
extern	VoidHand				DetailsH;
extern	DateType				RepeatEndDate;
extern	RepeatType			RepeatingEventType;
extern	Word					RepeatStartOfWeek;				// status of Repeat Dialog.

extern	Word					TimeBarColumns;					// Number of columns of time bars.

// Multisegment stuff
Handle gPlugInResH;					// handle to our (locked) plug-in resource
PlugInMainF	*gPlugInResP;				// pointer to our (locked) plug-in resource
DmOpenRef gPlugInDbRef;					// reference to plug-in database

// The following structure is used by the details dialog to hold
// changes made to an appointment record.
typedef struct {
	Boolean					secret;
	ApptDateTimeType		when;
	AlarmInfoType 			alarm;
	RepeatInfoType 		repeat;
} DetailsType;

typedef DetailsType * DetailsPtr;

/***********************************************************************
 *
 *	Internal Functions
 *
 ***********************************************************************/
static void FrmCloseAllForms (void);

static void DayViewLoadTable (void);

static void DayViewLayoutDay (Boolean retieve);

static Boolean ClearEditState (void);

static void DayViewDrawTimeBars (void);

static DWord	DBPilotMain (Word cmd, Ptr cmdPBP, Word launchFlags);

static Word DayViewGetDescriptionHeight (Int apptIndex, Word width, Word maxHeight,
	WordPtr iconsWidthP, FontID * fontIdP);

static void DayViewInitRow (TablePtr table, Word row, Word apptIndex, 
	short rowHeight, ULong uniqueID, Word iconsWidth, FontID fontID);

static Err RomVersionCompatible (DWord requiredVersion, Word launchFlags);


/***********************************************************************
 *
 *	Test Code
 *
 ***********************************************************************/

// Useful structure field offset and size macros
#define prvFieldOffset(type, field)		((DWord)(&((type*)0)->field))
#define prvFieldSize(type, field)		(sizeof(((type*)0)->field))


/***********************************************************************
 *
 * FUNCTION:    PilotMain
 *
 * DESCRIPTION: This is the main entry point for the Datebook
 *              application.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95		Initial Revision
 *
 ***********************************************************************/
// Note: We need to create a branch island to PilotMain in order to successfully
//  link this application for the device.
DWord	PilotMain (Word cmd, Ptr cmdPBP, Word launchFlags)
{
	return DBPilotMain(cmd, cmdPBP, launchFlags);
}


/***********************************************************************
 *
 * FUNCTION:     MultiSegmentStart
 *
 * DESCRIPTION:  Connect up the other segments.
 *
 * PARAMETERS:   nothing
 *
 * RETURNED:     Err value 0 if nothing went wrong
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static Err MultiSegmentStart(DmOpenRef *plugInDbRef, Handle *plugInResHP, PlugInMainF **plugInResPP)
{
	// The following code will locate our plug-in resource (which may be in our own
	// resource file or in a separate PRC file to be opened by type and creator as
	// demonstrated below).  Note that when building a (Mac) Simulator application,
	// we skip all of this and simply link to the plug-in directly for easier debugging.
	
#if EMULATION_LEVEL == EMULATION_NONE		// When building for the handheld...
    {
		DmSearchStateType		searchState;
		UInt 						tempCardNo;
		Boolean		newSearch = true;
		LocalID		tempPlugInDbID = 0;
		Err			theErr = 0;
	

		// The following code could be modified to iterate through
		// multiple (separate) plug-in database(s), if desired...
		theErr = DmGetNextDatabaseByTypeCreator(newSearch, &searchState, sysFileTApplication, 
					 sysFileCDatebook, false /* all versions */, &tempCardNo, &tempPlugInDbID);

		if (theErr) {								// no plug-in database found
		
			tempPlugInDbID = 0;
			gPlugInDbRef = 0;

		} else {										// we found a plug-in database
		
			if (tempPlugInDbID) {				// open the plug-in database
				*plugInDbRef = DmOpenDatabase(tempCardNo, tempPlugInDbID, dmModeReadOnly);
			}

		}


		// Get a handle to our plug-in resource
		*plugInResHP = DmGetResource(sysResTAppCode, 2);
	
		// Make sure we found it
		if (!*plugInResHP) {
			return 1;
		}
	
		// Lock down the plug-in so it doesn't move
		**plugInResPP = (PlugInMainF *) MemHandleLock(*plugInResHP);
    }

#else		// When building a (Mac) Simulator app, direct linking makes debugging easier.

	**plugInResPP = (PlugInMainF *) &PlugIn1Main;

#endif


   return 0;
}


/***********************************************************************
 *
 * FUNCTION:    MultiSegmentStop
 *
 * DESCRIPTION: Undo the multisegment stuff.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static void MultiSegmentStop(DmOpenRef *plugInDbRefP, Handle *plugInResHP, PlugInMainF **plugInResPP)
{
#if EMULATION_LEVEL == EMULATION_NONE		// When building for the handheld...
	// Release our plug-in
	if (**plugInResPP) {
		// Unlock the plug-in resource
		MemHandleUnlock(*plugInResHP);

		// Release the plug-in resource
		DmReleaseResource(*plugInResHP);
		
		**plugInResPP = NULL;
	}
	
	// If we opened a separate plug-in database, close it now
	if (*plugInDbRefP) {
		DmCloseDatabase(*plugInDbRefP);
		*plugInDbRefP = NULL;
	}
#endif

}


#if EMULATION_LEVEL == EMULATION_NONE		// When building for the handheld...
	// At this point, we have a pointer to our plug-in code.
	// The following code illustrates how we might call the plug-in.
extern void DateSendRecord (DmOpenRef dbP, Int recordNum)
{
	myPlugInParamBlockType	plugInParamBlock;
	DWord							result;
	plugInParamBlock.call = DateSendRecordCall;				// parameter to pass to plug-in
	plugInParamBlock.params.dsr.dbP = dbP;						// parameter to pass to plug-in
	plugInParamBlock.params.dsr.recordNum = recordNum;		// parameter to pass to plug-in
	result = (*gPlugInResP) (&plugInParamBlock);	// call plug-in
	
	return;
}	

static Err DateReceiveDataFar(PlugInMainF *plugInResP, DmOpenRef dbP, ExgSocketPtr exgSocketP)
{
	myPlugInParamBlockType	plugInParamBlock;
	DWord							result;

	plugInParamBlock.call = DateReceiveDataCall;				// parameter to pass to plug-in
	plugInParamBlock.params.drd.dbP = dbP;						// parameter to pass to plug-in
	plugInParamBlock.params.drd.exgSocketP = exgSocketP;	// parameter to pass to plug-in
	result = (**plugInResP) (&plugInParamBlock);	// call plug-in
	
	return (Err) result;
}	

#else

static Err DateReceiveDataFar(PlugInMainF *plugInResP, DmOpenRef dbP, ExgSocketPtr exgSocketP)
{
	return DateReceiveData(dbP, exgSocketP);
}

#endif


/***********************************************************************
 *
 * FUNCTION:     DateGetDatabase
 *
 * DESCRIPTION:  Get the application's database.  Open the database if it
 * exists, create it if neccessary.
 *
 * PARAMETERS:   *dbPP - pointer to a database ref (DmOpenRef) to be set
 *					  mode - how to open the database (dmModeReadWrite)
 *
 * RETURNED:     Err - zero if no error, else the error
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			roger		12/3/97	Initial Revision
 *
 ***********************************************************************/
static Err DateGetDatabase (DmOpenRef *dbPP, UInt mode)
{
	Err error = 0;
	DmOpenRef dbP;
	UInt cardNo;
	LocalID dbID;
	Word attributes;
	
	
	*dbPP = 0;
	dbP = DmOpenDatabaseByTypeCreator(datebookDBType, sysFileCDatebook, mode);
	if (! dbP)
		{
		error = DmCreateDatabase (0, datebookDBName, sysFileCDatebook,
								datebookDBType, false);
		if (error) return error;
		
		dbP = DmOpenDatabaseByTypeCreator(datebookDBType, sysFileCDatebook, mode);
		if (! dbP) return ~0;

		// Set the backup bit.  This is to aid syncs with non Palm software.
		DmOpenDatabaseInfo(dbP, &dbID, NULL, NULL, &cardNo, NULL);
		DmDatabaseInfo(cardNo, dbID, NULL, &attributes, NULL, NULL,
					NULL, NULL, NULL, NULL, NULL, NULL, NULL);
		attributes |= dmHdrAttrBackup;
		DmSetDatabaseInfo(cardNo, dbID, NULL, &attributes, NULL, NULL,
					NULL, NULL, NULL, NULL, NULL, NULL, NULL);
		
		error = ApptAppInfoInit (dbP);
      if (error) 
      	{
      	DmCloseDatabase(dbP);
      	DmDeleteDatabase(cardNo, dbID);
         return error;
         }
		}
	
	*dbPP = dbP;
	return 0;
}


/***********************************************************************
 *
 * FUNCTION:     StartApplication
 *
 * DESCRIPTION:  This routine opens the application's database, loads the 
 *               saved-state information and initializes global variables.
 *
 * PARAMETERS:   nothing
 *
 * RETURNED:     nothing
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			art		6/12/95	Initial Revision
 *			trm		8/5/97	adds variable alarm sound settings
 *			frigino	9/9/97	Add AlarmSoundUniqueRecID initialization
 *			vmk		12/9/97	Call DatebookLoadPrefs() to load and fixup prefs
 *
 ***********************************************************************/
static Word StartApplication (void)
{
	Err err = 0;
	UInt mode;
	DateTimeType dateTime;
	DatebookPreferenceType prefs;
	SystemPreferencesType sysPrefs;
	SWord prefsVersion;
	
	
	MultiSegmentStart(&gPlugInDbRef, &gPlugInResH, &gPlugInResP);
	
	// Determime if secert record should be shown.
	PrefGetPreferences (&sysPrefs);
	HideSecretRecords = sysPrefs.hideSecretRecords;
	

	// Get the time formats from the system preferences.
	TimeFormat = sysPrefs.timeFormat;

	// Get the date formats from the system preferences.
	LongDateFormat = sysPrefs.longDateFormat;
	ShortDateFormat = sysPrefs.dateFormat;

	// Get the starting day of the week from the system preferences.
	StartDayOfWeek = sysPrefs.weekStartDay;
	

	// Get today's date.
	TimSecondsToDateTime (TimGetSeconds (), &dateTime);
	Date.year = dateTime.year - firstYear;
	Date.month = dateTime.month;
	Date.day = dateTime.day;


	// Find the application's data file.  If it don't exist create it.
	if (HideSecretRecords)
		mode = dmModeReadWrite;
	else
		mode = dmModeReadWrite | dmModeShowSecret;
	err = DateGetDatabase (&ApptDB, mode);
	if (err)	return err;
	
	
	// Read the preferences / saved-state information (will fix up incompatible versions).
	prefsVersion = DatebookLoadPrefs (&prefs);
	DayStartHour = prefs.dayStartHour;
	DayEndHour = prefs.dayEndHour;
	AlarmPreset = prefs.alarmPreset;
	NoteFont = prefs.noteFont;
	SaveBackup = prefs.saveBackup;
	ShowTimeBars = prefs.showTimeBars;
	CompressDayView = prefs.compressDayView;
	ShowTimedAppts = prefs.showTimedAppts;
	ShowUntimedAppts = prefs.showUntimedAppts;
	ShowDailyRepeatingAppts = prefs.showDailyRepeatingAppts;
	
	AlarmSoundRepeatCount = prefs.alarmSoundRepeatCount;
	AlarmSoundRepeatInterval = prefs.alarmSoundRepeatInterval;
	AlarmSoundUniqueRecID = prefs.alarmSoundUniqueRecID;
	ApptDescFont = prefs.apptDescFont;

	// The first time this app starts register to handle vCard data.
	if (prefsVersion != datebookPrefsVersionNum)
		ExgRegisterData(sysFileCDatebook, exgRegExtensionID, "vcs");
   

	TopVisibleAppt = 0;
	CurrentRecord = noRecordSelected;	
	

	// Laod the far call jump table.
	FarCalls.apptGetAppointments = ApptGetAppointments;
	FarCalls.apptGetRecord = ApptGetRecord;
	FarCalls.apptFindFirst = ApptFindFirst;
	FarCalls.apptNextRepeat = ApptNextRepeat;
	FarCalls.apptNewRecord = ApptNewRecord;
	FarCalls.moveEvent = MoveEvent;
	FarCalls.preferencesHandleEvent = PreferencesHandleEvent;
 	FarCalls.alarmReset = AlarmReset;
 	FarCalls.rescheduleAlarms = RescheduleAlarms;
 	FarCalls.displayAlarm = DisplayAlarm;

	return 0;
}


/***********************************************************************
 *
 * FUNCTION:    StopApplication
 *
 * DESCRIPTION: This routine closes the application's database
 *              and saves the current state of the application.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			art		6/12/95		Initial Revision
 *			trm		8/5/97		adds variable alarm sound settings
 *			frigino	9/9/97		Add saving of AlarmSoundUniqueRecID
 *			vmk		12/9/97		Call DatebookSavePrefs() to write out the prefs
 *
 ***********************************************************************/
static void StopApplication (void)
{

	DatebookSavePrefs();

	// Send a frmSave event to all the open forms.
	FrmSaveAllForms ();
	
	// Close all the open forms.
	FrmCloseAllForms ();

	// Close the application's data file.
	DmCloseDatabase (ApptDB);
	
	MultiSegmentStop(&gPlugInDbRef, &gPlugInResH, &gPlugInResP);
}


/***********************************************************************
 *
 * FUNCTION:		DatebookLoadPrefs
 *
 * DESCRIPTION:	Loads app's preferences and fixes them up if they didn't exist
 *						or were of the wrong version.
 *
 * PARAMETERS:		prefsP		-- ptr to preferences structure to fill in
 *
 * RETURNED:		the version of preferences from which values were read
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			vmk		12/9/97	Initial version
 *			vmk		12/11/97	Fix up note font
 *
 ***********************************************************************/
SWord DatebookLoadPrefs (DatebookPreferenceType* prefsP)
{
	Word	prefsSize;
	SWord	prefsVersion = noPreferenceFound;
	
	ErrNonFatalDisplayIf(!prefsP, "null prefP arg");
		
	
	// Read the preferences / saved-state information.  Fix-up if no prefs or older/newer version
	prefsSize = sizeof (DatebookPreferenceType);
	prefsVersion = PrefGetAppPreferences (sysFileCDatebook, datebookPrefID, prefsP, &prefsSize, true);
	
	// If the preferences version is from a future release (as can happen when going back
	// and syncing to an older version of the device), treat it the same as "not found" because
	// it could be significantly different
	if ( prefsVersion > datebookPrefsVersionNum )
		prefsVersion = noPreferenceFound;
		
	if ( prefsVersion == noPreferenceFound )
		{
		// Version 1 and 2 preferences
		prefsP->dayStartHour = defaultDayStartHour;
		prefsP->dayEndHour = defaultDayEndHour;
		prefsP->alarmPreset.advance = defaultAlarmPresetAdvance;
		prefsP->alarmPreset.advanceUnit = defaultAlarmPresetUnit;
		prefsP->v20NoteFont = defaultNoteFont;	// 2.0 compatibility (BGT)
		prefsP->saveBackup = defaultSaveBackup;
		prefsP->showTimeBars = defaultShowTimeBars;
		prefsP->compressDayView = defaultCompressDayView;
		prefsP->showTimedAppts = defaultShowTimedAppts;
		prefsP->showUntimedAppts = defaultShowUntimedAppts;
		prefsP->showDailyRepeatingAppts = defaultShowDailyRepeatingAppts;
		}
		
	if ( prefsVersion == noPreferenceFound || prefsVersion < datebookPrefsVersionNum )
		{
		// Version 3 preferences
		prefsP->alarmSoundRepeatCount = defaultAlarmSoundRepeatCount;
		prefsP->alarmSoundRepeatInterval = defaultAlarmSoundRepeatInterval;
		prefsP->alarmSoundUniqueRecID = defaultAlarmSoundUniqueRecID;
		prefsP->apptDescFont = defaultApptDescFont;
		prefsP->noteFont = prefsP->v20NoteFont;	// 2.0 compatibility (BGT)

		// Fix up the note font
		if (prefsP->noteFont == largeFont)
			prefsP->noteFont = largeBoldFont;
		}

	return prefsVersion;
}


/***********************************************************************
 *
 * FUNCTION:    DatebookSavePrefs
 *
 * DESCRIPTION: Saves the current preferences of the application.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * CALLED:	from DatePref.c and Datebook.c
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			vmk		12/9/97	Initial version
 *
 ***********************************************************************/
void DatebookSavePrefs (void)
{
	DatebookPreferenceType prefs;
	

	// Write the preferences / saved-state information.
	prefs.dayStartHour = DayStartHour;
	prefs.dayEndHour = DayEndHour;
	prefs.alarmPreset = AlarmPreset;
	prefs.saveBackup = SaveBackup;
	prefs.showTimeBars = ShowTimeBars;
	prefs.compressDayView = CompressDayView;
	prefs.showTimedAppts = ShowTimedAppts;
	prefs.showUntimedAppts = ShowUntimedAppts;
	prefs.showDailyRepeatingAppts = ShowDailyRepeatingAppts;
	prefs.alarmSoundRepeatCount = AlarmSoundRepeatCount;
	prefs.alarmSoundRepeatInterval = AlarmSoundRepeatInterval;
	prefs.alarmSoundUniqueRecID = AlarmSoundUniqueRecID;
	prefs.apptDescFont = ApptDescFont;
	prefs.noteFont = NoteFont;		

	// Handle 2.0 backwards compatibility for fonts.	(BGT)
	prefs.v20NoteFont = stdFont;


	// Write the state information.
	PrefSetAppPreferences (sysFileCDatebook, datebookPrefID, datebookPrefsVersionNum, 
		&prefs, sizeof (DatebookPreferenceType), true);
}


/***********************************************************************
 *
 * FUNCTION:    InitDatabase
 *
 * DESCRIPTION: This routine initializes the datebook database.
	*
 * PARAMETERS:	 datebase
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	10/19/95	Initial Revision
 *
 ***********************************************************************/
static void InitDatabase (DmOpenRef dbP)
{
	ApptAppInfoInit (dbP);
}


/***********************************************************************
 *
 * FUNCTION:    SyncNotification
 *
 * DESCRIPTION: This routine is called when the datebook database is 
 *              synchronized.  This routine will sort the database
 *              and schedule the next alarm.
 *
 * PARAMETERS:	 nothing
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/6/95	Initial Revision
 *
 ***********************************************************************/
static void SyncNotification (void)
{
	Err err = 0;
	UInt mode;
	DmOpenRef dbP;

	// Find the application's data file.
	mode = dmModeReadWrite;
	dbP = DmOpenDatabaseByTypeCreator(datebookDBType, sysFileCDatebook, mode);
	if (!dbP) return;

	// Resort the appointment database.
	ApptSort (dbP);
	
	// Reschedule the next alarm.
	RescheduleAlarms (dbP);

	DmCloseDatabase (dbP);
}

/***********************************************************************
 *
 * FUNCTION:    SearchDraw
 *
 * DESCRIPTION: This routine draws the description, date, and time of
 *              an appointment found by the text search routine.
 *
 * PARAMETERS:	 apptRecP - pointer to an appointment record.
 *              x        - draw position
 *              y        - draw position
 *              width    - maximum width to draw.
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/18/95	Initial Revision
 *
 ***********************************************************************/
#define maxSearchRepeatDescWidth	100
#define maxSearchDateWidth			42
#define maxSearchTimeWidth			39

static void SearchDraw (ApptDBRecordPtr apptRecP, short x, short y, 
	short width)
{
	Int i;
	Char timeStr [timeStringLength];
	Char dateStr [dateStringLength];
	Word len;
	Word charsToDraw;
	Word ellipseWidth;
	Word maxDescWidth;
	short drawX;
	short maxWidth;
	short titleWidth;
	CharPtr ptr;
	CharPtr desc;
	CharPtr rscP;
	VoidHand rscH;
	SystemPreferencesType sysPrefs;
	
	
	if (apptRecP->repeat)
		maxDescWidth = maxSearchRepeatDescWidth;
	else
		maxDescWidth = width - maxSearchDateWidth - maxSearchTimeWidth;

	// Draw the appointment's desciption.
	desc = apptRecP->description;
	ptr = StrChr (desc, linefeedChr);
	if (ptr)
		{
		charsToDraw = (Word) (ptr - desc);
		titleWidth = FntCharsWidth (desc, charsToDraw);
		if (titleWidth <= maxDescWidth)
			WinDrawChars (desc, charsToDraw, x, y);
		else
			{
			ellipseWidth = FntCharWidth ('.') * 3;
			while (titleWidth + ellipseWidth > maxDescWidth)
				titleWidth -= FntCharWidth (desc[charsToDraw--]);
			WinDrawChars (desc, charsToDraw, x, y);
			WinDrawChars ("...", 3, x+titleWidth, y);
			}
		}
	else
		{
		maxWidth = maxDescWidth - (FntCharWidth ('.') * 3);
		charsToDraw = 0;
		while (true)
			{
			if ( ! desc[charsToDraw]) break;
			maxWidth -= FntCharWidth (desc[charsToDraw]);
			if (maxWidth >= 0)
				charsToDraw++;
			else
				break;
			}
			
		WinDrawChars (desc, charsToDraw, x, y);
		if (maxWidth < 0)
			{
			titleWidth = FntCharsWidth (desc, charsToDraw);
			WinDrawChars ("...", 3, x+titleWidth, y);
			}
		}


	// If the event is repeating, draw the repeat type.
	if (apptRecP->repeat)
		{
		rscH = DmGetResource (strRsc, repeatTypesStrID);
		rscP = MemHandleLock (rscH);
		for (i = 0; i < apptRecP->repeat->repeatType; i++)
			rscP += StrLen(rscP) + 1;
		x += (width - FntCharsWidth (rscP, StrLen (rscP)));		
		WinDrawChars (rscP, StrLen (rscP), x, y);
		MemHandleUnlock (rscH);
		}
		
	// Draw the appointment's date and time.
	else 
		{
		// Get time and date formats for the system preference.
		PrefGetPreferences (&sysPrefs);

		if (TimeToInt (apptRecP->when->startTime) != apptNoTime)
			{
			TimeToAscii (apptRecP->when->startTime.hours, 
				apptRecP->when->startTime.minutes, sysPrefs.timeFormat, timeStr);
			len = StrLen (timeStr);
			drawX = x + (width - FntCharsWidth (timeStr, len));		
			WinDrawChars (timeStr, len, drawX, y);
			}

		DateToAscii (apptRecP->when->date.month, 
				 		 apptRecP->when->date.day, 
				 		 apptRecP->when->date.year + firstYear, 
				 		 sysPrefs.dateFormat, dateStr);
		len = StrLen (dateStr);
		drawX = x + (width - FntCharsWidth (dateStr, len) - maxSearchTimeWidth);		
		WinDrawChars (dateStr, len, drawX, y);
		}
}


/***********************************************************************
 *
 * FUNCTION:    Search
 *
 * DESCRIPTION: This routine searchs the datebook database for records 
 *              containing the string passed. 
 *
 * PARAMETERS:	 findParams - text search parameter block
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/18/95	Initial Revision
 *
 ***********************************************************************/
static void Search (FindParamsPtr findParams)
{
	Err					err;
	UInt 					pos;
	UInt 					cardNo = 0;
	UInt					fieldNum;
	UInt 					recordNum;
	CharPtr 				desc;
	CharPtr 				note;
	CharPtr 				header;
	Boolean 				done;
	Boolean 				match;
	LocalID 				dbID;
	DateType				date;
	VoidHand 			recordH;
	DmOpenRef 			dbP;
	RectangleType 		r;
	ApptDBRecordType	apptRec;
	DmSearchStateType searchInfo;

	// Find the application's data file.
	err =  DmGetNextDatabaseByTypeCreator (true, &searchInfo, datebookDBType, 
		sysFileCDatebook, true, &cardNo, &dbID);
	if (err)
		{
		findParams->more = false;
		return;
		}

	// Open the appointment database.
	dbP = DmOpenDatabase(cardNo, dbID, findParams->dbAccesMode);
	if (! dbP) 
		{
		findParams->more = false;
		return;
		}

	// Display the heading line.
	header = MemHandleLock (DmGetResource (strRsc, findDatebookHeaderStrID));
	FindDrawHeader (findParams, header);
	MemPtrUnlock (header);

	// Search the description and note fields for the "find" string.
	recordNum = findParams->recordNum;
	while (true)
		{
		// Because applications can take a long time to finish a find when
		// the result may be on the screen or for other reasons, users like
		// to be able to stop the find.  Stop the find if an event is pending.
		// This stops if the user does something with the device.  Because
		// this call slows down the search we perform it every so many 
		// records instead of every record.  The response time should still
		// be short without introducing much extra work to the search.
		
		// Note that in the implementation below, if the next 16th record is  
		// secret the check doesn't happen.  Generally this shouldn't be a 
		// problem since if most of the records are secret then the search 
		// won't take long anyways!
		if ((recordNum & 0x000f) == 0 &&			// every 16th record
			EvtSysEventAvail(true))
			{
			// Stop the search process.
			findParams->more = true;
			break;
			}
		
		
		recordH = DmQueryNextInCategory (dbP, &recordNum, dmAllCategories);

		// Have we run out of records?
		if (! recordH)
			{
			findParams->more = false;			
			break;
			}

		ApptGetRecord (dbP, recordNum, &apptRec, &recordH);
		 
		// Search the description field,  if a match is not found search the
		// note field.
		fieldNum = descSeacrchFieldNum;
		desc = apptRec.description;
		match = FindStrInStr (desc, findParams->strToFind, &pos);
		if (! match)
			{
			note = apptRec.note;
			if (note)
				{
				fieldNum = noteSeacrchFieldNum;
				match = FindStrInStr (note, findParams->strToFind, &pos);
				}
			}
		

		// If a match occurred in a repeating event,  make sure there is 
		// a displayable occurrence of the event.
		if (match && apptRec.repeat)
			{
			date = apptRec.when->date;
			match = ApptNextRepeat (&apptRec, &date);
			}

		if (match)
			{
			done = FindSaveMatch (findParams, recordNum, pos, fieldNum, 0, cardNo, dbID);
			if (done) 
				{
				MemHandleUnlock (recordH);
				break;
				}

			// Get the bounds of the region where we will draw the results.
			FindGetLineBounds (findParams, &r);
			
			// Display the appointment info.
			SearchDraw (&apptRec, r.topLeft.x+1, r.topLeft.y, r.extent.x-2);

			findParams->lineNumber++;
			}

		MemHandleUnlock (recordH);
		recordNum++;
		}
		
	DmCloseDatabase (dbP);	
}


/***********************************************************************
 *
 * FUNCTION:    GoToItem
 *
 * DESCRIPTION: This routine is called as the result of hitting the 
 *              "Go to" button in the text search dialog.
 *
 * PARAMETERS:	 goToParams   - where to go to.
 *              launchingApp - true if the application is being launched
 *
 * RETURNED:	 nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/23/95	Initial Revision
 *
 ***********************************************************************/
static void GoToItem (GoToParamsPtr goToParams, Boolean launchingApp)
{
	Word formID;
	Word recordNum;
	EventType event;
	ULong uniqueID;

	recordNum = goToParams->recordNum;

	// If the application is already running, destroy the UI, this may 
	// change the index of record we're going to.
	if (! launchingApp)
		{
		DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL); 
		FrmCloseAllForms ();
		ClearEditState ();
		DmFindRecordByID (ApptDB, uniqueID, &recordNum);
		}
		
	// Go to day view or note view.
	if (goToParams->matchFieldNum == noteSeacrchFieldNum)
		formID = NoteView;
	else
		formID = DayView;

	MemSet (&event, 0, sizeof(EventType));

	// Send an event to load the form we want to goto.
	event.eType = frmLoadEvent;
	event.data.frmLoad.formID = formID;
	EvtAddEventToQueue (&event);
 

	// Send an event to goto a form and select the matching text.
	event.eType = frmGotoEvent;
	event.data.frmGoto.formID = formID;
	event.data.frmGoto.recordNum = recordNum;
	event.data.frmGoto.matchPos = goToParams->matchPos;
	event.data.frmGoto.matchLen = goToParams->searchStrLen;
	event.data.frmGoto.matchFieldNum = goToParams->matchFieldNum;
	EvtAddEventToQueue (&event);
}


/***********************************************************************
 *
 * FUNCTION:    SetDateToNextOccurrence
 *
 * DESCRIPTION: This routine set the "current date" global variable to
 *              the date that the specified record occurs on.  If the
 *              record is a repeating appointmnet, we set the date to 
 *              the next occurrence of the appointment.  If we are beyond
 *              the end date of the repeating appointment, we set the 
 *              date to the last occurrence of the event.
 *
 * PARAMETERS:  recordNum - index of appointment record 
 *
 * RETURNED:    true if successful, false if not.  It's posible that 
 *              a repeating event may have no displayable occurrences.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/24/95	Initial Revision
 *
 ***********************************************************************/
static Boolean SetDateToNextOccurrence (Word recordNum)
{
	Boolean dateSet = true;
	VoidHand recordH;
	DateType today;
	DateTimeType dateTime;
	ApptDBRecordType apptRec;

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

	if (! apptRec.repeat)
		Date = apptRec.when->date;

	// If the appointment is a repeating event,  go to the date of the 
	// next occurrence of the appointment.
	else
		{
		// Get today's date.
		TimSecondsToDateTime (TimGetSeconds (), &dateTime);
		today.year = dateTime.year - firstYear;
		today.month = dateTime.month;
		today.day = dateTime.day;

		Date = today;
		if ( ! ApptNextRepeat (&apptRec, &Date))
			{
			// If we are beyond the end date of the repeating event, display
			// the last occurrence of the event.
			Date = apptRec.repeat->repeatEndDate;
			while ( ! ApptNextRepeat (&apptRec, &Date))
				{
				// It posible that there are no occurences that are displayable
				// (ex: an expections is created for each occurrences),  if so
				// just go to today.
				if (DateToInt (Date) == DateToInt (apptRec.when->date))
					{
					ErrDisplay ("No displayable occurrences of event");
					Date = today;
					dateSet = false;
					break;
					}
				DateAdjust (&Date, -1);
				}
			}
		}
	MemHandleUnlock (recordH);
	
	return (dateSet);
}


/***********************************************************************
 *
 * FUNCTION:    GetTime
 *
 * DESCRIPTION: This routine selects the start and end time of an event.
 *
 * PARAMETERS:  startP  - passed:   current start time
 *                        returned: selected start time
 *              endtP   - passed:   current end time
 *                        returned: selected end time
 *              titleID - resource id of the title to display in the 
 *                        time picker dialog.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	10/24/95	Initial Revision
 *
 ***********************************************************************/
static Boolean GetTime (TimePtr startP, TimePtr endP, Word titleStrID)
{
	CharPtr title;
	TimeType start, end;
	Boolean selected;
	Boolean untimed;

	// If the event is untimed, pass the default start time
	// and duration.
	if (TimeToInt (*startP) == apptNoTime)
		{
		untimed = true;
		start.hours = min (DayStartHour, hoursPerDay-1);
		start.minutes = 0;
		end.hours = min (DayStartHour + 1, hoursPerDay-1);
		end.minutes = 0;
		}
	else
		{
		untimed = false;
		start = *startP;
		end = *endP;
		}
	
	title = MemHandleLock(DmGetResource (strRsc, titleStrID));

	selected = SelectTime (&start, &end, untimed, title, DayStartHour);

	MemPtrUnlock (title);
	
	if (selected)
		{
		*startP = start;
		*endP = end;
		}
	
	return (selected);
}


/***********************************************************************
 *
 * FUNCTION:    GetObjectPtr
 *
 * DESCRIPTION: This routine returns a pointer to an object in the current
 *              form.
 *
 * PARAMETERS:  formId - id of the form to display
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static VoidPtr GetObjectPtr (Word objectID)
{
	FormPtr frm;
	
	frm = FrmGetActiveForm ();
	return (FrmGetObjectPtr (frm, FrmGetObjectIndex (frm, objectID)));

}


/***********************************************************************
 *
 * FUNCTION:    GetFocusObjectPtr
 *
 * DESCRIPTION: This routine returns a pointer to the field object, in 
 *              the current form, that has the focus.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    pointer to a field object or NULL of there is no fucus
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static FieldPtr GetFocusObjectPtr (void)
{
	FormPtr frm;
	Word focus;
	FormObjectKind objType;
	
	frm = FrmGetActiveForm ();
	focus = FrmGetFocus (frm);
	if (focus == noFocus)
		return (NULL);
		
	objType = FrmGetObjectType (frm, focus);
	
	if (objType == frmFieldObj)
		return (FrmGetObjectPtr (frm, focus));
	
	else if (objType == frmTableObj)
		return (TblGetCurrentField (FrmGetObjectPtr (frm, focus)));
	
	return (NULL);
}


/***********************************************************************
 *
 * FUNCTION:    ShowObject
 *
 * DESCRIPTION: This routine set an object usable and draws the object if
 *              the form it is in is visible.
 *
 * PARAMETERS:  frm      - pointer to a form
 *              objectID - id of the object to set usable
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static void ShowObject (FormPtr frm, Word objectID)
{
	FrmShowObject (frm, FrmGetObjectIndex (frm, objectID));
}


/***********************************************************************
 *
 * FUNCTION:    HideObject
 *
 * DESCRIPTION: This routine set an object not-usable and erases it
 *              if the form it is in is visible.
 *
 * PARAMETERS:  frm      - pointer to a form
 *              objectID - id of the object to set not usable
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static void HideObject (FormPtr frm, Word objectID)
{
	FrmHideObject (frm, FrmGetObjectIndex (frm, objectID));
}


/***********************************************************************
 *
 * FUNCTION:    DirtyRecord
 *
 * DESCRIPTION: Mark a record dirty (modified).  Record marked dirty 
 *              will be synchronized.
 *
 * PARAMETERS:  record index
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/15/95	Initial Revision
 *
 ***********************************************************************/
static void DirtyRecord (UInt index)
{
	UInt		attr;

	DmRecordInfo (ApptDB, index, &attr, NULL, NULL);
	attr |= dmRecAttrDirty;
	DmSetRecordInfo (ApptDB, index, &attr, NULL);
}


/***********************************************************************
 *
 * FUNCTION:    DeleteRecord
 *
 * DESCRIPTION: This routine deletes the specified appointment record.
 *
 * PARAMETERS:  record index
 *
 * RETURNED:    true if the record was deleted, false if the delete 
 *              operation was canceled.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/1/95		Initial Revision
 *			kcr	10/24/95		fixed bug with selection index of 'SaveBackup'
 *									object
 *
 ***********************************************************************/
static Boolean DeleteRecord (Word recordNum)
{
	Err err;
	Word ctlIndex;
	Word alertButton;
	FormPtr alert;
	VoidHand recordH;
	Boolean archive;
	Boolean exception = false;
	ApptDBRecordType apptRec;

	// If we're changing a repeating appointmemt, check if all occurrences
	// are being changed, or if and exception is being created.
	ApptGetRecord (ApptDB, recordNum, &apptRec, &recordH);
	MemHandleUnlock (recordH);
	
	if (apptRec.repeat)
		{
		alertButton = FrmAlert (ExceptionAlert);

		// If the alert was canceled don't delete the record.
		if (alertButton == ExceptionCancelButton)
			return (false);

		else if (alertButton == ExceptionCurrentButton)
			exception = true;
		}

	if (! exception)
		{
		// Display an alert to comfirm the delete operation.
		alert = FrmInitForm (DeleteApptDialog);
	
		ctlIndex = FrmGetObjectIndex (alert, DeleteApptSaveBackup);
		FrmSetControlValue (alert, ctlIndex, SaveBackup);

		alertButton = FrmDoDialog (alert);
		archive = FrmGetControlValue (alert, ctlIndex);
		FrmDeleteForm (alert);

		if (alertButton == DeleteApptCancel)
			return (false);

		SaveBackup = archive;
		}


	if (exception)
		{
		// Add an exception to the current record.
		err = ApptAddException (ApptDB, &recordNum, Date);
		if (err)
			{
			FrmAlert (DeviceFullAlert);
			return (false);
			}
		}
	else
		{
		// Delete or archive the record.
		if (archive)
			DmArchiveRecord (ApptDB, recordNum);
		else
			DmDeleteRecord (ApptDB, recordNum);
		DmMoveRecord (ApptDB, recordNum, DmNumRecords (ApptDB));
		}


	// If the appointment has an alarm, reschedule the next alarm.
	if (apptRec.alarm)
		{
		RescheduleAlarms (ApptDB);
		}

	return (true);
}


/***********************************************************************
 *
 * FUNCTION:    CreateException
 *
 * DESCRIPTION: This routine creates an exception record.  It does not
 *              add the exception to the exceptions list of the original 
 *              record.
 *
 * PARAMETERS:  newRec - new record
 *              indexP - passed:   index of record being excepted
 *                       returned: index of exception record created
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	11/22/95	Initial Revision
 *
 ***********************************************************************/
static Err CreateException (ApptDBRecordPtr newRec, WordPtr indexP)
{
	Err err;
	UInt attr;
	
	// Get the secert setting of the record.
	DmRecordInfo (ApptDB, *indexP, &attr, NULL, NULL);	

	err = ApptNewRecord (ApptDB, newRec, indexP);				

	if (! err)
		{
		if (attr & dmRecAttrSecret)
			{
			DmRecordInfo (ApptDB, *indexP, &attr, NULL, NULL);	
			attr |= dmRecAttrSecret;
			DmSetRecordInfo (ApptDB, *indexP, &attr, NULL);
			}
		}
	return (err);
}


/***********************************************************************
 *
 * FUNCTION:    CreateNote
 *
 * DESCRIPTION: This routine adds an empty note to the current record.
 *
 * PARAMETERS:  prompt - if true, ask if an exception should be created.
 *
 * RETURNED:    true if the note was added, false if it was not.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/4/95	Initial Revision
 *
 ***********************************************************************/
static Boolean CreateNote (Boolean prompt)
{
	Err err;
	Word alertButton;
	Boolean exception = false;
	VoidHand recordH;
	ApptDBRecordType newRec;
	ApptDBRecordType apptRec;
	ApptDateTimeType when;
	ApptDBRecordFlags changedFields;
	
	if (CurrentRecord == noRecordSelected) return (false);

	ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);
	MemHandleUnlock (recordH);

	// If the record already has a note, exit
	if (apptRec.note) return (true);

	// If we're changing a repeating appointmemt, check if all occurrences
	// are being changed, or if and exception is being created.
	if (apptRec.repeat && prompt)
		{
		alertButton = FrmAlert (RepeatAddNoteAlert);

		// If the alert was canceled don't create the note.
		if (alertButton == RepeatAddNoteCancelButton)
			return (false);

		else if (alertButton == RepeatAddNoteCurrentButton)
			exception = true;
		}

	if (exception)
		{
		// Add an exception to the current record.
		err = ApptAddException (ApptDB, &CurrentRecord, Date);
		if (err) goto Exit;

		// Create a new record on the current day that contains
		// the same description, time, and alarm setting as the 
		// repeating event.
		ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);

		when.startTime = apptRec.when->startTime;
		when.endTime = apptRec.when->endTime;
		when.date = Date;

		MemSet (&newRec, sizeof (newRec), 0);
		newRec.when = &when;
		newRec.description = apptRec.description;
		newRec.alarm = apptRec.alarm;
		newRec.note = "";
		
		err = CreateException (&newRec, &CurrentRecord);				
		MemHandleUnlock (recordH);
		if (err) goto Exit;
		}

	else
		{
		// Add the note to the record.
		MemSet (&changedFields, sizeof (changedFields), 0);
		changedFields.note = true;
		apptRec.note = "";
		err = ApptChangeRecord (ApptDB, &CurrentRecord, &apptRec, changedFields);
		if (err) goto Exit;
		}
	
	return (true);
	

Exit:
	FrmAlert (DeviceFullAlert);
	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    DeleteNote
 *
 * DESCRIPTION: This routine deletes the note field from an 
 *              appointment record.
 *
 * PARAMETERS:  exception - true if a new record, an exception, should be
 *                          created.
 *
 * RETURNED:    true if the note was deleted.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	10/13/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DeleteNote (Boolean exception)
{
	Err err;
	VoidHand recordH;
	ApptDBRecordType newRec;
	ApptDBRecordType apptRec;
	ApptDateTimeType when;
	ApptDBRecordFlags changedFields;
	

	if (exception)
		{
		// Add an exception to the current record.
		err = ApptAddException (ApptDB, &CurrentRecord, Date);
		if (err) goto Exit;		

		// Create a new record on the current day that contains
		// the same description, time, and alarm settings as the 
		// repeating event, but not the note.
		ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);

		when.startTime = apptRec.when->startTime;
		when.endTime = apptRec.when->endTime;
		when.date = Date;

		MemSet (&newRec, sizeof (newRec), 0);
		newRec.when = &when;
		newRec.description = apptRec.description;
		newRec.alarm = apptRec.alarm;
		
		err = CreateException (&newRec, &CurrentRecord);
		MemHandleUnlock (recordH);
		if (err) goto Exit;
		}

	else
		{
		// Remove the note from the record.
		MemSet (&changedFields, sizeof (changedFields), 0);
		changedFields.note = true;
		apptRec.note = NULL;

		err = ApptChangeRecord (ApptDB, &CurrentRecord, &apptRec, changedFields);
		if (err) goto Exit;
		}
	
	return (true);

Exit:
	FrmAlert (DeviceFullAlert);
	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    SplitRepeatingEvent
 *
 * DESCRIPTION: This routine splits a repeating appointment into two
 *              repeating appointment.  The orginal record record is 
 *              copied and the end date of the new record is set to 
 *              yesterday or the day before the current date, which ever
 *              earlier.
 *
 * PARAMETERS:  indexP  - passed:   index of records split.
 *                        returned: index of records orginal record.
 *
 * RETURNED:    error code
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	4/25/96	Initial Revision
 *
 ***********************************************************************/
static Err SplitRepeatingEvent (WordPtr indexP)
	{
	Err					err = 0;
	UInt 					index;
	ULong 				uniqueID;
	VoidHand				recordH;
	DateType				endDate;
	DateType				repeatDate;
//	DateTimeType		today;
 	RepeatInfoType		repeat;
	ApptDBRecordType	apptRec;


	// Get yesterday's date or the date of the day before the current date,
	// which ever earlier.
// 	TimSecondsToDateTime (TimGetSeconds(), &today);
//	endDate.year = today.year - firstYear;
//	endDate.month = today.month;
//	endDate.day = today.day;
//	if (DateToInt (endDate) > DateToInt (Date))
	endDate = Date;
	DateAdjust (&endDate, -1);


	ApptGetRecord (ApptDB, *indexP, &apptRec, &recordH);

	// Check for past occurrecnes of the event.
	repeatDate = apptRec.when->date;
	ApptNextRepeat (&apptRec, &repeatDate);
	if (DateToDays (repeatDate) <= DateToDays (endDate))
		{
		// Creating the new record may move a current record, so get its 
		// unique id so we can find it after the record is created.
		DmRecordInfo (ApptDB, *indexP, NULL, &uniqueID, NULL); 

		repeat = *apptRec.repeat;
		repeat.repeatEndDate = endDate;
		apptRec.repeat = &repeat;
		
		err = ApptNewRecord (ApptDB, &apptRec, &index);				
		DmFindRecordByID (ApptDB, uniqueID, indexP);
		}

	MemHandleUnlock (recordH);
	
	return (err);
	}


/***********************************************************************
 *
 * FUNCTION:    MoveEvent
 *
 * DESCRIPTION:  This routine changes the date and / or time of the 
 *               specified event
 *
 * PARAMETERS:  recordNumP - 
 *              startTime  -
 *              startTime  - 
 *					 date       -
 *					 splitEvent -
 *					 moved      - (returned) true if moved
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date			Description
 *			----	----			-----------
 *			art	4/1/96		Initial Revision
 *
 ***********************************************************************/
 Err MoveEvent (WordPtr recordNumP, TimeType startTime, TimeType endTime,
 		DateType date, Boolean splitEvent, BooleanPtr moved)
	{

	Err err;
	Word id;
	Word dayOfWeek;
	Word alertButton;
	Long adjust;
	FormPtr alert;
	Boolean exception = false;
	VoidHand recordH;
	RepeatInfoType repeat;
	ApptDBRecordType newRec;
	ApptDBRecordType apptRec;
	ApptDateTimeType when;
	ApptDBRecordFlags changedFields;

	ApptGetRecord (ApptDB, *recordNumP, &apptRec, &recordH);
	MemHandleUnlock (recordH);

	*moved = false;
	
	// If we're changing a repeating appointmemt, check if all occurrences
	// are being changed, or if and exception is being created.
	if (apptRec.repeat)
		{
		alertButton = FrmAlert (ExceptionAlert);

		// If the alert was canceled don't apply any of the changes.
		if (alertButton == ExceptionCancelButton)
			return (0);

		else if (alertButton == ExceptionCurrentButton)
			exception = true;
		}


	// Add an exception to the current record,  and create a new record
	// at the new time.
	if (exception)
		{
		err = ApptAddException (ApptDB, recordNumP, Date);
		if (err) goto Exit;
		
		ApptGetRecord (ApptDB, *recordNumP, &apptRec, &recordH);

		when.startTime = startTime;
		when.endTime = endTime;
		when.date = date;

		MemSet (&newRec, sizeof (newRec), 0);
		newRec.description = apptRec.description;
		newRec.note = apptRec.note;
		newRec.when = &when;
		newRec.alarm = apptRec.alarm;

		err = CreateException (&newRec, recordNumP);
		MemHandleUnlock (recordH);
		if (err) goto Exit;
		}

	// Change the time of the current record.
	else	
		{
		MemSet (&changedFields, sizeof (changedFields), 0);

		if (apptRec.repeat)
			{
			if (splitEvent)
				{
				err = SplitRepeatingEvent (recordNumP);
				if (err) goto Exit;
				}

			// Move the entire range of event, reset the start date, maintain the 
			// duration and clear the exceptions list.
			else 
				{
				repeat = *apptRec.repeat;
				newRec.repeat = &repeat;

				// Maintain the duration of the event.
				if ((DateToInt (apptRec.repeat->repeatEndDate) != apptNoEndDate))
					{
					adjust = (Long) DateToDays (date) -
			   	         (Long) DateToDays (apptRec.when->date);

					DateAdjust (&repeat.repeatEndDate, adjust);

					changedFields.repeat = true;
					}

				// If the repeat type is weekly and the start date of the event
				// has been changed,  update the 'repeat on' field, which contains
				// the days of the week the event repeats on, such that the 
				// event occurs on the start date.
				if (apptRec.repeat->repeatType == repeatWeekly)
					{
					dayOfWeek = DayOfWeek (apptRec.when->date.month, 
						apptRec.when->date.day,
						apptRec.when->date.year+firstYear);
					repeat.repeatOn &= ~(1 << dayOfWeek);
					
					dayOfWeek = DayOfWeek (date.month, 
						date.day,
						date.year+firstYear);
					repeat.repeatOn |= (1 << dayOfWeek);

					changedFields.repeat = true;
					}

				// If the repeat type is monthly by day, get the day of the month (ex:
				// fisrt Friday) of the start date of the event.
				else if (apptRec.repeat->repeatType == repeatMonthlyByDay)
					{
					repeat.repeatOn = DayOfMonth (date.month, date.day, date.year + firstYear);
					changedFields.repeat = true;

					// If we're in the fourth week, and the fourth week is also the last
					// week,  ask the user which week the event repeats in (fourth or last).
					if ( ((repeat.repeatOn / daysInWeek) == 3) &&
					      (date.day + daysInWeek > DaysInMonth (date.month, date.year + firstYear)))
						{
						alert = FrmInitForm (MonthlyRepeatDialog);
						
						// Set the 4th / last push button.
						if (apptRec.repeat->repeatOn > dom4thSat)
							id = MonthlyRepeatLastButton;
						else
							id = MonthlyRepeatFourthButton;
						FrmSetControlGroupSelection (alert, MonthlyRepeatWeekGroup,id);

						alertButton = FrmDoDialog (alert);

						if (FrmGetObjectIndex (alert, MonthlyRepeatLastButton) ==
						    FrmGetControlGroupSelection (alert, MonthlyRepeatWeekGroup))
						   repeat.repeatOn += daysInWeek;

						FrmDeleteForm (alert);

						if (alertButton == MonthlyRepeatCancel)
							return (0);
						}
					}

				// Clear the exceptions list.
				changedFields.exceptions = true;
				newRec.exceptions = NULL;
				}
			}

		changedFields.when = true;

		when.startTime = startTime;
		when.endTime = endTime;
		when.date = date;
		newRec.when = &when;

		err = ApptChangeRecord (ApptDB, recordNumP, &newRec, changedFields);
		if (err) goto Exit;
		}

	// If the appointment has an alarm, reschedule the next alarm.
	if (apptRec.alarm)
		{
		RescheduleAlarms (ApptDB);
		}

	*moved = true;
	return (0);
	

Exit:
	FrmAlert (DeviceFullAlert);
	return (err);
	}


/***********************************************************************
 *
 * FUNCTION:    PurgeRecords
 *
 * DESCRIPTION: This routine deletes appointments that are before the 
 *              user specified date.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    true if the current view may need to be redrawn.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/1/95	Initial Revision
 *
 ***********************************************************************/
static Boolean PurgeRecords (void)
{
	Long adjust;
	Word index;
	Word ctlIndex;
	Word numRecord;
	Word buttonHit;
	Word rangeItem;
	ListPtr lst;
	FormPtr alert;
	VoidHand recordH;
	Boolean purge;
	Boolean archive = false;
	DateType purgeDate;
	DateTimeType dateTime;
	ApptDBRecordType apptRec;

	// Display an alert to comfirm the operation.
	alert = FrmInitForm (PurgeDialog);

	ctlIndex = FrmGetObjectIndex (alert, PurgeSaveBackup);
	FrmSetControlValue (alert, ctlIndex, SaveBackup);

	buttonHit = FrmDoDialog (alert);

	archive = FrmGetControlValue (alert, ctlIndex);

	lst = FrmGetObjectPtr (alert, FrmGetObjectIndex (alert, PurgeRangeList));
	rangeItem = LstGetSelection (lst);

	FrmDeleteForm (alert);

	if (buttonHit == PurgeCancel)
		return (false);

	SaveBackup = archive;


	// Compute the purge date.
	TimSecondsToDateTime (TimGetSeconds (), &dateTime);
	
	// One, two, or three weeks
	if (rangeItem < 3)
		adjust = ((rangeItem + 1) * daysInWeek);

	// One month
	else if (dateTime.month > january)
		adjust = DaysInMonth (dateTime.month-1, dateTime.year);
	else
		adjust = DaysInMonth (december, dateTime.year-1);
		
	purgeDate.year = dateTime.year - firstYear;
	purgeDate.month = dateTime.month;
	purgeDate.day = dateTime.day;
	DateAdjust (&purgeDate, -adjust);
	

	// Delete records.
	numRecord = DmNumRecords (ApptDB);
	if (! numRecord) return (false);
	
	for (index = numRecord-1; (short) index >= 0; index--)
		{
		recordH = DmGetRecord (ApptDB, index);
		if (recordH == 0) continue;
		
		ApptGetRecord (ApptDB, index, &apptRec, &recordH);
		if (apptRec.repeat)
			purge = (DateToInt(apptRec.repeat->repeatEndDate) <= DateToInt(purgeDate));
		else
			purge = (DateToInt(apptRec.when->date) <= DateToInt(purgeDate));
		MemHandleUnlock (recordH);

		DmReleaseRecord (ApptDB, index, false);
		
		if (purge)
			{
			if (archive)
				DmArchiveRecord (ApptDB, index);
			else
				DmDeleteRecord (ApptDB, index);
				
			// Move deleted record to the end of the index so that the 
			// quick sort routine will work.
			DmMoveRecord (ApptDB, index, numRecord);
			}
		}
		
	// Schedule the next alarm.
	RescheduleAlarms (ApptDB);

	return (true);
}


/***********************************************************************
 *
 * FUNCTION:    ClearEditState
 *
 * DESCRIPTION: This routine take the application out of edit mode.
 *              The edit state of the current record is remember until
 *              this routine is called.  
 *
 *              If the current record is empty its deleted by this
 *              routine.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    true is current record is deleted by this routine.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/28/95	Initial Revision
 *
 ***********************************************************************/
static Boolean ClearEditState (void)
{
	Word recordNum;
	Boolean empty;
	Boolean hasAlarm;
	VoidHand recordH;
	ApptDBRecordType apptRec;

	if ( ! ItemSelected)
		{
		CurrentRecord = noRecordSelected;
		return (false);
		}
	
	recordNum = CurrentRecord;

	// Clear the global variables that keep track of the edit state of the
	// current record.
	ItemSelected = false;
	CurrentRecord = noRecordSelected;
	DayEditPosition = 0;
	DayEditSelectionLength = 0;
	
	// If the description field is empty and the note field is empty, delete
	// the record.
	ApptGetRecord (ApptDB, recordNum, &apptRec, &recordH);
	empty = true;
	if (apptRec.description && *apptRec.description)
		empty = false;
	else if (apptRec.note && *apptRec.note)
		empty = false;
		
	hasAlarm = (apptRec.alarm != NULL);	
	MemHandleUnlock (recordH);


	if (empty)
		{
		// If the record was not modified, and the description and 
		// note fields are empty, remove the record from the database.
		// This can occur when a new empty record is deleted.
		if (RecordDirty)
			{
			DmDeleteRecord (ApptDB, recordNum);
			DmMoveRecord (ApptDB, recordNum, DmNumRecords (ApptDB));
			}
		else
			DmRemoveRecord (ApptDB, recordNum);
		
		// If the appointment had an alarm, reschedule the next alarm.
		if (hasAlarm)
			{
			RescheduleAlarms (ApptDB);
			}

		return (true);
		}

	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    DatebookDayOfWeek
 *
 * DESCRIPTION: This routine returns the day-of-the-week, adjusted by the 
 *              preference setting that specifies the first day-of-
 *              the-week.  If the date passed is a Tuesday and the 
 *              start day of week is Monday, this routine will return
 *              a value of one.
 *
 * PARAMETERS:	 month - month (1-12)
 *              day   - day (1-31)
 *              year  - year (1904-2031)
 *
 * RETURNED:	 day of the week (0-first, 1-second)
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/27/95	Initial Revision
 *
 ***********************************************************************/
static UInt DatebookDayOfWeek (UInt month, UInt day, UInt year)
{
	return ((DayOfWeek (month, day, year) - StartDayOfWeek + daysInWeek)
	 % daysInWeek);
}


/***********************************************************************
 *
 * FUNCTION:    SubstituteStr
 *
 * DESCRIPTION: This routine substitutes the occurrence a token, within
 *              a string, with another string.
 *
 * PARAMETERS:  str    - string containing token string
 *              token  - the string to be replaced
 *              sub    - the string to substitute for the token
 *              subLen - length of the substitute string.
 *
 * RETURNED:    pointer to the string
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/6/95	Initial Revision
 *
 ***********************************************************************/
static CharPtr SubstituteStr (CharPtr str, CharPtr token, CharPtr sub, Word subLen)
{
	int charsToMove;
	Word tokenLen;
	Word strLen;
	Word blockSize;
	CharPtr ptr;
	VoidHand strH;

	// Find the start of the token string, if it doesn't exist, exit.
	ptr = StrStr(str, token);
	if (ptr == NULL) return (str);
	
	tokenLen = StrLen (token);
	charsToMove = subLen - tokenLen;
	
	
	// Resize the string if necessary.
	strH = MemPtrRecoverHandle (str);
	strLen = StrLen (str);
	blockSize = MemHandleSize (strH);
	if (strLen + charsToMove + 1 >= blockSize)
		{
		MemHandleUnlock (strH);
		MemHandleResize (strH, strLen + charsToMove + 1);
		str = MemHandleLock (strH);
		ptr = StrStr (str, token);
		}
	
	// Make room for the substitute string.
	if (charsToMove)
		MemMove (ptr + subLen, ptr + tokenLen, StrLen (ptr + tokenLen)+1);
		
	// Replace the token with the substitute string.
	MemMove (ptr, sub, subLen);
	
	return (str);
}


/***********************************************************************
 *
 * FUNCTION:    SelectFont
 *
 * DESCRIPTION: This routine handles selection of a font in the List 
 *              View. 
 *
 * PARAMETERS:  currFontID - id of current font
 *
 * RETURNED:    id of new font
 *
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/10/97	Initial Revision
 *
 ***********************************************************************/
static FontID SelectFont (FontID currFontID)
{
	Word formID;
	FontID fontID;
	
	formID = (FrmGetFormId (FrmGetActiveForm ()));

	// Call the OS font selector to get the id of a font.
	fontID = FontSelect (currFontID);

	if (fontID != currFontID)
		FrmUpdateForm (formID, updateFontChanged);

	return (fontID);
}


#pragma mark ----------------
/***********************************************************************
 *
 * FUNCTION:    RepeatSetDateTrigger
 *
 * DESCRIPTION: This routine sets the label of the trigger that displays 
 *              the end date of a repeating appointment. 
 *
 * PARAMETERS:  endDate	- date or -1 if no end date
 *
 * RETURNED:    nothing
 *
 * NOTES:
 *      This routine assumes that the memory allocated for the label of 
 *      the due date trigger is large enough to hold the lagest posible
 *      label.  This label's memory is reserved by initializing the label
 *      in the resource file.     
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/16/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatSetDateTrigger (DateType endDate)
{
	CharPtr label;
	ListPtr lst;
	ControlPtr ctl;

	lst = GetObjectPtr (RepeatEndOnList);
	ctl = GetObjectPtr (RepeatEndOnTrigger);
	label = CtlGetLabel (ctl);
	if (DateToInt (endDate) == apptNoEndDate)
		{
		StrCopy (label, LstGetSelectionText (lst, repeatNoEndDateItem));
		LstSetSelection (lst, noEndDateItem);
		}
	else
		{
		// Format the end date into a string.
		DateToDOWDMFormat (endDate.month, 
						 		 endDate.day, 
						 		 endDate.year + firstYear, 
						 		 ShortDateFormat, label);

//		DateToAscii (endDate.month, 
//						 endDate.day, 
//						 endDate.year + firstYear, 
//						 LongDateFormat, label);
		LstSetSelection (lst, repeatChooseDateItem);
		}
	CtlSetLabel (ctl, label);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatGetUIValues
 *
 * DESCRIPTION: This routine gets the current repeat settings of the 
 *              ui gadgets in the repeat dialog box
 *
 *
 * PARAMETERS:  frm     - pointer to the repeat dialog
 *              repeatP - RepeatInfoType structure (fill-in by this routine) 
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/10/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatGetUIValues (FormPtr frm, RepeatInfoPtr repeatP)
{
	Word freq;
	Word i;
	Word id;
	Word index;
	CharPtr str;
	DetailsPtr details;

	// Lock the block that contains the details of the current record.
	details = MemHandleLock (DetailsH);


	// Get the repeat type.
	index = FrmGetControlGroupSelection (frm, RepeatTypeGroup);
	id = FrmGetObjectId (frm, index);
	if (id == RepeatYearly)
		repeatP->repeatType = repeatYearly;
	else if (id <= RepeatWeekly)
		{
		repeatP->repeatType = (RepeatType) (id - RepeatNone);
		}
	else
		{
		index = FrmGetControlGroupSelection (frm, RepeatByGroup);
		id = FrmGetObjectId (frm, index);
		if (id == RepeatByDayPushButon)
			repeatP->repeatType = repeatMonthlyByDay;
		else
			repeatP->repeatType = repeatMonthlyByDate;
		}
	

	// Get the repeat end date.
	repeatP->repeatEndDate = RepeatEndDate;


	// Get the repeat frequency.
	str = FldGetTextPtr (GetObjectPtr (RepeatFrequenceField));
	if (str) freq = StrAToI (str);
	else freq = 0;
	
	if (freq)
		repeatP->repeatFrequency = freq;
	else
		repeatP->repeatFrequency = 1;


	// Get the start day of week.  If the original repeat type, that is the 
	// repeat type when the dialog was first displayed, is weekly then
	// use the start date in the repeat info (the unedit data), otherwise
	// use the current start of week.
	if (repeatP->repeatType == repeatWeekly)
		{
		if (details->repeat.repeatType == repeatWeekly)
			repeatP->repeatStartOfWeek = details->repeat.repeatStartOfWeek;
		else		
			repeatP->repeatStartOfWeek = StartDayOfWeek;
		}

	// For all other repeat types, the repeatStartOfWeek field is meaningless.
	else
		repeatP->repeatStartOfWeek = 0;


	// If the repeat type is weekly, get the day of the week the event
	// repeats on. 
	if (repeatP->repeatType == repeatWeekly)
		{
		repeatP->repeatOn = 0;
		index = FrmGetObjectIndex (frm, RepeatDayOfWeek1PushButton);
		for (i = 0; i < daysInWeek ; i++)
			{
			if (FrmGetControlValue (frm, index +
								((i - RepeatStartOfWeek + daysInWeek) % daysInWeek)))
				repeatP->repeatOn |= (1 << i);
			}
		}

	// If the repeat type is monthly by day, get the day of the month (ex:
	// fisrt Friday) of the start date of the event.
	else if (repeatP->repeatType == repeatMonthlyByDay)
		{
		if (details->repeat.repeatType == repeatMonthlyByDay)
			repeatP->repeatOn = details->repeat.repeatOn;
		else
			repeatP->repeatOn = DayOfMonth (details->when.date.month,
				details->when.date.day,
				details->when.date.year + firstYear);
		}

	// For all other repeat types, the repeatOn field is meaningless.
	else
		{
		repeatP->repeatOn = 0;
		}
	
	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatSetUIValues
 *
 * DESCRIPTION: This routine sets the current repeat settings of the 
 *              ui gadgets in the repeat dialog box
 *
 * PARAMETERS:  frm     - pointer to the Repeat Dialog
 *              repeatP - pointer to a RepeatInfoType structure.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/10/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatSetUIValues (FormPtr frm, RepeatInfoPtr repeatP)
{
	char			chr;
	Word			i;
	Word			id;
	Word			oldFreq;
	VoidHand		freqH;
	CharPtr		freqP;
	CharPtr		str1;
	CharPtr		str2;
	Boolean		on;
	FieldPtr		fld;

	// Set the selection of the "repeat type" push button group.
	id = repeatP->repeatType + RepeatNone;
	if (repeatP->repeatType > repeatMonthlyByDay)
		id--;
	FrmSetControlGroupSelection (frm, RepeatTypeGroup, id);
	

	// Set the frequency field
	if (repeatP->repeatType != repeatNone)	
		{
		fld = GetObjectPtr (RepeatFrequenceField);
		freqH = FldGetTextHandle (fld);
		if (freqH) 
			{
			freqP = MemHandleLock (freqH);
			oldFreq = StrAToI (freqP);
			}
		else
			{
			freqH = MemHandleNew (maxFrequenceFieldLen);
			freqP = MemHandleLock (freqH);
			oldFreq = 0;
			}

		if (oldFreq != repeatP->repeatFrequency)
			{
			StrIToA (freqP, repeatP->repeatFrequency);
			FldSetTextHandle (fld, freqH);
			if (FrmVisible (FrmGetActiveForm ()))
				{
				FldEraseField (fld);
				FldDrawField (fld);
				}
			}
		MemHandleUnlock (freqH);
		}	


	// Set the selection of the "repeat on" push button groups.
	if (repeatP->repeatType == repeatWeekly)
		{
		// If the appointment has a different start-day-of-week than
		// the dialog-box's current start-day-of-week, rearrange the
		//	labels on the days-of-week push buttons.
		//	Note that this will only handle button-label shifts of one day.
		if (StartDayOfWeek != RepeatStartOfWeek)
			{
			str1 = CtlGetLabel (GetObjectPtr(RepeatDayOfWeek1PushButton));
			chr = *str1;
			for (id = RepeatDayOfWeek2PushButton; id <= RepeatDayOfWeek7PushButton; id++)
				{
				str2 = CtlGetLabel (GetObjectPtr(id));
				*str1 = *str2;
				str1 = str2;
				}
			*str1 = chr;
			RepeatStartOfWeek = StartDayOfWeek;
			}
		// Turn on the push buttons for the days the appointment repeats on.
		for (i = 0; i < daysInWeek; i++)
			{
			on = ((repeatP->repeatOn & (1 << i) ) != 0);
			id = RepeatDayOfWeek1PushButton + 
				((i - RepeatStartOfWeek + daysInWeek) % daysInWeek);
			CtlSetValue (GetObjectPtr (id), on);
			}
		}


	// Set the selection of the "repeat by" push button groups.
	if (repeatP->repeatType == repeatMonthlyByDate)	
		FrmSetControlGroupSelection (frm, RepeatByGroup, RepeatByDatePushButon);
	else
		FrmSetControlGroupSelection (frm, RepeatByGroup, RepeatByDayPushButon);
	

	// Set the "end on" trigger label and popup list selection.
	if (repeatP->repeatType != repeatNone)	
		{
		RepeatSetDateTrigger (repeatP->repeatEndDate);
		}
}


/***********************************************************************
 *
 * FUNCTION:    RepeatDrawDescription
 *
 * DESCRIPTION: This routine draws the text description of the current
 *              repeat type and frequency.
 *
 *              The description is created from a template string.  The 
 *              repeat type and frequency determines which template is 
 *              used.  The template may contain one or more of the 
 *              following token:
 *                   ^d - day name (ex: Monday)
 *							^f - frequency
 *                   ^x - day of the month ordinal number (ex: 1st - 31th)
 *                   ^m - month name (ex: July)
 *                   ^w - week ordinal number (1st, 2nd, 3rd, 4th, or last)
 *
 * PARAMETERS:  frm - pointer to the repeat dialog box
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/6/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatDrawDescription (FormPtr frm)
{
	Byte repeatOn;
	Word i;
	Word len;
	Word freq;
	Word dayOfWeek;
	Word templateId;
	Word repeatOnCount = 0;
	CharPtr descP;
	CharPtr resP;
	VoidHand descH;
	VoidHand resH;
	FieldPtr fld;
	DetailsPtr details;
	RepeatInfoType repeat;
	RectangleType r;
	
	// Lock the block that contains the details of the current record.
	details = MemHandleLock (DetailsH);

	fld = GetObjectPtr (RepeatDescField);
	FldEraseField (fld);
	
	// Draw a frame around the field.
	FldGetBounds (fld, &r);
	RctInsetRectangle (&r, -4);
	WinDrawRectangleFrame (simpleFrame, &r);
	
	// Get the current setting of the repeat ui gadgets.
	RepeatGetUIValues (frm, &repeat);

	// Determine which template string to use.  The template string is 
	// used to format the description string.
	freq = repeat.repeatFrequency;
	switch (repeat.repeatType)
		{
		case repeatNone:
			templateId = repeatNoneStrID;
			break;

		case repeatDaily:
			templateId = dailyRepeatStrID;
			break;

		case repeatWeekly:
			templateId = weeklyRepeat1DayStrID;
			for (i = 0; i < daysInWeek; i++)
				{
				if (repeat.repeatOn & (1 << i) ) repeatOnCount++;
				}
			templateId += (repeatOnCount - 1);
			break;
			
		case repeatMonthlyByDate: 
			templateId = monthtlByDateRepeatStrID;
			break;

		case repeatMonthlyByDay:
			templateId = monthtlByDayRepeatStrID;
			break;

		case repeatYearly:
			templateId = yearlyRepeatStrID;
			break;
		}

	// Allocate a block to hold the description and copy the template 
	// string into it.
	resH = DmGetResource (strRsc, templateId);
	resP = MemHandleLock (resH);
	descH = MemHandleNew (MemPtrSize(resP));
	descP = MemHandleLock (descH);
	StrCopy (descP, resP);
	MemHandleUnlock (resH);
	

	// Substitute the month name string for the month name token.
	resH = DmGetResource (strRsc, monthFullNamesStrID);
	resP = MemHandleLock (resH);
	for (i = 1; i < details->when.date.month; i++)
		resP = StrChr (resP, spaceChr) + 1;
	len = (Word) (StrChr (resP, spaceChr) - resP);
	descP = SubstituteStr (descP, monthNameToken, resP, len);
	MemHandleUnlock (resH);


	// Substitute the day name string for the day name token.
	resH = DmGetResource (strRsc, dayFullNamesStrID);
	resP = MemHandleLock (resH);
	if (repeat.repeatType == repeatWeekly)
		{
		dayOfWeek = repeat.repeatStartOfWeek;
		repeatOn = repeat.repeatOn;
		while (StrStr (descP, dayNameToken))
			{
			for (i = 0; i < daysInWeek; i++)
				{
				if (repeatOn & (1 << dayOfWeek) )
					{
					repeatOn &= ~(1 << dayOfWeek);
					break;
					}
				dayOfWeek = (dayOfWeek + 1 + daysInWeek) % daysInWeek;
				}
			resP = MemDeref (resH);
			for (i = 0; i < dayOfWeek; i++)
				resP = StrChr (resP, spaceChr) + 1;
			if (repeatOnCount == 1)
				len = (Word) (StrChr (resP, spaceChr) - resP);
			else
				len = 3;
			descP = SubstituteStr (descP, dayNameToken, resP, len);
			}
		}
	else
		{
		dayOfWeek = DayOfWeek (details->when.date.month, details->when.date.day, 
			details->when.date.year + firstYear);
		for (i = 0; i < dayOfWeek; i++)
			resP = StrChr (resP, spaceChr) + 1;
		len = (Word) (StrChr (resP, spaceChr) - resP);
		descP = SubstituteStr (descP, dayNameToken, resP, len);
		}
	MemHandleUnlock (resH);


	// Substitute the repeat frequency string for the frequency token.
	resH = DmGetResource (strRsc, freqOrdinalsStrID);
	resP = MemHandleLock (resH);
	for (i = 1; i < freq; i++)
		resP = StrChr (resP, spaceChr) + 1;
	len = (Word) (StrChr (resP, spaceChr) - resP);
	descP = SubstituteStr (descP, frequenceToken, resP, len);
	MemHandleUnlock (resH);


	// Substitute the repeat week string (1st, 2nd, 3rd, 4th, or last)
	// for the week ordinal token.
	resH = DmGetResource (strRsc, weekOrdinalsStrID);
	resP = MemHandleLock (resH);
	for (i = 0; i < repeat.repeatOn / daysInWeek; i++)
		resP = StrChr (resP, spaceChr) + 1;
	len = (Word) (StrChr (resP, spaceChr) - resP);
	descP = SubstituteStr (descP, weekOrdinalToken, resP, len);
	MemHandleUnlock (resH);


	// Substitute the repeat date string (1st, 2nd, ..., 31th) for the
	// day ordinal token.
	resH = DmGetResource (strRsc, dayOrdinalsStrID);
	resP = MemHandleLock (resH);
	for (i = 1; i < details->when.date.day; i++)
		resP = StrChr (resP, spaceChr) + 1;
	len = (Word) (StrChr (resP, spaceChr) - resP);
	descP = SubstituteStr (descP, dayOrdinalToken, resP, len);
	MemHandleUnlock (resH);
	
	// Draw the description.
	MemHandleUnlock (descH);
	FldFreeMemory (fld);
	FldSetTextHandle (fld, descH);
	FldDrawField (fld);

	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatSelectEndDate
 *
 * DESCRIPTION: This routine selects the end date of a repeating event.
 *
 * PARAMETERS:  event - pointer to a popup select event
 *
 * RETURNED:    nothing
 *
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/16/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatSelectEndDate (EventPtr event)
{
	SWord month, day, year;
	CharPtr titleP;
	VoidHand titleH;
	DetailsPtr details;

	// "No due date" items selected?
	if (event->data.popSelect.selection == repeatNoEndDateItem)
		{
		DateToInt (RepeatEndDate) = apptNoEndDate;
		}

	// "Select date" item selected?
	else if (event->data.popSelect.selection == repeatChooseDateItem)
		{
		details = MemHandleLock (DetailsH);

		if ( DateToInt (RepeatEndDate) == apptNoEndDate)
			{
			year = details->when.date.year + firstYear;
			month = details->when.date.month;
			day = details->when.date.day;
			}
		else
			{
			year = RepeatEndDate.year + firstYear;
			month = RepeatEndDate.month;
			day = RepeatEndDate.day;
			}

		titleH = DmGetResource (strRsc, endDateTitleStrID);
		titleP = (CharPtr) MemHandleLock (titleH);

		if (SelectDay (selectDayByDay, &month, &day, &year, titleP))
			{
			RepeatEndDate.day = day;
			RepeatEndDate.month = month;
			RepeatEndDate.year = year - firstYear;
			
			// Make sure the end date is not before the start date.
			if (DateToInt(RepeatEndDate) < DateToInt (details->when.date))
				{
				SndPlaySystemSound (sndError);
				DateToInt (RepeatEndDate) = apptNoEndDate;
				}
			}

		MemHandleUnlock (titleH);
		MemPtrUnlock (details);
		}

	RepeatSetDateTrigger (RepeatEndDate);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatChangeRepeatOn
 *
 * DESCRIPTION: This routine is called when one of the weekly "repeat on" 
 *              push button is pushed.  This routine checks 
 *              if all the buttons has been turned off,  if so the day
 *              of the week of the appointment's start date is turn on.
 *
 * PARAMETERS:  event - pointer to and event
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/7/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatChangeRepeatOn (EventPtr event)
{
	Word i;
	Word id;
	Word index;
	Word dayOfWeek;
	FormPtr frm;
	Boolean on = false;
	DetailsPtr details;

	// Lock the block that contains the details of the current record.
	details = MemHandleLock (DetailsH);

	frm = FrmGetActiveForm ();

	// Check if any of the buttons are on.
	index = FrmGetObjectIndex (frm, RepeatDayOfWeek1PushButton);
	for (i = 0; i < daysInWeek; i++)
		{
		on |= (FrmGetControlValue (frm, index + i) != 0);
		}

	// If all the buttons are off, turn on the start date's button.
	if (! on)
		{
		dayOfWeek = DayOfWeek (details->when.date.month,
			details->when.date.day,
			details->when.date.year+firstYear);
		dayOfWeek = (( dayOfWeek  - 
			details->repeat.repeatStartOfWeek + daysInWeek) % daysInWeek);

		id = RepeatDayOfWeek1PushButton + dayOfWeek;
		CtlSetValue (GetObjectPtr (id), true);
		}

	// Update the display of the repeat descrition.
	RepeatDrawDescription (frm);
	
	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatChangeType
 *
 * DESCRIPTION: This routine changes the ui gadgets in the repeat dialog
 *              such that they match the newly selected repeat type.  The 
 *              routine is called when one of the repeat type push buttons
 *              are pushed.
 *
 * PARAMETERS:  event - pointer to and event
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/7/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatChangeType (EventPtr event)
{
	Word id;
	Word dayOfWeek;
	FormPtr frm;
	DetailsPtr details;
	RepeatType oldType;
	RepeatType newType;
	RepeatInfoType repeat;
	
	// If the type if monthly default to monthly-by-date.
	newType = (RepeatType) (event->data.ctlSelect.controlID - RepeatNone);
	if (newType > repeatWeekly) newType++;

	oldType = RepeatingEventType;
	if (oldType == newType) return;
	
	frm = FrmGetActiveForm ();
	
	// Lock the block that contains the details of the current record.
	details = MemHandleLock (DetailsH);

	// Initialize the ui gadgets.
	if (newType == details->repeat.repeatType)
		RepeatSetUIValues (frm, &details->repeat);
	else
		{
		repeat.repeatType = newType;
		DateToInt(repeat.repeatEndDate) = defaultRepeatEndDate;
		repeat.repeatFrequency = defaultRepeatFrequency;
		repeat.repeatStartOfWeek = StartDayOfWeek;
		if (newType == repeatWeekly)
			{
			dayOfWeek = DayOfWeek (details->when.date.month, 
				details->when.date.day,
				details->when.date.year+firstYear);
			repeat.repeatOn = (1 << dayOfWeek);
			}
		else if (newType == repeatMonthlyByDay)
			{
			repeat.repeatOn = DayOfMonth (details->when.date.month, 
				details->when.date.day,
				details->when.date.year + firstYear);
			}
		else
			{
			repeat.repeatOn = 0;
			}
		RepeatSetUIValues (frm, &repeat);
		}
	

	// Hide the ui gadgets that are unique to the repeat type we are 
	// nolonger editing.
	switch (oldType)
		{
		case repeatNone:
			HideObject (frm, RepeatNoRepeatLabel);
			break;

		case repeatDaily:
			HideObject (frm, RepeatDaysLabel);
			break;
		
		case repeatWeekly:
			HideObject (frm, RepeatWeeksLabel);
			for (id = RepeatRepeatOnLabel; id <= RepeatDayOfWeek7PushButton; id++)
				HideObject (frm, id);
			break;

		case repeatMonthlyByDay:
		case repeatMonthlyByDate:
			HideObject (frm, RepeatMonthsLabel);
			for (id = RepeatByLabel; id <= RepeatByDatePushButon; id++)
				HideObject (frm, id);
			break;

		case repeatYearly:
			HideObject (frm, RepeatYearsLabel);
			break;
		}


	// Handle switching to or from "no" repeat.
	if (oldType == repeatNone)
		{
		ShowObject (frm, RepeatEveryLabel);
		ShowObject (frm, RepeatFrequenceField);
		ShowObject (frm, RepeatEndOnLabel);
		ShowObject (frm, RepeatEndOnTrigger);
		}
	else if (newType == repeatNone)
		{
		HideObject (frm, RepeatEveryLabel);
		HideObject (frm, RepeatFrequenceField);
		HideObject (frm, RepeatEndOnLabel);
		HideObject (frm, RepeatEndOnTrigger);
		}



	// Show the ui object that are appropriate for the new repeat
	// type.
	switch (newType)
		{
		case repeatNone:
			ShowObject (frm, RepeatNoRepeatLabel);
			break;

		case repeatDaily:
			ShowObject (frm, RepeatDaysLabel);
			break;

		case repeatWeekly:
			ShowObject (frm, RepeatWeeksLabel);
			ShowObject (frm, RepeatRepeatOnLabel);
			for (id = RepeatRepeatOnLabel; id <= RepeatDayOfWeek7PushButton; id++)
				ShowObject (frm, id);
			break;
			
		case repeatMonthlyByDay: 
		case repeatMonthlyByDate:
			ShowObject (frm, RepeatMonthsLabel);
			ShowObject (frm, RepeatByLabel);
			ShowObject (frm, RepeatByDayPushButon);
			ShowObject (frm, RepeatByDatePushButon);
			break;

		case repeatYearly:
			ShowObject (frm, RepeatYearsLabel);
			break;
		}	

	RepeatingEventType = newType;
	
	// Update the display of the repeat descrition.
	RepeatDrawDescription (frm);
	
	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatApply
 *
 * DESCRIPTION: This routine applies the changes made in the Repeat Dialog.
 *              The changes or copied to a block intiialize by the 
 *              Details Dialog,  they a not written to the database until
 *              the Details Dialog is applied.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/24/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatApply (void)
{
	DetailsPtr		details;
	RepeatInfoType repeat;


	// Lock the block that contains the details of the current record,
	// this block was initialized by the details dialog initializtion
	// routine.
	details = MemHandleLock (DetailsH);
	
	RepeatGetUIValues (FrmGetActiveForm (), &repeat);
	details->repeat = repeat;

	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatInit
 *
 * DESCRIPTION: This routine initializes tthe "Repeat Dialog Box".  All
 *              the object in the dialog are initialize, even if they
 *              are not used given the current repeat type.
 *
 * PARAMETERS:  frm - pointer to the repeat dialog box
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/4/95	Initial Revision
 *
 ***********************************************************************/
static void RepeatInit (FormPtr frm)
{
	Word				id;
	DetailsPtr		details;


	// Lock the block that contains the details of the current record,
	// this block was initialized by the details dialog initializtion
	// routine.
	details = MemHandleLock (DetailsH);
	

	// Set usable the ui object that are appropriate for the given repeat
	// type.
	switch (details->repeat.repeatType)
		{
		case repeatNone:
			ShowObject (frm, RepeatNoRepeatLabel);
			break;

		case repeatDaily:
			ShowObject (frm, RepeatEveryLabel);
			ShowObject (frm, RepeatFrequenceField);
			ShowObject (frm, RepeatDaysLabel);
			ShowObject (frm, RepeatEndOnLabel);
			ShowObject (frm, RepeatEndOnTrigger);
			break;

		case repeatWeekly:
			ShowObject (frm, RepeatEveryLabel);
			ShowObject (frm, RepeatFrequenceField);
			ShowObject (frm, RepeatWeeksLabel);
			ShowObject (frm, RepeatRepeatOnLabel);
			ShowObject (frm, RepeatEndOnLabel);
			ShowObject (frm, RepeatEndOnTrigger);
			for (id = RepeatDayOfWeek1PushButton; id <= RepeatDayOfWeek7PushButton; id++)
				ShowObject (frm, id);
			break;
			
		case repeatMonthlyByDay: 
		case repeatMonthlyByDate:
			ShowObject (frm, RepeatEveryLabel);
			ShowObject (frm, RepeatFrequenceField);
			ShowObject (frm, RepeatMonthsLabel);
			ShowObject (frm, RepeatByLabel);
			ShowObject (frm, RepeatByDayPushButon);
			ShowObject (frm, RepeatByDatePushButon);
			ShowObject (frm, RepeatEndOnLabel);
			ShowObject (frm, RepeatEndOnTrigger);
			break;

		case repeatYearly:
			ShowObject (frm, RepeatEveryLabel);
			ShowObject (frm, RepeatFrequenceField);
			ShowObject (frm, RepeatYearsLabel);
			ShowObject (frm, RepeatEndOnLabel);
			ShowObject (frm, RepeatEndOnTrigger);
			break;
		}

	RepeatStartOfWeek = sunday;	
	RepeatEndDate = details->repeat.repeatEndDate;
	RepeatingEventType = details->repeat.repeatType;
	
	RepeatSetUIValues (frm, &details->repeat);

	MemPtrUnlock (details);
}


/***********************************************************************
 *
 * FUNCTION:    RepeatHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the "Repeat
 *              Dialog Box".
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event was handled and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/23/95	Initial Revision
 *
 ***********************************************************************/
static Boolean RepeatHandleEvent (EventPtr event)
{
	Word chr;
	FormPtr frm;
	WordPtr charAttr;
	FieldPtr fld;
	Boolean handled = false;

	if (event->eType == ctlSelectEvent)
		{
		switch (event->data.ctlSelect.controlID)
			{
			case RepeatOkButton:
				RepeatApply ();
				FrmGotoForm (DetailsDialog);
				handled = true;
				break;

			case RepeatCancelButton:
				FrmGotoForm (DetailsDialog);
				handled = true;
				break;				

			case RepeatNone:
			case RepeatDaily:
			case RepeatWeekly:
			case RepeatMonthly:
			case RepeatYearly:
				RepeatChangeType (event);
				handled = true;
				break;				

			case RepeatDayOfWeek1PushButton:
			case RepeatDayOfWeek2PushButton:
			case RepeatDayOfWeek3PushButton:
			case RepeatDayOfWeek4PushButton:
			case RepeatDayOfWeek5PushButton:
			case RepeatDayOfWeek6PushButton:
			case RepeatDayOfWeek7PushButton:
				RepeatChangeRepeatOn (event);
				handled = true;
				break;				

			case RepeatByDayPushButon:
			case RepeatByDatePushButon:
				RepeatDrawDescription (FrmGetActiveForm());
				handled = true;
				break;
			}
		}

	else if (event->eType == keyDownEvent)
		{
		charAttr = GetCharAttr();
		chr = event->data.keyDown.chr;
		if (IsDigit (charAttr, chr) || IsCntrl (charAttr, chr))
			{
			fld = GetObjectPtr (RepeatFrequenceField);
			FldHandleEvent (fld, event);
			RepeatDrawDescription (FrmGetActiveForm());
			}
		handled = true;
		}
		
	else if (event->eType == popSelectEvent)
		{
		if (event->data.popSelect.listID == RepeatEndOnList)
			{
			RepeatSelectEndDate (event);			
			handled = true;
			}
		}

	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		RepeatInit (frm);
		FrmDrawForm (frm);
		FrmSetFocus (frm, FrmGetObjectIndex (frm, RepeatFrequenceField));
		RepeatDrawDescription (frm);
		handled = true;
		}

	return (handled);
}


#pragma mark ----------------
/***********************************************************************
 *
 * FUNCTION:    DetailsAlarmOnOff
 *
 * DESCRIPTION: This routine shows or hides the alarm advance ui object.
 *              It is called when the alarm checkbox is turn on or off.
 *
 * PARAMETERS:  on - true to show object, false to hide
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/21/95	Initial Revision
 *
 ***********************************************************************/
 static void DetailsAlarmOnOff (Boolean on)
 {
 	Word advance;
 	Word advanceUnit;
 	CharPtr textP;
 	CharPtr label;
 	VoidHand textH;
 	FormPtr frm;
 	ListPtr lst;
 	FieldPtr fld;
 	ControlPtr ctl;
 
	frm = FrmGetActiveForm ();
	fld = GetObjectPtr (DetailsAlarmAdvanceField);

 	if (on)
 		{
		if (AlarmPreset.advance != apptNoAlarm)
			{
			advance = AlarmPreset.advance;
			advanceUnit = AlarmPreset.advanceUnit;
			}
		else
			{
			advance = defaultAlarmAdvance;
			advanceUnit = defaultAdvanceUnit;
			}
		

		// Set the value of the alarm advance field.
		textH = FldGetTextHandle (fld);
		if (textH) MemHandleFree (textH);
		textH = MemHandleNew (maxAdvanceFieldLen);
		textP = MemHandleLock (textH);
		StrIToA (textP, advance);
		MemPtrUnlock (textP);

		FldSetTextHandle (fld, textH);
		
		// Set the alarm advance unit of measure (minutes, hours, or days).
		lst = GetObjectPtr (DetailsAlarmAdvanceList);		
		LstSetSelection (lst, advanceUnit);
		label = LstGetSelectionText (lst, advanceUnit);

		ctl = GetObjectPtr (DetailsAlarmAdvanceSelector);
		CtlSetLabel (ctl, label);
		ShowObject (frm, DetailsAlarmAdvanceSelector);

		// Show the alarm advance ui objects. 		
 		ShowObject (frm, DetailsAlarmAdvanceField);
 		ShowObject (frm, DetailsAlarmAdvanceSelector);
 		}
 	else
 		{
		FldFreeMemory (fld);

		CtlSetValue (GetObjectPtr (DetailsAlarmCheckbox), false);

		// Hide the alarm advance ui objects. 		
 		HideObject (frm, DetailsAlarmAdvanceField);
 		HideObject (frm, DetailsAlarmAdvanceSelector);
 		}
 }


/***********************************************************************
 *
 * FUNCTION:    DetailsSetTimeTrigger
 *
 * DESCRIPTION: This routine sets the label of the trigger in a details
 *              dialog that displays the appointment's start and end 
 *              time.
 *
 * PARAMETERS:  start  - start time or minus one if no-time event
 *              end    - end time
 *
 * RETURNED:    nothing
 *
 * NOTES:
 *      This routine assumes that the memory allocated for the label of 
 *      the time trigger is large enough to hold the largest posible
 *      label.  This label's memory is reserved by initializing the label
 *      in the resource file.     
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static void DetailsSetTimeTrigger (TimeType start, TimeType end)
{
	CharPtr str;
	CharPtr label;
	ControlPtr ctl;
	CharPtr rscP;

	ctl = GetObjectPtr (DetailsTimeSelector);
	label = CtlGetLabel (ctl);
	
	if (TimeToInt (start) == apptNoTime)
		{
		rscP = MemHandleLock (DmGetResource (strRsc, noTimeStrID));
		StrCopy (label, rscP);
		MemPtrUnlock (rscP);
		}

	else
		{
		str = label;
		TimeToAscii (start.hours, start.minutes, TimeFormat, str);
		str += StrLen (str);
		*str++ = spaceChr;
		*str++ = '-';
		*str++ = spaceChr;
		TimeToAscii (end.hours, end.minutes, TimeFormat, str);
		}
	
	CtlSetLabel (ctl, label);
}


/***********************************************************************
 *
 * FUNCTION:    DetailsSelectTime
 *
 * DESCRIPTION: This routine selects the start date of an appointment.
 *
 * PARAMETERS:  startP - passed:   current start time
 *                       returned: selected start time
 *              endtP  - passed:   current end time
 *                       returned: selected end time
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static void DetailsSelectTime (TimePtr startP, TimePtr endP)
{
	if (GetTime (startP, endP, setTimeTitleStrID))
		{
		DetailsSetTimeTrigger (*startP, *endP);
		if (TimeToInt (*startP) == apptNoTime)
			DetailsAlarmOnOff (false);
		}
}


/***********************************************************************
 *
 * FUNCTION:    DetailsSelectDate
 *
 * DESCRIPTION: This routine selects the start date of an appointment.
 *
 * PARAMETERS:  dateP - passed:   current start date
 *                      returned: selected start date, if selection was
 *                                made
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *       art	4/2/96	Adjusted end of if repeating event
 *
 ***********************************************************************/
static void DetailsSelectDate (DetailsPtr details)
{
	SWord month, day, year;
	CharPtr label;
	CharPtr title;
	ControlPtr ctl;

	year = details->when.date.year + firstYear;
	month = details->when.date.month;
	day = details->when.date.day;
	
	title = MemHandleLock(DmGetResource (strRsc, startDateTitleStrID));

	if (SelectDay (selectDayByDay, &month, &day, &year, title))
		{
		// Set the label of the date selector.
		ctl = GetObjectPtr (DetailsDateSelector);
		label = CtlGetLabel (ctl);
		DateToDOWDMFormat (month, day, year, ShortDateFormat, label);
		CtlSetLabel (ctl, label);

		// Return the date selected.
		details->when.date.day = day;
		details->when.date.month = month;
		details->when.date.year = year - firstYear;


		// If the event repeats monthly-by-day update the day the the 
		// month the event repeats on.
		if (details->repeat.repeatType == repeatMonthlyByDay)
			{
			details->repeat.repeatOn = DayOfMonth (month, day, year + firstYear);
			}
		}

	MemPtrUnlock (title);
}


/***********************************************************************
 *
 * FUNCTION:    DetailsDeleteAppointment
 *
 * DESCRIPTION: This routine deletes an appointment record. It is called 
 *              when the delete button in the details dialog is pressed.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    true if the record was delete or archived.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DetailsDeleteAppointment (void)
{
	Word recordNum;
		
	recordNum = CurrentRecord;

	// Clear the edit state, this will delete the current record if is 
	// blank.
	if (ClearEditState ())
		return (true);

	// Delete the record,  this routine will display an appropriate 
	// dialog to confirm the action.  If the dialog is canceled 
	// don't update the display.
	if (! DeleteRecord (recordNum))
		return (false);

	return (true);
}


/***********************************************************************
 *
 * FUNCTION:    DetailsGet
 *
 * DESCRIPTION: This routine get the current setting of the details
 *              dialog.  
 *
 * PARAMETERS:  details - pointer to a structure that hold the info about
 *                        the current record.
 *
 * RETURNED:    true if the record was delete or archived.
 *
 * NOTE:        Not all the members of the structure passed are filled
 *              in by this routine.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static void DetailsGet (DetailsPtr details)
{
	ListPtr lst;
	FieldPtr fld;
	ControlPtr ctl;
		
	// Get the alarm settings.
	ctl = GetObjectPtr (DetailsAlarmCheckbox);
	if (CtlGetValue (ctl))
		{
		fld = GetObjectPtr (DetailsAlarmAdvanceField);
		details->alarm.advance = StrAToI (FldGetTextPtr (fld));

		lst = GetObjectPtr (DetailsAlarmAdvanceList);		
		details->alarm.advanceUnit = (AlarmUnitType) LstGetSelection (lst);
		}
	else
		details->alarm.advance = apptNoAlarm;		// no alarm is set

	// Get the private setting.
	details->secret = CtlGetValue (GetObjectPtr (DetailsPrivateCheckbox));

}


/***********************************************************************
 *
 * FUNCTION:    DetailsApply
 *
 * DESCRIPTION: This routine applies the changes made in the Details Dialog.
 *
 * PARAMETERS:  details     - appointment details.
 *              attachNote  - true if pressing the note button being caused
 *                            the changes to be applied.
 *              updateCodeP - pointer to a code which indicates how the
 *									   appointment was changed,  this code is send
 *									   as the update code in a frmUpdate event.
 *
 * RETURNED:    true if the changes were applied, false if the changes
 *              were not appield.
 *
 *	NOTE:			 If a note is being attached to a repeating event the 
 *              user is prompted to determine if an exception should be
 *              created,  the exception is create be this routine,  the
 *              note is attached elsewhere.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	3/10/95	Initial Revision
 *			kcr	10/9/95	added 'private records' alert
 *
 ***********************************************************************/
static Boolean DetailsApply (DetailsPtr details, Boolean attachNote,
	WordPtr updateCodeP)
{
	Err					err = 0;
	UInt					attr;
	Word					id;
	Word					repeatOn;
	Word					dayOfWeek;
	Word 					updateCode = 0;
	Word					alertButton;
	ULong					adjust;
	Boolean				dirty = false;
	Boolean				attrDirty = false;
	Boolean				exception = false;
	Boolean				pastRepeats = false;
	FormPtr				alert;
	VoidHand 			recordH;
	ApptDateTimeType	when;
	ApptDBRecordType	apptRec;
	ApptDBRecordType	newRec;
	ApptDBRecordFlags changedFields;
	

	// Get the ui setting for the appointment.
	DetailsGet (details);
	when = details->when;

	// Compare the start date setting in the dialog with the date in the
	// current record.  Update the record if necessary.
	ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);

	MemSet (&changedFields, sizeof (changedFields), 0);

	// Has the start time of the appointment been changed?
	if (TimeToInt(apptRec.when->startTime) != TimeToInt(details->when.startTime))
		{
		when.date = apptRec.when->date;
		newRec.when = &when;
		changedFields.when = true;
		updateCode |= updateTimeChanged;
		dirty = true;
		}


	// Has the end time of the appointment been changed?
	if (TimeToInt(apptRec.when->endTime) != TimeToInt(details->when.endTime))
		{
		when.date = apptRec.when->date;
		newRec.when = &when;
		changedFields.when = true;
		updateCode |= updateTimeChanged;
		dirty = true;
		}


	// Has the date of the appointment been changed?
	if (DateToInt(Date) != DateToInt(details->when.date))
		{
		when.date = details->when.date;
		newRec.when = &when;
		changedFields.when = true;
		updateCode |= updateDateChanged;
		dirty = true;
		}
	


	// Has an alarm been set?
	if ((! apptRec.alarm) && (details->alarm.advance != apptNoAlarm))
		{
		newRec.alarm = &details->alarm;
		changedFields.alarm = true;
		updateCode |= updateAlarmChanged;
		dirty = true;
		}

	// Has an alarm been canceled?
	else if ((apptRec.alarm) && (details->alarm.advance == apptNoAlarm))
		{
		newRec.alarm = NULL;
		changedFields.alarm = true;
		updateCode |= updateAlarmChanged;
		dirty = true;
		}

	// Has the alarm advance-notice-time been changed?
	else if ( (apptRec.alarm) &&
				((apptRec.alarm->advance != details->alarm.advance) ||
				 (apptRec.alarm->advanceUnit != details->alarm.advanceUnit)))
		{
		newRec.alarm = &details->alarm;
		changedFields.alarm = true;
		updateCode |= updateAlarmChanged;
		dirty = true;
		}
	


	// Has a non-repeating event been changed to a repeating event?
	if ((! apptRec.repeat) && (details->repeat.repeatType != repeatNone))
		{
		newRec.repeat = &details->repeat;
		changedFields.repeat = true;
		updateCode |= updateRepeatChanged;
		dirty = true;
		}

	// Has a repeating event beed changed to a non-repeating event?
	else if ((apptRec.repeat) && (details->repeat.repeatType == repeatNone))
		{
		newRec.repeat = NULL;
		updateCode |= updateRepeatChanged;
		changedFields.repeat = true;
		dirty = true;
		}
	
	// Has any of the repeat info been changed?
	else if (apptRec.repeat &&
					(apptRec.repeat->repeatType != details->repeat.repeatType ||
			   	 DateToInt (apptRec.repeat->repeatEndDate) != DateToInt(details->repeat.repeatEndDate) ||
			   	 apptRec.repeat->repeatFrequency != details->repeat.repeatFrequency ||
					 (details->repeat.repeatType == repeatWeekly &&
			 			apptRec.repeat->repeatOn != details->repeat.repeatOn)))
		{
		newRec.repeat = &details->repeat;
		changedFields.repeat = true;
		updateCode |= updateRepeatChanged;
		dirty = true;
		}
	


	// Get the current setting of the secret checkbox and compare it the
	// the setting of the record.
	DmRecordInfo (ApptDB, CurrentRecord, &attr, NULL, NULL);	
	if (((attr & dmRecAttrSecret) == dmRecAttrSecret) != details->secret)
		{
		if (HideSecretRecords)
			updateCode |= updateItemHide;
		attrDirty = true;
		
		if (details->secret && !HideSecretRecords)
			FrmAlert (privateRecordInfoAlert);
		}


	// If the record is a repeating appointment and the repeat info
	// has not been modified,  find out if we should create an exception.
	if (apptRec.repeat && (!changedFields.repeat) && 
	   (dirty || attrDirty))
		{
		alertButton = FrmAlert (ExceptionAlert);

		// If the alert was canceled don't apply any of the changes.
		if (alertButton == ExceptionCancelButton)
			goto cancelExit;

		else if (alertButton == ExceptionCurrentButton)
			{
			updateCode |= updateException;
			exception = true;

			// If the date of the appointment has not be changed then set the
			// date of the exception to the current date.
			if ( ! (updateCode & updateDateChanged))
				when.date = Date;
			}

		else
			// Split the repeating event into two event, one of past occurrences
			// and one for future occurreneces.
			{
			if ( ! (updateCode & updateDateChanged))
				{
				pastRepeats = true;
				when.date = Date;
				newRec.when = &when;
				changedFields.when = true;
				}
			}
		}


	// If the record is a repeating appointment and the repeat info
	// has not been modified,  and a note is being attached, find out if 
	// we should create an exception.
	else if (apptRec.repeat && (!changedFields.repeat) && 
				attachNote && (!apptRec.note))
		{
		alertButton = FrmAlert (RepeatAddNoteAlert);

		// If the alert was canceled don't apply any of the changes.
		if (alertButton == RepeatAddNoteCancelButton)
			goto cancelExit;

		else if (alertButton == RepeatAddNoteCurrentButton)
			{
			updateCode |= updateException;
			exception = true;
			}
		}


	// If the record is a repeating appointment, and the repeat info has been
	// changed, and there are past occurrences of the event then we need
	// to duplicate the event so the past occurrence will continue to exits.
	if (apptRec.repeat && (changedFields.repeat))
		{
		// If any of the repeat info other than the end date has changed
		// then spawn a repeating event for all past occurrences.
		if (apptRec.repeat->repeatType != details->repeat.repeatType ||
			 apptRec.repeat->repeatFrequency != details->repeat.repeatFrequency ||
			 apptRec.repeat->repeatOn != details->repeat.repeatOn)
			{
			pastRepeats = true;

			// If the date of the appointment has not been changed then set the
			// start date of the repeating appointment to the current date.
			if ( ! (updateCode & updateDateChanged))
				{
				updateCode |= updateDateChanged;
				when.date = Date;
				newRec.when = &when;
				changedFields.when = true;
				}
			}
		}


	// If the record is a repeating appointment, and the repeat info has not
	// been changed but the start date has, then we need to adjust the 
	// end date and posible split the event into two event.
	if ((! exception) && apptRec.repeat && (!changedFields.repeat) && 
		 (updateCode & updateDateChanged))
		{
		// If the event is a repeating event and it has an end date, move 
		// the end date such that the duration of the event is maintained.
		if ((DateToInt (apptRec.repeat->repeatEndDate) != apptNoEndDate))
			{
			adjust = DateToDays (apptRec.repeat->repeatEndDate) -
		         DateToDays (apptRec.when->date);
			details->repeat.repeatEndDate = details->when.date;
			DateAdjust (&details->repeat.repeatEndDate, adjust);
			}

		if (DateToInt (details->repeat.repeatEndDate) != 
			 (DateToInt(apptRec.repeat->repeatEndDate)))
			{
			newRec.repeat = &details->repeat;
			changedFields.repeat = true;
			updateCode |= updateRepeatChanged;
			dirty = true;
			}
		}
		

	// If the record is a repeating appointment, and the start date has, 
	// then delete the exceptions list.
	if ((! exception) && apptRec.repeat && (updateCode & updateDateChanged))
		{
		newRec.exceptions = NULL;
		changedFields.exceptions = true;
		dirty = true;
		}


	// If the repeat type is weekly and the start date of the event
	// has been changed,  update the 'repeat on' field, which contains
	// the days of the week the event repeats on, such that the 
	// event occurs on the start date.
	if ((! exception) && (details->repeat.repeatType == repeatWeekly) &&
		 ( (updateCode & updateDateChanged)) && (! changedFields.repeat))
		{
		dayOfWeek = DayOfWeek (apptRec.when->date.month, 
			apptRec.when->date.day,
			apptRec.when->date.year+firstYear);
		details->repeat.repeatOn &= ~(1 << dayOfWeek);
		
		dayOfWeek = DayOfWeek (when.date.month, 
			when.date.day,
			when.date.year+firstYear);
		details->repeat.repeatOn |= (1 << dayOfWeek);

		changedFields.repeat = true;
		newRec.repeat = &details->repeat;
		}
		
		
	// If the repeat type is monthly by day and the start date of the event
	// has been changed, update the repeat on field which contains
	// the date of the month the event repeating on (ex: first friday).
	if ((! exception) && (details->repeat.repeatType == repeatMonthlyByDay) &&
		 ( (updateCode & updateDateChanged) || (! apptRec.repeat) ))
		{
		repeatOn = DayOfMonth (when.date.month,
			when.date.day,
			when.date.year + firstYear);
			
		// If we're in the fourth week, and the fourth week is also the last
		// week,  ask the user which week the event repeats in (fourth or last).
		if ( ((repeatOn / daysInWeek) == 3) &&
		      (when.date.day + daysInWeek > DaysInMonth (
		      	when.date.month, when.date.year + firstYear)))
			{
			alert = FrmInitForm (MonthlyRepeatDialog);
			
			// Set the 4th / last push button.
			if (apptRec.repeat && 
				 apptRec.repeat->repeatType == repeatMonthlyByDay &&
				 apptRec.repeat->repeatOn > dom4thSat)
				id = MonthlyRepeatLastButton;
			else
				id = MonthlyRepeatFourthButton;
			FrmSetControlGroupSelection (alert, MonthlyRepeatWeekGroup,id);

			alertButton = FrmDoDialog (alert);

			if (FrmGetObjectIndex (alert, MonthlyRepeatLastButton) ==
			    FrmGetControlGroupSelection (alert, MonthlyRepeatWeekGroup))
			   repeatOn += daysInWeek;

			FrmDeleteForm (alert);

			if (alertButton == MonthlyRepeatCancel)
				goto cancelExit;
			}
			
		details->repeat.repeatOn = repeatOn;
		newRec.repeat = &details->repeat;
		changedFields.repeat = true;
		}


	// Unlock the appointment record.
	MemHandleUnlock (recordH);

	// Erase the details dialog before the changes are applied to the 
	// database.  It is necessary to do thing in this order because
	// erasing the details dialog may cause a frmUpdate event to be 
	// sent to list view, and the list view may not be able to redraw
	// properly once the database has been changed.
	FrmEraseForm (FrmGetActiveForm());


	// Write the changes to the database.
	if (exception)
		{
		err = ApptAddException (ApptDB, &CurrentRecord, Date);
		if (! err)
			{
			ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);
			MemSet (&newRec, sizeof (newRec), 0);
			newRec.description = apptRec.description;
			newRec.note = apptRec.note;
			newRec.when = &when;
			if (details->alarm.advance != apptNoAlarm)
				newRec.alarm = &details->alarm;
	
			err = CreateException (&newRec, &CurrentRecord);
			MemHandleUnlock (recordH);
			}
		}
	else if (dirty)
		{
		// Craete a copy a the repeating event and set its end date to yesterday.
		if (pastRepeats)
			err = SplitRepeatingEvent (&CurrentRecord);
			
		if (!err)
			err = ApptChangeRecord (ApptDB, &CurrentRecord, &newRec, changedFields);
		}		

	if (err)
		{
		FrmAlert (DeviceFullAlert);
		ClearEditState ();
		updateCode = 0;
		}

	// Save the new secret status if it's been changed.
	else if (attrDirty)
		{
		DmRecordInfo (ApptDB, CurrentRecord, &attr, NULL, NULL);	
		if (details->secret)
			attr |= dmRecAttrSecret;
		else
			attr &= ~dmRecAttrSecret;

		attr |= dmRecAttrDirty;
		DmSetRecordInfo (ApptDB, CurrentRecord, &attr, NULL);
		}

	// If the alarm info has been changed, or if the appointment has 
	// an alarm and the date, time, or repeat info has been changed,
	// reschedule the next alarm.
	if (changedFields.alarm || 
		(apptRec.alarm && (changedFields.when || changedFields.repeat)))
		{
		RescheduleAlarms (ApptDB);
		}


	*updateCodeP = updateCode;
	return (true);
	

	// We're here if the cancel button one of the confirmation dialogs
	// was pressed.	
cancelExit:
	MemHandleUnlock (recordH);
	return (false);	
}



/***********************************************************************
 *
 * FUNCTION:    DetailsExit
 *
 * DESCRIPTION: This routine is called when the details dialog is 
 *              applied or canceled.  It unlocks any memory locked 
 *              and frees any memery allocated by the Details Dialog routine.
 *
 * PARAMETERS:  free - true if allocated memory should be freed
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/21/95	Initial Revision
 *
 ***********************************************************************/
static void DetailsExit (DetailsPtr details, Boolean free)
{
	VoidHand rscH;

	// The label of the repeat trigger is in a locked resource, unlock
	// it.
	rscH = DmGetResource (strRsc, repeatTypesStrID);
	MemHandleUnlock (rscH);
	
	// Free the block that holds the changes to the appointment record. 
	if (free)
		{
		MemPtrFree (details);
		DetailsH = 0;
		}
}


/***********************************************************************
 *
 * FUNCTION:    DetailsInit
 *
 * DESCRIPTION: This routine initializes the Details Dialog, and allocates
 *              and initialize a memory block that hold the record
 *              info to be edited by the details dialog.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    details - memory block that hold info to be edited 
 *                        by the details dialog.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static DetailsPtr DetailsInit (void)
{
	UInt i;
	UInt attr;
	CharPtr rscP;
	CharPtr label;
	CharPtr textP;
	FormPtr frm;
	ListPtr lst;
	FieldPtr fld;
	ControlPtr ctl;
	DetailsPtr details;
	VoidHand textH;
	VoidHand recordH;
	ApptDBRecordType	apptRec;

	// Allocate and initialize a block to hold a temporary copy of the 
	// info from the appointment record, we don't want to apply any changes 
	// to the record until the "Details Dialog" is confirmed.
	if (! DetailsH)
		{
		DetailsH = MemHandleNew (sizeof (DetailsType));
		details = MemHandleLock (DetailsH);
		MemSet (details, sizeof (DetailsType), 0);
		
		// Get a pointer to the appointment record.
		ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);
		
		DmRecordInfo (ApptDB, CurrentRecord, &attr, NULL, NULL);

		details->secret = (attr & dmRecAttrSecret) == dmRecAttrSecret;
		details->when = *apptRec.when;
		details->when.date = Date;
		if (apptRec.alarm)
			details->alarm = *apptRec.alarm;
		else
			details->alarm.advance = apptNoAlarm;

		if (apptRec.repeat)
			details->repeat = *apptRec.repeat;
		else
			{
			details->repeat.repeatType = repeatNone;
			DateToInt (details->repeat.repeatEndDate) = apptNoEndDate;
			}
		
		
		// Unlock the appointment record
		MemHandleUnlock (recordH);
		}
	else
		details = MemDeref (DetailsH);

	// Set the time selector label.
	DetailsSetTimeTrigger (details->when.startTime, details->when.endTime);
	

	// Set the start date selector label.
	ctl = GetObjectPtr (DetailsDateSelector);
	label = CtlGetLabel (ctl);
	DateToDOWDMFormat (details->when.date.month, details->when.date.day, 
		details->when.date.year + firstYear, ShortDateFormat, label);
	CtlSetLabel (ctl, label);

	
	// Set the alarm check box.
	ctl = GetObjectPtr (DetailsAlarmCheckbox);
	CtlSetValue (ctl, (details->alarm.advance != apptNoAlarm));
	
	if (details->alarm.advance != apptNoAlarm)
		{
		frm = FrmGetActiveForm ();
		
		// Set the alarm advance value.
		fld = GetObjectPtr (DetailsAlarmAdvanceField);
		textH = MemHandleNew (maxAdvanceFieldLen);
		textP = MemHandleLock (textH);
		StrIToA (textP, details->alarm.advance);
		MemPtrUnlock (textP);
		FldSetTextHandle (fld, textH);
		ShowObject (frm, DetailsAlarmAdvanceField);
	
		// Set the alarm advance unit of measure (minutes, hours, or days).
		lst = GetObjectPtr (DetailsAlarmAdvanceList);		
		LstSetSelection (lst, details->alarm.advanceUnit);
		label = LstGetSelectionText (lst, details->alarm.advanceUnit);

		ctl = GetObjectPtr (DetailsAlarmAdvanceSelector);
		CtlSetLabel (ctl, label);
		ShowObject (frm, DetailsAlarmAdvanceSelector);
		}
	

	// Set the repeat type selector label.  The label will point
	// to a locked resouce string,  we'll need to unlock this 
	// resource when the dialog is dismissed.
	ctl = GetObjectPtr (DetailsRepeatSelector);
	rscP = MemHandleLock (DmGetResource (strRsc, repeatTypesStrID));
	for (i = 0; i < details->repeat.repeatType; i++)
		rscP += StrLen (rscP) + 1;
	CtlSetLabel (ctl, rscP);
	

	// If the record is mark secret, turn on the secret checkbox.
	ctl = GetObjectPtr (DetailsPrivateCheckbox);
	CtlSetValue (ctl, details->secret);


	return (details);
}


/***********************************************************************
 *
 * FUNCTION:    DetailsHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the "Details
 *              Dialog Box".
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handled and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/20/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DetailsHandleEvent (EventPtr event)
{
	static DetailsPtr	details;

	Word chr;
	Word updateCode = 0;
	FormPtr frm;
	Boolean handled = false;
	WordPtr charAttr;

	if (event->eType == ctlSelectEvent)
		{
		switch (event->data.ctlSelect.controlID)
			{
			case DetailsOkButton:
				if (DetailsApply (details, false, &updateCode))
					{
					DetailsExit (details, true);
					FrmReturnToForm (DayView);
					}
				FrmUpdateForm (DayView, updateCode);
				handled = true;
				break;

			case DetailsCancelButton:
				DetailsExit (details, true);
				FrmUpdateForm (DayView, updateCode);
				FrmReturnToForm (DayView);
				handled = true;
				break;
				
			case DetailsDeleteButton:
				DetailsExit (details, true);
				FrmReturnToForm (DayView);
				if ( DetailsDeleteAppointment ()) 
					updateCode = updateItemDelete;
				FrmUpdateForm (DayView, updateCode);
				handled = true;
				break;
				
			case DetailsNoteButton:
				if (DetailsApply (details, true, &PendingUpdate))
					{
					DetailsExit (details, true);
					FrmCloseAllForms ();
					if (CreateNote (false))
						FrmGotoForm (NoteView);
					else
						FrmGotoForm (DayView);
					}
				handled = true;
				break;
				
			case DetailsTimeSelector:
				DetailsSelectTime (&details->when.startTime, &details->when.endTime);
				handled = true;
				break;

			case DetailsDateSelector:
				DetailsSelectDate (details);
				handled = true;
				break;

			case DetailsAlarmCheckbox:
				DetailsAlarmOnOff (event->data.ctlSelect.on);
				handled = true;
				break;

			case DetailsRepeatSelector:
				DetailsGet (details);
				DetailsExit (details, false);
				FrmGotoForm (RepeatDialog);
				handled = true;
				break;
			}
		}


	else if (event->eType == keyDownEvent)
		{
		chr = event->data.keyDown.chr;
		charAttr = GetCharAttr();
		if (IsDigit (charAttr, chr) || IsCntrl (charAttr, chr))
			{
			FldHandleEvent (GetObjectPtr (DetailsAlarmAdvanceField), event);
			}
		handled = true;
		}


	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		details = DetailsInit ();
		FrmDrawForm (frm);
		FrmSetFocus (frm, FrmGetObjectIndex (frm, DetailsAlarmAdvanceField));
		handled = true;
		}

	return (handled);
}


#pragma mark ----------------
/***********************************************************************
 *
 * FUNCTION:    NoteViewDrawTitle
 *
 * DESCRIPTION: This routine draws the title of the note view.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/3/95	Initial Revision
 *
 ***********************************************************************/
 static void NoteViewDrawTitle (void)
 {
 	short x;
	short maxWidth;
	short winWidth;
	short winHeight;
	Word len;
	Word width;
	FontID curFont;
	CharPtr desc;
	char title[maxNoteTitleLen+4];
	VoidHand recordH;
	RectangleType r;
	ApptDBRecordType	apptRec;
	
	curFont = FntSetFont (noteTitleFont);

	ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);

	desc = apptRec.description;

	WinGetWindowExtent (&winWidth, &winHeight);
	maxWidth = winWidth - 8;
	width = 0;
	*title = 0;
	desc = apptRec.description;
	for (len = 0; len < maxNoteTitleLen; len++)
		{
		if (desc[len] == linefeedChr) break;
		
		title[len] = desc[len];
		title[len+1] = 0;
		width += FntCharWidth (desc[len]);
		
		if (width >= maxWidth) break;
		}

	if ( (width >= maxWidth) && (desc[len] != linefeedChr) )
		{
		maxWidth -= FntCharWidth ('.') * 3;
		while (width > maxWidth)
			{
			width -= FntCharWidth (title[len]);
			len--;
			}
		title[len+1] = '.';
		title[len+2] = '.';
		title[len+3] = '.';
		title[len+4] = 0;
		}

	RctSetRectangle (&r, 0, 0, winWidth, FntLineHeight()+2 );
	WinDrawRectangle (&r, 3);
	x = (winWidth - FntCharsWidth (title, StrLen (title)) + 1 ) / 2;
	WinInvertChars (title, StrLen(title), x, 1);

	MemHandleUnlock (recordH);
	FntSetFont (curFont);
 }
 


/***********************************************************************
 *
 * FUNCTION:    NoteViewUpdateScrollBar
 *
 * DESCRIPTION: This routine update the scroll bar.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/1/96	Initial Revision
 *
 ***********************************************************************/
static void NoteViewUpdateScrollBar (void)
{
	Word scrollPos;
	Word textHeight;
	Word fieldHeight;
	Short maxValue;
	FieldPtr fld;
	ScrollBarPtr bar;

	fld = GetObjectPtr (NoteField);
	bar = GetObjectPtr (NoteScrollBar);
	
	FldGetScrollValues (fld, &scrollPos, &textHeight,  &fieldHeight);

	if (textHeight > fieldHeight)
		maxValue = textHeight - fieldHeight;
	else if (scrollPos)
		maxValue = scrollPos;
	else
		maxValue = 0;

	SclSetScrollBar (bar, scrollPos, 0, maxValue, fieldHeight-1);
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewLoadRecord
 *
 * DESCRIPTION: This routine loads the note db field into the note edit 
 *              object.
 *
 * PARAMETERS:  frm - pointer to the Edit View form
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static void NoteViewLoadRecord (void)
{
	Word offset;
	CharPtr ptr;
	FieldPtr fld;
	VoidHand recordH;
	ApptDBRecordType	apptRec;
	
	// Get a pointer to the note field.
	fld = GetObjectPtr (NoteField);
	
	// Set the font used in the note field.
	FldSetFont (fld, NoteFont);
	
	ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);
	ErrFatalDisplayIf (! apptRec.note, "Invalid record");

	// Compute the offset within the appointment record of the note string.
	// The field object will edit the note in place, its is not copied
	// to the dynamic heap.
	ptr = MemDeref (recordH);
	offset = apptRec.note - ptr;
	FldSetText (fld, recordH, offset, StrLen(apptRec.note)+1);
	
	MemHandleUnlock (recordH);
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewSave
 *
 * DESCRIPTION: This routine removed any empty space that the field
 *              routines may a add to the note,  the field object
 *              modifies the note db field in place.  The current
 *              record is also mark dirty.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static void NoteViewSave (void)
{
	FieldPtr fld;
	Boolean empty = false;

	fld = GetObjectPtr (NoteField);

	// Was the note string modified by the user.
	if (FldDirty (fld))
		{
		// Release any free space in the note field.
		FldCompactText (fld);

		// Mark the record dirty.	
		DirtyRecord (CurrentRecord);
		}
		
	empty = (FldGetTextLength (fld) == 0);


	// Clear the handle value in the field, otherwise the handle
	// will be free when the form is disposed of,  this call also unlocks
	// the handle that contains the note string.
	FldSetTextHandle (fld, 0);
	

	// Remove the note from the record, if it is empty.
	if (empty)
		{
		DeleteNote (false);
		}
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewDeleteNote
 *
 * DESCRIPTION: This routine deletes a the note field from an appointment
 *              record.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    true if the note was deleted.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/4/95	Initial Revision
 *
 ***********************************************************************/
static Boolean NoteViewDeleteNote (void)
{
	Word alertButton;
	FieldPtr fld;
	Boolean exception = false;
	VoidHand recordH;
	ApptDBRecordType apptRec;
	
	ApptGetRecord (ApptDB, CurrentRecord, &apptRec, &recordH);
	MemHandleUnlock (recordH);

	// If we're changing a repeating appointmemt, check if all occurrences
	// are being changed, or if and exception is being created.
	if (apptRec.repeat)
		{
		alertButton = FrmAlert (RepeatDeleteNoteAlert);

		// If the alert was canceled don't delete the note.
		if (alertButton == RepeatDeleteNoteCancelButton)
			return (false);

		else if (alertButton == RepeatDeleteNoteCurrentButton)
			exception = true;
		}

	// Confirm the operation.
	else if (FrmAlert(DeleteNoteAlert) != DeleteNoteYes)
		return (false);


	// Clear the handle value in the field, otherwise the handle
	// will be free when the form is disposed of.  This call also 
	// unlocks the handle that contains the note string.
	fld = GetObjectPtr (NoteField);
	FldCompactText (fld);
	FldSetTextHandle (fld, 0);	

	// Remove the note field form the record.
	if (DeleteNote (exception))
		return (true);

	// If we were unable to delete the note, restore the state of the 
	// note view.  Deletes can fails if the appointment repeats and
	// there not enough space to create an exception.
	NoteViewLoadRecord ();
	
	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewDoCommand
 *
 * DESCRIPTION: This routine preforms the menu command specified.
 *
 * PARAMETERS:  command  - menu item id
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	3/29/95	Initial Revision
 *
 ***********************************************************************/
static Boolean NoteViewDoCommand (Word command)
{
	FieldPtr fld;
	Boolean handled = true;
	
	switch (command)
		{
		case noteTopOfPageCmd:
			fld = GetObjectPtr (NoteField);
			FldSetScrollPosition (fld, 0);
			NoteViewUpdateScrollBar ();
			break;

		case noteBottomOfPageCmd:
			fld = GetObjectPtr (NoteField);
			FldSetScrollPosition (fld, FldGetTextLength (fld));
			NoteViewUpdateScrollBar ();
			break;
			
		case notePhoneLookupCmd:
			fld = GetObjectPtr (NoteField);
			PhoneNumberLookup (fld);
			break;
			
		case noteFontCmd:
			NoteFont = SelectFont (NoteFont);
			break; 

		default:
			handled = false;
		}	
	return (handled);
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewScroll
 *
 * DESCRIPTION: This routine scrolls the mote Note View a page or a 
 *              line at a time.
 *
 * PARAMETERS:  direction - up or dowm
 *              oneLine   - true if scrolling a single line
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/1/96	Initial Revision
 *
 ***********************************************************************/
static void NoteViewScroll (Short linesToScroll)
{
	Word				blankLines;
	Short				min;
	Short				max;
	Short				value;
	Short				pageSize;
	FieldPtr			fld;
	ScrollBarPtr	bar;
	
	fld = GetObjectPtr (NoteField);

	if (linesToScroll < 0)
		{
		blankLines = FldGetNumberOfBlankLines (fld);
		FldScrollField (fld, -linesToScroll, up);
		
		// If there were blank lines visible at the end of the field
		// then we need to update the scroll bar.
		if (blankLines)
			{
			// Update the scroll bar.
			bar = GetObjectPtr (NoteScrollBar);
			SclGetScrollBar (bar, &value, &min, &max, &pageSize);
			if (blankLines > -linesToScroll)
				max += linesToScroll;
			else
				max -= blankLines;
			SclSetScrollBar (bar, value, min, max, pageSize);
			}
		}

	else if (linesToScroll > 0)
		FldScrollField (fld, linesToScroll, down);
}

/***********************************************************************
 *
 * FUNCTION:    NoteViewPageScroll
 *
 * DESCRIPTION: This routine scrolls the message a page up or down.
 *
 * PARAMETERS:   direction     up or down
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/1/96	Initial Revision
 *
 ***********************************************************************/
static void NoteViewPageScroll (DirectionType direction)
{
	Short value;
	Short min;
	Short max;
	Short pageSize;
	Word linesToScroll;
	FieldPtr fld;
	ScrollBarPtr bar;

	fld = GetObjectPtr (NoteField);
	
	if (FldScrollable (fld, direction))
		{
		linesToScroll = FldGetVisibleLines (fld) - 1;
		FldScrollField (fld, linesToScroll, direction);

		// Update the scroll bar.
		bar = GetObjectPtr (NoteScrollBar);
		SclGetScrollBar (bar, &value, &min, &max, &pageSize);

		if (direction == up)
			value -= linesToScroll;
		else
			value += linesToScroll;
		
		SclSetScrollBar (bar, value, min, max, pageSize);
		return;
		}
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewInit
 *
 * DESCRIPTION: This routine initializes the Note View form.
 *
 * PARAMETERS:  frm - pointer to the Note View form.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	3/31/95	Initial Revision
 *
 ***********************************************************************/
static void NoteViewInit (FormPtr frm)
{
	
	NoteViewLoadRecord ();

	// Hide the font controls that are used in version 1.0 and 2.0 .
	FrmHideObject (frm, FrmGetObjectIndex (frm, NoteSmallFontButton));
	FrmHideObject (frm, FrmGetObjectIndex (frm, NoteLargeFontButton));
}


/***********************************************************************
 *
 * FUNCTION:    NoteViewHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the "Note View".
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handled and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/3/95	Initial Revision
 *
 ***********************************************************************/
static Boolean NoteViewHandleEvent (EventPtr event)
{
	Word pos;
	FormPtr frm;
	FieldPtr fld;
	Boolean handled = false;

	if (event->eType == keyDownEvent)
		{
		// Datebook button pressed?
		if (ChrIsHardKey(event->data.keyDown.chr))
			{
			NoteViewSave ();
			ClearEditState ();
			DateSecondsToDate (TimGetSeconds (), &Date);
			FrmGotoForm (DayView);
			handled = true;
			}

		else if (event->data.keyDown.chr == pageUpChr)
			{
			NoteViewPageScroll (up);
			handled = true;
			}

		else if (event->data.keyDown.chr == pageDownChr)
			{
			NoteViewPageScroll (down);
			handled = true;
			}
		}


	else if (event->eType == ctlSelectEvent)
		{		
		switch (event->data.ctlSelect.controlID)
			{
			case NoteDoneButton:
				NoteViewSave ();
				FrmGotoForm (DayView);
				handled = true;
				break;

			case NoteDeleteButton:
				if (NoteViewDeleteNote())
					FrmGotoForm (DayView);
				handled = true;
				break;
			}
		}


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

	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		NoteViewInit (frm);
		NoteViewDrawTitle ();
		FrmDrawForm (frm);
		NoteViewUpdateScrollBar ();
		FrmSetFocus (frm, FrmGetObjectIndex (frm, NoteField));
		handled = true;
		}
		

	else if (event->eType == frmGotoEvent)
		{
		frm = FrmGetActiveForm ();
		CurrentRecord = event->data.frmGoto.recordNum;
		SetDateToNextOccurrence (CurrentRecord);
		NoteViewInit (frm);

		fld = GetObjectPtr (NoteField);
		pos = event->data.frmGoto.matchPos;
		FldSetScrollPosition (fld, pos);
		FldSetSelection (fld, pos, pos + event->data.frmGoto.matchLen);

		NoteViewDrawTitle ();
		FrmDrawForm (frm);
		NoteViewUpdateScrollBar ();
		FrmSetFocus (frm, FrmGetObjectIndex (frm, NoteField));
		handled = true;
		}
		

	else if (event->eType == fldChangedEvent)
		{
		frm = FrmGetActiveForm ();
		NoteViewUpdateScrollBar ();
		handled = true;
		}
		

	else if (event->eType == frmUpdateEvent)
		{
		if (event->data.frmUpdate.updateCode & updateFontChanged)
			{
			fld = GetObjectPtr (NoteField);
			FldSetFont (fld, NoteFont);
			NoteViewUpdateScrollBar ();
			handled = true;
			}
		else
			{
			frm = FrmGetActiveForm ();
			NoteViewDrawTitle ();
			FrmDrawForm (frm);
			handled = true;
			}
		}


	else if (event->eType == frmCloseEvent)
		{
		if ( FldGetTextHandle (GetObjectPtr (NoteField)))
			NoteViewSave ();
		}


	else if (event->eType == sclRepeatEvent)
		{
		NoteViewScroll (event->data.sclRepeat.newValue - 
			event->data.sclRepeat.value);
		}

	return (handled);
}


#pragma mark ----------------
/***********************************************************************
 *
 * FUNCTION:    DayViewRestoreEditState
 *
 * DESCRIPTION: This routine restores the edit state of the day view,
 *              if the view is in edit mode. This routine is 
 *              called when the time of an appointment is changed, or when
 *              returning from the details dialog or note view.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/28/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewRestoreEditState ()
{
	Word row;
	ULong uniqueID;
	FormPtr frm;
	TablePtr table;
	FieldPtr fld;

	if ( ! ItemSelected) return;

	// Find the row that the current record is in.  It's posible 
	// that the current record is no longer displayable (ex: the record
	// has marked private).
	table = GetObjectPtr (DayTable);
	DmRecordInfo (ApptDB, CurrentRecord, NULL, &uniqueID, NULL);

	if ( ! TblFindRowData (table, uniqueID, &row) )
		{
		ClearEditState ();
		return;
		}

	frm = FrmGetActiveForm ();
	FrmSetFocus (frm, FrmGetObjectIndex (frm, DayTable));
	TblGrabFocus (table, row, descColumn);
	
	// Restore the insertion point position.
	fld = TblGetCurrentField (table);
	FldSetInsPtPosition (fld, DayEditPosition);
	if (DayEditSelectionLength)
		FldSetSelection (fld, DayEditPosition, DayEditPosition + DayEditSelectionLength);

	FldGrabFocus (fld);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewClearEditState
 *
 * DESCRIPTION: This routine clears the edit state of the day view.
 *              It is called whenever a table item is selected.
 *
 *              If the new item selected is in a different row than
 *              the current record the edit state is cleared,  and if 
 *              current record is empty it is deleted.
 *
 * PARAMETERS:  newRow - row number of newly table item
 *
 * RETURNED:    true if the current record is deleted and items
 *              of the table have been move around on the display
 *              as a result.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/28/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewClearEditState (void)
{
	Word row;
	Word numAppts;
	ULong uniqueID;
	TablePtr table;

	if ( ! ItemSelected)
		{
		CurrentRecord = noRecordSelected;
		return (false);
		}

	table = GetObjectPtr (DayTable);
	DmRecordInfo (ApptDB, CurrentRecord, NULL, &uniqueID, NULL);
	ErrFatalDisplayIf ( (! TblFindRowData (table, uniqueID, &row)), 
		"Wrong record");

	TblReleaseFocus (table);

	// If a different row has been selected, clear the edit state, this 
	// will delete the current record if its empty.
	if (ClearEditState ())
		{
		numAppts = NumAppts;

		// Layout the day again, empty time slots may needed to be add to 
		// full-in the gap left by the deleted appointment.
		DayViewLayoutDay (true);
		
		DayViewLoadTable ();
		TblRedrawTable (table);
		DayViewDrawTimeBars ();

		// If the number of appointments has changed as a result of
		// deleting the currently selected empty appointment, then 
		// the item in the table have move around and tblEnter event
		// should be ignored.
		return (numAppts != NumAppts);
		}

	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewFindAppointment
 *
 * DESCRIPTION: Given the database index of a record, this routine 
 *              finds the record in the appointment list and returns
 *              the index of the appointment
 *
 * PARAMETERS:  recordNum - db index of record to fine 
 *              recordNum - 
 *
 * RETURNED:   appointment list index
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/27/95	Initial Revision
 *
 ***********************************************************************/
static Word DayViewFindAppointment (Word recordNum)
{
	Int i;
	ApptInfoPtr appts;
	
	appts = MemHandleLock (ApptsH);

	for (i = 0; i < NumAppts; i++)
		{
		if (appts[i].recordNum == recordNum)
			{
			MemPtrUnlock (appts);
			return (i);
			}
		}

	MemPtrUnlock (appts);

	// If we're beyond the maximun number of appointment that can be 
	// shown on a day, then the record passed may not be in the list.
	if (NumApptsOnly >= apptMaxPerDay)
		{
		ClearEditState ();
		return (0);
		}

	
	ErrDisplay ("Record not on day");

	return (0);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewSetTopAppointment
 *
 * DESCRIPTION: This routine determines the first appointment that should
 *              be visible on the current day.  For all dates other than
 *              today the fisrt time slot of the appointment list
 *              is the first visible appointment.  For today the time
 *              slot that stats before to the current time should be the top 
 *              visible time slot.
 *
 * PARAMETERS:  nothing.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewSetTopAppointment (void)
{
	Int i;
	TimeType time;
	DateTimeType dateTime;
	ApptInfoPtr appts;

	TopVisibleAppt = 0;

	TimSecondsToDateTime (TimGetSeconds (), &dateTime);

	// If the current date is not today, then the first appointment 
	// is the first one visible.
	if ( (dateTime.year - firstYear != Date.year) ||
		  (dateTime.month != Date.month) ||
		  (dateTime.day != Date.day))
		{
		return;
		}

	// If the current date is today, then the top visible appointment is
	// the appointment with the greatest end time that is before the 
	// current time.
	time.hours = dateTime.hour;
	time.minutes = dateTime.minute;
	
	appts = MemHandleLock (ApptsH);
	for (i = 0; i < NumAppts; i++)
		{
		if (TimeToInt (appts[i].endTime) < TimeToInt (time))
			TopVisibleAppt = i;
		}

	MemPtrUnlock (appts);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDrawTime
 *
 * DESCRIPTION: This routine draws the start time of an appointment.  This
 *              routine is called by the table object as a callback 
 *              routine.
 *
 * PARAMETERS:  table  - pointer to the memo Day table (TablePtr)
 *              row    - row of the table to draw
 *              column - column of the table to draw
 *              bounds - region to draw in 
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *			kcr	11/14/95	Display 'no time' char for untimed events
 *
 ***********************************************************************/
static void DayViewDrawTime (VoidPtr table, Word row, Word column, 
	RectanglePtr bounds)
{
	Int apptIndex;
	Word len;
	Word width = 8;
	Word height = 2;
	Word recordNum;
	Short x;
	char timeStr [timeStringLength];
	FontID curFont;
	TimeFormatType format;
	TimeType startTime;
	ApptInfoPtr appts;
	

	// Get the appointment index that corresponds to the table item.
	// The index of the appointment in the appointment list, is stored
	// as the row id.
	apptIndex =TblGetRowID (table, row);

	// Get the start time of the appointment.
	appts = MemHandleLock (ApptsH);
	startTime = appts[apptIndex].startTime;
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);
	
	// No-time appointment?
	if (TimeToInt(startTime) == apptNoTime)
		{
		curFont = FntSetFont (symbolFont);

		timeStr[0] = symbolNoTime;
		//	Center the single symbol horizontally in the time rectangle
		WinDrawChars (timeStr,
						  1,
						  bounds->topLeft.x +
								(bounds->extent.x - FntCharWidth (symbolNoTime)) / 2,
						  bounds->topLeft.y);
		}
		
	else
		{
		curFont = FntSetFont (apptTimeFont);

		if (TimeFormat == tfColonAMPM)
			format = tfColon;
		 else if (TimeFormat == tfDotAMPM)
		 	format = tfDot;
		 else
			format = TimeFormat;

		TimeToAscii (startTime.hours, startTime.minutes, format, timeStr);
		
		// Left justify.
		len = StrLen (timeStr);
		x = bounds->topLeft.x + (bounds->extent.x - FntCharsWidth (timeStr, len));

		WinDrawChars (timeStr, len, x, bounds->topLeft.y);	
		}	

	FntSetFont (curFont);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDrawIcons
 *
 * DESCRIPTION: This routine draws the note, alarm and repeat icons.
 *              It is called by the table object as a callback 
 *              routine. 
 *
 * PARAMETERS:  table  - pointer to the memo Day table (TablePtr)
 *              row    - row of the table to draw
 *              column - column of the table to draw
 *              bounds - region to draw in 
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/16/96	Initial Revision
 *
 ***********************************************************************/
static void DayViewDrawIcons (VoidPtr table, Word row, Word column, 
	RectanglePtr bounds)
{
	Char					chr;
	Int					apptIndex;
	Word 					recordNum;
	Short					x, y;
	FontID				curFont;
	VoidHand 			recordH;
	ApptInfoPtr 		appts;
	ApptDBRecordType	apptRec;

	// Get the appointment index that corresponds to the table item.
	// The index of the appointment in the appointment list, is stored
	// as the row id.
	apptIndex =TblGetRowID (table, row);

	// Get the start time of the appointment.
	appts = MemHandleLock (ApptsH);
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);

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

	x = bounds->topLeft.x + bounds->extent.x - TblGetItemInt (table, row, column);
	y = bounds->topLeft.y;
	curFont = FntSetFont (symbolFont);

	// Draw note icon
	if (apptRec.note)
		{
		chr = symbolNote;
		WinDrawChars (&chr, 1, x, y);
		x += FntCharWidth (chr) + 1;
		}

	// Draw alarm icon
	if (apptRec.alarm)
		{
		chr = symbolAlarm;
		WinDrawChars (&chr, 1, x, y);
		x += FntCharWidth (chr) + 1;
		}

	// Draw repeat icon
	if (apptRec.repeat)
		{
		chr = symbolRepeat;
		WinDrawChars (&chr, 1, x, y);
		x += FntCharWidth (chr) + 1;
		}

	FntSetFont (curFont);

	MemHandleUnlock (recordH);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewCheckForConflicts
 *
 * DESCRIPTION: This routine check the apointment list for conflicts
 *              (overlapping appointmens).
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    the number of columns of time bars necessary to display
 *              the conflicts
 *              
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/3/96	Initial Revision
 *
 ***********************************************************************/
static Word DayViewCheckForConflicts (void)
{
	Int				i;
	Int				numColumns;
	Int				apptIndex;
	Word				width;
	TablePtr			table;
	TimeType			endTime [maxTimeBarColumns];
	ApptInfoPtr		appts;
	RectangleType	tableR;
	
	MemSet (endTime, sizeof (endTime), 0);

	numColumns = 1;

	appts = MemHandleLock (ApptsH);
	for (apptIndex = 0; apptIndex < NumAppts; apptIndex++)
		{
		if (appts[apptIndex].recordNum == emptySlot)
			continue;

		else if (TimeToInt (appts[apptIndex].startTime) == apptNoTime)
			continue;

		for (i = 0; i < maxTimeBarColumns; i++)
			{
			if (TimeToInt (appts[apptIndex].startTime) >= TimeToInt (endTime[i]))
				{
				endTime[i] = appts[apptIndex].endTime;
				if (i+1 > numColumns)
					numColumns = i+1;
				break;
				}
			}
		}
	MemPtrUnlock (appts);
	

	// Reserve spase for the time bars.  We will show time bars if the user
	// has requested them or if there are overlapping appointments.
	if (numColumns == 1 && (! ShowTimeBars))
		numColumns = 0;

	if (TimeBarColumns != numColumns)
		{
		TimeBarColumns = numColumns;
		table = GetObjectPtr (DayTable);
		
		// Set the width of the time bar table column.
		TblSetColumnWidth (table, timeBarColumn, numColumns * timeBarWidth);
		
		// Adjust the width of the description column.
		TblGetBounds (table, &tableR);
		width = tableR.extent.x - 
				  (numColumns * timeBarWidth) -
 				  TblGetColumnWidth (table, timeColumn) -
 				  TblGetColumnSpacing (table, timeColumn);
 		TblSetColumnWidth (table, descColumn, width);
 		
 		// Invalid the whole table since the positions of the time and 
 		// description columns has changed.
 		TblMarkTableInvalid (table);
		}

	return (numColumns);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDrawTimeBars
 *
 * DESCRIPTION: This routine draw the time bars the indicate the durations
 *              of apointments.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *              
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/3/96	Initial Revision
 *
 ***********************************************************************/
static void DayViewDrawTimeBars (void)
{
	Int				i, j;
	Int				numColums = 0;
	Int				apptIndex;
	Int				numColumns;
	Word				row;
	Word				lineHeight;
	Short				x, y1, y2;
	FontID			curFont;
	TablePtr			table;
	Boolean			drawTop;
	Boolean			drawBottom;
	Short				endPoint [maxTimeBarColumns];
	TimeType			endTime [maxTimeBarColumns];
	ApptInfoPtr		appts;
	RectangleType	r;
	RectangleType	tableR;
	RectangleType	eraseR;
	

	if (! TimeBarColumns) return;

	MemSet (endTime, sizeof (endTime), 0);
	numColumns = 1;

	table = GetObjectPtr (DayTable);
	TblGetBounds (table, &tableR);

	for (i = 0; i < maxTimeBarColumns; i++)
		endPoint[i] = tableR.topLeft.y;

	curFont = FntSetFont (apptTimeFont);
	lineHeight = FntLineHeight ();
	FntSetFont (curFont);

	appts = MemHandleLock (ApptsH);
	for (apptIndex = 0; apptIndex < NumAppts; apptIndex++)
		{
		if (appts[apptIndex].recordNum == emptySlot)
			continue;
		else if (TimeToInt (appts[apptIndex].startTime) == apptNoTime)
			continue;
		
		for (i = 0; i < maxTimeBarColumns; i++)
			{
			if (TimeToInt (appts[apptIndex].startTime) >= TimeToInt (endTime[i]))
				{
				endTime[i] = appts[apptIndex].endTime;
				
				// Find the row that hold the appointment, it may not be
				// visible.
				if (TblFindRowID (table, apptIndex, &row))
					{
					TblGetItemBounds (table, row, descColumn, &r);
					y1 = r.topLeft.y + (lineHeight >> 1);
					drawTop = true;
					}

				// Is the appointment off the top of the display.
				else if (apptIndex < TopVisibleAppt)
					{
					y1 = tableR.topLeft.y;
					drawTop = false;
					}

				// If the appointment is below the bottom of the display we
				// don't draw anything.	
				else 
					break;


				// Find the row that contains the end time of the appointment.
				for (j = apptIndex + 1; j < NumAppts; j++)
					{
					// There may be more the one time slot with the time
					// we're searching for, get the last one.
					if (TimeToInt (appts[apptIndex].endTime) <=
						 TimeToInt (appts[j].startTime))
						break;
					}

				// Is the end-time visible.
				if (TblFindRowID (table, j, &row))
					{
					TblGetItemBounds (table, row, descColumn, &r);
					y2 = r.topLeft.y + (lineHeight >> 1);
					drawBottom = true;				
					}

				// Is the end of the appointment off the top of the display, if so
				// don't draw anything.
				else if (j < TopVisibleAppt)
					break;

				else
					{
					y2 = tableR.topLeft.y + tableR.extent.y - 1;
					drawBottom = false;				
					}

				x = tableR.topLeft.x + (i * timeBarWidth);


				// Erase the region between the top of the time bar we're
				// about to draw and the bottom of the previous time bar.
				if (y1 > endPoint[i])
					{
					eraseR.topLeft.x = x;
					eraseR.topLeft.y = endPoint[i];
					eraseR.extent.x = timeBarWidth;
					eraseR.extent.y = y1 - endPoint[i];
					WinEraseRectangle (&eraseR, 0);
					}
				endPoint[i] = y2 + 1;
				

				// Draw the time bar.
				WinEraseLine (x+1, y1+1, x+1, y2-2);

				if (drawTop) y1++;
				if (drawBottom) y2--;

				WinDrawLine (x, y1, x, y2);
				if (drawTop)
					WinDrawLine (x, y1, x + timeBarWidth - 1, y1);
				if (drawBottom)
					WinDrawLine (x, y2, x + timeBarWidth - 1, y2);
				
				if (i+1 > numColumns)
					numColumns = i+1;

				break;
				}
			}
		}
		
	// Erase the regions between the botton of the last time bar in 
	// each column and the bottom of the table.
	for (i = 0; i < numColumns; i++)
		{
		if (tableR.topLeft.y + tableR.extent.y > endPoint[i])
			{
			eraseR.topLeft.x = tableR.topLeft.x + (i * timeBarWidth);
			eraseR.topLeft.y = endPoint[i];
			eraseR.extent.x = timeBarWidth;
			eraseR.extent.y = tableR.topLeft.y + tableR.extent.y - endPoint[i];
			WinEraseRectangle (&eraseR, 0);
			}
		}
	
	MemPtrUnlock (appts);
	}


/***********************************************************************
 *
 * FUNCTION:    DayViewInsertAppointment
 *
 * DESCRIPTION: This routine inserts the record index of a new record 
 *              into the structure that keeps track of the appointment
 *              on the current day.
 *
 * PARAMETERS:  apptIndex - 
 *              recordNum - appointment record index
 *              row       - row in the table object of the new record
 *
 * RETURNED:   nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/28/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewInsertAppointment (Int apptIndex, Word recordNum, Word row)
{
	Int i;
	ULong uniqueID;
	TablePtr table;
	ApptInfoPtr appts;
	
	appts = MemHandleLock (ApptsH);

	// Adjust all the record index that are greater than the new record.
	for (i = 0; i < NumAppts; i++)
		{
		if ((appts[i].recordNum != emptySlot) && 
			 (appts[i].recordNum >= recordNum))
			appts[i].recordNum++;
		}

	appts[apptIndex].recordNum = recordNum;
//	appts[apptIndex].endTime.hours = appts[apptIndex].startTime.hours + 1;

	MemHandleUnlock (ApptsH);

	// Store the unique id of the record in the row.
	table = GetObjectPtr (DayTable);
	DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL);
	TblSetRowData (table, row, uniqueID);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewGetDescription
 *
 * DESCRIPTION: This routine returns a pointer to the description field
 *              of a appointment record.  This routine is called by 
 *              the table object as a callback routine when it wants to 
 *              display or edit the appointment's description.
 *
 * PARAMETERS:  table         - pointer to the Day View table (TablePtr)
 *              row           - row in the table
 *              column        - column in the table
 *              editable      - true if the field will be edited by the table
 *              textOffset    - offset within the record of the desc field (returned)
 *              textAllocSize - allocated size the the description field (returned)
 *
 * RETURNED:    handle of the appointment record
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static Err DayViewGetDescription (VoidPtr table, Word row, Word column,
	Boolean editable, VoidHand * textH, WordPtr textOffset, 
	WordPtr textAllocSize, FieldPtr fld)
{
	Err error = 0;
	Int apptIndex;
	Word recordNum;
	CharPtr recordP;
	VoidHand recordH;
	Boolean redraw = false;
	FieldAttrType attr;
	ApptInfoPtr appts;
	ApptDBRecordType apptRec;
	ApptDateTimeType when;
//	Word height;
//	Word iconsWidth;
//	Word tableHeight;
//	Word columnWidth;
//	ULong uniqueID;
//	FontID fontID;
//	RectangleType r;
	
	*textH = 0;

	// Get the appoitment that corresponds to the table item.
	// The index of the appointment in the appointment list, is stored
	// as the row id.
	apptIndex = TblGetRowID (table, row);

	// Get the record index of the next appointment,  empty time slots 
	// have a minus one in the recordNum field.
	appts = MemHandleLock (ApptsH);
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);

	if (recordNum == -1)
		{
		// If we're drawing the description, return a null handle.
		if  (! editable) 
			return (0);

		// If we have reached the maximum number of displayable event, then
		// exit returning an error.
		if (NumApptsOnly >= apptMaxPerDay)
			return (-1);


		// If we're editing the description, create a new record.
		MemSet (&apptRec, sizeof (apptRec), 0);

		appts = MemHandleLock (ApptsH);
		when.startTime = appts[apptIndex].startTime;

		// If the start time is before 11:00 pm, the end time is one hour 
		// after the start time.
		if (when.startTime.hours < maxHours)
			{
			when.endTime.hours = when.startTime.hours + 1;
			when.endTime.minutes = when.startTime.minutes;
			}
			
		// If the start time is 11:00 pm or later, the end time is 11:55 pm. 
		else
			{
			when.endTime.hours = maxHours;
			when.endTime.minutes = maxMinutes;
			}

			// Don't let the new appointment overlap the next appointment.
		if (((apptIndex+1) < NumAppts) &&
			 (TimeToInt(when.endTime) > TimeToInt(appts[apptIndex+1].startTime)))
			{
			when.endTime = appts[apptIndex+1].startTime;
			appts[apptIndex].endTime = when.endTime;
			}

			// If the end time of the new event is not currently displayed, then
		// don't redraw the time bars.  We need to redraw the day, but we cannot
		// do it here.  We'll redraw the row on the tblSelect event.
		if (((apptIndex+1) == NumAppts) ||
			 (((apptIndex+1) < NumAppts) &&
				(TimeToInt(when.endTime) < TimeToInt(appts[apptIndex+1].startTime))))
			{
			redraw = true;
			TblMarkRowInvalid (table, row);
			}

		// If the description font is a different than the empty appointment font 
		// then we need to redraw the day, but we cannot
		// do it here.  We'll redraw the row on the tblSelect event.
		if (ApptDescFont != apptEmptyDescFont)
			{
			redraw = true;
			TblMarkRowInvalid (table, row);
			}

		MemHandleUnlock (ApptsH);

		when.date = Date;
		apptRec.when = &when;

		// Make sure the record has a description field so that we have
		// something to edit.
		apptRec.description = "";
		
		if (AlarmPreset.advance != apptNoAlarm)
			apptRec.alarm = &AlarmPreset;

		error = ApptNewRecord (ApptDB, &apptRec, &recordNum);

		if (error)
			{
			FrmAlert (DeviceFullAlert);
			return (error);
			}

		DayViewInsertAppointment (apptIndex, recordNum, row);

		// If the alarm preset preference is set we needed to reinitialize the
		// row so that the alarm icon will draw.  We don't redraw the row
		// here, we'll do that on the tblSelect event.
		if (AlarmPreset.advance != apptNoAlarm)
			{
//			columnWidth = TblGetColumnWidth (table, descColumn);
//			TblGetBounds (table, &r);
//			tableHeight = r.extent.y;
//			height = DayViewGetDescriptionHeight (apptIndex, columnWidth, tableHeight, &iconsWidth, &fontID);
//			DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL);
//			appts = MemHandleLock (ApptsH);
//			DayViewInitRow (table, row, apptIndex, height, uniqueID, iconsWidth, fontID);
//			MemPtrUnlock (appts);

			TblMarkRowInvalid (table, row);
			}

		if (! redraw)
			DayViewDrawTimeBars ();
		}


	// Get the offset and length of the description field 
	ApptGetRecord (ApptDB, recordNum, &apptRec, &recordH);
	
	
	if (apptRec.description == NULL)
		{
		ApptDBRecordFlags changedFields;
		
		
		// Add the note to the record.
		MemSet (&changedFields, sizeof (changedFields), 0);
		changedFields.description = true;
		apptRec.description = "";
		error = ApptChangeRecord (ApptDB, &recordNum, &apptRec, changedFields);
		if (error) return error;
		
		ApptGetRecord (ApptDB, recordNum, &apptRec, &recordH);
		}
	
	recordP = MemDeref (recordH);
	*textOffset = apptRec.description - recordP;
	*textAllocSize = StrLen (apptRec.description) + 1;  // one for null terminator
	*textH = recordH;
	MemHandleUnlock (recordH);

	// Set the field to support auto-shift.
	if (fld)
		{
		FldGetAttributes (fld, &attr);
		attr.autoShift = true;
		FldSetAttributes (fld, &attr);
		}

	return (0);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewSaveDescription
 *
 * DESCRIPTION: This routine saves the description field of a appointment 
 *              to its db record.  This routine is called by the table 
 *              object, as a callback routine, when it wants to save
 *              the description.
 *
 * PARAMETERS:  table  - pointer to the memo Day table (TablePtr)
 *              row    - row of the table to draw
 *              column - column of the table to draw 
 *
 * RETURNED:    true if the table needs to be redrawn
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewSaveDescription (VoidPtr table, Word row, Word column)
{
	Word recordNum;
	Int apptIndex;
	Word selectStart, selectEnd;
	Boolean dirty;
	FieldPtr fld;
	ApptInfoPtr appts;
	
	
	// Get the appointment that corresponds to the table item passed.
	apptIndex = TblGetRowID (table, row);

	// Get the record index of the appointment,  empty time slots 
	// have a minus one in the recordNum field.
	appts = MemHandleLock (ApptsH);
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);

	ErrFatalDisplayIf ( (recordNum == -1), "Error saving appointment");


	// If the description has been modified mark the record dirty,  any 
	// change made to the description were written directly to the 
	// record by the field object.
	fld = TblGetCurrentField (table);
	dirty = FldDirty (fld);
	if (dirty)
		DirtyRecord (recordNum);


	// Save the dirty state, we'll need it if we auto-delete an empty record.
	RecordDirty = dirty;

	// Check if the top of the description is scroll off the top of the 
	// field, if it is then redraw the field.
	if (FldGetScrollPosition (fld))
		{
		FldSetSelection (fld, 0, 0);
		FldSetScrollPosition (fld, 0);
		DayEditPosition = 0;
		DayEditSelectionLength = 0;
		}

	// Save the insertion point position, and length of the selection.  
	// We'll need the insertion point position an selection length
	// if we put the table back into edit mode.
	else
		{
		DayEditPosition = FldGetInsPtPosition (fld);
		
		FldGetSelection (fld, &selectStart, &selectEnd);
		DayEditSelectionLength = selectEnd - selectStart;
		if (DayEditSelectionLength)
			DayEditPosition = selectStart;
		}

	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewGetDescriptionHeight
 *
 * DESCRIPTION: This routine returns the height, in pixels, of the 
 *              description field of an appointment record.
 *
 * PARAMETERS:  apptIndex   - index in appointment list
 *              width       - width of the description column
 * 				 maxHeight   - the maximum height of the field
 *              iconsWidthP - space ot reserve for note, alarm and 
 *                            repeat icons
 *              fontIdP     - font id to draw the text with,
 *
 * RETURNED:    height in pixels
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static Word DayViewGetDescriptionHeight (Int apptIndex, Word width, Word maxHeight,
	WordPtr iconsWidthP, FontID * fontIdP)
{
	Word height;
	Word iconsWidth;
	Word recordNum;
	Word lineHeight;
	FontID curFont;
	VoidHand recordH;
	ApptInfoPtr	appts;
	ApptDBRecordType apptRec;
	

	// Get the record index.
	appts = MemHandleLock (ApptsH);
	recordNum = appts[apptIndex].recordNum;
	MemPtrUnlock (appts);

	iconsWidth = 0;

	// Empty time slot?
	if (recordNum == -1)
		{
		curFont = FntSetFont (apptTimeFont);
		height = FntLineHeight ();
		FntSetFont (curFont);
		*fontIdP = apptTimeFont;
		}
	else
		{	  
		// Get the appointment record.
		ApptGetRecord (ApptDB, recordNum, &apptRec, &recordH);


		// Compute the width needed to draw the note, alarm and repeat icons.
		curFont = FntSetFont (symbolFont);

		if (apptRec.note)
			iconsWidth += FntCharWidth (symbolNote);

		if (apptRec.alarm)
			{
			if (iconsWidth) iconsWidth++;
			iconsWidth += FntCharWidth (symbolAlarm);
			}

		if (apptRec.repeat)
			{
			if (iconsWidth) iconsWidth++;
			iconsWidth += FntCharWidth (symbolRepeat);
			}


		// Compute the height of the appointment description.
		FntSetFont (ApptDescFont);
		
		height = FldCalcFieldHeight (apptRec.description, width - iconsWidth);
		lineHeight = FntLineHeight ();
		height = min (height, (maxHeight / lineHeight));
		height *= lineHeight;
		
		*fontIdP = ApptDescFont;

		FntSetFont (curFont);

		MemHandleUnlock (recordH);
		}


	*iconsWidthP = iconsWidth;
	return (height);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewUpdateScrollers
 *
 * DESCRIPTION: This routine draws or erases the Day View scroll arrow
 *              buttons.
 *
 * PARAMETERS:  frm             -  pointer to the to do Day form
 *              bottomAppt      -  record index of the last visible record
 *              lastItemClipped - true if the list is partially off the 
 *                                display
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/28/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewUpdateScrollers (FormPtr frm, Word bottomAppt,
	Boolean lastItemClipped)
{
	Word upIndex;
	Word downIndex;
	Boolean scrollableUp;
	Boolean scrollableDown;
	
	// If the first appointment displayed is not the fist appointment
	// of the day, enable the up scroller.
	scrollableUp = (TopVisibleAppt > 0);

	// If the last appointment displayed is not the last appointment
	// of the day or if it partially clipped, enable the down scroller.
	scrollableDown = ( lastItemClipped || (bottomAppt+1 < NumAppts) );

	// Update the scroll button.
	upIndex = FrmGetObjectIndex (frm, DayUpButton);
	downIndex = FrmGetObjectIndex (frm, DayDownButton);
	FrmUpdateScrollers (frm, upIndex, downIndex, scrollableUp, scrollableDown);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewInitRow
 *
 * DESCRIPTION: This routine initializes a row in the Day View table.
 *
 * PARAMETERS:  table      - pointer to the table of appointments
 *              row        - row number (first row is zero)
 *              apptIndex  - index in appointment list
 *              rowHeight  - height of the row in pixels
 *              uniqueID   - unique ID of appointment record
 *              iconsWidth - spase to reserve for note, alarm and repeat
 *                           icons
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewInitRow (TablePtr table, Word row, Word apptIndex, 
	short rowHeight, ULong uniqueID, Word iconsWidth, FontID fontID)
{
	Word time;
	ApptInfoPtr	appts;	

	// Make the row usable.
	TblSetRowUsable (table, row, true);
	
	// Set the height of the row to the height of the description.
	TblSetRowHeight (table, row, rowHeight);
	
	// Store the record number as the row id.
	TblSetRowID (table, row, apptIndex);
	
	// Store the start time of the appointment in the table.
	appts = MemDeref (ApptsH);
	time = TimeToInt(appts[(Int)apptIndex].startTime);
	TblSetItemInt (table, row, timeColumn, time);
	
	// Store the unique id of the record in the row.
	TblSetRowData (table, row, uniqueID);

	// Set the table item type for the description,  it will differ depending
	// on the presents of a note.
	if (! iconsWidth)
		{
		TblSetItemStyle (table, row, descColumn, textTableItem);		
		TblSetItemInt (table, row, descColumn, 0);
		}
	else
		{
		TblSetItemStyle (table, row, descColumn, narrowTextTableItem);
		TblSetItemInt (table, row, descColumn, iconsWidth);
		}


	// Set the font used to draw the text of the row.
	TblSetItemFont (table, row, descColumn, fontID);

	// Mark the row invalid so that it will draw when we call the 
	// draw routine.
	TblMarkRowInvalid (table, row);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewLoadTable
 *
 * DESCRIPTION: This routine reloads appointment database records into
 *              the Day view.  This routine is called when:
 *              	o A new item is inserted
 *              	o An item is deleted
 *              	o The time of an items is changed
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewLoadTable (void)
{
	Int apptIndex;
	Word row;
	Word numRows;
	Word recordNum;
	Word lastAppt;
	Word iconsWidth;
	Word lineHeight;
	Word dataHeight;
	Word tableHeight;
	Word columnWidth;
	Word pos, oldPos;
	Word height, oldHeight;
	ULong	uniqueID;
	FontID fontID;
	FontID currFont;
	FormPtr frm;
	TablePtr table;
	Boolean init;
	Boolean rowUsable;
	Boolean rowsInserted = false;
	Boolean lastItemClipped;
	ApptInfoPtr	appts;
	RectangleType r;
	

	appts = MemHandleLock (ApptsH);

	frm = FrmGetActiveForm ();
	
	// Get the height of the table and the width of the description
	// column.
	table = GetObjectPtr (DayTable);
	TblGetBounds (table, &r);
	tableHeight = r.extent.y;
	columnWidth = TblGetColumnWidth (table, descColumn);


	// If we currently have a selected record, make sure that it is not
	// above the first visible record.
	if (CurrentRecord != noRecordSelected)
		{
		apptIndex = DayViewFindAppointment (CurrentRecord);
		if (apptIndex < TopVisibleAppt)
			TopVisibleAppt = apptIndex;
		}

	apptIndex = TopVisibleAppt;
	lastAppt = apptIndex;

	// Load records into the table.
	row = 0;
	dataHeight = 0;
	oldPos = pos = 0;
	apptIndex = TopVisibleAppt;

	while (apptIndex < NumAppts)
		{		
		// Compute the height of the appointment's description.
		height = DayViewGetDescriptionHeight (apptIndex, columnWidth, tableHeight, &iconsWidth, &fontID);

		// Is there enought room for at least one line of the the decription.
		currFont = FntSetFont (fontID);
		lineHeight = FntLineHeight ();
		FntSetFont (currFont);
		if (tableHeight >= dataHeight + lineHeight)
			{
			// Get the height of the current row.
			rowUsable = TblRowUsable (table, row);
			if (rowUsable)
				oldHeight = TblGetRowHeight (table, row);
			else
				oldHeight = 0;

			// Determine if the row needs to be initialized.  We will initialize 
			// the row if: the row is not usable (not displayed),  the unique
			// id of the record does not match the unique id stored in the 
			// row, or if the start time of the appointment does not match the
			// start time stored in the table.
			init = (! rowUsable);
			uniqueID = 0;
			recordNum = appts[apptIndex].recordNum;
			if (recordNum != -1)	// empty time slot?
				{
				DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL);
				init |= TblGetRowData (table, row) != uniqueID;
				}
			else if (! init)
				init |= (TblGetRowData (table, row) != 0);			

			if (! init)
				init = TimeToInt (appts[apptIndex].startTime) != 
					    TblGetItemInt (table, row, timeColumn);
					    
			if (! init)
				init = TblGetItemInt (table, row, descColumn) != iconsWidth;

			if (! init)
				init = TblGetItemFont (table, row, descColumn) != fontID;

			// If the record is not already being displayed in the current 
			// row load the record into the table.
			if (init)
				{
				DayViewInitRow (table, row, apptIndex, height, uniqueID, iconsWidth, fontID);
				}

			// If the height or the position of the item has changed draw the item.
			else 
				{
				TblSetRowID (table, row, apptIndex);
				if (height != oldHeight)
					{
					TblSetRowHeight (table, row, height);
					TblMarkRowInvalid (table, row);
					}
				else if (pos != oldPos)
					{
					TblMarkRowInvalid (table, row);
					}
				}
				
			pos += height;
			oldPos += oldHeight;

			lastAppt = apptIndex;
			apptIndex++;
			row++;
			}
		
		dataHeight += height;

		// Is the table full?
		if (dataHeight >= tableHeight)		
			{
			// If we have a currently selected record, make sure that it is
			// not below the last visible record.  If the currently selected 
			// record is the last visible record, make sure the whole description 
			// is visible.
			if (CurrentRecord == noRecordSelected) break;

			apptIndex = DayViewFindAppointment (CurrentRecord);
			if (apptIndex < lastAppt)
				 break;

			// Last visible?
			else if (apptIndex == lastAppt)
				{
				if ((apptIndex == TopVisibleAppt) || (dataHeight == tableHeight))
					break;
					
				// Remove the top item from the table and reload the table again.
				TopVisibleAppt++;
				apptIndex = TopVisibleAppt;
				}
			// Below last visible.
			else
				TopVisibleAppt = apptIndex;
				
			row = 0;
			dataHeight = 0;
			oldPos = pos = 0;
			}
		}



	// Hide the items that don't have any data.
	numRows = TblGetNumberOfRows (table);
	while (row < numRows)
		{		
		TblSetRowUsable (table, row, false);
		row++;
		}


	// If the table is not full and the first visible record is 
	// not the first record	in the database, displays enough records
	// to fill out the table.
	while (dataHeight < tableHeight)
		{
		apptIndex = TopVisibleAppt;
		if (apptIndex == 0) break;
		apptIndex--;

		height = DayViewGetDescriptionHeight (apptIndex, columnWidth, tableHeight, &iconsWidth, &fontID);
			
		// If adding the item to the table will overflow the height of
		// the table, don't add the item.
		if (dataHeight + height > tableHeight)
			break;
		
		// Insert a row before the first row.
		TblInsertRow (table, 0);

		recordNum = appts[apptIndex].recordNum;
		if (recordNum != -1)	// empty time slot?
			DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL);
		else
			uniqueID = 0;

		DayViewInitRow (table, 0, apptIndex, height, uniqueID, iconsWidth, fontID);
		
		TopVisibleAppt = apptIndex;
		
		rowsInserted = true;

		dataHeight += height;
		}
		
	// If rows were inserted to full out the page, invalidate the whole
	// table, it all needs to be redrawn.
	if (rowsInserted)
		TblMarkTableInvalid (table);

	// If the height of the data in the table is greater than the height
	// of the table, then the bottom of the last row is clip and the 
	// table is scrollable.
	lastItemClipped = (dataHeight > tableHeight);

	// Update the scroll arrows.
	DayViewUpdateScrollers (frm, lastAppt, lastItemClipped);

	MemPtrUnlock (appts);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewLayoutDay
 *
 * DESCRIPTION: This routine builds a list of: untimed appointment, 
 *              timed appointment, and empty time slots, for the 
 *              current day (the date store in the global variable Date).
 *
 * PARAMETERS:  retrieve - true if the list if appointment should be 
 *
 * RETURNED:    nothing
 *
 * NOTE:			the global variables ApptsH and NumAppts are set by
 *             this routine.
 *              
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/1/96	Initial Revision
 *
 ***********************************************************************/
static void DayViewLayoutDay (Boolean retieve)
{
	Int				i, j;
	Int				index;
	Int				numRows;
	Word				height;
	Word				lineHeight;
	Word				iconsWidth;
	Word				tableHeight;
	Word				columnWidth;
	FontID			fontID;
	FontID			currFont;
	TablePtr			table;
	TimeType			next;
	TimeType			endTime;
	Boolean			replace;
	Boolean			addEndTime;
	ApptInfoPtr		appts;
	ApptInfoPtr		apptsOnly;
	RectangleType 	r;
	

	// Get a list of: untimed appointment and timed appointment for the
	// current day.
	if (retieve)
		{
		if (ApptsOnlyH) MemHandleFree (ApptsOnlyH);
		ApptGetAppointments (ApptDB, Date, 1, &ApptsOnlyH, &NumApptsOnly);
		}


	// Free the existing list.
	if (ApptsH)
		MemHandleFree (ApptsH);

	// If there are no appointsment on the day, fill in the appointment list
	// with empty time slots.
	if (! ApptsOnlyH)
		{
		NumAppts = DayEndHour - DayStartHour + 1;
		ApptsH = MemHandleNew (NumAppts * sizeof (ApptInfoType));
		appts = MemHandleLock (ApptsH);

		for (i = 0; i < NumAppts; i++)
			{
			appts[i].startTime.hours = DayStartHour + i;				
			appts[i].startTime.minutes = 0;				
			appts[i].endTime.hours = DayStartHour + i + 1;				
			appts[i].endTime.minutes = 0;				
			appts[i].recordNum = emptySlot;	
			}
			
		DayViewCheckForConflicts ();
		MemHandleUnlock (ApptsH);	
		return;
		}
	
	// Merge empty time slots into the appointment list.
	//
	// Allocate space for the maximun number of empty time slots that
	// we may need to add. 
	ApptsH = MemHandleNew ((NumApptsOnly+(hoursPerDay*2)) * sizeof (ApptInfoType));
	appts = MemHandleLock (ApptsH);
	NumAppts = 0;
	index = 0;

	// Add the untimed events, the timed events, and a blank time slot for 
	// the end-time of each timed event.
	apptsOnly = MemHandleLock (ApptsOnlyH);
	for (i = 0; i < NumApptsOnly; i++)
		{
		// Find the correct position at which to insert the current event.
		replace = false;
		for (j = index; j < NumAppts; j++)
			{
			if (appts[j].recordNum == emptySlot)
				{
				// If an empty time slot with the same start-time already exist, then
				// replace it.
				if (TimeToInt (appts[j].startTime) == TimeToInt (apptsOnly[i].startTime))
					{
					replace = true;
					break;
					}

				// If we find an empty time slot that has an start-time before
				// the start-time of the current event and an end-time after the 
				// the start-time of the current event, adjust the end-time of the 
				// empty time such that it is equal to the start of the current event.
			 	if (TimeToInt (appts[j].startTime) < TimeToInt (apptsOnly[i].startTime) &&
			 		 TimeToInt (appts[j].endTime)   > TimeToInt (apptsOnly[i].startTime))
			 		appts[j].endTime = apptsOnly[i].startTime;
			 	}
			
			if (TimeToInt (appts[j].startTime) > TimeToInt (apptsOnly[i].startTime))
				{
				// Make room for the empty time slot we're about to add.
				MemMove (&appts[j+1], &appts[j], (NumAppts-j) * sizeof (ApptInfoType));
				break;
				}
			}

		// Add the event to the list.
		appts[j] = apptsOnly[i];
		index = j + 1;
		if (! replace)
			NumAppts++;
			

		// If the event is a timed event add an empty time slot to display the end-time.
		if (TimeToInt (apptsOnly[i].startTime) != apptNoTime)
			{
			// Find the correct position at which to insert the end-time time slot.
			addEndTime = true;
			for (j = index; j < NumAppts; j++)
				{
				// If an event already exist that has a start-time equal to the 
				// end-time of the current event then we don't need to add an 
				//  end-time time slot.
				if (TimeToInt (appts[j].startTime) == TimeToInt (apptsOnly[i].endTime))
					{
					addEndTime = false;
					break;
					}
					
				// We're found the position to insert the empty time slot when we find 
				// an appointment with a start-time greater than the end-time of the 
				// current event.
				if (TimeToInt (appts[j].startTime) > TimeToInt (apptsOnly[i].endTime))
					{
					// Make room for the empty time slot we're about to add.
					MemMove (&appts[j+1], &appts[j], (NumAppts-j) * sizeof (ApptInfoType));
					break;
					}
				}
			
			if (addEndTime)
				{
				// The end time of the empty time slot is the earlier of:
				//		o the start time plus one hour
				//		o 11:55 pm
				//		o the start time of the next event.
				if (apptsOnly[i].endTime.hours < 23)
					{
					endTime.hours = apptsOnly[i].endTime.hours + 1;
					endTime.minutes = 0;
//					endTime.minutes = apptsOnly[i].endTime.minutes;
					}
				else
					{
					endTime.hours = 23;		// max end time is 11:55 pm
					endTime.minutes = 55;
					}
	
				if (j < NumAppts && TimeToInt(endTime) > TimeToInt(appts[j+1].startTime))
					endTime = appts[j+1].startTime;
		
	
				appts[j].recordNum = emptySlot;
				appts[j].startTime = apptsOnly[i].endTime;
				appts[j].endTime = endTime;
				NumAppts++;
				}
			}
		}


	// Reserve spase for the time bars.  We will show time bars if the user
	// has requested them or if there are overlapping appointments.
	DayViewCheckForConflicts ();


	// Determine if that is space to add empty time slot, these time slot are in
	// addition to the empty time slot that represent end times of events.
	table = GetObjectPtr (DayTable);
	numRows = TblGetNumberOfRows (table);
	if (( ! CompressDayView) || (numRows > NumAppts))
		{
		TblGetBounds (table, &r);
		tableHeight = r.extent.y;
		height = 0;
		columnWidth = TblGetColumnWidth (table, descColumn);

		currFont = FntSetFont (apptEmptyDescFont);
		lineHeight = FntLineHeight ();
		FntSetFont (currFont);

		if (CompressDayView)
			{
			for (j = 0; j < NumAppts; j++)
				{
				height += DayViewGetDescriptionHeight (j, columnWidth, tableHeight, &iconsWidth, &fontID);
				if (height >= tableHeight)
					break;
				}
			}
		
		// Add empty time slots to the list of appointment until the table is full.
		next.hours = DayStartHour;
		next.minutes = 0;
		i = 0;

		while (( ! CompressDayView) || (height + lineHeight <= tableHeight))
			{
			if ((i < NumAppts) &&
				 (TimeToInt (next) >= TimeToInt (appts[i].startTime)))
				{
				if (TimeToInt (next) < TimeToInt (appts[i].endTime) &&
					(appts[i].endTime.hours >= DayStartHour))
					{
					next = appts[i].endTime;
					if (next.minutes)
						{
						next.hours++;
						next.minutes = 0;
						}
					}
				i++;
				}

			// Insert an empty time slot if we're not passed the end of the 
			// day.
			else if ((next.hours < DayEndHour) || 
						((next.hours == DayEndHour) && next.minutes == 0))
				{
				MemMove (&appts[i+1], &appts[i], (NumAppts-i) * sizeof (ApptInfoType));
				NumAppts++;
	
				appts[i].startTime = next;
				appts[i].recordNum = emptySlot;	
	
				// The end time is the beginning of the next hour or the 
				// start time of the next appointment, which ever is earliest.
				next.hours++;
				next.minutes = 0;
				if ( (i+1 < NumAppts) &&
					  (TimeToInt (next) > TimeToInt (appts[i+1].startTime)))
					next = appts[i+1].startTime;
	
				appts[i].endTime = next;
				
				height += DayViewGetDescriptionHeight (i, columnWidth, tableHeight, &iconsWidth, &fontID);
				i++;
				}

			else if (i < NumAppts)
				{
				next.hours++;
				next.minutes = 0;
				}
			
			else
				break;
			}
		}
				
	MemHandleUnlock (ApptsOnlyH);
			
	// Release any unused space in the appointment list;
	MemHandleUnlock (ApptsH);
	MemHandleResize (ApptsH, (NumAppts * sizeof (ApptInfoType)));
}


/***********************************************************************
 *
 * FUNCTION:    DayViewNewAppointment
 *
 * DESCRIPTION: This routine adds a new untimed appointment to the top of
 *              current day.
 *
 * PARAMETERS:  event - pointer to the keyDown event, or NULL
 *
 * RETURNED:    true if the key has handle by this routine
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	7/29/95		Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewNewAppointment (EventPtr event)
{
	Err error;
	Word row;
	Int apptIndex;
	Word recordNum;
	Char desc [2];
	FormPtr frm;
	TablePtr table;
	TimeType startTime;
	TimeType endTime;
	Boolean handled = false;
	ApptDBRecordType newAppt;
	ApptDateTimeType when;
	

	TimeToInt (startTime) = apptNoTime;
	TimeToInt (endTime) = apptNoTime;
	*desc = 0;

	// We'll have an event if the appointment is being created as the result
	// writting a character when no appoint is selected.
	if (event)
		{
		if (IsDigit (GetCharAttr(), event->data.keyDown.chr))
			{
			EvtAddEventToQueue (event);
			
			startTime.hours = event->data.keyDown.chr - '0';
			startTime.minutes = 0;
			endTime.hours = startTime.hours + 1;
			endTime.minutes = 0;
			if (!GetTime (&startTime, &endTime, setTimeTitleStrID))
				return (true);
			}

		// Convert lower case alpha character to upper-case.
		else
			{
			desc[0] = event->data.keyDown.chr;
			desc[1] = 0;
			if ((UChar)desc[0] >= 'a' && (UChar)desc[0] <= 'z')
				desc[0] -= ('a' - 'A');
			}
		handled = true;
		}


	// Limit the number of appointments that can be enter on a day.
	if (NumApptsOnly >= apptMaxPerDay)
		return (true);

	// Create a untimed appointment on the current day.
	MemSet (&newAppt, sizeof (newAppt), 0);
	when.startTime = startTime;
	when.endTime = endTime;
	when.date = Date;
	newAppt.when = &when;
	newAppt.description = desc;
	if (AlarmPreset.advance != apptNoAlarm)
		newAppt.alarm = &AlarmPreset;
	error = ApptNewRecord (ApptDB, &newAppt, &recordNum);
	
	// If necessary display an alert that indicates that the new record could 
	// not be created.
	if (error)
		{
		FrmAlert (DeviceFullAlert);
		return (true);
		}

	CurrentRecord = recordNum;
	ItemSelected = true;

	frm = FrmGetActiveForm ();
	table = GetObjectPtr (DayTable);
	
	// Reload and redraw the appointment table.
	DayViewLayoutDay (true);
	DayViewLoadTable ();
	TblRedrawTable (table);
	DayViewDrawTimeBars ();


	// Give the focus to the new item.
	apptIndex = DayViewFindAppointment (recordNum);
	TblFindRowID (table, apptIndex, &row);
	FrmSetFocus (frm, FrmGetObjectIndex (frm, DayTable));
	TblGrabFocus (table, row, descColumn);
	FldGrabFocus (TblGetCurrentField (table));
	
	return (handled);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDeleteAppointment
 *
 * DESCRIPTION: This routine deletes the selected appointment.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewDeleteAppointment (void)
{
	Word row;
	Word column;
	Int apptIndex;
	Word recordNum;
	TablePtr table;
	ApptInfoPtr	appts;

		
	// If appointment is selected, return.
	table = GetObjectPtr (DayTable);
	if (! TblEditing (table))
		return;

	TblGetSelection (table, &row, &column);
	TblReleaseFocus (table);


	// Get the record index.
	apptIndex = TblGetRowID (table, row);
	appts = MemHandleLock (ApptsH);
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);
	
	ErrFatalDisplayIf ((recordNum != CurrentRecord), "Wrong record");

	// Clear the edit state, this will delete the current record if is 
	// blank.
	if (! ClearEditState ())
		{
		// Delete the record,  this routine will display an appropriate 
		// dialog to confirm the action.  If the dialog is canceled 
		// don't update the display.
		if (! DeleteRecord (recordNum))
			return;
		}

	// Layout the day again, empty time slots may needed to be add to 
	// full-in the gap left by the deleted appointment.
	DayViewLayoutDay (true);

	DayViewLoadTable ();
	TblRedrawTable (table);
	DayViewDrawTimeBars ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDeleteNote
 *
 * DESCRIPTION: This routine deletes the note attached to the selected 
 *              appointment.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/1/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewDeleteNote ()
{
	Word i;
	Word row;
	Word column;
	Word height;
	Word tableHeight;
	Word iconsWidth;
	Word newHeight;
	Int apptIndex;
	Word alertButton;
	Word columnWidth;
	Word rowsInTable;
	FontID fontID;
	TablePtr table;
	Boolean empty;
	Boolean exception = false;
	VoidHand recordH;
	RectangleType r;
	ApptDBRecordType apptRec;
		
	table = GetObjectPtr (DayTable);

	// Check if we are editing an item.
	if (! TblEditing (table))
		return;

	// Check if the record has a note attached.
	ApptGetRecordFar (ApptDB, CurrentRecord, &apptRec, &recordH);
	empty = ( (! apptRec.note) || (*apptRec.note == 0));
	MemHandleUnlock (recordH);
	if (empty) return;


	// If we're changing a repeating appointmemt, check if all occurrences
	// are being changed, or if and exception is being created.
	if (apptRec.repeat)
		{
		alertButton = FrmAlert (RepeatDeleteNoteAlert);

		// If the alert was canceled don't delete the note.
		if (alertButton == RepeatDeleteNoteCancelButton)
			return;

		else if (alertButton == RepeatDeleteNoteCurrentButton)
			exception = true;
		}

	else if (FrmAlert(DeleteNoteAlert) != DeleteNoteYes)
		return;


	// Get the selected row.
	TblGetSelection (table, &row, &column);

	// Release the focus, this will unlock the current record.
	TblReleaseFocus (table);

	// Remove the note field from the database record.
	if (! DeleteNote (exception))
		return;

	// Mark the current row non-usable so the it will redraw.
	TblSetRowUsable (table, row, false);
	
	// Get the current height of the description.
	height = TblGetRowHeight (table, row);

	// Get the new height of the description, the desciption may be short
	// because we can draw in the space vacated by the note indicator.
	apptIndex = TblGetRowID (table, row);
	columnWidth = TblGetColumnWidth (table, descColumn);
	TblGetBounds (table, &r);
	tableHeight = r.extent.y;
	newHeight = DayViewGetDescriptionHeight (apptIndex, columnWidth, tableHeight, &iconsWidth, &fontID);
	
	// If the height of the description has changed, invalid all the row
	// after the current row so that they be drawn.
	if (height != newHeight)
		{
		rowsInTable = TblGetNumberOfRows (table);
		for (i = row+1; i < rowsInTable; i++)
			TblSetRowUsable (table, i, false);
		}
	
	// Creating an exception will move records around, so we need to rebuild
	// the appointment list.
	if (exception)
		DayViewLayoutDay (true);

	DayViewLoadTable ();
	TblRedrawTable (table);
	DayViewDrawTimeBars ();

	DayViewRestoreEditState ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewSelectTime
 *
 * DESCRIPTION: This routine is called when a time item in the day view
 *              table is selected.  The time picker is displayed, if 
 *              the start or end time of the appointment is changed, 
 *              the day's appointments are resorted and the appointment
 *              table is redrawn.
 *
 * PARAMETERS:  table - table of appointments
 *              row   - row selected
 *              
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewSelectTime (TablePtr table, Word row)
{
	Int apptIndex;
	Word recordNum;
	Boolean sameTime;
	Boolean moved;
	Boolean exception = false;
	TimeType startTime;
	TimeType endTime;
	ApptInfoPtr appts;

	// Get the record index, start time, and end time.
	apptIndex = TblGetRowID (table, row);
	appts = MemHandleLock (ApptsH);
	startTime = appts[apptIndex].startTime;
	endTime = appts[apptIndex].endTime;
	recordNum = appts[apptIndex].recordNum;
	MemHandleUnlock (ApptsH);
	
	// Display the time picker, exit if the time picker if not confirmed.
	sameTime = (! GetTime (&startTime, &endTime, setTimeTitleStrID));
	if (sameTime)
		{
		DayViewRestoreEditState ();
		return;
		}
		

	if (MoveEvent (&recordNum, startTime, endTime, Date, true, &moved))
		return;
	
	if (moved)
		{
		CurrentRecord = recordNum;	
		DayViewLayoutDay (true);
		DayViewLoadTable ();
		TblRedrawTable (table);
		DayViewDrawTimeBars ();
		}

	DayViewRestoreEditState ();
}

/***********************************************************************
 *
 * FUNCTION:    DayViewSelectIcons
 *
 * DESCRIPTION: This routine handles the selection of the note, alarm 
 *              and repeat icons.  If determains which icon the pen is
 *              on and tracks the pen until it is released.  If the pen 
 *              is released within the bounds of an icon we nagivate to
 *              apprpperiate form,
 *
 * PARAMETERS:  event  - pointer to a tblEnter event.
 *
 * RETURNED:    true if an icon is selected.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/16/96	Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewSelectIcons (EventPtr event)
{
	Int				apptIndex;
	Word				row;
	Word				recordNum;
	Word				iconsWidth;
	Short				x, y;
	FontID			curFont;
	VoidHand 		recordH;
	TablePtr			table;
	Boolean			penDown = true;
	Boolean			selected = true;
	Boolean			inNoteIcon = false;
	Boolean			inAlarmIcon = false;
	Boolean			inRepeatIcon = false;
	ApptInfoPtr		appts;
	RectangleType	r;
	RectangleType	itemR;
	ApptDBRecordType apptRec;
	

	if (event->data.tblEnter.column != descColumn)
		return (false);

	// Check if there are any icons.
	table = (TablePtr) event->data.tblEnter.pTable;
	row = event->data.tblEnter.row;
	iconsWidth = TblGetItemInt (table, row, descColumn);
	if (! iconsWidth)
		return (false);
	
	// Check if the pen is within the bounds of the icons.
	TblGetItemBounds (table, row, descColumn, &itemR);

	r.topLeft.x = itemR.topLeft.x + itemR.extent.x - iconsWidth;
	r.topLeft.y = itemR.topLeft.y;
	r.extent.x = iconsWidth;
	curFont = FntSetFont (ApptDescFont);
	r.extent.y = FntLineHeight ();
	FntSetFont (curFont);
	
	x = event->screenX;
	y = event->screenY;
	
	if (RctPtInRectangle (x, y, &r))
		{
		// Get the record index of the selected appointment.
		apptIndex = TblGetRowID (table, row);
		appts = MemHandleLock (ApptsH);
		recordNum = appts[apptIndex].recordNum;
		MemPtrUnlock (appts);

		// Get the appointment record.
		ApptGetRecordFar (ApptDB, recordNum, &apptRec, &recordH);

		curFont = FntSetFont (symbolFont);
		
		// Check if the pen is on the note icon.
		if (apptRec.note)
			{
			r.extent.x = FntCharWidth (symbolNote);
			inNoteIcon = RctPtInRectangle (x, y, &r);
			if (! inNoteIcon)
				r.topLeft.x += r.extent.x + 1;
			}

		// Check if the pen is on the alarm icon.
		if (apptRec.alarm && (! inNoteIcon))
			{
			r.extent.x = FntCharWidth (symbolAlarm);
			inAlarmIcon = RctPtInRectangle (x, y, &r);
			if (! inAlarmIcon)
				r.topLeft.x += r.extent.x + 1;
			}

		// Check if the pen is on the repeat icon.
		if (apptRec.repeat && (! inNoteIcon) && (! inAlarmIcon) )
			{
			r.extent.x = FntCharWidth (symbolRepeat);
			inRepeatIcon = RctPtInRectangle (x, y, &r);
			if (! inRepeatIcon)
				r.topLeft.x += r.extent.x  + 1;
			}
			
		FntSetFont (curFont);
		MemHandleUnlock (recordH);

		TblReleaseFocus (table);

		// Highlight the icon
		WinInvertRectangle (&r, 0);

		// Track the pen until its released.
		do 
			{
			PenGetPoint (&x, &y, &penDown);
	
			if (RctPtInRectangle (x, y, &r))
				{
				if (! selected)
					{
					WinInvertRectangle (&r, 0);
					selected = true;
					}
				}
	
			else if (selected)
				{
				WinInvertRectangle (&r, 0);
				selected = false;
				}
	
			} while (penDown);

		if (selected)
			{
			WinInvertRectangle (&r, 0);

			CurrentRecord = recordNum;

			if (inNoteIcon)
				FrmGotoForm (NoteView);
			else
				FrmPopupForm (DetailsDialog);
			return (true);
			}
		}

	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewItemSelected
 *
 * DESCRIPTION: This routine is called when an item in Day View table
 *              is selected.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/9/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewItemSelected (EventPtr event)
{
	Err error;
	Int apptIndex;
	Word row;
	Word column;
	Word recordNum;
	ULong uniqueID;
	TablePtr table;
	ApptInfoPtr appts;
	ApptDBRecordType newAppt;
	ApptDateTimeType when;
	
	table = event->data.tblSelect.pTable;
	row = event->data.tblSelect.row;
	column = event->data.tblSelect.column;

	// Was a time item selected?
	if (column == timeColumn)
		{
		// Unhighlight the time.
		TblUnhighlightSelection (table);
		
		// If an empty time slot has been selected then create a 
		// new appointment.
		uniqueID = TblGetRowData (table, event->data.tblEnter.row);
		if (uniqueID == 0)
			{
			// If we have reached the maximum number of displayable event, then
			// exit.
			if (NumApptsOnly >= apptMaxPerDay)
				return;

			// Get the start time, and end time of the row selected.
			apptIndex = TblGetRowID (table, row);
			appts = MemHandleLock (ApptsH);
		
			// Create a untimed appointment on the current day.
			MemSet (&newAppt, sizeof (newAppt), 0);
			when.startTime = appts[apptIndex].startTime;
			when.endTime = appts[apptIndex].endTime;
			when.date = Date;
			newAppt.when = &when;
			newAppt.description = "";

			if (AlarmPreset.advance != apptNoAlarm)
				newAppt.alarm = &AlarmPreset;		

			error = ApptNewRecord (ApptDB, &newAppt, &recordNum);
			
			if (! error)
				{
				appts[apptIndex].recordNum =  recordNum;
		
				// Store the unique id of the record in the row.
				DmRecordInfo (ApptDB, recordNum, NULL, &uniqueID, NULL);
				TblSetRowData (table, row, uniqueID);

				CurrentRecord = recordNum;
				ItemSelected = true;
				}

			MemHandleUnlock (ApptsH);

			// Display an alert that indicates that the new record could 
			// not be created.
			if (error)
				{
				FrmAlert (DeviceFullAlert);
				return;
				}
			}

		DayViewSelectTime (table, row);
		}


	// Was a description selected?
	else if (column == descColumn)
		{
		// Get the record index of the selected appointment.
		apptIndex = TblGetRowID (table, row);
		appts = MemHandleLock (ApptsH);
		CurrentRecord = appts[apptIndex].recordNum;
		MemPtrUnlock (appts);
		
		// If the table is in edit mode then the description field
		// was selected, otherwise the note indictor must have
		// been selected.
		if (TblEditing (table))
			{
			ItemSelected = true;

			// If the row will have been visually invalidate if: an empty slot
			// was selected and the alarm preset preference is on, or
			// the end time of the event is not displayed, or the font for 
			// drawing descriptions are a different height than the font for 
			// drawing empty time slots.

			// If the alarm preset preference is on then selecting an empty
			// appointment will visually invalidate that row.  We need to
			// redraw the table so the the alarm icon can be drawn.
			if (TblRowInvalid (table, row))
				{
				TblReleaseFocus (table);
				DayViewLayoutDay (true);
				DayViewLoadTable ();
				TblRedrawTable (table);
				DayViewDrawTimeBars ();
				DayViewRestoreEditState ();
				}
			}
		else
			FrmGotoForm (NoteView);
		}
}


/***********************************************************************
 *
 * FUNCTION:    DayViewResizeDescription
 *
 * DESCRIPTION: This routine is called when the height of appointment's
 *              description is changed as a result of user input.
 *              If the new hieght of the field is shorter,  more items
 *              may need to be added to the bottom of the Day.
 *              
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/18/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewResizeDescription (EventPtr event)
{
	Int apptIndex;
	Word row;
	Word currentRow;
	Word currentColumn;
	FieldPtr fld;
	TablePtr table;
	RectangleType fieldR;
	
	// Get the current height of the field;
	fld = event->data.fldHeightChanged.pField;
	FldGetBounds (fld, &fieldR);

	// Have the table object resize the field and move the items below
	// the field up or down.
	table = GetObjectPtr (DayTable);
	TblHandleEvent (table, event);
	

	// If the field's height has been expanded , and we don't have items scrolled 
	// off the top of the table, just update the scrollers.

	if (event->data.fldHeightChanged.newHeight >= fieldR.extent.y)
		{
		TopVisibleAppt = TblGetRowID (table, 0);
		}
		

	// Relayout the day to add or remove empty time slots.  We don't need 
	// to rebuild the list of records.
	DayViewLayoutDay (true);
	DayViewLoadTable ();


	// Relaying-out the day migth move the row that has the focus, if so 
	// we need to correct the table's current row.
	apptIndex = DayViewFindAppointment (CurrentRecord);
	TblFindRowID (table, apptIndex, &row);
	TblGetSelection (table, &currentRow, &currentColumn);
	if (row != currentRow)
		// zzz write API routine to do this.
		table->currentRow = row;


	TblRedrawTable (table);		
	DayViewDrawTimeBars ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDrawTitle
 *
 * DESCRIPTION: This routine draws the day view title and highlights
 *              the current day's the day-of-week push button. 
 *
 * PARAMETERS:  void
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/1/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewDrawTitle (void)
{
	UInt		dayOfWeek;
	Char		title[longDateStrLength];
	FormPtr	frm;

	// Set the title of the day view.
	DateToAscii (Date.month, Date.day, (Date.year+firstYear) % 100, 
		LongDateFormat, title);

	frm = FrmGetActiveForm ();
	FrmCopyTitle (frm, title);
	
	// Update the day-of-week push button to highlight the correct day of
	// the week.
	dayOfWeek = DatebookDayOfWeek (Date.month, Date.day, Date.year+firstYear);
	FrmSetControlGroupSelection (frm, DayOfWeekGroup, DayDOW1Button + dayOfWeek);

	TimeDisplayed = false;
}


/***********************************************************************
 *
 * FUNCTION:    DayViewShowTime
 *
 * DESCRIPTION: This routine display the current time in the title of the
 *              day 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	5/14/96	Initial Revision
 *
 ***********************************************************************/
static void DayViewShowTime (void)
{
	Char				title[timeStringLength];
	DateTimeType 	dateTime;

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


/***********************************************************************
 *
 * FUNCTION:    DayViewHideTime
 *
 * DESCRIPTION: If the title of the Day View is displaying the current 
 *              time, this routine will change the title to the standard
 *					 title (the current date).
 *
 * PARAMETERS:  nothing
 *
 * PARAMETERS:  hide - true to always hide, false hide only if
 *                     to time has been display for the require
 *                      length of time.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	5/14/96	Initial Revision
 *
 ***********************************************************************/
static void DayViewHideTime (Boolean hide)
{
	if (TimeDisplayed)
		{
		if (hide || (TimGetTicks () >= TimeDisplayTick))
			{
			// If the Day View is the draw window then redraw the title.
			if (WinGetDrawWindow () == FrmGetWindowHandle (FrmGetFormPtr (DayView)))
				DayViewDrawTitle ();
				
			// Else, cause a null event to be sent in a few seconds so that we can
			// try to redraw the title later.
			else
				{
				TimeDisplayTick = TimGetTicks () + timeDisplayTicks;
				EvtSetNullEventTick (TimeDisplayTick);
				}
			}
		else
			{
			EvtSetNullEventTick (TimeDisplayTick);
			}
		}
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDrawDate
 *
 * DESCRIPTION: This routine display the date passed.
 *
 * PARAMETERS:  date - date to display
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewDrawDate (DateType date)
{
	TablePtr table;

	// Adjust the current date.
	Date = date;

	DayViewDrawTitle ();
		
	// Get all the appointments and empty time slots on the new day.
	DayViewLayoutDay (true);

	// Determine the first appointment to display.
	DayViewSetTopAppointment ();

 	// Load the appointments and empty time slots into the table object 
	// that will display them.
	DayViewLoadTable ();
	
	// Draw the new day's events.
	table = GetObjectPtr (DayTable);
	TblRedrawTable (table);
	DayViewDrawTimeBars ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDayOfWeekSelected
 *
 * DESCRIPTION: This routine is called when of the day-of-week push buttons
 *              is pressed.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/27/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewDayOfWeekSelected (EventPtr event)
{
	Int		adjust;
	UInt		dayOfWeek;
	UInt		newDayOfWeek;

	// Adjust the current date.
	dayOfWeek = DatebookDayOfWeek (Date.month, Date.day, Date.year+firstYear);
	newDayOfWeek = event->data.ctlSelect.controlID - DayDOW1Button;
	if (dayOfWeek == newDayOfWeek) return;
	
	adjust = newDayOfWeek - dayOfWeek;
	DateAdjust (&Date, adjust);

	DayViewDrawDate (Date);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewGoToDate
 *
 * DESCRIPTION: This routine displays the date picker so that the 
 *              user can select a date to navigate to.  If the date
 *              picker is confirmed, the date selected is displayed.
 *
 *              This routine is called when a "go to" button is pressed.
 *              
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/29/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewGoToDate (void)
{
	CharPtr title;
	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.
	if (SelectDay (selectDayByDay, &month, &day, &year, title))
		{
		Date.day = day;
		Date.month = month;
		Date.year = year - firstYear;

		DayViewDrawDate (Date);
		}
		
	MemHandleUnlock (titleH);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewGotoAppointment
 *
 * DESCRIPTION: This routine sets gloabal variables such the Day View
 *              will display the text found by the text search
 *              command.
 *
 * PARAMETERS:  event - frmGotoEvent 
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/24/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewGotoAppointment (EventPtr event)
{
	TopVisibleAppt = 0;
	ItemSelected = true;
	CurrentRecord = event->data.frmGoto.recordNum;
	DayEditPosition = event->data.frmGoto.matchPos;
	DayEditSelectionLength = event->data.frmGoto.matchLen;
	
	SetDateToNextOccurrence (CurrentRecord);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewScroll
 *
 * DESCRIPTION: This routine scrolls the day of of appointments
 *              in the direction specified.
 *
 * PARAMETERS:  direction - up or dowm
 *              wrap      - if true the day is wrap to the first appointment
 *                          if we're at the end of the day.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	2/21/95	Initial Revision
 *
 ***********************************************************************/
static void DayViewScroll (DirectionType direction, Boolean wrap)
{
	Word				row;
	Word				height;
	Word				apptIndex;
	Word				iconsWidth;
	Word 				columnWidth;
	Word 				tableHeight;
	FontID			fontID;
	TablePtr			table;
	RectangleType	r;

	table = GetObjectPtr (DayTable);
	TblReleaseFocus (table);

	// Get the height of the table and the width of the description
	// column.
	TblGetBounds (table, &r);
	tableHeight = r.extent.y;
	height = 0;
	columnWidth = TblGetColumnWidth (table, descColumn);


	// Scroll the table down.
	if (direction == down)
		{
		// If we're at the bottom of the day, and page wrapping is allowed,
		// go to the top of the page.
		if (wrap && ( ! CtlEnabled (GetObjectPtr (DayDownButton))))
			TopVisibleAppt = 0;
		
		else if (TopVisibleAppt+1 >= NumAppts) 
			return;

		else
			{
			row = TblGetLastUsableRow (table);
			apptIndex = TblGetRowID (table, row);				
	
			// If there is only one appointment visible, this is the case 
			// when a appointment occupies the whole screeen, and its not
			// the last appointment, move to the next appointment.
			if (row == 0)
				apptIndex++;
			}
		}


	// Scroll the table up.
	else
		{
		if (TopVisibleAppt == 0) return;
		
		// Scan the records starting with the first visible record to 
		// determine how many record we need to scroll.  Since the 
		// heights of the records vary,  we sum the heights of the 
		// records until we get a screen full.
		apptIndex = TopVisibleAppt;
		height = TblGetRowHeight (table, 0);
		if (height >= tableHeight)
			height = 0;							

		while ( (height < tableHeight) && (apptIndex > 0) )
			{
			height += DayViewGetDescriptionHeight (apptIndex-1, columnWidth, tableHeight, &iconsWidth, &fontID);
			if ((height <= tableHeight) || (apptIndex == TopVisibleAppt))
				apptIndex--;
			}
		}

	TblMarkTableInvalid (table);
				
	TopVisibleAppt = apptIndex;
	DayViewLoadTable ();	

	TblUnhighlightSelection (table);
	TblRedrawTable (table);
	DayViewDrawTimeBars ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewPurge
 *
 * DESCRIPTION: This routine deletes appointment that are before the 
 *              user specified date.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/1/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewPurge (void)
{
	TablePtr table;
	Boolean redraw;

	redraw = PurgeRecords ();

	// If the current date is before the purge date redraw the day, we may
	// have deleted some of the appointments being displayed.
	if (redraw)
		{
		DayViewLayoutDay (true);		
		DayViewLoadTable ();	
	
		table = GetObjectPtr (DayTable);
		TblRedrawTable (table);
		DayViewDrawTimeBars ();
		}
}


/***********************************************************************
 *
 * FUNCTION:    DayViewDoCommand
 *
 * DESCRIPTION: This routine preforms the menu command specified.
 *
 * PARAMETERS:  command  - menu item id
 *
 * RETURNED:    true if 
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	3/29/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewDoCommand (Word command)
{
	Word			row;
	Word			column;
	Word 			pasteLen;
	VoidHand 	pasteCharsH;
	FontID		fontID;
	FieldPtr 	fld;
	TablePtr 	table;
	Boolean 		handled = true;
	
	// New
	if (command == NewItemCmd)
		{
		DayViewClearEditState ();
		DayViewNewAppointment (NULL);
		if (ItemSelected)
			{
			table = GetObjectPtr (DayTable);
			TblGetSelection (table, &row, &column);
			TblReleaseFocus (table);
			DayViewSelectTime (table, row);
			}
		}


	// Delete
	else if (command == DeleteCmd)
		{
		if (ItemSelected)
			DayViewDeleteAppointment ();
		else
			FrmAlert (SelectItemAlert);
		}


	// Create note
	else if (command == CreateNoteCmd)
		{
		if (ItemSelected)
			{
			TblReleaseFocus (GetObjectPtr (DayTable));
			if (CreateNote (true))
				{
				MenuEraseStatus (NULL);
				FrmGotoForm (NoteView);
				}
			else
				DayViewRestoreEditState ();
			}
		else
			FrmAlert (SelectItemAlert);
		}


	// Delete nore
	else if (command == DeleteNoteCmd)
		{
		if (ItemSelected)
			DayViewDeleteNote ();
		else
			FrmAlert (SelectItemAlert);
		}
		

	// Purge
	else if (command == PurgeCmd)
		{
		DayViewClearEditState ();
		DayViewPurge ();
		}
					

	// Send Record
	else if (command == SendRecordCmd)
		{
		if (ItemSelected)
			{
			TblReleaseFocus (GetObjectPtr (DayTable));		// Save the Data
			DateSendRecord(ApptDB, CurrentRecord);
			}
		else
			FrmAlert (SelectItemAlert);
		}
					

	// Font Selector
	else if (command == DayFontsCmd)
		{
		TblReleaseFocus (GetObjectPtr (DayTable));
		fontID = SelectFont (ApptDescFont);
		if (fontID != ApptDescFont)
			ApptDescFont = fontID;
		else
			DayViewRestoreEditState ();
		}

	// Preferences
	else if (command == DayPreferencesCmd)
		{
		DayViewClearEditState ();
		FrmPopupForm (PreferencesDialog);
		}

	// Display Options
	else if (command == DayDisplayOptionsCmd)
		{
		DayViewClearEditState ();
		FrmPopupForm (DisplayDialog);
		}

	// Phone Lookup
	else if (command == DayPhoneLookup)
		{
		fld = GetFocusObjectPtr ();
		if (fld)
			PhoneNumberLookup (fld);
		else
			FrmAlert (SelectItemAlert);
		}

	// About
	else if (command == DayGetInfoCmd)
		{
		DayViewClearEditState ();
		AbtShowAbout (sysFileCDatebook);
		}


	// Paste
	else if (command == sysEditMenuPasteCmd)
		{
		fld = GetFocusObjectPtr ();
		if (! fld)
			{
			pasteCharsH = ClipboardGetItem (clipboardText, &pasteLen);
			if (pasteCharsH && pasteLen)
				{
				DayViewNewAppointment (NULL);
				GrfSetState (false, false, false);
				fld = GetFocusObjectPtr ();
				}
			}
		handled = false;
		}

	// Some the the edit menu commands are handled by FrmHandleEvent.
	else
		{
		handled = false;
		}
	
	return (handled);
}


/***********************************************************************
 *
 * FUNCTION:    DayViewUpdateDisplay
 *
 * DESCRIPTION: This routine updates the display of the day View.
 *
 * PARAMETERS:  updateCode - a code that indicated what changes have been
 *                           made to the Day View.
 *                		
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewUpdateDisplay (Word updateCode)
{
	Int apptIndex;
	Word row, column;
	DateType next;
	TablePtr table;
	Boolean repeatsAgain;
	VoidHand recordH;
	ApptDBRecordType apptRec;
	
	table = GetObjectPtr (DayTable);

	// Was the UI unable to save an image of the day view when is 
	// obscured part of the day view with another dialog?
	if (updateCode & frmRedrawUpdateCode)
		{
		FrmDrawForm (FrmGetActiveForm ());
		DayViewDrawTimeBars ();
		return;
		}
		
	// Was the display options modified (Preferences dialog) or was the 
	// font changed.
	else if (updateCode & updateDisplayOptsChanged)
		{
		DayViewLayoutDay (true);
		DayViewSetTopAppointment ();
		}

	// Was an item deleted or marked sercet.
	else if ( (updateCode & updateItemDelete) ||
				 (updateCode & updateItemHide))
		{
		ClearEditState ();
		DayViewLayoutDay (true);
		}


	// Was the repeat infomation changed?
	else if (updateCode & updateRepeatChanged)
		{
		ApptGetRecordFar (ApptDB, CurrentRecord, &apptRec, &recordH);
		if (apptRec.repeat)
			{
			next = Date;
			repeatsAgain = ApptNextRepeatFar (&apptRec, &next);
			if (! repeatsAgain)
				{
				next = apptRec.when->date;
				repeatsAgain = ApptNextRepeatFar (&apptRec, &next);
				}
			MemHandleUnlock (recordH);

			if (repeatsAgain && (DateToInt (next) != DateToInt (Date)))
				{
				Date = next;
				DayViewDrawDate (Date);
				return;
				}
			else if (! repeatsAgain)
				ClearEditState ();
			}
		else
			{
			next = apptRec.when->date;
			MemHandleUnlock (recordH);
			// If a repeating event was changed to a non-repeating event
			// and the start date was also change then go to the new 
			// start date.
			if (DateToInt (next) != DateToInt (Date))
				{
				Date = next;
				DayViewDrawDate (Date);
				return;
				}
			}
			
		// Redraw the current record if it's still visible so the
		// the repeat indictor is draw or erased
		TblGetSelection (table, &row, &column);
		TblSetRowUsable (table, row, false);

		DayViewLayoutDay (true);
		}


	// Was the date of an appointment changed?
	else if (updateCode & updateDateChanged)
		{
		ApptGetRecordFar (ApptDB, CurrentRecord, &apptRec, &recordH);
		Date = apptRec.when->date;
		MemHandleUnlock (recordH);
			
		DayViewDrawDate (Date);
		return;
		}


	// Was the time of an appointment or the font changed?
	else if (updateCode & (updateTimeChanged | updateException | updateFontChanged))
		{
		DayViewLayoutDay (true);
		}

	// Was an alarm set or cleard?
	else if (updateCode & updateAlarmChanged)
		{
		DayViewLayoutDay (true);

		// Redraw the current record if it's still visible so the
		// the alarm indictor will be drawn or erased.
		apptIndex = DayViewFindAppointment (CurrentRecord);
		if (TblFindRowID (table, apptIndex, &row))
			TblSetRowUsable (table, row, false);
		}

	DayViewLoadTable ();
	TblRedrawTable (table);
	DayViewDrawTimeBars ();
}


/***********************************************************************
 *
 * FUNCTION:    DayViewInit
 *
 * DESCRIPTION: This routine initializes the "Day View" of the 
 *              Datebook application.
 *
 * PARAMETERS:  frm - pointer to the day view form.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95		Initial Revision
 *
 ***********************************************************************/
static void DayViewInit (FormPtr frm)
{
	Char chr;
	UInt month;
	UInt day;
	UInt year;
	UInt dayOfWeek;
	Word id;
	Word row;
	Word rowsInTable;
	TablePtr table;
	CharPtr title;
	CharPtr str1, str2;

	// Get the day we're displaying.
	day = Date.day;
	month = Date.month;
	year = Date.year+firstYear;


	// Set the title of the day view.
	title = FrmGetTitle (frm);
	DateToAscii (month, day, year % 100, LongDateFormat,  title);
	FrmSetTitle (frm, title);
	

	// If the start-day-of-week is monday rearrange the labels on the 
	// days-of-week push buttons.
	if (StartDayOfWeek == monday)
		{
		str1 = CtlGetLabel (GetObjectPtr(DayDOW1Button));
		chr = *str1;
		for (id = DayDOW2Button; id <= DayDOW7Button; id++)
			{
			str2 = CtlGetLabel (GetObjectPtr(id));
			*str1 = *str2;
			str1 = str2;
			}
		*str1 = chr;
		}

	// Highlight the correct day-of-week push button.
	dayOfWeek = DatebookDayOfWeek (month, day, year);
	FrmSetControlGroupSelection (frm, DayOfWeekGroup, DayDOW1Button + dayOfWeek);

	// Highlight the Day View push button.
	FrmSetControlGroupSelection (frm, DayViewGroup, DayDayViewButton);

	// Initialize the table used to display the day's appointments.
	table = FrmGetObjectPtr (frm, FrmGetObjectIndex (frm, DayTable));

	rowsInTable = TblGetNumberOfRows (table);
	for (row = 0; row < rowsInTable; row++)
		{		
		TblSetItemStyle (table, row, timeBarColumn, customTableItem);
		TblSetItemStyle (table, row, timeColumn, customTableItem);
		TblSetItemStyle (table, row, descColumn, textTableItem);
		TblSetRowUsable (table, row, false);
		}

	TblSetColumnUsable (table, timeBarColumn, true);
	TblSetColumnUsable (table, timeColumn, true);
	TblSetColumnUsable (table, descColumn, true);

	TblSetColumnSpacing (table, timeBarColumn, spaceAfterTimeBarColumn);
	TblSetColumnSpacing (table, timeColumn, spaceAfterTimeColumn);
	
	TblSetColumnEditIndicator (table, timeBarColumn, false);

	// Set the callback routines that will load and save the 
	// description field.
	TblSetLoadDataProcedure (table, descColumn, DayViewGetDescription);
	TblSetSaveDataProcedure (table, descColumn, DayViewSaveDescription);
	
	// Set the callback routine that draws the time field.
	TblSetCustomDrawProcedure (table, timeColumn, DayViewDrawTime);

	// Set the callback routine that draws the note, alarm, and repeat icons.
	TblSetCustomDrawProcedure (table, descColumn, DayViewDrawIcons);

	// By default the list view assume no time bar are displayed.
	TimeBarColumns = 0;

	// Get all the appointments and empty time slots on the current day.
	DayViewLayoutDay (true);


	// If we do not have an appointment selected, then position the table
	// so the the first appointment of the day is visible, unless we're on
	// today, then make sure the next appointment is visible.
	if (! ItemSelected)
		DayViewSetTopAppointment ();

	// Load the appointments and empty time slots into the table object 
	// that will display them.
	if (PendingUpdate && ItemSelected)
		DayViewUpdateDisplay (PendingUpdate);
	else
		DayViewLoadTable ();


	// Initial miscellaneous global variables.
	TimeDisplayed = false;
	PendingUpdate = 0;
}


/***********************************************************************
 *
 * FUNCTION:    DayViewHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the Day View
 *              of the Datebook application.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event was handled and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95	Initial Revision
 *
 ***********************************************************************/
static Boolean DayViewHandleEvent (EventPtr event)
{
	Word row, column;
	ULong uniqueID;
	DateType date;
	FormPtr frm;
	TablePtr table;
	Boolean handled = false;


	if (event->eType == keyDownEvent)
		{
		// Datebook key pressed?
		if (ChrIsHardKey(event->data.keyDown.chr))
			{
			DayViewClearEditState ();
			DateSecondsToDate (TimGetSeconds (), &date);
			if (DateToInt (date) != DateToInt (Date) ||
				 ((event->data.keyDown.modifiers & poweredOnKeyMask)))
				DayViewDrawDate (date);
			else
				FrmGotoForm (WeekView);
			handled = true;
			}

		// Scroll up key presed?
		else if (event->data.keyDown.chr == pageUpChr)
			{
			DayViewClearEditState ();
			DateAdjust (&Date, -1);
			DayViewDrawDate (Date);
			handled = true;
			}

		// Scroll down key presed?
		else if (event->data.keyDown.chr == pageDownChr)
			{
			DayViewClearEditState ();
			DateAdjust (&Date, 1);
			DayViewDrawDate (Date);
			handled = true;
			}

		// Send data key presed?
		else if (event->data.keyDown.chr == sendDataChr)
			{
			if (ItemSelected)
				{
				TblReleaseFocus (GetObjectPtr (DayTable));		// Save the Data
				DateSendRecord(ApptDB, CurrentRecord);
				}
			else
				FrmAlert (SelectItemAlert);
			handled = true;
			}

		// command key?
		else if (event->data.keyDown.modifiers & commandKeyMask)
			{
			handled = false;
			}


		// If no item is selected and the character is displayable, 
		// create a new appointment.
		else if ((! ItemSelected) && 
			     (IsPrint (GetCharAttr(), event->data.keyDown.chr)))
			{
			handled = DayViewNewAppointment (event);
			}
		}


	// If the pen is not in any of the object of the view, take the 
	// view out of edit mode.
	else if (event->eType == penDownEvent)
		{
		frm = FrmGetActiveForm ();
		handled = FrmHandleEvent (frm, event);
		if (! handled)
			{
			DayViewClearEditState ();
			}
		}

	// Check for buttons that take us out of edit mode.
	else if (event->eType == ctlEnterEvent)
		{
		switch (event->data.ctlEnter.controlID)
			{
			case DayNextWeekButton:
			case DayDOW1Button:
			case DayDOW2Button:
			case DayDOW3Button:
			case DayDOW4Button:
			case DayDOW5Button:
			case DayDOW6Button:
			case DayDOW7Button:
			case DayPrevWeekButton:
			case DayWeekViewButton:
			case DayMonthViewButton:
			case DayNewButton:
			case DayGoToButton:
			case DayUpButton:
			case DayDownButton:
				DayViewClearEditState ();
				break;
			}
		}


	// Handle the button that was selected.
	else if (event->eType == ctlSelectEvent)
		{
		switch (event->data.ctlSelect.controlID)
			{
			case DayWeekViewButton:
				FrmGotoForm (WeekView);
				handled = true;
				break;

			case DayMonthViewButton:
				FrmGotoForm (MonthView);
				handled = true;
				break;

			case DayDetailsButton:
				if (ItemSelected)
					FrmPopupForm (DetailsDialog);
				else
					FrmAlert (SelectItemAlert);
				handled = true;
				break;

			case DayNewButton:
				DayViewNewAppointment (NULL);
				if (ItemSelected)
					{
					table = GetObjectPtr (DayTable);
					TblGetSelection (table, &row, &column);
					TblReleaseFocus (table);
					DayViewSelectTime (table, row);
					}
				break;

			case DayGoToButton:
				DayViewGoToDate ();
				handled = true;
				break;

			case DayDOW1Button:
			case DayDOW2Button:
			case DayDOW3Button:
			case DayDOW4Button:
			case DayDOW5Button:
			case DayDOW6Button:
			case DayDOW7Button:
				DayViewDayOfWeekSelected (event);
				handled = true;
				break;
			}
		}


	// If the pen when down in the details button but did not go up in it,
	// restore the edit state.
	else if (event->eType == ctlExitEvent)
		{
		if (event->data.ctlEnter.controlID == DayDetailsButton)
			DayViewRestoreEditState ();
		}


	// Handle the scrooling controls.
	else if (event->eType == ctlRepeatEvent)
		{
		switch (event->data.ctlRepeat.controlID)
			{
			case DayPrevWeekButton:
				DateAdjust (&Date, -daysInWeek);
				DayViewDrawDate (Date);
				break;

			case DayNextWeekButton:
				DateAdjust (&Date, daysInWeek);
				DayViewDrawDate (Date);
				break;

			case DayUpButton:
				DayViewScroll (up, false);
				break;
				
			case DayDownButton:
				DayViewScroll (down, false);
				break;
			}
		}


	// Check if we've changed row in the day view table, if so 
	// clear the edit state.
	else if (event->eType == tblEnterEvent)
		{
		table = (TablePtr) event->data.tblEnter.pTable;
		if (ItemSelected)
			{
			DmRecordInfo (ApptDB, CurrentRecord, NULL, &uniqueID, NULL);
			if (TblFindRowData (table, uniqueID, &row))
				{
				if (event->data.tblEnter.row != row)
					handled = DayViewClearEditState ();
				}
			}
		if (event->data.tblEnter.column == timeBarColumn)
			handled = true;
		else if (! handled)
			handled = DayViewSelectIcons (event);;
		}
		

	// An item in the table has been selected.
	else if (event->eType == tblSelectEvent)
		{
		DayViewItemSelected (event);
		handled = true;
		}
		

	// Expand or compress the height of the appointments description.
	else if (event->eType == fldHeightChangedEvent)
		{
		DayViewResizeDescription (event);
		handled = true;
		}


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

	else if (event->eType == frmOpenEvent)
		{
		frm = FrmGetActiveForm ();
		DayViewInit (frm);
		FrmDrawForm (frm);
		DayViewDrawTimeBars ();
		DayViewRestoreEditState ();
		handled = true;
		}


	else if (event->eType == frmGotoEvent)
		{
		frm = FrmGetActiveForm ();
		DayViewGotoAppointment (event);
		DayViewInit (frm);
		FrmDrawForm (frm);
		DayViewDrawTimeBars ();
		DayViewRestoreEditState ();
		handled = true;
		}


	else if (event->eType == frmUpdateEvent)
		{
		DayViewUpdateDisplay (event->data.frmUpdate.updateCode);
		if (event->data.frmUpdate.updateCode != frmRedrawUpdateCode)
			DayViewRestoreEditState ();
		handled = true;
		}


	else if (event->eType == frmSaveEvent)
		{
		DayViewClearEditState ();
		}


	else if (event->eType == frmTitleSelectEvent)
		{
		// If the pen is in the title toggle between the current date
		// and the current time.
		if (TimeDisplayed)
			DayViewHideTime (true);
		else
			{
			DayViewShowTime ();

			// Cause a null event to be sent in a few seconds so that we can
			// toggle back to displaying the date.
			TimeDisplayTick = TimGetTicks () + timeDisplayTicks;
			EvtSetNullEventTick (TimeDisplayTick);
			}
		}


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


	return (handled);
}



#pragma mark ----------------
/***********************************************************************
 *
 * FUNCTION:    ApplicationHandleEvent
 *
 * DESCRIPTION: This routine loads form resources and set the event
 *              handler for the form loaded.
 *
 * 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	9/11/95	Initial Revision
 *
 ***********************************************************************/
static Boolean ApplicationHandleEvent (EventPtr event)
{
	Word formId;
	FormPtr frm;

	if (event->eType == frmLoadEvent)
		{
		// Load the form resource.
		formId = event->data.frmLoad.formID;
		frm = FrmInitForm (formId);
		FrmSetActiveForm (frm);		
		
		// Set the event handler for the form.  The handler of the currently
		// active form is called by FrmDispatchEvent each time is receives an
		// event.
		if (formId == DayView)
			FrmSetEventHandler (frm, DayViewHandleEvent);
			
		else if (formId == WeekView)
			FrmSetEventHandler (frm, WeekViewHandleEvent);
	
		else if (formId == MonthView)
			FrmSetEventHandler (frm, MonthViewHandleEvent);
	
		else if (formId == NoteView)
			FrmSetEventHandler (frm, NoteViewHandleEvent);
	
		else if (formId == DetailsDialog)
			FrmSetEventHandler (frm, DetailsHandleEvent);
	

		else if (formId == RepeatDialog)
			FrmSetEventHandler (frm, RepeatHandleEvent);
	
		else if (formId == PreferencesDialog)
			FrmSetEventHandler (frm, PreferencesHandleEventFar);

		else if (formId == DisplayDialog)
			FrmSetEventHandler (frm, DisplayOptionsHandleEvent);

		return (true);
		}

	return (false);
}


/***********************************************************************
 *
 * FUNCTION:    PreprocessEvent
 *
 * DESCRIPTION: This routine handles special event processing that
 *              needs to occur before the System Event Handler get 
 *              and event.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	1/10/97	Initial Revision
 *
 ***********************************************************************/
static void PreprocessEvent (EventPtr event)
{

	// We want to allow the datebook event handled see the command keys
	// before the any other event handler get them.  Some of the databook
	// views display UI that dispappears automaticial (the time in the 
	// title, or an event's descripition in the week view).  This UI
	// needs to be dismissed before the System Event Handle or the 
	// Menu Event Handler displays any UI objects.  
	if (event->eType == keyDownEvent) 
		{
		if (event->data.keyDown.modifiers & commandKeyMask)
			if (! (ChrIsHardKey (event->data.keyDown.chr) ||
				    event->data.keyDown.chr == pageUpChr ||
				    event->data.keyDown.chr == sendDataChr ||
				    event->data.keyDown.chr == pageDownChr))
			FrmDispatchEvent (event); 
		}
}


/***********************************************************************
 *
 * FUNCTION:    EventLoop
 *
 * DESCRIPTION: This routine is the event loop for the Datebook
 *              aplication.  
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95	Initial Revision
 *
 ***********************************************************************/
static void EventLoop (void)
{
	Word error;
	EventType event;

	do
		{
		EvtGetEvent (&event, evtWaitForever);
		
		PreprocessEvent (&event);
		
		if (! SysHandleEvent (&event))
			
			if (! MenuHandleEvent (NULL, &event, &error))
				
				if (! ApplicationHandleEvent (&event))
		
					FrmDispatchEvent (&event); 

		#if	EMULATION_LEVEL != EMULATION_NONE
			ECApptDBValidate (ApptDB);
		#endif
		}
	while (event.eType != appStopEvent);
}


/***********************************************************************
 *
 * FUNCTION:    DBPilotMain
 *
 * DESCRIPTION: This is the main entry point for the Datebook
 *              application.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/12/95	Initial Revision
 *			vmk	10/22/97	Moved MIDI db creation to general panel
 *			art	1/7/98	Save current record before receiving a beamed record
 *
 ***********************************************************************/
// Note: We need to create a branch island to PilotMain in order to successfully
//  link this application for the device.
static DWord	DBPilotMain (Word cmd, Ptr cmdPBP, Word launchFlags)
{
	Word error;
	Boolean launched;


	/* are we version compliant? */	
	error = RomVersionCompatible (0x03000000, launchFlags);
	if (error) return (error);
	
	// Launch code sent by the launcher or the datebook button.
	if (cmd == sysAppLaunchCmdNormalLaunch)
		{
		error = StartApplication ();
		if (error) return (error);

		FrmGotoForm (DayView);
		EventLoop ();
		StopApplication ();
		}
	

	// Launch code sent by text search.
	else if (cmd == sysAppLaunchCmdFind)
		{
		Search ((FindParamsPtr)cmdPBP);
		}
	

	// This action code might be sent to the app when it's already running
	// if the use hits the "Go To" button in the Find Results dialog box.
	else if (cmd == sysAppLaunchCmdGoTo)
		{
		launched = launchFlags & sysAppLaunchFlagNewGlobals;
		if (launched)
			{
			error = StartApplication ();
			if (error) return (error);

			GoToItem ((GoToParamsPtr) cmdPBP, launched);

			EventLoop ();
			StopApplication ();	
			}
		else
			GoToItem ((GoToParamsPtr) cmdPBP, launched);
		}


	// Launch code sent by sync application to notify the datebook 
	// application that its database was been synced.
	else if (cmd == sysAppLaunchCmdSyncNotify)
		{
		SyncNotification ();
		}
	

	// Launch code sent by Alarm Manager to notify the datebook 
	// application that an alarm has triggered.
	else if (cmd == sysAppLaunchCmdAlarmTriggered)
		{
		AlarmTriggered ((SysAlarmTriggeredParamType *)cmdPBP);
		}


	// Launch code sent by Alarm Manager to notify the datebook 
	// application that is should display its alarm dialog.
	else if (cmd == sysAppLaunchCmdDisplayAlarm)
		{
		DisplayAlarm ();
		}
	

	// Launch code sent when the system time is changed.
	else if (cmd == sysAppLaunchCmdTimeChange)
		{
		AlarmReset (false);
		}
		

	// This action code is sent after the system is reset. We use this time
	// to create our default database if this is a hard reset
	// Note: This code is used by ROM based applications only. A RAM based 
	//  application will never receive this event.
	else if (cmd == sysAppLaunchCmdSystemReset) 
		{
		if (((SysAppLaunchCmdSystemResetType*)cmdPBP)->createDefaultDB)
			{
			Handle	resH;
			resH = DmGet1Resource(sysResTDefaultDB, sysResIDDefaultDB);
			if (resH) 
				{
				DmCreateDatabaseFromImage(MemHandleLock(resH));
				MemHandleUnlock(resH);
				DmReleaseResource(resH);
				}
			ExgRegisterData(sysFileCDatebook, exgRegExtensionID, "vcs");
			}

		if (! ((SysAppLaunchCmdSystemResetType*)cmdPBP)->hardReset)
			{
			AlarmReset (false);
			}
			
		}
	
	
   // Receive the record.  The app will parse the data and add it to the database.
   // This data should be displayed by the app.
	else if (cmd == sysAppLaunchCmdExgReceiveData) 
   	{
      DmOpenRef dbP;
      Handle plugInResH;
		PlugInMainF	*plugInResP;				// pointer to our (locked) plug-in resource
		DmOpenRef plugInDbRef;					// reference to plug-in database
		Err err;

       
      // if our app is not active, we need to open the database 
      // the subcall flag is used here since this call can be made without launching the app
      if (!(launchFlags & sysAppLaunchFlagSubCall))
      	{
      	err = DateGetDatabase(&dbP, dmModeReadWrite);
      	
      	MultiSegmentStart(&plugInDbRef, &plugInResH, &plugInResP);
      	}
      else
      	{
      	dbP = ApptDB;
      	
      	// Support loopback mode (where this app is already running).
      	plugInResP = gPlugInResP;
      	
			// Save any data the we may be editing.
			FrmSaveAllForms ();
      	}
      
      if (dbP != NULL)
      	{
			error = DateReceiveDataFar(plugInResP, dbP, (ExgSocketPtr) cmdPBP);
			
			// The received event may have an alarm, reschedule the next alarm.
			if (! error)
				RescheduleAlarms (dbP);

         if (!(launchFlags & sysAppLaunchFlagSubCall))
				error = DmCloseDatabase(dbP);
			}
		
      if (!(launchFlags & sysAppLaunchFlagSubCall))
      	{
      	MultiSegmentStop(&plugInDbRef, &plugInResH, &plugInResP);
      	}
		}
      
      
	// This action code is sent by the DesktopLink server when it create 
	// a new database.  We will initializes the new database.
	else if (cmd == sysAppLaunchCmdInitDatabase)
		{
		InitDatabase (((SysAppLaunchCmdInitDatabaseType*)cmdPBP)->dbP);
		}

	return (0);
}

/***********************************************************************
 *
 * FUNCTION:    RomVersionCompatible
 *
 * DESCRIPTION: This routine checks that a ROM version meets your
 *              minimum requirement.
 *
 * PARAMETERS:  requiredVersion - minimum rom version required
 *                                (see sysFtrNumROMVersion in SystemMgr.h 
 *                                for format)
 *              launchFlags     - flags that indicate if the application 
 *                                UI is initialized.
 *
 * RETURNED:    error code or zero if rom is compatible
 *                             
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	11/15/96	Initial Revision
 *
 ***********************************************************************/
static Err RomVersionCompatible (DWord requiredVersion, Word launchFlags)
{
	DWord romVersion;

	// See if we have at least the minimum required version of the ROM or later.
	FtrGet(sysFtrCreator, sysFtrNumROMVersion, &romVersion);
	if (romVersion < requiredVersion)
		{
		if ((launchFlags & (sysAppLaunchFlagNewGlobals | sysAppLaunchFlagUIApp)) ==
			(sysAppLaunchFlagNewGlobals | sysAppLaunchFlagUIApp))
			{
			FrmAlert (RomIncompatibleAlert);
		
			// Pilot 1.0 will continuously relaunch this app unless we switch to 
			// another safe one.
			if (romVersion < 0x02000000)
				AppLaunchWithCommand(sysFileCDefaultApp, sysAppLaunchCmdNormalLaunch, NULL);
			}
		
		return (sysErrRomIncompatible);
		}

	return (0);
}



