(************************************************************************
 *                                                                      *
 *   Ant Movie Catalog 4.x                                              *
 *   (C) 2000-2011 Antoine Potten, Mickaël Vanneufville                 *
 *   http://www.antp.be/software                                        *
 *                                                                      *
 ************************************************************************
 *                                                                      *
 *   This program is free software; you can redistribute it and/or      *
 *   modify it under the terms of the GNU General Public License        *
 *   as published by the Free Software Foundation; either version 2     *
 *   of the License, or (at your option) any later version.             *
 *                                                                      *
 *   This program is distributed in the hope that it will be useful,    *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of     *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *
 *   GNU General Public License for more details.                       *
 *                                                                      *
 ************************************************************************)

unit export;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Buttons, ExtCtrls, ShellAPI, ImgList, ComCtrls, Menus,
  ActnList,

  AntCorelButton, AntStringList, AntJvLabel, AntJvHotLink,
  TB2Item, TBX, TB2MRU, TBXExtItems,
  TB2Dock, TB2Toolbar, AntAutoHintLabel, AntJvLinkLabel,
  SynEdit, SynEditHighlighter, SynHighlighterHtml,

  main, // Needed for some labels translations in HTML export

  framefields, MovieClass, FileManager, base, framesortby, ConstValues,
  frameincludemov;


