
#include "windows.h"
#include "math.h"
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "uimanager.h"
#include "display.h"
#include "prefsXML.h"
#include "gigeapp.h"
#include "plathread.h"
#include "giged3d.h"
#include "config.h"
#include "devicemanager.h"
#include "framestore.h"
#include "lut3d.h"
#include "playlist.h"
#include "project.h"
#include "config.h"
#include "display.h"
#include "playwnd.h"
#include "buttoncb.h"
#include "logger.h"
#include <io.h>

extern void IncSwap(void);
extern bool OpenProject( char *filename );
extern void OnStartGrabbing( void );
extern char * TrimPath( char *str );
extern int ConfigAutoload( ECamRaster raster, ECamFramerate framerate, bool connect );
extern void FlushFiles( char volumeLetter );
extern void OnStopRecording( void );
extern void OnSetZoom( int zoomFactor );

extern CSIDSMediaFilePlayer *gSIPlayer;

CUIManager::CUIManager()
{
	mScreen = NULL;
	mIsPlaying = false;
}

CUIManager::~CUIManager()
{
	if ( mScreen ) delete mScreen;
}

bool CUIManager::Init( void )
{
	mScreen = new CUIScreen;
	mScreen->Init();
	gUIScreen = mScreen;
	return false;
}

void UtilGetProgramDir( char *inText )
{
	DWORD red = GetModuleFileName(
		NULL,
		inText,
		252
	);

	int len = (int)strlen(inText);
	char *cptr = inText + len;
	while ( *cptr != '\\' )
	{
		*cptr-- = 0;
	}

	cptr--;
	while ( *cptr != '\\' )
	{
		*cptr-- = 0;
	}
}


void CUIManager::Render( HDC hdc, bool clear )
{
	if ( !gD3D->CheckDevice() )
	{
		return;
	}

	bool doBlit = true;
	if ( mScreen->mFileDialog || 
		mScreen->mMacroListDialog || 
		mScreen->mKeyboard || 
		gIridas || 
		mScreen->mPrefs )
	{
		doBlit = false;
	}

	gD3D->RenderSceneStart( doBlit );

	if ( ! mScreen->mFileDialog && 
		 ! gUIManager->mScreen->mMacroListDialog  && 
		 ! mScreen->mPrefs && 
		 ! gUIManager->mScreen->mDisplayModesListDialog )
	{
#ifndef NO_DIRECTX_VIDEO

		if ( Globals.GetColorBars() )
			gD3D->RenderBars();
		else
		{
			gDisplay.RefreshBuffer( clear );
			if ( ( Globals.GetRecall() == GLOBALS_RECALL_100 || Globals.GetRecall() == GLOBALS_RECALL_50 ) && !Globals.GetIridasOn() )
				gD3D->RenderStore();
       		mScreen->RenderOverlayText();
		}
#endif
	}

	if ( ! ( Globals.GetMainMonitorMode() == MAIN_MONITOR_OFF ) )
		mScreen->Render();

	gD3D->RenderSceneEnd();
	gD3D->RenderSceneTwo();
}


void CUIManager::OnClick( int x, int y )
{
	mScreen->OnClick( x, y );
}

void CUIManager::OnRightClick( void )
{
	mScreen->OnRightClick();
}

void CUIManager::OnKeydown( DWORD key )
{
	mScreen->OnKeydown( key );
}

void CUIManager::OnVK( DWORD key )
{
	mScreen->OnVK( key );
}

void CUIManager::ToggleFullScreen( void )
{
	// Turn off loupe when switching between full screen and main GUI modes
	Globals.SetLoupeState( 0 );
	Globals.SetFocusCheck( false );

	EScreenMode mode = gUIManager->GetScreenMode();

	if ( mode == SCREEN_MODE_PLAY )
	{
		gUIManager->mScreen->mPlayFS->SetText( "EXIT" );
		gUIManager->SetPlayMode( true );
	}
	else if ( mode == SCREEN_MODE_PREVIEW )
	{
		gUIManager->mScreen->mPlayFS->SetText( "PLAY" );
		gUIManager->SetPlayMode( false );
	}

	mScreen->IncDisplayMode();
	gDisplay.ResetImageCoordinates();
	InvalidateRect( Globals.hwnd, NULL, false );
}

