#include "QMediaBibliothek.h"

//
QMediaBibliothek::QMediaBibliothek( QWidget * parent, Qt::WFlags f) : QMainWindow(parent, f)
{
	version = "Version 0.3.1 ";
	QCoreApplication::setApplicationName("QMediaBibliothek");
	this->setMinimumSize(QSize(700,570));
	this->setWindowIcon(QPixmap(":/src/icons/qmediabibliothek.png"));
	dataModified = 0;
	defaultBrowser = "Konqueror";
	genre << "Action" << "Science Fiction" << "Phantasie" << "Drama" << "Comedy" << "Thriller" << "Music" << "Documentation" << "Education" << "misc";
	basePath = (QString)getenv("HOME");
	QDir tempDir(basePath); 
	if (!QFile::exists(basePath+"/.MediaBib")){
		tempDir.mkpath(basePath + (QString)"/.MediaBib");
	}

	mainMenu = new QMenuBar(this);
	fileMenu = new QMenu(tr("&File"),mainMenu);
	optionMenu = new QMenu(tr("&Option"),mainMenu);
	helpMenu = new QMenu(tr("&Help"),mainMenu);
	orderByMenu = new QMenu(tr("&Order table by"),optionMenu);
	toolBar = new QToolBar(this);
	toolBar->setFloatable(false);
	toolBar->setMovable(false);
	recentlyUsedMenu = new QMenu(tr("&recently used Databases"),fileMenu);
	actionNewDatabase = new QAction(this);
	actionQuit = new QAction(this);
	actionOpen = new QAction(this);
	actionSave = new QAction(this);
	actionSaveAs = new QAction(this);
	actionGenreSetup = new QAction(this);
	actionOrderByTitle = new QAction(this);
	actionOrderByGenre = new QAction(this);
	actionOrderByTime = new QAction(this);
	actionMultiAddMovies = new QAction(this);
	actionSetup = new QAction(this);
	actionAboutQt = new QAction(this);
	actionHelp = new QAction(this);
	actionAboutQMediaBibliothek = new QAction(this);
	actionConsistencyCheck = new QAction(this);
	
	actionRecentlyUsed = new QAction(this);
	recentlyUsedMenu->setIcon(QIcon(":/src/icons/recently.png"));
	actionRecentlyUsed1 = new QAction(this);
	actionRecentlyUsed1->setIcon(QIcon(":/src/icons/recently.png"));
	actionRecentlyUsed2 = new QAction(this);
	actionRecentlyUsed2->setIcon(QIcon(":/src/icons/recently.png"));
	actionRecentlyUsed3 = new QAction(this);
	actionRecentlyUsed3->setIcon(QIcon(":/src/icons/recently.png"));
	actionRecentlyUsed4 = new QAction(this);
	actionRecentlyUsed4->setIcon(QIcon(":/src/icons/recently.png"));
	actionRecentlyUsed5 = new QAction(this);
	actionRecentlyUsed5->setIcon(QIcon(":/src/icons/recently.png"));
	
	connect(actionRecentlyUsed1,SIGNAL(activated()),this,SLOT(slot_actionRecentlyUsed1Activated()));
	connect(actionRecentlyUsed2,SIGNAL(activated()),this,SLOT(slot_actionRecentlyUsed2Activated()));
	connect(actionRecentlyUsed3,SIGNAL(activated()),this,SLOT(slot_actionRecentlyUsed3Activated()));
	connect(actionRecentlyUsed4,SIGNAL(activated()),this,SLOT(slot_actionRecentlyUsed4Activated()));
	connect(actionRecentlyUsed5,SIGNAL(activated()),this,SLOT(slot_actionRecentlyUsed5Activated()));
	
	toolBarActionNew = new QAction(this);
	toolBarActionNew->setToolTip(tr("New Database"));
	toolBarActionOpen = new QAction(this);
	toolBarActionOpen->setToolTip(tr("Open Database"));
	toolBarActionSave = new QAction(this);
	toolBarActionSave->setToolTip(tr("Save Database"));
	toolBarActionQuit = new QAction(this);
	toolBarActionQuit->setToolTip(tr("Close Application"));
	toolBarActionCopy = new QAction(this);
	toolBarActionCopy->setToolTip(tr("Copy File to destination"));
	
	actionNewDatabase->setIcon(QIcon(":/src/icons/new.png"));
	actionNewDatabase->setText(tr("&New Database"));
	actionOpen->setIcon(QIcon(":/src/icons/open.png"));
	actionOpen->setText(tr("&Open Database"));
	actionSave->setIcon(QIcon(":/src/icons/save.png"));
	actionSave->setText(tr("&Save Database"));
	actionSaveAs->setIcon(QIcon(":/src/icons/saveas.png"));
	actionSaveAs->setText(tr("Save Database &as"));
	actionQuit->setIcon(QIcon(":/src/icons/exit.png"));
	actionQuit->setText(tr("&Quit"));
	actionMultiAddMovies->setIcon(QIcon(":/src/icons/addadd.png"));
	actionMultiAddMovies->setText(tr("&add multiple Movies"));
	actionGenreSetup->setIcon(QIcon(":/src/icons/configure.png"));
	actionGenreSetup->setText(tr("&Genre Setup"));
	actionOrderByTitle->setText(tr("&Title"));
	actionOrderByGenre->setText(tr("&Genre"));
	actionOrderByTime->setText(tr("T&ime"));
	actionSetup->setIcon(QIcon(":/src/icons/settings.png"));
	actionSetup->setText(tr("&Settings"));
	actionAboutQt->setText(tr("&About Qt"));
	actionAboutQt->setIcon(QIcon(":/src/icons/qt.png"));
	actionAboutQMediaBibliothek->setText(tr("About &me"));
	actionAboutQMediaBibliothek->setIcon(QIcon(":/src/icons/aboutme.png"));
	actionConsistencyCheck->setText(tr("&Check Consistency"));
	actionConsistencyCheck->setIcon(QIcon(":/src/icons/consistencycheck.png"));
	actionHelp->setText(tr("&Help"));
	actionHelp->setIcon(QIcon(":/src/icons/help.png"));

	toolBarActionNew->setIcon(QIcon(":/src/icons/new.png"));
	toolBarActionOpen->setIcon(QIcon(":/src/icons/open.png"));
	toolBarActionSave->setIcon(QIcon(":/src/icons/save.png"));
	toolBarActionQuit->setIcon(QIcon(":/src/icons/exit.png"));
	toolBarActionCopy->setIcon(QIcon(":/src/icons/copy.png"));

	toolBar->addAction(toolBarActionNew);
	toolBar->addAction(toolBarActionOpen);
	toolBar->addAction(toolBarActionSave);
	toolBar->addAction(toolBarActionCopy);
	toolBar->addSeparator();
	toolBarSortByLabel = new QLabel(tr("Table sort by "),this);
	toolBarSortByLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	toolBar->addWidget(toolBarSortByLabel);
	sortByComboBox = new QComboBox(this);
	sortByComboBox->setToolTip(tr("select Table sort order"));
	sortByComboBox->addItem(tr("Title"));
	sortByComboBox->addItem(tr("Genre"));
	sortByComboBox->addItem(tr("Time"));
	toolBar->addWidget(sortByComboBox);
	toolBar->addSeparator();
	toolBarWebSourcesLabel = new QLabel(tr("Web Source "),this);
	toolBarWebSourcesLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	toolBar->addWidget(toolBarWebSourcesLabel);
	webLookupSources = new QComboBox(this);
	webLookupSources->setFont(QFont("Helvetic",10,QFont::Normal,false));
	webLookupSources->addItem("IMDB (www.imdb.com)");
	webLookupSources->addItem("IMDB (www.imdb.de)");
	webLookupSources->addItem("Wikipedia (de.wikipedia.org)");
	webLookupSources->addItem("FilmDB (www.filmdb.de)");
	webLookupSources->addItem("Yahoo Movie DB (de.movies.yahoo.com)");
	webLookupSources->addItem("Cineasten (www.cineasten.de)");
	toolBar->addWidget(webLookupSources);
	toolBar->addSeparator();
	toolBar->addAction(toolBarActionQuit);

	mainMenu->addAction(fileMenu->menuAction());
	mainMenu->addAction(optionMenu->menuAction());
	mainMenu->addAction(helpMenu->menuAction());
	optionMenu->addAction(actionMultiAddMovies);
	optionMenu->addAction(actionGenreSetup);
	optionMenu->addSeparator();
	optionMenu->addAction(orderByMenu->menuAction());
	optionMenu->addSeparator();
	optionMenu->addAction(actionConsistencyCheck);
	optionMenu->addSeparator();
	optionMenu->addAction(actionSetup);
	helpMenu->addAction(actionAboutQt);
	helpMenu->addAction(actionAboutQMediaBibliothek);
	helpMenu->addSeparator();
	helpMenu->addAction(actionHelp);
	
	fileMenu->addAction(actionNewDatabase);
	fileMenu->addAction(actionOpen);
	fileMenu->addSeparator();
	fileMenu->addAction(actionSave);
	fileMenu->addAction(actionSaveAs);
	fileMenu->addSeparator();
	fileMenu->addAction(recentlyUsedMenu->menuAction());
	fileMenu->addSeparator();
	fileMenu->addAction(actionQuit);
	orderByMenu->setIcon(QIcon(":/src/icons/sortby.png"));
	orderByMenu->addAction(actionOrderByTitle);
	orderByMenu->addAction(actionOrderByGenre);
	orderByMenu->addAction(actionOrderByTime);
	
	this->setMenuBar(mainMenu);
	
	searchEditLabel = new QLabel(tr("search : "),this);
	searchEditLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	searchEdit = new QLineEdit(this);
	searchEdit->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	submitButton = new QPushButton(tr("OK"),this);
	submitButton->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	hitLabel = new QLabel(tr("hits : "),this);
	hitLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	movieTable = new QTableWidget(0,3,this);
	QStringList tableHeader;
	tableHeader << tr("Title") << tr("Time") << tr("Genre");
	movieTable->setHorizontalHeaderLabels(tableHeader);
	movieTable->setEditTriggers(0);
	sortBy = 0;
	
	connect(actionQuit, SIGNAL(activated()), this, SLOT(close()));
	connect(toolBarActionQuit, SIGNAL(activated()), this, SLOT(close()));
	
	mediaPlayerFrame = new QFrame(this);
	mediaPlayerFrame->setFrameStyle(QFrame::Panel|QFrame::Raised);
	mediaObject = new Phonon::MediaObject(this);
	mediaObject->setTickInterval(100);
	videoWidget = new Phonon::VideoWidget(this);
	Phonon::createPath(mediaObject,videoWidget);
	audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory,this);
	Phonon::createPath(mediaObject,audioOutput);

	beginButton = new QPushButton(QIcon(":/src/icons/player_start.png"),"",this);
	beginButton->setToolTip(tr("Go to the start"));
	rewindButton = new QPushButton(QIcon(":/src/icons/player_rew.png"),"",this);
	rewindButton->setToolTip(tr("Rewind the movie"));
	playButton = new QPushButton(QIcon(":/src/icons/player_play.png"),"",this);
	playButton->setToolTip(tr("Start playing"));
	pauseButton = new QPushButton(QIcon(":/src/icons/player_pause.png"),"",this);
	pauseButton->setToolTip(tr("Pause the movie"));
	stopButton = new QPushButton(QIcon(":/src/icons/player_stop.png"),"",this);
	stopButton->setToolTip(tr("Stop the movie"));
	ffButton = new QPushButton(QIcon(":/src/icons/player_fwd.png"),"",this);
	ffButton->setToolTip(tr("Fast forward the movie"));
	endButton = new QPushButton(QIcon(":/src/icons/player_end.png"),"",this);
	endButton->setToolTip(tr("Go to the end of the movie"));
	playFullScreenButton = new QPushButton(QIcon(":/src/icons/fullscreen.png"),"",this);
	playFullScreenButton->setToolTip(tr("Play movie in external Player"));
	
	playTimeLabel = new QLabel(tr("Time : 00:00:00"),this);
	playTimeLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));

	progress = new QSlider(Qt::Horizontal,this);
	progress->setTracking(false);
	progress->setSingleStep(1000);
	progress->setPageStep(10000);
	progress->setValue(0);
			
	connect(playButton,SIGNAL(clicked()),this,SLOT(slot_playButtonClicked()));
	connect(pauseButton,SIGNAL(clicked()),this,SLOT(slot_pauseButtonClicked()));
	connect(stopButton,SIGNAL(clicked()),mediaObject,SLOT(stop()));
	connect(ffButton,SIGNAL(clicked()),this,SLOT(slot_ffButtonClicked()));
	connect(rewindButton,SIGNAL(clicked()),this,SLOT(slot_rewindButtonClicked()));
	connect(mediaObject,SIGNAL(tick(qint64)),this,SLOT(slot_tickInterval(qint64)));
	connect(progress,SIGNAL(sliderMoved(int)),this,SLOT(slot_sliderMoved(int)));
	connect(beginButton,SIGNAL(clicked()),this,SLOT(slot_beginButtonClicked()));
	connect(endButton,SIGNAL(clicked()),this,SLOT(slot_endButtonClicked()));
	connect(actionOpen,SIGNAL(activated()),this,SLOT(slot_openActionActivated()));
	connect(toolBarActionOpen,SIGNAL(activated()),this,SLOT(slot_openActionActivated()));
	connect(actionSave,SIGNAL(activated()),this,SLOT(slot_saveActionActivated()));
	connect(actionSaveAs,SIGNAL(activated()),this,SLOT(slot_saveAsActionActivated()));
	connect(toolBarActionSave,SIGNAL(activated()),this,SLOT(slot_saveActionActivated()));
	connect(submitButton,SIGNAL(clicked()),this,SLOT(slot_submitButtonClicked()));
	connect(searchEdit,SIGNAL(returnPressed()),this,SLOT(slot_submitButtonClicked()));
	connect(playFullScreenButton,SIGNAL(clicked()),this,SLOT(slot_playFullScreenButtonClicked()));
	connect(sortByComboBox,SIGNAL(activated(int)),this,SLOT(slot_orderByComboBoxActivated(int)));
	connect(actionAboutQMediaBibliothek,SIGNAL(activated()),this,SLOT(slot_aboutMediaBibliothek()));
	connect(actionConsistencyCheck,SIGNAL(activated()),this,SLOT(slot_consistencyCheckActivated()));
	connect(actionHelp,SIGNAL(activated()),this,SLOT(slot_actionHelpActivated()));
	
	inputFrame = new QFrame(this);
	inputFrame->setFrameStyle(QFrame::Panel|QFrame::Sunken);

	filenameLabel = new QLabel(tr("File: "),this);
	filenameLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	filenameEdit = new QLineEdit(this);
	filenameEdit->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	titleLabel = new QLabel(tr("Title : "),this);
	titleLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	titleEdit = new QLineEdit(this);
	titleEdit->setFont(QFont("Helvetic",10,QFont::Normal,false));
	fileSelectButton = new QPushButton(QIcon(":/src/icons/folder.png"),"",this);
	fileSelectButton->setToolTip(tr("Select a movie to add."));

	genreLabel = new QLabel(tr("Genre : "),this);
	genreLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	genreComboBox = new QComboBox(this);
	genreComboBox->insertItems(0,genre);
	
	timeLabelLabel = new QLabel(tr("Time : "),this);
	timeLabelLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	timeLabel = new QLabel("",this);
	timeLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	descriptionLabel = new QLabel(tr("Description"),this);
	descriptionLabel->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	lookupButton = new QPushButton("",this);
	lookupButton->setIcon(QIcon(":/src/icons/weblookup.png"));
	lookupButton->setToolTip(tr("Title lookup in the web"));

	commentEdit = new QTextEdit(this);
	commentEdit->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	addButton = new QPushButton(QIcon(":/src/icons/add.png"),tr("add"),this);
	addButton->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	delButton = new QPushButton(QIcon(":/src/icons/del.png"),tr("del"),this);
	delButton->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	modifyButton = new QPushButton(QIcon(":/src/icons/modify.png"),tr("modify"),this);
	modifyButton->setFont(QFont("Helvetic",10,QFont::Normal,false));
	
	printButton = new QPushButton(QIcon(":/src/icons/printer.png"),"",this);
	printButton->setFont(QFont("Helvetic",10,QFont::Normal,false));

	connect(fileSelectButton,SIGNAL(clicked()),this,SLOT(slot_fileSelectButtonClicked()));
	connect(movieTable,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(slot_movieTableDoubleClicked(QModelIndex)));
	connect(addButton,SIGNAL(clicked()),this,SLOT(slot_addButtonClicked()));
	connect(modifyButton,SIGNAL(clicked()),this,SLOT(slot_modifyButtonClicked()));
	connect(delButton,SIGNAL(clicked()),this,SLOT(slot_delButtonClicked()));
	connect(actionOrderByTitle,SIGNAL(activated()),this,SLOT(slot_actionOrderByTitleActivated()));
	connect(actionOrderByGenre,SIGNAL(activated()),this,SLOT(slot_actionOrderByGenreActivated()));
	connect(actionOrderByTime,SIGNAL(activated()),this,SLOT(slot_actionOrderByTimeActivated()));
	connect(actionGenreSetup,SIGNAL(activated()),this,SLOT(slot_actionGenreSetupActivated()));
	connect(actionMultiAddMovies,SIGNAL(activated()),this,SLOT(slot_actionMultiAddMoviesActivated()));
	connect(actionSetup,SIGNAL(activated()),this,SLOT(slot_actionSetupActivated()));
	connect(actionNewDatabase,SIGNAL(activated()),this,SLOT(slot_actionNewDatabaseActivated()));
	connect(toolBarActionNew,SIGNAL(activated()),this,SLOT(slot_actionNewDatabaseActivated()));
	connect(lookupButton,SIGNAL(clicked()),this,SLOT(slot_lookupButtonClicked()));
	connect(actionAboutQt,SIGNAL(activated()),this,SLOT(slot_aboutQt()));
	connect(toolBarActionCopy,SIGNAL(activated()),this,SLOT(slot_copyActionActivated()));
	connect(printButton,SIGNAL(clicked()),this,SLOT(slot_printButtonClicked()));
	this->showMaximized();
	setup();
	QMessageBox::information(this,"QMediaBibliothek","<center><img src=':/src/icons/qmediabibliothekabout.png'><br><br>" + version + "<br><br>written 2009 by J&ouml;rg Zopes<br>Published under GPL 2.0 or newer.</center>");
	if (!defaultDatabase.isNull()){
		filename = defaultDatabase;
		loadDatabase(defaultDatabase);
	}
	rebuildRecentlyUsedMenu();
}