{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

const

  strFilterExtHTML    = 'html';
  strFilterExtCSV     = 'csv';
  strFilterExtSQL     = 'sql';
  strFilterExtImages  = '';
  strFilterExtOrigons = 'ogs';
  strFilterExtXML     = 'xml';

  ToHTML    = 0;
  ToCSV     = 1;
  ToSQL     = 2;
  ToImages  = 3;
  ToOrigons = 4;
  ToXML     = 5;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

type
  TExportWin = class(TBaseDlg)
    ActionDisplayFull: TAction;
    ActionDisplayIndividual: TAction;
    ActionEditCopy: TAction;
    ActionEditCut: TAction;
    ActionEditDelete: TAction;
    ActionEditPaste: TAction;
    ActionEditSelectAll: TAction;
    ActionEditUndo: TAction;
    ActionExportBoth: TAction;
    ActionExportSelected: TAction;
    ActionHTMLNew: TAction;
    ActionHTMLNoRecent: TAction;
    ActionHTMLOpen: TAction;
    ActionHTMLSave: TAction;
    ActionHTMLSaveAs: TAction;
    ActionInsertTag: TAction;
    ActionList1: TActionList;
    btnDisplayFull: TTBXItem;
    btnDisplayIndividual: TTBXItem;
    btnHTMLExport: TTBXSubmenuItem;
    btnHTMLExportBoth: TTBXItem;
    btnHTMLExportSelected: TTBXItem;
    BtnInsertTag: TTBXSubmenuItem;
    BtnLoadTemplate: TTBXSubmenuItem;
    BtnNewTemplate: TTBXItem;
    BtnNoRecentTemplate: TTBXItem;
    BtnSaveAsTemplate: TTBXItem;
    BtnSaveTemplate: TTBXItem;
    btnSeparator1: TTBXSeparatorItem;
    btnSeparator2: TTBXSeparatorItem;
    CBCopyPictures: TCheckBox;
    CBCopyPicturesNew: TCheckBox;
    CBCSVColumnTitles: TCheckBox;
    CBSQLCreate: TCheckBox;
    CBSQLDrop: TCheckBox;
    CBSQLUpdate: TCheckBox;
    ESQLTableName: TEdit;
    ETemplate: TSynEdit;
    FieldsCSV: TFieldsFrame;
    FieldsSQL: TFieldsFrame;
    grpImages: TGroupBox;
    HtmEdtCpy: TTBXItem;
    HtmEdtCut: TTBXItem;
    HtmEdtPst: TTBXItem;
    HtmEdtSel: TTBXItem;
    HtmEdtUnd: TTBXItem;
    ImageListFormat: TImageList;
    LCSVDelimiter: TLabel;
    LHTMLTemplateFileName: TTBXLabelItem;
    LImgFilename: TLabel;
    LSelectFormat: TLabel;
    LSQLCommands: TLabel;
    LSQLTableName: TLabel;
    Messages: TAntStringList;
    MnuCat: TTBXSubmenuItem;
    MnuCat__1: TTBXSeparatorItem;
    MnuCat__2: TTBXSeparatorItem;
    MnuCatDsc: TTBXItem;
    MnuCatDsk: TTBXItem;
    MnuCatNbr: TTBXItem;
    MnuCatNme: TTBXItem;
    MnuCatPth: TTBXItem;
    MnuGen: TTBXSubmenuItem;
    MnuGenDte: TTBXItem;
    MnuGenTme: TTBXItem;
    MnuMov: TTBXSubmenuItem;
    MnuMovAbr: TTBXItem;
    MnuMovAct: TTBXItem;
    MnuMovAfm: TTBXItem;
    MnuMovApp: TTBXItem;
    MnuMovBeg: TTBXItem;
    MnuMovBor: TTBXItem;
    MnuMovCat: TTBXItem;
    MnuMovChk: TTBXItem;
    MnuMovCom: TTBXItem;
    MnuMovCou: TTBXItem;
    MnuMovDir: TTBXItem;
    MnuMovDsc: TTBXItem;
    MnuMovDsk: TTBXItem;
    MnuMovDte: TTBXItem;
    MnuMovEnd: TTBXItem;
    MnuMovFoT: TTBXItem;
    MnuMovFps: TTBXItem;
    MnuMovInd: TTBXItem;
    MnuMovLen: TTBXItem;
    MnuMovLng: TTBXItem;
    MnuMovMed: TTBXItem;
    MnuMovNum: TTBXItem;
    MnuMovOrT: TTBXItem;
    MnuMovPfn: TTBXItem;
    MnuMovPic: TTBXItem;
    MnuMovPro: TTBXItem;
    MnuMovRat: TTBXItem;
    MnuMovRec: TTBXItem;
    MnuMovRes: TTBXItem;
    MnuMovSiz: TTBXItem;
    MnuMovSrc: TTBXItem;
    MnuMovSub: TTBXItem;
    MnuMovTrT: TTBXItem;
    MnuMovTyp: TTBXItem;
    MnuMovURL: TTBXItem;
    MnuMovVbr: TTBXItem;
    MnuMovVfm: TTBXItem;
    MnuMovYea: TTBXItem;
    MnuOwnEml: TTBXItem;
    MnuOwnNam: TTBXItem;
    MnuOwnWeb: TTBXItem;
    PageControl1: TPageControl;
    Panel1: TPanel;
    PopupHTML: TTBXPopupMenu;
    RBImgAppend: TRadioButton;
    RBImgNumber: TRadioButton;
    RBImgTitle: TRadioButton;
    SortBy: TSortByFrame;
    SynHTMLSyn1: TSynHTMLSyn;
    TBDock1: TTBXDock;
    TBMRUList1: TTBXMRUList;
    TBMRUListItem1: TTBXMRUListItem;
    TBSeparatorItem1: TTBXSeparatorItem;
    TBSeparatorItem2: TTBXSeparatorItem;
    TBSeparatorItem3: TTBXSeparatorItem;
    TBSeparatorItem4: TTBXSeparatorItem;
    TBSubmenuItem1: TTBXSubmenuItem;
    TBToolbar1: TTBXToolbar;
    ToolbarHTML: TTBXToolbar;
    tshCSV: TTabSheet;
    tshEmpty: TTabSheet;
    tshHTML: TTabSheet;
    tshPictures: TTabSheet;
    tshSQL: TTabSheet;
    ECSVDelimiter: TComboBox;
    LCSVBloc: TLabel;
    ECSVBloc: TComboBox;
    LCSVLinebreaks: TLabel;
    ECSVLinebreaks: TComboBox;
    LSQLLinebreaks: TLabel;
    ESQLLinebreaks: TComboBox;
    LvFormat: TListView;
    pnlLeft: TPanel;
    Splitter1: TSplitter;
    Includemov: TIncludemovFrame;
    tshXML: TTabSheet;
    LXMLNote: TLabel;
    LOrigonsLink: TAntJvLinkLabel;
    MnuLab: TTBXSubmenuItem;
    MnuLabNum: TTBXItem;
    MnuLabChl: TTBXItem;
    MnuLabMed: TTBXItem;
    MnuLabTyp: TTBXItem;
    MnuLabSrc: TTBXItem;
    MnuLabDte: TTBXItem;
    MnuLabBor: TTBXItem;
    MnuLabRat: TTBXItem;
    MnuLabOrT: TTBXItem;
    MnuLabTrT: TTBXItem;
    MnuLabFoT: TTBXItem;
    MnuLabDir: TTBXItem;
    MnuLabPro: TTBXItem;
    MnuLabCou: TTBXItem;
    MnuLabCat: TTBXItem;
    MnuLabYea: TTBXItem;
    MnuLabLen: TTBXItem;
    MnuLabAct: TTBXItem;
    MnuLabURL: TTBXItem;
    MnuLabDsc: TTBXItem;
    MnuLabCom: TTBXItem;
    MnuLabVfm: TTBXItem;
    MnuLabVbr: TTBXItem;
    MnuLabAfm: TTBXItem;
    MnuLabABr: TTBXItem;
    MnuLabRes: TTBXItem;
    MnuLabFps: TTBXItem;
    MnuLabLng: TTBXItem;
    MnuLabSub: TTBXItem;
    MnuLabSiz: TTBXItem;
    MnuLabDsk: TTBXItem;
    MnuLabPic: TTBXItem;
    MnuLabUAF: TTBXItem;
    MnuLabUVF: TTBXItem;
    MnuLabUFS: TTBXItem;
    MnuLabUFP: TTBXItem;
    MnuMovFT1: TTBXItem;
    MnuMovFT2: TTBXItem;
    MnuMovA10: TTBXItem;
    MnuMovCF: TTBXSubmenuItem;
    MnuLabCF: TTBXSubmenuItem;
    procedure ActionDisplayFullExecute(Sender: TObject);
    procedure ActionEditCopyExecute(Sender: TObject);
    procedure ActionEditCutExecute(Sender: TObject);
    procedure ActionEditDeleteExecute(Sender: TObject);
    procedure ActionEditPasteExecute(Sender: TObject);
    procedure ActionEditSelectAllExecute(Sender: TObject);
    procedure ActionEditUndoExecute(Sender: TObject);
    procedure ActionExportBothExecute(Sender: TObject);
    procedure ActionHTMLNewExecute(Sender: TObject);
    procedure ActionHTMLOpenExecute(Sender: TObject);
    procedure ActionHTMLSaveAsExecute(Sender: TObject);
    procedure ActionHTMLSaveExecute(Sender: TObject);
    procedure ActionInsertTagExecute(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure btn3Click(Sender: TObject);
    procedure CBCopyPicturesClick(Sender: TObject);
    procedure CBSQLUpdateClick(Sender: TObject);
    procedure ETemplateChange(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormShow(Sender: TObject);
    procedure LvFormatSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
    procedure MnuCatDscClick(Sender: TObject);
    procedure MnuCatDskClick(Sender: TObject);
    procedure MnuCatNbrClick(Sender: TObject);
    procedure MnuCatNmeClick(Sender: TObject);
    procedure MnuCatPthClick(Sender: TObject);
    procedure MnuGenDteClick(Sender: TObject);
    procedure MnuGenTmeClick(Sender: TObject);
    procedure MnuMovAbrClick(Sender: TObject);
    procedure MnuMovActClick(Sender: TObject);
    procedure MnuMovAfmClick(Sender: TObject);
    procedure MnuMovAppClick(Sender: TObject);
    procedure MnuMovBegClick(Sender: TObject);
    procedure MnuMovBorClick(Sender: TObject);
    procedure MnuMovCatClick(Sender: TObject);
    procedure MnuMovChkClick(Sender: TObject);
    procedure MnuMovComClick(Sender: TObject);
    procedure MnuMovCouClick(Sender: TObject);
    procedure MnuMovDirClick(Sender: TObject);
    procedure MnuMovDscClick(Sender: TObject);
    procedure MnuMovDskClick(Sender: TObject);
    procedure MnuMovDteClick(Sender: TObject);
    procedure MnuMovEndClick(Sender: TObject);
    procedure MnuMovFoTClick(Sender: TObject);
    procedure MnuMovFpsClick(Sender: TObject);
    procedure MnuMovIndClick(Sender: TObject);
    procedure MnuMovLenClick(Sender: TObject);
    procedure MnuMovLngClick(Sender: TObject);
    procedure MnuMovMedClick(Sender: TObject);
    procedure MnuMovNumClick(Sender: TObject);
    procedure MnuMovOrTClick(Sender: TObject);
    procedure MnuMovPfnClick(Sender: TObject);
    procedure MnuMovPicClick(Sender: TObject);
    procedure MnuMovProClick(Sender: TObject);
    procedure MnuMovRatClick(Sender: TObject);
    procedure MnuMovRecClick(Sender: TObject);
    procedure MnuMovResClick(Sender: TObject);
    procedure MnuMovSizClick(Sender: TObject);
    procedure MnuMovSrcClick(Sender: TObject);
    procedure MnuMovSubClick(Sender: TObject);
    procedure MnuMovTrTClick(Sender: TObject);
    procedure MnuMovTypClick(Sender: TObject);
    procedure MnuMovURLClick(Sender: TObject);
    procedure MnuMovVbrClick(Sender: TObject);
    procedure MnuMovVfmClick(Sender: TObject);
    procedure MnuMovYeaClick(Sender: TObject);
    procedure MnuMovA10Click(Sender: TObject);
    procedure MnuMovFT1Click(Sender: TObject);
    procedure MnuMovFT2Click(Sender: TObject);
    procedure MnuOwnEmlClick(Sender: TObject);
    procedure MnuOwnNamClick(Sender: TObject);
    procedure MnuOwnWebClick(Sender: TObject);
    procedure MnuLabNumClick(Sender: TObject);
    procedure MnuLabChkClick(Sender: TObject);
    procedure MnuLabBorClick(Sender: TObject);
    procedure MnuLabOrTClick(Sender: TObject);
    procedure MnuLabTrTClick(Sender: TObject);
    procedure MnuLabFoTClick(Sender: TObject);
    procedure MnuLabDirClick(Sender: TObject);
    procedure MnuLabProClick(Sender: TObject);
    procedure MnuLabCouClick(Sender: TObject);
    procedure MnuLabYeaClick(Sender: TObject);
    procedure MnuLabCatClick(Sender: TObject);
    procedure MnuLabLenClick(Sender: TObject);
    procedure MnuLabActClick(Sender: TObject);
    procedure MnuLabURLClick(Sender: TObject);
    procedure MnuLabDscClick(Sender: TObject);
    procedure MnuLabComClick(Sender: TObject);
    procedure MnuLabVfmClick(Sender: TObject);
    procedure MnuLabVbrClick(Sender: TObject);
    procedure MnuLabResClick(Sender: TObject);
    procedure MnuLabSizClick(Sender: TObject);
    procedure MnuLabLngClick(Sender: TObject);
    procedure MnuLabSubClick(Sender: TObject);
    procedure MnuLabRatClick(Sender: TObject);
    procedure MnuLabPicClick(Sender: TObject);
    procedure MnuLabDteClick(Sender: TObject);
    procedure MnuLabAfmClick(Sender: TObject);
    procedure MnuLabAbrClick(Sender: TObject);
    procedure MnuLabFpsClick(Sender: TObject);
    procedure MnuLabDskClick(Sender: TObject);
    procedure MnuLabMedClick(Sender: TObject);
    procedure MnuLabTypClick(Sender: TObject);
    procedure MnuLabSrcClick(Sender: TObject);
    procedure MnuLabUAFClick(Sender: TObject);
    procedure MnuLabUFPClick(Sender: TObject);
    procedure MnuLabUFSClick(Sender: TObject);
    procedure MnuLabUVFClick(Sender: TObject);

    procedure MnuMovCFClick(Sender: TObject);
    procedure MnuLabCFClick(Sender: TObject);

    procedure SortByBtnAdvSortClick(Sender: TObject);
    procedure SortByEOrderByChange(Sender: TObject);
    procedure TBMRUList1Click(Sender: TObject; const Filename: String);
    procedure LinkLabelLinkClick(Sender: TObject; LinkNumber: Integer;
      LinkText: String);
  private
    MovieList: TMovieList;
    SourceFile: string;
    DestFile: string;
    BaseFile: string;

    FHTMLFullFile, FHTMLIndivFile: TFileManager;
    FHTMLFullDoc,  FHTMLIndivDoc:  TStringList;
    FHTMLIMGAttr: string;

    FExpFileStyle: Integer;
    FExpFileExt: string;
    FExpFileNames: TStringList;

    procedure OnFileChange(Sender: TObject; AFileName: TFileName; var Result: Boolean);
    procedure OnNewFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
    procedure OnOpenFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
    procedure OnSaveFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
    procedure UpdateMRU(const strFilePath: string);
    function  HTMLCurrFile: TFileManager;
    function  HTMLCurrDoc:  TStringList;
    function  HTMLRelDoc(AFile: TFileManager): TStringList;
    procedure HTMLLoadTemplate;
    procedure HTMLStoreTemplate;

    function GetExpFileName(const AMovie: TMovie): string;

    procedure InsertTag(const strTag: string);
    procedure ReplaceTagsGeneral(var Page: string; const LineBreak: string);
    procedure ReplaceTagsMovie(var Page: string; const AMovie: TMovie; ExportPic, OnlyNewPic: Boolean; const LineBreak: string; const RecNr: Integer);

    procedure ExportToHTML;
    procedure ExportToCSV;
    procedure ExportToSQL;
    procedure ExportToImages;
    procedure ExportToOrigons;
    procedure ExportToXml;
  protected
    procedure LoadOptions; override;
    procedure SaveOptions; override;
  public
    procedure Translate; override;
    function Execute(const Movies: TMovieList; const Path: string): TModalResult;
  end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

var
  ExportWin: TExportWin;

implementation

uses
  StrUtils,

  fields, sort, Global, functions_files, functions_str, ProgramSettings,
  progress;

{$R *.DFM}

const
  msgErrorSave        =  0;
  msgErrorOpen        =  1;
  msgToOrigons        =  2;
  msgExportInit       =  3;
  msgExporting        =  4;
  msgCopying          =  5;
  msgToHTML           =  6;
  msgToCSV            =  7;
  msgToSQL            =  8;
  msgToImages         =  9;
  msgHTMLFullUnsaved  = 10;
  msgHTMLIndivUnsaved = 11;
  msgToXml            = 12;

{-------------------------------------------------------------------------------
   Options
-------------------------------------------------------------------------------}

procedure TExportWin.LoadOptions;
begin
  with Settings do
  begin
    with rExport do
    begin
      case WindowState of
        1:
          begin
            self.WindowState := wsNormal;
            self.Width := WindowWidth;
            self.Height := WindowHeight;
          end;
        2:
          begin
            self.WindowState := wsMaximized;
          end;
        else
          begin
            self.WindowState := wsNormal;
          end;
      end;
      case ImgFileName of
        1: RBImgNumber.Checked := true;
        2: RBImgTitle.Checked := true;
        else RBImgAppend.Checked := true;
      end;

      ECSVDelimiter.Text := CSVDelimiter;
      ECSVBloc.Text := CSVBloc;
      ECSVLinebreaks.Text := CSVLinebreaks;
      CBCSVColumnTitles.Checked := CSVColumnTitles;

      CBSQLUpdate.Checked := SQLUpdate;
      CBSQLDrop.Checked := SQLDrop;
      CBSQLCreate.Checked := SQLCreate;
      CBSQLUpdateClick(CBSQLUpdate);
      ESQLTableName.Text := SQLTableName;
      ESQLLinebreaks.Text := SQLLinebreaks;

      Self.SortBy.EOrderBy.ItemIndex := OrderBy;
      Self.Includemov.ItemIndex := TMovieIncludeOption(Includemov);

      if ExportBoth then
        ActionExportBothExecute(ActionExportBoth)
      else
        ActionExportBothExecute(ActionExportSelected);

      with rOptions.rExport do
      begin
        CBCopyPictures.Checked := CopyPictures;
        CBCopyPicturesNew.Checked := CopyPicturesNew;
        if LoadTemplate and (HTMLLastTemplate <> '') and FileExists(HTMLLastTemplate) then
          FHTMLFullFile.Open(HTMLLastTemplate)
        else
          FHTMLFullFile.New;
        if LoadTemplate and (HTMLLastTemplate2 <> '') and FileExists(HTMLLastTemplate2) then
          FHTMLIndivFile.Open(HTMLLastTemplate2)
        else
          FHTMLIndivFile.New;
        FExpFileStyle := ExpFileStyle;
        FHTMLIMGAttr := '';
        if ForcePicSizeW >= 0 then
          FHTMLIMGAttr := Format(' width="%d"', [ForcePicSizeW]);
        if ForcePicSizeH >= 0 then
          FHTMLIMGAttr := Format('%s height="%d"', [FHTMLIMGAttr, ForcePicSizeH]);
      end; // with rOptions.rExport

      TBMRUList1.Items.Assign(HTMLMRU);
      TBMRUList1.MaxItems := rOptions.rFiles.RecentFiles;

    end; // with rExport

    ToolbarHTML.Images := ToolbarImages;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.SaveOptions;
begin
  with Settings do
  begin
    with rExport do
    begin
      case self.WindowState of
        wsNormal:
          begin
            WindowState := 1;
            WindowWidth := Width;
            WindowHeight := Height;
          end;
        wsMaximized:
          begin
            WindowState := 2;
          end;
      end;
      OrderBy := Self.SortBy.EOrderBy.ItemIndex;
      SortWin.Fields.SaveToStrings(OrderFields, MovieList.CustomFieldsProperties);
      Includemov := Integer(Self.Includemov.ItemIndex);

      with rOptions.rExport do
      begin
        CopyPictures := CBCopyPictures.Checked;
        CopyPicturesNew := CBCopyPicturesNew.Checked;
      end;

      CSVDelimiter := ECSVDelimiter.Text;
      CSVBloc := ECSVBloc.Text;
      CSVLinebreaks := ECSVLinebreaks.Text;
      CSVColumnTitles := CBCSVColumnTitles.checked;
      FieldsCSV.SaveToStrings(CSVFields, MovieList.CustomFieldsProperties);

      SQLUpdate := CBSQLUpdate.Checked;
      SQLDrop := CBSQLDrop.Checked;
      SQLCreate := CBSQLCreate.Checked;
      FieldsSQL.SaveToStrings(SQLFields, MovieList.CustomFieldsProperties);
      SQLTableName := ESQLTableName.Text;
      SQLLinebreaks := ESQLLinebreaks.Text;

      if RBImgNumber.Checked then
        ImgFileName := 1
      else if RBImgTitle.Checked then
        ImgFileName := 2
      else
        ImgFileName := 0;

      HTMLMRU.Assign(TBMRUList1.Items);

      ExportBoth := btnHTMLExport.Action = ActionExportBoth;

//      LastFormat := LvFormat.ItemIndex;

    end;
  end;
end;

{-------------------------------------------------------------------------------
   General window management
-------------------------------------------------------------------------------}

function TExportWin.Execute(const Movies: TMovieList; const Path: string): TModalResult;
var
  i: Integer;
  newMenuItem : TTBXItem;
begin
  // Used in place of the ShowModal to allow the initialization of some variables
  MovieList := Movies;
  SourceFile := Path;
  FHTMLFullFile.MessageSaveQuery := Messages.Strings[msgHTMLFullUnsaved];
  FHTMLIndivFile.MessageSaveQuery := Messages.Strings[msgHTMLIndivUnsaved];
  Includemov.SetCount(Movies);

  with Settings.rExport do
  begin
    FieldsCSV.LoadFromStrings(CSVFields, MovieList.CustomFieldsProperties);
    FieldsSQL.LoadFromStrings(SQLFields, MovieList.CustomFieldsProperties);
    with SortWin.Fields do
    begin
      LoadFromStrings(OrderFields, MovieList.CustomFieldsProperties);
      DeleteField(fieldActors);
      DeleteField(fieldDescription);
      DeleteField(fieldComments);
    end;
  end;

  MnuMovCF.Clear;
  for i := 0 to MovieList.CustomFieldsProperties.Count-1 do
  begin
    newMenuItem := TTBXItem.Create(MnuMovCF);
    MnuMovCF.Add(newMenuItem);
    with newMenuItem, MovieList.CustomFieldsProperties.Objects[i] do
    begin
      Name := UpperCase(FieldTag);
      Caption := FieldName;
      OnClick := MnuMovCFClick;
    end;
  end;
  MnuLabCF.Clear;
  for i := 0 to MovieList.CustomFieldsProperties.Count-1 do
  begin
    newMenuItem := TTBXItem.Create(MnuLabCF);
    MnuLabCF.Add(newMenuItem);
    with newMenuItem, MovieList.CustomFieldsProperties.Objects[i] do
    begin
      Name := UpperCase(FieldTag);
      Caption := FieldName;
      OnClick := MnuLabCFClick;
    end;
  end;

  Result := ShowModal;
end;

{-------------------------------------------------------------------------------
   Export to ...
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToHTML;
var
  Page, Part, Output, LineBreak: string;
  i, EndPos, RecNr: Integer;
  ExportPic, OnlyNewPic: Boolean;
  IncOpt: TMovieIncludeOption;
  HTML: TextFile;
begin
  HTMLStoreTemplate;

  Output := '';
  ExportPic := CBCopyPictures.Checked;
  OnlyNewPic := CBCopyPicturesNew.Checked;
  IncOpt := Includemov.ItemIndex;
  LineBreak := Settings.rOptions.rExport.Linebreak;

  if (Pos(TAG_ITEMAPPR10, FHTMLFullDoc.Text) <> 0)
    or (Pos(TAG_ITEMAPPR10, FHTMLIndivDoc.Text) <> 0) then
  begin
    CopyAllFiles(strDirApp + strDirTemplates + 'rating*.gif', ExtractFilePath(DestFile));
  end;

  if (Pos(TAG_ITEMAPPRECIATION, FHTMLFullDoc.Text) <> 0)
    or (Pos(TAG_ITEMAPPRECIATION, FHTMLIndivDoc.Text) <> 0) then
  begin
    CopyAllFiles(strDirApp + strDirTemplates + 'appr*.gif', ExtractFilePath(DestFile));
  end;

  ProgressWin.Status := Format(Messages.Strings[msgExporting],['HTML']);

  Page := FHTMLFullDoc.Text;
  if (((btnHTMLExport.Action = ActionExportSelected) and (ActionDisplayFull.Checked)) or (btnHTMLExport.Action <> ActionExportSelected)) and (not IsReallyEmpty(Page)) then
  begin
    AssignFile(HTML, DestFile);
    Rewrite(HTML);
    ReplaceTagsGeneral(Page, LineBreak);
    while Length(Page) > 0 do
    begin
      if Pos(TAG_ITEMBEGIN, Page) = 1 then
      begin
        Delete(Page, 1, Length(TAG_ITEMBEGIN));
        EndPos := Pos(TAG_ITEMEND, Page);
        if EndPos = 0 then
          EndPos := Length(Page) + 1;
        RecNr := 1;
        with MovieList do
          for i := 0 to Count-1 do
            if TMovie(Items[i]).CanInclude(IncOpt) then
            begin
              Part := Copy(Page, 1, EndPos-1);
              ReplaceTagsMovie(Part, TMovie(Items[i]), ExportPic, OnlyNewPic, LineBreak, RecNr);
              Inc(RecNr);
              Output := Output + Part;
            end;
        Inc(EndPos, Length(TAG_ITEMEND));
      end else
      begin
        EndPos := Pos(TAG_ITEMBEGIN, Page);
        if EndPos = 0 then
          EndPos := Length(Page) + 1;
        Output := Output + Copy(Page, 1, EndPos-1);
      end;
      Delete(Page, 1, EndPos-1);
    end;
    WriteLn(HTML, Output);
    CloseFile(HTML);
  end;

  ProgressWin.IntProgress := 2;

  Page := FHTMLIndivDoc.Text;
  RecNr := 1;
  if (((btnHTMLExport.Action = ActionExportSelected) and (ActionDisplayIndividual.Checked)) or (btnHTMLExport.Action <> ActionExportSelected)) and (not IsReallyEmpty(Page)) then
    with MovieList do
      for i := 0 to Count-1 do
        if TMovie(Items[i]).CanInclude(IncOpt) then
        begin
          AssignFile(HTML, GetExpFileName(TMovie(Items[i])));
          Rewrite(HTML);
          Output := Page;
          ReplaceTagsGeneral(Output, LineBreak);
          ReplaceTagsMovie(Output, TMovie(Items[i]), ExportPic, OnlyNewPic, LineBreak, RecNr);
          Inc(RecNr);
          WriteLn(HTML, Output);
          CloseFile(HTML);
        end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToCSV;
var
  CSV: TextFile;
  imovie, ifield, field: Integer;
  CurrentLine, ImageFileName, fieldval, ReplLinebr: string;
  DelimChar, QuoteChar: Char;
  bCopyPictures, bOnlyNewPictures: Boolean;
  IncOpt: TMovieIncludeOption;
  FieldsList: TStringList;
begin
  bCopyPictures := CBCopyPictures.Checked;
  bOnlyNewPictures := CBCopyPicturesNew.Checked;
  IncOpt := Includemov.ItemIndex;
  DelimChar := StrToChar(ECSVDelimiter.Text);
  QuoteChar := StrToChar(ECSVBloc.Text);
  ReplLinebr := ECSVLinebreaks.Text;
  ProgressWin.Status := Format(Messages.Strings[msgExporting],['CSV']);
  AssignFile(CSV, DestFile);
  Rewrite(CSV);
  FieldsList := TStringList.Create;
  FieldsCSV.SaveToStrings(FieldsList, MovieList.CustomFieldsProperties);
  if CBCSVColumnTitles.Checked then
  begin
    CurrentLine := '';
    for ifield := 0 to FieldsList.Count-1 do
    begin
      if ifield > 0 then
        CurrentLine := CurrentLine + DelimChar;
      if (FieldsList.Strings[ifield][1] in ['0'..'9']) then // movie field (Field Number)
      begin
        field := StrToIntDef(FieldsList.Strings[ifield], -1);
        if field > -1 then
          CurrentLine := CurrentLine + strTagFields[field]
        else
          CurrentLine := CurrentLine + 'UNKNOW_' + IntToStr(ifield);
      end else // custom field (Custom Field Tag)
      begin
        field := MovieList.CustomFieldsProperties.IndexOf(FieldsList.Strings[ifield]);
        if field > -1 then
          CurrentLine := CurrentLine + MovieList.CustomFieldsProperties.Objects[field].FieldTag
        else
          CurrentLine := CurrentLine + 'UNKNOW_' + IntToStr(ifield);
      end;
    end;
    if bCopyPictures then
    begin
      if FieldsList.Count > 0 then
        CurrentLine := CurrentLine + DelimChar;
      CurrentLine := CurrentLine + strTagFieldPicture;
    end;
    Writeln(CSV,CurrentLine);
  end;
  for iMovie := 0 to MovieList.Count-1 do
  begin
    with TMovie(MovieList.Items[iMovie]) do
    begin
      if not CanInclude(IncOpt) then
        continue;
      CurrentLine := '';
      for iField := 0 to FieldsList.Count-1 do
      begin
        if iField > 0 then
          CurrentLine := CurrentLine + DelimChar;
        if FieldsList.Strings[ifield][1] in ['0'..'9'] then // movie field (Field Number)
          fieldval := GetFieldValue(StrToIntDef(FieldsList.Strings[ifield], -1))
        else // custom field (Custom Field Tag)
          fieldval := CustomFields.GetFieldValue(FieldsList.Strings[ifield]);
        fieldval := QuotedStrEx(fieldval, QuoteChar);
        CurrentLine := CurrentLine + StringReplace(fieldval, sLineBreak, ReplLinebr, [rfReplaceAll]);
      end;
      if bCopyPictures then
      begin
        if strPicture <> '' then
        begin
          if Picture <> nil then
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(TMovie(MovieList.Items[iMovie])), strPicture);
            if not bOnlyNewPictures or (bOnlyNewPictures and not FileExists(ImageFileName)) then
              try
                Picture.SaveToFile(ImageFileName);
              except
                ImageFileName := '';
              end;
          end else
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(TMovie(MovieList.Items[iMovie])), ExtractFileExt(strPicture));
            CopyFile(PChar(ExpandFileName(strPicture)), PChar(ImageFileName), bOnlyNewPictures);
          end;
          CurrentLine := CurrentLine + DelimChar + ExtractFileName(ImageFileName);
        end
        else
          CurrentLine := CurrentLine + DelimChar;
      end;
      Writeln(CSV,CurrentLine);
    end;
  end;
  ProgressWin.IntProgress := 2;
  Closefile(CSV);
  FieldsList.Free;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToSQL;

var
  SQL: TextFile;
  imovie, ifield, field: Integer;
  CurrentLine, ImageFileName, TableName,
  DateMask, FieldValue, ReplLinebr: string;
  bCopyPictures, bOnlyNewPictures, bUseUpdate: Boolean;
  IncOpt: TMovieIncludeOption;
  FieldsList: TStringList;
  FieldProperties: TCustomFieldProperties;

  function GetSQLName(FieldName: string; Index: Integer) : string;
  var
    idx: Integer;
  begin
    if (FieldName[1] in ['0'..'9']) then // movie field (Field Number)
    begin
      idx := StrToIntDef(FieldName, -1);
      if idx > -1 then
        Result := strSqlFields[idx]
      else
        Result := 'UNKNOW_' + IntToStr(Index);
    end else // custom field (Custom Field Tag)
    begin
      idx  := MovieList.CustomFieldsProperties.IndexOf(FieldName);
      if idx  > -1 then
        with MovieList.CustomFieldsProperties.Objects[idx] do
          Result := 'CF_' + UpperCase(FieldTag)
      else
        Result := 'UNKNOW_' + IntToStr(Index);
    end;
  end;
begin
  ReplLinebr := ESQLLinebreaks.Text;
  bCopyPictures := CBCopyPictures.Checked;
  bOnlyNewPictures := CBCopyPicturesNew.Checked;
  bUseUpdate := CBSQLUpdate.Checked;
  IncOpt := Includemov.ItemIndex;
  FieldsList := TStringList.Create;
  FieldsSQL.SaveToStrings(FieldsList, MovieList.CustomFieldsProperties);
  if bUseUpdate then
  begin
    ifield := FieldsList.IndexOf(IntToStr(fieldNumber));
    if ifield <> -1 then
      FieldsList.Delete(ifield);
  end;
  DateMask := Settings.rOptions.rExport.SQLDate;
  TableName := ESQLTableName.Text;
  if TableName = '' then
    TableName := 'Movies'
  else
  if TableName[1] in ['0'..'9'] then
    TableName := '_' + TableName;
  ProgressWin.Status := Format(Messages.Strings[msgExporting], ['SQL']);
  AssignFile(SQL, DestFile);
  Rewrite(SQL);
  if CBSQLDrop.Checked then
  begin
    CurrentLine := 'DROP TABLE IF EXISTS ' + TableName + ';';
    Writeln(SQL,CurrentLine);
  end;
  if CBSQLCreate.Checked then
  begin
    CurrentLine := 'CREATE TABLE ' + TableName + ' (';
    for ifield := 0 to FieldsList.Count-1 do
    begin
      if ifield > 0 then
        CurrentLine := CurrentLine + ', ';
      if (FieldsList.Strings[ifield][1] in ['0'..'9']) then // movie field (Field Number)
      begin
        field := StrToIntDef(FieldsList.Strings[ifield], -1);
        if field > -1 then
        begin
          CurrentLine := CurrentLine + strSqlFields[field] + ' ' + ConvertFieldTypeToSQL(GetFieldType(field));
          if field = fieldNumber then
            CurrentLine := CurrentLine + ' NOT NULL';
        end else
          CurrentLine := CurrentLine + 'UNKNOW_' + IntToStr(ifield) + ' TEXT';
      end else // custom field (Custom Field Tag)
      begin
        field := MovieList.CustomFieldsProperties.IndexOf(FieldsList.Strings[ifield]);
        if field > -1 then
          with MovieList.CustomFieldsProperties.Objects[field] do
            CurrentLine := CurrentLine + 'CF_' + UpperCase(FieldTag) + ' ' + ConvertFieldTypeToSQL(FieldType)
        else
          CurrentLine := CurrentLine + 'UNKNOW_' + IntToStr(ifield) + ' TEXT';
      end;
    end;
    if bCopyPictures then
    begin
      if FieldsList.Count > 0 then
        CurrentLine := CurrentLine + ', ';
      CurrentLine := Format('%s%s TEXT', [CurrentLine, strSqlFieldPicture]);
    end;
    if FieldsList.IndexOf(IntToStr(fieldNumber)) <> -1 then
      CurrentLine := CurrentLine + ', PRIMARY KEY (' + strSqlFields[fieldNumber] + ')';
    CurrentLine := CurrentLine + ');';
    Writeln(SQL,CurrentLine);
  end;
  for iMovie := 0 to MovieList.Count-1 do
  begin
    with TMovie(MovieList.Items[iMovie]) do
    begin
      if not CanInclude(IncOpt) then
        continue;
      if bUseUpdate then
        CurrentLine := 'UPDATE ' + TableName + ' SET '
      else
      begin
        CurrentLine := 'INSERT INTO '+ TableName +' (';
        for ifield := 0 to FieldsList.Count-1 do
        begin
          if ifield > 0 then
            CurrentLine := CurrentLine + ', ';
          CurrentLine := CurrentLine + GetSQLName(FieldsList.Strings[ifield], ifield);
        end;
        if bCopyPictures then
        begin
          if FieldsList.Count > 0 then
            CurrentLine := CurrentLine + ', ';
          CurrentLine := CurrentLine + strSqlFieldPicture;
        end;
        CurrentLine := CurrentLine + ') VALUES (';
      end;
      with FieldsList do
        for iField := 0 to Count-1 do
        begin
          if iField > 0 then
            CurrentLine := CurrentLine + ', ';

          if FieldsList.Strings[ifield][1] in ['0'..'9'] then // movie field (Field Number)
          begin
            field := StrToIntDef(FieldsList.Strings[ifield], -1);
            if (field = fieldDate) and (DateMask <> '') and (iDate > 0) then
              FieldValue := QuotedStr(FormatDateTime(DateMask, iDate))
            else
              FieldValue := QuotedStr(StringReplace(GetFieldValue(field), sLineBreak, ReplLinebr, [rfReplaceAll]));
          end else // custom field (Custom Field Tag)
          begin
            FieldProperties := MovieList.CustomFieldsProperties.GetField(FieldsList.Strings[ifield]);
            if (FieldProperties <> nil) and (FieldProperties.FieldType = ftDate) and
              (DateMask <> '') and (CustomFields.GetFieldValue(FieldsList.Strings[ifield]) <> '') then
              FieldValue := QuotedStr(FormatDateTime(DateMask, CustomFields.GetIntFieldValue(FieldsList.Strings[ifield])))
            else
              FieldValue := QuotedStr(StringReplace(CustomFields.GetFieldValue(FieldsList.Strings[ifield]), sLineBreak, ReplLinebr, [rfReplaceAll]));
          end;

          if bUseUpdate then
            CurrentLine := CurrentLine + GetSQLName(FieldsList.Strings[ifield], ifield) + ' = ' + FieldValue
          else
            CurrentLine := CurrentLine + FieldValue;
        end;
      if bCopyPictures then
      begin
        ImageFileName := '';
        if (strPicture <> '') then
        begin
          if Picture <> nil then
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(TMovie(MovieList.Items[iMovie])), strPicture);
            if not bOnlyNewPictures or (bOnlyNewPictures and not FileExists(ImageFileName)) then
              try
                Picture.SaveToFile(ImageFileName);
              except
                ImageFileName := '';
              end;
          end else
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(TMovie(MovieList.Items[iMovie])), ExtractFileExt(strPicture));
            CopyFile(PChar(ExpandFileName(strPicture)), PChar(ImageFileName), bOnlyNewPictures);
          end;
        end;
        if FieldsList.Count > 0 then
          CurrentLine := CurrentLine + ', ';
        FieldValue := QuotedStr(ExtractFileName(ImageFileName));
        if bUseUpdate then
          CurrentLine := Format('%s%s = %s', [CurrentLine, strSqlFieldPicture, FieldValue])
        else
          CurrentLine := Format('%s%s', [CurrentLine, FieldValue]);
      end;
      if bUseUpdate then
        CurrentLine := Format('%s WHERE %s = %d;', [CurrentLine, strSqlFields[fieldNumber], iNumber])
      else
        CurrentLine := CurrentLine + ');';
      Writeln(SQL, CurrentLine);
    end;
  end;
  ProgressWin.IntProgress := 2;
  Closefile(SQL);
  FieldsList.Free;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToImages;
