-- 	*** vSpeedCallouts v1.10 by ManosK - copyright 2017 - 2021 *** --
--  *** Forum link: http://forums.x-plane.org/index.php?/files/file/38144-vspeedcallouts-by-m/ *** --
--  *** Sounds created with NaturalReader - and further tweaked by me *** --

-- 	*** vSpeedCallouts was originally based on the script: 
		--- IXEG vSpeed Beta v0.110 by Wizball / Tom Stian - 2017
		--- Forum: http://forums.x-pilot.com/forums/topic/12002-vspeed-callouts-for-ixeg-733-lua-script/

-- *** but heavily extended in a form that can accommodate a number of aircrafts, from Airliners to General Aviation
-- *** However, this script is mostly targeted for airliners and best suited for the following: *** --
-- 		Aircraft			Design Studio/Team 				Authors

-- 		Boeing B738-800		Laminar Research	
-- 		x737-800_v503		x737project,EADT				Benedikt Stratmann, Pierre Stone
-- 		Boeing B738-800X	Laminar Research mod by Zibo	Alex Unruh

-- *** ... but in manual mode works for... just about every aircraft ! *** --

-- *** In order to manually adjust the v-Speeds just click on the relative panel BUG settings *** --
-- *** You can also assign a keyboard shortcut such as Alt+v from X-Plane's Keyboard settings, in order to toggle the view of the panel *** --
-- *** FlyWithLua Macros can also be used to toggle the panel view or disable the 80 Knots and Gear Up callouts


-- While at first this script was only intended for airliners (hence the following commented out line of code), then I just thought that it 
-- would be nice not to restrict it, since it supports manual input !
-- if (PLANE_ICAO == "B738") or (PLANE_ICAO == "B744") or (PLANE_ICAO == "B741") or (PLANE_ICAO == "MD82") then


-- ********************** --
--        SETTINGS        -- 
-- ********************** --
function file_exists(file)
  local f = io.open(file, "rb")
  
  if f then f:close() end
  return f ~= nil
end

