/****************************************************************************
** DialogMovie class
**
** Created: Wed March 16 22:48:00 2005
**      by: Varol Okan using Kate
**
**
****************************************************************************/
#include <qlabel.h>
#include <qimage.h>
#include <qtimer.h>
#include <qregexp.h>
#include <qpixmap.h>
#include <qlayout.h>
#include <qlistbox.h>
#include <qspinbox.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qdatetime.h>
#include <qcheckbox.h>
#include <qfileinfo.h>
#include <qgroupbox.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qcolordialog.h>

#ifndef QPLAYER_ONLY
#include "dvdmenu.h"
#include "qdvdauthor.h"
#endif
#include "qplayer/mediainfo.h"
#include "qplayer/mediacreator.h"
#include "qplayer/startstopcontrol.h"
#include "qplayer/engines/mediainterface.h"

#include "messagebox.h"
#include "movieobject.h"
#include "dialogmovie.h"
#include "dialoganimation.h"
#include "dialogmediainfo.h"

#define PROPERTIES_TAB  0
#define CHAPTERS_TAB    1
#define GEOMETRY_TAB    2
#define TRANSCODING_TAB 3

#define COLOR_TRANSCODE   238,  33,  43
#define COLOR_NOTRANSCODE 209, 226, 238

ListViewColorItem::ListViewColorItem (QListView *parent, QColor theColor, QString l1, QString l2, QString l3, QString l4, QString l5, QString l6, QString l7, QString l8)
        : QListViewItem (parent, l1, l2, l3, l4, l5, l6, l7, l8)
{
	m_theColor = theColor;
}

void ListViewColorItem::paintCell ( QPainter *p, const QColorGroup & cg, int column, int width, int align)
{
	QColorGroup theColors = cg;
	if (isSelected())       {
		theColors.setColor(QColorGroup::Base, theColors.highlight() );
		theColors.setColor(QColorGroup::Text, theColors.highlightedText() );
	}
	else
		theColors.setColor(QColorGroup::Base, m_theColor);
	QListViewItem::paintCell(p, theColors, column, width, align);
}

DialogMovie::DialogMovie(QWidget * parent, const char * name, WFlags f)
	: uiDialogMovie (parent, name, f)
{
	m_pMediaInterface   = NULL;
	m_pStartStopControl = NULL;
	m_pTranscodeTab     = NULL;
	m_pMovieObject      = NULL;
	m_iMovieLength      =    1;// 1ms default, so we never have 0
	m_pDVDMenu          = NULL;
	connect (m_pEditWidth,       SIGNAL(lostFocus ()), this, SLOT (slotWidth          ()));
	connect (m_pEditHeight,      SIGNAL(lostFocus ()), this, SLOT (slotHeight         ()));
	connect (m_pButtonPlay,      SIGNAL(clicked   ()), this, SLOT (slotPlay           ()));
	connect (m_pButtonStop,      SIGNAL(clicked   ()), this, SLOT (slotStop           ()));
	connect (m_pButtonStart,     SIGNAL(clicked   ()), this, SLOT (slotStart          ()));
	connect (m_pButtonEnd,       SIGNAL(clicked   ()), this, SLOT (slotEnd            ()));
	connect (m_pButtonThumbnail, SIGNAL(clicked   ()), this, SLOT (slotSetThumbnail   ()));
	connect (m_pButtonTranscode, SIGNAL(clicked   ()), this, SLOT (slotTranscode      ()));
	connect (m_pButtonEncodeNow, SIGNAL(clicked   ()), this, SLOT (slotEncodeNow      ()));
	connect (m_pButtonAnimation, SIGNAL(clicked   ()), this, SLOT (slotAnimation      ()));
	connect (m_pButtonAddCK,     SIGNAL(clicked   ()), this, SLOT (slotAddColorKey    ()));
	connect (m_pButtonDelCK,     SIGNAL(clicked   ()), this, SLOT (slotDelColorKey    ()));
	connect (m_pButtonCK,        SIGNAL(clicked   ()), this, SLOT (slotBrowseColorKey ()));
	connect (m_pButtonEdit,      SIGNAL(clicked   ()), this, SLOT (slotEditMediaInfo  ()));
}

DialogMovie::~DialogMovie()
{
	delete m_pMediaInterface;
	delete m_pStartStopControl;
}