var
  path, fileName, ext, imageName: string;
  nameFormat, i, titleFormat: Integer;
  IncOpt: TMovieIncludeOption;
begin
  titleFormat := 0;
  if RBImgAppend.Checked then
    nameFormat := 0
  else if RBImgNumber.Checked then
    nameFormat := 1
  else
  begin
    nameFormat := 2;
    titleFormat := Settings.rOptions.rMovieList.TitleColumn;
  end;
  path := ExtractFilePath(DestFile);
  fileName := ExtractFileName(DestFile);
  IncOpt := Includemov.ItemIndex;
  ProgressWin.Status := Format(Messages.Strings[msgExporting],[path]);
  for i := 0 to MovieList.Count-1 do
  begin
    with TMovie(MovieList.Items[i]) do
    begin
      if CanInclude(IncOpt) and (strPicture <> '') then
      begin
        ext := ExtractFileExt(strPicture);
        case nameFormat of
          0:
              imageName := Format('%s%s%d%s', [path, FileName, iNumber, ext]);
          1:
              imageName := Format('%s%d%s', [path, iNumber, ext]);
          2:
              imageName := path + ValidateFileName(GetFormattedTitle(titleFormat, False)) + ext;
        end;
        if Picture <> nil then
        begin
          try
            Picture.SaveToFile(imageName);
          except
          end;
        end else
        begin
          try
            SetCurrentDir(ExtractFilePath(SourceFile));
            CopyFile(PChar(ExpandFileName(strPicture)), PChar(ImageName), false);
          except
          end;
        end;
      end;
    end;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToOrigons;