function read_file(file)
  if not file_exists(file) then 
	logMsg("- Preferences file "..file.." not found! -")
	return {} 
  end
  
  logMsg("- Preferences file "..file.." found! -")
  
  tableValues = {}

  for line in io.lines(file) do 
	if string.sub(line,1,2) ~= '--' then tableValues[#tableValues + 1] = line end
  end
  logMsg("- Preferences file read! -")
  return tableValues
end

-- -- Initialize preferences
local preferences_FileName = SCRIPT_DIRECTORY .. "preferences.cfg"

function get_Preferences(fileName)
	local preferencesTable = read_file(fileName)
	local pref_Settings_lines = {}
	
	for i,j in pairs(preferencesTable) do
		local pref_Settings_words = {}
		
		for value in j:gmatch("[^=]+") do 
			table.insert(pref_Settings_words, value)
			
		end 
		table.insert(pref_Settings_lines, pref_Settings_words)

-- print all line numbers and their contents	  
	  logMsg('[' .. i .. '] - ' .. pref_Settings_lines[i][1]..' = '..pref_Settings_lines[i][2])
	  
	end
	return pref_Settings_lines
--	preferencesTable = nil
end

prefTable = get_Preferences(preferences_FileName)

function findSetting(searchTable, setting)
	for i=1,#searchTable do
		if searchTable[i][1] == setting then
			if searchTable[i][2] == 'activate' then
				return true
			else
				return false
			end
		end
	end
  return nil
end

function findSettingPos(searchTable, setting)
	for i=1,#searchTable do
		if searchTable[i][1] == setting then
		  return i
		end
	end
  return nil
end

function setSettingNewValue(setting, newValue)
	local p = findSettingPos(prefTable, setting)
	logMsg ('Setting position = '..p)
	prefTable[p][2] = newValue
	logMsg (prefTable[p][1]..'='..newValue)
end
 
function ActivateSetting(settingStr)
	setSettingNewValue(settingStr, 'activate')
	if not onload then savePreferences(prefTable) end
	logMsg (settingStr..' is now activate')
end

function DeactivateSetting(settingStr)
	setSettingNewValue(settingStr, 'deactivate')
	if not onload then savePreferences(prefTable) end
	logMsg (settingStr..' is now deactivate')
end

function setCommandState(preference)
	if preference then 
		return 'activate' 
	else
		return 'deactivate'
	end
end

function savePreferences(t)

   local file = assert(io.open(preferences_FileName, "w"))
   
   for i=1,#t do
		str = t[i][1]..'='..t[i][2]
		file:write(str.."\n")
	end
   file:close()
end

-- true and false have to be written with lowercase letters.

-- Set to true to enable "V2" callout and false to disable it.
Enable_V2 = findSetting(prefTable, 'Enable_V2')

-- Set to true to individually enable "80 Knots" callout and false to disable it.
Enable_80Kts = findSetting(prefTable, 'Enable_80Kts')

-- Set to true to individually enable "80 Knots" callout and false to disable it.
Enable_100Kts = findSetting(prefTable, 'Enable_100Kts')

-- Set to true to enable "Positive rate/Gear up" callout and false to disable.
EnablePosGearUp = findSetting(prefTable, 'EnablePosGearUp')

-- "80 Knots" and "Positive rate/Gear up" callouts can be mutually enabled/disabled by the relative macro in the FlyWithLua Macros

-- Change "SoundLevel" to adjust volume for the callouts. Adjust between 0.10 min - 1.00 max 
SoundLevel = 0.8

-- Toggles the display of the values panel. Also controlled by the FlyWithLua Macros, as well as the assigned keyboard command "Display vSpeed values toggle"
show_values = findSetting(prefTable, 'show_values')

-- Toggles the 10,000ft in the climb or descent annunciation. Also controlled by the FlyWithLua Macros
pass_10Kft = findSetting(prefTable, 'pass_10Kft')

-- Toggles the automatic switch-on and switch-off of the landing lights at 10,000ft. Also controlled by the FlyWithLua Macros
auto_lights = findSetting(prefTable, 'auto_lights')

-- Toggles the 60Knots manual breaks annunciation when landing. Also controlled by the FlyWithLua Macros
manual_Breaks = findSetting(prefTable, 'manual_Breaks')

-- Toggles the Gear Down annunciation when landing. Also controlled by the FlyWithLua Macros
Gear_Down = findSetting(prefTable, 'Gear_Down')

-- 10K Feet Switch for enabling correct Gear Down annunciation
TenKFeetSwitch = findSetting(prefTable, 'TenKFeetSwitch')

-- *************************** --
-- DO NOT EDIT BELOW THIS LINE --
-- *************************** --

require("graphics")

function sleep(a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end -- end function sleep()

V1_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/V1.wav")
VR_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/Rotate.wav")
V2_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/V2.wav")
KTS80_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/80knots.wav")
KTS100_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/100knots.wav")
PosGearUp_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/PosRateGearUp.wav")
Pass10KLightsOn_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/Pass10000LightsOn.wav")
Pass10KLightsOff_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/Pass10000LightsOff.wav")
ManualBreaks60KTS_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/60KnotsManualBrakes.wav")
GearDown_Sound = load_WAV_file(SCRIPT_DIRECTORY .. "vSpeed_Sounds/GearDown.wav")

set_sound_gain(V1_Sound, SoundLevel)
set_sound_gain(VR_Sound, SoundLevel)
set_sound_gain(V2_Sound, SoundLevel)
set_sound_gain(KTS80_Sound, SoundLevel)
set_sound_gain(KTS100_Sound, SoundLevel)
set_sound_gain(PosGearUp_Sound, SoundLevel)
set_sound_gain(Pass10KLightsOn_Sound, SoundLevel)
set_sound_gain(Pass10KLightsOff_Sound, SoundLevel)
set_sound_gain(ManualBreaks60KTS_Sound, SoundLevel)
set_sound_gain(GearDown_Sound, SoundLevel)

local V1_value
local VR_value
local V2_value

local manualVSpeeds = false
local userInputActivated = false
local sValue = ""
local manualVSpeedParam = 0
local aircraft = ""
local x737800SPDREF = false

function getAircraftName()
local t = {}                   -- table to store the indices
local i = 0

    while true do
      i = string.find(AIRCRAFT_PATH, "/", i+1)    -- find next "/" pattern in path
      if i == nil then break end
      table.insert(t, i)
    end

	aircraft = AIRCRAFT_PATH:sub(t[table.maxn(t)-1] + 1,AIRCRAFT_PATH.len(AIRCRAFT_PATH) - 1)

	if aircraft:sub(0, 8) == "x737-800" then aircraft = aircraft:sub(0, 8) end
	
	if string.upper(string.sub(aircraft,1,9)) == "TOLISS319" then aircraft = "tolissa319" end -- hummelmose's addition for Toliss A319
	-- current version (V1p3p1) has TOLISSA321 not TOLISS321:
	-- if string.upper(string.sub(aircraft,1,9)) == "TOLISS321" then aircraft = "tolissa321" end -- addition for Toliss A321
	if string.upper(string.sub(aircraft,1,10)) == "TOLISSA321" then aircraft = "tolissa321" end -- addition for Toliss A321

	if PLANE_ICAO == "B77W" or PLANE_ICAO == "B772" or PLANE_ICAO == "B77L" or PLANE_ICAO == "B77F" then aircraft = "FF777" end -- katyjason's addition for FlightFactor 777

	t = nil
	i = nil

end -- end function getAircraftName()

getAircraftName()
logMsg("vSpeedCallouts aircraft type: "..aircraft)

dataref( "AUTHOR", "sim/aircraft/view/acf_author", "readonly", 0)
logMsg(AUTHOR)

-- *** For future use. Detection of an active X-FMC plugin *** --
-- dataref( "X_FMC_ISACTIVE", "xfmc/Status", "readonly")
-- logMsg(X_FMC_ISACTIVE)

dataref( "IAS", "sim/cockpit2/gauges/indicators/airspeed_kts_pilot", "readonly")
dataref( "GS", "sim/flightmodel/position/groundspeed", "readonly")
dataref( "AGL", "sim/flightmodel/position/y_agl", "readonly")
dataref( "VSI", "sim/cockpit2/gauges/indicators/vvi_fpm_pilot", "readonly") 
dataref( "IALT", "sim/cockpit2/gauges/indicators/altitude_ft_pilot", "readonly")
dataref( "THROTTLE", "sim/cockpit2/engine/actuators/throttle_ratio_all", "readonly")
dataref( "REVTHROTTLE", "sim/cockpit2/engine/actuators/throttle_beta_rev_ratio_all", "readonly")
dataref( "GEARSTATUS", "sim/flightmodel2/gear/deploy_ratio", "readonly", 0)
-- gearStatus_table = dataref_table( "sim/flightmodel2/gear/deploy_ratio" )
-- GEARSTATUS = gearStatus_table [0]

-- copied from A319_Custom_cmnd.lua.TXT (https://forums.x-plane.org/index.php?/forums/topic/201877-keybinding-lights/)
if aircraft == "tolissa321" then
  LIGHTS = dataref_table("AirbusFBW/OHPLightSwitches")
end
if aircraft == "AirbusA350" then
  LIGHTS = dataref_table("sim/cockpit2/switches/landing_lights_switch")
end

if aircraft == "B737-800X" then
	dataref( "FMC_REF", "laminar/B738/fmc1/Line00_L","readonly", 5)
	dataref( "FMC_REF_PAGE", "laminar/B738/fmc1/Line00_S","readonly", 0)
	dataref( "BUG_V1", "laminar/B738/fmc1/Line01_L","readonly", 0)
	dataref( "BUG_VR", "laminar/B738/fmc1/Line02_L","readonly", 0)
	dataref( "BUG_V2", "laminar/B738/fmc1/Line03_L","readonly", 0)
end

if aircraft == "x737-800" then
	dataref( "BUG_V1", "x737/systems/SPDREF/manual_v1","readonly")
	dataref( "BUG_VR", "x737/systems/SPDREF/manual_vR","readonly")
	dataref( "BUG_V2", "x737/systems/SPDREF/manual_v2","readonly")
	
	-- For future use. Detection if using the default x737-800 FMS *** --
	-- dataref( "USE_DEFAULT_FMC", "x737/systems/FMC/useDefaultFMS", "readonly")
	-- if USE_DEFAULT_FMC then manualVSpeeds=true end
	-- logMsg(USE_DEFAULT_FMC)
end 

if aircraft == "A350_FlightFactor" or aircraft == "A320_FlightFactor" then -->datarefs by Oliver 
-- CAUTION: you need the A320 Connector Script from FlightFactor, otherwise it won't work !!!
    dataref( "FFA320_V1", "MOKNY/FFA320/Aircraft/TakeoffDecision","readonly")
    dataref( "FFA320_VR", "MOKNY/FFA320/Aircraft/TakeoffRotate","readonly")
    dataref( "FFA320_V2", "MOKNY/FFA320/Aircraft/TakeoffReference","readonly")
    dataref( "FFA320_IAS", "MOKNY/FFA320/Aircraft/AirSpeed","readonly")

end 

-- disabled, PMCO doing call-outs now:
if aircraft == "tolissa319" or aircraft == "_tolissa321" then -->datarefs by hummelmose
	-- logMsg("- vSpeedCallouts aircraft type: A321")
    dataref( "BUG_V1", "toliss_airbus/performance/V1","readonly")
    dataref( "BUG_V2", "toliss_airbus/performance/V2","readonly")
    dataref( "BUG_VR", "toliss_airbus/performance/VR","readonly")
end 
 
-- new section for FF A350 using dataref tool (disabled, PMCO doing call-outs now):
if aircraft == "_AirbusA350" then
	logMsg("- vSpeedCallouts aircraft type: A359")
	dataref( "FFA350_V1", "1-sim/fms/perf/speed/v1","readonly")
    dataref( "FFA350_VR", "1-sim/fms/perf/speed/vr","readonly")
    dataref( "FFA350_V2", "1-sim/fms/perf/speed/v2","readonly")
    dataref( "FFA350_IAS", "AirbusFBW/IASCapt","readonly")
-- possible alternate for IAS:
--  dataref( "FFA350_IAS", "sim/flightmodel/position/indicated_airspeed","readonly")
end	

if aircraft == "FF777" then -->datarefs by katyjason
		dataref( "BUG_V1", "T7Avionics/fms/v1","readonly")
		dataref( "BUG_VR", "T7Avionics/fms/vr","readonly")
		dataref( "BUG_V2", "T7Avionics/fms/v2","readonly")
end 


function assignVSpeedsFromUserInput()
	if aircraft == "x737-800" then
		set( "x737/systems/SPDREF/manual_v1",V1_value)
		set( "x737/systems/SPDREF/manual_vR",VR_value)
		set( "x737/systems/SPDREF/manual_v2",V2_value)
		set( "x737/systems/SPDREF/mode", 1) -- set SPDREF mode in V1 so that V1 and VR speeds are displayed in PFD 
	end
end -- end function assignVSpeedsFromUserInput()


function getVSpeedsFromFMC()
	if aircraft == "B737-800X" then
		if string.find(FMC_REF, "TAKEOFF REF") ~= nil and string.find(FMC_REF_PAGE, "1/2") ~= nil  then
			V1_value = tonumber(BUG_V1:sub(22,24))
			VR_value = tonumber(BUG_VR:sub(22,24))
			V2_value = tonumber(BUG_V2:sub(22,24))
		end
	end
	-- disabled, PMCO doing call-outs now:
	if aircraft == "x737-800" or aircraft == "tolissa319" or aircraft == "_tolissa321" then --> V speed adjustments by hummelmose for tolissa319
		-- logMsg("- vSpeedCallouts #337 aircraft type: A321")
		V1_value = BUG_V1
		VR_value = BUG_VR
		V2_value = BUG_V2
	end
	
	if aircraft == "A350_FlightFactor" or aicraft == "A320_FlightFactor" then --> V speed adjustments by Oliver
--		logMsg("- FFA320_V1: "..FFA320_V1)
--		logMsg("- FFA320_VR: "..FFA320_VR)
        V1_value = math.floor(FFA320_V1 * 1.943844547019393)
        VR_value = math.floor(FFA320_VR * 1.943844547019393)
        V2_value = math.floor(FFA320_V2 * 1.943844547019393)
        IAS = math.floor(FFA320_IAS * 1.943844547019393)
    end 
	-- disabled, PMCO doing call-outs now:
	if aircraft == "_AirbusA350" then
        V1_value = FFA350_V1
        VR_value = FFA350_VR
        V2_value = FFA350_V2
        IAS = FFA350_IAS
-- these will fill log in loop, only enable temporarily:
--		logMsg("- vSpeedCallouts #366 aircraft type: A359")
--		logMsg("- V1_value: "..V1_value)
--		logMsg("- VR_value: "..VR_value)
--		logMsg("- IAS: "..IAS)
	end
	
	if aircraft == "FF777" then --> V speed adjustments by katyjason
		V1_value = math.floor(BUG_V1 + 0.5)
		VR_value = math.floor(BUG_VR + 0.5)
		V2_value = math.floor(BUG_V2 + 0.5)
	end
	
	if (V1_value == nil or V1_value == -1) then V1_value = 0 end
	if (VR_value == nil or VR_value == -1) then VR_value = 0 end 
	if (V2_value == nil or V2_value == -1) then V2_value = 0 end
	if (IAS == nil or IAS == -1) then IAS = 0 end
	if (GS == nil or GS == -1) then GS = 0 end
	if (AGL == nil or AGL == -1) then AGL = 0 end
	
end -- end function getVSpeedsFromFMC()

getVSpeedsFromFMC()

-- *** log initial values for debugging purposes *** --
logMsg("*** VSpedCallouts initial values ***")
logMsg("V1_value: "..V1_value)
logMsg("VR_value: "..VR_value)
logMsg("V2_value: "..V2_value)
logMsg("IAS: "..IAS)
logMsg("GS: "..GS)
logMsg("AGL: "..AGL)


PlayedKTS80 = false
PlayedKTS100 = false
PlayedV1 = false
PlayedVR = false
PlayedV2 = false
PlayedPosGear = false
PlayedPass10KLightsOn = false
PlayedPass10KLightsOff = false
SwitchedLightsOn = true
SwitchedLightsOff = false
PlayedManualBreaks = false
PlayedGearDown = false


local window_x = 150	-- Display position from right edge of window
local window_y = 250	-- Display position from top edge of window


-- *** Experimental. Examining the use of jjjLib1 *** --
-- local vSpeedPanel_plId = jjjLib1.getPlId("vSpeedCallouts")
-- local vSpeedPanel = false

function display_values_panel()
	if show_values then 
		
--		if MOUSE_STATUS ~= nil then draw_string(400, 400, "Status: "..MOUSE_STATUS.." / ".."X: "..MOUSE_X.." Y: "..MOUSE_Y.." window_x: "..window_x.." window_y: "..window_y) end
		
		XPLMSetGraphicsState(0,0,0,1,1,0,0)
		
		-- draw the title
		graphics.set_color(0, 0, 0, 1)
		graphics.draw_rectangle(SCREEN_WIDTH - window_x + 10, SCREEN_HIGHT - window_y + 200, SCREEN_WIDTH - window_x + 180, SCREEN_HIGHT - window_y + 220)
		graphics.set_color(1, 1, 1, 0.8)
		draw_string_Helvetica_18(SCREEN_WIDTH - window_x + 15, SCREEN_HIGHT - window_y + 202, "vSpeedCallouts")		
		
		-- draw the transparent background
		graphics.set_color(0, 0, 0, 0.5) 
		graphics.draw_rectangle(SCREEN_WIDTH - window_x + 10, SCREEN_HIGHT - window_y + 60, SCREEN_WIDTH - window_x + 180, SCREEN_HIGHT - window_y + 200)
		
		-- draw the parameters
		graphics.set_color(1, 1, 1, 0.8)
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 180, "GS: "..math.floor(GS).." m/sec")
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 160, "IAS: "..math.floor(IAS).." Kts")
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 140 , "AGL: "..math.floor(AGL).." m / "..math.floor(AGL*3.28084).." ft")
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 120, "BUG_V1: "..V1_value)
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 100, "BUG_VR: "..VR_value)
		draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 20, SCREEN_HIGHT - window_y + 80, "BUG_V2: "..V2_value)
		
		-- *** Experimental. Examining the use of jjjLib1 *** --
		-- jjjLib1.setColor("blue", false, false, true, false, 0.9)
		-- vSpeedPanel = jjjLib1.createPanel(vSpeedPanel_plId, "vSpeeds", 870, "", "blue", true)
		-- jjjLib1.setPanelPos(vSpeedPanel_plId, vSpeedPanel, SCREEN_WIDTH - 870, SCREEN_HIGHT - 180)
		
  end
