aboutsummaryrefslogblamecommitdiffstats
path: root/apps/windoze/CBuilder5/BibleCS/mainfrm.cpp
blob: d064133adefc595a2b4cd0c7232fed905038f4b0 (plain) (tree)























































                                                                             
                                      










                                                                                                                

                                                             
            























                                                                    
            



































































































                                                                             
                                            






















                                                                                     
                                   



                                                                             
                                               




                                                




                                                    





                                                                                           
                                                


































                                                                                                        


                                                          
         
                                 
 
 
                                   


                                                                             
                                          




















                                                        

                                                            
                                    



















                                                                                                                                                                     
                                            

























                                                                    
                                                      
                                                          
                                                     

                                 
                                                                        




                                                  
                                   


















                                                                             
                                                         






































































                                                                                                                                  

                                                                                         



















                                                                                            
                                                 











































                                                                             
                                                                          

                                                
                                                                                            
                 
                                                     










                                                                             
                             




                                                                                      
                                                







                                                                     

                                                                                


                              

                                                





                                                                                   
                                                                                              








                                                                                                              
                                      













































































                                                                                                                                                                   










































                                                                                                                            
                                                  


































































                                                                                        
                                                                                                                                               




                                                                

                                                                                 

                                                                   
                                                                        

                                                                                           
                                                                                         









                                                                                               
                                                                         

                                                                                           
                                                                                


                                                                                    
                                                         
                                                     
                                                                     



























                                                                            
                                                                                                                








                                                                                                                 
                                                                            


                                                 
                                                


                                                        






                                                                                      

































































                                                                             













                                                                                                                              
                                                             



                                                           

                                                                 
 

                                                                 
        


                                      











                                                                                                                          
















































                                                                                                                                                      



                                                                      
                                                     

                                                                    
                                                        

                                                                     
                                                     

                                                                               
                                                         


                                                                    


                                                                                                                               
                 

                                    




















                                                                                                   

                                                                                     
                                                                      
                                                                                               
                 

                                                                                    









                                                                                        


                                                                                                              


                                                         
























                                                                                              

























                                                                                                                       












                                                                                                                    

         
                                       


















                                                                



                                                                                                                                  
 





                                                                 

                            









                                                                                  

 
 


























                                                                                                                                       

                                                    



























































                                                                                                   



                                                                      





























                                                                                                      














































































































































                                                                                                                                                                   

                                              

                                                  



                                                  
                                              

                                                         
                                    
                                    
         


















                                                                             
                                                    










































































                                                                                                               



























                                                                                       





                                                                                             













                                                                                                                                    
                                 























                                                                                                      
                                                                         



















                                                                                                                 
                                                                                                 
































                                                                                                             
                                   




























                                                                                                          


                                                                                     




























































                                                                                                                  
                                                                                               




















































                                                                                                           
                                                                                              







































                                                                                                                      




                                                                                      





                                                  

                                                              
















































                                                                                           
                                





















































                                                                             
                                  
                            
                      
                      
 

                                                                                       





                                                                                 
                                                                              



                                                    


                                                                                    
 




                                           
 
                                                                                                      
                                                




                                                  


















                                                                       
                                        

                              
                                          



                                                                            






                                                                          
















                                                                                                                                             




                         

                                                                                          
                                                                                      


                                                                                          




                                                                        





                                                          

                                                                                                         
                                                                                                         

                           

                                           
 



                                                                     
 













                                                                                                                                   





                                                                                             










                                                                                                                                    
                                         

                                                        
                                 
                         





                                                  

                                                                            
















                                                                                                                                    
                                                   



                                                                                               
                                                           
                                 


                                                                                
                         




                                                       
                         
                 
 






                                                                                             
                        









                                                                                                                      
                                 

                                                  
                         
                 
 

                                        
                                                                                 
                                                                      


                                                        

                                                                     


                                              
                                                                              



                                                                                                   
                                                                                                      





                                                                                    




                                                                                                                   

                                 


                                                                  
                                         
                                                                                        






                                                                                                           
                                                                          
                                      





                                
                                                
                                                                  
                                



                                                        
  
                              
                                      
         
                           






































































































                                                                                                 






































































                                                                                                               
                                


































































                                                                                                                 



                           


                                                  
                                                              






































                                                                                                
















                                                                                                         
//---------------------------------------------------------------------------
#include <vcl\vcl.h>
#include <vcl/clipbrd.hpp>
#pragma hdrstop

#include "mainfrm.h"
#include "swdisprtfchap.h"
#include "searchfrm.h"
#include "swwinlog.h"
#include "AboutBoxfrm.h"
#include "ModInstForm.h"
#include "biblecsmgr.h"
#include "Greek2Greek.h"
#include "bookmarkfrm.h"
#include "optionfrm.h"
#include "vrslstfrm.h"
#include <utilstr.h>
#include <filemgr.h>
#include <localemgr.h>
#include "editentryfrm.h"
#include "versesel.h"
#include "splashfrm.h"
#include "ModVisFrm.h"
#include "DevOfTheDay.h"
#include "SplashPage.h"
//#include "nsEmbedAPI.h"
#include <graphics.hpp>
#include "sword.h"
#include "rtfhintfrm.h"
#include "newbmfilefrm.h"
#include "RangeMaintFrm.h"
#include "PrintFrm.h"
#include "PreviewForm.h"
//---------------------------------------------------------------------------
#pragma link "RxRichEd"
//#pragma link "MOZILLACONTROLLib_OCX"
//#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"

static const char *rtfclasses[] = {"RTFDisp", "SWDisplay", "SWObject", 0};
SWClass RTFDisp::classdef(rtfclasses);

TForm1 *Form1;
//---------------------------------------------------------------------------


/*
inline AnsiString& operator=(AnsiString& dest, const string& src) {
	dest = src.c_str();
	return dest;
}

*/

void __fastcall TForm1::AppMessage(tagMSG &Msg, bool &Handled)
{
        if (Msg.message == WM_VERSE) {
                HKEY hkey;
                LONG result;
                unsigned long verSize = 32;
                result = RegOpenKeyEx(HKEY_CLASSES_ROOT, "sword\\OpenVerse", NULL, KEY_READ | KEY_WRITE, &hkey);
                result = RegQueryValueEx(hkey, NULL, NULL, NULL, NULL, &verSize);
                char* verStr = new char[verSize];
			 result = RegQueryValueEx(hkey, NULL, NULL, NULL, verStr, &verSize);
                result = RegCloseKey(hkey);
                result = RegDeleteKey(HKEY_CLASSES_ROOT, "sword\\OpenVerse");
                NavigateVerseURL(verStr);
			 Handled = true;
			 Form1->Show();
			 ::SetForegroundWindow(this->Handle);
	   }
}

void TForm1::NavigateVerseURL (char* verStrIN)
{
        unsigned long verSize = strlen(verStrIN) + 1;
        char * verStr = new char[verSize];
        strcpy (verStr, verStrIN);        
        char * verStr2 = new char[verSize];
        unsigned long verSize2 = 0;
        if (*(verStr + verSize - 2) == '\"') {
                *(verStr + verSize - 2) = 0;
        }
	   verSize = 0;
        if (strstr(verStr, "libronix")) {
                char* bib = strstr(verStr, "bible:");
                if (bib) {
                        verSize = 6 + (unsigned long)(bib - verStr);
                }
	   }
        else if (strstr(verStr, "sword://")) {
                verSize = 9;
        }
	   else if (*verStr == '\"') {
			 verSize = 1;
	   }

        while (verStr[verSize] != 0) {
                verStr2[verSize2] = verStr[verSize];
                verSize++;
                verSize2++;
        }
        verStr2[verSize2] = 0;

	   char * verse = strstr(verStr2, "/");
	   if (verse) {
			 *verse = 0;
			 verse++;
	   }
	   else {
			 verse = verStr2;
			 verStr2 = 0;
	   }

	   freeHandLookup->Text = verse;
	   freeHandLookupoldKeyPress(0, '\r');

	   delete [] verStr;
	   delete [] verStr2;
}

__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
	optionsconf = new SWConfig("./options.conf");

	// add our ui locale info to sword's system localemgr
	LocaleMgr::systemLocaleMgr.loadConfigDir("./uilocales.d");

	Lookup->Text = "[ SWORD DDE Lookup ]";
	Search->Text = "[ SWORD DDE Search ]";
	modstates.clear();
	displays.clear();
	ctrlstates.clear();
	DefaultVSKey = 0;
	DefaultStrKey = 0;
	clickText = "";

	lbDictKeysOld->Visible = false;
	DictKeyEditOld->Visible = false;
	lbDictKeys = new TTntListBox(this);
	lbDictKeys->Parent = Panel2;
	lbDictKeys->Align = alClient;
	lbDictKeys->Font->Name = "Code2000";
	lbDictKeys->OnClick = lbDictKeysOldClick;
	
	DictKeyEdit = new TTntEdit(this);
	DictKeyEdit->Parent = Panel2;
	DictKeyEdit->Align = alTop;
	DictKeyEdit->Font->Name = "Code2000";
	DictKeyEdit->OnChange = DictKeyEditOldChange;
	renderingHint = false;	
	closing = false;
}

void __fastcall TForm1::DisplayHint(TObject* Sender) 
{ 
	StatusBar1->SimpleText = GetLongHint(Application->Hint);
}

//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{

	list <SWDisplay *>::iterator it;
	int loop;

	
	if (mainmgr)
		delete mainmgr;
	for (it = displays.begin(); it != displays.end(); it++)
		delete *it;

	if (layoutconf)
		delete layoutconf;

	if (optionsconf)
		delete optionsconf;
		
	for (loop = 0; loop < 10; loop++) {
		if (ctrlstates[loop])
			delete ctrlstates[loop];
	}

	if (DefaultVSKey)
		delete DefaultVSKey;
	if (DefaultStrKey)
		delete DefaultStrKey;
		
	list <ModState *>::iterator mit;
	for (mit = modstates.begin(); mit != modstates.end(); mit++) {
		delete (*mit);
	}
}
//---------------------------------------------------------------------------

char TForm1::CreateTextPane(SWModule *mod) {
	TTabSheet *newtab = new TTabSheet(this);
	SWDispRTFChap *newrtf = new SWDispRTFChap(this);
	char buf[1024];
	SectionMap::iterator sit;

	newtab->Caption = mod->Name();
	newtab->Hint = mod->Description();
	newtab->ParentShowHint = true;
	newtab->PageControl = TextPageControl;
	newrtf->Parent = newtab;
	newrtf->Align = alClient;
	newrtf->ScrollBars = ssVertical;
	newrtf->ReadOnly = true;
	newrtf->PopupMenu = (strcmp(mod->Name(), "N27U4")) ? PopupMenu2 : PopupMenu1;
	newrtf->OnMouseDown = RTFMouseDown;
	newrtf->Name = String("TextRTF")+mod->Name();

	newrtf->module = mod;
	newrtf->recalcAppearance();

	SWDisplay *disp = new RTFDisp(newrtf);
	mod->Disp(disp);
	displays.insert(displays.begin(), disp);
	mod->setKey(*DefaultVSKey);

	return 0;
}
//---------------------------------------------------------------------------
char TForm1::CreateCommentPane(SWModule *mod) {
	TTabSheet *newtab = new TTabSheet(this);
	   TWinControl *newrtf;
	char buf[1024];
	SectionMap::iterator sit;

	newtab->Caption = mod->Name();
	newtab->Hint = mod->Description();
	newtab->ParentShowHint = true;
	newtab->PageControl = CommentaryPageControl;

	if ((*mainmgr->config->Sections[mod->Name()].find("ModDrv")).second == "HREFCom") {
//		if (mainmgr->config->Sections[mod->Name()]["External"] == "1") {
			newrtf = new TPanel(this);
			((TPanel *)newrtf)->Caption = "Syncronizing to External Viewer";
			SWDisplay *disp = new DispExternal();
			mod->Disp(*displays.insert(displays.begin(), disp));
			newrtf->Parent = newtab;
/*
		}
		else {
	//		newrtf = new THTML(this->Handle);
	//		newrtf = new SWDispRTF(this);
			newrtf = HTML1;
			newrtf->Visible = true;
			mod->Disp(*displays.insert(displays.begin(), new HREFDisp((THTML *)newrtf)));
	//		mod->Disp(*displays.insert(displays.begin(), new RTFDisp((SWDispRTF *)newrtf)));
		}
*/
	}
	else {
/*	IE Control
		newrtf = new TCppWebBrowser(this);
		HREFDisp *disp = new HREFDisp((TCppWebBrowser *)newrtf);
		newrtf->Visible = true;
		mod->Disp(*displays.insert(displays.begin(), disp));
		((TCppWebBrowser *)newrtf)->OnBeforeNavigate2 = CppWebBrowser1BeforeNavigate2;
*/		
		newrtf = new SWDispRTF(this);
		
		SWDisplay *disp = new RTFDisp((SWDispRTF *)newrtf);
		mod->Disp(*displays.insert(displays.begin(), disp));
		((SWDispRTF *)newrtf)->ScrollBars = ssVertical;
		((SWDispRTF *)newrtf)->ReadOnly = true;
		((SWDispRTF *)newrtf)->Name = String("CommentRTF")+mod->Name();

		if ((*mainmgr->config->Sections[mod->Name()].find("ModDrv")).second == "RawFiles") {
			((SWDispRTF *)newrtf)->PopupMenu = PopupMenu3;
			((SWDispRTF *)newrtf)->ExpandNewLine = false;
		}
		else	((SWDispRTF *)newrtf)->PopupMenu = PopupMenu2;
		((SWDispRTF *)newrtf)->OnMouseDown = RTFMouseDown;
		((SWDispRTF *)newrtf)->OnURLClick = RTFURLClick;		
		newrtf->Parent = newtab;
		((SWDispRTF *)newrtf)->module = mod;
		((SWDispRTF *)newrtf)->recalcAppearance();
	}
	newrtf->Align = alClient;


	mod->setKey(*DefaultVSKey);
	return 0;
}
//---------------------------------------------------------------------------
char TForm1::CreateLDPane(SWModule *mod) {
	TTabSheet *newtab = new TTabSheet(this);
	SWDispRTF *newrtf = new SWDispRTF(this);
	SectionMap::iterator sit;
	char buf[1024];
	   
	newtab->Caption = mod->Name();
	newtab->Hint = mod->Description();
	newtab->ParentShowHint = true;
	newtab->PageControl = LexDictPageControl;

	newrtf->Parent = newtab;
	newrtf->Align = alClient;
	newrtf->ScrollBars = ssVertical;
	newrtf->ReadOnly = true;
	newrtf->Name = String("LexDictRTF")+mod->Name();
	newrtf->PopupMenu = PopupMenu2;
	newrtf->OnMouseDown = RTFMouseDown;
	newrtf->OnURLClick = RTFURLClick;		
	newrtf->module = mod;
	newrtf->recalcAppearance();

	SWDisplay *disp = new RTFDisp(newrtf);
	mod->Disp(*displays.insert(displays.begin(), disp));
	mod->setKey(*DefaultStrKey);
	return 0;
}
//---------------------------------------------------------------------------


