Index » Empathy Jukebox : Blob 666cd4 / Main.pas
unit Main;

//   Copyright (C) 2012 Matthew Smith

//    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 3 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.

//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

interface

uses
  Forms,Windows, Messages, SysUtils, Classes, Graphics, Controls, Menus,
  ImgList, ExtCtrls, ComCtrls, Buttons, StdCtrls, MPlayer,checklst, Gauges,
  olespeech,mmsystem, ToolWin,registry,windowsversion,
  shellapi,OleCtrls,jpeg,global,volume,
{$IFNDEF kiosk}
 printcatalog,
{$ENDIF}
videoform,
inifuncs, Dialogs,resourceskins,commctrl;

const INIFILE='Empathy.ini';
const VOLINCREMENTS =150;


type TMDeviceChange = record
  Msg : Cardinal;
  Event : Uint;
  dwData : pointer;
  Result : Longint;
  end;


  type
  Tmainform = class(TForm)
    playpanel: TPanel;
    albumlist: TComboBox;
    Timers: TTimer;
    Playlist: TPanel;
    Dalbumlist: TComboBox;
    dtracklist: TListBox;
    dplaylist: TListBox;
    playlistcaption: TLabel;
    numberoftracks: TTimer;
    showcover: TCheckBox;
    tracklist: TListBox;
    transport: TPanel;
    Stop: TSpeedButton;
    play: TSpeedButton;
    fwd: TSpeedButton;
    bck: TSpeedButton;
    timemodebut: TSpeedButton;
    counter: TLabel;
    tr: TLabel;
    skipforward: TSpeedButton;
    skipback: TSpeedButton;
    progress: TTrackBar;
    coverPanel: TPanel;
    cover: TImage;
    Bevel1: TBevel;
    Bevel2: TBevel;
    pause: TSpeedButton;
    vol: TTrackBar;
    vol_triangle: TImage;
    audition: TSpeedButton;
    mutebut: TSpeedButton;
    dj: TSpeedButton;
    Bevel3: TBevel;
    coverpickbut: TSpeedButton;
    thumbspopupmenu: TPopupMenu;
    SelectAlbum: TMenuItem;
    Addalltrackstoplaylist: TMenuItem;
    ReturntoPlayer: TMenuItem;
    dplaylistmenu: TPopupMenu;
    popupplay: TMenuItem;
    popupremove: TMenuItem;
    Cancel1: TMenuItem;
    playbutmod: TShape;
    Add: TButton;
    del: TButton;
    toolbar: TPanel;
    butcd: TImage;
    butcdlist: TImage;
    butjukebox: TImage;
    butrandom: TImage;
    butimages: TImageList;
    bevel4: TBevel;
    Bevel5: TBevel;
    MainMenu: TMainMenu;
    filemenu: TMenuItem;
    fileexit: TMenuItem;
    modemenu: TMenuItem;
    Cdplayerbut: TMenuItem;
    playlistbut: TMenuItem;
    randombut: TMenuItem;
    jukeboxbut : TMenuItem;
    clearlist: TButton;
    helpmenu: TMenuItem;
    menuabout: TMenuItem;
    reload: TMenuItem;
    insert: TButton;
    N2: TMenuItem;
    buttonstimer: TTimer;
    SaveDialog: TSaveDialog;
    OpenDialog: TOpenDialog;
    procedure albumlistChange(Sender: TObject);
    procedure tracklistClick(Sender: TObject);
    procedure MPNotify(Sender: TObject);
    procedure playClick(Sender: TObject);
    procedure StopClick(Sender: TObject);
    procedure bckClick(Sender: TObject);
    procedure fwdClick(Sender: TObject);
    procedure TimersTimer(Sender: TObject);
    procedure timemodebutClick(Sender: TObject);
    procedure playlistbutClick(Sender: TObject);
    procedure CdplayerbutClick(Sender: TObject);
    procedure randombutClick(Sender: TObject);
    procedure DalbumlistChange(Sender: TObject);
    procedure dtracklistClick(Sender: TObject);
    procedure AddClick(Sender: TObject);
    procedure dplaylistClick(Sender: TObject);
    procedure DelClick(Sender: TObject);
    procedure restoreClick(Sender: TObject);
    procedure picturepanelClick(Sender: TObject);
    procedure clearlistClick(Sender: TObject);
    procedure coverMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure numberoftracksTimer(Sender: TObject);
    procedure coverClick(Sender: TObject);
    procedure showcoverClick(Sender: TObject);
    procedure skipbackward(Sender: TObject);
    procedure progressChange(Sender: TObject);
    procedure skipforwardClick(Sender: TObject);
    procedure pauseClick(Sender: TObject);
    procedure volChange(Sender: TObject);
    procedure mutebutClick(Sender: TObject);
    procedure auditionClick(Sender: TObject);
    procedure djClick(Sender: TObject);
    procedure coverpickbutClick(Sender: TObject);