end -- end function display_values_panel()

		-- *** Experimental. Examining the use of jjjLib1 *** --
		-- jjjLib1.openPanel(vSpeedPanel_plId,vSpeedPanel)

function DrawVSpeedInputLine(vSpeedParam) -- Modified function based on the FlyWithLua Internals

	if not userInputActivated then return end
	
	local yOffset = 0
	
	if vSpeedParam == 1 then yOffset = 0 end
	if vSpeedParam == 2 then yOffset = 20 end
	if vSpeedParam == 3 then yOffset = 40 end
	
	-- draw the background
	XPLMSetGraphicsState(0,0,0,1,1,0,0)
	
	glColor4f(0,0,0,1)
	glRectf(SCREEN_WIDTH - window_x + 102, SCREEN_HIGHT - window_y + 115 - yOffset, SCREEN_WIDTH - window_x + 140, SCREEN_HIGHT - window_y + 135 - yOffset)
	
	-- draw the input field
	glColor4f(0, 1, 0, 1)
	draw_string_Helvetica_12(SCREEN_WIDTH - window_x + 105, SCREEN_HIGHT - window_y + 120 - yOffset, sValue)
	
	-- draw cursor
	glColor4f(1,1,1,1)
	glBegin_LINES()
	local x_pos = SCREEN_WIDTH - window_x + 105 + measure_string(sValue, "Helvetica_12")
	glVertex2f(x_pos, SCREEN_HIGHT - window_y + 135 - yOffset)
	glVertex2f(x_pos, SCREEN_HIGHT - window_y + 135 - yOffset - 20)
	glEnd()