void DialogMovie::initMe(DVDMenu *pMenu)
{
	// Called when handling the background of a menu (Image background or MovieBackground.)
	if (!pMenu)
		return;
	if ( (pMenu->getInterface()->qsMovieFileName.isNull()) && (pMenu->getInterface()->qsBackgroundFileName.isNull()) )
		return;

	QFileInfo fileInfo;
	QString qsFormat, qsBackgroundName;

	m_pDVDMenu = pMenu;
	qsFormat = QString ("hh:mm:ss.zzz");
	QTime endingTime = pMenu->getInterface()->timeOffset.addMSecs(-pMenu->getInterface()->timeDuration.msecsTo(QTime()));
	m_pEditStarting2->setText (pMenu->getInterface()->timeOffset.toString(qsFormat));
	m_pEditEnding2  ->setText (endingTime.toString (qsFormat));

	// Okay coming from the MovieObject we need only the Geometry - tab
	QWidget *pTab = m_pTabWidget->page (TRANSCODING_TAB);
	m_pTabWidget->removePage (pTab);
	delete pTab;
	pTab = m_pTabWidget->page (CHAPTERS_TAB);
	m_pTabWidget->removePage (pTab);
	delete pTab;
	// Also no transcoding buttons will be needed.
	delete m_pButtonTranscode;
	delete m_pButtonEncodeNow;
	m_pButtonTranscode = NULL;
	m_pButtonEncodeNow = NULL;
	// Here we trick the object in accepting the right QLineEdits
	m_pEditStarting1 = m_pEditStarting2;
	m_pEditEnding1   = m_pEditEnding2;

	pTab = m_pTabWidget->page ( GEOMETRY_TAB );

	// The following lines will display the [Change Size ...] button.
	QSizePolicy policy (QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	delete textLabel4;
	delete m_pListViewCK;
	delete m_pButtonAddCK;
	delete m_pButtonDelCK;
	delete m_pEditCK;
	delete textLabel3_3;
	delete textLabel2_2;
	m_pButtonCK->setText (tr("Change Size ..."));
	m_pButtonCK->setSizePolicy ( policy );
	disconnect ( m_pButtonCK, SIGNAL(clicked ()), this, SLOT (slotBrowseColorKey ()) );
	connect    ( m_pButtonCK, SIGNAL(clicked ()), this, SLOT ( slotSizeDialog ()) );
	groupBox8->setTitle ("");

	// Here we handle a MovieBackground ...
	if ( ! pMenu->getInterface()->qsMovieFileName.isEmpty() ) 	{
		initMediaInterface (pMenu);
		m_pTabWidget->setTabLabel (pTab, "MovieBackground");
		m_pTabWidget->setCurrentPage ( 1 );
	}
	else	{	// Here we handle a ImageBackground ...
		if ( ! pMenu->getInterface()->qsBackgroundFileName.isEmpty ())	{
			QPixmap thePixmap;
			QImage theImage ( pMenu->getInterface()->qsBackgroundFileName );
			theImage = theImage.smoothScale (275, 275, QImage::ScaleFree);
			thePixmap.convertFromImage (theImage);
			m_pMediaPreview->setPixmap (thePixmap);
		}
		m_pMediaPreview->setFixedSize (275, 275);
		m_pEditStarting2  ->setEnabled  ( false );
		fileInfo.setFile ( pMenu->getInterface()->qsBackgroundFileName );
		m_pTextTitle->setText (tr ("ImageBackground : %1").arg(fileInfo.fileName()));
		setCaption ( fileInfo.fileName () );
		m_pTabWidget->setTabLabel (pTab, "ImageBackground");
		// And finally we hide the play buttons etc.
		delete m_pButtonPlay;
		delete m_pButtonStop;
		delete m_pButtonThumbnail;
		delete m_pButtonStart;
		delete m_pButtonEnd;
		delete m_pSliderVolume;
		delete m_pLabelCurrentPos;
		delete m_pFrameControl;
	}
	// These controls are not used ...
	delete groupBox2;
	resize (400, 300);		
}

void DialogMovie::initMe(SourceFileEntry *pSourceFileEntry)
{
	if (!pSourceFileEntry)
		return;

	m_sourceFileInfo   = *pSourceFileEntry->listFileInfos[0];
	QFileInfo fileInfo;
	QString qsFormat, qsBackgroundName;

	// Okay coming from transcodeAll ...
	//	QWidget *pTabProp = m_pTabWidget->page (PROPERTIES_TAB);
	QWidget *pTabChap = m_pTabWidget->page (CHAPTERS_TAB);
	QWidget *pTabGeom = m_pTabWidget->page (GEOMETRY_TAB);
	//	m_pTabWidget->removePage (pTabProp);
	//	delete pTabProp;
	m_pTabWidget->removePage (pTabChap);
	delete pTabChap;
	m_pTabWidget->removePage (pTabGeom);
	delete pTabGeom;
	// Also no transcoding buttons will be needed.
	delete m_pButtonTranscode;
	delete m_pButtonEncodeNow;
	delete m_pGroupCurrentFormat;
	m_pButtonTranscode = NULL;
	m_pButtonEncodeNow = NULL;
	m_pEditStarting1   = NULL;
	m_pEditEnding1     = NULL;
	m_pComboPreCommand->setCurrentText  ( pSourceFileEntry->qsPre  );
	m_pComboPostCommand->setCurrentText ( pSourceFileEntry->qsPost );

	setCaption ( "Transcoding all files of the SourceFileEntry" );
	m_pTextTitle->setText (tr ("SourceFileEntry : %1 Files").arg(pSourceFileEntry->listFileInfos.count()));
	// And finally we hide the play buttons etc.
	delete m_pMediaPreview;
	delete m_pButtonPlay;
	delete m_pButtonStop;
	delete m_pButtonThumbnail;
	delete m_pButtonStart;
	delete m_pButtonEnd;
	delete m_pSliderVolume;
	delete m_pLabelCurrentPos;
	delete m_pFrameControl;

	connect (m_pComboVideoOut,        SIGNAL( activated(const QString &)), this, SLOT (slotVideoOutChanged(const QString &)));
	connect (m_pComboVideoResolution, SIGNAL( activated(const QString &)), this, SLOT (slotVideoResolutionChanged(const QString &)));
	connect (m_pComboVideoRate,       SIGNAL( activated(const QString &)), this, SLOT (slotVideoRateChanged(const QString &)));
	connect (m_pComboVideoType,       SIGNAL( activated(const QString &)), this, SLOT (slotVideoTypeChanged(const QString &)));
	connect (m_pComboVideoAspect,     SIGNAL( activated(const QString &)), this, SLOT (slotVideoAspectChanged(const QString &)));
	connect (m_pComboVideoBitrate,    SIGNAL( activated(const QString &)), this, SLOT (slotVideoBitrateChanged(const QString &)));
	resize (300, 250);
}

void DialogMovie::initMe(SourceFileInfo *pInfo, const void *pExistingMediaEngine, int iThumbnailSize)
{
	Utils theUtil;
	if (!pInfo)
		return;

	// Okay coming from the SourceToolbar we do not need the Geometry - tab
	QWidget *pGeometry  = m_pTabWidget->page (GEOMETRY_TAB);
	m_pTranscodeTab = m_pTabWidget->page (TRANSCODING_TAB);
	m_pTabWidget->removePage (pGeometry);
	m_pTabWidget->removePage (m_pTranscodeTab);
	delete pGeometry;
	// we keep the Transcode widget around in case the user wants to transcode the file.

	// And next we init the chapters - tab
	int iLength = theUtil.getMsFromString(pInfo->qsLength);
	// Check if the default 5 minutes chapter creation is out of range anyways ...
	QString qsReturn = theUtil.getStringFromMs (iLength);
	if (iLength < 5*60*1000)	{
		m_pEditEvery->setText (QString ("%1").arg((int)(iLength/1000)));
		m_pEditAdd->setText (qsReturn);
	}
	m_pEditEnding1->setText(qsReturn);

	// Here we copy the infos over ...
	m_sourceFileInfo = *pInfo;
	QFileInfo fileInfo(m_sourceFileInfo.qsFileName);

	// and now on to initializing the dialog. Length : 00:07:23.123 File : Cool Video.mpg
	m_pTextTitle->setText (tr ("Length : <%1> File : %2").arg(qsReturn).arg(fileInfo.fileName()));
	setCaption (fileInfo.fileName ());

	m_pListBoxChapters->clear ();
	if (m_sourceFileInfo.listChapters.count() == 0)
		m_pListBoxChapters->insertItem (QString ("00:00:00.000"));
	m_pListBoxChapters->insertStringList   (m_sourceFileInfo.listChapters);
	m_pListBoxChapters->setCurrentItem     (0);
	m_pListBoxChapters->setSelected        (0, true);

	m_pComboPreCommand->setCurrentText  (m_sourceFileInfo.qsPreCommand);
	m_pComboPostCommand->setCurrentText (m_sourceFileInfo.qsPostCommand);
	m_pSpinBoxPause->setValue           (m_sourceFileInfo.iPause);

	m_pMediaInterface = MediaCreator::createPreferredWidget (m_pMediaPreview, "ChapterXineWidget", (void *)pExistingMediaEngine);

	connect (m_pMediaInterface, SIGNAL(signalNewPosition(int, const QString&)), this, SLOT(slotNewPosition(int, const QString&)));
	QGridLayout *pVideoLayout = new QGridLayout (m_pMediaPreview, 1, 1, 2, 2, "MediaMainLayout");
	pVideoLayout->addWidget (m_pMediaInterface->getWidget(), 0, 0);
	// This is take care of in the polish () function for Xine and not necessary for MPlayer ...
	m_pMediaInterface->initMediaEngine();

	m_qsFileName = m_sourceFileInfo.qsFileName;
	m_pMediaInterface->openMRL  ( m_qsFileName );
	m_pMediaInterface->getScreenshot ( );

	// This is the new version, where I have a new WidgetControl.
	QGridLayout *pLayout = new QGridLayout      ( m_pFrameControl, 1, 1, 2, 2, "pLayout");
	m_pStartStopControl  = new StartStopControl ( m_pFrameControl );
	m_pStartStopControl->initMe (m_sourceFileInfo.qsFileName, iThumbnailSize, iLength);
	connect (m_pStartStopControl, SIGNAL (signalSliderValues   ( float, float ) ), this, SLOT ( slotSliderValues   ( float, float ) ) );
	connect (m_pStartStopControl, SIGNAL (signalSliderReleased ( bool ) ),         this, SLOT ( slotSliderReleased ( bool ) ) );

	m_iMovieLength = iLength;
	if ( m_iMovieLength < 1 )
	     m_iMovieLength = 1;
	pLayout->addWidget( m_pStartStopControl, 0, 0 );

	if (m_sourceFileInfo.pTranscodeInterface)	{
		if (m_sourceFileInfo.pTranscodeInterface->iEndingAt == 0)
			m_sourceFileInfo.pTranscodeInterface->iEndingAt = m_iMovieLength;
		QString qsFormat = QString ("hh:mm:ss.zzz");
		QTime endingTime, startingTime;
		startingTime = startingTime.addMSecs ( m_sourceFileInfo.pTranscodeInterface->iStartingAt );
		endingTime   = endingTime.addMSecs   ( m_sourceFileInfo.pTranscodeInterface->iEndingAt   );
		m_pEditStarting1->setText (startingTime.toString(qsFormat));
		m_pEditEnding1  ->setText (endingTime.toString  (qsFormat));
	}

	// Here we init the properties - tab
	MediaInfo *pMediaInfo = m_pMediaInterface->getMediaInfo ();
	if (!pMediaInfo)	{
		pMediaInfo = MediaCreator::createInfo ((void *)pExistingMediaEngine);
		if (!pMediaInfo)
			return;
		pMediaInfo->setFileName (m_qsFileName);
	}

	//	m_pLabelVideoFormat->setText (QString ("%1(%2) %3Hz")
	//.arg (pMediaInfo->getFormat(true))
	//.arg (pMediaInfo->getResolutionString())
	//.arg (pMediaInfo->getFPS())
	//);
	m_pLabelVideoFormat->setText (QString ("%1(%2) %3Hz")
		.arg ( pInfo->qsVideoFormat )
		.arg ( pInfo->qsResolution  )
		.arg ( pInfo->qsFPS         )
	);

	m_pLabelVideoCodec->setText (pMediaInfo->getCodec(true));

	//	m_pLabelAudioFormat->setText(QString ("%1 %2bit %3")
	//.arg(pMediaInfo->getFormat(false))
	//.arg(pMediaInfo->getBits())
	//.arg(pMediaInfo->getSampleString())
	//);
	m_pLabelAudioFormat->setText(QString ("%1 %2bit %3")
		.arg( pInfo->qsAudioFormat )
		.arg( pInfo->qsBits        )
		.arg( pInfo->qsSample      )
	);

	m_pLabelAudioCodec->setText (pMediaInfo->getCodec (false) );  // Stereo 2.0
	m_pButtonEncodeNow->hide ();

	// Here we init the properties - tab
	initTranscodeTab ();
	m_pTabWidget->setCurrentPage (0);

	// And finally here are the callback functions ...
	connect (m_pButtonAdd,            SIGNAL( clicked ()), this, SLOT (slotAddChapter()));
	connect (m_pButtonDel,            SIGNAL( clicked ()), this, SLOT (slotDelChapters()));
	connect (m_pButtonAuto,           SIGNAL( clicked ()), this, SLOT (slotAutoChapters()));
	connect (m_pListBoxChapters,      SIGNAL( currentChanged (QListBoxItem *)), this, SLOT (slotCurrentChanged(QListBoxItem *)));

	connect (m_pComboVideoOut,        SIGNAL( activated(const QString &)), this, SLOT (slotVideoOutChanged(const QString &)));
	connect (m_pComboVideoResolution, SIGNAL( activated(const QString &)), this, SLOT (slotVideoResolutionChanged(const QString &)));
	connect (m_pComboVideoRate,       SIGNAL( activated(const QString &)), this, SLOT (slotVideoRateChanged(const QString &)));
	connect (m_pComboVideoType,       SIGNAL( activated(const QString &)), this, SLOT (slotVideoTypeChanged(const QString &)));
	connect (m_pComboVideoAspect,     SIGNAL( activated(const QString &)), this, SLOT (slotVideoAspectChanged(const QString &)));
	connect (m_pComboVideoBitrate,    SIGNAL( activated(const QString &)), this, SLOT (slotVideoBitrateChanged(const QString &)));
	connect (m_pSliderVolume,         SIGNAL( valueChanged (int)),         this, SLOT (slotNewVolume (int)));

	QTimer::singleShot (50, this, SLOT(slotSetStartStop()));
}

void DialogMovie::initMe(MovieObject *pMovieObject)
{
	int t;
	// Called when coming from a MovieObject in the Menu.
	if (!pMovieObject)
		return;

	QString qsFormat;
	m_pMovieObject = pMovieObject;

	// Okay coming from the MovieObject we need only the Geometry - tab
	QWidget *pTab = m_pTabWidget->page (TRANSCODING_TAB);
	m_pTabWidget->removePage (pTab);
	delete pTab;
	pTab = m_pTabWidget->page (CHAPTERS_TAB);
	m_pTabWidget->removePage (pTab);
	delete pTab;
	pTab = m_pTabWidget->page (PROPERTIES_TAB);
	m_pTabWidget->removePage (pTab);
	delete pTab;
	// ALso no transcoding buttons will be needed.
	delete m_pButtonTranscode;
	delete m_pButtonEncodeNow;
	m_pButtonTranscode = NULL;
	m_pButtonEncodeNow = NULL;
	m_pEditStarting1 = m_pEditStarting2;
	m_pEditEnding1 = m_pEditEnding2;

	// Set the values .
	m_pEditX->setText (QString ("%1").arg(pMovieObject->rect().x()));
	m_pEditY->setText (QString ("%1").arg(pMovieObject->rect().y()));
	m_pEditWidth ->setText (QString ("%1").arg(pMovieObject->rect().width()));
	m_pEditHeight->setText (QString ("%1").arg(pMovieObject->rect().height()));
	
	qsFormat = QString ("hh:mm:ss.zzz");
	QTime endingTime = pMovieObject->offset().addMSecs(-pMovieObject->duration().msecsTo(QTime()));
	m_pEditStarting2->setText (pMovieObject->offset().toString(qsFormat));
	m_pEditEnding2  ->setText (endingTime.toString (qsFormat));

	m_rectGeometry = pMovieObject->rect();
	m_qsFileName   = pMovieObject->fileName();

	QColor theColor;
	ImageManipulator::colorKeying *pKey;
	ImageManipulator *pMan = &pMovieObject->manipulator();
	for (t=0;t<(int)pMan->listColorKeys.count();t++)	{
		pKey = pMan->listColorKeys[t];
		theColor.setRgb (pKey->theColor);
		new ListViewColorItem (m_pListViewCK, theColor, theColor.name(), QString ("%1").arg(pKey->fDeltaColor));
	}
	
	QFileInfo fileInfo(m_qsFileName);
	// and now on to initializing the dialog. Length : 00:07:23.123 File : Cool Video.mpg
	m_pTextTitle->setText (tr ("File : %1").arg(fileInfo.fileName()));
	setCaption (fileInfo.fileName ());

	// we'll init the MediaEngine here
	DVDMenu *pDVDMenu = pMovieObject->dvdMenu();
	initMediaInterface(pDVDMenu);
}

void DialogMovie::initMediaInterface(DVDMenu *pDVDMenu)
{
	QFileInfo fileInfo;
	QString qsBackgroundName, qsFormat;
	int iThumbnailSize = 50;
	MediaInfo *pMediaInfo           = NULL;
	void      *pExistingMediaEngine = NULL;
	qsFormat = QString ("hh:mm:ss.zzz");

	if (pDVDMenu)	{
		pMediaInfo = pDVDMenu->getDVDAuthor()->getMediaInfo   ();
		pExistingMediaEngine = pMediaInfo->getMediaEngine     ();
		iThumbnailSize = pDVDMenu->getDVDAuthor()->getDragNDropContainer()->sizeThumbnail.width();
		if (m_qsFileName.isEmpty() || m_qsFileName.isNull() )	{
			if (pDVDMenu->getInterface()->qsMovieFileName.isNull())
				m_qsFileName = pDVDMenu->getInterface()->qsBackgroundFileName;
			else
				m_qsFileName = pDVDMenu->getInterface()->qsMovieFileName;
		}
		fileInfo.setFile (m_qsFileName);
		qsBackgroundName = QString (" : %1 <%2>").arg(fileInfo.fileName()).arg(pDVDMenu->getInterface()->timeDuration.toString(qsFormat));

		m_pTextTitle->setText (pDVDMenu->name() + qsBackgroundName);
	}
	// Here we create the MediaInterface (the widget) If the mediaengine in NULL or not ...
	m_pMediaInterface = MediaCreator::createPreferredWidget (m_pMediaPreview, "ChapterXineWidget", pExistingMediaEngine);
	connect (m_pMediaInterface, SIGNAL(signalNewPosition(int, const QString&)), this, SLOT(slotNewPosition(int, const QString&)));
	QGridLayout *pVideoLayout = new QGridLayout (m_pMediaPreview, 1, 1, 2, 2, "MediaMainLayout");
	pVideoLayout->addWidget (m_pMediaInterface->getWidget(), 0, 0);
	// This is taken care of in the polish () function for Xine and not necessary for MPlayer ...
	m_pMediaInterface->initMediaEngine();

	m_pMediaInterface->openMRL (m_qsFileName);
	m_pMediaInterface->getScreenshot  ();

	// Here we ensure the availability of a MediaInfo - object
	if (!pMediaInfo)
		pMediaInfo =  m_pMediaInterface->getMediaInfo ();

	if (!pMediaInfo)
		return;

	// here we extract some information + the screenshot.
	pMediaInfo->setFileName (m_qsFileName);
	m_pTextTitle->setText (tr ("Length : <%1> File : %2").arg(pMediaInfo->getLengthString()).arg(fileInfo.fileName()));
	setCaption (fileInfo.fileName());
	m_iMovieLength = pMediaInfo->getLength ();
	if (m_iMovieLength < 1)
		m_iMovieLength = 1;

	QGridLayout *pLayout = new QGridLayout      ( m_pFrameControl, 1, 1, 2, 2, "pLayout");
	m_pStartStopControl  = new StartStopControl ( m_pFrameControl );
	m_pStartStopControl->initMe (m_qsFileName, iThumbnailSize, m_iMovieLength);
	pLayout->addWidget( m_pStartStopControl, 0, 0 );

	// next is to set the satrting / ending points ...
	QTimer::singleShot (50, this, SLOT(slotSetStartStop()));
	connect (m_pStartStopControl, SIGNAL (signalSliderValues   ( float, float)), this, SLOT ( slotSliderValues   ( float, float ) ) );

	connect (m_pStartStopControl, SIGNAL (signalSliderReleased ( bool ) ),       this, SLOT ( slotSliderReleased ( bool ) ) );
	connect (m_pSliderVolume,     SIGNAL (valueChanged         ( int  ) ),       this, SLOT ( slotNewVolume      ( int ) ) );
}

void DialogMovie::slotSetStartStop ()
{
	int iStarting, iEnding;
	QTime      zeroTime;
	iStarting = 0;
	iEnding = m_iMovieLength;

	if (m_pDVDMenu)	{
		iStarting = zeroTime.msecsTo (m_pDVDMenu->getInterface()->timeOffset);
		iEnding   = iStarting + zeroTime.msecsTo (m_pDVDMenu->getInterface()->timeDuration);
	}
	else if (m_pMovieObject)	{
		iStarting = zeroTime.msecsTo (m_pMovieObject->offset()); 
		iEnding   = iStarting + zeroTime.msecsTo(m_pMovieObject->duration());
	}
	else if (m_sourceFileInfo.pTranscodeInterface)	{
		iStarting = m_sourceFileInfo.pTranscodeInterface->iStartingAt;
		iEnding   = m_sourceFileInfo.pTranscodeInterface->iEndingAt;
	}
	m_pStartStopControl->setStart ((float) iStarting / m_iMovieLength);
	m_pStartStopControl->setEnd   ((float) iEnding   / m_iMovieLength);
}

void DialogMovie::slotEditMediaInfo ()
{
  // This will open the media info dialog, where the user can modify the auto detected values (through Xine, VLC or MPlayer)
  DialogMediaInfo theDialog ( this );
  theDialog.initMe ( &m_sourceFileInfo );
  
  if ( theDialog.exec () == QDialog::Accepted ) {
    m_sourceFileInfo.qsRatio       = theDialog.m_pEditVideoAspect->text ( );
    m_sourceFileInfo.qsFPS         = theDialog.m_pEditVideoFPS->text    ( );
    m_sourceFileInfo.qsLength      = theDialog.m_pEditVideoLength->text ( );
    m_sourceFileInfo.qsVideoFormat = theDialog.m_pEditVideoFormat->text ( );
    m_sourceFileInfo.qsAudioFormat = theDialog.m_pEditAudioFormat->text ( );
    m_sourceFileInfo.qsBits        = theDialog.m_pEditAudioBits->text   ( );
    m_sourceFileInfo.qsBPS         = theDialog.m_pEditAudioBPS->text    ( );
    m_sourceFileInfo.qsSample      = theDialog.m_pEditAudioSample->text ( );
    m_pLabelVideoFormat->setText (QString ("%1(%2) %3Hz")
	          .arg ( m_sourceFileInfo.qsVideoFormat )
	          .arg ( m_sourceFileInfo.qsResolution  )
                  .arg ( m_sourceFileInfo.qsFPS         )
    );
    m_pLabelAudioFormat->setText(QString ("%1 %2bit %3")
		 .arg ( m_sourceFileInfo.qsAudioFormat )
		 .arg ( m_sourceFileInfo.qsBits        )
		 .arg ( m_sourceFileInfo.qsSample      )
    );
  }
}

SourceFileInfo *DialogMovie::sourceFileInfo ()
{
	return &m_sourceFileInfo;
}

void DialogMovie::slotNewVolume ( int iNewVolume )
{
  // slider min = 0 slider max = 100
  float fNewVolume = (100 - iNewVolume) / 100.0;
  m_pMediaInterface->setVolume ( fNewVolume );
}

void DialogMovie::slotBlink ( )
{
	if (transcodeEnabled ())	{
		if (m_pTextTranscoding->paletteForegroundColor () == QColor (0, 0, 0))
			m_pTextTranscoding->setPaletteForegroundColor (QColor (COLOR_TRANSCODE));
		else
			m_pTextTranscoding->setPaletteForegroundColor (QColor (0, 0, 0));
		QTimer::singleShot (1000, this, SLOT(slotBlink()));
	}
}

bool DialogMovie::transcodeEnabled ()
{
	// If the background color of the title is set to -RED- then we are in the transcoding mode
	return (m_pTextTitle->paletteBackgroundColor () == QColor (COLOR_TRANSCODE));
}

void DialogMovie::initTranscodeTab ()
{
	// DVD restrictions ...
	// NTSC : 720x480 704x480 352x480 352x240 * 29.97Hz
	// PAL  : 720x576 704x576 352x576 352x288 * 25Hz
	// Mpeg2: up to 9800 kbps
	// Mpeg1: 352x288 or 352x240 limited to 4:3 up to 1856 kbps
	// Audio bitrate : 32 .. 1536 kbps
	// Video bitrate : Mpeg2 max9800kbps Mpeg1 max 1856 kbps
	// Allow for muxing with this error.
	// If Warn: skipping sector, waiting for first VOBU, then simply re-multiplex. (check kdvdauthor)
	
	if (!m_sourceFileInfo.pTranscodeInterface)
		return;

	m_sourceFileInfo.pTranscodeInterface->qsVideoFormat.remove ("Keep ");
	m_sourceFileInfo.pTranscodeInterface->qsVideoType.remove ("Keep ");
	m_sourceFileInfo.pTranscodeInterface->qsResolution.remove ("Keep ");
//	m_pComboVideoBitrate->insertItem    (QString ("Keep %1").arg(longToNorm(m_sourceFileInfo.pTranscodeInterface->iVideoBitrate) + QString ("bps")), 0);
//	m_pComboVideoRate->insertItem       (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->fFrameRate), 0);
	m_sourceFileInfo.pTranscodeInterface->qsRatio.remove ("Keep ");
	
//	m_pComboAudioOut->insertItem        ("Keep Original", 0);
	m_sourceFileInfo.pTranscodeInterface->qsAudioType.remove ("Keep ");
//	m_pComboAudioBitrate->insertItem    (QString ("Keep %1").arg(longToNorm(m_sourceFileInfo.pTranscodeInterface->iAudioBitrate) + QString ("bps")), 0);
//	m_pComboAudioSampleRate->insertItem (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->iSample), 0);

	m_pComboVideoOut->insertItem        (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->qsVideoFormat), 0);
	m_pComboVideoType->insertItem       (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->qsVideoType), 0);
	m_pComboVideoResolution->insertItem (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->qsResolution), 0);
	if (m_sourceFileInfo.pTranscodeInterface->iVideoBitrate < 0)
		m_sourceFileInfo.pTranscodeInterface->iVideoBitrate *= -1;
	m_pComboVideoBitrate->insertItem    (QString ("Keep %1").arg(longToNorm(m_sourceFileInfo.pTranscodeInterface->iVideoBitrate) + QString ("bps")), 0);
	if (m_sourceFileInfo.pTranscodeInterface->fFrameRate < 0.0)
		m_sourceFileInfo.pTranscodeInterface->fFrameRate *= -1.0;
	m_pComboVideoRate->insertItem       (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->fFrameRate), 0);
	m_pComboVideoAspect->insertItem     (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->qsRatio), 0);
	
	m_pComboAudioOut->insertItem        ("Keep Original", 0);
	m_pComboAudioType->insertItem       (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->qsAudioType), 0);

	if (m_sourceFileInfo.pTranscodeInterface->iAudioBitrate < 0)
		m_sourceFileInfo.pTranscodeInterface->iAudioBitrate *= -1;
	m_pComboAudioBitrate->insertItem    (QString ("Keep %1").arg(longToNorm(m_sourceFileInfo.pTranscodeInterface->iAudioBitrate) + QString ("bps")), 0);
	if (m_sourceFileInfo.pTranscodeInterface->iSample < 0)
		m_sourceFileInfo.pTranscodeInterface->iSample *= -1;
	m_pComboAudioSampleRate->insertItem (QString ("Keep %1").arg(m_sourceFileInfo.pTranscodeInterface->iSample), 0);
	