//    procedure thumbviewgo(show : boolean);
    procedure FormCreate(Sender: TObject);
    procedure trackeditClick(Sender: TObject);
    procedure OptionsClick(Sender: TObject);
    procedure ThumbscancelClick(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure ReturntoPlayerClick(Sender: TObject);
    procedure AddalltrackstoplaylistClick(Sender: TObject);
    procedure FormKeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure popupplayClick(Sender: TObject);
    procedure popupremoveClick(Sender: TObject);
    procedure burncdbutClick(Sender: TObject);
    procedure launchscreensaverClick(Sender: TObject);
    procedure dplaylistDblClick(Sender: TObject);
    procedure jukeboxbutClick(Sender: TObject);
    procedure tracklistDblClick(Sender: TObject);
    procedure dtracklistDblClick(Sender: TObject);
    procedure ripcdClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure buttonsMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure butfilterClick(Sender: TObject);
    procedure filtermenuClick(Sender: TObject);
    procedure fileexitClick(Sender: TObject);
    procedure menuaboutClick(Sender: TObject);
    procedure reloadClick(Sender: TObject);
    function loadtitles (sender : TListbox; albumindex : integer) : boolean;
    procedure hyperlink_helpfilesystemClick(Sender: TObject);
    procedure hyperlink_helpalbuminfoClick(Sender: TObject);
    procedure helpClick(Sender: TObject);
    procedure insertClick(Sender: TObject);
    procedure dplaylistDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure dplaylistDragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure menuprintClick(Sender: TObject);
    procedure buttonstimerTimer(Sender: TObject);
    procedure butexploreClick(Sender: TObject);
    procedure menufiletagClick(Sender: TObject);
{$IFNDEF kiosk}
    procedure saveClick(Sender: TObject);
    procedure openClick(Sender: TObject);
{$ENDIF}
    private

    { Private declarations }

    procedure doDJ(album : string);

    procedure drawtriangle(pos : integer);
    procedure mpplay;

    procedure maketitles(path : string);
 //   procedure WMDeviceChange(var msg : TMDeviceChange); message WM_DEVICECHANGE;
    procedure hideall;
    procedure setupfrequency;





  public
    {$IFNDEF NEWMEDIAPLAYER}
    mp : TMediaplayer;
    {$ENDIF}
    {$IFDEF NEWMEDIAPLAYER}
    mp : TDXMP;
    {$ENDIF}

  function buildcontentlist(forceload : boolean) : boolean;
  procedure initlistboxes;

procedure sorttimemode;
function setuptrackname(num : integer) : string;

    { Public declarations }
  end;


talbumtype = record
album : string;
artist : string;
end;

type
  albumtype = array  of talbumtype;
  PlayListMatrixTrk = array of integer;
  PlayListMatrixAlb = array of string;
  PlayListMatrixAlbNumber = array of integer;




 type tdylist = record
  data : array of string;
  count : integer;
 end;

  Type
  MCI_DGV_SETAUDIO_PARMS = record
   dwCallback : DWORD;
   dwItem     : DWORd;
   dwValue : DWORD;
   dwOver : DWORD;
   lpstrAlgorithm : PChar;
   lpstrQuality : PChar;
  end;


function readini : boolean;
procedure writeini;
procedure showerror(txt : string; errortype : integer);
procedure alphablendbitmapwithcolor(blend : tbitmap;blendcolor : tcolor;source : tbitmap;alpha : real);
function extractalbumandaristfrompath(s : string;var artist : string;var album : string) : string;
function loadbitmap(target : timage;rc : string) : longint;
procedure badfile(fn : string;act : string);
function runprogram(commandline : string; windowstate : integer;waitfor :boolean) : boolean;
procedure loadbmpcompressedresource(resname : string;dest : tbitmap);
procedure loadblankmp3file;


const

DONTCHECKCACHE=false;
cdwidth =260;
cdheight =260;

VERSIONNO ='2.6';
APPTITLE ='Empathy v'+VERSIONNO;
PLAYLISTFILEHEADER = 'EMPATHYPLAYLISTFILEFORMAT';

DIVISION = 1000;
vtxtst_STATEMENT = 1;
vtxtst_QUESTION = 2;
vtxtst_COMMAND =4;
vtxtst_WARNING = 8;
vtxtst_READING = 16;
vtxtst_NUMBERS = 32;
vtxtst_SPREADSHEET = 64;
vtxtst_VERYHIGH = 128;
vtxtst_HIGH = 256;
vtxtst_NORMAL = 512;
  MCI_SETAUDIO               = 73;
  MCI_DGV_SETAUDIO_VOLUME    = 02;
  MCI_DGV_SETAUDIO_ITEM      = {viewgit}{/viewgit}800000;
  MCI_DGV_SETAUDIO_VALUE     = 000000;


var
SLOWPROCESSOR : boolean = FALSE;
DEBUGON : boolean = false;
MAINFORMWIDTH, MAINFORMHEIGHT : integer;
thumbsdone : boolean = false;
mainform: Tmainform;
albumcount : integer = 0;
album : albumtype;
currentalbumpath : string;
dcurrentalbumpath : string;
playmode : integer;
timermode: integer;
dcurrentlyplayingtrack : integer;
dCurrentTrack : integer;
dPlayListMatrixTrk : PlayListMatrixTrk;
dPlayListMatrixAlb : PlayListMatrixAlb;
albumref : albumtype;
albumrefonload : albumtype;
albumrefonloadcount : integer;
audition_mode : boolean;
winposX,winposY : integer;
olditem: integer;
paused : boolean;
muted : boolean;
//preferences :   Tpreferences;
deviceremoveable : boolean;
cancelthumbs : boolean;
thumbundercursor : TObject;
progressmove : boolean;
progresslastpos : dword;
hinttimercount : integer;
thumb : array of timage;
thumbcount : integer = 0;
loadedblankmp3file: boolean = false;
blankfilepath : string;
phrases : tdylist;
genre : tdylist;
artisttype : tdylist;
kiosk : boolean = true;
tvmode : boolean = false;



autoplaytime : integer = 60;
WEBSITEURL : string;
firstrun : boolean = true;
cached : boolean = false;
dice1 : tbitmap;
dice2 : tbitmap;
dice3 : tbitmap;
dice4 : tbitmap;

procedure uninstallfont;

implementation

uses random_dialog, cover,loadjpegorbmp, burn, jukeboxform, warn,aboutform,albuminfo,
   backgroundplay, tagmp3files,
  jbnoalbums,
  {$IFNDEF kiosk}
  tracklistform,
 {$ENDIF}

  empripmain; //videditform;



{$R *.DFM}
{$R WindowsXP.res}
{$R empathyres.res}




procedure loadbmpcompressedresource(resname : string;dest : tbitmap);
var
sr : Tresourcestream;
begin
sr:=TresourceStream.create(hinstance,resname,RT_RCDATA);
dest.LoadFromStream(sr);
sr.free;
end;




procedure badfile(fn : string;act : string);
begin
{$IFNDEF kiosk}
messagedlg('Error '+act+' file "'+fn+'".',mterror,[mbOk],0);

{$ENDIF}

end;



function loadbitmap(target : timage;rc : string) : longint;
begin
result:=0;
try
target.Picture.Bitmap.LoadFromResourceName(hinstance,rc);
//loadjpegresource(rc,target.picture.bitmap);
except;
result:=-1;
end;
end;


function extractalbumandaristfrompath(s : string;var artist : string;var album : string) : string;
var
x : integer;
a : integer;
begin
a:=1;
while(a<>0) do begin
  a:=pos('\',s);
  s:=copy(s,a+1,length(s)-a);
end;

//s:=copy(s,length(config.pathtocd)+1,(length(s)-length(config.pathtocd)));
x:=pos('__',s);
artist:=copy(s,0,x-1);
album:=copy(s,x+2,length(s)-x+2);
result:=album+' - '+artist;
end;



procedure alphablendbitmapwithcolor(blend : tbitmap;blendcolor : tcolor;source : tbitmap;alpha : real);
var
x,y : integer;
rin,rout : pbytearray;
outval : integer;
br,bg,bb : integer;

function rangecheck(inp : integer) : byte;
begin
     if inp>255 then outval:=255;
     if inp<0 then outval:=0;
     result:=byte(inp);
end;

begin
if SLOWPROCESSOR=TRUE then exit;
source.width:=blend.width;
source.height:=blend.height;
source.pixelformat:=pf24bit;
br:=getrvalue(ColorToRGB(blendcolor));
bg:=getgvalue(ColorToRGB(blendcolor));
bb:=getbvalue(ColorToRGB(blendcolor));


with source do begin
       for y:=0 to source.height -1 do begin
         rin:=scanline[y];
         rout:=source.scanline[y];
         x:=0;
      // application.processmessages;
         while x< 3*width-1 do begin
      // application.processmessages;

         outval:=round((alpha*(rin[x]-br))+br);
         rout[x]:=rangecheck(outval);
      // application.processmessages;
         outval:=round((alpha*(rin[x+1]-bg))+bg);
         rout[x+1]:=rangecheck(outval);
      // application.processmessages;

         outval:=round((alpha*(rin[x+2]-bb))+bb);
         rout[x+2]:=rangecheck(outval);
         x:=x+3;
         end;
     end;
end;
end;


procedure mainmenuvisible(i : boolean);
begin
mainform.filemenu.enabled:=i;
mainform.modemenu.enabled:=i;
//mainform.toolsmenu.enabled:=i;
end;


procedure installfont;
const
fontname='EMPTDIGI.TTF';
var
  rs : TResourceStream;
  pwd : array [0..MAX_PATH] of char;
  wd : string;
  areg : tregistry;
  rscreate : boolean;
begin
rs:=nil;
fillchar(pwd,sizeof(pwd),0);
getwindowsdirectory(pwd,sizeof(pwd));
wd:=pwd;
wd:=wd+'\fonts\'+fontname;
rscreate:=false;
if fileexists(wd)=false then begin
  try
  rscreate:=true;
  rs:=TResourceStream.Create(hInstance, 'FONT', RT_RCDATA);
  rs.SavetoFile(wd);
  SendMessage(HWND_BROADCAST,WM_FONTCHANGE,0,0);
except
end;
end;

areg:=tregistry.create;
try
areg.closekey;
areg.rootkey:=HKEY_LOCAL_MACHINE;
if getwindowsversion>2 then areg.openkey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',false) else areg.openkey('SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts',false);
areg.writestring('Empathy Digital Font (TrueType)',fontname);
except;
end;
AddFontResource(PChar(wd));
if rscreate=true then rs.free;
end;


procedure uninstallfont;
const
fontname='EMPTDIGI.TTF';
var
  pwd : array [0..MAX_PATH] of char;
  wd : string;
  areg : tregistry;
begin
fillchar(pwd,sizeof(pwd),0);
getwindowsdirectory(pwd,sizeof(pwd));
wd:=pwd;
wd:=wd+'\fonts\'+fontname;
 try
 RemoveFontResource(PChar(wd));
 SendMessage(HWND_BROADCAST,WM_FONTCHANGE,0,0);
 sleep(100);
 Deletefile(wd);
except
end;
areg:=tregistry.create;
try
areg.rootkey:=HKEY_LOCAL_MACHINE;
if getwindowsversion>2 then areg.openkey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',false) else areg.openkey('SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts',false);
areg.deletevalue('Empathy Digital Font (TrueType)');
except;
end;

end;


function readini : boolean;
var
x : integer;
filterbytes : tfilterbytearray;
pth : string;
a : tinifile;
s : string;
altinipath : string;
cp : array[0..1024] of char;

begin
a:=tinifile.create;
gettemppath(1023,cp);

result:=true;
pth:=paramstr(0);
a.inipath:= ExtractFileDir(pth)+'\'+INIFILE;

a.section:='main';

altinipath:=a.readppString('AltINI','');


if altinipath<>'' then a.inipath:=altinipath;

if fileexists(a.inipath)=false  then begin
application.messagebox('Please install or create an .ini file in the program folder','empathy.ini not found. Cannot continue.');
application.terminate;
halt;
end;


config.path:=a.readppString('Path','');
if config.path=''  then begin
//application.messagebox('Cannot find path entry in [Main] section of .ini file','Error reading empathy.ini. Cannot continue.');
//application.terminate;
config.path:=extractfilepath(paramstr(0));
//halt;
end;


cached:=a.readppBool('Cached','0');
cachepath:=a.readppstring('CachePath',cp);
if ((cachepath='') or (DirectoryExists(cachepath)=false))then cachepath:=cp;


if config.path[length(config.path)]<>'\' then config.path:=config.path+'\';
if config.path='' then begin
result:=false;

end;

SLOWPROCESSOR:=a.readppBool('SlowProcessor','0');
config.volume:=a.readppInteger('Volume','7');
config.Dj_default:=a.readppBool('DJ On','0');
config.Dj_comment:=a.readppBool('DJ Comment','0');
config.lastalbum:=a.readppInteger('LastAlbum','1');
config.dlastalbum:=a.readppInteger('dLastAlbum','1');
config.jlastalbum:=a.readppInteger('jLastAlbum','1');
config.auditiontimeout:=a.readppInteger('AuditionTimeout','5');
config.burnpath:=a.readppstring('burnpath',' ');
config.screensaverpath:=a.readppString('screensaverpath',' ');
config.bgstyle:=a.readppinteger('BackgroundStyle','');
config.borderstyle:=a.readppinteger('BorderStyle','');
config.bgcolor:=a.readppinteger('BackgroundColor','');
config.bordercolor:=a.readppinteger('BorderColor','');
config.cdopt:=a.readppinteger('CDopt','');
config.timeannounce:=a.readppBool('timeannounce','1');
config.mediaplayermode:=a.readppBool('mediaplayermode','0');
config.hideexit:=a.readppBool('hideexit','0');
config.hidepanel:=a.readppBool('jukeboxcontrolpanel','1');
config.litewarn:=a.readppbool('litewarn','1');
config.defaultfilteron:=a.readppbool('defaultfilteron','0');
config.autoplay:=a.readppbool('autoplay','1');
autoplaymode:=config.autoplay;
config.lock:=a.readppbool('lock','0');
config.norepeat:=a.readppbool('norepeat','0');
config.jukeboxaddall:=a.readppbool('jukeboxaddall','1');
config.jukeboxvolumepanel:=a.readppbool('jukeboxvolumepanel','1');
config.password:=a.readppstring('password','');
config.copytrackdest:=a.readppstring('CopyTrackDestination','');
config.monitor:=a.readppinteger('Monitor','0');
config.errorlog:=a.readppstring('ErrorLog','');
config.videomonitor:=a.readppinteger('VideoMonitor',inttostr(config.monitor));
config.fontsize:=a.readppinteger('FontSize','7');
config.showminimize:=a.readppinteger('ShowMinimize','0');
config.poweroff:=a.readppBool('PowerOff','0');
config.disable3D:=a.readppBool('Disable3D','0');
config.wraponunderscore:=a.readppBool('WrapOnUnderscore','1');

a.section:='Genre';
genre.count:=0;
x:=0;
n:=1;


s:='';
while x=0 do begin
   setlength(genre.data,n);
   s:=a.readppstring(inttostr(n-1),'');
   if s<>'' then begin
      genre.data[n-1]:=s;
   end else break;
inc(n);
end;
genre.count:=n-1;

a.section:='ArtistType';
ArtistType.count:=0;
x:=0;
n:=1;
while x=0 do begin
   setlength(ArtistType.data,n);
   s:=a.readppstring(inttostr(n-1),'');
   if s<>'' then begin
     ArtistType.data[n-1]:=s;
   end else break;
inc(n);
end;
ArtistType.count:=n-1;

a.section:='main';
config.username:=a.readppstring('Username','');
config.serial:=a.readppstring('Serial','');

config.bitrate:=a.readppInteger('Bitrate','192');
config.cddbserver:=a.readppString('CDDBServer','www.freedb.org');
config.cddbcgi:=a.readppString('CDDBcgi','/~cddb/cddb.cgi');
config.email:=a.readppString('email','user@isp');
config.networksettings:=a.readppstring('networksettings','');

s:=a.readppstring('defaultfilter','');
if (s<>'') and config.defaultfilteron=true then begin
s:=a.readppstring('defaultfilter','');
setlength(filterbytes,length(s));
filterbytes:=tfilterbytearray(s);
filter:=bytearraytofilter(filterbytes);
end;


a.section:='Phrases';
phrases.count:=0;
x:=0;
n:=1;
while x=0 do begin
s:=a.readppstring(inttostr(n-1),'');
   setlength(phrases.data,n);
   if s<>'' then begin phrases.data[n-1]:=s;
   end else break;
inc(n);
end;
phrases.count:=n-1;

a.section:='Skins';

 config.theme.sbut.Skin:=a.readppstring('sbut','');
 config.theme.sbut.Color:=a.readppinteger('cbut','');
 config.theme.skeypad.Skin:=a.readppstring('skeypad','');
 config.theme.skeypad.Color:=a.readppinteger('ckeypad','');
 config.theme.slcorner.Skin:=a.readppstring('slcorner','');
 config.theme.slcorner.Color:=a.readppinteger('clcorner','');
 config.theme.srcorner.Skin:=a.readppstring('srcorner','');
 config.theme.srcorner.Color:=a.readppinteger('crcorner','');
 config.theme.sblcorner.Skin:=a.readppstring('sblcorner','');
 config.theme.sblcorner.Color:=a.readppinteger('cblcorner','');
 config.theme.sbrcorner.Skin:=a.readppstring('sbrcorner','');
 config.theme.sbrcorner.Color:=a.readppinteger('cbrcorner','');
 config.theme.salphabuttons.Skin:=a.readppstring('salphabuttons','');
 config.theme.salphabuttons.Color:=a.readppinteger('calphabuttons','');
 config.theme.swidebut.Skin:=a.readppstring('swidebut','');
 config.theme.swidebut.Color:=a.readppinteger('cwidebut','');
 config.theme.sbackground.Skin:=a.readppstring('sbackground','');
 config.theme.sbackground.Color:=a.readppinteger('cbackground','');
 config.theme.alphaorientation:=a.readppinteger('alphaorientation','2');

 a.section:='Commercial';
 config.creditsystem:=a.readppbool('creditsystem','0');
 config.playspercoincredit:=a.readppinteger('playspercoincredit','5');
 config.allowfreecredit:=a.readppbool('allowfreecredit','1');
 config.bgvolumemax:=a.readppinteger('bgvolumemax','30');
 config.bgduration:=a.readppinteger('bgduration','15');
 config.bgwaittime:=a.readppinteger('bgwaittime','15');
 config.trackslogfile:=a.readppstring('trackslogfile','');
 config.credittotal:=a.readppinteger('credittotal','0');
 config.freecredittotal:=a.readppinteger('freecredittotal','0');
 config.bgvolume:=a.readppinteger('bgvolume','15');



 a.free;

end;

procedure writeini;
var
n : integer;
filterbytes : tfilterbytearray;
pth : string;
a : tinifile;
s : string;
altinipath : string;
begin
a:=tinifile.create;
try

pth:=paramstr(0);
a.inipath:= ExtractFileDir(pth)+'\'+INIFILE;
a.section:='Main';

altinipath:=a.readppString('AltINI','');

if altinipath<>'' then a.inipath:=altinipath;




a.WritePPString('path',config.path);
a.WritePPString('burnpath',config.burnpath);
a.WritePPString('screensaverpath',config.screensaverpath);
a.WritePPInteger('Volume',config.volume);
a.WritePPBool('DJ On',config.Dj_default);
a.WritePPBool('DJ Comment',config.Dj_comment);
a.WritePPInteger('LastAlbum',config.lastalbum);
a.WritePPInteger('dLastAlbum',config.dlastalbum);
a.WritePPInteger('jLastAlbum',config.jlastalbum);
a.WritePPInteger('AuditionTimeout',config.auditiontimeout);
a.WritePPinteger('BackgroundStyle',config.bgstyle);
a.WritePPinteger('BorderStyle',config.borderstyle);
a.WritePPinteger('BackgroundColor',config.bgcolor);
a.WritePPinteger('BorderColor',config.bordercolor);
a.WritePPinteger('CDopt',config.cdopt);
a.WritePPbool('timeannounce',config.timeannounce);
a.WritePPbool('hideexit',config.hideexit);
a.WritePPbool('litewarn',config.litewarn);
a.WritePPbool('defaultfilteron',config.defaultfilteron);
a.WritePPbool('autoplay',config.autoplay);
a.WritePPbool('lock',config.lock);
a.WritePPbool('norepeat',config.norepeat);
a.WritePPstring('password',config.password);
a.WritePPbool('jukeboxvolumepanel',config.jukeboxvolumepanel);
a.WritePPbool('jukeboxaddall',config.jukeboxaddall);

fillchar(filterbytes,0,0);
filterbytes:=tfiltertobytearray(filter);
s:=string(filterbytes);
a.WritePPString('defaultfilter',s);


//if reg.keyexists('Phrases') then reg.deletekey('Phrases');
a.section:='Phrases';
if phrases.count>0 then for n:=0 to phrases.count-1 do a.WritePPstring(inttostr(n),phrases.data[n]);

a.section:='Genre';

if genre.count>0 then for n:=0 to genre.count-1 do a.WritePPstring(inttostr(n),genre.data[n]);


a.Section:='ArtistType';
if ArtistType.count>0 then for n:=0 to ArtistType.count-1 do a.WritePPstring(inttostr(n),ArtistType.data[n]);

a.section:='main';
a.WritePPstring('Username',Config.username);
a.WritePPstring('Serial',Config.serial);
a.WritePPString('Path',config.path);
a.WritePPInteger('Bitrate',config.bitrate);
//a.WritePPString('CDDBServer',config.cddbserver);
//a.WritePPString('CDDBcgi',config.cddbcgi);
a.WritePPString('email',config.email);
a.writeppbool('PowerOff',config.poweroff);


a.section:='Skins';
a.writeppstring('sbut',config.theme.sbut.Skin);
a.writeppinteger('cbut',config.theme.sbut.Color);
a.writeppstring('skeypad',config.theme.skeypad.Skin);
a.writeppinteger('ckeypad',config.theme.skeypad.Color);
a.writeppstring('slcorner',config.theme.slcorner.Skin);
a.writeppinteger('clcorner',config.theme.slcorner.Color);
a.writeppstring('srcorner',config.theme.srcorner.Skin);
a.writeppinteger('crcorner',config.theme.srcorner.Color);
a.writeppstring('sblcorner',config.theme.sblcorner.Skin);
a.writeppinteger('cblcorner',config.theme.sblcorner.Color);
a.writeppstring('sbrcorner',config.theme.sbrcorner.Skin);
a.writeppinteger('cbrcorner',config.theme.sbrcorner.Color);
a.writeppstring('salphabuttons',config.theme.salphabuttons.Skin);
a.writeppinteger('calphabuttons',config.theme.salphabuttons.Color);
a.writeppstring('swidebut',config.theme.swidebut.Skin);
a.writeppinteger('cwidebut',config.theme.swidebut.Color);
a.writeppstring('sbackground',config.theme.sbackground.Skin);
a.writeppinteger('cbackground',config.theme.sbackground.Color);
a.writeppinteger('alphaorientation',config.theme.alphaorientation);

a.section:='Commercial';
a.WritePPBool('creditsystem',Config.creditsystem);
a.WritePPInteger('playspercoincredit',Config.playspercoincredit);
a.WritePPBool('allowfreecredit',config.allowfreecredit);
a.WritePPInteger('bgvolumemax',config.bgvolumemax);
a.WritePPInteger('bgduration',config.bgduration);
a.WritePPInteger('bgwaittime',config.bgwaittime);
a.writeppstring('trackslogfile',config.trackslogfile);
a.writeppinteger('credittotal',config.credittotal);
a.writeppinteger('freecredittotal',config.freecredittotal);
a.writeppinteger('bgvolume',config.bgvolume);




a.Free;


except;
end;
end;

procedure loadblankmp3file;
var
rs : Tresourcestream;
fs : tfilestream;
begin
blankfilepath:=cachepath+'\blank.mp3';

if fileexists(blankfilepath)=false then begin
try
rs:=Tresourcestream.create(hinstance,'blank',RT_RCDATA);
fs:=tfilestream.create(blankfilepath,fmCreate);
fs.copyfrom(rs,0);
fs.free;
except
messagedlg('Cannot create temporary file. Please check .INI file and make sure '+cachepath+
           ' exists and can be written to'#13#10'or specify and alterative temporary location under the "cachepath=" section of the .INI file',mtError,[MbOk],0);
halt;
end;
end;


if fileexists(blankfilepath)=false then begin
messagedlg('Cannot find temporary file. Please check .INI file and make sure '+cachepath+
           ' exists and can be written to'#13#10'or specify and alterative temporary location under the "cachepath=" section of the .INI file',mtError,[MbOk],0);
halt;
end;

mainform.mp.close;
mainform.mp.filename:=blankfilepath;

try
mainform.mp.open;
except;
end;
loadedblankmp3file:=true;

end;




procedure Tmainform.albumlistChange(Sender: TObject);
var
n : integer;
spp : string;
var
o : tbitmap;
begin
o:=nil;
n:=albumlist.itemindex+1;
config.lastalbum:=n;

if albumcount<>0 then begin
  spp:=album[n].artist+'__'+album[n].album;
  screen.cursor:=crhourglass;
  loadjpegbmp(config.path+spp,o);
  cover.picture.bitmap.assign(o);
  o.free;
  cover.refresh;
  screen.cursor:=crdefault;
  albumlist.hint:=albumlist.items[albumlist.itemindex];
end;
  if albumcount<>0 then  if loadtitles(tracklist,n)=false then begin
  maketitles(album[n].album+'__'+album[n].artist);
  loadtitles(tracklist,n)
  end;

if cdplayerbut.checked=true then begin
skipforward.enabled:=false;
skipback.enabled:=false;
progress.enabled:=false;
play.enabled:=false;
fwd.enabled:=false;
bck.enabled:=false;
pause.enabled:=false;
timermode:=0;
end;
end;

procedure showerror(txt : string; errortype : integer);
var
showerrortext : string;
fl : textfile;
dt : string;
begin
killspeech;
if errortype=0 then showerrortext:='File:'+copy(txt,1,length(txt)-1)+'? does not exist';
if errortype=1 then showerrortext:='File:'+txt+' is corrupt';

if (jukebox<>nil) then begin
  if jukebox.visible=true then begin
     jukebox.domessage(showerrortext);
   end;
end;

if config.errorlog<>'' then begin
 assignfile(fl,config.errorlog);
 try
  if fileexists(config.errorlog) then begin
  append(fl);
  if (filesize(fl)>(10240 div 128)) then begin; closefile(fl); rewrite(fl);end;
  datetimetostring(dt,'ddddd tt',now);
  writeln(fl,dt+' - '+showerrortext);
  closefile(fl);
  end;
 except;
 end;
end;

if config.creditsystem=true then begin
//if autoplaymode=true then startautoplay;
end;




//if ((uppercase(paramstr(1))='/J') or (KIOSK=true)) then exit;

end;

function gettrackatfilepos(i : integer;pth : string) : string;
var
sr : TSearchrec;
res : integer;
n : integer;
begin
res:=findfirst(pth+'\*.MP?',faanyfile,sr);
n:=1;
while(res)=0 do begin
 if n=i then begin
   result:=pth+'\'+sr.Name;
   break;
 end;
 inc(n);
res:=findnext(sr);
end;
findclose(sr);

end;

procedure Tmainform.tracklistClick(Sender: TObject);
var
ts : string;
fn : string;
seconds : integer;
minutes : integer;
sec : string;
begin
progressmove:=true;
progress.position:=0;
progressmove:=false;
If tracklist.itemindex<9 then ts:='0'+InttoStr(tracklist.itemindex+1) else ts:=InttoStr(tracklist.itemindex+1);

If (tracklist.itemindex>-1) then begin
  fn:=currentalbumpath+'\TRACK'+ts+'.MP3';
  if fileexists(fn)=false then fn:=currentalbumpath+'\'+tracklist.items[tracklist.itemindex]+'.mp3';
end;
timers.enabled:=false;
if fn='' then begin
counter.caption:='---';
mainform.caption:='No track';
exit;
end;





mp.filename:=fn;
mp.notify:=false;
if fileexists(fn)=false then begin
 //extractalbumartist(fn,alb,art);
 showerror(fn,0);
 exit;
end;

try
mp.open;
except
//extractalbumartist(fn,alb,art);
showerror(fn,1);
exit;
end;

 setupfrequency;
 seconds:=mp.length div 1000;
 minutes:= seconds div 60;
 seconds:=seconds-(minutes*60);
 sec := inttostr(seconds);
 if seconds<10 then sec:='0'+inttostr(seconds);
 counter.caption:=inttostr(minutes)+':'+sec;
 Tr.Caption:='LEN';
stop.down:=true;
play.enabled:=true;
fwd.enabled:=true;
bck.enabled:=true;
pause.enabled:=true;
skipforward.enabled:=true;
skipback.enabled:=true;
progress.enabled:=true;
if albumlist.Items.count = 0 then exit;
mainform.caption:=albumlist.items[albumlist.itemindex]+' : '+tracklist.items[tracklist.itemindex];
if jukebox<>nil then jukebox.domessage('Now playing: '+mainform.caption);
end;

procedure Tmainform.MPNotify(Sender: TObject);
var
alb : string;
wasautoplaying: boolean;
begin
if paused=true then begin
exit;
end;


wasautoplaying:=autoplaying;
If (Mp.NotifyValue=nvSuccessful) then autoplaying:=false;


If playlistbut.checked=true then begin

If (Mp.NotifyValue=nvSuccessful) and (playmode=1) then begin
    If dcurrentlyplayingtrack+1<=dplaylist.items.count-1 then begin
       dcurrentlyplayingtrack:=dcurrentlyplayingtrack+1;
       playlistpanel.lb.highlighteditem2:=dcurrentlyplayingtrack;
       if playlistpanel.Visible=true then playlistpanel.lb.Paint;
       alb:=setuptrackname(dcurrentlyplayingtrack);
       playmode:=0;
       MP.Notify:=true;
       timers.enabled:=true;
       sorttimemode;


       if showcover.checked=true then begin
       covershow(dPlayListMatrixAlb[dcurrentlyplayingtrack],true);
       end;

        if dj.down=true then doDJ(dPlayListMatrixAlb[dcurrentlyplayingtrack]);
        mpplay;
        if mutebut.down=true then volchange(mutebut) else volchange(sender);
        playmode:=1;
       play.down:=true;
    end
    else begin
       stop.down:=true;
       timers.enabled:=false;
       counter.caption:='---';
       mainform.caption:='No track';
       if jukebox.visible=true then jukebox.domessage('');
       vol.Position:=config.volume;
       jukebox.backgroundtimer.tag:=1;
       jukebox.backgroundtimercount:=0;
       if (wasautoplaying=true) and (autoplaymode=true) then startautoplay;
    end;
    end;
  MP.Notify:=true;

end;

If playlistbut.checked=true then exit;

 If (Mp.NotifyValue=nvSuccessful) and (playmode=1) then begin
 If tracklist.itemindex+1<tracklist.items.count then begin
 tracklist.itemindex:=tracklist.itemindex+1;
 tracklistClick(tracklist);
 playmode:=0;
 MP.Notify:=true;
 timers.enabled:=true;
 sorttimemode;
 //alb:=setuptrackname(dcurrentlyplayingtrack);
 if dj.down=true then doDJ(dPlayListMatrixAlb[dcurrentlyplayingtrack]);

 mpplay;
 if mutebut.down=true then volchange(mutebut) else volchange(sender);
 playmode:=1;
 play.down:=true;
 end
 else begin
 stop.down:=true;
 timers.enabled:=false;
 vol.Position:=config.volume;
 if autoplaymode=true then startautoplay;
 end;
  end;
  MP.Notify:=true;
end;



procedure Tmainform.playClick(Sender: TObject);
var
alb : string;
begin

playbutmod.visible:=false;

{Play List Style}
//if play.down=false then begin
//pause.down:=true;
//pauseclick(Sender);
//exit;
//end;


if paused=true then begin
mpplay;

if mutebut.down=true then volchange(mutebut) else volchange(sender);
paused:=false;
exit;
end;



dcurrentlyplayingtrack :=dplaylist.itemindex;
playlistpanel.lb.highlighteditem2:=dcurrentlyplayingtrack;
if playlistpanel.Visible=true then playlistpanel.lb.Paint;


If dcurrentlyplayingtrack=-1 then dcurrentlyplayingtrack:=0;
if playlistbut.checked = true then begin
alb:=setuptrackname(dcurrentlyplayingtrack);
if dj.down=true then doDJ(dplaylistMatrixAlb[dcurrentlyplayingtrack]);

 if showcover.checked=true then begin
       covershow(dplaylistMatrixAlb[dcurrentlyplayingtrack],true);
  end;

playmode:=1;
sorttimemode;
play.down:=true;
mpplay;
if mutebut.down=true then volchange(mutebut) else volchange(sender);
timers.enabled:=true;
end;

if playlistbut.checked = true then exit;

{CD Style}
//if dj.down=true then doDJ(dPlayListMatrixAlb[dcurrentlyplayingtrack]);

playmode:=1;
sorttimemode;
mpplay;
if mutebut.down=true then volchange(mutebut) else volchange(sender);
timers.enabled:=true;

end;

procedure Tmainform.StopClick(Sender: TObject);
begin
//if jukebox<>nil then if jukebox.visible=true then jukebox.domessage('');
if assigned(video) then if video.Visible=true  then video.hide;
if jukebox.coverimagepanel.Visible=true then jukebox.coverimagepanel.Visible:=false;

progressmove:=true;
progress.position:=0;
progressmove:=false;
paused:=false;
killspeech;
if playlistbut.checked=true then begin
dcurrentlyplayingtrack :=dplaylist.itemindex;

if (uppercase(copy(mainform.mp.filename,length(mainform.mp.filename),1))='G') then loadblankmp3file;


If dcurrentlyplayingtrack=-1 then dcurrentlyplayingtrack:=0;
playmode:=0;
application.processmessages;
try
mp.stop;
except
end;
dtracklistclick(dtracklist);
timers.enabled:=false;
exit;
end;

playmode:=0;
try
mp.stop;
except
end;

timers.enabled:=false;
tracklistclick(tracklist);

end;



procedure Tmainform.bckClick(Sender: TObject);
var
dplaymodewas : integer;
begin
vol.position:=config.volume;
dplaymodewas:=0;
If playlistbut.checked=true then begin
if playmode=1 then begin
   dplaymodewas:=1;
   end;
   if (dplaylist.itemindex>0) then dplaylist.itemindex:=dplaylist.itemindex-1;
   dplaylistclick(sender);
   if dplaymodewas=1 then playclick(sender);
  exit
end;



If playmode=0 then begin
 If tracklist.itemindex-1>-1 then begin
 tracklist.itemindex:=tracklist.itemindex-1;
 tracklistClick(tracklist);
 end;
end;

If (playmode=1) then begin
 If tracklist.itemindex-1>-1 then begin
 tracklist.itemindex:=tracklist.itemindex-1;
 tracklistClick(tracklist);
 playmode:=0;
 MP.Notify:=true;
 sorttimemode;
 mpplay;
 if mutebut.down=true then volchange(mutebut) else volchange(sender);
 timers.enabled:=true;
 playmode:=1;
 play.down:=true;
 end
 else begin
 If tracklist.itemindex-1>-1 then begin
 tracklist.itemindex:=tracklist.itemindex-1;
 tracklistClick(tracklist);
 timers.enabled:=false;
 end;
 end;

 end;
 If playmode=1 then play.down:=true;
 If playmode=0 then stop.down:=true;
end;

procedure Tmainform.fwdClick(Sender: TObject);
var
dplaymodewas : integer;
begin
vol.position:=config.volume;
If playlistbut.checked=true then begin
   dplaymodewas:=0;
 if playmode=1 then begin
   dplaymodewas:=1;
   //stopclick(sender);
   //stop.down:=true;
 end;
 if (dplaylist.itemindex>=0) then begin
   dplaylist.itemindex:=dplaylist.itemindex+1;
   dplaylistclick(sender);
   if dplaymodewas=1 then playclick(sender);
 end;
exit
end;


If playmode=0 then begin
 If tracklist.itemindex+1<tracklist.items.count then begin
 tracklist.itemindex:=tracklist.itemindex+1;
 tracklistClick(tracklist);
 End;
 End;

If (playmode=1) then begin
 If tracklist.itemindex+1<tracklist.items.count then begin
 tracklist.itemindex:=tracklist.itemindex+1;
 tracklistClick(tracklist);
 playmode:=0;
 MP.Notify:=true;
 sorttimemode;
 mpplay;
 if mutebut.down=true then volchange(mutebut) else volchange(sender);

 timers.enabled:=true;
 playmode:=1;
 play.down:=true;
 end
 else begin
 If tracklist.itemindex+1<tracklist.items.count then begin
 tracklist.itemindex:=tracklist.itemindex+1;
 tracklistClick(tracklist);
 timers.enabled:=false;
 end;
 end;
 end;
 If playmode=1 then play.down:=true;
 If playmode=0 then stop.down:=true;
end;

procedure Tmainform.TimersTimer(Sender: TObject);
var

seconds : integer;
minutes : integer;
sec : string;
begin
application.processmessages;
//if audition_mode=true then begin
//if mp.Position>5000then fwdclick(Sender);
//end;
 progressmove:=true;
try
if mp.error=0 then progress.max:=Round(mp.length/1000);
 progress.position:=Round(mp.position/1000);
except
try
mp.stop;
except;
end;
end;
 progressmove:=false;
 seconds:=progress.position;
 minutes:= seconds div 60;
 seconds:=seconds-(minutes*60);
 sec := inttostr(seconds);
 If timermode=0 then begin
 if seconds<10 then sec:='0'+inttostr(seconds);
 counter.caption:=inttostr(minutes)+':'+sec;
end;


If timermode=1 then begin
try
 seconds:=round((mp.length-mp.position)/1000);
 minutes:= seconds div 60;
 seconds:=seconds-(minutes*60);
 sec := inttostr(seconds);
 if seconds<10 then sec:='0'+inttostr(seconds);
 counter.caption:=inttostr(minutes)+':'+sec;
except
mp.stop;
end;
end;

end;


procedure Tmainform.timemodebutClick(Sender: TObject);
begin
if timermode=0 then begin
timermode:=1;
end
else begin
timermode:=0;
end;
sorttimemode;
end;




procedure Tmainform.sorttimemode;
begin
if timermode=1 then begin
counter.hint:='Time Remaining';
tr.hint:='Time Remaining';
tr.caption:='TR'
end
else begin
counter.hint:='Time Elapsed';
tr.hint:='Time Elapsed';
tr.caption:='TE'
end;
end;






procedure Tmainform.playlistbutClick(Sender: TObject);
begin
dj.enabled:=true;
//open.enabled:=true;
//save.enabled:=true;
playlistbut.checked:=true;
if dalbumlist.itemindex=-1 then begin
dalbumlist.itemindex:=albumlist.itemindex;
dalbumlistchange(nil);
end;

numberoftracks.enabled:=true;
If playlistbut.checked=true then begin
//trackedit.enabled:=false;
playlist.visible:=true;
end;
buttonsMouseMove(nil,[],0,0);
end;




procedure Tmainform.CdplayerbutClick(Sender: TObject);
begin
dj.enabled:=false;
//save.enabled:=false;
numberoftracks.enabled:=false;
cdplayerbut.checked:=true;
If cdplayerbut.checked=true then begin
//trackedit.enabled:=true;
playlist.visible:=false;
end;
buttonsMouseMove(nil,[],0,0);
end;



procedure Tmainform.randombutClick(Sender: TObject);

begin
rnd_dialog.showmodal;
playlistbutClick(playlistbut);
playlistbut.checked:=true;
screen.cursor:=crDefault;
dplaylist.itemindex:=0;
//trackedit.enabled:=false;
buttonsMouseMove(nil,[],0,0);
end;





procedure Tmainform.DalbumlistChange(Sender: TObject);
var
n : integer;
spp : string;
{playlist Style}
begin

  n:=dalbumlist.itemindex+1;
  config.dlastalbum:=n;
if albumcount<>0 then begin
  spp:=album[n].artist+'__'+album[n].artist;
  dalbumlist.hint:=dalbumlist.items[dalbumlist.itemindex];
end;
 if albumcount<>0 then  if loadtitles(dtracklist,n)=false then begin
     maketitles(album[n].artist+'__'+album[n].artist);
     loadtitles(dtracklist,n)
  end;
  dtracklist.itemindex:=0;
end;

procedure Tmainform.dtracklistClick(Sender: TObject);
var
hintitem : string;
begin
if (dtracklist.itemindex>-1) and (dtracklist.items.count>0) then hintitem:='"'+dtracklist.items[dtracklist.itemindex]+'"';

add.hint:='Add '+hintitem+' to end of playlist';
Insert.hint:='Insert "'+hintitem+'" into playlist';

If dtracklist.itemindex>-1 then add.enabled:=true;
If dplaylist.itemindex>-1 then del.enabled:=true;
If dplaylist.itemindex=-1 then del.enabled:=false;

end;

procedure Tmainform.AddClick(Sender: TObject);
var
n : integer;
alb,art : string;
begin
audition.enabled:=true;

if (config.norepeat=true) and (dplaylist.itemindex>-1) then begin
 for n:=dplaylist.itemindex to dplaylist.items.count-1 do begin;
 if  (dplaylistMatrixAlb[n]=dcurrentalbumpath) and  (dplaylistMatrixTrk[n]=dtrackList.itemindex+1) then begin
  jukebox.credit.RefundCredit;
  jukebox.domessage('NO CREDIT TAKEN - TRACK ALREADY IN QUEUE');
  exit;
 end;
 end;
end;



if (dtracklist.itemindex>-1) then begin
   dplaylist.items.add (dtracklist.items[dtracklist.itemindex]);
   setlength(dplaylistmatrixtrk,dplaylist.items.count+1);
   setlength(dplaylistMatrixAlb,dplaylist.items.count+1);

   dplaylistMatrixAlb[dcurrenttrack]:=dcurrentalbumpath;
   dplaylistMatrixTrk[dcurrenttrack]:=dtrackList.itemindex+1;
   dcurrenttrack:=dcurrenttrack+1;

   if jukebox<>nil then begin
    if dtracklist.itemindex+1<dtracklist.items.count then jukebox.domessage('Added Track: '+dtracklist.items[dtracklist.itemindex]);
    if config.trackslogfile<>'' then begin
     extractalbumartist(dcurrentalbumpath,alb,art);
     jukebox.log.writeentry(art,alb,dtracklist.items[dtracklist.itemindex]);
    end;
   end;


   if dplaylist.items.count>0 then begin
      play.enabled:=true;
      fwd.enabled:=true;
      bck.enabled:=true;
      pause.enabled:=true;
   end;

   if dplaylist.itemindex=-1 then begin
      dplaylist.itemindex:=0;
      dplaylistclick(Sender);
   end;

end;

if dplaylist.items.count>0 then begin
   //save.enabled:=true;
   clearlist.enabled:=true;
   end
   else begin
   //save.enabled:=false;
   clearlist.enabled:=false;
end;

end;

procedure Tmainform.dplaylistClick(Sender: TObject);
begin
vol.position:=config.volume;
if dplaylist.itemindex>-1 then del.hint:='Remove "'+dplaylist.items[dplaylist.itemindex]+'" from playlist';
If dplaylist.itemindex>-1 then del.enabled:=true;
If dplaylist.itemindex=-1 then del.enabled:=false;
if (sender=dplaylist) and (dplaylist.itemindex<>-1) and (dplaylist.itemindex<>dcurrentlyplayingtrack) then playbutmod.visible:=true;
if (sender=dplaylist) and (dplaylist.itemindex=dcurrentlyplayingtrack) then playbutmod.visible:=false;

if sender=dplaylist then begin
//   menupos:=mouse.cursorpos;
//   dplaylistmenu.popup(menupos.x,menupos.y);
end;
end;

procedure Tmainform.DelClick(Sender: TObject);
var
old : integer;
n : integer;
begin


old:=dplaylist.itemindex;
dplaylist.Items.delete(dplaylist.itemindex);
//if dplaylist.items.count>0 then save.enabled:=true else save.enabled:=false;

for n:=old to dplaylist.Items.count do begin
dplaylistMatrixAlb[n]:=dplaylistMatrixAlb[n+1];
dplaylistMatrixTrk[n]:=dplaylistMatrixTrk[n+1];
end;

If dplaylist.Items.count > 0 then begin
If old<=dplaylist.Items.count-1 then dplaylist.itemindex:=old else begin
dplaylist.itemindex:=old-1;
end;

dcurrenttrack:=dcurrenttrack-1;

end
else begin
del.enabled:=false;
clearlist.enabled:=false;
dcurrenttrack:=0;
end;
if dplaylist.items.count=0 then begin
progress.enabled:=false;
skipforward.enabled:=false;
skipback.enabled:=false;
play.enabled:=false;
bck.enabled:=false;
pause.enabled:=true;
fwd.enabled:=false;
end;
end;


function Tmainform.setuptrackname(num : integer) : string;
var
ts : string;
fn : string;
seconds : integer;
minutes : integer;
sec : string;
alb : string;
scrap1,scrap2 : string;
a,b : string;
videomode : boolean;
begin
if albumcount=0 then exit;
if length(dplaylistMatrixAlb)=0 then exit;


killspeech;
progressmove:=true;
progress.position:=0;
progressmove:=false;




alb:=dplaylistMatrixAlb[num];

If dplaylistMatrixTrk[num]<10 then ts:='0'+inttostr(dplaylistMatrixTrk[num]) else ts:=inttostr(dplaylistMatrixTrk[num]);
fn:=alb+'\TRACK'+ts+'.MP3';
if fileexists(fn)=false then fn:=alb+'\TRACK'+ts+'.MPG';

if fileexists(fn)=false then begin
  fn:=gettrackatfilepos(dplaylistMatrixTrk[num],alb);
end;


timers.enabled:=false;
dplaylist.itemindex:=num;
if (fn='') or (alb='') then begin
counter.caption:='---';
mainform.caption:='No track';
jukebox.domessage('');
exit;
end;
mp.filename:=fn;
mp.notify:=false;



if fileexists(fn)=false then begin

showerror(fn,0);
if (dplaylist.itemindex)<>dplaylist.items.count-1 then begin
fwdclick(nil);
exit;
end
else
begin
//jukebox.domessage('');
stopclick(nil);
exit;
end;
end;




try
mp.open;
except;
showerror(mp.filename,1);
loadblankmp3file;
mainform.play.down:=true;
fn:=a+' '+b+' TRACK: '+ts;
exit;
end;

if (uppercase(copy(mp.filename,length(mp.filename),1))='G')then begin
{$IFDEF KIOSK}
videomode:=true;
{$ENDIF}
{$IFNDEF KIOSK}
videomode:=false;
{$ENDIF}



  if ((videomode=false) or (config.videomonitor=0)) then begin
    mainform.mp.Display:=jukebox.coverimagepanel;
    jukebox.jbcovershow('');
    mainform.mp.DisplayRect:=jukebox.coverimagepanel.ClientRect;
   end else begin
    videoshow;
   end;



end;

 setupfrequency;
 seconds:=mp.length div DIVISION;
 minutes:= seconds div 60;
 seconds:=seconds-(minutes*60);
 sec := inttostr(seconds);
 if seconds<10 then sec:='0'+inttostr(seconds);
 counter.caption:=inttostr(minutes)+':'+sec;
 Tr.Caption:='LEN';
 Tr.Refresh;
stop.down:=true;
progress.enabled:=true;
skipforward.enabled:=true;
skipback.enabled:=true;
play.enabled:=true;
fwd.enabled:=true;
bck.enabled:=true;
pause.enabled:=true;
mainform.caption:=dplaylist.items[num]+' - '+extractalbumandaristfrompath(dplaylistMatrixAlb[num],scrap1,scrap2);
result:=alb;
jukebox.domessage('Now playing '+mainform.caption);



end;



procedure Tmainform.restoreClick(Sender: TObject);
begin
mainform.Windowstate:=wsnormal;
mainform.BorderStyle:=bsSingle;
end;

procedure Tmainform.picturepanelClick(Sender: TObject);
begin
restoreClick(Sender);
end;



procedure Tmainform.clearlistClick(Sender: TObject);
begin
stopclick(sender);
stop.down:=true;
dcurrenttrack:=0;
dplaylist.Items.clear;
progress.enabled:=false;
skipforward.enabled:=false;
skipback.enabled:=false;
play.enabled:=false;
bck.enabled:=false;
pause.enabled:=true;
fwd.enabled:=false;
del.enabled:=false;
clearlist.enabled:=false;
end;


procedure Tmainform.coverMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
//if button=mbRight then thumbviewgo(true);
end;





procedure Tmainform.doDJ(album : string);
var
a,b,c,d : integer;
pre : string;
artist,alb,track : string;

begin
killspeech;
randomize;
if phrases.count>0 then begin
a :=round(random(phrases.count));
pre:=phrases.data[a];

a := round(random*phrases.count-1);
if (a=((phrases.count+1) div 2)) and (config.timeannounce=true) then pre:=formatdatetime('hh mm',time);
end;
extractalbumandaristfrompath(album,artist,alb);




if playlistbut.checked=true then track:=dplaylist.items[dplaylist.itemindex];
if cdplayerbut.checked=true then track:=tracklist.items[tracklist.itemindex];

d := round(random*3)+1;
c := round(random*3)+1;
b := round(random*2)+1;
a:= round(random*40)+140;

case d of
1 : d:=vtxtst_STATEMENT;
2 : d:=vtxtst_COMMAND;
3 : d:=vtxtst_WARNING;
4 : d:=vtxtst_READING;
5 : d:=vtxtst_QUESTION;

end;

case c of
1 : c:=vtxtst_STATEMENT;
2 : c:=vtxtst_COMMAND;
3 : c:=vtxtst_WARNING;
4 : c:=vtxtst_READING;
5 : d:=vtxtst_QUESTION;
end;



if  config.dj_comment=false then begin
speak(artist+','+' '+alb+','+track ,a , d or vtxtst_VERYHIGH);
exit;
end;

if dplaylist.itemindex<>0 then speak(pre, a, c or vtxtst_VERYHIGH);
if b=1 then speak(track+' by '+artist, a,  d or vtxtst_VERYHIGH);
if b=2 then speak(track+' from '+alb+' by '+artist,a , d or vtxtst_VERYHIGH);
if b=3 then speak(track+' '+artist ,a , d or vtxtst_VERYHIGH);

end;


procedure Tmainform.FormClose(Sender: TObject; var Action: TCloseAction);
begin

{if initcovers<>nil then begin
   initcovers.terminate;
  // initcovers.waitfor;
end;}
//killspeech;
writeini;
deletefile(blankfilepath);
application.OnMessage:=nil;
application.terminate;
end;

procedure Tmainform.numberoftracksTimer(Sender: TObject);
var
numoftracks,currenttrack : string;
begin

if playmode=0 then begin
str(dplaylist.items.count,numoftracks);
playlistcaption.caption:=numoftracks+' tracks';
end;

if playmode=1 then begin
str(dplaylist.itemindex+1,currenttrack);
str(dplaylist.items.count,numoftracks);
playlistcaption.caption:=currenttrack+'\'+numoftracks+' tracks';
end;


if playlistcaption.tag=0 then begin
playlistcaption.visible:=false;
playlistcaption.tag:=1;
exit;
end;

if playlistcaption.tag=1 then begin
playlistcaption.visible:=true;
playlistcaption.tag:=0;
end;


end;


procedure Tmainform.coverClick(Sender: TObject);
begin
covershow(currentalbumpath,true);
//if tracklist.items.count>0 then mainform.playlist.setfocus;
end;





procedure Tmainform.showcoverClick(Sender: TObject);
begin
if (showcover.checked=true) and (playmode=1) and (dplaylist.itemindex<>-1) then begin;
if dcurrentlyplayingtrack=0 then exit;
covershow(dPlayListMatrixAlb[dcurrentlyplayingtrack],false);
end;
end;



procedure Tmainform.skipbackward(Sender: TObject);
begin
progressmove:=true;
if (progress.position-(progress.linesize*2)>0) then progress.position:=progress.position-(progress.linesize*2) else progress.Position:=0;
progressmove:=false;

progressChange(Sender);
if playmode=1 then begin
if paused=false then play.down:=true else pause.down:=true;
end;

end;


procedure Tmainform.progressChange(Sender: TObject);
var
seekst : TMCI_Seek_Parms;

begin


if progressmove=false then begin
fillchar(seekst,sizeof(seekst),0);
seekst.dwTo := progress.position*DIVISION;
if (progresslastpos<>seekst.dwTo)  then begin
mciSendCommand(mp.DeviceID, MCI_SEEK,MCI_TO or MCI_WAIT,longint(@seekst));
if (paused=false) and (stop.down=false) then mp.play;
end;
progresslastpos:=seekst.dwTo;
//timerstimer(self);

end;


if paused=false then exit;

if (playmode=1) and (paused=false) then begin
mpplay;
if mutebut.down=true then volchange(mutebut) else volchange(sender);
end;
end;

procedure Tmainform.skipforwardClick(Sender: TObject);
begin
progressmove:=true;
if (progress.position+(progress.linesize*2)<progress.max) then progress.position:=progress.position+(progress.linesize*2) else progress.position:=progress.max;
progressmove:=false;

progressChange(Sender);
if playmode=1 then begin
if paused=false then play.down:=true else pause.down:=true;
end;
end;


procedure Tmainform.pauseClick(Sender: TObject);
begin
if paused=true then begin
paused:=false;
play.down:=true;
mp.play;
exit;
end;
paused:=true;
try
mp.pause;
except;
end;
end;

procedure Tmainform.volChange(Sender: TObject);
var
p       : MCI_DGV_SETAUDIO_PARMS;
begin




if sender<>mutebut then mutebut.down:=false;
   drawtriangle(vol.position);
   { Volume: 0 - 1000 }
   p.dwCallback := 0;
   p.dwItem := MCI_DGV_SETAUDIO_VOLUME;
   p.dwValue := 1000* vol.position div VOLINCREMENTS;
   if vol.position=VOLINCREMENTS then begin
      p.dwValue:=1000;
   end;
   if mutebut.down=true then p.dwValue:=0;

   p.dwOver := 0;
   p.lpstrAlgorithm := nil;
   p.lpstrQuality := nil;

   mciSendCommand(MP.DeviceID, MCI_SETAUDIO, MCI_DGV_SETAUDIO_VALUE or MCI_DGV_SETAUDIO_ITEM, Cardinal(@p));






   if (volumedisplay<>nil) then begin
    if (sender=vol) or (sender=mutebut) then volume.draw(vol.position);
    if (jukebox.Visible=true) and (ripmain.visible=false) then jukebox.SetFocus;

   end;
end;



procedure tmainform.drawtriangle(pos : integer);
var
a : array [0..2] of tpoint;
fs : tfillstyle;
p : tpoint;
pnm : tpenmode;
r : integer;
m : integer;
begin
pos:=round(pos / 3.3);
r:=round( ((mainform.vol_triangle.width-2) / 10)*pos);
pnm:=pmCopy;
mainform.vol_triangle.canvas.pen.mode:=pnm;
mainform.vol_triangle.canvas.pen.width:=1;
fs:=fsborder;
mainform.vol_triangle.canvas.brush.color:=clBtnFace;
mainform.vol_triangle.canvas.floodfill(1,1,clBtnFace,fs);
//vol_triangle.canvas.brush.color:=clBtnShadow;


p.x:=0;
p.y:=mainform.vol_triangle.height-2;
mainform.vol_triangle.canvas.penpos:=p;
mainform.vol_triangle.canvas.pen.color:=clBtnHighlight;
mainform.vol_triangle.canvas.lineto(mainform.vol_triangle.width-1,mainform.vol_triangle.height-2);
mainform.vol_triangle.canvas.pen.color:=clBtnHighlight;
mainform.vol_triangle.canvas.lineto(mainform.vol_triangle.width-1,0);
mainform.vol_triangle.canvas.pen.color:=clBtnShadow;
mainform.vol_triangle.canvas.lineto(p.x,p.y);

a[0].x:=2;
a[0].y:=mainform.vol_triangle.height-3;

a[1].x:=r;
a[1].y:=(mainform.vol_triangle.height-3);

a[2].x:=r;
m:=round(((mainform.vol_triangle.height-3)/10)*pos);

a[2].y:=(mainform.vol_triangle.height-3)-m;

if pos=0 then exit;
mainform.vol_triangle.canvas.brush.color:=clhighlight;
mainform.vol_triangle.canvas.polygon(a);






end;


procedure Tmainform.mutebutClick(Sender: TObject);
begin
volchange(sender);
end;


procedure Tmainform.auditionClick(Sender: TObject);
begin
if audition.down=true then begin
audition_mode:=true;
end;

if audition.down=false then begin
audition_mode:=false;
stopclick(sender);
stop.down:=true;
end;
end;

procedure tmainform.mpplay;
var
alb,art,fn : string;
begin
if fileexists(mp.filename)=false then begin
extractalbumartist(mp.filename,alb,art);
//fn:=alb+' '+art;
showerror(fn,0);
stop.down:=true;
exit;
end;

counter.caption:='---';
if audition_mode=false then try mp.play except; end;
if audition_mode=true then begin
mp.endpos:=1000*config.auditiontimeout;
mp.Play;

end;
end;





procedure Tmainform.djClick(Sender: TObject);
begin
if (DJ.down=true) then if (initspeech<>0) then begin
{$IFNDEF kiosk}
messagedlg('The Microsoft Text-to-Speech runtime files (SAPI) are not installed on this system.',mterror,[mbOk],0);

{$ENDIF}

dj.enabled:=false;
end;
end;



procedure Tmainform.coverpickbutClick(Sender: TObject);
begin
//thumbviewgo(true);
thumbmode:=1;
jukebox.setvisualspanel(true);
jukebox.showmodal;
albumlist.itemindex:=jukebox.thumbs.itemindex;
albumlistchange(nil);
dalbumlist.itemindex:=jukebox.thumbs.itemindex;
dalbumlistchange(nil);

coverpickbut.down:=false;
end;








procedure tmainform.initlistboxes;
var
n : integer;
hidden : boolean;
begin

albumlist.clear;
dalbumlist.clear;
n:=0;
albumlist.Items.Delimiter:=#2;
While (n<albumcount) do begin
n:=n+1;
if (albumref[n].artist<>'') and (albumref[n].album <>'') then begin
 albumlist.items.addobject (albumref[n].artist+' - '+albumref[n].album,@albumref[n]);
 dalbumlist.items.add (albumref[n].artist+' - '+albumref[n].album);
application.processmessages;
end;

end;


//MOVE _* to end of list
albumlist.Sorted:=false;
dalbumlist.Sorted:=false;

n:=0;
if dalbumlist.items.count>0 then  begin

while dalbumlist.items[n][1]='_' do begin
 dalbumlist.items.Move(n,dalbumlist.items.count-1);
 albumlist.items.Move(n,albumlist.items.count-1);
end;
end;

initmessage('Creating albumlists..','','');
for n:=0 to albumlist.items.count-1 do begin
album[n+1]:=talbumtype(pointer(albumlist.Items.Objects[n])^);

{

 for x:=1 to albumcount do begin
 application.processmessages;
 if comparetext(albumlist.items[n],albumref[x].artist+' - '+albumref[x].album)=0 then begin
    album[n+1].artist:=albumref[x].artist;
    album[n+1].album:=albumref[x].album;
   end;

end;}
end;






initmessage('Creating albumlists....','','');


if (mp.filename<>'') and (cdplayerbut.checked=true) and (play.down=true) then
try
stopclick(nil);
except;
end;


if (config.lastalbum<=albumlist.items.count) and  (config.dlastalbum>0) then albumlist.itemindex:=config.lastalbum-1 else albumlist.itemindex:=0;
if (config.dlastalbum<=dalbumlist.items.count) and  (config.dlastalbum>0) then dalbumlist.itemindex:=config.dlastalbum-1 else dalbumlist.itemindex:=0;

albumlistChange(albumlist);
dalbumlistChange(dalbumlist);



if albumcount=0 then hidden:=false else hidden:=true;
if (hidden=false) and (dplaylist.items.count=0) then begin
       cdplayerbutclick(nil);
       butcdlist.visible:=hidden;
       playlistbut.enabled:=hidden;
end;

if (hidden=false) and (cdplayerbut.checked=true) and (dplaylist.items.count<>0) then begin
       playlistbutclick(nil);
end;

   dtracklist.clear;
   //open.enabled:=true;
   add.enabled:=hidden;
   insert.enabled:=hidden;
   transport.Enabled:=hidden;
   playpanel.visible:=hidden;
   //menuprint.enabled:=hidden;
   tracklist.visible:=hidden;
   cover.visible:=hidden;
   coverpanel.visible:=hidden;
   butcdlist.visible:=true;
   playlistbut.enabled:=true;
   albumlist.enabled:=hidden;
   dalbumlist.enabled:=hidden;
   //trackedit.enabled:=hidden;
   //burncdbut.enabled:=hidden;
   //butcdburn.visible:=hidden;
   butcd.visible:=hidden;
   CDplayerbut.enabled:=hidden;
   randombut.enabled:=hidden;
   jukeboxbut.enabled:=true;
   coverpickbut.enabled:=hidden;
   butrandom.visible:=hidden;
   butjukebox.visible:=hidden;









initmessage('Initialising Jukebox....','','');
//if (albumlist.items.count>2) then begin
gojukebox(false);
//end;

if albumcount=0 then jukebox.domessage('No CDs on system');
if ((uppercase(paramstr(1))='/J') or (KIOSK=true)) and (jukeboxbut.enabled=true)  then  begin
   if (config.autoplay=true) and (albumcount>0) then begin
      initautoplay;
      startautoplay;
   end;
   jukeboxbutclick(nil);
end;


end;


procedure Tmainform.FormCreate(Sender: TObject);
const
toolbaralpha=0.35;
var
hc : hcursor;
devrem : pchar;
_devrem : string;
remv : integer;
reg : Tregistry;
pp : tbitmap;
tr : Trect;
begin
{$IFNDEF NEWMEDIAPLAYER}
mp:=Tmediaplayer.Create(self);
mp.parent:=self;
mp.Visible:=false;
mp.onnotify:=MPNotify;
{$ENDIF}

{$IFDEF NEWMEDIAPLAYER}
mp:=TDXMP.Create(self.handle);

{$ENDIF}

{$IFNDEF kiosk}
Save.OnClick:=SaveClick;
Open.OnClick:=OpenClick;
{$ENDIF}
mainform.DoubleBuffered:=true;
toolbar.ControlStyle:=toolbar.ControlStyle + [csOpaque];

//create jukebox mode backdrop; needed if jukebox for can't be launched as well (jbnoalbums)
vol.max:=VOLINCREMENTS;

bg:=tbitmap.create;
bg.width:=screen.width;
bg.height:=screen.height;



sbg:=LoadSkinResource('ADMINBACKDROP','',clNone,true);
tr.top:=0;
tr.left:=0;
tr.bottom:=screen.height;
tr.right:=screen.width;
bg.Canvas.StretchDraw(tr,sbg);
//sbg.free;





kiosk:=false;

{$IFDEF kiosk}
kiosk:=true;
{$ENDIF}

{$IFDEF tv}
kiosk:=true;
tvmode:=true;
{$ENDIF}
if uppercase(paramstr(1))='KIOSK' then kiosk:=true;



if (kiosk=true) then begin
kiosk:=true;
hc:=loadcursor(hinstance,'BLANKCURSOR');
screen.Cursors[-21]:=hc;
end;


if readini=false then begin
 if application.messagebox('Empathy is not yet configured for this user. Configure it now?','Empathy Configuration Not Found',MB_APPLMODAL or MB_ICONQUESTION or MB_YESNO)=IDNO then begin
 application.terminate;
 exit;
 end;


installfont;

config.path:='C:\';
config.volume:=7;
config.Dj_default:=false;
config.Dj_comment:=false;
config.lastalbum:=1;
config.dlastalbum:=1;
config.jlastalbum:=1;
config.auditiontimeout:=5;
config.burnpath:='';
config.screensaverpath:='';
config.timeannounce:=true;
config.hideexit:=true;
config.hidepanel:=false;
config.litewarn:=true;
config.defaultfilteron:=false;
config.autoplay:=true;
config.jukeboxaddall:=true;
config.jukeboxvolumepanel:=true;
config.bitrate:=192;
config.cddbserver:='www.freedb.org';
config.cddbcgi:='/~cddb/cddb.cgi';
config.email:='user@isp';



config.bgstyle:=0;
config.borderstyle:=0;
config.bgcolor:=$FFFFFF;
config.bordercolor:=rgb(90,121,165);
config.timeannounce:=true;
if getwindowsversion<6 then config.cdopt:=0 else config.cdopt:=1;

//phrases
setlength(phrases.data,10);
phrases.count:=10;
phrases.data[0]:='Great!';
phrases.data[1]:='Nice!';
phrases.data[2]:='Just Great!';
phrases.data[3]:='Here we go.';
phrases.data[4]:='Excellent';
phrases.data[5]:='Rockin.';
phrases.data[6]:='Good Sounds';
phrases.data[7]:='Lets keep them coming';
phrases.data[8]:='Super!';
phrases.data[9]:='Yeh.';



//genre
genre.count:=27;
setlength(genre.data,genre.count);
genre.data[0]:='Ambient';
genre.data[1]:='Blues';
genre.data[2]:='Childrens';
genre.data[3]:='Classical';
genre.data[4]:='Comedy';
genre.data[5]:='Country';
genre.data[6]:='Dance';
genre.data[7]:='Disco';
genre.data[8]:='Easy Listening';
genre.data[9]:='Electronic';
genre.data[10]:='Folk';
genre.data[11]:='Funk';
genre.data[12]:='Hip Hop';
genre.data[13]:='Jazz';
genre.data[14]:='Latin';
genre.data[15]:='Metal';
genre.data[16]:='Miscellaneous';
genre.data[17]:='New Wave';
genre.data[18]:='Pop';
genre.data[19]:='Punk';
genre.data[20]:='Reggae';
genre.data[21]:='R and B';
genre.data[22]:='Rock';
genre.data[23]:='Rock and Roll';
genre.data[24]:='Spoken Word';
genre.data[25]:='Various';
genre.data[26]:='World';

//ArtistType
ArtistType.count:=10;
setlength(ArtistType.data,ArtistType.count);
ArtistType.data[0]:='Band';
ArtistType.data[1]:='DJ';
ArtistType.data[2]:='Duo';
ArtistType.data[3]:='Female singer/songwriter';
ArtistType.data[4]:='Male singer/songwriter';
ArtistType.data[5]:='Female solo artist';
ArtistType.data[6]:='Male solo artist';
ArtistType.data[7]:='Orchestra';
ArtistType.data[8]:='Ensemble';
ArtistType.data[9]:='Various';


writeini;
//showprefs(true);
end;


backdrp:=tbitmap.create;
backdrp.PixelFormat:=pf24Bit;
backdrp:=LoadSkinResource('BACKGROUND',config.theme.sbackground.skin,config.theme.sbackground.Color,true);
tr.top:=0;
tr.left:=0;
tr.bottom:=screen.height;
tr.right:=screen.width;
jbbg.Free;
jbbg:=tbitmap.create;
jbbg.width:=screen.width;
jbbg.height:=screen.height;
jbbg.Canvas.StretchDraw(tr,backdrp);


application.title:=apptitle;
mainform.caption:=apptitle;


filter.genre.count:=-1;
filter.artist.count:=-1;
filter.keywords.count:=-1;
filter.recordlabel.count:=-1;
filter.excludecompilations:=false;
filter.excludenoncompilations:=false;
filter.yearlower:=-1;
filter.decadelower:=-1;


if firstrun=true then begin
cursor:=crAppstart;
application.ProcessMessages;
pp:=tbitmap.create;
butimages.getbitmap(0,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(1,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(2,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(3,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(4,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(5,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(6,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(7,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(8,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);
butimages.getbitmap(9,pp);
alphablendbitmapwithcolor(pp,CLBTNFACE,pp,toolbaralpha);
butimages.add(pp,nil);

pp.free;
end;

toolbar.doublebuffered:=true;
buttonsmousemove(nil,[],0,0);


dcurrentlyplayingtrack:=0;
dCurrentTrack:=0;

thumbsdone:=false;

cancelthumbs:=false;
paused := false;
MAINFORMWIDTH:=mainform.width;
MAINFORMHEIGHT:=mainform.height;
winposX:=mainform.left;
winposY:=mainform.height;
//thumbsdone:=false;
playmode:=0;
deviceremoveable:=false;


reg:=tregistry.Create;
reg.RootKey:=HKEY_LOCAL_MACHINE;

if getwindowsversion>2 then begin
   reg.openkey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',false) end
   else begin
   reg.openkey('SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts',false);
   end;
if reg.valueexists('Empathy Digital Font (TrueType)')=false then installfont;
reg.free;



if loadedblankmp3file=false then loadblankmp3file;

albumlist.clear;
dalbumlist.clear;
dplaylist.clear;
del.enabled:=false;
clearlist.enabled:=false;
tracklist.clear;
dtracklist.clear;


playlist.visible:=false;
playpanel.visible:=true;
transport.visible:=true;
cdplayerbut.enabled:=true;
playlistbut.enabled:=true;
jukeboxbut.enabled:=true;
//burncdbut.enabled:=true;
randombut.enabled:=true;
//trackedit.enabled:=true;
cdplayerbut.checked:=true;
//options.checked:=false;
//trackedit.checked:=false;

butcd.visible:=true;
butcdlist.visible:=true;
butrandom.visible:=true;
butjukebox.visible:=true;
//butcdburn.visible:=true;
//butcdrip.visible:=true;
bevel4.visible:=true;
bevel5.visible:=true;


showabout(0);






vol.position:=config.volume;

_devrem:=copy(config.path,0,2);
new(devrem);
strpcopy(devrem,_devrem);
remv:=GetDriveType(devrem);
if (remv and DRIVE_REMOVABLE)=DRIVE_REMOVABLE then deviceremoveable:=true else deviceremoveable:=true;




buildcontentlist(firstrun);; {=false then begin
hideall;
  if (firstrun=true) and (about.visible=true) then begin
   about.close;
   about.free;
   screen.cursor:=crDefault;
  end;
exit;
end;}


initlistboxes;
initmessage('Initialising......','','');




mp.timeformat:=tfMilliseconds;
{progress.brush.color:={viewgit}{/viewgit};}
if config.lastalbum<=albumlist.items.count then albumlist.itemindex:=config.lastalbum-1 else albumlist.itemindex:=0;
if config.dlastalbum<=dalbumlist.items.count then dalbumlist.itemindex:=config.dlastalbum-1 else dalbumlist.itemindex:=0;

albumlistChange(albumlist);
dalbumlistChange(dalbumlist);
playmode:=0;
{dcurrenttrack:=0;}

if (about.visible=true) then begin
   about.close;
   about.free;
   screen.cursor:=crDefault;
end;




end;




function tmainform.buildcontentlist(forceload : boolean) : boolean;
var
res,n,x : integer;
SearchRec : TSearchRec;
var
SavedErrorMode : dword;
begin
if forceload=false then begin
   result:=true;
    if albumcount=0 then result:=false;
   exit;
end;
SavedErrorMode:=SetErrorMode(SEM_FailCriticalErrors);
res:=FindFirst(config.path+'*__*', {viewgit}{/viewgit}000010, searchrec);
SetErrorMode(SavedErrorMode);
initmessage('Building Album List....','','');
if res=0 then begin
n:=1;
while res=0 do begin
setlength(albumref,n+1);
setlength(albumrefonload,n+1);
setlength(album,n+1);
x:=pos('__',searchrec.name);
    albumref[n].artist:=copy(searchrec.name,0,x-1);
    albumref[n].album:=copy(searchrec.name,x+2,length(searchrec.name)-x+2);
    albumrefonload[n].artist:=albumref[n].artist;
    albumrefonload[n].album:=albumref[n].album;
    res:=FindNext(searchrec);
    if (fileexists(config.path+'\'+searchrec.name+'\title.dat'))=false then begin
      maketitles(searchrec.name);
    end;

    //initmessage('Building Album List: ',albumref[n].artist,albumref[n].album);
    application.processmessages;
n:=n+1;

end;

albumcount:=n-1;
albumrefonloadcount:=albumcount;
FindClose(SearchRec);
result:=true;

//if kiosk=false then loadalbuminformation;

exit;
end;
result:=false;
end;



procedure Tmainform.trackeditClick(Sender: TObject);
begin
{$IFNDEF kiosk}
trackedit.checked:=false;
if cdplayerbut.checked=true then if showtitleedit(albumlist.itemindex)=1 then begin
formcreate(sender);

end;

if playlistbut.checked=true then if showtitleedit(dalbumlist.itemindex)=1 then begin
formcreate(sender);
end;
{$ENDIF}
end;

function tmainform.loadtitles (sender : TListbox; albumindex : integer) : boolean;
var
content : textfile;
spp : string;
fn : string;
begin
result:=false;
if albumcount=0 then exit;
fn:=config.path+album[albumindex].artist+'__'+album[albumindex].album+'\title.dat';
  AssignFile(content,fn);
  spp:=album[albumindex].artist+'__'+album[albumindex].album;
  if sender=tracklist then currentalbumpath:=config.path+spp;
  if sender=dtracklist then dcurrentalbumpath:=config.path+spp;
 try
  Reset(content);
 except;
  result:=true;
  exit;
 end;

            sender.clear;
              While (NOT EOF(content)) do begin

                   Readln (content,spp);
                  //tracklist.items.add('['+format('%.2d',[tracknm])+'] - '+spp);
                   if spp<>'' then sender.items.add(spp) else sender.items.add('Unknown track name');
             end;
CloseFile(content);
result:=true;


end;

procedure tmainform.maketitles(path : string);

var
content : textfile;
searchrec : tsearchrec;
res : integer;
tn : string;
begin
AssignFile(content,config.path+'\'+path+'\title.dat');
rewrite(content);

res:=FindFirst(config.path+'\'+path+'\*.mp?', faanyfile, searchrec);
 if res=0 then begin
           while res=0 do begin
           tn:=copy(searchrec.Name,1,length(searchrec.name)-4);
           writeln(content,tn);
           res:=FindNext(searchrec);
           end;
 end;
Closefile(content);
FindClose(SearchRec);
{$IFNDEF kiosk}
//if messagedlg('No title information file found for '+album[albumindex].artist+' '+album[albumindex].album+'. Enter title info now?',mtConfirmation,[MbYes,MbNo],0)=MrYes then showtitleedit(albumindex);
{$ENDIF}
end;

{procedure tmainform.WMDeviceChange(var msg : TMDeviceChange);
const
DEV_ARRIVAL =   00;
DEV_REMOVEQUERY  =  01;
DEV_REMOVECOMPLETE = 04;

type

PDEV_BROADCAST_HDR = ^TDEV_BROADCAST_HDR;
TDEV_BROADCAST_HDR = packed record
dbch_size: DWORD;
dbch_devicetype : DWORD;
dbch_reserved : DWORD;
end;


PDEV_BROADCAST_VOLUME = ^TDEV_BROADCAST_VOLUME;
TDEV_BROADCAST_VOLUME = packed record
dbcv_size : DWORD;
dbcv_devicetype : DWORD;
dbcv_reserved : DWORD;
dbcv_unitmask : DWORD;
dbcv_flags : WORD;
end;

var
lpdb : PDEV_BROADCAST_HDR;
lpdbv : PDEV_BROADCAST_VOLUME;
driveletter : shortint;
unitmask : longint;
begin
if deviceremoveable=false then exit;
fillchar(lpdbv,sizeof(lpdbv),0);
fillchar(lpdb,sizeof(lpdb),0);
lpdb :=PDEV_BROADCAST_HDR(msg.dwData);

if lpdb=nil then exit;

try
if (lpdb^.dbch_devicetype= {viewgit}{/viewgit}000002) then begin
     lpdbv :=PDEV_BROADCAST_VOLUME(Msg.dwData);
   end;
except
end;

DriveLetter:=Ord('A');
//fillchar(lpdbv,sizeof(lpdbv),0);
unitmask:=lpdbv.dbcv_unitmask;
while(unitmask and 1)=0 do begin
unitmask :=unitmask shr 1;
inc(Driveletter);
end;

config.path:=uppercase(config.path);
if char(driveletter)<>(config.path[1]) then exit;

case Msg.Event of

//win 9x only
DEV_REMOVEQUERY : begin

if playmode=1 then begin
if mp.filename<>'' then begin
try
stopclick(nil);
mp.stop;
except;
end;
end;
playmode:=0;
end;
hideall;
end;


DEV_REMOVECOMPLETE : begin

if playmode=1 then begin
if mp.filename<>'' then begin
try
mp.stop;
except
end;
end;
end;
hideall;
end;


DEV_ARRIVAL : begin

formcreate(mainform);
end;

end;


end;
 }
procedure tmainform.hideall;
begin
exit;
   cdplayerbutclick(nil);
   //open.enabled:=false;
   playpanel.visible:=false;
   butcdlist.visible:=false;
   playlistbut.enabled:=false;
   tracklist.visible:=false;
   cover.visible:=false;
   coverpanel.visible:=false;
   butcdlist.visible:=false;
   playlistbut.enabled:=true;
   albumlist.enabled:=false;
   //menuprint.enabled:=false;
   dalbumlist.enabled:=false;
   //trackedit.enabled:=false;
   //burncdbut.enabled:=false;
   //butcdburn.visible:=false;
   butcd.visible:=false;
   CDplayerbut.enabled:=false;
   randombut.enabled:=false;
   jukeboxbut.enabled:=true;
   coverpickbut.enabled:=false;
   butrandom.visible:=false;
   butjukebox.visible:=false;
   transport.Enabled:=false;
   stop.down:=true;
   play.down:=false;
   //if kiosk=true then begin
   // jb:=TJukeboxnoalbums.Create(application);
   // Jb.showmodal;
   // jb.free;
   //end;

end;

procedure Tmainform.OptionsClick(Sender: TObject);
begin
try
//options.checked:=false;
application.processmessages;
except;
end;
//res:=showprefs(false);
//if res=1 then hideall;
play.down:=false;
stopclick(sender);
stop.down:=true;
firstrun:=true;
formcreate(mainform);
end;




procedure Tmainform.ThumbscancelClick(Sender: TObject);
begin
     windowstate:=wsNormal;
     restoreClick(sender);
     cancelthumbs:=true;
     mainmenuvisible(true);
     toolbar.visible:=true;
end;



procedure Tmainform.FormResize(Sender: TObject);
begin
//if jukebox.visible=true then jukebox.setfocus;
{albumlist.width:=tracklist.left+tracklist.width;
dalbumlist.width:=dplaylist.left+dplaylist.width;
dalbumlist.left:=dtracklist.left;}

end;




procedure Tmainform.setupfrequency;
begin
 progress.max:=Round (mp.length / DIVISION);
 progress.linesize:=1;
 progress.pagesize:=100;
 progress.frequency:=5;
end;

procedure Tmainform.ReturntoPlayerClick(Sender: TObject);
begin
Thumbscancelclick(sender);
end;

procedure Tmainform.AddalltrackstoplaylistClick(Sender: TObject);
var
n,i : integer;

begin
for n:=1 to albumcount do begin
sender:=thumbundercursor;
if sender=thumb[n] then begin
     restoreClick(sender);
     albumlist.itemindex:=n-1;
     albumlistChange(sender);
     dalbumlist.itemindex:=n-1;
     dalbumlistChange(sender);
     mainmenuvisible(true);
     toolbar.visible:=true;
     playlistbut.checked:=true;
     playlistbutclick(sender);
     for i:=0 to dtracklist.items.count-1 do begin
     dtracklist.itemindex:=i;
     addclick(sender);
     end;
exit;
end;
end;
end;


procedure Tmainform.FormKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=ord('P')) and (Shift=[ssCTRL,ssALT]) then begin
if play.enabled=true then begin
   play.down:=true;
   playclick(sender);
   end;

if play.enabled=false then begin
if tracklist.selected[tracklist.itemindex]=false then
tracklist.setfocus;
keybd_event(VK_SPACE,0,0,0);
application.processmessages;
play.down:=true;
playclick(sender);

end;
end;

if (key=VK_ESCAPE) then begin

if (stop.enabled=true) and (stop.down=false) then begin
   stop.down:=true;
   stopclick(sender);
   exit;
   end;
if stop.down=true then begin
   cdplayerbut.checked:=true;
   cdplayerbutclick(nil);
end;

end;

if (key=ord('M')) and (Shift=[ssCTRL,ssALT]) then begin
if pause.enabled=true then begin
   pause.down:=true;
   pauseclick(sender);
   end;
end;


if (key=ord('A')) and (Shift=[ssCTRL,ssALT]) then begin
albumlist.SetFocus;
keybd_event(VK_UP,0,0,0);
end;

if (key=ord('Z')) and (Shift=[ssCTRL,ssALT]) then begin
albumlist.SetFocus;
keybd_event(VK_DOWN,0,0,0);
end;

if (key=ord('S')) and (Shift=[ssCTRL,ssALT]) then begin
bckclick(sender);
end;

if (key=ord('T')) and (Shift=[ssCTRL,ssALT]) then begin
if (dj.enabled=true) and (dj.down=false) then begin; dj.down:=true; djclick(nil); exit; end;
if (dj.enabled=true) and (dj.down=true) then begin; dj.down:=false; djclick(nil); exit; end;

end;


if (key=ord('X')) and (Shift=[ssCTRL,ssALT]) then begin
tracklist.setfocus;
application.processmessages;
if tracklist.selected[tracklist.itemindex]=true then fwdclick(sender) else begin
keybd_event(VK_SPACE,0,0,0);
end;
end;

if (key=ord('C')) and (Shift=[ssCTRL,ssALT]) then begin
coverclick(sender);
end;

if (key=ord('R')) and (Shift=[ssCTRL,ssALT]) then begin
if playmode=1 then stopclick(sender);
rnd_dialog.show;
playlistbutClick(playlistbut);
playlistbut.checked:=true;
dplaylist.itemindex:=0;
rnd_dialog.all.click;
rnd_dialog.Okbtn.Click;
screen.cursor:=crDefault;
application.processmessages;
end;
end;

procedure Tmainform.popupplayClick(Sender: TObject);
begin
If dplaylist.Items.count>0 then del.enabled:=true;
dcurrentlyplayingtrack:=dplaylist.itemindex;
playmode:=0;
setuptrackname(dplaylist.itemindex);
play.down:=true;
playclick(Sender);
end;

procedure Tmainform.popupremoveClick(Sender: TObject);
begin
delclick(sender);

end;

procedure Tmainform.burncdbutClick(Sender: TObject);
begin
if kiosk=false then begin
//burncdbut.checked:=true;
burncd.show;
end;
end;


function runprogram(commandline : string; windowstate : integer;waitfor :boolean) : boolean;
type
tenv = pchar;
var
comline : array [0..255] of char;
startupinfo : tstartupinfo;
processinfo : tProcessinformation;
lpExitcode : cardinal;
msg : tmsg;
pass : array [0..255] of char;
begin
strpcopy(comline,commandline);

with startupinfo do begin
cb := sizeof(startupinfo);
lpreserved:=nil;
lpdesktop:=nil;
lptitle:=nil;
dwflags := STARTF_USESHOWWINDOW;
lpreserved := nil;
cbreserved2 :=0;
lpreserved2 := nil;
if windowstate=0 then wshowwindow:=sw_normal else wshowwindow:=sw_hide;
end;

fillchar(pass,sizeof(pass),0);
//SetPrivilege('SeAssignPrimaryTokenPrivilege',true); //maybe needed



result:=createprocess(nil,comline,nil,nil,false,normal_priority_class, nil,nil,startupinfo,processinfo);
if result=true then begin

   if waitfor=true then begin
      lpexitcode:=STILL_ACTIVE;
     	 while(lpexitcode=STILL_ACTIVE) do begin;
           while(peekmessage(msg,0,0,0,PM_REMOVE)) do begin
   		If msg.message = WM_QUIT then halt(msg.wparam);
   		TranslateMessage(msg);
   		DispatchMessage(Msg);
   		end;
      	getexitcodeprocess(processinfo.hprocess,lpexitcode);
   	end;
   end;
end;
end;



procedure Tmainform.launchscreensaverClick(Sender: TObject);
//var
//h : thandle;
//fs : Tfilestream;
//ladapter : TStreamAdapter;
begin
//write image list out using API experiment for DFM removal
//fs:=Tfilestream.Create('c:\tst.txt',fmCreate);
//h:=mainform.butimages.Handle;
//    LAdapter := TStreamAdapter.Create(fs);
//imagelist_write(h,ladapter);
//fs.free;
//ladapter.free;
if runprogram(config.screensaverpath,0,false)=false then showwarning('Launch eyecandy program','Could not run eyecandy program. Check that you have specified a correct path in options. If the program is a screen saver, try placing " /s" after the program path to activate screen save mode.','An eyecandy program is visualisation software such as a sound to light program or a screen saver.','Recommended programs',WEBSITEURL+'navigation.php?sec=links#eyecandy',false);
end;

{procedure Tmainform.hinttimerTimer(Sender: TObject);
var
msg : tmsg;
begin
inc(hinttimercount);
if (hinttimercount=20) or (hintwindow.ishintmsg(msg)=true) then begin
//hinttimer.Enabled:=false;
hintwindow.releasehandle;
end;
end;
 }
procedure Tmainform.dplaylistDblClick(Sender: TObject);
begin
playbutmod.visible:=false;
if dplaylist.itemindex<>-1 then playClick(Sender)
end;

procedure Tmainform.jukeboxbutClick(Sender: TObject);
begin
if assigned(sender) then if tcomponent(sender).name='butjukebox' then begin
  config.mediaplayermode:=false;
end;
  //if thumbsdone=false then mainform.thumbviewgo(false);   //Load thumbs for jukebix
if albumlist.items.count<3 then begin
//if kiosk=false then messagedlg('You must have at least 3 albums loaded before jukebox mode can be used',mterror,[mbok],0);
if kiosk=true then begin
                         hideall;
                         end;
end;
//trackedit.enabled:=true;
playlistbut.checked:=true;
playlistbutclick(nil);
initmessage('Initalising Jukebox....','','');

gojukebox(true);

moveformtomonitor(TForm(jukebox));
if config.mediaplayermode=true then jukebox.close;

end;


procedure Tmainform.tracklistDblClick(Sender: TObject);
begin
playclick(nil);
play.down:=true;

end;

procedure Tmainform.dtracklistDblClick(Sender: TObject);
begin
addclick(sender);
end;

procedure Tmainform.ripcdClick(Sender: TObject);
begin
//ripcd.checked:=false;
end;


procedure Tmainform.FormActivate(Sender: TObject);
begin
if config.Dj_default=true then begin
dj.down:=true;
djclick(sender);
end;
moveformtomonitor(self);

volchange(sender);
buttonsMouseMove(nil,[],0,0);

end;


procedure Tmainform.buttonsMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
if (jukebox<>nil) then if (jukebox.visible=true)  then exit;

if (sender=butcd) or (cdplayerbut.checked) then butimages.GetBitmap(0,butcd.picture.bitmap) else butimages.GetBitmap(10,butcd.picture.bitmap);
if (sender=butcdlist) or (playlistbut.checked) then butimages.GetBitmap(1,butcdlist.picture.bitmap) else butimages.GetBitmap(11,butcdlist.picture.bitmap);
if (sender=butrandom) or (randombut.checked) then butimages.GetBitmap(2,butrandom.picture.bitmap) else butimages.GetBitmap(12,butrandom.picture.bitmap);
if (sender=butjukebox) or (jukeboxbut.checked) then butimages.GetBitmap(3,butjukebox.picture.bitmap) else butimages.GetBitmap(13,butjukebox.picture.bitmap);
//if (sender=butcdburn) then butimages.GetBitmap(6,butcdburn.picture.bitmap);
//if (sender=butcdrip) then butimages.GetBitmap(7,butcdrip.picture.bitmap);
//if (sender=buttools) then butimages.GetBitmap(8,buttools.picture.bitmap);
///if (sender=butexplore) then butimages.GetBitmap(9,butexplore.picture.bitmap);




//if( sender<>butcd) then butimages.GetBitmap(9,butcd.picture.bitmap);
//if (sender<>butcdlist) then butimages.GetBitmap(10,butcdlist.picture.bitmap);
//if (sender<>butrandom) then butimages.GetBitmap(11,butrandom.picture.bitmap);
//if (sender<>butjukebox) then butimages.GetBitmap(12,butjukebox.picture.bitmap);
//if (sender<>butcdburn) then butimages.GetBitmap(16,butcdburn.picture.bitmap);
//if (sender<>butcdrip) then butimages.GetBitmap(17,butcdrip.picture.bitmap);
//if (sender<>buttools) then butimages.GetBitmap(18,buttools.picture.bitmap);
//if (sender<>butexplore) then butimages.GetBitmap(19,butexplore.picture.bitmap);


toolbar.invalidate;

end;


procedure Tmainform.butfilterClick(Sender: TObject);
begin
//filter.checked:=true;
end;

procedure Tmainform.filtermenuClick(Sender: TObject);
begin
butfilterclick(nil);
end;

procedure Tmainform.fileexitClick(Sender: TObject);
begin
close;
application.terminate;
end;

procedure Tmainform.menuaboutClick(Sender: TObject);
begin
showabout(1);
end;


{$IFNDEF kiosk}
//  NOTE: Components originally placed on mainform. Removed for kiosk. Need replacing e.g. create at runtime and assign events.

procedure Tmainform.saveClick(Sender: TObject);
var
fl : tfilestream;
bytefilt : tfilterbytearray;
size : longint;
n : integer;

    function tfilterbytearraywritesizeanddata(str : tfilterbytearray) : integer;overload;
    begin
      result:=0;
      try
      size:=length(str);
      fl.write(size,sizeof(size));
      fl.write(pointer(str)^,length(str));
      except
      result:=-1;
      end;
    end;


    function writesizeanddata(str : string) : integer;overload;
    begin
      result:=0;
      try
      size:=length(str);
      fl.write(size,sizeof(size));
      fl.write(pointer(str)^,length(str));
      except
      result:=-1;
      end;
    end;


begin

if savedialog.execute=false then exit;

if fileexists(savedialog.filename) then if deletefile(savedialog.filename)=false then begin
   messagedlg('Error opening file: '+savedialog.filename,mterror,[mbOK],0);
   exit;
end;
fl:=tfilestream.create(savedialog.filename,fmCreate);
fl.seek(0,soFromBeginning);
fl.Write(PLAYLISTFILEHEADER,length(PLAYLISTFILEHEADER));
bytefilt:=tfiltertobytearray(filter);
tfilterbytearraywritesizeanddata(bytefilt);

n:=dplaylist.items.count-1;
fl.write(n,sizeof(integer));
for n:=0 to dplaylist.items.count-1 do begin
 writesizeanddata(dPlayListMatrixAlb[n]);
 fl.write(dPlayListMatrixTrk[n],sizeof(dPlayListMatrixTrk[n]));
 writesizeanddata(dplaylist.Items[n]);
end;

fl.free;
end;

procedure Tmainform.OpenClick(Sender: TObject);
var
fl : tfilestream;
bytefilt : tfilterbytearray;
filt : tfilter;
size : longint;
scrap : string;
itemstotal : integer;
n : integer;

function readsizeanddata : string;overload;
    var
    count : integer;
    begin
      try
      count:=sizeof(size);
      fl.read(size,count);
      if (count<sizeof(size)) then begin; result:=''; exit; end;
      setlength(result,size);
      fl.read(pointer(result)^,size);
      except
      result:='';
      end;
    end;



    function tfilterbytearrayread : tfilterbytearray;overload;
    var
    count : integer;
    begin
      try
      count:=sizeof(size);
      fl.read(size,count);
      if (count<sizeof(size)) then begin; result:=nil; exit; end;
      setlength(result,size);
      fl.read(pointer(result)^,size);
      except
      result:=nil;
      end;
    end;

begin
setlength(bytefilt,1);
bytefilt[0]:=0;
if opendialog.execute=true then begin
if cdplayerbut.checked=true then playlistbutclick(nil);
clearlistclick(nil);
fl:=tfilestream.create(opendialog.filename,fmOpenRead);
setlength(scrap,length(PLAYLISTFILEHEADER));
fl.read(pointer(scrap)^,length(PLAYLISTFILEHEADER));
bytefilt:=tfilterbytearrayread;
filt:=bytearraytofilter(bytefilt);

if NOT((filt.genre.count=-1) and (filt.artist.count=-1) and
   (filt.keywords.count=-1) and (filt.recordlabel.count=-1) and
   (filt.excludecompilations=false) and (filt.excludenoncompilations=false) and
   (filt.yearlower=-1) and (filt.decadelower=-1)) then begin
   if Messagedlg('A filter was in place when this playlist was saved. Restore the filter?',mtconfirmation,[mbYes,mbNo],0)=MrYes then begin
     dofilter(filter);
     end;
   end;
dplaylist.items.clear;


fl.read(itemstotal,sizeof(integer));
setlength(dPlayListMatrixAlb,itemstotal+2);
setlength(dPlayListMatrixTrk,itemstotal+2);

for n:=0 to itemstotal do begin
 dPlayListMatrixAlb[n]:=readsizeanddata;
 fl.read(dPlayListMatrixTrk[n],sizeof(dPlayListMatrixTrk[n]));
 dplaylist.items.add(readsizeanddata);
end;

end;
fl.free;

end;
{$ENDIF}

procedure Tmainform.reloadClick(Sender: TObject);
begin
firstrun:=true;
try
if mp.filename<>'' then mp.stop;
except;
end;
writeini;
mainform.enabled:=false;
formcreate(nil);
mainform.enabled:=true;
end;

procedure Tmainform.hyperlink_helpfilesystemClick(Sender: TObject);
begin
ShellExecute (0, nil, pchar(WEBSITEURL+'?help=filesystem'), nil, nil, SW_SHOWNORMAL);
end;

procedure Tmainform.hyperlink_helpalbuminfoClick(Sender: TObject);
begin
ShellExecute (0, nil, pchar(WEBSITEURL+'?help=filters'), nil, nil, SW_SHOWNORMAL);
end;

procedure Tmainform.helpClick(Sender: TObject);
begin
ShellExecute (0, nil, pchar(WEBSITEURL+'?sec=2&sub=2'), nil, nil, SW_SHOWNORMAL);
end;


procedure Tmainform.insertClick(Sender: TObject);
var
point : integer;
n : integer;
begin
if dplaylist.itemindex=dplaylist.items.count-1 then begin
addclick(sender);
exit;
end;
setlength(dplaylistMatrixAlb,dplaylist.Items.count+1);
setlength(dplaylistMatrixTrk,dplaylist.Items.count+1);

point:=dplaylist.itemindex+1;

n:=dplaylist.Items.count-1;
while(n>=(point-1)) do begin
dplaylistMatrixAlb[n+1]:=dplaylistMatrixAlb[n];
dplaylistMatrixTrk[n+1]:=dplaylistMatrixTrk[n];
dec(n);
end;

dplaylist.items.insert(point,dtracklist.items[dtracklist.itemindex]);
dplaylistMatrixAlb[point]:=dcurrentalbumpath;
dplaylistMatrixTrk[point]:=dtrackList.itemindex+1;
dcurrenttrack:=dcurrenttrack+1;




end;

procedure Tmainform.dplaylistDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
begin
if Source is tlistbox then Accept := True;

end;

procedure Tmainform.dplaylistDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var
sfirst,ssecond : string;
ifirst,isecond : integer;
n : integer;
tp : tpoint;
alb : string;
trk : integer;

begin
if source=dtracklist then begin
addclick(nil);
end;


if source=self then begin
ifirst:=-1;
for n:=0 to TListBox(Source).items.count do begin
  if TListBox(Source).selected[n]=true then begin
     sfirst:=TListBox(Source).items[n];
     ifirst:=n;
     break;
  end;
end;
tp.x:=x;
tp.y:=y;
isecond:=TListbox(Source).itematpos(tp,true);
ssecond:=TListbox(Source).items[isecond];
Tlistbox(Source).items[ifirst]:=ssecond;
Tlistbox(Source).items[isecond]:=sfirst;

alb:=dplaylistMatrixAlb[isecond];
trk:=dplaylistMatrixTrk[isecond];

dplaylistMatrixAlb[isecond]:=dplaylistMatrixAlb[ifirst];
dplaylistMatrixTrk[isecond]:=dplaylistMatrixTrk[ifirst];

dplaylistMatrixAlb[ifirst]:=alb;
dplaylistMatrixTrk[ifirst]:=trk;
end;

end;

procedure Tmainform.menuprintClick(Sender: TObject);
begin
{$IFNDEF kiosk}
showprint;
{$ENDIF}
end;

procedure Tmainform.buttonstimerTimer(Sender: TObject);
begin
if DEBUGON=false then begin
buttonstimer.enabled:=false;
exit;
end;
buttonsMouseMove(nil,[],0,0);  transport.repaint;
end;


procedure Tmainform.butexploreClick(Sender: TObject);
begin
{$IFNDEF kiosk}
//if explorego=mrOK then reloadclick(nil);
{$ENDIF}
end;



procedure Tmainform.menufiletagClick(Sender: TObject);
begin
{$IFNDEF kiosk}
if messagedlg('This will run through each album and tag all MP3 files with album and artist info.'#10#13'Are you sure you want to do this?',mtconfirmation,[mbYes,mbNo],0)=MrYes then tagmp3s.showmodal;
{$ENDIF}
end;




end.