end -- end function DrawVSpeedInputLine()


function GetVSpeedLineFromKeyboard() -- Modified function based on the FlyWithLua Internals

	if userInputActivated and KEY_ACTION == "pressed" then
		RESUME_KEY = true
		-- escape
		if VKEY == 27 then
			sValue = ""
			userInputActivated = false
			return
		end
		-- backspace
		if VKEY == 8 and sValue ~= "" then
			sValue = string.sub(sValue, 1, string.len(sValue)-1)
			return
		end
		-- enter
		if VKEY == 13 then
			if sValue ~= "" then
				--assert(loadstring(sValue))()
				if manualVSpeedParam == 1 then
					V1_value = tonumber(sValue)
				elseif manualVSpeedParam == 2 then
					VR_value = tonumber(sValue)
				else
					V2_value = tonumber(sValue)
				end	
				assignVSpeedsFromUserInput() 
			end
			sValue = ""
			userInputActivated = false
			return
		end
		-- any other number key
		if (VKEY >= 48 and VKEY <= 59) or (VKEY >= 96 and VKEY <= 105) then sValue = sValue .. CKEY end
	end
end -- end function GetVSpeedLineFromKeyboard()


function activateUserInput()
	if show_values then -- if panel is visible
		
		if not userInputActivated and MOUSE_X >= SCREEN_WIDTH - window_x - 40 and MOUSE_X <= SCREEN_WIDTH - window_x + 180 and MOUSE_Y >= SCREEN_HIGHT - window_y + 150 and MOUSE_Y <= SCREEN_HIGHT - window_y + 270 then 
		
			if MOUSE_STATUS == "up" then 
				RESUME_MOUSE_CLICK = false
			else
				RESUME_MOUSE_CLICK = true
			end
						
			if MOUSE_STATUS == "drag" then  
				if MOUSE_X < SCREEN_WIDTH - 92 and MOUSE_X > 45 then window_x = SCREEN_WIDTH - MOUSE_X + 65 end
				if MOUSE_Y < SCREEN_HIGHT - 32 and MOUSE_Y > 150 then window_y = SCREEN_HIGHT - MOUSE_Y + 210 end 				
			end
		end
	
		if not userInputActivated and MOUSE_STATUS ~= "drag" and MOUSE_X >= SCREEN_WIDTH - window_x + 20 and MOUSE_X <= SCREEN_WIDTH - window_x + 140 and MOUSE_Y >= SCREEN_HIGHT - window_y + 120 and MOUSE_Y <= SCREEN_HIGHT - window_y + 130 then 
			manualVSpeedParam = 1
			vSpeedParam = 1
			sValue = V1_value
			userInputActivated = true
		end
		
		if not userInputActivated and MOUSE_STATUS ~= "drag" and MOUSE_X >= SCREEN_WIDTH - window_x + 20 and MOUSE_X <= SCREEN_WIDTH - window_x + 140 and MOUSE_Y >= SCREEN_HIGHT - window_y + 100 and MOUSE_Y <= SCREEN_HIGHT - window_y + 110 then 
			manualVSpeedParam = 2
			vSpeedParam = 2
			sValue = VR_value
			userInputActivated = true
		end

		if not userInputActivated and MOUSE_STATUS ~= "drag" and MOUSE_X >= SCREEN_WIDTH - window_x + 20 and MOUSE_X <= SCREEN_WIDTH - window_x + 140 and MOUSE_Y >= SCREEN_HIGHT - window_y + 80 and MOUSE_Y <= SCREEN_HIGHT - window_y + 90 then 
			manualVSpeedParam = 3
			vSpeedParam = 3
			sValue = V2_value
			userInputActivated = true
		end

	
	end