//	m_pComboVideoOut->setCurrentText        (m_sourceFileInfo.pTranscodeInterface->qsVideoFormat);
//	m_pComboVideoType->setCurrentText       (m_sourceFileInfo.pTranscodeInterface->qsVideoType);
//	m_pComboVideoResolution->setCurrentText (m_sourceFileInfo.pTranscodeInterface->qsResolution);
//	m_pComboVideoBitrate->setCurrentText    (longToNorm(m_sourceFileInfo.pTranscodeInterface->iVideoBitrate) + QString ("bps"));
//	m_pComboVideoRate->setCurrentText       (QString ("%1").arg(m_sourceFileInfo.pTranscodeInterface->fFrameRate));
//	m_pComboVideoAspect->setCurrentText     (m_sourceFileInfo.pTranscodeInterface->qsRatio);
	
//	m_pComboAudioOut->setCurrentText        (m_sourceFileInfo.pTranscodeInterface->qsAudioFormat);
//	m_pComboAudioType->setCurrentText       (m_sourceFileInfo.pTranscodeInterface->qsAudioType);
//	m_pComboAudioBitrate->setCurrentText    (longToNorm(m_sourceFileInfo.pTranscodeInterface->iAudioBitrate) + QString ("bps"));
//	m_pComboAudioSampleRate->setCurrentText (QString ("%1").arg(m_sourceFileInfo.pTranscodeInterface->iSample));
	// And make the transcode - tab visible again ...
	slotTranscode ();
}