bool AddStereoFile( char *playbackPath, std::vector<char*> *SIVPlaybackPaths )
{
	if ( !isFile( playbackPath, "siv" ) )
        return false;

	int isStereo = gUtils->IsSIVStereoPair( playbackPath );
	if ( ( isStereo == SIV_FILE_CAM_LEFT ) || ( isStereo == SIV_FILE_CAM_RIGHT ) )
	{
        char * secondFile = playbackPath;
		gUtils->SwapCamABExt( secondFile );

		// If the second file of the stereo pair is the same directory as the primary file, add it to the vector
		FILE *file = fopen( secondFile, "rt" );
		if ( file )
		{
			SIVPlaybackPaths->push_back( secondFile );
			fclose( file );
			return true;
		}
		else if ( gProject )
		{
			// Else, look in the SIL file for the secondary recording directory
			char projectfilepath[ MAX_PATH ];
			char secondaryFileFromSIL[ 512 ];
			DWORD destSize = MAX_PATH;
					
			strcpy( projectfilepath, gPrefs.GetRecentProject() );
			GetPrivateProfileString( "dirs", "secondaryDir", "", secondaryFileFromSIL, destSize, projectfilepath );

			// If secondary directory path from project file is not found, use the temporary selected path
			if ( ! access( secondaryFileFromSIL, 0 ) == 0 )
			{
				strcpy( secondaryFileFromSIL, Globals.GetMatchingPairDir() );
			}
					
			char secondaryFileName[ MAX_PATH ];
			strcpy( secondaryFileName, secondaryFileFromSIL );
			strcat( secondaryFileName, "\\" );
			strcat( secondaryFileName, gUtils->TrimPath( secondFile ) );

			// If the second file of the stereo pair is found in the secondary recording directory, add it to the vector
			FILE *file = fopen( secondaryFileName, "rt" );
			if ( file )
			{
                strcpy( playbackPath, secondaryFileName );
				SIVPlaybackPaths->push_back( playbackPath );
				fclose( file );
				return true;
			}
			// If a project is loaded, and we need to load the matching pair from another directory,
			// pop up dialog and ask to manually select the file - this sets a temporary secondary player path.
			else
			{
				if ( ! Globals.GetMatchingPairMode() )
				{
					gUIScreen->OpenFindFileMatchDialog();
					Globals.SetMatchingPairMode( false );
				}
			}
		}
		else
		{
			// No second file of a stereo pair found, or no project loaded - pop up dialog and ask to manually select the file
			if ( ! Globals.GetMatchingPairMode() )
			{
				gUIScreen->OpenFindFileMatchDialog();
				Globals.SetMatchingPairMode( false );
			}
		}
	}
	else
	{
		// No stereo pair
		Globals.SetMatchingPairMode( false );
		return false;
	}
    return false;
}


void CUIManager::RefreshPlayList( char * path )
{
    gLogger.info( 0, "%d   CUIManager::RefreshPlayList\n", GetTickCount() );
	if ( mIsPlaying )
	{
		char location[ MAX_PATH ];
		if ( gProject )
		{
			gProject->GetDirectory( location );
			gLogger.info( 1, "%d   CUIManager::RefreshPlayList project location: %s\n", GetTickCount(), location );
		}
		else
		{
			strcpy( location, path );
			gLogger.info( 1, "%d   CUIManager::RefreshPlayList no project location: %s\n", GetTickCount(), location );
		}

		SetCurrentDirectory( location );
        gLogger.info( 0, "%d   CUIManager::RefreshPlayList A\n", GetTickCount() );
		gPlayList = new CPlayList( location, FILE_TYPE_VIDEO );
        gLogger.info( 0, "%d   CUIManager::RefreshPlayList B\n", GetTickCount() );
		char *latestFile = gPlayList->GetCurrent();

		if ( latestFile )
		{
			// Store the name of path of current file for playback
			char playbackPath [ 512 ];
			strcpy( playbackPath, location );
			strcat( playbackPath, "\\" );
			strcat( playbackPath, latestFile );
			Globals.SetCurrentPlaybackFile( playbackPath );

			strcat( location, "\\" );
			strcat( location, latestFile );

			if ( isFile( latestFile, "siv" ) )
			{
				char secondFile[ 512 ];
                std::vector<char*> *SIVPlaybackPaths = new std::vector<char*>();
            	SIVPlaybackPaths->push_back( playbackPath );
                strcpy(secondFile,playbackPath);
                bool res = AddStereoFile( secondFile, SIVPlaybackPaths );

				// If the second file of a stereo SIV pair cannot be found, resize the vector to 1
				if ( ! res )
				{
					SIVPlaybackPaths->resize( 1 );
				}

				gConfig.StartPlayingSIV( SIVPlaybackPaths );
                delete SIVPlaybackPaths;
			}
			else if ( isFile( latestFile, "avi" ) || isFile(latestFile, "mov") )
			{
                gLogger.info(0, "%d   CUIManager::RefreshPlayList C\n", GetTickCount() );
				gConfig.StartPlayingAVI( latestFile );
			}
			else
				assert(0);
		}
	}
}

