#include <PalmOS.h>
#include "T-Suite.h"

Err BlkSEventDequedHandle (SysNotifyParamType *notifyParamsP)
{

	EventType *event = (EventType*)notifyParamsP->notifyDetailsP;

	FormType *frmP;
	FieldType* fldP;
	FieldAttrType attr;
	Boolean capsLock;
	Boolean numLock;
	UInt16 tempShift;
	Boolean autoShifted;

	switch (Swap16(event->eType))
	{
	case penDownEvent:
		return errNone;

	case nilEvent:
	case penUpEvent:
	case keyDownEvent:
	case winExitEvent:
	case fldHeightChangedEvent:
	case tblSelectEvent:
		frmP = FrmGetActiveForm ();
		if (frmP != NULL)
		{
			UInt16 objIndex = FrmGetFocus (frmP);
			if (objIndex != noFocus)
			{
				switch (FrmGetObjectType (frmP, objIndex))
				{
				case  frmFieldObj:
					fldP = (FieldType*)FrmGetObjectPtr (frmP, objIndex);
					goto checkAutoshifting;

				case frmTableObj:
					TableType *tableP;
					tableP = (TableType*)FrmGetObjectPtr (frmP, objIndex);
					fldP = (FieldType*)TblGetCurrentField (tableP);
					if (fldP != NULL)
						goto checkAutoshifting;
				}
			}
		}
	}

	if (Swap16(event->eType) == keyDownEvent)
		goto checkCurKeyEventIsAutoShifted;
	else
		return errNone;

checkAutoshifting:
	FldGetAttributes (fldP, &attr);
	if (attr.autoShift == IsOn)
	{
		attr.autoShift = IsOff;
		FldSetAttributes (fldP, &attr);
		GrfGetState (&capsLock, &numLock, &tempShift, &autoShifted);
		if ((tempShift == grfTempShiftUpper) && (capsLock != true))
		{
			GrfSetState (capsLock, numLock, false);
		}
	}

checkCurKeyEventIsAutoShifted:
	WChar curChr = Swap16(event->data.keyDown.chr);

	UInt32 ftrValue;
	FtrGet (appFileCreator, ftr_appStatus, &ftrValue);
	TSuitePreferenceType *prefsP = (TSuitePreferenceType*)ftrValue;

	if (Swap16 (event->eType) == keyDownEvent)
	{
		if (TxtCharIsAlpha (curChr))
		{
			if (TxtCharIsUpper (curChr) &&
				TxtCharIsLower ((WChar)(UInt16)prefsP->chr))
			{
				if (fldP != prefsP->fldP)
				{
					if ( curChr - ('A' - 'a') == ((WChar)(UInt16)prefsP->chr))
						event->data.keyDown.chr = Swap16(curChr - ('A' - 'a'));
				}
			}

		TSuitePreferenceType prefs;
			MemMove (&prefs, prefsP, sizeof (TSuitePreferenceType));
		prefs.fldP = (FieldPtr)fldP;
		prefs.chr = (UInt16)curChr;
		DmWrite (prefsP, 0, &prefs, sizeof (TSuitePreferenceType));
		}
	}
	
	notifyParamsP->handled = true;

	return errNone;
}