void DialogMovie::slotVideoOutChanged (const QString &)
{
	// NTSC : 720x480 704x480 352x480 352x240 * 29.97Hz
	// PAL  : 720x576 704x576 352x576 352x288 * 25Hz
	m_pComboVideoRate->clear ();
	m_pComboVideoAspect->clear ();
	m_pComboVideoResolution->clear ();
//	QString qsCurrentResolution = m_pComboVideoResolution->currentText ();
	QString qsNewString = m_pComboVideoOut->currentText ().upper();

	MediaInfo *pMediaInfo = NULL;
	if (m_pMediaInterface)
		m_pMediaInterface->getMediaInfo ();
	if (pMediaInfo)	{
		m_pComboVideoResolution->insertItem (QString ("Keep %1").arg(pMediaInfo->getResolutionString()));
		m_pComboVideoAspect->insertItem     (QString ("Keep %1").arg(pMediaInfo->getRatio()));
		m_pComboVideoRate->insertItem       (QString ("Keep %1").arg(pMediaInfo->getFPS()));
	}
	if ( (qsNewString == "PAL") || (qsNewString == "CUSTOM") )	{
		if (m_pComboVideoType->currentText () != "Mpeg 1")	{
			m_pComboVideoResolution->insertItem ("720x576");
			m_pComboVideoResolution->insertItem ("704x576");
			m_pComboVideoResolution->insertItem ("352x576");
		}
		m_pComboVideoResolution->insertItem ("352x288");
		m_pComboVideoRate->insertItem ("25");
	}
	if ( (qsNewString == "NTSC") || (qsNewString == "CUSTOM") )	{
		if (m_pComboVideoType->currentText () != "Mpeg 1")	{
			m_pComboVideoResolution->insertItem ("720x480");
			m_pComboVideoResolution->insertItem ("704x480");
			m_pComboVideoResolution->insertItem ("352x480");
		}
		m_pComboVideoResolution->insertItem ("352x240");
		m_pComboVideoRate->insertItem ("29.97");
	}

	m_pComboVideoAspect->insertItem ("4:3");
	m_pComboVideoAspect->insertItem ("1:1");
	if (m_pComboVideoType->currentText () != "Mpeg 1")	{
		m_pComboVideoAspect->insertItem ("16:9");
		m_pComboVideoAspect->insertItem ("2.21:1");
	}
}