void CUIManager::SetPlayMode( bool playOn )
{
    gLogger.info(0, "%d   CUIManager::SetPlayMode %d \n", GetTickCount(), playOn );
	if ( !mIsPlaying && playOn )
	{
		//Globals.SetSaveTimecode( *(Globals.GetTimecode()) );
		mIsPlaying = playOn;
		gConfig.StopGrabbing( false, false) ;
		Globals.SetColorBars( false );
		SetScreenMode( SCREEN_MODE_PLAY );

		// Disable CAM SETUP and LOAD LOOK modes when going into PLAY mode
		gUIScreen->SetCamSetupMode( false );
		gUIScreen->SetLoadLookMode( false );

		if ( gProject )
		{
			char location[256];
			gProject->GetDirectory(location);
			SetCurrentDirectory(location);
			gPlayList = new CPlayList( location, FILE_TYPE_VIDEO );
			char *latestFile = gPlayList->GetCurrent();

			if ( latestFile )
			{
				// Store the name of path of current file for playback
				char playbackPath [ 512 ];
				strcpy( playbackPath, location );
				strcat( playbackPath, "\\" );
				strcat( playbackPath, latestFile );
				Globals.SetCurrentPlaybackFile( playbackPath );

				strcat( location, "\\" );
				strcat( location, latestFile );

				if ( isFile( latestFile, "siv" ) )
				{
    				char secondFile[ 512 ];
                    std::vector<char*> *SIVPlaybackPaths = new std::vector<char*>();
                	SIVPlaybackPaths->push_back( playbackPath );
                    strcpy(secondFile,playbackPath);
                    bool res = AddStereoFile( secondFile, SIVPlaybackPaths );

					// If the second file of a stereo SIV pair cannot be found, resize the vector to 1
					if ( ! res )
					{
						SIVPlaybackPaths->resize( 1 );
					}

					gConfig.StartPlayingSIV( SIVPlaybackPaths );
                    delete SIVPlaybackPaths;
				}
				else if ( isFile( latestFile, "avi" ) || isFile(latestFile, "mov") )
				{
					gConfig.StartPlayingAVI( latestFile );
				}
				else
					assert(0);
			}
		}
	}
	else if ( mIsPlaying && !playOn )
	{
		mIsPlaying = playOn;

		if ( isProgramPlayingAVI() )
		{
			gConfig.StopPlayingAVI(false);
		}
		else if ( isProgramPlayingSIV() )
		{
			gConfig.StopPlayingSIV(false);
		}

		//Globals.SetTimecode( *(Globals.GetSaveTimecode()) );
		if ( isProgramConfigured() )
		{
            gLogger.info( 2, "%d   CUIManager::SetPlayMode() about to gConfig.StartGrabbing\n", GetTickCount());
			gConfig.StartGrabbing();
		}
		gUIScreen->mLookAsShot->SetActive( false );
		SetPreviewWB();
		gD3D->SetLut3DTextures();
		SetScreenMode( SCREEN_MODE_PREVIEW );
	}

	InvalidateRect( Globals.hwnd, NULL, false );
}