void __fastcall TForm1::BookTOCChange(TObject* Sender, TTreeNode* Node) {
	ModMap::iterator it;

	if (mainmgr) {
		it = mainmgr->Modules.find(CommentaryPageControl->ActivePage->Caption.c_str());
		if (it != mainmgr->Modules.end()) {
			((TreeKeyIdx *)(SWKey *)*(it->second))->setOffset((long)Node->Data);
			(*it).second->Display();
			if (logmodstate)
				modstates.insert(modstates.begin(), new ModState(CommentaryPageControl, CommentaryPageControl->ActivePage, (*it).second->KeyText()));
		}
	}
}


char TForm1::CreateBookPane(SWModule *mod) {
	TTabSheet *newtab = new TTabSheet(this);
	   TWinControl *newrtf;
	char buf[1024];
	SectionMap::iterator sit;
	TTreeView *toc = new TTreeView(this);

	newtab->Caption = mod->Name();
	newtab->Hint = mod->Description();
	newtab->ParentShowHint = true;
	newtab->PageControl = CommentaryPageControl;

	TSplitter *splitter = new TSplitter(this);
	splitter->Parent = newtab;
	splitter->Align = alLeft;

	toc->Parent = newtab;
	toc->Align = alLeft;
	toc->OnChange = BookTOCChange;
	toc->Items->Clear();

	newrtf = new SWDispRTF(this);
	SWDisplay *disp = new RTFBookDisp((SWDispRTF *)newrtf, toc);
	mod->Disp(*displays.insert(displays.begin(), disp));
	((SWDispRTF *)newrtf)->ScrollBars = ssVertical;
	((SWDispRTF *)newrtf)->ReadOnly = true;

	((SWDispRTF *)newrtf)->PopupMenu = PopupMenu2;
	((SWDispRTF *)newrtf)->OnMouseDown = RTFMouseDown;
	newrtf->Name = String("BookRTF")+mod->Name();
	newrtf->Parent = newtab;
	newrtf->Align = alClient;
	((SWDispRTF *)newrtf)->OnURLClick = RTFURLClick;		
	((SWDispRTF *)newrtf)->module = mod;
	((SWDispRTF *)newrtf)->recalcAppearance();



//	mod->setKey(*DefaultVSKey);
	return 0;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::TextPageControlChange(TObject *Sender)
{
	RefreshActiveSheet(TextPageControl);
	Form1->ActiveControl = TextPageControl;
}
//---------------------------------------------------------------------------
void TForm1::RefreshActiveSheet(TPageControl *pc)
{
	ModMap::iterator it;

	if (mainmgr) {
		it = mainmgr->Modules.find(pc->ActivePage->Caption.c_str());
		if (it != mainmgr->Modules.end()) {
			SWModule *module = it->second;
			module->Display();
			pc->Hint = module->Description();
			if (logmodstate)
				modstates.insert(modstates.begin(), new ModState(pc, pc->ActivePage, module->KeyText()));
			if (pc == LexDictPageControl)
				FillDictKeys();
		}
	}
}


void TForm1::TextKeyChanged()
{
	cbBook->ItemIndex = cbBook->Items->IndexOf(DefaultVSKey->books[DefaultVSKey->Testament()-1][DefaultVSKey->Book()-1].name);
	CHBox->Text  = DefaultVSKey->Chapter();
	VSBox->Text  = DefaultVSKey->Verse();
	freeHandLookup->Text = (const char *)*DefaultVSKey;
	RefreshActiveSheet(TextPageControl);
	logmodstate = false;		// only log state once
	RefreshActiveSheet(CommentaryPageControl);
	logmodstate = true;
}


void __fastcall TForm1::btnLookupClick(TObject *Sender)
{
	if (!(StrToInt(CHBox->Text)) || (!StrToInt(VSBox->Text)))
		DefaultVSKey->AutoNormalize(0);

	if (StrToInt(CHBox->Text) < 0)
		CHBox->Text = StrToInt(CHBox->Text) + 1;
	if (StrToInt(VSBox->Text) < 0)
		VSBox->Text = StrToInt(VSBox->Text) + 1;

	(*DefaultVSKey)       = (cbBook->Text + " " + CHBox->Text + ":" + VSBox->Text).c_str();
	TextKeyChanged();
	DefaultVSKey->AutoNormalize(1);	
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CommentaryPageControlChange(TObject *Sender)
{
	RefreshActiveSheet(CommentaryPageControl);
	Form1->ActiveControl = CommentaryPageControl;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::DictKeyEditOldChange(TObject *Sender)
{
	if (DefaultStrKey) {
//		if (DictKeyEdit->Modified) {
			*DefaultStrKey = WideStringToUTF8(DictKeyEdit->Text).c_str();
			RefreshActiveSheet(LexDictPageControl);
			DictKeyEdit->Modified = false;
//		}
	}
}

void TForm1::FillDictKeys() {
	ModMap::iterator it;
	int index = 0;
	SWKey saveKey;
	ConfigEntMap::const_iterator const_eit;
	string fontname;

	if (mainmgr) {
		it = mainmgr->Modules.find(LexDictPageControl->ActivePage->Caption.c_str());
		if (it != mainmgr->Modules.end()) {
			SWModule *module = (*it).second;
			RTFDisp *disp = SWDYNAMIC_CAST(RTFDisp, module->Disp());
			if (disp) {
				SWDispRTF *rtfDisp = (SWDispRTF*) disp->editControl();
				rtfDisp->recalcAppearance();
				lbDictKeys->Font->Name = rtfDisp->dispAttribs.fontName;
				lbDictKeys->Font->Size = rtfDisp->dispAttribs.fontSize;
				lbDictKeys->Color = rtfDisp->dispAttribs.backColor;
				lbDictKeys->Font->Color = rtfDisp->dispAttribs.fontColor;

				DictKeyEdit->Font->Name = rtfDisp->dispAttribs.fontName;
				DictKeyEdit->Font->Size = rtfDisp->dispAttribs.fontSize;
			}

			module->KeyText(); // snap to entry
			saveKey = module->KeyText();
			int count = lbDictKeys->Height / lbDictKeys->ItemHeight;
			lbDictKeys->Items->Clear();
			for (int i = 0; i < (count / 2); i++)
				(*module)++;
			for (int i = 0; i < count-1; i++)
				(*module)--;
			module->Error();
			for (;!module->Error() && count;count--,(*module)++) {
				lbDictKeys->Items->Add(UTF8ToWideString(module->KeyText()));
				if (saveKey == module->Key())
					index = lbDictKeys->Items->Count-1;
			}
			lbDictKeys->ItemIndex = index;
			*DefaultStrKey = saveKey;
		}
	}
}


//---------------------------------------------------------------------------
void __fastcall TForm1::LexDictPageControlChange(TObject *Sender)
{
	*DefaultStrKey = WideStringToUTF8(DictKeyEdit->Text).c_str();
	RefreshActiveSheet(LexDictPageControl);
	Form1->ActiveControl = LexDictPageControl;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NewSearchWindow1Click(TObject *Sender) {

	searchForm->Show();	
}

//---------------------------------------------------------------------------
void __fastcall TForm1::Exit1Click(TObject *Sender)
{
	Close();	
}

void __fastcall TForm1::About1Click(TObject *Sender)
{
	AboutBox->ShowModal();	
}


WideString TForm1::TrimJunk(WideString src) {
	bool hasDigit = false;
     bool hasAlpha = false;
	WideString retVal = "";
	
	int len = src.Length();
	for (int i = 1; i <=len; i++) {
		if (isdigit(src[i]))
			hasDigit = true;
		if (isalpha(src[i]) || (src[i] > 255))
			hasAlpha = true;
	}
	for (int i = 1; i <= len; i++) {
		if (hasDigit && !hasAlpha) {	// number
			if (isdigit(src[i])) retVal += (WideString)src[i];
		}
		else if (hasAlpha) {	// alpha
			if (isalpha(src[i]) || (src[i] > 255)) retVal += (WideString)src[i];
		}
		else	retVal += (WideString)src[i];
	}
	return retVal;
}


//---------------------------------------------------------------------------
void __fastcall TForm1::DictionaryLookup1Click(TObject *Sender)
{
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	int wordstart;
	int saveSelStart = rtf->SelStart;
	WideString lookupKey;
	ConfigEntMap::iterator eit;
	char preChar = 0;
		
	if (!rtf->SelLength) {
		preChar = (rtf->WordAtCursor().Length()) ? rtf->WordAtCursor()[1] : 0;
		lookupKey = rtf->WordAtCursor();
	}
	else	{
		preChar = rtf->Text[(rtf->SelStart)?rtf->SelStart:0];
		lookupKey = Trim(rtf->SelText);
	}
		
	// check if all digits (strongs)
	int i;
	for (i = 0; i < lookupKey.Length(); i++) {
		if (!isdigit(lookupKey[i+1]) && !strchr("<>()", lookupKey[i+1]))
			break;
	}

	if ((i == lookupKey.Length()) && (i)) {
		lookupKey = TrimJunk(lookupKey);
		String curLex = LexDictPageControl->ActivePage->Caption;
		String feature = (DefaultVSKey->Testament() == 1)?"Hebrew":"Greek";
		feature += (preChar == '(')?"Parse":"Def";
		if (!strncmp(rtf->Name.c_str(), "TextRTFLXX", 10))
			feature = "GreekDef";
		if (!hasFeature(mainmgr, curLex.c_str(), feature.c_str())) {
			string tmpval = optionsconf->Sections["ModDefaults"][feature.c_str()];
			for (int i = 0; i < LexDictPageControl->PageCount; i++) {
				if (!stricmp(LexDictPageControl->Pages[i]->Caption.c_str(), tmpval.c_str())) {
					LexDictPageControl->ActivePageIndex = i;
					break;
				}
			}
		}
	}
	
	DictKeyEdit->Text = lookupKey;
}


void __fastcall TForm1::verseLookupClick(TObject *Sender)
{
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	int wordstart;
	int saveSelStart = rtf->SelStart;
	
	if (!rtf->SelLength) {
		for (wordstart = rtf->SelStart; (wordstart > -1)&&(isdigit(rtf->Text[wordstart])||isalpha(rtf->Text[wordstart])); wordstart--);
		rtf->SelStart = (wordstart > -1) ? wordstart: 0;
		for (wordstart = rtf->SelStart + 1; (wordstart < rtf->Text.Length())&&(isdigit(rtf->Text[wordstart])||isalpha(rtf->Text[wordstart])); wordstart++);
		rtf->SelLength = ((wordstart < rtf->Text.Length()) ? wordstart : rtf->Text.Length()) - rtf->SelStart - 1;
		freeHandLookup->Text = Trim(rtf->SelText);
		rtf->SelStart = saveSelStart;
		rtf->SelLength = 0;
	}
	else	freeHandLookup->Text = Trim(rtf->SelText);
	char ret = '\r';
	freeHandLookupoldKeyPress(Sender, ret);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SaveLayout1Click(TObject *Sender)
{
	ConfigEntMap sit;
	sit = layoutconf->Sections["Screen"];
	if(Form1->WindowState == wsMaximized) {
		sit["Maximized"] = "true";
	}
	else {
		sit["Maximized"] = "false";
		sit["MainTop"] = IntToStr(Form1->Top).c_str();
		sit["MainLeft"] = IntToStr(Form1->Left).c_str();
		sit["MainHeight"] = IntToStr(Form1->Height).c_str();
		sit["MainWidth"] = IntToStr(Form1->Width).c_str();
	}
	sit["TextComHeight"] = IntToStr(pnlTextCom->Height).c_str();
	sit["TextWidth"] = IntToStr(pnlText->Width).c_str();

	if(searchForm->WindowState == wsMaximized) {
		sit["SearchMaximized"] = "true";
	}
	else {
		sit["SearchMaximized"] = "false";
		sit["SearchTop"] = IntToStr(searchForm->Top).c_str();
		sit["SearchLeft"] = IntToStr(searchForm->Left).c_str();
		sit["SearchWidth"] = IntToStr(searchForm->Width).c_str();
		sit["SearchHeight"] = IntToStr(searchForm->Height).c_str();
	}

	OptionsList options = mainmgr->getGlobalOptions();
	for (OptionsList::iterator it = options.begin(); it != options.end(); it++) {
		string value = mainmgr->getGlobalOption(it->c_str());
		(*layoutconf)["ModuleOptions"][it->c_str()] = value;
	}
	layoutconf->Sections["Screen"] = sit;
	layoutconf->Save();
}


void TForm1::fillVKeySelector(VerseKey *vk) {
	VerseKey *myVk = (VerseKey *)vk->clone();
	myVk->Error();	//clear error
	(*myVk) = TOP;
	cbBook->Clear();
	while (!myVk->Error()) {
		AnsiString s1 = (const char *)(*myVk);
		s1.SetLength(s1.Length() - 4);
		cbBook->Items->Add(s1);
		myVk->Book(myVk->Book() + 1);
	}
	delete myVk;
}


void TForm1::i12ize(const char *lang) {
	LocaleMgr::systemLocaleMgr.setDefaultLocaleName(lang);
	// TODO 5 -cConfiguration Ops -oScribe: add mainmgr->configpath, or something, to beginning of these image names ???
	const char *tmp;
	Graphics::TBitmap *bitmap = 0;
	TPicture *pic = new TPicture();

	ImageList1->Clear();		
	
	tmp = _tr("BackBtnImage");
	if (strcmp("BackBtnImage", tmp)) {
		pic->LoadFromFile(tmp);
		bitmap = pic->Bitmap;
	}
	else bitmap = BackBtnImage->Picture->Bitmap;
	
	TColor transColor = bitmap->Canvas->Pixels[0][0];
	ImageList1->AddMasked(bitmap, transColor);

	tmp = _tr("SearchBtnImage");
	if (strcmp("SearchBtnImage", tmp)) {
		pic->LoadFromFile(tmp);
		bitmap = pic->Bitmap;
	}
	else bitmap = SearchBtnImage->Picture->Bitmap;
	
	transColor = bitmap->Canvas->Pixels[0][0];
	ImageList1->AddMasked(bitmap, transColor);
	
	bitmap = BookmarkBtnImage->Picture->Bitmap;
	transColor = bitmap->Canvas->Pixels[0][0];
	ImageList2->AddMasked(bitmap, transColor);

	delete pic;
	
	// MainForm
	File1->Caption = _tr("&File");
	SaveLayout1->Caption = _tr("S&ave Layout");
	Print1->Caption = _tr("&Print...");
	Exit1->Caption = _tr("E&xit");
	Edit1->Caption = _tr("&Edit");
	Copy1->Caption = _tr("&Copy");
	Copy2->Caption = _tr("&Copy");
	Copy3->Caption = _tr("&Copy");
	Copy4->Caption = _tr("&Copy");
	NewVer1->Caption = _tr("&New Verse List");
	CopyasBGreekTransliteration1->Caption = _tr("Copy as &B-Greek Transliteration");
	MenuItem1->Caption = _tr("Dictionary Lookup");
	Copy4->Caption = _tr("&Copy");
	Copy4->Caption = _tr("&Copy");
	Copy4->Caption = _tr("&Copy");
	Options2->Caption = _tr("Options");
	Options1->Caption = _tr("&Preferences...");
	Search1->Caption = _tr("&Search");
	NewSearchWindow1->Caption = _tr("&New Search Window");
	Tools1->Caption = _tr("&Tools");
	InstallManager1->Caption = _tr("Install Manager");
	Help1->Caption = _tr("&Help");
	Contents1->Caption = _tr("Contents");
	DevotionaloftheDay1->Caption = _tr("Devotional of the Day");
	About1->Caption = _tr("&About");
	Bookmarkbtn->Caption = _tr("Bookmark");
	DictionaryLookup1->Caption = _tr("Dictionary Lookup");
	DictionaryLookup2->Caption = _tr("Dictionary Lookup");
	EditEntry1->Caption = _tr("&Edit Entry");
	DeleteEntry1->Caption = _tr("&Delete Entry");
	LinktoVerse1->Caption = _tr("Link to Comment for Verse...");
	AddBookmark1->Caption = _tr("&Add Bookmark");
	EditBookmarks1->Caption = _tr("&Edit Bookmarks / Tree View...");
	HideShowModules1->Caption = _tr("Hide / Show Modules");
	ToolButton3->Hint = _tr("Go Back To Previous Location");
	ToolButton4->Hint = _tr("Bring Up Search Window");
	TextPageControl->Hint = _tr("Biblical Texts");
	CommentaryPageControl->Hint = _tr("Commentaries");
	LexDictPageControl->Hint = _tr("Lexicons / Dictionaries");
	// AboutBox
	AboutBox->Caption = _tr("About The SWORD Project");
	AboutBox->OKButton->Caption = _tr("OK");

	// bookmarkForm
	bookmarkForm->Caption = _tr("Bookmarks");

	// DevOfTheDay2
	DevOfTheDay2->Caption = _tr("Devotion for Today");
	DevOfTheDay2->ckShowTip->Caption = _tr("Show Devotional at Startup");
	DevOfTheDay2->btnOK->Caption = _tr("&Close");
	DevOfTheDay2->Label1->Caption = _tr("Words To Live By...");

	// EditEntryForm
	EditEntryForm->Caption = _tr("Edit Entry");
	EditEntryForm->Label1->Caption = _tr("Font Size:");
	
	
	
	// ModInstForm
	ModInstFrm->Caption = _tr("Found New Module...");
	ModInstFrm->OkBtn->Caption = _tr("OK");	
	
	// ModVisForm
	ModVisForm->Caption = _tr("Check Modules To Show As Tabs");
	ModVisForm->modList->Columns->Items[0]->Caption = _tr("Module");
	ModVisForm->modList->Columns->Items[1]->Caption = _tr("Description");
	ModVisForm->OkBtn->Caption = _tr("OK");
	ModVisForm->CancelBtn->Caption = _tr("Cancel");

	// NewBMfrm
	NewBMfrm->Caption = _tr("Add New Bookmark File");
	NewBMfrm->Label1->Caption = _tr("File Name (without extension):");
	NewBMfrm->Label2->Caption = _tr("Bookmark Section Title:");
	NewBMfrm->OkBtn->Caption = _tr("OK");
	NewBMfrm->CancelBtn->Caption = _tr("Cancel");

	// OptionsForm
	 /* DONE 2 -cLocalize : Change Module Type to Window Type here and in the localization files and get it updated by our local guys :) */
	Optionsfrm->Caption = _tr("Preferences");
	Optionsfrm->TabSheet1->Caption = _tr("General");
	Optionsfrm->TabSheet2->Caption = _tr("Special Modules");
	Optionsfrm->TabSheet3->Caption = _tr("Display");
	Optionsfrm->gbPersonalize->Caption = _tr("Personalize");
	Optionsfrm->AutoBMPersonal->Caption = _tr("Autosave Personal Bookmarks");
	Optionsfrm->AutoBMOther->Caption = _tr("Autosave Other Bookmarks");
	Optionsfrm->HintPopups->Caption = _tr("Show Hint Pop-ups");
	Optionsfrm->Label4->Caption = _tr("Language");
	Optionsfrm->AutoLayout->Caption = _tr("Autosave Screen Layout");
	Optionsfrm->HintStrongs->Caption = _tr("Show Lexicon Lookup Over Strongs Numbers");
	Optionsfrm->HintVLists->Caption = _tr("Show Preview Over Verse Lists");
	Optionsfrm->HintWords->Caption = _tr("Show Glossary Lookup Over Words (CTRL-W)");
	Optionsfrm->OkBtn->Caption = _tr("OK");
	Optionsfrm->CancelBtn->Caption = _tr("Cancel");
	Optionsfrm->gbDefModules->Caption = _tr("Original Language Support - Default Modules");
	Optionsfrm->Label7->Caption = _tr("Definitions");
	Optionsfrm->Label8->Caption = _tr("Parsing");
	Optionsfrm->Label5->Caption = _tr("Greek");
	Optionsfrm->Label6->Caption = _tr("Hebrew");
	Optionsfrm->Label10->Caption = _tr("Strong's Numbered Text");
	Optionsfrm->gbDevos->Caption = _tr("Daily Devotionals");
	Optionsfrm->Label9->Caption = _tr("Default Devotional");
	Optionsfrm->Label17->Caption = _tr("Default General Dictionary");
	Optionsfrm->devSplashCB->Caption = _tr("Show Devotional Splash Screen on Startup");
	Optionsfrm->devsAsDictsCB->Caption = _tr("Show Devotionals as Dictionaries");
	Optionsfrm->gbGloss->Caption = _tr("Glossaries / General Dictionaries");
	Optionsfrm->glosAsDictsCB->Caption = _tr("Show Glossaries as Dictionaries");
	Optionsfrm->gbColors->Caption = _tr("Display Colors");
	Optionsfrm->Label2->Caption = _tr("Preview");
	Optionsfrm->Label3->Caption = _tr("Window Type");
	Optionsfrm->Label14->Caption = _tr("Scheme");
	Optionsfrm->Label11->Caption = _tr("Text Styles and Colors");
	Optionsfrm->btnFont->Caption = _tr("Select Font...");
	Optionsfrm->Label13->Caption = _tr("Verse Number Color");
	Optionsfrm->btnNumClr->Caption = _tr("Select Color...");
	Optionsfrm->AutoVSColor->Caption = _tr("Current Verse Color");
	Optionsfrm->btnCurrVerse->Caption = _tr("Select Color...");
	Optionsfrm->Label15->Caption = _tr("Combo/Edit Fields");
	Optionsfrm->btnFieldClr->Caption = _tr("Select Color...");
	Optionsfrm->Label1->Caption = _tr("Individual Modules (Font Only)");
	Optionsfrm->btnModFonts->Caption = _tr("Select Font...");
	Optionsfrm->Label12->Caption = _tr("Strong's Numbers <...>");
	Optionsfrm->Label16->Caption = _tr("Strong's Tense (...)");
	Optionsfrm->btnStrongClr->Caption = _tr("Select Color...");
	Optionsfrm->btnMorphClr->Caption = _tr("Select Color...");

	// RangeMaintForm
	RangeMaintForm->Caption = _tr("Maintain Custom Ranges");
	RangeMaintForm->Label1->Caption = _tr("Range Name");
	RangeMaintForm->Label2->Caption = _tr("Range Text");
	RangeMaintForm->Label3->Caption = _tr("eg. mat-jo;rev4");
	RangeMaintForm->SpeedButton1->Caption = _tr("&Add");
	RangeMaintForm->SpeedButton2->Caption = _tr("&Remove");
	RangeMaintForm->SpeedButton3->Caption = _tr("&Save");
	RangeMaintForm->SpeedButton4->Caption = _tr("&Cancel");

	// searchForm
	searchForm->Caption = _tr("Search...");
	searchForm->searchBtn->Caption = _tr("Search");
	searchForm->searchTypeGroup->Caption = _tr("Search Type");
	searchForm->searchTypeGroup->Items->CommaText = _tr("\"Multi Word\",\"Phrase\",\"Regular Expression\"");
	searchForm->caseSensitiveCkBx->Caption = _tr("Case Sensitive");
	searchForm->searchOptionsGroup->Caption = _tr("Search Options");
	searchForm->scopeGroup->Caption = _tr("Scope");
	searchForm->scopeGroup->Items->CommaText = _tr("\"Entire Module\",\"Current Results\",\"Custom Range\"");
	searchForm->customRangeBtn->Caption = _tr("Define Custom Range");
	searchForm->resultsLV->Columns->Items[0]->Caption = _tr("Reference");
	searchForm->resultsLV->Columns->Items[1]->Caption = _tr("Preview...");
	searchForm->lblChooseModule->Caption = _tr("Choose Module");
	searchForm->Button2->Caption = _tr("&Help");
	searchForm->Button3->Caption = _tr("Create Verse&List From Result");

	// VerseSelFrm
	VerseSelFrm->Caption = _tr("Type Verse");
	VerseSelFrm->OkBtn->Caption = _tr("OK");
	VerseSelFrm->CancelBtn->Caption = _tr("Cancel");

	// VerseListFrm
	VerseListForm->Caption = _tr("Verse List");
	VerseListForm->SpeedButton1->Hint = _tr("Add Current Verse To List");
	VerseListForm->SpeedButton2->Hint = _tr("Remove Highlighted Entry From List");
	VerseListForm->SpeedButton3->Hint = _tr("Copy All Entries To Clipboard");
	VerseListForm->SpeedButton4->Hint = _tr("Print All Entries");
	VerseListForm->SpeedButton5->Hint = _tr("Save Verse List To File");
	VerseListForm->SpeedButton6->Hint = _tr("Load Verse List From File");

	// Print Form
	PrintForm->shtSelection->Caption = _tr("Print Selection");
	PrintForm->radText->Caption = _tr("Bible Text");
	PrintForm->radComm->Caption = _tr("Commentary Text");
	PrintForm->radLD->Caption = _tr("Lexicon/Dictionary Text");
	PrintForm->lblModName->Caption = _tr("Module Name");
	PrintForm->GroupBox1->Caption = _tr("Print Source");
	PrintForm->GroupBox2->Caption = _tr("Print Range");
	PrintForm->staticRange->Caption = _tr("Verse List");
	PrintForm->shtSetup->Caption = _tr("Page Setup");
	PrintForm->labelLeft->Caption = _tr("Left:");
	PrintForm->labelRight->Caption = _tr("Right:");
	PrintForm->labelTop->Caption = _tr("Top:");
	PrintForm->labelBot->Caption = _tr("Bottom:");
	PrintForm->ckHeader->Caption = _tr("Print Header");
	PrintForm->labelHeader->Caption = _tr("Header Text:");
	PrintForm->ckFooter->Caption = _tr("Print Footer");
	PrintForm->labelFooter->Caption = _tr("Footer Text:");
	PrintForm->editFooter->Text = _tr("Page &p of &t");
	PrintForm->GroupBox4->Caption = _tr("Margins (Inches)");
	PrintForm->GroupBox5->Caption = _tr("Header/Footer");
	PrintForm->shtFormat->Caption = _tr("Formatting Options");
	PrintForm->GroupBox3->Caption = _tr("Font and Size");
	PrintForm->Label10->Caption = _tr("Chapter Heading");
	PrintForm->Label11->Caption = _tr("Body Text:");
	PrintForm->Label12->Caption = _tr("Verse Numbers:");
	PrintForm->ckBookHead->Caption = _tr("Book Name");
	PrintForm->ckChHead->Caption = _tr("Chapter Headings");
	PrintForm->ckParagraph->Caption = _tr("Paragraph Format");
	PrintForm->labelFont->Caption = _tr("Font:");
	PrintForm->ckVSNum->Caption = _tr("Verse Numbers");
	PrintForm->ckSuperVS->Caption = _tr("Superscripted");
	PrintForm->ckPrefix->Caption = _tr("Prefixed (John 1:1 KJV)...");
	PrintForm->ckPostfix->Caption = _tr("Postfixed ...(John 1:1 KJV)");
	PrintForm->btnPrint->Caption = _tr("&Print");
	PrintForm->btnPreview->Caption = _tr("P&review...");
	PrintForm->btnSetup->Caption = _tr("Printer&s...");
	PrintForm->btnClose->Caption = _tr("&Close");

	// Print Preview Form
	PreviewForm->btnPrint->Caption = "Print";
	PreviewForm->btnClose->Caption = "&Close";
	
}


//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow(TObject *Sender)
{
	ModMap::iterator it;
	SectionMap::iterator sit;
	ConfigEntMap::iterator eit, eitend;
	AnsiString s1;
	char textFont[128];
	char commentFont[128];
	char LDFont[128];
	char tempTextFont[128];
	char tempCommFont[128];
	char tempLDFont[128];
	int loop;
	int maxFiles;
	TColor fieldColor;
	string tmpval;
	bool showDevos;
	bool showGlos;

/*
	showLocked = true;
	for (int i=0;i<=ParamCount();i++) {
		if (LowerCase(ParamStr(i)) == "-noLocked")
			showLocked = false;
	}
*/

	logmodstate = true;
	freshdict   = true;
	if (SWLog::systemlog)
		delete SWLog::systemlog;
	SWLog::systemlog = new SWWinLog(this->Handle);		// set the system logger to our MSWindows specific SWLog class
	tmpval = optionsconf->Sections["System"]["MaxFiles"];
	if ((maxFiles = atoi(tmpval.c_str()))) {
		FileMgr::systemFileMgr.maxFiles = maxFiles;
	}

	tmpval = optionsconf->Sections["General"]["DevsAsDicts"];
	showDevos = (stricmp(tmpval.c_str(), "false"));

	tmpval = optionsconf->Sections["General"]["GlosAsDicts"];
	showGlos = (stricmp(tmpval.c_str(), "false"));
	
	DefaultVSKey = new VerseKey();
	DefaultStrKey = new StrKey();

	fillVKeySelector(DefaultVSKey);

	cbBook->ItemIndex = cbBook->Items->IndexOf("James");

	DefaultVSKey->Persist(1);	// when set to a module, make the module hold on to this actual key and not a copy
	*DefaultVSKey = "James 1:19"; // set to our standard starting verse
	DefaultStrKey->Persist(1);
	*DefaultStrKey = "";

	mainmgr = new BibleCSMGR(ModInstFrm);

	// Load devotion and show form

	for (it = mainmgr->Modules.begin(); it != mainmgr->Modules.end(); it++) {
		bool devotional = false;
		bool glossary = false;

		// leave out enciphered texts with no key
		if ((sit = mainmgr->config->Sections.find((*it).second->Name())) != mainmgr->config->Sections.end()) {
			if ((eit = (*sit).second.find("CipherKey")) != (*sit).second.end()) {
				const char *cipherKey = (char *)(*eit).second.c_str();
				if (strlen(cipherKey) < 1)
					continue;
			}

			for (eit = (*sit).second.lower_bound("Feature"), eitend = (*sit).second.upper_bound("Feature"); eit != eitend; eit++) {
				const char *feature = eit->second.c_str();
				if (!stricmp(feature, "StrongsNumbers")) {
					Optionsfrm->strongsNumsCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					if (optionsconf->Sections["ModDefaults"].find("StrongsNumbers") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["StrongsNumbers"] = it->second->Name();
				}
				if (!stricmp(feature, "GreekDef")) {
					Optionsfrm->greekDefCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					if (optionsconf->Sections["ModDefaults"].find("GreekDef") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["GreekDef"] = it->second->Name();
				}
				if (!stricmp(feature, "GreekParse")) {
					Optionsfrm->greekParseCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					if (optionsconf->Sections["ModDefaults"].find("GreekParse") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["GreekParse"] = it->second->Name();
				}
				if (!stricmp(feature, "HebrewDef")) {
					Optionsfrm->hebrewDefCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					if (optionsconf->Sections["ModDefaults"].find("HebrewDef") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["HebrewDef"] = it->second->Name();
				}
				if (!stricmp(feature, "HebrewParse")) {
					Optionsfrm->hebrewParseCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					if (optionsconf->Sections["ModDefaults"].find("HebrewParse") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["HebrewParse"] = it->second->Name();
				}
				if (!stricmp(feature, "DailyDevotion")) {
					Optionsfrm->dailyDefaultCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
					devotional = true;
					if (optionsconf->Sections["ModDefaults"].find("DailyDevotion") == optionsconf->Sections["ModDefaults"].end())
						(*optionsconf)["ModDefaults"]["DailyDevotion"] = it->second->Name();
				}
				if (!stricmp(feature, "Glossary")) {
					glossary = true;
				}
			}
		}

		if (!strcmp((*it).second->Type(), "Biblical Texts")) {
			CreateTextPane((*it).second);
		}
		if (!strcmp((*it).second->Type(), "Commentaries")) {
			CreateCommentPane((*it).second);
		}
		if (!strcmp((*it).second->Type(), "Generic Books")) {
			CreateBookPane((*it).second);
		}
		if (!strcmp((*it).second->Type(), "Lexicons / Dictionaries")) {
			if ((!devotional && !glossary) ||
					(showDevos && devotional) ||
					(showGlos && glossary))
				CreateLDPane((*it).second);
			Optionsfrm->genDictCB->Items->AddObject(it->second->Description(), (TObject *)it->second->Name());
			if (optionsconf->Sections["ModDefaults"].find("GenDict") == optionsconf->Sections["ModDefaults"].end())
				(*optionsconf)["ModDefaults"]["GenDict"] = it->second->Name();
		}
		optionsconf->Save();

	}

	layoutconf = new SWConfig("./layout.conf");

	if ((sit = layoutconf->Sections.find("Screen")) != layoutconf->Sections.end()) {

		if ((eit = (*sit).second.find("MainTop")) != (*sit).second.end())
			Form1->Top = atoi((*eit).second.c_str());
		if ((eit = (*sit).second.find("MainLeft")) != (*sit).second.end())
			Form1->Left = atoi((*eit).second.c_str());
		if ((eit = (*sit).second.find("MainHeight")) != (*sit).second.end())
			Form1->Height = atoi((*eit).second.c_str());
		if ((eit = (*sit).second.find("MainWidth")) != (*sit).second.end())
			Form1->Width = atoi((*eit).second.c_str());

		Form1->WindowState = (sit->second["Maximized"] == "true") ? wsMaximized : wsNormal;

		if ((eit = (*sit).second.find("TextComHeight")) != (*sit).second.end())
			pnlTextCom->Height = atoi((*eit).second.c_str());
		if ((eit = (*sit).second.find("TextWidth")) != (*sit).second.end())
			pnlText->Width = atoi((*eit).second.c_str());

		if ((eit = (*sit).second.find("SearchTop")) != (*sit).second.end()) {
			searchForm->Top = atoi((*eit).second.c_str());
			searchForm->Position = poDesigned;	// because we've set the values
		}
		if ((eit = (*sit).second.find("SearchLeft")) != (*sit).second.end())
			searchForm->Left = atoi((*eit).second.c_str());
		if ((eit = (*sit).second.find("SearchHeight")) != (*sit).second.end()) {
			int val = atoi((*eit).second.c_str());
			val = max(val, searchForm->Constraints->MinHeight);
			searchForm->Height = val;
		}
		if ((eit = (*sit).second.find("SearchWidth")) != (*sit).second.end()) {
			int val = atoi((*eit).second.c_str());
			val = max(val, searchForm->Constraints->MinWidth);
			searchForm->Width = val;
		}
		searchForm->WindowState = (sit->second["SearchMaximized"] == "true") ? wsMaximized : wsNormal;
	}

	for (loop = 0; loop < 10; loop++)
		ctrlstates.insert(ctrlstates.begin(), 0);
	
	// Add options to Options Main Menu choice
	sit = layoutconf->Sections.find("ModuleOptions");
	OptionsList options = mainmgr->getGlobalOptions();
	for (OptionsList::iterator it = options.begin(); it != options.end(); it++) {
		TMenuItem *newitem = new TMenuItem(MainMenu1);
		newitem->Caption = it->c_str();
		newitem->Default = false;
		newitem->OnClick = OptionShowVals;
		newitem->Hint = mainmgr->getGlobalOptionTip(it->c_str());
		if (sit != layoutconf->Sections.end()) {
			if ((eit = sit->second.find(it->c_str())) != sit->second.end())
				mainmgr->setGlobalOption(it->c_str(), eit->second.c_str());
		}
		OptionsList values = mainmgr->getGlobalOptionValues(it->c_str());    
		for (OptionsList::iterator it2 = values.begin(); it2 != values.end(); it2++) {
			TMenuItem *newitem2 = new TMenuItem(MainMenu1);
			newitem2->Caption = it2->c_str();
			newitem2->Default = false;
			newitem2->OnClick = GlobalOptionChange;
			newitem->Add(newitem2);
		}
//		Mainmenu->Items->Add(newitem);
		Options2->Add(newitem);
	}

	if ((sit = layoutconf->Sections.find("History")) != layoutconf->Sections.end()) {

		eitend = (*sit).second.upper_bound("SearchText");
		for (eit = (*sit).second.lower_bound("SearchText"); eit != eitend; eit++)
			searchForm->SearchText->Items->Add(UTF8ToWideString(eit->second.c_str()));

		eitend = (*sit).second.upper_bound("LookupText");
		for (eit = (*sit).second.lower_bound("LookupText"); eit != eitend; eit++)
			freeHandLookup->Items->Add(eit->second.c_str());

		if ((eit = (*sit).second.find("LastTextModule")) != (*sit).second.end()) {
			for (int i = 0; i < TextPageControl->PageCount; i++) {
				if (!strcmp(TextPageControl->Pages[i]->Caption.c_str(), (*eit).second.c_str())) {
					TextPageControl->ActivePageIndex = i;
					break;
				}
			}
		}
		if ((eit = (*sit).second.find("LastComModule")) != (*sit).second.end()) {
			for (int i = 0; i < CommentaryPageControl->PageCount; i++) {
				if (!strcmp(CommentaryPageControl->Pages[i]->Caption.c_str(), (*eit).second.c_str())) {
					CommentaryPageControl->ActivePageIndex = i;
					break;
				}
			}
		}

		if ((eit = (*sit).second.find("LastLDModule")) != (*sit).second.end()) {
			for (int i = 0; i < LexDictPageControl->PageCount; i++) {
				if (!strcmp(LexDictPageControl->Pages[i]->Caption.c_str(), (*eit).second.c_str())) {
					LexDictPageControl->ActivePageIndex = i;
					break;
				}
			}
		}
		if ((eit = (*sit).second.find("LastLDKey")) != (*sit).second.end()) {
			DictKeyEdit->Text = UTF8ToWideString((*eit).second.c_str());
		}

	}

	// set the correct tabs visible
	ConfigEntMap *section;
	TPageControl *pc = 0;
	for (int pcs = 0; pcs < 3; pcs++) {
		switch (pcs) {
		case 0:
			pc = TextPageControl;
			section = &(*layoutconf)["TextView"];
			break;
		case 1:
			pc = CommentaryPageControl;
			section = &(*layoutconf)["CommentView"];
			break;
		case 2:
			pc = LexDictPageControl;
			section = &(*layoutconf)["LDView"];
			break;
		}
		
		for (int i = 0; i < pc->PageCount; i++) {
			string heading = pc->Pages[i]->Caption.c_str();
			pc->Pages[i]->TabVisible = !((*section)[heading.c_str()] == "false");  // !false allows default to be true
		}
	}

	SplashPg->Hide();

	tmpval = optionsconf->Sections["General"]["TipOfTheDay"];
	if(!stricmp(tmpval.c_str(), "Devotional")) {
		DevOfTheDay2->Show();
	}

	refreshAppearance();

	if (this->Tag) {
		NavigateVerseURL((char*)(this->Tag));
	}
	else if ((eit = (*sit).second.find("LastVerse")) != (*sit).second.end()) {
		freeHandLookup->Text = (*eit).second.c_str();
		char ret = '\r';
		freeHandLookupoldKeyPress(0, ret);
	}

}


bool TForm1::hasFeature(SWMgr *mgr, const char *modName, const char *feature) {
	SectionMap::iterator sit;
	ConfigEntMap::iterator eit, eitend;

	if ((sit = mgr->config->Sections.find(modName)) != mgr->config->Sections.end()) {
		for (eit = (*sit).second.lower_bound("Feature"), eitend = (*sit).second.upper_bound("Feature"); eit != eitend; eit++) {
			const char *tfeature = eit->second.c_str();
			if (!stricmp(tfeature, feature))
				return true;
		}
	}
	return false;
}


//---------------------------------------------------------------------------
void __fastcall TForm1::LookupPokeData(TObject *Sender)
{
	char buf[255];
	char *token;
	ModMap::iterator it;

	strncpy(buf, Lookup->Text.c_str(), 254);
	buf[254] = 0;
	token = strtok(buf, " ");
	if ((it = mainmgr->Modules.find(token)) != mainmgr->Modules.end()) {
		token = strtok(NULL, "");
		SWKey *key = (SWKey *)*(it->second);
		(*key) = token;
		Lookup->Text = (const char *)(*(*it).second);
	}
	else Lookup->Text = "";
			
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SearchPokeData(TObject *Sender)
{
	char buf[255];
	char *token;
	ModMap::iterator it;
	AnsiString retval = "";

	strncpy(buf, Search->Text.c_str(), 254);
	buf[254] = 0;
	token = strtok(buf, " ");
	if ((it = mainmgr->Modules.find(token)) != mainmgr->Modules.end()) {
		token = strtok(NULL, "");
		ListKey &results = (*it).second->Search(token, REG_ICASE);
		while (!results.Error()) {
			retval = retval + (const char *)results + "; ";
			results++;
		}
		Search->Text = retval;
	}
	else Search->Text = "";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::UpDown3Click(TObject *Sender, TUDBtnType Button)
{
	ModMap::iterator it;
	
	it = mainmgr->Modules.find(LexDictPageControl->ActivePage->Caption.c_str());
	if (it != mainmgr->Modules.end()) {
		if (Button == btNext)
			(*((*it).second))++;
		else	(*((*it).second))--;
		DictKeyEdit->Text = UTF8ToWideString(((*it).second)->KeyText());
	}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::UpDown1Click(TObject *Sender, TUDBtnType Button)
{
	if (Sender == UpDown1)
		UpDown2->Position = 1;
	btnLookupClick(Sender);
}
//---------------------------------------------------------------------------

void TForm1::RestoreState(ModState *state)
{
    ModMap::iterator it;

	if (state) {
		state->pc->ActivePage = (TTabSheet *)state->ap;
		if ((state->pc == TextPageControl) || (state->pc == CommentaryPageControl)) {
			if (mainmgr) {
				it = mainmgr->Modules.find(state->pc->ActivePage->Caption.c_str());
				if (it != mainmgr->Modules.end()) {
					SWModule *module = it->second;
					SWKey *key = (SWKey *)*module;
					(*key) = state->key;
					*DefaultVSKey = state->key;
					TextKeyChanged();
				}
			}
		}
		if (state->pc == LexDictPageControl) {
			DictKeyEdit->Text = UTF8ToWideString((const char *)state->key);
		}
		if (state->pc->ActivePage->ControlCount){
			Form1->SetFocusedControl( (TWinControl *)state->pc->ActivePage->Controls[0] );
		}
	}
}


void __fastcall TForm1::BackbtnClick(TObject *Sender)
{
	list <ModState *>::iterator it;
	logmodstate = false;
	it = modstates.begin();
	if (it != modstates.end()) {
		it++;
	
		if (it != modstates.end()) {
			RestoreState(*it);
			delete *modstates.begin();
			modstates.erase(modstates.begin(), it);
		}
	}
	logmodstate = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CopyasBGreekTransliteration1Click(TObject *Sender)
{
	char *retbuf;
	int len;
	TClipboard *clip = new TClipboard();
	
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	len = rtf->SelText.Length() * 2;
	retbuf = new char [ len ];
	if (!Greek2bGreek(retbuf, rtf->SelText.c_str(), len)) {
		clip->SetTextBuf(retbuf);
	}
	delete clip;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Copy1Click(TObject *Sender)
{
	int wordstart;
	
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	if (!rtf->SelLength) {
		for (wordstart = rtf->SelStart; (wordstart > -1)&&(isdigit(rtf->Text[wordstart])||isalpha(rtf->Text[wordstart])); wordstart--);
		rtf->SelStart = (wordstart > -1) ? wordstart: 0;
		for (wordstart = rtf->SelStart + 1; (wordstart < rtf->Text.Length())&&(isdigit(rtf->Text[wordstart])||isalpha(rtf->Text[wordstart])); wordstart++);
		rtf->SelLength = ((wordstart < rtf->Text.Length()) ? wordstart : rtf->Text.Length()) - rtf->SelStart - 1;
	}
	rtf->CopyToClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BookmarkItemClick(TObject *Sender)
{
	TMenuItem *menuchoice = (TMenuItem *)Sender;
	const char *source = menuchoice->Caption.c_str();
	char *value = new char [strlen(source) + 1];
	int k = 0;
	for (unsigned int j = 0; j < strlen(source); j++) {
		if (source[j] != '&')
			value[k++] = source[j];
	}
	value[k] = 0;
	*DefaultVSKey = value;	
	delete [] value;
	TextKeyChanged();
}

void __fastcall TForm1::AddBookmark1Click(TObject *Sender)
{
//	TMenuItem *newitem;

	bookmarkForm->bmtree->Items->AddChild(bookmarkForm->bmtree->Items->Item[0], (const char *)*DefaultVSKey);
}

void TForm1::AddSectionToMenu(TMenu *menu, TMenuItem *item, TTreeNode *tree)
{
	TMenuItem *newitem;
	
	for (tree = tree->getFirstChild(); tree; tree = tree->getNextSibling()) {
		newitem = new TMenuItem(menu);
		newitem->Caption = tree->Text;
		if (!tree->getFirstChild()) 
			newitem->OnClick = BookmarkItemClick;
		item->Add(newitem);
		AddSectionToMenu(menu, newitem, tree);
	}
}

void TForm1::RefreshBookmarksMenu(TMenu *menu, TTreeView *treeview)
{
	TMenuItem *newitem;
	TTreeNode *tree = 0;

	if (treeview->Items->Count)
		tree = treeview->Items->Item[0];
	
	while (menu->Items->Count > 3)
		menu->Items->Delete(3);

	for (;tree;tree = tree->getNextSibling()) {
		newitem = new TMenuItem(menu);
		newitem->Caption = tree->Text;
		menu->Items->Add(newitem);
		AddSectionToMenu(menu, newitem, tree);
	}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BookmarkbtnClick(TObject *Sender)
{
	TPoint menup, point;
	point.x = 0;
	point.y = Bookmarkbtn->Height;
	menup = Bookmarkbtn->ClientToScreen(point);
	RefreshBookmarksMenu(BookmarkPopup, bookmarkForm->bmtree);
	BookmarkPopup->Popup(menup.x, menup.y);	
}
//---------------------------------------------------------------------------


void __fastcall TForm1::EditBookmarks1Click(TObject *Sender)
{
	bookmarkForm->Show();	
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key,
	TShiftState Shift)
{
	char buf[5];
	int val;
	ModMap::iterator it;
	TPageControl *pc = TextPageControl;

	if ((Shift.Contains(ssCtrl)) && (!Shift.Contains(ssAlt))) {
		if ((Key >= '0') && (Key <= '9')) {
			sprintf(buf, "%c", Key);
			val = atoi(buf);

			if (!Shift.Contains(ssShift)) {
				if ((Screen->ActiveControl == CommentaryPageControl) || (IsChild(CommentaryPageControl->Handle, Screen->ActiveControl->Handle)))
					pc = CommentaryPageControl;
				if ((Screen->ActiveControl == LexDictPageControl) || (IsChild(LexDictPageControl->Handle, Screen->ActiveControl->Handle)))
					pc = LexDictPageControl;

				it = mainmgr->Modules.find(pc->ActivePage->Caption.c_str());
				if (it != mainmgr->Modules.end()) {
					if (ctrlstates[val])
						delete ctrlstates[val];
					
					ctrlstates[val] = new ModState(pc, pc->ActivePage, (*it).second->KeyText());
				}
			}
			else	RestoreState(ctrlstates[val]);
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Options1Click(TObject *Sender)
{
	ModMap::iterator it;
	SectionMap::iterator sit;
	ConfigEntMap::iterator eit;
	ConfigEntMap emap;
	int color;
	string tmpval;

	   //*********************************
	   //Initialize Preferences Dialog Box

	Optionsfrm->LoadDispSettings(optionsconf);
	Optionsfrm->LoadMiscSettings(optionsconf);
	
	//*********************************
	// Show Dialog Box
	if (Optionsfrm->ShowModal() == mrOk) {
		// Save Preferences settings :)
		Optionsfrm->extractSettings(optionsconf);
		optionsconf->Save();
		refreshAppearance();
	}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::cbBookChange(TObject *Sender)
{
	CHBox->Text = "1";
	VSBox->Text = "1";
	if (Screen->ActiveControl == cbBook)	
		btnLookupClick(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
//	Application->OnHint = DisplayHint;
//	Application->ShowHint = true;
//	this->ShowHint = true;
//	nsresult rv;
//	rv = NS_InitEmbedding(nsnull, nsnull);

	   Application->OnMessage = AppMessage;
	   Application->Title = "The SWORD Project";
}


void TForm1::AddVerseChoices(TPopupMenu *menu, const char *buf, TRxRichEdit *rtf) {
	TMenuItem *newitem;

	tmpVerseList = DefaultVSKey->ParseVerseList((char *)buf, *DefaultVSKey);

	ModMap::iterator target;
	target = mainmgr->Modules.find(((TPageControl*)rtf->Parent->Parent)->ActivePage->Caption.c_str());
	if (target != Form1->mainmgr->Modules.end()) {
		char *keytext = 0;		// check for and remove return at end of keytext
		stdstr(&keytext, (*(*target).second).KeyText());
		if (keytext[strlen(keytext)-1] == '\r')
			keytext[strlen(keytext)-1] = 0;
					
		tmpVerseListCaption = String("VerseList from- ") + (*target).first.c_str() + ": " + keytext;
		delete [] keytext;		// ---------------------------------
	}
	newitem = new TMenuItem(menu);
	newitem->Caption = "-";
	menu->Items->Add(newitem);
	newitem = new TMenuItem(menu);
	newitem->Caption = _tr("Create Verse List");
	newitem->Hint = _tr("Create a New Verse List Window");
	newitem->Default = true;
	newitem->OnClick = createVerseList;
	menu->Items->Add(newitem);
	int breakcnt = 3;
	while (!tmpVerseList.Error()) {
		breakcnt++;
		newitem = new TMenuItem(menu);
		newitem->Caption = (const char *)tmpVerseList;
		newitem->OnClick = BookmarkItemClick;
		if (!(breakcnt%15))
			newitem->Break = mbBreak;
		menu->Items->Add(newitem);
		tmpVerseList++;
	}



}


void __fastcall TForm1::PopupMenuPopup(TObject *Sender) {

	int versestart, verseend;
	TPopupMenu *menu = (TPopupMenu *)Sender;
	int staticMenuItemsCount = 0;
	TMenuItem *newitem;

	if (menu == PopupMenu1)
		staticMenuItemsCount = 4;
	else if (menu == PopupMenu2)
		staticMenuItemsCount = 3;
	else if (menu == PopupMenu3)
		staticMenuItemsCount = 7;
		
	while (menu->Items->Count > staticMenuItemsCount)
		menu->Items->Delete(staticMenuItemsCount);

	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	if (clickText.Length()) {
		string highlight = Trim(clickText).c_str();
		tmpVerseList = DefaultVSKey->ParseVerseList((char *)highlight.c_str(), *DefaultVSKey);
		if (tmpVerseList.Count())
			AddVerseChoices(menu, highlight.c_str(), rtf);
	}
	else	if (!rtf->SelLength) {
		int entrylen = strlen(rtf->Text.c_str());
		char *entrytext = new char [ entrylen + 1 ];
		int selstart = rtf->SelStart;
		strcpy(entrytext, rtf->Text.c_str());
//		for (versestart = rtf->SelStart; ((versestart)&&(rtf->Text[versestart] != '#')); versestart--);

		String verseList = "";
		rtf->SelLength = 1;
		if (rtf->SelAttributes->Link) {
			int saveStart = rtf->SelStart;
			int last = -1;
			while ((rtf->SelStart != last) && (rtf->SelAttributes->Link)) {
				last = rtf->SelStart;
				rtf->SelStart -= 1;
				rtf->SelLength = 1;
			}
			int start = rtf->SelStart + 1;
			rtf->SelStart++;
			rtf->SelLength = 1;
			last = -1;
			while ((rtf->SelStart != last) && (rtf->SelAttributes->Link)) {
				last = rtf->SelStart;
				rtf->SelStart += 1;
				rtf->SelLength = 1;
			}
			int len = (rtf->SelStart - start);
			rtf->SelStart = saveStart;
			verseList = rtf->GetTextRange(start, start+len);
			AddVerseChoices(menu, verseList.c_str(), rtf);
		}
		rtf->SelLength = 0;

		if (!verseList.Length()) {
			versestart = selstart;
			for (int i = 0; ((i < versestart) && (i < entrylen)); i++) {
				if (entrytext[i] == '\r')
					versestart++;
			}
			for (; ((versestart)&&(entrytext[versestart] != '#')); versestart--);
			if (versestart) {
				for (verseend = versestart; ((verseend < entrylen) && (entrytext[verseend] != '|')); verseend++);
				if ((verseend < entrylen) && (verseend > selstart)) {
					int len = (verseend - versestart) + 1;
					char *buf = new char [ len + 1 ];
					memset(buf, 0 , len + 1);
					strncpy(buf, &entrytext[versestart+1], len - 2);	// strip the # and | from the string
					int buflen = strlen(buf);
					for (int i = 0; i < buflen; i++) {
						if ((buf[i] == 10) || (buf[i] == 13))
							buf[i] = ' ';
					}
					AddVerseChoices(menu, buf, rtf);
					delete [] buf;
				}
			}
		}
		delete [] entrytext;
	}
	else {
		string highlight = Trim(rtf->SelText).c_str();
		tmpVerseList = DefaultVSKey->ParseVerseList((char *)highlight.c_str(), *DefaultVSKey);
		if (tmpVerseList.Count())
			AddVerseChoices(menu, highlight.c_str(), rtf);
			
//		newitem = new TMenuItem(menu);
//		newitem->Caption = "Verse Lookup";
//		newitem->Hint = "Attempt to lookup highlighted text as a verse";
//		newitem->OnClick = verseLookupClick;
//		menu->Items->Add(newitem);
	}
	clickText = "";
	
}
//---------------------------------------------------------------------------


void __fastcall TForm1::createVerseList(TObject *Sender)
{
	TVerseListForm *tmpForm = new TVerseListForm(this, tmpVerseList);
	tmpForm->Caption = tmpVerseListCaption;
	tmpForm->Show();	
}
//---------------------------------------------------------------------------

void __fastcall TForm1::freeHandLookupoldKeyPress(TObject *Sender, char &Key)
{
	if (Key == '\r') {
		ListKey tmpVerseList = DefaultVSKey->ParseVerseList(freeHandLookup->Text.c_str(), *DefaultVSKey);

		if (tmpVerseList.Count()) {
			int index = freeHandLookup->Items->IndexOf(freeHandLookup->Text);
			freeHandLookup->Items->Insert(0, freeHandLookup->Text);

			if (index >= 0)
				freeHandLookup->Items->Delete(index+1);

			freeHandLookup->ItemIndex = 0;

			if (tmpVerseList.Count() > 1) {
				TVerseListForm *tmpForm = new TVerseListForm(this, tmpVerseList);
				tmpForm->Caption = _tr("User Verse List");
				tmpForm->Show();
			}

			tmpVerseList = TOP;
			*DefaultVSKey = tmpVerseList;
			TextKeyChanged();
		}
	}
}
//---------------------------------------------------------------------------


void __fastcall TForm1::RTFMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) {
	((TWinControl *)Sender)->SetFocus();
	TRichEdit *rtf = (TRichEdit *)Sender;
	if (Button == mbRight) {
		if (!rtf->SelLength)
			SendMessage(rtf->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELONG(X, Y));
		TPoint menup, point;
		point.x = X;
		point.y = Y;
		menup = rtf->ClientToScreen(point);
		rtf->PopupMenu->Popup(menup.x, menup.y);	
	}
}

void __fastcall TForm1::RTFURLClick(TObject *Sender, const AnsiString URLText, TMouseButton Button) {
	if (!renderingHint) {
		TRichEdit *rtf = (TRichEdit *)Sender;
		clickText = URLText;
		rtf->PopupMenu->Popup(Mouse->CursorPos.x, Mouse->CursorPos.y);
	}
	else renderingHint = false;
}


//---------------------------------------------------------------------------

void __fastcall TForm1::EditEntry1Click(TObject *Sender)
{
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	SWModule *module;
//	EditEntry->RichEdit1->Text = rtf->Text;
	ModMap::iterator target;
	target = mainmgr->Modules.find(((TPageControl*)rtf->Parent->Parent)->ActivePage->Caption.c_str());
	if (target != Form1->mainmgr->Modules.end()) {
		EditEntryForm->Module = module = (*target).second;
		EditEntryForm->RTFDisplay = rtf;
	}
	else	EditEntryForm->Module = module = 0;
	EditEntryForm->ShowModal();
	if (EditEntryForm->ResultBuf) {
		if (module)
//			DictKeyEdit->Text = EditEntry->ResultBuf;  // for testing purposes
			*module << EditEntryForm->ResultBuf;
	}
	RefreshActiveSheet(CommentaryPageControl);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::DeleteEntry1Click(TObject *Sender)
{
	string message = _tr("Are you sure you wish to delete this entry?");
	string header = _tr("Delete Entry");
	if (MessageBox(Handle, message.c_str(), header.c_str(), MB_YESNO) == IDYES) {
		SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
		SWModule *module;
		ModMap::iterator target;

		target = mainmgr->Modules.find(((TPageControl*)rtf->Parent->Parent)->ActivePage->Caption.c_str());
		if (target != Form1->mainmgr->Modules.end()) {
			module = (*target).second;
			module->deleteEntry();
		}
		RefreshActiveSheet(CommentaryPageControl);
	}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::LinktoVerse1Click(TObject *Sender)
{
	if (VerseSelFrm->ShowModal() == mrOk) {
		SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
		SWModule *module;
		ModMap::iterator target;
		SWKey *linkkey = new VerseKey(VerseSelFrm->Panel2->Caption.c_str());

		target = mainmgr->Modules.find(((TPageControl*)rtf->Parent->Parent)->ActivePage->Caption.c_str());
		if (target != Form1->mainmgr->Modules.end()) {
			module = (*target).second;
			*module << linkkey;
		}
		RefreshActiveSheet(CommentaryPageControl);
	}
}
//---------------------------------------------------------------------------


void __fastcall TForm1::GlobalOptionChange(TObject *Sender)
{
//	ModMap::iterator it;
//	SectionMap::iterator sit;
//	ConfigEntMap::iterator eit, eitend;
	ConfigEntMap::iterator eit;
	TMenuItem *menuchoice = (TMenuItem *)Sender;
	const char *source = menuchoice->Caption.c_str();
	char *value = new char [strlen(source) + 1];
	int k = 0;
	for (unsigned int j = 0; j < strlen(source); j++) {
		if (source[j] != '&')
			value[k++] = source[j];
	}
	value[k] = 0;
	source = menuchoice->Parent->Caption.c_str();
	char *option = new char [strlen(source) + 1];
	k = 0;
	for (unsigned int j = 0; j < strlen(source); j++) {
		if (source[j] != '&')
			option[k++] = source[j];
	}
	option[k] = 0;
	mainmgr->setGlobalOption(option, value);
	
	if ((!stricmp(option, "Strong's Numbers")) && (!stricmp(value, "On"))) {
		string curText = TextPageControl->ActivePage->Caption.c_str();
		if (!hasFeature(mainmgr, curText.c_str(), "StrongsNumbers")) {
			string tmpval = optionsconf->Sections["ModDefaults"]["StrongsNumbers"];
			for (int i = 0; i < TextPageControl->PageCount; i++) {
				if (!stricmp(TextPageControl->Pages[i]->Caption.c_str(), tmpval.c_str())) {
					TextPageControl->ActivePageIndex = i;
					break;
				}
			}
		}
	}

	
	delete [] option;
	delete [] value;
	TextKeyChanged();
}
//---------------------------------------------------------------------------



void __fastcall TForm1::OptionShowVals(TObject *Sender)
{
	TMenuItem *menuChoice = (TMenuItem *)Sender;

	string option = menuChoice->Caption.c_str();
	int k = 0;
	const char *source = option.c_str();
	char *caption = new char [strlen(source) + 1];
	for (unsigned int j = 0; j < strlen(source); j++) {
		if (source[j] != '&')
			caption[k++] = source[j];
	}
	caption[k] = 0;
		
	string value = mainmgr->getGlobalOption(caption);
	delete [] caption;
	for (int i = 0; i < menuChoice->Count; i++) {
		int k = 0;
		char *source = menuChoice->Items[i]->Caption.c_str();
		char *caption = new char [strlen(source) + 1];
		for (unsigned int j = 0; j < strlen(source); j++) {
			if (source[j] != '&')
				caption[k++] = source[j];
		}
		caption[k] = 0;
		if (!stricmp(caption, value.c_str()))
			menuChoice->Items[i]->Checked = true;
		else	menuChoice->Items[i]->Checked = false;                            
		delete [] caption;
	}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Contents1Click(TObject *Sender)
{
	string helpDir = optionsconf->Sections["Help"].getWithDefault("Directory", ".\\help");
	string helpExe = helpDir + "\\sword.chm";
	
	if ((int)ShellExecute(this->Handle, "open", helpExe.c_str(), NULL, NULL, SW_SHOWNORMAL) < 33) {
		helpExe = helpDir + "\\index.html";
		ShellExecute(this->Handle, "open", helpExe.c_str(), NULL, NULL, SW_SHOWNORMAL);
	}
}
//---------------------------------------------------------------------------


void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
	int saveCount = 5;
	closing = true;	

	ConfigEntMap section;
	ConfigEntMap::iterator entryIt;


	section = layoutconf->Sections["History"];
	entryIt = section.find("SearchSaveCount");
	if (entryIt != section.end())
		saveCount = atoi(entryIt->second.c_str());
	else	section.insert(ConfigEntMap::value_type("SearchSaveCount", "5"));

	section.erase("SearchText");
	for (int loop = 0; ((loop < saveCount) && (loop <	searchForm->SearchText->Items->Count)); loop++) {
		WideString entry = searchForm->SearchText->Items->Strings[loop];
		section.insert(ConfigEntMap::value_type("SearchText", WideStringToUTF8(entry).c_str()));
	}

	entryIt = section.find("LookupSaveCount");
	if (entryIt != section.end())
		saveCount = atoi(entryIt->second.c_str());
	else	section.insert(ConfigEntMap::value_type("LookupSaveCount", "5"));

	section.erase("LookupText");
	for (int loop = 0; ((loop < saveCount) && (loop <	freeHandLookup->Items->Count)); loop++)
		 section.insert(ConfigEntMap::value_type("LookupText", freeHandLookup->Items->Strings[loop].c_str()));

	section["LastVerse"] = (const char *)*DefaultVSKey;
	section["LastLDKey"] = WideStringToUTF8(DictKeyEdit->Text).c_str();
	section["LastTextModule"] = TextPageControl->ActivePage->Caption.c_str();
	section["LastComModule"] = CommentaryPageControl->ActivePage->Caption.c_str();
	section["LastLDModule"] = LexDictPageControl->ActivePage->Caption.c_str();

	layoutconf->Sections["History"] = section;
	layoutconf->Save();

//	NS_TermEmbedding();	

	if ((*optionsconf)["Layout"]["AutoSaveLayout"] == "1")
		SaveLayout1Click(this);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::lbDictKeysOldClick(TObject *Sender)
{
	DictKeyEdit->Text = lbDictKeys->Items->Strings[lbDictKeys->ItemIndex];
}
//---------------------------------------------------------------------------


void __fastcall TForm1::HideShowModules1Click(TObject *Sender)
{
	ConfigEntMap *section;
     TMenuItem *menuItem = (TMenuItem *)Sender;
     TPopupMenu *menu = (TPopupMenu *)menuItem->GetParentMenu();
     TComponent *comp = menu->PopupComponent;
     TPageControl *pc = 0;
	
     if ((comp == TextPageControl) || (comp == pnlText)) {
		pc = TextPageControl;
	     section = &(*layoutconf)["TextView"];
     }
     if ((comp == CommentaryPageControl) || (comp == pnlComment)) {
		pc = CommentaryPageControl;
		section = &(*layoutconf)["CommentView"];
     }
     if ((comp == LexDictPageControl) || (comp == pnlDict)) {
		pc = LexDictPageControl;
     	section = &(*layoutconf)["LDView"];
     }

     if (!pc) return;	// assert pc
     	
	for (int i = 0; i < pc->PageCount; i++) {
     	string heading = pc->Pages[i]->Caption.c_str();
     	(*section)[heading.c_str()] = ((pc->Pages[i]->TabVisible) ? "true" : "false");
     }
     ModVisForm->mgr = mainmgr;
	ModVisForm->section = section;
	if (ModVisForm->ShowModal() == mrOk) {
          for (int i = 0; i < pc->PageCount; i++) {
               string heading = pc->Pages[i]->Caption.c_str();
			pc->Pages[i]->TabVisible = ((*section)[heading.c_str()] == "true");
          }
	}	
}
//---------------------------------------------------------------------------

void __fastcall TForm1::DevotionaloftheDay1Click(TObject *Sender) {
	   DevOfTheDay2->Show();
}
//---------------------------------------------------------------------------

void dehtmlize(char *buf) {
	bool deref = false;
	int nums = 0;
	while (*buf) {
		if (deref) {
			if (!isdigit(*buf))
				deref = false;
			else {
				*buf = ' ';
				nums++;
			}
			if (nums > 1)
				deref = false;
		}
		if (*buf == '%') {
			deref = true;
			nums = 0;
			*buf = ' ';
		}
		buf++;
	}
}

void __fastcall TForm1::CppWebBrowser1BeforeNavigate2(TObject *Sender,
	 LPDISPATCH pDisp, TVariant *URL, TVariant *Flags,
	 TVariant *TargetFrameName, TVariant *PostData, TVariant *Headers,
	 TOLEBOOL *Cancel)
{
	AnsiString url = *URL;
	string stuff = url.c_str();
	char *offset = strstr(url.c_str(), "passage");
	if (offset > 0) {
		string verse = (offset+8);
		char * buf = new char [ verse.length() + 1 ];
		strcpy(buf, verse.c_str());
		dehtmlize(buf);
		(*Cancel) = true;
		*DefaultVSKey = (buf);
		TextKeyChanged();
		delete [] buf;
	}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::InstallManager1Click(TObject *Sender)
{
	WinExec("InstallMgr.exe", SW_SHOWNORMAL);
}
//---------------------------------------------------------------------------


void TForm1::refreshAppearance() {
	ModMap::iterator it;
	string locale;
	string tmpval;

	locale = optionsconf->Sections["Appearance"].getWithDefault("locale", "en_us");
	i12ize(locale.c_str());

	// Change the panels attributes here
	for (it = mainmgr->Modules.begin(); it != mainmgr->Modules.end(); it++) {
		SWModule *module = it->second;
		RTFDisp *disp = SWDYNAMIC_CAST(RTFDisp, module->Disp());
		if (disp) {
			SWDispRTF* rtfDisp = (SWDispRTF*) disp->editControl();
			rtfDisp->recalcAppearance();
		}
	}

	// Change the text entry field color
	tmpval = optionsconf->Sections["Appearance"]["FieldColor"];
	TColor fieldColor = tmpval.length() ? TColor(atoi(tmpval.c_str())) : clAqua;

	cbBook->Color         = fieldColor;
	CHBox->Color          = fieldColor;
	VSBox->Color          = fieldColor;
	freeHandLookup->Color = fieldColor;
	DictKeyEdit->Color    = fieldColor;

	Form1->ShowHint = (optionsconf->Sections["Hints"].getWithDefault("Hints", "true") != "false");
	DefaultVSKey->setLocale(locale.c_str());
	fillVKeySelector(DefaultVSKey);
	TextKeyChanged();
	RefreshActiveSheet(LexDictPageControl);
	RefreshActiveSheet(CommentaryPageControl);
	RefreshActiveSheet(TextPageControl);
}


void __fastcall TForm1::ApplicationEvents1Hint(TObject *Sender)
{
	StatusBar1->SimpleText = GetLongHint(Application->Hint);
}


void __fastcall TForm1::ApplicationEvents1ShowHint(AnsiString &HintStr,
	 bool &CanShow, THintInfo &HintInfo)
{
	ConfigEntMap::const_iterator const_eit;
	string fontname;
	char buf[1024];
	static TRect lastRect(0,0,0,0);
	bool selected = false;
	bool link = false;
	static WideString lastWord = "";
	static String lastHint = "yoyo";
	String verseList = "";
	WideString targetWord;
	THintInfo saveHintInfo = HintInfo;
	// assert we are in a sword module rtf window and we're not grinding
	if (HintInfo.HintControl == searchForm->resultsLV) {
		HintStr = "";
	}
	if ((HintInfo.HintControl == TextPageControl) ||
			(HintInfo.HintControl == CommentaryPageControl) ||
			(HintInfo.HintControl == LexDictPageControl)) {
		TPageControl *pc = (TPageControl *)HintInfo.HintControl;
		TPoint mousePoint = pc->ScreenToClient(Mouse->CursorPos);
		int tab = pc->IndexOfTabAt(mousePoint.x, mousePoint.y);
		if (tab >=0) {
			int visTabs = -1;
			int i;
			for (i = 0; i < pc->PageCount; i++) {
				if (pc->Pages[i]->TabVisible) {
					if (++visTabs >= tab)
						break;
				}
			}
			if (pc->PageCount) {
				TTabSheet *ts = pc->Pages[i];
				
				SWModule *module = mainmgr->Modules[ts->Caption.c_str()];
				if (module) {
					HintStr = module->Description();
					HintInfo.CursorRect = pc->TabRect(tab);
//				HintInfo.CursorRect = >TRect(TPoint(mousePoint.x-7, mousePoint.y-7), TPoint(mousePoint.x+7, mousePoint.y+7));
				}
			}
		}
		return;
	}

	if ((strncmp(HintInfo.HintControl->Name.c_str(), "TextRTF", 7)) &&
			(strncmp(HintInfo.HintControl->Name.c_str(), "CommentRTF", 10)) &&
			(strncmp(HintInfo.HintControl->Name.c_str(), "BookRTF", 7)) &&
			(strncmp(HintInfo.HintControl->Name.c_str(), "LexDictRTF", 10))) {
		return;
	}
	char *modName = 0;
	stdstr(&modName, HintInfo.HintControl->Name.c_str());
	SWModule *module = mainmgr->Modules[(strstr(modName, "RTF")+3)];
	delete [] modName;
		
//	Application->HintHidePause = HintDisplayTime;
	HintInfo.HintWindowClass = __classid(THintWindow);

	if (!Form1->Active)
		return;
		
	bool hintStrongs = (optionsconf->Sections["Hints"].getWithDefault("Strongs", "true") != "false");
	bool hintVLists  = (optionsconf->Sections["Hints"].getWithDefault("VLists",  "true") != "false");
	bool hintWords   = (optionsconf->Sections["Hints"].getWithDefault("Words",   "false") == "true");
			
	SWDispRTF *rtf = 0;
	do {
		ConfigEntMap::iterator eit;

		HintInfo.HideTimeout = 32000;
		HintInfo.HintWindowClass = __classid(TRTFHintWindow);
		HintInfo.CursorRect = lastRect;
		HintStr = "";

		rtf = (SWDispRTF *)HintInfo.HintControl;

		renderingHint = true;

		if (!rtf->SelLength) {
			SendMessage(rtf->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELONG(HintInfo.CursorPos.x, HintInfo.CursorPos.y));
			selected = false;
			targetWord = rtf->WordAtCursor();

			int entrylen = strlen(rtf->Text.c_str());
			char *entrytext = new char [ entrylen + 1 ];
			int selstart = rtf->SelStart;
			int versestart, verseend;
			strcpy(entrytext, rtf->Text.c_str());
			versestart = selstart;
			for (int i = 0; ((i < versestart) && (i < entrylen)); i++) {
				if (entrytext[i] == '\r')
					versestart++;
			}
			for (; ((versestart)&&(entrytext[versestart] != '#')); versestart--);
			if (versestart) {
				for (verseend = versestart; ((verseend < entrylen) && (entrytext[verseend] != '|')); verseend++);
				if ((verseend < entrylen) && (verseend > selstart)) {
					int len = (verseend - versestart) + 1;
					char *buf = new char [ len + 1 ];
					memset(buf, 0 , len + 1);
					strncpy(buf, &entrytext[versestart+1], len - 2);	// strip the # and | from the string
					int buflen = strlen(buf);
					for (int i = 0; i < buflen; i++) {
						if ((buf[i] == 10) || (buf[i] == 13))
							buf[i] = ' ';
					}
					verseList = buf;
					delete [] buf;
				}
			}
			delete [] entrytext;
		}
		else {
			selected = true;
			targetWord = rtf->SelText;
		}
			
//			TPoint currentChar = rtf->GetCharPos(rtf->SelStart);
		TPoint currentChar = rtf->ScreenToClient(Mouse->CursorPos);
		HintInfo.CursorRect = TRect(TPoint(currentChar.x-15, currentChar.y-15), TPoint(currentChar.x+15, currentChar.y+15));
		lastRect = HintInfo.CursorRect;

		if (!selected) {
			rtf->SelLength = 1;
			if (rtf->SelAttributes->Link) {
				link = true;
				int saveStart = rtf->SelStart;
				int last = -1;
				while ((rtf->SelStart != last) && (rtf->SelAttributes->Link)) {
					last = rtf->SelStart;
					rtf->SelStart -= 1;
					rtf->SelLength = 1;
				}
				int start = rtf->SelStart + 1;
				rtf->SelStart++;
				rtf->SelLength = 1;
				last = -1;
				while ((rtf->SelStart != last) && (rtf->SelAttributes->Link)) {
					last = rtf->SelStart;
					rtf->SelStart += 1;
					rtf->SelLength = 1;
				}
				int len = (rtf->SelStart - start);
				rtf->SelStart = saveStart;
				verseList = rtf->GetTextRange(start, start+len);
			}
			rtf->SelLength = 0;
		}
		else {
			if (rtf->SelAttributes->Link) {
				link = true;
			}
		}

		// use cache if same word
		if (targetWord.Length() && (targetWord == lastWord) && (currentRTF == rtf)) {
			HintStr = "reshow same text";
			break;
		}
		currentRTF = rtf;
		lastWord = targetWord;
			
		// currently assume all links are verselists
		if (verseList.Length() && hintVLists) {
			ModMap::iterator it;
			it = mainmgr->Modules.find(TextPageControl->ActivePage->Caption.c_str());
			if (it != mainmgr->Modules.end()) {
				SWModule *module = it->second;
				ListKey verses = DefaultVSKey->ParseVerseList(verseList.c_str(), *DefaultVSKey, true);
				if (verses.Count()) {
					RTFHintForm->rtfDrawer->fillWithVerses(module, &verses, true, true, "Popup");
					HintStr = "show rtf";
				}
				else HintStr = "";
				break;
			}
		}

		// see if strongs number
		if (hintStrongs) {
			char preChar = (targetWord.Length()) ? targetWord[1] : 0;
			WideString strongsWord = TrimJunk(targetWord);

			// check if all digits (strongs)
			int i;
			for (i = 1; i <= strongsWord.Length(); i++) {
				if (!isdigit(strongsWord[i]))
					break;
			}

			if (!link && (i == strongsWord.Length()+1) && (i-1)) {
				String feature = (DefaultVSKey->Testament() == 1)?"Hebrew":"Greek";
				feature += (preChar == '(')?"Parse":"Def";
				if (!strncmp(HintInfo.HintControl->Name.c_str(), "TextRTFLXX", 10))
					feature = "GreekDef";
				string tmpval = optionsconf->Sections["ModDefaults"][feature.c_str()];
				if (tmpval.size()) {
					SWModule *defMod = mainmgr->Modules[tmpval];
					if (!defMod) {
						HintStr = "";
						break;
					}
					ListKey key;
					key << WideStringToUTF8(strongsWord).c_str();
					RTFHintForm->rtfDrawer->fillWithVerses(defMod, &key, true, false, "Popup");
					HintStr = "show rtf";
					break;
				}
			}
		}

		// try looking up the word in a general dictionary
		if (!link && hintWords) {
			string tmpval = optionsconf->Sections["ModDefaults"]["GenDict"];
			if (tmpval.size()) {
				SWModule *defMod = mainmgr->Modules[tmpval];
				if (!defMod)
					break;
				ListKey key;
				key << WideStringToUTF8(targetWord).c_str();
				RTFHintForm->rtfDrawer->fillWithVerses(defMod, &key, true, false, "Popup");
				HintStr = (key.Count()) ? "show rtf" : "";
				break;
			}
		}
		HintStr = "";
	} while (false);

	if (!HintStr.Length()) {
//			HintInfo = saveHintInfo;
		HintInfo.HintWindowClass = __classid(THintWindow);
/*				
		if (module)
			HintStr = module->Description();
		if (lastHint == HintStr)
			HintStr = "";
*/
		lastWord = "";
//		renderingHint = false;
	}
	lastHint = HintStr;
}
//---------------------------------------------------------------------------


__fastcall TRTFHintWindow::TRTFHintWindow(Classes::TComponent* AOwner)
									   : THintWindow(AOwner)
{
  Canvas->Font->Name = "Arial";
  Canvas->Font->Color = clWindowText;
}

__fastcall TRTFHintWindow::~TRTFHintWindow(void) {
//	RTFHintForm->Hide();
}


//------------------------------------------------------------------------------------------//

void __fastcall TRTFHintWindow::CreateParams(TCreateParams &Params)
{
  inherited::CreateParams(Params);

  Params.Style = WS_POPUP;
  Params.WindowClass.style = Params.WindowClass.style | CS_SAVEBITS;

  if(NewStyleControls)
  {
	Params.ExStyle = WS_EX_TOOLWINDOW;
	AddBiDiModeExStyle(Params.ExStyle);
  }
}
//------------------------------------------------------------------------------------------//

void __fastcall TRTFHintWindow::Paint(void)
{
	TRect Rect = ClientRect;
	
	TColor penColor;
	string strColor;
	strColor = Form1->optionsconf->Sections["Appearance"]["PopupFontColor"];
	if(strColor == "")
		penColor = clBlack;
	else
		penColor = StrToInt((AnsiString)strColor.c_str());

	TColor backColor;
	strColor = Form1->optionsconf->Sections["Appearance"]["PopupBackColor"];
	if(strColor == "")
		backColor = 14680063;
	else
		backColor = StrToInt((AnsiString)strColor.c_str());

	Canvas->Brush->Color = penColor;
	Canvas->FillRect(Rect);

	Rect.Left += 4;
	Rect.Top  += 4;
	Rect.Right -= 4;
	Rect.Bottom -= 4;

	Frame3D(Canvas, Rect, clBtnShadow, clBtnHighlight, 1);

	Canvas->Brush->Color = backColor;//TColor(0xB4CDBB);
	Canvas->FillRect(Rect);


	Graphics::TMetafile *AMetaFile= new Graphics::TMetafile();
	Graphics::TMetafileCanvas *AMetaFileCanvas = new Graphics::TMetafileCanvas(AMetaFile, 0);
	Rect = ClientRect;
	Rect.Right -= 12;
	Rect.Bottom -=12;
	bool jagged = RTFHintForm->rtfDrawer->paintTo(AMetaFileCanvas->Handle, &Rect);
	delete AMetaFileCanvas;
	Canvas->Draw(7,7,AMetaFile);
	delete AMetaFile;

	if (jagged) {
		int triCount = (Rect.Right/60) + 1;
		Canvas->Pen->Color = penColor; //clBlack; // TColor(0xA4BDAB);
		Canvas->Brush->Color = penColor;  //clBlack;
		int i;
		for (i = 0; i < triCount; i++) {
			TPoint points[3];
			points[0].x = i * 60;
			points[0].y = ClientRect.Bottom;
			points[1].x = (i * 60) + 30;
			points[1].y = ClientRect.Bottom-15;
			points[2].x = (i+1) * 60;
			points[2].y = ClientRect.Bottom;
			Canvas->Polygon(points, 2);
		}
/*
		Canvas->Pen->Color = clBlack;
		TPoint points[4];
		points[0].x = 0; points[0].y = Rect.Bottom-1;
		points[1].x = Rect.Right; points[1].y = Rect.Bottom-1;
		points[2].x = Rect.Right; points[2].y = Rect.Bottom;
		points[3].x = 0; points[3].y = Rect.Bottom;
		Canvas->Polygon(points, 3);
*/
	}

//	RTFHintForm->rtfDrawer->PaintTo(Canvas->Handle, 4, 4);
//	RTFHintForm->Repaint();
//	RTFHintForm->rtfDrawer->Repaint();
//	Graphics::TBitmap *hintBit = RTFHintForm->GetFormImage();
//	Clipboard()->Assign(hintBit);
//	Canvas->CopyRect(Rect, hintBit->Canvas, Rect);
//	delete hintBit;

/*
   Rect.Left += 1;
   Rect.Top  += 5;
   Rect.Right -= 1;
   Rect.Bottom -= 1;

   DrawText( Canvas->Handle,
		   Caption.c_str(),
		   -1,
		   &Rect,
		   DT_RIGHT|DT_NOPREFIX|DT_WORDBREAK|DrawTextBiDiModeFlagsReadingOnly() );
 */
}
//------------------------------------------------------------------------------------------//

void __fastcall TRTFHintWindow::ActivateHint(const /*Windows::*/TRect& Rect,
							  const AnsiString AHint)
{
	inherited::ActivateHint(Rect, AHint);
}
//------------------------------------------------------------------------------------------//

void __fastcall TRTFHintWindow::ActivateHintData(const /*Windows::*/TRect& Rect,
								 const AnsiString AHint,
								  void* AData)
{
	TRect newRect = Rect;
	// for dual head monitors, be sure we're all on one monitor
	TForm1::ClipOrCenterRectToMonitor(&newRect, MONITOR_CLIP);
	inherited::ActivateHintData(newRect, AHint, AData);
}
//------------------------------------------------------------------------------------------//

bool __fastcall TRTFHintWindow::IsHintMsg(tagMSG& Msg)
{
	bool retVal = inherited::IsHintMsg(Msg);
	if (retVal)
		Form1->renderingHint = false;
	return retVal;
}

//------------------------------------------------------------------------------------------//

/*Windows::*/TRect __fastcall TRTFHintWindow::CalcHintRect(int MaxWidth,
											const AnsiString AHint,
											void* AData)
{
	TRect Rect(0, 0, 0, 0);	// EmptyRect asks for size

	Graphics::TMetafile *AMetaFile= new Graphics::TMetafile();
	Graphics::TMetafileCanvas *AMetaFileCanvas = new Graphics::TMetafileCanvas(AMetaFile, 0);
	RTFHintForm->rtfDrawer->paintTo(AMetaFileCanvas->Handle, &Rect);
	delete AMetaFileCanvas;
	delete AMetaFile;

	Rect.Right += 12;
	Rect.Bottom += 12;
	return Rect;
}
//------------------------------------------------------------------------------------------//


void __fastcall TForm1::Print1Click(TObject *Sender)
{
	PrintForm->print();	
}
//---------------------------------------------------------------------------



void __fastcall TForm1::SearchForWord1Click(TObject *Sender)
{
	SWDispRTF *rtf = (SWDispRTF *)Screen->ActiveControl;
	int wordstart;
	int saveSelStart = rtf->SelStart;
	WideString lookupKey;
	ConfigEntMap::iterator eit;
		
	if (!rtf->SelLength) {
		lookupKey = rtf->WordAtCursor();
		lookupKey = TrimJunk(lookupKey);

		int entrylen = strlen(rtf->Text.c_str());
		WideString entrytext = rtf->GetText();
		int selstart = rtf->SelStart;
		int versestart, verseend;
		for (versestart = selstart; versestart; versestart--) {
			if (!isdigit(entrytext[versestart]))
				break;
		}
		if ((entrytext[versestart] == '<') ||
				(entrytext[versestart] == '(')) {
			for (verseend = versestart+1; (verseend < entrylen); verseend++) {
				if (!isdigit(entrytext[verseend]))
					break;
			}
			if ((entrytext[verseend] == '>') ||
					(entrytext[verseend] == ')')) {
				if ((verseend < entrylen) && (verseend > selstart)) {
					int len = (verseend - versestart) + 1;
					lookupKey = entrytext.SubString(versestart, len);
				}
			}
		}
	}
	else	{
		lookupKey = TRxRichEditX::Trim(rtf->GetTextRange(rtf->SelStart, rtf->SelStart + rtf->SelLength));
	}
		
	searchForm->SearchText->Text = lookupKey;
	searchForm->Show();
}
//---------------------------------------------------------------------------

//
//  ClipOrCenterRectToMonitor
//
//  The most common problem apps have when running on a
//  multimonitor system is that they "clip" or "pin" windows
//  based on the SM_CXSCREEN and SM_CYSCREEN system metrics.
//  Because of app compatibility reasons these system metrics
//  return the size of the primary monitor.
//
//  This shows how you use the multi-monitor functions
//  to do the same thing.
//
void TForm1::ClipOrCenterRectToMonitor(LPRECT prc, UINT flags) {
    HMONITOR hMonitor;
    MONITORINFO mi;
    RECT        rc;
    int         w = prc->right  - prc->left;
    int         h = prc->bottom - prc->top;
    rc.left = prc->left;
    rc.right = prc->left+1;
    rc.top = prc->top;
    rc.bottom = prc->top+1;
    //
    // get the nearest monitor to the passed rect.
    //
    hMonitor = MonitorFromRect(&rc, MONITOR_DEFAULTTONEAREST);

    //
    // get the work area or entire monitor rect.
    //
    mi.cbSize = sizeof(mi);
    GetMonitorInfo(hMonitor, &mi);

    if (flags & MONITOR_WORKAREA)
	   rc = mi.rcWork;
    else
	   rc = mi.rcMonitor;

    //
    // center or clip the passed rect to the monitor rect
    //
    if (flags & MONITOR_CENTER)
    {
	   prc->left   = rc.left + (rc.right  - rc.left - w) / 2;
	   prc->top    = rc.top  + (rc.bottom - rc.top  - h) / 2;
	   prc->right  = prc->left + w;
	   prc->bottom = prc->top  + h;
    }
    else
    {
	   prc->left   = max(rc.left, min(rc.right-w,  prc->left));
	   prc->top    = max(rc.top,  min(rc.bottom-h, prc->top));
	   prc->right  = prc->left + w;
	   prc->bottom = prc->top  + h;
    }
}


void TForm1::ClipOrCenterWindowToMonitor(HWND hwnd, UINT flags) {
    RECT rc;
    GetWindowRect(hwnd, &rc);
    ClipOrCenterRectToMonitor(&rc, flags);
    SetWindowPos(hwnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}


void __fastcall TForm1::Action1Execute(TObject *Sender)
{
	bool hintWords   = (optionsconf->Sections["Hints"].getWithDefault("Words",   "false") == "true");
	optionsconf->Sections["Hints"]["Words"] = (!hintWords) ? "true" : "false";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NewVer1Click(TObject *Sender)
{
	ListKey verses;
	TVerseListForm *tmpForm = new TVerseListForm(this, verses);
	tmpForm->Caption = _tr("User Verse List");
	tmpForm->Show();	
}
//---------------------------------------------------------------------------