void DialogMovie::slotVideoTypeChanged (const QString &)
{
	slotVideoOutChanged (QString ());
}

void DialogMovie::slotVideoResolutionChanged (const QString &)
{
}

void DialogMovie::slotVideoRateChanged (const QString &)
{
}

void DialogMovie::slotVideoAspectChanged (const QString &)
{
}

void DialogMovie::slotVideoBitrateChanged (const QString &)
{
}

void DialogMovie::slotAudioOutChanged (const QString &)
{
}

void DialogMovie::slotAudioTypeChanged (const QString &)
{
}

void DialogMovie::slotAudioBitrateChanged (const QString &)
{
}

void DialogMovie::slotAddColorKey ()
{
	float fDelta = m_pEditCK->text().toFloat();
	//QListViewItem *pItem = 
	new ListViewColorItem (m_pListViewCK, m_pButtonCK->paletteBackgroundColor(), QString (m_pButtonCK->paletteBackgroundColor().name ()), QString ("%1").arg(fDelta) );
}

void DialogMovie::slotDelColorKey ()
{
	QListViewItem *pItem = m_pListViewCK->selectedItem ();
	// First we check if anything has been selected.
	if ( ! pItem )
		return;
	delete pItem;
}

void DialogMovie::slotBrowseColorKey ()
{
	QColor theColor = QColorDialog::getColor(m_pButtonCK->paletteBackgroundColor ());

	m_pButtonCK->setPaletteBackgroundColor ( theColor );
}