void CUIManager::TogglePlayMode( void )
{
	bool playOn = mIsPlaying;
	playOn ^= 1;
	SetPlayMode( playOn );
}

void CUIManager::SetScreenMode( EScreenMode mode )
{
	mScreen->SetScreenMode( mode );
}

EScreenMode CUIManager::GetScreenMode()
{
	return mScreen->mMode;
}

void CUIManager::OnReplacePlayerLookFile()
{
	if ( ( isProgramPlayingAVI() ) || ( isProgramPlayingSIV() ) )
	{
		gIridas->ReplacePlayerLookFile();
	}
}

void CUIManager::OnCustomExtMode()
{
	int mode = Globals.GetSplitZoomMode();

	if ( mode == CUSTOM_MODE_SPLIT_SCREEN )
	{
		gPrefs.SetDispExtMode( MODE3D_SPLITSCREEN );
	}
	else if ( mode == CUSTOM_MODE_EXT_HISTOGRAM )
	{
		gPrefs.SetHistogramExt( 1 );
	}
	else if ( mode == CUSTOM_MODE_ZOOM )
	{
		OnSetZoom( 4 );
	}
	else
	{
		// Reset settings
		gPrefs.SetDispExtMode( MODE3D_LEFT );
		OnSetZoom( 1 );
		gPrefs.SetHistogramExt( 0 );
		Globals.SetHistogramOn( false );
	}

	mode ++;
	if ( mode == CUSTOM_MODE_SPLIT_ZOOM_LAST )
	{
		mode = CUSTOM_MODE_SPLIT_ZOOM_NONE;
	}

	Globals.SetSplitZoomMode( mode );
}

extern void OnToggleZoom( void );
extern void OnToggleExposureMeter( void );
extern void OnStopRecording( void );


void OnDefectivePixelMap( int x, int y )
{
	gUIScreen->OpenDefectivePixelmapDialog();
}

void UpdateProgressDialog( int part, int whole, char * filename )
{
	gUIScreen->UpdateProgressDialog( part, whole, filename );
}

void OnIncDisplay3DMode( int x, int y )
{
	if ( Globals.GetDraw3D() )
	{
		// Disable 3D display modes if sobel is on
		if ( ! Globals.GetSobelOn() )
		{
			gUIScreen->IncDisplay3DMode();
		}
	}
	else
	{
		if ( isProgramRecording() )
		{
			return;
		}

		if ( gIrex )
		{
			int look = gPrefs.GetRecordLook();
			char * fileName = gPrefs.GetLookName( look );
			gUIScreen->LoadIridas( fileName, look );
		}
	}
}

void OnIncLeftRightMode(int x, int y)
{
	if ( Globals.GetDraw3D() )
	{
		gUIScreen->IncLeftRightMode();
	}
	else
	{
		if ( isProgramRecording() )
		{
			return;
		}

		Globals.SetSlatePreview();

		if ( Globals.GetSlatePreview() )
		{
			gUIScreen->mSlatePreview->SetHighlight( true );
		}
		else
		{
			gUIScreen->mSlatePreview->SetHighlight( false );
		}
	}
}

void OnToggleStatusbarMode( int x, int y )
{
	gUIScreen->ToggleStatusbarMode();
}

void OnRepairFile( int x, int y )
{
	gLogger.info( 1, "%s OnRepairFile x=%d y=%d\n", GetSystemTimeString(), x, y );
	gUIScreen->OpenRepairDialog();
}

void OnLoadClipInfoEditor( int x, int y )
{
	gUIScreen->LoadClipInfoEditor();
}


void OnCloseMetaDataCtrl()
{
	if ( isProgramPlayingAVI() )
	{
		gConfig.StopPlayingAVI( false );
	}
	else if ( isProgramPlayingSIV() )
	{
		gConfig.StopPlayingSIV( false );
	}

	char * file = Globals.GetCurrentPlaybackFile();
	if ( isFile( file, "siv" ) )
	{
		char secondFile[ 512 ];
        std::vector<char*> *SIVPlaybackPaths = new std::vector<char*>();
        SIVPlaybackPaths->push_back( file );
        strcpy( secondFile,file );
        bool res = AddStereoFile( secondFile, SIVPlaybackPaths );

		// If the second file of a stereo SIV pair cannot be found, resize the vector to 1
		if ( ! res )
		{
			SIVPlaybackPaths->resize( 1 );
		}

		gConfig.StartPlayingSIV( SIVPlaybackPaths );
        delete SIVPlaybackPaths;
	}
	else
	{
		gConfig.StartPlayingAVI( file );
	}
	gUIScreen->CloseMetaDataCtrl();
}

