{***************************************************************************}
{ TMS IntraWeb Component Pack Pro                                           }
{ for Delphi & C++Builder                                                   }
{                                                                           }
{ written by TMS Software                                                   }
{            copyright © 2002 - 2009                                        }
{            Email : info@tmssoftware.com                                   }
{            Web : http://www.tmssoftware.com                               }
{                                                                           }
{ The source code is given as is. The author is not responsible             }
{ for any possible damage done due to the use of this code.                 }
{ The component can be freely used in any application. The complete         }
{ source code remains property of the author and may not be distributed,    }
{ published, given or sold in any form as such. No parts of the source      }
{ code can be included in any other component or application without        }
{ written authorization of the author.                                      }
{***************************************************************************}

unit IWMultiColumnComboBox;

interface

{$I TMSDEFS.INC}

uses
  {$IFDEF LINUX}
  QControls, QGraphics, QIWPicCntnr, QForms,
  {$ELSE}
  Windows, Graphics, Controls, {IWPicCntnr,} Forms, IWTMSImg,
  {$ENDIF}
  {$IFDEF DELPHI6_LVL}
  Types,
  {$ENDIF}
  Classes,
  IWControl, IWTypes, SysUtils, IWCompButton, IWFont, IWForm,
  IWCompEdit, IWCompLabel, IWCompCheckbox, IWExtCtrls, IWHTMLTag, IWCompListbox,
  IWTMSBase
  {$IFDEF TMSIW51}
  , IWColor
  {$ENDIF}
  {$IFDEF TMSIW6}
  , IWRenderContext
  {$ENDIF}
  {$IFDEF TMSIW7}
  , IWBaseHTMLControl
  {$ENDIF}
  {$IFDEF TMSIW9}
  , IWXMLTag
  {$ENDIF}
  ;

type

  TTIWMultiColumnComboBoxEvent = procedure(Sender: TObject; Index: integer) of object;
  {$IFDEF TMSIW9}
  TIWAsyncMultiColumnComboBoxEvent = procedure (Sender: TObject; EventParams: TStringList; Index: Integer; Value: string) of object;
  {$ENDIF}

  TTIWGradientDirection = (gdHorizontal, gdVertical);

  TTIWDropDownDisplay = (ddOnFocus, ddOnLookup, ddManual);

  TTIWLookupMethod = (lmSelect, lmSelectSorted, lmFilter);

  TTIWMultiColumnComboBox = class;

  TTIWColumnTitles = class(TPersistent)
  private
    FBackColor: TIWColor;
    FTitles: TStrings;
    FVisible: boolean;
    FFont: TIWFont;
    procedure SetBackColor(const Value: TIWColor);
    procedure SetTitles(const Value: TStrings);
    procedure SetFont(const Value: TIWFont);
    procedure SetVisible(const Value: boolean);
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property BackColor: TIWColor read FBackColor write SetBackColor default clBtnFace;
    property Titles: TStrings read FTitles write SetTitles;
    property Visible: boolean read FVisible write SetVisible;
    property Font: TIWFont read FFont write SetFont;
  end;

  TTComboRow = class(TCollectionItem)
  private
    FVisible: Boolean;
    FRowData: TStringList;
    procedure SetRowData(const Value: TStringList);
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
  published
    property RowData : TStringList read FRowData write SetRowData;
  end;

  TTComboRows = class(TCollection)
  private
    FOwner: TTIWMultiColumnComboBox;
    function GetItem(Index: Integer): TTComboRow;
    procedure SetItem(Index: Integer; const Value: TTComboRow);
  public
    constructor Create(AOwner: TTIWMultiColumnComboBox);
    function Add: TTComboRow;
    function Insert(Index: Integer): TTComboRow;
    property Items[Index: Integer]: TTComboRow read GetItem write SetItem; default;
    property IWColumnComboBox: TTIWMultiColumnComboBox read FOwner;
  end;


  TTIWMultiColumnComboBox = class(TIWCustomEdit)
  private
    FBorderWidth: Integer;
    FColor: TColor;
    FDropDownDisplay: TTIWDropDownDisplay;
    FPopUpColor: TColor;
    FPopUpColorTo: TColor;
    FPopUpColorGradientDirection: TTIWGradientDirection;
    FPopUpHeight: Integer;
    FPopUpWidth: Integer;
    FBorderColor: TColor;
    FFlat: Boolean;
    FAlignment: TAlignment;
    FFocusColor: TColor;
    FSelectAll: Boolean;
    FAdvanceOnReturn: Boolean;
    FSubmitOnReturn: Boolean;
    FList: TStringList;
    FLookupAfterChars: Integer;
    FLookupMethod: TTIWLookupMethod;
    FLookupTypeAhead: bool;
    FNoMatchingItems: string;
    FSelected: TList;
    FText: string;
    FColCount: Integer;
    FComboRows: TTComboRows;
    FSelectionColor: TColor;
    FSelectionTextColor: TColor;
    FCaseSensitiveLookUp: Boolean;
    FShowGridBorder: Boolean;
    FPopUpFont: TIWFont;
    FColumnTitles: TTIWColumnTitles;
    FColumnSeparator: char;
    FItemIndexl: Integer;
    FDropDownImage: TIPicture;
    FDropDownImageURL: string;    
    FOnChange: TTIWMultiColumnComboBoxEvent;
    {$IFDEF TMSIW9}
    FOnAsyncChange: TIWAsyncMultiColumnComboBoxEvent;
    {$ENDIF}

    procedure SetBorderColor(const Value: TColor);
    procedure SetBorderWidth(const Value: Integer);
    procedure SetColor(const Value: TColor);
    procedure SetFlat(const Value: Boolean);
    procedure SetAlignment(const Value: TAlignment);
    procedure SetColcount(const Value: integer);
    function GetSelected(i: integer): boolean;
    procedure SetSelected(i: Integer; value: boolean);
    procedure SetDropDownImage(const Value: TIPicture);    

    procedure SetColumnTitles(const Value: TTIWColumnTitles);
    procedure SetPopUpFont(const Value: TIWFont);

  protected
    function HTMLClr(color: TColor): string;
    procedure SetValue(const value:string); override;
    procedure Submit(const AValue:string); override;
    {$IFDEF TMSIW72_NEW}
    function get_ShouldRenderTabOrder: Boolean; override;
    {$ENDIF}
    {$IFDEF TMSIW9}
    procedure DoAsyncChange(AParams: TStringList);
    {$ENDIF}
  public
    {$IFDEF TMSIW72}
    function get_HasTabOrder: boolean; override;
    {$ENDIF}
    {$IFDEF TMSIW6}
    procedure IWPaint; override;
    function RenderHTML(AContext: TIWBaseComponentContext): TIWHTMLTag; override;
    {$ELSE}
    procedure Paint; override;
    function RenderHTML: TIWHTMLTag; override;
    {$ENDIF}
    {$IFDEF TMSIW9}
    function RenderAsync(AContext: TIWBaseHTMLComponentContext): TIWXMLTag; override;
    {$ENDIF}
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property Selected[i: Integer]: boolean read GetSelected write SetSelected;
    function AddRow(a: string): string;
  published
    property AdvanceOnReturn: Boolean read FAdvanceOnReturn write FAdvanceOnReturn;
    property Alignment: TAlignment read FAlignment write SetAlignment;
    property BorderColor: TColor read FBorderColor write SetBorderColor;
    property BorderWidth: Integer read FBorderWidth write SetBorderWidth;
    property Color: TColor read FColor write SetColor;
    property DropDownDisplay: TTIWDropDownDisplay read FDropDownDisplay write FDropDownDisplay default ddOnLookup;
    property DropDownImage: TIPicture read FDropDownImage write SetDropDownImage;
    property DropDownImageURL: string read FDropDownImageURL write FDropDownImageURL;
    property LookupAfterChars: Integer read FLookupAfterChars write FLookupAfterChars default 0;
    property LookupMethod: TTIWLookupMethod read FLookupMethod write FLookupMethod default lmFilter;
    property LookupTypeAhead: bool read FLookupTypeAhead write FLookupTypeAhead default false;
    property PopUpColor: TColor read FPopUpColor write FPopUpColor;
    property PopUpColorTo: TColor read FPopUpColorTo write FPopUpColorTo;
    property PopUpColorGradientDirection: TTIWGradientDirection read FPopUpColorGradientDirection write FPopUpColorGradientDirection;
    property PopUpHeight: Integer read FPopUpHeight write FPopUpHeight default 0;
    property PopUpWidth: Integer read FPopUpWidth write FPopUpWidth default 0;
    property FocusColor: TColor read FFocusColor write FFocusColor;
    property Flat: Boolean read FFlat write SetFlat;
    property NoMatchingItems: string read FNoMatchingItems write FNoMatchingItems;
    property SelectAll: Boolean read FSelectAll write FSelectAll;
    property SubmitOnReturn: Boolean read FSubmitOnReturn write FSubmitOnReturn;
    property Text: string read FText write FText;
    property ColCount: integer read FColCount write SetColCount;
    property SelectionColor: TColor read FSelectionColor write FSelectionColor;
    property SelectionTextColor: TColor read FSelectionTextColor write FSelectionTextColor;
    property Items: TTComboRows read FComboRows write FComboRows;
    property CaseSensitiveLookUp: Boolean read FCaseSensitiveLookUp write FCaseSensitiveLookUp default false;
    property ShowGridBorder: Boolean read FShowGridBorder write FShowGridBorder default false;
    property PopUpFont: TIWFont read FPopUpFont write SetPopUpFont;
    property ColumnTitles: TTIWColumnTitles read FColumnTitles write SetColumnTitles;
    property ColumnSeparator: char read FColumnSeparator write FColumnSeparator default ';';
    property ItemIndex: integer read FItemIndexl write FItemIndexl default -1;
    property OnChange: TTIWMultiColumnComboBoxEvent read FOnChange write FOnChange;
    {$IFDEF TMSIW9}
    property OnAsyncChange: TIWAsyncMultiColumnComboBoxEvent read FOnAsyncChange write FOnAsyncChange;
    {$ENDIF}
  end;

procedure Register;

implementation

uses
  {$IFDEF LINUX}
  QImgList,
  {$ELSE}
  ImgList, ShellAPI, CommCtrl,
  {$ENDIF}
  IWApplication, IWServerControllerBase,IWResourceStrings,
  SWStrings, SWSystem, IWAppForm, TypInfo;

procedure Register;
begin
  RegisterComponents('TMS', [TTIWMultiColumnComboBox]);
end;

//------------------------------------------------------------------------------
procedure Draw3DCtrl(FCanvas: TCanvas; Left,Top,Right,Bottom: Integer);
begin
  with FCanvas do
  begin
    Pen.Color := clBlack;
    MoveTo(Left,Bottom);
    LineTo(Left,Top);
    LineTo(Right,Top);

    Pen.Color := clSilver;
    LineTo(Right,Bottom);
    LineTo(Left,Bottom);

    Pen.Color := clGray;
    LineTo(Left + 1,Bottom);
    LineTo(Left + 1,Top + 1);
    LineTo(Right - 1,Top + 1);
    Pen.Color := Brush.Color;
    Rectangle(Left+1,Top+1,Right-1,Bottom-1);
  end;
end;

//------------------------------------------------------------------------------
//-----------------------------{ TTComboRow }-----------------------------------
//------------------------------------------------------------------------------
constructor TTComboRow.Create(Collection: TCollection);
begin
  inherited;
  FVisible:= true;
  FRowData:= TStringList.Create;
  //DisplayName:= FCaption;
end;

//------------------------------------------------------------------------------
procedure TTComboRow.SetRowData(const Value: TStringList);
begin
  FRowData.Assign(Value);
end;

//------------------------------------------------------------------------------
destructor TTComboRow.Destroy;
begin
  FRowData.Free;
  inherited;
end;

//------------------------------------------------------------------------------
//-----------------------------{ TTComboRows }----------------------------------
//------------------------------------------------------------------------------
constructor TTComboRows.Create(AOwner: TTIWMultiColumnComboBox);
begin
  inherited Create(TTComboRow);
  FOwner := AOwner;
end;

//------------------------------------------------------------------------------
function TTComboRows.GetItem(Index: Integer): TTComboRow;
begin
  Result := TTComboRow(inherited Items[Index]);
end;

//------------------------------------------------------------------------------
function TTComboRows.Add: TTComboRow;
begin
  Result := TTComboRow(inherited Add);
end;

//------------------------------------------------------------------------------
function TTComboRows.Insert(Index: Integer): TTComboRow;
begin
  Result := TTComboRow(inherited Insert(Index));
end;


//------------------------------------------------------------------------------
procedure TTComboRows.SetItem(Index: Integer; const Value: TTComboRow);
begin
  inherited Items[Index] := Value;
end;


//------------------------------------------------------------------------------
//--------------------------{ TTIWMultiColumnComboBox }-------------------------
//------------------------------------------------------------------------------
{$IFDEF TMSIW9}
procedure TTIWMultiColumnComboBox.DoAsyncChange(AParams: TStringList);
begin
  if Assigned(OnAsyncChange) then
    OnAsyncChange(Self, AParams, ItemIndex, Text);
end;

function TTIWMultiColumnComboBox.RenderAsync(
  AContext: TIWBaseHTMLComponentContext): TIWXMLTag;
begin
  Result := TIWXMLTag.CreateTag('control');
  try
    Result.AddStringParam('id', HTMLName);
    Result.AddStringParam('type', 'TTIWMULTICOLUMNCOMBOBOX');
    RenderAsyncCommonProperties( AContext, Result );
  except
    FreeAndNil(Result);
  end;
end;
{$ENDIF}

constructor TTIWMultiColumnComboBox.Create(AOwner: TComponent);
begin
  inherited;
  FBorderWidth := 1;
  FBorderColor := clBlack;
  FColor := clWhite;
  FFocusColor := clWhite;
  {$IFDEF TMSIW6}
  SetRenderSize(True);
  {$ELSE}
  FRenderSize := True;
  {$ENDIF}
  FNeedsFormTag := True;
  {$IFDEF TMSIW6}
  {TODO}
  {$ELSE}
  FSupportedScriptEvents := 'OnChange,OnSelect';
  FSupportsInput := true;
  FSupportsSubmit := true;
  {$ENDIF}

  FList := TStringList.Create;
  FSelected := TList.Create;
  FPopUpColor := clWhite;
  FPopupColorTo := clNone;
  FPopUpColorGradientDirection := gdHorizontal;
  Text := '';

  Font.FontName := 'Arial';
  Font.Size := 10;

  FComboRows:= TTComboRows.Create(self);
  FDropDownDisplay := ddOnLookup;
  FLookupAfterChars := 0;
  FLookupMethod := lmFilter;
  FLookupTypeAhead := false;
  FSelectionColor:= clNavy;
  FSelectionTextColor:= clWhite;
  FNoMatchingItems := 'No matching items found';
 // FGridBorderColor:= clSilver;
  FCaseSensitiveLookUp:= false;
  FShowGridBorder:= false;
  FPopUpFont:= TIWFont.Create;
  FPopUpHeight:= 0;
  FPopUpWidth:= 0;

  FColumnTitles := TTIWColumnTitles.Create;
  FColumnSeparator := ';';

  FDropDownImage := TIPicture.Create;

  FItemIndexl := -1;
end;

//------------------------------------------------------------------------------
destructor TTIWMultiColumnComboBox.Destroy;
begin
  FComboRows.Free;
  FPopUpFont.Free;

  FList.Free;
  FSelected.Free;

  FColumnTitles.Free;

  FDropDownImage.Free;
  inherited;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetPopUpFont(const Value: TIWFont);
begin
  FPopUpFont:= Value;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetSelected(i: Integer; value: boolean);
begin
  while (i >= FSelected.Count) do
    FSelected.Add(TObject(false));

  FSelected.Items[i] := TObject(value);
end;

//------------------------------------------------------------------------------
function TTIWMultiColumnComboBox.GetSelected(i: Integer): boolean;
begin
  if (i < FSelected.Count) then
    Result := boolean(FSelected.Items[i])
  else
    Result := False;
end;

//------------------------------------------------------------------------------
function TTIWMultiColumnComboBox.AddRow(a: string): string;
var
  su: string;
  ttr: TTComboRow;
begin
  ttr := FComboRows.Add;

  while (pos(ColumnSeparator,a) > 0) do
  begin
    su := copy(a,1,pos(ColumnSeparator,a) - 1);
    ttr.RowData.Add(StringReplace(su, '"', '&quot;', [rfReplaceAll]));
    delete(a,1,pos(ColumnSeparator,a));
  end;
  ttr.RowData.Add(a)
end;

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

{$IFDEF TMSIW6}
procedure TTIWMultiColumnComboBox.IWPaint;
{$ELSE}
procedure TTIWMultiColumnComboBox.Paint;
{$ENDIF}
var
  R : TRect;
begin
  with Canvas do
  begin
    Rectangle(4,4,Width,20);
    r := Rect(Width - 18,4,Width,20);
    {$IFNDEF LINUX}
    DrawFrameControl(Handle,r, DFC_SCROLL,DFCS_SCROLLCOMBOBOX );
    {$ENDIF}
  end;
end;


//------------------------------------------------------------------------------
function TTIWMultiColumnComboBox.HTMLClr(color: TColor):string;
begin
  Result := ColorToRGBString(color);
end;

procedure TTIWMultiColumnComboBox.SetValue(const value:string);
var
  vp: integer;
  varvalue : string; 
begin
  varvalue := value;

  if Length(value) > 0 then
  begin
    vp := Pos('~', varvalue);

    if vp > 0 then
    begin
      Delete(varvalue,vp,Length(varvalue) - vp + 1);
      ItemIndex := StrToInt(varvalue);
      inherited SetValue(varvalue);
    end;

    if (ItemIndex >=0) and (ItemIndex < Items.Count) then
      Text := Items[ItemIndex].RowData[0]
    else if (ItemIndex = -1) then
    begin
      varvalue := value;
      Delete(varvalue,1,3);
      Text := varvalue;
    end
    else
      Text := EmptyStr;
  end
end;

procedure TTIWMultiColumnComboBox.Submit(const AValue: string);
begin
  inherited;

  if Assigned(FOnChange) then
    FOnChange(Self,StrToInt(AValue));
end;

//------------------------------------------------------------------------------
{$IFDEF TMSIW6}
function TTIWMultiColumnComboBox.RenderHTML(AContext: TIWBaseComponentContext): TIWHTMLTag;
{$ELSE}
function TTIWMultiColumnComboBox.RenderHTML: TIWHTMLTag;
{$ENDIF}
var
  htmlres: string;
  r, c: Integer;
  gradient, fontstyle, S, rowval, buttonval: string;
  CScript: TStrings;

  tabidx: string;
  backcolor: string;
  forecolor: string;
  style: string;
  rowtitle: string;
  i : integer;
  gborder: string;
  InitText: string;
  ajaxcall, submitclick: string;

   function MakeAlign(AAlignment: TAlignment):string;
   begin
     Result := '';
     case AAlignment of
     taRightJustify: Result := ' style=text-align:right;';
     taCenter: Result := ' style=text-align:center;';
     end;
   end;

   function MakeScript: string;
   var
     LScript: TStringList;
     i: integer;
     ItemText: string;
   begin
     LScript := TStringList.Create;
     with LScript do
     begin
       Add('<Script Language="JavaScript">');
       Add('var '+ HTMLName +'dohide = 0;');

       Add('var '+HTMLName+'obj = new Object();');
       Add(HTMLName+'obj.ID = "'+HTMLName+'";');
       Add(HTMLName+'obj.popupHeight = '+ IntToStr(PopUpHeight) +';');
       Add(HTMLName+'obj.dohide = 0;');
       Add(HTMLName+'obj.HighLightedRow = "";');
       Add(HTMLName+'obj.DivStartLeft = 0;');
       Add(HTMLName+'obj.DivStartTop = 0;');
       Add(HTMLName+'obj.DivEndLeft = 0;');
       Add(HTMLName+'obj.DivEndTop = 0;');
       Add(HTMLName+'obj.ClrSel = "'+ HTMLClr(FSelectionColor)+'"');
       Add(HTMLName+'obj.ClrTextSel = "'+ HTMLClr(FSelectionTextColor)+'"');
       Add(HTMLName+'obj.CCount = '+IntToStr(FColCount - 1));
       Add(HTMLName+'obj.RCount = '+IntToStr(FComboRows.Count));
       Add(HTMLName+'obj.ForeColor = "'+ HTMLClr(PopUpFont.Color)+'"');
       Add(HTMLName+'obj.PopUpColor = "'+ HTMLClr(PopUpColor)+'"');
       Add(HTMLName+'obj.SelectedRow = -1;');
       Add(HTMLName+'obj.ItemIndex = '+ IntToStr(ItemIndex) +';');
       Add(HTMLName+'obj.ItemSel = false;');       
       Add(HTMLName+'obj.UsedKeyb = false;');

       Add('var '+HTMLName+'dosubmit = true;');

        Add(HTMLName+'obj.Item = new Array();');

        for i := 1 to Items.Count do
        begin

          if (Items[i-1].RowData.Count > 0) then
            ItemText := Items[i-1].RowData[0]
          else
            ItemText := '';

          if not CaseSensitiveLookUp then
            ItemText := StrUpper(pchar(ItemText));

           Add(HTMLName+'obj.Item['+HTMLName+'obj.Item.length] = "' + ItemText + '";');
        end;

       Add('function '+HTMLName+'showdivonclick() {');

       if ( (LookupMethod = lmFilter) and (NoMatchingItems <> EmptyStr) ) then
         Add('document.getElementById("'+HTMLName+'RowNo'+ IntToStr(FComboRows.Count) +'").style.display = "none";');

//       if LookupMethod = lmFilter then
//        Add(' CCDisplayAllRows('+IntToStr(FComboRows.Count)+',"'+HTMLName+'");');

       //Add(' '+HTMLName+'showdiv('+HTMLName+'obj);');

       //Add(' var itemHeight = parseInt(document.getElementById("'+HTMLName+'tbl").offsetHeight);');
       //Add(' if ( (itemHeight < parseInt('+IntToStr(PopUpHeight)+')) && (itemHeight > 0) ){ ');
       //Add('   document.getElementById("'+HTMLName+'popup").style.height = itemHeight;');
       //Add('   document.getElementById("'+HTMLName+'popup").style.overflow = "";');
       //Add(' } else {');
       //Add('   document.getElementById("'+HTMLName+'popup").style.height = parseInt("'+IntToStr(PopUpHeight)+'");');
       //Add('   document.getElementById("'+HTMLName+'popup").style.overflow = "auto";');
       //Add(' }');

        Add(
        '  if ('+HTMLName+'obj.HighLightedRow == "")'#13
        +   HTMLName+'ShowLookUp(null);'#13
        + ' document.getElementById("'+HTMLName+'checklist").style.display = "none";'#13
        +   HTMLName+'showdiv('+HTMLName+'obj);');

       Add('}');

       Add('function '+HTMLName+'showdiv(obj) {');
       Add(' document.getElementById("'+ HTMLName +'tbl").style.borderCollapse = "collapse";');

       //Moved after display = "";
       //Add(' CCgetPositionDiv(document.getElementById("'+HTMLName+'checklist"),'+HTMLName+'obj);');

       Add(' if (document.getElementById("'+HTMLName+'checklist").style.display == "none"){');
       Add('   if (obj.HighLightedRow !="")');
       Add('     CCShowUnHighLighted(obj.HighLightedRow,'+IntToStr(FColCount - 1)+',obj);');


      if ( (LookupMethod = lmFilter) and (NoMatchingItems <> EmptyStr) ) then
      begin
        Add('if ( ('+HTMLName+'obj.SelectedRow == -1) && (document.getElementById("'+HTMLName+'_TEXT").value.length > 0) )');
        Add('  document.getElementById("'+HTMLName+'RowNo'+ IntToStr(FComboRows.Count) +'").style.display = "";');
      end;

        Add('  document.getElementById("'+HTMLName+'checklist").style.display = "";');

       if FCaseSensitiveLookup then
         Add('   CCHighLightSelected("'+HTMLName+'",obj,true);')
       else
         Add('   CCHighLightSelected("'+HTMLName+'",obj,false);');

       Add(' CCgetPositionDiv(document.getElementById("'+HTMLName+'checklist"),'+HTMLName+'obj);');

       Add('   document.onmouseup = '+HTMLName+'docMouseUp;');
       Add('   CCshowWindowedObjects(false,'+HTMLName+'obj.DivStartLeft,'+HTMLName+'obj.DivStartTop,'+HTMLName+'obj.DivEndLeft,'+HTMLName+'obj.DivEndTop);');
       Add('   document.getElementById("'+HTMLName+'_TEXT").focus();');
       Add(' }else {');
       Add('   document.getElementById("'+HTMLName+'popup").scrollTop = 0;');       
       Add('   document.getElementById("'+HTMLName+'checklist").style.display = "none";');
       Add('   CCshowWindowedObjects(true,'+HTMLName+'obj.DivStartLeft,'+HTMLName+'obj.DivStartTop,'+HTMLName+'obj.DivEndLeft,'+HTMLName+'obj.DivEndTop);');
       Add(' }');
       Add('}');                              

       Add('function '+HTMLName+'docMouseUp() {');
       Add(' if ('+ HTMLName +'dohide == 0) {');
       Add('   document.getElementById("'+HTMLName+'popup").scrollTop = 0;');       
       Add('   document.getElementById("'+HTMLName+'checklist").style.display = "none";');
       Add('   CCshowWindowedObjects(true,'+HTMLName+'obj.DivStartLeft,'+HTMLName+'obj.DivStartTop,'+HTMLName+'obj.DivEndLeft,'+HTMLName+'obj.DivEndTop);');
       Add('   document.onmouseup = "";');
       Add(' } else {');
       Add('   '+ HTMLName +'dohide = 0; ');
       Add(' }');
       Add('}');

       Add('function '+HTMLName+'resetdoc(){');
       Add(' '+ HTMLName +'dohide = 1; ');
       Add('}');

       Add('function ' + HTMLName + 'Focus(ctrl) {');
//      if FFocusColor <> FColor then
       Add(' ctrl.style.backgroundColor = '#39+HTMLClr(FFocusColor)+#39'');

      if FSelectAll then
      begin
        Add(' var rNew = ctrl.createTextRange();');
        Add(' rNew.moveStart('#39'character'#39', 0) ;');
        Add(' rNew.select();');
      end;
      Add('}');

       Add('function ' + HTMLName + 'Blur(ctrl,obj) {');
//       Add('if (ctrl.value == "")');
       Add('  if (obj.ItemSel == false)');
       Add('    FindElem(''' + HTMLName + '_INPUT'').value = "-1~" + ctrl.value;');
       Add('  obj.ItemSel = false;');

//      if (BGColor <> clNone) then
       Add(' ctrl.style.backgroundColor = "'+HTMLClr(Color)+'"');
       Add('}');

       if Assigned(FOnChange) then
         submitclick := 'return SubmitClick('#39+HTMLName+#39', index, '#39'false'#39');'#13;

       {$IFDEF TMSIW9}
       if Assigned(FOnAsyncChange) then
       begin
          ajaxcall := 'processAjaxEvent(''onChange'', '
            + HTMLControlImplementation.IWCLName
            + ',''' + HTMLName + '.' + 'DoAsyncChange' + ''','              
            + 'true' + ', null, '
            + 'true' + ');';

         Acontext.WebApplication.RegisterCallBack(HTMLName+'.DoAsyncChange', DoAsyncChange);

         submitclick := '';
       end;
       {$ENDIF}

       Add('function '+HTMLName+'ChangeEditValue(EDId,id,index){');
       Add(' if (id!="") {');
       Add('  var fullid = "val" + id;');
       Add('   document.getElementById(EDId).value = document.getElementById(fullid).innerHTML;');
       Add(    HTMLName+'docMouseUp();');
       Add( HTMLName+'obj.ItemIndex = index;');
       Add(' FindElem(''' + HTMLName + '_INPUT'').value = index + "~" + FindElem(''' + HTMLName + '_TEXT'').value;');
       Add(ajaxcall);
       Add(submitclick);
       Add(' }');
       Add('}');

       Add('function '+HTMLName+'SelectHighLighted(obj) {');
       Add('    '+HTMLName+'ChangeEditValue("'+ HTMLName+'_TEXT",obj.HighLightedRow, obj.HighLightedRow.substr(obj.HighLightedRow.indexOf("RowNo")+5));');
       Add('  '+HTMLName+'dosubmit = true;');
       Add('}');


       Add('function '+HTMLName+'noenter(event) {');
       Add(' var isIE = navigator.appName.indexOf("Microsoft") != -1;');
       Add(' if (isIE) {key = event.keyCode;} else {key = event.which;}');
       Add(' if (! '+HTMLName+'dosubmit) ');
       Add('  return !(event && key == 13); ');
       Add('}');

       Add('function '+HTMLName+'ShowLookUp(event){');

       //if ( (LookupMethod = lmFilter) and (NoMatchingItems <> EmptyStr) ) then
       //begin
         //Add('if ('+HTMLName+'obj.SelectedRow == -1)');
         //Add('  document.getElementById("'+HTMLName+'RowNo'+ IntToStr(FComboRows.Count) +'").style.display = "none";');
       //end;

       Add(' '+HTMLName+'dosubmit = false;');
       Add(' var isIE = navigator.appName.indexOf("Microsoft") != -1;');
       Add(' var key;');
       Add(' if (event == null) '#13
            + ' key = null; '#13
            + ' else');
       Add(' if (isIE) {key = event.keyCode;} else {key = event.which;}');
       Add('   displayRowCount = 0;');

      if DropDownDisplay <> ddOnFocus then
        Add('if ((key == 9) || (key == 0) || (key == 13)) return;');

       Add(' if ( ((key == 40) || (key == 38) || (key == 13) || (key == 33) || (key == 34) || (key == 35) || (key == 36))'
       + ' && (document.getElementById("'+HTMLName+'checklist").style.display != "none") ) {');
       Add(' }');
       Add(' else {');

      if LookupMethod = lmFilter then
       Add('  CCDisplayAllRows('+IntToStr(FComboRows.Count)+',"'+HTMLName+'");');

       Add('  var editor = document.getElementById("'+HTMLName+'_TEXT");');
       Add('  if (editor.value.length > 0) {');
       Add('   SelectedRow = -1;');

     if LookupMethod <> lmSelectSorted then
     begin
       Add('   for (i=0;i<'+IntToStr(FComboRows.Count)+';i++){');
       Add('    RowID = "'+ HTMLName +'RowNo" + i;');
       Add('    valRow = document.getElementById("val"+RowID);');       
       Add('    elRow = document.getElementById(RowID);');

       if not FCaseSensitiveLookUp then
         Add('   if ( (valRow.innerHTML.substr(0,editor.value.length).toUpperCase()) != (editor.value.toUpperCase()) ) {')
       else
         Add('   if ( valRow.innerHTML.substr(0,editor.value.length) != editor.value ) {');

       if LookupMethod = lmFilter then
         Add('     elRow.style.display = "none";');

       Add('    }else {');
       Add('     displayRowCount++;');
       Add('     if (displayRowCount ==1)');
       Add('       SelectedRow=RowID;');

       if LookupMethod = lmFilter then
         Add('     elRow.style.display = ""; ');
       
       Add('     }');
       Add('    }');

    end
    else
    begin

        Add('   keyval = editor.value;');
        if not CaseSensitiveLookUp then
          Add('   keyval = editor.value.toUpperCase();');

        Add(
          ' SelectedRow = CCBinary('+HTMLName+'obj,keyval);'#13
          + 'if (SelectedRow != -1)'#13
          + '{'#13
          + ' SelectedRow = "" + SelectedRow;'#13
          + ' if (SelectedRow.indexOf(".") >= 0)'#13
          + '  SelectedRow = SelectedRow.substring(0,SelectedRow.indexOf("."));'#13
          + ' displayRowCount = 1;'#13
          + ' SelectedRow = "'+ HTMLName +'RowNo" + SelectedRow;'#13
          + '}'#13
          );
     end;

     Add(HTMLName+'obj.SelectedRow = SelectedRow;');

      if ( (LookupMethod = lmFilter) and (NoMatchingItems <> EmptyStr) ) then
      begin
        Add('  if (document.getElementById("'+HTMLName+'checklist").style.display == "none"){');
        Add(     HTMLName+'showdiv('+HTMLName+'obj);');
        Add('  }');

        Add('if ('+HTMLName+'obj.SelectedRow == -1)');
        Add('  document.getElementById("'+HTMLName+'RowNo'+ IntToStr(FComboRows.Count) +'").style.display = "";');
        Add('else');
        Add('  document.getElementById("'+HTMLName+'RowNo'+ IntToStr(FComboRows.Count) +'").style.display = "none";');        

      end
      else
      begin

       Add('   if ((document.getElementById("'+HTMLName+'checklist").style.display == "none") && (displayRowCount >0)){');
       Add(       HTMLName+'showdiv('+HTMLName+'obj);');
       Add('   }');
       Add('   else if (displayRowCount <=0) {');
       Add('     if (document.getElementById("'+HTMLName+'checklist").style.display != "none")');
			 Add(       HTMLName+'showdiv('+HTMLName+'obj);');
       Add('   }');

       end;

      if LookupMethod = lmFilter then
       Add('  CCNormalAllRows('+IntToStr(FComboRows.Count)+',"'+HTMLName+'");');
       
       Add('  if (SelectedRow != -1){');
       Add('    CCShowHighLighted(SelectedRow,'+HTMLName+'obj,'+IntToStr(FColCount - 1)+');');

      if LookupMethod <> lmFilter then
        Add('     document.getElementById("'+HTMLName+'popup").scrollTop = document.getElementById(SelectedRow).offsetTop;');

       Add('    }');
       Add('  }');
       Add('  else '+HTMLName+'showdiv('+HTMLName+'obj);');

       Add(' }');
        Add(' var itemHeight = parseInt(document.getElementById("'+HTMLName+'tbl").offsetHeight);');
        Add(' if ( (itemHeight < parseInt('+IntToStr(PopUpHeight)+')) && (itemHeight > 0) ){ ');
        Add('   document.getElementById("'+HTMLName+'popup").style.height = itemHeight;');
        Add('   document.getElementById("'+HTMLName+'popup").style.overflow = "";');
        Add(' } else {');
        Add('   document.getElementById("'+HTMLName+'popup").style.height = parseInt("'+IntToStr(PopUpHeight)+'");');
        Add('   document.getElementById("'+HTMLName+'popup").style.overflow = "auto";');
        Add(' }');
        Add('}');


       Add('function '+HTMLName+'KeyDown(event,obj){');
       Add(' var isIE = navigator.appName.indexOf("Microsoft") != -1;');
       Add(' ' + HTMLName + 'obj.UsedKeyb = true;');       
       Add(' var key;');
       Add(' if (isIE) {key = event.keyCode;} else {key = event.which;}');
       Add('   displayRowCount = 0;');

       Add(' if ((key == 40) || (key == 38) || (key == 13) || (key == 33) || (key == 34) || (key == 35) || (key == 36)) {');
       Add('  if (key == 40) {');      // down key
       Add('    CCHighLightNext("'+HTMLName+'",'+HTMLName+'obj);');
       Add('  }');
       Add('  if (key == 38) {');      // up key
       Add('    CCHighLightPrevious("'+HTMLName+'",'+HTMLName+'obj);');
       Add('  }');
       Add('  if (key == 33) {');      // pgup key
       Add('    CCHighLightPrevious("'+HTMLName+'",'+HTMLName+'obj,"pgup");');
       Add('  }');
       Add('  if (key == 34) {');      // pgdn key
       Add('    CCHighLightNext("'+HTMLName+'",'+HTMLName+'obj,"pgdn");');
       Add('  }');
       Add('  if (key == 35) {');      // end key
       Add('    CCHighLightNext("'+HTMLName+'",'+HTMLName+'obj,"end");');
       Add('  }');
       Add('  if (key == 36) {');      // home key
       Add('    CCHighLightPrevious("'+HTMLName+'",'+HTMLName+'obj,"home");');
       Add('  }');
       Add('  if (key == 13) {');     // Enter key
       Add('    '+HTMLName+'SelectHighLighted('+HTMLName+'obj);');
       Add('    obj.ItemSel = true;');       
       Add('  }');
       Add(' }');
       Add(' else ');
       Add(' {');
       Add('    obj.ItemSel = false;');
       Add(' }');
       Add('}');

       Add('</script>');
    end;
    Result := LScript.Text;
    LScript.Free;
  end;

  procedure MakeCScript;
  begin
    CScript := TStringList.Create;
    with CScript do
    begin
      Add('function CCshowWindowedObjects(show,ALeft,ATop,ARight,ABottom) {');
      Add(' isIE = navigator.appName.indexOf("Microsoft") != -1;');
      Add(' hideWindowedControls = true;');
      Add(' if (hideWindowedControls) {');
      Add('   var windowedObjectTags = new Array("SELECT", "IFRAME", "OBJECT","APPLET","EMBED");');
      Add('   var windowedObjects = new Array();');
      Add('   var j=0;');
      Add('   if (isIE == true) {');
      Add('     for (var i=0; i<windowedObjectTags.length; i++) {');
      Add('       var tmpTags = document.all.tags(windowedObjectTags[i]);');
      Add('       if (tmpTags.length > 0) {');
      Add('         for (var k=0; k<tmpTags.length; k++) {');
      Add('           windowedObjects[j++] = tmpTags[k];');
      Add('         }');
      Add('       }');
      Add('     }');
      Add('   }');
      Add('   else {');
      Add('     for (var i=0; i<windowedObjectTags.length; i++) {');
      Add('       var tmpTags = document.getElementsByTagName(windowedObjectTags[i]);');
      Add('       if (tmpTags.length > 0) {');
      Add('         for (var k=0; k<tmpTags.length; k++) {');
      Add('          if (tmpTags[k].style.visibility != "hidden")');
      Add('           windowedObjects[j++] = tmpTags[k];');
      Add('         }');
      Add('       }');
      Add('     }');
      Add('   }');
      Add('   for (var i=0; i<windowedObjects.length; i++) {');
      Add('     if (show)');
      Add('      { windowedObjects[i].style.visibility = "visible";');
      Add('      }');
      Add('     else {');

      Add('if (windowedObjects[i].style.left == "") {');
      Add('  var cell = windowedObjects[i];');
      Add('  var leftBegin = 0;');
		  Add('  var elem = cell;');
      Add('  do');
			Add('    leftBegin += elem.offsetLeft;');
      Add('  while ((elem = elem.offsetParent));');
      Add('  leftInt = leftBegin;}');
      Add('else {');
      Add('  var leftObject = document.getElementById(windowedObjects[i].id).style.left;');
      Add('  var leftInt = parseInt(leftObject.substring(0,leftObject.length - 2));}');
      Add('  if (windowedObjects[i].style.top == ""){');
      Add('var cell = windowedObjects[i];');
      Add('var topBegin = 0;');
      Add('elem = cell;');
      Add('do');
      Add('  topBegin += elem.offsetTop;');
      Add('while ((elem = elem.offsetParent))');
      Add('topInt = topBegin;}');
      Add('else {');
      Add('  var topObject = windowedObjects[i].style.top;');
      Add('  var topInt = parseInt(topObject.substring(0,topObject.length - 2));}');
      Add('  var widthObject = windowedObjects[i].offsetWidth;');
      Add('  var heightObject = windowedObjects[i].offsetHeight;');
      Add('  var rightInt = leftInt + parseInt(widthObject);');
      Add('  var bottomInt = topInt + parseInt(heightObject);');

      Add('var topRegion = 0;');
      Add('var leftRegion = 0;');
      Add(' var elem = windowedObjects[i];');
      Add(' do {');
      Add('   if (elem.tagName.toUpperCase() != "BODY") {');
      Add('     if (elem.id.indexOf("REGION") >= 0) {');
      Add('       var c = elem;');
      Add('       do {');
      Add('         leftRegion += c.offsetLeft;');
      Add('         topRegion += c.offsetTop;');
      Add('       }');
      Add('       while ((c = c.offsetParent))');
      Add('       break;');
      Add('     }');
      Add('  }');
      Add('} while ((elem = elem.offsetParent))');


      Add(' leftInt = leftInt + leftRegion;');
      Add(' topInt = topInt + topRegion;');
      Add(' bottomInt = bottomInt + topRegion;');
      Add(' rightInt = rightInt + leftRegion;');

      Add('  if ((((leftInt >= ALeft) && (leftInt <= ARight)) | ((rightInt >= ALeft)');
      Add('&& (rightInt <= ARight)) | ((leftInt <= ALeft) && (rightInt >= ALeft)))');
      Add('&& (((topInt >= ATop) && (topInt <= ABottom)) | ((bottomInt >= ATop) && (bottomInt <= ABottom))))');
      Add('  windowedObjects[i].style.visibility = "hidden";   }');
      Add('   }');
      Add(' }');
      Add('}');

      Add('function CCgetPositionDiv(divObject,obj) {');
      Add(' var cell = divObject;');
      Add(' var leftBegin = 0;');
      Add(' var topBegin = 0;');
      Add(' var elem = cell;');
      Add(' do {');
      Add('   leftBegin += elem.offsetLeft;');
      Add('   topBegin += elem.offsetTop;');
      Add(' }');
      Add(' while ((elem = elem.offsetParent));');
      Add(' obj.DivStartLeft = leftBegin;');
      Add(' obj.DivStartTop = topBegin;');

      //Modified - display none veroorzaakt offsetwidth 0
//      Add(' divObject.style.display = ""');
      Add(' obj.DivEndLeft = obj.DivStartLeft + divObject.offsetWidth;');
//      Add(' alert("startTop :" + obj.DivStartTop + "  offsetHeight : " + divObject.offsetHeight);');
      Add(' obj.DivEndTop = obj.DivStartTop + divObject.offsetHeight;');
      //Modified - display none veroorzaakt offsetwidth 0
//      Add(' divObject.style.display = "none"');
      Add('}');

      Add('function CCDisplayAllRows(CCount,CName){');
      Add('for (i=0;i<CCount;i++){');
      Add('  elRow = document.getElementById( CName + "RowNo"+i);');
      Add('  elRow.style.display = "";');
      Add('  }');
      Add('}');

      Add('function CCNormalAllRows(CCount,CName){');
      Add('for (i=0;i<CCount;i++){');
      Add('  RowID = CName + "RowNo" + i;');
      Add('el = document.getElementById(RowID);');
      Add('el.style.background = "";');
      Add('  }');
      Add('}');

      Add('function CCShowUnHighLighted(id,CCount,obj){');
      Add(' el = document.getElementById(id);');
      Add(' if(id != (obj.ID + "RowNo" + obj.RCount) ){');
      Add(' var isIE = navigator.appName.indexOf("Microsoft") != -1;');
      Add(' if (isIE) ');
      Add('  el.style.background = "";');
      Add(' else');
      Add('  el.style.background = obj.PopUpColor;');
      Add(' for (k=0; k<=CCount;k++)');
      Add('   el.getElementsByTagName("TD")[k].style.color = obj.ForeColor;');
      Add(' if (obj.HighLightedRow == id)');
      Add('   obj.HighLightedRow = "";');
      Add(' }');
      Add('}');      

      Add('function CCShowHighLighted(id,obj,CCount){');
      Add(' if (obj.HighLightedRow !="")');
      Add('   CCShowUnHighLighted(obj.HighLightedRow,CCount,obj);');
      Add(' obj.HighLightedRow = id;');
      Add(' if(id != (obj.ID + "RowNo" + obj.RCount) ){');
      Add('   el = document.getElementById(id);');
      Add('   el.style.background = obj.ClrSel;');
      Add('   for (k=0; k<=CCount;k++)');
      Add('     el.getElementsByTagName("TD")[k].style.color = obj.ClrTextSel;');
      Add('  }');
      Add('}');

      Add('function CCHighLightSelected(CName,obj,DoCase){');

      Add(''
        +'var editor = document.getElementById(CName + "_TEXT");'#13
        +'var keyval = editor.value;'#13
        +'if (DoCase == false)'#13
        +'  keyval = keyval.toUpperCase();'#13

        +'if ( ('+HTMLName+'obj.ItemIndex >= 0) && (! '+HTMLName+'obj.UsedKeyb))'#13
        +'  i = parseInt('+HTMLName+'obj.ItemIndex);'#13
        +'else'#13
        +'i = CCBinary(obj,keyval);'#13

        +'  if (i != -1)'#13
        +'  {'#13
        +'    rowid = CName + "RowNo"+i;'#13
        +'    CCShowHighLighted(rowid,obj, obj.CCount);'#13

            //scroll row into view'#13
        +'    var elRow = document.getElementById(rowid);'#13
        +'    var cell = document.getElementById(obj.ID+"popup");'#13

        +'    if ((obj.popupHeight + parseInt(cell.scrollTop) ) < (parseInt(elRow.offsetTop) + parseInt(elRow.offsetHeight)))'#13
        +'    {'#13
        +'      var rowh = parseInt(elRow.offsetTop);'#13
        +'      cell.scrollTop = rowh;'#13
        +'    }'#13
        +'  }'#13);
      Add('}');


      Add('function CCHighLightNext(CName, obj, special) {');
      Add('if (obj.HighLightedRow != ""){');
      Add('  elRow = document.getElementById(obj.HighLightedRow);');
      Add('  var rIndex = elRow.id.substr(elRow.id.indexOf("RowNo")+5,elRow.id.length);');
      Add('  rIndex = parseInt(rIndex);');
      Add('   if (rIndex <= obj.RCount-1){');
      Add('     nexIndex = rIndex + 1;');
      Add('  if (special == "pgdn")');
      Add('    nexIndex = rIndex + 10;');
      Add('  if ( (nexIndex > obj.RCount-1) || (special == "end") )');
      Add('    nexIndex = obj.RCount-1;');
      Add('     nexRow = CName + "RowNo" + nexIndex;');
      Add('     elRow = document.getElementById(nexRow);');
      Add('     while ((nexIndex <= obj.RCount) && (elRow.style.display != "")){');
      Add('      nexIndex = nexIndex + 1;');
      Add('      nexRow = CName + "RowNo" + nexIndex;');
      Add('      elRow = document.getElementById(nexRow);');
      Add('     }');
      Add('     if ((nexIndex <= obj.RCount) && (elRow.style.display == "")){');
      Add('       CCShowUnHighLighted(obj.HighLightedRow,obj.CCount,obj);');
      Add('       CCShowHighLighted(nexRow,obj,obj.CCount);');

           //scroll row into view');
      Add('    var cell = document.getElementById(obj.ID+"popup");');

      Add('    if ( (obj.popupHeight + parseInt(cell.scrollTop) ) < (parseInt(elRow.offsetTop) + parseInt(elRow.offsetHeight)))');
      Add('    {');
      Add('      var rowh = parseInt(elRow.offsetHeight);');
      Add('      if (special == "pgdn")');
      Add('        rowh = rowh*10;');
      Add('      cell.scrollTop = parseInt(cell.scrollTop) + rowh;');
      Add('    }');

      Add('    if (special == "end")');
      Add('      cell.scrollTop = cell.scrollHeight;');

      Add('     }');
      Add('   }');
      Add(' }');
      Add(' else');
      Add(' {');
                //select first row in the popup
      Add('          firstRow = CName + "RowNo0";');
      Add('          CCShowHighLighted(firstRow,obj,obj.CCount);');
      Add(' }');
      Add('}');


      Add('function CCHighLightPrevious(CName, obj, special) {');
      Add('if (obj.HighLightedRow != ""){');
      Add('  elRow = document.getElementById(obj.HighLightedRow);');
      Add('  var rIndex = elRow.id.substr(elRow.id.indexOf("RowNo")+5,elRow.id.length);');
      Add('  if (rIndex > 0){');
      Add('    prevIndex = rIndex - 1;');
      Add('  if (special == "pgup")');
      Add('    prevIndex = rIndex - 10;');
      Add('  if ( (prevIndex < 0) || (special == "home") )');
      Add('    prevIndex = 0;');
      Add('    prevRow = CName + "RowNo" + prevIndex;');
      Add('    elRow = document.getElementById(prevRow);');
      Add('    while ((prevIndex >= 1) && (elRow.style.display != "")){');
      Add('     prevIndex = prevIndex - 1;');
      Add('     prevRow = CName + "RowNo" + prevIndex;');
      Add('     elRow = document.getElementById(prevRow);');
      Add('    }');
      Add('    if ((prevIndex >= 0) && (elRow.style.display == "")){');
      Add('      CCShowUnHighLighted(obj.HighLightedRow,obj.CCount,obj);');
      Add('      CCShowHighLighted(prevRow,obj,obj.CCount);');

          //scroll row into view
      Add('    var cell = document.getElementById(obj.ID+"popup");');
      Add('    if (cell.scrollTop > parseInt(elRow.offsetTop))');
      Add('    {');
      Add('      var rowh = parseInt(elRow.offsetHeight);');
      Add('      if (special == "pgup")');
      Add('        rowh = rowh*10;');
      Add('      cell.scrollTop = parseInt(cell.scrollTop) - rowh;');

      Add('      if (cell.scrollTop < (elRow.offsetHeight*2))');
      Add('        cell.scrollTop = 0;');
      Add('    }');

      Add('    if (special == "home")');
      Add('      cell.scrollTop = 0;');

      Add('    }');
      Add('  }');
      Add(' }');
      Add('}');


      Add(''
        +'function CCBinary(obj, key)'#13
        +'{'#13
        +'  var item = obj.Item;'#13
        +'  var count = obj.RCount;'#13
        +'  var low = 0;'#13
        +'  var high = count-1;'#13
        +'  var mid = null;'#13

        +'  while(low <= high)'#13
        +'  {'#13
        +'    mid = (low + high)/2;'#13
        +'    mid = "" + mid;'#13

        +'    if (mid.indexOf(".") >= 0)'#13
        +'         mid = mid.substring(0,mid.indexOf("."));'#13

        +'    mid = parseInt(mid);'#13

        +'    if (key < item[mid].substring(0,key.length))'#13
        +'      high = mid-1;'#13
        +'    else if (key > item[mid].substring(0,key.length))'#13
        +'      low = mid+1;'#13
        +'    else'#13
        +'    {'#13
        +'        mid = parseInt(mid);'#13

        +'      while (mid > 0)'#13
        +'      {'#13
        +'        if (key == item[mid-1].substring(0,key.length))'#13
        +'            mid--;'#13
        +'        else'#13
        +'            break;'#13
        +'      }'#13

        +'      return mid; //found'#13
        +'     }'#13
        +'  }'#13

        +'  return -1; //not found'#13
        +'}'#13
      );

    end;
  end;


  function StripCRLF(s:string): string;
  begin
    while pos(#13,s) > 0 do
      delete(s,pos(#13,s),1);
    while pos(#10,s) > 0 do
      delete(s,pos(#10,s),1);
    Result := s;
  end;

begin
  if (PopUpColor <> clNone) and (PopUpColorTo <> clNone) then
    gradient := ' FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=' +
        IntToStr(1 - Integer(PopUpColorGradientDirection)) + ', StartColorStr='#39
        + HTMLClr(PopUpColor) + #39', EndColorStr='#39 + HTMLClr(PopUpColorTo) + #39');';

    gradient := gradient + ' background:'+HTMLClr(FPopUpColor)+';';

     {$IFNDEF TMSIW9}
     if (Font.CSSStyle = '') then
     {$ENDIF}
     begin
       {$IFDEF TMSIW6}
       fontstyle := ' ' + Font.FontToStringStyle(AContext.WebApplication.Browser) + ' ';
       {$ELSE}
       fontstyle := ' ' + Font.FontToStringStyle(WebApplication.Browser) + ' ';
       {$ENDIF}
     end;


  if TabOrder <> -1 then
    tabidx := 'tabindex="'+IntToStr(TabOrder)+'" '
  else
    tabidx := '';

  //InitText := Text;
  InitText := EmptyStr;
  if (ItemIndex >= 0)then
    InitText := Items[ItemIndex].RowData[0];

 if DropDownImageURL <> EmptyStr then
  begin
    buttonval := '<img src="' + DropDownImageURL + '" '
      +tabidx +IIF(Editable,' onclick="'+HTMLName+'showdivonclick()"', '') + '>';
  end
  else if FDropDownImage.Empty then
  begin

    if (AContext.WebApplication.Browser = brIE) then
      buttonval := '<font face="webdings">6</font>'
    else
      buttonval := '...';

    buttonval := '<BUTTON '+tabidx +IIF(Editable,'','disabled ')+'onclick="'+HTMLName+'showdivonclick()"'
     + ' style="width:18px;height:22px;vertical-align:middle;text-align:center;padding:0px;top:-3;position:relative;">'
     + '<div style=" font-family:Webdings;font-size:9pt;margin:0px;padding:0px;border:0px;margin-top:-0.2em;margin-right:-0.1em;">'
     + buttonval + ' </div></BUTTON>'

  end
  else
  begin

    if FDropDownImage.IsGIF then
    {$IFDEF TMSIW71}
      buttonval := TIWServerControllerBase.NewCacheFile('gif', true)
    {$ELSE}
      buttonval := TIWServerControllerBase.NewCacheFile('gif')
    {$ENDIF}
    else
    {$IFDEF TMSIW71}
      buttonval := TIWServerControllerBase.NewCacheFile('jpg', true);
    {$ELSE}
      buttonval := TIWServerControllerBase.NewCacheFile('jpg');
    {$ENDIF}

    FDropDownImage.SaveToFile(buttonval);

    buttonval := '<img src="' + GetCacheDir(Self) + ExtractFilename(buttonval)+ '" '
      +tabidx +IIF(Editable, ' onclick="'+HTMLName+'showdivonclick()"', '') + '>';
  end;


  htmlres := '' +
     MakeScript
     + '<style>.testmystyle {font-family:"Verdana";font-size:15pt}</style>'#13
     + '    <input ' + tabidx + IIF(Editable,'','disabled ') + 'type='
     + IIF(FPasswordPrompt, 'password', 'text') + ' name="' + HTMLName +'_TEXT"'
     {$IFNDEF TMSIW9}
     + ' class="'+font.CSSStyle+'"'
     {$ENDIF}
     + ' id="' + HTMLName +'_TEXT"'
     + IIF(MaxLength > 0, ' maxlength=' + IntToStr(MaxLength))
//     + ' size=' + IntToStr((Width div 7)-5)
     + ' style="width:'+inttostr(width-20)+';'
     + fontstyle
     + IIF(ReadOnly, ' readonly', '')
     + IIF(FFlat, ' border-style:solid;border-width:'+inttostr(FBorderWidth)+ 'px;border-color:'+HTMLClr(FBorderColor)+';')
     + IIF(FColor <> clNone, ' background-color:'+HTMLClr(FColor)+';')
     + '"'
     + ' value="' + InitText + '"'
     + ' onKeyPress="return '+HTMLName+'noenter(event);"'
     + IIF(DropDownDisplay <> ddManual, ' onKeyUp="if(this.value.length >= '+ IntToStr(LookupAfterChars)+')'+HTMLName+'ShowLookUp(event)"', '')
     + IIF(DropDownDisplay = ddOnFocus, ' onClick="'+HTMLName+'ShowLookUp(event)"', '')
		 + ' onFocus="'+HTMLName+'obj.ItemSel = ''true'';"'     
     + ' onBlur="'+HTMLName+'Blur(this,'+HTMLName+'obj);'+HTMLName+'docMouseUp();"'
		 + ' onKeyDown="'+HTMLName+'KeyDown(event,'+HTMLName+'obj)"'

     + ' autocomplete="off"'
     + IIF(FAlignment <> taLeftJustify,MakeAlign(FAlignment))
     + ' onFocus="'+HTMLName+'Focus(this);'
// + iif(FFocusColor <> FColor,' this.style.backgroundColor = '#39+HTMLClr(FocusColor)+#39';','')
     + '">' + buttonval
     + '<br>'
     + '<div'
     {$IFNDEF TMSIW9}
     + ' class="'+font.CSSStyle+'"'
     {$ENDIF}
     +' onMouseDown="'+HTMLName+'resetdoc();" id="'+HTMLName
     + 'checklist" style="z-index:1000;display:none; position:absolute; '+gradient
     + 'border-color:gray;border-width:1px;border-bottom:2 outset black;border-right:2 outset black;border-style:solid;padding:0px;'
     + ' width:'+IntToStr(PopUpWidth)+'px;'
     //+ IIF(PopUpWidth > 0, ' width:'+IntToStr(PopUpWidth)+'px;', '')
     //+ IIF(PopUpHeight > 0, ' height:'+IntToStr(PopUpHeight)+'px;overflow:auto;', '')
     + fontstyle
     + '">';

    //ColWidth := Width div FColCount;
    S:= '';

    if PopUpHeight > 0 then
      //S:= 'overflow-y:auto; height:'+inttostr(FDropDownHeight)+'px;';
      S:= ' height:'+inttostr(PopUpHeight)+'px;';
    if PopUpWidth > 0 then
      //S:= S + 'overflow-x:auto; width:'+inttostr(FDropDownWidth)+'px;';
      S:= S + ' width:'+inttostr(PopUpWidth)+'px;';

       S := S + ' overflow:auto;';
       
    if S <>'' then
      S:= 'style="'+S+'"';

    htmlres := htmlres + '<div id="'+HTMLName+'popup" '+S+'>';
    S:= '';
 //   if FGridBorderColor <> clNone then
 //     S := 'bordercolor="'+HTMLClr(FGridBorderColor)+'"';

    gborder := '0';
    if FShowGridBorder then
      gborder := '1';

    htmlres := htmlres + '<table width="100%" style="color:'+HTMLClr(PopUpFont.Color)+';font-family:'+PopUpFont.FontName+';font-size:'+IntToStr(PopUpFont.Size)+';cursor:default;" id="'+ HTMLName +'tbl" cellspacing="0" cellpadding="2" border="'+gborder+'" '+S+'>'#13;

    if ColumnTitles.Visible then
      begin
        backcolor := '';
        forecolor := '';
        style := '';

        if (ColumnTitles.BackColor <> clNone) then
          backcolor := HTMLClr(ColumnTitles.BackColor);

        if (ColumnTitles.Font.Color <> clNone) then
          forecolor := HTMLClr(ColumnTitles.Font.Color);

      style := 'style="background-color:'+backcolor+';color:'+forecolor+';font-size:'+IntToStr(ColumnTitles.Font.Size)+';font-family:'+ColumnTitles.Font.FontName+';"';

      htmlres := htmlres + '<TR '+style+'>';
        for i:=0 to ColCount-1 do
        begin
          rowtitle := '';
          if ColumnTitles.Titles.Count > i then
            rowTitle := ColumnTitles.Titles[i];
          htmlres := htmlres + '<TD>'+rowtitle+'&nbsp;</TD>';
        end;

        htmlres := htmlres + '</TR>';

      end;


    for r:=0 to FComboRows.Count-1 do
    begin
      rowval := EmptyStr;
      if FComboRows[r].RowData.Count <> 0 then
        rowval := FComboRows[r].RowData[0];

      htmlres := htmlres + '<span id="val'+ HTMLName +'RowNo'+inttostr(r)+'" style="visiblity:hidden;display:none;">'+rowval+'</span>';
      htmlres := htmlres + '<tr id="'+ HTMLName +'RowNo'+inttostr(r)+'" value="'+rowval+'" onmouseup = "'+HTMLName+'ChangeEditValue('''+ HTMLName +'_TEXT'','''+ HTMLName +'RowNo'+inttostr(r) +''','+ inttostr(r)+ ')" onmousemove = "CCShowHighLighted('''+ HTMLName +'RowNo'+inttostr(r) +''','+HTMLName+'obj,'+IntToStr(FColCount - 1)+')" onmouseout = "CCShowUnHighLighted('''+ HTMLName +'RowNo'+inttostr(r) +''','+IntToStr(FColCount - 1)+','+HTMLName+'obj)">'#13;

      for c:=0 to FColCount-1 do
      begin
//        htmlres := htmlres + '<td width="'+inttostr(ColWidth)+'">'#13;
        htmlres := htmlres + '<td>'#13;
        if c < FComboRows[r].RowData.Count then
          //htmlres := htmlres + '<font class="'+font.CSSStyle+'" '+S+'>' + FComboRows[r].RowData[c] + '&nbsp;</font>'
          htmlres := htmlres + '' + FComboRows[r].RowData[c] + '&nbsp;'
        else
          //htmlres := htmlres + '<font class="'+font.CSSStyle+'" '+S+'>&nbsp;</font>';
          htmlres := htmlres + '&nbsp;';
        htmlres := htmlres + '</td>'#13;
      end;
      htmlres := htmlres + '</tr>'#13;
    end;

      //NoMatchingItems
      if ( (LookupMethod = lmFilter) and (NoMatchingItems <> EmptyStr) ) then
      begin
        htmlres := htmlres + '<tr id="' + HTMLName + 'RowNo' +  IntToStr(FComboRows.Count)  + '" style="display:none;" >';
        htmlres := htmlres + '<td nowrap colspan='+IntToStr(ColCount)+'>';
        htmlres := htmlres + NoMatchingItems;
        htmlres := htmlres + '</td>';
        htmlres := htmlres + '</tr>';
      end;
      //end NoMatchingItems

    htmlres := htmlres + '</table>';
    htmlres := htmlres + '</div>';

    htmlres := htmlres
      + '</div>'#13
  //    + ' </td>'#13
  //    + ' </tr></table>';
   + '';

    MakeCScript;

    {$IFDEF TMSIW6}
    TIWComponent40Context(AContext).AddToJavaScriptOnce(CScript.Text);
    {$ELSE}
    AddToJavaScriptOnce(CScript.Text);
    {$ENDIF}

    FreeAndNil(CScript);

    if SupportsInput and Required then
    begin
      {$IFDEF TMSIW6}

        {$IFDEF TMSIW9}
        TIWComponent40Context(AContext).AddValidation('getSubmitForm().' + HTMLName + '.value.length==0'
         , Format(RSValidationRequeredField, [FriendlyName]));
        {$ELSE}
        TIWComponent40Context(AContext).AddValidation('GSubmitter.' + HTMLName + '.value.length==0'
         , Format(RSValidationRequeredField, [FriendlyName]));
        {$ENDIF}

      {$ELSE}
      TIWAppForm(Owner).AddValidation('GSubmitter.' + HTMLName + '.value.length==0'
       , Format(RSValidationRequeredField, [FriendlyName]));
      {$ENDIF}
    end;

  Result := TIWHTMLTag.CreateTag('DIV');
  Result.Contents.AddText(htmlres);

  with Result.Contents.AddTag('INPUT') do
  begin
    AddStringParam('TYPE','hidden');
    AddStringParam('NAME',HTMLName+'');
    AddStringParam('ID',HTMLName+'_INPUT');
    AddStringParam('VALUE', IntToStr(ItemIndex) + '~' + Text);
  end;

end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetAlignment(const Value: TAlignment);
begin
  FAlignment := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetColCount(const Value: Integer);
begin
  if (Value > 1) then
    FColCount := Value
  else
    FColCount := 1;
  Invalidate;
end;

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

procedure TTIWMultiColumnComboBox.SetBorderColor(const Value: TColor);
begin
  FBorderColor := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetBorderWidth(const Value: Integer);
begin
  FBorderWidth := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetColor(const Value: TColor);
begin
  FColor := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------
procedure TTIWMultiColumnComboBox.SetFlat(const Value: Boolean);
begin
  FFlat := Value;
  Invalidate;
end;

procedure TTIWMultiColumnComboBox.SetColumnTitles(const Value: TTIWColumnTitles);
begin
  FColumnTitles.Assign(Value);
  Invalidate;
end;

procedure TTIWMultiColumnComboBox.SetDropDownImage(const Value: TIPicture);
begin
  FDropDownImage.Assign(Value);
end;

{$IFDEF TMSIW72}
function TTIWMultiColumnComboBox.get_HasTabOrder: boolean;
begin
  {$IFNDEF TMSIW72_NEW}
  Result := false;
  {$ELSE}
  Result := true;
  {$ENDIF}
end;
{$ENDIF}

{$IFDEF TMSIW72_NEW}
function TTIWMultiColumnComboBox.get_ShouldRenderTabOrder: Boolean;
begin
  Result := false;
end;
{$ENDIF}


//------------------------------------------------------------------------------
{procedure TTIWColumnComboBox.SetList(const Value: TStringList);
begin
  FList.Assign(Value);
end;
}


{ TTIWColumnTitles }

constructor TTIWColumnTitles.Create;
begin
    FBackColor := clBtnFace;
    FFont := TIWFont.Create;
    FTitles := TStringList.Create;
    FVisible := false;
end;

destructor TTIWColumnTitles.Destroy;
begin
  FFont.Free;
  FTitles.Free;
  inherited;
end;

procedure TTIWColumnTitles.Assign(Source: TPersistent);
begin
  if not (Source is TTIWColumnTitles) then
    raise Exception.Create('Cannot assign Source to TTIWColumnTitles');

  with Source as TTIWColumnTitles do
  begin
    FBackColor := BackColor;
  //  FTitles.Assign(Titles);
    FTitles := Titles;
    FVisible := Visible;
    FFont.Assign(Font);
  end;
end;

procedure TTIWColumnTitles.SetBackColor(const Value: TIWColor);
begin
FBackColor := Value;
end;

procedure TTIWColumnTitles.SetFont(const Value: TIWFont);
begin
FFont := Value
end;


procedure TTIWColumnTitles.SetTitles(const Value: TStrings);
begin
  FTitles.Assign(Value);
end;

procedure TTIWColumnTitles.SetVisible(const Value: boolean);
begin
  FVisible := Value;
end;



end.