var
  f: TextFile;
  i, j: Integer;
  field: Byte;
  val: string;
  ival: Integer;
  PrevDateFormat: string;
  PrevDecSeparator: Char;
  IncMov: TMovieIncludeOption;
  procedure FindNextNumber;
  begin
    while j <= Length(Val) do
      if Val[j] in ['0'..'9'] then
        Break
      else
        Inc(j);
  end;
  procedure FindNumberEnd;
  begin
    while j <= Length(Val) do
      if not (Val[j] in ['0'..'9']) then
        Break
      else
        Inc(j);
  end;
begin
  IncMov := Includemov.ItemIndex;
  PrevDateFormat := ShortDateFormat;
  PrevDecSeparator := DecimalSeparator;
  ShortDateFormat := 'yyyyMMdd';
  DecimalSeparator := '.';
  try
    ProgressWin.Status := Format(Messages.Strings[msgExporting],['Origons.com']);
    AssignFile(f, DestFile);
    Rewrite(f);
    Writeln(f, 'AMC 3.4.2'); // file format from the view of Origons' site
    for i := 0 to MovieList.Count-1 do
      with TMovie(MovieList.Items[i]) do
        if CanInclude(IncMov) then
        begin
          for field := fieldLow to fieldCount-1 do
            if field in OrigonFields then
              case field of
                fieldResolution:
                  begin
                    val := GetFieldValue(fieldResolution);
                    j := 1;
                    FindNumberEnd;
                    Write(f, Copy(val, 1, j-1) + #9);
                    FindNextNumber;
                    Delete(val, 1, j-1);
                    j := 1;
                    FindNumberEnd;
                    Write(f, Copy(val, 1, j-1) + #9);
                  end;
                fieldSize:
                  begin
                    val := GetFieldValue(fieldSize);
                    ival := 0;
                    while val <> '' do
                    begin
                      j := 1;
                      FindNumberEnd;
                      if j > 1 then
                        Inc(ival, StrToInt(Copy(val, 1, j-1)));
                      FindNextNumber;
                      Delete(val, 1, j-1);
                    end;
                    Write(f, IntToStr(ival) + #9);
                  end;
                fieldDisks: // last field
                  begin
                    Write(f, ReplaceLineBreaks(GetFieldValue(field)) + sLineBreak);
                  end;
              else
                Write(f, ReplaceLineBreaks(GetFieldValue(field)) + #9);
              end;
        end;
    CloseFile(f);
  finally
    ShortDateFormat := PrevDateFormat;
    DecimalSeparator := PrevDecSeparator;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ExportToXml;
var
  OtherList: TMovieList;
  i: Integer;
begin
  ProgressWin.Status := Format(Messages.Strings[msgExporting], ['XML']);
  OtherList := TMovieList.Create;
  try
    OtherList.CustomFieldsProperties.Assign(MovieList.CustomFieldsProperties);
    for i := 0 to MovieList.Count - 1 do
      OtherList.Add.Assign(MovieList[i]);
    OtherList.SaveToXML(DestFile, CBCopyPictures.Checked);
  finally
    OtherList.Free;
  end;
end;

{-------------------------------------------------------------------------------
   HTML stuff
-------------------------------------------------------------------------------}

procedure TExportWin.InsertTag(const strTag: string);
begin
  ETemplate.SelText := strTag;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ReplaceTagsGeneral(var Page: string; const LineBreak: string);
var
  i, c: Integer;
begin
  Page := StringReplace(Page, TAG_FILENAME, ExtractFileName(SourceFile),[rfReplaceAll]);
  Page := StringReplace(Page, TAG_FILEPATH, SourceFile,[rfReplaceAll]);
  Page := StringReplace(Page, TAG_TOTALMOVIES, IntToStr(MovieList.Count(Includemov.ItemIndex)),[rfReplaceAll]);
  if Pos(TAG_TOTALDISKS, Page) > 0 then
  begin
    c := 0;
    for i := 0 to MovieList.Count-1 do
      if TMovie(MovieList.Items[i]).CanInclude(Includemov.ItemIndex) then
        Inc(c, TMovie(MovieList.Items[i]).iDisks);
    Page := StringReplace(Page, TAG_TOTALDISKS, IntToStr(c), [rfReplaceAll]);
  end;
  Page := StringReplace(Page, TAG_DATE, DateToStr(Date),[rfReplaceAll]);
  Page := StringReplace(Page, TAG_TIME, TimeToStr(Time),[rfReplaceAll]);
  with MovieList.MovieProperties do
  begin
    Page := StringReplace(Page, TAG_OWNERNAME, strName,[rfReplaceAll]);
    Page := StringReplace(Page, TAG_OWNERMAIL, strMail,[rfReplaceAll]);
    Page := StringReplace(Page, TAG_OWNERSITE, strSite,[rfReplaceAll]);
    Page := StringReplace(Page, TAG_DESCRIPTION, IfThen(LineBreak <> '', StringReplace(strDescription, #13#10, LineBreak, [rfReplaceAll]), strDescription), [rfReplaceAll]);
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ReplaceTagsMovie(var Page: string; const AMovie: TMovie; ExportPic, OnlyNewPic: Boolean; const LineBreak: string; const RecNr: Integer);
var
  ImageFileName: string;
  i: integer;
  FieldProperties: TCustomFieldProperties;
begin
  if AMovie <> nil then
  begin
    with AMovie do
    begin
      // Replace Labels
      Page := StringReplace(Page, TAG_LABELNUMBER, strFields.Strings[0], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELCHECKED, strFields.Strings[1], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELMEDIA, strFields.Strings[2], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELTYPE, strFields.Strings[3], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELSOURCE, strFields.Strings[4], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELDATEADD, strFields.Strings[5], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELBORROWER, strFields.Strings[6], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELRATING, strFields.Strings[7], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELORIGINALTITLE, strFields.Strings[8], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELTRANSLATEDTITLE, strFields.Strings[9], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELFORMATTEDTITLE, strFields.Strings[10], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELDIRECTOR, strFields.Strings[11], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELPRODUCER, strFields.Strings[12], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELCOUNTRY, strFields.Strings[13], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELCATEGORY, strFields.Strings[14], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELYEAR, strFields.Strings[15], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELLENGTH, strFields.Strings[16], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELACTORS, strFields.Strings[17], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELURL, strFields.Strings[18], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELDESCRIPTION, strFields.Strings[19], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELCOMMENTS, strFields.Strings[20], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELVIDEOFORMAT, strFields.Strings[21], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELVIDEOBITRATE, strFields.Strings[22], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELAUDIOFORMAT, strFields.Strings[23], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELAUDIOBITRATE, strFields.Strings[24], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELRESOLUTION, strFields.Strings[25], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELFRAMERATE, strFields.Strings[26], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELLANGUAGES, strFields.Strings[27], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELSUBTITLES, strFields.Strings[28], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELSIZE, strFields.Strings[29], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELDISKS, strFields.Strings[30], [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELPICTURE, MnuLabPic.Caption, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELAUDIOKBPS, MainWindow.FrmMovie.LAudioKbps.Caption, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELVIDEOKBPS, MainWindow.FrmMovie.LVideoKbps.Caption, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELFPS, MainWindow.FrmMovie.LFramerateFPS.Caption, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_LABELUNIT, MainWindow.FrmMovie.LSizeUnit.Caption, [rfReplaceAll]);
      with MovieList.CustomFieldsProperties do
        for i:= Count-1 downto 0 do
        begin
          FieldProperties := Objects[i];
          Page := StringReplace(Page, TAG_LABEL_CF + UpperCase(FieldProperties.FieldTag),
            FieldProperties.FieldName, [rfReplaceAll]);
        end;

      // Replace Items
      Page := StringReplace(Page, TAG_RECNR, IntToStr(RecNr), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMNUMBER, GetFieldValue(fieldNumber), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMCHECKED, IfThen(bChecked, 'x', ' '), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMTYPE, strMediaType, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMMEDIA, strMedia, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMSOURCE, strSource, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMBORROWER, strBorrower, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMDATEADD, GetFieldValue(fieldDate, True), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMORIGINALTITLE, strOriginalTitle, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMTRANSLATEDTITLE, strTranslatedTitle, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMFORMATTEDTITLE1, GetFormattedTitle(2, False), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMFORMATTEDTITLE2, GetFormattedTitle(3, False), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMFORMATTEDTITLE, GetFormattedTitle, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMDIRECTOR, strDirector, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMPRODUCER, strProducer, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMCOUNTRY, strCountry, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMYEAR, GetFieldValue(fieldYear), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMCATEGORY, strCategory, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMLENGTH, GetFieldValue(fieldLength), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMACTORS, IfThen(LineBreak <> '', StringReplace(strActors, #13#10, LineBreak, [rfReplaceAll]), strActors), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMURL, strURL, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMCOMMENTS, IfThen(LineBreak <> '', StringReplace(strComments, #13#10, LineBreak, [rfReplaceAll]), strComments), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMDESCRIPTION, IfThen(LineBreak <> '', StringReplace(strDescription, #13#10, LineBreak, [rfReplaceAll]), strDescription), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMFORMAT, strVideoFormat, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMVIDEOFORMAT, strVideoFormat, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMAUDIOFORMAT, strAudioFormat, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMVIDEOBITRATE, GetFieldValue(fieldVideoBitrate), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMAUDIOBITRATE, GetFieldValue(fieldAudioBitrate), [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMRESOLUTION, strResolution, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMFRAMERATE, strFramerate, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMSIZE, strSize, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMLANGUAGES, strLanguages, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMSUBTITLES, strSubtitles, [rfReplaceAll]);
      Page := StringReplace(Page, TAG_ITEMDISKS, GetFieldValue(fieldDisks), [rfReplaceAll]);
      with MovieList.CustomFieldsProperties do
      for i:= Count-1 downto 0 do
      begin
        FieldProperties := Objects[i];
        Page := StringReplace(Page, TAG_ITEM_CF + UpperCase(FieldProperties.FieldTag),
          AMovie.CustomFields.GetFieldValue(Strings[i], False, True), [rfReplaceAll]);
      end;

      if iRating > -1 then
      begin
        i := Round(iRating/10.0);
        Page := StringReplace(Page, TAG_ITEMAPPR10, Format('<img src="appr10_%d.gif" alt="%d/10" />', [i, i]), [rfReplaceAll]);
        i := 0;
        case iRating of
           0..29:  i := 0;
          30..49:  i := 1;
          50..69:  i := 2;
          70..89:  i := 3;
          90..100: i := 4;
        end;
        Page := StringReplace(Page, TAG_ITEMAPPRECIATION, Format('<img src="appr%d.gif" alt="%d/4" />', [i, i]), [rfReplaceAll]);
      end else
      begin
        Page := StringReplace(Page, TAG_ITEMAPPR10, '', [rfReplaceAll]);
        Page := StringReplace(Page, TAG_ITEMAPPRECIATION, '', [rfReplaceAll]);
      end;
      Page := StringReplace(Page, TAG_ITEMRATING, GetFieldValue(fieldRating, True), [rfReplaceAll]);

      if Pos(TAG_ITEMPICTURE, Page) > 0 then
      begin
        if strPicture <> '' then
        begin
          if Picture <> nil then
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(AMovie), strPicture);
            if ExportPic then
            begin
              try
                if (not OnlyNewPic) or ((OnlyNewPic) and (not FileExists(ImageFileName))) then
                  Picture.SaveToFile(ImageFileName);
              except
              end;
            end;
          end else  // if Picture <> nil
          begin
            ImageFileName := ChangeFileExt(GetExpFileName(AMovie), ExtractFileExt(strPicture));
            if ExportPic then
            begin
              CopyFile(PChar(ExpandFileName(strPicture)), PChar(ImageFileName), OnlyNewPic);
            end;
          end;
        end else // if strPicture <> ''
        begin
          ImageFileName := '';
        end;
        if ImageFileName <> '' then
          ImageFileName := ExtractFileName(ImageFileName);
        Page := StringReplace(Page, TAG_ITEMPICTUREFILENAME, ImageFileName, [rfReplaceAll]);
        if ImageFileName <> '' then
          Page := StringReplace(Page, TAG_ITEMPICTURE, Format('<img src="%s" alt="poster"%s />', [ImageFileName, FHTMLIMGAttr]), [rfReplaceAll])
        else
          Page := StringReplace(Page, TAG_ITEMPICTURE, '', [rfReplaceAll]);
      end;
      if Pos(TAG_ITEMFILEINDIV, Page) > 0 then
        Page := StringReplace(Page, TAG_ITEMFILEINDIV, ExtractFileName(GetExpFileName(AMovie)), [rfReplaceAll]);
    end; // with
  end; // if <> nil
end;

{-------------------------------------------------------------------------------
   Events
-------------------------------------------------------------------------------}

procedure TExportWin.FormShow(Sender: TObject);
begin
  inherited;
  LvFormat.SetFocus;
  LvFormat.Selected := nil;
  LvFormatSelectItem(Sender, nil, False);
  CBCopyPicturesClick(Self);
  UpdateMRU('');
  ActionDisplayFullExecute(ActionDisplayFull);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.FormCreate(Sender: TObject);
var
  i: integer;
  procedure InitFile(AFile: TFileManager);
  begin
    with AFile do
    begin
      OnNewFile := Self.OnNewFile;
      OnOpenFile := Self.OnOpenFile;
      OnSaveFile := Self.OnSaveFile;
      OnFileChange := Self.OnFileChange;
      with OpenDialog do
      begin
        Filter := DialogHTMLFilter;
        Options := DialogOpenOptions;
        DefaultExt := strFilterExtHTML;
      end;
      with SaveDialog do
      begin
        Filter := DialogHTMLFilter;
        Options := DialogSaveOptions;
        DefaultExt := strFilterExtHTML;
      end;
    end;
  end;
begin
  with PageControl1 do
    for i := 0 to PageCount-1 do
      Pages[i].TabVisible := false;
  SortWin := TSortWin.Create(Self);
  with MnuMov do
    for i := 0 to Count-1 do
      with Items[i] do
        if Tag > -1 then
          Caption := strFields.Strings[Tag];
  with MnuLab do
    for i := 0 to Count-1 do
      with Items[i] do
        if Tag > -1 then
          Caption := strFields.Strings[Tag];
  ActionHTMLNew.ImageIndex := Ord(ICON_TEMPLATENEW);
  ActionHTMLOpen.ImageIndex := Ord(ICON_TEMPLATELOAD);
  ActionHTMLSave.ImageIndex := Ord(ICON_TEMPLATESAVE);
  ActionHTMLSaveAs.ImageIndex := Ord(ICON_TEMPLATESAVEAS);

  FHTMLFullFile := TFileManager.Create(Self);
  InitFile(FHTMLFullFile);
  FHTMLFullDoc := TStringList.Create;

  FHTMLIndivFile := TFileManager.Create(Self);
  InitFile(FHTMLIndivFile);
  FHTMLIndivDoc := TStringList.Create;

  FExpFileNames := TStringList.Create;
  FExpFileNames.Sorted := True;
  FExpFileNames.Duplicates := dupIgnore;

  inherited;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.LvFormatSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
begin
  if Selected then
  begin
    PageControl1.ActivePageIndex := Item.Index + 1;
    Btn3.Enabled := True;
  end
  else
  begin
    pagecontrol1.ActivePageIndex := 0;
    Btn3.Enabled := False;
  end;
  Includemov.Visible := Selected and (Item.Index in [ToHTML, ToCSV, ToSQL, ToOrigons, ToImages]);
  Sortby.Visible := Selected and (Item.Index in [ToHTML, ToCSV, ToSQL, ToOrigons]);
  grpImages.Visible := Selected and (Item.Index in [ToHTML, ToCSV, ToSQL, ToXML]);
  CBCopyPicturesClick(CBCopyPictures);
end;

{-------------------------------------------------------------------------------
  HTML toolbar
-------------------------------------------------------------------------------}

procedure TExportWin.ActionInsertTagExecute(Sender: TObject);
begin
//
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionHTMLNewExecute(Sender: TObject);
begin
  HTMLCurrFile.New;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionHTMLOpenExecute(Sender: TObject);
begin
  with HTMLCurrFile do
  begin
    OpenDialog.InitialDir := Settings.rOptions.rFolders[fuTemplates].Value;
    Open;
    //if Open then // Do in OnOpenFile
    //  Settings.rOptions.rFolders[fuTemplates].Value := ExtractFilePath(CurrentFile);
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionHTMLSaveExecute(Sender: TObject);
begin
  with HTMLCurrFile do
  begin
    SaveDialog.InitialDir := Settings.rOptions.rFolders[fuTemplates].Value;
    Save;
    //if Save then // Do in OnSaveFile
    //  Settings.rOptions.rFolders[fuTemplates].Value := ExtractFilePath(CurrentFile);
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionHTMLSaveAsExecute(Sender: TObject);
begin
  with HTMLCurrFile do
  begin
    SaveDialog.InitialDir := Settings.rOptions.rFolders[fuTemplates].Value;
    SaveAs;
    //if SaveAs then // Do in OnSaveFile
    //  Settings.rOptions.rFolders[fuTemplates].Value := ExtractFilePath(CurrentFile);
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionDisplayFullExecute(Sender: TObject);
begin
  HTMLStoreTemplate;
  (Sender as TAction).Checked := True;
  HTMLLoadTemplate;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.TBMRUList1Click(Sender: TObject;
  const Filename: String);
begin
  HTMLCurrFile.Open(FileName);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.UpdateMRU(const strFilePath: string);
begin
  if strFilePath <> '' then
    TBMRUList1.Add(strFilePath);
  ActionHTMLNoRecent.Visible := TBMRUList1.Items.Count = 0;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.FormDestroy(Sender: TObject);
begin
  SortWin.Free;
  FHTMLFullFile.Free;
  FHTMLFullDoc.Free;
  FHTMLIndivFile.Free;
  FHTMLIndivDoc.Free;
  FExpFileNames.Free;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.btn1Click(Sender: TObject);
begin
  functions_files.LaunchHelp(HelpContext + LvFormat.ItemIndex + 1);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.btn3Click(Sender: TObject);
var
  NumberMask: string;
begin
  if LvFormat.Selected <> nil then
    with TSaveDialog.Create(Self) do
      try
        Options := DialogSaveOptions;
        case LvFormat.Selected.Index of
          ToHTML:
            begin
              Filter := DialogHTMLFilter;
              DefaultExt := strFilterExtHTML;
              Title := Messages.Strings[msgToHTML];
            end;
          ToCSV:
            begin
              Filter := DialogCSVFilter;
              DefaultExt := strFilterExtCSV;
              Title := Messages.Strings[msgToCSV];
            end;
          ToSQL:
            begin
              Filter := DialogSQLFilter;
              DefaultExt := strFilterExtSQL;
              Title := Messages.Strings[msgToSQL];
            end;
          ToImages:
            begin
              Filter := DialogImageFilter;
              DefaultExt := strFilterExtImages;
              Title := Messages.Strings[msgToImages];
            end;
          ToOrigons:
            begin
              Filter := DialogOrigonsFilter;
              DefaultExt := strFilterExtOrigons;
              Title := Messages.Strings[msgToOrigons];
            end;
          ToXML:
            begin
              Filter := DialogXmlFilter;
              DefaultExt := strFilterExtXML;
              Title := Messages.Strings[msgToXml];
            end;
        end;
        with Settings.rOptions do
        begin
          InitialDir := rFolders[fuExport].Value;
          if rExport.RememberLastFile then
            FileName := ChangeFileExt(ExtractFileName(rExport.LastFile), '.' + DefaultExt)
          else
            FileName := IfThen(SourceFile <> '', ChangeFileExt(ExtractFileName(SourceFile), '.' + DefaultExt), '');
        end;
        if Execute then
        begin
          with Settings.rOptions do
          begin
            if rExport.RememberLastFile then
              rExport.LastFile := ExtractFileName(FileName);
             rFolders[fuExport].Value := ExtractFilePath(FileName);
          end;
          ProgressWin.Execute(Self);
          try
            // Order the list
            ProgressWin.Status := Messages.Strings[msgExportInit];
            ProgressWin.Maximum := 2;
            ProgressWin.IntProgress := 0;
            if Settings.rOptions.rExport.AddZeroes then
              NumberMask := Format('_%%.%dd', [Length(IntToStr(MovieList.MaxNumber(False)))])
            else
              NumberMask := '_%d';
            if Sortby.Visible then
              SortBy.Sort(MovieList);
            ProgressWin.IntProgress := 1;
            // export the data
            SetCurrentDir(ExtractFilePath(SourceFile));
            DestFile := FileName;
            FExpFileNames.Clear;
            FExpFileExt := Settings.rOptions.rExport.ExpFileExt;
            if FExpFileExt = '' then
                FExpFileExt := ExtractFileExt(DestFile);
            case FExpFileStyle of
              0:
                BaseFile := ExtractFilePath(DestFile) + ExtractFileName(ChangeFileExt(DestFile, NumberMask + FExpFileExt));
              1:
                BaseFile := ExtractFilePath(DestFile) + ExtractFileName(ChangeFileExt(SourceFile, NumberMask + FExpFileExt));
              2:
                BaseFile := ExtractFilePath(DestFile) + '%s' + FExpFileExt;
            else
              BaseFile := '';
            end;
            case LvFormat.Selected.Index of
              ToHTML:
                ExportToHTML;
              ToCSV:
                ExportToCSV;
              ToSQL:
                ExportToSQL;
              ToImages:
                ExportToImages;
              ToOrigons:
                ExportToOrigons;
              ToXml:
                ExportToXml;
            end;
          finally
            ProgressWin.Close;
          end;
          if Settings.rOptions.rExport.OpenExportedFile then
            LaunchProg(DestFile, ExtractFilePath(DestFile));
        end;
      finally
        Free;
      end;
end;

{-------------------------------------------------------------------------------
    HTML tag menu
-------------------------------------------------------------------------------}

procedure TExportWin.MnuCatNmeClick(Sender: TObject);
begin
     InsertTag(TAG_FILENAME);
end;

procedure TExportWin.MnuMovBegClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMBEGIN);
end;

procedure TExportWin.MnuMovEndClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMEND);
end;

procedure TExportWin.MnuMovIndClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMFILEINDIV);
end;

procedure TExportWin.MnuMovRecClick(Sender: TObject);
begin
  InsertTag(TAG_RECNR);
end;
procedure TExportWin.MnuMovNumClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMNUMBER);
end;

procedure TExportWin.MnuMovChkClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMCHECKED);
end;

procedure TExportWin.MnuMovBorClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMBORROWER);
end;

procedure TExportWin.MnuMovOrTClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMORIGINALTITLE);
end;

procedure TExportWin.MnuMovTrTClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMTRANSLATEDTITLE);
end;

procedure TExportWin.MnuMovFoTClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMFORMATTEDTITLE);
end;

procedure TExportWin.MnuGenDteClick(Sender: TObject);
begin
  InsertTag(TAG_DATE);
end;

procedure TExportWin.MnuGenTmeClick(Sender: TObject);
begin
  InsertTag(TAG_TIME);
end;

procedure TExportWin.MnuCatPthClick(Sender: TObject);
begin
  InsertTag(TAG_FILEPATH);
end;

procedure TExportWin.MnuMovDirClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMDIRECTOR);
end;