void OpenFileType( char *name, EFileType type)
{
	bool dualCamMode = false;
	int len = 0;
	switch( type )
	{
	case FILE_TYPE_SIL:
		{
			char fileDir[256];
			GetCurrentDirectory( 255, fileDir );
			strcat( fileDir, "\\" );
			strcat( fileDir, name );
			OpenProject( fileDir );
			gPrefs.SetRecentProject( fileDir );
            FlushFiles( Globals.GetSIDir()[0] );
			gPrefs.SetProjectData( false );
		}
		break;
	case FILE_TYPE_SII:
		char filePath[ 256 ];
		GetCurrentDirectory( 255, filePath );
		strcat( filePath, "\\" );
		strcat( filePath, name );

        SHOThread::UpdateFrameStore(filePath);
		
		if ( gIridas )
		{
			gIridas->mGreyOn = false;
			gIridas->mGreyMatte->SetHighlight( false );
		}
		break;
	case FILE_TYPE_LOOK:
		// We only want to handle look dialog click if IRIDAS sialog is not active
		if ( ! gIridas )
		{
			gLookDialog->HandleClick( 0, 0 );
		}
		else
		{
			gLut3d.LoadLook( gIridas->GetActiveLook(), name );
			gD3D->SetLut3DTextures();
		}
		break;
	case FILE_TYPE_SIC:
		char path[ 256 ];
		GetCurrentDirectory( 255, path );

		// Workaround to prevent double backslash when in root directory
		len = (int) strlen( path );
		if ( len != 3 )
		{
			strcat( path, "\\" );
		}
		strcat( path, name );

		// gUIScreen->mModesDialog->UpdateCustomFile( path );
		break;
	case FILE_TYPE_VIDEO:
		// Store the name of path of the selected file for playback
		char playbackPath [ 512 ];
		char currentDir [ 256 ];
		GetCurrentDirectory( 255, currentDir );
		strcpy( playbackPath, currentDir );
		strcat( playbackPath, "\\" );
		strcat( playbackPath, name );

		// Project directory
		char location[ 256 ];
		gProject->GetDirectory( location );

		if ( strcmp( location, currentDir ) != 0 )
		{
			gPlayList = new CPlayList( currentDir, FILE_TYPE_VIDEO );
		}

		if ( ! Globals.GetMatchingPairMode() )
		{
			Globals.SetCurrentPlaybackFile( playbackPath );
		}

		if ( isProgramPlayingAVI() )
		{
			gConfig.StopPlayingAVI(false);
		}
		else if ( isProgramPlayingSIV() )
		{
			gConfig.StopPlayingSIV(false);
		}

		if ( isFile( name, "avi" ) || isFile(name, "mov") )
		{
			gConfig.StartPlayingAVI( name );
		}
		else if ( isFile( name, "siv" ) )
		{
			char secondFile[ 512 ];
            std::vector<char*> *SIVPlaybackPaths = new std::vector<char*>();
			bool res = false;

			// For matching pair mode, retrieve the previously stored primary file, and add the currently selected matching file
			if ( Globals.GetMatchingPairMode() )
			{
				SIVPlaybackPaths->push_back( Globals.GetCurrentPlaybackFile() );
				SIVPlaybackPaths->push_back( playbackPath );
				Globals.SetMatchingPairMode( false );

				res = gUtils->IsSIVStereoPair( SIVPlaybackPaths );

				// If we don't have a valid SIV pair resize the vector to 1
				if ( ! res )
				{
					SIVPlaybackPaths->resize( 1 );
				}
			}
			else
			{
				SIVPlaybackPaths->push_back( playbackPath );
				strcpy( secondFile, playbackPath);
				res = AddStereoFile( secondFile, SIVPlaybackPaths );

				// If the second file of a stereo SIV pair cannot be found, resize the vector to 1
				if ( ! res )
				{
					SIVPlaybackPaths->resize( 1 );
				}
			}

			gConfig.StartPlayingSIV( SIVPlaybackPaths );
            delete SIVPlaybackPaths;
		}
		else
			assert(0);
		break;
	}
	Globals.SetPolledEvent( POLLED_EVENT_DELETEFILEDIALOG );
}