void DialogMovie::slotAutoChapters ()
{
	uint t, i, iDeltaStep, iStarting, iEnding, iChapter, iPreviousChapter;
	int iTotalLength, iNumberOfNewChapters;
	QString qsTimeString;
	Utils theUtil;
	// Here we read in the list of currently generated chapters
	// then we convert them into milliseconds, and store them in an array
	// And finally we generate the chapters, sort the array and put it back into the
	// m_pListBoxChapters, and m_sourceFileInfo - structures.
	uint *pArrayExistingChapters = new uint[m_pListBoxChapters->count()];
	for (t=0;t<m_pListBoxChapters->count(); t++)	{
		qsTimeString = m_pListBoxChapters->text(t);
		pArrayExistingChapters[t] = theUtil.getMsFromString (qsTimeString);
	}
	iStarting  = theUtil.getMsFromString (m_pEditStarting1->text());
	iEnding    = theUtil.getMsFromString (m_pEditEnding1->text());
	iDeltaStep = theUtil.getMsFromString (m_pEditEvery->text());
	iTotalLength = (int)(iEnding - iStarting);
	// a DeltaStep of 0 would generate infinite number of chapters
	if ( ( iDeltaStep < 1 ) || ( iTotalLength < 1 ) ) {
	  delete []pArrayExistingChapters;
	  return;
	}
	if (iDeltaStep > (uint) iTotalLength)
		iDeltaStep = iTotalLength;
	iNumberOfNewChapters = (int)((float)iTotalLength / (float)iDeltaStep) + 1;

	QValueList<int> listAllChapters;
	// Okay this is the worst sort algo around but we would'nt sort thousands of chapters, now would we ???
	i = 0;
	for (t=0;t<(uint)iNumberOfNewChapters;t++)	{
		iChapter = t*iDeltaStep;
		for (i=0;i<m_pListBoxChapters->count();i++)	{
			// If we find an entry which is the same as a calculated chapter we should skip it ...
			if (pArrayExistingChapters[i] == iChapter)
				pArrayExistingChapters[i] = 0;
			// If we find an entry which is smaller but not 0, then we should include them ...
			else if ( (pArrayExistingChapters[i] < iChapter) && (pArrayExistingChapters[i] > 0) )	{
				listAllChapters.append (pArrayExistingChapters[i]);
				// Here we ensure the next time this entry is higher
				pArrayExistingChapters[i] = 0;
			}
		}
		listAllChapters.append (iChapter);
	}

	m_pListBoxChapters->clear ();
	iChapter = iPreviousChapter = 0;
	for (t=0;t<listAllChapters.count();t++)	{
		iChapter = listAllChapters[t];
		if (iChapter >= iPreviousChapter)
			m_pListBoxChapters->insertItem(theUtil.getStringFromMs (iChapter));
		iPreviousChapter = iChapter;
	}

	delete []pArrayExistingChapters;
}

void DialogMovie::slotAnimation ()
{
	// This function gets the Animation Dialog
	// Within this dialog, you can create a script
	// (or hardcode) Attributes of the object.
	// Before rendering the menu the script will 
	// get executed and all data sent to stdout 
	// will be captured in the data file, wich 
	// will provide the data for the animation.	
	QString qsEmpty, qsAnimation;
	int iType;
	DialogAnimation dialog ( this );
	if ( m_pMovieObject )	{
		dialog.initMe ( m_pMovieObject->animation(), m_pMovieObject->dvdMenu()->framesToRender(), m_pMovieObject->dvdMenu()->fps(), DialogAnimation::TypeMovie );
		if ( dialog.exec () == QDialog::Accepted )	{
			qsAnimation = dialog.string ();
			if (qsAnimation.length () < 5)
				qsAnimation = qsEmpty;
			m_pMovieObject->setAnimation ( qsAnimation );
		}
	}
	else if (m_pDVDMenu)	{
		iType = DialogAnimation::TypeImage;
		if (m_pEditStarting2->isEnabled ())
			iType = DialogAnimation::TypeMovie;
		dialog.initMe ( m_pDVDMenu->getInterface()->qsAnimation, m_pDVDMenu->framesToRender (), m_pDVDMenu->fps (), iType );
		if ( dialog.exec () == QDialog::Accepted )	{
			qsAnimation = dialog.string ();
			if (qsAnimation.length () < 5)
				qsAnimation = qsEmpty;
			m_pDVDMenu->getInterface()->qsAnimation = qsAnimation;
		}
	}
}

void DialogMovie::slotSizeDialog ()
{
  if ( ! m_pDVDMenu )
    return;
  m_pDVDMenu->changeSize ();
}

void DialogMovie::slotAddChapter ()
{
	// Here we add a chapter in the right space,
	// but only if this chapter does not already exists ...
	Utils theUtil;
	int iChapter, iAddChapter;
	uint t;
	iChapter = 0;
	iAddChapter = theUtil.getMsFromString (m_pEditAdd->text());
	for (t=0;t<m_pListBoxChapters->count();t++)	{
		iChapter = theUtil.getMsFromString (m_pListBoxChapters->text(t));
		if (iAddChapter == iChapter)
			break;
		else if (iAddChapter < iChapter)	{
			m_pListBoxChapters->insertItem (theUtil.getStringFromMs (iAddChapter), t);
			break;
		}
	}
	// and in case the Chpater is to be added at the end ...
	if (iAddChapter > iChapter)
		m_pListBoxChapters->insertItem (theUtil.getStringFromMs (iAddChapter));
}

void DialogMovie::slotDelChapters ()
{
	// This function will remove all chapters which are currently selected in m_pListBoxChapters
	uint t;
	QValueList<QListBoxItem *> listItems;
	for (t=0;t<m_pListBoxChapters->count();t++)	{
		if (m_pListBoxChapters->isSelected (t))
			listItems.append (m_pListBoxChapters->item(t));
	}
	for (t=0;t<listItems.count();t++)
			delete listItems[t];
}

void DialogMovie::slotCurrentChanged (QListBoxItem *pItem)
{
	uint t, iCount;
	iCount = 0;
	// we first count the number of selected chapters
	for (t=0;t<m_pListBoxChapters->count();t++)	{
		if (m_pListBoxChapters->isSelected (t))
			iCount ++;
	}
	if (iCount != 1)
		return;
	// Last we jump to the position
	if (m_pListBoxChapters->isSelected (pItem))	{
		int iChapter = 0;
		QTime chapterTime, zeroTime;
		QString qsChapter = m_pListBoxChapters->currentText ();
	
		chapterTime = QTime::fromString (qsChapter);
		iChapter = zeroTime.secsTo (chapterTime);
		m_pMediaInterface->setPositionByTime (iChapter);
//		if (!m_pMediaInterface->isPaused   ())
//			m_pMediaInterface->pause   ();
	}
}

void DialogMovie::slotTranscode ()
{
	if (m_pTranscodeTab)	{
		m_pTabWidget->addTab (m_pTranscodeTab, tr ("Transcoding"));
		m_pTranscodeTab = NULL;
		m_pButtonTranscode->setText (tr("<<< Transcode"));
		m_pTabWidget->setCurrentPage (2);
		m_pTextTitle->setBackgroundColor (QColor(COLOR_TRANSCODE));
		m_pTextTranscoding->setBackgroundColor (QColor(COLOR_TRANSCODE));
		m_pTextTranscoding->setPaletteBackgroundColor (QColor(COLOR_TRANSCODE));
		m_pFrameHeader->setPaletteBackgroundColor (QColor(COLOR_TRANSCODE));
		QTimer::singleShot (1, this, SLOT(slotBlink()));
		m_pButtonEncodeNow->show ();
	}
	else	{
		m_pTranscodeTab = m_pTabWidget->page (m_pTabWidget->count()-1);
		m_pTabWidget->removePage (m_pTranscodeTab);
		m_pButtonTranscode->setText (tr("Transcode >>>"));
		m_pTextTitle->setBackgroundColor (QColor(COLOR_NOTRANSCODE));
		m_pTextTranscoding->setBackgroundColor (QColor(COLOR_NOTRANSCODE));
		m_pTextTranscoding->setPaletteForegroundColor (QColor (COLOR_NOTRANSCODE));
		m_pFrameHeader->setPaletteBackgroundColor (QColor(COLOR_NOTRANSCODE));
		m_pButtonEncodeNow->hide ();
		m_pStartStopControl->setStart (0.0f);
		m_pStartStopControl->setEnd   (1.0f);
	}
}

void DialogMovie::slotEncodeNow ()
{
	MessageBox::warning (NULL, tr("Warning"), tr("Not yet implemented"), QMessageBox::Ok, QMessageBox::NoButton);
}

void DialogMovie::slotWidth()
{
	if (m_pCheckAspect->isChecked())	{
		float fAspect = (float)m_rectGeometry.height() / (float)m_rectGeometry.width();
		int iWidth = m_pEditWidth->text().toInt();
		m_pEditHeight->setText (QString ("%1").arg((int)(fAspect * iWidth)));
	}
}