procedure TExportWin.MnuMovProClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMPRODUCER);
end;

procedure TExportWin.MnuMovCouClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMCOUNTRY);
end;

procedure TExportWin.MnuMovYeaClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMYEAR);
end;

procedure TExportWin.MnuMovCatClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMCATEGORY);
end;

procedure TExportWin.MnuMovLenClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMLENGTH);
end;

procedure TExportWin.MnuMovActClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMACTORS);
end;

procedure TExportWin.MnuMovURLClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMURL);
end;

procedure TExportWin.MnuMovDscClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMDESCRIPTION);
end;

procedure TExportWin.MnuMovComClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMCOMMENTS);
end;

procedure TExportWin.MnuMovVfmClick(Sender: TObject);
begin
     InsertTag(TAG_ITEMVIDEOFORMAT);
end;

procedure TExportWin.MnuMovVbrClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMVIDEOBITRATE);
end;

procedure TExportWin.MnuMovResClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMRESOLUTION);
end;

procedure TExportWin.MnuMovSizClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMSIZE);
end;

procedure TExportWin.MnuMovLngClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMLANGUAGES);
end;

procedure TExportWin.MnuMovSubClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMSUBTITLES);
end;

procedure TExportWin.MnuCatNbrClick(Sender: TObject);
begin
  InsertTag(TAG_TOTALMOVIES);
