(************************************************************************
 *                                                                      *
 *   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 getscript;

interface

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

  ifspas, ifs_var, ifpsclass, ifpsdate,
  IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
  SynEdit, SynEditHighlighter, SynEditMiscClasses, SynEditSearch, SynHighlighterPas,
  TB2Item, TBX, TB2MRU, TBXExtItems, TB2Toolbar, TBXStatusBars,
  AntStringList, AntJvLinkLabel, TBXDkPanels, TB2Dock, AntCorelButton, AntAutoHintLabel,

  base, MovieClass, FileManager, frameincludemov,
  getscript_readscripts, getscript_debug;

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

type

  TIStatus = (iStopped, iRunning, iStepOver, iStepOverWaiting);
  TScriptWorkMode = (swmGetInfo, swmScripting);

const
  WM_CLOSEAFTERRUN = WM_USER + 1;

type
  TGetScriptWin = class(TBaseDlg)
    ActionDebugBreakpoint: TAction;
    ActionDebugBreakpointClear: TAction;
    ActionDebugEval: TAction;
    ActionDebugRun: TAction;
    ActionDebugRunToCursor: TAction;
    ActionDebugStep: TAction;
    ActionDebugStop: TAction;
    ActionDebugWatchAdd: TAction;
    ActionDebugWatchClear: TAction;
    ActionDebugWatchRemove: TAction;
    ActionDisplayEditor: TAction;
    ActionDisplayScripts: TAction;
    ActionEditCopy: TAction;
    ActionEditCut: TAction;
    ActionEditDelete: TAction;
    ActionEditFind: TAction;
    ActionEditFindNext: TAction;
    ActionEditPaste: TAction;
    ActionEditSelectAll: TAction;
    ActionEditUndo: TAction;
    ActionFileNew: TAction;
    ActionFileNoRecent: TAction;
    ActionFileOpen: TAction;
    ActionFileProperties: TAction;
    ActionFileSave: TAction;
    ActionFileSaveAs: TAction;
    ActionList1: TActionList;
    ActionListAll: TAction;
    ActionListCheck: TAction;
    ActionListNone: TAction;
    ActionListUncheck: TAction;
    ActionOptionsDefault: TAction;
    ActionOptionsEdit: TAction;
    ActionViewDetailed: TAction;
    ActionViewFilter: TAction;
    ActionViewFilterChange: TAction;
    ActionViewList: TAction;
    CBCloseThis: TTBXCheckBox;
    CBShowResults: TTBXCheckBox;
    DockpanelExec: TTBXDockablePanel;
    DockpanelLimitations: TTBXDockablePanel;
    DockpanelOptions: TTBXDockablePanel;
    DockpanelWatch: TTBXDockablePanel;
    DockScriptLeft: TTBXMultiDock;
    DockScriptRight: TTBXMultiDock;
    EScript: TSynEdit;
    grpLimitFields: TGroupBox;
    grpScriptInfo: TGroupBox;
    http: TIdHTTP;
    lblScriptInfo: TAntJvLinkLabel;
    lstDebugImages: TImageList;
    lstLimitFields: TListView;
    lstLimitMovies: TIncludemovFrame;
    lstScriptOptions: TListView;
    lstScripts: TListView;
    lstWatch: TListBox;
    MenuPopupDebug: TTBXPopupMenu;
    MenuPopupEdit: TTBXPopupMenu;
    MenuPopupList: TTBXPopupMenu;
    MenuPopupOptions: TTBXPopupMenu;
    Messages: TAntStringList;
    MnuDbp__1: TTBXSeparatorItem;
    MnuDbp__2: TTBXSeparatorItem;
    MnuDbpBrk: TTBXItem;
    MnuDbpEvl: TTBXItem;
    MnuDbpRtc: TTBXItem;
    MnuDbpSte: TTBXItem;
    MnuDbpWch: TTBXItem;
    MnuEdp__1: TTBXSeparatorItem;
    MnuEdp__2: TTBXSeparatorItem;
    MnuEdpAll: TTBXItem;
    MnuEdpCpy: TTBXItem;
    MnuEdpCut: TTBXItem;
    MnuEdpDel: TTBXItem;
    MnuEdpPst: TTBXItem;
    MnuEdpUnd: TTBXItem;
    MnuEdt__1: TTBXSeparatorItem;
    MnuEdt__2: TTBXSeparatorItem;
    MnuEdt__3: TTBXSeparatorItem;
    MnuEdt__4: TTBXSeparatorItem;
    MnuEdtBrc: TTBXItem;
    MnuEdtBrk: TTBXItem;
    MnuEdtEvl: TTBXItem;
    MnuEdtFnd: TTBXItem;
    MnuEdtFnx: TTBXItem;
    MnuEdtNew: TTBXItem;
    MnuEdtOpn: TTBXSubmenuItem;
    MnuEdtPro: TTBXItem;
    MnuEdtRec: TTBXItem;
    MnuEdtRtc: TTBXItem;
    MnuEdtRun: TTBXItem;
    MnuEdtSaa: TTBXItem;
    MnuEdtSav: TTBXItem;
    MnuEdtSte: TTBXItem;
    MnuEdtStp: TTBXItem;
    MnuEdtWch: TTBXItem;
    MnuFlt__1: TTBXSeparatorItem;
    MnuFltAll: TTBXItem;
    MnuFltNon: TTBXItem;
    MnuLsp__1: TTBXSeparatorItem;
    MnuLspAll: TTBXItem;
    MnuLspChk: TTBXItem;
    MnuLspNon: TTBXItem;
    MnuLspUnc: TTBXItem;
    MnuOpp__1: TTBXSeparatorItem;
    MnuOppDef: TTBXItem;
    MnuOppEdt: TTBXItem;
    MnuScrDet: TTBXItem;
    MnuScrFlt: TTBXSubmenuItem;
    MnuScrLst: TTBXItem;
    MnuScrRun: TTBXItem;
    MnuScrStp: TTBXItem;
    MnuTabEdt: TTBXItem;
    MnuTabScr: TTBXItem;
    PageControl1: TPageControl;
    Panel1: TPanel;
    pnlScriptInfo: TPanel;
    sbEditor: TTBXStatusBar;
    shtEditor: TTabSheet;
    shtScript: TTabSheet;
    Splitter1: TSplitter;
    SynEditSearch1: TSynEditSearch;
    SynPasSyn1: TSynPasSyn;
    tabScriptInfo: TTabSet;
    TBDock1: TTBXDock;
    TBMRUList1: TTBXMRUList;
    TBMRUListItem1: TTBXMRUListItem;
    TbsRun: TTBXSeparatorItem;
    DockEditRight: TTBXMultiDock;
    DockEditLeft: TTBXMultiDock;
    DockEditBottom: TTBXMultiDock;
    DockEditTop: TTBXMultiDock;
    TBXSeparatorItem1: TTBXSeparatorItem;
    ToolbarEditor: TTBXToolbar;
    ToolbarScript: TTBXToolbar;
    ToolbarTabs: TTBXToolbar;
    ToolbarWatch: TTBXToolbar;
    TBXItem5: TTBXItem;
    TBXItem4: TTBXItem;
    ToolbarWatchBevel: TBevel;
    ScrollBox1: TScrollBox;
    CBAllowClear: TTBXCheckBox;
    ActionFileCopy: TAction;
    ActionFilePaste: TAction;
    procedure ActionDebugBreakpointClearExecute(Sender: TObject);
    procedure ActionDebugBreakpointExecute(Sender: TObject);
    procedure ActionDebugEvalExecute(Sender: TObject);
    procedure ActionDebugRunExecute(Sender: TObject);
    procedure ActionDebugStepExecute(Sender: TObject);
    procedure ActionDebugStopExecute(Sender: TObject);
    procedure ActionDebugWatchAddExecute(Sender: TObject);
    procedure ActionDebugWatchClearExecute(Sender: TObject);
    procedure ActionDebugWatchRemoveExecute(Sender: TObject);
    procedure ActionDisplayExecute(Sender: TObject);
    procedure ActionEditCopyExecute(Sender: TObject);
    procedure ActionEditCutExecute(Sender: TObject);
    procedure ActionEditDeleteExecute(Sender: TObject);
    procedure ActionEditFindExecute(Sender: TObject);
    procedure ActionEditFindNextExecute(Sender: TObject);
    procedure ActionEditPasteExecute(Sender: TObject);
    procedure ActionEditSelectAllExecute(Sender: TObject);
    procedure ActionEditUndoExecute(Sender: TObject);
    procedure ActionFileNewExecute(Sender: TObject);
    procedure ActionFileOpenExecute(Sender: TObject);
    procedure ActionFilePropertiesExecute(Sender: TObject);
    procedure ActionFileSaveAsExecute(Sender: TObject);
    procedure ActionFileSaveExecute(Sender: TObject);
    procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean);
    procedure ActionListAllExecute(Sender: TObject);
    procedure ActionListCheckExecute(Sender: TObject);
    procedure ActionOptionsDefaultExecute(Sender: TObject);
    procedure ActionOptionsEditExecute(Sender: TObject);
    procedure ActionViewFilterChangeExecute(Sender: TObject);
    procedure ActionViewFilterExecute(Sender: TObject);
    procedure ActionViewListExecute(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure EScriptGutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark);
    procedure EScriptGutterPaint(Sender: TObject; aLine, X, Y: Integer);
    procedure EScriptSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor);
    procedure EScriptStatusChange(Sender: TObject; Changes: TSynStatusChanges);
    procedure FormActivate(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 lblScriptInfoLinkClick(Sender: TObject; LinkNumber: Integer; LinkText: String);
    procedure lstScriptOptionsInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
    procedure lstScriptOptionsKeyPress(Sender: TObject; var Key: Char);
    procedure lstScriptsInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
    procedure lstScriptsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
    procedure lstWatchKeyPress(Sender: TObject; var Key: Char);
    procedure tabScriptInfoChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
    procedure TBMRUList1Click(Sender: TObject; const Filename: string);
    procedure lstScriptsKeyPress(Sender: TObject; var Key: Char);
    procedure lstScriptsCustomDrawItem(Sender: TCustomListView;
      Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
    procedure lstLimitFieldsMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
  private
    FCurrentFile: TFileManager;
    FCurrentScript: TScriptInfo;
    FCurrentCatalog: TFileManager;
    FScript: TIfPasScript;
    FMovieList: TMovieList;
    FMovieListFiltered: TList;
    FRunForCount: Integer;
    FWorkMode: TScriptWorkMode;
    LastSearch: string;
    FScripts: TScriptList;
    FDebugPlugin: TDebugPlugin;
    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 OnModifFile(Sender: TObject; State: Boolean);
    procedure UpdateMRU(const FileName: string);
    procedure FillFields;
    procedure FillOptions;
    procedure SaveScriptFields;
    procedure SaveCustomFields;
    function FindScript(const AFile: TFileName): Boolean;
    procedure OnThreadEnd(Sender: TObject);
    procedure OnCancelDownload(Sender: TObject);
    procedure ReadScripts;
    procedure FillScripts;
    procedure SetCurrentLine(const Value: Integer);
    function GetCurrentLine: Integer;
    function GetVariableValue(Sender: TObject; const VarName: string): string;
    procedure CloseAfterRun(var Msg: TMessage); message WM_CLOSEAFTERRUN;
  protected
    procedure LoadOptions; override;
    procedure SaveOptions; override;
  public
    constructor Create(AOwner: TComponent; AWorkMode: TScriptWorkMode); reintroduce;
    function Execute(const Catalog: TFileManager; AMovieList: TMovieList): TModalResult;
    property CurrentCatalog: TFileManager read FCurrentCatalog;
    property CurrentScript: TScriptInfo read FCurrentScript;
    function HasRemainingMovies: Boolean;
    property DebugPlugin: TDebugPlugin read FDebugPlugin;
    property CurrentLine: Integer read GetCurrentLine write SetCurrentLine;
    property MovieList: TMovieList read FMovieList;
    procedure Translate; override;
  end;

  function OnScriptRunLine(id: Pointer; Sender: TIfPasScript; Position: Longint): TCs2Error;
  function OnScriptUses(id: Pointer; Sender: TIfPasScript; Name: string): TCs2Error;
  function OnScriptRegProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;
  function OnScriptRegPickProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;
//  function OnScriptRegXmlProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;

var
  GetScriptWin: TGetScriptWin;

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

implementation

uses
  strUtils,

  IdHTTPHeaderInfo, IdURI,
  stdimport, formsimport, stdctrlsimport, ifpslib, ifpstrans,
  ifpsdll, ifpsdll2, ifpsdelphi,
  JvSimpleXml, SynEditTypes,

  ConstValues, fields, functions_html, functions_files, functions_gui, Global,
  getscript_picktree, getscript_picklist, threaddownload, functions_str,
  getscript_results, getscript_properties, listform,
  functions_xml, ProgramSettings, getscript_xml;

{$R *.dfm}

var
  Cl: TIFPSClasses;
  FScriptStatus: TIStatus;
  DownloadThread: TDownloadThread;
  DownloadState: TDownloadState;
  DownloadResult: string;

const
  msgScriptError       =  0;
  msgUnsavedFile       =  1;
  msgUnknownLang       =  2;
  msgIAgree            =  3;
  msgNoMovieFound      =  4;
  msgAbortBatch        =  5;
  msgModified          =  6;
  msgValueForOption    =  7;
//  msg                =  8;
  msgFind              =  9;
  msgFindtext          = 10;
  msgNoMoreMatches     = 11;

const
  pnlEditorFile        =  0;
  pnlEditorModified    =  1;
  pnlEditorPos         =  2;

const
  strDefaultProgram    = 'program NewScript;'#13#10'begin'#13#10'end.';

const
  imgGutterBREAK        = 0;
  imgGutterBREAKVALID   = 1;
  imgGutterBREAKINVAL   = 2;
  imgGutterCOMPLINE     = 3;
  imgGutterEXECLINECL   = 4;
  imgGutterEXECLINEBP   = 5;
  imgGutterEXECLINE     = 6;

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

constructor TGetScriptWin.Create(AOwner: TComponent; AWorkMode: TScriptWorkMode);
begin
  FWorkMode := AWorkMode;
  inherited Create(AOwner);
end;

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

procedure TGetScriptWin.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  LastSearch := '';
  FCurrentFile := TFileManager.Create(Self);
  ActionFileNew.ImageIndex := Ord(ICON_SCRIPTNEW);
  ActionFileOpen.ImageIndex := Ord(ICON_SCRIPTOPEN);
  ActionFileSave.ImageIndex := Ord(ICON_SCRIPTSAVE);
  ActionFileSaveAs.ImageIndex := Ord(ICON_SCRIPTSAVEAS);
  ActionFileProperties.ImageIndex := Ord(ICON_SCRIPTSPROPERTIES);
  ActionEditFind.ImageIndex := Ord(ICON_SCRIPTFIND);
  ActionEditFindNext.ImageIndex := Ord(ICON_SCRIPTFINDNEXT);
  ActionDebugRun.ImageIndex := Ord(ICON_DEBUGRUN);
  ActionDebugStop.ImageIndex := Ord(ICON_DEBUGSTOP);
  ActionDebugBreakpoint.ImageIndex := Ord(ICON_DEBUGBREAKPOINT);
  ActionDebugBreakpointClear.ImageIndex := Ord(ICON_DEBUGBREAKCLEAR);
  ActionDebugStep.ImageIndex := Ord(ICON_DEBUGSTEPOVER);
  ActionDebugRunToCursor.ImageIndex := Ord(ICON_DEBUGRUNTOCURSOR);
  ActionDebugEval.ImageIndex := Ord(ICON_DEBUGEVALUATE);
  ActionDebugWatchAdd.ImageIndex := Ord(ICON_DEBUGWATCHADD);
  ActionDebugWatchRemove.ImageIndex := Ord(ICON_DEBUGWATCHREMOVE);
  ActionDebugWatchClear.ImageIndex := Ord(ICON_DEBUGWATCHCLEAR);
  ActionViewFilter.ImageIndex := Ord(ICON_VIEWFILTER);
  ActionViewList.ImageIndex := Ord(ICON_VIEWLIST);
  ActionViewDetailed.ImageIndex := Ord(ICON_VIEWDETAIL);
  lstScripts.SmallImages := ToolbarImages;
  PickTreeWin := TPickTreeWin.Create(Self);
  PickListWin := TPickListWin.Create(Self);
  ScriptResultsWin := TScriptResultsWin.Create(Self);
  ScriptResultsWin.lstValues.PopupMenu := MenuPopupList;
  ListWin := TListWin.Create(Self);
  ScriptPropertiesWin := TScriptPropertiesWin.Create(Self);
  with PageControl1 do
    for i := 0 to PageCount-1 do
      Pages[i].TabVisible := False;

  ReadScripts; // before inherited, since in inherited it will loadoptions, and check which languages have to be displayed
  inherited;

  with FCurrentFile do
  begin
    with OpenDialog do
    begin
      Filter := DialogScriptFilter;
      Options := DialogOpenOptions;
      DefaultExt := 'ifs';
    end;
    with SaveDialog do
    begin
      Filter := DialogScriptFilter;
      Options := DialogSaveOptions;
      DefaultExt := 'ifs';
    end;
    MessageSaveQuery := Messages.Strings[msgUnsavedFile];
    OnNewFile := Self.OnNewFile;
    OnOpenFile := Self.OnOpenFile;
    OnSaveFile := Self.OnSaveFile;
    OnFileModified := Self.OnModifFile;
    OnFileChange := Self.OnFileChange;
  end;

  PageControl1.Top := ToolbarTabs.Height - 5;
  PageControl1.Height := ClientHeight - 28 - ToolbarTabs.Height;
  PageControl1.Width := ClientWidth + 3;

  FDebugPlugin := TDebugPlugin.Create(EScript);
  FDebugPlugin.WatchList := lstWatch;
  FDebugPlugin.WatchPanel := DockpanelWatch;
  FDebugPlugin.OnGetVariable := GetVariableValue;

  // ifs
  FScript := TIfPasScript.Create(nil);
  with FScript do
  begin
    OnRunLine := OnScriptRunLine;
    OnUses := OnScriptUses;
  end;
  FScriptStatus := iStopped;
  Cl := TIFPSClasses.Create;
  SIRegister_std(Cl);
  SIRegister_stdctrls(Cl);
  SIRegister_Forms(Cl);
  SIRegister_Xml(Cl);
end;

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

procedure TGetScriptWin.Translate;
begin
  Translator.Translate(lstLimitMovies);
  inherited;
end;

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

procedure TGetScriptWin.FormShow(Sender: TObject);
begin
  PickTreeWin.Icon.Assign(Icon);
  PickListWin.Icon.Assign(Icon);
  ScriptResultsWin.Icon.Assign(Icon);
  ToolbarImages.GetIcon(Ord(ICON_SCRIPTSPROPERTIES), ListWin.Icon);
  ToolbarImages.GetIcon(Ord(ICON_SCRIPTSPROPERTIES), ScriptPropertiesWin.Icon);
  inherited;
  lstScripts.SetFocus;
  with ScriptPropertiesWin do
  begin
    Self.lstScripts.Columns[0].Caption := Trim(CopyExceptLastChars(Messages.Strings[msgInfoTitle], 1));
    Self.lstScripts.Columns[1].Caption := Trim(CopyExceptLastChars(Messages.Strings[msgInfoDescr], 1));
  end;
end;

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

procedure TGetScriptWin.FormActivate(Sender: TObject);
begin
  OnActivate := nil;
  lstScripts.Width := 123;
  lstScriptOptions.Width := 123;
  if FCurrentFile.CurrentFile <> '' then
    with Settings.rOptions.rScripting do
      if (FWorkMode = swmGetInfo) and (ScriptAutorun)  then
        ActionDebugRun.Execute;
end;

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

procedure TGetScriptWin.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  with Settings.rOptions do
    case FWorkMode of
      swmGetInfo:   Settings.rScripts.ScriptRemember1 := FCurrentFile.CurrentFile;
      swmScripting: Settings.rScripts.ScriptRemember2 := FCurrentFile.CurrentFile;
    end;
  CanClose := FCurrentFile.Close;
end;

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

procedure TGetScriptWin.FormDestroy(Sender: TObject);
begin
  lstScripts.OnSelectItem := nil;
  FreeAndNil(PickTreeWin);
  FreeAndNil(PickListWin);
  FreeAndNil(ScriptResultsWin);
  FreeAndNil(ScriptPropertiesWin);
  FreeAndNil(ListWin);
  FreeAndNil(FCurrentFile);
  FreeAndNil(FScripts);
  FreeAndNil(FDebugPlugin);
  // ifps
  FScript.Free;
  Cl.Free;
  inherited;
end;

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

procedure TGetScriptWin.LoadOptions;
var
  i, idx: Integer;
  L: TStringList;
begin
  TBCustomLoadPositions(Self, XmlReadInt, XmlReadString, Settings.rScripts.Toolbars);
  DockpanelWatch.Visible := False;
  with Settings.rScripts 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
    if FWorkMode = swmScripting then
    begin
      lstLimitMovies.ItemIndex := TMovieIncludeOption(Includemov);
      CBShowResults.Checked := ShowResScripting;
      CBCloseThis.Checked := CloseWinScripting;
      CBAllowClear.Checked := AllowClearScripting;
    end
    else
    begin
      lstLimitMovies.ItemIndex := mioSelected;
      CBShowResults.Checked := ShowResGetInfo;
      CBCloseThis.Checked := CloseWinGetInfo;
      CBAllowClear.Checked := AllowClearGetInfo;
    end;
    L := TStringList.Create;
    try
      L.Delimiter := '|';
      L.DelimitedText := LangFilterExcl;
      for i := 0 to L.Count-1 do
      begin
        idx := FScripts.Languages.IndexOf(L[i]);
        if idx <> -1 then
          (FScripts.Languages.Objects[idx] as TTBXItem).Checked := False; 
      end;
    finally
      L.Free;
    end;
    if TViewStyle(ListViewStyle) = vsReport then
      ActionViewDetailed.Execute
    else
      ActionViewList.Execute;
    TBMRUList1.Items.Assign(ScriptMRU);
  end; // with
  with Settings.rOptions do
  begin
    TBMRUList1.MaxItems := rFiles.RecentFiles;
    ToolbarScript.Images := ToolbarImages;
    ToolbarEditor.Images := ToolbarImages;
    ToolbarTabs.Images := ToolbarImages;
    ToolbarWatch.Images := ToolbarImages;
    if Settings.rOptions.rDisplay.ImagesInMenu then
      MenuPopupDebug.Images := ToolbarImages;
    with rScripting, http do
    begin
      if Proxy then
      begin
        ProxyParams.BasicAuthentication := True;
        Request.BasicAuthentication := True;
        ProxyParams.ProxyServer := ProxyServer;
        ProxyParams.ProxyPort := ProxyPort;
        ProxyParams.ProxyUsername := ProxyUsername;
        ProxyParams.ProxyPassword := ProxyPassword;
      end else
      begin
        ProxyParams.BasicAuthentication := False;
        Request.BasicAuthentication := False;
      end;
      if HTTP10 then
        ProtocolVersion := pv1_0
      else
        ProtocolVersion := pv1_1;
    end; // with
  end; // with
  UpdateMRU('');
end;

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

procedure TGetScriptWin.SaveOptions;
var
  i: Integer;
begin
  with Settings.rScripts do
  begin
    case self.WindowState of
      wsNormal:
        begin
          WindowState := 1;
          WindowWidth := Width;
          WindowHeight := Height;
        end;
      wsMaximized:
        begin
          WindowState := 2;
        end;
    end; // case
    if FWorkMode = swmScripting then
    begin
      Includemov := Integer(lstLimitMovies.ItemIndex);
      ShowResScripting := CBShowResults.Checked;
      CloseWinScripting := CBCloseThis.Checked;
      AllowClearScripting := CBAllowClear.Checked;
    end
    else
    begin
      ShowResGetInfo := CBShowResults.Checked;
      CloseWinGetInfo := CBCloseThis.Checked;
      AllowClearGetInfo := CBAllowClear.Checked;
    end;
    LangFilterExcl := '';
    for i := 0 to FScripts.Languages.Count-1 do
      if not (FScripts.Languages.Objects[i] as TTBXItem).Checked then
      begin
        if LangFilterExcl <> '' then
          LangFilterExcl := LangFilterExcl + '|';
        LangFilterExcl := LangFilterExcl + FScripts.Languages[i];
      end;
    ListViewStyle := Ord(lstScripts.ViewStyle);
    ScriptMRU.Assign(TBMRUList1.Items);
  end; // with
  FScripts.Save;  
  Settings.rScripts.Toolbars.Clear;
  TBCustomSavePositions(Self, XmlWriteInt, XmlWriteString, Settings.rScripts.Toolbars);
end;

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

procedure TGetScriptWin.ActionDisplayExecute(Sender: TObject);
begin
  with (Sender as TAction) do
  begin
    Checked := True;
    PageControl1.ActivePageIndex := Tag;
  end;
  ToolbarScript.Visible := Sender = ActionDisplayScripts;
  ToolbarEditor.Visible := Sender = ActionDisplayEditor;
end;

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

procedure TGetScriptWin.ActionEditUndoExecute(Sender: TObject);
begin
  EScript.Undo;
end;

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

procedure TGetScriptWin.ActionEditCutExecute(Sender: TObject);
begin
  EScript.CutToClipboard;
end;

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

procedure TGetScriptWin.ActionEditCopyExecute(Sender: TObject);
begin
  EScript.CopyToClipboard;
end;

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

procedure TGetScriptWin.ActionEditPasteExecute(Sender: TObject);
begin
  EScript.PasteFromClipboard;
end;

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

procedure TGetScriptWin.ActionEditDeleteExecute(Sender: TObject);
begin
  EScript.SelText := '';
end;

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

procedure TGetScriptWin.ActionEditSelectAllExecute(Sender: TObject);
begin
  EScript.SelectAll;
end;

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

procedure TGetScriptWin.OnFileChange(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  sbEditor.Panels[pnlEditorFile].Caption := AFileName;
  FDebugPlugin.ClearBreakpoints;
  DebugPlugin.ErrorLine := -1;
  EScriptStatusChange(EScript, [scCaretX, scCaretY, scInsertMode]);
end;

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

procedure TGetScriptWin.OnNewFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
begin
  Result := True;
  EScript.Lines.Text := strDefaultProgram;
  EScript.Modified := False;
  FindScript(AFileName);
end;

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

procedure TGetScriptWin.OnOpenFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
var
  f: TFileStream;
  s: string;
  EndPos: Integer;
begin
  Result := True;
  try
    f := TFileStream.Create(AFileName, fmOpenRead);
    try
      SetLength(s, f.Size);
      f.Read(s[1], f.Size);
      if StartsStr('(*', s) then
      begin
        EndPos := Pos('*)', s);
        if EndPos > 0 then
        begin
          Delete(s, 1, EndPos + 1);
          while StartsStr(sLineBreak, s) do
            Delete(s, 1, Length(sLineBreak));
        end;
      end;
      EScript.Lines.Text := s;
      UpdateMRU(AFileName);
    finally
      f.Free;
    end;
  except
    on e: Exception do
      MessageWin.Execute(e.Message, mtError, [mbOk]);
  end;
end;

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

procedure TGetScriptWin.OnSaveFile(Sender: TObject; AFileName: TFileName; var Result: Boolean);
var
  f: TFileStream;
begin
  Result := True;
  try
    f := TFileStream.Create(AFileName, fmCreate);
    try
      f.Size := 0;
      f.Seek(0, soFromBeginning);
      FCurrentScript.SaveToStream(f);
      EScript.Lines.SaveToStream(f);
    finally
      f.Free;
    end;
    FCurrentScript.Save(AFileName);
    FindScript(AFileName);
    UpdateMRU(AFileName);
  except on e: Exception do
    MessageWin.Execute(e.Message, mtError, [mbOk]);
  end;
end;

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

procedure TGetScriptWin.OnModifFile(Sender: TObject; State: Boolean);
begin
  EScript.Modified := State;
  if State then
    sbEditor.Panels[pnlEditorModified].Caption := Messages.Strings[msgModified]
  else
    sbEditor.Panels[pnlEditorModified].Caption := '';
end;

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

procedure TGetScriptWin.ActionFileNewExecute(Sender: TObject);
begin
  lstScripts.Selected := nil;
  FCurrentFile.New;
end;

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

procedure TGetScriptWin.ActionFileSaveExecute(Sender: TObject);
begin
  FCurrentFile.Save;
end;

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

procedure TGetScriptWin.ActionFileSaveAsExecute(Sender: TObject);
begin
  with FCurrentFile do
  begin
    SaveDialog.InitialDir := Settings.rOptions.rFolders[fuScripts].Value;
    if SaveAs then
    begin
      Settings.rOptions.rFolders[fuScripts].Value := ExtractFilePath(SaveDialog.FileName);
      lstScripts.OnSelectItem := nil;
      lstScripts.Selected := nil;
      lstScripts.OnSelectItem := lstScriptsSelectItem;
    end;
  end;
end;

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

procedure TGetScriptWin.ActionFileOpenExecute(Sender: TObject);
begin
  with FCurrentFile do
  begin
    OpenDialog.InitialDir := Settings.rOptions.rFolders[fuScripts].Value;
    if Open then
    begin
      FindScript(CurrentFile);
      Settings.rOptions.rFolders[fuScripts].Value := ExtractFilePath(OpenDialog.FileName);
    end;
  end;
end;

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

procedure TGetScriptWin.ActionFilePropertiesExecute(Sender: TObject);
var
  CanChange: Boolean;
begin
  if Assigned(FCurrentScript) then
  begin
    if ScriptPropertiesWin.Execute(FCurrentScript, FScripts.Languages) then
    begin
      FCurrentFile.Modified := True;
      CanChange := True;
      tabScriptInfoChange(tabScriptInfo, tabScriptInfo.TabIndex, CanChange); // re-read script info
    end;
    FillOptions; // even if not really modified, options are rebuild when closing the properties window
  end;
end;

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

procedure TGetScriptWin.lstScriptsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
var
  CanChange: Boolean;
begin
  CanChange := False;
  if (Selected) and (Item <> nil) then
    with Item do
      if Selected then
        if Data <> nil then
        begin
          FCurrentFile.Open(TScriptInfo(Data).FullPath);
          FCurrentScript := TScriptInfo(Data);
          CanChange := True;
        end;
  if not CanChange then
    FCurrentFile.New;
  CanChange := True;
  tabScriptInfoChange(tabScriptInfo, tabScriptInfo.TabIndex, CanChange);
  FillFields;
  FillOptions;
end;

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

procedure TGetScriptWin.lstScriptsKeyPress(Sender: TObject; var Key: Char);
begin
  if Word(Key) = VK_RETURN then
    ActionDebugRun.Execute;
end;

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

procedure TGetScriptWin.UpdateMRU(const FileName: string);
begin
  if FileName <> '' then
    TBMRUList1.Add(FileName);
  ActionFileNoRecent.Visible := TBMRUList1.Items.Count = 0;
end;

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

procedure TGetScriptWin.TBMRUList1Click(Sender: TObject; const Filename: string);
begin
  if FCurrentFile.Open(FileName) then
    FindScript(FCurrentFile.CurrentFile);
end;

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

procedure TGetScriptWin.ActionList1Update(Action: TBasicAction; var Handled: Boolean);
begin
  if Action = ActionDebugStop then
  begin
    Handled := True;
    ActionDebugStop.Enabled := FScriptStatus <> iStopped;
  end
  else
  if (Action = ActionDebugRun) or (Action = ActionDebugRunToCursor) then
  begin
    Handled := True;
    TAction(Action).Enabled := FScriptStatus <> iRunning;
  end
  else
  if (Action = ActionDebugStep) or (Action = ActionDebugEval) then
  begin
    Handled := True;
    TAction(Action).Enabled := FScriptStatus = iStepoverWaiting;
  end
  else
  if Action = ActionDebugWatchRemove then
  begin
    Handled := True;
    ActionDebugWatchRemove.Enabled := lstWatch.ItemIndex <> -1;
  end;
end;

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

procedure TGetScriptWin.ActionDebugRunExecute(Sender: TObject);
var
  i: Integer;
  IncOpt: TMovieIncludeOption;
  CurMovie: TMovie;
  LastResult: TScriptResult;
  ShowResultsWindow: Boolean;
begin
  if Sender = ActionDebugRunToCursor then
    FDebugPlugin.CursorLine := EScript.CaretY
  else
    FDebugPlugin.CursorLine := -1;
  if FScriptStatus = iStepOverWaiting then
  begin
    FScriptStatus := iRunning;
    ActionDebugRun.Update;
    ActionDebugStop.Update;
    EScript.InvalidateGutterLine(DebugPlugin.CurrentLine);
    EScript.InvalidateLine(DebugPlugin.CurrentLine);
    Exit;
  end
  else
  if FScriptStatus = iRunning then
  begin
    Exit;
  end;
  FScriptStatus := iRunning;
  ActionDebugRun.Update;
  ActionDebugStop.Update;
  EScript.PopupMenu := MenuPopupDebug;
  try
    if FCurrentScript = nil then
      Exit;
    SaveScriptFields;
    ShowResultsWindow := CBShowResults.Checked;
    LastResult := srSave;
    try
      FRunForCount := 0;
      FScript.SetText(EScript.Lines.Text);
      if FScript.ErrorCode = ENoError then
      begin
        EScript.ReadOnly := True;
        try
          IncOpt := lstLimitMovies.ItemIndex;
          FMovieListFiltered := TList.Create;
          try
            FMovieList.MakeFilteredList(FMovieListFiltered, IncOpt);
            if FMovieListFiltered.Count = 0 then
            begin
              MessageWin.Execute(Format(Messages.Strings[msgNoMovieFound], [lstLimitMovies.grp.Caption, lstLimitMovies.ItemIndexCaption]), mtWarning, [mbOk]);
              Abort;
            end;
            ScriptResultsWin.Init(AllFields - FCurrentScript.Fields.Excluded, FCurrentScript.Fields.Picture, FCurrentCatalog);
            btn2.ModalResult := mrOk;
            for i := 0 to FMovieListFiltered.Count-1 do
            begin
              CurMovie := TMovie(FMovieListFiltered[i]);
              ScriptResultsWin.CopyFrom(CurMovie);
              Inc(FRunForCount);
              FScript.RunScript;
              if FScriptStatus = iStopped then // stopped by user
              begin
                LastResult := srAbort;
                Break;
              end;
              if FScript.ErrorCode <> ENoError then
                Break;
              LastResult := ScriptResultsWin.Execute(ShowResultsWindow and (LastResult <> srSaveAll), FCurrentScript.Properties.Title);
              case LastResult of
                srSave,
                srSaveAll:
                  ScriptResultsWin.CopyTo(CurMovie, CBAllowClear.Checked);
                srAbort:
                  Break;
              end;
            end;
          finally
            FreeAndNil(FMovieListFiltered);
          end;
        finally
          EScript.ReadOnly := False;
        end;
      end;
      if (FScript.ErrorCode <> ENoError) then
      begin
        LastResult := srAbort;
        ActionDisplayExecute(ActionDisplayEditor);
        with EScript.CharIndexToRowCol(FScript.ErrorPos) do
        begin
          EScript.CaretX := Char;
          EScript.CaretY := Line;
          DebugPlugin.ErrorLine := Line;
          EScript.InvalidateGutterLine(Line);
          EScript.InvalidateLine(Line);
        end;
        EScript.Perform(EM_SCROLLCARET, 0, 0);
        EScript.SetFocus;
        with FScript do
          MessageWin.Execute(Format(Messages.Strings[msgScriptError], [ErrorModule, ErrorToString(ErrorCode, ErrorString), EScript.CaretY]), mtError, [mbOk]);
      end;
    finally
      Application.ProcessMessages;
      FScript.Cleanup;
      EScript.Invalidate;
      FCurrentScript.Save;
    end; // try
  finally
    FScriptStatus := iStopped;
    EScript.PopupMenu := MenuPopupEdit;
  end;
  if (LastResult <> srAbort) and (CBCloseThis.Checked) then
    PostMessage(Self.Handle, WM_CLOSEAFTERRUN, 0, 0);
  ActionDebugRun.Update;
  ActionDebugStop.Update;
end;

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

procedure TGetScriptWin.CloseAfterRun(var Msg: TMessage);
begin
  btn2.Click;
end;

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

procedure TGetScriptWin.ActionDebugStopExecute(Sender: TObject);
begin
  FScriptStatus := iStopped;
  ActionDebugRun.Update;
  ActionDebugStop.Update;
end;

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

procedure TGetScriptWin.ActionDebugBreakpointExecute(Sender: TObject);
begin
  // F5 key
  case PageControl1.ActivePageIndex of
    0:  FillScripts;
    1:  FDebugPlugin.ToggleBreakpoint(EScript.CaretY);
  end;
end;

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

procedure TGetScriptWin.ActionDebugStepExecute(Sender: TObject);
begin
  FScriptStatus := iStepOver;
  ActionDebugRun.Update;
  ActionDebugStop.Update;
end;

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

procedure TGetScriptWin.ActionDebugEvalExecute(Sender: TObject);
var
  VarName: string;
begin
  VarName := EScript.WordAtCursor;
  MessageWin.Execute(GetVariableValue(Self, VarName), VarName, [mbOk]);
end;

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

procedure TGetScriptWin.ActionDebugBreakpointClearExecute(Sender: TObject);
begin
  FDebugPlugin.ClearBreakpoints;
  EScript.Invalidate;
end;

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

procedure TGetScriptWin.ActionDebugWatchAddExecute(Sender: TObject);
begin
  FDebugPlugin.AddWatch(EScript.WordAtCursor);
end;

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

procedure TGetScriptWin.ActionDebugWatchRemoveExecute(Sender: TObject);
begin
  FDebugPlugin.DeleteWatch;
end;

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

procedure TGetScriptWin.ActionDebugWatchClearExecute(Sender: TObject);
begin
  FDebugPlugin.ClearWatches;
end;

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

function TGetScriptWin.FindScript(const AFile: TFileName): Boolean;
var
  i: Integer;
  CanChange: Boolean;
begin
  lstScripts.OnSelectItem := nil;
  try
    lstScripts.Selected := nil;
    Result := False;
    if AFile <> '' then
      with lstScripts.Items do
        for i := 0 to Count-1 do
          with Item[i] do
            if (Data <> nil) and (SameText(TScriptInfo(Data).FullPath, AFile)) then
            begin
              FCurrentScript := TScriptInfo(Data);
              lstScripts.Selected := Item[i];
              Focused := True;
              MakeVisible(False);
              Result := True;
              Break;
            end;
    if not Result then
    begin
      FCurrentScript := FScripts.Find(AFile);
      if FCurrentScript = nil then
      begin
        FCurrentScript := FScripts.Add(AFile);
      end;
    end;
    CanChange := True;
    tabScriptInfoChange(tabScriptInfo, tabScriptInfo.TabIndex, CanChange);
    FillFields;
    FillOptions;
  finally
    lstScripts.OnSelectItem := lstScriptsSelectItem;
  end;
end;

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

function TGetScriptWin.Execute(const Catalog: TFileManager; AMovieList: TMovieList): TModalResult;
var
  ToLoad: TFileName;
begin
  FCurrentCatalog := Catalog;
  FMovieList := AMovieList;
  FillScripts;
  FillFields;
  FillOptions;
  lstLimitMovies.SetCount(aMovieList);
  ActionDisplayExecute(ActionDisplayScripts);
  ScriptResultsWin.GenerateFields(FMovieList.CustomFieldsProperties);
  with Settings do
    case FWorkMode of
      swmGetInfo:   ToLoad := rScripts.ScriptRemember1;
      swmScripting: ToLoad := rScripts.ScriptRemember2;
    else
      ToLoad := ''
    end;
  if (ToLoad <> '') and FileExists(ToLoad) and FCurrentFile.Open(ToLoad) then
  begin
    FindScript(ToLoad)
  end
  else
    FCurrentFile.New;
  Result := ShowModal();
end;

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

procedure TGetScriptWin.btn1Click(Sender: TObject);
begin
  if (ActionDisplayEditor.Checked) then
    functions_files.LaunchHelp(1073) // tech info
  else
    functions_files.LaunchHelp(1080); // general info
end;

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

procedure TGetScriptWin.ActionListCheckExecute(Sender: TObject);
var
  i: Integer;
  bState: Boolean;
begin
  if Sender is TAction then
    if TAction(Sender).ActionComponent is TTBXItem then
      if MenuPopupList.Items.ContainsItem(TTBXItem(TAction(Sender).ActionComponent)) then
      begin
        bState := (Sender = ActionListCheck);
        if MenuPopupList.PopupComponent is TListView then
          with TListView(MenuPopupList.PopupComponent) do
            for i := 0 to Items.Count-1 do
              if Items[i].Selected then
                Items[i].Checked := bState;
      end;
end;

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

procedure TGetScriptWin.ActionListAllExecute(Sender: TObject);
var
  i: Integer;
  bState: Boolean;
begin
  bState := (Sender = ActionListAll);
  if Sender is TAction then
    if TAction(Sender).ActionComponent is TTBXItem then
      if MenuPopupList.Items.ContainsItem(TTBXItem(TAction(Sender).ActionComponent)) then
      begin
        if MenuPopupList.PopupComponent is TListView then
          with TListView(MenuPopupList.PopupComponent) do
            for i := 0 to Items.Count-1 do
              Items[i].Checked := bState;
      end
      else
      if MnuScrFlt.ContainsItem(TTBXItem(TAction(Sender).ActionComponent)) then
      begin
        for i := 0 to MnuScrFlt.Count-1 do
          if MnuScrFlt.Items[i].Tag > 0 then
            MnuScrFlt.Items[i].Checked := bState;
        ActionViewFilterChange.Execute;
      end;
end;

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

procedure TGetScriptWin.ActionEditFindExecute(Sender: TObject);
begin
  if EScript.SelAvail and (EScript.BlockBegin.Line = EScript.BlockEnd.Line)
  then
    LastSearch := EScript.SelText
  else
    LastSearch := EScript.WordAtCursor;
  if InputWin.Execute(Messages.Strings[msgFind], Messages.Strings[msgFindtext], LastSearch) then
    if LastSearch <> '' then
      ActionEditFindNextExecute(ActionEditFindNext);
end;

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

procedure TGetScriptWin.ActionEditFindNextExecute(Sender: TObject);
begin
  if LastSearch = '' then
  begin
    ActionEditFindExecute(ActionEditFind);
    Exit;
  end else
  begin
    if EScript.SearchReplace(LastSearch, '', []) = 0 then
      MessageWin.Execute(Format(Messages.Strings[msgNoMoreMatches], [LastSearch]), mtInformation, [mbOk]);
  end;
end;

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

procedure TGetScriptWin.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if ((Shift = [ssCtrl]) or (Shift = [ssCtrl, ssShift])) and (Key = VK_TAB) then
    case PageControl1.ActivePageIndex of
      0:  ActionDisplayExecute(ActionDisplayEditor);
      1:  ActionDisplayExecute(ActionDisplayScripts);
    end
end;

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

procedure TGetScriptWin.FillFields;
var
  NewItem: TListItem;
  f: Integer;
begin
  with lstLimitFields.Items do
  begin
    BeginUpdate;
    lstLimitFields.ViewStyle := vsIcon;
    try
      Clear;
      if FCurrentScript <> nil then
      begin
        NewItem := Add;
        NewItem.Caption := strFieldPicture;
        NewItem.Data := Pointer(fieldPicture);
        NewItem.Checked := FCurrentScript.Fields.Picture;
        for f := fieldLow to fieldCount-1 do
          if not (f in VirtualFields) then
          begin
            NewItem := Add;
            NewItem.Caption := strFields[f];
            NewItem.Data := Pointer(f);
            NewItem.Checked := not (f in FCurrentScript.Fields.Excluded);
          end;
      end;
      with FMovieList.CustomFieldsProperties do
        for f := 0 to Count-1 do
        begin
          NewItem := lstLimitFields.Items.Add;
          NewItem.Caption := Objects[f].FieldName + ' (' + Objects[f].FieldTag + ')';
          NewItem.Data := Pointer(customFieldLow+f);
          NewItem.Checked := not Objects[f].ExcludedInScripts;
        end;
      lstLimitFields.ViewStyle := vsSmallIcon;
    finally
      EndUpdate;
    end;
  end;
end;

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

procedure TGetScriptWin.FillOptions;
var
  NewItem: TListItem;
  i: Integer;
begin
  lstScriptOptions.Items.BeginUpdate;
  try
    lstScriptOptions.Clear;
    if FCurrentScript <> nil then
      for i := 0 to FCurrentScript.Options.Count-1 do
      begin
        NewItem := lstScriptOptions.Items.Add;
        NewItem.Caption := FCurrentScript.Options[i].Name;
        NewItem.SubItems.Add(IntToStr(FCurrentScript.Options[i].Value));
        NewItem.Data := FCurrentScript.Options[i];
      end;
  finally
    lstScriptOptions.Items.EndUpdate;
  end;
  lstScriptOptions.Width := 123;
end;

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

procedure TGetScriptWin.SaveScriptFields;
var
  i, f: Integer;
  UncheckedFields: TMovieFields;
begin
  SaveCustomFields;
  if FCurrentScript = nil then
    Exit;
  UncheckedFields := [];
  for i := 0 to lstLimitFields.Items.Count-1 do
  begin
    f := Integer(lstLimitFields.Items[i].Data);
    if f = fieldPicture then
      FCurrentScript.Fields.Picture := lstLimitFields.Items[i].Checked
    else if f in AllFields then
      if not lstLimitFields.Items[i].Checked then
        Include(UncheckedFields, f);
  end;
  FCurrentScript.Fields.Excluded := UncheckedFields;
  FCurrentScript.Save;
end;

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

procedure TGetScriptWin.SaveCustomFields;
var
  i, f: Integer;
begin
  for i := 0 to lstLimitFields.Items.Count-1 do
  begin
    f := Integer(lstLimitFields.Items[i].Data);
    if f in AllCustomFields then
      if FMovieList.CustomFieldsProperties.Objects[f-customFieldLow].
        ExcludedInScripts <> not lstLimitFields.Items[i].Checked then
      begin
        FMovieList.CustomFieldsProperties.Objects[f-customFieldLow].
          ExcludedInScripts := not lstLimitFields.Items[i].Checked;
        FCurrentCatalog.Modified := True;
      end;
  end;
end;

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

procedure TGetScriptWin.lstLimitFieldsMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  SaveCustomFields;
end;

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

procedure TGetScriptWin.ActionViewFilterExecute(Sender: TObject);
begin
  //
end;

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

procedure TGetScriptWin.ActionViewFilterChangeExecute(Sender: TObject);
begin
  FillScripts;
end;

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

procedure TGetScriptWin.ActionViewListExecute(Sender: TObject);
begin
  if ActionViewList.Checked then
  begin
    lstScripts.ViewStyle := vsList;
    lstScripts.OnInfoTip := lstScriptsInfoTip;
  end
  else
  begin
    lstScripts.ViewStyle := vsReport;
    lstScripts.OnInfoTip := nil;
  end;
  lstScripts.Width := 123;
end;

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

procedure TGetScriptWin.ReadScripts;
var
  NewItem: TTBXItem;
  i: Integer;
begin
  FScripts := TScriptList.Create(strDirApp + strDirScripts);
  for i := 0 to FScripts.Languages.Count-1 do
  begin
    NewItem := TTBXItem.Create(MnuScrFlt);
    NewItem.Caption := FScripts.Languages[i];
    NewItem.OnClick := ActionViewFilterChangeExecute;
    NewItem.Checked := True;
    NewItem.AutoCheck := True;
    NewItem.Tag := i + 1;
    FScripts.Languages.Objects[i] := NewItem;
    MnuScrFlt.Add(NewItem);
  end;
end;

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

procedure TGetScriptWin.FillScripts;
var
  NewItem: TListItem;
  CurScript: TScriptInfo;
  i, idx: Integer;
begin
  with lstScripts.Items do
  begin
    BeginUpdate;
    lstScripts.ViewStyle := vsSmallIcon;
    try
      Clear;
      for i := 0 to FScripts.Count-1 do
      begin
        CurScript := FScripts[i] as TScriptInfo;
        if CurScript.FileName = '' then
          Continue;
        if (FWorkMode = swmGetInfo) and (not CurScript.Properties.GetInfo) then
          Continue;
        idx := FScripts.Languages.IndexOf(CurScript.Properties.Language);
        if (CurScript.Properties.Language <> '') and (idx <> -1) and not (FScripts.Languages.Objects[idx] as TTBXItem).Checked then
          Continue;
        NewItem := Add;
        NewItem.Caption := CurScript.Properties.Title;
        if NewItem.Caption = '' then
          NewItem.Caption := CurScript.FileName;
        NewItem.SubItems.Text := CurScript.Properties.Description;
        NewItem.Data := CurScript;
        if CurScript.Properties.GetInfo then
          NewItem.ImageIndex := Ord(ICON_MOVIEIMPORTSCRIPT)
        else
          NewItem.ImageIndex := Ord(ICON_SCRIPTING);
      end;
      if ActionViewDetailed.Checked then
        lstScripts.ViewStyle := vsReport
      else
        lstScripts.ViewStyle := vsList;
    finally
      EndUpdate;
    end;
  end;
  lstScripts.AlphaSort;
  lstScripts.Width := 123;
end;

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

procedure TGetScriptWin.tabScriptInfoChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
begin
  AllowChange := True;
  lblScriptInfo.Caption := '';
  if {(lstScripts.Selected <> nil) and} (FCurrentScript <> nil) then
  begin
    case NewTab of
      0:
        with FCurrentScript.Properties, ScriptPropertiesWin.Messages do
        begin
          lblScriptInfo.Caption :=
            Format('%s %s<br>', [Strings[msgInfoAuthors], Authors]) +
            Format('%s <link>%s</link><br>', [Strings[msgInfoSite], Site]) +
            Format('%s %s<br>', [Strings[msgInfoLanguage], Language]) +
            Format('%s %s<br>', [Strings[msgInfoVersion], Version]) +
            Format('%s Ant Movie Catalog %s', [Strings[msgInfoRequires], Requires]);
        end;
      1:
        lblScriptInfo.Caption := StringReplace(FCurrentScript.Properties.Comments, '|', '<br>', [rfReplaceAll]);
      2:
        lblScriptInfo.Caption := StringReplace(FCurrentScript.Properties.License, '|', '<br>', [rfReplaceAll]);
    end;
  end;
end;

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

procedure TGetScriptWin.lblScriptInfoLinkClick(Sender: TObject; LinkNumber: Integer; LinkText: String);
begin
  if Pos('://', LinkText) > 0 then
    LaunchProg(LinkText)
  else
  if Pos('@', LinkText) > 0 then
    LaunchProg('mailto:' + LinkText)
  else
    LaunchProg('http://' + LinkText)
end;

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

procedure TGetScriptWin.ActionOptionsEditExecute(Sender: TObject);
var
  CurOption: TScriptOption;
  i, idx, res: Integer;
begin
  if lstScriptOptions.Selected <> nil then
  begin
    CurOption := TScriptOption(lstScriptOptions.Selected.Data);
    ListWin.Caption := Format(Messages.Strings[msgValueForOption], [CurOption.Name]);
    with ListWin.lst.Items do
    begin
      idx := -1;
      BeginUpdate;
      try
        Clear;
        for i := 0 to Length(CurOption.Values)-1 do
        begin
          res := AddObject(Format('%d -> %s', [CurOption.Values[i].Value, CurOption.Values[i].Description]), Pointer(CurOption.Values[i].Value));
          if CurOption.Values[i].Value = CurOption.Value then
            idx := res;
        end;
      finally
        EndUpdate;
      end;
      ListWin.lst.ItemIndex := idx;
    end;
    ListWin.FitToContents;
    if ListWin.Execute then
    begin
      idx := ListWin.lst.ItemIndex;
      if idx = -1 then
        Exit;
      CurOption.Value := Integer(ListWin.lst.Items.Objects[idx]);
      lstScriptOptions.Selected.SubItems[0] := IntToStr(CurOption.Value);
    end;
  end;
end;

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

procedure TGetScriptWin.ActionOptionsDefaultExecute(Sender: TObject);
var
  i: Integer;
begin
  if FCurrentScript <> nil then
  begin
    for i := 0 to FCurrentScript.Options.Count-1 do
      FCurrentScript.Options[i].Value := FCurrentScript.Options[i].DefValue;
    FillOptions;
  end;
end;

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

procedure TGetScriptWin.lstScriptOptionsKeyPress(Sender: TObject; var Key: Char);
begin
  if Word(Key) in [VK_RETURN, VK_SPACE] then
    ActionOptionsEdit.Execute;
end;

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

procedure TGetScriptWin.lstScriptOptionsInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
var
  CurOption: TScriptOption;
  i: Integer;
begin
  CurOption := TScriptOption(Item.Data);
  InfoTip := Format('%s = %d', [CurOption.Name, CurOption.Value]);
  for i := 0 to Length(CurOption.Values)-1 do
  begin
    if CurOption.Values[i].Value = CurOption.Value then
    begin
      InfoTip := Format('%s%s%s', [InfoTip, sLineBreak, CurOption.Values[i].Description]);
      Break;
    end;
  end;
end;

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

procedure TGetScriptWin.lstScriptsInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
var
  CurScript: TScriptInfo;
begin
  CurScript := TScriptInfo(Item.Data);
  InfoTip := CurScript.Properties.Description;
end;

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

procedure TGetScriptWin.lstWatchKeyPress(Sender: TObject; var Key: Char);
begin
  if Word(Key) = VK_DELETE then
    ActionDebugWatchRemove.Execute;
end;

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

procedure TGetScriptWin.EScriptGutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark);
begin
  if X <= EScript.Gutter.LeftOffset then
    FDebugPlugin.ToggleBreakpoint(Line);
end;

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

procedure TGetScriptWin.EScriptSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor);
begin
  if (FScriptStatus in [iStepOver, iStepOverWaiting]) and (Line = DebugPlugin.CurrentLine) then
  begin
    Special := True;
    FG := clWhite;
    BG := clNavy;
  end
  else
  if FDebugPlugin.IsBreakpoint(Line) then
  begin
    Special := True;
    FG := clWhite;
    BG := clRed;
  end
  else
  if (DebugPlugin.ErrorLine <> -1) and (Line = DebugPlugin.ErrorLine) then
  begin
    Special := True;
    FG := clWhite;
    BG := clMaroon;
  end
end;

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

procedure TGetScriptWin.EScriptGutterPaint(Sender: TObject; aLine, X, Y: Integer);
var
  IconIndex: Integer;
begin
  IconIndex := -1;
  if DebugPlugin.IsBreakpoint(ALine) then
  begin
    if FScriptStatus = iStopped then
      IconIndex := imgGutterBREAK
    else
    begin
      if DebugPlugin.CurrentLine = ALine then
        IconIndex := imgGutterEXECLINEBP
      else
        IconIndex := imgGutterBREAKVALID
    end;
  end
  else
  begin
    if (FScriptStatus = iStepoverWaiting) and (DebugPlugin.CurrentLine = ALine) then
      IconIndex := imgGutterEXECLINE;
  end;
  if IconIndex <> -1 then
    lstDebugImages.Draw(EScript.Canvas, X, Y, IconIndex);
end;

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

procedure TGetScriptWin.EScriptStatusChange(Sender: TObject; Changes: TSynStatusChanges);
var
  i: Integer;
begin
  if (scCaretX in Changes) or (scCaretY in Changes) then
  begin
    sbEditor.Panels[pnlEditorPos].Caption := Format('%d:%d', [EScript.CaretX, EScript.CaretY]);
    if DebugPlugin.ErrorLine <> -1 then
    begin
      i := DebugPlugin.ErrorLine;
      DebugPlugin.ErrorLine := -1;
      EScript.InvalidateGutterLine(i);
      EScript.InvalidateLine(i);
    end;
  end;
  if (scModified in Changes) then
  begin
    FCurrentFile.Modified := EScript.Modified;
  end;
end;

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

procedure TGetScriptWin.OnCancelDownload(Sender: TObject);
begin
  if Assigned(DownloadThread) then
  begin
    http.DisconnectSocket;
  end;
  if Assigned(ProgressWin) then
  begin
    ProgressWin.OnCancel := nil;
    ProgressWin.Close;
  end;
  Application.ProcessMessages;
  DownloadState := dsCanceled;
end;

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

procedure TGetScriptWin.OnThreadEnd(Sender: TObject);
begin
  if Assigned(DownloadThread) then // if nil then it has been canceled before
    with DownloadThread do
    begin
      DownloadState := FState;
      DownloadResult := '';
      case FState of
        dsFinished:
          begin
            DownloadResult := FResult;
          end;
        dsFailed:
          begin
            MessageWin.Execute(FResult, mtError, [mbOk]);
          end;
      end;
    end;
  DownloadThread := nil;
end;

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

procedure TGetScriptWin.lstScriptsCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
  Sender.Canvas.Font.Color := clWindowText;
  if (Item <> nil) then
  begin
    if TScriptInfo(Item.Data).Properties.OldFormat then
    begin
      Sender.Canvas.Font.Color := clGrayText;
    end;
  end;
  DefaultDraw := True;
end;

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

function TGetScriptWin.GetVariableValue(Sender: TObject; const VarName: string): string;
var
  v: PIfVariant;
begin
  Result := '?';
  v := FScript.GetVariable(VarName);
  if v <> nil then
  begin
    if IsIntegerType(v) then
      Result := IntToStr(GetInteger(v))
    else
    if IsStringType(v) then
      Result := QuotedStr(GetString(v))
    else
    if IsRealType(v) then
      Result := Format('%g', [GetReal(v)])
    else
    if IsBooleanType(v) then
      Result := BoolToStr(GetBoolean(v), True)
  end;
end;

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

function TGetScriptWin.HasRemainingMovies: Boolean;
begin
  Result := (FMovieListFiltered <> nil) and (FRunForCount < FMovieListFiltered.Count);
end;

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

function TGetScriptWin.GetCurrentLine: Integer;
begin
  Result := DebugPlugin.CurrentLine;
end;

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

procedure TGetScriptWin.SetCurrentLine(const Value: Integer);
begin
  if FScriptStatus <> iRunning then
  begin
    EScript.InvalidateGutterLine(FDebugPlugin.CurrentLine);
    EScript.InvalidateLine(FDebugPlugin.CurrentLine);
  end;
  FDebugPlugin.CurrentLine := EScript.CharIndexToRowCol(Value).Line;
  if ((FDebugPlugin.CursorLine <> -1) and (FDebugPlugin.CursorLine = FDebugPlugin.CurrentLine))
    or (FDebugPlugin.IsBreakpoint(FDebugPlugin.CurrentLine))
    or (FScriptStatus = iStepOver) then
  begin
    FScriptStatus := iStepOverWaiting;
    ActionDebugRun.Update;
    ActionDebugStop.Update;
    EScript.InvalidateGutterLine(FDebugPlugin.CurrentLine);
    EScript.InvalidateLine(FDebugPlugin.CurrentLine);
    EScript.CaretX := 0;
    EScript.CaretY := FDebugPlugin.CurrentLine;
    FDebugPlugin.UpdateWatches;
    while FScriptStatus = iStepOverWaiting do
    begin
      Application.HandleMessage;
    end;
  end;
end;

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

function GetPage(const address, referer, cookies: string): string;
var
  i: Integer;
begin
  GetScriptWin.http.Request.ContentType := '*/*';
  GetScriptWin.http.Request.Referer := referer;
  i := GetScriptWin.http.Request.CustomHeaders.IndexOfName('Cookie');
  if i <> -1 then
    GetScriptWin.http.Request.CustomHeaders.Delete(i);
  if cookies <> '' then
  begin
    GetScriptWin.http.Request.CustomHeaders.Values['Cookie'] := cookies;
  end;
  GetScriptWin.http.HTTPOptions := GetScriptWin.http.HTTPOptions - [hoKeepOrigProtocol];
  Result := '';
  with ProgressWin do
  begin
    Maximum := 1;
    IntProgress := 0;
    Status := 'Importing data from internet...';
    Execute(GetScriptWin);
    try
      Application.ProcessMessages;
      DownloadThread := TDownloadThread.Create(True);
      with DownloadThread do
      begin
        FState := dsNone;
        FURL := address;
        FToDo := daGetPage;
        FHTTP := GetScriptWin.http;
        OnTerminate := GetScriptWin.OnThreadEnd;
        ProgressWin.OnCancel := GetScriptWin.OnCancelDownload;
        DownloadState := dsBusy;
        Resume;
      end;
      IntProgress := 1;
      while DownloadState = dsBusy do
        Application.HandleMessage;
      if DownloadState = dsFinished then
        Result := AdjustLineBreaks(DownloadResult);
    finally
      OnCancel := nil;
      Close;
      Application.ProcessMessages;
    end;
  end;
end;

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

function PostPage(const address, params, content, referer: string; forceHTTP11: Boolean; forceEncodeParams: Boolean): string;
begin
  GetScriptWin.http.Request.ContentType := content;
  GetScriptWin.http.Request.Referer := referer;
  if forceHTTP11 then
    GetScriptWin.http.HTTPOptions := GetScriptWin.http.HTTPOptions + [hoKeepOrigProtocol]
  else
    GetScriptWin.http.HTTPOptions := GetScriptWin.http.HTTPOptions - [hoKeepOrigProtocol];
  if forceEncodeParams then
    GetScriptWin.http.HTTPOptions := GetScriptWin.http.HTTPOptions + [hoForceEncodeParams]
  else
    GetScriptWin.http.HTTPOptions := GetScriptWin.http.HTTPOptions - [hoForceEncodeParams];
  Result := '';
  with ProgressWin do
  begin
    Maximum := 1;
    IntProgress := 0;
    Status := 'Importing data from internet...';
    Execute(GetScriptWin);
    try
      Application.ProcessMessages;
      DownloadThread := TDownloadThread.Create(True);
      with DownloadThread do
      begin
        FState := dsNone;
        FURL := address;
        FParams := params;
        FToDo := daPostPage;
        FHTTP := GetScriptWin.http;
        OnTerminate := GetScriptWin.OnThreadEnd;
        ProgressWin.OnCancel := GetScriptWin.OnCancelDownload;
        DownloadState := dsBusy;
        Resume;
      end;
      IntProgress := 1;
      while DownloadState = dsBusy do
        Application.HandleMessage;
      if DownloadState = dsFinished then
        Result := AdjustLineBreaks(DownloadResult);
    finally
      OnCancel := nil;
      Close;
      Application.ProcessMessages;
    end;
  end;
end;

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

procedure GetPicture(const address, referer: string);
var
  Stream: TMemoryStream;
begin
  GetScriptWin.http.Request.Referer := referer;
  with ProgressWin do
  begin
    Maximum := 1;
    IntProgress := 0;
    Status := 'Importing picture from internet...';
    Stream := TMemoryStream.Create;
    Execute(GetScriptWin);
    try
      Application.ProcessMessages;
      DownloadThread := TDownloadThread.Create(True);
      with DownloadThread do
      begin
        FState := dsNone;
        FURL := address;
        FToDo := daGetFile;
        FHTTP := GetScriptWin.http;
        FStream := Stream;
        OnTerminate := GetScriptWin.OnThreadEnd;
        DownloadState := dsBusy;
        Resume;
      end;
      IntProgress := 1;
      while DownloadState = dsBusy do
        Application.HandleMessage;
      if DownloadState = dsFinished then
      begin
        ScriptResultsWin.SetPicture(Stream, address);
      end;
    finally
      Close;
      Stream.Free;
      Application.ProcessMessages;
    end;
  end;
end;

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

function OnScriptRunLine(id: Pointer; Sender: TIfPasScript; Position: Longint): TCs2Error;
begin
  Result := Sender.ErrorCode;
  Application.ProcessMessages;
  GetScriptWin.CurrentLine := Position;
  if FScriptStatus = iStopped then
    Result := EExitCommand
end;

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

function OnScriptUses(id: Pointer; Sender: TIfPasScript; Name: string): TCs2Error;
var
  SecondEngine: TIfPasScript;
  f: TFileStream;
  s: string;
begin
  if Name = 'SYSTEM' then
  begin
    RegisterStdLib(Sender, False);
    RegisterDateTimeLib(Sender);
    RegisterEClasses(Sender, Cl);
    RegisterDelphiFunction(Sender, 'function AnsiUpperCase(Value: string): string;', @AnsiUpperCase);
    RegisterDelphiFunction(Sender, 'function AnsiLowerCase(Value: string): string;', @AnsiLowerCase);
    RegisterDelphiFunction(Sender, 'function FileExists(FileName: string): Boolean;', @FileExists);
    RegisterDelphiFunction(Sender, 'function DirectoryExists(DirName: string): Boolean;', @DirectoryExists);
    RegisterDelphiFunction(Sender, 'function ExtractFileName(AFileName: string): string;', @ExtractFileName);
    RegisterDelphiFunction(Sender, 'function ExtractFileExt(AFileName: string): string;', @ExtractFileExt);
    RegisterDelphiFunction(Sender, 'function ExtractFilePath(AFileName: string): string;', @ExtractFilePath);
    RegisterDelphiFunction(Sender, 'function ChangeFileExt(AFileName: string; AExt: string): string;', @ChangeFileExt);
    RegisterDelphiFunction(Sender, 'function IncludeTrailingPathDelimiter(AFileName: string): string;', @IncludeTrailingPathDelimiter);
    RegisterDelphiFunction(Sender, 'function ExcludeTrailingPathDelimiter(AFileName: string): string;', @ExcludeTrailingPathDelimiter);
    with Sender do
    begin
      AddFunction(@OnScriptRegProc, 'procedure ShowMessage(message: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure ShowError(message: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure ShowInformation(message: string);', nil);
      AddFunction(@OnScriptRegProc, 'function ShowWarning(message: string): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function ShowConfirmation(message: string): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function Input(caption, prompt: string; var value: string): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function GetPage(address: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function GetPage2(address: string; referer: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function GetPage3(address: string; referer: string; cookies: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function PostPage(address: string; params: string): string', nil);
      AddFunction(@OnScriptRegProc, 'function PostPage2(address: string; params: string; content: string; referer: string; forceHTTP11: Boolean; forceEncodeParams: Boolean): string;', nil);
      AddFunction(@OnScriptRegProc, 'procedure GetPicture(address: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure GetPicture2(address: string; referer: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure ImportPicture(filename: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure ExportPicture(dir: string; name: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure HTMLDecode(var Value: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure HTMLRemoveTags(var Value: string);', nil);
      AddFunction(@OnScriptRegProc, 'function URLEncode(source: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function URLDecode(source: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'procedure SetField(field: Integer; value: string);', nil);
      AddFunction(@OnScriptRegProc, 'procedure SetCustomField(fieldTag: string; value: string);', nil);
      AddFunction(@OnScriptRegProc, 'function CanSetField(field: Integer): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function CanSetCustomField(fieldTag: String): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function CustomFieldExists(fieldTag: String): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function CanSetPicture: Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function GetField(field: Integer): string;', nil);
      AddFunction(@OnScriptRegProc, 'function GetCustomField(fieldTag: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function GetOption(OptName: string): Integer;', nil);
      AddFunction(@OnScriptRegProc, 'function StringReplace(S, Old, New: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'procedure Error;', nil);
      AddFunction(@OnScriptRegProc, 'procedure Sleep(ATime: Integer);', nil);
      AddFunction(@OnScriptRegProc, 'procedure Launch(command: string; parameters: string);', nil);
      AddFunction(@OnScriptRegProc, 'function CheckVersion(Major, Minor, Revision: Integer): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function AnsiUpFirstLetter(Value: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function AnsiMixedCase(Value: string; Delimiters: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function UTF8Encode(Value: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function UTF8Decode(Value: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function AcceptLicense(LicenseVersion: Integer): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'procedure SetStatic(AName: string; AValue: string);', nil);
      AddFunction(@OnScriptRegProc, 'function GetStatic(AName: string): string;', nil);
      AddFunction(@OnScriptRegProc, 'function DeleteFile(AFileName: string): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function CopyFile(ASourceFileName: string; ATargetFileName: string; SkipIfExists: Boolean): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function MoveFile(ASourceFileName: string; ATargetFileName: string): Boolean;', nil);
      AddFunction(@OnScriptRegProc, 'function ListDirectory(ADir: string; AMask: string): string;', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickTreeClear;', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickTreeAdd(Caption, Address: string);', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickTreeMoreLink(Address: string);', nil);
      AddFunction(@OnScriptRegPickProc, 'function PickTreeExec(var Address: string): Boolean;', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickTreeSort;', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickListClear;', nil);
      AddFunction(@OnScriptRegPickProc, 'procedure PickListAdd(Text: string);', nil);
      AddFunction(@OnScriptRegPickProc, 'function PickListExec(WelcomeText: string; var Selected: string): Boolean;', nil);
      SetInteger(AddVariable('fieldNumber', 'Integer', True), fieldNumber);
      SetInteger(AddVariable('fieldChecked', 'Integer', True), fieldChecked);
      SetInteger(AddVariable('fieldMedia', 'Integer', True), fieldMedia);
      SetInteger(AddVariable('fieldMediaType', 'Integer', True), fieldMediaType);
      SetInteger(AddVariable('fieldSource', 'Integer', True), fieldSource);
      SetInteger(AddVariable('fieldDate', 'Integer', True), fieldDate);
      SetInteger(AddVariable('fieldBorrower', 'Integer', True), fieldBorrower);
      SetInteger(AddVariable('fieldRating', 'Integer', True), fieldRating);
      SetInteger(AddVariable('fieldOriginalTitle', 'Integer', True), fieldOriginalTitle);
      SetInteger(AddVariable('fieldTranslatedTitle', 'Integer', True), fieldTranslatedTitle);
      SetInteger(AddVariable('fieldFormattedTitle', 'Integer', True), fieldFormattedTitle);
      SetInteger(AddVariable('fieldDirector', 'Integer', True), fieldDirector);
      SetInteger(AddVariable('fieldProducer', 'Integer', True), fieldProducer);
      SetInteger(AddVariable('fieldCountry', 'Integer', True), fieldCountry);
      SetInteger(AddVariable('fieldCategory', 'Integer', True), fieldCategory);
      SetInteger(AddVariable('fieldYear', 'Integer', True), fieldYear);
      SetInteger(AddVariable('fieldLength', 'Integer', True), fieldLength);
      SetInteger(AddVariable('fieldActors', 'Integer', True), fieldActors);
      SetInteger(AddVariable('fieldURL', 'Integer', True), fieldURL);
      SetInteger(AddVariable('fieldDescription', 'Integer', True), fieldDescription);
      SetInteger(AddVariable('fieldComments', 'Integer', True), fieldComments);
      SetInteger(AddVariable('fieldVideoFormat', 'Integer', True), fieldVideoFormat);
      SetInteger(AddVariable('fieldVideoBitrate', 'Integer', True), fieldVideoBitrate);
      SetInteger(AddVariable('fieldAudioFormat', 'Integer', True), fieldAudioFormat);
      SetInteger(AddVariable('fieldAudioBitrate', 'Integer', True), fieldAudioBitrate);
      SetInteger(AddVariable('fieldResolution', 'Integer', True), fieldResolution);
      SetInteger(AddVariable('fieldFrameRate', 'Integer', True), fieldFrameRate);
      SetInteger(AddVariable('fieldLanguages', 'Integer', True), fieldLanguages);
      SetInteger(AddVariable('fieldSubtitles', 'Integer', True), fieldSubtitles);
      SetInteger(AddVariable('fieldSize', 'Integer', True), fieldSize);
      SetInteger(AddVariable('fieldDisks', 'Integer', True), fieldDisks);
      SetString(AddVariable('dirApp', 'string', True), strDirApp);
      SetString(AddVariable('dirScripts', 'string', True), strDirApp + strDirScripts);
    end;
    Result := ENoError;
  end
  else
  begin
    SecondEngine := TIFPasScript.Create(nil);
    try
      f := TFileStream.Create(strDirApp + strDirScripts + Name + '.pas', fmOpenRead);
      SetLength(s, f.Size);
      f.Read(s[1], Length(S));
      f.Free;
    except
      SecondEngine.Free;
      Result := EUnitNotFound;
      Exit;
    end;
    SecondEngine.OnUses := OnScriptUses;
    SecondEngine.SetText(s);
    if SecondEngine.ErrorCode <> ENoError then
    begin
      Sender.RunError2(SecondEngine, SecondEngine.ErrorCode, SecondEngine.ErrorString);
      SecondEngine.Free;
      Result := EUnitNotFound;
    end
    else
    begin
      if not Sender.Attach(SecondEngine) then
      begin
        SecondEngine.Free;
        Result := ECustomError;
      end
      else
      begin
        Result := ENoError;
      end;
    end;
  end;
end;

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

function OnScriptRegProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;
var
  value: string;
  value2: string;
  i: Integer;
  resbool: Boolean;
  opt: TScriptOption;
  fieldProperties: TCustomFieldProperties;
begin
  result := ENoError;
  if proc^.Name = 'GETPAGE' then
    SetString(res, GetPage(GetString(Vm_Get(Params, 0)), '', ''))
  else
  if proc^.Name = 'GETPAGE2' then
    SetString(res, GetPage(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), ''))
  else
  if proc^.Name = 'GETPAGE3' then
    SetString(res, GetPage(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), GetString(Vm_Get(Params, 2))))
  else
  if proc^.Name = 'POSTPAGE' then
    SetString(res, PostPage(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), 'application/x-www-form-urlencoded', '', False, False))
  else
  if proc^.Name = 'POSTPAGE2' then
    SetString(res, PostPage(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), GetString(Vm_Get(Params, 2)), GetString(Vm_Get(Params, 3)), GetBoolean(Vm_Get(Params, 4)), GetBoolean(Vm_Get(Params, 5))))
  else
  if proc^.Name = 'GETPICTURE' then
  begin
    if GetScriptWin.CurrentScript.Fields.Picture then
      GetPicture(GetString(VM_Get(Params, 0)), '')
  end else
  if proc^.Name = 'GETPICTURE2' then
  begin
    if GetScriptWin.CurrentScript.Fields.Picture then
      GetPicture(GetString(VM_Get(Params, 0)), GetString(VM_Get(Params, 1)))
  end else
  if proc^.Name = 'IMPORTPICTURE' then
    ScriptResultsWin.ImportPicture(GetString(VM_Get(Params, 0)))
  else
  if proc^.Name = 'EXPORTPICTURE' then
    ScriptResultsWin.ExportPicture(GetString(VM_Get(Params, 0)), GetString(VM_Get(Params, 1)))
  else
  if proc^.Name = 'HTMLDECODE' then
    GetVarLink(Vm_Get(Params, 0))^.CV_Str := HTMLDecode(GetString(VM_Get(Params, 0)))
  else
  if proc^.Name = 'HTMLREMOVETAGS' then
    GetVarLink(Vm_Get(Params, 0))^.CV_Str := HTMLRemoveTags(GetString(VM_Get(Params, 0)))
  else
  if proc^.Name = 'URLENCODE' then
    SetString(res, TIdURI.ParamsEncode(GetString(VM_Get(Params, 0))))
  else
  if proc^.Name = 'URLDECODE' then
    SetString(res, TIdURI.URLDecode(GetString(VM_Get(Params, 0))))
  else
  if proc^.Name = 'SETFIELD' then
  begin
    if not (GetInteger(Vm_Get(Params, 0)) in GetScriptWin.CurrentScript.Fields.Excluded) then
      ScriptResultsWin.SetField(GetInteger(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)))
  end else
  if proc^.Name = 'SETCUSTOMFIELD' then
  begin
    fieldProperties := GetScriptWin.MovieList.CustomFieldsProperties.GetField(GetString(Vm_Get(Params, 0)));
    if (fieldProperties <> nil) and (not fieldProperties.ExcludedInScripts) then
      ScriptResultsWin.SetCustomField(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)))
  end else
  if proc^.Name = 'CANSETFIELD' then
    SetBoolean(res, not (GetInteger(Vm_Get(Params, 0)) in GetScriptWin.CurrentScript.Fields.Excluded))
  else
  if proc^.Name = 'CANSETCUSTOMFIELD' then
  begin
    fieldProperties := GetScriptWin.MovieList.CustomFieldsProperties.GetField(GetString(Vm_Get(Params, 0)));
    SetBoolean(res, (fieldProperties <> nil) and (not fieldProperties.ExcludedInScripts))
  end else
  if proc^.Name = 'CUSTOMFIELDEXISTS' then
  begin
    fieldProperties := GetScriptWin.MovieList.CustomFieldsProperties.GetField(GetString(Vm_Get(Params, 0)));
    SetBoolean(res, (fieldProperties <> nil))
  end else
  if proc^.Name = 'CANSETPICTURE' then
    SetBoolean(res, GetScriptWin.CurrentScript.Fields.Picture)
  else
  if proc^.Name = 'GETFIELD' then
    SetString(res, ScriptResultsWin.GetField(GetInteger(Vm_Get(Params, 0))))
  else
  if proc^.Name = 'GETCUSTOMFIELD' then
    SetString(res, ScriptResultsWin.GetCustomField(GetString(Vm_Get(Params, 0))))
  else
  if proc^.Name = 'GETOPTION' then
  begin
    opt := GetScriptWin.CurrentScript.Options.Find(GetString(VM_Get(Params, 0)));
    if opt <> nil then
      SetInteger(res, opt.Value)
    else
      SetInteger(res, -1);
  end
  else
  if proc^.Name = 'STRINGREPLACE' then
    SetString(res, StringReplace(getString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), getString(Vm_Get(Params, 2)), [rfReplaceAll]))
  else
  if proc^.Name = 'SHOWMESSAGE' then
    MessageWin.Execute(GetString(Vm_Get(Params, 0)), '', [mbOk])
  else
  if proc^.Name = 'SHOWERROR' then
    MessageWin.Execute(GetString(Vm_Get(Params, 0)), mtError, [mbOk])
  else
  if proc^.Name = 'SHOWINFORMATION' then
    MessageWin.Execute(GetString(Vm_Get(Params, 0)), mtInformation, [mbOk])
  else
  if proc^.Name = 'SHOWWARNING' then
    SetBoolean(res, MessageWin.Execute(GetString(Vm_Get(Params, 0)), mtWarning, [mbOk, mbCancel]) = 1)
  else
  if proc^.Name = 'SHOWCONFIRMATION' then
    SetBoolean(res, MessageWin.Execute(GetString(Vm_Get(Params, 0)), mtConfirmation, [mbYes, mbNo]) = 1)
  else
  if proc^.Name = 'INPUT' then
  begin
    value := GetString(Vm_Get(Params, 2));
    resbool := InputWin.Execute(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), value);
    SetBoolean(res, resbool);
    GetVarLink(Vm_Get(Params, 2))^.Cv_Str := value;
    if (not resbool) and (GetScriptWin.HasRemainingMovies) then
    begin
      if MessageWin.Execute(GetScriptWin.Messages.Strings[msgAbortBatch], mtConfirmation, [mbYes, mbNo]) = 1 then
        GetScriptWin.ActionDebugStop.Execute;
    end;
  end else
  if proc^.Name = 'CHECKVERSION' then
    SetBoolean(res, CheckVersion(
        GetInteger(Vm_Get(Params, 0)),
        GetInteger(Vm_Get(Params, 1)),
        GetInteger(Vm_Get(Params, 2))))
  else
  if proc^.Name = 'LAUNCH' then
  begin
    if GetString(Vm_Get(Params, 1)) = '' then
      LaunchProg(GetString(Vm_Get(Params, 0)), strDirApp)
    else
      LaunchProg(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)), strDirApp);
  end else
  if proc^.Name = 'ANSIUPFIRSTLETTER' then
  begin
    Value := GetString(Vm_Get(Params, 0));
    if Value <> '' then
      Value[1] := AnsiUpperCase(Copy(Value, 1, 1))[1];
    SetString(res, Value);
  end else
  if proc^.Name = 'ANSIMIXEDCASE' then
  begin
    Value := GetString(Vm_Get(Params, 0));
    Value2 := GetString(Vm_Get(Params, 1));
    for i := 1  to Length(Value) do
      if (i = 1) or (Pos(Copy(Value, i-1, 1), Value2) > 0) then
        Value[i] := AnsiUpperCase(Copy(Value, i, 1))[1];
    SetString(res, Value);
  end else
  if proc^.Name = 'UTF8DECODE' then
    SetString(res, UTF8Decode(GetString(Vm_Get(Params, 0))))
  else
  if proc^.Name = 'UTF8ENCODE' then
    SetString(res, UTF8Encode(GetString(Vm_Get(Params, 0))))
  else
  if proc^.Name = 'ACCEPTLICENSE' then
  begin
    if GetInteger(Vm_Get(Params, 0)) > GetScriptWin.CurrentScript.Properties.LicenseAccepted then
    begin
      resbool := MessageWin.Execute(InsertLineBreaks(GetScriptWin.CurrentScript.Properties.License), mtWarning, [GetScriptWin.Messages.Strings[msgIAgree], mbCancel]) = 1;
      if resbool then
        GetScriptWin.CurrentScript.AcceptLicense(GetInteger(Vm_Get(Params, 0)));
    end
    else
      resbool := True;
    SetBoolean(res, resbool);
  end else
  if proc^.Name = 'SETSTATIC' then
    GetScriptWin.CurrentScript.Static.Values[GetString(Vm_Get(Params, 0))] := GetString(Vm_Get(Params, 1))
  else
  if proc^.Name = 'GETSTATIC' then
     SetString(res, GetScriptWin.CurrentScript.Static.Values[GetString(Vm_Get(Params, 0))])
  else
  if proc^.Name = 'DELETEFILE' then
    SetBoolean(res, DeleteFile(GetString(Vm_Get(Params, 0))))
  else
  if proc^.Name = 'COPYFILE' then
    SetBoolean(res, CopyFile(PChar(GetString(Vm_Get(Params, 0))), PChar(GetString(Vm_Get(Params, 1))), GetBoolean(Vm_Get(Params, 2))))
  else
  if proc^.Name = 'MOVEFILE' then
    SetBoolean(res, MoveFile(PChar(GetString(Vm_Get(Params, 0))), PChar(GetString(Vm_Get(Params, 1)))))
  else
  if proc^.Name = 'LISTDIRECTORY' then
    SetString(res, ListDirectory(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1))))
  else
  if proc^.Name = 'SLEEP' then
  begin
    SetWaitCursor;
    try
      Sleep(GetInteger(Vm_Get(Params, 0)))
    finally
      RestoreCursor;
    end;
  end
  else
  if proc^.Name = 'ERROR' then
    result := ECustomError
