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

#include <vcl.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <SysUtils.hpp>
#include <Clipbrd.hpp>

#include "FDLGSelDir.h"
#include "FDLGProjectOptions.h"
#include "FDLGInsertHyperLink.h"
#include "FGUIHTMLPreview.h"
#include "FGUISourceViewer.h"
#include "FHTMLGenerator.h"

#include <vector.h>
#include "IniFiles.hpp"
#include "FreeImage.h"

#pragma hdrstop

#include "FGUI.h"

#include <dir.h>
#include <errno.h>
#include <stdio.h>

const AnsiString PAGE_OPTIONS_FILE = "pageoptions.ini";
//---------------------------------------------------------------------------
struct{

	TProjectOptions m_oPO;

	AnsiString	 m_asLastDirectory;

	AnsiString	 m_asFilenameEntry;
	AnsiString	 m_asProjectFile;
	bool		 m_bIncludeEntryDate;
}globals;
//---------------------------------------------------------------------------
#define MAX_ENTRIES 1000

#define MAX_THUMB_WIDTH  160
#define MAX_THUMB_HEIGHT 240
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TGUI *GUI;
//---------------------------------------------------------------------------
AnsiString asGetRelativeFilename(AnsiString _asBase,AnsiString _asFilename)
{
	int iLen = _asFilename.Length() - _asBase.Length();
    return _asFilename.SubString(_asBase.Length()+1,iLen);
}
//---------------------------------------------------------------------------
void MirrorFileInt(AnsiString _asSourceFilename,AnsiString _asDestinationFilename)
{
	AnsiString asDirectory = ExtractFileDir(_asDestinationFilename);
	if (! DirectoryExists(asDirectory))
	{
		if (! ForceDirectories(asDirectory))
			return;
	}

	CopyFile(_asSourceFilename.c_str(), _asDestinationFilename.c_str(), false);
}
//---------------------------------------------------------------------------
void MirrorFile(AnsiString _asFilename)
{
	if (globals.m_oPO.m_asSiteDir == "") return;

	// Get the full mirror file path
	int iLen = _asFilename.Length() - globals.m_oPO.m_asEntriesDir.Length();

	AnsiString asRelative   		= _asFilename.SubString(globals.m_oPO.m_asEntriesDir.Length()+1,iLen);
	AnsiString asCompleteFilename 	= globals.m_oPO.m_asSiteDir + "\\" + asRelative;
	AnsiString asMirrorFile 		= ExpandFileName( globals.m_oPO.m_asSiteDir + asRelative );

	MirrorFileInt(_asFilename,asMirrorFile);
}
//---------------------------------------------------------------------------
void MirrorPage(AnsiString _asFilename)
{
	if (globals.m_oPO.m_asSiteDir == "") return;

	// Get the full mirror file path
	int iLen = _asFilename.Length() - globals.m_oPO.m_asEntriesDir.Length();

	AnsiString asRelative   		= _asFilename.SubString(globals.m_oPO.m_asEntriesDir.Length()+1,iLen);
	AnsiString asCompleteFilename 	= globals.m_oPO.m_asSiteDir + "\\" + asRelative;
	AnsiString asMirrorFile 		= ExpandFileName( globals.m_oPO.m_asSiteDir + asRelative );

	MirrorFileInt(_asFilename,asMirrorFile);

	/*
	int iPos    = asMirrorFile.Length()-1;
	char* szStr = asMirrorFile.c_str();
	while ((iPos>0) && (szStr[iPos] != '\\'))
		iPos--;

	if (iPos >0)
		asMirrorFile = asMirrorFile.SubString(1,iPos)+ "."+globals.m_oPO.m_asFileType;
	*/
}
//---------------------------------------------------------------------------
void CreateFile(AnsiString _asFilename)
{
    FILE* fd = fopen(_asFilename.c_str(),"wb");
	fclose(fd);
}
//---------------------------------------------------------------------------
static AnsiString asDeleteTrailingBlanks(AnsiString _asString)
{
	int iPos = _asString.Length();
	char* szStr = _asString.c_str();

	while ((szStr[iPos] == '\n') || (szStr[iPos] == '\r') || (szStr[iPos] == 0))
		iPos--;

	return( _asString.SubString(0,iPos+1) );
}
//---------------------------------------------------------------------------
static void String2File(FILE *_fd,AnsiString _asString)
{
	AnsiString asStr = asDeleteTrailingBlanks(_asString);

	fwrite(asStr.c_str(),asStr.Length(),1,_fd);
    char szEOS[2] = {'\r','\n'};
    fwrite(&szEOS,2,1,_fd);
}
//---------------------------------------------------------------------------
AnsiString asGetDateFromFields(int _iDay,int _iMonth,int _iYear)
{
	_iMonth --;	// Month comes in the range (1..12)

	char* szMonths[12] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };

	char szStr[32];
	sprintf(szStr,"%02d-%s-%d",_iDay,szMonths[_iMonth],_iYear);

    return ( AnsiString(szStr) );
}
//---------------------------------------------------------------------------
AnsiString asGetNewEntryName(AnsiString _asDir)
{
	struct date d;
	getdate(&d);

    AnsiString asDate = asGetDateFromFields(d.da_day,d.da_mon,d.da_year);

    // contar entradas
	for (int i=0;i<MAX_ENTRIES;i++)
    {
    	char szNum[5];
        sprintf(szNum,"#%03d",i);

    	AnsiString asFilename = asDate + AnsiString(szNum) + ".entry";

        if (! FileExists(asFilename))
            return(asFilename);
    }

    return("");
}
//---------------------------------------------------------------------------
AnsiString __fastcall TGUI::asSelectedDirectory()
{
	return ( dlb_Directory->GetItemPath( dlb_Directory->ItemIndex ) );
}
//---------------------------------------------------------------------------
AnsiString asToForwardSlash(AnsiString _asString)
{
	AnsiString asString = _asString;

    for (int i=1; i <= asString.Length(); i++)
    	if (asString[i] == '\\')
        	asString[i] = '/';

    return(asString);
}
//---------------------------------------------------------------------------
static int filesize(FILE *fd)
{
	int iPos = ftell(fd);
	fseek(fd,-1,SEEK_END);
	int iSize = ftell(fd);
	fseek(fd,iPos,SEEK_SET);
	return(iSize+1);
}
//---------------------------------------------------------------------------
__fastcall TGUI::TGUI(TComponent* Owner) : TForm(Owner)
{
	globals.m_oPO.m_asEGroupPRE  	= "";
	globals.m_oPO.m_asEGroupPOST  	= "";
	globals.m_oPO.m_asEntryPRE  	= "";
	globals.m_oPO.m_asEntryPOST		= "";

	globals.m_oPO.m_asFileType 	= "html";
	globals.m_oPO.m_asDateTAG  	= "date";
	globals.m_oPO.m_asSiteDir  	= "";
	globals.m_bIncludeEntryDate = true;
    globals.m_asLastDirectory	= asSelectedDirectory();

    FreeImage_Initialise();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SelectFile(AnsiString _asFilename)
{
	flb_Entries->Update();

    for (int i=0;i<flb_Entries->Count;i++)
    	if (flb_Entries->Items->Strings[i] == _asFilename)
        	flb_Entries->ItemIndex = i;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::bt_NewEntryClick(TObject *Sender)
{
	// Get new entry file name
    AnsiString asFilename = asGetNewEntryName( asSelectedDirectory() );

    //
	AnsiString asFullFileName = globals.m_asLastDirectory + "\\" + asFilename;

    // Create the file
    CreateFile(asFullFileName);

    // Select the file in the file list box
	// flb_Entries->FileName = asSelectedDirectory() + "\\" + asFilename;
    SelectFile(asFilename);

    // NOTE: Put here at the end of the function
	globals.m_asFilenameEntry = asFullFileName;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::flb_EntriesChange(TObject *Sender)
{
	//
	globals.m_asFilenameEntry = flb_Entries->FileName;

	// Clear
	mem_Entry->Text = "";

	// Open the file in the editor
    FILE *fd = fopen(flb_Entries->FileName.c_str(),"rb");
	if (fd != NULL)
	{
    	int iSize = filesize(fd);

    	char *szStr = (char *)malloc(iSize+1);
        fread(szStr,iSize,1,fd);szStr[iSize] = 0;

    	fclose(fd);

        mem_Entry->Text = szStr;
		free(szStr);
    }
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SaveEntry(AnsiString _asFilename)
{
	// Open the file in the editor
    FILE *fd = fopen(_asFilename.c_str(),"wb");
	if (fd == NULL) return;

    String2File(fd,mem_Entry ->Text);
    fclose(fd);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::bt_PublishClick(TObject *Sender)
{
	SaveEntry(globals.m_asFilenameEntry);

    // Generate HTML
    AnsiString asFilename = ExtractFileName(asSelectedDirectory()) + "." + globals.m_oPO.m_asFileType;
    AnsiString asCompleteFilename;

	asCompleteFilename = asSelectedDirectory() + "\\..\\" + asFilename;
	CHTMLGenerator::GeneratePage( asCompleteFilename,asSelectedDirectory(),globals.m_oPO,globals.m_bIncludeEntryDate);

	// Generate page in site directory
	MirrorPage(asCompleteFilename);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SetupProjectOptions1Click(TObject *Sender)
{
	if (dlg_bSetupProjectOptions(globals.m_oPO))
	{
     	// Save the project data
        if (globals.m_asProjectFile == "")
        {
        	if (dlg_Save->Execute())
            	globals.m_asProjectFile = dlg_Save->FileName;
            else
            	return;
        }

    	//
        SaveProject(globals.m_asProjectFile);
	}
}
//---------------------------------------------------------------------------
void __fastcall TGUI::LoadProject1Click(TObject *Sender)
{
	if (dlg_Open->Execute())
    {
    	globals.m_asProjectFile = dlg_Open->FileName;
        LoadProject(globals.m_asProjectFile);

        dlb_Directory->Directory = globals.m_asLastDirectory;
    }
}
//---------------------------------------------------------------------------
void __fastcall TGUI::LoadProject(AnsiString _asFilename)
{
	TIniFile* poINI = new TIniFile(_asFilename);

	// General
	globals.m_oPO.m_asEGroupPRE        	= poINI->ReadString("CodeGeneration","EGroupPRE","");
	globals.m_oPO.m_asEGroupPOST       	= poINI->ReadString("CodeGeneration","EGroupPOST","");
	globals.m_oPO.m_asEntryPRE 	       	= poINI->ReadString("CodeGeneration","EntryPRE","");
	globals.m_oPO.m_asEntryPOST        	= poINI->ReadString("CodeGeneration","EntryPOST","");
	globals.m_oPO.m_asDateTAG 			= poINI->ReadString("CodeGeneration","dateTAG","date");
	globals.m_oPO.m_asShowImageScript 	= poINI->ReadString("CodeGeneration","ShowImageScript","");

	globals.m_oPO.m_asFileType		    = poINI->ReadString("Directories","fileTYPE","html");
	globals.m_oPO.m_asSiteDir 		    = poINI->ReadString("Directories","siteDIR","");
	globals.m_oPO.m_asEntriesDir	    = poINI->ReadString("Directories","EntriesDIR","");

	globals.m_asLastDirectory   	    = poINI->ReadString("General","LastDirectory",".");

	delete(poINI);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SaveProject(AnsiString _asFilename)
{
	// First delete file
	DeleteFile(_asFilename);

	//
	TIniFile* poINI = new TIniFile(_asFilename);

	// General
	poINI->WriteString("CodeGeneration","EGroupPRE",globals.m_oPO.m_asEGroupPRE);
	poINI->WriteString("CodeGeneration","EGroupPOST",globals.m_oPO.m_asEGroupPOST);
	poINI->WriteString("CodeGeneration","EntryPRE",globals.m_oPO.m_asEntryPRE);
	poINI->WriteString("CodeGeneration","EntryPOST",globals.m_oPO.m_asEntryPOST);
	poINI->WriteString("CodeGeneration","dateTAG",globals.m_oPO.m_asDateTAG);
	poINI->WriteString("CodeGeneration","ShowImageScript",globals.m_oPO.m_asShowImageScript);

	poINI->WriteString("Directories","siteDIR",globals.m_oPO.m_asSiteDir);
	poINI->WriteString("Directories","fileTYPE",globals.m_oPO.m_asFileType);
	poINI->WriteString("Directories","EntriesDIR",globals.m_oPO.m_asEntriesDir);

    poINI->WriteString("General","LastDirectory",globals.m_asLastDirectory);

	delete poINI;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::DeleteFile1Click(TObject *Sender)
{
	// Delete the file we have currently selected
    char szStr[1024];
    sprintf(szStr,"Delete File %s :",flb_Entries->FileName.c_str());


    if (Application->MessageBox(szStr,
    							"Are you sure?",
                                 MB_OKCANCEL) == ID_OK)
	{
    	DeleteFile(flb_Entries->FileName);
        flb_Entries->Update();
    }
}
//---------------------------------------------------------------------------
void __fastcall TGUI::RenameFile1Click(TObject *Sender)
{
	if (dlg_bRenameFile(flb_Entries->FileName))
    	flb_Entries->Update();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::CreateDirectory1Click(TObject *Sender)
{
	if (dlg_bCreateDirectory( dlb_Directory->GetItemPath( dlb_Directory->ItemIndex )) )
    	dlb_Directory->Update();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::RenameDirectory1Click(TObject *Sender)
{
	if (dlg_bRenameDirectory( dlb_Directory->GetItemPath( dlb_Directory->ItemIndex )) )
    	dlb_Directory->Update();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::DeleteDirectory1Click(TObject *Sender)
{
	if (dlg_bRemoveDirectory( dlb_Directory->GetItemPath( dlb_Directory->ItemIndex )) )
    	dlb_Directory->Update();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::Quit1Click(TObject *Sender)
{
	Close();
}
//---------------------------------------------------------------------------
// Entry Editor Options
//---------------------------------------------------------------------------
void __fastcall TGUI::mem_EntryKeyDown(TObject *Sender, WORD &Key,TShiftState Shift)
{
	if (Shift.Contains(ssCtrl))
    {
    	switch (Key)
        {
        	case 'S':
            {
            	bt_PublishClick(Sender);
            }
			break;

        	case 'N':
            {
            	bt_NewEntryClick(Sender);
            }
			break;

        	case 'A':
            {
            	SelectAll1Click(Sender);
            }
			break;

        	case 'C':
            {
            	Copy1Click(Sender);
            }
			break;

        	case 'V':
            {
            	Paste1Click(Sender);
            }
			break;

        	case 'X':

            {
            	Cut1Click(Sender);
            }
			break;

        	case 'Z':
            {
            	Undo1Click(Sender);
            }
			break;
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SelectAll1Click(TObject *Sender)
{
	mem_Entry->SelectAll();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::Copy1Click(TObject *Sender)
{
	mem_Entry->CopyToClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::Paste1Click(TObject *Sender)
{
	mem_Entry->PasteFromClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::Cut1Click(TObject *Sender)
{
	mem_Entry->CutToClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::Undo1Click(TObject *Sender)
{
	mem_Entry->Undo();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::dlb_DirectoryChange(TObject *Sender)
{
	globals.m_asLastDirectory = dlb_Directory->Directory;
	LoadPageOptions();
}
//---------------------------------------------------------------------------
void __fastcall TGUI::FormClose(TObject *Sender, TCloseAction &Action)
{
	if (globals.m_asProjectFile != "")
    	SaveProject(globals.m_asProjectFile);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::InsertStringIntoEntry(AnsiString _asString)
{
	//
	mem_Entry->SelText = _asString;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::InsertLink1Click(TObject *Sender)
{
	THyperLinkProps oHLP;

	oHLP.m_asHyperLink = "";

	// Si hay un texto seleccionado ponerlo como texto dentro del campo texto de insertar enlace
	if (mem_Entry->SelText.Length() > 0)
		oHLP.m_asText = mem_Entry->SelText;
	else
		oHLP.m_asText = "";

	if (dlg_bInsertHyperLink(oHLP))
	{
		if (oHLP.m_asHyperLink!="")
		{
			AnsiString asRelFile = asToForwardSlash( ExtractRelativePath(globals.m_asLastDirectory, oHLP.m_asHyperLink) );
			InsertStringIntoEntry( "<a href=\"" + asRelFile + "\">"+oHLP.m_asText+"</a>" );
		}
		else
			InsertStringIntoEntry( "<a href=\"#\">"+oHLP.m_asText+"</a>" );
	}
}
//---------------------------------------------------------------------------
void __fastcall TGUI::InsertImageToLink1Click(TObject *Sender)
{
	if ( dlg_InsertImage->Execute() )
	{
		AnsiString asRelFile = asToForwardSlash( ExtractRelativePath(globals.m_asLastDirectory, dlg_InsertImage->FileName) );

		InsertStringIntoEntry("\r\n");
		InsertStringIntoEntry("<p align=\"center\"><img style=\"border: 0px solid\" src=\"" + asRelFile + "\"align=\"middle\"></p>\r\n");
	}
}
//---------------------------------------------------------------------------
FIBITMAP* GenericLoader(const char* lpszPathName, int flag)
{
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;

	// check the file signature and deduce its format
	// (the second argument is currently not used by FreeImage)
	fif = FreeImage_GetFileType(lpszPathName, 0);
	if(fif == FIF_UNKNOWN) {
		// no signature ?
		// try to guess the file format from the file extension
		fif = FreeImage_GetFIFFromFilename(lpszPathName);
	}
	// check that the plugin has reading capabilities ...
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		// ok, let's load the file
		FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag);
		// unless a bad file format, we are done !
		return dib;
	}
	return NULL;
}
//---------------------------------------------------------------------------
/** Generic image writer
	@param dib Pointer to the dib to be saved
	@param lpszPathName Pointer to the full file name
	@param flag Optional save flag constant
	@return Returns true if successful, returns false otherwise
*/
bool GenericWriter(FIBITMAP* dib, const char* lpszPathName, int flag) {
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	BOOL bSuccess = FALSE;

	if(dib) {
		// try to guess the file format from the file extension
		fif = FreeImage_GetFIFFromFilename(lpszPathName);
		if(fif != FIF_UNKNOWN ) {
			// check that the plugin has sufficient writing and export capabilities ...
			WORD bpp = FreeImage_GetBPP(dib);
			if(FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)) {
				// ok, we can save the file
				bSuccess = FreeImage_Save(fif, dib, lpszPathName, flag);
				// unless an abnormal bug, we are done !
			}
		}
	}
	return (bSuccess == TRUE) ? true : false;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::InsertImage1Click(TObject *Sender)
{
    if ( dlg_InsertImage->Execute() )
    {
        AnsiString asImage     = dlg_InsertImage->FileName;
    	AnsiString asImageFile = ExtractFileName(asImage);

        FIBITMAP *dib = GenericLoader(asImage.c_str(), 0);

		if (dib != NULL)
        {
            AnsiString asNewDir;

			// Force the creation of images directory
			asNewDir = globals.m_asLastDirectory + "\\..\\images";
			if (mkdir(asNewDir.c_str())==0)
			{

			}

			// Copy the image to image directory
			AnsiString asNewImage = asNewDir + "\\" + asImageFile;
			CopyFile(asImage.c_str(),asNewImage.c_str(),false);
			MirrorFile(asNewImage);

			// Force the creation of thumbs directory
			asNewDir = globals.m_asLastDirectory + "\\..\\thumbs";
			if (mkdir(asNewDir.c_str())==0)
			{

            }
            AnsiString asNewThumb = asNewDir + "\\" + asImageFile;

            // Build the thumb
            int iWidth  = FreeImage_GetWidth (dib);
            int iHeight = FreeImage_GetHeight(dib);

            // Need a rescale?
            if ((iWidth>MAX_THUMB_WIDTH) || (iHeight>MAX_THUMB_HEIGHT))
            {
                float fRatio = ((float)iWidth / (float)iHeight);

                int iNewWidth  = 160;
                int iNewHeight = (int)((float)iNewWidth / fRatio);

                FIBITMAP* pnewdib = FreeImage_Rescale(dib,iNewWidth,iNewHeight,FILTER_BILINEAR);
                if (pnewdib)
                {
                	FreeImage_Unload(dib);
                    dib = pnewdib;
                }

				iWidth  = FreeImage_GetWidth (dib);
            	iHeight = FreeImage_GetHeight(dib);


            	// Save the thumb to thumb directory
                asNewThumb = ChangeFileExt(asNewThumb,".png");
				GenericWriter(dib,asNewThumb.c_str(),PNG_Z_BEST_COMPRESSION);
            }
            else
            {
            	CopyFile(asImage.c_str(),asNewThumb.c_str(),false);
            }

            MirrorFile(asNewThumb);

            // Write HTML code
			AnsiString asRelImage = asGetRelativeFilename(globals.m_oPO.m_asEntriesDir, asImage);
            AnsiString asThumbFile = ExtractFileName(asNewThumb);


            InsertStringIntoEntry("\r\n");
			InsertStringIntoEntry("<div style=\"text-align: center;\">\r\n");

            if (globals.m_oPO.m_asShowImageScript != "")
            {
            	// asGetRelativeFilename ( )
                // AnsiString asScriptRelFilename = asGetRelativeFilename(globals.m_oPO.m_asEntriesDir, globals.m_oPO.m_asShowImageScript);
            	AnsiString asScriptRelFilename = asToForwardSlash( ExtractRelativePath(globals.m_asLastDirectory , globals.m_oPO.m_asShowImageScript) );

            	InsertStringIntoEntry("<a href=\"" + asScriptRelFilename +"?images/" + asImageFile+"\">\r\n");
            }
            else
            	InsertStringIntoEntry("<a href=\"images/" + asImageFile + "\">\r\n");

			InsertStringIntoEntry("<img style=\"border: 0px solid\" src=\"thumbs/" + asThumbFile + "\" align=\"middle\">\r\n");
			InsertStringIntoEntry("</a>\r\n");
			InsertStringIntoEntry("</div>\r\n");

            // free the dib
            FreeImage_Unload(dib);
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TGUI::PreviewPage1Click(TObject *Sender)
{
	AnsiString asFilename = ExtractFileName(asSelectedDirectory()) + "." + globals.m_oPO.m_asFileType;
	AnsiString asCompleteFilename = asSelectedDirectory() + "\\..\\" + asFilename;

	if (! FileExists(asCompleteFilename)) return;

	gui_HTMLPreview(asCompleteFilename);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::RebuildPage1Click(TObject *Sender)
{
	// Generate HTML
	AnsiString asFilename = ExtractFileName(asSelectedDirectory()) + "." + globals.m_oPO.m_asFileType;
	AnsiString asCompleteFilename;

	asCompleteFilename = asSelectedDirectory() + "\\..\\" + asFilename;

	//
	CHTMLGenerator::GeneratePage( asCompleteFilename,asSelectedDirectory(),globals.m_oPO,globals.m_bIncludeEntryDate);

	// Generate page in site directory
	MirrorPage(asCompleteFilename);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::ViewPageSource1Click(TObject *Sender)
{
	AnsiString asFilename = ExtractFileName(asSelectedDirectory()) + "." + globals.m_oPO.m_asFileType;
	AnsiString asCompleteFilename = asSelectedDirectory() + "\\..\\" + asFilename;

	if (! FileExists(asCompleteFilename)) return;

	gui_ViewSource(asCompleteFilename);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::FormConstrainedResize(TObject *Sender, int &MinWidth,int &MinHeight, int &MaxWidth, int &MaxHeight)
{
	bt_Publish->Top   = Height - bt_Publish->Height - 60;
	mem_Entry->Height = bt_Publish->Top - mem_Entry->Top - 20;

	MinWidth  = 592;
	MaxWidth  = 592;
	MinHeight = 480;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::LoadPageOptions()
{
	TIniFile* poINI = new TIniFile(globals.m_asLastDirectory + "\\" + PAGE_OPTIONS_FILE);
	globals.m_bIncludeEntryDate = poINI->ReadBool("Options","IncludeEntryDates",true);
	delete(poINI);

	cb_IncludeEntryDate->Checked = globals.m_bIncludeEntryDate;
}
//---------------------------------------------------------------------------
void __fastcall TGUI::SavePageOptions()
{
	TIniFile* poINI = new TIniFile(globals.m_asLastDirectory + "\\" + PAGE_OPTIONS_FILE);
	poINI->WriteBool("Options","IncludeEntryDates",globals.m_bIncludeEntryDate);
	delete(poINI);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::cb_IncludeEntryDateClick(TObject *Sender)
{
	// Save the ini file in the current directory
	globals.m_bIncludeEntryDate = cb_IncludeEntryDate->Checked;
	SavePageOptions();
	RebuildPage1Click(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TGUI::InsertDate1Click(TObject *Sender)
{
	//
	struct date d;
	getdate(&d);
	AnsiString asDate = asGetDateFromFields(d.da_day,d.da_mon,d.da_year);

    AnsiString asText = "<" + globals.m_oPO.m_asDateTAG + ">" + mem_Entry->SelText + ":" + asDate + "</" + globals.m_oPO.m_asDateTAG + ">";
    InsertStringIntoEntry( asText );
}
//---------------------------------------------------------------------------
void __fastcall TGUI::RebuildRecursively(AnsiString _asDir)
{
	// Get current directory
	AnsiString asCurrentDir = GetCurrentDir();

	TSearchRec oSR;

	// Build the file containeed inside this directory
	if (FindFirst("*.entry",faAnyFile,oSR) == 0)
	{
		FindClose(oSR);

		//
		AnsiString asSelDir   = AnsiString(asCurrentDir);
		AnsiString asFilename = ExtractFileName(asSelDir) + "." + globals.m_oPO.m_asFileType;
		AnsiString asCompleteFilename;

		asCompleteFilename = asSelDir + "\\..\\" + asFilename;

		//
		CHTMLGenerator::GeneratePage( asCompleteFilename,asSelDir,globals.m_oPO,globals.m_bIncludeEntryDate);

		// Generate page in site directory
		MirrorPage(asCompleteFilename);
	}

	// Recurse into internals ...
	if (FindFirst("*.*",faAnyFile,oSR) == 0)
	{
		do{

			if ((oSR.Attr ==  faDirectory) && (oSR.Name != "..") && (oSR.Name != "."))
			{
				chdir( oSR.Name.c_str() );
				RebuildRecursively( oSR.Name );
				chdir( ".." );
			}

		}while(FindNext(oSR) == 0);
		FindClose(oSR);
	}
}
//---------------------------------------------------------------------------
void __fastcall TGUI::N2Click(TObject *Sender)
{
	//
	chdir( asSelectedDirectory().c_str() );
	RebuildRecursively( asSelectedDirectory() );
}
//---------------------------------------------------------------------------