end -- end function activateUserInput() 


function resetPanelPosition()
	if show_values and not userInputActivated then 
		window_x = 150 
		window_y = 250 
	end
	
end -- end function resetPanelPosition()

function toggle_show_values()
	if show_values then
		show_values = false
		DeactivateSetting('show_values')
	else
		show_values = true
		ActivateSetting('show_values')
	end
end -- end function toggle_show_values()


function mainVSpeedCallouts()
			
	getVSpeedsFromFMC()

	if IALT < 10300 and GS > 5 then
		
		if math.floor(IAS) + 5 == 80 and not PlayedKTS80 and Enable_80Kts then play_sound(KTS80_Sound) PlayedKTS80 = true end
		if math.floor(IAS) + 5 == 100 and not PlayedKTS100 and Enable_100Kts then play_sound(KTS100_Sound) PlayedKTS100 = true end
		if math.floor(IAS) + 3 == V1_value and not PlayedV1 and V1_value > 39 and GS > 5 then play_sound(V1_Sound) PlayedV1 = true end
		if math.floor(IAS) + 3 == VR_value and not PlayedVR and PlayedV1 then play_sound(VR_Sound) PlayedVR = true end
		if math.floor(IAS) + 3 == V2_value and not PlayedV2 and Enable_V2 and PlayedVR then play_sound(V2_Sound) PlayedV2 = true end
		if AGL > 15 and math.floor(VSI) > 10 and not PlayedPosGear and EnablePosGearUp and PlayedVR then play_sound(PosGearUp_Sound) PlayedPosGear = true end

		--if AGL > 3048 and not PlayedPass10KLightsOff and PlayedPosGear then
		if (pass_10Kft) and (math.floor(IALT) >= 10001) and (math.floor(IALT) <= 10010) and (not PlayedPass10KLightsOff) and (math.floor(VSI) > 0) then 
			PlayedPass10KLightsOff = true
			play_sound(Pass10KLightsOff_Sound) 
		end	
		
		if auto_lights and (math.floor(IALT) >= 10001) and (math.floor(IALT) <= 10010) and (math.floor(VSI) > 0) and (not SwitchedLightsOff) then
			SwitchedLightsOff = true
			if aircraft == "x737-800" then
				set("x737/systems/exteriorLights/leftFixedLanLtSwitch", 0)
				set("x737/systems/exteriorLights/rightFixedLanLtSwitch", 0)
				set("x737/systems/exteriorLights/leftRetrLanLtSwitch", 0)
				set("x737/systems/exteriorLights/rightRetrLanLtSwitch", 0)
			end
			if aircraft == "Boeing B747-400" then
				command_once("laminar/B747/toggle_switch/landing_light_IBL")
				command_once("laminar/B747/toggle_switch/landing_light_IBR")
				command_once("laminar/B747/toggle_switch/landing_light_OBL")
				command_once("laminar/B747/toggle_switch/landing_light_OBR")
			end
			if aircraft == "tolissa321" then
				LIGHTS[4] = 1   -- Left landing off
				LIGHTS[5] = 1   -- Right landing off
			end
			if aircraft == "AirbusA350" then
				LIGHTS[0] = 0   -- Left landing off
				LIGHTS[1] = 0   -- Right landing off
			else
				command_once("sim/lights/landing_lights_off") 
			end
		end
				
		
		--if AGL < 3048 and not PlayedPass10KLightsOn and PlayedPass10KLightsOff then
		if (pass_10Kft) and (math.floor(IALT) <= 9999) and (math.floor(IALT) >= 9990) and (not PlayedPass10KLightsOn) and (math.floor(VSI) < 0) then 
			PlayedPass10KLightsOn = true 
			play_sound(Pass10KLightsOn_Sound) 
		end
		
		if auto_lights and (math.floor(IALT) <= 9999) and (math.floor(IALT) >= 9990) and (math.floor(VSI) < 0) and (not SwitchedLightsOn) then
			SwitchedLightsOn = true
			if aircraft == "x737-800" then
				set("x737/systems/exteriorLights/leftFixedLanLtSwitch", 1)
				set("x737/systems/exteriorLights/rightFixedLanLtSwitch", 1)
				set("x737/systems/exteriorLights/leftRetrLanLtSwitch", 2)
				set("x737/systems/exteriorLights/rightRetrLanLtSwitch", 2)
			end
			if aircraft == "Boeing B747-400" then
				command_once("laminar/B747/toggle_switch/landing_light_IBL")
				command_once("laminar/B747/toggle_switch/landing_light_IBR")
				command_once("laminar/B747/toggle_switch/landing_light_OBL")
				command_once("laminar/B747/toggle_switch/landing_light_OBR")
			end
			if aircraft == "tolissa321" then
				LIGHTS[4] = 2   -- Left landing on
				LIGHTS[5] = 2   -- Right landing on
			end
			if aircraft == "AirbusA350" then
				LIGHTS[0] = 1   -- Left landing off
				LIGHTS[1] = 1   -- Right landing off
			else
				command_once("sim/lights/landing_lights_on") 
			end
		end
		
		-- 0=up, 1= down
		if math.floor(IALT) >= 9990 then TenKFeetSwitch = true end
		if Gear_Down and TenKFeetSwitch and (math.floor(AGL) <= 549) and (IAS <= 190) and (GEARSTATUS == 0) and (not PlayedGearDown) then
			PlayedGearDown = true
			play_sound(GearDown_Sound)
		end
		
		-- (1 knot = 0.514444 m/sec) 
		if manual_Breaks and (math.floor(AGL) == 0) and (IAS <= 61) and (IAS >= 56) and (THROTTLE == 0 or REVTHROTTLE <= -1) and (not PlayedManualBreaks) then
			PlayedManualBreaks = true
			play_sound(ManualBreaks60KTS_Sound) 
		end

		-- *** Alternative method for callout sounds, by using the XLMP FlyWithLua library *** --
		-- if math.floor(IAS) + 2 == 80 and not PlayedKTS80 and Enable_80Kts then XPLMSpeakString( "80 Knots" ) PlayedKTS80 = true end
		-- if math.floor(IAS) + 3 == V1_value and not PlayedV1 and V1_value > 39 and GS > 5 then XPLMSpeakString( "V1" ) PlayedV1 = true end
		-- if math.floor(IAS) == VR_value and not PlayedVR and PlayedV1 then XPLMSpeakString( "Rotate" ) PlayedVR = true end
		-- if math.floor(IAS) == V2_value and not PlayedV2 and Enable_V2 and PlayedVR then XPLMSpeakString( "V2" ) PlayedV2 = true end
		-- if AGL > 20 and math.floor(VSI) > 10 and not PlayedPosGear and EnablePosGearUp and PlayedVR then 
		-- 	XPLMSpeakString( "Positive rate of climb. Gear up" )
		--	PlayedPosGear = true
		-- end
		
		if AGL > 200 then
			PlayedKTS80 = true
			PlayedKTS100 = true
			PlayedV1 = true
			PlayedVR = true
			PlayedV2 = true
			PlayedPosGear = true
			if aircraft == "x737-800" and not x737800SPDREF then
				x737800SPDREF = true
				set( "x737/systems/SPDREF/mode", 0) -- set SPDREF mode in AUTO so that V1 and VR speeds are not displayed in PFD 
			end
		end

		if GS < 10 then
			PlayedKTS80 = false
			PlayedKTS100 = false
			PlayedV1 = false
			PlayedVR = false
			PlayedV2 = false
			PlayedPosGear = false
			x737800SPDREF = false
			PlayedManualBreaks = false
			PlayedGearDown = false
		end

		--if AGL > 3109 then
		if math.floor(IALT) > 10100 then
			PlayedPass10KLightsOn = false
			PlayedPass10KLightsOff = true
			SwitchedLightsOn = false
			SwitchedLightsOff = true
		end
	
		--if AGL < 2987 then
		if math.floor(IALT) < 9900 then
			PlayedPass10KLightsOn = true
			PlayedPass10KLightsOff = false
			SwitchedLightsOn = true
			SwitchedLightsOff = false
		end
	end