end;

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

function OnScriptRegPickProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;
var
  value: string;
  resbool: Boolean;
begin
  result := ENoError;
  if proc^.Name = 'PICKTREECLEAR' then
    PickTreeWin.Clear
  else
  if proc^.Name = 'PICKTREEADD' then
    PickTreeWin.Add(GetString(Vm_Get(Params, 0)), GetString(Vm_Get(Params, 1)))
  else
  if proc^.Name = 'PICKTREEMORELINK' then
    PickTreeWin.SetMoreLink(GetString(Vm_Get(Params, 0)))
  else
  if proc^.Name = 'PICKTREEEXEC' then
  begin
    resbool := PickTreeWin.Execute(value);
    SetBoolean(res, resbool);
    GetVarLink(Vm_Get(Params, 0))^.CV_Str := value;
    if (not resbool) and (GetScriptWin.HasRemainingMovies) then
    begin
      if MessageWin.Execute(GetScriptWin.Messages.Strings[msgAbortBatch], mtConfirmation, [mbYes, mbNo]) = 1 then
        GetScriptWin.ActionDebugStop.Execute;
    end;
  end else
  if proc^.Name = 'PICKTREESORT' then
    PickTreeWin.Sort
  else
  if proc^.Name = 'PICKLISTCLEAR' then
    PickListWin.Clear
  else
  if proc^.Name = 'PICKLISTADD' then
    PickListWin.Add(GetString(Vm_Get(Params, 0)))
  else
  if proc^.Name = 'PICKLISTEXEC' then
  begin
    resbool := PickListWin.Execute(GetString(Vm_Get(Params, 0)), value);
    SetBoolean(res, resbool);
    GetVarLink(Vm_Get(Params, 1))^.CV_Str := value;
    if (not resbool) and (GetScriptWin.HasRemainingMovies) then
    begin
      if MessageWin.Execute(GetScriptWin.Messages.Strings[msgAbortBatch], mtConfirmation, [mbYes, mbNo]) = 1 then
        GetScriptWin.ActionDebugStop.Execute;
    end;
  end