void OpenFileDialog( EFileType type, char *destText )
{
	gUIScreen->OpenFileDialog( type, destText );
}

void OpenMacroListDialog( DWORD index )
{
	gUIScreen->OpenMacroListDialog( index );
}

void OpenDisplayModesDialog( DWORD index )
{
	gUIScreen->OpenDisplayModesDialog( index );
}

void CloseKeyboard( char *text )
{
	gUIScreen->CloseKeyboard(text);
}

void ClosePrefs( bool doit )
{
	gUIScreen->ClosePrefs( doit );
}

void CloseBlack( bool doit, bool allGains )
{
	gUIScreen->CloseBlack( doit, allGains );
}

void CloseReconnect( bool doit, bool connect )
{
	gUIScreen->CloseReconnect( doit, true );
}

void CloseModes( bool doit, bool custom )
{
	if ( custom == true )
	{
		gUIScreen->CloseModes( doit, true );
	}
	else
	{
		gUIScreen->CloseModes( doit, false );
	}
}

void CloseSDIModes( bool doit )
{
	gUIScreen->CloseSDIModes( doit );
}

void OnNewProject(int,int )
{
	gUIScreen->NewProject();
}

void OnLoadIridasPlay( int, int )
{
	char lookName[ 256 ];
	int index = gPrefs.GetPlayerLook();
	strcpy( lookName, gPrefs.GetLookName( index ) );
	gUIScreen->LoadIridas( lookName, index );
}


void OnCloseRepairDialog( bool action )
{
	gUIScreen->CloseRepairDialog( action );
}

void OnCloseDefectivePixMapDialog( bool action )
{
	gUIScreen->CloseDefectivePixelmapDialog( action );
}

void OnCloseDlgFindFileMatch( bool action )
{
	gUIScreen->CloseDlgFindFileMatch( action );
}

void OnCloseMultiCamDialog( bool action )
{
	gUIScreen->CloseMultiCamDialog( action );
}

void OnCloseDPXExportOptions( bool action )
{
	// TODO: implement me please
}

void OnCamSetupMode( int, int )
{
	gUIScreen->OpenCamConnectionDialog( 0, "" );
}

void OnParallaxShift( int, int )
{
	int val = Globals.GetParallaxMode();
	val++;

	// Update UI controls
	gUIScreen->SetCamAlignMode( false );
	gUIScreen->mParallaxShift->SetHighlight( true );
	gUIScreen->mCamAlignModeBtn->SetHighlight( false );

	if ( val == PARALLAX_MODE_DIALOG )
	{
		gUIScreen->OpenParallaxShiftDlg();
	}

	// Cycle complete - close dialog
	if ( ( val > PARALLAX_MODE_DIALOG ) )
	{
		gUIScreen->mParallaxShift->SetHighlight( false );
		val = 0;
	}

    Globals.SetParallaxMode( val );
	InvalidateRect( Globals.hwnd, NULL, false );
}

void OnSDIModes( int, int )
{
	gUIScreen->OpenSDIModes();
	InvalidateRect( Globals.hwnd, NULL, false );
}

void On3DAlignmentSettings( int, int )
{
	if ( gUIScreen->mCamAlignModeBtn->GetHighlight() )
	{
		gUIScreen->SetCamAlignMode( false );
	}
	else
	{
		gUIScreen->SetCamAlignMode( true );
	}
	UpdateButtonStates();
}


void OnFlipCamA( int, int )
{
    gPrefs.IncFlip(0);
    gDisplay.mFlip[0] = gPrefs.GetFlip(0);
	SignalStereo();
}

void OnFlipCamB( int, int )
{
    gPrefs.IncFlip(1);
    gDisplay.mFlip[1] = gPrefs.GetFlip(1);
	SignalStereo();
}