QMediaBibliothek::~QMediaBibliothek(){
	if (dataModified == true){
		if (QMessageBox::question(this,tr("WARNING"),tr("There is modified data left. Do you want to save it?"), QMessageBox::Yes,QMessageBox::No )==QMessageBox::Yes){
			slot_saveActionActivated();
		}
	}
	saveSetup();
}

void QMediaBibliothek::resizeEvent(QResizeEvent * e){
int videowidth=this->width() / 2;
int videoheight = int ((double)videowidth / 1.5);

	e = e; // just to keep the compiler happy ....
	if ((videoheight * 2) > this->height()){
		videoheight = this->height() / 2;
		videowidth = (int)((double)videoheight * 1.5);
	}
	videoWidget->setGeometry(this->width()-videowidth-20,65,videowidth,videoheight);
	mainMenu->setGeometry(0,0,this->width(),25);
	toolBar->setGeometry(0,mainMenu->y()+mainMenu->height(),this->width(),30);
	mediaPlayerFrame->setGeometry(videoWidget->x()-10,videoWidget->y()-10,videoWidget->width()+20,videoWidget->height()+95);
	beginButton->setGeometry(mediaPlayerFrame->x()+5,mediaPlayerFrame->y()+mediaPlayerFrame->height()-30,40,25);
	rewindButton->setGeometry(beginButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	playButton->setGeometry(rewindButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	pauseButton->setGeometry(playButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	stopButton->setGeometry(pauseButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	ffButton->setGeometry(stopButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	endButton->setGeometry(ffButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	playFullScreenButton->setGeometry(endButton->x()+5+beginButton->width(),beginButton->y(),beginButton->width(),beginButton->height());
	progress->setGeometry(mediaPlayerFrame->x()+10,mediaPlayerFrame->y()+mediaPlayerFrame->height()-80,mediaPlayerFrame->width()-20,50);
	playTimeLabel->setGeometry(mediaPlayerFrame->x()+10,mediaPlayerFrame->y()+mediaPlayerFrame->height()-55,170,20);
	movieTable->setGeometry(5,mediaPlayerFrame->y() + 30,mediaPlayerFrame->x()-10,mediaPlayerFrame->height()-30);
	searchEditLabel->setGeometry(5,mediaPlayerFrame->y(),50,30);
	searchEdit->setGeometry(searchEditLabel->x()+searchEditLabel->width(),searchEditLabel->y(),movieTable->width()-210,searchEditLabel->height());
	submitButton->setGeometry(searchEdit->x()+searchEdit->width()+5,searchEdit->y(),searchEdit->height(),searchEdit->height());
	printButton->setGeometry(submitButton->x()+submitButton->width()+5,submitButton->y(),submitButton->width(),submitButton->height());
	hitLabel->setGeometry(printButton->x()+printButton->width()+5,printButton->y(),100,printButton->height());
	movieTable->setColumnWidth(0,(movieTable->width()-20)/6*4);
	movieTable->setColumnWidth(1,(movieTable->width()-20)/6);
	movieTable->setColumnWidth(2,(movieTable->width()-20)/6);
	
	inputFrame->setGeometry(10,mediaPlayerFrame->y()+mediaPlayerFrame->height()+10,this->width()-20,this->height()-mediaPlayerFrame->height()-90);
	filenameLabel->setGeometry(inputFrame->x()+5,inputFrame->y()+5,50,20);
	filenameEdit->setGeometry(filenameLabel->x()+filenameLabel->width()+5,filenameLabel->y(),movieTable->width()-filenameLabel->width()-50,25);
	fileSelectButton->setGeometry(filenameEdit->x()+filenameEdit->width()+5,filenameEdit->y(),30,25);
	titleLabel->setGeometry(filenameLabel->x(),filenameLabel->y()+filenameLabel->height()+5,filenameLabel->width(),filenameLabel->height());
	titleEdit->setGeometry(titleLabel->x()+titleLabel->width()+5,titleLabel->y(),filenameEdit->width(),filenameEdit->height());
	genreLabel->setGeometry(titleLabel->x(),titleLabel->y()+filenameLabel->height()+5,filenameLabel->width(),filenameLabel->height());
	genreComboBox->setGeometry(genreLabel->x()+genreLabel->width()+5,genreLabel->y(),filenameEdit->width(),filenameEdit->height());
	timeLabelLabel->setGeometry(genreLabel->x(),genreLabel->y()+genreLabel->height()+5,filenameLabel->width(),filenameLabel->height());
	timeLabel->setGeometry(timeLabelLabel->x()+timeLabelLabel->width()+5,timeLabelLabel->y(),100,timeLabelLabel->height());
	descriptionLabel->setGeometry(mediaPlayerFrame->x(),inputFrame->y()+5,80,30);
	lookupButton->setGeometry(titleEdit->x()+titleEdit->width()+5,titleEdit->y(),fileSelectButton->width(),fileSelectButton->height());
	commentEdit->setGeometry(mediaPlayerFrame->x(),inputFrame->y()+descriptionLabel->height()+5,mediaPlayerFrame->width()-5,this->inputFrame->height()-10-descriptionLabel->height());
	addButton->setGeometry(inputFrame->x()+5,inputFrame->y()+inputFrame->height()-45,(inputFrame->width()-20-commentEdit->width()) / 3,timeLabel->height()*2);
	delButton->setGeometry(addButton->x()+addButton->width()+5,addButton->y(),addButton->width(),addButton->height());
	modifyButton->setGeometry(delButton->x()+delButton->width()+5,delButton->y(),delButton->width(),delButton->height());
}


void QMediaBibliothek::slot_ffButtonClicked(){
qint64 position = mediaObject->currentTime();
	
	position+=10000;
	mediaObject->seek(position);
	pauseButton->setFocus();
}

void QMediaBibliothek::slot_rewindButtonClicked(){
qint64 position = mediaObject->currentTime();
	position-=10000;
	mediaObject->seek(position);
	pauseButton->setFocus();
}

void QMediaBibliothek::slot_tickInterval(qint64 value){
QString output;

	progress->setMinimum(0);
	progress->setMaximum(mediaObject->totalTime() / 1000);
	
	value = value / 1000.0;
	progress->setValue(value);
	output = calcPlayTime(value);
	
	value = mediaObject->totalTime();
	value = value / 1000.0;
	
	output = output + " / " + calcPlayTime(value);
	timeLabel->setText(calcPlayTime(value));
	
	playTimeLabel->setText(tr("Time : ")+output);
}


void QMediaBibliothek::slot_sliderMoved(int value){
long int position = value * 1000;
	mediaObject->seek(position);
}

void QMediaBibliothek::slot_beginButtonClicked(){
	mediaObject->seek(0);
}

void QMediaBibliothek::slot_endButtonClicked(){
qint64 position = mediaObject->totalTime();
	position-=1000;
	mediaObject->seek(position);
}

/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Die Movie Tabelle wird mit den Daten aus der 
                Datenbank befüllt.
 ****************************************************************/
void QMediaBibliothek::fillTableSelected(QString searchString,bool mode){
QString splitString;
QStringList entries = dataset.split("|");
QStringListIterator dataLine(entries);
QString line;
QStringList data;
QStringList header;
QString item;
int itCount,lineCount;
int tickCount=0;

QProgressDialog progress(tr("processing data ... please wait."), 0, 0, entries.count(), this);

	header << tr("Title") << tr("Genre") << tr("Time");
	movieTable->clear();
	movieTable->setRowCount(0);
	movieTable->setColumnCount(3);
	movieTable->setHorizontalHeaderLabels(header);
	movieTable->setColumnWidth(0,(movieTable->width()-20)/6*4);
	movieTable->setColumnWidth(1,(movieTable->width()-20)/6);
	movieTable->setColumnWidth(2,(movieTable->width()-20)/6);
	lineCount=0;
	if (mode){
		progress.setWindowModality(Qt::WindowModal);
		progress.setValue(1);
	} else {
		progress.setValue(0);
	}
	while (dataLine.hasNext()){
		line = dataLine.next();
		if (!(line.isNull()) && (line.contains(searchString,Qt::CaseInsensitive) == true)){
			movieTable->insertRow(lineCount);
			data = line.split("<");
			QStringListIterator dataIterator(data);
			itCount = 0;
			while (dataIterator.hasNext()){
				item = dataIterator.next();
				switch (itCount){
				case 1 : movieTable->setItem(lineCount,0,new QTableWidgetItem(item));
					break;
				case 2 : movieTable->setItem(lineCount,1,new QTableWidgetItem(item));
						 if (genreComboBox->findText(item) == -1) genreComboBox->addItem(item);
					break;
				case 3 : movieTable->setItem(lineCount,2,new QTableWidgetItem(item));
					break;
				}
 				itCount++;
			}
			lineCount++;
			if (mode){
				if (tickCount == 10){
					progress.setValue(lineCount);
					tickCount = 0;
				} else {
					tickCount++;
				}
				
			}
		}
	}
	if (mode) progress.setValue(entries.count());
	movieTable->sortItems(sortBy);
	hitLabel->setText(tr("Hit(s) : ") + QString::number(movieTable->rowCount()));
}

void QMediaBibliothek::slot_openActionActivated(){
QString filetemp = filename;
	if (filename.isNull()) filename = getenv("HOME");
	filename = QFileDialog::getOpenFileName(this, tr("Open File"),filename,tr("Movies Database (*.mdb)"));
	if(filename != ""){
		loadDatabase(filename);
		if (recentlyUsed.contains(filename) == false){
			recentlyUsed = filename + "\n" + recentlyUsed;
			rebuildRecentlyUsedMenu();
		}
	} else {
		filename=filetemp;
	}
}


void QMediaBibliothek::loadDatabase(QString filename){
QString line;
	if(filename != ""){
		QFile file (filename);
		dataset = "";
		if (file.open(QIODevice::ReadOnly|QIODevice::Text)){
			QTextStream stream(&file);
			line = stream.readLine();
			while (!line.isNull()){
				dataset = dataset + line; 
				line = stream.readLine();
				if (!line.isNull()) dataset = dataset + "\n";
			}
			statusBar()->showMessage(tr("File successfully loaded"),3000);
		} else {
			QMessageBox::information(this,tr("ERROR"),tr("File not found!"));
		}
		fillTableSelected(searchEdit->text(),true);
	}
	this->setWindowTitle((QString)"QMediaBibliothek - " + filename);
}

void QMediaBibliothek::slot_submitButtonClicked(){
  fillTableSelected(searchEdit->text(),false);
}

/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Einstellungen des Programms werden geladen
 ****************************************************************/
void QMediaBibliothek::setup(){
QString basePath2=basePath;
QFile file((QString)getenv("HOME")+"/.MediaBib/setup");
int lineCount=0;
QString line;
	if (file.open(QIODevice::ReadOnly|QIODevice::Text)){
		QTextStream stream(&file);
		while (!stream.atEnd()){
			line = stream.readLine();
			switch (lineCount){
			case 0  : basePath = line;
						break;
			case 1  : defaultDatabase = line;
						break;
			case 2  : defaultMediaPlayer = line;
						break;
			case 3	: webLookupSource = line;
					  for (int i=0;i<webLookupSources->count();i++){
						if (webLookupSources->itemText(i) == line){
						  webLookupSources->setCurrentIndex(i);
					  	}
					  }
						break;
			case 4	: defaultBrowser = line;
						break;
			case 5	: recentlyUsed = line;
					  recentlyUsed.replace("|","\n");
						break;
			}
			lineCount++;
		}
		file.close();
	}
  
QFile file2((QString)getenv("HOME")+"/.MediaBib/genre.txt");

	if (file2.open(QIODevice::ReadOnly|QIODevice::Text)){
		QTextStream stream2(&file2);
		genreComboBox->clear();
		while (!stream2.atEnd()){
			line = stream2.readLine();
			genreComboBox->addItem(line);
		}
		file2.close();
	}

QFile file3((QString)getenv("HOME")+"/bin/createmoviedb.sh");
QString content = "#/bin/bash\n#\n\ndirname=`dirname $0`;\n\nif [ $# == \"3\" ];\nthen\n    find \"$1\" -name '*.[am][vp][ig]' -exec $dirname/addmovie.sh '{}' $2 $3 ';'\nelse\n    echo \"Falsche Anzahl von Parametern\"\nfi";
QString command = "chmod 777 " + basePath2 + "/bin/createmoviedb.sh";

	file3.open(QIODevice::WriteOnly|QIODevice::Text);
	QTextStream stream3(&file3);
	stream3 << content << endl;
	file3.close();    
	file3.setPermissions(QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner|QFile::ReadUser|QFile::WriteUser|QFile::ExeUser|QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup|QFile::ReadOther|QFile::WriteOther|QFile::ExeOther);

QFile file4((QString)getenv("HOME")+"/bin/addmovie.sh");  
QString content2 = "#!/bin/bash\n# Erster Parameter ist der Dateiname des Films\n# Zweiter Parameter ist das Genre\n# Dritter Paramater ist die Moviedatenbank, die zu verwendenist.\n\n";
content2 = content2 + "time=`tcprobe -i \"$1\" 2>&1 | grep duration | cut -d \",\" -f 3 | cut -d \"=\" -f 2 | cut -c 1-7`\n";
content2 = content2 + "hour=`echo $time | cut -d \":\" -f 1`\nmin=`echo $time | cut -d \":\" -f 2`\nsec=`echo $time | cut -d \":\" -f 3`\n";
content2 = content2 + "if [ \"$hour\" -le \"9\" ];\nthen\n  hour=\"0\"$hour\nfi\ntime=\"$hour:$min:$sec\"\n";
content2 = content2 + "rc=`basename \"$1\"`\ntempname=`echo \"$rc\" | sed 's/_/ /g'`\ntempname2=`echo \"$tempname\" | sed 's/-/ /g'`\nmoviename=`echo \"$tempname2\" | cut -d \".\" -f 1`\ngenre=$2\nif [ \"$2\" = \"auto\" ];\nthen\n  genretemp=`dirname \"$1\"`\n  genre=`basename \"$genretemp\"`\nfi\nrc=`fgrep \"$1<\" $3`\n";
content2 = content2 + "if [ -z \"$rc\" ];\nthen\n    echo -n \"$1<$moviename<$genre<$time<##auto generated##|\" >> $3\n   echo $moviename\nfi\n";  
QString command2 = "chmod 777 " + basePath2 + "/bin/addmovie.sh";

	file4.open(QIODevice::WriteOnly|QIODevice::Text);
	QTextStream stream4(&file4);
	stream4 << content2 << endl;
	file4.close();    
	file4.setPermissions(QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner|QFile::ReadUser|QFile::WriteUser|QFile::ExeUser|QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup|QFile::ReadOther|QFile::WriteOther|QFile::ExeOther);
	
QStringList programs;
QStringList programNames;
QString missing;
programs << "/usr/bin/firefox" << "/usr/bin/opera" << "/usr/bin/konqueror" << "/usr/bin/mplayer" << "/usr/bin/vlc" << "/opt/kde3/bin/kaffeine" << "/usr/bin/xine" << "/usr/bin/tcprobe";
programNames << "Firefox" << "Opera" << "Konqueror" << "MPlayer" << "VLC" << "Kaffeine" << "XINE" << "TCProbe";
QStringListIterator programIterator(programs);
QStringListIterator programNameIterator(programNames);
QString program;
QString programName;

	while (programNameIterator.hasNext()){
		programName = programNameIterator.next();
		program = programIterator.next();
		if (!QFile::exists(program)){
			missing = missing + "\n- " + programName + "\t <-----> \t" + program;
		}
	}
	if (missing != ""){
		missing = (QString)"These programs are missing. Please install!\n-----------------------------------------------------------------" + missing + (QString)"\n-----------------------------------------------------------------";
		QMessageBox::information(this,tr("WARNING"),missing);
	}
}


/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Die Einstellungen für das Programm werden im 
                Home-Ordner des Nutzer abgespeichert.
 ****************************************************************/
void QMediaBibliothek::saveSetup(){
QString setupFilename = (QString)getenv("HOME") + (QString)"/.MediaBib/setup";
QFile file(setupFilename);
  if(file.open(QIODevice::WriteOnly|QIODevice::Text)){
    QTextStream stream(&file);
    recentlyUsed.replace("\n","|");
    stream << basePath << "\n" << defaultDatabase << "\n" << defaultMediaPlayer << "\n" << webLookupSource << "\n" << defaultBrowser << "\n" << recentlyUsed << "\n";
    file.close();
    file.flush();
  }
}


/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Der Button für Dateiauswahl eines Films wurde
                angeklickt. 
 ****************************************************************/
void QMediaBibliothek::slot_fileSelectButtonClicked(){
QString SplitString;
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),basePath,tr("Movies (*.avi *.mpeg *.mpg)"));
basePath = fileName.left(fileName.lastIndexOf("/"));

	if (fileName != ""){
		filenameEdit->setText(fileName);
		mediaObject->setCurrentSource(fileName);
		mediaObject->play();
	}

	fileName.remove(0,fileName.lastIndexOf("/")+1);
	fileName.remove(fileName.indexOf("."),5);
	fileName.replace("_"," ");
	fileName.replace("-"," ");
	titleEdit->setText(fileName);
}

QString QMediaBibliothek::calcPlayTime(long int value){
long int hour,minutes,seconds;
QString output;

	hour = value / (long int)3600;
	value = value - (hour * (long int)3600);
	minutes = value / (long int)60;
	seconds = value - (minutes * (long int)60);
	hour < 10?output="0"+QString::number(hour):output=QString::number(hour);
	output = output + ":";
	minutes < 10?output = output + "0"+QString::number(minutes):output = output + QString::number(minutes);
	output = output + ":";
	seconds < 10?output = output + "0"+QString::number(seconds):output = output + QString::number(seconds);
	return output;
}


/****************************************************************
 Parameter    : Index des doppelgeklickten Eintrags
 Rückgabewert : keiner
 Beschreibung : Ein Eintrag in der Movieliste wurde doppelgeklickt
                und der dazugehörige Datensatz wird in die Edit-
                felder geladen und der Film gestartet.
 ****************************************************************/
void QMediaBibliothek::slot_movieTableDoubleClicked(QModelIndex index){
QStringList entries = dataset.split("|");
QStringList data;
QStringListIterator dataLine(entries);
QString line;
QString temp;
int count=0;
int found=0;
QString comboEntry;
QString compString;

	compString = movieTable->item(index.row(),0)->text() + "<" + movieTable->item(index.row(),1)->text() + "<" + movieTable->item(index.row(),2)->text();
	while ((dataLine.hasNext()) && (line == "")){
		temp = dataLine.next();
		if (temp.contains(compString) == true){
			line = temp;
			oldDataSet = temp + "|";
		}
		count++;
	}
	if (line != ""){
		data = line.split("<");
		QStringListIterator dataIterator(data);
		filenameEdit->setText(dataIterator.next());
		titleEdit->setText(dataIterator.next());
		comboEntry=dataIterator.next();

		for (int i=0;i<genreComboBox->count();i++){
			if (genreComboBox->itemText(i) == comboEntry){
					genreComboBox->setCurrentIndex(i);
			found=1;
			}
		}
		if (found==0){
			genreComboBox->addItem(comboEntry);
			genreComboBox->setCurrentIndex(genreComboBox->count()-1);
		}
		timeLabel->setText(dataIterator.next());
		commentEdit->setPlainText(dataIterator.next());

		mediaObject->setCurrentSource(filenameEdit->text());
		mediaObject->play();
		pauseButton->setFocus();

	}
}


/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Mit den in der Eingabemaske eingegebenen Werten
                wird ein neuer Datensatz angelegt.
 ****************************************************************/
void QMediaBibliothek::slot_addButtonClicked(){
QString unique;
QString Entry;

	if (titleEdit->text() != "") {
		Entry = filenameEdit->text() + "<" + titleEdit->text() + "<" + genreComboBox->currentText() + "<" + timeLabel->text() + "<" + commentEdit->toPlainText() + "|";
		unique = titleEdit->text() + "<" + genreComboBox->currentText() + "<" + timeLabel->text();
		if (dataset.contains(unique) == false){
			dataset = dataset + Entry;
			filenameEdit->setText("");
			titleEdit->setText("");
			timeLabel->setText("00:00:00");
			commentEdit->setPlainText("");
			statusBar()->showMessage(tr("New Entry added"),3000);
			fillTableSelected(searchEdit->text(),false);
			if (dataModified == false) {
				this->setWindowTitle(this->windowTitle() + (QString)tr(" (unsaved)"));
			}
			dataModified = true;
		} else {
			QMessageBox::information(this,tr("ERROR"),tr("The entry \"") + titleEdit->text() +  tr("\" already exists!"));
		}
	} else {
		QMessageBox::information(this,tr("WARNING"),tr("There is no movie to add"));
	}
}


/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Der aktuelle Datensatz wird mit den geänderten 
                Daten überschrieben.
 ****************************************************************/
void QMediaBibliothek::slot_modifyButtonClicked(){
QString Entry;
	if (titleEdit->text() != ""){
		Entry = filenameEdit->text() + "<" + titleEdit->text() + "<" + genreComboBox->currentText() + "<" + timeLabel->text() + "<" + commentEdit->toPlainText() + "|";
		if (!oldDataSet.isNull()){
			dataset.replace(oldDataSet,Entry);
			oldDataSet="";
		} else {
			slot_addButtonClicked();
		}
		filenameEdit->setText("");
		titleEdit->setText("");
		genreComboBox->setCurrentIndex(0);
		timeLabel->setText("00:00:00");
		commentEdit->setPlainText("");
		statusBar()->showMessage(tr("Entry modified"),3000);
		if (dataModified == false) {
			this->setWindowTitle(this->windowTitle() + (QString)tr(" (unsaved)"));
		}
		dataModified = true;
		fillTableSelected(searchEdit->text(),false);
	} else {
		QMessageBox::information(this,tr("WARNING"),tr("Please select a movie first"));
	}
}

/****************************************************************
Parameter    : keine
Rückgabewert : keiner
Beschreibung : Der aktuell Datensatz wird aus der Datenbank ent-
               fernt und die Tabelle neu aufgebaut.
****************************************************************/
void QMediaBibliothek::slot_delButtonClicked(){
QStringList entries = dataset.split("|");
QStringListIterator dataLine(entries);
QString line;
QString temp;

	if (movieTable->currentRow() != -1){
		QString compString = (QString)movieTable->item(movieTable->currentRow(),0)->text() + "<" + (QString)movieTable->item(movieTable->currentRow(),1)->text() + "<" + (QString)movieTable->item(movieTable->currentRow(),2)->text();
		while ((dataLine.hasNext()) && (line == "")){
			temp = dataLine.next();
			if (temp.contains(compString) == true){
				line = temp;
				oldDataSet = line + "|";
			}
		}
		QString message = tr("Delete Entry : \n---------------------------------------------\n") + movieTable->item(movieTable->currentRow(),0)->text() + "\n" + movieTable->item(movieTable->currentRow(),1)->text() + "\n" + movieTable->item(movieTable->currentRow(),2)->text()  + tr("\n---------------------------------\n Are you sure?");
		int rc = QMessageBox::question(this,tr("WARINING"),message,QMessageBox::Yes,QMessageBox::No);
		if (rc == QMessageBox::Yes){
			dataset.replace(oldDataSet,"");
			dataModified = true;
			fillTableSelected(searchEdit->text(),true);
		}
	} else {
		QMessageBox::information(this,tr("WARNING"),"Please select a movie first!");
	}
}


/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Der Menupunkt File - Save wurde ausgewählt. 
                Hiermit wird die aktuelle Datenbank gesichert.
 ****************************************************************/
void QMediaBibliothek::slot_saveActionActivated(){
	if (filename.isNull()) filename=basePath;
	QString filetemp=filename;
	if (filename == "") filename=QFileDialog::getSaveFileName(this, tr("Save File"),filename,tr("Movies Database (*.mdb)"));
	if (!filename.isNull()){
		QFile file(filename);
		if (file.open(QIODevice::WriteOnly|QIODevice::Text)){
			QTextStream stream(&file);
			stream << dataset;
			file.close();
			statusBar()->showMessage(tr("File successfully saved"),3000);
			dataModified = false;
			this->setWindowTitle((QString)"QMediaBibliothek - " + filename);
		}
	} else {
		filename=filetemp;
	}
}

/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Der Menupunkt File - Save wurde ausgewählt. 
                Hiermit wird die aktuelle Datenbank gesichert.
 ****************************************************************/
void QMediaBibliothek::slot_saveAsActionActivated(){
bool doit = true;
	if (filename.isNull()) filename=basePath;
	QString filetemp=filename;
	filename=QFileDialog::getSaveFileName(this, tr("Save File"),filename,tr("Movies Database (*.mdb)"));
	if (!filename.isNull()){
		if (QFile::exists(filename)){
			int rc = QMessageBox::information(this,tr("WARNING"),tr("File already exists. Do you want to overwrite it."),QMessageBox::Yes,QMessageBox::No);
			if (rc == QMessageBox::No) doit = false;
		}
		if (doit){
			QFile file(filename);
			if (file.open(QIODevice::WriteOnly|QIODevice::Text)){
				QTextStream stream(&file);
				stream << dataset;
				file.close();
				statusBar()->showMessage(tr("File successfully saved"),3000);
				dataModified = false;
				this->setWindowTitle((QString)"QMediaBibliothek - " + filename);
			}
		}
	} else {
		filename=filetemp;
	}
}



/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Der Button für das Abspielen im Vollbildmodus wurde
 				geklickt. 
 ****************************************************************/
void QMediaBibliothek::slot_playFullScreenButtonClicked(){
QStringList param;	
	if (defaultMediaPlayer == "MPlayer"){
		if (!filenameEdit->text().isNull()){
			mediaObject->stop();  
			param << "-fs" << "-volume" << "100" << filenameEdit->text();
			QProcess::execute("mplayer",param);
		}
	}
	if (defaultMediaPlayer == "VLC Player"){
		if (!filenameEdit->text().isNull()){
			mediaObject->stop();  
			param << "-f" << "--volume" << "1024" << filenameEdit->text();
			QProcess::execute("vlc",param);
		}
	}
	if (defaultMediaPlayer == "Kaffeine Player"){
		if (!filenameEdit->text().isNull()){
			mediaObject->stop();  
			param << "-f" << filenameEdit->text();
			QProcess::execute("kaffeine",param);
		}
	}
		if (defaultMediaPlayer == "XINE Player"){
		if (!filenameEdit->text().isNull()){
			mediaObject->stop();  
			param << "-f" << filenameEdit->text();
			QProcess::execute("xine",param);
		}
	}
}

void QMediaBibliothek::slot_actionOrderByTitleActivated(){
	sortBy = 0;
	fillTableSelected(searchEdit->text(),false);
}

void QMediaBibliothek::slot_actionOrderByGenreActivated(){
	sortBy = 1;
	fillTableSelected(searchEdit->text(),false);
}

void QMediaBibliothek::slot_actionOrderByTimeActivated(){
	sortBy = 2;
	fillTableSelected(searchEdit->text(),false);
}

void QMediaBibliothek::slot_actionGenreSetupActivated(){
genreSetup * GenreSetup = new genreSetup();
	GenreSetup->exec();
	
QString basePath = (QString)getenv("HOME")+(QString)"/.MediaBib/genre.txt";
QFile file(basePath);
QString line;

	if (file.open(QIODevice::ReadOnly|QIODevice::Text)){
		QTextStream stream(&file);
		genreComboBox->clear();
		while (!stream.atEnd()){
			line = stream.readLine();
			genreComboBox->addItem(line);
		}
		file.close();
	}
}

/****************************************************************
 Parameter    : keine
 Rückgabewert : keiner
 Beschreibung : Durchsucht ein Unterverzeichnis nach Filmdateien
                und trägt die gefundenen Filme ein.
 ****************************************************************/
void QMediaBibliothek::slot_actionMultiAddMoviesActivated(){
	if (dataModified == false){
		multiAddDialog * dialog = new multiAddDialog(this,0,filename);
		if (!filename.isNull()){
			dialog->exec();
			QFile file (filename);
			QString line;
			dataset = "";
			statusBar()->showMessage(tr("Reloading database"),3000);
			if (file.open(QIODevice::ReadOnly|QIODevice::Text)){
				QTextStream stream(&file);
				line = stream.readLine();
				while (!line.isNull()){
					dataset = dataset + line; 
					line = stream.readLine();
					if (!line.isNull()) dataset = dataset + "\n";
				}
				statusBar()->showMessage(tr("Database successfully loaded"),3000);
			}
			fillTableSelected(searchEdit->text(),true);
		} else {
			QMessageBox::information(this,tr("WARNING"),tr("please select or create a database first"));
		}
	} else {
		QMessageBox::information(this,tr("WARNING"),tr("Modified and unsaved data found. Please save database first!"));
	}
}

void QMediaBibliothek::slot_actionSetupActivated(){
setupDialog * dialog = new setupDialog((QDialog *)this,0);
	saveSetup();
	dialog->exec();
	setup();
}

void QMediaBibliothek::slot_actionNewDatabaseActivated(){
	dataset = "";
	dataModified = false;
	filename = "";
	fillTableSelected("",false);
}

void QMediaBibliothek::slot_lookupButtonClicked(){
QString param;
QString searchString;
QStringList parameter;
QString browser;
QProcess  * process = new QProcess(this);
QString webLookupSource = webLookupSources->itemText(webLookupSources->currentIndex());

	if (titleEdit->text() != ""){
		if (defaultBrowser == "Firefox") browser = "firefox";
		if (defaultBrowser == "Opera") browser = "opera";
		if (defaultBrowser == "Dolphin") browser = "dolphin";
		if (defaultBrowser == "Konqueror") browser = "konqueror";
	
		if (webLookupSource == "IMDB (www.imdb.com)"){
			param = "http://www.imdb.com/find?s=all&q=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString + "&x=0&y=0";
			parameter << param;
			process->start(browser,parameter);
		}
		if (webLookupSource == "IMDB (www.imdb.de)"){
			param = "http://www.imdb.de/find?s=all&q=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString + "&x=0&y=0";
			parameter << param;
			process->start(browser,parameter);
		}
		if (webLookupSource == "Wikipedia (de.wikipedia.org)"){
			param = "http://de.wikipedia.org/w/index.php?title=Spezial%3ASuche&search=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString + "&go=Artikel";
			parameter << param;
			process->start(browser,parameter);
		}
		if (webLookupSource == "FilmDB (www.filmdb.de)"){
			param = "http://www.filmdb.de/globalsuche.php?name=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString;
			parameter << param;
			process->start(browser,parameter);
		}
		if (webLookupSource == "Yahoo Movie DB (de.movies.yahoo.com)"){
			param = "http://de.movies.yahoo.com/suchergebnisse.html?p=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString;
			parameter << param;
			process->start(browser,parameter);
		}
		if (webLookupSource == "Cineasten (www.cineasten.de)"){
			param = "http://www.cineasten.de/suche/?q=";
			searchString = titleEdit->text();
			searchString.replace(" ","+");
			param = param + searchString + "&x=0&y=0";
			parameter << param;
			process->start(browser,parameter);
		}
	} else {
		QMessageBox::information(this,tr("WARNING"),tr("select a movie first"));
	}
}

void QMediaBibliothek::slot_orderByComboBoxActivated(int index){
	switch (index){
	case 0	:	slot_actionOrderByTitleActivated();
					break;
	case 1	:	slot_actionOrderByGenreActivated();
					break;
	case 2	:	slot_actionOrderByTimeActivated();
					break;
	}
}

void QMediaBibliothek::slot_aboutQt(){
	QMessageBox::aboutQt(this,tr("About Qt"));
}

void QMediaBibliothek::slot_aboutMediaBibliothek(){
QString message = "<b><font style='font-size:28px;font-style:italic' align=left>QMediaBibliothek</font></b><br>"+version;
		message = message + "<font size=3><p style='text-align:justify'>QMediaBibliothek is published under the GPL 2.0 or<br>";
		message = message + "any newer version. Feel free to change the program so<br> it meets your";
		message = message + " requirements.</p>You can find more programms at<br><br><a href='www.linux-specialist.com'>";
		message = message + "www.linux-specialist.com</a><br><br>Bug reports can be send to<br><br><a href='mailto:info@linux-specialsit.com'>info@linux-specialist.com</a>";
		
	QMessageBox::about(this,"About MediaBibliothek",message);
}


void QMediaBibliothek::slot_playButtonClicked(){
	mediaObject->play();
	pauseButton->setFocus();
}

void QMediaBibliothek::slot_pauseButtonClicked(){
	mediaObject->pause();
	playButton->setFocus();
}

void QMediaBibliothek::rebuildRecentlyUsedMenu(){
QString menuLine;
QString workString=recentlyUsed;
QString newRecentlyUsed;
int index=0;
int pos;

	recentlyUsedMenu->clear();
	
	if (workString != ""){
		while (workString.contains("\n")){
			pos = workString.indexOf("\n");
			menuLine = workString.mid(0,pos);
			if (index < 5) newRecentlyUsed = newRecentlyUsed + menuLine + "\n";
			index++;
			workString = workString.mid(pos+1);
			switch (index){
			case 1 : actionRecentlyUsed1->setText(menuLine);
					 recentlyUsedMenu->addAction(actionRecentlyUsed1);
					 	break;
			case 2 : actionRecentlyUsed2->setText(menuLine);
					 recentlyUsedMenu->addAction(actionRecentlyUsed2);
					 	break;
			case 3 : actionRecentlyUsed3->setText(menuLine);
					 recentlyUsedMenu->addAction(actionRecentlyUsed3);
					 	break;
			case 4 : actionRecentlyUsed4->setText(menuLine);
					 recentlyUsedMenu->addAction(actionRecentlyUsed4);
					 	break;
			case 5 : actionRecentlyUsed5->setText(menuLine);
					 recentlyUsedMenu->addAction(actionRecentlyUsed5);
					 	break;
			}
		}
		recentlyUsed = newRecentlyUsed;
	}
}


void QMediaBibliothek::slot_actionRecentlyUsed1Activated(){
	filename = actionRecentlyUsed1->text();
	loadDatabase(actionRecentlyUsed1->text());
}

void QMediaBibliothek::slot_actionRecentlyUsed2Activated(){
	filename = actionRecentlyUsed2->text();
	loadDatabase(actionRecentlyUsed2->text());
}

void QMediaBibliothek::slot_actionRecentlyUsed3Activated(){
	filename = actionRecentlyUsed3->text();
	loadDatabase(actionRecentlyUsed3->text());
}

void QMediaBibliothek::slot_actionRecentlyUsed4Activated(){
	filename = actionRecentlyUsed4->text();
	loadDatabase(actionRecentlyUsed4->text());
}

void QMediaBibliothek::slot_actionRecentlyUsed5Activated(){
	filename = actionRecentlyUsed5->text();
	loadDatabase(actionRecentlyUsed5->text());
}

void QMediaBibliothek::slot_consistencyCheckActivated(){
QString splitString;
QStringList entries = dataset.split("|");
QStringListIterator dataLine(entries);
QString line;
QStringList data;
QString item;
int itCount,rc;
bool skip = false;
int lineCount = 1;
int maxValue=entries.count();
	QProgressDialog progress(tr("checking consistency .... please wait."), 0, 0, maxValue, this);
	while ((dataLine.hasNext()) && (skip == false)){
		progress.setWindowModality(Qt::WindowModal);
		progress.setValue(lineCount);
		line = dataLine.next();
		if (!(line.isNull())){
			data = line.split("<");
			QStringListIterator dataIterator(data);
			itCount = 0;
			while (dataIterator.hasNext()){
				item = dataIterator.next();
				switch (itCount){
				case 0 : if (QFile::exists(item) == false){
							rc = QMessageBox::information(this,tr("INFO"),tr("The File \n------------------------------------------\n>>> ") + item + tr(" <<<\n------------------------------------------\ndoes not exist!\n\nShall I remove the entry?"),QMessageBox::Yes,QMessageBox::No,QMessageBox::Cancel);
							switch (rc){
							case QMessageBox::Yes 		: dataset.replace(line + (QString)"|","");
														  if (dataModified == false) {
															this->setWindowTitle(this->windowTitle() + (QString)tr(" (unsaved)"));
														  }
														  dataModified = true;
																break;
							case QMessageBox::Cancel	: skip = true;
														  QMessageBox::information(this,("INFO"),tr("process terminated by the user!"));
														  progress.setValue(0);
																break;
							}
						 }
					break;
				}
 				itCount++;
			}
		}
		lineCount++;
		progress.setValue(lineCount);
	}
	fillTableSelected(searchEdit->text(),false);
}

void QMediaBibliothek::slot_actionHelpActivated(){
QString command="";
	if (defaultBrowser == "Firefox") command = "firefox /usr/share/doc/qmediabibliothek/index.html";
	if (defaultBrowser == "Opera") command = "opera /usr/share/doc/qmediabibliothek/index.html";
	if (defaultBrowser == "Konqueror") command = "konqueror file:///usr/share/doc/qmediabibliothek/index.html";
	if (defaultBrowser == "Dolphin") command = "dolphin file:///usr/share/doc/qmediabibliothek/index.html"; 
	if (command != "") QProcess::execute(command);
}


void QMediaBibliothek::slot_copyActionActivated(){
QString destPath;
QString filename;
bool ok;
	if (filenameEdit->text() != ""){
		filename = filenameEdit->text().mid(filenameEdit->text().lastIndexOf("/"));
		destPath = QFileDialog::getExistingDirectory(this,tr("Destination Folder"),basePath);
		if (destPath != ""){
			basePath = destPath;
			copydialog * cpdialog = new copydialog(0,filenameEdit->text(),destPath+filename,&ok);
			cpdialog->exec();
			if (ok){
				QMessageBox::information(this,tr("INFO"),"Copy procedure finished!");
			} else {
				QMessageBox::information(this,tr("INFO"),"An error occured while copying files.");
			}
		}
	}
}

void QMediaBibliothek::slot_printButtonClicked(){
QPrinter * printer = new QPrinter();
printer->setColorMode(QPrinter::Color);
printer->setResolution(85);
int yinc = 15;
int ypos = 15;
int linecount = 0;
int x1 = 5;
int x2 = 410;
int x3 = 530;

QPrintDialog dlg(printer,0);

    if((movieTable->rowCount() > 0) && (dlg.exec() == QDialog::Accepted)){
      QPainter * printerDevice = new QPainter(printer);
      printerDevice->setPen(QPen(Qt::black,1,Qt::SolidLine));
      printerDevice->setBrush(QColor("#e0e0e0"));
      printerDevice->drawRect(0,0,620,18);
      printerDevice->setBrush(Qt::NoBrush);
      printerDevice->setFont(QFont("Helvetic",10,QFont::Normal,false));
      printerDevice->drawText(x1,ypos,tr("Titel"));
      printerDevice->drawText(x2,ypos,tr("Genre"));
      printerDevice->drawText(x3,ypos,tr("Zeit"));
      printerDevice->drawLine(x2-5,0,x2-5,20);
      printerDevice->drawLine(x3-5,0,x3-5,20);
      printerDevice->drawLine(620,ypos,620,ypos-yinc);
      
      ypos = 20;
      for(int i=0;i<movieTable->rowCount();i++){
        ypos += yinc;
        printerDevice->drawText(x1,ypos-2,movieTable->item(i,0)->text());
        printerDevice->drawText(x2,ypos-2,movieTable->item(i,1)->text());
        printerDevice->drawText(x3,ypos-2,movieTable->item(i,2)->text());
        printerDevice->drawLine(x1-5,ypos,x1-5,ypos-yinc);
        printerDevice->drawLine(x2-5,ypos,x2-5,ypos-yinc);
        printerDevice->drawLine(x3-5,ypos,x3-5,ypos-yinc);
        printerDevice->drawLine(620,ypos,620,ypos-yinc);
        printerDevice->drawLine(0,ypos,620,ypos);
        linecount++;
        if (linecount == 62){
          printer->newPage();
          linecount = 0;
          ypos = 15;
          printerDevice->setPen(QPen(QColor(Qt::black),1,Qt::SolidLine));
          printerDevice->setBrush(QColor("#e0e0e0"));
          printerDevice->drawRect(0,0,620,18);
          printerDevice->setBrush(Qt::NoBrush);
          printerDevice->setFont(QFont("Helvetic",10,QFont::Normal,false));
          printerDevice->drawText(x1,ypos,tr("Titel"));
          printerDevice->drawText(x2,ypos,tr("Genre"));
          printerDevice->drawText(x3,ypos,tr("Zeit"));
          printerDevice->drawLine(x1-5,0,x1-5,20);
          printerDevice->drawLine(x2-5,0,x2-5,20);
          printerDevice->drawLine(x3-5,0,x3-5,20);
          ypos = 20;
        }
      }
      printerDevice->end();
    }
}
//