end;

procedure TExportWin.MnuCatDskClick(Sender: TObject);
begin
  InsertTag(TAG_TOTALDISKS);
end;

procedure TExportWin.MnuMovAppClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMAPPRECIATION);
end;

procedure TExportWin.MnuMovRatClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMRATING);
end;

procedure TExportWin.MnuMovPicClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMPICTURE);
end;

procedure TExportWin.MnuMovPfnClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMPICTUREFILENAME);
end;

procedure TExportWin.MnuOwnNamClick(Sender: TObject);
begin
  InsertTag(TAG_OWNERNAME);
end;

procedure TExportWin.MnuOwnEmlClick(Sender: TObject);
begin
  InsertTag(TAG_OWNERMAIL);
end;

procedure TExportWin.MnuOwnWebClick(Sender: TObject);
begin
  InsertTag(TAG_OWNERSITE);
end;

procedure TExportWin.MnuCatDscClick(Sender: TObject);
begin
  InsertTag(TAG_DESCRIPTION);
end;

procedure TExportWin.MnuMovDteClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMDATEADD);
end;

procedure TExportWin.MnuMovAfmClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMAUDIOFORMAT);
end;

procedure TExportWin.MnuMovAbrClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMAUDIOBITRATE);
end;

procedure TExportWin.MnuMovFpsClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMFRAMERATE);
end;