void OnSaveLookFile(int,int )
{
	gIridas->OpenSaveLookFileDlg();
}

void OnLoadLooks(int,int )
{
	gUIScreen->LoadLooks();
}

void OnLoadMacros(int,int )
{
	gUIScreen->LoadMacros();
}

void OnLoadDispModes( int, int )
{
	gUIScreen->LoadDispModes();
}

void OnSendSerial(int,int )
{
	gUIScreen->SendSerial();
}

void OnAboutBox(int,int )
{
	gUIScreen->AboutBox();
}

void OnQualityCtrl( int, int )
{
	gUIScreen->mMessageBox = new CUIMessageBox( MB_TYPE_QC_INIT, 330, 260, 600, 220, "MessageBox" );
	gUIScreen->mMessageBox->Init( "Welcome to SiliconDVR-QC.", 
		                          "This application will perform a series of tests.", 
		                          "By clicking CONTINUE, you move to the next step.", 
								  "Clicking QUIT exits SiliconDVR." );
	InvalidateRect( Globals.hwnd, NULL, false );
}

void OnUpdateFirmware(int,int )
{
	if ( isProgramConfigured() )
	{
		gUIScreen->UpdateFirmware();
	}
}

void OnExitUtilityMenu(int,int )
{
	gUIScreen->SetUtilityMode( false );
}

void OnEnterUtilityMenu(int,int )
{
	gUIScreen->SetUtilityMode( true );
}

void OnShutterDialog(int,int )
{
	gUIScreen->ShutterDialog();
}

void OnTimecodeDialog(int,int )
{
	gUIScreen->TimecodeDialog();
}

void OnTimecode2Dialog(int,int )
{
	gUIScreen->Timecode2Dialog();
}

void OnDisplayPrefsDialog( int, int )
{
	gUIScreen->LoadDisplayPrefs();
}

void OnCloseDisplayPrefsDialog( bool action)
{
	gUIScreen->CloseDisplayPrefs( action );
}

void OnBlackCalibration( int, int )
{
	Globals.SetHighBlackLevel( false );
	if ( gUIScreen->mBlackDialog )
	{
		delete gUIScreen->mBlackDialog;
		gUIScreen->mBlackDialog = NULL;
	}

	extern CDevice *gDevice[];
	if ( ! gDeviceManager.GetDevice( 0 ) )
	{
		return;
	}
	gUIScreen->OnBlackDialog();
}

void OnMulticamMode( int, int )
{
	gUIScreen->OpenMultiCamDialog();
}

void OnSetWB3200( int, int )
{
	gUIScreen->mWhiteBalance3200->SetHighlight( true );
	gUIScreen->mWhiteBalance5600->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser1->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser2->SetHighlight( false );
	SetWB( PREFS_WB_3200K );
}

void OnSetWB5600( int, int )
{
	gUIScreen->mWhiteBalance3200->SetHighlight( false );
	gUIScreen->mWhiteBalance5600->SetHighlight( true );
	gUIScreen->mWhiteBalanceUser1->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser2->SetHighlight( false );
	SetWB( PREFS_WB_5600K );
}

void OnSetWBUser1( int, int )
{
	gUIScreen->mWhiteBalance3200->SetHighlight( false );
	gUIScreen->mWhiteBalance5600->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser1->SetHighlight( true );
	gUIScreen->mWhiteBalanceUser2->SetHighlight( false );
	SetWB( PREFS_WB_USER_1 );
}

void OnSetWBUser2( int, int )
{
	gUIScreen->mWhiteBalance3200->SetHighlight( false );
	gUIScreen->mWhiteBalance5600->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser1->SetHighlight( false );
	gUIScreen->mWhiteBalanceUser2->SetHighlight( true );
	SetWB( PREFS_WB_USER_2 );
}

void OnLoadAsShot( int, int )
{
	int activeLook = gPrefs.GetPlayerLook();
	gUIManager->LoadLook( 4 );
}

void OnLoadLookA( int, int )
{
	gUIManager->LoadLook( 0 );
}