void DialogMovie::slotHeight()
{
	if (m_pCheckAspect->isChecked())	{
		float fAspect = (float)m_rectGeometry.width() / (float)m_rectGeometry.height();
		int iHeight = m_pEditHeight->text().toInt();
		m_pEditWidth->setText (QString ("%1").arg((int)(fAspect * iHeight)));
	}
}

void DialogMovie::slotPlay  ()
{
	if (m_pMediaInterface)	{
		if      (m_pMediaInterface->isPaused ())
			 m_pMediaInterface->play ();
		else if (m_pMediaInterface->isPlaying())
			 m_pMediaInterface->pause();
		else
			m_pMediaInterface->playMRL(m_qsFileName);
	
		if (m_pMediaInterface->isPaused ())
			m_pButtonPlay->setText (tr("Play"));
		else
			m_pButtonPlay->setText (tr("Pause"));
	}
}

void DialogMovie::slotStop  ()
{
	if (m_pMediaInterface)	{
		// In case the state is paused we should get back to play mode before stopping
		if (m_pMediaInterface->isPaused ())
			m_pMediaInterface->play ();
		m_pMediaInterface->stop ();
		// The button should display "Play" now
		m_pButtonPlay->setText (tr("Play"));
		// and then logically we should put the screen to the beginnning.
		m_pMediaInterface->getScreenshot ();
	}
}

void DialogMovie::slotSetThumbnail ()
{
  // The user presses SetAsThumbnail ...
  Utils theUtils;
  QRegExp rx ( "<[^>]*>" );
  QString qsCurrentTime =  m_pLabelCurrentPos->text ( );
  qsCurrentTime.replace ( rx, "" ); // = rx.cap ( 0 );

  long  iMSecOffset     = theUtils.getMsFromString ( qsCurrentTime );
  if  ( m_pEditStarting1 ) // indicates that we are coming from the Sourcetoolbar-SourceFileInfo
    emit ( signalSetThumbnail ( iMSecOffset ) ); // calls SourceToolbar::slotSetThumbnail ( long )

  m_sourceFileInfo.iMSecPreview = iMSecOffset;
}

void DialogMovie::slotStart ()
{	// This function will set the Start offset of the video clip
	if (m_qsPosition.length () < 8)
		m_pEditStarting1->setText (QString ("0") + m_qsPosition + QString (".000"));
	else
		m_pEditStarting1->setText (m_qsPosition);
	// But we also need to make sure that the start is not set before the end ...
	setStartStop (true);
}

void DialogMovie::slotEnd   ()
{
	if (m_qsPosition.length () < 8)
		m_pEditEnding1->setText (QString ("0") + m_qsPosition + QString (".000"));
	else
		m_pEditEnding1->setText (m_qsPosition);
	// But we also need to make sure that the end is not set before the start ...
	setStartStop (false);
}

void DialogMovie::setStartStop (bool bStart)
{
	QTime zeroTime;
	QTime startTime = QTime::fromString (m_pEditStarting1->text());
	QTime endTime   = QTime::fromString (m_pEditEnding1  ->text());
	if (endTime < startTime)	{
		if (bStart)
			m_pEditEnding1->setText (m_pEditStarting1->text());
		else
			m_pEditStarting1->setText (m_pEditEnding1->text());
	}
	// and last but not least we should set the slider controls ...
	int iStartTime = zeroTime.msecsTo (startTime);	
	int iEndTime   = zeroTime.msecsTo   (endTime);	
	float fPercentage = (float)iStartTime / (float)m_iMovieLength;
	m_pStartStopControl->setStart (fPercentage);
	fPercentage = (float)iEndTime / (float)m_iMovieLength;
	m_pStartStopControl->setEnd   (fPercentage);
	if ( (iStartTime > 10) || (fPercentage < 0.9999) )	{
		if ( (m_pButtonTranscode) && ( ! transcodeEnabled ()) )
			slotTranscode ();
	}
}

void DialogMovie::slotSliderReleased ( bool bStartSlider )
{
  // if the start slider was released AND the MediaEngine is NOT playing, then we 
  // should create a new preview in the MediaInterface - window.
  if ( bStartSlider ) {
    if ( ! m_pMediaInterface->isPlaying ( ) ) {
      m_pLabelCurrentPos->setText ( m_pEditStarting1->text ( ) );
      // The user presses SetAsThumbnail ...
      Utils theUtils;
      QRegExp rx ( "<[^>]*>" );
      QString qsCurrentTime =  m_pLabelCurrentPos->text ( );
      qsCurrentTime.replace ( rx, "" );
      
      long  iMSecOffset     = theUtils.getMsFromString ( qsCurrentTime );
      m_pMediaInterface->setScreenshot ( iMSecOffset );
    }
  }
}

void DialogMovie::slotSliderValues (float fStart, float fEnd)
{
  // This function is called when the user uses the slider controls (values in percentage)
  QTime startTime;
  QTime endTime;
  QString qsFormat ("hh:mm:ss.zzz");
  startTime = startTime.addMSecs ((int)(fStart * m_iMovieLength));
  endTime = endTime.addMSecs ((int)(fEnd   * m_iMovieLength));
  m_pEditStarting1->setText (startTime.toString (qsFormat));
  m_pEditEnding1  ->setText (endTime.toString   (qsFormat));

  // For now we disable auto transcoding of only the start slider is moved ...
  //	if ( ( fStart > 0.0001 ) || ( fEnd < 0.9999) )	{
  if ( fEnd < 0.995 ){
    if ( (m_pButtonTranscode) && ( ! transcodeEnabled ()) )
      slotTranscode ();
  }
}

void DialogMovie::slotNewPosition(int, const QString &qsPosition)
{
	m_qsPosition = qsPosition;
	if (m_qsPosition.length() == 8)
		m_qsPosition += ".000";

	m_pLabelCurrentPos->setText ("<p align=\"center\">" + m_qsPosition + "</p>");
	if ( ( ! m_pDVDMenu ) && ( ! m_pMovieObject ) )	// if this is a BackgroundMovie/Image then this button does not exist.
		m_pEditAdd->setText (m_qsPosition);
	if (m_iMovieLength == 0)
		return;
	QTime curTime = QTime::fromString(qsPosition);
	QTime zeroTime;
	int iCurTime = zeroTime.msecsTo (curTime);	
	float fPercentage = (float)iCurTime / (float)m_iMovieLength;
	m_pStartStopControl->setProgress (fPercentage);
}

long DialogMovie::normToLong ( QString qsInput )
{
	QString qsValue, arrayDigit (".0123456789");
	uint t, i;
	long iReturn, iMultiplicator = 1;
	// Here we take a string like 4400kbps and return 4400000.
	for (t=0;t<qsInput.length();t++)	{
		for (i=0;i<arrayDigit.length();i++)	{
			if (qsInput[t] == arrayDigit[i])	{
				qsValue += qsInput[t];
				i = 10;
				continue;
			}
		}
		if (qsInput[t].upper () == "K")	{
			iMultiplicator = 1000;
			break;
		}
		if (qsInput[t].upper () == "M")	{
			iMultiplicator = 1000000;
			break;
		}
		if (qsInput[t].upper () == "G")	{
			iMultiplicator = 1000000000;
			break;
		}
	}
	iReturn = (long)(qsValue.toFloat() * iMultiplicator);
	return iReturn;
}

QString DialogMovie::longToNorm ( long iInput )
{
	// This function returns a string like 4400k from 4400000
	QString qsReturn;
	float fValue;
	if (iInput > 1000000000)	{
		fValue = (double)iInput / 1000000000.0;
		qsReturn = QString ("%1G").arg(fValue);
	}
	else if (iInput > 1000000)	{
		fValue = (double)iInput / 1000000.0;
		qsReturn = QString ("%1M").arg(fValue);
	}
	else if (iInput > 1000)	{
		fValue = (double)iInput / 1000.0;
		qsReturn = QString ("%1k").arg(fValue);
	}
	else	{
		qsReturn = QString ("%1").arg(iInput);
	}
	return qsReturn;
}