procedure TExportWin.MnuMovDskClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMDISKS);
end;

procedure TExportWin.MnuMovMedClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMMEDIA);
end;

procedure TExportWin.MnuMovTypClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMTYPE);
end;

procedure TExportWin.MnuMovSrcClick(Sender: TObject);
begin
  InsertTag(TAG_ITEMSOURCE);
end;

procedure TExportWin.MnuMovA10Click(Sender: TObject);
begin
  InsertTag(TAG_ITEMAPPR10);
end;

procedure TExportWin.MnuMovFT1Click(Sender: TObject);
begin
  InsertTag(TAG_ITEMFORMATTEDTITLE1);
end;

procedure TExportWin.MnuMovFT2Click(Sender: TObject);
begin
  InsertTag(TAG_ITEMFORMATTEDTITLE2);
end;

procedure TExportWin.MnuLabNumClick(Sender: TObject);
begin
  InsertTag(TAG_LABELNUMBER);
end;

procedure TExportWin.MnuLabChkClick(Sender: TObject);
begin
  InsertTag(TAG_LABELCHECKED);
end;

procedure TExportWin.MnuLabBorClick(Sender: TObject);
begin
  InsertTag(TAG_LABELBORROWER);
end;

procedure TExportWin.MnuLabOrTClick(Sender: TObject);
begin
  InsertTag(TAG_LABELORIGINALTITLE);
end;

procedure TExportWin.MnuLabTrTClick(Sender: TObject);
begin
  InsertTag(TAG_LABELTRANSLATEDTITLE);
end;

procedure TExportWin.MnuLabFoTClick(Sender: TObject);
begin
  InsertTag(TAG_LABELFORMATTEDTITLE);
end;

procedure TExportWin.MnuLabDirClick(Sender: TObject);
begin
  InsertTag(TAG_LABELDIRECTOR);
end;

procedure TExportWin.MnuLabProClick(Sender: TObject);
begin
  InsertTag(TAG_LABELPRODUCER);
end;

procedure TExportWin.MnuLabCouClick(Sender: TObject);
begin
  InsertTag(TAG_LABELCOUNTRY);
end;

procedure TExportWin.MnuLabYeaClick(Sender: TObject);
begin
  InsertTag(TAG_LABELYEAR);
end;

procedure TExportWin.MnuLabCatClick(Sender: TObject);
begin
  InsertTag(TAG_LABELCATEGORY);
end;

procedure TExportWin.MnuLabLenClick(Sender: TObject);
begin
  InsertTag(TAG_LABELLENGTH);
end;

procedure TExportWin.MnuLabActClick(Sender: TObject);
begin
  InsertTag(TAG_LABELACTORS);
end;

procedure TExportWin.MnuLabURLClick(Sender: TObject);
begin
  InsertTag(TAG_LABELURL);
end;

procedure TExportWin.MnuLabDscClick(Sender: TObject);
begin
  InsertTag(TAG_LABELDESCRIPTION);
end;

procedure TExportWin.MnuLabComClick(Sender: TObject);
begin
  InsertTag(TAG_LABELCOMMENTS);
end;

procedure TExportWin.MnuLabVfmClick(Sender: TObject);
begin
  InsertTag(TAG_LABELVIDEOFORMAT);