void OnLoadLookB( int, int )
{
	gUIManager->LoadLook( 1 );
}

void OnLoadLookC( int, int )
{
	gUIManager->LoadLook( 2 );
}

void OnLoadLookD( int, int )
{
	gUIManager->LoadLook( 3 );
}

void CUIManager::LoadLook( int mIndex )
{
	if ( isProgramPlayingAVI() || isProgramPlayingSIV() )
	{
		gPrefs.SetPlayerLook( mIndex );
	}
	else if ( gPrefs.GetPreviewLookActive() )
	{
		gPrefs.SetViewLook( mIndex );
	}
	else
	{
		gPrefs.SetRecordLook( mIndex );
	}
	gUIManager->UpdateLookButtonStates( mIndex );
	gD3D->SetLut3DTextures();
	if ( gPrefs.GetSdiMode() )
	{
		static char lookpath[256];
		strcpy(lookpath,Globals.GetSIDir());
		strcat(lookpath,gLut3d.GetCurrentLookFile());
		gSdiThread->mLookPath = lookpath;
        gLogger.info(1,"%s   Signalling SDI thread with new look.\n",
			Globals.GetPrettyHighResClockString());
        SetEvent(gSdiSignal);
	}
	InvalidateRect( Globals.hwnd, NULL, false );
}

void CUIManager::UpdateLookButtonStates( int mIndex )
{
	gUIScreen->mLookAsShot->SetHighlight( false );
	gUIScreen->mLoadLookBtnA->SetHighlight( false );
	gUIScreen->mLoadLookBtnB->SetHighlight( false );
	gUIScreen->mLoadLookBtnC->SetHighlight( false );
	gUIScreen->mLoadLookBtnD->SetHighlight( false );

	switch ( mIndex )
	{
		case 0:
			gUIScreen->mLoadLookBtnA->SetHighlight( true );
			break;
		case 1:
			gUIScreen->mLoadLookBtnB->SetHighlight( true );
			break;
		case 2:
			gUIScreen->mLoadLookBtnC->SetHighlight( true );
			break;
		case 3:
			gUIScreen->mLoadLookBtnD->SetHighlight( true );
			break;
		case 4:
			gUIScreen->mLookAsShot->SetHighlight( true );
			break;
		default:
			break;
	}
}

void OnPlayStepBack( int, int )
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent( CUIIconButton::kIconStepBack );
	}
	else if ( isProgramPlayingSIV() )
	{
		if( gPlaThread )
		{
			gPlaThread->SetState( PLAY_STATE_STEP_BACK );
		}
	}
}

void OnPlayPlay(int, int)
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent(CUIIconButton::kIconPlay);
	}
	else if ( isProgramPlayingSIV() )
	{
		if ( gPlaThread && gPlaThread->mPlayState != PLAY_STATE_PLAY )
		{
			gPlaThread->SetState( PLAY_STATE_PLAY );
		}
	}
}

void OnPlayFastForward(int, int)
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent(CUIIconButton::kIconFastForward);
	}
}

void OnPlayPause(int, int)
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent(CUIIconButton::kIconPause);
	}
	else if ( isProgramPlayingSIV() )
	{
		if( gPlaThread )
		{
			if ( gPlaThread->mPlayState == PLAY_STATE_PLAY )
				gPlaThread->SetState( PLAY_STATE_PAUSE );
		}
	}
}


void OnPlayStepForward(int, int)
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent(CUIIconButton::kIconStepForward);
	}
	else if ( isProgramPlayingSIV() )
	{
		if( gPlaThread )
		{
			gPlaThread->SetState( PLAY_STATE_STEP_FORWARD );
		}
	}
}

void OnPlayNext(int, int)
{
	gUIManager->mScreen->OnIncPlay( 1 );
}

void OnPlayPrevious(int, int)
{
	gUIManager->mScreen->OnIncPlay( -1 );
}

void OnPlayFastBack(int, int)
{
	if ( isProgramPlayingAVI() )
	{
		gPlayWnd.AviHandleButtonEvent(CUIIconButton::kIconFastBack);
	}
}

void UpdateButtonStates(void)
{
	gUIManager->mScreen->UpdateButtonStates();
}