end;

{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}
(*
function OnScriptRegXmlProc(Sender: TIfPasScript; ScriptID: Pointer; proc: PProcedure; Params: PVariableManager; res: PIfVariant): TIfPasScriptError;
var
  xml: TJvSimpleXml;
  Found: TJvSimpleXmlElem;
begin
  Result := ENoError;
  xml := GetScriptWin.DebugPlugin.XmlParser;
  SetString(Sender.GetVariable('XmlLastError'), '');
  if proc^.Name = 'XMLLOADFROMSTRING' then
    try
      xml.LoadFromString(GetString(Vm_Get(Params, 0)));
      SetBoolean(res, True);
    except
      on e: Exception do
      begin
        SetString(Sender.GetVariable('XmlLastError'), e.Message);
        SetBoolean(res, False);
      end;
    end
  else
  if proc^.Name = 'XMLLOADFROMFILE' then
    try
      xml.LoadFromFile(GetString(Vm_Get(Params, 0)));
      SetBoolean(res, True);
    except
      on e: Exception do
      begin
        SetString(Sender.GetVariable('XmlLastError'), e.Message);
        SetBoolean(res, False);
      end;
    end
  else
  if proc^.Name = 'XMLSAVETOSTRING' then
    SetString(res, xml.SaveToString)
  else
  if proc^.Name = 'XMLSAVETOFILE' then
    try
      xml.LoadFromFile(GetString(Vm_Get(Params, 0)));
      SetBoolean(res, True);
    except
      on e: Exception do
      begin
        SetString(Sender.GetVariable('XmlLastError'), e.Message);
        SetBoolean(res, False);
      end;
    end
  else
  if proc^.Name = 'XMLCLEAR' then
  begin
    xml.Root.Clear;
    xml.Root.Name := 'New';
    xml.Prolog.Clear;
  end
  else
  if proc^.Name = 'XMLITEMEXISTS' then
    SetBoolean(res, functions_xml.FindItem(xml, GetString(Vm_Get(Params, 0))) <> nil)
  else
  if proc^.Name = 'XMLITEMVALUE' then
  begin
    Found := functions_xml.FindItem(xml, GetString(Vm_Get(Params, 0)));
    if Found <> nil then
      SetString(res, Found.Value)
    else
      SetString(res, GetString(Vm_Get(Params, 1)));
  end
  else
  if proc^.Name = 'XMLPROPERTYEXISTS' then
  begin
    Found := functions_xml.FindItem(xml, GetString(Vm_Get(Params, 0)));
    if Found <> nil then
      SetBoolean(res, Found.Properties.ItemNamed[GetString(Vm_Get(Params, 1))] <> nil)
    else
      SetBoolean(res, False);
  end
  else
  if proc^.Name = 'XMLPROPERTYVALUE' then
  begin
    Found := functions_xml.FindItem(xml, GetString(Vm_Get(Params, 0)));
    if Found <> nil then
      SetString(res, Found.Properties.Value(GetString(Vm_Get(Params, 1)), GetString(Vm_Get(Params, 2))))
    else
      SetString(res, GetString(Vm_Get(Params, 2)));
  end
end;
*)
{-------------------------------------------------------------------------------
-------------------------------------------------------------------------------}

end.