void DialogMovie::accept ()
{
	uint t;
	long iBitrate;
	long iTemp;
	float fTemp;
	QFileInfo fileInfo;
	QString qsTemp;
	QString qsFormat ("hh:mm:ss.zzz");
	QTime startingTime, endingTime, duration, zeroTime;

	if ( m_pDVDMenu )	{
		startingTime = QTime::fromString (m_pEditStarting1->text());
		endingTime   = QTime::fromString (m_pEditEnding1->text());
		// Here we hande the start/stop time.
		if (startingTime.isValid())	{
			m_pDVDMenu->getInterface()->timeOffset = startingTime;
			if (endingTime.isValid ())	{
				int iMSecs = startingTime.msecsTo  (endingTime);
				duration   = duration.addMSecs (iMSecs);
				m_pDVDMenu->getInterface()->timeDuration = duration;
			}
		}
	}
	else if (m_pMovieObject)	{
		// Here we handle MovieObjects. Check out if we have set Color Keying.
		ImageManipulator::colorKeying *pColorKey;
		ListViewColorItem *pItem;
		float  fDelta;
		QColor theColor;

		// First we should remove all entries in the color Key
		ImageManipulator *pMan= &m_pMovieObject->manipulator();
		for (t=0;t<pMan->listColorKeys.count();t++)
			delete pMan->listColorKeys[t];
		pMan->listColorKeys.clear();
		// And then we add whats currently in the widget.
		if ( m_pListViewCK->childCount() )	{
			pItem = (ListViewColorItem *)m_pListViewCK->firstChild ();
			while (pItem)	{
				theColor.setNamedColor (pItem->text (0));	// The Color nam is stored in the first text
				fDelta = pItem->text(1).toFloat();		// The delta value is stored in the second column.
				pColorKey = new ImageManipulator::colorKeying ( theColor.rgb(), fDelta );
				pMan->listColorKeys.append ( pColorKey );
				pItem = (ListViewColorItem *)pItem->itemBelow ();
			}
		}
	}
	else if (m_pEditStarting1)	{// used as an indicator if we were coming from the SourceToolbar->SourceFileInfo
		startingTime = QTime::fromString (m_pEditStarting1->text());
		endingTime   = QTime::fromString (m_pEditEnding1->text());
		m_sourceFileInfo.qsPreCommand  = m_pComboPreCommand->currentText ();
		m_sourceFileInfo.qsPostCommand = m_pComboPostCommand->currentText ();
		m_sourceFileInfo.iPause        = m_pSpinBoxPause->value ();
		m_sourceFileInfo.bAutotranscode= false; // once the user clicks ok we don't want to change any transcoding settings any more.

		if (transcodeEnabled ())	{
		        Utils theUtils;
			if (!m_sourceFileInfo.pTranscodeInterface)
				m_sourceFileInfo.pTranscodeInterface = new TranscodeInterface;
			m_sourceFileInfo.pTranscodeInterface->qsVideoFormat = m_pComboVideoOut->currentText        ();
			m_sourceFileInfo.pTranscodeInterface->qsVideoType   = m_pComboVideoType->currentText       ();
			m_sourceFileInfo.pTranscodeInterface->qsResolution  = m_pComboVideoResolution->currentText ();
			fileInfo.setFile ( m_sourceFileInfo.qsFileName );
			m_sourceFileInfo.pTranscodeInterface->qsTempFile = QString ( "%1/%2.mpeg2" ).arg (theUtils.getTempPath ( fileInfo.baseName () ) ).arg(fileInfo.baseName () );
			qsTemp = m_pComboVideoBitrate->currentText ();
			if ( qsTemp.contains ("Keep "))	{
				qsTemp.remove ("Keep ");
				iBitrate = -normToLong(qsTemp);
			}
			else
				iBitrate =  normToLong(qsTemp);
			m_sourceFileInfo.pTranscodeInterface->iVideoBitrate = iBitrate;
			qsTemp = m_pComboVideoRate->currentText ();
			if ( qsTemp.contains ("Keep "))	{
				qsTemp.remove ("Keep ");
				fTemp = -qsTemp.toFloat ();
			}
			else
				fTemp =  qsTemp.toFloat ();
			m_sourceFileInfo.pTranscodeInterface->fFrameRate    = fTemp;
			m_sourceFileInfo.pTranscodeInterface->qsRatio       = m_pComboVideoAspect->currentText     ();
			m_sourceFileInfo.pTranscodeInterface->qsAudioFormat = m_pComboAudioOut->currentText        ();
			m_sourceFileInfo.pTranscodeInterface->qsAudioType   = m_pComboAudioType->currentText       ();
			qsTemp = m_pComboAudioBitrate->currentText();
			if ( qsTemp.contains ("Keep "))	{
				qsTemp.remove ("Keep ");
				iBitrate = -normToLong(qsTemp);
			}
			else
				iBitrate =  normToLong(qsTemp);
			m_sourceFileInfo.pTranscodeInterface->iAudioBitrate = iBitrate;
			qsTemp = m_pComboAudioSampleRate->currentText ();
			if ( qsTemp.contains ("Keep "))	{
				qsTemp.remove ("Keep ");
				iTemp = -qsTemp.toInt();
			}
			else
				iTemp =  qsTemp.toInt();
			m_sourceFileInfo.pTranscodeInterface->iSample       = iTemp;
			m_sourceFileInfo.pTranscodeInterface->iStartingAt   = zeroTime.msecsTo(startingTime);
			m_sourceFileInfo.pTranscodeInterface->iEndingAt     = zeroTime.msecsTo(endingTime);
//		m_sourceFileInfo.pTranscodeInterface->bTranscoding  = later to indicate transcoding in progress.
		}
		else if (m_sourceFileInfo.pTranscodeInterface)	{
			// Okay there used to be a TranscodeInterface but now the user wants to undo the transcoding.
			delete m_sourceFileInfo.pTranscodeInterface;
			m_sourceFileInfo.pTranscodeInterface = NULL;
		}
	
		// Adding chapters ...
		m_sourceFileInfo.listChapters.clear ();
		for (t=0;t<m_pListBoxChapters->count ();t++)
			m_sourceFileInfo.listChapters.append(m_pListBoxChapters->text (t));
	}
	else {	// Or if we are coming from the transcodeAll context menu
	        m_sourceFileInfo.bAutotranscode = false;
		if (!m_sourceFileInfo.pTranscodeInterface)
			m_sourceFileInfo.pTranscodeInterface = new TranscodeInterface;
		m_sourceFileInfo.pTranscodeInterface->qsVideoFormat = m_pComboVideoOut->currentText        ( );
		m_sourceFileInfo.pTranscodeInterface->qsVideoType   = m_pComboVideoType->currentText       ( );
		m_sourceFileInfo.pTranscodeInterface->qsResolution  = m_pComboVideoResolution->currentText ( );
		iBitrate = normToLong(m_pComboVideoBitrate->currentText ());
		m_sourceFileInfo.pTranscodeInterface->iVideoBitrate = iBitrate;
		m_sourceFileInfo.pTranscodeInterface->fFrameRate    = m_pComboVideoRate->currentText       ( ).toFloat();
		m_sourceFileInfo.pTranscodeInterface->qsRatio       = m_pComboVideoAspect->currentText     ( );
		m_sourceFileInfo.pTranscodeInterface->qsAudioFormat = m_pComboAudioOut->currentText        ( );
		m_sourceFileInfo.pTranscodeInterface->qsAudioType   = m_pComboAudioType->currentText       ( );
		iBitrate = normToLong (m_pComboAudioBitrate->currentText());
		m_sourceFileInfo.pTranscodeInterface->iAudioBitrate = iBitrate;
		m_sourceFileInfo.pTranscodeInterface->iSample       = m_pComboAudioSampleRate->currentText ( ).toInt();
		m_sourceFileInfo.pTranscodeInterface->iStartingAt   = 0;
		m_sourceFileInfo.pTranscodeInterface->iEndingAt     = 0;
	}

	QDialog::accept ();
}

