//Based on FLIR script by Gachopin

_vehicle = vehicle(player);

disableSerialization;

sleep 0.1;

if (_this select 1 == "off") exitWith 
{
	call FLIROFF;
};

if (_this select 1 == "on") exitWith 
{
	hint localize "@STR_DN_FLIRON";

	_aperture = -1;

	_daytime = round daytime;
	switch (_daytime) do 
	{
		case 0:{_aperture = 0.05;setaperture _aperture;};
		case 1:{_aperture = 0.1;setaperture _aperture;};
		case 2:{_aperture = 0.1;setaperture _aperture;};
		case 3:{_aperture = 0.1;setaperture _aperture;};
		case 4:{_aperture = 0.1;setaperture _aperture;};
		case 5:{_aperture = 0.1;setaperture _aperture;};
		case 6:{_aperture = 1.0;setaperture _aperture;};
		case 7:{_aperture = 4.0;setaperture _aperture;};
		case 8:{_aperture = 12.0;setaperture _aperture;};
		case 9:{_aperture = 23.0;setaperture _aperture;};
		case 15:{_aperture = 25.0;setaperture _aperture;};
		case 16:{_aperture = 14.0;setaperture _aperture;};
		case 17:{_aperture = 4;setaperture _aperture;};
		case 18:{_aperture = 1;setaperture _aperture;};
		case 19:{_aperture = 0.03;setaperture _aperture;};
		case 20:{_aperture = 0.03;setaperture _aperture;};
		case 21:{_aperture = 0.03;setaperture _aperture;};
		case 22:{_aperture = 0.03;setaperture _aperture;};
		case 23:{_aperture = 0.05;setaperture _aperture;};
		case 24:{_aperture = 0.05;setaperture _aperture;};
		default {_aperture = 35.0;setaperture _aperture;};
	};

	_color = "white";
	_vehicle setvariable ["FLIR",[_aperture,_color]];

	call FLIRON;


	_displayEH_keydown = (finddisplay 46) displayaddeventhandler ["keydown","

		_key = _this select 1;

		switch (_key) do 
		{
			case 42:{if (cameraView == ""GUNNER"") then {call FLIRREVERSE;};};
			case 72:{if (cameraView == ""GUNNER"") then {call FLIRBRIGHTUP;};};
			case 80:{if (cameraView == ""GUNNER"") then {call FLIRBRIGHTDOWN;};};
		};
	"];


	for [{_loop=0}, {_loop<1}, {_loop=_loop}] do
	{
		if (ch_m1abrams_TermicVision == 0 || vehicle player == player || (vehicle player) animationPhase "HatchCommander" > 0 || !(gunner (vehicle player) == player || commander (vehicle player) == player) || !(alive player)) then
		{
			[_vehicle, "off"] execVM "\ch_m1abrams_cfg\scripts\flir_main.sqf"; ch_m1abrams_TermicVision = 0;
			(finddisplay 46) displayRemoveEventHandler ["keydown", _displayEH_keydown];
			hint "";
			_loop=1;
		};

		if (ch_m1abrams_TermicVision == 1 && cameraView != "GUNNER") then
		{
			call FLIROFF;
		} else 

		{
			if (ch_m1abrams_TermicVision == 1 && cameraView == "GUNNER") then
			{
				if ((_vehicle getvariable "FLIR" select 1) == "white") then {call FLIRON;} else {call FLIRBLACK;};

				setaperture (_vehicle getvariable "FLIR" select 0);
			};
		};

	sleep 0.1;

	};
};