end;

procedure TExportWin.MnuLabVbrClick(Sender: TObject);
begin
  InsertTag(TAG_LABELVIDEOBITRATE);
end;

procedure TExportWin.MnuLabResClick(Sender: TObject);
begin
  InsertTag(TAG_LABELRESOLUTION);
end;

procedure TExportWin.MnuLabSizClick(Sender: TObject);
begin
  InsertTag(TAG_LABELSIZE);
end;

procedure TExportWin.MnuLabLngClick(Sender: TObject);
begin
  InsertTag(TAG_LABELLANGUAGES);
end;

procedure TExportWin.MnuLabSubClick(Sender: TObject);
begin
  InsertTag(TAG_LABELSUBTITLES);
end;

procedure TExportWin.MnuLabRatClick(Sender: TObject);
begin
  InsertTag(TAG_LABELRATING);
end;

procedure TExportWin.MnuLabPicClick(Sender: TObject);
begin
  InsertTag(TAG_LABELPICTURE);
end;

procedure TExportWin.MnuLabDteClick(Sender: TObject);
begin
  InsertTag(TAG_LABELDATEADD);
end;

procedure TExportWin.MnuLabAfmClick(Sender: TObject);
begin
  InsertTag(TAG_LABELAUDIOFORMAT);
end;

procedure TExportWin.MnuLabAbrClick(Sender: TObject);
begin
  InsertTag(TAG_LABELAUDIOBITRATE);
end;

procedure TExportWin.MnuLabFpsClick(Sender: TObject);
begin
  InsertTag(TAG_LABELFRAMERATE);
end;

procedure TExportWin.MnuLabDskClick(Sender: TObject);
begin
  InsertTag(TAG_LABELDISKS);
end;

procedure TExportWin.MnuLabMedClick(Sender: TObject);
begin
  InsertTag(TAG_LABELMEDIA);
end;

procedure TExportWin.MnuLabTypClick(Sender: TObject);
begin
  InsertTag(TAG_LABELTYPE);
end;

procedure TExportWin.MnuLabSrcClick(Sender: TObject);
begin
  InsertTag(TAG_LABELSOURCE);
end;

procedure TExportWin.MnuLabUAFClick(Sender: TObject);
begin
  InsertTag(TAG_LABELAUDIOKBPS);
end;

procedure TExportWin.MnuLabUFPClick(Sender: TObject);
begin
  InsertTag(TAG_LABELVIDEOKBPS);
end;

procedure TExportWin.MnuLabUFSClick(Sender: TObject);
begin
  InsertTag(TAG_LABELUNIT);
end;

procedure TExportWin.MnuLabUVFClick(Sender: TObject);
begin
  InsertTag(TAG_LABELFPS);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.MnuMovCFClick(Sender: TObject);
begin
  InsertTag(TAG_ITEM_CF + TTBXItem(Sender).Name);
end;

procedure TExportWin.MnuLabCFClick(Sender: TObject);
begin
  InsertTag(TAG_LABEL_CF + TTBXItem(Sender).Name);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.SortByBtnAdvSortClick(Sender: TObject);
begin
  SortBy.BtnAdvSortClick(Sender);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.SortByEOrderByChange(Sender: TObject);
begin
  SortBy.EOrderByChange(Sender);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ETemplateChange(Sender: TObject);
begin
  HTMLCurrFile.Modified := True;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.FormCloseQuery(Sender: TObject;
  var CanClose: Boolean);
begin
  //Settings.rExport.HTMLLastTemplate := FHTMLFullFile.CurrentFile; // Done in OnNewFile/OnOpenFile/OnSaveFile
  //Settings.rExport.HTMLLastTemplate2 := FHTMLIndivFile.CurrentFile; // Done in OnNewFiel/OnOpenFile/OnSaveFile
  CanClose := FHTMLFullFile.Close and FHTMLIndivFile.Close;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.OnFileChange(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  with LHTMLTemplateFileName do
  begin
    Caption := ExtractFileName(AFileName);
    Hint := AFileName;
  end;
  UpdateMRU(AFileName);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.OnNewFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  if Sender = FHTMLFullFile then
  begin
    FHTMLFullDoc.Clear;
    Settings.rExport.HTMLLastTemplate := '';
  end
  else if Sender = FHTMLIndivFile then
  begin
    FHTMLIndivDoc.Clear;
    Settings.rExport.HTMLLastTemplate2 := '';
  end;
  HTMLLoadTemplate;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.OnOpenFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  try
    HTMLRelDoc(Sender as TFileManager).LoadFromFile(AFileName);
    Settings.rOptions.rFolders[fuTemplates].Value := ExtractFilePath(AFileName);
    if Sender = FHTMLFullFile then
      Settings.rExport.HTMLLastTemplate := FHTMLFullFile.CurrentFile
    else if Sender = FHTMLIndivFile then
      Settings.rExport.HTMLLastTemplate2 := FHTMLIndivFile.CurrentFile;
    HTMLLoadTemplate;
  except
    on e: Exception do
      if Visible then
        MessageWin.Execute(Format(Messages.Strings[msgErrorOpen],[AFilename, e.Message]),mtError,[mbOk])
      else
        TFileManager(Sender).New;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.OnSaveFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  try
    HTMLStoreTemplate;
    HTMLRelDoc(Sender as TFileManager).SaveToFile(AFileName);
    Settings.rOptions.rFolders[fuTemplates].Value := ExtractFilePath(AFileName);
    if Sender = FHTMLFullFile then
      Settings.rExport.HTMLLastTemplate := FHTMLFullFile.CurrentFile
    else if Sender = FHTMLIndivFile then
      Settings.rExport.HTMLLastTemplate2 := FHTMLIndivFile.CurrentFile;
  except
    on e: Exception do
      MessageWin.Execute(Format(Messages.Strings[msgErrorSave], [AFileName, e.Message]),mtError,[mbOk]);
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

function TExportWin.HTMLCurrFile: TFileManager;
begin
  if ActionDisplayIndividual.Checked then
    Result := FHTMLIndivFile
  else
    Result := FHTMLFullFile;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

function TExportWin.HTMLCurrDoc: TStringList;
begin
  if ActionDisplayIndividual.Checked then
    Result := FHTMLIndivDoc
  else
    Result := FHTMLFullDoc;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

function TExportWin.HTMLRelDoc(AFile: TFileManager): TStringList;
begin
  if AFile = FHTMLIndivFile then
    Result := FHTMLIndivDoc
  else
    Result := FHTMLFullDoc;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.HTMLLoadTemplate;
begin
  ETemplate.Lines.Assign(HTMLCurrDoc);
  with LHTMLTemplateFileName, HTMLCurrFile do
  begin
    Caption := ExtractFileName(CurrentFile);
    Hint := '|' + CurrentFile;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.HTMLStoreTemplate;
begin
  HTMLCurrDoc.Assign(ETemplate.Lines);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditUndoExecute(Sender: TObject);
begin
  ETemplate.Undo;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditCutExecute(Sender: TObject);
begin
  ETemplate.CutToClipboard;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditCopyExecute(Sender: TObject);
begin
  ETemplate.CopyToClipboard;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditPasteExecute(Sender: TObject);
begin
  ETemplate.PasteFromClipboard;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditDeleteExecute(Sender: TObject);
begin
  ETemplate.SelText := '';
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionEditSelectAllExecute(Sender: TObject);
begin
  ETemplate.SelectAll;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.CBCopyPicturesClick(Sender: TObject);
begin
  CBCopyPicturesNew.Enabled := CBCopyPictures.Checked and CBCopyPictures.Enabled and (LvFormat.ItemIndex <> ToXML);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.ActionExportBothExecute(Sender: TObject);
begin
  if(Sender is TAction) then
    btnHTMLExport.Action := Sender as TAction
  else
    btnHTMLExport.Action := ActionExportBoth;
  btnHTMLExport.OnClick := nil;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

function TExportWin.GetExpFileName(const AMovie: TMovie): string;
var
  OriginalName, Ext: string;
  c, i: Integer;
begin
  case FExpFileStyle of
    0, 1:
      OriginalName := LowerCase(Format(BaseFile, [AMovie.iNumber]));
    2:
      begin
        OriginalName := AMovie.strOriginalTitle;
        if OriginalName = '' then
          OriginalName := AMovie.strTranslatedTitle;
        if OriginalName = '' then
          OriginalName := 'untitled';
        OriginalName := LowerCase(Format(BaseFile, [ValidateFileName(OriginalName)]));
      end;
  else
    OriginalName := LowerCase(BaseFile);
  end;
  Result := OriginalName;
  Ext := ExtractFileExt(OriginalName);
  c := 1;
  i := FExpFileNames.IndexOf(Result);
  if (i <> -1) and (FExpFileNames.Objects[i] <> AMovie) then
  begin
    i := FExpFileNames.IndexOfObject(AMovie);
    if (i = -1) then
      repeat
        Inc(c);
        Result := ChangeFileExt(OriginalName, Format(' (%d)%s', [c, Ext]));
      until FExpFileNames.IndexOf(Result) = -1
    else
      Result := FExpFileNames[i];
  end;
  FExpFileNames.AddObject(Result, AMovie);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.CBSQLUpdateClick(Sender: TObject);
var
  UseUpdate: Boolean;
begin
  UseUpdate := CBSQLUpdate.Checked;
  CBSQLDrop.Enabled := not UseUpdate;
  CBSQLCreate.Enabled := not UseUpdate;
  if UseUpdate then
  begin
    CBSQLDrop.Checked := False;
    CBSQLCreate.Checked := False;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (LvFormat.Selected <> nil) and (LvFormat.Selected.Index = ToHTML) then
  begin
    if (ssCtrl in Shift) and (Key = VK_TAB) then
    begin
      if ActionDisplayFull.Checked then
        ActionDisplayFullExecute(ActionDisplayIndividual)
      else
      if ActionDisplayIndividual.Checked then
        ActionDisplayFullExecute(ActionDisplayFull);
    end;
  end;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.Translate;
begin
  Translator.Translate(FieldsCSV);
  Translator.Translate(FieldsSQL);
  Translator.Translate(SortBy);
  Translator.Translate(Includemov);
  inherited;
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

procedure TExportWin.LinkLabelLinkClick(Sender: TObject; LinkNumber: Integer; LinkText: String);
begin
  LaunchProg('http://' + LinkText);
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

end.