end --end function mainVSpeedCallouts()

onload = true

-- *** Main function calls, macros and keyboard command creation
	create_command("FlyWithLua/vSpeedCallouts/panel_toggle", "Display vSpeedCallouts panel toggle", "toggle_show_values()", "", "")
	add_macro("vSpeedCallouts Panel toggle", "show_values=true ActivateSetting('show_values')", "show_values=false DeactivateSetting('show_values')", setCommandState(show_values))
	add_macro("vSpeedCallouts Reset Panel position", "resetPanelPosition()")
	add_macro("vSpeedCallouts 80Kts toggle", "Enable_80Kts=true ActivateSetting('Enable_80Kts')", "Enable_80Kts=false DeactivateSetting('Enable_80Kts')", setCommandState(Enable_80Kts))
	add_macro("vSpeedCallouts 100Kts toggle", "Enable_100Kts=true ActivateSetting('Enable_100Kts')", "Enable_100Kts=false DeactivateSetting('Enable_100Kts')", setCommandState(Enable_100Kts))
	add_macro("vSpeedCallouts GearUp toggle", "EnablePosGearUp=true ActivateSetting('EnablePosGearUp')", "EnablePosGearUp=false DeactivateSetting('EnablePosGearUp')", setCommandState(EnablePosGearUp))
	add_macro("vSpeedCallouts Auto-Lights@10,000ft toggle", "auto_lights=true ActivateSetting('auto_lights')", "auto_lights=false DeactivateSetting('auto_lights')", setCommandState(auto_lights))
	add_macro("vSpeedCallouts 10,000ft annunciation toggle", "pass_10Kft=true ActivateSetting('pass_10Kft')", "pass_10Kft=false DeactivateSetting('pass_10Kft')", setCommandState(pass_10Kft))
	add_macro("vSpeedCallouts 60Kts/ManualBreaks annunciation toggle", "manual_Breaks=true ActivateSetting('manual_Breaks')", "manual_Breaks=false DeactivateSetting('manual_Breaks')", setCommandState(manual_Breaks))
	add_macro("vSpeedCallouts Gear Down annunciation toggle", "Gear_Down=true ActivateSetting('Gear_Down')", "Gear_Down=false DeactivateSetting('Gear_Down')", setCommandState(Gear_Down))

onload = false

	do_on_keystroke("GetVSpeedLineFromKeyboard()")

	do_on_mouse_click("activateUserInput()")

	do_every_draw("display_values_panel()")

	do_every_draw("DrawVSpeedInputLine(vSpeedParam)")

	do_every_frame ("mainVSpeedCallouts()")
	
	print ("-- vSpeedCallouts v1.10 by 'ManosK' loaded successfully --")

-- end
